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_NUM_RESERVED = 1,
177 UFSHCD_CMD_PER_LUN = 32 - UFSHCD_NUM_RESERVED,
178 UFSHCD_CAN_QUEUE = 32 - UFSHCD_NUM_RESERVED,
181 static const char *const ufshcd_state_name[] = {
182 [UFSHCD_STATE_RESET] = "reset",
183 [UFSHCD_STATE_OPERATIONAL] = "operational",
184 [UFSHCD_STATE_ERROR] = "error",
185 [UFSHCD_STATE_EH_SCHEDULED_FATAL] = "eh_fatal",
186 [UFSHCD_STATE_EH_SCHEDULED_NON_FATAL] = "eh_non_fatal",
189 /* UFSHCD error handling flags */
191 UFSHCD_EH_IN_PROGRESS = (1 << 0),
194 /* UFSHCD UIC layer error flags */
196 UFSHCD_UIC_DL_PA_INIT_ERROR = (1 << 0), /* Data link layer error */
197 UFSHCD_UIC_DL_NAC_RECEIVED_ERROR = (1 << 1), /* Data link layer error */
198 UFSHCD_UIC_DL_TCx_REPLAY_ERROR = (1 << 2), /* Data link layer error */
199 UFSHCD_UIC_NL_ERROR = (1 << 3), /* Network layer error */
200 UFSHCD_UIC_TL_ERROR = (1 << 4), /* Transport Layer error */
201 UFSHCD_UIC_DME_ERROR = (1 << 5), /* DME error */
202 UFSHCD_UIC_PA_GENERIC_ERROR = (1 << 6), /* Generic PA error */
205 #define ufshcd_set_eh_in_progress(h) \
206 ((h)->eh_flags |= UFSHCD_EH_IN_PROGRESS)
207 #define ufshcd_eh_in_progress(h) \
208 ((h)->eh_flags & UFSHCD_EH_IN_PROGRESS)
209 #define ufshcd_clear_eh_in_progress(h) \
210 ((h)->eh_flags &= ~UFSHCD_EH_IN_PROGRESS)
212 const struct ufs_pm_lvl_states ufs_pm_lvl_states[] = {
213 [UFS_PM_LVL_0] = {UFS_ACTIVE_PWR_MODE, UIC_LINK_ACTIVE_STATE},
214 [UFS_PM_LVL_1] = {UFS_ACTIVE_PWR_MODE, UIC_LINK_HIBERN8_STATE},
215 [UFS_PM_LVL_2] = {UFS_SLEEP_PWR_MODE, UIC_LINK_ACTIVE_STATE},
216 [UFS_PM_LVL_3] = {UFS_SLEEP_PWR_MODE, UIC_LINK_HIBERN8_STATE},
217 [UFS_PM_LVL_4] = {UFS_POWERDOWN_PWR_MODE, UIC_LINK_HIBERN8_STATE},
218 [UFS_PM_LVL_5] = {UFS_POWERDOWN_PWR_MODE, UIC_LINK_OFF_STATE},
220 * For DeepSleep, the link is first put in hibern8 and then off.
221 * Leaving the link in hibern8 is not supported.
223 [UFS_PM_LVL_6] = {UFS_DEEPSLEEP_PWR_MODE, UIC_LINK_OFF_STATE},
226 static inline enum ufs_dev_pwr_mode
227 ufs_get_pm_lvl_to_dev_pwr_mode(enum ufs_pm_level lvl)
229 return ufs_pm_lvl_states[lvl].dev_state;
232 static inline enum uic_link_state
233 ufs_get_pm_lvl_to_link_pwr_state(enum ufs_pm_level lvl)
235 return ufs_pm_lvl_states[lvl].link_state;
238 static inline enum ufs_pm_level
239 ufs_get_desired_pm_lvl_for_dev_link_state(enum ufs_dev_pwr_mode dev_state,
240 enum uic_link_state link_state)
242 enum ufs_pm_level lvl;
244 for (lvl = UFS_PM_LVL_0; lvl < UFS_PM_LVL_MAX; lvl++) {
245 if ((ufs_pm_lvl_states[lvl].dev_state == dev_state) &&
246 (ufs_pm_lvl_states[lvl].link_state == link_state))
250 /* if no match found, return the level 0 */
254 static const struct ufs_dev_quirk ufs_fixups[] = {
255 /* UFS cards deviations table */
256 { .wmanufacturerid = UFS_VENDOR_MICRON,
257 .model = UFS_ANY_MODEL,
258 .quirk = UFS_DEVICE_QUIRK_DELAY_BEFORE_LPM |
259 UFS_DEVICE_QUIRK_SWAP_L2P_ENTRY_FOR_HPB_READ },
260 { .wmanufacturerid = UFS_VENDOR_SAMSUNG,
261 .model = UFS_ANY_MODEL,
262 .quirk = UFS_DEVICE_QUIRK_DELAY_BEFORE_LPM |
263 UFS_DEVICE_QUIRK_HOST_PA_TACTIVATE |
264 UFS_DEVICE_QUIRK_RECOVERY_FROM_DL_NAC_ERRORS },
265 { .wmanufacturerid = UFS_VENDOR_SKHYNIX,
266 .model = UFS_ANY_MODEL,
267 .quirk = UFS_DEVICE_QUIRK_HOST_PA_SAVECONFIGTIME },
268 { .wmanufacturerid = UFS_VENDOR_SKHYNIX,
269 .model = "hB8aL1" /*H28U62301AMR*/,
270 .quirk = UFS_DEVICE_QUIRK_HOST_VS_DEBUGSAVECONFIGTIME },
271 { .wmanufacturerid = UFS_VENDOR_TOSHIBA,
272 .model = UFS_ANY_MODEL,
273 .quirk = UFS_DEVICE_QUIRK_DELAY_BEFORE_LPM },
274 { .wmanufacturerid = UFS_VENDOR_TOSHIBA,
275 .model = "THGLF2G9C8KBADG",
276 .quirk = UFS_DEVICE_QUIRK_PA_TACTIVATE },
277 { .wmanufacturerid = UFS_VENDOR_TOSHIBA,
278 .model = "THGLF2G9D8KBADG",
279 .quirk = UFS_DEVICE_QUIRK_PA_TACTIVATE },
283 static irqreturn_t ufshcd_tmc_handler(struct ufs_hba *hba);
284 static void ufshcd_async_scan(void *data, async_cookie_t cookie);
285 static int ufshcd_reset_and_restore(struct ufs_hba *hba);
286 static int ufshcd_eh_host_reset_handler(struct scsi_cmnd *cmd);
287 static int ufshcd_clear_tm_cmd(struct ufs_hba *hba, int tag);
288 static void ufshcd_hba_exit(struct ufs_hba *hba);
289 static int ufshcd_probe_hba(struct ufs_hba *hba, bool init_dev_params);
290 static int ufshcd_setup_clocks(struct ufs_hba *hba, bool on);
291 static inline void ufshcd_add_delay_before_dme_cmd(struct ufs_hba *hba);
292 static int ufshcd_host_reset_and_restore(struct ufs_hba *hba);
293 static void ufshcd_resume_clkscaling(struct ufs_hba *hba);
294 static void ufshcd_suspend_clkscaling(struct ufs_hba *hba);
295 static void __ufshcd_suspend_clkscaling(struct ufs_hba *hba);
296 static int ufshcd_scale_clks(struct ufs_hba *hba, bool scale_up);
297 static irqreturn_t ufshcd_intr(int irq, void *__hba);
298 static int ufshcd_change_power_mode(struct ufs_hba *hba,
299 struct ufs_pa_layer_attr *pwr_mode);
300 static int ufshcd_setup_hba_vreg(struct ufs_hba *hba, bool on);
301 static int ufshcd_setup_vreg(struct ufs_hba *hba, bool on);
302 static inline int ufshcd_config_vreg_hpm(struct ufs_hba *hba,
303 struct ufs_vreg *vreg);
304 static int ufshcd_try_to_abort_task(struct ufs_hba *hba, int tag);
305 static void ufshcd_wb_toggle_buf_flush_during_h8(struct ufs_hba *hba,
307 static void ufshcd_hba_vreg_set_lpm(struct ufs_hba *hba);
308 static void ufshcd_hba_vreg_set_hpm(struct ufs_hba *hba);
310 static inline void ufshcd_enable_irq(struct ufs_hba *hba)
312 if (!hba->is_irq_enabled) {
313 enable_irq(hba->irq);
314 hba->is_irq_enabled = true;
318 static inline void ufshcd_disable_irq(struct ufs_hba *hba)
320 if (hba->is_irq_enabled) {
321 disable_irq(hba->irq);
322 hba->is_irq_enabled = false;
326 static void ufshcd_configure_wb(struct ufs_hba *hba)
328 if (!ufshcd_is_wb_allowed(hba))
331 ufshcd_wb_toggle(hba, true);
333 ufshcd_wb_toggle_buf_flush_during_h8(hba, true);
335 if (ufshcd_is_wb_buf_flush_allowed(hba))
336 ufshcd_wb_toggle_buf_flush(hba, true);
339 static void ufshcd_scsi_unblock_requests(struct ufs_hba *hba)
341 if (atomic_dec_and_test(&hba->scsi_block_reqs_cnt))
342 scsi_unblock_requests(hba->host);
345 static void ufshcd_scsi_block_requests(struct ufs_hba *hba)
347 if (atomic_inc_return(&hba->scsi_block_reqs_cnt) == 1)
348 scsi_block_requests(hba->host);
351 static void ufshcd_add_cmd_upiu_trace(struct ufs_hba *hba, unsigned int tag,
352 enum ufs_trace_str_t str_t)
354 struct utp_upiu_req *rq = hba->lrb[tag].ucd_req_ptr;
355 struct utp_upiu_header *header;
357 if (!trace_ufshcd_upiu_enabled())
360 if (str_t == UFS_CMD_SEND)
361 header = &rq->header;
363 header = &hba->lrb[tag].ucd_rsp_ptr->header;
365 trace_ufshcd_upiu(dev_name(hba->dev), str_t, header, &rq->sc.cdb,
369 static void ufshcd_add_query_upiu_trace(struct ufs_hba *hba,
370 enum ufs_trace_str_t str_t,
371 struct utp_upiu_req *rq_rsp)
373 if (!trace_ufshcd_upiu_enabled())
376 trace_ufshcd_upiu(dev_name(hba->dev), str_t, &rq_rsp->header,
377 &rq_rsp->qr, UFS_TSF_OSF);
380 static void ufshcd_add_tm_upiu_trace(struct ufs_hba *hba, unsigned int tag,
381 enum ufs_trace_str_t str_t)
383 struct utp_task_req_desc *descp = &hba->utmrdl_base_addr[tag];
385 if (!trace_ufshcd_upiu_enabled())
388 if (str_t == UFS_TM_SEND)
389 trace_ufshcd_upiu(dev_name(hba->dev), str_t,
390 &descp->upiu_req.req_header,
391 &descp->upiu_req.input_param1,
394 trace_ufshcd_upiu(dev_name(hba->dev), str_t,
395 &descp->upiu_rsp.rsp_header,
396 &descp->upiu_rsp.output_param1,
400 static void ufshcd_add_uic_command_trace(struct ufs_hba *hba,
401 const struct uic_command *ucmd,
402 enum ufs_trace_str_t str_t)
406 if (!trace_ufshcd_uic_command_enabled())
409 if (str_t == UFS_CMD_SEND)
412 cmd = ufshcd_readl(hba, REG_UIC_COMMAND);
414 trace_ufshcd_uic_command(dev_name(hba->dev), str_t, cmd,
415 ufshcd_readl(hba, REG_UIC_COMMAND_ARG_1),
416 ufshcd_readl(hba, REG_UIC_COMMAND_ARG_2),
417 ufshcd_readl(hba, REG_UIC_COMMAND_ARG_3));
420 static void ufshcd_add_command_trace(struct ufs_hba *hba, unsigned int tag,
421 enum ufs_trace_str_t str_t)
424 u8 opcode = 0, group_id = 0;
428 struct ufshcd_lrb *lrbp = &hba->lrb[tag];
429 struct scsi_cmnd *cmd = lrbp->cmd;
430 struct request *rq = scsi_cmd_to_rq(cmd);
431 int transfer_len = -1;
436 /* trace UPIU also */
437 ufshcd_add_cmd_upiu_trace(hba, tag, str_t);
438 if (!trace_ufshcd_command_enabled())
441 opcode = cmd->cmnd[0];
443 if (opcode == READ_10 || opcode == WRITE_10) {
445 * Currently we only fully trace read(10) and write(10) commands
448 be32_to_cpu(lrbp->ucd_req_ptr->sc.exp_data_transfer_len);
449 lba = scsi_get_lba(cmd);
450 if (opcode == WRITE_10)
451 group_id = lrbp->cmd->cmnd[6];
452 } else if (opcode == UNMAP) {
454 * The number of Bytes to be unmapped beginning with the lba.
456 transfer_len = blk_rq_bytes(rq);
457 lba = scsi_get_lba(cmd);
460 intr = ufshcd_readl(hba, REG_INTERRUPT_STATUS);
462 if (is_mcq_enabled(hba)) {
463 struct ufs_hw_queue *hwq = ufshcd_mcq_req_to_hwq(hba, rq);
467 doorbell = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
469 trace_ufshcd_command(dev_name(hba->dev), str_t, tag,
470 doorbell, hwq_id, transfer_len, intr, lba, opcode, group_id);
473 static void ufshcd_print_clk_freqs(struct ufs_hba *hba)
475 struct ufs_clk_info *clki;
476 struct list_head *head = &hba->clk_list_head;
478 if (list_empty(head))
481 list_for_each_entry(clki, head, list) {
482 if (!IS_ERR_OR_NULL(clki->clk) && clki->min_freq &&
484 dev_err(hba->dev, "clk: %s, rate: %u\n",
485 clki->name, clki->curr_freq);
489 static void ufshcd_print_evt(struct ufs_hba *hba, u32 id,
490 const char *err_name)
494 const struct ufs_event_hist *e;
496 if (id >= UFS_EVT_CNT)
499 e = &hba->ufs_stats.event[id];
501 for (i = 0; i < UFS_EVENT_HIST_LENGTH; i++) {
502 int p = (i + e->pos) % UFS_EVENT_HIST_LENGTH;
504 if (e->tstamp[p] == 0)
506 dev_err(hba->dev, "%s[%d] = 0x%x at %lld us\n", err_name, p,
507 e->val[p], div_u64(e->tstamp[p], 1000));
512 dev_err(hba->dev, "No record of %s\n", err_name);
514 dev_err(hba->dev, "%s: total cnt=%llu\n", err_name, e->cnt);
517 static void ufshcd_print_evt_hist(struct ufs_hba *hba)
519 ufshcd_dump_regs(hba, 0, UFSHCI_REG_SPACE_SIZE, "host_regs: ");
521 ufshcd_print_evt(hba, UFS_EVT_PA_ERR, "pa_err");
522 ufshcd_print_evt(hba, UFS_EVT_DL_ERR, "dl_err");
523 ufshcd_print_evt(hba, UFS_EVT_NL_ERR, "nl_err");
524 ufshcd_print_evt(hba, UFS_EVT_TL_ERR, "tl_err");
525 ufshcd_print_evt(hba, UFS_EVT_DME_ERR, "dme_err");
526 ufshcd_print_evt(hba, UFS_EVT_AUTO_HIBERN8_ERR,
528 ufshcd_print_evt(hba, UFS_EVT_FATAL_ERR, "fatal_err");
529 ufshcd_print_evt(hba, UFS_EVT_LINK_STARTUP_FAIL,
530 "link_startup_fail");
531 ufshcd_print_evt(hba, UFS_EVT_RESUME_ERR, "resume_fail");
532 ufshcd_print_evt(hba, UFS_EVT_SUSPEND_ERR,
534 ufshcd_print_evt(hba, UFS_EVT_WL_RES_ERR, "wlun resume_fail");
535 ufshcd_print_evt(hba, UFS_EVT_WL_SUSP_ERR,
536 "wlun suspend_fail");
537 ufshcd_print_evt(hba, UFS_EVT_DEV_RESET, "dev_reset");
538 ufshcd_print_evt(hba, UFS_EVT_HOST_RESET, "host_reset");
539 ufshcd_print_evt(hba, UFS_EVT_ABORT, "task_abort");
541 ufshcd_vops_dbg_register_dump(hba);
545 void ufshcd_print_tr(struct ufs_hba *hba, int tag, bool pr_prdt)
547 const struct ufshcd_lrb *lrbp;
550 lrbp = &hba->lrb[tag];
552 dev_err(hba->dev, "UPIU[%d] - issue time %lld us\n",
553 tag, div_u64(lrbp->issue_time_stamp_local_clock, 1000));
554 dev_err(hba->dev, "UPIU[%d] - complete time %lld us\n",
555 tag, div_u64(lrbp->compl_time_stamp_local_clock, 1000));
557 "UPIU[%d] - Transfer Request Descriptor phys@0x%llx\n",
558 tag, (u64)lrbp->utrd_dma_addr);
560 ufshcd_hex_dump("UPIU TRD: ", lrbp->utr_descriptor_ptr,
561 sizeof(struct utp_transfer_req_desc));
562 dev_err(hba->dev, "UPIU[%d] - Request UPIU phys@0x%llx\n", tag,
563 (u64)lrbp->ucd_req_dma_addr);
564 ufshcd_hex_dump("UPIU REQ: ", lrbp->ucd_req_ptr,
565 sizeof(struct utp_upiu_req));
566 dev_err(hba->dev, "UPIU[%d] - Response UPIU phys@0x%llx\n", tag,
567 (u64)lrbp->ucd_rsp_dma_addr);
568 ufshcd_hex_dump("UPIU RSP: ", lrbp->ucd_rsp_ptr,
569 sizeof(struct utp_upiu_rsp));
571 prdt_length = le16_to_cpu(
572 lrbp->utr_descriptor_ptr->prd_table_length);
573 if (hba->quirks & UFSHCD_QUIRK_PRDT_BYTE_GRAN)
574 prdt_length /= ufshcd_sg_entry_size(hba);
577 "UPIU[%d] - PRDT - %d entries phys@0x%llx\n",
579 (u64)lrbp->ucd_prdt_dma_addr);
582 ufshcd_hex_dump("UPIU PRDT: ", lrbp->ucd_prdt_ptr,
583 ufshcd_sg_entry_size(hba) * prdt_length);
586 static bool ufshcd_print_tr_iter(struct request *req, void *priv)
588 struct scsi_device *sdev = req->q->queuedata;
589 struct Scsi_Host *shost = sdev->host;
590 struct ufs_hba *hba = shost_priv(shost);
592 ufshcd_print_tr(hba, req->tag, *(bool *)priv);
598 * ufshcd_print_trs_all - print trs for all started requests.
599 * @hba: per-adapter instance.
600 * @pr_prdt: need to print prdt or not.
602 static void ufshcd_print_trs_all(struct ufs_hba *hba, bool pr_prdt)
604 blk_mq_tagset_busy_iter(&hba->host->tag_set, ufshcd_print_tr_iter, &pr_prdt);
607 static void ufshcd_print_tmrs(struct ufs_hba *hba, unsigned long bitmap)
611 for_each_set_bit(tag, &bitmap, hba->nutmrs) {
612 struct utp_task_req_desc *tmrdp = &hba->utmrdl_base_addr[tag];
614 dev_err(hba->dev, "TM[%d] - Task Management Header\n", tag);
615 ufshcd_hex_dump("", tmrdp, sizeof(*tmrdp));
619 static void ufshcd_print_host_state(struct ufs_hba *hba)
621 const struct scsi_device *sdev_ufs = hba->ufs_device_wlun;
623 dev_err(hba->dev, "UFS Host state=%d\n", hba->ufshcd_state);
624 dev_err(hba->dev, "outstanding reqs=0x%lx tasks=0x%lx\n",
625 hba->outstanding_reqs, hba->outstanding_tasks);
626 dev_err(hba->dev, "saved_err=0x%x, saved_uic_err=0x%x\n",
627 hba->saved_err, hba->saved_uic_err);
628 dev_err(hba->dev, "Device power mode=%d, UIC link state=%d\n",
629 hba->curr_dev_pwr_mode, hba->uic_link_state);
630 dev_err(hba->dev, "PM in progress=%d, sys. suspended=%d\n",
631 hba->pm_op_in_progress, hba->is_sys_suspended);
632 dev_err(hba->dev, "Auto BKOPS=%d, Host self-block=%d\n",
633 hba->auto_bkops_enabled, hba->host->host_self_blocked);
634 dev_err(hba->dev, "Clk gate=%d\n", hba->clk_gating.state);
636 "last_hibern8_exit_tstamp at %lld us, hibern8_exit_cnt=%d\n",
637 div_u64(hba->ufs_stats.last_hibern8_exit_tstamp, 1000),
638 hba->ufs_stats.hibern8_exit_cnt);
639 dev_err(hba->dev, "last intr at %lld us, last intr status=0x%x\n",
640 div_u64(hba->ufs_stats.last_intr_ts, 1000),
641 hba->ufs_stats.last_intr_status);
642 dev_err(hba->dev, "error handling flags=0x%x, req. abort count=%d\n",
643 hba->eh_flags, hba->req_abort_count);
644 dev_err(hba->dev, "hba->ufs_version=0x%x, Host capabilities=0x%x, caps=0x%x\n",
645 hba->ufs_version, hba->capabilities, hba->caps);
646 dev_err(hba->dev, "quirks=0x%x, dev. quirks=0x%x\n", hba->quirks,
649 dev_err(hba->dev, "UFS dev info: %.8s %.16s rev %.4s\n",
650 sdev_ufs->vendor, sdev_ufs->model, sdev_ufs->rev);
652 ufshcd_print_clk_freqs(hba);
656 * ufshcd_print_pwr_info - print power params as saved in hba
658 * @hba: per-adapter instance
660 static void ufshcd_print_pwr_info(struct ufs_hba *hba)
662 static const char * const names[] = {
673 * Using dev_dbg to avoid messages during runtime PM to avoid
674 * never-ending cycles of messages written back to storage by user space
675 * causing runtime resume, causing more messages and so on.
677 dev_dbg(hba->dev, "%s:[RX, TX]: gear=[%d, %d], lane[%d, %d], pwr[%s, %s], rate = %d\n",
679 hba->pwr_info.gear_rx, hba->pwr_info.gear_tx,
680 hba->pwr_info.lane_rx, hba->pwr_info.lane_tx,
681 names[hba->pwr_info.pwr_rx],
682 names[hba->pwr_info.pwr_tx],
683 hba->pwr_info.hs_rate);
686 static void ufshcd_device_reset(struct ufs_hba *hba)
690 err = ufshcd_vops_device_reset(hba);
693 ufshcd_set_ufs_dev_active(hba);
694 if (ufshcd_is_wb_allowed(hba)) {
695 hba->dev_info.wb_enabled = false;
696 hba->dev_info.wb_buf_flush_enabled = false;
699 if (err != -EOPNOTSUPP)
700 ufshcd_update_evt_hist(hba, UFS_EVT_DEV_RESET, err);
703 void ufshcd_delay_us(unsigned long us, unsigned long tolerance)
711 usleep_range(us, us + tolerance);
713 EXPORT_SYMBOL_GPL(ufshcd_delay_us);
716 * ufshcd_wait_for_register - wait for register value to change
717 * @hba: per-adapter interface
718 * @reg: mmio register offset
719 * @mask: mask to apply to the read register value
720 * @val: value to wait for
721 * @interval_us: polling interval in microseconds
722 * @timeout_ms: timeout in milliseconds
725 * -ETIMEDOUT on error, zero on success.
727 static int ufshcd_wait_for_register(struct ufs_hba *hba, u32 reg, u32 mask,
728 u32 val, unsigned long interval_us,
729 unsigned long timeout_ms)
732 unsigned long timeout = jiffies + msecs_to_jiffies(timeout_ms);
734 /* ignore bits that we don't intend to wait on */
737 while ((ufshcd_readl(hba, reg) & mask) != val) {
738 usleep_range(interval_us, interval_us + 50);
739 if (time_after(jiffies, timeout)) {
740 if ((ufshcd_readl(hba, reg) & mask) != val)
750 * ufshcd_get_intr_mask - Get the interrupt bit mask
751 * @hba: Pointer to adapter instance
753 * Returns interrupt bit mask per version
755 static inline u32 ufshcd_get_intr_mask(struct ufs_hba *hba)
757 if (hba->ufs_version == ufshci_version(1, 0))
758 return INTERRUPT_MASK_ALL_VER_10;
759 if (hba->ufs_version <= ufshci_version(2, 0))
760 return INTERRUPT_MASK_ALL_VER_11;
762 return INTERRUPT_MASK_ALL_VER_21;
766 * ufshcd_get_ufs_version - Get the UFS version supported by the HBA
767 * @hba: Pointer to adapter instance
769 * Returns UFSHCI version supported by the controller
771 static inline u32 ufshcd_get_ufs_version(struct ufs_hba *hba)
775 if (hba->quirks & UFSHCD_QUIRK_BROKEN_UFS_HCI_VERSION)
776 ufshci_ver = ufshcd_vops_get_ufs_hci_version(hba);
778 ufshci_ver = ufshcd_readl(hba, REG_UFS_VERSION);
781 * UFSHCI v1.x uses a different version scheme, in order
782 * to allow the use of comparisons with the ufshci_version
783 * function, we convert it to the same scheme as ufs 2.0+.
785 if (ufshci_ver & 0x00010000)
786 return ufshci_version(1, ufshci_ver & 0x00000100);
792 * ufshcd_is_device_present - Check if any device connected to
793 * the host controller
794 * @hba: pointer to adapter instance
796 * Returns true if device present, false if no device detected
798 static inline bool ufshcd_is_device_present(struct ufs_hba *hba)
800 return ufshcd_readl(hba, REG_CONTROLLER_STATUS) & DEVICE_PRESENT;
804 * ufshcd_get_tr_ocs - Get the UTRD Overall Command Status
805 * @lrbp: pointer to local command reference block
806 * @cqe: pointer to the completion queue entry
808 * This function is used to get the OCS field from UTRD
809 * Returns the OCS field in the UTRD
811 static enum utp_ocs ufshcd_get_tr_ocs(struct ufshcd_lrb *lrbp,
812 struct cq_entry *cqe)
815 return le32_to_cpu(cqe->status) & MASK_OCS;
817 return le32_to_cpu(lrbp->utr_descriptor_ptr->header.dword_2) & MASK_OCS;
821 * ufshcd_utrl_clear() - Clear requests from the controller request list.
822 * @hba: per adapter instance
823 * @mask: mask with one bit set for each request to be cleared
825 static inline void ufshcd_utrl_clear(struct ufs_hba *hba, u32 mask)
827 if (hba->quirks & UFSHCI_QUIRK_BROKEN_REQ_LIST_CLR)
830 * From the UFSHCI specification: "UTP Transfer Request List CLear
831 * Register (UTRLCLR): This field is bit significant. Each bit
832 * corresponds to a slot in the UTP Transfer Request List, where bit 0
833 * corresponds to request slot 0. A bit in this field is set to ‘0’
834 * by host software to indicate to the host controller that a transfer
835 * request slot is cleared. The host controller
836 * shall free up any resources associated to the request slot
837 * immediately, and shall set the associated bit in UTRLDBR to ‘0’. The
838 * host software indicates no change to request slots by setting the
839 * associated bits in this field to ‘1’. Bits in this field shall only
840 * be set ‘1’ or ‘0’ by host software when UTRLRSR is set to ‘1’."
842 ufshcd_writel(hba, ~mask, REG_UTP_TRANSFER_REQ_LIST_CLEAR);
846 * ufshcd_utmrl_clear - Clear a bit in UTMRLCLR register
847 * @hba: per adapter instance
848 * @pos: position of the bit to be cleared
850 static inline void ufshcd_utmrl_clear(struct ufs_hba *hba, u32 pos)
852 if (hba->quirks & UFSHCI_QUIRK_BROKEN_REQ_LIST_CLR)
853 ufshcd_writel(hba, (1 << pos), REG_UTP_TASK_REQ_LIST_CLEAR);
855 ufshcd_writel(hba, ~(1 << pos), REG_UTP_TASK_REQ_LIST_CLEAR);
859 * ufshcd_get_lists_status - Check UCRDY, UTRLRDY and UTMRLRDY
860 * @reg: Register value of host controller status
862 * Returns integer, 0 on Success and positive value if failed
864 static inline int ufshcd_get_lists_status(u32 reg)
866 return !((reg & UFSHCD_STATUS_READY) == UFSHCD_STATUS_READY);
870 * ufshcd_get_uic_cmd_result - Get the UIC command result
871 * @hba: Pointer to adapter instance
873 * This function gets the result of UIC command completion
874 * Returns 0 on success, non zero value on error
876 static inline int ufshcd_get_uic_cmd_result(struct ufs_hba *hba)
878 return ufshcd_readl(hba, REG_UIC_COMMAND_ARG_2) &
879 MASK_UIC_COMMAND_RESULT;
883 * ufshcd_get_dme_attr_val - Get the value of attribute returned by UIC command
884 * @hba: Pointer to adapter instance
886 * This function gets UIC command argument3
887 * Returns 0 on success, non zero value on error
889 static inline u32 ufshcd_get_dme_attr_val(struct ufs_hba *hba)
891 return ufshcd_readl(hba, REG_UIC_COMMAND_ARG_3);
895 * ufshcd_get_req_rsp - returns the TR response transaction type
896 * @ucd_rsp_ptr: pointer to response UPIU
899 ufshcd_get_req_rsp(struct utp_upiu_rsp *ucd_rsp_ptr)
901 return be32_to_cpu(ucd_rsp_ptr->header.dword_0) >> 24;
905 * ufshcd_get_rsp_upiu_result - Get the result from response UPIU
906 * @ucd_rsp_ptr: pointer to response UPIU
908 * This function gets the response status and scsi_status from response UPIU
909 * Returns the response result code.
912 ufshcd_get_rsp_upiu_result(struct utp_upiu_rsp *ucd_rsp_ptr)
914 return be32_to_cpu(ucd_rsp_ptr->header.dword_1) & MASK_RSP_UPIU_RESULT;
918 * ufshcd_get_rsp_upiu_data_seg_len - Get the data segment length
920 * @ucd_rsp_ptr: pointer to response UPIU
922 * Return the data segment length.
924 static inline unsigned int
925 ufshcd_get_rsp_upiu_data_seg_len(struct utp_upiu_rsp *ucd_rsp_ptr)
927 return be32_to_cpu(ucd_rsp_ptr->header.dword_2) &
928 MASK_RSP_UPIU_DATA_SEG_LEN;
932 * ufshcd_is_exception_event - Check if the device raised an exception event
933 * @ucd_rsp_ptr: pointer to response UPIU
935 * The function checks if the device raised an exception event indicated in
936 * the Device Information field of response UPIU.
938 * Returns true if exception is raised, false otherwise.
940 static inline bool ufshcd_is_exception_event(struct utp_upiu_rsp *ucd_rsp_ptr)
942 return be32_to_cpu(ucd_rsp_ptr->header.dword_2) &
943 MASK_RSP_EXCEPTION_EVENT;
947 * ufshcd_reset_intr_aggr - Reset interrupt aggregation values.
948 * @hba: per adapter instance
951 ufshcd_reset_intr_aggr(struct ufs_hba *hba)
953 ufshcd_writel(hba, INT_AGGR_ENABLE |
954 INT_AGGR_COUNTER_AND_TIMER_RESET,
955 REG_UTP_TRANSFER_REQ_INT_AGG_CONTROL);
959 * ufshcd_config_intr_aggr - Configure interrupt aggregation values.
960 * @hba: per adapter instance
961 * @cnt: Interrupt aggregation counter threshold
962 * @tmout: Interrupt aggregation timeout value
965 ufshcd_config_intr_aggr(struct ufs_hba *hba, u8 cnt, u8 tmout)
967 ufshcd_writel(hba, INT_AGGR_ENABLE | INT_AGGR_PARAM_WRITE |
968 INT_AGGR_COUNTER_THLD_VAL(cnt) |
969 INT_AGGR_TIMEOUT_VAL(tmout),
970 REG_UTP_TRANSFER_REQ_INT_AGG_CONTROL);
974 * ufshcd_disable_intr_aggr - Disables interrupt aggregation.
975 * @hba: per adapter instance
977 static inline void ufshcd_disable_intr_aggr(struct ufs_hba *hba)
979 ufshcd_writel(hba, 0, REG_UTP_TRANSFER_REQ_INT_AGG_CONTROL);
983 * ufshcd_enable_run_stop_reg - Enable run-stop registers,
984 * When run-stop registers are set to 1, it indicates the
985 * host controller that it can process the requests
986 * @hba: per adapter instance
988 static void ufshcd_enable_run_stop_reg(struct ufs_hba *hba)
990 ufshcd_writel(hba, UTP_TASK_REQ_LIST_RUN_STOP_BIT,
991 REG_UTP_TASK_REQ_LIST_RUN_STOP);
992 ufshcd_writel(hba, UTP_TRANSFER_REQ_LIST_RUN_STOP_BIT,
993 REG_UTP_TRANSFER_REQ_LIST_RUN_STOP);
997 * ufshcd_hba_start - Start controller initialization sequence
998 * @hba: per adapter instance
1000 static inline void ufshcd_hba_start(struct ufs_hba *hba)
1002 u32 val = CONTROLLER_ENABLE;
1004 if (ufshcd_crypto_enable(hba))
1005 val |= CRYPTO_GENERAL_ENABLE;
1007 ufshcd_writel(hba, val, REG_CONTROLLER_ENABLE);
1011 * ufshcd_is_hba_active - Get controller state
1012 * @hba: per adapter instance
1014 * Returns true if and only if the controller is active.
1016 static inline bool ufshcd_is_hba_active(struct ufs_hba *hba)
1018 return ufshcd_readl(hba, REG_CONTROLLER_ENABLE) & CONTROLLER_ENABLE;
1021 u32 ufshcd_get_local_unipro_ver(struct ufs_hba *hba)
1023 /* HCI version 1.0 and 1.1 supports UniPro 1.41 */
1024 if (hba->ufs_version <= ufshci_version(1, 1))
1025 return UFS_UNIPRO_VER_1_41;
1027 return UFS_UNIPRO_VER_1_6;
1029 EXPORT_SYMBOL(ufshcd_get_local_unipro_ver);
1031 static bool ufshcd_is_unipro_pa_params_tuning_req(struct ufs_hba *hba)
1034 * If both host and device support UniPro ver1.6 or later, PA layer
1035 * parameters tuning happens during link startup itself.
1037 * We can manually tune PA layer parameters if either host or device
1038 * doesn't support UniPro ver 1.6 or later. But to keep manual tuning
1039 * logic simple, we will only do manual tuning if local unipro version
1040 * doesn't support ver1.6 or later.
1042 return ufshcd_get_local_unipro_ver(hba) < UFS_UNIPRO_VER_1_6;
1046 * ufshcd_set_clk_freq - set UFS controller clock frequencies
1047 * @hba: per adapter instance
1048 * @scale_up: If True, set max possible frequency othewise set low frequency
1050 * Returns 0 if successful
1051 * Returns < 0 for any other errors
1053 static int ufshcd_set_clk_freq(struct ufs_hba *hba, bool scale_up)
1056 struct ufs_clk_info *clki;
1057 struct list_head *head = &hba->clk_list_head;
1059 if (list_empty(head))
1062 list_for_each_entry(clki, head, list) {
1063 if (!IS_ERR_OR_NULL(clki->clk)) {
1064 if (scale_up && clki->max_freq) {
1065 if (clki->curr_freq == clki->max_freq)
1068 ret = clk_set_rate(clki->clk, clki->max_freq);
1070 dev_err(hba->dev, "%s: %s clk set rate(%dHz) failed, %d\n",
1071 __func__, clki->name,
1072 clki->max_freq, ret);
1075 trace_ufshcd_clk_scaling(dev_name(hba->dev),
1076 "scaled up", clki->name,
1080 clki->curr_freq = clki->max_freq;
1082 } else if (!scale_up && clki->min_freq) {
1083 if (clki->curr_freq == clki->min_freq)
1086 ret = clk_set_rate(clki->clk, clki->min_freq);
1088 dev_err(hba->dev, "%s: %s clk set rate(%dHz) failed, %d\n",
1089 __func__, clki->name,
1090 clki->min_freq, ret);
1093 trace_ufshcd_clk_scaling(dev_name(hba->dev),
1094 "scaled down", clki->name,
1097 clki->curr_freq = clki->min_freq;
1100 dev_dbg(hba->dev, "%s: clk: %s, rate: %lu\n", __func__,
1101 clki->name, clk_get_rate(clki->clk));
1109 * ufshcd_scale_clks - scale up or scale down UFS controller clocks
1110 * @hba: per adapter instance
1111 * @scale_up: True if scaling up and false if scaling down
1113 * Returns 0 if successful
1114 * Returns < 0 for any other errors
1116 static int ufshcd_scale_clks(struct ufs_hba *hba, bool scale_up)
1119 ktime_t start = ktime_get();
1121 ret = ufshcd_vops_clk_scale_notify(hba, scale_up, PRE_CHANGE);
1125 ret = ufshcd_set_clk_freq(hba, scale_up);
1129 ret = ufshcd_vops_clk_scale_notify(hba, scale_up, POST_CHANGE);
1131 ufshcd_set_clk_freq(hba, !scale_up);
1134 trace_ufshcd_profile_clk_scaling(dev_name(hba->dev),
1135 (scale_up ? "up" : "down"),
1136 ktime_to_us(ktime_sub(ktime_get(), start)), ret);
1141 * ufshcd_is_devfreq_scaling_required - check if scaling is required or not
1142 * @hba: per adapter instance
1143 * @scale_up: True if scaling up and false if scaling down
1145 * Returns true if scaling is required, false otherwise.
1147 static bool ufshcd_is_devfreq_scaling_required(struct ufs_hba *hba,
1150 struct ufs_clk_info *clki;
1151 struct list_head *head = &hba->clk_list_head;
1153 if (list_empty(head))
1156 list_for_each_entry(clki, head, list) {
1157 if (!IS_ERR_OR_NULL(clki->clk)) {
1158 if (scale_up && clki->max_freq) {
1159 if (clki->curr_freq == clki->max_freq)
1162 } else if (!scale_up && clki->min_freq) {
1163 if (clki->curr_freq == clki->min_freq)
1174 * Determine the number of pending commands by counting the bits in the SCSI
1175 * device budget maps. This approach has been selected because a bit is set in
1176 * the budget map before scsi_host_queue_ready() checks the host_self_blocked
1177 * flag. The host_self_blocked flag can be modified by calling
1178 * scsi_block_requests() or scsi_unblock_requests().
1180 static u32 ufshcd_pending_cmds(struct ufs_hba *hba)
1182 const struct scsi_device *sdev;
1185 lockdep_assert_held(hba->host->host_lock);
1186 __shost_for_each_device(sdev, hba->host)
1187 pending += sbitmap_weight(&sdev->budget_map);
1193 * Wait until all pending SCSI commands and TMFs have finished or the timeout
1196 * Return: 0 upon success; -EBUSY upon timeout.
1198 static int ufshcd_wait_for_doorbell_clr(struct ufs_hba *hba,
1199 u64 wait_timeout_us)
1201 unsigned long flags;
1205 bool timeout = false, do_last_check = false;
1208 ufshcd_hold(hba, false);
1209 spin_lock_irqsave(hba->host->host_lock, flags);
1211 * Wait for all the outstanding tasks/transfer requests.
1212 * Verify by checking the doorbell registers are clear.
1214 start = ktime_get();
1216 if (hba->ufshcd_state != UFSHCD_STATE_OPERATIONAL) {
1221 tm_doorbell = ufshcd_readl(hba, REG_UTP_TASK_REQ_DOOR_BELL);
1222 tr_pending = ufshcd_pending_cmds(hba);
1223 if (!tm_doorbell && !tr_pending) {
1226 } else if (do_last_check) {
1230 spin_unlock_irqrestore(hba->host->host_lock, flags);
1231 io_schedule_timeout(msecs_to_jiffies(20));
1232 if (ktime_to_us(ktime_sub(ktime_get(), start)) >
1236 * We might have scheduled out for long time so make
1237 * sure to check if doorbells are cleared by this time
1240 do_last_check = true;
1242 spin_lock_irqsave(hba->host->host_lock, flags);
1243 } while (tm_doorbell || tr_pending);
1247 "%s: timedout waiting for doorbell to clear (tm=0x%x, tr=0x%x)\n",
1248 __func__, tm_doorbell, tr_pending);
1252 spin_unlock_irqrestore(hba->host->host_lock, flags);
1253 ufshcd_release(hba);
1258 * ufshcd_scale_gear - scale up/down UFS gear
1259 * @hba: per adapter instance
1260 * @scale_up: True for scaling up gear and false for scaling down
1262 * Returns 0 for success,
1263 * Returns -EBUSY if scaling can't happen at this time
1264 * Returns non-zero for any other errors
1266 static int ufshcd_scale_gear(struct ufs_hba *hba, bool scale_up)
1269 struct ufs_pa_layer_attr new_pwr_info;
1272 memcpy(&new_pwr_info, &hba->clk_scaling.saved_pwr_info,
1273 sizeof(struct ufs_pa_layer_attr));
1275 memcpy(&new_pwr_info, &hba->pwr_info,
1276 sizeof(struct ufs_pa_layer_attr));
1278 if (hba->pwr_info.gear_tx > hba->clk_scaling.min_gear ||
1279 hba->pwr_info.gear_rx > hba->clk_scaling.min_gear) {
1280 /* save the current power mode */
1281 memcpy(&hba->clk_scaling.saved_pwr_info,
1283 sizeof(struct ufs_pa_layer_attr));
1285 /* scale down gear */
1286 new_pwr_info.gear_tx = hba->clk_scaling.min_gear;
1287 new_pwr_info.gear_rx = hba->clk_scaling.min_gear;
1291 /* check if the power mode needs to be changed or not? */
1292 ret = ufshcd_config_pwr_mode(hba, &new_pwr_info);
1294 dev_err(hba->dev, "%s: failed err %d, old gear: (tx %d rx %d), new gear: (tx %d rx %d)",
1296 hba->pwr_info.gear_tx, hba->pwr_info.gear_rx,
1297 new_pwr_info.gear_tx, new_pwr_info.gear_rx);
1303 * Wait until all pending SCSI commands and TMFs have finished or the timeout
1306 * Return: 0 upon success; -EBUSY upon timeout.
1308 static int ufshcd_clock_scaling_prepare(struct ufs_hba *hba, u64 timeout_us)
1312 * make sure that there are no outstanding requests when
1313 * clock scaling is in progress
1315 ufshcd_scsi_block_requests(hba);
1316 mutex_lock(&hba->wb_mutex);
1317 down_write(&hba->clk_scaling_lock);
1319 if (!hba->clk_scaling.is_allowed ||
1320 ufshcd_wait_for_doorbell_clr(hba, timeout_us)) {
1322 up_write(&hba->clk_scaling_lock);
1323 mutex_unlock(&hba->wb_mutex);
1324 ufshcd_scsi_unblock_requests(hba);
1328 /* let's not get into low power until clock scaling is completed */
1329 ufshcd_hold(hba, false);
1335 static void ufshcd_clock_scaling_unprepare(struct ufs_hba *hba, int err, bool scale_up)
1337 up_write(&hba->clk_scaling_lock);
1339 /* Enable Write Booster if we have scaled up else disable it */
1340 if (ufshcd_enable_wb_if_scaling_up(hba) && !err)
1341 ufshcd_wb_toggle(hba, scale_up);
1343 mutex_unlock(&hba->wb_mutex);
1345 ufshcd_scsi_unblock_requests(hba);
1346 ufshcd_release(hba);
1350 * ufshcd_devfreq_scale - scale up/down UFS clocks and gear
1351 * @hba: per adapter instance
1352 * @scale_up: True for scaling up and false for scalin down
1354 * Returns 0 for success,
1355 * Returns -EBUSY if scaling can't happen at this time
1356 * Returns non-zero for any other errors
1358 static int ufshcd_devfreq_scale(struct ufs_hba *hba, bool scale_up)
1362 ret = ufshcd_clock_scaling_prepare(hba, 1 * USEC_PER_SEC);
1366 /* scale down the gear before scaling down clocks */
1368 ret = ufshcd_scale_gear(hba, false);
1373 ret = ufshcd_scale_clks(hba, scale_up);
1376 ufshcd_scale_gear(hba, true);
1380 /* scale up the gear after scaling up clocks */
1382 ret = ufshcd_scale_gear(hba, true);
1384 ufshcd_scale_clks(hba, false);
1390 ufshcd_clock_scaling_unprepare(hba, ret, scale_up);
1394 static void ufshcd_clk_scaling_suspend_work(struct work_struct *work)
1396 struct ufs_hba *hba = container_of(work, struct ufs_hba,
1397 clk_scaling.suspend_work);
1398 unsigned long irq_flags;
1400 spin_lock_irqsave(hba->host->host_lock, irq_flags);
1401 if (hba->clk_scaling.active_reqs || hba->clk_scaling.is_suspended) {
1402 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1405 hba->clk_scaling.is_suspended = true;
1406 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1408 __ufshcd_suspend_clkscaling(hba);
1411 static void ufshcd_clk_scaling_resume_work(struct work_struct *work)
1413 struct ufs_hba *hba = container_of(work, struct ufs_hba,
1414 clk_scaling.resume_work);
1415 unsigned long irq_flags;
1417 spin_lock_irqsave(hba->host->host_lock, irq_flags);
1418 if (!hba->clk_scaling.is_suspended) {
1419 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1422 hba->clk_scaling.is_suspended = false;
1423 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1425 devfreq_resume_device(hba->devfreq);
1428 static int ufshcd_devfreq_target(struct device *dev,
1429 unsigned long *freq, u32 flags)
1432 struct ufs_hba *hba = dev_get_drvdata(dev);
1434 bool scale_up, sched_clk_scaling_suspend_work = false;
1435 struct list_head *clk_list = &hba->clk_list_head;
1436 struct ufs_clk_info *clki;
1437 unsigned long irq_flags;
1439 if (!ufshcd_is_clkscaling_supported(hba))
1442 clki = list_first_entry(&hba->clk_list_head, struct ufs_clk_info, list);
1443 /* Override with the closest supported frequency */
1444 *freq = (unsigned long) clk_round_rate(clki->clk, *freq);
1445 spin_lock_irqsave(hba->host->host_lock, irq_flags);
1446 if (ufshcd_eh_in_progress(hba)) {
1447 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1451 if (!hba->clk_scaling.active_reqs)
1452 sched_clk_scaling_suspend_work = true;
1454 if (list_empty(clk_list)) {
1455 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1459 /* Decide based on the rounded-off frequency and update */
1460 scale_up = *freq == clki->max_freq;
1462 *freq = clki->min_freq;
1463 /* Update the frequency */
1464 if (!ufshcd_is_devfreq_scaling_required(hba, scale_up)) {
1465 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1467 goto out; /* no state change required */
1469 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1471 start = ktime_get();
1472 ret = ufshcd_devfreq_scale(hba, scale_up);
1474 trace_ufshcd_profile_clk_scaling(dev_name(hba->dev),
1475 (scale_up ? "up" : "down"),
1476 ktime_to_us(ktime_sub(ktime_get(), start)), ret);
1479 if (sched_clk_scaling_suspend_work)
1480 queue_work(hba->clk_scaling.workq,
1481 &hba->clk_scaling.suspend_work);
1486 static int ufshcd_devfreq_get_dev_status(struct device *dev,
1487 struct devfreq_dev_status *stat)
1489 struct ufs_hba *hba = dev_get_drvdata(dev);
1490 struct ufs_clk_scaling *scaling = &hba->clk_scaling;
1491 unsigned long flags;
1492 struct list_head *clk_list = &hba->clk_list_head;
1493 struct ufs_clk_info *clki;
1496 if (!ufshcd_is_clkscaling_supported(hba))
1499 memset(stat, 0, sizeof(*stat));
1501 spin_lock_irqsave(hba->host->host_lock, flags);
1502 curr_t = ktime_get();
1503 if (!scaling->window_start_t)
1506 clki = list_first_entry(clk_list, struct ufs_clk_info, list);
1508 * If current frequency is 0, then the ondemand governor considers
1509 * there's no initial frequency set. And it always requests to set
1510 * to max. frequency.
1512 stat->current_frequency = clki->curr_freq;
1513 if (scaling->is_busy_started)
1514 scaling->tot_busy_t += ktime_us_delta(curr_t,
1515 scaling->busy_start_t);
1517 stat->total_time = ktime_us_delta(curr_t, scaling->window_start_t);
1518 stat->busy_time = scaling->tot_busy_t;
1520 scaling->window_start_t = curr_t;
1521 scaling->tot_busy_t = 0;
1523 if (scaling->active_reqs) {
1524 scaling->busy_start_t = curr_t;
1525 scaling->is_busy_started = true;
1527 scaling->busy_start_t = 0;
1528 scaling->is_busy_started = false;
1530 spin_unlock_irqrestore(hba->host->host_lock, flags);
1534 static int ufshcd_devfreq_init(struct ufs_hba *hba)
1536 struct list_head *clk_list = &hba->clk_list_head;
1537 struct ufs_clk_info *clki;
1538 struct devfreq *devfreq;
1541 /* Skip devfreq if we don't have any clocks in the list */
1542 if (list_empty(clk_list))
1545 clki = list_first_entry(clk_list, struct ufs_clk_info, list);
1546 dev_pm_opp_add(hba->dev, clki->min_freq, 0);
1547 dev_pm_opp_add(hba->dev, clki->max_freq, 0);
1549 ufshcd_vops_config_scaling_param(hba, &hba->vps->devfreq_profile,
1550 &hba->vps->ondemand_data);
1551 devfreq = devfreq_add_device(hba->dev,
1552 &hba->vps->devfreq_profile,
1553 DEVFREQ_GOV_SIMPLE_ONDEMAND,
1554 &hba->vps->ondemand_data);
1555 if (IS_ERR(devfreq)) {
1556 ret = PTR_ERR(devfreq);
1557 dev_err(hba->dev, "Unable to register with devfreq %d\n", ret);
1559 dev_pm_opp_remove(hba->dev, clki->min_freq);
1560 dev_pm_opp_remove(hba->dev, clki->max_freq);
1564 hba->devfreq = devfreq;
1569 static void ufshcd_devfreq_remove(struct ufs_hba *hba)
1571 struct list_head *clk_list = &hba->clk_list_head;
1572 struct ufs_clk_info *clki;
1577 devfreq_remove_device(hba->devfreq);
1578 hba->devfreq = NULL;
1580 clki = list_first_entry(clk_list, struct ufs_clk_info, list);
1581 dev_pm_opp_remove(hba->dev, clki->min_freq);
1582 dev_pm_opp_remove(hba->dev, clki->max_freq);
1585 static void __ufshcd_suspend_clkscaling(struct ufs_hba *hba)
1587 unsigned long flags;
1589 devfreq_suspend_device(hba->devfreq);
1590 spin_lock_irqsave(hba->host->host_lock, flags);
1591 hba->clk_scaling.window_start_t = 0;
1592 spin_unlock_irqrestore(hba->host->host_lock, flags);
1595 static void ufshcd_suspend_clkscaling(struct ufs_hba *hba)
1597 unsigned long flags;
1598 bool suspend = false;
1600 cancel_work_sync(&hba->clk_scaling.suspend_work);
1601 cancel_work_sync(&hba->clk_scaling.resume_work);
1603 spin_lock_irqsave(hba->host->host_lock, flags);
1604 if (!hba->clk_scaling.is_suspended) {
1606 hba->clk_scaling.is_suspended = true;
1608 spin_unlock_irqrestore(hba->host->host_lock, flags);
1611 __ufshcd_suspend_clkscaling(hba);
1614 static void ufshcd_resume_clkscaling(struct ufs_hba *hba)
1616 unsigned long flags;
1617 bool resume = false;
1619 spin_lock_irqsave(hba->host->host_lock, flags);
1620 if (hba->clk_scaling.is_suspended) {
1622 hba->clk_scaling.is_suspended = false;
1624 spin_unlock_irqrestore(hba->host->host_lock, flags);
1627 devfreq_resume_device(hba->devfreq);
1630 static ssize_t ufshcd_clkscale_enable_show(struct device *dev,
1631 struct device_attribute *attr, char *buf)
1633 struct ufs_hba *hba = dev_get_drvdata(dev);
1635 return sysfs_emit(buf, "%d\n", hba->clk_scaling.is_enabled);
1638 static ssize_t ufshcd_clkscale_enable_store(struct device *dev,
1639 struct device_attribute *attr, const char *buf, size_t count)
1641 struct ufs_hba *hba = dev_get_drvdata(dev);
1645 if (kstrtou32(buf, 0, &value))
1648 down(&hba->host_sem);
1649 if (!ufshcd_is_user_access_allowed(hba)) {
1655 if (value == hba->clk_scaling.is_enabled)
1658 ufshcd_rpm_get_sync(hba);
1659 ufshcd_hold(hba, false);
1661 hba->clk_scaling.is_enabled = value;
1664 ufshcd_resume_clkscaling(hba);
1666 ufshcd_suspend_clkscaling(hba);
1667 err = ufshcd_devfreq_scale(hba, true);
1669 dev_err(hba->dev, "%s: failed to scale clocks up %d\n",
1673 ufshcd_release(hba);
1674 ufshcd_rpm_put_sync(hba);
1677 return err ? err : count;
1680 static void ufshcd_init_clk_scaling_sysfs(struct ufs_hba *hba)
1682 hba->clk_scaling.enable_attr.show = ufshcd_clkscale_enable_show;
1683 hba->clk_scaling.enable_attr.store = ufshcd_clkscale_enable_store;
1684 sysfs_attr_init(&hba->clk_scaling.enable_attr.attr);
1685 hba->clk_scaling.enable_attr.attr.name = "clkscale_enable";
1686 hba->clk_scaling.enable_attr.attr.mode = 0644;
1687 if (device_create_file(hba->dev, &hba->clk_scaling.enable_attr))
1688 dev_err(hba->dev, "Failed to create sysfs for clkscale_enable\n");
1691 static void ufshcd_remove_clk_scaling_sysfs(struct ufs_hba *hba)
1693 if (hba->clk_scaling.enable_attr.attr.name)
1694 device_remove_file(hba->dev, &hba->clk_scaling.enable_attr);
1697 static void ufshcd_init_clk_scaling(struct ufs_hba *hba)
1699 char wq_name[sizeof("ufs_clkscaling_00")];
1701 if (!ufshcd_is_clkscaling_supported(hba))
1704 if (!hba->clk_scaling.min_gear)
1705 hba->clk_scaling.min_gear = UFS_HS_G1;
1707 INIT_WORK(&hba->clk_scaling.suspend_work,
1708 ufshcd_clk_scaling_suspend_work);
1709 INIT_WORK(&hba->clk_scaling.resume_work,
1710 ufshcd_clk_scaling_resume_work);
1712 snprintf(wq_name, sizeof(wq_name), "ufs_clkscaling_%d",
1713 hba->host->host_no);
1714 hba->clk_scaling.workq = create_singlethread_workqueue(wq_name);
1716 hba->clk_scaling.is_initialized = true;
1719 static void ufshcd_exit_clk_scaling(struct ufs_hba *hba)
1721 if (!hba->clk_scaling.is_initialized)
1724 ufshcd_remove_clk_scaling_sysfs(hba);
1725 destroy_workqueue(hba->clk_scaling.workq);
1726 ufshcd_devfreq_remove(hba);
1727 hba->clk_scaling.is_initialized = false;
1730 static void ufshcd_ungate_work(struct work_struct *work)
1733 unsigned long flags;
1734 struct ufs_hba *hba = container_of(work, struct ufs_hba,
1735 clk_gating.ungate_work);
1737 cancel_delayed_work_sync(&hba->clk_gating.gate_work);
1739 spin_lock_irqsave(hba->host->host_lock, flags);
1740 if (hba->clk_gating.state == CLKS_ON) {
1741 spin_unlock_irqrestore(hba->host->host_lock, flags);
1745 spin_unlock_irqrestore(hba->host->host_lock, flags);
1746 ufshcd_hba_vreg_set_hpm(hba);
1747 ufshcd_setup_clocks(hba, true);
1749 ufshcd_enable_irq(hba);
1751 /* Exit from hibern8 */
1752 if (ufshcd_can_hibern8_during_gating(hba)) {
1753 /* Prevent gating in this path */
1754 hba->clk_gating.is_suspended = true;
1755 if (ufshcd_is_link_hibern8(hba)) {
1756 ret = ufshcd_uic_hibern8_exit(hba);
1758 dev_err(hba->dev, "%s: hibern8 exit failed %d\n",
1761 ufshcd_set_link_active(hba);
1763 hba->clk_gating.is_suspended = false;
1766 ufshcd_scsi_unblock_requests(hba);
1770 * ufshcd_hold - Enable clocks that were gated earlier due to ufshcd_release.
1771 * Also, exit from hibern8 mode and set the link as active.
1772 * @hba: per adapter instance
1773 * @async: This indicates whether caller should ungate clocks asynchronously.
1775 int ufshcd_hold(struct ufs_hba *hba, bool async)
1779 unsigned long flags;
1781 if (!ufshcd_is_clkgating_allowed(hba) ||
1782 !hba->clk_gating.is_initialized)
1784 spin_lock_irqsave(hba->host->host_lock, flags);
1785 hba->clk_gating.active_reqs++;
1788 switch (hba->clk_gating.state) {
1791 * Wait for the ungate work to complete if in progress.
1792 * Though the clocks may be in ON state, the link could
1793 * still be in hibner8 state if hibern8 is allowed
1794 * during clock gating.
1795 * Make sure we exit hibern8 state also in addition to
1798 if (ufshcd_can_hibern8_during_gating(hba) &&
1799 ufshcd_is_link_hibern8(hba)) {
1802 hba->clk_gating.active_reqs--;
1805 spin_unlock_irqrestore(hba->host->host_lock, flags);
1806 flush_result = flush_work(&hba->clk_gating.ungate_work);
1807 if (hba->clk_gating.is_suspended && !flush_result)
1809 spin_lock_irqsave(hba->host->host_lock, flags);
1814 if (cancel_delayed_work(&hba->clk_gating.gate_work)) {
1815 hba->clk_gating.state = CLKS_ON;
1816 trace_ufshcd_clk_gating(dev_name(hba->dev),
1817 hba->clk_gating.state);
1821 * If we are here, it means gating work is either done or
1822 * currently running. Hence, fall through to cancel gating
1823 * work and to enable clocks.
1827 hba->clk_gating.state = REQ_CLKS_ON;
1828 trace_ufshcd_clk_gating(dev_name(hba->dev),
1829 hba->clk_gating.state);
1830 if (queue_work(hba->clk_gating.clk_gating_workq,
1831 &hba->clk_gating.ungate_work))
1832 ufshcd_scsi_block_requests(hba);
1834 * fall through to check if we should wait for this
1835 * work to be done or not.
1841 hba->clk_gating.active_reqs--;
1845 spin_unlock_irqrestore(hba->host->host_lock, flags);
1846 flush_work(&hba->clk_gating.ungate_work);
1847 /* Make sure state is CLKS_ON before returning */
1848 spin_lock_irqsave(hba->host->host_lock, flags);
1851 dev_err(hba->dev, "%s: clk gating is in invalid state %d\n",
1852 __func__, hba->clk_gating.state);
1855 spin_unlock_irqrestore(hba->host->host_lock, flags);
1859 EXPORT_SYMBOL_GPL(ufshcd_hold);
1861 static void ufshcd_gate_work(struct work_struct *work)
1863 struct ufs_hba *hba = container_of(work, struct ufs_hba,
1864 clk_gating.gate_work.work);
1865 unsigned long flags;
1868 spin_lock_irqsave(hba->host->host_lock, flags);
1870 * In case you are here to cancel this work the gating state
1871 * would be marked as REQ_CLKS_ON. In this case save time by
1872 * skipping the gating work and exit after changing the clock
1875 if (hba->clk_gating.is_suspended ||
1876 (hba->clk_gating.state != REQ_CLKS_OFF)) {
1877 hba->clk_gating.state = CLKS_ON;
1878 trace_ufshcd_clk_gating(dev_name(hba->dev),
1879 hba->clk_gating.state);
1883 if (hba->clk_gating.active_reqs
1884 || hba->ufshcd_state != UFSHCD_STATE_OPERATIONAL
1885 || hba->outstanding_reqs || hba->outstanding_tasks
1886 || hba->active_uic_cmd || hba->uic_async_done)
1889 spin_unlock_irqrestore(hba->host->host_lock, flags);
1891 /* put the link into hibern8 mode before turning off clocks */
1892 if (ufshcd_can_hibern8_during_gating(hba)) {
1893 ret = ufshcd_uic_hibern8_enter(hba);
1895 hba->clk_gating.state = CLKS_ON;
1896 dev_err(hba->dev, "%s: hibern8 enter failed %d\n",
1898 trace_ufshcd_clk_gating(dev_name(hba->dev),
1899 hba->clk_gating.state);
1902 ufshcd_set_link_hibern8(hba);
1905 ufshcd_disable_irq(hba);
1907 ufshcd_setup_clocks(hba, false);
1909 /* Put the host controller in low power mode if possible */
1910 ufshcd_hba_vreg_set_lpm(hba);
1912 * In case you are here to cancel this work the gating state
1913 * would be marked as REQ_CLKS_ON. In this case keep the state
1914 * as REQ_CLKS_ON which would anyway imply that clocks are off
1915 * and a request to turn them on is pending. By doing this way,
1916 * we keep the state machine in tact and this would ultimately
1917 * prevent from doing cancel work multiple times when there are
1918 * new requests arriving before the current cancel work is done.
1920 spin_lock_irqsave(hba->host->host_lock, flags);
1921 if (hba->clk_gating.state == REQ_CLKS_OFF) {
1922 hba->clk_gating.state = CLKS_OFF;
1923 trace_ufshcd_clk_gating(dev_name(hba->dev),
1924 hba->clk_gating.state);
1927 spin_unlock_irqrestore(hba->host->host_lock, flags);
1932 /* host lock must be held before calling this variant */
1933 static void __ufshcd_release(struct ufs_hba *hba)
1935 if (!ufshcd_is_clkgating_allowed(hba))
1938 hba->clk_gating.active_reqs--;
1940 if (hba->clk_gating.active_reqs || hba->clk_gating.is_suspended ||
1941 hba->ufshcd_state != UFSHCD_STATE_OPERATIONAL ||
1942 hba->outstanding_tasks || !hba->clk_gating.is_initialized ||
1943 hba->active_uic_cmd || hba->uic_async_done ||
1944 hba->clk_gating.state == CLKS_OFF)
1947 hba->clk_gating.state = REQ_CLKS_OFF;
1948 trace_ufshcd_clk_gating(dev_name(hba->dev), hba->clk_gating.state);
1949 queue_delayed_work(hba->clk_gating.clk_gating_workq,
1950 &hba->clk_gating.gate_work,
1951 msecs_to_jiffies(hba->clk_gating.delay_ms));
1954 void ufshcd_release(struct ufs_hba *hba)
1956 unsigned long flags;
1958 spin_lock_irqsave(hba->host->host_lock, flags);
1959 __ufshcd_release(hba);
1960 spin_unlock_irqrestore(hba->host->host_lock, flags);
1962 EXPORT_SYMBOL_GPL(ufshcd_release);
1964 static ssize_t ufshcd_clkgate_delay_show(struct device *dev,
1965 struct device_attribute *attr, char *buf)
1967 struct ufs_hba *hba = dev_get_drvdata(dev);
1969 return sysfs_emit(buf, "%lu\n", hba->clk_gating.delay_ms);
1972 void ufshcd_clkgate_delay_set(struct device *dev, unsigned long value)
1974 struct ufs_hba *hba = dev_get_drvdata(dev);
1975 unsigned long flags;
1977 spin_lock_irqsave(hba->host->host_lock, flags);
1978 hba->clk_gating.delay_ms = value;
1979 spin_unlock_irqrestore(hba->host->host_lock, flags);
1981 EXPORT_SYMBOL_GPL(ufshcd_clkgate_delay_set);
1983 static ssize_t ufshcd_clkgate_delay_store(struct device *dev,
1984 struct device_attribute *attr, const char *buf, size_t count)
1986 unsigned long value;
1988 if (kstrtoul(buf, 0, &value))
1991 ufshcd_clkgate_delay_set(dev, value);
1995 static ssize_t ufshcd_clkgate_enable_show(struct device *dev,
1996 struct device_attribute *attr, char *buf)
1998 struct ufs_hba *hba = dev_get_drvdata(dev);
2000 return sysfs_emit(buf, "%d\n", hba->clk_gating.is_enabled);
2003 static ssize_t ufshcd_clkgate_enable_store(struct device *dev,
2004 struct device_attribute *attr, const char *buf, size_t count)
2006 struct ufs_hba *hba = dev_get_drvdata(dev);
2007 unsigned long flags;
2010 if (kstrtou32(buf, 0, &value))
2015 spin_lock_irqsave(hba->host->host_lock, flags);
2016 if (value == hba->clk_gating.is_enabled)
2020 __ufshcd_release(hba);
2022 hba->clk_gating.active_reqs++;
2024 hba->clk_gating.is_enabled = value;
2026 spin_unlock_irqrestore(hba->host->host_lock, flags);
2030 static void ufshcd_init_clk_gating_sysfs(struct ufs_hba *hba)
2032 hba->clk_gating.delay_attr.show = ufshcd_clkgate_delay_show;
2033 hba->clk_gating.delay_attr.store = ufshcd_clkgate_delay_store;
2034 sysfs_attr_init(&hba->clk_gating.delay_attr.attr);
2035 hba->clk_gating.delay_attr.attr.name = "clkgate_delay_ms";
2036 hba->clk_gating.delay_attr.attr.mode = 0644;
2037 if (device_create_file(hba->dev, &hba->clk_gating.delay_attr))
2038 dev_err(hba->dev, "Failed to create sysfs for clkgate_delay\n");
2040 hba->clk_gating.enable_attr.show = ufshcd_clkgate_enable_show;
2041 hba->clk_gating.enable_attr.store = ufshcd_clkgate_enable_store;
2042 sysfs_attr_init(&hba->clk_gating.enable_attr.attr);
2043 hba->clk_gating.enable_attr.attr.name = "clkgate_enable";
2044 hba->clk_gating.enable_attr.attr.mode = 0644;
2045 if (device_create_file(hba->dev, &hba->clk_gating.enable_attr))
2046 dev_err(hba->dev, "Failed to create sysfs for clkgate_enable\n");
2049 static void ufshcd_remove_clk_gating_sysfs(struct ufs_hba *hba)
2051 if (hba->clk_gating.delay_attr.attr.name)
2052 device_remove_file(hba->dev, &hba->clk_gating.delay_attr);
2053 if (hba->clk_gating.enable_attr.attr.name)
2054 device_remove_file(hba->dev, &hba->clk_gating.enable_attr);
2057 static void ufshcd_init_clk_gating(struct ufs_hba *hba)
2059 char wq_name[sizeof("ufs_clk_gating_00")];
2061 if (!ufshcd_is_clkgating_allowed(hba))
2064 hba->clk_gating.state = CLKS_ON;
2066 hba->clk_gating.delay_ms = 150;
2067 INIT_DELAYED_WORK(&hba->clk_gating.gate_work, ufshcd_gate_work);
2068 INIT_WORK(&hba->clk_gating.ungate_work, ufshcd_ungate_work);
2070 snprintf(wq_name, ARRAY_SIZE(wq_name), "ufs_clk_gating_%d",
2071 hba->host->host_no);
2072 hba->clk_gating.clk_gating_workq = alloc_ordered_workqueue(wq_name,
2073 WQ_MEM_RECLAIM | WQ_HIGHPRI);
2075 ufshcd_init_clk_gating_sysfs(hba);
2077 hba->clk_gating.is_enabled = true;
2078 hba->clk_gating.is_initialized = true;
2081 static void ufshcd_exit_clk_gating(struct ufs_hba *hba)
2083 if (!hba->clk_gating.is_initialized)
2086 ufshcd_remove_clk_gating_sysfs(hba);
2088 /* Ungate the clock if necessary. */
2089 ufshcd_hold(hba, false);
2090 hba->clk_gating.is_initialized = false;
2091 ufshcd_release(hba);
2093 destroy_workqueue(hba->clk_gating.clk_gating_workq);
2096 static void ufshcd_clk_scaling_start_busy(struct ufs_hba *hba)
2098 bool queue_resume_work = false;
2099 ktime_t curr_t = ktime_get();
2100 unsigned long flags;
2102 if (!ufshcd_is_clkscaling_supported(hba))
2105 spin_lock_irqsave(hba->host->host_lock, flags);
2106 if (!hba->clk_scaling.active_reqs++)
2107 queue_resume_work = true;
2109 if (!hba->clk_scaling.is_enabled || hba->pm_op_in_progress) {
2110 spin_unlock_irqrestore(hba->host->host_lock, flags);
2114 if (queue_resume_work)
2115 queue_work(hba->clk_scaling.workq,
2116 &hba->clk_scaling.resume_work);
2118 if (!hba->clk_scaling.window_start_t) {
2119 hba->clk_scaling.window_start_t = curr_t;
2120 hba->clk_scaling.tot_busy_t = 0;
2121 hba->clk_scaling.is_busy_started = false;
2124 if (!hba->clk_scaling.is_busy_started) {
2125 hba->clk_scaling.busy_start_t = curr_t;
2126 hba->clk_scaling.is_busy_started = true;
2128 spin_unlock_irqrestore(hba->host->host_lock, flags);
2131 static void ufshcd_clk_scaling_update_busy(struct ufs_hba *hba)
2133 struct ufs_clk_scaling *scaling = &hba->clk_scaling;
2134 unsigned long flags;
2136 if (!ufshcd_is_clkscaling_supported(hba))
2139 spin_lock_irqsave(hba->host->host_lock, flags);
2140 hba->clk_scaling.active_reqs--;
2141 if (!scaling->active_reqs && scaling->is_busy_started) {
2142 scaling->tot_busy_t += ktime_to_us(ktime_sub(ktime_get(),
2143 scaling->busy_start_t));
2144 scaling->busy_start_t = 0;
2145 scaling->is_busy_started = false;
2147 spin_unlock_irqrestore(hba->host->host_lock, flags);
2150 static inline int ufshcd_monitor_opcode2dir(u8 opcode)
2152 if (opcode == READ_6 || opcode == READ_10 || opcode == READ_16)
2154 else if (opcode == WRITE_6 || opcode == WRITE_10 || opcode == WRITE_16)
2160 static inline bool ufshcd_should_inform_monitor(struct ufs_hba *hba,
2161 struct ufshcd_lrb *lrbp)
2163 const struct ufs_hba_monitor *m = &hba->monitor;
2165 return (m->enabled && lrbp && lrbp->cmd &&
2166 (!m->chunk_size || m->chunk_size == lrbp->cmd->sdb.length) &&
2167 ktime_before(hba->monitor.enabled_ts, lrbp->issue_time_stamp));
2170 static void ufshcd_start_monitor(struct ufs_hba *hba,
2171 const struct ufshcd_lrb *lrbp)
2173 int dir = ufshcd_monitor_opcode2dir(*lrbp->cmd->cmnd);
2174 unsigned long flags;
2176 spin_lock_irqsave(hba->host->host_lock, flags);
2177 if (dir >= 0 && hba->monitor.nr_queued[dir]++ == 0)
2178 hba->monitor.busy_start_ts[dir] = ktime_get();
2179 spin_unlock_irqrestore(hba->host->host_lock, flags);
2182 static void ufshcd_update_monitor(struct ufs_hba *hba, const struct ufshcd_lrb *lrbp)
2184 int dir = ufshcd_monitor_opcode2dir(*lrbp->cmd->cmnd);
2185 unsigned long flags;
2187 spin_lock_irqsave(hba->host->host_lock, flags);
2188 if (dir >= 0 && hba->monitor.nr_queued[dir] > 0) {
2189 const struct request *req = scsi_cmd_to_rq(lrbp->cmd);
2190 struct ufs_hba_monitor *m = &hba->monitor;
2191 ktime_t now, inc, lat;
2193 now = lrbp->compl_time_stamp;
2194 inc = ktime_sub(now, m->busy_start_ts[dir]);
2195 m->total_busy[dir] = ktime_add(m->total_busy[dir], inc);
2196 m->nr_sec_rw[dir] += blk_rq_sectors(req);
2198 /* Update latencies */
2200 lat = ktime_sub(now, lrbp->issue_time_stamp);
2201 m->lat_sum[dir] += lat;
2202 if (m->lat_max[dir] < lat || !m->lat_max[dir])
2203 m->lat_max[dir] = lat;
2204 if (m->lat_min[dir] > lat || !m->lat_min[dir])
2205 m->lat_min[dir] = lat;
2207 m->nr_queued[dir]--;
2208 /* Push forward the busy start of monitor */
2209 m->busy_start_ts[dir] = now;
2211 spin_unlock_irqrestore(hba->host->host_lock, flags);
2215 * ufshcd_send_command - Send SCSI or device management commands
2216 * @hba: per adapter instance
2217 * @task_tag: Task tag of the command
2218 * @hwq: pointer to hardware queue instance
2221 void ufshcd_send_command(struct ufs_hba *hba, unsigned int task_tag,
2222 struct ufs_hw_queue *hwq)
2224 struct ufshcd_lrb *lrbp = &hba->lrb[task_tag];
2225 unsigned long flags;
2227 lrbp->issue_time_stamp = ktime_get();
2228 lrbp->issue_time_stamp_local_clock = local_clock();
2229 lrbp->compl_time_stamp = ktime_set(0, 0);
2230 lrbp->compl_time_stamp_local_clock = 0;
2231 ufshcd_add_command_trace(hba, task_tag, UFS_CMD_SEND);
2232 ufshcd_clk_scaling_start_busy(hba);
2233 if (unlikely(ufshcd_should_inform_monitor(hba, lrbp)))
2234 ufshcd_start_monitor(hba, lrbp);
2236 if (is_mcq_enabled(hba)) {
2237 int utrd_size = sizeof(struct utp_transfer_req_desc);
2238 struct utp_transfer_req_desc *src = lrbp->utr_descriptor_ptr;
2239 struct utp_transfer_req_desc *dest = hwq->sqe_base_addr + hwq->sq_tail_slot;
2241 spin_lock(&hwq->sq_lock);
2242 memcpy(dest, src, utrd_size);
2243 ufshcd_inc_sq_tail(hwq);
2244 spin_unlock(&hwq->sq_lock);
2246 spin_lock_irqsave(&hba->outstanding_lock, flags);
2247 if (hba->vops && hba->vops->setup_xfer_req)
2248 hba->vops->setup_xfer_req(hba, lrbp->task_tag,
2250 __set_bit(lrbp->task_tag, &hba->outstanding_reqs);
2251 ufshcd_writel(hba, 1 << lrbp->task_tag,
2252 REG_UTP_TRANSFER_REQ_DOOR_BELL);
2253 spin_unlock_irqrestore(&hba->outstanding_lock, flags);
2258 * ufshcd_copy_sense_data - Copy sense data in case of check condition
2259 * @lrbp: pointer to local reference block
2261 static inline void ufshcd_copy_sense_data(struct ufshcd_lrb *lrbp)
2263 u8 *const sense_buffer = lrbp->cmd->sense_buffer;
2267 ufshcd_get_rsp_upiu_data_seg_len(lrbp->ucd_rsp_ptr)) {
2270 len = be16_to_cpu(lrbp->ucd_rsp_ptr->sr.sense_data_len);
2271 len_to_copy = min_t(int, UFS_SENSE_SIZE, len);
2273 memcpy(sense_buffer, lrbp->ucd_rsp_ptr->sr.sense_data,
2279 * ufshcd_copy_query_response() - Copy the Query Response and the data
2281 * @hba: per adapter instance
2282 * @lrbp: pointer to local reference block
2285 int ufshcd_copy_query_response(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
2287 struct ufs_query_res *query_res = &hba->dev_cmd.query.response;
2289 memcpy(&query_res->upiu_res, &lrbp->ucd_rsp_ptr->qr, QUERY_OSF_SIZE);
2291 /* Get the descriptor */
2292 if (hba->dev_cmd.query.descriptor &&
2293 lrbp->ucd_rsp_ptr->qr.opcode == UPIU_QUERY_OPCODE_READ_DESC) {
2294 u8 *descp = (u8 *)lrbp->ucd_rsp_ptr +
2295 GENERAL_UPIU_REQUEST_SIZE;
2299 /* data segment length */
2300 resp_len = be32_to_cpu(lrbp->ucd_rsp_ptr->header.dword_2) &
2301 MASK_QUERY_DATA_SEG_LEN;
2302 buf_len = be16_to_cpu(
2303 hba->dev_cmd.query.request.upiu_req.length);
2304 if (likely(buf_len >= resp_len)) {
2305 memcpy(hba->dev_cmd.query.descriptor, descp, resp_len);
2308 "%s: rsp size %d is bigger than buffer size %d",
2309 __func__, resp_len, buf_len);
2318 * ufshcd_hba_capabilities - Read controller capabilities
2319 * @hba: per adapter instance
2321 * Return: 0 on success, negative on error.
2323 static inline int ufshcd_hba_capabilities(struct ufs_hba *hba)
2327 hba->capabilities = ufshcd_readl(hba, REG_CONTROLLER_CAPABILITIES);
2328 if (hba->quirks & UFSHCD_QUIRK_BROKEN_64BIT_ADDRESS)
2329 hba->capabilities &= ~MASK_64_ADDRESSING_SUPPORT;
2331 /* nutrs and nutmrs are 0 based values */
2332 hba->nutrs = (hba->capabilities & MASK_TRANSFER_REQUESTS_SLOTS) + 1;
2334 ((hba->capabilities & MASK_TASK_MANAGEMENT_REQUEST_SLOTS) >> 16) + 1;
2335 hba->reserved_slot = hba->nutrs - 1;
2337 /* Read crypto capabilities */
2338 err = ufshcd_hba_init_crypto_capabilities(hba);
2340 dev_err(hba->dev, "crypto setup failed\n");
2342 hba->mcq_sup = FIELD_GET(MASK_MCQ_SUPPORT, hba->capabilities);
2346 hba->mcq_capabilities = ufshcd_readl(hba, REG_MCQCAP);
2347 hba->ext_iid_sup = FIELD_GET(MASK_EXT_IID_SUPPORT,
2348 hba->mcq_capabilities);
2354 * ufshcd_ready_for_uic_cmd - Check if controller is ready
2355 * to accept UIC commands
2356 * @hba: per adapter instance
2357 * Return true on success, else false
2359 static inline bool ufshcd_ready_for_uic_cmd(struct ufs_hba *hba)
2361 return ufshcd_readl(hba, REG_CONTROLLER_STATUS) & UIC_COMMAND_READY;
2365 * ufshcd_get_upmcrs - Get the power mode change request status
2366 * @hba: Pointer to adapter instance
2368 * This function gets the UPMCRS field of HCS register
2369 * Returns value of UPMCRS field
2371 static inline u8 ufshcd_get_upmcrs(struct ufs_hba *hba)
2373 return (ufshcd_readl(hba, REG_CONTROLLER_STATUS) >> 8) & 0x7;
2377 * ufshcd_dispatch_uic_cmd - Dispatch an UIC command to the Unipro layer
2378 * @hba: per adapter instance
2379 * @uic_cmd: UIC command
2382 ufshcd_dispatch_uic_cmd(struct ufs_hba *hba, struct uic_command *uic_cmd)
2384 lockdep_assert_held(&hba->uic_cmd_mutex);
2386 WARN_ON(hba->active_uic_cmd);
2388 hba->active_uic_cmd = uic_cmd;
2391 ufshcd_writel(hba, uic_cmd->argument1, REG_UIC_COMMAND_ARG_1);
2392 ufshcd_writel(hba, uic_cmd->argument2, REG_UIC_COMMAND_ARG_2);
2393 ufshcd_writel(hba, uic_cmd->argument3, REG_UIC_COMMAND_ARG_3);
2395 ufshcd_add_uic_command_trace(hba, uic_cmd, UFS_CMD_SEND);
2398 ufshcd_writel(hba, uic_cmd->command & COMMAND_OPCODE_MASK,
2403 * ufshcd_wait_for_uic_cmd - Wait for completion of an UIC command
2404 * @hba: per adapter instance
2405 * @uic_cmd: UIC command
2407 * Returns 0 only if success.
2410 ufshcd_wait_for_uic_cmd(struct ufs_hba *hba, struct uic_command *uic_cmd)
2413 unsigned long flags;
2415 lockdep_assert_held(&hba->uic_cmd_mutex);
2417 if (wait_for_completion_timeout(&uic_cmd->done,
2418 msecs_to_jiffies(UIC_CMD_TIMEOUT))) {
2419 ret = uic_cmd->argument2 & MASK_UIC_COMMAND_RESULT;
2423 "uic cmd 0x%x with arg3 0x%x completion timeout\n",
2424 uic_cmd->command, uic_cmd->argument3);
2426 if (!uic_cmd->cmd_active) {
2427 dev_err(hba->dev, "%s: UIC cmd has been completed, return the result\n",
2429 ret = uic_cmd->argument2 & MASK_UIC_COMMAND_RESULT;
2433 spin_lock_irqsave(hba->host->host_lock, flags);
2434 hba->active_uic_cmd = NULL;
2435 spin_unlock_irqrestore(hba->host->host_lock, flags);
2441 * __ufshcd_send_uic_cmd - Send UIC commands and retrieve the result
2442 * @hba: per adapter instance
2443 * @uic_cmd: UIC command
2444 * @completion: initialize the completion only if this is set to true
2446 * Returns 0 only if success.
2449 __ufshcd_send_uic_cmd(struct ufs_hba *hba, struct uic_command *uic_cmd,
2452 lockdep_assert_held(&hba->uic_cmd_mutex);
2453 lockdep_assert_held(hba->host->host_lock);
2455 if (!ufshcd_ready_for_uic_cmd(hba)) {
2457 "Controller not ready to accept UIC commands\n");
2462 init_completion(&uic_cmd->done);
2464 uic_cmd->cmd_active = 1;
2465 ufshcd_dispatch_uic_cmd(hba, uic_cmd);
2471 * ufshcd_send_uic_cmd - Send UIC commands and retrieve the result
2472 * @hba: per adapter instance
2473 * @uic_cmd: UIC command
2475 * Returns 0 only if success.
2477 int ufshcd_send_uic_cmd(struct ufs_hba *hba, struct uic_command *uic_cmd)
2480 unsigned long flags;
2482 if (hba->quirks & UFSHCD_QUIRK_BROKEN_UIC_CMD)
2485 ufshcd_hold(hba, false);
2486 mutex_lock(&hba->uic_cmd_mutex);
2487 ufshcd_add_delay_before_dme_cmd(hba);
2489 spin_lock_irqsave(hba->host->host_lock, flags);
2490 ret = __ufshcd_send_uic_cmd(hba, uic_cmd, true);
2491 spin_unlock_irqrestore(hba->host->host_lock, flags);
2493 ret = ufshcd_wait_for_uic_cmd(hba, uic_cmd);
2495 mutex_unlock(&hba->uic_cmd_mutex);
2497 ufshcd_release(hba);
2502 * ufshcd_sgl_to_prdt - SG list to PRTD (Physical Region Description Table, 4DW format)
2503 * @hba: per-adapter instance
2504 * @lrbp: pointer to local reference block
2505 * @sg_entries: The number of sg lists actually used
2506 * @sg_list: Pointer to SG list
2508 static void ufshcd_sgl_to_prdt(struct ufs_hba *hba, struct ufshcd_lrb *lrbp, int sg_entries,
2509 struct scatterlist *sg_list)
2511 struct ufshcd_sg_entry *prd;
2512 struct scatterlist *sg;
2517 if (hba->quirks & UFSHCD_QUIRK_PRDT_BYTE_GRAN)
2518 lrbp->utr_descriptor_ptr->prd_table_length =
2519 cpu_to_le16(sg_entries * ufshcd_sg_entry_size(hba));
2521 lrbp->utr_descriptor_ptr->prd_table_length = cpu_to_le16(sg_entries);
2523 prd = lrbp->ucd_prdt_ptr;
2525 for_each_sg(sg_list, sg, sg_entries, i) {
2526 const unsigned int len = sg_dma_len(sg);
2529 * From the UFSHCI spec: "Data Byte Count (DBC): A '0'
2530 * based value that indicates the length, in bytes, of
2531 * the data block. A maximum of length of 256KB may
2532 * exist for any entry. Bits 1:0 of this field shall be
2533 * 11b to indicate Dword granularity. A value of '3'
2534 * indicates 4 bytes, '7' indicates 8 bytes, etc."
2536 WARN_ONCE(len > 256 * 1024, "len = %#x\n", len);
2537 prd->size = cpu_to_le32(len - 1);
2538 prd->addr = cpu_to_le64(sg->dma_address);
2540 prd = (void *)prd + ufshcd_sg_entry_size(hba);
2543 lrbp->utr_descriptor_ptr->prd_table_length = 0;
2548 * ufshcd_map_sg - Map scatter-gather list to prdt
2549 * @hba: per adapter instance
2550 * @lrbp: pointer to local reference block
2552 * Returns 0 in case of success, non-zero value in case of failure
2554 static int ufshcd_map_sg(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
2556 struct scsi_cmnd *cmd = lrbp->cmd;
2557 int sg_segments = scsi_dma_map(cmd);
2559 if (sg_segments < 0)
2562 ufshcd_sgl_to_prdt(hba, lrbp, sg_segments, scsi_sglist(cmd));
2568 * ufshcd_enable_intr - enable interrupts
2569 * @hba: per adapter instance
2570 * @intrs: interrupt bits
2572 static void ufshcd_enable_intr(struct ufs_hba *hba, u32 intrs)
2574 u32 set = ufshcd_readl(hba, REG_INTERRUPT_ENABLE);
2576 if (hba->ufs_version == ufshci_version(1, 0)) {
2578 rw = set & INTERRUPT_MASK_RW_VER_10;
2579 set = rw | ((set ^ intrs) & intrs);
2584 ufshcd_writel(hba, set, REG_INTERRUPT_ENABLE);
2588 * ufshcd_disable_intr - disable interrupts
2589 * @hba: per adapter instance
2590 * @intrs: interrupt bits
2592 static void ufshcd_disable_intr(struct ufs_hba *hba, u32 intrs)
2594 u32 set = ufshcd_readl(hba, REG_INTERRUPT_ENABLE);
2596 if (hba->ufs_version == ufshci_version(1, 0)) {
2598 rw = (set & INTERRUPT_MASK_RW_VER_10) &
2599 ~(intrs & INTERRUPT_MASK_RW_VER_10);
2600 set = rw | ((set & intrs) & ~INTERRUPT_MASK_RW_VER_10);
2606 ufshcd_writel(hba, set, REG_INTERRUPT_ENABLE);
2610 * ufshcd_prepare_req_desc_hdr - Fill UTP Transfer request descriptor header according to request
2611 * descriptor according to request
2612 * @lrbp: pointer to local reference block
2613 * @upiu_flags: flags required in the header
2614 * @cmd_dir: requests data direction
2615 * @ehs_length: Total EHS Length (in 32‐bytes units of all Extra Header Segments)
2617 static void ufshcd_prepare_req_desc_hdr(struct ufshcd_lrb *lrbp, u8 *upiu_flags,
2618 enum dma_data_direction cmd_dir, int ehs_length)
2620 struct utp_transfer_req_desc *req_desc = lrbp->utr_descriptor_ptr;
2626 if (cmd_dir == DMA_FROM_DEVICE) {
2627 data_direction = UTP_DEVICE_TO_HOST;
2628 *upiu_flags = UPIU_CMD_FLAGS_READ;
2629 } else if (cmd_dir == DMA_TO_DEVICE) {
2630 data_direction = UTP_HOST_TO_DEVICE;
2631 *upiu_flags = UPIU_CMD_FLAGS_WRITE;
2633 data_direction = UTP_NO_DATA_TRANSFER;
2634 *upiu_flags = UPIU_CMD_FLAGS_NONE;
2637 dword_0 = data_direction | (lrbp->command_type << UPIU_COMMAND_TYPE_OFFSET) |
2640 dword_0 |= UTP_REQ_DESC_INT_CMD;
2642 /* Prepare crypto related dwords */
2643 ufshcd_prepare_req_desc_hdr_crypto(lrbp, &dword_0, &dword_1, &dword_3);
2645 /* Transfer request descriptor header fields */
2646 req_desc->header.dword_0 = cpu_to_le32(dword_0);
2647 req_desc->header.dword_1 = cpu_to_le32(dword_1);
2649 * assigning invalid value for command status. Controller
2650 * updates OCS on command completion, with the command
2653 req_desc->header.dword_2 =
2654 cpu_to_le32(OCS_INVALID_COMMAND_STATUS);
2655 req_desc->header.dword_3 = cpu_to_le32(dword_3);
2657 req_desc->prd_table_length = 0;
2661 * ufshcd_prepare_utp_scsi_cmd_upiu() - fills the utp_transfer_req_desc,
2663 * @lrbp: local reference block pointer
2664 * @upiu_flags: flags
2667 void ufshcd_prepare_utp_scsi_cmd_upiu(struct ufshcd_lrb *lrbp, u8 upiu_flags)
2669 struct scsi_cmnd *cmd = lrbp->cmd;
2670 struct utp_upiu_req *ucd_req_ptr = lrbp->ucd_req_ptr;
2671 unsigned short cdb_len;
2673 /* command descriptor fields */
2674 ucd_req_ptr->header.dword_0 = UPIU_HEADER_DWORD(
2675 UPIU_TRANSACTION_COMMAND, upiu_flags,
2676 lrbp->lun, lrbp->task_tag);
2677 ucd_req_ptr->header.dword_1 = UPIU_HEADER_DWORD(
2678 UPIU_COMMAND_SET_TYPE_SCSI, 0, 0, 0);
2680 /* Total EHS length and Data segment length will be zero */
2681 ucd_req_ptr->header.dword_2 = 0;
2683 ucd_req_ptr->sc.exp_data_transfer_len = cpu_to_be32(cmd->sdb.length);
2685 cdb_len = min_t(unsigned short, cmd->cmd_len, UFS_CDB_SIZE);
2686 memset(ucd_req_ptr->sc.cdb, 0, UFS_CDB_SIZE);
2687 memcpy(ucd_req_ptr->sc.cdb, cmd->cmnd, cdb_len);
2689 memset(lrbp->ucd_rsp_ptr, 0, sizeof(struct utp_upiu_rsp));
2693 * ufshcd_prepare_utp_query_req_upiu() - fill the utp_transfer_req_desc for query request
2695 * @lrbp: local reference block pointer
2696 * @upiu_flags: flags
2698 static void ufshcd_prepare_utp_query_req_upiu(struct ufs_hba *hba,
2699 struct ufshcd_lrb *lrbp, u8 upiu_flags)
2701 struct utp_upiu_req *ucd_req_ptr = lrbp->ucd_req_ptr;
2702 struct ufs_query *query = &hba->dev_cmd.query;
2703 u16 len = be16_to_cpu(query->request.upiu_req.length);
2705 /* Query request header */
2706 ucd_req_ptr->header.dword_0 = UPIU_HEADER_DWORD(
2707 UPIU_TRANSACTION_QUERY_REQ, upiu_flags,
2708 lrbp->lun, lrbp->task_tag);
2709 ucd_req_ptr->header.dword_1 = UPIU_HEADER_DWORD(
2710 0, query->request.query_func, 0, 0);
2712 /* Data segment length only need for WRITE_DESC */
2713 if (query->request.upiu_req.opcode == UPIU_QUERY_OPCODE_WRITE_DESC)
2714 ucd_req_ptr->header.dword_2 =
2715 UPIU_HEADER_DWORD(0, 0, (len >> 8), (u8)len);
2717 ucd_req_ptr->header.dword_2 = 0;
2719 /* Copy the Query Request buffer as is */
2720 memcpy(&ucd_req_ptr->qr, &query->request.upiu_req,
2723 /* Copy the Descriptor */
2724 if (query->request.upiu_req.opcode == UPIU_QUERY_OPCODE_WRITE_DESC)
2725 memcpy(ucd_req_ptr + 1, query->descriptor, len);
2727 memset(lrbp->ucd_rsp_ptr, 0, sizeof(struct utp_upiu_rsp));
2730 static inline void ufshcd_prepare_utp_nop_upiu(struct ufshcd_lrb *lrbp)
2732 struct utp_upiu_req *ucd_req_ptr = lrbp->ucd_req_ptr;
2734 memset(ucd_req_ptr, 0, sizeof(struct utp_upiu_req));
2736 /* command descriptor fields */
2737 ucd_req_ptr->header.dword_0 =
2739 UPIU_TRANSACTION_NOP_OUT, 0, 0, lrbp->task_tag);
2740 /* clear rest of the fields of basic header */
2741 ucd_req_ptr->header.dword_1 = 0;
2742 ucd_req_ptr->header.dword_2 = 0;
2744 memset(lrbp->ucd_rsp_ptr, 0, sizeof(struct utp_upiu_rsp));
2748 * ufshcd_compose_devman_upiu - UFS Protocol Information Unit(UPIU)
2749 * for Device Management Purposes
2750 * @hba: per adapter instance
2751 * @lrbp: pointer to local reference block
2753 static int ufshcd_compose_devman_upiu(struct ufs_hba *hba,
2754 struct ufshcd_lrb *lrbp)
2759 if (hba->ufs_version <= ufshci_version(1, 1))
2760 lrbp->command_type = UTP_CMD_TYPE_DEV_MANAGE;
2762 lrbp->command_type = UTP_CMD_TYPE_UFS_STORAGE;
2764 ufshcd_prepare_req_desc_hdr(lrbp, &upiu_flags, DMA_NONE, 0);
2765 if (hba->dev_cmd.type == DEV_CMD_TYPE_QUERY)
2766 ufshcd_prepare_utp_query_req_upiu(hba, lrbp, upiu_flags);
2767 else if (hba->dev_cmd.type == DEV_CMD_TYPE_NOP)
2768 ufshcd_prepare_utp_nop_upiu(lrbp);
2776 * ufshcd_comp_scsi_upiu - UFS Protocol Information Unit(UPIU)
2778 * @hba: per adapter instance
2779 * @lrbp: pointer to local reference block
2781 static int ufshcd_comp_scsi_upiu(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
2786 if (hba->ufs_version <= ufshci_version(1, 1))
2787 lrbp->command_type = UTP_CMD_TYPE_SCSI;
2789 lrbp->command_type = UTP_CMD_TYPE_UFS_STORAGE;
2791 if (likely(lrbp->cmd)) {
2792 ufshcd_prepare_req_desc_hdr(lrbp, &upiu_flags, lrbp->cmd->sc_data_direction, 0);
2793 ufshcd_prepare_utp_scsi_cmd_upiu(lrbp, upiu_flags);
2802 * ufshcd_upiu_wlun_to_scsi_wlun - maps UPIU W-LUN id to SCSI W-LUN ID
2803 * @upiu_wlun_id: UPIU W-LUN id
2805 * Returns SCSI W-LUN id
2807 static inline u16 ufshcd_upiu_wlun_to_scsi_wlun(u8 upiu_wlun_id)
2809 return (upiu_wlun_id & ~UFS_UPIU_WLUN_ID) | SCSI_W_LUN_BASE;
2812 static inline bool is_device_wlun(struct scsi_device *sdev)
2815 ufshcd_upiu_wlun_to_scsi_wlun(UFS_UPIU_UFS_DEVICE_WLUN);
2819 * Associate the UFS controller queue with the default and poll HCTX types.
2820 * Initialize the mq_map[] arrays.
2822 static void ufshcd_map_queues(struct Scsi_Host *shost)
2824 struct ufs_hba *hba = shost_priv(shost);
2825 int i, queue_offset = 0;
2827 if (!is_mcq_supported(hba)) {
2828 hba->nr_queues[HCTX_TYPE_DEFAULT] = 1;
2829 hba->nr_queues[HCTX_TYPE_READ] = 0;
2830 hba->nr_queues[HCTX_TYPE_POLL] = 1;
2831 hba->nr_hw_queues = 1;
2834 for (i = 0; i < shost->nr_maps; i++) {
2835 struct blk_mq_queue_map *map = &shost->tag_set.map[i];
2837 map->nr_queues = hba->nr_queues[i];
2838 if (!map->nr_queues)
2840 map->queue_offset = queue_offset;
2841 if (i == HCTX_TYPE_POLL && !is_mcq_supported(hba))
2842 map->queue_offset = 0;
2844 blk_mq_map_queues(map);
2845 queue_offset += map->nr_queues;
2849 static void ufshcd_init_lrb(struct ufs_hba *hba, struct ufshcd_lrb *lrb, int i)
2851 struct utp_transfer_cmd_desc *cmd_descp = (void *)hba->ucdl_base_addr +
2852 i * sizeof_utp_transfer_cmd_desc(hba);
2853 struct utp_transfer_req_desc *utrdlp = hba->utrdl_base_addr;
2854 dma_addr_t cmd_desc_element_addr = hba->ucdl_dma_addr +
2855 i * sizeof_utp_transfer_cmd_desc(hba);
2856 u16 response_offset = offsetof(struct utp_transfer_cmd_desc,
2858 u16 prdt_offset = offsetof(struct utp_transfer_cmd_desc, prd_table);
2860 lrb->utr_descriptor_ptr = utrdlp + i;
2861 lrb->utrd_dma_addr = hba->utrdl_dma_addr +
2862 i * sizeof(struct utp_transfer_req_desc);
2863 lrb->ucd_req_ptr = (struct utp_upiu_req *)cmd_descp->command_upiu;
2864 lrb->ucd_req_dma_addr = cmd_desc_element_addr;
2865 lrb->ucd_rsp_ptr = (struct utp_upiu_rsp *)cmd_descp->response_upiu;
2866 lrb->ucd_rsp_dma_addr = cmd_desc_element_addr + response_offset;
2867 lrb->ucd_prdt_ptr = (struct ufshcd_sg_entry *)cmd_descp->prd_table;
2868 lrb->ucd_prdt_dma_addr = cmd_desc_element_addr + prdt_offset;
2872 * ufshcd_queuecommand - main entry point for SCSI requests
2873 * @host: SCSI host pointer
2874 * @cmd: command from SCSI Midlayer
2876 * Returns 0 for success, non-zero in case of failure
2878 static int ufshcd_queuecommand(struct Scsi_Host *host, struct scsi_cmnd *cmd)
2880 struct ufs_hba *hba = shost_priv(host);
2881 int tag = scsi_cmd_to_rq(cmd)->tag;
2882 struct ufshcd_lrb *lrbp;
2884 struct ufs_hw_queue *hwq = NULL;
2886 WARN_ONCE(tag < 0 || tag >= hba->nutrs, "Invalid tag %d\n", tag);
2889 * Allows the UFS error handler to wait for prior ufshcd_queuecommand()
2894 switch (hba->ufshcd_state) {
2895 case UFSHCD_STATE_OPERATIONAL:
2897 case UFSHCD_STATE_EH_SCHEDULED_NON_FATAL:
2899 * SCSI error handler can call ->queuecommand() while UFS error
2900 * handler is in progress. Error interrupts could change the
2901 * state from UFSHCD_STATE_RESET to
2902 * UFSHCD_STATE_EH_SCHEDULED_NON_FATAL. Prevent requests
2903 * being issued in that case.
2905 if (ufshcd_eh_in_progress(hba)) {
2906 err = SCSI_MLQUEUE_HOST_BUSY;
2910 case UFSHCD_STATE_EH_SCHEDULED_FATAL:
2912 * pm_runtime_get_sync() is used at error handling preparation
2913 * stage. If a scsi cmd, e.g. the SSU cmd, is sent from hba's
2914 * PM ops, it can never be finished if we let SCSI layer keep
2915 * retrying it, which gets err handler stuck forever. Neither
2916 * can we let the scsi cmd pass through, because UFS is in bad
2917 * state, the scsi cmd may eventually time out, which will get
2918 * err handler blocked for too long. So, just fail the scsi cmd
2919 * sent from PM ops, err handler can recover PM error anyways.
2921 if (hba->pm_op_in_progress) {
2922 hba->force_reset = true;
2923 set_host_byte(cmd, DID_BAD_TARGET);
2928 case UFSHCD_STATE_RESET:
2929 err = SCSI_MLQUEUE_HOST_BUSY;
2931 case UFSHCD_STATE_ERROR:
2932 set_host_byte(cmd, DID_ERROR);
2937 hba->req_abort_count = 0;
2939 err = ufshcd_hold(hba, true);
2941 err = SCSI_MLQUEUE_HOST_BUSY;
2944 WARN_ON(ufshcd_is_clkgating_allowed(hba) &&
2945 (hba->clk_gating.state != CLKS_ON));
2947 lrbp = &hba->lrb[tag];
2949 lrbp->task_tag = tag;
2950 lrbp->lun = ufshcd_scsi_to_upiu_lun(cmd->device->lun);
2951 lrbp->intr_cmd = !ufshcd_is_intr_aggr_allowed(hba);
2953 ufshcd_prepare_lrbp_crypto(scsi_cmd_to_rq(cmd), lrbp);
2955 lrbp->req_abort_skip = false;
2957 ufshpb_prep(hba, lrbp);
2959 ufshcd_comp_scsi_upiu(hba, lrbp);
2961 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 * Clear all the requests from the controller for which a bit has been set in
3001 * @mask and wait until the controller confirms that these requests have been
3004 static int ufshcd_clear_cmds(struct ufs_hba *hba, u32 mask)
3006 unsigned long flags;
3008 /* clear outstanding transaction before retry */
3009 spin_lock_irqsave(hba->host->host_lock, flags);
3010 ufshcd_utrl_clear(hba, mask);
3011 spin_unlock_irqrestore(hba->host->host_lock, flags);
3014 * wait for h/w to clear corresponding bit in door-bell.
3015 * max. wait is 1 sec.
3017 return ufshcd_wait_for_register(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL,
3018 mask, ~mask, 1000, 1000);
3022 ufshcd_check_query_response(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
3024 struct ufs_query_res *query_res = &hba->dev_cmd.query.response;
3026 /* Get the UPIU response */
3027 query_res->response = ufshcd_get_rsp_upiu_result(lrbp->ucd_rsp_ptr) >>
3028 UPIU_RSP_CODE_OFFSET;
3029 return query_res->response;
3033 * ufshcd_dev_cmd_completion() - handles device management command responses
3034 * @hba: per adapter instance
3035 * @lrbp: pointer to local reference block
3038 ufshcd_dev_cmd_completion(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
3043 hba->ufs_stats.last_hibern8_exit_tstamp = ktime_set(0, 0);
3044 resp = ufshcd_get_req_rsp(lrbp->ucd_rsp_ptr);
3047 case UPIU_TRANSACTION_NOP_IN:
3048 if (hba->dev_cmd.type != DEV_CMD_TYPE_NOP) {
3050 dev_err(hba->dev, "%s: unexpected response %x\n",
3054 case UPIU_TRANSACTION_QUERY_RSP:
3055 err = ufshcd_check_query_response(hba, lrbp);
3057 err = ufshcd_copy_query_response(hba, lrbp);
3059 case UPIU_TRANSACTION_REJECT_UPIU:
3060 /* TODO: handle Reject UPIU Response */
3062 dev_err(hba->dev, "%s: Reject UPIU not fully implemented\n",
3065 case UPIU_TRANSACTION_RESPONSE:
3066 if (hba->dev_cmd.type != DEV_CMD_TYPE_RPMB) {
3068 dev_err(hba->dev, "%s: unexpected response %x\n", __func__, resp);
3073 dev_err(hba->dev, "%s: Invalid device management cmd response: %x\n",
3081 static int ufshcd_wait_for_dev_cmd(struct ufs_hba *hba,
3082 struct ufshcd_lrb *lrbp, int max_timeout)
3084 unsigned long time_left = msecs_to_jiffies(max_timeout);
3085 unsigned long flags;
3090 time_left = wait_for_completion_timeout(hba->dev_cmd.complete,
3093 if (likely(time_left)) {
3095 * The completion handler called complete() and the caller of
3096 * this function still owns the @lrbp tag so the code below does
3097 * not trigger any race conditions.
3099 hba->dev_cmd.complete = NULL;
3100 err = ufshcd_get_tr_ocs(lrbp, hba->dev_cmd.cqe);
3102 err = ufshcd_dev_cmd_completion(hba, lrbp);
3105 dev_dbg(hba->dev, "%s: dev_cmd request timedout, tag %d\n",
3106 __func__, lrbp->task_tag);
3107 if (ufshcd_clear_cmds(hba, 1U << lrbp->task_tag) == 0) {
3108 /* successfully cleared the command, retry if needed */
3111 * Since clearing the command succeeded we also need to
3112 * clear the task tag bit from the outstanding_reqs
3115 spin_lock_irqsave(&hba->outstanding_lock, flags);
3116 pending = test_bit(lrbp->task_tag,
3117 &hba->outstanding_reqs);
3119 hba->dev_cmd.complete = NULL;
3120 __clear_bit(lrbp->task_tag,
3121 &hba->outstanding_reqs);
3123 spin_unlock_irqrestore(&hba->outstanding_lock, flags);
3127 * The completion handler ran while we tried to
3128 * clear the command.
3134 dev_err(hba->dev, "%s: failed to clear tag %d\n",
3135 __func__, lrbp->task_tag);
3137 spin_lock_irqsave(&hba->outstanding_lock, flags);
3138 pending = test_bit(lrbp->task_tag,
3139 &hba->outstanding_reqs);
3141 hba->dev_cmd.complete = NULL;
3142 spin_unlock_irqrestore(&hba->outstanding_lock, flags);
3146 * The completion handler ran while we tried to
3147 * clear the command.
3159 * ufshcd_exec_dev_cmd - API for sending device management requests
3161 * @cmd_type: specifies the type (NOP, Query...)
3162 * @timeout: timeout in milliseconds
3164 * NOTE: Since there is only one available tag for device management commands,
3165 * it is expected you hold the hba->dev_cmd.lock mutex.
3167 static int ufshcd_exec_dev_cmd(struct ufs_hba *hba,
3168 enum dev_cmd_type cmd_type, int timeout)
3170 DECLARE_COMPLETION_ONSTACK(wait);
3171 const u32 tag = hba->reserved_slot;
3172 struct ufshcd_lrb *lrbp;
3175 /* Protects use of hba->reserved_slot. */
3176 lockdep_assert_held(&hba->dev_cmd.lock);
3178 down_read(&hba->clk_scaling_lock);
3180 lrbp = &hba->lrb[tag];
3182 err = ufshcd_compose_dev_cmd(hba, lrbp, cmd_type, tag);
3186 hba->dev_cmd.complete = &wait;
3187 hba->dev_cmd.cqe = NULL;
3189 ufshcd_add_query_upiu_trace(hba, UFS_QUERY_SEND, lrbp->ucd_req_ptr);
3191 ufshcd_send_command(hba, tag, hba->dev_cmd_queue);
3192 err = ufshcd_wait_for_dev_cmd(hba, lrbp, timeout);
3193 ufshcd_add_query_upiu_trace(hba, err ? UFS_QUERY_ERR : UFS_QUERY_COMP,
3194 (struct utp_upiu_req *)lrbp->ucd_rsp_ptr);
3197 up_read(&hba->clk_scaling_lock);
3202 * ufshcd_init_query() - init the query response and request parameters
3203 * @hba: per-adapter instance
3204 * @request: address of the request pointer to be initialized
3205 * @response: address of the response pointer to be initialized
3206 * @opcode: operation to perform
3207 * @idn: flag idn to access
3208 * @index: LU number to access
3209 * @selector: query/flag/descriptor further identification
3211 static inline void ufshcd_init_query(struct ufs_hba *hba,
3212 struct ufs_query_req **request, struct ufs_query_res **response,
3213 enum query_opcode opcode, u8 idn, u8 index, u8 selector)
3215 *request = &hba->dev_cmd.query.request;
3216 *response = &hba->dev_cmd.query.response;
3217 memset(*request, 0, sizeof(struct ufs_query_req));
3218 memset(*response, 0, sizeof(struct ufs_query_res));
3219 (*request)->upiu_req.opcode = opcode;
3220 (*request)->upiu_req.idn = idn;
3221 (*request)->upiu_req.index = index;
3222 (*request)->upiu_req.selector = selector;
3225 static int ufshcd_query_flag_retry(struct ufs_hba *hba,
3226 enum query_opcode opcode, enum flag_idn idn, u8 index, bool *flag_res)
3231 for (retries = 0; retries < QUERY_REQ_RETRIES; retries++) {
3232 ret = ufshcd_query_flag(hba, opcode, idn, index, flag_res);
3235 "%s: failed with error %d, retries %d\n",
3236 __func__, ret, retries);
3243 "%s: query flag, opcode %d, idn %d, failed with error %d after %d retries\n",
3244 __func__, opcode, idn, ret, retries);
3249 * ufshcd_query_flag() - API function for sending flag query requests
3250 * @hba: per-adapter instance
3251 * @opcode: flag query to perform
3252 * @idn: flag idn to access
3253 * @index: flag index to access
3254 * @flag_res: the flag value after the query request completes
3256 * Returns 0 for success, non-zero in case of failure
3258 int ufshcd_query_flag(struct ufs_hba *hba, enum query_opcode opcode,
3259 enum flag_idn idn, u8 index, bool *flag_res)
3261 struct ufs_query_req *request = NULL;
3262 struct ufs_query_res *response = NULL;
3263 int err, selector = 0;
3264 int timeout = QUERY_REQ_TIMEOUT;
3268 ufshcd_hold(hba, false);
3269 mutex_lock(&hba->dev_cmd.lock);
3270 ufshcd_init_query(hba, &request, &response, opcode, idn, index,
3274 case UPIU_QUERY_OPCODE_SET_FLAG:
3275 case UPIU_QUERY_OPCODE_CLEAR_FLAG:
3276 case UPIU_QUERY_OPCODE_TOGGLE_FLAG:
3277 request->query_func = UPIU_QUERY_FUNC_STANDARD_WRITE_REQUEST;
3279 case UPIU_QUERY_OPCODE_READ_FLAG:
3280 request->query_func = UPIU_QUERY_FUNC_STANDARD_READ_REQUEST;
3282 /* No dummy reads */
3283 dev_err(hba->dev, "%s: Invalid argument for read request\n",
3291 "%s: Expected query flag opcode but got = %d\n",
3297 err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_QUERY, timeout);
3301 "%s: Sending flag query for idn %d failed, err = %d\n",
3302 __func__, idn, err);
3307 *flag_res = (be32_to_cpu(response->upiu_res.value) &
3308 MASK_QUERY_UPIU_FLAG_LOC) & 0x1;
3311 mutex_unlock(&hba->dev_cmd.lock);
3312 ufshcd_release(hba);
3317 * ufshcd_query_attr - API function for sending attribute requests
3318 * @hba: per-adapter instance
3319 * @opcode: attribute opcode
3320 * @idn: attribute idn to access
3321 * @index: index field
3322 * @selector: selector field
3323 * @attr_val: the attribute value after the query request completes
3325 * Returns 0 for success, non-zero in case of failure
3327 int ufshcd_query_attr(struct ufs_hba *hba, enum query_opcode opcode,
3328 enum attr_idn idn, u8 index, u8 selector, u32 *attr_val)
3330 struct ufs_query_req *request = NULL;
3331 struct ufs_query_res *response = NULL;
3337 dev_err(hba->dev, "%s: attribute value required for opcode 0x%x\n",
3342 ufshcd_hold(hba, false);
3344 mutex_lock(&hba->dev_cmd.lock);
3345 ufshcd_init_query(hba, &request, &response, opcode, idn, index,
3349 case UPIU_QUERY_OPCODE_WRITE_ATTR:
3350 request->query_func = UPIU_QUERY_FUNC_STANDARD_WRITE_REQUEST;
3351 request->upiu_req.value = cpu_to_be32(*attr_val);
3353 case UPIU_QUERY_OPCODE_READ_ATTR:
3354 request->query_func = UPIU_QUERY_FUNC_STANDARD_READ_REQUEST;
3357 dev_err(hba->dev, "%s: Expected query attr opcode but got = 0x%.2x\n",
3363 err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_QUERY, QUERY_REQ_TIMEOUT);
3366 dev_err(hba->dev, "%s: opcode 0x%.2x for idn %d failed, index %d, err = %d\n",
3367 __func__, opcode, idn, index, err);
3371 *attr_val = be32_to_cpu(response->upiu_res.value);
3374 mutex_unlock(&hba->dev_cmd.lock);
3375 ufshcd_release(hba);
3380 * ufshcd_query_attr_retry() - API function for sending query
3381 * attribute with retries
3382 * @hba: per-adapter instance
3383 * @opcode: attribute opcode
3384 * @idn: attribute idn to access
3385 * @index: index field
3386 * @selector: selector field
3387 * @attr_val: the attribute value after the query request
3390 * Returns 0 for success, non-zero in case of failure
3392 int ufshcd_query_attr_retry(struct ufs_hba *hba,
3393 enum query_opcode opcode, enum attr_idn idn, u8 index, u8 selector,
3399 for (retries = QUERY_REQ_RETRIES; retries > 0; retries--) {
3400 ret = ufshcd_query_attr(hba, opcode, idn, index,
3401 selector, attr_val);
3403 dev_dbg(hba->dev, "%s: failed with error %d, retries %d\n",
3404 __func__, ret, retries);
3411 "%s: query attribute, idn %d, failed with error %d after %d retries\n",
3412 __func__, idn, ret, QUERY_REQ_RETRIES);
3416 static int __ufshcd_query_descriptor(struct ufs_hba *hba,
3417 enum query_opcode opcode, enum desc_idn idn, u8 index,
3418 u8 selector, u8 *desc_buf, int *buf_len)
3420 struct ufs_query_req *request = NULL;
3421 struct ufs_query_res *response = NULL;
3427 dev_err(hba->dev, "%s: descriptor buffer required for opcode 0x%x\n",
3432 if (*buf_len < QUERY_DESC_MIN_SIZE || *buf_len > QUERY_DESC_MAX_SIZE) {
3433 dev_err(hba->dev, "%s: descriptor buffer size (%d) is out of range\n",
3434 __func__, *buf_len);
3438 ufshcd_hold(hba, false);
3440 mutex_lock(&hba->dev_cmd.lock);
3441 ufshcd_init_query(hba, &request, &response, opcode, idn, index,
3443 hba->dev_cmd.query.descriptor = desc_buf;
3444 request->upiu_req.length = cpu_to_be16(*buf_len);
3447 case UPIU_QUERY_OPCODE_WRITE_DESC:
3448 request->query_func = UPIU_QUERY_FUNC_STANDARD_WRITE_REQUEST;
3450 case UPIU_QUERY_OPCODE_READ_DESC:
3451 request->query_func = UPIU_QUERY_FUNC_STANDARD_READ_REQUEST;
3455 "%s: Expected query descriptor opcode but got = 0x%.2x\n",
3461 err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_QUERY, QUERY_REQ_TIMEOUT);
3464 dev_err(hba->dev, "%s: opcode 0x%.2x for idn %d failed, index %d, err = %d\n",
3465 __func__, opcode, idn, index, err);
3469 *buf_len = be16_to_cpu(response->upiu_res.length);
3472 hba->dev_cmd.query.descriptor = NULL;
3473 mutex_unlock(&hba->dev_cmd.lock);
3474 ufshcd_release(hba);
3479 * ufshcd_query_descriptor_retry - API function for sending descriptor requests
3480 * @hba: per-adapter instance
3481 * @opcode: attribute opcode
3482 * @idn: attribute idn to access
3483 * @index: index field
3484 * @selector: selector field
3485 * @desc_buf: the buffer that contains the descriptor
3486 * @buf_len: length parameter passed to the device
3488 * Returns 0 for success, non-zero in case of failure.
3489 * The buf_len parameter will contain, on return, the length parameter
3490 * received on the response.
3492 int ufshcd_query_descriptor_retry(struct ufs_hba *hba,
3493 enum query_opcode opcode,
3494 enum desc_idn idn, u8 index,
3496 u8 *desc_buf, int *buf_len)
3501 for (retries = QUERY_REQ_RETRIES; retries > 0; retries--) {
3502 err = __ufshcd_query_descriptor(hba, opcode, idn, index,
3503 selector, desc_buf, buf_len);
3504 if (!err || err == -EINVAL)
3512 * ufshcd_read_desc_param - read the specified descriptor parameter
3513 * @hba: Pointer to adapter instance
3514 * @desc_id: descriptor idn value
3515 * @desc_index: descriptor index
3516 * @param_offset: offset of the parameter to read
3517 * @param_read_buf: pointer to buffer where parameter would be read
3518 * @param_size: sizeof(param_read_buf)
3520 * Return 0 in case of success, non-zero otherwise
3522 int ufshcd_read_desc_param(struct ufs_hba *hba,
3523 enum desc_idn desc_id,
3531 int buff_len = QUERY_DESC_MAX_SIZE;
3532 bool is_kmalloc = true;
3535 if (desc_id >= QUERY_DESC_IDN_MAX || !param_size)
3538 /* Check whether we need temp memory */
3539 if (param_offset != 0 || param_size < buff_len) {
3540 desc_buf = kzalloc(buff_len, GFP_KERNEL);
3544 desc_buf = param_read_buf;
3548 /* Request for full descriptor */
3549 ret = ufshcd_query_descriptor_retry(hba, UPIU_QUERY_OPCODE_READ_DESC,
3550 desc_id, desc_index, 0,
3551 desc_buf, &buff_len);
3553 dev_err(hba->dev, "%s: Failed reading descriptor. desc_id %d, desc_index %d, param_offset %d, ret %d\n",
3554 __func__, desc_id, desc_index, param_offset, ret);
3558 /* Update descriptor length */
3559 buff_len = desc_buf[QUERY_DESC_LENGTH_OFFSET];
3561 if (param_offset >= buff_len) {
3562 dev_err(hba->dev, "%s: Invalid offset 0x%x in descriptor IDN 0x%x, length 0x%x\n",
3563 __func__, param_offset, desc_id, buff_len);
3569 if (desc_buf[QUERY_DESC_DESC_TYPE_OFFSET] != desc_id) {
3570 dev_err(hba->dev, "%s: invalid desc_id %d in descriptor header\n",
3571 __func__, desc_buf[QUERY_DESC_DESC_TYPE_OFFSET]);
3577 /* Make sure we don't copy more data than available */
3578 if (param_offset >= buff_len)
3581 memcpy(param_read_buf, &desc_buf[param_offset],
3582 min_t(u32, param_size, buff_len - param_offset));
3591 * struct uc_string_id - unicode string
3593 * @len: size of this descriptor inclusive
3594 * @type: descriptor type
3595 * @uc: unicode string character
3597 struct uc_string_id {
3603 /* replace non-printable or non-ASCII characters with spaces */
3604 static inline char ufshcd_remove_non_printable(u8 ch)
3606 return (ch >= 0x20 && ch <= 0x7e) ? ch : ' ';
3610 * ufshcd_read_string_desc - read string descriptor
3611 * @hba: pointer to adapter instance
3612 * @desc_index: descriptor index
3613 * @buf: pointer to buffer where descriptor would be read,
3614 * the caller should free the memory.
3615 * @ascii: if true convert from unicode to ascii characters
3616 * null terminated string.
3619 * * string size on success.
3620 * * -ENOMEM: on allocation failure
3621 * * -EINVAL: on a wrong parameter
3623 int ufshcd_read_string_desc(struct ufs_hba *hba, u8 desc_index,
3624 u8 **buf, bool ascii)
3626 struct uc_string_id *uc_str;
3633 uc_str = kzalloc(QUERY_DESC_MAX_SIZE, GFP_KERNEL);
3637 ret = ufshcd_read_desc_param(hba, QUERY_DESC_IDN_STRING, desc_index, 0,
3638 (u8 *)uc_str, QUERY_DESC_MAX_SIZE);
3640 dev_err(hba->dev, "Reading String Desc failed after %d retries. err = %d\n",
3641 QUERY_REQ_RETRIES, ret);
3646 if (uc_str->len <= QUERY_DESC_HDR_SIZE) {
3647 dev_dbg(hba->dev, "String Desc is of zero length\n");
3656 /* remove header and divide by 2 to move from UTF16 to UTF8 */
3657 ascii_len = (uc_str->len - QUERY_DESC_HDR_SIZE) / 2 + 1;
3658 str = kzalloc(ascii_len, GFP_KERNEL);
3665 * the descriptor contains string in UTF16 format
3666 * we need to convert to utf-8 so it can be displayed
3668 ret = utf16s_to_utf8s(uc_str->uc,
3669 uc_str->len - QUERY_DESC_HDR_SIZE,
3670 UTF16_BIG_ENDIAN, str, ascii_len);
3672 /* replace non-printable or non-ASCII characters with spaces */
3673 for (i = 0; i < ret; i++)
3674 str[i] = ufshcd_remove_non_printable(str[i]);
3679 str = kmemdup(uc_str, uc_str->len, GFP_KERNEL);
3693 * ufshcd_read_unit_desc_param - read the specified unit descriptor parameter
3694 * @hba: Pointer to adapter instance
3696 * @param_offset: offset of the parameter to read
3697 * @param_read_buf: pointer to buffer where parameter would be read
3698 * @param_size: sizeof(param_read_buf)
3700 * Return 0 in case of success, non-zero otherwise
3702 static inline int ufshcd_read_unit_desc_param(struct ufs_hba *hba,
3704 enum unit_desc_param param_offset,
3709 * Unit descriptors are only available for general purpose LUs (LUN id
3710 * from 0 to 7) and RPMB Well known LU.
3712 if (!ufs_is_valid_unit_desc_lun(&hba->dev_info, lun))
3715 return ufshcd_read_desc_param(hba, QUERY_DESC_IDN_UNIT, lun,
3716 param_offset, param_read_buf, param_size);
3719 static int ufshcd_get_ref_clk_gating_wait(struct ufs_hba *hba)
3722 u32 gating_wait = UFSHCD_REF_CLK_GATING_WAIT_US;
3724 if (hba->dev_info.wspecversion >= 0x300) {
3725 err = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
3726 QUERY_ATTR_IDN_REF_CLK_GATING_WAIT_TIME, 0, 0,
3729 dev_err(hba->dev, "Failed reading bRefClkGatingWait. err = %d, use default %uus\n",
3732 if (gating_wait == 0) {
3733 gating_wait = UFSHCD_REF_CLK_GATING_WAIT_US;
3734 dev_err(hba->dev, "Undefined ref clk gating wait time, use default %uus\n",
3738 hba->dev_info.clk_gating_wait_us = gating_wait;
3745 * ufshcd_memory_alloc - allocate memory for host memory space data structures
3746 * @hba: per adapter instance
3748 * 1. Allocate DMA memory for Command Descriptor array
3749 * Each command descriptor consist of Command UPIU, Response UPIU and PRDT
3750 * 2. Allocate DMA memory for UTP Transfer Request Descriptor List (UTRDL).
3751 * 3. Allocate DMA memory for UTP Task Management Request Descriptor List
3753 * 4. Allocate memory for local reference block(lrb).
3755 * Returns 0 for success, non-zero in case of failure
3757 static int ufshcd_memory_alloc(struct ufs_hba *hba)
3759 size_t utmrdl_size, utrdl_size, ucdl_size;
3761 /* Allocate memory for UTP command descriptors */
3762 ucdl_size = sizeof_utp_transfer_cmd_desc(hba) * hba->nutrs;
3763 hba->ucdl_base_addr = dmam_alloc_coherent(hba->dev,
3765 &hba->ucdl_dma_addr,
3769 * UFSHCI requires UTP command descriptor to be 128 byte aligned.
3771 if (!hba->ucdl_base_addr ||
3772 WARN_ON(hba->ucdl_dma_addr & (128 - 1))) {
3774 "Command Descriptor Memory allocation failed\n");
3779 * Allocate memory for UTP Transfer descriptors
3780 * UFSHCI requires 1024 byte alignment of UTRD
3782 utrdl_size = (sizeof(struct utp_transfer_req_desc) * hba->nutrs);
3783 hba->utrdl_base_addr = dmam_alloc_coherent(hba->dev,
3785 &hba->utrdl_dma_addr,
3787 if (!hba->utrdl_base_addr ||
3788 WARN_ON(hba->utrdl_dma_addr & (1024 - 1))) {
3790 "Transfer Descriptor Memory allocation failed\n");
3795 * Skip utmrdl allocation; it may have been
3796 * allocated during first pass and not released during
3797 * MCQ memory allocation.
3798 * See ufshcd_release_sdb_queue() and ufshcd_config_mcq()
3800 if (hba->utmrdl_base_addr)
3803 * Allocate memory for UTP Task Management descriptors
3804 * UFSHCI requires 1024 byte alignment of UTMRD
3806 utmrdl_size = sizeof(struct utp_task_req_desc) * hba->nutmrs;
3807 hba->utmrdl_base_addr = dmam_alloc_coherent(hba->dev,
3809 &hba->utmrdl_dma_addr,
3811 if (!hba->utmrdl_base_addr ||
3812 WARN_ON(hba->utmrdl_dma_addr & (1024 - 1))) {
3814 "Task Management Descriptor Memory allocation failed\n");
3819 /* Allocate memory for local reference block */
3820 hba->lrb = devm_kcalloc(hba->dev,
3821 hba->nutrs, sizeof(struct ufshcd_lrb),
3824 dev_err(hba->dev, "LRB Memory allocation failed\n");
3833 * ufshcd_host_memory_configure - configure local reference block with
3835 * @hba: per adapter instance
3837 * Configure Host memory space
3838 * 1. Update Corresponding UTRD.UCDBA and UTRD.UCDBAU with UCD DMA
3840 * 2. Update each UTRD with Response UPIU offset, Response UPIU length
3842 * 3. Save the corresponding addresses of UTRD, UCD.CMD, UCD.RSP and UCD.PRDT
3843 * into local reference block.
3845 static void ufshcd_host_memory_configure(struct ufs_hba *hba)
3847 struct utp_transfer_req_desc *utrdlp;
3848 dma_addr_t cmd_desc_dma_addr;
3849 dma_addr_t cmd_desc_element_addr;
3850 u16 response_offset;
3855 utrdlp = hba->utrdl_base_addr;
3858 offsetof(struct utp_transfer_cmd_desc, response_upiu);
3860 offsetof(struct utp_transfer_cmd_desc, prd_table);
3862 cmd_desc_size = sizeof_utp_transfer_cmd_desc(hba);
3863 cmd_desc_dma_addr = hba->ucdl_dma_addr;
3865 for (i = 0; i < hba->nutrs; i++) {
3866 /* Configure UTRD with command descriptor base address */
3867 cmd_desc_element_addr =
3868 (cmd_desc_dma_addr + (cmd_desc_size * i));
3869 utrdlp[i].command_desc_base_addr_lo =
3870 cpu_to_le32(lower_32_bits(cmd_desc_element_addr));
3871 utrdlp[i].command_desc_base_addr_hi =
3872 cpu_to_le32(upper_32_bits(cmd_desc_element_addr));
3874 /* Response upiu and prdt offset should be in double words */
3875 if (hba->quirks & UFSHCD_QUIRK_PRDT_BYTE_GRAN) {
3876 utrdlp[i].response_upiu_offset =
3877 cpu_to_le16(response_offset);
3878 utrdlp[i].prd_table_offset =
3879 cpu_to_le16(prdt_offset);
3880 utrdlp[i].response_upiu_length =
3881 cpu_to_le16(ALIGNED_UPIU_SIZE);
3883 utrdlp[i].response_upiu_offset =
3884 cpu_to_le16(response_offset >> 2);
3885 utrdlp[i].prd_table_offset =
3886 cpu_to_le16(prdt_offset >> 2);
3887 utrdlp[i].response_upiu_length =
3888 cpu_to_le16(ALIGNED_UPIU_SIZE >> 2);
3891 ufshcd_init_lrb(hba, &hba->lrb[i], i);
3896 * ufshcd_dme_link_startup - Notify Unipro to perform link startup
3897 * @hba: per adapter instance
3899 * UIC_CMD_DME_LINK_STARTUP command must be issued to Unipro layer,
3900 * in order to initialize the Unipro link startup procedure.
3901 * Once the Unipro links are up, the device connected to the controller
3904 * Returns 0 on success, non-zero value on failure
3906 static int ufshcd_dme_link_startup(struct ufs_hba *hba)
3908 struct uic_command uic_cmd = {0};
3911 uic_cmd.command = UIC_CMD_DME_LINK_STARTUP;
3913 ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
3916 "dme-link-startup: error code %d\n", ret);
3920 * ufshcd_dme_reset - UIC command for DME_RESET
3921 * @hba: per adapter instance
3923 * DME_RESET command is issued in order to reset UniPro stack.
3924 * This function now deals with cold reset.
3926 * Returns 0 on success, non-zero value on failure
3928 static int ufshcd_dme_reset(struct ufs_hba *hba)
3930 struct uic_command uic_cmd = {0};
3933 uic_cmd.command = UIC_CMD_DME_RESET;
3935 ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
3938 "dme-reset: error code %d\n", ret);
3943 int ufshcd_dme_configure_adapt(struct ufs_hba *hba,
3949 if (agreed_gear < UFS_HS_G4)
3950 adapt_val = PA_NO_ADAPT;
3952 ret = ufshcd_dme_set(hba,
3953 UIC_ARG_MIB(PA_TXHSADAPTTYPE),
3957 EXPORT_SYMBOL_GPL(ufshcd_dme_configure_adapt);
3960 * ufshcd_dme_enable - UIC command for DME_ENABLE
3961 * @hba: per adapter instance
3963 * DME_ENABLE command is issued in order to enable UniPro stack.
3965 * Returns 0 on success, non-zero value on failure
3967 static int ufshcd_dme_enable(struct ufs_hba *hba)
3969 struct uic_command uic_cmd = {0};
3972 uic_cmd.command = UIC_CMD_DME_ENABLE;
3974 ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
3977 "dme-enable: error code %d\n", ret);
3982 static inline void ufshcd_add_delay_before_dme_cmd(struct ufs_hba *hba)
3984 #define MIN_DELAY_BEFORE_DME_CMDS_US 1000
3985 unsigned long min_sleep_time_us;
3987 if (!(hba->quirks & UFSHCD_QUIRK_DELAY_BEFORE_DME_CMDS))
3991 * last_dme_cmd_tstamp will be 0 only for 1st call to
3994 if (unlikely(!ktime_to_us(hba->last_dme_cmd_tstamp))) {
3995 min_sleep_time_us = MIN_DELAY_BEFORE_DME_CMDS_US;
3997 unsigned long delta =
3998 (unsigned long) ktime_to_us(
3999 ktime_sub(ktime_get(),
4000 hba->last_dme_cmd_tstamp));
4002 if (delta < MIN_DELAY_BEFORE_DME_CMDS_US)
4004 MIN_DELAY_BEFORE_DME_CMDS_US - delta;
4006 return; /* no more delay required */
4009 /* allow sleep for extra 50us if needed */
4010 usleep_range(min_sleep_time_us, min_sleep_time_us + 50);
4014 * ufshcd_dme_set_attr - UIC command for DME_SET, DME_PEER_SET
4015 * @hba: per adapter instance
4016 * @attr_sel: uic command argument1
4017 * @attr_set: attribute set type as uic command argument2
4018 * @mib_val: setting value as uic command argument3
4019 * @peer: indicate whether peer or local
4021 * Returns 0 on success, non-zero value on failure
4023 int ufshcd_dme_set_attr(struct ufs_hba *hba, u32 attr_sel,
4024 u8 attr_set, u32 mib_val, u8 peer)
4026 struct uic_command uic_cmd = {0};
4027 static const char *const action[] = {
4031 const char *set = action[!!peer];
4033 int retries = UFS_UIC_COMMAND_RETRIES;
4035 uic_cmd.command = peer ?
4036 UIC_CMD_DME_PEER_SET : UIC_CMD_DME_SET;
4037 uic_cmd.argument1 = attr_sel;
4038 uic_cmd.argument2 = UIC_ARG_ATTR_TYPE(attr_set);
4039 uic_cmd.argument3 = mib_val;
4042 /* for peer attributes we retry upon failure */
4043 ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
4045 dev_dbg(hba->dev, "%s: attr-id 0x%x val 0x%x error code %d\n",
4046 set, UIC_GET_ATTR_ID(attr_sel), mib_val, ret);
4047 } while (ret && peer && --retries);
4050 dev_err(hba->dev, "%s: attr-id 0x%x val 0x%x failed %d retries\n",
4051 set, UIC_GET_ATTR_ID(attr_sel), mib_val,
4052 UFS_UIC_COMMAND_RETRIES - retries);
4056 EXPORT_SYMBOL_GPL(ufshcd_dme_set_attr);
4059 * ufshcd_dme_get_attr - UIC command for DME_GET, DME_PEER_GET
4060 * @hba: per adapter instance
4061 * @attr_sel: uic command argument1
4062 * @mib_val: the value of the attribute as returned by the UIC command
4063 * @peer: indicate whether peer or local
4065 * Returns 0 on success, non-zero value on failure
4067 int ufshcd_dme_get_attr(struct ufs_hba *hba, u32 attr_sel,
4068 u32 *mib_val, u8 peer)
4070 struct uic_command uic_cmd = {0};
4071 static const char *const action[] = {
4075 const char *get = action[!!peer];
4077 int retries = UFS_UIC_COMMAND_RETRIES;
4078 struct ufs_pa_layer_attr orig_pwr_info;
4079 struct ufs_pa_layer_attr temp_pwr_info;
4080 bool pwr_mode_change = false;
4082 if (peer && (hba->quirks & UFSHCD_QUIRK_DME_PEER_ACCESS_AUTO_MODE)) {
4083 orig_pwr_info = hba->pwr_info;
4084 temp_pwr_info = orig_pwr_info;
4086 if (orig_pwr_info.pwr_tx == FAST_MODE ||
4087 orig_pwr_info.pwr_rx == FAST_MODE) {
4088 temp_pwr_info.pwr_tx = FASTAUTO_MODE;
4089 temp_pwr_info.pwr_rx = FASTAUTO_MODE;
4090 pwr_mode_change = true;
4091 } else if (orig_pwr_info.pwr_tx == SLOW_MODE ||
4092 orig_pwr_info.pwr_rx == SLOW_MODE) {
4093 temp_pwr_info.pwr_tx = SLOWAUTO_MODE;
4094 temp_pwr_info.pwr_rx = SLOWAUTO_MODE;
4095 pwr_mode_change = true;
4097 if (pwr_mode_change) {
4098 ret = ufshcd_change_power_mode(hba, &temp_pwr_info);
4104 uic_cmd.command = peer ?
4105 UIC_CMD_DME_PEER_GET : UIC_CMD_DME_GET;
4106 uic_cmd.argument1 = attr_sel;
4109 /* for peer attributes we retry upon failure */
4110 ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
4112 dev_dbg(hba->dev, "%s: attr-id 0x%x error code %d\n",
4113 get, UIC_GET_ATTR_ID(attr_sel), ret);
4114 } while (ret && peer && --retries);
4117 dev_err(hba->dev, "%s: attr-id 0x%x failed %d retries\n",
4118 get, UIC_GET_ATTR_ID(attr_sel),
4119 UFS_UIC_COMMAND_RETRIES - retries);
4121 if (mib_val && !ret)
4122 *mib_val = uic_cmd.argument3;
4124 if (peer && (hba->quirks & UFSHCD_QUIRK_DME_PEER_ACCESS_AUTO_MODE)
4126 ufshcd_change_power_mode(hba, &orig_pwr_info);
4130 EXPORT_SYMBOL_GPL(ufshcd_dme_get_attr);
4133 * ufshcd_uic_pwr_ctrl - executes UIC commands (which affects the link power
4134 * state) and waits for it to take effect.
4136 * @hba: per adapter instance
4137 * @cmd: UIC command to execute
4139 * DME operations like DME_SET(PA_PWRMODE), DME_HIBERNATE_ENTER &
4140 * DME_HIBERNATE_EXIT commands take some time to take its effect on both host
4141 * and device UniPro link and hence it's final completion would be indicated by
4142 * dedicated status bits in Interrupt Status register (UPMS, UHES, UHXS) in
4143 * addition to normal UIC command completion Status (UCCS). This function only
4144 * returns after the relevant status bits indicate the completion.
4146 * Returns 0 on success, non-zero value on failure
4148 static int ufshcd_uic_pwr_ctrl(struct ufs_hba *hba, struct uic_command *cmd)
4150 DECLARE_COMPLETION_ONSTACK(uic_async_done);
4151 unsigned long flags;
4154 bool reenable_intr = false;
4156 mutex_lock(&hba->uic_cmd_mutex);
4157 ufshcd_add_delay_before_dme_cmd(hba);
4159 spin_lock_irqsave(hba->host->host_lock, flags);
4160 if (ufshcd_is_link_broken(hba)) {
4164 hba->uic_async_done = &uic_async_done;
4165 if (ufshcd_readl(hba, REG_INTERRUPT_ENABLE) & UIC_COMMAND_COMPL) {
4166 ufshcd_disable_intr(hba, UIC_COMMAND_COMPL);
4168 * Make sure UIC command completion interrupt is disabled before
4169 * issuing UIC command.
4172 reenable_intr = true;
4174 ret = __ufshcd_send_uic_cmd(hba, cmd, false);
4175 spin_unlock_irqrestore(hba->host->host_lock, flags);
4178 "pwr ctrl cmd 0x%x with mode 0x%x uic error %d\n",
4179 cmd->command, cmd->argument3, ret);
4183 if (!wait_for_completion_timeout(hba->uic_async_done,
4184 msecs_to_jiffies(UIC_CMD_TIMEOUT))) {
4186 "pwr ctrl cmd 0x%x with mode 0x%x completion timeout\n",
4187 cmd->command, cmd->argument3);
4189 if (!cmd->cmd_active) {
4190 dev_err(hba->dev, "%s: Power Mode Change operation has been completed, go check UPMCRS\n",
4200 status = ufshcd_get_upmcrs(hba);
4201 if (status != PWR_LOCAL) {
4203 "pwr ctrl cmd 0x%x failed, host upmcrs:0x%x\n",
4204 cmd->command, status);
4205 ret = (status != PWR_OK) ? status : -1;
4209 ufshcd_print_host_state(hba);
4210 ufshcd_print_pwr_info(hba);
4211 ufshcd_print_evt_hist(hba);
4214 spin_lock_irqsave(hba->host->host_lock, flags);
4215 hba->active_uic_cmd = NULL;
4216 hba->uic_async_done = NULL;
4218 ufshcd_enable_intr(hba, UIC_COMMAND_COMPL);
4220 ufshcd_set_link_broken(hba);
4221 ufshcd_schedule_eh_work(hba);
4224 spin_unlock_irqrestore(hba->host->host_lock, flags);
4225 mutex_unlock(&hba->uic_cmd_mutex);
4231 * ufshcd_uic_change_pwr_mode - Perform the UIC power mode chage
4232 * using DME_SET primitives.
4233 * @hba: per adapter instance
4234 * @mode: powr mode value
4236 * Returns 0 on success, non-zero value on failure
4238 int ufshcd_uic_change_pwr_mode(struct ufs_hba *hba, u8 mode)
4240 struct uic_command uic_cmd = {0};
4243 if (hba->quirks & UFSHCD_QUIRK_BROKEN_PA_RXHSUNTERMCAP) {
4244 ret = ufshcd_dme_set(hba,
4245 UIC_ARG_MIB_SEL(PA_RXHSUNTERMCAP, 0), 1);
4247 dev_err(hba->dev, "%s: failed to enable PA_RXHSUNTERMCAP ret %d\n",
4253 uic_cmd.command = UIC_CMD_DME_SET;
4254 uic_cmd.argument1 = UIC_ARG_MIB(PA_PWRMODE);
4255 uic_cmd.argument3 = mode;
4256 ufshcd_hold(hba, false);
4257 ret = ufshcd_uic_pwr_ctrl(hba, &uic_cmd);
4258 ufshcd_release(hba);
4263 EXPORT_SYMBOL_GPL(ufshcd_uic_change_pwr_mode);
4265 int ufshcd_link_recovery(struct ufs_hba *hba)
4268 unsigned long flags;
4270 spin_lock_irqsave(hba->host->host_lock, flags);
4271 hba->ufshcd_state = UFSHCD_STATE_RESET;
4272 ufshcd_set_eh_in_progress(hba);
4273 spin_unlock_irqrestore(hba->host->host_lock, flags);
4275 /* Reset the attached device */
4276 ufshcd_device_reset(hba);
4278 ret = ufshcd_host_reset_and_restore(hba);
4280 spin_lock_irqsave(hba->host->host_lock, flags);
4282 hba->ufshcd_state = UFSHCD_STATE_ERROR;
4283 ufshcd_clear_eh_in_progress(hba);
4284 spin_unlock_irqrestore(hba->host->host_lock, flags);
4287 dev_err(hba->dev, "%s: link recovery failed, err %d",
4292 EXPORT_SYMBOL_GPL(ufshcd_link_recovery);
4294 int ufshcd_uic_hibern8_enter(struct ufs_hba *hba)
4297 struct uic_command uic_cmd = {0};
4298 ktime_t start = ktime_get();
4300 ufshcd_vops_hibern8_notify(hba, UIC_CMD_DME_HIBER_ENTER, PRE_CHANGE);
4302 uic_cmd.command = UIC_CMD_DME_HIBER_ENTER;
4303 ret = ufshcd_uic_pwr_ctrl(hba, &uic_cmd);
4304 trace_ufshcd_profile_hibern8(dev_name(hba->dev), "enter",
4305 ktime_to_us(ktime_sub(ktime_get(), start)), ret);
4308 dev_err(hba->dev, "%s: hibern8 enter failed. ret = %d\n",
4311 ufshcd_vops_hibern8_notify(hba, UIC_CMD_DME_HIBER_ENTER,
4316 EXPORT_SYMBOL_GPL(ufshcd_uic_hibern8_enter);
4318 int ufshcd_uic_hibern8_exit(struct ufs_hba *hba)
4320 struct uic_command uic_cmd = {0};
4322 ktime_t start = ktime_get();
4324 ufshcd_vops_hibern8_notify(hba, UIC_CMD_DME_HIBER_EXIT, PRE_CHANGE);
4326 uic_cmd.command = UIC_CMD_DME_HIBER_EXIT;
4327 ret = ufshcd_uic_pwr_ctrl(hba, &uic_cmd);
4328 trace_ufshcd_profile_hibern8(dev_name(hba->dev), "exit",
4329 ktime_to_us(ktime_sub(ktime_get(), start)), ret);
4332 dev_err(hba->dev, "%s: hibern8 exit failed. ret = %d\n",
4335 ufshcd_vops_hibern8_notify(hba, UIC_CMD_DME_HIBER_EXIT,
4337 hba->ufs_stats.last_hibern8_exit_tstamp = local_clock();
4338 hba->ufs_stats.hibern8_exit_cnt++;
4343 EXPORT_SYMBOL_GPL(ufshcd_uic_hibern8_exit);
4345 void ufshcd_auto_hibern8_update(struct ufs_hba *hba, u32 ahit)
4347 unsigned long flags;
4348 bool update = false;
4350 if (!ufshcd_is_auto_hibern8_supported(hba))
4353 spin_lock_irqsave(hba->host->host_lock, flags);
4354 if (hba->ahit != ahit) {
4358 spin_unlock_irqrestore(hba->host->host_lock, flags);
4361 !pm_runtime_suspended(&hba->ufs_device_wlun->sdev_gendev)) {
4362 ufshcd_rpm_get_sync(hba);
4363 ufshcd_hold(hba, false);
4364 ufshcd_auto_hibern8_enable(hba);
4365 ufshcd_release(hba);
4366 ufshcd_rpm_put_sync(hba);
4369 EXPORT_SYMBOL_GPL(ufshcd_auto_hibern8_update);
4371 void ufshcd_auto_hibern8_enable(struct ufs_hba *hba)
4373 if (!ufshcd_is_auto_hibern8_supported(hba))
4376 ufshcd_writel(hba, hba->ahit, REG_AUTO_HIBERNATE_IDLE_TIMER);
4380 * ufshcd_init_pwr_info - setting the POR (power on reset)
4381 * values in hba power info
4382 * @hba: per-adapter instance
4384 static void ufshcd_init_pwr_info(struct ufs_hba *hba)
4386 hba->pwr_info.gear_rx = UFS_PWM_G1;
4387 hba->pwr_info.gear_tx = UFS_PWM_G1;
4388 hba->pwr_info.lane_rx = 1;
4389 hba->pwr_info.lane_tx = 1;
4390 hba->pwr_info.pwr_rx = SLOWAUTO_MODE;
4391 hba->pwr_info.pwr_tx = SLOWAUTO_MODE;
4392 hba->pwr_info.hs_rate = 0;
4396 * ufshcd_get_max_pwr_mode - reads the max power mode negotiated with device
4397 * @hba: per-adapter instance
4399 static int ufshcd_get_max_pwr_mode(struct ufs_hba *hba)
4401 struct ufs_pa_layer_attr *pwr_info = &hba->max_pwr_info.info;
4403 if (hba->max_pwr_info.is_valid)
4406 if (hba->quirks & UFSHCD_QUIRK_HIBERN_FASTAUTO) {
4407 pwr_info->pwr_tx = FASTAUTO_MODE;
4408 pwr_info->pwr_rx = FASTAUTO_MODE;
4410 pwr_info->pwr_tx = FAST_MODE;
4411 pwr_info->pwr_rx = FAST_MODE;
4413 pwr_info->hs_rate = PA_HS_MODE_B;
4415 /* Get the connected lane count */
4416 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_CONNECTEDRXDATALANES),
4417 &pwr_info->lane_rx);
4418 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_CONNECTEDTXDATALANES),
4419 &pwr_info->lane_tx);
4421 if (!pwr_info->lane_rx || !pwr_info->lane_tx) {
4422 dev_err(hba->dev, "%s: invalid connected lanes value. rx=%d, tx=%d\n",
4430 * First, get the maximum gears of HS speed.
4431 * If a zero value, it means there is no HSGEAR capability.
4432 * Then, get the maximum gears of PWM speed.
4434 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_MAXRXHSGEAR), &pwr_info->gear_rx);
4435 if (!pwr_info->gear_rx) {
4436 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_MAXRXPWMGEAR),
4437 &pwr_info->gear_rx);
4438 if (!pwr_info->gear_rx) {
4439 dev_err(hba->dev, "%s: invalid max pwm rx gear read = %d\n",
4440 __func__, pwr_info->gear_rx);
4443 pwr_info->pwr_rx = SLOW_MODE;
4446 ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_MAXRXHSGEAR),
4447 &pwr_info->gear_tx);
4448 if (!pwr_info->gear_tx) {
4449 ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_MAXRXPWMGEAR),
4450 &pwr_info->gear_tx);
4451 if (!pwr_info->gear_tx) {
4452 dev_err(hba->dev, "%s: invalid max pwm tx gear read = %d\n",
4453 __func__, pwr_info->gear_tx);
4456 pwr_info->pwr_tx = SLOW_MODE;
4459 hba->max_pwr_info.is_valid = true;
4463 static int ufshcd_change_power_mode(struct ufs_hba *hba,
4464 struct ufs_pa_layer_attr *pwr_mode)
4468 /* if already configured to the requested pwr_mode */
4469 if (!hba->force_pmc &&
4470 pwr_mode->gear_rx == hba->pwr_info.gear_rx &&
4471 pwr_mode->gear_tx == hba->pwr_info.gear_tx &&
4472 pwr_mode->lane_rx == hba->pwr_info.lane_rx &&
4473 pwr_mode->lane_tx == hba->pwr_info.lane_tx &&
4474 pwr_mode->pwr_rx == hba->pwr_info.pwr_rx &&
4475 pwr_mode->pwr_tx == hba->pwr_info.pwr_tx &&
4476 pwr_mode->hs_rate == hba->pwr_info.hs_rate) {
4477 dev_dbg(hba->dev, "%s: power already configured\n", __func__);
4482 * Configure attributes for power mode change with below.
4483 * - PA_RXGEAR, PA_ACTIVERXDATALANES, PA_RXTERMINATION,
4484 * - PA_TXGEAR, PA_ACTIVETXDATALANES, PA_TXTERMINATION,
4487 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_RXGEAR), pwr_mode->gear_rx);
4488 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_ACTIVERXDATALANES),
4490 if (pwr_mode->pwr_rx == FASTAUTO_MODE ||
4491 pwr_mode->pwr_rx == FAST_MODE)
4492 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_RXTERMINATION), true);
4494 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_RXTERMINATION), false);
4496 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TXGEAR), pwr_mode->gear_tx);
4497 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_ACTIVETXDATALANES),
4499 if (pwr_mode->pwr_tx == FASTAUTO_MODE ||
4500 pwr_mode->pwr_tx == FAST_MODE)
4501 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TXTERMINATION), true);
4503 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TXTERMINATION), false);
4505 if (pwr_mode->pwr_rx == FASTAUTO_MODE ||
4506 pwr_mode->pwr_tx == FASTAUTO_MODE ||
4507 pwr_mode->pwr_rx == FAST_MODE ||
4508 pwr_mode->pwr_tx == FAST_MODE)
4509 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_HSSERIES),
4512 if (!(hba->quirks & UFSHCD_QUIRK_SKIP_DEF_UNIPRO_TIMEOUT_SETTING)) {
4513 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_PWRMODEUSERDATA0),
4514 DL_FC0ProtectionTimeOutVal_Default);
4515 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_PWRMODEUSERDATA1),
4516 DL_TC0ReplayTimeOutVal_Default);
4517 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_PWRMODEUSERDATA2),
4518 DL_AFC0ReqTimeOutVal_Default);
4519 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_PWRMODEUSERDATA3),
4520 DL_FC1ProtectionTimeOutVal_Default);
4521 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_PWRMODEUSERDATA4),
4522 DL_TC1ReplayTimeOutVal_Default);
4523 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_PWRMODEUSERDATA5),
4524 DL_AFC1ReqTimeOutVal_Default);
4526 ufshcd_dme_set(hba, UIC_ARG_MIB(DME_LocalFC0ProtectionTimeOutVal),
4527 DL_FC0ProtectionTimeOutVal_Default);
4528 ufshcd_dme_set(hba, UIC_ARG_MIB(DME_LocalTC0ReplayTimeOutVal),
4529 DL_TC0ReplayTimeOutVal_Default);
4530 ufshcd_dme_set(hba, UIC_ARG_MIB(DME_LocalAFC0ReqTimeOutVal),
4531 DL_AFC0ReqTimeOutVal_Default);
4534 ret = ufshcd_uic_change_pwr_mode(hba, pwr_mode->pwr_rx << 4
4535 | pwr_mode->pwr_tx);
4539 "%s: power mode change failed %d\n", __func__, ret);
4541 ufshcd_vops_pwr_change_notify(hba, POST_CHANGE, NULL,
4544 memcpy(&hba->pwr_info, pwr_mode,
4545 sizeof(struct ufs_pa_layer_attr));
4552 * ufshcd_config_pwr_mode - configure a new power mode
4553 * @hba: per-adapter instance
4554 * @desired_pwr_mode: desired power configuration
4556 int ufshcd_config_pwr_mode(struct ufs_hba *hba,
4557 struct ufs_pa_layer_attr *desired_pwr_mode)
4559 struct ufs_pa_layer_attr final_params = { 0 };
4562 ret = ufshcd_vops_pwr_change_notify(hba, PRE_CHANGE,
4563 desired_pwr_mode, &final_params);
4566 memcpy(&final_params, desired_pwr_mode, sizeof(final_params));
4568 ret = ufshcd_change_power_mode(hba, &final_params);
4572 EXPORT_SYMBOL_GPL(ufshcd_config_pwr_mode);
4575 * ufshcd_complete_dev_init() - checks device readiness
4576 * @hba: per-adapter instance
4578 * Set fDeviceInit flag and poll until device toggles it.
4580 static int ufshcd_complete_dev_init(struct ufs_hba *hba)
4583 bool flag_res = true;
4586 err = ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_SET_FLAG,
4587 QUERY_FLAG_IDN_FDEVICEINIT, 0, NULL);
4590 "%s: setting fDeviceInit flag failed with error %d\n",
4595 /* Poll fDeviceInit flag to be cleared */
4596 timeout = ktime_add_ms(ktime_get(), FDEVICEINIT_COMPL_TIMEOUT);
4598 err = ufshcd_query_flag(hba, UPIU_QUERY_OPCODE_READ_FLAG,
4599 QUERY_FLAG_IDN_FDEVICEINIT, 0, &flag_res);
4602 usleep_range(500, 1000);
4603 } while (ktime_before(ktime_get(), timeout));
4607 "%s: reading fDeviceInit flag failed with error %d\n",
4609 } else if (flag_res) {
4611 "%s: fDeviceInit was not cleared by the device\n",
4620 * ufshcd_make_hba_operational - Make UFS controller operational
4621 * @hba: per adapter instance
4623 * To bring UFS host controller to operational state,
4624 * 1. Enable required interrupts
4625 * 2. Configure interrupt aggregation
4626 * 3. Program UTRL and UTMRL base address
4627 * 4. Configure run-stop-registers
4629 * Returns 0 on success, non-zero value on failure
4631 int ufshcd_make_hba_operational(struct ufs_hba *hba)
4636 /* Enable required interrupts */
4637 ufshcd_enable_intr(hba, UFSHCD_ENABLE_INTRS);
4639 /* Configure interrupt aggregation */
4640 if (ufshcd_is_intr_aggr_allowed(hba))
4641 ufshcd_config_intr_aggr(hba, hba->nutrs - 1, INT_AGGR_DEF_TO);
4643 ufshcd_disable_intr_aggr(hba);
4645 /* Configure UTRL and UTMRL base address registers */
4646 ufshcd_writel(hba, lower_32_bits(hba->utrdl_dma_addr),
4647 REG_UTP_TRANSFER_REQ_LIST_BASE_L);
4648 ufshcd_writel(hba, upper_32_bits(hba->utrdl_dma_addr),
4649 REG_UTP_TRANSFER_REQ_LIST_BASE_H);
4650 ufshcd_writel(hba, lower_32_bits(hba->utmrdl_dma_addr),
4651 REG_UTP_TASK_REQ_LIST_BASE_L);
4652 ufshcd_writel(hba, upper_32_bits(hba->utmrdl_dma_addr),
4653 REG_UTP_TASK_REQ_LIST_BASE_H);
4656 * Make sure base address and interrupt setup are updated before
4657 * enabling the run/stop registers below.
4662 * UCRDY, UTMRLDY and UTRLRDY bits must be 1
4664 reg = ufshcd_readl(hba, REG_CONTROLLER_STATUS);
4665 if (!(ufshcd_get_lists_status(reg))) {
4666 ufshcd_enable_run_stop_reg(hba);
4669 "Host controller not ready to process requests");
4675 EXPORT_SYMBOL_GPL(ufshcd_make_hba_operational);
4678 * ufshcd_hba_stop - Send controller to reset state
4679 * @hba: per adapter instance
4681 void ufshcd_hba_stop(struct ufs_hba *hba)
4683 unsigned long flags;
4687 * Obtain the host lock to prevent that the controller is disabled
4688 * while the UFS interrupt handler is active on another CPU.
4690 spin_lock_irqsave(hba->host->host_lock, flags);
4691 ufshcd_writel(hba, CONTROLLER_DISABLE, REG_CONTROLLER_ENABLE);
4692 spin_unlock_irqrestore(hba->host->host_lock, flags);
4694 err = ufshcd_wait_for_register(hba, REG_CONTROLLER_ENABLE,
4695 CONTROLLER_ENABLE, CONTROLLER_DISABLE,
4698 dev_err(hba->dev, "%s: Controller disable failed\n", __func__);
4700 EXPORT_SYMBOL_GPL(ufshcd_hba_stop);
4703 * ufshcd_hba_execute_hce - initialize the controller
4704 * @hba: per adapter instance
4706 * The controller resets itself and controller firmware initialization
4707 * sequence kicks off. When controller is ready it will set
4708 * the Host Controller Enable bit to 1.
4710 * Returns 0 on success, non-zero value on failure
4712 static int ufshcd_hba_execute_hce(struct ufs_hba *hba)
4714 int retry_outer = 3;
4718 if (ufshcd_is_hba_active(hba))
4719 /* change controller state to "reset state" */
4720 ufshcd_hba_stop(hba);
4722 /* UniPro link is disabled at this point */
4723 ufshcd_set_link_off(hba);
4725 ufshcd_vops_hce_enable_notify(hba, PRE_CHANGE);
4727 /* start controller initialization sequence */
4728 ufshcd_hba_start(hba);
4731 * To initialize a UFS host controller HCE bit must be set to 1.
4732 * During initialization the HCE bit value changes from 1->0->1.
4733 * When the host controller completes initialization sequence
4734 * it sets the value of HCE bit to 1. The same HCE bit is read back
4735 * to check if the controller has completed initialization sequence.
4736 * So without this delay the value HCE = 1, set in the previous
4737 * instruction might be read back.
4738 * This delay can be changed based on the controller.
4740 ufshcd_delay_us(hba->vps->hba_enable_delay_us, 100);
4742 /* wait for the host controller to complete initialization */
4744 while (!ufshcd_is_hba_active(hba)) {
4749 "Controller enable failed\n");
4756 usleep_range(1000, 1100);
4759 /* enable UIC related interrupts */
4760 ufshcd_enable_intr(hba, UFSHCD_UIC_MASK);
4762 ufshcd_vops_hce_enable_notify(hba, POST_CHANGE);
4767 int ufshcd_hba_enable(struct ufs_hba *hba)
4771 if (hba->quirks & UFSHCI_QUIRK_BROKEN_HCE) {
4772 ufshcd_set_link_off(hba);
4773 ufshcd_vops_hce_enable_notify(hba, PRE_CHANGE);
4775 /* enable UIC related interrupts */
4776 ufshcd_enable_intr(hba, UFSHCD_UIC_MASK);
4777 ret = ufshcd_dme_reset(hba);
4779 dev_err(hba->dev, "DME_RESET failed\n");
4783 ret = ufshcd_dme_enable(hba);
4785 dev_err(hba->dev, "Enabling DME failed\n");
4789 ufshcd_vops_hce_enable_notify(hba, POST_CHANGE);
4791 ret = ufshcd_hba_execute_hce(hba);
4796 EXPORT_SYMBOL_GPL(ufshcd_hba_enable);
4798 static int ufshcd_disable_tx_lcc(struct ufs_hba *hba, bool peer)
4800 int tx_lanes = 0, i, err = 0;
4803 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_CONNECTEDTXDATALANES),
4806 ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_CONNECTEDTXDATALANES),
4808 for (i = 0; i < tx_lanes; i++) {
4810 err = ufshcd_dme_set(hba,
4811 UIC_ARG_MIB_SEL(TX_LCC_ENABLE,
4812 UIC_ARG_MPHY_TX_GEN_SEL_INDEX(i)),
4815 err = ufshcd_dme_peer_set(hba,
4816 UIC_ARG_MIB_SEL(TX_LCC_ENABLE,
4817 UIC_ARG_MPHY_TX_GEN_SEL_INDEX(i)),
4820 dev_err(hba->dev, "%s: TX LCC Disable failed, peer = %d, lane = %d, err = %d",
4821 __func__, peer, i, err);
4829 static inline int ufshcd_disable_device_tx_lcc(struct ufs_hba *hba)
4831 return ufshcd_disable_tx_lcc(hba, true);
4834 void ufshcd_update_evt_hist(struct ufs_hba *hba, u32 id, u32 val)
4836 struct ufs_event_hist *e;
4838 if (id >= UFS_EVT_CNT)
4841 e = &hba->ufs_stats.event[id];
4842 e->val[e->pos] = val;
4843 e->tstamp[e->pos] = local_clock();
4845 e->pos = (e->pos + 1) % UFS_EVENT_HIST_LENGTH;
4847 ufshcd_vops_event_notify(hba, id, &val);
4849 EXPORT_SYMBOL_GPL(ufshcd_update_evt_hist);
4852 * ufshcd_link_startup - Initialize unipro link startup
4853 * @hba: per adapter instance
4855 * Returns 0 for success, non-zero in case of failure
4857 static int ufshcd_link_startup(struct ufs_hba *hba)
4860 int retries = DME_LINKSTARTUP_RETRIES;
4861 bool link_startup_again = false;
4864 * If UFS device isn't active then we will have to issue link startup
4865 * 2 times to make sure the device state move to active.
4867 if (!ufshcd_is_ufs_dev_active(hba))
4868 link_startup_again = true;
4872 ufshcd_vops_link_startup_notify(hba, PRE_CHANGE);
4874 ret = ufshcd_dme_link_startup(hba);
4876 /* check if device is detected by inter-connect layer */
4877 if (!ret && !ufshcd_is_device_present(hba)) {
4878 ufshcd_update_evt_hist(hba,
4879 UFS_EVT_LINK_STARTUP_FAIL,
4881 dev_err(hba->dev, "%s: Device not present\n", __func__);
4887 * DME link lost indication is only received when link is up,
4888 * but we can't be sure if the link is up until link startup
4889 * succeeds. So reset the local Uni-Pro and try again.
4891 if (ret && retries && ufshcd_hba_enable(hba)) {
4892 ufshcd_update_evt_hist(hba,
4893 UFS_EVT_LINK_STARTUP_FAIL,
4897 } while (ret && retries--);
4900 /* failed to get the link up... retire */
4901 ufshcd_update_evt_hist(hba,
4902 UFS_EVT_LINK_STARTUP_FAIL,
4907 if (link_startup_again) {
4908 link_startup_again = false;
4909 retries = DME_LINKSTARTUP_RETRIES;
4913 /* Mark that link is up in PWM-G1, 1-lane, SLOW-AUTO mode */
4914 ufshcd_init_pwr_info(hba);
4915 ufshcd_print_pwr_info(hba);
4917 if (hba->quirks & UFSHCD_QUIRK_BROKEN_LCC) {
4918 ret = ufshcd_disable_device_tx_lcc(hba);
4923 /* Include any host controller configuration via UIC commands */
4924 ret = ufshcd_vops_link_startup_notify(hba, POST_CHANGE);
4928 /* Clear UECPA once due to LINERESET has happened during LINK_STARTUP */
4929 ufshcd_readl(hba, REG_UIC_ERROR_CODE_PHY_ADAPTER_LAYER);
4930 ret = ufshcd_make_hba_operational(hba);
4933 dev_err(hba->dev, "link startup failed %d\n", ret);
4934 ufshcd_print_host_state(hba);
4935 ufshcd_print_pwr_info(hba);
4936 ufshcd_print_evt_hist(hba);
4942 * ufshcd_verify_dev_init() - Verify device initialization
4943 * @hba: per-adapter instance
4945 * Send NOP OUT UPIU and wait for NOP IN response to check whether the
4946 * device Transport Protocol (UTP) layer is ready after a reset.
4947 * If the UTP layer at the device side is not initialized, it may
4948 * not respond with NOP IN UPIU within timeout of %NOP_OUT_TIMEOUT
4949 * and we retry sending NOP OUT for %NOP_OUT_RETRIES iterations.
4951 static int ufshcd_verify_dev_init(struct ufs_hba *hba)
4956 ufshcd_hold(hba, false);
4957 mutex_lock(&hba->dev_cmd.lock);
4958 for (retries = NOP_OUT_RETRIES; retries > 0; retries--) {
4959 err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_NOP,
4960 hba->nop_out_timeout);
4962 if (!err || err == -ETIMEDOUT)
4965 dev_dbg(hba->dev, "%s: error %d retrying\n", __func__, err);
4967 mutex_unlock(&hba->dev_cmd.lock);
4968 ufshcd_release(hba);
4971 dev_err(hba->dev, "%s: NOP OUT failed %d\n", __func__, err);
4976 * ufshcd_setup_links - associate link b/w device wlun and other luns
4977 * @sdev: pointer to SCSI device
4978 * @hba: pointer to ufs hba
4980 static void ufshcd_setup_links(struct ufs_hba *hba, struct scsi_device *sdev)
4982 struct device_link *link;
4985 * Device wlun is the supplier & rest of the luns are consumers.
4986 * This ensures that device wlun suspends after all other luns.
4988 if (hba->ufs_device_wlun) {
4989 link = device_link_add(&sdev->sdev_gendev,
4990 &hba->ufs_device_wlun->sdev_gendev,
4991 DL_FLAG_PM_RUNTIME | DL_FLAG_RPM_ACTIVE);
4993 dev_err(&sdev->sdev_gendev, "Failed establishing link - %s\n",
4994 dev_name(&hba->ufs_device_wlun->sdev_gendev));
4998 /* Ignore REPORT_LUN wlun probing */
4999 if (hba->luns_avail == 1) {
5000 ufshcd_rpm_put(hba);
5005 * Device wlun is probed. The assumption is that WLUNs are
5006 * scanned before other LUNs.
5013 * ufshcd_lu_init - Initialize the relevant parameters of the LU
5014 * @hba: per-adapter instance
5015 * @sdev: pointer to SCSI device
5017 static void ufshcd_lu_init(struct ufs_hba *hba, struct scsi_device *sdev)
5019 int len = QUERY_DESC_MAX_SIZE;
5020 u8 lun = ufshcd_scsi_to_upiu_lun(sdev->lun);
5021 u8 lun_qdepth = hba->nutrs;
5025 desc_buf = kzalloc(len, GFP_KERNEL);
5029 ret = ufshcd_read_unit_desc_param(hba, lun, 0, desc_buf, len);
5031 if (ret == -EOPNOTSUPP)
5032 /* If LU doesn't support unit descriptor, its queue depth is set to 1 */
5038 if (desc_buf[UNIT_DESC_PARAM_LU_Q_DEPTH]) {
5040 * In per-LU queueing architecture, bLUQueueDepth will not be 0, then we will
5041 * use the smaller between UFSHCI CAP.NUTRS and UFS LU bLUQueueDepth
5043 lun_qdepth = min_t(int, desc_buf[UNIT_DESC_PARAM_LU_Q_DEPTH], hba->nutrs);
5046 * According to UFS device specification, the write protection mode is only supported by
5047 * normal LU, not supported by WLUN.
5049 if (hba->dev_info.f_power_on_wp_en && lun < hba->dev_info.max_lu_supported &&
5050 !hba->dev_info.is_lu_power_on_wp &&
5051 desc_buf[UNIT_DESC_PARAM_LU_WR_PROTECT] == UFS_LU_POWER_ON_WP)
5052 hba->dev_info.is_lu_power_on_wp = true;
5054 /* In case of RPMB LU, check if advanced RPMB mode is enabled */
5055 if (desc_buf[UNIT_DESC_PARAM_UNIT_INDEX] == UFS_UPIU_RPMB_WLUN &&
5056 desc_buf[RPMB_UNIT_DESC_PARAM_REGION_EN] & BIT(4))
5057 hba->dev_info.b_advanced_rpmb_en = true;
5063 * For WLUNs that don't support unit descriptor, queue depth is set to 1. For LUs whose
5064 * bLUQueueDepth == 0, the queue depth is set to a maximum value that host can queue.
5066 dev_dbg(hba->dev, "Set LU %x queue depth %d\n", lun, lun_qdepth);
5067 scsi_change_queue_depth(sdev, lun_qdepth);
5071 * ufshcd_slave_alloc - handle initial SCSI device configurations
5072 * @sdev: pointer to SCSI device
5076 static int ufshcd_slave_alloc(struct scsi_device *sdev)
5078 struct ufs_hba *hba;
5080 hba = shost_priv(sdev->host);
5082 /* Mode sense(6) is not supported by UFS, so use Mode sense(10) */
5083 sdev->use_10_for_ms = 1;
5085 /* DBD field should be set to 1 in mode sense(10) */
5086 sdev->set_dbd_for_ms = 1;
5088 /* allow SCSI layer to restart the device in case of errors */
5089 sdev->allow_restart = 1;
5091 /* REPORT SUPPORTED OPERATION CODES is not supported */
5092 sdev->no_report_opcodes = 1;
5094 /* WRITE_SAME command is not supported */
5095 sdev->no_write_same = 1;
5097 ufshcd_lu_init(hba, sdev);
5099 ufshcd_setup_links(hba, sdev);
5105 * ufshcd_change_queue_depth - change queue depth
5106 * @sdev: pointer to SCSI device
5107 * @depth: required depth to set
5109 * Change queue depth and make sure the max. limits are not crossed.
5111 static int ufshcd_change_queue_depth(struct scsi_device *sdev, int depth)
5113 return scsi_change_queue_depth(sdev, min(depth, sdev->host->can_queue));
5116 static void ufshcd_hpb_destroy(struct ufs_hba *hba, struct scsi_device *sdev)
5118 /* skip well-known LU */
5119 if ((sdev->lun >= UFS_UPIU_MAX_UNIT_NUM_ID) ||
5120 !(hba->dev_info.hpb_enabled) || !ufshpb_is_allowed(hba))
5123 ufshpb_destroy_lu(hba, sdev);
5126 static void ufshcd_hpb_configure(struct ufs_hba *hba, struct scsi_device *sdev)
5128 /* skip well-known LU */
5129 if ((sdev->lun >= UFS_UPIU_MAX_UNIT_NUM_ID) ||
5130 !(hba->dev_info.hpb_enabled) || !ufshpb_is_allowed(hba))
5133 ufshpb_init_hpb_lu(hba, sdev);
5137 * ufshcd_slave_configure - adjust SCSI device configurations
5138 * @sdev: pointer to SCSI device
5140 static int ufshcd_slave_configure(struct scsi_device *sdev)
5142 struct ufs_hba *hba = shost_priv(sdev->host);
5143 struct request_queue *q = sdev->request_queue;
5145 ufshcd_hpb_configure(hba, sdev);
5147 blk_queue_update_dma_pad(q, PRDT_DATA_BYTE_COUNT_PAD - 1);
5148 if (hba->quirks & UFSHCD_QUIRK_4KB_DMA_ALIGNMENT)
5149 blk_queue_update_dma_alignment(q, 4096 - 1);
5151 * Block runtime-pm until all consumers are added.
5152 * Refer ufshcd_setup_links().
5154 if (is_device_wlun(sdev))
5155 pm_runtime_get_noresume(&sdev->sdev_gendev);
5156 else if (ufshcd_is_rpm_autosuspend_allowed(hba))
5157 sdev->rpm_autosuspend = 1;
5159 * Do not print messages during runtime PM to avoid never-ending cycles
5160 * of messages written back to storage by user space causing runtime
5161 * resume, causing more messages and so on.
5163 sdev->silence_suspend = 1;
5165 ufshcd_crypto_register(hba, q);
5171 * ufshcd_slave_destroy - remove SCSI device configurations
5172 * @sdev: pointer to SCSI device
5174 static void ufshcd_slave_destroy(struct scsi_device *sdev)
5176 struct ufs_hba *hba;
5177 unsigned long flags;
5179 hba = shost_priv(sdev->host);
5181 ufshcd_hpb_destroy(hba, sdev);
5183 /* Drop the reference as it won't be needed anymore */
5184 if (ufshcd_scsi_to_upiu_lun(sdev->lun) == UFS_UPIU_UFS_DEVICE_WLUN) {
5185 spin_lock_irqsave(hba->host->host_lock, flags);
5186 hba->ufs_device_wlun = NULL;
5187 spin_unlock_irqrestore(hba->host->host_lock, flags);
5188 } else if (hba->ufs_device_wlun) {
5189 struct device *supplier = NULL;
5191 /* Ensure UFS Device WLUN exists and does not disappear */
5192 spin_lock_irqsave(hba->host->host_lock, flags);
5193 if (hba->ufs_device_wlun) {
5194 supplier = &hba->ufs_device_wlun->sdev_gendev;
5195 get_device(supplier);
5197 spin_unlock_irqrestore(hba->host->host_lock, flags);
5201 * If a LUN fails to probe (e.g. absent BOOT WLUN), the
5202 * device will not have been registered but can still
5203 * have a device link holding a reference to the device.
5205 device_link_remove(&sdev->sdev_gendev, supplier);
5206 put_device(supplier);
5212 * ufshcd_scsi_cmd_status - Update SCSI command result based on SCSI status
5213 * @lrbp: pointer to local reference block of completed command
5214 * @scsi_status: SCSI command status
5216 * Returns value base on SCSI command status
5219 ufshcd_scsi_cmd_status(struct ufshcd_lrb *lrbp, int scsi_status)
5223 switch (scsi_status) {
5224 case SAM_STAT_CHECK_CONDITION:
5225 ufshcd_copy_sense_data(lrbp);
5228 result |= DID_OK << 16 | scsi_status;
5230 case SAM_STAT_TASK_SET_FULL:
5232 case SAM_STAT_TASK_ABORTED:
5233 ufshcd_copy_sense_data(lrbp);
5234 result |= scsi_status;
5237 result |= DID_ERROR << 16;
5239 } /* end of switch */
5245 * ufshcd_transfer_rsp_status - Get overall status of the response
5246 * @hba: per adapter instance
5247 * @lrbp: pointer to local reference block of completed command
5248 * @cqe: pointer to the completion queue entry
5250 * Returns result of the command to notify SCSI midlayer
5253 ufshcd_transfer_rsp_status(struct ufs_hba *hba, struct ufshcd_lrb *lrbp,
5254 struct cq_entry *cqe)
5260 scsi_set_resid(lrbp->cmd,
5261 be32_to_cpu(lrbp->ucd_rsp_ptr->sr.residual_transfer_count));
5263 /* overall command status of utrd */
5264 ocs = ufshcd_get_tr_ocs(lrbp, cqe);
5266 if (hba->quirks & UFSHCD_QUIRK_BROKEN_OCS_FATAL_ERROR) {
5267 if (be32_to_cpu(lrbp->ucd_rsp_ptr->header.dword_1) &
5268 MASK_RSP_UPIU_RESULT)
5274 result = ufshcd_get_req_rsp(lrbp->ucd_rsp_ptr);
5275 hba->ufs_stats.last_hibern8_exit_tstamp = ktime_set(0, 0);
5277 case UPIU_TRANSACTION_RESPONSE:
5279 * get the response UPIU result to extract
5280 * the SCSI command status
5282 result = ufshcd_get_rsp_upiu_result(lrbp->ucd_rsp_ptr);
5285 * get the result based on SCSI status response
5286 * to notify the SCSI midlayer of the command status
5288 scsi_status = result & MASK_SCSI_STATUS;
5289 result = ufshcd_scsi_cmd_status(lrbp, scsi_status);
5292 * Currently we are only supporting BKOPs exception
5293 * events hence we can ignore BKOPs exception event
5294 * during power management callbacks. BKOPs exception
5295 * event is not expected to be raised in runtime suspend
5296 * callback as it allows the urgent bkops.
5297 * During system suspend, we are anyway forcefully
5298 * disabling the bkops and if urgent bkops is needed
5299 * it will be enabled on system resume. Long term
5300 * solution could be to abort the system suspend if
5301 * UFS device needs urgent BKOPs.
5303 if (!hba->pm_op_in_progress &&
5304 !ufshcd_eh_in_progress(hba) &&
5305 ufshcd_is_exception_event(lrbp->ucd_rsp_ptr))
5306 /* Flushed in suspend */
5307 schedule_work(&hba->eeh_work);
5309 if (scsi_status == SAM_STAT_GOOD)
5310 ufshpb_rsp_upiu(hba, lrbp);
5312 case UPIU_TRANSACTION_REJECT_UPIU:
5313 /* TODO: handle Reject UPIU Response */
5314 result = DID_ERROR << 16;
5316 "Reject UPIU not fully implemented\n");
5320 "Unexpected request response code = %x\n",
5322 result = DID_ERROR << 16;
5327 result |= DID_ABORT << 16;
5329 case OCS_INVALID_COMMAND_STATUS:
5330 result |= DID_REQUEUE << 16;
5332 case OCS_INVALID_CMD_TABLE_ATTR:
5333 case OCS_INVALID_PRDT_ATTR:
5334 case OCS_MISMATCH_DATA_BUF_SIZE:
5335 case OCS_MISMATCH_RESP_UPIU_SIZE:
5336 case OCS_PEER_COMM_FAILURE:
5337 case OCS_FATAL_ERROR:
5338 case OCS_DEVICE_FATAL_ERROR:
5339 case OCS_INVALID_CRYPTO_CONFIG:
5340 case OCS_GENERAL_CRYPTO_ERROR:
5342 result |= DID_ERROR << 16;
5344 "OCS error from controller = %x for tag %d\n",
5345 ocs, lrbp->task_tag);
5346 ufshcd_print_evt_hist(hba);
5347 ufshcd_print_host_state(hba);
5349 } /* end of switch */
5351 if ((host_byte(result) != DID_OK) &&
5352 (host_byte(result) != DID_REQUEUE) && !hba->silence_err_logs)
5353 ufshcd_print_tr(hba, lrbp->task_tag, true);
5357 static bool ufshcd_is_auto_hibern8_error(struct ufs_hba *hba,
5360 if (!ufshcd_is_auto_hibern8_supported(hba) ||
5361 !ufshcd_is_auto_hibern8_enabled(hba))
5364 if (!(intr_mask & UFSHCD_UIC_HIBERN8_MASK))
5367 if (hba->active_uic_cmd &&
5368 (hba->active_uic_cmd->command == UIC_CMD_DME_HIBER_ENTER ||
5369 hba->active_uic_cmd->command == UIC_CMD_DME_HIBER_EXIT))
5376 * ufshcd_uic_cmd_compl - handle completion of uic command
5377 * @hba: per adapter instance
5378 * @intr_status: interrupt status generated by the controller
5381 * IRQ_HANDLED - If interrupt is valid
5382 * IRQ_NONE - If invalid interrupt
5384 static irqreturn_t ufshcd_uic_cmd_compl(struct ufs_hba *hba, u32 intr_status)
5386 irqreturn_t retval = IRQ_NONE;
5388 spin_lock(hba->host->host_lock);
5389 if (ufshcd_is_auto_hibern8_error(hba, intr_status))
5390 hba->errors |= (UFSHCD_UIC_HIBERN8_MASK & intr_status);
5392 if ((intr_status & UIC_COMMAND_COMPL) && hba->active_uic_cmd) {
5393 hba->active_uic_cmd->argument2 |=
5394 ufshcd_get_uic_cmd_result(hba);
5395 hba->active_uic_cmd->argument3 =
5396 ufshcd_get_dme_attr_val(hba);
5397 if (!hba->uic_async_done)
5398 hba->active_uic_cmd->cmd_active = 0;
5399 complete(&hba->active_uic_cmd->done);
5400 retval = IRQ_HANDLED;
5403 if ((intr_status & UFSHCD_UIC_PWR_MASK) && hba->uic_async_done) {
5404 hba->active_uic_cmd->cmd_active = 0;
5405 complete(hba->uic_async_done);
5406 retval = IRQ_HANDLED;
5409 if (retval == IRQ_HANDLED)
5410 ufshcd_add_uic_command_trace(hba, hba->active_uic_cmd,
5412 spin_unlock(hba->host->host_lock);
5416 /* Release the resources allocated for processing a SCSI command. */
5417 static void ufshcd_release_scsi_cmd(struct ufs_hba *hba,
5418 struct ufshcd_lrb *lrbp)
5420 struct scsi_cmnd *cmd = lrbp->cmd;
5422 scsi_dma_unmap(cmd);
5423 ufshcd_release(hba);
5424 ufshcd_clk_scaling_update_busy(hba);
5428 * ufshcd_compl_one_cqe - handle a completion queue entry
5429 * @hba: per adapter instance
5430 * @task_tag: the task tag of the request to be completed
5431 * @cqe: pointer to the completion queue entry
5433 void ufshcd_compl_one_cqe(struct ufs_hba *hba, int task_tag,
5434 struct cq_entry *cqe)
5436 struct ufshcd_lrb *lrbp;
5437 struct scsi_cmnd *cmd;
5439 lrbp = &hba->lrb[task_tag];
5440 lrbp->compl_time_stamp = ktime_get();
5443 if (unlikely(ufshcd_should_inform_monitor(hba, lrbp)))
5444 ufshcd_update_monitor(hba, lrbp);
5445 ufshcd_add_command_trace(hba, task_tag, UFS_CMD_COMP);
5446 cmd->result = ufshcd_transfer_rsp_status(hba, lrbp, cqe);
5447 ufshcd_release_scsi_cmd(hba, lrbp);
5448 /* Do not touch lrbp after scsi done */
5450 } else if (lrbp->command_type == UTP_CMD_TYPE_DEV_MANAGE ||
5451 lrbp->command_type == UTP_CMD_TYPE_UFS_STORAGE) {
5452 if (hba->dev_cmd.complete) {
5453 hba->dev_cmd.cqe = cqe;
5454 ufshcd_add_command_trace(hba, task_tag, UFS_DEV_COMP);
5455 complete(hba->dev_cmd.complete);
5456 ufshcd_clk_scaling_update_busy(hba);
5462 * __ufshcd_transfer_req_compl - handle SCSI and query command completion
5463 * @hba: per adapter instance
5464 * @completed_reqs: bitmask that indicates which requests to complete
5466 static void __ufshcd_transfer_req_compl(struct ufs_hba *hba,
5467 unsigned long completed_reqs)
5471 for_each_set_bit(tag, &completed_reqs, hba->nutrs)
5472 ufshcd_compl_one_cqe(hba, tag, NULL);
5475 /* Any value that is not an existing queue number is fine for this constant. */
5477 UFSHCD_POLL_FROM_INTERRUPT_CONTEXT = -1
5480 static void ufshcd_clear_polled(struct ufs_hba *hba,
5481 unsigned long *completed_reqs)
5485 for_each_set_bit(tag, completed_reqs, hba->nutrs) {
5486 struct scsi_cmnd *cmd = hba->lrb[tag].cmd;
5490 if (scsi_cmd_to_rq(cmd)->cmd_flags & REQ_POLLED)
5491 __clear_bit(tag, completed_reqs);
5496 * Returns > 0 if one or more commands have been completed or 0 if no
5497 * requests have been completed.
5499 static int ufshcd_poll(struct Scsi_Host *shost, unsigned int queue_num)
5501 struct ufs_hba *hba = shost_priv(shost);
5502 unsigned long completed_reqs, flags;
5504 struct ufs_hw_queue *hwq;
5506 if (is_mcq_enabled(hba)) {
5507 hwq = &hba->uhq[queue_num + UFSHCD_MCQ_IO_QUEUE_OFFSET];
5509 return ufshcd_mcq_poll_cqe_lock(hba, hwq);
5512 spin_lock_irqsave(&hba->outstanding_lock, flags);
5513 tr_doorbell = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
5514 completed_reqs = ~tr_doorbell & hba->outstanding_reqs;
5515 WARN_ONCE(completed_reqs & ~hba->outstanding_reqs,
5516 "completed: %#lx; outstanding: %#lx\n", completed_reqs,
5517 hba->outstanding_reqs);
5518 if (queue_num == UFSHCD_POLL_FROM_INTERRUPT_CONTEXT) {
5519 /* Do not complete polled requests from interrupt context. */
5520 ufshcd_clear_polled(hba, &completed_reqs);
5522 hba->outstanding_reqs &= ~completed_reqs;
5523 spin_unlock_irqrestore(&hba->outstanding_lock, flags);
5526 __ufshcd_transfer_req_compl(hba, completed_reqs);
5528 return completed_reqs != 0;
5532 * ufshcd_transfer_req_compl - handle SCSI and query command completion
5533 * @hba: per adapter instance
5536 * IRQ_HANDLED - If interrupt is valid
5537 * IRQ_NONE - If invalid interrupt
5539 static irqreturn_t ufshcd_transfer_req_compl(struct ufs_hba *hba)
5541 /* Resetting interrupt aggregation counters first and reading the
5542 * DOOR_BELL afterward allows us to handle all the completed requests.
5543 * In order to prevent other interrupts starvation the DB is read once
5544 * after reset. The down side of this solution is the possibility of
5545 * false interrupt if device completes another request after resetting
5546 * aggregation and before reading the DB.
5548 if (ufshcd_is_intr_aggr_allowed(hba) &&
5549 !(hba->quirks & UFSHCI_QUIRK_SKIP_RESET_INTR_AGGR))
5550 ufshcd_reset_intr_aggr(hba);
5552 if (ufs_fail_completion())
5556 * Ignore the ufshcd_poll() return value and return IRQ_HANDLED since we
5557 * do not want polling to trigger spurious interrupt complaints.
5559 ufshcd_poll(hba->host, UFSHCD_POLL_FROM_INTERRUPT_CONTEXT);
5564 int __ufshcd_write_ee_control(struct ufs_hba *hba, u32 ee_ctrl_mask)
5566 return ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_WRITE_ATTR,
5567 QUERY_ATTR_IDN_EE_CONTROL, 0, 0,
5571 int ufshcd_write_ee_control(struct ufs_hba *hba)
5575 mutex_lock(&hba->ee_ctrl_mutex);
5576 err = __ufshcd_write_ee_control(hba, hba->ee_ctrl_mask);
5577 mutex_unlock(&hba->ee_ctrl_mutex);
5579 dev_err(hba->dev, "%s: failed to write ee control %d\n",
5584 int ufshcd_update_ee_control(struct ufs_hba *hba, u16 *mask,
5585 const u16 *other_mask, u16 set, u16 clr)
5587 u16 new_mask, ee_ctrl_mask;
5590 mutex_lock(&hba->ee_ctrl_mutex);
5591 new_mask = (*mask & ~clr) | set;
5592 ee_ctrl_mask = new_mask | *other_mask;
5593 if (ee_ctrl_mask != hba->ee_ctrl_mask)
5594 err = __ufshcd_write_ee_control(hba, ee_ctrl_mask);
5595 /* Still need to update 'mask' even if 'ee_ctrl_mask' was unchanged */
5597 hba->ee_ctrl_mask = ee_ctrl_mask;
5600 mutex_unlock(&hba->ee_ctrl_mutex);
5605 * ufshcd_disable_ee - disable exception event
5606 * @hba: per-adapter instance
5607 * @mask: exception event to disable
5609 * Disables exception event in the device so that the EVENT_ALERT
5612 * Returns zero on success, non-zero error value on failure.
5614 static inline int ufshcd_disable_ee(struct ufs_hba *hba, u16 mask)
5616 return ufshcd_update_ee_drv_mask(hba, 0, mask);
5620 * ufshcd_enable_ee - enable exception event
5621 * @hba: per-adapter instance
5622 * @mask: exception event to enable
5624 * Enable corresponding exception event in the device to allow
5625 * device to alert host in critical scenarios.
5627 * Returns zero on success, non-zero error value on failure.
5629 static inline int ufshcd_enable_ee(struct ufs_hba *hba, u16 mask)
5631 return ufshcd_update_ee_drv_mask(hba, mask, 0);
5635 * ufshcd_enable_auto_bkops - Allow device managed BKOPS
5636 * @hba: per-adapter instance
5638 * Allow device to manage background operations on its own. Enabling
5639 * this might lead to inconsistent latencies during normal data transfers
5640 * as the device is allowed to manage its own way of handling background
5643 * Returns zero on success, non-zero on failure.
5645 static int ufshcd_enable_auto_bkops(struct ufs_hba *hba)
5649 if (hba->auto_bkops_enabled)
5652 err = ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_SET_FLAG,
5653 QUERY_FLAG_IDN_BKOPS_EN, 0, NULL);
5655 dev_err(hba->dev, "%s: failed to enable bkops %d\n",
5660 hba->auto_bkops_enabled = true;
5661 trace_ufshcd_auto_bkops_state(dev_name(hba->dev), "Enabled");
5663 /* No need of URGENT_BKOPS exception from the device */
5664 err = ufshcd_disable_ee(hba, MASK_EE_URGENT_BKOPS);
5666 dev_err(hba->dev, "%s: failed to disable exception event %d\n",
5673 * ufshcd_disable_auto_bkops - block device in doing background operations
5674 * @hba: per-adapter instance
5676 * Disabling background operations improves command response latency but
5677 * has drawback of device moving into critical state where the device is
5678 * not-operable. Make sure to call ufshcd_enable_auto_bkops() whenever the
5679 * host is idle so that BKOPS are managed effectively without any negative
5682 * Returns zero on success, non-zero on failure.
5684 static int ufshcd_disable_auto_bkops(struct ufs_hba *hba)
5688 if (!hba->auto_bkops_enabled)
5692 * If host assisted BKOPs is to be enabled, make sure
5693 * urgent bkops exception is allowed.
5695 err = ufshcd_enable_ee(hba, MASK_EE_URGENT_BKOPS);
5697 dev_err(hba->dev, "%s: failed to enable exception event %d\n",
5702 err = ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_CLEAR_FLAG,
5703 QUERY_FLAG_IDN_BKOPS_EN, 0, NULL);
5705 dev_err(hba->dev, "%s: failed to disable bkops %d\n",
5707 ufshcd_disable_ee(hba, MASK_EE_URGENT_BKOPS);
5711 hba->auto_bkops_enabled = false;
5712 trace_ufshcd_auto_bkops_state(dev_name(hba->dev), "Disabled");
5713 hba->is_urgent_bkops_lvl_checked = false;
5719 * ufshcd_force_reset_auto_bkops - force reset auto bkops state
5720 * @hba: per adapter instance
5722 * After a device reset the device may toggle the BKOPS_EN flag
5723 * to default value. The s/w tracking variables should be updated
5724 * as well. This function would change the auto-bkops state based on
5725 * UFSHCD_CAP_KEEP_AUTO_BKOPS_ENABLED_EXCEPT_SUSPEND.
5727 static void ufshcd_force_reset_auto_bkops(struct ufs_hba *hba)
5729 if (ufshcd_keep_autobkops_enabled_except_suspend(hba)) {
5730 hba->auto_bkops_enabled = false;
5731 hba->ee_ctrl_mask |= MASK_EE_URGENT_BKOPS;
5732 ufshcd_enable_auto_bkops(hba);
5734 hba->auto_bkops_enabled = true;
5735 hba->ee_ctrl_mask &= ~MASK_EE_URGENT_BKOPS;
5736 ufshcd_disable_auto_bkops(hba);
5738 hba->urgent_bkops_lvl = BKOPS_STATUS_PERF_IMPACT;
5739 hba->is_urgent_bkops_lvl_checked = false;
5742 static inline int ufshcd_get_bkops_status(struct ufs_hba *hba, u32 *status)
5744 return ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
5745 QUERY_ATTR_IDN_BKOPS_STATUS, 0, 0, status);
5749 * ufshcd_bkops_ctrl - control the auto bkops based on current bkops status
5750 * @hba: per-adapter instance
5751 * @status: bkops_status value
5753 * Read the bkops_status from the UFS device and Enable fBackgroundOpsEn
5754 * flag in the device to permit background operations if the device
5755 * bkops_status is greater than or equal to "status" argument passed to
5756 * this function, disable otherwise.
5758 * Returns 0 for success, non-zero in case of failure.
5760 * NOTE: Caller of this function can check the "hba->auto_bkops_enabled" flag
5761 * to know whether auto bkops is enabled or disabled after this function
5762 * returns control to it.
5764 static int ufshcd_bkops_ctrl(struct ufs_hba *hba,
5765 enum bkops_status status)
5768 u32 curr_status = 0;
5770 err = ufshcd_get_bkops_status(hba, &curr_status);
5772 dev_err(hba->dev, "%s: failed to get BKOPS status %d\n",
5775 } else if (curr_status > BKOPS_STATUS_MAX) {
5776 dev_err(hba->dev, "%s: invalid BKOPS status %d\n",
5777 __func__, curr_status);
5782 if (curr_status >= status)
5783 err = ufshcd_enable_auto_bkops(hba);
5785 err = ufshcd_disable_auto_bkops(hba);
5791 * ufshcd_urgent_bkops - handle urgent bkops exception event
5792 * @hba: per-adapter instance
5794 * Enable fBackgroundOpsEn flag in the device to permit background
5797 * If BKOPs is enabled, this function returns 0, 1 if the bkops in not enabled
5798 * and negative error value for any other failure.
5800 static int ufshcd_urgent_bkops(struct ufs_hba *hba)
5802 return ufshcd_bkops_ctrl(hba, hba->urgent_bkops_lvl);
5805 static inline int ufshcd_get_ee_status(struct ufs_hba *hba, u32 *status)
5807 return ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
5808 QUERY_ATTR_IDN_EE_STATUS, 0, 0, status);
5811 static void ufshcd_bkops_exception_event_handler(struct ufs_hba *hba)
5814 u32 curr_status = 0;
5816 if (hba->is_urgent_bkops_lvl_checked)
5817 goto enable_auto_bkops;
5819 err = ufshcd_get_bkops_status(hba, &curr_status);
5821 dev_err(hba->dev, "%s: failed to get BKOPS status %d\n",
5827 * We are seeing that some devices are raising the urgent bkops
5828 * exception events even when BKOPS status doesn't indicate performace
5829 * impacted or critical. Handle these device by determining their urgent
5830 * bkops status at runtime.
5832 if (curr_status < BKOPS_STATUS_PERF_IMPACT) {
5833 dev_err(hba->dev, "%s: device raised urgent BKOPS exception for bkops status %d\n",
5834 __func__, curr_status);
5835 /* update the current status as the urgent bkops level */
5836 hba->urgent_bkops_lvl = curr_status;
5837 hba->is_urgent_bkops_lvl_checked = true;
5841 err = ufshcd_enable_auto_bkops(hba);
5844 dev_err(hba->dev, "%s: failed to handle urgent bkops %d\n",
5848 static void ufshcd_temp_exception_event_handler(struct ufs_hba *hba, u16 status)
5852 if (ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
5853 QUERY_ATTR_IDN_CASE_ROUGH_TEMP, 0, 0, &value))
5856 dev_info(hba->dev, "exception Tcase %d\n", value - 80);
5858 ufs_hwmon_notify_event(hba, status & MASK_EE_URGENT_TEMP);
5861 * A placeholder for the platform vendors to add whatever additional
5866 static int __ufshcd_wb_toggle(struct ufs_hba *hba, bool set, enum flag_idn idn)
5869 enum query_opcode opcode = set ? UPIU_QUERY_OPCODE_SET_FLAG :
5870 UPIU_QUERY_OPCODE_CLEAR_FLAG;
5872 index = ufshcd_wb_get_query_index(hba);
5873 return ufshcd_query_flag_retry(hba, opcode, idn, index, NULL);
5876 int ufshcd_wb_toggle(struct ufs_hba *hba, bool enable)
5880 if (!ufshcd_is_wb_allowed(hba) ||
5881 hba->dev_info.wb_enabled == enable)
5884 ret = __ufshcd_wb_toggle(hba, enable, QUERY_FLAG_IDN_WB_EN);
5886 dev_err(hba->dev, "%s: Write Booster %s failed %d\n",
5887 __func__, enable ? "enabling" : "disabling", ret);
5891 hba->dev_info.wb_enabled = enable;
5892 dev_dbg(hba->dev, "%s: Write Booster %s\n",
5893 __func__, enable ? "enabled" : "disabled");
5898 static void ufshcd_wb_toggle_buf_flush_during_h8(struct ufs_hba *hba,
5903 ret = __ufshcd_wb_toggle(hba, enable,
5904 QUERY_FLAG_IDN_WB_BUFF_FLUSH_DURING_HIBERN8);
5906 dev_err(hba->dev, "%s: WB-Buf Flush during H8 %s failed %d\n",
5907 __func__, enable ? "enabling" : "disabling", ret);
5910 dev_dbg(hba->dev, "%s: WB-Buf Flush during H8 %s\n",
5911 __func__, enable ? "enabled" : "disabled");
5914 int ufshcd_wb_toggle_buf_flush(struct ufs_hba *hba, bool enable)
5918 if (!ufshcd_is_wb_allowed(hba) ||
5919 hba->dev_info.wb_buf_flush_enabled == enable)
5922 ret = __ufshcd_wb_toggle(hba, enable, QUERY_FLAG_IDN_WB_BUFF_FLUSH_EN);
5924 dev_err(hba->dev, "%s: WB-Buf Flush %s failed %d\n",
5925 __func__, enable ? "enabling" : "disabling", ret);
5929 hba->dev_info.wb_buf_flush_enabled = enable;
5930 dev_dbg(hba->dev, "%s: WB-Buf Flush %s\n",
5931 __func__, enable ? "enabled" : "disabled");
5936 static bool ufshcd_wb_presrv_usrspc_keep_vcc_on(struct ufs_hba *hba,
5943 index = ufshcd_wb_get_query_index(hba);
5944 ret = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
5945 QUERY_ATTR_IDN_CURR_WB_BUFF_SIZE,
5946 index, 0, &cur_buf);
5948 dev_err(hba->dev, "%s: dCurWriteBoosterBufferSize read failed %d\n",
5954 dev_info(hba->dev, "dCurWBBuf: %d WB disabled until free-space is available\n",
5958 /* Let it continue to flush when available buffer exceeds threshold */
5959 return avail_buf < hba->vps->wb_flush_threshold;
5962 static void ufshcd_wb_force_disable(struct ufs_hba *hba)
5964 if (ufshcd_is_wb_buf_flush_allowed(hba))
5965 ufshcd_wb_toggle_buf_flush(hba, false);
5967 ufshcd_wb_toggle_buf_flush_during_h8(hba, false);
5968 ufshcd_wb_toggle(hba, false);
5969 hba->caps &= ~UFSHCD_CAP_WB_EN;
5971 dev_info(hba->dev, "%s: WB force disabled\n", __func__);
5974 static bool ufshcd_is_wb_buf_lifetime_available(struct ufs_hba *hba)
5980 index = ufshcd_wb_get_query_index(hba);
5981 ret = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
5982 QUERY_ATTR_IDN_WB_BUFF_LIFE_TIME_EST,
5983 index, 0, &lifetime);
5986 "%s: bWriteBoosterBufferLifeTimeEst read failed %d\n",
5991 if (lifetime == UFS_WB_EXCEED_LIFETIME) {
5992 dev_err(hba->dev, "%s: WB buf lifetime is exhausted 0x%02X\n",
5993 __func__, lifetime);
5997 dev_dbg(hba->dev, "%s: WB buf lifetime is 0x%02X\n",
5998 __func__, lifetime);
6003 static bool ufshcd_wb_need_flush(struct ufs_hba *hba)
6009 if (!ufshcd_is_wb_allowed(hba))
6012 if (!ufshcd_is_wb_buf_lifetime_available(hba)) {
6013 ufshcd_wb_force_disable(hba);
6018 * The ufs device needs the vcc to be ON to flush.
6019 * With user-space reduction enabled, it's enough to enable flush
6020 * by checking only the available buffer. The threshold
6021 * defined here is > 90% full.
6022 * With user-space preserved enabled, the current-buffer
6023 * should be checked too because the wb buffer size can reduce
6024 * when disk tends to be full. This info is provided by current
6025 * buffer (dCurrentWriteBoosterBufferSize). There's no point in
6026 * keeping vcc on when current buffer is empty.
6028 index = ufshcd_wb_get_query_index(hba);
6029 ret = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
6030 QUERY_ATTR_IDN_AVAIL_WB_BUFF_SIZE,
6031 index, 0, &avail_buf);
6033 dev_warn(hba->dev, "%s: dAvailableWriteBoosterBufferSize read failed %d\n",
6038 if (!hba->dev_info.b_presrv_uspc_en)
6039 return avail_buf <= UFS_WB_BUF_REMAIN_PERCENT(10);
6041 return ufshcd_wb_presrv_usrspc_keep_vcc_on(hba, avail_buf);
6044 static void ufshcd_rpm_dev_flush_recheck_work(struct work_struct *work)
6046 struct ufs_hba *hba = container_of(to_delayed_work(work),
6048 rpm_dev_flush_recheck_work);
6050 * To prevent unnecessary VCC power drain after device finishes
6051 * WriteBooster buffer flush or Auto BKOPs, force runtime resume
6052 * after a certain delay to recheck the threshold by next runtime
6055 ufshcd_rpm_get_sync(hba);
6056 ufshcd_rpm_put_sync(hba);
6060 * ufshcd_exception_event_handler - handle exceptions raised by device
6061 * @work: pointer to work data
6063 * Read bExceptionEventStatus attribute from the device and handle the
6064 * exception event accordingly.
6066 static void ufshcd_exception_event_handler(struct work_struct *work)
6068 struct ufs_hba *hba;
6071 hba = container_of(work, struct ufs_hba, eeh_work);
6073 ufshcd_scsi_block_requests(hba);
6074 err = ufshcd_get_ee_status(hba, &status);
6076 dev_err(hba->dev, "%s: failed to get exception status %d\n",
6081 trace_ufshcd_exception_event(dev_name(hba->dev), status);
6083 if (status & hba->ee_drv_mask & MASK_EE_URGENT_BKOPS)
6084 ufshcd_bkops_exception_event_handler(hba);
6086 if (status & hba->ee_drv_mask & MASK_EE_URGENT_TEMP)
6087 ufshcd_temp_exception_event_handler(hba, status);
6089 ufs_debugfs_exception_event(hba, status);
6091 ufshcd_scsi_unblock_requests(hba);
6094 /* Complete requests that have door-bell cleared */
6095 static void ufshcd_complete_requests(struct ufs_hba *hba)
6097 ufshcd_transfer_req_compl(hba);
6098 ufshcd_tmc_handler(hba);
6102 * ufshcd_quirk_dl_nac_errors - This function checks if error handling is
6103 * to recover from the DL NAC errors or not.
6104 * @hba: per-adapter instance
6106 * Returns true if error handling is required, false otherwise
6108 static bool ufshcd_quirk_dl_nac_errors(struct ufs_hba *hba)
6110 unsigned long flags;
6111 bool err_handling = true;
6113 spin_lock_irqsave(hba->host->host_lock, flags);
6115 * UFS_DEVICE_QUIRK_RECOVERY_FROM_DL_NAC_ERRORS only workaround the
6116 * device fatal error and/or DL NAC & REPLAY timeout errors.
6118 if (hba->saved_err & (CONTROLLER_FATAL_ERROR | SYSTEM_BUS_FATAL_ERROR))
6121 if ((hba->saved_err & DEVICE_FATAL_ERROR) ||
6122 ((hba->saved_err & UIC_ERROR) &&
6123 (hba->saved_uic_err & UFSHCD_UIC_DL_TCx_REPLAY_ERROR)))
6126 if ((hba->saved_err & UIC_ERROR) &&
6127 (hba->saved_uic_err & UFSHCD_UIC_DL_NAC_RECEIVED_ERROR)) {
6130 * wait for 50ms to see if we can get any other errors or not.
6132 spin_unlock_irqrestore(hba->host->host_lock, flags);
6134 spin_lock_irqsave(hba->host->host_lock, flags);
6137 * now check if we have got any other severe errors other than
6140 if ((hba->saved_err & INT_FATAL_ERRORS) ||
6141 ((hba->saved_err & UIC_ERROR) &&
6142 (hba->saved_uic_err & ~UFSHCD_UIC_DL_NAC_RECEIVED_ERROR)))
6146 * As DL NAC is the only error received so far, send out NOP
6147 * command to confirm if link is still active or not.
6148 * - If we don't get any response then do error recovery.
6149 * - If we get response then clear the DL NAC error bit.
6152 spin_unlock_irqrestore(hba->host->host_lock, flags);
6153 err = ufshcd_verify_dev_init(hba);
6154 spin_lock_irqsave(hba->host->host_lock, flags);
6159 /* Link seems to be alive hence ignore the DL NAC errors */
6160 if (hba->saved_uic_err == UFSHCD_UIC_DL_NAC_RECEIVED_ERROR)
6161 hba->saved_err &= ~UIC_ERROR;
6162 /* clear NAC error */
6163 hba->saved_uic_err &= ~UFSHCD_UIC_DL_NAC_RECEIVED_ERROR;
6164 if (!hba->saved_uic_err)
6165 err_handling = false;
6168 spin_unlock_irqrestore(hba->host->host_lock, flags);
6169 return err_handling;
6172 /* host lock must be held before calling this func */
6173 static inline bool ufshcd_is_saved_err_fatal(struct ufs_hba *hba)
6175 return (hba->saved_uic_err & UFSHCD_UIC_DL_PA_INIT_ERROR) ||
6176 (hba->saved_err & (INT_FATAL_ERRORS | UFSHCD_UIC_HIBERN8_MASK));
6179 void ufshcd_schedule_eh_work(struct ufs_hba *hba)
6181 lockdep_assert_held(hba->host->host_lock);
6183 /* handle fatal errors only when link is not in error state */
6184 if (hba->ufshcd_state != UFSHCD_STATE_ERROR) {
6185 if (hba->force_reset || ufshcd_is_link_broken(hba) ||
6186 ufshcd_is_saved_err_fatal(hba))
6187 hba->ufshcd_state = UFSHCD_STATE_EH_SCHEDULED_FATAL;
6189 hba->ufshcd_state = UFSHCD_STATE_EH_SCHEDULED_NON_FATAL;
6190 queue_work(hba->eh_wq, &hba->eh_work);
6194 static void ufshcd_force_error_recovery(struct ufs_hba *hba)
6196 spin_lock_irq(hba->host->host_lock);
6197 hba->force_reset = true;
6198 ufshcd_schedule_eh_work(hba);
6199 spin_unlock_irq(hba->host->host_lock);
6202 static void ufshcd_clk_scaling_allow(struct ufs_hba *hba, bool allow)
6204 mutex_lock(&hba->wb_mutex);
6205 down_write(&hba->clk_scaling_lock);
6206 hba->clk_scaling.is_allowed = allow;
6207 up_write(&hba->clk_scaling_lock);
6208 mutex_unlock(&hba->wb_mutex);
6211 static void ufshcd_clk_scaling_suspend(struct ufs_hba *hba, bool suspend)
6214 if (hba->clk_scaling.is_enabled)
6215 ufshcd_suspend_clkscaling(hba);
6216 ufshcd_clk_scaling_allow(hba, false);
6218 ufshcd_clk_scaling_allow(hba, true);
6219 if (hba->clk_scaling.is_enabled)
6220 ufshcd_resume_clkscaling(hba);
6224 static void ufshcd_err_handling_prepare(struct ufs_hba *hba)
6226 ufshcd_rpm_get_sync(hba);
6227 if (pm_runtime_status_suspended(&hba->ufs_device_wlun->sdev_gendev) ||
6228 hba->is_sys_suspended) {
6229 enum ufs_pm_op pm_op;
6232 * Don't assume anything of resume, if
6233 * resume fails, irq and clocks can be OFF, and powers
6234 * can be OFF or in LPM.
6236 ufshcd_setup_hba_vreg(hba, true);
6237 ufshcd_enable_irq(hba);
6238 ufshcd_setup_vreg(hba, true);
6239 ufshcd_config_vreg_hpm(hba, hba->vreg_info.vccq);
6240 ufshcd_config_vreg_hpm(hba, hba->vreg_info.vccq2);
6241 ufshcd_hold(hba, false);
6242 if (!ufshcd_is_clkgating_allowed(hba))
6243 ufshcd_setup_clocks(hba, true);
6244 ufshcd_release(hba);
6245 pm_op = hba->is_sys_suspended ? UFS_SYSTEM_PM : UFS_RUNTIME_PM;
6246 ufshcd_vops_resume(hba, pm_op);
6248 ufshcd_hold(hba, false);
6249 if (ufshcd_is_clkscaling_supported(hba) &&
6250 hba->clk_scaling.is_enabled)
6251 ufshcd_suspend_clkscaling(hba);
6252 ufshcd_clk_scaling_allow(hba, false);
6254 ufshcd_scsi_block_requests(hba);
6255 /* Drain ufshcd_queuecommand() */
6257 cancel_work_sync(&hba->eeh_work);
6260 static void ufshcd_err_handling_unprepare(struct ufs_hba *hba)
6262 ufshcd_scsi_unblock_requests(hba);
6263 ufshcd_release(hba);
6264 if (ufshcd_is_clkscaling_supported(hba))
6265 ufshcd_clk_scaling_suspend(hba, false);
6266 ufshcd_rpm_put(hba);
6269 static inline bool ufshcd_err_handling_should_stop(struct ufs_hba *hba)
6271 return (!hba->is_powered || hba->shutting_down ||
6272 !hba->ufs_device_wlun ||
6273 hba->ufshcd_state == UFSHCD_STATE_ERROR ||
6274 (!(hba->saved_err || hba->saved_uic_err || hba->force_reset ||
6275 ufshcd_is_link_broken(hba))));
6279 static void ufshcd_recover_pm_error(struct ufs_hba *hba)
6281 struct Scsi_Host *shost = hba->host;
6282 struct scsi_device *sdev;
6283 struct request_queue *q;
6286 hba->is_sys_suspended = false;
6288 * Set RPM status of wlun device to RPM_ACTIVE,
6289 * this also clears its runtime error.
6291 ret = pm_runtime_set_active(&hba->ufs_device_wlun->sdev_gendev);
6293 /* hba device might have a runtime error otherwise */
6295 ret = pm_runtime_set_active(hba->dev);
6297 * If wlun device had runtime error, we also need to resume those
6298 * consumer scsi devices in case any of them has failed to be
6299 * resumed due to supplier runtime resume failure. This is to unblock
6300 * blk_queue_enter in case there are bios waiting inside it.
6303 shost_for_each_device(sdev, shost) {
6304 q = sdev->request_queue;
6305 if (q->dev && (q->rpm_status == RPM_SUSPENDED ||
6306 q->rpm_status == RPM_SUSPENDING))
6307 pm_request_resume(q->dev);
6312 static inline void ufshcd_recover_pm_error(struct ufs_hba *hba)
6317 static bool ufshcd_is_pwr_mode_restore_needed(struct ufs_hba *hba)
6319 struct ufs_pa_layer_attr *pwr_info = &hba->pwr_info;
6322 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_PWRMODE), &mode);
6324 if (pwr_info->pwr_rx != ((mode >> PWRMODE_RX_OFFSET) & PWRMODE_MASK))
6327 if (pwr_info->pwr_tx != (mode & PWRMODE_MASK))
6333 static bool ufshcd_abort_all(struct ufs_hba *hba)
6335 bool needs_reset = false;
6338 /* Clear pending transfer requests */
6339 for_each_set_bit(tag, &hba->outstanding_reqs, hba->nutrs) {
6340 ret = ufshcd_try_to_abort_task(hba, tag);
6341 dev_err(hba->dev, "Aborting tag %d / CDB %#02x %s\n", tag,
6342 hba->lrb[tag].cmd ? hba->lrb[tag].cmd->cmnd[0] : -1,
6343 ret ? "failed" : "succeeded");
6350 /* Clear pending task management requests */
6351 for_each_set_bit(tag, &hba->outstanding_tasks, hba->nutmrs) {
6352 if (ufshcd_clear_tm_cmd(hba, tag)) {
6359 /* Complete the requests that are cleared by s/w */
6360 ufshcd_complete_requests(hba);
6366 * ufshcd_err_handler - handle UFS errors that require s/w attention
6367 * @work: pointer to work structure
6369 static void ufshcd_err_handler(struct work_struct *work)
6371 int retries = MAX_ERR_HANDLER_RETRIES;
6372 struct ufs_hba *hba;
6373 unsigned long flags;
6378 hba = container_of(work, struct ufs_hba, eh_work);
6381 "%s started; HBA state %s; powered %d; shutting down %d; saved_err = %d; saved_uic_err = %d; force_reset = %d%s\n",
6382 __func__, ufshcd_state_name[hba->ufshcd_state],
6383 hba->is_powered, hba->shutting_down, hba->saved_err,
6384 hba->saved_uic_err, hba->force_reset,
6385 ufshcd_is_link_broken(hba) ? "; link is broken" : "");
6387 down(&hba->host_sem);
6388 spin_lock_irqsave(hba->host->host_lock, flags);
6389 if (ufshcd_err_handling_should_stop(hba)) {
6390 if (hba->ufshcd_state != UFSHCD_STATE_ERROR)
6391 hba->ufshcd_state = UFSHCD_STATE_OPERATIONAL;
6392 spin_unlock_irqrestore(hba->host->host_lock, flags);
6396 ufshcd_set_eh_in_progress(hba);
6397 spin_unlock_irqrestore(hba->host->host_lock, flags);
6398 ufshcd_err_handling_prepare(hba);
6399 /* Complete requests that have door-bell cleared by h/w */
6400 ufshcd_complete_requests(hba);
6401 spin_lock_irqsave(hba->host->host_lock, flags);
6403 needs_restore = false;
6404 needs_reset = false;
6406 if (hba->ufshcd_state != UFSHCD_STATE_ERROR)
6407 hba->ufshcd_state = UFSHCD_STATE_RESET;
6409 * A full reset and restore might have happened after preparation
6410 * is finished, double check whether we should stop.
6412 if (ufshcd_err_handling_should_stop(hba))
6413 goto skip_err_handling;
6415 if (hba->dev_quirks & UFS_DEVICE_QUIRK_RECOVERY_FROM_DL_NAC_ERRORS) {
6418 spin_unlock_irqrestore(hba->host->host_lock, flags);
6419 /* release the lock as ufshcd_quirk_dl_nac_errors() may sleep */
6420 ret = ufshcd_quirk_dl_nac_errors(hba);
6421 spin_lock_irqsave(hba->host->host_lock, flags);
6422 if (!ret && ufshcd_err_handling_should_stop(hba))
6423 goto skip_err_handling;
6426 if ((hba->saved_err & (INT_FATAL_ERRORS | UFSHCD_UIC_HIBERN8_MASK)) ||
6427 (hba->saved_uic_err &&
6428 (hba->saved_uic_err != UFSHCD_UIC_PA_GENERIC_ERROR))) {
6429 bool pr_prdt = !!(hba->saved_err & SYSTEM_BUS_FATAL_ERROR);
6431 spin_unlock_irqrestore(hba->host->host_lock, flags);
6432 ufshcd_print_host_state(hba);
6433 ufshcd_print_pwr_info(hba);
6434 ufshcd_print_evt_hist(hba);
6435 ufshcd_print_tmrs(hba, hba->outstanding_tasks);
6436 ufshcd_print_trs_all(hba, pr_prdt);
6437 spin_lock_irqsave(hba->host->host_lock, flags);
6441 * if host reset is required then skip clearing the pending
6442 * transfers forcefully because they will get cleared during
6443 * host reset and restore
6445 if (hba->force_reset || ufshcd_is_link_broken(hba) ||
6446 ufshcd_is_saved_err_fatal(hba) ||
6447 ((hba->saved_err & UIC_ERROR) &&
6448 (hba->saved_uic_err & (UFSHCD_UIC_DL_NAC_RECEIVED_ERROR |
6449 UFSHCD_UIC_DL_TCx_REPLAY_ERROR)))) {
6455 * If LINERESET was caught, UFS might have been put to PWM mode,
6456 * check if power mode restore is needed.
6458 if (hba->saved_uic_err & UFSHCD_UIC_PA_GENERIC_ERROR) {
6459 hba->saved_uic_err &= ~UFSHCD_UIC_PA_GENERIC_ERROR;
6460 if (!hba->saved_uic_err)
6461 hba->saved_err &= ~UIC_ERROR;
6462 spin_unlock_irqrestore(hba->host->host_lock, flags);
6463 if (ufshcd_is_pwr_mode_restore_needed(hba))
6464 needs_restore = true;
6465 spin_lock_irqsave(hba->host->host_lock, flags);
6466 if (!hba->saved_err && !needs_restore)
6467 goto skip_err_handling;
6470 hba->silence_err_logs = true;
6471 /* release lock as clear command might sleep */
6472 spin_unlock_irqrestore(hba->host->host_lock, flags);
6474 needs_reset = ufshcd_abort_all(hba);
6476 spin_lock_irqsave(hba->host->host_lock, flags);
6477 hba->silence_err_logs = false;
6482 * After all reqs and tasks are cleared from doorbell,
6483 * now it is safe to retore power mode.
6485 if (needs_restore) {
6486 spin_unlock_irqrestore(hba->host->host_lock, flags);
6488 * Hold the scaling lock just in case dev cmds
6489 * are sent via bsg and/or sysfs.
6491 down_write(&hba->clk_scaling_lock);
6492 hba->force_pmc = true;
6493 pmc_err = ufshcd_config_pwr_mode(hba, &(hba->pwr_info));
6496 dev_err(hba->dev, "%s: Failed to restore power mode, err = %d\n",
6499 hba->force_pmc = false;
6500 ufshcd_print_pwr_info(hba);
6501 up_write(&hba->clk_scaling_lock);
6502 spin_lock_irqsave(hba->host->host_lock, flags);
6506 /* Fatal errors need reset */
6510 hba->force_reset = false;
6511 spin_unlock_irqrestore(hba->host->host_lock, flags);
6512 err = ufshcd_reset_and_restore(hba);
6514 dev_err(hba->dev, "%s: reset and restore failed with err %d\n",
6517 ufshcd_recover_pm_error(hba);
6518 spin_lock_irqsave(hba->host->host_lock, flags);
6523 if (hba->ufshcd_state == UFSHCD_STATE_RESET)
6524 hba->ufshcd_state = UFSHCD_STATE_OPERATIONAL;
6525 if (hba->saved_err || hba->saved_uic_err)
6526 dev_err_ratelimited(hba->dev, "%s: exit: saved_err 0x%x saved_uic_err 0x%x",
6527 __func__, hba->saved_err, hba->saved_uic_err);
6529 /* Exit in an operational state or dead */
6530 if (hba->ufshcd_state != UFSHCD_STATE_OPERATIONAL &&
6531 hba->ufshcd_state != UFSHCD_STATE_ERROR) {
6534 hba->ufshcd_state = UFSHCD_STATE_ERROR;
6536 ufshcd_clear_eh_in_progress(hba);
6537 spin_unlock_irqrestore(hba->host->host_lock, flags);
6538 ufshcd_err_handling_unprepare(hba);
6541 dev_info(hba->dev, "%s finished; HBA state %s\n", __func__,
6542 ufshcd_state_name[hba->ufshcd_state]);
6546 * ufshcd_update_uic_error - check and set fatal UIC error flags.
6547 * @hba: per-adapter instance
6550 * IRQ_HANDLED - If interrupt is valid
6551 * IRQ_NONE - If invalid interrupt
6553 static irqreturn_t ufshcd_update_uic_error(struct ufs_hba *hba)
6556 irqreturn_t retval = IRQ_NONE;
6558 /* PHY layer error */
6559 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_PHY_ADAPTER_LAYER);
6560 if ((reg & UIC_PHY_ADAPTER_LAYER_ERROR) &&
6561 (reg & UIC_PHY_ADAPTER_LAYER_ERROR_CODE_MASK)) {
6562 ufshcd_update_evt_hist(hba, UFS_EVT_PA_ERR, reg);
6564 * To know whether this error is fatal or not, DB timeout
6565 * must be checked but this error is handled separately.
6567 if (reg & UIC_PHY_ADAPTER_LAYER_LANE_ERR_MASK)
6568 dev_dbg(hba->dev, "%s: UIC Lane error reported\n",
6571 /* Got a LINERESET indication. */
6572 if (reg & UIC_PHY_ADAPTER_LAYER_GENERIC_ERROR) {
6573 struct uic_command *cmd = NULL;
6575 hba->uic_error |= UFSHCD_UIC_PA_GENERIC_ERROR;
6576 if (hba->uic_async_done && hba->active_uic_cmd)
6577 cmd = hba->active_uic_cmd;
6579 * Ignore the LINERESET during power mode change
6580 * operation via DME_SET command.
6582 if (cmd && (cmd->command == UIC_CMD_DME_SET))
6583 hba->uic_error &= ~UFSHCD_UIC_PA_GENERIC_ERROR;
6585 retval |= IRQ_HANDLED;
6588 /* PA_INIT_ERROR is fatal and needs UIC reset */
6589 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_DATA_LINK_LAYER);
6590 if ((reg & UIC_DATA_LINK_LAYER_ERROR) &&
6591 (reg & UIC_DATA_LINK_LAYER_ERROR_CODE_MASK)) {
6592 ufshcd_update_evt_hist(hba, UFS_EVT_DL_ERR, reg);
6594 if (reg & UIC_DATA_LINK_LAYER_ERROR_PA_INIT)
6595 hba->uic_error |= UFSHCD_UIC_DL_PA_INIT_ERROR;
6596 else if (hba->dev_quirks &
6597 UFS_DEVICE_QUIRK_RECOVERY_FROM_DL_NAC_ERRORS) {
6598 if (reg & UIC_DATA_LINK_LAYER_ERROR_NAC_RECEIVED)
6600 UFSHCD_UIC_DL_NAC_RECEIVED_ERROR;
6601 else if (reg & UIC_DATA_LINK_LAYER_ERROR_TCx_REPLAY_TIMEOUT)
6602 hba->uic_error |= UFSHCD_UIC_DL_TCx_REPLAY_ERROR;
6604 retval |= IRQ_HANDLED;
6607 /* UIC NL/TL/DME errors needs software retry */
6608 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_NETWORK_LAYER);
6609 if ((reg & UIC_NETWORK_LAYER_ERROR) &&
6610 (reg & UIC_NETWORK_LAYER_ERROR_CODE_MASK)) {
6611 ufshcd_update_evt_hist(hba, UFS_EVT_NL_ERR, reg);
6612 hba->uic_error |= UFSHCD_UIC_NL_ERROR;
6613 retval |= IRQ_HANDLED;
6616 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_TRANSPORT_LAYER);
6617 if ((reg & UIC_TRANSPORT_LAYER_ERROR) &&
6618 (reg & UIC_TRANSPORT_LAYER_ERROR_CODE_MASK)) {
6619 ufshcd_update_evt_hist(hba, UFS_EVT_TL_ERR, reg);
6620 hba->uic_error |= UFSHCD_UIC_TL_ERROR;
6621 retval |= IRQ_HANDLED;
6624 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_DME);
6625 if ((reg & UIC_DME_ERROR) &&
6626 (reg & UIC_DME_ERROR_CODE_MASK)) {
6627 ufshcd_update_evt_hist(hba, UFS_EVT_DME_ERR, reg);
6628 hba->uic_error |= UFSHCD_UIC_DME_ERROR;
6629 retval |= IRQ_HANDLED;
6632 dev_dbg(hba->dev, "%s: UIC error flags = 0x%08x\n",
6633 __func__, hba->uic_error);
6638 * ufshcd_check_errors - Check for errors that need s/w attention
6639 * @hba: per-adapter instance
6640 * @intr_status: interrupt status generated by the controller
6643 * IRQ_HANDLED - If interrupt is valid
6644 * IRQ_NONE - If invalid interrupt
6646 static irqreturn_t ufshcd_check_errors(struct ufs_hba *hba, u32 intr_status)
6648 bool queue_eh_work = false;
6649 irqreturn_t retval = IRQ_NONE;
6651 spin_lock(hba->host->host_lock);
6652 hba->errors |= UFSHCD_ERROR_MASK & intr_status;
6654 if (hba->errors & INT_FATAL_ERRORS) {
6655 ufshcd_update_evt_hist(hba, UFS_EVT_FATAL_ERR,
6657 queue_eh_work = true;
6660 if (hba->errors & UIC_ERROR) {
6662 retval = ufshcd_update_uic_error(hba);
6664 queue_eh_work = true;
6667 if (hba->errors & UFSHCD_UIC_HIBERN8_MASK) {
6669 "%s: Auto Hibern8 %s failed - status: 0x%08x, upmcrs: 0x%08x\n",
6670 __func__, (hba->errors & UIC_HIBERNATE_ENTER) ?
6672 hba->errors, ufshcd_get_upmcrs(hba));
6673 ufshcd_update_evt_hist(hba, UFS_EVT_AUTO_HIBERN8_ERR,
6675 ufshcd_set_link_broken(hba);
6676 queue_eh_work = true;
6679 if (queue_eh_work) {
6681 * update the transfer error masks to sticky bits, let's do this
6682 * irrespective of current ufshcd_state.
6684 hba->saved_err |= hba->errors;
6685 hba->saved_uic_err |= hba->uic_error;
6687 /* dump controller state before resetting */
6688 if ((hba->saved_err &
6689 (INT_FATAL_ERRORS | UFSHCD_UIC_HIBERN8_MASK)) ||
6690 (hba->saved_uic_err &&
6691 (hba->saved_uic_err != UFSHCD_UIC_PA_GENERIC_ERROR))) {
6692 dev_err(hba->dev, "%s: saved_err 0x%x saved_uic_err 0x%x\n",
6693 __func__, hba->saved_err,
6694 hba->saved_uic_err);
6695 ufshcd_dump_regs(hba, 0, UFSHCI_REG_SPACE_SIZE,
6697 ufshcd_print_pwr_info(hba);
6699 ufshcd_schedule_eh_work(hba);
6700 retval |= IRQ_HANDLED;
6703 * if (!queue_eh_work) -
6704 * Other errors are either non-fatal where host recovers
6705 * itself without s/w intervention or errors that will be
6706 * handled by the SCSI core layer.
6710 spin_unlock(hba->host->host_lock);
6715 * ufshcd_tmc_handler - handle task management function completion
6716 * @hba: per adapter instance
6719 * IRQ_HANDLED - If interrupt is valid
6720 * IRQ_NONE - If invalid interrupt
6722 static irqreturn_t ufshcd_tmc_handler(struct ufs_hba *hba)
6724 unsigned long flags, pending, issued;
6725 irqreturn_t ret = IRQ_NONE;
6728 spin_lock_irqsave(hba->host->host_lock, flags);
6729 pending = ufshcd_readl(hba, REG_UTP_TASK_REQ_DOOR_BELL);
6730 issued = hba->outstanding_tasks & ~pending;
6731 for_each_set_bit(tag, &issued, hba->nutmrs) {
6732 struct request *req = hba->tmf_rqs[tag];
6733 struct completion *c = req->end_io_data;
6738 spin_unlock_irqrestore(hba->host->host_lock, flags);
6744 * ufshcd_handle_mcq_cq_events - handle MCQ completion queue events
6745 * @hba: per adapter instance
6747 * Returns IRQ_HANDLED if interrupt is handled
6749 static irqreturn_t ufshcd_handle_mcq_cq_events(struct ufs_hba *hba)
6751 struct ufs_hw_queue *hwq;
6752 unsigned long outstanding_cqs;
6753 unsigned int nr_queues;
6757 ret = ufshcd_vops_get_outstanding_cqs(hba, &outstanding_cqs);
6759 outstanding_cqs = (1U << hba->nr_hw_queues) - 1;
6761 /* Exclude the poll queues */
6762 nr_queues = hba->nr_hw_queues - hba->nr_queues[HCTX_TYPE_POLL];
6763 for_each_set_bit(i, &outstanding_cqs, nr_queues) {
6766 events = ufshcd_mcq_read_cqis(hba, i);
6768 ufshcd_mcq_write_cqis(hba, events, i);
6770 if (events & UFSHCD_MCQ_CQIS_TAIL_ENT_PUSH_STS)
6771 ufshcd_mcq_poll_cqe_nolock(hba, hwq);
6778 * ufshcd_sl_intr - Interrupt service routine
6779 * @hba: per adapter instance
6780 * @intr_status: contains interrupts generated by the controller
6783 * IRQ_HANDLED - If interrupt is valid
6784 * IRQ_NONE - If invalid interrupt
6786 static irqreturn_t ufshcd_sl_intr(struct ufs_hba *hba, u32 intr_status)
6788 irqreturn_t retval = IRQ_NONE;
6790 if (intr_status & UFSHCD_UIC_MASK)
6791 retval |= ufshcd_uic_cmd_compl(hba, intr_status);
6793 if (intr_status & UFSHCD_ERROR_MASK || hba->errors)
6794 retval |= ufshcd_check_errors(hba, intr_status);
6796 if (intr_status & UTP_TASK_REQ_COMPL)
6797 retval |= ufshcd_tmc_handler(hba);
6799 if (intr_status & UTP_TRANSFER_REQ_COMPL)
6800 retval |= ufshcd_transfer_req_compl(hba);
6802 if (intr_status & MCQ_CQ_EVENT_STATUS)
6803 retval |= ufshcd_handle_mcq_cq_events(hba);
6809 * ufshcd_intr - Main interrupt service routine
6811 * @__hba: pointer to adapter instance
6814 * IRQ_HANDLED - If interrupt is valid
6815 * IRQ_NONE - If invalid interrupt
6817 static irqreturn_t ufshcd_intr(int irq, void *__hba)
6819 u32 intr_status, enabled_intr_status = 0;
6820 irqreturn_t retval = IRQ_NONE;
6821 struct ufs_hba *hba = __hba;
6822 int retries = hba->nutrs;
6824 intr_status = ufshcd_readl(hba, REG_INTERRUPT_STATUS);
6825 hba->ufs_stats.last_intr_status = intr_status;
6826 hba->ufs_stats.last_intr_ts = local_clock();
6829 * There could be max of hba->nutrs reqs in flight and in worst case
6830 * if the reqs get finished 1 by 1 after the interrupt status is
6831 * read, make sure we handle them by checking the interrupt status
6832 * again in a loop until we process all of the reqs before returning.
6834 while (intr_status && retries--) {
6835 enabled_intr_status =
6836 intr_status & ufshcd_readl(hba, REG_INTERRUPT_ENABLE);
6837 ufshcd_writel(hba, intr_status, REG_INTERRUPT_STATUS);
6838 if (enabled_intr_status)
6839 retval |= ufshcd_sl_intr(hba, enabled_intr_status);
6841 intr_status = ufshcd_readl(hba, REG_INTERRUPT_STATUS);
6844 if (enabled_intr_status && retval == IRQ_NONE &&
6845 (!(enabled_intr_status & UTP_TRANSFER_REQ_COMPL) ||
6846 hba->outstanding_reqs) && !ufshcd_eh_in_progress(hba)) {
6847 dev_err(hba->dev, "%s: Unhandled interrupt 0x%08x (0x%08x, 0x%08x)\n",
6850 hba->ufs_stats.last_intr_status,
6851 enabled_intr_status);
6852 ufshcd_dump_regs(hba, 0, UFSHCI_REG_SPACE_SIZE, "host_regs: ");
6858 static int ufshcd_clear_tm_cmd(struct ufs_hba *hba, int tag)
6861 u32 mask = 1 << tag;
6862 unsigned long flags;
6864 if (!test_bit(tag, &hba->outstanding_tasks))
6867 spin_lock_irqsave(hba->host->host_lock, flags);
6868 ufshcd_utmrl_clear(hba, tag);
6869 spin_unlock_irqrestore(hba->host->host_lock, flags);
6871 /* poll for max. 1 sec to clear door bell register by h/w */
6872 err = ufshcd_wait_for_register(hba,
6873 REG_UTP_TASK_REQ_DOOR_BELL,
6874 mask, 0, 1000, 1000);
6876 dev_err(hba->dev, "Clearing task management function with tag %d %s\n",
6877 tag, err ? "succeeded" : "failed");
6883 static int __ufshcd_issue_tm_cmd(struct ufs_hba *hba,
6884 struct utp_task_req_desc *treq, u8 tm_function)
6886 struct request_queue *q = hba->tmf_queue;
6887 struct Scsi_Host *host = hba->host;
6888 DECLARE_COMPLETION_ONSTACK(wait);
6889 struct request *req;
6890 unsigned long flags;
6894 * blk_mq_alloc_request() is used here only to get a free tag.
6896 req = blk_mq_alloc_request(q, REQ_OP_DRV_OUT, 0);
6898 return PTR_ERR(req);
6900 req->end_io_data = &wait;
6901 ufshcd_hold(hba, false);
6903 spin_lock_irqsave(host->host_lock, flags);
6905 task_tag = req->tag;
6906 WARN_ONCE(task_tag < 0 || task_tag >= hba->nutmrs, "Invalid tag %d\n",
6908 hba->tmf_rqs[req->tag] = req;
6909 treq->upiu_req.req_header.dword_0 |= cpu_to_be32(task_tag);
6911 memcpy(hba->utmrdl_base_addr + task_tag, treq, sizeof(*treq));
6912 ufshcd_vops_setup_task_mgmt(hba, task_tag, tm_function);
6914 /* send command to the controller */
6915 __set_bit(task_tag, &hba->outstanding_tasks);
6917 ufshcd_writel(hba, 1 << task_tag, REG_UTP_TASK_REQ_DOOR_BELL);
6918 /* Make sure that doorbell is committed immediately */
6921 spin_unlock_irqrestore(host->host_lock, flags);
6923 ufshcd_add_tm_upiu_trace(hba, task_tag, UFS_TM_SEND);
6925 /* wait until the task management command is completed */
6926 err = wait_for_completion_io_timeout(&wait,
6927 msecs_to_jiffies(TM_CMD_TIMEOUT));
6929 ufshcd_add_tm_upiu_trace(hba, task_tag, UFS_TM_ERR);
6930 dev_err(hba->dev, "%s: task management cmd 0x%.2x timed-out\n",
6931 __func__, tm_function);
6932 if (ufshcd_clear_tm_cmd(hba, task_tag))
6933 dev_WARN(hba->dev, "%s: unable to clear tm cmd (slot %d) after timeout\n",
6934 __func__, task_tag);
6938 memcpy(treq, hba->utmrdl_base_addr + task_tag, sizeof(*treq));
6940 ufshcd_add_tm_upiu_trace(hba, task_tag, UFS_TM_COMP);
6943 spin_lock_irqsave(hba->host->host_lock, flags);
6944 hba->tmf_rqs[req->tag] = NULL;
6945 __clear_bit(task_tag, &hba->outstanding_tasks);
6946 spin_unlock_irqrestore(hba->host->host_lock, flags);
6948 ufshcd_release(hba);
6949 blk_mq_free_request(req);
6955 * ufshcd_issue_tm_cmd - issues task management commands to controller
6956 * @hba: per adapter instance
6957 * @lun_id: LUN ID to which TM command is sent
6958 * @task_id: task ID to which the TM command is applicable
6959 * @tm_function: task management function opcode
6960 * @tm_response: task management service response return value
6962 * Returns non-zero value on error, zero on success.
6964 static int ufshcd_issue_tm_cmd(struct ufs_hba *hba, int lun_id, int task_id,
6965 u8 tm_function, u8 *tm_response)
6967 struct utp_task_req_desc treq = { { 0 }, };
6968 enum utp_ocs ocs_value;
6971 /* Configure task request descriptor */
6972 treq.header.dword_0 = cpu_to_le32(UTP_REQ_DESC_INT_CMD);
6973 treq.header.dword_2 = cpu_to_le32(OCS_INVALID_COMMAND_STATUS);
6975 /* Configure task request UPIU */
6976 treq.upiu_req.req_header.dword_0 = cpu_to_be32(lun_id << 8) |
6977 cpu_to_be32(UPIU_TRANSACTION_TASK_REQ << 24);
6978 treq.upiu_req.req_header.dword_1 = cpu_to_be32(tm_function << 16);
6981 * The host shall provide the same value for LUN field in the basic
6982 * header and for Input Parameter.
6984 treq.upiu_req.input_param1 = cpu_to_be32(lun_id);
6985 treq.upiu_req.input_param2 = cpu_to_be32(task_id);
6987 err = __ufshcd_issue_tm_cmd(hba, &treq, tm_function);
6988 if (err == -ETIMEDOUT)
6991 ocs_value = le32_to_cpu(treq.header.dword_2) & MASK_OCS;
6992 if (ocs_value != OCS_SUCCESS)
6993 dev_err(hba->dev, "%s: failed, ocs = 0x%x\n",
6994 __func__, ocs_value);
6995 else if (tm_response)
6996 *tm_response = be32_to_cpu(treq.upiu_rsp.output_param1) &
6997 MASK_TM_SERVICE_RESP;
7002 * ufshcd_issue_devman_upiu_cmd - API for sending "utrd" type requests
7003 * @hba: per-adapter instance
7004 * @req_upiu: upiu request
7005 * @rsp_upiu: upiu reply
7006 * @desc_buff: pointer to descriptor buffer, NULL if NA
7007 * @buff_len: descriptor size, 0 if NA
7008 * @cmd_type: specifies the type (NOP, Query...)
7009 * @desc_op: descriptor operation
7011 * Those type of requests uses UTP Transfer Request Descriptor - utrd.
7012 * Therefore, it "rides" the device management infrastructure: uses its tag and
7013 * tasks work queues.
7015 * Since there is only one available tag for device management commands,
7016 * the caller is expected to hold the hba->dev_cmd.lock mutex.
7018 static int ufshcd_issue_devman_upiu_cmd(struct ufs_hba *hba,
7019 struct utp_upiu_req *req_upiu,
7020 struct utp_upiu_req *rsp_upiu,
7021 u8 *desc_buff, int *buff_len,
7022 enum dev_cmd_type cmd_type,
7023 enum query_opcode desc_op)
7025 DECLARE_COMPLETION_ONSTACK(wait);
7026 const u32 tag = hba->reserved_slot;
7027 struct ufshcd_lrb *lrbp;
7031 /* Protects use of hba->reserved_slot. */
7032 lockdep_assert_held(&hba->dev_cmd.lock);
7034 down_read(&hba->clk_scaling_lock);
7036 lrbp = &hba->lrb[tag];
7038 lrbp->task_tag = tag;
7040 lrbp->intr_cmd = true;
7041 ufshcd_prepare_lrbp_crypto(NULL, lrbp);
7042 hba->dev_cmd.type = cmd_type;
7044 if (hba->ufs_version <= ufshci_version(1, 1))
7045 lrbp->command_type = UTP_CMD_TYPE_DEV_MANAGE;
7047 lrbp->command_type = UTP_CMD_TYPE_UFS_STORAGE;
7049 /* update the task tag in the request upiu */
7050 req_upiu->header.dword_0 |= cpu_to_be32(tag);
7052 ufshcd_prepare_req_desc_hdr(lrbp, &upiu_flags, DMA_NONE, 0);
7054 /* just copy the upiu request as it is */
7055 memcpy(lrbp->ucd_req_ptr, req_upiu, sizeof(*lrbp->ucd_req_ptr));
7056 if (desc_buff && desc_op == UPIU_QUERY_OPCODE_WRITE_DESC) {
7057 /* The Data Segment Area is optional depending upon the query
7058 * function value. for WRITE DESCRIPTOR, the data segment
7059 * follows right after the tsf.
7061 memcpy(lrbp->ucd_req_ptr + 1, desc_buff, *buff_len);
7065 memset(lrbp->ucd_rsp_ptr, 0, sizeof(struct utp_upiu_rsp));
7067 hba->dev_cmd.complete = &wait;
7069 ufshcd_add_query_upiu_trace(hba, UFS_QUERY_SEND, lrbp->ucd_req_ptr);
7071 ufshcd_send_command(hba, tag, hba->dev_cmd_queue);
7073 * ignore the returning value here - ufshcd_check_query_response is
7074 * bound to fail since dev_cmd.query and dev_cmd.type were left empty.
7075 * read the response directly ignoring all errors.
7077 ufshcd_wait_for_dev_cmd(hba, lrbp, QUERY_REQ_TIMEOUT);
7079 /* just copy the upiu response as it is */
7080 memcpy(rsp_upiu, lrbp->ucd_rsp_ptr, sizeof(*rsp_upiu));
7081 if (desc_buff && desc_op == UPIU_QUERY_OPCODE_READ_DESC) {
7082 u8 *descp = (u8 *)lrbp->ucd_rsp_ptr + sizeof(*rsp_upiu);
7083 u16 resp_len = be32_to_cpu(lrbp->ucd_rsp_ptr->header.dword_2) &
7084 MASK_QUERY_DATA_SEG_LEN;
7086 if (*buff_len >= resp_len) {
7087 memcpy(desc_buff, descp, resp_len);
7088 *buff_len = resp_len;
7091 "%s: rsp size %d is bigger than buffer size %d",
7092 __func__, resp_len, *buff_len);
7097 ufshcd_add_query_upiu_trace(hba, err ? UFS_QUERY_ERR : UFS_QUERY_COMP,
7098 (struct utp_upiu_req *)lrbp->ucd_rsp_ptr);
7100 up_read(&hba->clk_scaling_lock);
7105 * ufshcd_exec_raw_upiu_cmd - API function for sending raw upiu commands
7106 * @hba: per-adapter instance
7107 * @req_upiu: upiu request
7108 * @rsp_upiu: upiu reply - only 8 DW as we do not support scsi commands
7109 * @msgcode: message code, one of UPIU Transaction Codes Initiator to Target
7110 * @desc_buff: pointer to descriptor buffer, NULL if NA
7111 * @buff_len: descriptor size, 0 if NA
7112 * @desc_op: descriptor operation
7114 * Supports UTP Transfer requests (nop and query), and UTP Task
7115 * Management requests.
7116 * It is up to the caller to fill the upiu conent properly, as it will
7117 * be copied without any further input validations.
7119 int ufshcd_exec_raw_upiu_cmd(struct ufs_hba *hba,
7120 struct utp_upiu_req *req_upiu,
7121 struct utp_upiu_req *rsp_upiu,
7123 u8 *desc_buff, int *buff_len,
7124 enum query_opcode desc_op)
7127 enum dev_cmd_type cmd_type = DEV_CMD_TYPE_QUERY;
7128 struct utp_task_req_desc treq = { { 0 }, };
7129 enum utp_ocs ocs_value;
7130 u8 tm_f = be32_to_cpu(req_upiu->header.dword_1) >> 16 & MASK_TM_FUNC;
7133 case UPIU_TRANSACTION_NOP_OUT:
7134 cmd_type = DEV_CMD_TYPE_NOP;
7136 case UPIU_TRANSACTION_QUERY_REQ:
7137 ufshcd_hold(hba, false);
7138 mutex_lock(&hba->dev_cmd.lock);
7139 err = ufshcd_issue_devman_upiu_cmd(hba, req_upiu, rsp_upiu,
7140 desc_buff, buff_len,
7142 mutex_unlock(&hba->dev_cmd.lock);
7143 ufshcd_release(hba);
7146 case UPIU_TRANSACTION_TASK_REQ:
7147 treq.header.dword_0 = cpu_to_le32(UTP_REQ_DESC_INT_CMD);
7148 treq.header.dword_2 = cpu_to_le32(OCS_INVALID_COMMAND_STATUS);
7150 memcpy(&treq.upiu_req, req_upiu, sizeof(*req_upiu));
7152 err = __ufshcd_issue_tm_cmd(hba, &treq, tm_f);
7153 if (err == -ETIMEDOUT)
7156 ocs_value = le32_to_cpu(treq.header.dword_2) & MASK_OCS;
7157 if (ocs_value != OCS_SUCCESS) {
7158 dev_err(hba->dev, "%s: failed, ocs = 0x%x\n", __func__,
7163 memcpy(rsp_upiu, &treq.upiu_rsp, sizeof(*rsp_upiu));
7176 * ufshcd_advanced_rpmb_req_handler - handle advanced RPMB request
7177 * @hba: per adapter instance
7178 * @req_upiu: upiu request
7179 * @rsp_upiu: upiu reply
7180 * @req_ehs: EHS field which contains Advanced RPMB Request Message
7181 * @rsp_ehs: EHS field which returns Advanced RPMB Response Message
7182 * @sg_cnt: The number of sg lists actually used
7183 * @sg_list: Pointer to SG list when DATA IN/OUT UPIU is required in ARPMB operation
7184 * @dir: DMA direction
7186 * Returns zero on success, non-zero on failure
7188 int ufshcd_advanced_rpmb_req_handler(struct ufs_hba *hba, struct utp_upiu_req *req_upiu,
7189 struct utp_upiu_req *rsp_upiu, struct ufs_ehs *req_ehs,
7190 struct ufs_ehs *rsp_ehs, int sg_cnt, struct scatterlist *sg_list,
7191 enum dma_data_direction dir)
7193 DECLARE_COMPLETION_ONSTACK(wait);
7194 const u32 tag = hba->reserved_slot;
7195 struct ufshcd_lrb *lrbp;
7202 /* Protects use of hba->reserved_slot. */
7203 ufshcd_hold(hba, false);
7204 mutex_lock(&hba->dev_cmd.lock);
7205 down_read(&hba->clk_scaling_lock);
7207 lrbp = &hba->lrb[tag];
7209 lrbp->task_tag = tag;
7210 lrbp->lun = UFS_UPIU_RPMB_WLUN;
7212 lrbp->intr_cmd = true;
7213 ufshcd_prepare_lrbp_crypto(NULL, lrbp);
7214 hba->dev_cmd.type = DEV_CMD_TYPE_RPMB;
7216 /* Advanced RPMB starts from UFS 4.0, so its command type is UTP_CMD_TYPE_UFS_STORAGE */
7217 lrbp->command_type = UTP_CMD_TYPE_UFS_STORAGE;
7219 ufshcd_prepare_req_desc_hdr(lrbp, &upiu_flags, dir, 2);
7221 /* update the task tag and LUN in the request upiu */
7222 req_upiu->header.dword_0 |= cpu_to_be32(upiu_flags << 16 | UFS_UPIU_RPMB_WLUN << 8 | tag);
7224 /* copy the UPIU(contains CDB) request as it is */
7225 memcpy(lrbp->ucd_req_ptr, req_upiu, sizeof(*lrbp->ucd_req_ptr));
7226 /* Copy EHS, starting with byte32, immediately after the CDB package */
7227 memcpy(lrbp->ucd_req_ptr + 1, req_ehs, sizeof(*req_ehs));
7229 if (dir != DMA_NONE && sg_list)
7230 ufshcd_sgl_to_prdt(hba, lrbp, sg_cnt, sg_list);
7232 memset(lrbp->ucd_rsp_ptr, 0, sizeof(struct utp_upiu_rsp));
7234 hba->dev_cmd.complete = &wait;
7236 ufshcd_send_command(hba, tag, hba->dev_cmd_queue);
7238 err = ufshcd_wait_for_dev_cmd(hba, lrbp, ADVANCED_RPMB_REQ_TIMEOUT);
7241 /* Just copy the upiu response as it is */
7242 memcpy(rsp_upiu, lrbp->ucd_rsp_ptr, sizeof(*rsp_upiu));
7243 /* Get the response UPIU result */
7244 result = ufshcd_get_rsp_upiu_result(lrbp->ucd_rsp_ptr);
7246 ehs_len = be32_to_cpu(lrbp->ucd_rsp_ptr->header.dword_2) >> 24;
7248 * Since the bLength in EHS indicates the total size of the EHS Header and EHS Data
7249 * in 32 Byte units, the value of the bLength Request/Response for Advanced RPMB
7252 if (ehs_len == 2 && rsp_ehs) {
7254 * ucd_rsp_ptr points to a buffer with a length of 512 bytes
7255 * (ALIGNED_UPIU_SIZE = 512), and the EHS data just starts from byte32
7257 ehs_data = (u8 *)lrbp->ucd_rsp_ptr + EHS_OFFSET_IN_RESPONSE;
7258 memcpy(rsp_ehs, ehs_data, ehs_len * 32);
7262 up_read(&hba->clk_scaling_lock);
7263 mutex_unlock(&hba->dev_cmd.lock);
7264 ufshcd_release(hba);
7265 return err ? : result;
7269 * ufshcd_eh_device_reset_handler() - Reset a single logical unit.
7270 * @cmd: SCSI command pointer
7272 * Returns SUCCESS/FAILED
7274 static int ufshcd_eh_device_reset_handler(struct scsi_cmnd *cmd)
7276 unsigned long flags, pending_reqs = 0, not_cleared = 0;
7277 struct Scsi_Host *host;
7278 struct ufs_hba *hba;
7283 host = cmd->device->host;
7284 hba = shost_priv(host);
7286 lun = ufshcd_scsi_to_upiu_lun(cmd->device->lun);
7287 err = ufshcd_issue_tm_cmd(hba, lun, 0, UFS_LOGICAL_RESET, &resp);
7288 if (err || resp != UPIU_TASK_MANAGEMENT_FUNC_COMPL) {
7294 /* clear the commands that were pending for corresponding LUN */
7295 spin_lock_irqsave(&hba->outstanding_lock, flags);
7296 for_each_set_bit(pos, &hba->outstanding_reqs, hba->nutrs)
7297 if (hba->lrb[pos].lun == lun)
7298 __set_bit(pos, &pending_reqs);
7299 hba->outstanding_reqs &= ~pending_reqs;
7300 spin_unlock_irqrestore(&hba->outstanding_lock, flags);
7302 if (ufshcd_clear_cmds(hba, pending_reqs) < 0) {
7303 spin_lock_irqsave(&hba->outstanding_lock, flags);
7304 not_cleared = pending_reqs &
7305 ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
7306 hba->outstanding_reqs |= not_cleared;
7307 spin_unlock_irqrestore(&hba->outstanding_lock, flags);
7309 dev_err(hba->dev, "%s: failed to clear requests %#lx\n",
7310 __func__, not_cleared);
7312 __ufshcd_transfer_req_compl(hba, pending_reqs & ~not_cleared);
7315 hba->req_abort_count = 0;
7316 ufshcd_update_evt_hist(hba, UFS_EVT_DEV_RESET, (u32)err);
7320 dev_err(hba->dev, "%s: failed with err %d\n", __func__, err);
7326 static void ufshcd_set_req_abort_skip(struct ufs_hba *hba, unsigned long bitmap)
7328 struct ufshcd_lrb *lrbp;
7331 for_each_set_bit(tag, &bitmap, hba->nutrs) {
7332 lrbp = &hba->lrb[tag];
7333 lrbp->req_abort_skip = true;
7338 * ufshcd_try_to_abort_task - abort a specific task
7339 * @hba: Pointer to adapter instance
7340 * @tag: Task tag/index to be aborted
7342 * Abort the pending command in device by sending UFS_ABORT_TASK task management
7343 * command, and in host controller by clearing the door-bell register. There can
7344 * be race between controller sending the command to the device while abort is
7345 * issued. To avoid that, first issue UFS_QUERY_TASK to check if the command is
7346 * really issued and then try to abort it.
7348 * Returns zero on success, non-zero on failure
7350 static int ufshcd_try_to_abort_task(struct ufs_hba *hba, int tag)
7352 struct ufshcd_lrb *lrbp = &hba->lrb[tag];
7358 for (poll_cnt = 100; poll_cnt; poll_cnt--) {
7359 err = ufshcd_issue_tm_cmd(hba, lrbp->lun, lrbp->task_tag,
7360 UFS_QUERY_TASK, &resp);
7361 if (!err && resp == UPIU_TASK_MANAGEMENT_FUNC_SUCCEEDED) {
7362 /* cmd pending in the device */
7363 dev_err(hba->dev, "%s: cmd pending in the device. tag = %d\n",
7366 } else if (!err && resp == UPIU_TASK_MANAGEMENT_FUNC_COMPL) {
7368 * cmd not pending in the device, check if it is
7371 dev_err(hba->dev, "%s: cmd at tag %d not pending in the device.\n",
7373 reg = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
7374 if (reg & (1 << tag)) {
7375 /* sleep for max. 200us to stabilize */
7376 usleep_range(100, 200);
7379 /* command completed already */
7380 dev_err(hba->dev, "%s: cmd at tag %d successfully cleared from DB.\n",
7385 "%s: no response from device. tag = %d, err %d\n",
7386 __func__, tag, err);
7388 err = resp; /* service response error */
7398 err = ufshcd_issue_tm_cmd(hba, lrbp->lun, lrbp->task_tag,
7399 UFS_ABORT_TASK, &resp);
7400 if (err || resp != UPIU_TASK_MANAGEMENT_FUNC_COMPL) {
7402 err = resp; /* service response error */
7403 dev_err(hba->dev, "%s: issued. tag = %d, err %d\n",
7404 __func__, tag, err);
7409 err = ufshcd_clear_cmds(hba, 1U << tag);
7411 dev_err(hba->dev, "%s: Failed clearing cmd at tag %d, err %d\n",
7412 __func__, tag, err);
7419 * ufshcd_abort - scsi host template eh_abort_handler callback
7420 * @cmd: SCSI command pointer
7422 * Returns SUCCESS/FAILED
7424 static int ufshcd_abort(struct scsi_cmnd *cmd)
7426 struct Scsi_Host *host = cmd->device->host;
7427 struct ufs_hba *hba = shost_priv(host);
7428 int tag = scsi_cmd_to_rq(cmd)->tag;
7429 struct ufshcd_lrb *lrbp = &hba->lrb[tag];
7430 unsigned long flags;
7435 WARN_ONCE(tag < 0, "Invalid tag %d\n", tag);
7437 ufshcd_hold(hba, false);
7438 reg = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
7439 /* If command is already aborted/completed, return FAILED. */
7440 if (!(test_bit(tag, &hba->outstanding_reqs))) {
7442 "%s: cmd at tag %d already completed, outstanding=0x%lx, doorbell=0x%x\n",
7443 __func__, tag, hba->outstanding_reqs, reg);
7447 /* Print Transfer Request of aborted task */
7448 dev_info(hba->dev, "%s: Device abort task at tag %d\n", __func__, tag);
7451 * Print detailed info about aborted request.
7452 * As more than one request might get aborted at the same time,
7453 * print full information only for the first aborted request in order
7454 * to reduce repeated printouts. For other aborted requests only print
7457 scsi_print_command(cmd);
7458 if (!hba->req_abort_count) {
7459 ufshcd_update_evt_hist(hba, UFS_EVT_ABORT, tag);
7460 ufshcd_print_evt_hist(hba);
7461 ufshcd_print_host_state(hba);
7462 ufshcd_print_pwr_info(hba);
7463 ufshcd_print_tr(hba, tag, true);
7465 ufshcd_print_tr(hba, tag, false);
7467 hba->req_abort_count++;
7469 if (!(reg & (1 << tag))) {
7471 "%s: cmd was completed, but without a notifying intr, tag = %d",
7473 __ufshcd_transfer_req_compl(hba, 1UL << tag);
7478 * Task abort to the device W-LUN is illegal. When this command
7479 * will fail, due to spec violation, scsi err handling next step
7480 * will be to send LU reset which, again, is a spec violation.
7481 * To avoid these unnecessary/illegal steps, first we clean up
7482 * the lrb taken by this cmd and re-set it in outstanding_reqs,
7483 * then queue the eh_work and bail.
7485 if (lrbp->lun == UFS_UPIU_UFS_DEVICE_WLUN) {
7486 ufshcd_update_evt_hist(hba, UFS_EVT_ABORT, lrbp->lun);
7488 spin_lock_irqsave(host->host_lock, flags);
7489 hba->force_reset = true;
7490 ufshcd_schedule_eh_work(hba);
7491 spin_unlock_irqrestore(host->host_lock, flags);
7495 /* Skip task abort in case previous aborts failed and report failure */
7496 if (lrbp->req_abort_skip) {
7497 dev_err(hba->dev, "%s: skipping abort\n", __func__);
7498 ufshcd_set_req_abort_skip(hba, hba->outstanding_reqs);
7502 err = ufshcd_try_to_abort_task(hba, tag);
7504 dev_err(hba->dev, "%s: failed with err %d\n", __func__, err);
7505 ufshcd_set_req_abort_skip(hba, hba->outstanding_reqs);
7511 * Clear the corresponding bit from outstanding_reqs since the command
7512 * has been aborted successfully.
7514 spin_lock_irqsave(&hba->outstanding_lock, flags);
7515 outstanding = __test_and_clear_bit(tag, &hba->outstanding_reqs);
7516 spin_unlock_irqrestore(&hba->outstanding_lock, flags);
7519 ufshcd_release_scsi_cmd(hba, lrbp);
7524 /* Matches the ufshcd_hold() call at the start of this function. */
7525 ufshcd_release(hba);
7530 * ufshcd_host_reset_and_restore - reset and restore host controller
7531 * @hba: per-adapter instance
7533 * Note that host controller reset may issue DME_RESET to
7534 * local and remote (device) Uni-Pro stack and the attributes
7535 * are reset to default state.
7537 * Returns zero on success, non-zero on failure
7539 static int ufshcd_host_reset_and_restore(struct ufs_hba *hba)
7544 * Stop the host controller and complete the requests
7547 ufshpb_toggle_state(hba, HPB_PRESENT, HPB_RESET);
7548 ufshcd_hba_stop(hba);
7549 hba->silence_err_logs = true;
7550 ufshcd_complete_requests(hba);
7551 hba->silence_err_logs = false;
7553 /* scale up clocks to max frequency before full reinitialization */
7554 ufshcd_scale_clks(hba, true);
7556 err = ufshcd_hba_enable(hba);
7558 /* Establish the link again and restore the device */
7560 err = ufshcd_probe_hba(hba, false);
7563 dev_err(hba->dev, "%s: Host init failed %d\n", __func__, err);
7564 ufshcd_update_evt_hist(hba, UFS_EVT_HOST_RESET, (u32)err);
7569 * ufshcd_reset_and_restore - reset and re-initialize host/device
7570 * @hba: per-adapter instance
7572 * Reset and recover device, host and re-establish link. This
7573 * is helpful to recover the communication in fatal error conditions.
7575 * Returns zero on success, non-zero on failure
7577 static int ufshcd_reset_and_restore(struct ufs_hba *hba)
7580 u32 saved_uic_err = 0;
7582 unsigned long flags;
7583 int retries = MAX_HOST_RESET_RETRIES;
7585 spin_lock_irqsave(hba->host->host_lock, flags);
7588 * This is a fresh start, cache and clear saved error first,
7589 * in case new error generated during reset and restore.
7591 saved_err |= hba->saved_err;
7592 saved_uic_err |= hba->saved_uic_err;
7594 hba->saved_uic_err = 0;
7595 hba->force_reset = false;
7596 hba->ufshcd_state = UFSHCD_STATE_RESET;
7597 spin_unlock_irqrestore(hba->host->host_lock, flags);
7599 /* Reset the attached device */
7600 ufshcd_device_reset(hba);
7602 err = ufshcd_host_reset_and_restore(hba);
7604 spin_lock_irqsave(hba->host->host_lock, flags);
7607 /* Do not exit unless operational or dead */
7608 if (hba->ufshcd_state != UFSHCD_STATE_OPERATIONAL &&
7609 hba->ufshcd_state != UFSHCD_STATE_ERROR &&
7610 hba->ufshcd_state != UFSHCD_STATE_EH_SCHEDULED_NON_FATAL)
7612 } while (err && --retries);
7615 * Inform scsi mid-layer that we did reset and allow to handle
7616 * Unit Attention properly.
7618 scsi_report_bus_reset(hba->host, 0);
7620 hba->ufshcd_state = UFSHCD_STATE_ERROR;
7621 hba->saved_err |= saved_err;
7622 hba->saved_uic_err |= saved_uic_err;
7624 spin_unlock_irqrestore(hba->host->host_lock, flags);
7630 * ufshcd_eh_host_reset_handler - host reset handler registered to scsi layer
7631 * @cmd: SCSI command pointer
7633 * Returns SUCCESS/FAILED
7635 static int ufshcd_eh_host_reset_handler(struct scsi_cmnd *cmd)
7638 unsigned long flags;
7639 struct ufs_hba *hba;
7641 hba = shost_priv(cmd->device->host);
7643 spin_lock_irqsave(hba->host->host_lock, flags);
7644 hba->force_reset = true;
7645 ufshcd_schedule_eh_work(hba);
7646 dev_err(hba->dev, "%s: reset in progress - 1\n", __func__);
7647 spin_unlock_irqrestore(hba->host->host_lock, flags);
7649 flush_work(&hba->eh_work);
7651 spin_lock_irqsave(hba->host->host_lock, flags);
7652 if (hba->ufshcd_state == UFSHCD_STATE_ERROR)
7654 spin_unlock_irqrestore(hba->host->host_lock, flags);
7660 * ufshcd_get_max_icc_level - calculate the ICC level
7661 * @sup_curr_uA: max. current supported by the regulator
7662 * @start_scan: row at the desc table to start scan from
7663 * @buff: power descriptor buffer
7665 * Returns calculated max ICC level for specific regulator
7667 static u32 ufshcd_get_max_icc_level(int sup_curr_uA, u32 start_scan,
7675 for (i = start_scan; i >= 0; i--) {
7676 data = get_unaligned_be16(&buff[2 * i]);
7677 unit = (data & ATTR_ICC_LVL_UNIT_MASK) >>
7678 ATTR_ICC_LVL_UNIT_OFFSET;
7679 curr_uA = data & ATTR_ICC_LVL_VALUE_MASK;
7681 case UFSHCD_NANO_AMP:
7682 curr_uA = curr_uA / 1000;
7684 case UFSHCD_MILI_AMP:
7685 curr_uA = curr_uA * 1000;
7688 curr_uA = curr_uA * 1000 * 1000;
7690 case UFSHCD_MICRO_AMP:
7694 if (sup_curr_uA >= curr_uA)
7699 pr_err("%s: Couldn't find valid icc_level = %d", __func__, i);
7706 * ufshcd_find_max_sup_active_icc_level - calculate the max ICC level
7707 * In case regulators are not initialized we'll return 0
7708 * @hba: per-adapter instance
7709 * @desc_buf: power descriptor buffer to extract ICC levels from.
7711 * Returns calculated ICC level
7713 static u32 ufshcd_find_max_sup_active_icc_level(struct ufs_hba *hba,
7718 if (!hba->vreg_info.vcc || !hba->vreg_info.vccq ||
7719 !hba->vreg_info.vccq2) {
7721 * Using dev_dbg to avoid messages during runtime PM to avoid
7722 * never-ending cycles of messages written back to storage by
7723 * user space causing runtime resume, causing more messages and
7727 "%s: Regulator capability was not set, actvIccLevel=%d",
7728 __func__, icc_level);
7732 if (hba->vreg_info.vcc->max_uA)
7733 icc_level = ufshcd_get_max_icc_level(
7734 hba->vreg_info.vcc->max_uA,
7735 POWER_DESC_MAX_ACTV_ICC_LVLS - 1,
7736 &desc_buf[PWR_DESC_ACTIVE_LVLS_VCC_0]);
7738 if (hba->vreg_info.vccq->max_uA)
7739 icc_level = ufshcd_get_max_icc_level(
7740 hba->vreg_info.vccq->max_uA,
7742 &desc_buf[PWR_DESC_ACTIVE_LVLS_VCCQ_0]);
7744 if (hba->vreg_info.vccq2->max_uA)
7745 icc_level = ufshcd_get_max_icc_level(
7746 hba->vreg_info.vccq2->max_uA,
7748 &desc_buf[PWR_DESC_ACTIVE_LVLS_VCCQ2_0]);
7753 static void ufshcd_set_active_icc_lvl(struct ufs_hba *hba)
7759 desc_buf = kzalloc(QUERY_DESC_MAX_SIZE, GFP_KERNEL);
7763 ret = ufshcd_read_desc_param(hba, QUERY_DESC_IDN_POWER, 0, 0,
7764 desc_buf, QUERY_DESC_MAX_SIZE);
7767 "%s: Failed reading power descriptor ret = %d",
7772 icc_level = ufshcd_find_max_sup_active_icc_level(hba, desc_buf);
7773 dev_dbg(hba->dev, "%s: setting icc_level 0x%x", __func__, icc_level);
7775 ret = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_WRITE_ATTR,
7776 QUERY_ATTR_IDN_ACTIVE_ICC_LVL, 0, 0, &icc_level);
7780 "%s: Failed configuring bActiveICCLevel = %d ret = %d",
7781 __func__, icc_level, ret);
7787 static inline void ufshcd_blk_pm_runtime_init(struct scsi_device *sdev)
7789 scsi_autopm_get_device(sdev);
7790 blk_pm_runtime_init(sdev->request_queue, &sdev->sdev_gendev);
7791 if (sdev->rpm_autosuspend)
7792 pm_runtime_set_autosuspend_delay(&sdev->sdev_gendev,
7793 RPM_AUTOSUSPEND_DELAY_MS);
7794 scsi_autopm_put_device(sdev);
7798 * ufshcd_scsi_add_wlus - Adds required W-LUs
7799 * @hba: per-adapter instance
7801 * UFS device specification requires the UFS devices to support 4 well known
7803 * "REPORT_LUNS" (address: 01h)
7804 * "UFS Device" (address: 50h)
7805 * "RPMB" (address: 44h)
7806 * "BOOT" (address: 30h)
7807 * UFS device's power management needs to be controlled by "POWER CONDITION"
7808 * field of SSU (START STOP UNIT) command. But this "power condition" field
7809 * will take effect only when its sent to "UFS device" well known logical unit
7810 * hence we require the scsi_device instance to represent this logical unit in
7811 * order for the UFS host driver to send the SSU command for power management.
7813 * We also require the scsi_device instance for "RPMB" (Replay Protected Memory
7814 * Block) LU so user space process can control this LU. User space may also
7815 * want to have access to BOOT LU.
7817 * This function adds scsi device instances for each of all well known LUs
7818 * (except "REPORT LUNS" LU).
7820 * Returns zero on success (all required W-LUs are added successfully),
7821 * non-zero error value on failure (if failed to add any of the required W-LU).
7823 static int ufshcd_scsi_add_wlus(struct ufs_hba *hba)
7826 struct scsi_device *sdev_boot, *sdev_rpmb;
7828 hba->ufs_device_wlun = __scsi_add_device(hba->host, 0, 0,
7829 ufshcd_upiu_wlun_to_scsi_wlun(UFS_UPIU_UFS_DEVICE_WLUN), NULL);
7830 if (IS_ERR(hba->ufs_device_wlun)) {
7831 ret = PTR_ERR(hba->ufs_device_wlun);
7832 hba->ufs_device_wlun = NULL;
7835 scsi_device_put(hba->ufs_device_wlun);
7837 sdev_rpmb = __scsi_add_device(hba->host, 0, 0,
7838 ufshcd_upiu_wlun_to_scsi_wlun(UFS_UPIU_RPMB_WLUN), NULL);
7839 if (IS_ERR(sdev_rpmb)) {
7840 ret = PTR_ERR(sdev_rpmb);
7841 goto remove_ufs_device_wlun;
7843 ufshcd_blk_pm_runtime_init(sdev_rpmb);
7844 scsi_device_put(sdev_rpmb);
7846 sdev_boot = __scsi_add_device(hba->host, 0, 0,
7847 ufshcd_upiu_wlun_to_scsi_wlun(UFS_UPIU_BOOT_WLUN), NULL);
7848 if (IS_ERR(sdev_boot)) {
7849 dev_err(hba->dev, "%s: BOOT WLUN not found\n", __func__);
7851 ufshcd_blk_pm_runtime_init(sdev_boot);
7852 scsi_device_put(sdev_boot);
7856 remove_ufs_device_wlun:
7857 scsi_remove_device(hba->ufs_device_wlun);
7862 static void ufshcd_wb_probe(struct ufs_hba *hba, const u8 *desc_buf)
7864 struct ufs_dev_info *dev_info = &hba->dev_info;
7866 u32 d_lu_wb_buf_alloc;
7867 u32 ext_ufs_feature;
7869 if (!ufshcd_is_wb_allowed(hba))
7873 * Probe WB only for UFS-2.2 and UFS-3.1 (and later) devices or
7874 * UFS devices with quirk UFS_DEVICE_QUIRK_SUPPORT_EXTENDED_FEATURES
7877 if (!(dev_info->wspecversion >= 0x310 ||
7878 dev_info->wspecversion == 0x220 ||
7879 (hba->dev_quirks & UFS_DEVICE_QUIRK_SUPPORT_EXTENDED_FEATURES)))
7882 ext_ufs_feature = get_unaligned_be32(desc_buf +
7883 DEVICE_DESC_PARAM_EXT_UFS_FEATURE_SUP);
7885 if (!(ext_ufs_feature & UFS_DEV_WRITE_BOOSTER_SUP))
7889 * WB may be supported but not configured while provisioning. The spec
7890 * says, in dedicated wb buffer mode, a max of 1 lun would have wb
7891 * buffer configured.
7893 dev_info->wb_buffer_type = desc_buf[DEVICE_DESC_PARAM_WB_TYPE];
7895 dev_info->b_presrv_uspc_en =
7896 desc_buf[DEVICE_DESC_PARAM_WB_PRESRV_USRSPC_EN];
7898 if (dev_info->wb_buffer_type == WB_BUF_MODE_SHARED) {
7899 if (!get_unaligned_be32(desc_buf +
7900 DEVICE_DESC_PARAM_WB_SHARED_ALLOC_UNITS))
7903 for (lun = 0; lun < UFS_UPIU_MAX_WB_LUN_ID; lun++) {
7904 d_lu_wb_buf_alloc = 0;
7905 ufshcd_read_unit_desc_param(hba,
7907 UNIT_DESC_PARAM_WB_BUF_ALLOC_UNITS,
7908 (u8 *)&d_lu_wb_buf_alloc,
7909 sizeof(d_lu_wb_buf_alloc));
7910 if (d_lu_wb_buf_alloc) {
7911 dev_info->wb_dedicated_lu = lun;
7916 if (!d_lu_wb_buf_alloc)
7920 if (!ufshcd_is_wb_buf_lifetime_available(hba))
7926 hba->caps &= ~UFSHCD_CAP_WB_EN;
7929 static void ufshcd_temp_notif_probe(struct ufs_hba *hba, const u8 *desc_buf)
7931 struct ufs_dev_info *dev_info = &hba->dev_info;
7932 u32 ext_ufs_feature;
7935 if (!(hba->caps & UFSHCD_CAP_TEMP_NOTIF) || dev_info->wspecversion < 0x300)
7938 ext_ufs_feature = get_unaligned_be32(desc_buf + DEVICE_DESC_PARAM_EXT_UFS_FEATURE_SUP);
7940 if (ext_ufs_feature & UFS_DEV_LOW_TEMP_NOTIF)
7941 mask |= MASK_EE_TOO_LOW_TEMP;
7943 if (ext_ufs_feature & UFS_DEV_HIGH_TEMP_NOTIF)
7944 mask |= MASK_EE_TOO_HIGH_TEMP;
7947 ufshcd_enable_ee(hba, mask);
7948 ufs_hwmon_probe(hba, mask);
7952 static void ufshcd_ext_iid_probe(struct ufs_hba *hba, u8 *desc_buf)
7954 struct ufs_dev_info *dev_info = &hba->dev_info;
7955 u32 ext_ufs_feature;
7959 /* Only UFS-4.0 and above may support EXT_IID */
7960 if (dev_info->wspecversion < 0x400)
7963 ext_ufs_feature = get_unaligned_be32(desc_buf +
7964 DEVICE_DESC_PARAM_EXT_UFS_FEATURE_SUP);
7965 if (!(ext_ufs_feature & UFS_DEV_EXT_IID_SUP))
7968 err = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
7969 QUERY_ATTR_IDN_EXT_IID_EN, 0, 0, &ext_iid_en);
7971 dev_err(hba->dev, "failed reading bEXTIIDEn. err = %d\n", err);
7974 dev_info->b_ext_iid_en = ext_iid_en;
7977 void ufshcd_fixup_dev_quirks(struct ufs_hba *hba,
7978 const struct ufs_dev_quirk *fixups)
7980 const struct ufs_dev_quirk *f;
7981 struct ufs_dev_info *dev_info = &hba->dev_info;
7986 for (f = fixups; f->quirk; f++) {
7987 if ((f->wmanufacturerid == dev_info->wmanufacturerid ||
7988 f->wmanufacturerid == UFS_ANY_VENDOR) &&
7989 ((dev_info->model &&
7990 STR_PRFX_EQUAL(f->model, dev_info->model)) ||
7991 !strcmp(f->model, UFS_ANY_MODEL)))
7992 hba->dev_quirks |= f->quirk;
7995 EXPORT_SYMBOL_GPL(ufshcd_fixup_dev_quirks);
7997 static void ufs_fixup_device_setup(struct ufs_hba *hba)
7999 /* fix by general quirk table */
8000 ufshcd_fixup_dev_quirks(hba, ufs_fixups);
8002 /* allow vendors to fix quirks */
8003 ufshcd_vops_fixup_dev_quirks(hba);
8006 static int ufs_get_device_desc(struct ufs_hba *hba)
8010 u8 b_ufs_feature_sup;
8012 struct ufs_dev_info *dev_info = &hba->dev_info;
8014 desc_buf = kzalloc(QUERY_DESC_MAX_SIZE, GFP_KERNEL);
8020 err = ufshcd_read_desc_param(hba, QUERY_DESC_IDN_DEVICE, 0, 0, desc_buf,
8021 QUERY_DESC_MAX_SIZE);
8023 dev_err(hba->dev, "%s: Failed reading Device Desc. err = %d\n",
8029 * getting vendor (manufacturerID) and Bank Index in big endian
8032 dev_info->wmanufacturerid = desc_buf[DEVICE_DESC_PARAM_MANF_ID] << 8 |
8033 desc_buf[DEVICE_DESC_PARAM_MANF_ID + 1];
8035 /* getting Specification Version in big endian format */
8036 dev_info->wspecversion = desc_buf[DEVICE_DESC_PARAM_SPEC_VER] << 8 |
8037 desc_buf[DEVICE_DESC_PARAM_SPEC_VER + 1];
8038 dev_info->bqueuedepth = desc_buf[DEVICE_DESC_PARAM_Q_DPTH];
8039 b_ufs_feature_sup = desc_buf[DEVICE_DESC_PARAM_UFS_FEAT];
8041 model_index = desc_buf[DEVICE_DESC_PARAM_PRDCT_NAME];
8043 if (dev_info->wspecversion >= UFS_DEV_HPB_SUPPORT_VERSION &&
8044 (b_ufs_feature_sup & UFS_DEV_HPB_SUPPORT)) {
8045 bool hpb_en = false;
8047 ufshpb_get_dev_info(hba, desc_buf);
8049 if (!ufshpb_is_legacy(hba))
8050 err = ufshcd_query_flag_retry(hba,
8051 UPIU_QUERY_OPCODE_READ_FLAG,
8052 QUERY_FLAG_IDN_HPB_EN, 0,
8055 if (ufshpb_is_legacy(hba) || (!err && hpb_en))
8056 dev_info->hpb_enabled = true;
8059 err = ufshcd_read_string_desc(hba, model_index,
8060 &dev_info->model, SD_ASCII_STD);
8062 dev_err(hba->dev, "%s: Failed reading Product Name. err = %d\n",
8067 hba->luns_avail = desc_buf[DEVICE_DESC_PARAM_NUM_LU] +
8068 desc_buf[DEVICE_DESC_PARAM_NUM_WLU];
8070 ufs_fixup_device_setup(hba);
8072 ufshcd_wb_probe(hba, desc_buf);
8074 ufshcd_temp_notif_probe(hba, desc_buf);
8076 if (hba->ext_iid_sup)
8077 ufshcd_ext_iid_probe(hba, desc_buf);
8080 * ufshcd_read_string_desc returns size of the string
8081 * reset the error value
8090 static void ufs_put_device_desc(struct ufs_hba *hba)
8092 struct ufs_dev_info *dev_info = &hba->dev_info;
8094 kfree(dev_info->model);
8095 dev_info->model = NULL;
8099 * ufshcd_tune_pa_tactivate - Tunes PA_TActivate of local UniPro
8100 * @hba: per-adapter instance
8102 * PA_TActivate parameter can be tuned manually if UniPro version is less than
8103 * 1.61. PA_TActivate needs to be greater than or equal to peerM-PHY's
8104 * RX_MIN_ACTIVATETIME_CAPABILITY attribute. This optimal value can help reduce
8105 * the hibern8 exit latency.
8107 * Returns zero on success, non-zero error value on failure.
8109 static int ufshcd_tune_pa_tactivate(struct ufs_hba *hba)
8112 u32 peer_rx_min_activatetime = 0, tuned_pa_tactivate;
8114 ret = ufshcd_dme_peer_get(hba,
8116 RX_MIN_ACTIVATETIME_CAPABILITY,
8117 UIC_ARG_MPHY_RX_GEN_SEL_INDEX(0)),
8118 &peer_rx_min_activatetime);
8122 /* make sure proper unit conversion is applied */
8123 tuned_pa_tactivate =
8124 ((peer_rx_min_activatetime * RX_MIN_ACTIVATETIME_UNIT_US)
8125 / PA_TACTIVATE_TIME_UNIT_US);
8126 ret = ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TACTIVATE),
8127 tuned_pa_tactivate);
8134 * ufshcd_tune_pa_hibern8time - Tunes PA_Hibern8Time of local UniPro
8135 * @hba: per-adapter instance
8137 * PA_Hibern8Time parameter can be tuned manually if UniPro version is less than
8138 * 1.61. PA_Hibern8Time needs to be maximum of local M-PHY's
8139 * TX_HIBERN8TIME_CAPABILITY & peer M-PHY's RX_HIBERN8TIME_CAPABILITY.
8140 * This optimal value can help reduce the hibern8 exit latency.
8142 * Returns zero on success, non-zero error value on failure.
8144 static int ufshcd_tune_pa_hibern8time(struct ufs_hba *hba)
8147 u32 local_tx_hibern8_time_cap = 0, peer_rx_hibern8_time_cap = 0;
8148 u32 max_hibern8_time, tuned_pa_hibern8time;
8150 ret = ufshcd_dme_get(hba,
8151 UIC_ARG_MIB_SEL(TX_HIBERN8TIME_CAPABILITY,
8152 UIC_ARG_MPHY_TX_GEN_SEL_INDEX(0)),
8153 &local_tx_hibern8_time_cap);
8157 ret = ufshcd_dme_peer_get(hba,
8158 UIC_ARG_MIB_SEL(RX_HIBERN8TIME_CAPABILITY,
8159 UIC_ARG_MPHY_RX_GEN_SEL_INDEX(0)),
8160 &peer_rx_hibern8_time_cap);
8164 max_hibern8_time = max(local_tx_hibern8_time_cap,
8165 peer_rx_hibern8_time_cap);
8166 /* make sure proper unit conversion is applied */
8167 tuned_pa_hibern8time = ((max_hibern8_time * HIBERN8TIME_UNIT_US)
8168 / PA_HIBERN8_TIME_UNIT_US);
8169 ret = ufshcd_dme_set(hba, UIC_ARG_MIB(PA_HIBERN8TIME),
8170 tuned_pa_hibern8time);
8176 * ufshcd_quirk_tune_host_pa_tactivate - Ensures that host PA_TACTIVATE is
8177 * less than device PA_TACTIVATE time.
8178 * @hba: per-adapter instance
8180 * Some UFS devices require host PA_TACTIVATE to be lower than device
8181 * PA_TACTIVATE, we need to enable UFS_DEVICE_QUIRK_HOST_PA_TACTIVATE quirk
8184 * Returns zero on success, non-zero error value on failure.
8186 static int ufshcd_quirk_tune_host_pa_tactivate(struct ufs_hba *hba)
8189 u32 granularity, peer_granularity;
8190 u32 pa_tactivate, peer_pa_tactivate;
8191 u32 pa_tactivate_us, peer_pa_tactivate_us;
8192 static const u8 gran_to_us_table[] = {1, 4, 8, 16, 32, 100};
8194 ret = ufshcd_dme_get(hba, UIC_ARG_MIB(PA_GRANULARITY),
8199 ret = ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_GRANULARITY),
8204 if ((granularity < PA_GRANULARITY_MIN_VAL) ||
8205 (granularity > PA_GRANULARITY_MAX_VAL)) {
8206 dev_err(hba->dev, "%s: invalid host PA_GRANULARITY %d",
8207 __func__, granularity);
8211 if ((peer_granularity < PA_GRANULARITY_MIN_VAL) ||
8212 (peer_granularity > PA_GRANULARITY_MAX_VAL)) {
8213 dev_err(hba->dev, "%s: invalid device PA_GRANULARITY %d",
8214 __func__, peer_granularity);
8218 ret = ufshcd_dme_get(hba, UIC_ARG_MIB(PA_TACTIVATE), &pa_tactivate);
8222 ret = ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_TACTIVATE),
8223 &peer_pa_tactivate);
8227 pa_tactivate_us = pa_tactivate * gran_to_us_table[granularity - 1];
8228 peer_pa_tactivate_us = peer_pa_tactivate *
8229 gran_to_us_table[peer_granularity - 1];
8231 if (pa_tactivate_us >= peer_pa_tactivate_us) {
8232 u32 new_peer_pa_tactivate;
8234 new_peer_pa_tactivate = pa_tactivate_us /
8235 gran_to_us_table[peer_granularity - 1];
8236 new_peer_pa_tactivate++;
8237 ret = ufshcd_dme_peer_set(hba, UIC_ARG_MIB(PA_TACTIVATE),
8238 new_peer_pa_tactivate);
8245 static void ufshcd_tune_unipro_params(struct ufs_hba *hba)
8247 if (ufshcd_is_unipro_pa_params_tuning_req(hba)) {
8248 ufshcd_tune_pa_tactivate(hba);
8249 ufshcd_tune_pa_hibern8time(hba);
8252 ufshcd_vops_apply_dev_quirks(hba);
8254 if (hba->dev_quirks & UFS_DEVICE_QUIRK_PA_TACTIVATE)
8255 /* set 1ms timeout for PA_TACTIVATE */
8256 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TACTIVATE), 10);
8258 if (hba->dev_quirks & UFS_DEVICE_QUIRK_HOST_PA_TACTIVATE)
8259 ufshcd_quirk_tune_host_pa_tactivate(hba);
8262 static void ufshcd_clear_dbg_ufs_stats(struct ufs_hba *hba)
8264 hba->ufs_stats.hibern8_exit_cnt = 0;
8265 hba->ufs_stats.last_hibern8_exit_tstamp = ktime_set(0, 0);
8266 hba->req_abort_count = 0;
8269 static int ufshcd_device_geo_params_init(struct ufs_hba *hba)
8274 desc_buf = kzalloc(QUERY_DESC_MAX_SIZE, GFP_KERNEL);
8280 err = ufshcd_read_desc_param(hba, QUERY_DESC_IDN_GEOMETRY, 0, 0,
8281 desc_buf, QUERY_DESC_MAX_SIZE);
8283 dev_err(hba->dev, "%s: Failed reading Geometry Desc. err = %d\n",
8288 if (desc_buf[GEOMETRY_DESC_PARAM_MAX_NUM_LUN] == 1)
8289 hba->dev_info.max_lu_supported = 32;
8290 else if (desc_buf[GEOMETRY_DESC_PARAM_MAX_NUM_LUN] == 0)
8291 hba->dev_info.max_lu_supported = 8;
8293 if (desc_buf[QUERY_DESC_LENGTH_OFFSET] >=
8294 GEOMETRY_DESC_PARAM_HPB_MAX_ACTIVE_REGS)
8295 ufshpb_get_geo_info(hba, desc_buf);
8302 struct ufs_ref_clk {
8303 unsigned long freq_hz;
8304 enum ufs_ref_clk_freq val;
8307 static const struct ufs_ref_clk ufs_ref_clk_freqs[] = {
8308 {19200000, REF_CLK_FREQ_19_2_MHZ},
8309 {26000000, REF_CLK_FREQ_26_MHZ},
8310 {38400000, REF_CLK_FREQ_38_4_MHZ},
8311 {52000000, REF_CLK_FREQ_52_MHZ},
8312 {0, REF_CLK_FREQ_INVAL},
8315 static enum ufs_ref_clk_freq
8316 ufs_get_bref_clk_from_hz(unsigned long freq)
8320 for (i = 0; ufs_ref_clk_freqs[i].freq_hz; i++)
8321 if (ufs_ref_clk_freqs[i].freq_hz == freq)
8322 return ufs_ref_clk_freqs[i].val;
8324 return REF_CLK_FREQ_INVAL;
8327 void ufshcd_parse_dev_ref_clk_freq(struct ufs_hba *hba, struct clk *refclk)
8331 freq = clk_get_rate(refclk);
8333 hba->dev_ref_clk_freq =
8334 ufs_get_bref_clk_from_hz(freq);
8336 if (hba->dev_ref_clk_freq == REF_CLK_FREQ_INVAL)
8338 "invalid ref_clk setting = %ld\n", freq);
8341 static int ufshcd_set_dev_ref_clk(struct ufs_hba *hba)
8345 u32 freq = hba->dev_ref_clk_freq;
8347 err = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
8348 QUERY_ATTR_IDN_REF_CLK_FREQ, 0, 0, &ref_clk);
8351 dev_err(hba->dev, "failed reading bRefClkFreq. err = %d\n",
8356 if (ref_clk == freq)
8357 goto out; /* nothing to update */
8359 err = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_WRITE_ATTR,
8360 QUERY_ATTR_IDN_REF_CLK_FREQ, 0, 0, &freq);
8363 dev_err(hba->dev, "bRefClkFreq setting to %lu Hz failed\n",
8364 ufs_ref_clk_freqs[freq].freq_hz);
8368 dev_dbg(hba->dev, "bRefClkFreq setting to %lu Hz succeeded\n",
8369 ufs_ref_clk_freqs[freq].freq_hz);
8375 static int ufshcd_device_params_init(struct ufs_hba *hba)
8380 /* Init UFS geometry descriptor related parameters */
8381 ret = ufshcd_device_geo_params_init(hba);
8385 /* Check and apply UFS device quirks */
8386 ret = ufs_get_device_desc(hba);
8388 dev_err(hba->dev, "%s: Failed getting device info. err = %d\n",
8393 ufshcd_get_ref_clk_gating_wait(hba);
8395 if (!ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_READ_FLAG,
8396 QUERY_FLAG_IDN_PWR_ON_WPE, 0, &flag))
8397 hba->dev_info.f_power_on_wp_en = flag;
8399 /* Probe maximum power mode co-supported by both UFS host and device */
8400 if (ufshcd_get_max_pwr_mode(hba))
8402 "%s: Failed getting max supported power mode\n",
8409 * ufshcd_add_lus - probe and add UFS logical units
8410 * @hba: per-adapter instance
8412 static int ufshcd_add_lus(struct ufs_hba *hba)
8416 /* Add required well known logical units to scsi mid layer */
8417 ret = ufshcd_scsi_add_wlus(hba);
8421 /* Initialize devfreq after UFS device is detected */
8422 if (ufshcd_is_clkscaling_supported(hba)) {
8423 memcpy(&hba->clk_scaling.saved_pwr_info,
8425 sizeof(struct ufs_pa_layer_attr));
8426 hba->clk_scaling.is_allowed = true;
8428 ret = ufshcd_devfreq_init(hba);
8432 hba->clk_scaling.is_enabled = true;
8433 ufshcd_init_clk_scaling_sysfs(hba);
8438 scsi_scan_host(hba->host);
8439 pm_runtime_put_sync(hba->dev);
8445 /* SDB - Single Doorbell */
8446 static void ufshcd_release_sdb_queue(struct ufs_hba *hba, int nutrs)
8448 size_t ucdl_size, utrdl_size;
8450 ucdl_size = sizeof(struct utp_transfer_cmd_desc) * nutrs;
8451 dmam_free_coherent(hba->dev, ucdl_size, hba->ucdl_base_addr,
8452 hba->ucdl_dma_addr);
8454 utrdl_size = sizeof(struct utp_transfer_req_desc) * nutrs;
8455 dmam_free_coherent(hba->dev, utrdl_size, hba->utrdl_base_addr,
8456 hba->utrdl_dma_addr);
8458 devm_kfree(hba->dev, hba->lrb);
8461 static int ufshcd_alloc_mcq(struct ufs_hba *hba)
8464 int old_nutrs = hba->nutrs;
8466 ret = ufshcd_mcq_decide_queue_depth(hba);
8471 ret = ufshcd_mcq_init(hba);
8476 * Previously allocated memory for nutrs may not be enough in MCQ mode.
8477 * Number of supported tags in MCQ mode may be larger than SDB mode.
8479 if (hba->nutrs != old_nutrs) {
8480 ufshcd_release_sdb_queue(hba, old_nutrs);
8481 ret = ufshcd_memory_alloc(hba);
8484 ufshcd_host_memory_configure(hba);
8487 ret = ufshcd_mcq_memory_alloc(hba);
8493 hba->nutrs = old_nutrs;
8497 static void ufshcd_config_mcq(struct ufs_hba *hba)
8501 ret = ufshcd_mcq_vops_config_esi(hba);
8502 dev_info(hba->dev, "ESI %sconfigured\n", ret ? "is not " : "");
8504 ufshcd_enable_intr(hba, UFSHCD_ENABLE_MCQ_INTRS);
8505 ufshcd_mcq_make_queues_operational(hba);
8506 ufshcd_mcq_config_mac(hba, hba->nutrs);
8508 hba->host->can_queue = hba->nutrs - UFSHCD_NUM_RESERVED;
8509 hba->reserved_slot = hba->nutrs - UFSHCD_NUM_RESERVED;
8511 /* Select MCQ mode */
8512 ufshcd_writel(hba, ufshcd_readl(hba, REG_UFS_MEM_CFG) | 0x1,
8514 hba->mcq_enabled = true;
8516 dev_info(hba->dev, "MCQ configured, nr_queues=%d, io_queues=%d, read_queue=%d, poll_queues=%d, queue_depth=%d\n",
8517 hba->nr_hw_queues, hba->nr_queues[HCTX_TYPE_DEFAULT],
8518 hba->nr_queues[HCTX_TYPE_READ], hba->nr_queues[HCTX_TYPE_POLL],
8522 static int ufshcd_device_init(struct ufs_hba *hba, bool init_dev_params)
8525 struct Scsi_Host *host = hba->host;
8527 hba->ufshcd_state = UFSHCD_STATE_RESET;
8529 ret = ufshcd_link_startup(hba);
8533 if (hba->quirks & UFSHCD_QUIRK_SKIP_PH_CONFIGURATION)
8536 /* Debug counters initialization */
8537 ufshcd_clear_dbg_ufs_stats(hba);
8539 /* UniPro link is active now */
8540 ufshcd_set_link_active(hba);
8542 /* Reconfigure MCQ upon reset */
8543 if (is_mcq_enabled(hba) && !init_dev_params)
8544 ufshcd_config_mcq(hba);
8546 /* Verify device initialization by sending NOP OUT UPIU */
8547 ret = ufshcd_verify_dev_init(hba);
8551 /* Initiate UFS initialization, and waiting until completion */
8552 ret = ufshcd_complete_dev_init(hba);
8557 * Initialize UFS device parameters used by driver, these
8558 * parameters are associated with UFS descriptors.
8560 if (init_dev_params) {
8561 ret = ufshcd_device_params_init(hba);
8564 if (is_mcq_supported(hba) && !hba->scsi_host_added) {
8565 ret = ufshcd_alloc_mcq(hba);
8567 ufshcd_config_mcq(hba);
8569 /* Continue with SDB mode */
8570 use_mcq_mode = false;
8571 dev_err(hba->dev, "MCQ mode is disabled, err=%d\n",
8574 ret = scsi_add_host(host, hba->dev);
8576 dev_err(hba->dev, "scsi_add_host failed\n");
8579 hba->scsi_host_added = true;
8580 } else if (is_mcq_supported(hba)) {
8581 /* UFSHCD_QUIRK_REINIT_AFTER_MAX_GEAR_SWITCH is set */
8582 ufshcd_config_mcq(hba);
8586 ufshcd_tune_unipro_params(hba);
8588 /* UFS device is also active now */
8589 ufshcd_set_ufs_dev_active(hba);
8590 ufshcd_force_reset_auto_bkops(hba);
8592 /* Gear up to HS gear if supported */
8593 if (hba->max_pwr_info.is_valid) {
8595 * Set the right value to bRefClkFreq before attempting to
8596 * switch to HS gears.
8598 if (hba->dev_ref_clk_freq != REF_CLK_FREQ_INVAL)
8599 ufshcd_set_dev_ref_clk(hba);
8600 ret = ufshcd_config_pwr_mode(hba, &hba->max_pwr_info.info);
8602 dev_err(hba->dev, "%s: Failed setting power mode, err = %d\n",
8612 * ufshcd_probe_hba - probe hba to detect device and initialize it
8613 * @hba: per-adapter instance
8614 * @init_dev_params: whether or not to call ufshcd_device_params_init().
8616 * Execute link-startup and verify device initialization
8618 static int ufshcd_probe_hba(struct ufs_hba *hba, bool init_dev_params)
8620 ktime_t start = ktime_get();
8621 unsigned long flags;
8624 ret = ufshcd_device_init(hba, init_dev_params);
8628 if (hba->quirks & UFSHCD_QUIRK_REINIT_AFTER_MAX_GEAR_SWITCH) {
8629 /* Reset the device and controller before doing reinit */
8630 ufshcd_device_reset(hba);
8631 ufshcd_hba_stop(hba);
8632 ufshcd_vops_reinit_notify(hba);
8633 ret = ufshcd_hba_enable(hba);
8635 dev_err(hba->dev, "Host controller enable failed\n");
8636 ufshcd_print_evt_hist(hba);
8637 ufshcd_print_host_state(hba);
8641 /* Reinit the device */
8642 ret = ufshcd_device_init(hba, init_dev_params);
8647 ufshcd_print_pwr_info(hba);
8650 * bActiveICCLevel is volatile for UFS device (as per latest v2.1 spec)
8651 * and for removable UFS card as well, hence always set the parameter.
8652 * Note: Error handler may issue the device reset hence resetting
8653 * bActiveICCLevel as well so it is always safe to set this here.
8655 ufshcd_set_active_icc_lvl(hba);
8657 /* Enable UFS Write Booster if supported */
8658 ufshcd_configure_wb(hba);
8660 if (hba->ee_usr_mask)
8661 ufshcd_write_ee_control(hba);
8662 /* Enable Auto-Hibernate if configured */
8663 ufshcd_auto_hibern8_enable(hba);
8665 ufshpb_toggle_state(hba, HPB_RESET, HPB_PRESENT);
8667 spin_lock_irqsave(hba->host->host_lock, flags);
8669 hba->ufshcd_state = UFSHCD_STATE_ERROR;
8670 else if (hba->ufshcd_state == UFSHCD_STATE_RESET)
8671 hba->ufshcd_state = UFSHCD_STATE_OPERATIONAL;
8672 spin_unlock_irqrestore(hba->host->host_lock, flags);
8674 trace_ufshcd_init(dev_name(hba->dev), ret,
8675 ktime_to_us(ktime_sub(ktime_get(), start)),
8676 hba->curr_dev_pwr_mode, hba->uic_link_state);
8681 * ufshcd_async_scan - asynchronous execution for probing hba
8682 * @data: data pointer to pass to this function
8683 * @cookie: cookie data
8685 static void ufshcd_async_scan(void *data, async_cookie_t cookie)
8687 struct ufs_hba *hba = (struct ufs_hba *)data;
8690 down(&hba->host_sem);
8691 /* Initialize hba, detect and initialize UFS device */
8692 ret = ufshcd_probe_hba(hba, true);
8697 /* Probe and add UFS logical units */
8698 ret = ufshcd_add_lus(hba);
8701 * If we failed to initialize the device or the device is not
8702 * present, turn off the power/clocks etc.
8705 pm_runtime_put_sync(hba->dev);
8706 ufshcd_hba_exit(hba);
8710 static enum scsi_timeout_action ufshcd_eh_timed_out(struct scsi_cmnd *scmd)
8712 struct ufs_hba *hba = shost_priv(scmd->device->host);
8714 if (!hba->system_suspending) {
8715 /* Activate the error handler in the SCSI core. */
8716 return SCSI_EH_NOT_HANDLED;
8720 * If we get here we know that no TMFs are outstanding and also that
8721 * the only pending command is a START STOP UNIT command. Handle the
8722 * timeout of that command directly to prevent a deadlock between
8723 * ufshcd_set_dev_pwr_mode() and ufshcd_err_handler().
8725 ufshcd_link_recovery(hba);
8726 dev_info(hba->dev, "%s() finished; outstanding_tasks = %#lx.\n",
8727 __func__, hba->outstanding_tasks);
8729 return hba->outstanding_reqs ? SCSI_EH_RESET_TIMER : SCSI_EH_DONE;
8732 static const struct attribute_group *ufshcd_driver_groups[] = {
8733 &ufs_sysfs_unit_descriptor_group,
8734 &ufs_sysfs_lun_attributes_group,
8735 #ifdef CONFIG_SCSI_UFS_HPB
8736 &ufs_sysfs_hpb_stat_group,
8737 &ufs_sysfs_hpb_param_group,
8742 static struct ufs_hba_variant_params ufs_hba_vps = {
8743 .hba_enable_delay_us = 1000,
8744 .wb_flush_threshold = UFS_WB_BUF_REMAIN_PERCENT(40),
8745 .devfreq_profile.polling_ms = 100,
8746 .devfreq_profile.target = ufshcd_devfreq_target,
8747 .devfreq_profile.get_dev_status = ufshcd_devfreq_get_dev_status,
8748 .ondemand_data.upthreshold = 70,
8749 .ondemand_data.downdifferential = 5,
8752 static const struct scsi_host_template ufshcd_driver_template = {
8753 .module = THIS_MODULE,
8755 .proc_name = UFSHCD,
8756 .map_queues = ufshcd_map_queues,
8757 .queuecommand = ufshcd_queuecommand,
8758 .mq_poll = ufshcd_poll,
8759 .slave_alloc = ufshcd_slave_alloc,
8760 .slave_configure = ufshcd_slave_configure,
8761 .slave_destroy = ufshcd_slave_destroy,
8762 .change_queue_depth = ufshcd_change_queue_depth,
8763 .eh_abort_handler = ufshcd_abort,
8764 .eh_device_reset_handler = ufshcd_eh_device_reset_handler,
8765 .eh_host_reset_handler = ufshcd_eh_host_reset_handler,
8766 .eh_timed_out = ufshcd_eh_timed_out,
8768 .sg_tablesize = SG_ALL,
8769 .cmd_per_lun = UFSHCD_CMD_PER_LUN,
8770 .can_queue = UFSHCD_CAN_QUEUE,
8771 .max_segment_size = PRDT_DATA_BYTE_COUNT_MAX,
8772 .max_sectors = (1 << 20) / SECTOR_SIZE, /* 1 MiB */
8773 .max_host_blocked = 1,
8774 .track_queue_depth = 1,
8775 .skip_settle_delay = 1,
8776 .sdev_groups = ufshcd_driver_groups,
8777 .rpm_autosuspend_delay = RPM_AUTOSUSPEND_DELAY_MS,
8780 static int ufshcd_config_vreg_load(struct device *dev, struct ufs_vreg *vreg,
8789 * "set_load" operation shall be required on those regulators
8790 * which specifically configured current limitation. Otherwise
8791 * zero max_uA may cause unexpected behavior when regulator is
8792 * enabled or set as high power mode.
8797 ret = regulator_set_load(vreg->reg, ua);
8799 dev_err(dev, "%s: %s set load (ua=%d) failed, err=%d\n",
8800 __func__, vreg->name, ua, ret);
8806 static inline int ufshcd_config_vreg_lpm(struct ufs_hba *hba,
8807 struct ufs_vreg *vreg)
8809 return ufshcd_config_vreg_load(hba->dev, vreg, UFS_VREG_LPM_LOAD_UA);
8812 static inline int ufshcd_config_vreg_hpm(struct ufs_hba *hba,
8813 struct ufs_vreg *vreg)
8818 return ufshcd_config_vreg_load(hba->dev, vreg, vreg->max_uA);
8821 static int ufshcd_config_vreg(struct device *dev,
8822 struct ufs_vreg *vreg, bool on)
8824 if (regulator_count_voltages(vreg->reg) <= 0)
8827 return ufshcd_config_vreg_load(dev, vreg, on ? vreg->max_uA : 0);
8830 static int ufshcd_enable_vreg(struct device *dev, struct ufs_vreg *vreg)
8834 if (!vreg || vreg->enabled)
8837 ret = ufshcd_config_vreg(dev, vreg, true);
8839 ret = regulator_enable(vreg->reg);
8842 vreg->enabled = true;
8844 dev_err(dev, "%s: %s enable failed, err=%d\n",
8845 __func__, vreg->name, ret);
8850 static int ufshcd_disable_vreg(struct device *dev, struct ufs_vreg *vreg)
8854 if (!vreg || !vreg->enabled || vreg->always_on)
8857 ret = regulator_disable(vreg->reg);
8860 /* ignore errors on applying disable config */
8861 ufshcd_config_vreg(dev, vreg, false);
8862 vreg->enabled = false;
8864 dev_err(dev, "%s: %s disable failed, err=%d\n",
8865 __func__, vreg->name, ret);
8871 static int ufshcd_setup_vreg(struct ufs_hba *hba, bool on)
8874 struct device *dev = hba->dev;
8875 struct ufs_vreg_info *info = &hba->vreg_info;
8877 ret = ufshcd_toggle_vreg(dev, info->vcc, on);
8881 ret = ufshcd_toggle_vreg(dev, info->vccq, on);
8885 ret = ufshcd_toggle_vreg(dev, info->vccq2, on);
8889 ufshcd_toggle_vreg(dev, info->vccq2, false);
8890 ufshcd_toggle_vreg(dev, info->vccq, false);
8891 ufshcd_toggle_vreg(dev, info->vcc, false);
8896 static int ufshcd_setup_hba_vreg(struct ufs_hba *hba, bool on)
8898 struct ufs_vreg_info *info = &hba->vreg_info;
8900 return ufshcd_toggle_vreg(hba->dev, info->vdd_hba, on);
8903 int ufshcd_get_vreg(struct device *dev, struct ufs_vreg *vreg)
8910 vreg->reg = devm_regulator_get(dev, vreg->name);
8911 if (IS_ERR(vreg->reg)) {
8912 ret = PTR_ERR(vreg->reg);
8913 dev_err(dev, "%s: %s get failed, err=%d\n",
8914 __func__, vreg->name, ret);
8919 EXPORT_SYMBOL_GPL(ufshcd_get_vreg);
8921 static int ufshcd_init_vreg(struct ufs_hba *hba)
8924 struct device *dev = hba->dev;
8925 struct ufs_vreg_info *info = &hba->vreg_info;
8927 ret = ufshcd_get_vreg(dev, info->vcc);
8931 ret = ufshcd_get_vreg(dev, info->vccq);
8933 ret = ufshcd_get_vreg(dev, info->vccq2);
8938 static int ufshcd_init_hba_vreg(struct ufs_hba *hba)
8940 struct ufs_vreg_info *info = &hba->vreg_info;
8942 return ufshcd_get_vreg(hba->dev, info->vdd_hba);
8945 static int ufshcd_setup_clocks(struct ufs_hba *hba, bool on)
8948 struct ufs_clk_info *clki;
8949 struct list_head *head = &hba->clk_list_head;
8950 unsigned long flags;
8951 ktime_t start = ktime_get();
8952 bool clk_state_changed = false;
8954 if (list_empty(head))
8957 ret = ufshcd_vops_setup_clocks(hba, on, PRE_CHANGE);
8961 list_for_each_entry(clki, head, list) {
8962 if (!IS_ERR_OR_NULL(clki->clk)) {
8964 * Don't disable clocks which are needed
8965 * to keep the link active.
8967 if (ufshcd_is_link_active(hba) &&
8968 clki->keep_link_active)
8971 clk_state_changed = on ^ clki->enabled;
8972 if (on && !clki->enabled) {
8973 ret = clk_prepare_enable(clki->clk);
8975 dev_err(hba->dev, "%s: %s prepare enable failed, %d\n",
8976 __func__, clki->name, ret);
8979 } else if (!on && clki->enabled) {
8980 clk_disable_unprepare(clki->clk);
8983 dev_dbg(hba->dev, "%s: clk: %s %sabled\n", __func__,
8984 clki->name, on ? "en" : "dis");
8988 ret = ufshcd_vops_setup_clocks(hba, on, POST_CHANGE);
8994 list_for_each_entry(clki, head, list) {
8995 if (!IS_ERR_OR_NULL(clki->clk) && clki->enabled)
8996 clk_disable_unprepare(clki->clk);
8998 } else if (!ret && on) {
8999 spin_lock_irqsave(hba->host->host_lock, flags);
9000 hba->clk_gating.state = CLKS_ON;
9001 trace_ufshcd_clk_gating(dev_name(hba->dev),
9002 hba->clk_gating.state);
9003 spin_unlock_irqrestore(hba->host->host_lock, flags);
9006 if (clk_state_changed)
9007 trace_ufshcd_profile_clk_gating(dev_name(hba->dev),
9008 (on ? "on" : "off"),
9009 ktime_to_us(ktime_sub(ktime_get(), start)), ret);
9013 static enum ufs_ref_clk_freq ufshcd_parse_ref_clk_property(struct ufs_hba *hba)
9016 int ret = device_property_read_u32(hba->dev, "ref-clk-freq", &freq);
9019 dev_dbg(hba->dev, "Cannot query 'ref-clk-freq' property = %d", ret);
9020 return REF_CLK_FREQ_INVAL;
9023 return ufs_get_bref_clk_from_hz(freq);
9026 static int ufshcd_init_clocks(struct ufs_hba *hba)
9029 struct ufs_clk_info *clki;
9030 struct device *dev = hba->dev;
9031 struct list_head *head = &hba->clk_list_head;
9033 if (list_empty(head))
9036 list_for_each_entry(clki, head, list) {
9040 clki->clk = devm_clk_get(dev, clki->name);
9041 if (IS_ERR(clki->clk)) {
9042 ret = PTR_ERR(clki->clk);
9043 dev_err(dev, "%s: %s clk get failed, %d\n",
9044 __func__, clki->name, ret);
9049 * Parse device ref clk freq as per device tree "ref_clk".
9050 * Default dev_ref_clk_freq is set to REF_CLK_FREQ_INVAL
9051 * in ufshcd_alloc_host().
9053 if (!strcmp(clki->name, "ref_clk"))
9054 ufshcd_parse_dev_ref_clk_freq(hba, clki->clk);
9056 if (clki->max_freq) {
9057 ret = clk_set_rate(clki->clk, clki->max_freq);
9059 dev_err(hba->dev, "%s: %s clk set rate(%dHz) failed, %d\n",
9060 __func__, clki->name,
9061 clki->max_freq, ret);
9064 clki->curr_freq = clki->max_freq;
9066 dev_dbg(dev, "%s: clk: %s, rate: %lu\n", __func__,
9067 clki->name, clk_get_rate(clki->clk));
9073 static int ufshcd_variant_hba_init(struct ufs_hba *hba)
9080 err = ufshcd_vops_init(hba);
9082 dev_err(hba->dev, "%s: variant %s init failed err %d\n",
9083 __func__, ufshcd_get_var_name(hba), err);
9088 static void ufshcd_variant_hba_exit(struct ufs_hba *hba)
9093 ufshcd_vops_exit(hba);
9096 static int ufshcd_hba_init(struct ufs_hba *hba)
9101 * Handle host controller power separately from the UFS device power
9102 * rails as it will help controlling the UFS host controller power
9103 * collapse easily which is different than UFS device power collapse.
9104 * Also, enable the host controller power before we go ahead with rest
9105 * of the initialization here.
9107 err = ufshcd_init_hba_vreg(hba);
9111 err = ufshcd_setup_hba_vreg(hba, true);
9115 err = ufshcd_init_clocks(hba);
9117 goto out_disable_hba_vreg;
9119 if (hba->dev_ref_clk_freq == REF_CLK_FREQ_INVAL)
9120 hba->dev_ref_clk_freq = ufshcd_parse_ref_clk_property(hba);
9122 err = ufshcd_setup_clocks(hba, true);
9124 goto out_disable_hba_vreg;
9126 err = ufshcd_init_vreg(hba);
9128 goto out_disable_clks;
9130 err = ufshcd_setup_vreg(hba, true);
9132 goto out_disable_clks;
9134 err = ufshcd_variant_hba_init(hba);
9136 goto out_disable_vreg;
9138 ufs_debugfs_hba_init(hba);
9140 hba->is_powered = true;
9144 ufshcd_setup_vreg(hba, false);
9146 ufshcd_setup_clocks(hba, false);
9147 out_disable_hba_vreg:
9148 ufshcd_setup_hba_vreg(hba, false);
9153 static void ufshcd_hba_exit(struct ufs_hba *hba)
9155 if (hba->is_powered) {
9156 ufshcd_exit_clk_scaling(hba);
9157 ufshcd_exit_clk_gating(hba);
9159 destroy_workqueue(hba->eh_wq);
9160 ufs_debugfs_hba_exit(hba);
9161 ufshcd_variant_hba_exit(hba);
9162 ufshcd_setup_vreg(hba, false);
9163 ufshcd_setup_clocks(hba, false);
9164 ufshcd_setup_hba_vreg(hba, false);
9165 hba->is_powered = false;
9166 ufs_put_device_desc(hba);
9170 static int ufshcd_execute_start_stop(struct scsi_device *sdev,
9171 enum ufs_dev_pwr_mode pwr_mode,
9172 struct scsi_sense_hdr *sshdr)
9174 const unsigned char cdb[6] = { START_STOP, 0, 0, 0, pwr_mode << 4, 0 };
9175 const struct scsi_exec_args args = {
9177 .req_flags = BLK_MQ_REQ_PM,
9178 .scmd_flags = SCMD_FAIL_IF_RECOVERING,
9181 return scsi_execute_cmd(sdev, cdb, REQ_OP_DRV_IN, /*buffer=*/NULL,
9182 /*bufflen=*/0, /*timeout=*/10 * HZ, /*retries=*/0,
9187 * ufshcd_set_dev_pwr_mode - sends START STOP UNIT command to set device
9189 * @hba: per adapter instance
9190 * @pwr_mode: device power mode to set
9192 * Returns 0 if requested power mode is set successfully
9193 * Returns < 0 if failed to set the requested power mode
9195 static int ufshcd_set_dev_pwr_mode(struct ufs_hba *hba,
9196 enum ufs_dev_pwr_mode pwr_mode)
9198 struct scsi_sense_hdr sshdr;
9199 struct scsi_device *sdp;
9200 unsigned long flags;
9203 spin_lock_irqsave(hba->host->host_lock, flags);
9204 sdp = hba->ufs_device_wlun;
9205 if (sdp && scsi_device_online(sdp))
9206 ret = scsi_device_get(sdp);
9209 spin_unlock_irqrestore(hba->host->host_lock, flags);
9215 * If scsi commands fail, the scsi mid-layer schedules scsi error-
9216 * handling, which would wait for host to be resumed. Since we know
9217 * we are functional while we are here, skip host resume in error
9220 hba->host->eh_noresume = 1;
9223 * Current function would be generally called from the power management
9224 * callbacks hence set the RQF_PM flag so that it doesn't resume the
9225 * already suspended childs.
9227 for (retries = 3; retries > 0; --retries) {
9228 ret = ufshcd_execute_start_stop(sdp, pwr_mode, &sshdr);
9230 * scsi_execute() only returns a negative value if the request
9237 sdev_printk(KERN_WARNING, sdp,
9238 "START_STOP failed for power mode: %d, result %x\n",
9241 if (scsi_sense_valid(&sshdr))
9242 scsi_print_sense_hdr(sdp, NULL, &sshdr);
9246 hba->curr_dev_pwr_mode = pwr_mode;
9249 scsi_device_put(sdp);
9250 hba->host->eh_noresume = 0;
9254 static int ufshcd_link_state_transition(struct ufs_hba *hba,
9255 enum uic_link_state req_link_state,
9256 bool check_for_bkops)
9260 if (req_link_state == hba->uic_link_state)
9263 if (req_link_state == UIC_LINK_HIBERN8_STATE) {
9264 ret = ufshcd_uic_hibern8_enter(hba);
9266 ufshcd_set_link_hibern8(hba);
9268 dev_err(hba->dev, "%s: hibern8 enter failed %d\n",
9274 * If autobkops is enabled, link can't be turned off because
9275 * turning off the link would also turn off the device, except in the
9276 * case of DeepSleep where the device is expected to remain powered.
9278 else if ((req_link_state == UIC_LINK_OFF_STATE) &&
9279 (!check_for_bkops || !hba->auto_bkops_enabled)) {
9281 * Let's make sure that link is in low power mode, we are doing
9282 * this currently by putting the link in Hibern8. Otherway to
9283 * put the link in low power mode is to send the DME end point
9284 * to device and then send the DME reset command to local
9285 * unipro. But putting the link in hibern8 is much faster.
9287 * Note also that putting the link in Hibern8 is a requirement
9288 * for entering DeepSleep.
9290 ret = ufshcd_uic_hibern8_enter(hba);
9292 dev_err(hba->dev, "%s: hibern8 enter failed %d\n",
9297 * Change controller state to "reset state" which
9298 * should also put the link in off/reset state
9300 ufshcd_hba_stop(hba);
9302 * TODO: Check if we need any delay to make sure that
9303 * controller is reset
9305 ufshcd_set_link_off(hba);
9312 static void ufshcd_vreg_set_lpm(struct ufs_hba *hba)
9314 bool vcc_off = false;
9317 * It seems some UFS devices may keep drawing more than sleep current
9318 * (atleast for 500us) from UFS rails (especially from VCCQ rail).
9319 * To avoid this situation, add 2ms delay before putting these UFS
9320 * rails in LPM mode.
9322 if (!ufshcd_is_link_active(hba) &&
9323 hba->dev_quirks & UFS_DEVICE_QUIRK_DELAY_BEFORE_LPM)
9324 usleep_range(2000, 2100);
9327 * If UFS device is either in UFS_Sleep turn off VCC rail to save some
9330 * If UFS device and link is in OFF state, all power supplies (VCC,
9331 * VCCQ, VCCQ2) can be turned off if power on write protect is not
9332 * required. If UFS link is inactive (Hibern8 or OFF state) and device
9333 * is in sleep state, put VCCQ & VCCQ2 rails in LPM mode.
9335 * Ignore the error returned by ufshcd_toggle_vreg() as device is anyway
9336 * in low power state which would save some power.
9338 * If Write Booster is enabled and the device needs to flush the WB
9339 * buffer OR if bkops status is urgent for WB, keep Vcc on.
9341 if (ufshcd_is_ufs_dev_poweroff(hba) && ufshcd_is_link_off(hba) &&
9342 !hba->dev_info.is_lu_power_on_wp) {
9343 ufshcd_setup_vreg(hba, false);
9345 } else if (!ufshcd_is_ufs_dev_active(hba)) {
9346 ufshcd_toggle_vreg(hba->dev, hba->vreg_info.vcc, false);
9348 if (ufshcd_is_link_hibern8(hba) || ufshcd_is_link_off(hba)) {
9349 ufshcd_config_vreg_lpm(hba, hba->vreg_info.vccq);
9350 ufshcd_config_vreg_lpm(hba, hba->vreg_info.vccq2);
9355 * Some UFS devices require delay after VCC power rail is turned-off.
9357 if (vcc_off && hba->vreg_info.vcc &&
9358 hba->dev_quirks & UFS_DEVICE_QUIRK_DELAY_AFTER_LPM)
9359 usleep_range(5000, 5100);
9363 static int ufshcd_vreg_set_hpm(struct ufs_hba *hba)
9367 if (ufshcd_is_ufs_dev_poweroff(hba) && ufshcd_is_link_off(hba) &&
9368 !hba->dev_info.is_lu_power_on_wp) {
9369 ret = ufshcd_setup_vreg(hba, true);
9370 } else if (!ufshcd_is_ufs_dev_active(hba)) {
9371 if (!ufshcd_is_link_active(hba)) {
9372 ret = ufshcd_config_vreg_hpm(hba, hba->vreg_info.vccq);
9375 ret = ufshcd_config_vreg_hpm(hba, hba->vreg_info.vccq2);
9379 ret = ufshcd_toggle_vreg(hba->dev, hba->vreg_info.vcc, true);
9384 ufshcd_config_vreg_lpm(hba, hba->vreg_info.vccq);
9386 ufshcd_toggle_vreg(hba->dev, hba->vreg_info.vcc, false);
9390 #endif /* CONFIG_PM */
9392 static void ufshcd_hba_vreg_set_lpm(struct ufs_hba *hba)
9394 if (ufshcd_is_link_off(hba) || ufshcd_can_aggressive_pc(hba))
9395 ufshcd_setup_hba_vreg(hba, false);
9398 static void ufshcd_hba_vreg_set_hpm(struct ufs_hba *hba)
9400 if (ufshcd_is_link_off(hba) || ufshcd_can_aggressive_pc(hba))
9401 ufshcd_setup_hba_vreg(hba, true);
9404 static int __ufshcd_wl_suspend(struct ufs_hba *hba, enum ufs_pm_op pm_op)
9407 bool check_for_bkops;
9408 enum ufs_pm_level pm_lvl;
9409 enum ufs_dev_pwr_mode req_dev_pwr_mode;
9410 enum uic_link_state req_link_state;
9412 hba->pm_op_in_progress = true;
9413 if (pm_op != UFS_SHUTDOWN_PM) {
9414 pm_lvl = pm_op == UFS_RUNTIME_PM ?
9415 hba->rpm_lvl : hba->spm_lvl;
9416 req_dev_pwr_mode = ufs_get_pm_lvl_to_dev_pwr_mode(pm_lvl);
9417 req_link_state = ufs_get_pm_lvl_to_link_pwr_state(pm_lvl);
9419 req_dev_pwr_mode = UFS_POWERDOWN_PWR_MODE;
9420 req_link_state = UIC_LINK_OFF_STATE;
9423 ufshpb_suspend(hba);
9426 * If we can't transition into any of the low power modes
9427 * just gate the clocks.
9429 ufshcd_hold(hba, false);
9430 hba->clk_gating.is_suspended = true;
9432 if (ufshcd_is_clkscaling_supported(hba))
9433 ufshcd_clk_scaling_suspend(hba, true);
9435 if (req_dev_pwr_mode == UFS_ACTIVE_PWR_MODE &&
9436 req_link_state == UIC_LINK_ACTIVE_STATE) {
9440 if ((req_dev_pwr_mode == hba->curr_dev_pwr_mode) &&
9441 (req_link_state == hba->uic_link_state))
9442 goto enable_scaling;
9444 /* UFS device & link must be active before we enter in this function */
9445 if (!ufshcd_is_ufs_dev_active(hba) || !ufshcd_is_link_active(hba)) {
9447 goto enable_scaling;
9450 if (pm_op == UFS_RUNTIME_PM) {
9451 if (ufshcd_can_autobkops_during_suspend(hba)) {
9453 * The device is idle with no requests in the queue,
9454 * allow background operations if bkops status shows
9455 * that performance might be impacted.
9457 ret = ufshcd_urgent_bkops(hba);
9459 goto enable_scaling;
9461 /* make sure that auto bkops is disabled */
9462 ufshcd_disable_auto_bkops(hba);
9465 * If device needs to do BKOP or WB buffer flush during
9466 * Hibern8, keep device power mode as "active power mode"
9469 hba->dev_info.b_rpm_dev_flush_capable =
9470 hba->auto_bkops_enabled ||
9471 (((req_link_state == UIC_LINK_HIBERN8_STATE) ||
9472 ((req_link_state == UIC_LINK_ACTIVE_STATE) &&
9473 ufshcd_is_auto_hibern8_enabled(hba))) &&
9474 ufshcd_wb_need_flush(hba));
9477 flush_work(&hba->eeh_work);
9479 ret = ufshcd_vops_suspend(hba, pm_op, PRE_CHANGE);
9481 goto enable_scaling;
9483 if (req_dev_pwr_mode != hba->curr_dev_pwr_mode) {
9484 if (pm_op != UFS_RUNTIME_PM)
9485 /* ensure that bkops is disabled */
9486 ufshcd_disable_auto_bkops(hba);
9488 if (!hba->dev_info.b_rpm_dev_flush_capable) {
9489 ret = ufshcd_set_dev_pwr_mode(hba, req_dev_pwr_mode);
9490 if (ret && pm_op != UFS_SHUTDOWN_PM) {
9492 * If return err in suspend flow, IO will hang.
9493 * Trigger error handler and break suspend for
9496 ufshcd_force_error_recovery(hba);
9500 goto enable_scaling;
9505 * In the case of DeepSleep, the device is expected to remain powered
9506 * with the link off, so do not check for bkops.
9508 check_for_bkops = !ufshcd_is_ufs_dev_deepsleep(hba);
9509 ret = ufshcd_link_state_transition(hba, req_link_state, check_for_bkops);
9510 if (ret && pm_op != UFS_SHUTDOWN_PM) {
9512 * If return err in suspend flow, IO will hang.
9513 * Trigger error handler and break suspend for
9516 ufshcd_force_error_recovery(hba);
9520 goto set_dev_active;
9524 * Call vendor specific suspend callback. As these callbacks may access
9525 * vendor specific host controller register space call them before the
9526 * host clocks are ON.
9528 ret = ufshcd_vops_suspend(hba, pm_op, POST_CHANGE);
9530 goto set_link_active;
9535 * Device hardware reset is required to exit DeepSleep. Also, for
9536 * DeepSleep, the link is off so host reset and restore will be done
9539 if (ufshcd_is_ufs_dev_deepsleep(hba)) {
9540 ufshcd_device_reset(hba);
9541 WARN_ON(!ufshcd_is_link_off(hba));
9543 if (ufshcd_is_link_hibern8(hba) && !ufshcd_uic_hibern8_exit(hba))
9544 ufshcd_set_link_active(hba);
9545 else if (ufshcd_is_link_off(hba))
9546 ufshcd_host_reset_and_restore(hba);
9548 /* Can also get here needing to exit DeepSleep */
9549 if (ufshcd_is_ufs_dev_deepsleep(hba)) {
9550 ufshcd_device_reset(hba);
9551 ufshcd_host_reset_and_restore(hba);
9553 if (!ufshcd_set_dev_pwr_mode(hba, UFS_ACTIVE_PWR_MODE))
9554 ufshcd_disable_auto_bkops(hba);
9556 if (ufshcd_is_clkscaling_supported(hba))
9557 ufshcd_clk_scaling_suspend(hba, false);
9559 hba->dev_info.b_rpm_dev_flush_capable = false;
9561 if (hba->dev_info.b_rpm_dev_flush_capable) {
9562 schedule_delayed_work(&hba->rpm_dev_flush_recheck_work,
9563 msecs_to_jiffies(RPM_DEV_FLUSH_RECHECK_WORK_DELAY_MS));
9567 ufshcd_update_evt_hist(hba, UFS_EVT_WL_SUSP_ERR, (u32)ret);
9568 hba->clk_gating.is_suspended = false;
9569 ufshcd_release(hba);
9572 hba->pm_op_in_progress = false;
9577 static int __ufshcd_wl_resume(struct ufs_hba *hba, enum ufs_pm_op pm_op)
9580 enum uic_link_state old_link_state = hba->uic_link_state;
9582 hba->pm_op_in_progress = true;
9585 * Call vendor specific resume callback. As these callbacks may access
9586 * vendor specific host controller register space call them when the
9587 * host clocks are ON.
9589 ret = ufshcd_vops_resume(hba, pm_op);
9593 /* For DeepSleep, the only supported option is to have the link off */
9594 WARN_ON(ufshcd_is_ufs_dev_deepsleep(hba) && !ufshcd_is_link_off(hba));
9596 if (ufshcd_is_link_hibern8(hba)) {
9597 ret = ufshcd_uic_hibern8_exit(hba);
9599 ufshcd_set_link_active(hba);
9601 dev_err(hba->dev, "%s: hibern8 exit failed %d\n",
9603 goto vendor_suspend;
9605 } else if (ufshcd_is_link_off(hba)) {
9607 * A full initialization of the host and the device is
9608 * required since the link was put to off during suspend.
9609 * Note, in the case of DeepSleep, the device will exit
9610 * DeepSleep due to device reset.
9612 ret = ufshcd_reset_and_restore(hba);
9614 * ufshcd_reset_and_restore() should have already
9615 * set the link state as active
9617 if (ret || !ufshcd_is_link_active(hba))
9618 goto vendor_suspend;
9621 if (!ufshcd_is_ufs_dev_active(hba)) {
9622 ret = ufshcd_set_dev_pwr_mode(hba, UFS_ACTIVE_PWR_MODE);
9624 goto set_old_link_state;
9627 if (ufshcd_keep_autobkops_enabled_except_suspend(hba))
9628 ufshcd_enable_auto_bkops(hba);
9631 * If BKOPs operations are urgently needed at this moment then
9632 * keep auto-bkops enabled or else disable it.
9634 ufshcd_urgent_bkops(hba);
9636 if (hba->ee_usr_mask)
9637 ufshcd_write_ee_control(hba);
9639 if (ufshcd_is_clkscaling_supported(hba))
9640 ufshcd_clk_scaling_suspend(hba, false);
9642 if (hba->dev_info.b_rpm_dev_flush_capable) {
9643 hba->dev_info.b_rpm_dev_flush_capable = false;
9644 cancel_delayed_work(&hba->rpm_dev_flush_recheck_work);
9647 /* Enable Auto-Hibernate if configured */
9648 ufshcd_auto_hibern8_enable(hba);
9654 ufshcd_link_state_transition(hba, old_link_state, 0);
9656 ufshcd_vops_suspend(hba, pm_op, PRE_CHANGE);
9657 ufshcd_vops_suspend(hba, pm_op, POST_CHANGE);
9660 ufshcd_update_evt_hist(hba, UFS_EVT_WL_RES_ERR, (u32)ret);
9661 hba->clk_gating.is_suspended = false;
9662 ufshcd_release(hba);
9663 hba->pm_op_in_progress = false;
9667 static int ufshcd_wl_runtime_suspend(struct device *dev)
9669 struct scsi_device *sdev = to_scsi_device(dev);
9670 struct ufs_hba *hba;
9672 ktime_t start = ktime_get();
9674 hba = shost_priv(sdev->host);
9676 ret = __ufshcd_wl_suspend(hba, UFS_RUNTIME_PM);
9678 dev_err(&sdev->sdev_gendev, "%s failed: %d\n", __func__, ret);
9680 trace_ufshcd_wl_runtime_suspend(dev_name(dev), ret,
9681 ktime_to_us(ktime_sub(ktime_get(), start)),
9682 hba->curr_dev_pwr_mode, hba->uic_link_state);
9687 static int ufshcd_wl_runtime_resume(struct device *dev)
9689 struct scsi_device *sdev = to_scsi_device(dev);
9690 struct ufs_hba *hba;
9692 ktime_t start = ktime_get();
9694 hba = shost_priv(sdev->host);
9696 ret = __ufshcd_wl_resume(hba, UFS_RUNTIME_PM);
9698 dev_err(&sdev->sdev_gendev, "%s failed: %d\n", __func__, ret);
9700 trace_ufshcd_wl_runtime_resume(dev_name(dev), ret,
9701 ktime_to_us(ktime_sub(ktime_get(), start)),
9702 hba->curr_dev_pwr_mode, hba->uic_link_state);
9708 #ifdef CONFIG_PM_SLEEP
9709 static int ufshcd_wl_suspend(struct device *dev)
9711 struct scsi_device *sdev = to_scsi_device(dev);
9712 struct ufs_hba *hba;
9714 ktime_t start = ktime_get();
9716 hba = shost_priv(sdev->host);
9717 down(&hba->host_sem);
9718 hba->system_suspending = true;
9720 if (pm_runtime_suspended(dev))
9723 ret = __ufshcd_wl_suspend(hba, UFS_SYSTEM_PM);
9725 dev_err(&sdev->sdev_gendev, "%s failed: %d\n", __func__, ret);
9731 hba->is_sys_suspended = true;
9732 trace_ufshcd_wl_suspend(dev_name(dev), ret,
9733 ktime_to_us(ktime_sub(ktime_get(), start)),
9734 hba->curr_dev_pwr_mode, hba->uic_link_state);
9739 static int ufshcd_wl_resume(struct device *dev)
9741 struct scsi_device *sdev = to_scsi_device(dev);
9742 struct ufs_hba *hba;
9744 ktime_t start = ktime_get();
9746 hba = shost_priv(sdev->host);
9748 if (pm_runtime_suspended(dev))
9751 ret = __ufshcd_wl_resume(hba, UFS_SYSTEM_PM);
9753 dev_err(&sdev->sdev_gendev, "%s failed: %d\n", __func__, ret);
9755 trace_ufshcd_wl_resume(dev_name(dev), ret,
9756 ktime_to_us(ktime_sub(ktime_get(), start)),
9757 hba->curr_dev_pwr_mode, hba->uic_link_state);
9759 hba->is_sys_suspended = false;
9760 hba->system_suspending = false;
9766 static void ufshcd_wl_shutdown(struct device *dev)
9768 struct scsi_device *sdev = to_scsi_device(dev);
9769 struct ufs_hba *hba;
9771 hba = shost_priv(sdev->host);
9773 down(&hba->host_sem);
9774 hba->shutting_down = true;
9777 /* Turn on everything while shutting down */
9778 ufshcd_rpm_get_sync(hba);
9779 scsi_device_quiesce(sdev);
9780 shost_for_each_device(sdev, hba->host) {
9781 if (sdev == hba->ufs_device_wlun)
9783 scsi_device_quiesce(sdev);
9785 __ufshcd_wl_suspend(hba, UFS_SHUTDOWN_PM);
9789 * ufshcd_suspend - helper function for suspend operations
9790 * @hba: per adapter instance
9792 * This function will put disable irqs, turn off clocks
9793 * and set vreg and hba-vreg in lpm mode.
9795 static int ufshcd_suspend(struct ufs_hba *hba)
9799 if (!hba->is_powered)
9802 * Disable the host irq as host controller as there won't be any
9803 * host controller transaction expected till resume.
9805 ufshcd_disable_irq(hba);
9806 ret = ufshcd_setup_clocks(hba, false);
9808 ufshcd_enable_irq(hba);
9811 if (ufshcd_is_clkgating_allowed(hba)) {
9812 hba->clk_gating.state = CLKS_OFF;
9813 trace_ufshcd_clk_gating(dev_name(hba->dev),
9814 hba->clk_gating.state);
9817 ufshcd_vreg_set_lpm(hba);
9818 /* Put the host controller in low power mode if possible */
9819 ufshcd_hba_vreg_set_lpm(hba);
9825 * ufshcd_resume - helper function for resume operations
9826 * @hba: per adapter instance
9828 * This function basically turns on the regulators, clocks and
9831 * Returns 0 for success and non-zero for failure
9833 static int ufshcd_resume(struct ufs_hba *hba)
9837 if (!hba->is_powered)
9840 ufshcd_hba_vreg_set_hpm(hba);
9841 ret = ufshcd_vreg_set_hpm(hba);
9845 /* Make sure clocks are enabled before accessing controller */
9846 ret = ufshcd_setup_clocks(hba, true);
9850 /* enable the host irq as host controller would be active soon */
9851 ufshcd_enable_irq(hba);
9856 ufshcd_vreg_set_lpm(hba);
9859 ufshcd_update_evt_hist(hba, UFS_EVT_RESUME_ERR, (u32)ret);
9862 #endif /* CONFIG_PM */
9864 #ifdef CONFIG_PM_SLEEP
9866 * ufshcd_system_suspend - system suspend callback
9867 * @dev: Device associated with the UFS controller.
9869 * Executed before putting the system into a sleep state in which the contents
9870 * of main memory are preserved.
9872 * Returns 0 for success and non-zero for failure
9874 int ufshcd_system_suspend(struct device *dev)
9876 struct ufs_hba *hba = dev_get_drvdata(dev);
9878 ktime_t start = ktime_get();
9880 if (pm_runtime_suspended(hba->dev))
9883 ret = ufshcd_suspend(hba);
9885 trace_ufshcd_system_suspend(dev_name(hba->dev), ret,
9886 ktime_to_us(ktime_sub(ktime_get(), start)),
9887 hba->curr_dev_pwr_mode, hba->uic_link_state);
9890 EXPORT_SYMBOL(ufshcd_system_suspend);
9893 * ufshcd_system_resume - system resume callback
9894 * @dev: Device associated with the UFS controller.
9896 * Executed after waking the system up from a sleep state in which the contents
9897 * of main memory were preserved.
9899 * Returns 0 for success and non-zero for failure
9901 int ufshcd_system_resume(struct device *dev)
9903 struct ufs_hba *hba = dev_get_drvdata(dev);
9904 ktime_t start = ktime_get();
9907 if (pm_runtime_suspended(hba->dev))
9910 ret = ufshcd_resume(hba);
9913 trace_ufshcd_system_resume(dev_name(hba->dev), ret,
9914 ktime_to_us(ktime_sub(ktime_get(), start)),
9915 hba->curr_dev_pwr_mode, hba->uic_link_state);
9919 EXPORT_SYMBOL(ufshcd_system_resume);
9920 #endif /* CONFIG_PM_SLEEP */
9924 * ufshcd_runtime_suspend - runtime suspend callback
9925 * @dev: Device associated with the UFS controller.
9927 * Check the description of ufshcd_suspend() function for more details.
9929 * Returns 0 for success and non-zero for failure
9931 int ufshcd_runtime_suspend(struct device *dev)
9933 struct ufs_hba *hba = dev_get_drvdata(dev);
9935 ktime_t start = ktime_get();
9937 ret = ufshcd_suspend(hba);
9939 trace_ufshcd_runtime_suspend(dev_name(hba->dev), ret,
9940 ktime_to_us(ktime_sub(ktime_get(), start)),
9941 hba->curr_dev_pwr_mode, hba->uic_link_state);
9944 EXPORT_SYMBOL(ufshcd_runtime_suspend);
9947 * ufshcd_runtime_resume - runtime resume routine
9948 * @dev: Device associated with the UFS controller.
9950 * This function basically brings controller
9951 * to active state. Following operations are done in this function:
9953 * 1. Turn on all the controller related clocks
9954 * 2. Turn ON VCC rail
9956 int ufshcd_runtime_resume(struct device *dev)
9958 struct ufs_hba *hba = dev_get_drvdata(dev);
9960 ktime_t start = ktime_get();
9962 ret = ufshcd_resume(hba);
9964 trace_ufshcd_runtime_resume(dev_name(hba->dev), ret,
9965 ktime_to_us(ktime_sub(ktime_get(), start)),
9966 hba->curr_dev_pwr_mode, hba->uic_link_state);
9969 EXPORT_SYMBOL(ufshcd_runtime_resume);
9970 #endif /* CONFIG_PM */
9973 * ufshcd_shutdown - shutdown routine
9974 * @hba: per adapter instance
9976 * This function would turn off both UFS device and UFS hba
9977 * regulators. It would also disable clocks.
9979 * Returns 0 always to allow force shutdown even in case of errors.
9981 int ufshcd_shutdown(struct ufs_hba *hba)
9983 if (ufshcd_is_ufs_dev_poweroff(hba) && ufshcd_is_link_off(hba))
9984 ufshcd_suspend(hba);
9986 hba->is_powered = false;
9987 /* allow force shutdown even in case of errors */
9990 EXPORT_SYMBOL(ufshcd_shutdown);
9993 * ufshcd_remove - de-allocate SCSI host and host memory space
9994 * data structure memory
9995 * @hba: per adapter instance
9997 void ufshcd_remove(struct ufs_hba *hba)
9999 if (hba->ufs_device_wlun)
10000 ufshcd_rpm_get_sync(hba);
10001 ufs_hwmon_remove(hba);
10002 ufs_bsg_remove(hba);
10003 ufshpb_remove(hba);
10004 ufs_sysfs_remove_nodes(hba->dev);
10005 blk_mq_destroy_queue(hba->tmf_queue);
10006 blk_put_queue(hba->tmf_queue);
10007 blk_mq_free_tag_set(&hba->tmf_tag_set);
10008 scsi_remove_host(hba->host);
10009 /* disable interrupts */
10010 ufshcd_disable_intr(hba, hba->intr_mask);
10011 ufshcd_hba_stop(hba);
10012 ufshcd_hba_exit(hba);
10014 EXPORT_SYMBOL_GPL(ufshcd_remove);
10016 #ifdef CONFIG_PM_SLEEP
10017 int ufshcd_system_freeze(struct device *dev)
10020 return ufshcd_system_suspend(dev);
10023 EXPORT_SYMBOL_GPL(ufshcd_system_freeze);
10025 int ufshcd_system_restore(struct device *dev)
10028 struct ufs_hba *hba = dev_get_drvdata(dev);
10031 ret = ufshcd_system_resume(dev);
10035 /* Configure UTRL and UTMRL base address registers */
10036 ufshcd_writel(hba, lower_32_bits(hba->utrdl_dma_addr),
10037 REG_UTP_TRANSFER_REQ_LIST_BASE_L);
10038 ufshcd_writel(hba, upper_32_bits(hba->utrdl_dma_addr),
10039 REG_UTP_TRANSFER_REQ_LIST_BASE_H);
10040 ufshcd_writel(hba, lower_32_bits(hba->utmrdl_dma_addr),
10041 REG_UTP_TASK_REQ_LIST_BASE_L);
10042 ufshcd_writel(hba, upper_32_bits(hba->utmrdl_dma_addr),
10043 REG_UTP_TASK_REQ_LIST_BASE_H);
10045 * Make sure that UTRL and UTMRL base address registers
10046 * are updated with the latest queue addresses. Only after
10047 * updating these addresses, we can queue the new commands.
10051 /* Resuming from hibernate, assume that link was OFF */
10052 ufshcd_set_link_off(hba);
10057 EXPORT_SYMBOL_GPL(ufshcd_system_restore);
10059 int ufshcd_system_thaw(struct device *dev)
10061 return ufshcd_system_resume(dev);
10063 EXPORT_SYMBOL_GPL(ufshcd_system_thaw);
10064 #endif /* CONFIG_PM_SLEEP */
10067 * ufshcd_dealloc_host - deallocate Host Bus Adapter (HBA)
10068 * @hba: pointer to Host Bus Adapter (HBA)
10070 void ufshcd_dealloc_host(struct ufs_hba *hba)
10072 scsi_host_put(hba->host);
10074 EXPORT_SYMBOL_GPL(ufshcd_dealloc_host);
10077 * ufshcd_set_dma_mask - Set dma mask based on the controller
10078 * addressing capability
10079 * @hba: per adapter instance
10081 * Returns 0 for success, non-zero for failure
10083 static int ufshcd_set_dma_mask(struct ufs_hba *hba)
10085 if (hba->capabilities & MASK_64_ADDRESSING_SUPPORT) {
10086 if (!dma_set_mask_and_coherent(hba->dev, DMA_BIT_MASK(64)))
10089 return dma_set_mask_and_coherent(hba->dev, DMA_BIT_MASK(32));
10093 * ufshcd_alloc_host - allocate Host Bus Adapter (HBA)
10094 * @dev: pointer to device handle
10095 * @hba_handle: driver private handle
10096 * Returns 0 on success, non-zero value on failure
10098 int ufshcd_alloc_host(struct device *dev, struct ufs_hba **hba_handle)
10100 struct Scsi_Host *host;
10101 struct ufs_hba *hba;
10106 "Invalid memory reference for dev is NULL\n");
10111 host = scsi_host_alloc(&ufshcd_driver_template,
10112 sizeof(struct ufs_hba));
10114 dev_err(dev, "scsi_host_alloc failed\n");
10118 host->nr_maps = HCTX_TYPE_POLL + 1;
10119 hba = shost_priv(host);
10122 hba->dev_ref_clk_freq = REF_CLK_FREQ_INVAL;
10123 hba->nop_out_timeout = NOP_OUT_TIMEOUT;
10124 ufshcd_set_sg_entry_size(hba, sizeof(struct ufshcd_sg_entry));
10125 INIT_LIST_HEAD(&hba->clk_list_head);
10126 spin_lock_init(&hba->outstanding_lock);
10133 EXPORT_SYMBOL(ufshcd_alloc_host);
10135 /* This function exists because blk_mq_alloc_tag_set() requires this. */
10136 static blk_status_t ufshcd_queue_tmf(struct blk_mq_hw_ctx *hctx,
10137 const struct blk_mq_queue_data *qd)
10139 WARN_ON_ONCE(true);
10140 return BLK_STS_NOTSUPP;
10143 static const struct blk_mq_ops ufshcd_tmf_ops = {
10144 .queue_rq = ufshcd_queue_tmf,
10148 * ufshcd_init - Driver initialization routine
10149 * @hba: per-adapter instance
10150 * @mmio_base: base register address
10151 * @irq: Interrupt line of device
10152 * Returns 0 on success, non-zero value on failure
10154 int ufshcd_init(struct ufs_hba *hba, void __iomem *mmio_base, unsigned int irq)
10157 struct Scsi_Host *host = hba->host;
10158 struct device *dev = hba->dev;
10159 char eh_wq_name[sizeof("ufs_eh_wq_00")];
10162 * dev_set_drvdata() must be called before any callbacks are registered
10163 * that use dev_get_drvdata() (frequency scaling, clock scaling, hwmon,
10166 dev_set_drvdata(dev, hba);
10170 "Invalid memory reference for mmio_base is NULL\n");
10175 hba->mmio_base = mmio_base;
10177 hba->vps = &ufs_hba_vps;
10179 err = ufshcd_hba_init(hba);
10183 /* Read capabilities registers */
10184 err = ufshcd_hba_capabilities(hba);
10188 /* Get UFS version supported by the controller */
10189 hba->ufs_version = ufshcd_get_ufs_version(hba);
10191 /* Get Interrupt bit mask per version */
10192 hba->intr_mask = ufshcd_get_intr_mask(hba);
10194 err = ufshcd_set_dma_mask(hba);
10196 dev_err(hba->dev, "set dma mask failed\n");
10200 /* Allocate memory for host memory space */
10201 err = ufshcd_memory_alloc(hba);
10203 dev_err(hba->dev, "Memory allocation failed\n");
10207 /* Configure LRB */
10208 ufshcd_host_memory_configure(hba);
10210 host->can_queue = hba->nutrs - UFSHCD_NUM_RESERVED;
10211 host->cmd_per_lun = hba->nutrs - UFSHCD_NUM_RESERVED;
10212 host->max_id = UFSHCD_MAX_ID;
10213 host->max_lun = UFS_MAX_LUNS;
10214 host->max_channel = UFSHCD_MAX_CHANNEL;
10215 host->unique_id = host->host_no;
10216 host->max_cmd_len = UFS_CDB_SIZE;
10218 hba->max_pwr_info.is_valid = false;
10220 /* Initialize work queues */
10221 snprintf(eh_wq_name, sizeof(eh_wq_name), "ufs_eh_wq_%d",
10222 hba->host->host_no);
10223 hba->eh_wq = create_singlethread_workqueue(eh_wq_name);
10225 dev_err(hba->dev, "%s: failed to create eh workqueue\n",
10230 INIT_WORK(&hba->eh_work, ufshcd_err_handler);
10231 INIT_WORK(&hba->eeh_work, ufshcd_exception_event_handler);
10233 sema_init(&hba->host_sem, 1);
10235 /* Initialize UIC command mutex */
10236 mutex_init(&hba->uic_cmd_mutex);
10238 /* Initialize mutex for device management commands */
10239 mutex_init(&hba->dev_cmd.lock);
10241 /* Initialize mutex for exception event control */
10242 mutex_init(&hba->ee_ctrl_mutex);
10244 mutex_init(&hba->wb_mutex);
10245 init_rwsem(&hba->clk_scaling_lock);
10247 ufshcd_init_clk_gating(hba);
10249 ufshcd_init_clk_scaling(hba);
10252 * In order to avoid any spurious interrupt immediately after
10253 * registering UFS controller interrupt handler, clear any pending UFS
10254 * interrupt status and disable all the UFS interrupts.
10256 ufshcd_writel(hba, ufshcd_readl(hba, REG_INTERRUPT_STATUS),
10257 REG_INTERRUPT_STATUS);
10258 ufshcd_writel(hba, 0, REG_INTERRUPT_ENABLE);
10260 * Make sure that UFS interrupts are disabled and any pending interrupt
10261 * status is cleared before registering UFS interrupt handler.
10265 /* IRQ registration */
10266 err = devm_request_irq(dev, irq, ufshcd_intr, IRQF_SHARED, UFSHCD, hba);
10268 dev_err(hba->dev, "request irq failed\n");
10271 hba->is_irq_enabled = true;
10274 if (!is_mcq_supported(hba)) {
10275 err = scsi_add_host(host, hba->dev);
10277 dev_err(hba->dev, "scsi_add_host failed\n");
10282 hba->tmf_tag_set = (struct blk_mq_tag_set) {
10284 .queue_depth = hba->nutmrs,
10285 .ops = &ufshcd_tmf_ops,
10286 .flags = BLK_MQ_F_NO_SCHED,
10288 err = blk_mq_alloc_tag_set(&hba->tmf_tag_set);
10290 goto out_remove_scsi_host;
10291 hba->tmf_queue = blk_mq_init_queue(&hba->tmf_tag_set);
10292 if (IS_ERR(hba->tmf_queue)) {
10293 err = PTR_ERR(hba->tmf_queue);
10294 goto free_tmf_tag_set;
10296 hba->tmf_rqs = devm_kcalloc(hba->dev, hba->nutmrs,
10297 sizeof(*hba->tmf_rqs), GFP_KERNEL);
10298 if (!hba->tmf_rqs) {
10300 goto free_tmf_queue;
10303 /* Reset the attached device */
10304 ufshcd_device_reset(hba);
10306 ufshcd_init_crypto(hba);
10308 /* Host controller enable */
10309 err = ufshcd_hba_enable(hba);
10311 dev_err(hba->dev, "Host controller enable failed\n");
10312 ufshcd_print_evt_hist(hba);
10313 ufshcd_print_host_state(hba);
10314 goto free_tmf_queue;
10318 * Set the default power management level for runtime and system PM.
10319 * Default power saving mode is to keep UFS link in Hibern8 state
10320 * and UFS device in sleep state.
10322 hba->rpm_lvl = ufs_get_desired_pm_lvl_for_dev_link_state(
10323 UFS_SLEEP_PWR_MODE,
10324 UIC_LINK_HIBERN8_STATE);
10325 hba->spm_lvl = ufs_get_desired_pm_lvl_for_dev_link_state(
10326 UFS_SLEEP_PWR_MODE,
10327 UIC_LINK_HIBERN8_STATE);
10329 INIT_DELAYED_WORK(&hba->rpm_dev_flush_recheck_work,
10330 ufshcd_rpm_dev_flush_recheck_work);
10332 /* Set the default auto-hiberate idle timer value to 150 ms */
10333 if (ufshcd_is_auto_hibern8_supported(hba) && !hba->ahit) {
10334 hba->ahit = FIELD_PREP(UFSHCI_AHIBERN8_TIMER_MASK, 150) |
10335 FIELD_PREP(UFSHCI_AHIBERN8_SCALE_MASK, 3);
10338 /* Hold auto suspend until async scan completes */
10339 pm_runtime_get_sync(dev);
10340 atomic_set(&hba->scsi_block_reqs_cnt, 0);
10342 * We are assuming that device wasn't put in sleep/power-down
10343 * state exclusively during the boot stage before kernel.
10344 * This assumption helps avoid doing link startup twice during
10345 * ufshcd_probe_hba().
10347 ufshcd_set_ufs_dev_active(hba);
10349 async_schedule(ufshcd_async_scan, hba);
10350 ufs_sysfs_add_nodes(hba->dev);
10352 device_enable_async_suspend(dev);
10356 blk_mq_destroy_queue(hba->tmf_queue);
10357 blk_put_queue(hba->tmf_queue);
10359 blk_mq_free_tag_set(&hba->tmf_tag_set);
10360 out_remove_scsi_host:
10361 scsi_remove_host(hba->host);
10363 hba->is_irq_enabled = false;
10364 ufshcd_hba_exit(hba);
10368 EXPORT_SYMBOL_GPL(ufshcd_init);
10370 void ufshcd_resume_complete(struct device *dev)
10372 struct ufs_hba *hba = dev_get_drvdata(dev);
10374 if (hba->complete_put) {
10375 ufshcd_rpm_put(hba);
10376 hba->complete_put = false;
10379 EXPORT_SYMBOL_GPL(ufshcd_resume_complete);
10381 static bool ufshcd_rpm_ok_for_spm(struct ufs_hba *hba)
10383 struct device *dev = &hba->ufs_device_wlun->sdev_gendev;
10384 enum ufs_dev_pwr_mode dev_pwr_mode;
10385 enum uic_link_state link_state;
10386 unsigned long flags;
10389 spin_lock_irqsave(&dev->power.lock, flags);
10390 dev_pwr_mode = ufs_get_pm_lvl_to_dev_pwr_mode(hba->spm_lvl);
10391 link_state = ufs_get_pm_lvl_to_link_pwr_state(hba->spm_lvl);
10392 res = pm_runtime_suspended(dev) &&
10393 hba->curr_dev_pwr_mode == dev_pwr_mode &&
10394 hba->uic_link_state == link_state &&
10395 !hba->dev_info.b_rpm_dev_flush_capable;
10396 spin_unlock_irqrestore(&dev->power.lock, flags);
10401 int __ufshcd_suspend_prepare(struct device *dev, bool rpm_ok_for_spm)
10403 struct ufs_hba *hba = dev_get_drvdata(dev);
10407 * SCSI assumes that runtime-pm and system-pm for scsi drivers
10408 * are same. And it doesn't wake up the device for system-suspend
10409 * if it's runtime suspended. But ufs doesn't follow that.
10410 * Refer ufshcd_resume_complete()
10412 if (hba->ufs_device_wlun) {
10413 /* Prevent runtime suspend */
10414 ufshcd_rpm_get_noresume(hba);
10416 * Check if already runtime suspended in same state as system
10417 * suspend would be.
10419 if (!rpm_ok_for_spm || !ufshcd_rpm_ok_for_spm(hba)) {
10420 /* RPM state is not ok for SPM, so runtime resume */
10421 ret = ufshcd_rpm_resume(hba);
10422 if (ret < 0 && ret != -EACCES) {
10423 ufshcd_rpm_put(hba);
10427 hba->complete_put = true;
10431 EXPORT_SYMBOL_GPL(__ufshcd_suspend_prepare);
10433 int ufshcd_suspend_prepare(struct device *dev)
10435 return __ufshcd_suspend_prepare(dev, true);
10437 EXPORT_SYMBOL_GPL(ufshcd_suspend_prepare);
10439 #ifdef CONFIG_PM_SLEEP
10440 static int ufshcd_wl_poweroff(struct device *dev)
10442 struct scsi_device *sdev = to_scsi_device(dev);
10443 struct ufs_hba *hba = shost_priv(sdev->host);
10445 __ufshcd_wl_suspend(hba, UFS_SHUTDOWN_PM);
10450 static int ufshcd_wl_probe(struct device *dev)
10452 struct scsi_device *sdev = to_scsi_device(dev);
10454 if (!is_device_wlun(sdev))
10457 blk_pm_runtime_init(sdev->request_queue, dev);
10458 pm_runtime_set_autosuspend_delay(dev, 0);
10459 pm_runtime_allow(dev);
10464 static int ufshcd_wl_remove(struct device *dev)
10466 pm_runtime_forbid(dev);
10470 static const struct dev_pm_ops ufshcd_wl_pm_ops = {
10471 #ifdef CONFIG_PM_SLEEP
10472 .suspend = ufshcd_wl_suspend,
10473 .resume = ufshcd_wl_resume,
10474 .freeze = ufshcd_wl_suspend,
10475 .thaw = ufshcd_wl_resume,
10476 .poweroff = ufshcd_wl_poweroff,
10477 .restore = ufshcd_wl_resume,
10479 SET_RUNTIME_PM_OPS(ufshcd_wl_runtime_suspend, ufshcd_wl_runtime_resume, NULL)
10483 * ufs_dev_wlun_template - describes ufs device wlun
10484 * ufs-device wlun - used to send pm commands
10485 * All luns are consumers of ufs-device wlun.
10487 * Currently, no sd driver is present for wluns.
10488 * Hence the no specific pm operations are performed.
10489 * With ufs design, SSU should be sent to ufs-device wlun.
10490 * Hence register a scsi driver for ufs wluns only.
10492 static struct scsi_driver ufs_dev_wlun_template = {
10494 .name = "ufs_device_wlun",
10495 .owner = THIS_MODULE,
10496 .probe = ufshcd_wl_probe,
10497 .remove = ufshcd_wl_remove,
10498 .pm = &ufshcd_wl_pm_ops,
10499 .shutdown = ufshcd_wl_shutdown,
10503 static int __init ufshcd_core_init(void)
10507 ufs_debugfs_init();
10509 ret = scsi_register_driver(&ufs_dev_wlun_template.gendrv);
10511 ufs_debugfs_exit();
10515 static void __exit ufshcd_core_exit(void)
10517 ufs_debugfs_exit();
10518 scsi_unregister_driver(&ufs_dev_wlun_template.gendrv);
10521 module_init(ufshcd_core_init);
10522 module_exit(ufshcd_core_exit);
10524 MODULE_AUTHOR("Santosh Yaragnavi <santosh.sy@samsung.com>");
10525 MODULE_AUTHOR("Vinayak Holikatti <h.vinayak@samsung.com>");
10526 MODULE_DESCRIPTION("Generic UFS host controller driver Core");
10527 MODULE_SOFTDEP("pre: governor_simpleondemand");
10528 MODULE_LICENSE("GPL");