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 <linux/iopoll.h>
26 #include <scsi/scsi_cmnd.h>
27 #include <scsi/scsi_dbg.h>
28 #include <scsi/scsi_driver.h>
29 #include <scsi/scsi_eh.h>
30 #include "ufshcd-priv.h"
31 #include <ufs/ufs_quirks.h>
32 #include <ufs/unipro.h>
33 #include "ufs-sysfs.h"
34 #include "ufs-debugfs.h"
35 #include "ufs-fault-injection.h"
37 #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. */
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 module_param(use_mcq_mode, bool, 0644);
110 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");
112 #define ufshcd_toggle_vreg(_dev, _vreg, _on) \
116 _ret = ufshcd_enable_vreg(_dev, _vreg); \
118 _ret = ufshcd_disable_vreg(_dev, _vreg); \
122 #define ufshcd_hex_dump(prefix_str, buf, len) do { \
123 size_t __len = (len); \
124 print_hex_dump(KERN_ERR, prefix_str, \
125 __len > 4 ? DUMP_PREFIX_OFFSET : DUMP_PREFIX_NONE,\
126 16, 4, buf, __len, false); \
129 int ufshcd_dump_regs(struct ufs_hba *hba, size_t offset, size_t len,
135 if (offset % 4 != 0 || len % 4 != 0) /* keep readl happy */
138 regs = kzalloc(len, GFP_ATOMIC);
142 for (pos = 0; pos < len; pos += 4) {
144 pos >= REG_UIC_ERROR_CODE_PHY_ADAPTER_LAYER &&
145 pos <= REG_UIC_ERROR_CODE_DME)
147 regs[pos / 4] = ufshcd_readl(hba, offset + pos);
150 ufshcd_hex_dump(prefix, regs, len);
155 EXPORT_SYMBOL_GPL(ufshcd_dump_regs);
158 UFSHCD_MAX_CHANNEL = 0,
160 UFSHCD_CMD_PER_LUN = 32 - UFSHCD_NUM_RESERVED,
161 UFSHCD_CAN_QUEUE = 32 - UFSHCD_NUM_RESERVED,
164 static const char *const ufshcd_state_name[] = {
165 [UFSHCD_STATE_RESET] = "reset",
166 [UFSHCD_STATE_OPERATIONAL] = "operational",
167 [UFSHCD_STATE_ERROR] = "error",
168 [UFSHCD_STATE_EH_SCHEDULED_FATAL] = "eh_fatal",
169 [UFSHCD_STATE_EH_SCHEDULED_NON_FATAL] = "eh_non_fatal",
172 /* UFSHCD error handling flags */
174 UFSHCD_EH_IN_PROGRESS = (1 << 0),
177 /* UFSHCD UIC layer error flags */
179 UFSHCD_UIC_DL_PA_INIT_ERROR = (1 << 0), /* Data link layer error */
180 UFSHCD_UIC_DL_NAC_RECEIVED_ERROR = (1 << 1), /* Data link layer error */
181 UFSHCD_UIC_DL_TCx_REPLAY_ERROR = (1 << 2), /* Data link layer error */
182 UFSHCD_UIC_NL_ERROR = (1 << 3), /* Network layer error */
183 UFSHCD_UIC_TL_ERROR = (1 << 4), /* Transport Layer error */
184 UFSHCD_UIC_DME_ERROR = (1 << 5), /* DME error */
185 UFSHCD_UIC_PA_GENERIC_ERROR = (1 << 6), /* Generic PA error */
188 #define ufshcd_set_eh_in_progress(h) \
189 ((h)->eh_flags |= UFSHCD_EH_IN_PROGRESS)
190 #define ufshcd_eh_in_progress(h) \
191 ((h)->eh_flags & UFSHCD_EH_IN_PROGRESS)
192 #define ufshcd_clear_eh_in_progress(h) \
193 ((h)->eh_flags &= ~UFSHCD_EH_IN_PROGRESS)
195 const struct ufs_pm_lvl_states ufs_pm_lvl_states[] = {
196 [UFS_PM_LVL_0] = {UFS_ACTIVE_PWR_MODE, UIC_LINK_ACTIVE_STATE},
197 [UFS_PM_LVL_1] = {UFS_ACTIVE_PWR_MODE, UIC_LINK_HIBERN8_STATE},
198 [UFS_PM_LVL_2] = {UFS_SLEEP_PWR_MODE, UIC_LINK_ACTIVE_STATE},
199 [UFS_PM_LVL_3] = {UFS_SLEEP_PWR_MODE, UIC_LINK_HIBERN8_STATE},
200 [UFS_PM_LVL_4] = {UFS_POWERDOWN_PWR_MODE, UIC_LINK_HIBERN8_STATE},
201 [UFS_PM_LVL_5] = {UFS_POWERDOWN_PWR_MODE, UIC_LINK_OFF_STATE},
203 * For DeepSleep, the link is first put in hibern8 and then off.
204 * Leaving the link in hibern8 is not supported.
206 [UFS_PM_LVL_6] = {UFS_DEEPSLEEP_PWR_MODE, UIC_LINK_OFF_STATE},
209 static inline enum ufs_dev_pwr_mode
210 ufs_get_pm_lvl_to_dev_pwr_mode(enum ufs_pm_level lvl)
212 return ufs_pm_lvl_states[lvl].dev_state;
215 static inline enum uic_link_state
216 ufs_get_pm_lvl_to_link_pwr_state(enum ufs_pm_level lvl)
218 return ufs_pm_lvl_states[lvl].link_state;
221 static inline enum ufs_pm_level
222 ufs_get_desired_pm_lvl_for_dev_link_state(enum ufs_dev_pwr_mode dev_state,
223 enum uic_link_state link_state)
225 enum ufs_pm_level lvl;
227 for (lvl = UFS_PM_LVL_0; lvl < UFS_PM_LVL_MAX; lvl++) {
228 if ((ufs_pm_lvl_states[lvl].dev_state == dev_state) &&
229 (ufs_pm_lvl_states[lvl].link_state == link_state))
233 /* if no match found, return the level 0 */
237 static const struct ufs_dev_quirk ufs_fixups[] = {
238 /* UFS cards deviations table */
239 { .wmanufacturerid = UFS_VENDOR_MICRON,
240 .model = UFS_ANY_MODEL,
241 .quirk = UFS_DEVICE_QUIRK_DELAY_BEFORE_LPM },
242 { .wmanufacturerid = UFS_VENDOR_SAMSUNG,
243 .model = UFS_ANY_MODEL,
244 .quirk = UFS_DEVICE_QUIRK_DELAY_BEFORE_LPM |
245 UFS_DEVICE_QUIRK_HOST_PA_TACTIVATE |
246 UFS_DEVICE_QUIRK_RECOVERY_FROM_DL_NAC_ERRORS },
247 { .wmanufacturerid = UFS_VENDOR_SKHYNIX,
248 .model = UFS_ANY_MODEL,
249 .quirk = UFS_DEVICE_QUIRK_HOST_PA_SAVECONFIGTIME },
250 { .wmanufacturerid = UFS_VENDOR_SKHYNIX,
251 .model = "hB8aL1" /*H28U62301AMR*/,
252 .quirk = UFS_DEVICE_QUIRK_HOST_VS_DEBUGSAVECONFIGTIME },
253 { .wmanufacturerid = UFS_VENDOR_TOSHIBA,
254 .model = UFS_ANY_MODEL,
255 .quirk = UFS_DEVICE_QUIRK_DELAY_BEFORE_LPM },
256 { .wmanufacturerid = UFS_VENDOR_TOSHIBA,
257 .model = "THGLF2G9C8KBADG",
258 .quirk = UFS_DEVICE_QUIRK_PA_TACTIVATE },
259 { .wmanufacturerid = UFS_VENDOR_TOSHIBA,
260 .model = "THGLF2G9D8KBADG",
261 .quirk = UFS_DEVICE_QUIRK_PA_TACTIVATE },
265 static irqreturn_t ufshcd_tmc_handler(struct ufs_hba *hba);
266 static void ufshcd_async_scan(void *data, async_cookie_t cookie);
267 static int ufshcd_reset_and_restore(struct ufs_hba *hba);
268 static int ufshcd_eh_host_reset_handler(struct scsi_cmnd *cmd);
269 static int ufshcd_clear_tm_cmd(struct ufs_hba *hba, int tag);
270 static void ufshcd_hba_exit(struct ufs_hba *hba);
271 static int ufshcd_probe_hba(struct ufs_hba *hba, bool init_dev_params);
272 static int ufshcd_setup_clocks(struct ufs_hba *hba, bool on);
273 static inline void ufshcd_add_delay_before_dme_cmd(struct ufs_hba *hba);
274 static int ufshcd_host_reset_and_restore(struct ufs_hba *hba);
275 static void ufshcd_resume_clkscaling(struct ufs_hba *hba);
276 static void ufshcd_suspend_clkscaling(struct ufs_hba *hba);
277 static int ufshcd_scale_clks(struct ufs_hba *hba, bool scale_up);
278 static irqreturn_t ufshcd_intr(int irq, void *__hba);
279 static int ufshcd_change_power_mode(struct ufs_hba *hba,
280 struct ufs_pa_layer_attr *pwr_mode);
281 static int ufshcd_setup_hba_vreg(struct ufs_hba *hba, bool on);
282 static int ufshcd_setup_vreg(struct ufs_hba *hba, bool on);
283 static inline int ufshcd_config_vreg_hpm(struct ufs_hba *hba,
284 struct ufs_vreg *vreg);
285 static void ufshcd_wb_toggle_buf_flush_during_h8(struct ufs_hba *hba,
287 static void ufshcd_hba_vreg_set_lpm(struct ufs_hba *hba);
288 static void ufshcd_hba_vreg_set_hpm(struct ufs_hba *hba);
290 static inline void ufshcd_enable_irq(struct ufs_hba *hba)
292 if (!hba->is_irq_enabled) {
293 enable_irq(hba->irq);
294 hba->is_irq_enabled = true;
298 static inline void ufshcd_disable_irq(struct ufs_hba *hba)
300 if (hba->is_irq_enabled) {
301 disable_irq(hba->irq);
302 hba->is_irq_enabled = false;
306 static void ufshcd_configure_wb(struct ufs_hba *hba)
308 if (!ufshcd_is_wb_allowed(hba))
311 ufshcd_wb_toggle(hba, true);
313 ufshcd_wb_toggle_buf_flush_during_h8(hba, true);
315 if (ufshcd_is_wb_buf_flush_allowed(hba))
316 ufshcd_wb_toggle_buf_flush(hba, true);
319 static void ufshcd_scsi_unblock_requests(struct ufs_hba *hba)
321 if (atomic_dec_and_test(&hba->scsi_block_reqs_cnt))
322 scsi_unblock_requests(hba->host);
325 static void ufshcd_scsi_block_requests(struct ufs_hba *hba)
327 if (atomic_inc_return(&hba->scsi_block_reqs_cnt) == 1)
328 scsi_block_requests(hba->host);
331 static void ufshcd_add_cmd_upiu_trace(struct ufs_hba *hba, unsigned int tag,
332 enum ufs_trace_str_t str_t)
334 struct utp_upiu_req *rq = hba->lrb[tag].ucd_req_ptr;
335 struct utp_upiu_header *header;
337 if (!trace_ufshcd_upiu_enabled())
340 if (str_t == UFS_CMD_SEND)
341 header = &rq->header;
343 header = &hba->lrb[tag].ucd_rsp_ptr->header;
345 trace_ufshcd_upiu(dev_name(hba->dev), str_t, header, &rq->sc.cdb,
349 static void ufshcd_add_query_upiu_trace(struct ufs_hba *hba,
350 enum ufs_trace_str_t str_t,
351 struct utp_upiu_req *rq_rsp)
353 if (!trace_ufshcd_upiu_enabled())
356 trace_ufshcd_upiu(dev_name(hba->dev), str_t, &rq_rsp->header,
357 &rq_rsp->qr, UFS_TSF_OSF);
360 static void ufshcd_add_tm_upiu_trace(struct ufs_hba *hba, unsigned int tag,
361 enum ufs_trace_str_t str_t)
363 struct utp_task_req_desc *descp = &hba->utmrdl_base_addr[tag];
365 if (!trace_ufshcd_upiu_enabled())
368 if (str_t == UFS_TM_SEND)
369 trace_ufshcd_upiu(dev_name(hba->dev), str_t,
370 &descp->upiu_req.req_header,
371 &descp->upiu_req.input_param1,
374 trace_ufshcd_upiu(dev_name(hba->dev), str_t,
375 &descp->upiu_rsp.rsp_header,
376 &descp->upiu_rsp.output_param1,
380 static void ufshcd_add_uic_command_trace(struct ufs_hba *hba,
381 const struct uic_command *ucmd,
382 enum ufs_trace_str_t str_t)
386 if (!trace_ufshcd_uic_command_enabled())
389 if (str_t == UFS_CMD_SEND)
392 cmd = ufshcd_readl(hba, REG_UIC_COMMAND);
394 trace_ufshcd_uic_command(dev_name(hba->dev), str_t, cmd,
395 ufshcd_readl(hba, REG_UIC_COMMAND_ARG_1),
396 ufshcd_readl(hba, REG_UIC_COMMAND_ARG_2),
397 ufshcd_readl(hba, REG_UIC_COMMAND_ARG_3));
400 static void ufshcd_add_command_trace(struct ufs_hba *hba, unsigned int tag,
401 enum ufs_trace_str_t str_t)
404 u8 opcode = 0, group_id = 0;
408 struct ufshcd_lrb *lrbp = &hba->lrb[tag];
409 struct scsi_cmnd *cmd = lrbp->cmd;
410 struct request *rq = scsi_cmd_to_rq(cmd);
411 int transfer_len = -1;
416 /* trace UPIU also */
417 ufshcd_add_cmd_upiu_trace(hba, tag, str_t);
418 if (!trace_ufshcd_command_enabled())
421 opcode = cmd->cmnd[0];
423 if (opcode == READ_10 || opcode == WRITE_10) {
425 * Currently we only fully trace read(10) and write(10) commands
428 be32_to_cpu(lrbp->ucd_req_ptr->sc.exp_data_transfer_len);
429 lba = scsi_get_lba(cmd);
430 if (opcode == WRITE_10)
431 group_id = lrbp->cmd->cmnd[6];
432 } else if (opcode == UNMAP) {
434 * The number of Bytes to be unmapped beginning with the lba.
436 transfer_len = blk_rq_bytes(rq);
437 lba = scsi_get_lba(cmd);
440 intr = ufshcd_readl(hba, REG_INTERRUPT_STATUS);
442 if (is_mcq_enabled(hba)) {
443 struct ufs_hw_queue *hwq = ufshcd_mcq_req_to_hwq(hba, rq);
447 doorbell = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
449 trace_ufshcd_command(cmd->device, str_t, tag, doorbell, hwq_id,
450 transfer_len, intr, lba, opcode, group_id);
453 static void ufshcd_print_clk_freqs(struct ufs_hba *hba)
455 struct ufs_clk_info *clki;
456 struct list_head *head = &hba->clk_list_head;
458 if (list_empty(head))
461 list_for_each_entry(clki, head, list) {
462 if (!IS_ERR_OR_NULL(clki->clk) && clki->min_freq &&
464 dev_err(hba->dev, "clk: %s, rate: %u\n",
465 clki->name, clki->curr_freq);
469 static void ufshcd_print_evt(struct ufs_hba *hba, u32 id,
470 const char *err_name)
474 const struct ufs_event_hist *e;
476 if (id >= UFS_EVT_CNT)
479 e = &hba->ufs_stats.event[id];
481 for (i = 0; i < UFS_EVENT_HIST_LENGTH; i++) {
482 int p = (i + e->pos) % UFS_EVENT_HIST_LENGTH;
484 if (e->tstamp[p] == 0)
486 dev_err(hba->dev, "%s[%d] = 0x%x at %lld us\n", err_name, p,
487 e->val[p], div_u64(e->tstamp[p], 1000));
492 dev_err(hba->dev, "No record of %s\n", err_name);
494 dev_err(hba->dev, "%s: total cnt=%llu\n", err_name, e->cnt);
497 static void ufshcd_print_evt_hist(struct ufs_hba *hba)
499 ufshcd_dump_regs(hba, 0, UFSHCI_REG_SPACE_SIZE, "host_regs: ");
501 ufshcd_print_evt(hba, UFS_EVT_PA_ERR, "pa_err");
502 ufshcd_print_evt(hba, UFS_EVT_DL_ERR, "dl_err");
503 ufshcd_print_evt(hba, UFS_EVT_NL_ERR, "nl_err");
504 ufshcd_print_evt(hba, UFS_EVT_TL_ERR, "tl_err");
505 ufshcd_print_evt(hba, UFS_EVT_DME_ERR, "dme_err");
506 ufshcd_print_evt(hba, UFS_EVT_AUTO_HIBERN8_ERR,
508 ufshcd_print_evt(hba, UFS_EVT_FATAL_ERR, "fatal_err");
509 ufshcd_print_evt(hba, UFS_EVT_LINK_STARTUP_FAIL,
510 "link_startup_fail");
511 ufshcd_print_evt(hba, UFS_EVT_RESUME_ERR, "resume_fail");
512 ufshcd_print_evt(hba, UFS_EVT_SUSPEND_ERR,
514 ufshcd_print_evt(hba, UFS_EVT_WL_RES_ERR, "wlun resume_fail");
515 ufshcd_print_evt(hba, UFS_EVT_WL_SUSP_ERR,
516 "wlun suspend_fail");
517 ufshcd_print_evt(hba, UFS_EVT_DEV_RESET, "dev_reset");
518 ufshcd_print_evt(hba, UFS_EVT_HOST_RESET, "host_reset");
519 ufshcd_print_evt(hba, UFS_EVT_ABORT, "task_abort");
521 ufshcd_vops_dbg_register_dump(hba);
525 void ufshcd_print_tr(struct ufs_hba *hba, int tag, bool pr_prdt)
527 const struct ufshcd_lrb *lrbp;
530 lrbp = &hba->lrb[tag];
532 dev_err(hba->dev, "UPIU[%d] - issue time %lld us\n",
533 tag, div_u64(lrbp->issue_time_stamp_local_clock, 1000));
534 dev_err(hba->dev, "UPIU[%d] - complete time %lld us\n",
535 tag, div_u64(lrbp->compl_time_stamp_local_clock, 1000));
537 "UPIU[%d] - Transfer Request Descriptor phys@0x%llx\n",
538 tag, (u64)lrbp->utrd_dma_addr);
540 ufshcd_hex_dump("UPIU TRD: ", lrbp->utr_descriptor_ptr,
541 sizeof(struct utp_transfer_req_desc));
542 dev_err(hba->dev, "UPIU[%d] - Request UPIU phys@0x%llx\n", tag,
543 (u64)lrbp->ucd_req_dma_addr);
544 ufshcd_hex_dump("UPIU REQ: ", lrbp->ucd_req_ptr,
545 sizeof(struct utp_upiu_req));
546 dev_err(hba->dev, "UPIU[%d] - Response UPIU phys@0x%llx\n", tag,
547 (u64)lrbp->ucd_rsp_dma_addr);
548 ufshcd_hex_dump("UPIU RSP: ", lrbp->ucd_rsp_ptr,
549 sizeof(struct utp_upiu_rsp));
551 prdt_length = le16_to_cpu(
552 lrbp->utr_descriptor_ptr->prd_table_length);
553 if (hba->quirks & UFSHCD_QUIRK_PRDT_BYTE_GRAN)
554 prdt_length /= ufshcd_sg_entry_size(hba);
557 "UPIU[%d] - PRDT - %d entries phys@0x%llx\n",
559 (u64)lrbp->ucd_prdt_dma_addr);
562 ufshcd_hex_dump("UPIU PRDT: ", lrbp->ucd_prdt_ptr,
563 ufshcd_sg_entry_size(hba) * prdt_length);
566 static bool ufshcd_print_tr_iter(struct request *req, void *priv)
568 struct scsi_device *sdev = req->q->queuedata;
569 struct Scsi_Host *shost = sdev->host;
570 struct ufs_hba *hba = shost_priv(shost);
572 ufshcd_print_tr(hba, req->tag, *(bool *)priv);
578 * ufshcd_print_trs_all - print trs for all started requests.
579 * @hba: per-adapter instance.
580 * @pr_prdt: need to print prdt or not.
582 static void ufshcd_print_trs_all(struct ufs_hba *hba, bool pr_prdt)
584 blk_mq_tagset_busy_iter(&hba->host->tag_set, ufshcd_print_tr_iter, &pr_prdt);
587 static void ufshcd_print_tmrs(struct ufs_hba *hba, unsigned long bitmap)
591 for_each_set_bit(tag, &bitmap, hba->nutmrs) {
592 struct utp_task_req_desc *tmrdp = &hba->utmrdl_base_addr[tag];
594 dev_err(hba->dev, "TM[%d] - Task Management Header\n", tag);
595 ufshcd_hex_dump("", tmrdp, sizeof(*tmrdp));
599 static void ufshcd_print_host_state(struct ufs_hba *hba)
601 const struct scsi_device *sdev_ufs = hba->ufs_device_wlun;
603 dev_err(hba->dev, "UFS Host state=%d\n", hba->ufshcd_state);
604 dev_err(hba->dev, "outstanding reqs=0x%lx tasks=0x%lx\n",
605 hba->outstanding_reqs, hba->outstanding_tasks);
606 dev_err(hba->dev, "saved_err=0x%x, saved_uic_err=0x%x\n",
607 hba->saved_err, hba->saved_uic_err);
608 dev_err(hba->dev, "Device power mode=%d, UIC link state=%d\n",
609 hba->curr_dev_pwr_mode, hba->uic_link_state);
610 dev_err(hba->dev, "PM in progress=%d, sys. suspended=%d\n",
611 hba->pm_op_in_progress, hba->is_sys_suspended);
612 dev_err(hba->dev, "Auto BKOPS=%d, Host self-block=%d\n",
613 hba->auto_bkops_enabled, hba->host->host_self_blocked);
614 dev_err(hba->dev, "Clk gate=%d\n", hba->clk_gating.state);
616 "last_hibern8_exit_tstamp at %lld us, hibern8_exit_cnt=%d\n",
617 div_u64(hba->ufs_stats.last_hibern8_exit_tstamp, 1000),
618 hba->ufs_stats.hibern8_exit_cnt);
619 dev_err(hba->dev, "last intr at %lld us, last intr status=0x%x\n",
620 div_u64(hba->ufs_stats.last_intr_ts, 1000),
621 hba->ufs_stats.last_intr_status);
622 dev_err(hba->dev, "error handling flags=0x%x, req. abort count=%d\n",
623 hba->eh_flags, hba->req_abort_count);
624 dev_err(hba->dev, "hba->ufs_version=0x%x, Host capabilities=0x%x, caps=0x%x\n",
625 hba->ufs_version, hba->capabilities, hba->caps);
626 dev_err(hba->dev, "quirks=0x%x, dev. quirks=0x%x\n", hba->quirks,
629 dev_err(hba->dev, "UFS dev info: %.8s %.16s rev %.4s\n",
630 sdev_ufs->vendor, sdev_ufs->model, sdev_ufs->rev);
632 ufshcd_print_clk_freqs(hba);
636 * ufshcd_print_pwr_info - print power params as saved in hba
638 * @hba: per-adapter instance
640 static void ufshcd_print_pwr_info(struct ufs_hba *hba)
642 static const char * const names[] = {
653 * Using dev_dbg to avoid messages during runtime PM to avoid
654 * never-ending cycles of messages written back to storage by user space
655 * causing runtime resume, causing more messages and so on.
657 dev_dbg(hba->dev, "%s:[RX, TX]: gear=[%d, %d], lane[%d, %d], pwr[%s, %s], rate = %d\n",
659 hba->pwr_info.gear_rx, hba->pwr_info.gear_tx,
660 hba->pwr_info.lane_rx, hba->pwr_info.lane_tx,
661 names[hba->pwr_info.pwr_rx],
662 names[hba->pwr_info.pwr_tx],
663 hba->pwr_info.hs_rate);
666 static void ufshcd_device_reset(struct ufs_hba *hba)
670 err = ufshcd_vops_device_reset(hba);
673 ufshcd_set_ufs_dev_active(hba);
674 if (ufshcd_is_wb_allowed(hba)) {
675 hba->dev_info.wb_enabled = false;
676 hba->dev_info.wb_buf_flush_enabled = false;
679 if (err != -EOPNOTSUPP)
680 ufshcd_update_evt_hist(hba, UFS_EVT_DEV_RESET, err);
683 void ufshcd_delay_us(unsigned long us, unsigned long tolerance)
691 usleep_range(us, us + tolerance);
693 EXPORT_SYMBOL_GPL(ufshcd_delay_us);
696 * ufshcd_wait_for_register - wait for register value to change
697 * @hba: per-adapter interface
698 * @reg: mmio register offset
699 * @mask: mask to apply to the read register value
700 * @val: value to wait for
701 * @interval_us: polling interval in microseconds
702 * @timeout_ms: timeout in milliseconds
704 * Return: -ETIMEDOUT on error, zero on success.
706 static int ufshcd_wait_for_register(struct ufs_hba *hba, u32 reg, u32 mask,
707 u32 val, unsigned long interval_us,
708 unsigned long timeout_ms)
711 unsigned long timeout = jiffies + msecs_to_jiffies(timeout_ms);
713 /* ignore bits that we don't intend to wait on */
716 while ((ufshcd_readl(hba, reg) & mask) != val) {
717 usleep_range(interval_us, interval_us + 50);
718 if (time_after(jiffies, timeout)) {
719 if ((ufshcd_readl(hba, reg) & mask) != val)
729 * ufshcd_get_intr_mask - Get the interrupt bit mask
730 * @hba: Pointer to adapter instance
732 * Return: interrupt bit mask per version
734 static inline u32 ufshcd_get_intr_mask(struct ufs_hba *hba)
736 if (hba->ufs_version == ufshci_version(1, 0))
737 return INTERRUPT_MASK_ALL_VER_10;
738 if (hba->ufs_version <= ufshci_version(2, 0))
739 return INTERRUPT_MASK_ALL_VER_11;
741 return INTERRUPT_MASK_ALL_VER_21;
745 * ufshcd_get_ufs_version - Get the UFS version supported by the HBA
746 * @hba: Pointer to adapter instance
748 * Return: UFSHCI version supported by the controller
750 static inline u32 ufshcd_get_ufs_version(struct ufs_hba *hba)
754 if (hba->quirks & UFSHCD_QUIRK_BROKEN_UFS_HCI_VERSION)
755 ufshci_ver = ufshcd_vops_get_ufs_hci_version(hba);
757 ufshci_ver = ufshcd_readl(hba, REG_UFS_VERSION);
760 * UFSHCI v1.x uses a different version scheme, in order
761 * to allow the use of comparisons with the ufshci_version
762 * function, we convert it to the same scheme as ufs 2.0+.
764 if (ufshci_ver & 0x00010000)
765 return ufshci_version(1, ufshci_ver & 0x00000100);
771 * ufshcd_is_device_present - Check if any device connected to
772 * the host controller
773 * @hba: pointer to adapter instance
775 * Return: true if device present, false if no device detected
777 static inline bool ufshcd_is_device_present(struct ufs_hba *hba)
779 return ufshcd_readl(hba, REG_CONTROLLER_STATUS) & DEVICE_PRESENT;
783 * ufshcd_get_tr_ocs - Get the UTRD Overall Command Status
784 * @lrbp: pointer to local command reference block
785 * @cqe: pointer to the completion queue entry
787 * This function is used to get the OCS field from UTRD
789 * Return: the OCS field in the UTRD.
791 static enum utp_ocs ufshcd_get_tr_ocs(struct ufshcd_lrb *lrbp,
792 struct cq_entry *cqe)
795 return le32_to_cpu(cqe->status) & MASK_OCS;
797 return lrbp->utr_descriptor_ptr->header.ocs & MASK_OCS;
801 * ufshcd_utrl_clear() - Clear requests from the controller request list.
802 * @hba: per adapter instance
803 * @mask: mask with one bit set for each request to be cleared
805 static inline void ufshcd_utrl_clear(struct ufs_hba *hba, u32 mask)
807 if (hba->quirks & UFSHCI_QUIRK_BROKEN_REQ_LIST_CLR)
810 * From the UFSHCI specification: "UTP Transfer Request List CLear
811 * Register (UTRLCLR): This field is bit significant. Each bit
812 * corresponds to a slot in the UTP Transfer Request List, where bit 0
813 * corresponds to request slot 0. A bit in this field is set to ‘0’
814 * by host software to indicate to the host controller that a transfer
815 * request slot is cleared. The host controller
816 * shall free up any resources associated to the request slot
817 * immediately, and shall set the associated bit in UTRLDBR to ‘0’. The
818 * host software indicates no change to request slots by setting the
819 * associated bits in this field to ‘1’. Bits in this field shall only
820 * be set ‘1’ or ‘0’ by host software when UTRLRSR is set to ‘1’."
822 ufshcd_writel(hba, ~mask, REG_UTP_TRANSFER_REQ_LIST_CLEAR);
826 * ufshcd_utmrl_clear - Clear a bit in UTMRLCLR register
827 * @hba: per adapter instance
828 * @pos: position of the bit to be cleared
830 static inline void ufshcd_utmrl_clear(struct ufs_hba *hba, u32 pos)
832 if (hba->quirks & UFSHCI_QUIRK_BROKEN_REQ_LIST_CLR)
833 ufshcd_writel(hba, (1 << pos), REG_UTP_TASK_REQ_LIST_CLEAR);
835 ufshcd_writel(hba, ~(1 << pos), REG_UTP_TASK_REQ_LIST_CLEAR);
839 * ufshcd_get_lists_status - Check UCRDY, UTRLRDY and UTMRLRDY
840 * @reg: Register value of host controller status
842 * Return: 0 on success; a positive value if failed.
844 static inline int ufshcd_get_lists_status(u32 reg)
846 return !((reg & UFSHCD_STATUS_READY) == UFSHCD_STATUS_READY);
850 * ufshcd_get_uic_cmd_result - Get the UIC command result
851 * @hba: Pointer to adapter instance
853 * This function gets the result of UIC command completion
855 * Return: 0 on success; non-zero value on error.
857 static inline int ufshcd_get_uic_cmd_result(struct ufs_hba *hba)
859 return ufshcd_readl(hba, REG_UIC_COMMAND_ARG_2) &
860 MASK_UIC_COMMAND_RESULT;
864 * ufshcd_get_dme_attr_val - Get the value of attribute returned by UIC command
865 * @hba: Pointer to adapter instance
867 * This function gets UIC command argument3
869 * Return: 0 on success; non-zero value on error.
871 static inline u32 ufshcd_get_dme_attr_val(struct ufs_hba *hba)
873 return ufshcd_readl(hba, REG_UIC_COMMAND_ARG_3);
877 * ufshcd_get_req_rsp - returns the TR response transaction type
878 * @ucd_rsp_ptr: pointer to response UPIU
882 static inline enum upiu_response_transaction
883 ufshcd_get_req_rsp(struct utp_upiu_rsp *ucd_rsp_ptr)
885 return ucd_rsp_ptr->header.transaction_code;
889 * ufshcd_is_exception_event - Check if the device raised an exception event
890 * @ucd_rsp_ptr: pointer to response UPIU
892 * The function checks if the device raised an exception event indicated in
893 * the Device Information field of response UPIU.
895 * Return: true if exception is raised, false otherwise.
897 static inline bool ufshcd_is_exception_event(struct utp_upiu_rsp *ucd_rsp_ptr)
899 return ucd_rsp_ptr->header.device_information & 1;
903 * ufshcd_reset_intr_aggr - Reset interrupt aggregation values.
904 * @hba: per adapter instance
907 ufshcd_reset_intr_aggr(struct ufs_hba *hba)
909 ufshcd_writel(hba, INT_AGGR_ENABLE |
910 INT_AGGR_COUNTER_AND_TIMER_RESET,
911 REG_UTP_TRANSFER_REQ_INT_AGG_CONTROL);
915 * ufshcd_config_intr_aggr - Configure interrupt aggregation values.
916 * @hba: per adapter instance
917 * @cnt: Interrupt aggregation counter threshold
918 * @tmout: Interrupt aggregation timeout value
921 ufshcd_config_intr_aggr(struct ufs_hba *hba, u8 cnt, u8 tmout)
923 ufshcd_writel(hba, INT_AGGR_ENABLE | INT_AGGR_PARAM_WRITE |
924 INT_AGGR_COUNTER_THLD_VAL(cnt) |
925 INT_AGGR_TIMEOUT_VAL(tmout),
926 REG_UTP_TRANSFER_REQ_INT_AGG_CONTROL);
930 * ufshcd_disable_intr_aggr - Disables interrupt aggregation.
931 * @hba: per adapter instance
933 static inline void ufshcd_disable_intr_aggr(struct ufs_hba *hba)
935 ufshcd_writel(hba, 0, REG_UTP_TRANSFER_REQ_INT_AGG_CONTROL);
939 * ufshcd_enable_run_stop_reg - Enable run-stop registers,
940 * When run-stop registers are set to 1, it indicates the
941 * host controller that it can process the requests
942 * @hba: per adapter instance
944 static void ufshcd_enable_run_stop_reg(struct ufs_hba *hba)
946 ufshcd_writel(hba, UTP_TASK_REQ_LIST_RUN_STOP_BIT,
947 REG_UTP_TASK_REQ_LIST_RUN_STOP);
948 ufshcd_writel(hba, UTP_TRANSFER_REQ_LIST_RUN_STOP_BIT,
949 REG_UTP_TRANSFER_REQ_LIST_RUN_STOP);
953 * ufshcd_hba_start - Start controller initialization sequence
954 * @hba: per adapter instance
956 static inline void ufshcd_hba_start(struct ufs_hba *hba)
958 u32 val = CONTROLLER_ENABLE;
960 if (ufshcd_crypto_enable(hba))
961 val |= CRYPTO_GENERAL_ENABLE;
963 ufshcd_writel(hba, val, REG_CONTROLLER_ENABLE);
967 * ufshcd_is_hba_active - Get controller state
968 * @hba: per adapter instance
970 * Return: true if and only if the controller is active.
972 bool ufshcd_is_hba_active(struct ufs_hba *hba)
974 return ufshcd_readl(hba, REG_CONTROLLER_ENABLE) & CONTROLLER_ENABLE;
976 EXPORT_SYMBOL_GPL(ufshcd_is_hba_active);
978 u32 ufshcd_get_local_unipro_ver(struct ufs_hba *hba)
980 /* HCI version 1.0 and 1.1 supports UniPro 1.41 */
981 if (hba->ufs_version <= ufshci_version(1, 1))
982 return UFS_UNIPRO_VER_1_41;
984 return UFS_UNIPRO_VER_1_6;
986 EXPORT_SYMBOL(ufshcd_get_local_unipro_ver);
988 static bool ufshcd_is_unipro_pa_params_tuning_req(struct ufs_hba *hba)
991 * If both host and device support UniPro ver1.6 or later, PA layer
992 * parameters tuning happens during link startup itself.
994 * We can manually tune PA layer parameters if either host or device
995 * doesn't support UniPro ver 1.6 or later. But to keep manual tuning
996 * logic simple, we will only do manual tuning if local unipro version
997 * doesn't support ver1.6 or later.
999 return ufshcd_get_local_unipro_ver(hba) < UFS_UNIPRO_VER_1_6;
1003 * ufshcd_set_clk_freq - set UFS controller clock frequencies
1004 * @hba: per adapter instance
1005 * @scale_up: If True, set max possible frequency othewise set low frequency
1007 * Return: 0 if successful; < 0 upon failure.
1009 static int ufshcd_set_clk_freq(struct ufs_hba *hba, bool scale_up)
1012 struct ufs_clk_info *clki;
1013 struct list_head *head = &hba->clk_list_head;
1015 if (list_empty(head))
1018 list_for_each_entry(clki, head, list) {
1019 if (!IS_ERR_OR_NULL(clki->clk)) {
1020 if (scale_up && clki->max_freq) {
1021 if (clki->curr_freq == clki->max_freq)
1024 ret = clk_set_rate(clki->clk, clki->max_freq);
1026 dev_err(hba->dev, "%s: %s clk set rate(%dHz) failed, %d\n",
1027 __func__, clki->name,
1028 clki->max_freq, ret);
1031 trace_ufshcd_clk_scaling(dev_name(hba->dev),
1032 "scaled up", clki->name,
1036 clki->curr_freq = clki->max_freq;
1038 } else if (!scale_up && clki->min_freq) {
1039 if (clki->curr_freq == clki->min_freq)
1042 ret = clk_set_rate(clki->clk, clki->min_freq);
1044 dev_err(hba->dev, "%s: %s clk set rate(%dHz) failed, %d\n",
1045 __func__, clki->name,
1046 clki->min_freq, ret);
1049 trace_ufshcd_clk_scaling(dev_name(hba->dev),
1050 "scaled down", clki->name,
1053 clki->curr_freq = clki->min_freq;
1056 dev_dbg(hba->dev, "%s: clk: %s, rate: %lu\n", __func__,
1057 clki->name, clk_get_rate(clki->clk));
1065 * ufshcd_scale_clks - scale up or scale down UFS controller clocks
1066 * @hba: per adapter instance
1067 * @scale_up: True if scaling up and false if scaling down
1069 * Return: 0 if successful; < 0 upon failure.
1071 static int ufshcd_scale_clks(struct ufs_hba *hba, bool scale_up)
1074 ktime_t start = ktime_get();
1076 ret = ufshcd_vops_clk_scale_notify(hba, scale_up, PRE_CHANGE);
1080 ret = ufshcd_set_clk_freq(hba, scale_up);
1084 ret = ufshcd_vops_clk_scale_notify(hba, scale_up, POST_CHANGE);
1086 ufshcd_set_clk_freq(hba, !scale_up);
1089 trace_ufshcd_profile_clk_scaling(dev_name(hba->dev),
1090 (scale_up ? "up" : "down"),
1091 ktime_to_us(ktime_sub(ktime_get(), start)), ret);
1096 * ufshcd_is_devfreq_scaling_required - check if scaling is required or not
1097 * @hba: per adapter instance
1098 * @scale_up: True if scaling up and false if scaling down
1100 * Return: true if scaling is required, false otherwise.
1102 static bool ufshcd_is_devfreq_scaling_required(struct ufs_hba *hba,
1105 struct ufs_clk_info *clki;
1106 struct list_head *head = &hba->clk_list_head;
1108 if (list_empty(head))
1111 list_for_each_entry(clki, head, list) {
1112 if (!IS_ERR_OR_NULL(clki->clk)) {
1113 if (scale_up && clki->max_freq) {
1114 if (clki->curr_freq == clki->max_freq)
1117 } else if (!scale_up && clki->min_freq) {
1118 if (clki->curr_freq == clki->min_freq)
1129 * Determine the number of pending commands by counting the bits in the SCSI
1130 * device budget maps. This approach has been selected because a bit is set in
1131 * the budget map before scsi_host_queue_ready() checks the host_self_blocked
1132 * flag. The host_self_blocked flag can be modified by calling
1133 * scsi_block_requests() or scsi_unblock_requests().
1135 static u32 ufshcd_pending_cmds(struct ufs_hba *hba)
1137 const struct scsi_device *sdev;
1140 lockdep_assert_held(hba->host->host_lock);
1141 __shost_for_each_device(sdev, hba->host)
1142 pending += sbitmap_weight(&sdev->budget_map);
1148 * Wait until all pending SCSI commands and TMFs have finished or the timeout
1151 * Return: 0 upon success; -EBUSY upon timeout.
1153 static int ufshcd_wait_for_doorbell_clr(struct ufs_hba *hba,
1154 u64 wait_timeout_us)
1156 unsigned long flags;
1160 bool timeout = false, do_last_check = false;
1164 spin_lock_irqsave(hba->host->host_lock, flags);
1166 * Wait for all the outstanding tasks/transfer requests.
1167 * Verify by checking the doorbell registers are clear.
1169 start = ktime_get();
1171 if (hba->ufshcd_state != UFSHCD_STATE_OPERATIONAL) {
1176 tm_doorbell = ufshcd_readl(hba, REG_UTP_TASK_REQ_DOOR_BELL);
1177 tr_pending = ufshcd_pending_cmds(hba);
1178 if (!tm_doorbell && !tr_pending) {
1181 } else if (do_last_check) {
1185 spin_unlock_irqrestore(hba->host->host_lock, flags);
1186 io_schedule_timeout(msecs_to_jiffies(20));
1187 if (ktime_to_us(ktime_sub(ktime_get(), start)) >
1191 * We might have scheduled out for long time so make
1192 * sure to check if doorbells are cleared by this time
1195 do_last_check = true;
1197 spin_lock_irqsave(hba->host->host_lock, flags);
1198 } while (tm_doorbell || tr_pending);
1202 "%s: timedout waiting for doorbell to clear (tm=0x%x, tr=0x%x)\n",
1203 __func__, tm_doorbell, tr_pending);
1207 spin_unlock_irqrestore(hba->host->host_lock, flags);
1208 ufshcd_release(hba);
1213 * ufshcd_scale_gear - scale up/down UFS gear
1214 * @hba: per adapter instance
1215 * @scale_up: True for scaling up gear and false for scaling down
1217 * Return: 0 for success; -EBUSY if scaling can't happen at this time;
1218 * non-zero for any other errors.
1220 static int ufshcd_scale_gear(struct ufs_hba *hba, bool scale_up)
1223 struct ufs_pa_layer_attr new_pwr_info;
1226 memcpy(&new_pwr_info, &hba->clk_scaling.saved_pwr_info,
1227 sizeof(struct ufs_pa_layer_attr));
1229 memcpy(&new_pwr_info, &hba->pwr_info,
1230 sizeof(struct ufs_pa_layer_attr));
1232 if (hba->pwr_info.gear_tx > hba->clk_scaling.min_gear ||
1233 hba->pwr_info.gear_rx > hba->clk_scaling.min_gear) {
1234 /* save the current power mode */
1235 memcpy(&hba->clk_scaling.saved_pwr_info,
1237 sizeof(struct ufs_pa_layer_attr));
1239 /* scale down gear */
1240 new_pwr_info.gear_tx = hba->clk_scaling.min_gear;
1241 new_pwr_info.gear_rx = hba->clk_scaling.min_gear;
1245 /* check if the power mode needs to be changed or not? */
1246 ret = ufshcd_config_pwr_mode(hba, &new_pwr_info);
1248 dev_err(hba->dev, "%s: failed err %d, old gear: (tx %d rx %d), new gear: (tx %d rx %d)",
1250 hba->pwr_info.gear_tx, hba->pwr_info.gear_rx,
1251 new_pwr_info.gear_tx, new_pwr_info.gear_rx);
1257 * Wait until all pending SCSI commands and TMFs have finished or the timeout
1260 * Return: 0 upon success; -EBUSY upon timeout.
1262 static int ufshcd_clock_scaling_prepare(struct ufs_hba *hba, u64 timeout_us)
1266 * make sure that there are no outstanding requests when
1267 * clock scaling is in progress
1269 ufshcd_scsi_block_requests(hba);
1270 mutex_lock(&hba->wb_mutex);
1271 down_write(&hba->clk_scaling_lock);
1273 if (!hba->clk_scaling.is_allowed ||
1274 ufshcd_wait_for_doorbell_clr(hba, timeout_us)) {
1276 up_write(&hba->clk_scaling_lock);
1277 mutex_unlock(&hba->wb_mutex);
1278 ufshcd_scsi_unblock_requests(hba);
1282 /* let's not get into low power until clock scaling is completed */
1289 static void ufshcd_clock_scaling_unprepare(struct ufs_hba *hba, int err, bool scale_up)
1291 up_write(&hba->clk_scaling_lock);
1293 /* Enable Write Booster if we have scaled up else disable it */
1294 if (ufshcd_enable_wb_if_scaling_up(hba) && !err)
1295 ufshcd_wb_toggle(hba, scale_up);
1297 mutex_unlock(&hba->wb_mutex);
1299 ufshcd_scsi_unblock_requests(hba);
1300 ufshcd_release(hba);
1304 * ufshcd_devfreq_scale - scale up/down UFS clocks and gear
1305 * @hba: per adapter instance
1306 * @scale_up: True for scaling up and false for scalin down
1308 * Return: 0 for success; -EBUSY if scaling can't happen at this time; non-zero
1309 * for any other errors.
1311 static int ufshcd_devfreq_scale(struct ufs_hba *hba, bool scale_up)
1315 ret = ufshcd_clock_scaling_prepare(hba, 1 * USEC_PER_SEC);
1319 /* scale down the gear before scaling down clocks */
1321 ret = ufshcd_scale_gear(hba, false);
1326 ret = ufshcd_scale_clks(hba, scale_up);
1329 ufshcd_scale_gear(hba, true);
1333 /* scale up the gear after scaling up clocks */
1335 ret = ufshcd_scale_gear(hba, true);
1337 ufshcd_scale_clks(hba, false);
1343 ufshcd_clock_scaling_unprepare(hba, ret, scale_up);
1347 static void ufshcd_clk_scaling_suspend_work(struct work_struct *work)
1349 struct ufs_hba *hba = container_of(work, struct ufs_hba,
1350 clk_scaling.suspend_work);
1351 unsigned long irq_flags;
1353 spin_lock_irqsave(hba->host->host_lock, irq_flags);
1354 if (hba->clk_scaling.active_reqs || hba->clk_scaling.is_suspended) {
1355 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1358 hba->clk_scaling.is_suspended = true;
1359 hba->clk_scaling.window_start_t = 0;
1360 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1362 devfreq_suspend_device(hba->devfreq);
1365 static void ufshcd_clk_scaling_resume_work(struct work_struct *work)
1367 struct ufs_hba *hba = container_of(work, struct ufs_hba,
1368 clk_scaling.resume_work);
1369 unsigned long irq_flags;
1371 spin_lock_irqsave(hba->host->host_lock, irq_flags);
1372 if (!hba->clk_scaling.is_suspended) {
1373 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1376 hba->clk_scaling.is_suspended = false;
1377 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1379 devfreq_resume_device(hba->devfreq);
1382 static int ufshcd_devfreq_target(struct device *dev,
1383 unsigned long *freq, u32 flags)
1386 struct ufs_hba *hba = dev_get_drvdata(dev);
1388 bool scale_up, sched_clk_scaling_suspend_work = false;
1389 struct list_head *clk_list = &hba->clk_list_head;
1390 struct ufs_clk_info *clki;
1391 unsigned long irq_flags;
1393 if (!ufshcd_is_clkscaling_supported(hba))
1396 clki = list_first_entry(&hba->clk_list_head, struct ufs_clk_info, list);
1397 /* Override with the closest supported frequency */
1398 *freq = (unsigned long) clk_round_rate(clki->clk, *freq);
1399 spin_lock_irqsave(hba->host->host_lock, irq_flags);
1400 if (ufshcd_eh_in_progress(hba)) {
1401 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1405 /* Skip scaling clock when clock scaling is suspended */
1406 if (hba->clk_scaling.is_suspended) {
1407 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1408 dev_warn(hba->dev, "clock scaling is suspended, skip");
1412 if (!hba->clk_scaling.active_reqs)
1413 sched_clk_scaling_suspend_work = true;
1415 if (list_empty(clk_list)) {
1416 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1420 /* Decide based on the rounded-off frequency and update */
1421 scale_up = *freq == clki->max_freq;
1423 *freq = clki->min_freq;
1424 /* Update the frequency */
1425 if (!ufshcd_is_devfreq_scaling_required(hba, scale_up)) {
1426 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1428 goto out; /* no state change required */
1430 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1432 start = ktime_get();
1433 ret = ufshcd_devfreq_scale(hba, scale_up);
1435 trace_ufshcd_profile_clk_scaling(dev_name(hba->dev),
1436 (scale_up ? "up" : "down"),
1437 ktime_to_us(ktime_sub(ktime_get(), start)), ret);
1440 if (sched_clk_scaling_suspend_work && !scale_up)
1441 queue_work(hba->clk_scaling.workq,
1442 &hba->clk_scaling.suspend_work);
1447 static int ufshcd_devfreq_get_dev_status(struct device *dev,
1448 struct devfreq_dev_status *stat)
1450 struct ufs_hba *hba = dev_get_drvdata(dev);
1451 struct ufs_clk_scaling *scaling = &hba->clk_scaling;
1452 unsigned long flags;
1453 struct list_head *clk_list = &hba->clk_list_head;
1454 struct ufs_clk_info *clki;
1457 if (!ufshcd_is_clkscaling_supported(hba))
1460 memset(stat, 0, sizeof(*stat));
1462 spin_lock_irqsave(hba->host->host_lock, flags);
1463 curr_t = ktime_get();
1464 if (!scaling->window_start_t)
1467 clki = list_first_entry(clk_list, struct ufs_clk_info, list);
1469 * If current frequency is 0, then the ondemand governor considers
1470 * there's no initial frequency set. And it always requests to set
1471 * to max. frequency.
1473 stat->current_frequency = clki->curr_freq;
1474 if (scaling->is_busy_started)
1475 scaling->tot_busy_t += ktime_us_delta(curr_t,
1476 scaling->busy_start_t);
1478 stat->total_time = ktime_us_delta(curr_t, scaling->window_start_t);
1479 stat->busy_time = scaling->tot_busy_t;
1481 scaling->window_start_t = curr_t;
1482 scaling->tot_busy_t = 0;
1484 if (scaling->active_reqs) {
1485 scaling->busy_start_t = curr_t;
1486 scaling->is_busy_started = true;
1488 scaling->busy_start_t = 0;
1489 scaling->is_busy_started = false;
1491 spin_unlock_irqrestore(hba->host->host_lock, flags);
1495 static int ufshcd_devfreq_init(struct ufs_hba *hba)
1497 struct list_head *clk_list = &hba->clk_list_head;
1498 struct ufs_clk_info *clki;
1499 struct devfreq *devfreq;
1502 /* Skip devfreq if we don't have any clocks in the list */
1503 if (list_empty(clk_list))
1506 clki = list_first_entry(clk_list, struct ufs_clk_info, list);
1507 dev_pm_opp_add(hba->dev, clki->min_freq, 0);
1508 dev_pm_opp_add(hba->dev, clki->max_freq, 0);
1510 ufshcd_vops_config_scaling_param(hba, &hba->vps->devfreq_profile,
1511 &hba->vps->ondemand_data);
1512 devfreq = devfreq_add_device(hba->dev,
1513 &hba->vps->devfreq_profile,
1514 DEVFREQ_GOV_SIMPLE_ONDEMAND,
1515 &hba->vps->ondemand_data);
1516 if (IS_ERR(devfreq)) {
1517 ret = PTR_ERR(devfreq);
1518 dev_err(hba->dev, "Unable to register with devfreq %d\n", ret);
1520 dev_pm_opp_remove(hba->dev, clki->min_freq);
1521 dev_pm_opp_remove(hba->dev, clki->max_freq);
1525 hba->devfreq = devfreq;
1530 static void ufshcd_devfreq_remove(struct ufs_hba *hba)
1532 struct list_head *clk_list = &hba->clk_list_head;
1533 struct ufs_clk_info *clki;
1538 devfreq_remove_device(hba->devfreq);
1539 hba->devfreq = NULL;
1541 clki = list_first_entry(clk_list, struct ufs_clk_info, list);
1542 dev_pm_opp_remove(hba->dev, clki->min_freq);
1543 dev_pm_opp_remove(hba->dev, clki->max_freq);
1546 static void ufshcd_suspend_clkscaling(struct ufs_hba *hba)
1548 unsigned long flags;
1549 bool suspend = false;
1551 cancel_work_sync(&hba->clk_scaling.suspend_work);
1552 cancel_work_sync(&hba->clk_scaling.resume_work);
1554 spin_lock_irqsave(hba->host->host_lock, flags);
1555 if (!hba->clk_scaling.is_suspended) {
1557 hba->clk_scaling.is_suspended = true;
1558 hba->clk_scaling.window_start_t = 0;
1560 spin_unlock_irqrestore(hba->host->host_lock, flags);
1563 devfreq_suspend_device(hba->devfreq);
1566 static void ufshcd_resume_clkscaling(struct ufs_hba *hba)
1568 unsigned long flags;
1569 bool resume = false;
1571 spin_lock_irqsave(hba->host->host_lock, flags);
1572 if (hba->clk_scaling.is_suspended) {
1574 hba->clk_scaling.is_suspended = false;
1576 spin_unlock_irqrestore(hba->host->host_lock, flags);
1579 devfreq_resume_device(hba->devfreq);
1582 static ssize_t ufshcd_clkscale_enable_show(struct device *dev,
1583 struct device_attribute *attr, char *buf)
1585 struct ufs_hba *hba = dev_get_drvdata(dev);
1587 return sysfs_emit(buf, "%d\n", hba->clk_scaling.is_enabled);
1590 static ssize_t ufshcd_clkscale_enable_store(struct device *dev,
1591 struct device_attribute *attr, const char *buf, size_t count)
1593 struct ufs_hba *hba = dev_get_drvdata(dev);
1597 if (kstrtou32(buf, 0, &value))
1600 down(&hba->host_sem);
1601 if (!ufshcd_is_user_access_allowed(hba)) {
1607 if (value == hba->clk_scaling.is_enabled)
1610 ufshcd_rpm_get_sync(hba);
1613 hba->clk_scaling.is_enabled = value;
1616 ufshcd_resume_clkscaling(hba);
1618 ufshcd_suspend_clkscaling(hba);
1619 err = ufshcd_devfreq_scale(hba, true);
1621 dev_err(hba->dev, "%s: failed to scale clocks up %d\n",
1625 ufshcd_release(hba);
1626 ufshcd_rpm_put_sync(hba);
1629 return err ? err : count;
1632 static void ufshcd_init_clk_scaling_sysfs(struct ufs_hba *hba)
1634 hba->clk_scaling.enable_attr.show = ufshcd_clkscale_enable_show;
1635 hba->clk_scaling.enable_attr.store = ufshcd_clkscale_enable_store;
1636 sysfs_attr_init(&hba->clk_scaling.enable_attr.attr);
1637 hba->clk_scaling.enable_attr.attr.name = "clkscale_enable";
1638 hba->clk_scaling.enable_attr.attr.mode = 0644;
1639 if (device_create_file(hba->dev, &hba->clk_scaling.enable_attr))
1640 dev_err(hba->dev, "Failed to create sysfs for clkscale_enable\n");
1643 static void ufshcd_remove_clk_scaling_sysfs(struct ufs_hba *hba)
1645 if (hba->clk_scaling.enable_attr.attr.name)
1646 device_remove_file(hba->dev, &hba->clk_scaling.enable_attr);
1649 static void ufshcd_init_clk_scaling(struct ufs_hba *hba)
1651 char wq_name[sizeof("ufs_clkscaling_00")];
1653 if (!ufshcd_is_clkscaling_supported(hba))
1656 if (!hba->clk_scaling.min_gear)
1657 hba->clk_scaling.min_gear = UFS_HS_G1;
1659 INIT_WORK(&hba->clk_scaling.suspend_work,
1660 ufshcd_clk_scaling_suspend_work);
1661 INIT_WORK(&hba->clk_scaling.resume_work,
1662 ufshcd_clk_scaling_resume_work);
1664 snprintf(wq_name, sizeof(wq_name), "ufs_clkscaling_%d",
1665 hba->host->host_no);
1666 hba->clk_scaling.workq = create_singlethread_workqueue(wq_name);
1668 hba->clk_scaling.is_initialized = true;
1671 static void ufshcd_exit_clk_scaling(struct ufs_hba *hba)
1673 if (!hba->clk_scaling.is_initialized)
1676 ufshcd_remove_clk_scaling_sysfs(hba);
1677 destroy_workqueue(hba->clk_scaling.workq);
1678 ufshcd_devfreq_remove(hba);
1679 hba->clk_scaling.is_initialized = false;
1682 static void ufshcd_ungate_work(struct work_struct *work)
1685 unsigned long flags;
1686 struct ufs_hba *hba = container_of(work, struct ufs_hba,
1687 clk_gating.ungate_work);
1689 cancel_delayed_work_sync(&hba->clk_gating.gate_work);
1691 spin_lock_irqsave(hba->host->host_lock, flags);
1692 if (hba->clk_gating.state == CLKS_ON) {
1693 spin_unlock_irqrestore(hba->host->host_lock, flags);
1697 spin_unlock_irqrestore(hba->host->host_lock, flags);
1698 ufshcd_hba_vreg_set_hpm(hba);
1699 ufshcd_setup_clocks(hba, true);
1701 ufshcd_enable_irq(hba);
1703 /* Exit from hibern8 */
1704 if (ufshcd_can_hibern8_during_gating(hba)) {
1705 /* Prevent gating in this path */
1706 hba->clk_gating.is_suspended = true;
1707 if (ufshcd_is_link_hibern8(hba)) {
1708 ret = ufshcd_uic_hibern8_exit(hba);
1710 dev_err(hba->dev, "%s: hibern8 exit failed %d\n",
1713 ufshcd_set_link_active(hba);
1715 hba->clk_gating.is_suspended = false;
1720 * ufshcd_hold - Enable clocks that were gated earlier due to ufshcd_release.
1721 * Also, exit from hibern8 mode and set the link as active.
1722 * @hba: per adapter instance
1724 void ufshcd_hold(struct ufs_hba *hba)
1727 unsigned long flags;
1729 if (!ufshcd_is_clkgating_allowed(hba) ||
1730 !hba->clk_gating.is_initialized)
1732 spin_lock_irqsave(hba->host->host_lock, flags);
1733 hba->clk_gating.active_reqs++;
1736 switch (hba->clk_gating.state) {
1739 * Wait for the ungate work to complete if in progress.
1740 * Though the clocks may be in ON state, the link could
1741 * still be in hibner8 state if hibern8 is allowed
1742 * during clock gating.
1743 * Make sure we exit hibern8 state also in addition to
1746 if (ufshcd_can_hibern8_during_gating(hba) &&
1747 ufshcd_is_link_hibern8(hba)) {
1748 spin_unlock_irqrestore(hba->host->host_lock, flags);
1749 flush_result = flush_work(&hba->clk_gating.ungate_work);
1750 if (hba->clk_gating.is_suspended && !flush_result)
1752 spin_lock_irqsave(hba->host->host_lock, flags);
1757 if (cancel_delayed_work(&hba->clk_gating.gate_work)) {
1758 hba->clk_gating.state = CLKS_ON;
1759 trace_ufshcd_clk_gating(dev_name(hba->dev),
1760 hba->clk_gating.state);
1764 * If we are here, it means gating work is either done or
1765 * currently running. Hence, fall through to cancel gating
1766 * work and to enable clocks.
1770 hba->clk_gating.state = REQ_CLKS_ON;
1771 trace_ufshcd_clk_gating(dev_name(hba->dev),
1772 hba->clk_gating.state);
1773 queue_work(hba->clk_gating.clk_gating_workq,
1774 &hba->clk_gating.ungate_work);
1776 * fall through to check if we should wait for this
1777 * work to be done or not.
1781 spin_unlock_irqrestore(hba->host->host_lock, flags);
1782 flush_work(&hba->clk_gating.ungate_work);
1783 /* Make sure state is CLKS_ON before returning */
1784 spin_lock_irqsave(hba->host->host_lock, flags);
1787 dev_err(hba->dev, "%s: clk gating is in invalid state %d\n",
1788 __func__, hba->clk_gating.state);
1791 spin_unlock_irqrestore(hba->host->host_lock, flags);
1793 EXPORT_SYMBOL_GPL(ufshcd_hold);
1795 static void ufshcd_gate_work(struct work_struct *work)
1797 struct ufs_hba *hba = container_of(work, struct ufs_hba,
1798 clk_gating.gate_work.work);
1799 unsigned long flags;
1802 spin_lock_irqsave(hba->host->host_lock, flags);
1804 * In case you are here to cancel this work the gating state
1805 * would be marked as REQ_CLKS_ON. In this case save time by
1806 * skipping the gating work and exit after changing the clock
1809 if (hba->clk_gating.is_suspended ||
1810 (hba->clk_gating.state != REQ_CLKS_OFF)) {
1811 hba->clk_gating.state = CLKS_ON;
1812 trace_ufshcd_clk_gating(dev_name(hba->dev),
1813 hba->clk_gating.state);
1817 if (hba->clk_gating.active_reqs
1818 || hba->ufshcd_state != UFSHCD_STATE_OPERATIONAL
1819 || hba->outstanding_reqs || hba->outstanding_tasks
1820 || hba->active_uic_cmd || hba->uic_async_done)
1823 spin_unlock_irqrestore(hba->host->host_lock, flags);
1825 /* put the link into hibern8 mode before turning off clocks */
1826 if (ufshcd_can_hibern8_during_gating(hba)) {
1827 ret = ufshcd_uic_hibern8_enter(hba);
1829 hba->clk_gating.state = CLKS_ON;
1830 dev_err(hba->dev, "%s: hibern8 enter failed %d\n",
1832 trace_ufshcd_clk_gating(dev_name(hba->dev),
1833 hba->clk_gating.state);
1836 ufshcd_set_link_hibern8(hba);
1839 ufshcd_disable_irq(hba);
1841 ufshcd_setup_clocks(hba, false);
1843 /* Put the host controller in low power mode if possible */
1844 ufshcd_hba_vreg_set_lpm(hba);
1846 * In case you are here to cancel this work the gating state
1847 * would be marked as REQ_CLKS_ON. In this case keep the state
1848 * as REQ_CLKS_ON which would anyway imply that clocks are off
1849 * and a request to turn them on is pending. By doing this way,
1850 * we keep the state machine in tact and this would ultimately
1851 * prevent from doing cancel work multiple times when there are
1852 * new requests arriving before the current cancel work is done.
1854 spin_lock_irqsave(hba->host->host_lock, flags);
1855 if (hba->clk_gating.state == REQ_CLKS_OFF) {
1856 hba->clk_gating.state = CLKS_OFF;
1857 trace_ufshcd_clk_gating(dev_name(hba->dev),
1858 hba->clk_gating.state);
1861 spin_unlock_irqrestore(hba->host->host_lock, flags);
1866 /* host lock must be held before calling this variant */
1867 static void __ufshcd_release(struct ufs_hba *hba)
1869 if (!ufshcd_is_clkgating_allowed(hba))
1872 hba->clk_gating.active_reqs--;
1874 if (hba->clk_gating.active_reqs || hba->clk_gating.is_suspended ||
1875 hba->ufshcd_state != UFSHCD_STATE_OPERATIONAL ||
1876 hba->outstanding_tasks || !hba->clk_gating.is_initialized ||
1877 hba->active_uic_cmd || hba->uic_async_done ||
1878 hba->clk_gating.state == CLKS_OFF)
1881 hba->clk_gating.state = REQ_CLKS_OFF;
1882 trace_ufshcd_clk_gating(dev_name(hba->dev), hba->clk_gating.state);
1883 queue_delayed_work(hba->clk_gating.clk_gating_workq,
1884 &hba->clk_gating.gate_work,
1885 msecs_to_jiffies(hba->clk_gating.delay_ms));
1888 void ufshcd_release(struct ufs_hba *hba)
1890 unsigned long flags;
1892 spin_lock_irqsave(hba->host->host_lock, flags);
1893 __ufshcd_release(hba);
1894 spin_unlock_irqrestore(hba->host->host_lock, flags);
1896 EXPORT_SYMBOL_GPL(ufshcd_release);
1898 static ssize_t ufshcd_clkgate_delay_show(struct device *dev,
1899 struct device_attribute *attr, char *buf)
1901 struct ufs_hba *hba = dev_get_drvdata(dev);
1903 return sysfs_emit(buf, "%lu\n", hba->clk_gating.delay_ms);
1906 void ufshcd_clkgate_delay_set(struct device *dev, unsigned long value)
1908 struct ufs_hba *hba = dev_get_drvdata(dev);
1909 unsigned long flags;
1911 spin_lock_irqsave(hba->host->host_lock, flags);
1912 hba->clk_gating.delay_ms = value;
1913 spin_unlock_irqrestore(hba->host->host_lock, flags);
1915 EXPORT_SYMBOL_GPL(ufshcd_clkgate_delay_set);
1917 static ssize_t ufshcd_clkgate_delay_store(struct device *dev,
1918 struct device_attribute *attr, const char *buf, size_t count)
1920 unsigned long value;
1922 if (kstrtoul(buf, 0, &value))
1925 ufshcd_clkgate_delay_set(dev, value);
1929 static ssize_t ufshcd_clkgate_enable_show(struct device *dev,
1930 struct device_attribute *attr, char *buf)
1932 struct ufs_hba *hba = dev_get_drvdata(dev);
1934 return sysfs_emit(buf, "%d\n", hba->clk_gating.is_enabled);
1937 static ssize_t ufshcd_clkgate_enable_store(struct device *dev,
1938 struct device_attribute *attr, const char *buf, size_t count)
1940 struct ufs_hba *hba = dev_get_drvdata(dev);
1941 unsigned long flags;
1944 if (kstrtou32(buf, 0, &value))
1949 spin_lock_irqsave(hba->host->host_lock, flags);
1950 if (value == hba->clk_gating.is_enabled)
1954 __ufshcd_release(hba);
1956 hba->clk_gating.active_reqs++;
1958 hba->clk_gating.is_enabled = value;
1960 spin_unlock_irqrestore(hba->host->host_lock, flags);
1964 static void ufshcd_init_clk_gating_sysfs(struct ufs_hba *hba)
1966 hba->clk_gating.delay_attr.show = ufshcd_clkgate_delay_show;
1967 hba->clk_gating.delay_attr.store = ufshcd_clkgate_delay_store;
1968 sysfs_attr_init(&hba->clk_gating.delay_attr.attr);
1969 hba->clk_gating.delay_attr.attr.name = "clkgate_delay_ms";
1970 hba->clk_gating.delay_attr.attr.mode = 0644;
1971 if (device_create_file(hba->dev, &hba->clk_gating.delay_attr))
1972 dev_err(hba->dev, "Failed to create sysfs for clkgate_delay\n");
1974 hba->clk_gating.enable_attr.show = ufshcd_clkgate_enable_show;
1975 hba->clk_gating.enable_attr.store = ufshcd_clkgate_enable_store;
1976 sysfs_attr_init(&hba->clk_gating.enable_attr.attr);
1977 hba->clk_gating.enable_attr.attr.name = "clkgate_enable";
1978 hba->clk_gating.enable_attr.attr.mode = 0644;
1979 if (device_create_file(hba->dev, &hba->clk_gating.enable_attr))
1980 dev_err(hba->dev, "Failed to create sysfs for clkgate_enable\n");
1983 static void ufshcd_remove_clk_gating_sysfs(struct ufs_hba *hba)
1985 if (hba->clk_gating.delay_attr.attr.name)
1986 device_remove_file(hba->dev, &hba->clk_gating.delay_attr);
1987 if (hba->clk_gating.enable_attr.attr.name)
1988 device_remove_file(hba->dev, &hba->clk_gating.enable_attr);
1991 static void ufshcd_init_clk_gating(struct ufs_hba *hba)
1993 char wq_name[sizeof("ufs_clk_gating_00")];
1995 if (!ufshcd_is_clkgating_allowed(hba))
1998 hba->clk_gating.state = CLKS_ON;
2000 hba->clk_gating.delay_ms = 150;
2001 INIT_DELAYED_WORK(&hba->clk_gating.gate_work, ufshcd_gate_work);
2002 INIT_WORK(&hba->clk_gating.ungate_work, ufshcd_ungate_work);
2004 snprintf(wq_name, ARRAY_SIZE(wq_name), "ufs_clk_gating_%d",
2005 hba->host->host_no);
2006 hba->clk_gating.clk_gating_workq = alloc_ordered_workqueue(wq_name,
2007 WQ_MEM_RECLAIM | WQ_HIGHPRI);
2009 ufshcd_init_clk_gating_sysfs(hba);
2011 hba->clk_gating.is_enabled = true;
2012 hba->clk_gating.is_initialized = true;
2015 static void ufshcd_exit_clk_gating(struct ufs_hba *hba)
2017 if (!hba->clk_gating.is_initialized)
2020 ufshcd_remove_clk_gating_sysfs(hba);
2022 /* Ungate the clock if necessary. */
2024 hba->clk_gating.is_initialized = false;
2025 ufshcd_release(hba);
2027 destroy_workqueue(hba->clk_gating.clk_gating_workq);
2030 static void ufshcd_clk_scaling_start_busy(struct ufs_hba *hba)
2032 bool queue_resume_work = false;
2033 ktime_t curr_t = ktime_get();
2034 unsigned long flags;
2036 if (!ufshcd_is_clkscaling_supported(hba))
2039 spin_lock_irqsave(hba->host->host_lock, flags);
2040 if (!hba->clk_scaling.active_reqs++)
2041 queue_resume_work = true;
2043 if (!hba->clk_scaling.is_enabled || hba->pm_op_in_progress) {
2044 spin_unlock_irqrestore(hba->host->host_lock, flags);
2048 if (queue_resume_work)
2049 queue_work(hba->clk_scaling.workq,
2050 &hba->clk_scaling.resume_work);
2052 if (!hba->clk_scaling.window_start_t) {
2053 hba->clk_scaling.window_start_t = curr_t;
2054 hba->clk_scaling.tot_busy_t = 0;
2055 hba->clk_scaling.is_busy_started = false;
2058 if (!hba->clk_scaling.is_busy_started) {
2059 hba->clk_scaling.busy_start_t = curr_t;
2060 hba->clk_scaling.is_busy_started = true;
2062 spin_unlock_irqrestore(hba->host->host_lock, flags);
2065 static void ufshcd_clk_scaling_update_busy(struct ufs_hba *hba)
2067 struct ufs_clk_scaling *scaling = &hba->clk_scaling;
2068 unsigned long flags;
2070 if (!ufshcd_is_clkscaling_supported(hba))
2073 spin_lock_irqsave(hba->host->host_lock, flags);
2074 hba->clk_scaling.active_reqs--;
2075 if (!scaling->active_reqs && scaling->is_busy_started) {
2076 scaling->tot_busy_t += ktime_to_us(ktime_sub(ktime_get(),
2077 scaling->busy_start_t));
2078 scaling->busy_start_t = 0;
2079 scaling->is_busy_started = false;
2081 spin_unlock_irqrestore(hba->host->host_lock, flags);
2084 static inline int ufshcd_monitor_opcode2dir(u8 opcode)
2086 if (opcode == READ_6 || opcode == READ_10 || opcode == READ_16)
2088 else if (opcode == WRITE_6 || opcode == WRITE_10 || opcode == WRITE_16)
2094 static inline bool ufshcd_should_inform_monitor(struct ufs_hba *hba,
2095 struct ufshcd_lrb *lrbp)
2097 const struct ufs_hba_monitor *m = &hba->monitor;
2099 return (m->enabled && lrbp && lrbp->cmd &&
2100 (!m->chunk_size || m->chunk_size == lrbp->cmd->sdb.length) &&
2101 ktime_before(hba->monitor.enabled_ts, lrbp->issue_time_stamp));
2104 static void ufshcd_start_monitor(struct ufs_hba *hba,
2105 const struct ufshcd_lrb *lrbp)
2107 int dir = ufshcd_monitor_opcode2dir(*lrbp->cmd->cmnd);
2108 unsigned long flags;
2110 spin_lock_irqsave(hba->host->host_lock, flags);
2111 if (dir >= 0 && hba->monitor.nr_queued[dir]++ == 0)
2112 hba->monitor.busy_start_ts[dir] = ktime_get();
2113 spin_unlock_irqrestore(hba->host->host_lock, flags);
2116 static void ufshcd_update_monitor(struct ufs_hba *hba, const struct ufshcd_lrb *lrbp)
2118 int dir = ufshcd_monitor_opcode2dir(*lrbp->cmd->cmnd);
2119 unsigned long flags;
2121 spin_lock_irqsave(hba->host->host_lock, flags);
2122 if (dir >= 0 && hba->monitor.nr_queued[dir] > 0) {
2123 const struct request *req = scsi_cmd_to_rq(lrbp->cmd);
2124 struct ufs_hba_monitor *m = &hba->monitor;
2125 ktime_t now, inc, lat;
2127 now = lrbp->compl_time_stamp;
2128 inc = ktime_sub(now, m->busy_start_ts[dir]);
2129 m->total_busy[dir] = ktime_add(m->total_busy[dir], inc);
2130 m->nr_sec_rw[dir] += blk_rq_sectors(req);
2132 /* Update latencies */
2134 lat = ktime_sub(now, lrbp->issue_time_stamp);
2135 m->lat_sum[dir] += lat;
2136 if (m->lat_max[dir] < lat || !m->lat_max[dir])
2137 m->lat_max[dir] = lat;
2138 if (m->lat_min[dir] > lat || !m->lat_min[dir])
2139 m->lat_min[dir] = lat;
2141 m->nr_queued[dir]--;
2142 /* Push forward the busy start of monitor */
2143 m->busy_start_ts[dir] = now;
2145 spin_unlock_irqrestore(hba->host->host_lock, flags);
2149 * ufshcd_send_command - Send SCSI or device management commands
2150 * @hba: per adapter instance
2151 * @task_tag: Task tag of the command
2152 * @hwq: pointer to hardware queue instance
2155 void ufshcd_send_command(struct ufs_hba *hba, unsigned int task_tag,
2156 struct ufs_hw_queue *hwq)
2158 struct ufshcd_lrb *lrbp = &hba->lrb[task_tag];
2159 unsigned long flags;
2161 lrbp->issue_time_stamp = ktime_get();
2162 lrbp->issue_time_stamp_local_clock = local_clock();
2163 lrbp->compl_time_stamp = ktime_set(0, 0);
2164 lrbp->compl_time_stamp_local_clock = 0;
2165 ufshcd_add_command_trace(hba, task_tag, UFS_CMD_SEND);
2167 ufshcd_clk_scaling_start_busy(hba);
2168 if (unlikely(ufshcd_should_inform_monitor(hba, lrbp)))
2169 ufshcd_start_monitor(hba, lrbp);
2171 if (is_mcq_enabled(hba)) {
2172 int utrd_size = sizeof(struct utp_transfer_req_desc);
2173 struct utp_transfer_req_desc *src = lrbp->utr_descriptor_ptr;
2174 struct utp_transfer_req_desc *dest = hwq->sqe_base_addr + hwq->sq_tail_slot;
2176 spin_lock(&hwq->sq_lock);
2177 memcpy(dest, src, utrd_size);
2178 ufshcd_inc_sq_tail(hwq);
2179 spin_unlock(&hwq->sq_lock);
2181 spin_lock_irqsave(&hba->outstanding_lock, flags);
2182 if (hba->vops && hba->vops->setup_xfer_req)
2183 hba->vops->setup_xfer_req(hba, lrbp->task_tag,
2185 __set_bit(lrbp->task_tag, &hba->outstanding_reqs);
2186 ufshcd_writel(hba, 1 << lrbp->task_tag,
2187 REG_UTP_TRANSFER_REQ_DOOR_BELL);
2188 spin_unlock_irqrestore(&hba->outstanding_lock, flags);
2193 * ufshcd_copy_sense_data - Copy sense data in case of check condition
2194 * @lrbp: pointer to local reference block
2196 static inline void ufshcd_copy_sense_data(struct ufshcd_lrb *lrbp)
2198 u8 *const sense_buffer = lrbp->cmd->sense_buffer;
2202 resp_len = be16_to_cpu(lrbp->ucd_rsp_ptr->header.data_segment_length);
2203 if (sense_buffer && resp_len) {
2206 len = be16_to_cpu(lrbp->ucd_rsp_ptr->sr.sense_data_len);
2207 len_to_copy = min_t(int, UFS_SENSE_SIZE, len);
2209 memcpy(sense_buffer, lrbp->ucd_rsp_ptr->sr.sense_data,
2215 * ufshcd_copy_query_response() - Copy the Query Response and the data
2217 * @hba: per adapter instance
2218 * @lrbp: pointer to local reference block
2220 * Return: 0 upon success; < 0 upon failure.
2223 int ufshcd_copy_query_response(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
2225 struct ufs_query_res *query_res = &hba->dev_cmd.query.response;
2227 memcpy(&query_res->upiu_res, &lrbp->ucd_rsp_ptr->qr, QUERY_OSF_SIZE);
2229 /* Get the descriptor */
2230 if (hba->dev_cmd.query.descriptor &&
2231 lrbp->ucd_rsp_ptr->qr.opcode == UPIU_QUERY_OPCODE_READ_DESC) {
2232 u8 *descp = (u8 *)lrbp->ucd_rsp_ptr +
2233 GENERAL_UPIU_REQUEST_SIZE;
2237 /* data segment length */
2238 resp_len = be16_to_cpu(lrbp->ucd_rsp_ptr->header
2239 .data_segment_length);
2240 buf_len = be16_to_cpu(
2241 hba->dev_cmd.query.request.upiu_req.length);
2242 if (likely(buf_len >= resp_len)) {
2243 memcpy(hba->dev_cmd.query.descriptor, descp, resp_len);
2246 "%s: rsp size %d is bigger than buffer size %d",
2247 __func__, resp_len, buf_len);
2256 * ufshcd_hba_capabilities - Read controller capabilities
2257 * @hba: per adapter instance
2259 * Return: 0 on success, negative on error.
2261 static inline int ufshcd_hba_capabilities(struct ufs_hba *hba)
2265 hba->capabilities = ufshcd_readl(hba, REG_CONTROLLER_CAPABILITIES);
2266 if (hba->quirks & UFSHCD_QUIRK_BROKEN_64BIT_ADDRESS)
2267 hba->capabilities &= ~MASK_64_ADDRESSING_SUPPORT;
2269 /* nutrs and nutmrs are 0 based values */
2270 hba->nutrs = (hba->capabilities & MASK_TRANSFER_REQUESTS_SLOTS) + 1;
2272 ((hba->capabilities & MASK_TASK_MANAGEMENT_REQUEST_SLOTS) >> 16) + 1;
2273 hba->reserved_slot = hba->nutrs - 1;
2275 /* Read crypto capabilities */
2276 err = ufshcd_hba_init_crypto_capabilities(hba);
2278 dev_err(hba->dev, "crypto setup failed\n");
2282 hba->mcq_sup = FIELD_GET(MASK_MCQ_SUPPORT, hba->capabilities);
2286 hba->mcq_capabilities = ufshcd_readl(hba, REG_MCQCAP);
2287 hba->ext_iid_sup = FIELD_GET(MASK_EXT_IID_SUPPORT,
2288 hba->mcq_capabilities);
2294 * ufshcd_ready_for_uic_cmd - Check if controller is ready
2295 * to accept UIC commands
2296 * @hba: per adapter instance
2298 * Return: true on success, else false.
2300 static inline bool ufshcd_ready_for_uic_cmd(struct ufs_hba *hba)
2303 int ret = read_poll_timeout(ufshcd_readl, val, val & UIC_COMMAND_READY,
2304 500, UIC_CMD_TIMEOUT * 1000, false, hba,
2305 REG_CONTROLLER_STATUS);
2306 return ret == 0 ? true : false;
2310 * ufshcd_get_upmcrs - Get the power mode change request status
2311 * @hba: Pointer to adapter instance
2313 * This function gets the UPMCRS field of HCS register
2315 * Return: value of UPMCRS field.
2317 static inline u8 ufshcd_get_upmcrs(struct ufs_hba *hba)
2319 return (ufshcd_readl(hba, REG_CONTROLLER_STATUS) >> 8) & 0x7;
2323 * ufshcd_dispatch_uic_cmd - Dispatch an UIC command to the Unipro layer
2324 * @hba: per adapter instance
2325 * @uic_cmd: UIC command
2328 ufshcd_dispatch_uic_cmd(struct ufs_hba *hba, struct uic_command *uic_cmd)
2330 lockdep_assert_held(&hba->uic_cmd_mutex);
2332 WARN_ON(hba->active_uic_cmd);
2334 hba->active_uic_cmd = uic_cmd;
2337 ufshcd_writel(hba, uic_cmd->argument1, REG_UIC_COMMAND_ARG_1);
2338 ufshcd_writel(hba, uic_cmd->argument2, REG_UIC_COMMAND_ARG_2);
2339 ufshcd_writel(hba, uic_cmd->argument3, REG_UIC_COMMAND_ARG_3);
2341 ufshcd_add_uic_command_trace(hba, uic_cmd, UFS_CMD_SEND);
2344 ufshcd_writel(hba, uic_cmd->command & COMMAND_OPCODE_MASK,
2349 * ufshcd_wait_for_uic_cmd - Wait for completion of an UIC command
2350 * @hba: per adapter instance
2351 * @uic_cmd: UIC command
2353 * Return: 0 only if success.
2356 ufshcd_wait_for_uic_cmd(struct ufs_hba *hba, struct uic_command *uic_cmd)
2359 unsigned long flags;
2361 lockdep_assert_held(&hba->uic_cmd_mutex);
2363 if (wait_for_completion_timeout(&uic_cmd->done,
2364 msecs_to_jiffies(UIC_CMD_TIMEOUT))) {
2365 ret = uic_cmd->argument2 & MASK_UIC_COMMAND_RESULT;
2369 "uic cmd 0x%x with arg3 0x%x completion timeout\n",
2370 uic_cmd->command, uic_cmd->argument3);
2372 if (!uic_cmd->cmd_active) {
2373 dev_err(hba->dev, "%s: UIC cmd has been completed, return the result\n",
2375 ret = uic_cmd->argument2 & MASK_UIC_COMMAND_RESULT;
2379 spin_lock_irqsave(hba->host->host_lock, flags);
2380 hba->active_uic_cmd = NULL;
2381 spin_unlock_irqrestore(hba->host->host_lock, flags);
2387 * __ufshcd_send_uic_cmd - Send UIC commands and retrieve the result
2388 * @hba: per adapter instance
2389 * @uic_cmd: UIC command
2390 * @completion: initialize the completion only if this is set to true
2392 * Return: 0 only if success.
2395 __ufshcd_send_uic_cmd(struct ufs_hba *hba, struct uic_command *uic_cmd,
2398 lockdep_assert_held(&hba->uic_cmd_mutex);
2400 if (!ufshcd_ready_for_uic_cmd(hba)) {
2402 "Controller not ready to accept UIC commands\n");
2407 init_completion(&uic_cmd->done);
2409 uic_cmd->cmd_active = 1;
2410 ufshcd_dispatch_uic_cmd(hba, uic_cmd);
2416 * ufshcd_send_uic_cmd - Send UIC commands and retrieve the result
2417 * @hba: per adapter instance
2418 * @uic_cmd: UIC command
2420 * Return: 0 only if success.
2422 int ufshcd_send_uic_cmd(struct ufs_hba *hba, struct uic_command *uic_cmd)
2426 if (hba->quirks & UFSHCD_QUIRK_BROKEN_UIC_CMD)
2430 mutex_lock(&hba->uic_cmd_mutex);
2431 ufshcd_add_delay_before_dme_cmd(hba);
2433 ret = __ufshcd_send_uic_cmd(hba, uic_cmd, true);
2435 ret = ufshcd_wait_for_uic_cmd(hba, uic_cmd);
2437 mutex_unlock(&hba->uic_cmd_mutex);
2439 ufshcd_release(hba);
2444 * ufshcd_sgl_to_prdt - SG list to PRTD (Physical Region Description Table, 4DW format)
2445 * @hba: per-adapter instance
2446 * @lrbp: pointer to local reference block
2447 * @sg_entries: The number of sg lists actually used
2448 * @sg_list: Pointer to SG list
2450 static void ufshcd_sgl_to_prdt(struct ufs_hba *hba, struct ufshcd_lrb *lrbp, int sg_entries,
2451 struct scatterlist *sg_list)
2453 struct ufshcd_sg_entry *prd;
2454 struct scatterlist *sg;
2459 if (hba->quirks & UFSHCD_QUIRK_PRDT_BYTE_GRAN)
2460 lrbp->utr_descriptor_ptr->prd_table_length =
2461 cpu_to_le16(sg_entries * ufshcd_sg_entry_size(hba));
2463 lrbp->utr_descriptor_ptr->prd_table_length = cpu_to_le16(sg_entries);
2465 prd = lrbp->ucd_prdt_ptr;
2467 for_each_sg(sg_list, sg, sg_entries, i) {
2468 const unsigned int len = sg_dma_len(sg);
2471 * From the UFSHCI spec: "Data Byte Count (DBC): A '0'
2472 * based value that indicates the length, in bytes, of
2473 * the data block. A maximum of length of 256KB may
2474 * exist for any entry. Bits 1:0 of this field shall be
2475 * 11b to indicate Dword granularity. A value of '3'
2476 * indicates 4 bytes, '7' indicates 8 bytes, etc."
2478 WARN_ONCE(len > SZ_256K, "len = %#x\n", len);
2479 prd->size = cpu_to_le32(len - 1);
2480 prd->addr = cpu_to_le64(sg->dma_address);
2482 prd = (void *)prd + ufshcd_sg_entry_size(hba);
2485 lrbp->utr_descriptor_ptr->prd_table_length = 0;
2490 * ufshcd_map_sg - Map scatter-gather list to prdt
2491 * @hba: per adapter instance
2492 * @lrbp: pointer to local reference block
2494 * Return: 0 in case of success, non-zero value in case of failure.
2496 static int ufshcd_map_sg(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
2498 struct scsi_cmnd *cmd = lrbp->cmd;
2499 int sg_segments = scsi_dma_map(cmd);
2501 if (sg_segments < 0)
2504 ufshcd_sgl_to_prdt(hba, lrbp, sg_segments, scsi_sglist(cmd));
2510 * ufshcd_enable_intr - enable interrupts
2511 * @hba: per adapter instance
2512 * @intrs: interrupt bits
2514 static void ufshcd_enable_intr(struct ufs_hba *hba, u32 intrs)
2516 u32 set = ufshcd_readl(hba, REG_INTERRUPT_ENABLE);
2518 if (hba->ufs_version == ufshci_version(1, 0)) {
2520 rw = set & INTERRUPT_MASK_RW_VER_10;
2521 set = rw | ((set ^ intrs) & intrs);
2526 ufshcd_writel(hba, set, REG_INTERRUPT_ENABLE);
2530 * ufshcd_disable_intr - disable interrupts
2531 * @hba: per adapter instance
2532 * @intrs: interrupt bits
2534 static void ufshcd_disable_intr(struct ufs_hba *hba, u32 intrs)
2536 u32 set = ufshcd_readl(hba, REG_INTERRUPT_ENABLE);
2538 if (hba->ufs_version == ufshci_version(1, 0)) {
2540 rw = (set & INTERRUPT_MASK_RW_VER_10) &
2541 ~(intrs & INTERRUPT_MASK_RW_VER_10);
2542 set = rw | ((set & intrs) & ~INTERRUPT_MASK_RW_VER_10);
2548 ufshcd_writel(hba, set, REG_INTERRUPT_ENABLE);
2552 * ufshcd_prepare_req_desc_hdr - Fill UTP Transfer request descriptor header according to request
2553 * descriptor according to request
2554 * @lrbp: pointer to local reference block
2555 * @upiu_flags: flags required in the header
2556 * @cmd_dir: requests data direction
2557 * @ehs_length: Total EHS Length (in 32‐bytes units of all Extra Header Segments)
2559 static void ufshcd_prepare_req_desc_hdr(struct ufshcd_lrb *lrbp, u8 *upiu_flags,
2560 enum dma_data_direction cmd_dir, int ehs_length)
2562 struct utp_transfer_req_desc *req_desc = lrbp->utr_descriptor_ptr;
2563 struct request_desc_header *h = &req_desc->header;
2564 enum utp_data_direction data_direction;
2566 *h = (typeof(*h)){ };
2568 if (cmd_dir == DMA_FROM_DEVICE) {
2569 data_direction = UTP_DEVICE_TO_HOST;
2570 *upiu_flags = UPIU_CMD_FLAGS_READ;
2571 } else if (cmd_dir == DMA_TO_DEVICE) {
2572 data_direction = UTP_HOST_TO_DEVICE;
2573 *upiu_flags = UPIU_CMD_FLAGS_WRITE;
2575 data_direction = UTP_NO_DATA_TRANSFER;
2576 *upiu_flags = UPIU_CMD_FLAGS_NONE;
2579 h->command_type = lrbp->command_type;
2580 h->data_direction = data_direction;
2581 h->ehs_length = ehs_length;
2586 /* Prepare crypto related dwords */
2587 ufshcd_prepare_req_desc_hdr_crypto(lrbp, h);
2590 * assigning invalid value for command status. Controller
2591 * updates OCS on command completion, with the command
2594 h->ocs = OCS_INVALID_COMMAND_STATUS;
2596 req_desc->prd_table_length = 0;
2600 * ufshcd_prepare_utp_scsi_cmd_upiu() - fills the utp_transfer_req_desc,
2602 * @lrbp: local reference block pointer
2603 * @upiu_flags: flags
2606 void ufshcd_prepare_utp_scsi_cmd_upiu(struct ufshcd_lrb *lrbp, u8 upiu_flags)
2608 struct scsi_cmnd *cmd = lrbp->cmd;
2609 struct utp_upiu_req *ucd_req_ptr = lrbp->ucd_req_ptr;
2610 unsigned short cdb_len;
2612 ucd_req_ptr->header = (struct utp_upiu_header){
2613 .transaction_code = UPIU_TRANSACTION_COMMAND,
2614 .flags = upiu_flags,
2616 .task_tag = lrbp->task_tag,
2617 .command_set_type = UPIU_COMMAND_SET_TYPE_SCSI,
2620 ucd_req_ptr->sc.exp_data_transfer_len = cpu_to_be32(cmd->sdb.length);
2622 cdb_len = min_t(unsigned short, cmd->cmd_len, UFS_CDB_SIZE);
2623 memset(ucd_req_ptr->sc.cdb, 0, UFS_CDB_SIZE);
2624 memcpy(ucd_req_ptr->sc.cdb, cmd->cmnd, cdb_len);
2626 memset(lrbp->ucd_rsp_ptr, 0, sizeof(struct utp_upiu_rsp));
2630 * ufshcd_prepare_utp_query_req_upiu() - fill the utp_transfer_req_desc for query request
2632 * @lrbp: local reference block pointer
2633 * @upiu_flags: flags
2635 static void ufshcd_prepare_utp_query_req_upiu(struct ufs_hba *hba,
2636 struct ufshcd_lrb *lrbp, u8 upiu_flags)
2638 struct utp_upiu_req *ucd_req_ptr = lrbp->ucd_req_ptr;
2639 struct ufs_query *query = &hba->dev_cmd.query;
2640 u16 len = be16_to_cpu(query->request.upiu_req.length);
2642 /* Query request header */
2643 ucd_req_ptr->header = (struct utp_upiu_header){
2644 .transaction_code = UPIU_TRANSACTION_QUERY_REQ,
2645 .flags = upiu_flags,
2647 .task_tag = lrbp->task_tag,
2648 .query_function = query->request.query_func,
2649 /* Data segment length only need for WRITE_DESC */
2650 .data_segment_length =
2651 query->request.upiu_req.opcode ==
2652 UPIU_QUERY_OPCODE_WRITE_DESC ?
2657 /* Copy the Query Request buffer as is */
2658 memcpy(&ucd_req_ptr->qr, &query->request.upiu_req,
2661 /* Copy the Descriptor */
2662 if (query->request.upiu_req.opcode == UPIU_QUERY_OPCODE_WRITE_DESC)
2663 memcpy(ucd_req_ptr + 1, query->descriptor, len);
2665 memset(lrbp->ucd_rsp_ptr, 0, sizeof(struct utp_upiu_rsp));
2668 static inline void ufshcd_prepare_utp_nop_upiu(struct ufshcd_lrb *lrbp)
2670 struct utp_upiu_req *ucd_req_ptr = lrbp->ucd_req_ptr;
2672 memset(ucd_req_ptr, 0, sizeof(struct utp_upiu_req));
2674 ucd_req_ptr->header = (struct utp_upiu_header){
2675 .transaction_code = UPIU_TRANSACTION_NOP_OUT,
2676 .task_tag = lrbp->task_tag,
2679 memset(lrbp->ucd_rsp_ptr, 0, sizeof(struct utp_upiu_rsp));
2683 * ufshcd_compose_devman_upiu - UFS Protocol Information Unit(UPIU)
2684 * for Device Management Purposes
2685 * @hba: per adapter instance
2686 * @lrbp: pointer to local reference block
2688 * Return: 0 upon success; < 0 upon failure.
2690 static int ufshcd_compose_devman_upiu(struct ufs_hba *hba,
2691 struct ufshcd_lrb *lrbp)
2696 if (hba->ufs_version <= ufshci_version(1, 1))
2697 lrbp->command_type = UTP_CMD_TYPE_DEV_MANAGE;
2699 lrbp->command_type = UTP_CMD_TYPE_UFS_STORAGE;
2701 ufshcd_prepare_req_desc_hdr(lrbp, &upiu_flags, DMA_NONE, 0);
2702 if (hba->dev_cmd.type == DEV_CMD_TYPE_QUERY)
2703 ufshcd_prepare_utp_query_req_upiu(hba, lrbp, upiu_flags);
2704 else if (hba->dev_cmd.type == DEV_CMD_TYPE_NOP)
2705 ufshcd_prepare_utp_nop_upiu(lrbp);
2713 * ufshcd_comp_scsi_upiu - UFS Protocol Information Unit(UPIU)
2715 * @hba: per adapter instance
2716 * @lrbp: pointer to local reference block
2718 static void ufshcd_comp_scsi_upiu(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
2720 struct request *rq = scsi_cmd_to_rq(lrbp->cmd);
2721 unsigned int ioprio_class = IOPRIO_PRIO_CLASS(req_get_ioprio(rq));
2724 if (hba->ufs_version <= ufshci_version(1, 1))
2725 lrbp->command_type = UTP_CMD_TYPE_SCSI;
2727 lrbp->command_type = UTP_CMD_TYPE_UFS_STORAGE;
2729 ufshcd_prepare_req_desc_hdr(lrbp, &upiu_flags,
2730 lrbp->cmd->sc_data_direction, 0);
2731 if (ioprio_class == IOPRIO_CLASS_RT)
2732 upiu_flags |= UPIU_CMD_FLAGS_CP;
2733 ufshcd_prepare_utp_scsi_cmd_upiu(lrbp, upiu_flags);
2737 * ufshcd_upiu_wlun_to_scsi_wlun - maps UPIU W-LUN id to SCSI W-LUN ID
2738 * @upiu_wlun_id: UPIU W-LUN id
2740 * Return: SCSI W-LUN id.
2742 static inline u16 ufshcd_upiu_wlun_to_scsi_wlun(u8 upiu_wlun_id)
2744 return (upiu_wlun_id & ~UFS_UPIU_WLUN_ID) | SCSI_W_LUN_BASE;
2747 static inline bool is_device_wlun(struct scsi_device *sdev)
2750 ufshcd_upiu_wlun_to_scsi_wlun(UFS_UPIU_UFS_DEVICE_WLUN);
2754 * Associate the UFS controller queue with the default and poll HCTX types.
2755 * Initialize the mq_map[] arrays.
2757 static void ufshcd_map_queues(struct Scsi_Host *shost)
2759 struct ufs_hba *hba = shost_priv(shost);
2760 int i, queue_offset = 0;
2762 if (!is_mcq_supported(hba)) {
2763 hba->nr_queues[HCTX_TYPE_DEFAULT] = 1;
2764 hba->nr_queues[HCTX_TYPE_READ] = 0;
2765 hba->nr_queues[HCTX_TYPE_POLL] = 1;
2766 hba->nr_hw_queues = 1;
2769 for (i = 0; i < shost->nr_maps; i++) {
2770 struct blk_mq_queue_map *map = &shost->tag_set.map[i];
2772 map->nr_queues = hba->nr_queues[i];
2773 if (!map->nr_queues)
2775 map->queue_offset = queue_offset;
2776 if (i == HCTX_TYPE_POLL && !is_mcq_supported(hba))
2777 map->queue_offset = 0;
2779 blk_mq_map_queues(map);
2780 queue_offset += map->nr_queues;
2784 static void ufshcd_init_lrb(struct ufs_hba *hba, struct ufshcd_lrb *lrb, int i)
2786 struct utp_transfer_cmd_desc *cmd_descp = (void *)hba->ucdl_base_addr +
2787 i * ufshcd_get_ucd_size(hba);
2788 struct utp_transfer_req_desc *utrdlp = hba->utrdl_base_addr;
2789 dma_addr_t cmd_desc_element_addr = hba->ucdl_dma_addr +
2790 i * ufshcd_get_ucd_size(hba);
2791 u16 response_offset = offsetof(struct utp_transfer_cmd_desc,
2793 u16 prdt_offset = offsetof(struct utp_transfer_cmd_desc, prd_table);
2795 lrb->utr_descriptor_ptr = utrdlp + i;
2796 lrb->utrd_dma_addr = hba->utrdl_dma_addr +
2797 i * sizeof(struct utp_transfer_req_desc);
2798 lrb->ucd_req_ptr = (struct utp_upiu_req *)cmd_descp->command_upiu;
2799 lrb->ucd_req_dma_addr = cmd_desc_element_addr;
2800 lrb->ucd_rsp_ptr = (struct utp_upiu_rsp *)cmd_descp->response_upiu;
2801 lrb->ucd_rsp_dma_addr = cmd_desc_element_addr + response_offset;
2802 lrb->ucd_prdt_ptr = (struct ufshcd_sg_entry *)cmd_descp->prd_table;
2803 lrb->ucd_prdt_dma_addr = cmd_desc_element_addr + prdt_offset;
2807 * ufshcd_queuecommand - main entry point for SCSI requests
2808 * @host: SCSI host pointer
2809 * @cmd: command from SCSI Midlayer
2811 * Return: 0 for success, non-zero in case of failure.
2813 static int ufshcd_queuecommand(struct Scsi_Host *host, struct scsi_cmnd *cmd)
2815 struct ufs_hba *hba = shost_priv(host);
2816 int tag = scsi_cmd_to_rq(cmd)->tag;
2817 struct ufshcd_lrb *lrbp;
2819 struct ufs_hw_queue *hwq = NULL;
2821 switch (hba->ufshcd_state) {
2822 case UFSHCD_STATE_OPERATIONAL:
2824 case UFSHCD_STATE_EH_SCHEDULED_NON_FATAL:
2826 * SCSI error handler can call ->queuecommand() while UFS error
2827 * handler is in progress. Error interrupts could change the
2828 * state from UFSHCD_STATE_RESET to
2829 * UFSHCD_STATE_EH_SCHEDULED_NON_FATAL. Prevent requests
2830 * being issued in that case.
2832 if (ufshcd_eh_in_progress(hba)) {
2833 err = SCSI_MLQUEUE_HOST_BUSY;
2837 case UFSHCD_STATE_EH_SCHEDULED_FATAL:
2839 * pm_runtime_get_sync() is used at error handling preparation
2840 * stage. If a scsi cmd, e.g. the SSU cmd, is sent from hba's
2841 * PM ops, it can never be finished if we let SCSI layer keep
2842 * retrying it, which gets err handler stuck forever. Neither
2843 * can we let the scsi cmd pass through, because UFS is in bad
2844 * state, the scsi cmd may eventually time out, which will get
2845 * err handler blocked for too long. So, just fail the scsi cmd
2846 * sent from PM ops, err handler can recover PM error anyways.
2848 if (hba->pm_op_in_progress) {
2849 hba->force_reset = true;
2850 set_host_byte(cmd, DID_BAD_TARGET);
2855 case UFSHCD_STATE_RESET:
2856 err = SCSI_MLQUEUE_HOST_BUSY;
2858 case UFSHCD_STATE_ERROR:
2859 set_host_byte(cmd, DID_ERROR);
2864 hba->req_abort_count = 0;
2868 lrbp = &hba->lrb[tag];
2870 lrbp->task_tag = tag;
2871 lrbp->lun = ufshcd_scsi_to_upiu_lun(cmd->device->lun);
2872 lrbp->intr_cmd = !ufshcd_is_intr_aggr_allowed(hba);
2874 ufshcd_prepare_lrbp_crypto(scsi_cmd_to_rq(cmd), lrbp);
2876 lrbp->req_abort_skip = false;
2878 ufshcd_comp_scsi_upiu(hba, lrbp);
2880 err = ufshcd_map_sg(hba, lrbp);
2882 ufshcd_release(hba);
2886 if (is_mcq_enabled(hba))
2887 hwq = ufshcd_mcq_req_to_hwq(hba, scsi_cmd_to_rq(cmd));
2889 ufshcd_send_command(hba, tag, hwq);
2892 if (ufs_trigger_eh()) {
2893 unsigned long flags;
2895 spin_lock_irqsave(hba->host->host_lock, flags);
2896 ufshcd_schedule_eh_work(hba);
2897 spin_unlock_irqrestore(hba->host->host_lock, flags);
2903 static int ufshcd_compose_dev_cmd(struct ufs_hba *hba,
2904 struct ufshcd_lrb *lrbp, enum dev_cmd_type cmd_type, int tag)
2907 lrbp->task_tag = tag;
2908 lrbp->lun = 0; /* device management cmd is not specific to any LUN */
2909 lrbp->intr_cmd = true; /* No interrupt aggregation */
2910 ufshcd_prepare_lrbp_crypto(NULL, lrbp);
2911 hba->dev_cmd.type = cmd_type;
2913 return ufshcd_compose_devman_upiu(hba, lrbp);
2917 * Check with the block layer if the command is inflight
2918 * @cmd: command to check.
2920 * Return: true if command is inflight; false if not.
2922 bool ufshcd_cmd_inflight(struct scsi_cmnd *cmd)
2929 rq = scsi_cmd_to_rq(cmd);
2930 if (!blk_mq_request_started(rq))
2937 * Clear the pending command in the controller and wait until
2938 * the controller confirms that the command has been cleared.
2939 * @hba: per adapter instance
2940 * @task_tag: The tag number of the command to be cleared.
2942 static int ufshcd_clear_cmd(struct ufs_hba *hba, u32 task_tag)
2944 u32 mask = 1U << task_tag;
2945 unsigned long flags;
2948 if (is_mcq_enabled(hba)) {
2950 * MCQ mode. Clean up the MCQ resources similar to
2951 * what the ufshcd_utrl_clear() does for SDB mode.
2953 err = ufshcd_mcq_sq_cleanup(hba, task_tag);
2955 dev_err(hba->dev, "%s: failed tag=%d. err=%d\n",
2956 __func__, task_tag, err);
2962 /* clear outstanding transaction before retry */
2963 spin_lock_irqsave(hba->host->host_lock, flags);
2964 ufshcd_utrl_clear(hba, mask);
2965 spin_unlock_irqrestore(hba->host->host_lock, flags);
2968 * wait for h/w to clear corresponding bit in door-bell.
2969 * max. wait is 1 sec.
2971 return ufshcd_wait_for_register(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL,
2972 mask, ~mask, 1000, 1000);
2976 * ufshcd_dev_cmd_completion() - handles device management command responses
2977 * @hba: per adapter instance
2978 * @lrbp: pointer to local reference block
2980 * Return: 0 upon success; < 0 upon failure.
2983 ufshcd_dev_cmd_completion(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
2985 enum upiu_response_transaction resp;
2988 hba->ufs_stats.last_hibern8_exit_tstamp = ktime_set(0, 0);
2989 resp = ufshcd_get_req_rsp(lrbp->ucd_rsp_ptr);
2992 case UPIU_TRANSACTION_NOP_IN:
2993 if (hba->dev_cmd.type != DEV_CMD_TYPE_NOP) {
2995 dev_err(hba->dev, "%s: unexpected response %x\n",
2999 case UPIU_TRANSACTION_QUERY_RSP: {
3000 u8 response = lrbp->ucd_rsp_ptr->header.response;
3003 err = ufshcd_copy_query_response(hba, lrbp);
3006 case UPIU_TRANSACTION_REJECT_UPIU:
3007 /* TODO: handle Reject UPIU Response */
3009 dev_err(hba->dev, "%s: Reject UPIU not fully implemented\n",
3012 case UPIU_TRANSACTION_RESPONSE:
3013 if (hba->dev_cmd.type != DEV_CMD_TYPE_RPMB) {
3015 dev_err(hba->dev, "%s: unexpected response %x\n", __func__, resp);
3020 dev_err(hba->dev, "%s: Invalid device management cmd response: %x\n",
3028 static int ufshcd_wait_for_dev_cmd(struct ufs_hba *hba,
3029 struct ufshcd_lrb *lrbp, int max_timeout)
3031 unsigned long time_left = msecs_to_jiffies(max_timeout);
3032 unsigned long flags;
3037 time_left = wait_for_completion_timeout(hba->dev_cmd.complete,
3040 if (likely(time_left)) {
3042 * The completion handler called complete() and the caller of
3043 * this function still owns the @lrbp tag so the code below does
3044 * not trigger any race conditions.
3046 hba->dev_cmd.complete = NULL;
3047 err = ufshcd_get_tr_ocs(lrbp, NULL);
3049 err = ufshcd_dev_cmd_completion(hba, lrbp);
3052 dev_dbg(hba->dev, "%s: dev_cmd request timedout, tag %d\n",
3053 __func__, lrbp->task_tag);
3056 if (is_mcq_enabled(hba)) {
3057 err = ufshcd_clear_cmd(hba, lrbp->task_tag);
3058 hba->dev_cmd.complete = NULL;
3063 if (ufshcd_clear_cmd(hba, lrbp->task_tag) == 0) {
3064 /* successfully cleared the command, retry if needed */
3067 * Since clearing the command succeeded we also need to
3068 * clear the task tag bit from the outstanding_reqs
3071 spin_lock_irqsave(&hba->outstanding_lock, flags);
3072 pending = test_bit(lrbp->task_tag,
3073 &hba->outstanding_reqs);
3075 hba->dev_cmd.complete = NULL;
3076 __clear_bit(lrbp->task_tag,
3077 &hba->outstanding_reqs);
3079 spin_unlock_irqrestore(&hba->outstanding_lock, flags);
3083 * The completion handler ran while we tried to
3084 * clear the command.
3090 dev_err(hba->dev, "%s: failed to clear tag %d\n",
3091 __func__, lrbp->task_tag);
3093 spin_lock_irqsave(&hba->outstanding_lock, flags);
3094 pending = test_bit(lrbp->task_tag,
3095 &hba->outstanding_reqs);
3097 hba->dev_cmd.complete = NULL;
3098 spin_unlock_irqrestore(&hba->outstanding_lock, flags);
3102 * The completion handler ran while we tried to
3103 * clear the command.
3115 * ufshcd_exec_dev_cmd - API for sending device management requests
3117 * @cmd_type: specifies the type (NOP, Query...)
3118 * @timeout: timeout in milliseconds
3120 * Return: 0 upon success; < 0 upon failure.
3122 * NOTE: Since there is only one available tag for device management commands,
3123 * it is expected you hold the hba->dev_cmd.lock mutex.
3125 static int ufshcd_exec_dev_cmd(struct ufs_hba *hba,
3126 enum dev_cmd_type cmd_type, int timeout)
3128 DECLARE_COMPLETION_ONSTACK(wait);
3129 const u32 tag = hba->reserved_slot;
3130 struct ufshcd_lrb *lrbp;
3133 /* Protects use of hba->reserved_slot. */
3134 lockdep_assert_held(&hba->dev_cmd.lock);
3136 down_read(&hba->clk_scaling_lock);
3138 lrbp = &hba->lrb[tag];
3140 err = ufshcd_compose_dev_cmd(hba, lrbp, cmd_type, tag);
3144 hba->dev_cmd.complete = &wait;
3146 ufshcd_add_query_upiu_trace(hba, UFS_QUERY_SEND, lrbp->ucd_req_ptr);
3148 ufshcd_send_command(hba, tag, hba->dev_cmd_queue);
3149 err = ufshcd_wait_for_dev_cmd(hba, lrbp, timeout);
3150 ufshcd_add_query_upiu_trace(hba, err ? UFS_QUERY_ERR : UFS_QUERY_COMP,
3151 (struct utp_upiu_req *)lrbp->ucd_rsp_ptr);
3154 up_read(&hba->clk_scaling_lock);
3159 * ufshcd_init_query() - init the query response and request parameters
3160 * @hba: per-adapter instance
3161 * @request: address of the request pointer to be initialized
3162 * @response: address of the response pointer to be initialized
3163 * @opcode: operation to perform
3164 * @idn: flag idn to access
3165 * @index: LU number to access
3166 * @selector: query/flag/descriptor further identification
3168 static inline void ufshcd_init_query(struct ufs_hba *hba,
3169 struct ufs_query_req **request, struct ufs_query_res **response,
3170 enum query_opcode opcode, u8 idn, u8 index, u8 selector)
3172 *request = &hba->dev_cmd.query.request;
3173 *response = &hba->dev_cmd.query.response;
3174 memset(*request, 0, sizeof(struct ufs_query_req));
3175 memset(*response, 0, sizeof(struct ufs_query_res));
3176 (*request)->upiu_req.opcode = opcode;
3177 (*request)->upiu_req.idn = idn;
3178 (*request)->upiu_req.index = index;
3179 (*request)->upiu_req.selector = selector;
3182 static int ufshcd_query_flag_retry(struct ufs_hba *hba,
3183 enum query_opcode opcode, enum flag_idn idn, u8 index, bool *flag_res)
3188 for (retries = 0; retries < QUERY_REQ_RETRIES; retries++) {
3189 ret = ufshcd_query_flag(hba, opcode, idn, index, flag_res);
3192 "%s: failed with error %d, retries %d\n",
3193 __func__, ret, retries);
3200 "%s: query flag, opcode %d, idn %d, failed with error %d after %d retries\n",
3201 __func__, opcode, idn, ret, retries);
3206 * ufshcd_query_flag() - API function for sending flag query requests
3207 * @hba: per-adapter instance
3208 * @opcode: flag query to perform
3209 * @idn: flag idn to access
3210 * @index: flag index to access
3211 * @flag_res: the flag value after the query request completes
3213 * Return: 0 for success, non-zero in case of failure.
3215 int ufshcd_query_flag(struct ufs_hba *hba, enum query_opcode opcode,
3216 enum flag_idn idn, u8 index, bool *flag_res)
3218 struct ufs_query_req *request = NULL;
3219 struct ufs_query_res *response = NULL;
3220 int err, selector = 0;
3221 int timeout = QUERY_REQ_TIMEOUT;
3226 mutex_lock(&hba->dev_cmd.lock);
3227 ufshcd_init_query(hba, &request, &response, opcode, idn, index,
3231 case UPIU_QUERY_OPCODE_SET_FLAG:
3232 case UPIU_QUERY_OPCODE_CLEAR_FLAG:
3233 case UPIU_QUERY_OPCODE_TOGGLE_FLAG:
3234 request->query_func = UPIU_QUERY_FUNC_STANDARD_WRITE_REQUEST;
3236 case UPIU_QUERY_OPCODE_READ_FLAG:
3237 request->query_func = UPIU_QUERY_FUNC_STANDARD_READ_REQUEST;
3239 /* No dummy reads */
3240 dev_err(hba->dev, "%s: Invalid argument for read request\n",
3248 "%s: Expected query flag opcode but got = %d\n",
3254 err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_QUERY, timeout);
3258 "%s: Sending flag query for idn %d failed, err = %d\n",
3259 __func__, idn, err);
3264 *flag_res = (be32_to_cpu(response->upiu_res.value) &
3265 MASK_QUERY_UPIU_FLAG_LOC) & 0x1;
3268 mutex_unlock(&hba->dev_cmd.lock);
3269 ufshcd_release(hba);
3274 * ufshcd_query_attr - API function for sending attribute requests
3275 * @hba: per-adapter instance
3276 * @opcode: attribute opcode
3277 * @idn: attribute idn to access
3278 * @index: index field
3279 * @selector: selector field
3280 * @attr_val: the attribute value after the query request completes
3282 * Return: 0 for success, non-zero in case of failure.
3284 int ufshcd_query_attr(struct ufs_hba *hba, enum query_opcode opcode,
3285 enum attr_idn idn, u8 index, u8 selector, u32 *attr_val)
3287 struct ufs_query_req *request = NULL;
3288 struct ufs_query_res *response = NULL;
3294 dev_err(hba->dev, "%s: attribute value required for opcode 0x%x\n",
3301 mutex_lock(&hba->dev_cmd.lock);
3302 ufshcd_init_query(hba, &request, &response, opcode, idn, index,
3306 case UPIU_QUERY_OPCODE_WRITE_ATTR:
3307 request->query_func = UPIU_QUERY_FUNC_STANDARD_WRITE_REQUEST;
3308 request->upiu_req.value = cpu_to_be32(*attr_val);
3310 case UPIU_QUERY_OPCODE_READ_ATTR:
3311 request->query_func = UPIU_QUERY_FUNC_STANDARD_READ_REQUEST;
3314 dev_err(hba->dev, "%s: Expected query attr opcode but got = 0x%.2x\n",
3320 err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_QUERY, QUERY_REQ_TIMEOUT);
3323 dev_err(hba->dev, "%s: opcode 0x%.2x for idn %d failed, index %d, err = %d\n",
3324 __func__, opcode, idn, index, err);
3328 *attr_val = be32_to_cpu(response->upiu_res.value);
3331 mutex_unlock(&hba->dev_cmd.lock);
3332 ufshcd_release(hba);
3337 * ufshcd_query_attr_retry() - API function for sending query
3338 * attribute with retries
3339 * @hba: per-adapter instance
3340 * @opcode: attribute opcode
3341 * @idn: attribute idn to access
3342 * @index: index field
3343 * @selector: selector field
3344 * @attr_val: the attribute value after the query request
3347 * Return: 0 for success, non-zero in case of failure.
3349 int ufshcd_query_attr_retry(struct ufs_hba *hba,
3350 enum query_opcode opcode, enum attr_idn idn, u8 index, u8 selector,
3356 for (retries = QUERY_REQ_RETRIES; retries > 0; retries--) {
3357 ret = ufshcd_query_attr(hba, opcode, idn, index,
3358 selector, attr_val);
3360 dev_dbg(hba->dev, "%s: failed with error %d, retries %d\n",
3361 __func__, ret, retries);
3368 "%s: query attribute, idn %d, failed with error %d after %d retries\n",
3369 __func__, idn, ret, QUERY_REQ_RETRIES);
3373 static int __ufshcd_query_descriptor(struct ufs_hba *hba,
3374 enum query_opcode opcode, enum desc_idn idn, u8 index,
3375 u8 selector, u8 *desc_buf, int *buf_len)
3377 struct ufs_query_req *request = NULL;
3378 struct ufs_query_res *response = NULL;
3384 dev_err(hba->dev, "%s: descriptor buffer required for opcode 0x%x\n",
3389 if (*buf_len < QUERY_DESC_MIN_SIZE || *buf_len > QUERY_DESC_MAX_SIZE) {
3390 dev_err(hba->dev, "%s: descriptor buffer size (%d) is out of range\n",
3391 __func__, *buf_len);
3397 mutex_lock(&hba->dev_cmd.lock);
3398 ufshcd_init_query(hba, &request, &response, opcode, idn, index,
3400 hba->dev_cmd.query.descriptor = desc_buf;
3401 request->upiu_req.length = cpu_to_be16(*buf_len);
3404 case UPIU_QUERY_OPCODE_WRITE_DESC:
3405 request->query_func = UPIU_QUERY_FUNC_STANDARD_WRITE_REQUEST;
3407 case UPIU_QUERY_OPCODE_READ_DESC:
3408 request->query_func = UPIU_QUERY_FUNC_STANDARD_READ_REQUEST;
3412 "%s: Expected query descriptor opcode but got = 0x%.2x\n",
3418 err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_QUERY, QUERY_REQ_TIMEOUT);
3421 dev_err(hba->dev, "%s: opcode 0x%.2x for idn %d failed, index %d, err = %d\n",
3422 __func__, opcode, idn, index, err);
3426 *buf_len = be16_to_cpu(response->upiu_res.length);
3429 hba->dev_cmd.query.descriptor = NULL;
3430 mutex_unlock(&hba->dev_cmd.lock);
3431 ufshcd_release(hba);
3436 * ufshcd_query_descriptor_retry - API function for sending descriptor requests
3437 * @hba: per-adapter instance
3438 * @opcode: attribute opcode
3439 * @idn: attribute idn to access
3440 * @index: index field
3441 * @selector: selector field
3442 * @desc_buf: the buffer that contains the descriptor
3443 * @buf_len: length parameter passed to the device
3445 * The buf_len parameter will contain, on return, the length parameter
3446 * received on the response.
3448 * Return: 0 for success, non-zero in case of failure.
3450 int ufshcd_query_descriptor_retry(struct ufs_hba *hba,
3451 enum query_opcode opcode,
3452 enum desc_idn idn, u8 index,
3454 u8 *desc_buf, int *buf_len)
3459 for (retries = QUERY_REQ_RETRIES; retries > 0; retries--) {
3460 err = __ufshcd_query_descriptor(hba, opcode, idn, index,
3461 selector, desc_buf, buf_len);
3462 if (!err || err == -EINVAL)
3470 * ufshcd_read_desc_param - read the specified descriptor parameter
3471 * @hba: Pointer to adapter instance
3472 * @desc_id: descriptor idn value
3473 * @desc_index: descriptor index
3474 * @param_offset: offset of the parameter to read
3475 * @param_read_buf: pointer to buffer where parameter would be read
3476 * @param_size: sizeof(param_read_buf)
3478 * Return: 0 in case of success, non-zero otherwise.
3480 int ufshcd_read_desc_param(struct ufs_hba *hba,
3481 enum desc_idn desc_id,
3489 int buff_len = QUERY_DESC_MAX_SIZE;
3490 bool is_kmalloc = true;
3493 if (desc_id >= QUERY_DESC_IDN_MAX || !param_size)
3496 /* Check whether we need temp memory */
3497 if (param_offset != 0 || param_size < buff_len) {
3498 desc_buf = kzalloc(buff_len, GFP_KERNEL);
3502 desc_buf = param_read_buf;
3506 /* Request for full descriptor */
3507 ret = ufshcd_query_descriptor_retry(hba, UPIU_QUERY_OPCODE_READ_DESC,
3508 desc_id, desc_index, 0,
3509 desc_buf, &buff_len);
3511 dev_err(hba->dev, "%s: Failed reading descriptor. desc_id %d, desc_index %d, param_offset %d, ret %d\n",
3512 __func__, desc_id, desc_index, param_offset, ret);
3516 /* Update descriptor length */
3517 buff_len = desc_buf[QUERY_DESC_LENGTH_OFFSET];
3519 if (param_offset >= buff_len) {
3520 dev_err(hba->dev, "%s: Invalid offset 0x%x in descriptor IDN 0x%x, length 0x%x\n",
3521 __func__, param_offset, desc_id, buff_len);
3527 if (desc_buf[QUERY_DESC_DESC_TYPE_OFFSET] != desc_id) {
3528 dev_err(hba->dev, "%s: invalid desc_id %d in descriptor header\n",
3529 __func__, desc_buf[QUERY_DESC_DESC_TYPE_OFFSET]);
3535 /* Make sure we don't copy more data than available */
3536 if (param_offset >= buff_len)
3539 memcpy(param_read_buf, &desc_buf[param_offset],
3540 min_t(u32, param_size, buff_len - param_offset));
3549 * struct uc_string_id - unicode string
3551 * @len: size of this descriptor inclusive
3552 * @type: descriptor type
3553 * @uc: unicode string character
3555 struct uc_string_id {
3561 /* replace non-printable or non-ASCII characters with spaces */
3562 static inline char ufshcd_remove_non_printable(u8 ch)
3564 return (ch >= 0x20 && ch <= 0x7e) ? ch : ' ';
3568 * ufshcd_read_string_desc - read string descriptor
3569 * @hba: pointer to adapter instance
3570 * @desc_index: descriptor index
3571 * @buf: pointer to buffer where descriptor would be read,
3572 * the caller should free the memory.
3573 * @ascii: if true convert from unicode to ascii characters
3574 * null terminated string.
3577 * * string size on success.
3578 * * -ENOMEM: on allocation failure
3579 * * -EINVAL: on a wrong parameter
3581 int ufshcd_read_string_desc(struct ufs_hba *hba, u8 desc_index,
3582 u8 **buf, bool ascii)
3584 struct uc_string_id *uc_str;
3591 uc_str = kzalloc(QUERY_DESC_MAX_SIZE, GFP_KERNEL);
3595 ret = ufshcd_read_desc_param(hba, QUERY_DESC_IDN_STRING, desc_index, 0,
3596 (u8 *)uc_str, QUERY_DESC_MAX_SIZE);
3598 dev_err(hba->dev, "Reading String Desc failed after %d retries. err = %d\n",
3599 QUERY_REQ_RETRIES, ret);
3604 if (uc_str->len <= QUERY_DESC_HDR_SIZE) {
3605 dev_dbg(hba->dev, "String Desc is of zero length\n");
3614 /* remove header and divide by 2 to move from UTF16 to UTF8 */
3615 ascii_len = (uc_str->len - QUERY_DESC_HDR_SIZE) / 2 + 1;
3616 str = kzalloc(ascii_len, GFP_KERNEL);
3623 * the descriptor contains string in UTF16 format
3624 * we need to convert to utf-8 so it can be displayed
3626 ret = utf16s_to_utf8s(uc_str->uc,
3627 uc_str->len - QUERY_DESC_HDR_SIZE,
3628 UTF16_BIG_ENDIAN, str, ascii_len);
3630 /* replace non-printable or non-ASCII characters with spaces */
3631 for (i = 0; i < ret; i++)
3632 str[i] = ufshcd_remove_non_printable(str[i]);
3637 str = kmemdup(uc_str, uc_str->len, GFP_KERNEL);
3651 * ufshcd_read_unit_desc_param - read the specified unit descriptor parameter
3652 * @hba: Pointer to adapter instance
3654 * @param_offset: offset of the parameter to read
3655 * @param_read_buf: pointer to buffer where parameter would be read
3656 * @param_size: sizeof(param_read_buf)
3658 * Return: 0 in case of success, non-zero otherwise.
3660 static inline int ufshcd_read_unit_desc_param(struct ufs_hba *hba,
3662 enum unit_desc_param param_offset,
3667 * Unit descriptors are only available for general purpose LUs (LUN id
3668 * from 0 to 7) and RPMB Well known LU.
3670 if (!ufs_is_valid_unit_desc_lun(&hba->dev_info, lun))
3673 return ufshcd_read_desc_param(hba, QUERY_DESC_IDN_UNIT, lun,
3674 param_offset, param_read_buf, param_size);
3677 static int ufshcd_get_ref_clk_gating_wait(struct ufs_hba *hba)
3680 u32 gating_wait = UFSHCD_REF_CLK_GATING_WAIT_US;
3682 if (hba->dev_info.wspecversion >= 0x300) {
3683 err = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
3684 QUERY_ATTR_IDN_REF_CLK_GATING_WAIT_TIME, 0, 0,
3687 dev_err(hba->dev, "Failed reading bRefClkGatingWait. err = %d, use default %uus\n",
3690 if (gating_wait == 0) {
3691 gating_wait = UFSHCD_REF_CLK_GATING_WAIT_US;
3692 dev_err(hba->dev, "Undefined ref clk gating wait time, use default %uus\n",
3696 hba->dev_info.clk_gating_wait_us = gating_wait;
3703 * ufshcd_memory_alloc - allocate memory for host memory space data structures
3704 * @hba: per adapter instance
3706 * 1. Allocate DMA memory for Command Descriptor array
3707 * Each command descriptor consist of Command UPIU, Response UPIU and PRDT
3708 * 2. Allocate DMA memory for UTP Transfer Request Descriptor List (UTRDL).
3709 * 3. Allocate DMA memory for UTP Task Management Request Descriptor List
3711 * 4. Allocate memory for local reference block(lrb).
3713 * Return: 0 for success, non-zero in case of failure.
3715 static int ufshcd_memory_alloc(struct ufs_hba *hba)
3717 size_t utmrdl_size, utrdl_size, ucdl_size;
3719 /* Allocate memory for UTP command descriptors */
3720 ucdl_size = ufshcd_get_ucd_size(hba) * hba->nutrs;
3721 hba->ucdl_base_addr = dmam_alloc_coherent(hba->dev,
3723 &hba->ucdl_dma_addr,
3727 * UFSHCI requires UTP command descriptor to be 128 byte aligned.
3729 if (!hba->ucdl_base_addr ||
3730 WARN_ON(hba->ucdl_dma_addr & (128 - 1))) {
3732 "Command Descriptor Memory allocation failed\n");
3737 * Allocate memory for UTP Transfer descriptors
3738 * UFSHCI requires 1KB alignment of UTRD
3740 utrdl_size = (sizeof(struct utp_transfer_req_desc) * hba->nutrs);
3741 hba->utrdl_base_addr = dmam_alloc_coherent(hba->dev,
3743 &hba->utrdl_dma_addr,
3745 if (!hba->utrdl_base_addr ||
3746 WARN_ON(hba->utrdl_dma_addr & (SZ_1K - 1))) {
3748 "Transfer Descriptor Memory allocation failed\n");
3753 * Skip utmrdl allocation; it may have been
3754 * allocated during first pass and not released during
3755 * MCQ memory allocation.
3756 * See ufshcd_release_sdb_queue() and ufshcd_config_mcq()
3758 if (hba->utmrdl_base_addr)
3761 * Allocate memory for UTP Task Management descriptors
3762 * UFSHCI requires 1KB alignment of UTMRD
3764 utmrdl_size = sizeof(struct utp_task_req_desc) * hba->nutmrs;
3765 hba->utmrdl_base_addr = dmam_alloc_coherent(hba->dev,
3767 &hba->utmrdl_dma_addr,
3769 if (!hba->utmrdl_base_addr ||
3770 WARN_ON(hba->utmrdl_dma_addr & (SZ_1K - 1))) {
3772 "Task Management Descriptor Memory allocation failed\n");
3777 /* Allocate memory for local reference block */
3778 hba->lrb = devm_kcalloc(hba->dev,
3779 hba->nutrs, sizeof(struct ufshcd_lrb),
3782 dev_err(hba->dev, "LRB Memory allocation failed\n");
3791 * ufshcd_host_memory_configure - configure local reference block with
3793 * @hba: per adapter instance
3795 * Configure Host memory space
3796 * 1. Update Corresponding UTRD.UCDBA and UTRD.UCDBAU with UCD DMA
3798 * 2. Update each UTRD with Response UPIU offset, Response UPIU length
3800 * 3. Save the corresponding addresses of UTRD, UCD.CMD, UCD.RSP and UCD.PRDT
3801 * into local reference block.
3803 static void ufshcd_host_memory_configure(struct ufs_hba *hba)
3805 struct utp_transfer_req_desc *utrdlp;
3806 dma_addr_t cmd_desc_dma_addr;
3807 dma_addr_t cmd_desc_element_addr;
3808 u16 response_offset;
3813 utrdlp = hba->utrdl_base_addr;
3816 offsetof(struct utp_transfer_cmd_desc, response_upiu);
3818 offsetof(struct utp_transfer_cmd_desc, prd_table);
3820 cmd_desc_size = ufshcd_get_ucd_size(hba);
3821 cmd_desc_dma_addr = hba->ucdl_dma_addr;
3823 for (i = 0; i < hba->nutrs; i++) {
3824 /* Configure UTRD with command descriptor base address */
3825 cmd_desc_element_addr =
3826 (cmd_desc_dma_addr + (cmd_desc_size * i));
3827 utrdlp[i].command_desc_base_addr =
3828 cpu_to_le64(cmd_desc_element_addr);
3830 /* Response upiu and prdt offset should be in double words */
3831 if (hba->quirks & UFSHCD_QUIRK_PRDT_BYTE_GRAN) {
3832 utrdlp[i].response_upiu_offset =
3833 cpu_to_le16(response_offset);
3834 utrdlp[i].prd_table_offset =
3835 cpu_to_le16(prdt_offset);
3836 utrdlp[i].response_upiu_length =
3837 cpu_to_le16(ALIGNED_UPIU_SIZE);
3839 utrdlp[i].response_upiu_offset =
3840 cpu_to_le16(response_offset >> 2);
3841 utrdlp[i].prd_table_offset =
3842 cpu_to_le16(prdt_offset >> 2);
3843 utrdlp[i].response_upiu_length =
3844 cpu_to_le16(ALIGNED_UPIU_SIZE >> 2);
3847 ufshcd_init_lrb(hba, &hba->lrb[i], i);
3852 * ufshcd_dme_link_startup - Notify Unipro to perform link startup
3853 * @hba: per adapter instance
3855 * UIC_CMD_DME_LINK_STARTUP command must be issued to Unipro layer,
3856 * in order to initialize the Unipro link startup procedure.
3857 * Once the Unipro links are up, the device connected to the controller
3860 * Return: 0 on success, non-zero value on failure.
3862 static int ufshcd_dme_link_startup(struct ufs_hba *hba)
3864 struct uic_command uic_cmd = {0};
3867 uic_cmd.command = UIC_CMD_DME_LINK_STARTUP;
3869 ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
3872 "dme-link-startup: error code %d\n", ret);
3876 * ufshcd_dme_reset - UIC command for DME_RESET
3877 * @hba: per adapter instance
3879 * DME_RESET command is issued in order to reset UniPro stack.
3880 * This function now deals with cold reset.
3882 * Return: 0 on success, non-zero value on failure.
3884 static int ufshcd_dme_reset(struct ufs_hba *hba)
3886 struct uic_command uic_cmd = {0};
3889 uic_cmd.command = UIC_CMD_DME_RESET;
3891 ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
3894 "dme-reset: error code %d\n", ret);
3899 int ufshcd_dme_configure_adapt(struct ufs_hba *hba,
3905 if (agreed_gear < UFS_HS_G4)
3906 adapt_val = PA_NO_ADAPT;
3908 ret = ufshcd_dme_set(hba,
3909 UIC_ARG_MIB(PA_TXHSADAPTTYPE),
3913 EXPORT_SYMBOL_GPL(ufshcd_dme_configure_adapt);
3916 * ufshcd_dme_enable - UIC command for DME_ENABLE
3917 * @hba: per adapter instance
3919 * DME_ENABLE command is issued in order to enable UniPro stack.
3921 * Return: 0 on success, non-zero value on failure.
3923 static int ufshcd_dme_enable(struct ufs_hba *hba)
3925 struct uic_command uic_cmd = {0};
3928 uic_cmd.command = UIC_CMD_DME_ENABLE;
3930 ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
3933 "dme-enable: error code %d\n", ret);
3938 static inline void ufshcd_add_delay_before_dme_cmd(struct ufs_hba *hba)
3940 #define MIN_DELAY_BEFORE_DME_CMDS_US 1000
3941 unsigned long min_sleep_time_us;
3943 if (!(hba->quirks & UFSHCD_QUIRK_DELAY_BEFORE_DME_CMDS))
3947 * last_dme_cmd_tstamp will be 0 only for 1st call to
3950 if (unlikely(!ktime_to_us(hba->last_dme_cmd_tstamp))) {
3951 min_sleep_time_us = MIN_DELAY_BEFORE_DME_CMDS_US;
3953 unsigned long delta =
3954 (unsigned long) ktime_to_us(
3955 ktime_sub(ktime_get(),
3956 hba->last_dme_cmd_tstamp));
3958 if (delta < MIN_DELAY_BEFORE_DME_CMDS_US)
3960 MIN_DELAY_BEFORE_DME_CMDS_US - delta;
3962 return; /* no more delay required */
3965 /* allow sleep for extra 50us if needed */
3966 usleep_range(min_sleep_time_us, min_sleep_time_us + 50);
3970 * ufshcd_dme_set_attr - UIC command for DME_SET, DME_PEER_SET
3971 * @hba: per adapter instance
3972 * @attr_sel: uic command argument1
3973 * @attr_set: attribute set type as uic command argument2
3974 * @mib_val: setting value as uic command argument3
3975 * @peer: indicate whether peer or local
3977 * Return: 0 on success, non-zero value on failure.
3979 int ufshcd_dme_set_attr(struct ufs_hba *hba, u32 attr_sel,
3980 u8 attr_set, u32 mib_val, u8 peer)
3982 struct uic_command uic_cmd = {0};
3983 static const char *const action[] = {
3987 const char *set = action[!!peer];
3989 int retries = UFS_UIC_COMMAND_RETRIES;
3991 uic_cmd.command = peer ?
3992 UIC_CMD_DME_PEER_SET : UIC_CMD_DME_SET;
3993 uic_cmd.argument1 = attr_sel;
3994 uic_cmd.argument2 = UIC_ARG_ATTR_TYPE(attr_set);
3995 uic_cmd.argument3 = mib_val;
3998 /* for peer attributes we retry upon failure */
3999 ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
4001 dev_dbg(hba->dev, "%s: attr-id 0x%x val 0x%x error code %d\n",
4002 set, UIC_GET_ATTR_ID(attr_sel), mib_val, ret);
4003 } while (ret && peer && --retries);
4006 dev_err(hba->dev, "%s: attr-id 0x%x val 0x%x failed %d retries\n",
4007 set, UIC_GET_ATTR_ID(attr_sel), mib_val,
4008 UFS_UIC_COMMAND_RETRIES - retries);
4012 EXPORT_SYMBOL_GPL(ufshcd_dme_set_attr);
4015 * ufshcd_dme_get_attr - UIC command for DME_GET, DME_PEER_GET
4016 * @hba: per adapter instance
4017 * @attr_sel: uic command argument1
4018 * @mib_val: the value of the attribute as returned by the UIC command
4019 * @peer: indicate whether peer or local
4021 * Return: 0 on success, non-zero value on failure.
4023 int ufshcd_dme_get_attr(struct ufs_hba *hba, u32 attr_sel,
4024 u32 *mib_val, u8 peer)
4026 struct uic_command uic_cmd = {0};
4027 static const char *const action[] = {
4031 const char *get = action[!!peer];
4033 int retries = UFS_UIC_COMMAND_RETRIES;
4034 struct ufs_pa_layer_attr orig_pwr_info;
4035 struct ufs_pa_layer_attr temp_pwr_info;
4036 bool pwr_mode_change = false;
4038 if (peer && (hba->quirks & UFSHCD_QUIRK_DME_PEER_ACCESS_AUTO_MODE)) {
4039 orig_pwr_info = hba->pwr_info;
4040 temp_pwr_info = orig_pwr_info;
4042 if (orig_pwr_info.pwr_tx == FAST_MODE ||
4043 orig_pwr_info.pwr_rx == FAST_MODE) {
4044 temp_pwr_info.pwr_tx = FASTAUTO_MODE;
4045 temp_pwr_info.pwr_rx = FASTAUTO_MODE;
4046 pwr_mode_change = true;
4047 } else if (orig_pwr_info.pwr_tx == SLOW_MODE ||
4048 orig_pwr_info.pwr_rx == SLOW_MODE) {
4049 temp_pwr_info.pwr_tx = SLOWAUTO_MODE;
4050 temp_pwr_info.pwr_rx = SLOWAUTO_MODE;
4051 pwr_mode_change = true;
4053 if (pwr_mode_change) {
4054 ret = ufshcd_change_power_mode(hba, &temp_pwr_info);
4060 uic_cmd.command = peer ?
4061 UIC_CMD_DME_PEER_GET : UIC_CMD_DME_GET;
4062 uic_cmd.argument1 = attr_sel;
4065 /* for peer attributes we retry upon failure */
4066 ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
4068 dev_dbg(hba->dev, "%s: attr-id 0x%x error code %d\n",
4069 get, UIC_GET_ATTR_ID(attr_sel), ret);
4070 } while (ret && peer && --retries);
4073 dev_err(hba->dev, "%s: attr-id 0x%x failed %d retries\n",
4074 get, UIC_GET_ATTR_ID(attr_sel),
4075 UFS_UIC_COMMAND_RETRIES - retries);
4077 if (mib_val && !ret)
4078 *mib_val = uic_cmd.argument3;
4080 if (peer && (hba->quirks & UFSHCD_QUIRK_DME_PEER_ACCESS_AUTO_MODE)
4082 ufshcd_change_power_mode(hba, &orig_pwr_info);
4086 EXPORT_SYMBOL_GPL(ufshcd_dme_get_attr);
4089 * ufshcd_uic_pwr_ctrl - executes UIC commands (which affects the link power
4090 * state) and waits for it to take effect.
4092 * @hba: per adapter instance
4093 * @cmd: UIC command to execute
4095 * DME operations like DME_SET(PA_PWRMODE), DME_HIBERNATE_ENTER &
4096 * DME_HIBERNATE_EXIT commands take some time to take its effect on both host
4097 * and device UniPro link and hence it's final completion would be indicated by
4098 * dedicated status bits in Interrupt Status register (UPMS, UHES, UHXS) in
4099 * addition to normal UIC command completion Status (UCCS). This function only
4100 * returns after the relevant status bits indicate the completion.
4102 * Return: 0 on success, non-zero value on failure.
4104 static int ufshcd_uic_pwr_ctrl(struct ufs_hba *hba, struct uic_command *cmd)
4106 DECLARE_COMPLETION_ONSTACK(uic_async_done);
4107 unsigned long flags;
4110 bool reenable_intr = false;
4112 mutex_lock(&hba->uic_cmd_mutex);
4113 ufshcd_add_delay_before_dme_cmd(hba);
4115 spin_lock_irqsave(hba->host->host_lock, flags);
4116 if (ufshcd_is_link_broken(hba)) {
4120 hba->uic_async_done = &uic_async_done;
4121 if (ufshcd_readl(hba, REG_INTERRUPT_ENABLE) & UIC_COMMAND_COMPL) {
4122 ufshcd_disable_intr(hba, UIC_COMMAND_COMPL);
4124 * Make sure UIC command completion interrupt is disabled before
4125 * issuing UIC command.
4128 reenable_intr = true;
4130 spin_unlock_irqrestore(hba->host->host_lock, flags);
4131 ret = __ufshcd_send_uic_cmd(hba, cmd, false);
4134 "pwr ctrl cmd 0x%x with mode 0x%x uic error %d\n",
4135 cmd->command, cmd->argument3, ret);
4139 if (!wait_for_completion_timeout(hba->uic_async_done,
4140 msecs_to_jiffies(UIC_CMD_TIMEOUT))) {
4142 "pwr ctrl cmd 0x%x with mode 0x%x completion timeout\n",
4143 cmd->command, cmd->argument3);
4145 if (!cmd->cmd_active) {
4146 dev_err(hba->dev, "%s: Power Mode Change operation has been completed, go check UPMCRS\n",
4156 status = ufshcd_get_upmcrs(hba);
4157 if (status != PWR_LOCAL) {
4159 "pwr ctrl cmd 0x%x failed, host upmcrs:0x%x\n",
4160 cmd->command, status);
4161 ret = (status != PWR_OK) ? status : -1;
4165 ufshcd_print_host_state(hba);
4166 ufshcd_print_pwr_info(hba);
4167 ufshcd_print_evt_hist(hba);
4170 spin_lock_irqsave(hba->host->host_lock, flags);
4171 hba->active_uic_cmd = NULL;
4172 hba->uic_async_done = NULL;
4174 ufshcd_enable_intr(hba, UIC_COMMAND_COMPL);
4176 ufshcd_set_link_broken(hba);
4177 ufshcd_schedule_eh_work(hba);
4180 spin_unlock_irqrestore(hba->host->host_lock, flags);
4181 mutex_unlock(&hba->uic_cmd_mutex);
4187 * ufshcd_uic_change_pwr_mode - Perform the UIC power mode chage
4188 * using DME_SET primitives.
4189 * @hba: per adapter instance
4190 * @mode: powr mode value
4192 * Return: 0 on success, non-zero value on failure.
4194 int ufshcd_uic_change_pwr_mode(struct ufs_hba *hba, u8 mode)
4196 struct uic_command uic_cmd = {0};
4199 if (hba->quirks & UFSHCD_QUIRK_BROKEN_PA_RXHSUNTERMCAP) {
4200 ret = ufshcd_dme_set(hba,
4201 UIC_ARG_MIB_SEL(PA_RXHSUNTERMCAP, 0), 1);
4203 dev_err(hba->dev, "%s: failed to enable PA_RXHSUNTERMCAP ret %d\n",
4209 uic_cmd.command = UIC_CMD_DME_SET;
4210 uic_cmd.argument1 = UIC_ARG_MIB(PA_PWRMODE);
4211 uic_cmd.argument3 = mode;
4213 ret = ufshcd_uic_pwr_ctrl(hba, &uic_cmd);
4214 ufshcd_release(hba);
4219 EXPORT_SYMBOL_GPL(ufshcd_uic_change_pwr_mode);
4221 int ufshcd_link_recovery(struct ufs_hba *hba)
4224 unsigned long flags;
4226 spin_lock_irqsave(hba->host->host_lock, flags);
4227 hba->ufshcd_state = UFSHCD_STATE_RESET;
4228 ufshcd_set_eh_in_progress(hba);
4229 spin_unlock_irqrestore(hba->host->host_lock, flags);
4231 /* Reset the attached device */
4232 ufshcd_device_reset(hba);
4234 ret = ufshcd_host_reset_and_restore(hba);
4236 spin_lock_irqsave(hba->host->host_lock, flags);
4238 hba->ufshcd_state = UFSHCD_STATE_ERROR;
4239 ufshcd_clear_eh_in_progress(hba);
4240 spin_unlock_irqrestore(hba->host->host_lock, flags);
4243 dev_err(hba->dev, "%s: link recovery failed, err %d",
4248 EXPORT_SYMBOL_GPL(ufshcd_link_recovery);
4250 int ufshcd_uic_hibern8_enter(struct ufs_hba *hba)
4253 struct uic_command uic_cmd = {0};
4254 ktime_t start = ktime_get();
4256 ufshcd_vops_hibern8_notify(hba, UIC_CMD_DME_HIBER_ENTER, PRE_CHANGE);
4258 uic_cmd.command = UIC_CMD_DME_HIBER_ENTER;
4259 ret = ufshcd_uic_pwr_ctrl(hba, &uic_cmd);
4260 trace_ufshcd_profile_hibern8(dev_name(hba->dev), "enter",
4261 ktime_to_us(ktime_sub(ktime_get(), start)), ret);
4264 dev_err(hba->dev, "%s: hibern8 enter failed. ret = %d\n",
4267 ufshcd_vops_hibern8_notify(hba, UIC_CMD_DME_HIBER_ENTER,
4272 EXPORT_SYMBOL_GPL(ufshcd_uic_hibern8_enter);
4274 int ufshcd_uic_hibern8_exit(struct ufs_hba *hba)
4276 struct uic_command uic_cmd = {0};
4278 ktime_t start = ktime_get();
4280 ufshcd_vops_hibern8_notify(hba, UIC_CMD_DME_HIBER_EXIT, PRE_CHANGE);
4282 uic_cmd.command = UIC_CMD_DME_HIBER_EXIT;
4283 ret = ufshcd_uic_pwr_ctrl(hba, &uic_cmd);
4284 trace_ufshcd_profile_hibern8(dev_name(hba->dev), "exit",
4285 ktime_to_us(ktime_sub(ktime_get(), start)), ret);
4288 dev_err(hba->dev, "%s: hibern8 exit failed. ret = %d\n",
4291 ufshcd_vops_hibern8_notify(hba, UIC_CMD_DME_HIBER_EXIT,
4293 hba->ufs_stats.last_hibern8_exit_tstamp = local_clock();
4294 hba->ufs_stats.hibern8_exit_cnt++;
4299 EXPORT_SYMBOL_GPL(ufshcd_uic_hibern8_exit);
4301 void ufshcd_auto_hibern8_update(struct ufs_hba *hba, u32 ahit)
4303 unsigned long flags;
4304 bool update = false;
4306 if (!ufshcd_is_auto_hibern8_supported(hba))
4309 spin_lock_irqsave(hba->host->host_lock, flags);
4310 if (hba->ahit != ahit) {
4314 spin_unlock_irqrestore(hba->host->host_lock, flags);
4317 !pm_runtime_suspended(&hba->ufs_device_wlun->sdev_gendev)) {
4318 ufshcd_rpm_get_sync(hba);
4320 ufshcd_auto_hibern8_enable(hba);
4321 ufshcd_release(hba);
4322 ufshcd_rpm_put_sync(hba);
4325 EXPORT_SYMBOL_GPL(ufshcd_auto_hibern8_update);
4327 void ufshcd_auto_hibern8_enable(struct ufs_hba *hba)
4329 if (!ufshcd_is_auto_hibern8_supported(hba))
4332 ufshcd_writel(hba, hba->ahit, REG_AUTO_HIBERNATE_IDLE_TIMER);
4336 * ufshcd_init_pwr_info - setting the POR (power on reset)
4337 * values in hba power info
4338 * @hba: per-adapter instance
4340 static void ufshcd_init_pwr_info(struct ufs_hba *hba)
4342 hba->pwr_info.gear_rx = UFS_PWM_G1;
4343 hba->pwr_info.gear_tx = UFS_PWM_G1;
4344 hba->pwr_info.lane_rx = UFS_LANE_1;
4345 hba->pwr_info.lane_tx = UFS_LANE_1;
4346 hba->pwr_info.pwr_rx = SLOWAUTO_MODE;
4347 hba->pwr_info.pwr_tx = SLOWAUTO_MODE;
4348 hba->pwr_info.hs_rate = 0;
4352 * ufshcd_get_max_pwr_mode - reads the max power mode negotiated with device
4353 * @hba: per-adapter instance
4355 * Return: 0 upon success; < 0 upon failure.
4357 static int ufshcd_get_max_pwr_mode(struct ufs_hba *hba)
4359 struct ufs_pa_layer_attr *pwr_info = &hba->max_pwr_info.info;
4361 if (hba->max_pwr_info.is_valid)
4364 if (hba->quirks & UFSHCD_QUIRK_HIBERN_FASTAUTO) {
4365 pwr_info->pwr_tx = FASTAUTO_MODE;
4366 pwr_info->pwr_rx = FASTAUTO_MODE;
4368 pwr_info->pwr_tx = FAST_MODE;
4369 pwr_info->pwr_rx = FAST_MODE;
4371 pwr_info->hs_rate = PA_HS_MODE_B;
4373 /* Get the connected lane count */
4374 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_CONNECTEDRXDATALANES),
4375 &pwr_info->lane_rx);
4376 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_CONNECTEDTXDATALANES),
4377 &pwr_info->lane_tx);
4379 if (!pwr_info->lane_rx || !pwr_info->lane_tx) {
4380 dev_err(hba->dev, "%s: invalid connected lanes value. rx=%d, tx=%d\n",
4388 * First, get the maximum gears of HS speed.
4389 * If a zero value, it means there is no HSGEAR capability.
4390 * Then, get the maximum gears of PWM speed.
4392 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_MAXRXHSGEAR), &pwr_info->gear_rx);
4393 if (!pwr_info->gear_rx) {
4394 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_MAXRXPWMGEAR),
4395 &pwr_info->gear_rx);
4396 if (!pwr_info->gear_rx) {
4397 dev_err(hba->dev, "%s: invalid max pwm rx gear read = %d\n",
4398 __func__, pwr_info->gear_rx);
4401 pwr_info->pwr_rx = SLOW_MODE;
4404 ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_MAXRXHSGEAR),
4405 &pwr_info->gear_tx);
4406 if (!pwr_info->gear_tx) {
4407 ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_MAXRXPWMGEAR),
4408 &pwr_info->gear_tx);
4409 if (!pwr_info->gear_tx) {
4410 dev_err(hba->dev, "%s: invalid max pwm tx gear read = %d\n",
4411 __func__, pwr_info->gear_tx);
4414 pwr_info->pwr_tx = SLOW_MODE;
4417 hba->max_pwr_info.is_valid = true;
4421 static int ufshcd_change_power_mode(struct ufs_hba *hba,
4422 struct ufs_pa_layer_attr *pwr_mode)
4426 /* if already configured to the requested pwr_mode */
4427 if (!hba->force_pmc &&
4428 pwr_mode->gear_rx == hba->pwr_info.gear_rx &&
4429 pwr_mode->gear_tx == hba->pwr_info.gear_tx &&
4430 pwr_mode->lane_rx == hba->pwr_info.lane_rx &&
4431 pwr_mode->lane_tx == hba->pwr_info.lane_tx &&
4432 pwr_mode->pwr_rx == hba->pwr_info.pwr_rx &&
4433 pwr_mode->pwr_tx == hba->pwr_info.pwr_tx &&
4434 pwr_mode->hs_rate == hba->pwr_info.hs_rate) {
4435 dev_dbg(hba->dev, "%s: power already configured\n", __func__);
4440 * Configure attributes for power mode change with below.
4441 * - PA_RXGEAR, PA_ACTIVERXDATALANES, PA_RXTERMINATION,
4442 * - PA_TXGEAR, PA_ACTIVETXDATALANES, PA_TXTERMINATION,
4445 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_RXGEAR), pwr_mode->gear_rx);
4446 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_ACTIVERXDATALANES),
4448 if (pwr_mode->pwr_rx == FASTAUTO_MODE ||
4449 pwr_mode->pwr_rx == FAST_MODE)
4450 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_RXTERMINATION), true);
4452 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_RXTERMINATION), false);
4454 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TXGEAR), pwr_mode->gear_tx);
4455 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_ACTIVETXDATALANES),
4457 if (pwr_mode->pwr_tx == FASTAUTO_MODE ||
4458 pwr_mode->pwr_tx == FAST_MODE)
4459 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TXTERMINATION), true);
4461 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TXTERMINATION), false);
4463 if (pwr_mode->pwr_rx == FASTAUTO_MODE ||
4464 pwr_mode->pwr_tx == FASTAUTO_MODE ||
4465 pwr_mode->pwr_rx == FAST_MODE ||
4466 pwr_mode->pwr_tx == FAST_MODE)
4467 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_HSSERIES),
4470 if (!(hba->quirks & UFSHCD_QUIRK_SKIP_DEF_UNIPRO_TIMEOUT_SETTING)) {
4471 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_PWRMODEUSERDATA0),
4472 DL_FC0ProtectionTimeOutVal_Default);
4473 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_PWRMODEUSERDATA1),
4474 DL_TC0ReplayTimeOutVal_Default);
4475 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_PWRMODEUSERDATA2),
4476 DL_AFC0ReqTimeOutVal_Default);
4477 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_PWRMODEUSERDATA3),
4478 DL_FC1ProtectionTimeOutVal_Default);
4479 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_PWRMODEUSERDATA4),
4480 DL_TC1ReplayTimeOutVal_Default);
4481 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_PWRMODEUSERDATA5),
4482 DL_AFC1ReqTimeOutVal_Default);
4484 ufshcd_dme_set(hba, UIC_ARG_MIB(DME_LocalFC0ProtectionTimeOutVal),
4485 DL_FC0ProtectionTimeOutVal_Default);
4486 ufshcd_dme_set(hba, UIC_ARG_MIB(DME_LocalTC0ReplayTimeOutVal),
4487 DL_TC0ReplayTimeOutVal_Default);
4488 ufshcd_dme_set(hba, UIC_ARG_MIB(DME_LocalAFC0ReqTimeOutVal),
4489 DL_AFC0ReqTimeOutVal_Default);
4492 ret = ufshcd_uic_change_pwr_mode(hba, pwr_mode->pwr_rx << 4
4493 | pwr_mode->pwr_tx);
4497 "%s: power mode change failed %d\n", __func__, ret);
4499 ufshcd_vops_pwr_change_notify(hba, POST_CHANGE, NULL,
4502 memcpy(&hba->pwr_info, pwr_mode,
4503 sizeof(struct ufs_pa_layer_attr));
4510 * ufshcd_config_pwr_mode - configure a new power mode
4511 * @hba: per-adapter instance
4512 * @desired_pwr_mode: desired power configuration
4514 * Return: 0 upon success; < 0 upon failure.
4516 int ufshcd_config_pwr_mode(struct ufs_hba *hba,
4517 struct ufs_pa_layer_attr *desired_pwr_mode)
4519 struct ufs_pa_layer_attr final_params = { 0 };
4522 ret = ufshcd_vops_pwr_change_notify(hba, PRE_CHANGE,
4523 desired_pwr_mode, &final_params);
4526 memcpy(&final_params, desired_pwr_mode, sizeof(final_params));
4528 ret = ufshcd_change_power_mode(hba, &final_params);
4532 EXPORT_SYMBOL_GPL(ufshcd_config_pwr_mode);
4535 * ufshcd_complete_dev_init() - checks device readiness
4536 * @hba: per-adapter instance
4538 * Set fDeviceInit flag and poll until device toggles it.
4540 * Return: 0 upon success; < 0 upon failure.
4542 static int ufshcd_complete_dev_init(struct ufs_hba *hba)
4545 bool flag_res = true;
4548 err = ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_SET_FLAG,
4549 QUERY_FLAG_IDN_FDEVICEINIT, 0, NULL);
4552 "%s: setting fDeviceInit flag failed with error %d\n",
4557 /* Poll fDeviceInit flag to be cleared */
4558 timeout = ktime_add_ms(ktime_get(), FDEVICEINIT_COMPL_TIMEOUT);
4560 err = ufshcd_query_flag(hba, UPIU_QUERY_OPCODE_READ_FLAG,
4561 QUERY_FLAG_IDN_FDEVICEINIT, 0, &flag_res);
4564 usleep_range(500, 1000);
4565 } while (ktime_before(ktime_get(), timeout));
4569 "%s: reading fDeviceInit flag failed with error %d\n",
4571 } else if (flag_res) {
4573 "%s: fDeviceInit was not cleared by the device\n",
4582 * ufshcd_make_hba_operational - Make UFS controller operational
4583 * @hba: per adapter instance
4585 * To bring UFS host controller to operational state,
4586 * 1. Enable required interrupts
4587 * 2. Configure interrupt aggregation
4588 * 3. Program UTRL and UTMRL base address
4589 * 4. Configure run-stop-registers
4591 * Return: 0 on success, non-zero value on failure.
4593 int ufshcd_make_hba_operational(struct ufs_hba *hba)
4598 /* Enable required interrupts */
4599 ufshcd_enable_intr(hba, UFSHCD_ENABLE_INTRS);
4601 /* Configure interrupt aggregation */
4602 if (ufshcd_is_intr_aggr_allowed(hba))
4603 ufshcd_config_intr_aggr(hba, hba->nutrs - 1, INT_AGGR_DEF_TO);
4605 ufshcd_disable_intr_aggr(hba);
4607 /* Configure UTRL and UTMRL base address registers */
4608 ufshcd_writel(hba, lower_32_bits(hba->utrdl_dma_addr),
4609 REG_UTP_TRANSFER_REQ_LIST_BASE_L);
4610 ufshcd_writel(hba, upper_32_bits(hba->utrdl_dma_addr),
4611 REG_UTP_TRANSFER_REQ_LIST_BASE_H);
4612 ufshcd_writel(hba, lower_32_bits(hba->utmrdl_dma_addr),
4613 REG_UTP_TASK_REQ_LIST_BASE_L);
4614 ufshcd_writel(hba, upper_32_bits(hba->utmrdl_dma_addr),
4615 REG_UTP_TASK_REQ_LIST_BASE_H);
4618 * Make sure base address and interrupt setup are updated before
4619 * enabling the run/stop registers below.
4624 * UCRDY, UTMRLDY and UTRLRDY bits must be 1
4626 reg = ufshcd_readl(hba, REG_CONTROLLER_STATUS);
4627 if (!(ufshcd_get_lists_status(reg))) {
4628 ufshcd_enable_run_stop_reg(hba);
4631 "Host controller not ready to process requests");
4637 EXPORT_SYMBOL_GPL(ufshcd_make_hba_operational);
4640 * ufshcd_hba_stop - Send controller to reset state
4641 * @hba: per adapter instance
4643 void ufshcd_hba_stop(struct ufs_hba *hba)
4645 unsigned long flags;
4649 * Obtain the host lock to prevent that the controller is disabled
4650 * while the UFS interrupt handler is active on another CPU.
4652 spin_lock_irqsave(hba->host->host_lock, flags);
4653 ufshcd_writel(hba, CONTROLLER_DISABLE, REG_CONTROLLER_ENABLE);
4654 spin_unlock_irqrestore(hba->host->host_lock, flags);
4656 err = ufshcd_wait_for_register(hba, REG_CONTROLLER_ENABLE,
4657 CONTROLLER_ENABLE, CONTROLLER_DISABLE,
4660 dev_err(hba->dev, "%s: Controller disable failed\n", __func__);
4662 EXPORT_SYMBOL_GPL(ufshcd_hba_stop);
4665 * ufshcd_hba_execute_hce - initialize the controller
4666 * @hba: per adapter instance
4668 * The controller resets itself and controller firmware initialization
4669 * sequence kicks off. When controller is ready it will set
4670 * the Host Controller Enable bit to 1.
4672 * Return: 0 on success, non-zero value on failure.
4674 static int ufshcd_hba_execute_hce(struct ufs_hba *hba)
4676 int retry_outer = 3;
4680 if (ufshcd_is_hba_active(hba))
4681 /* change controller state to "reset state" */
4682 ufshcd_hba_stop(hba);
4684 /* UniPro link is disabled at this point */
4685 ufshcd_set_link_off(hba);
4687 ufshcd_vops_hce_enable_notify(hba, PRE_CHANGE);
4689 /* start controller initialization sequence */
4690 ufshcd_hba_start(hba);
4693 * To initialize a UFS host controller HCE bit must be set to 1.
4694 * During initialization the HCE bit value changes from 1->0->1.
4695 * When the host controller completes initialization sequence
4696 * it sets the value of HCE bit to 1. The same HCE bit is read back
4697 * to check if the controller has completed initialization sequence.
4698 * So without this delay the value HCE = 1, set in the previous
4699 * instruction might be read back.
4700 * This delay can be changed based on the controller.
4702 ufshcd_delay_us(hba->vps->hba_enable_delay_us, 100);
4704 /* wait for the host controller to complete initialization */
4706 while (!ufshcd_is_hba_active(hba)) {
4711 "Controller enable failed\n");
4718 usleep_range(1000, 1100);
4721 /* enable UIC related interrupts */
4722 ufshcd_enable_intr(hba, UFSHCD_UIC_MASK);
4724 ufshcd_vops_hce_enable_notify(hba, POST_CHANGE);
4729 int ufshcd_hba_enable(struct ufs_hba *hba)
4733 if (hba->quirks & UFSHCI_QUIRK_BROKEN_HCE) {
4734 ufshcd_set_link_off(hba);
4735 ufshcd_vops_hce_enable_notify(hba, PRE_CHANGE);
4737 /* enable UIC related interrupts */
4738 ufshcd_enable_intr(hba, UFSHCD_UIC_MASK);
4739 ret = ufshcd_dme_reset(hba);
4741 dev_err(hba->dev, "DME_RESET failed\n");
4745 ret = ufshcd_dme_enable(hba);
4747 dev_err(hba->dev, "Enabling DME failed\n");
4751 ufshcd_vops_hce_enable_notify(hba, POST_CHANGE);
4753 ret = ufshcd_hba_execute_hce(hba);
4758 EXPORT_SYMBOL_GPL(ufshcd_hba_enable);
4760 static int ufshcd_disable_tx_lcc(struct ufs_hba *hba, bool peer)
4762 int tx_lanes = 0, i, err = 0;
4765 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_CONNECTEDTXDATALANES),
4768 ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_CONNECTEDTXDATALANES),
4770 for (i = 0; i < tx_lanes; i++) {
4772 err = ufshcd_dme_set(hba,
4773 UIC_ARG_MIB_SEL(TX_LCC_ENABLE,
4774 UIC_ARG_MPHY_TX_GEN_SEL_INDEX(i)),
4777 err = ufshcd_dme_peer_set(hba,
4778 UIC_ARG_MIB_SEL(TX_LCC_ENABLE,
4779 UIC_ARG_MPHY_TX_GEN_SEL_INDEX(i)),
4782 dev_err(hba->dev, "%s: TX LCC Disable failed, peer = %d, lane = %d, err = %d",
4783 __func__, peer, i, err);
4791 static inline int ufshcd_disable_device_tx_lcc(struct ufs_hba *hba)
4793 return ufshcd_disable_tx_lcc(hba, true);
4796 void ufshcd_update_evt_hist(struct ufs_hba *hba, u32 id, u32 val)
4798 struct ufs_event_hist *e;
4800 if (id >= UFS_EVT_CNT)
4803 e = &hba->ufs_stats.event[id];
4804 e->val[e->pos] = val;
4805 e->tstamp[e->pos] = local_clock();
4807 e->pos = (e->pos + 1) % UFS_EVENT_HIST_LENGTH;
4809 ufshcd_vops_event_notify(hba, id, &val);
4811 EXPORT_SYMBOL_GPL(ufshcd_update_evt_hist);
4814 * ufshcd_link_startup - Initialize unipro link startup
4815 * @hba: per adapter instance
4817 * Return: 0 for success, non-zero in case of failure.
4819 static int ufshcd_link_startup(struct ufs_hba *hba)
4822 int retries = DME_LINKSTARTUP_RETRIES;
4823 bool link_startup_again = false;
4826 * If UFS device isn't active then we will have to issue link startup
4827 * 2 times to make sure the device state move to active.
4829 if (!ufshcd_is_ufs_dev_active(hba))
4830 link_startup_again = true;
4834 ufshcd_vops_link_startup_notify(hba, PRE_CHANGE);
4836 ret = ufshcd_dme_link_startup(hba);
4838 /* check if device is detected by inter-connect layer */
4839 if (!ret && !ufshcd_is_device_present(hba)) {
4840 ufshcd_update_evt_hist(hba,
4841 UFS_EVT_LINK_STARTUP_FAIL,
4843 dev_err(hba->dev, "%s: Device not present\n", __func__);
4849 * DME link lost indication is only received when link is up,
4850 * but we can't be sure if the link is up until link startup
4851 * succeeds. So reset the local Uni-Pro and try again.
4853 if (ret && retries && ufshcd_hba_enable(hba)) {
4854 ufshcd_update_evt_hist(hba,
4855 UFS_EVT_LINK_STARTUP_FAIL,
4859 } while (ret && retries--);
4862 /* failed to get the link up... retire */
4863 ufshcd_update_evt_hist(hba,
4864 UFS_EVT_LINK_STARTUP_FAIL,
4869 if (link_startup_again) {
4870 link_startup_again = false;
4871 retries = DME_LINKSTARTUP_RETRIES;
4875 /* Mark that link is up in PWM-G1, 1-lane, SLOW-AUTO mode */
4876 ufshcd_init_pwr_info(hba);
4877 ufshcd_print_pwr_info(hba);
4879 if (hba->quirks & UFSHCD_QUIRK_BROKEN_LCC) {
4880 ret = ufshcd_disable_device_tx_lcc(hba);
4885 /* Include any host controller configuration via UIC commands */
4886 ret = ufshcd_vops_link_startup_notify(hba, POST_CHANGE);
4890 /* Clear UECPA once due to LINERESET has happened during LINK_STARTUP */
4891 ufshcd_readl(hba, REG_UIC_ERROR_CODE_PHY_ADAPTER_LAYER);
4892 ret = ufshcd_make_hba_operational(hba);
4895 dev_err(hba->dev, "link startup failed %d\n", ret);
4896 ufshcd_print_host_state(hba);
4897 ufshcd_print_pwr_info(hba);
4898 ufshcd_print_evt_hist(hba);
4904 * ufshcd_verify_dev_init() - Verify device initialization
4905 * @hba: per-adapter instance
4907 * Send NOP OUT UPIU and wait for NOP IN response to check whether the
4908 * device Transport Protocol (UTP) layer is ready after a reset.
4909 * If the UTP layer at the device side is not initialized, it may
4910 * not respond with NOP IN UPIU within timeout of %NOP_OUT_TIMEOUT
4911 * and we retry sending NOP OUT for %NOP_OUT_RETRIES iterations.
4913 * Return: 0 upon success; < 0 upon failure.
4915 static int ufshcd_verify_dev_init(struct ufs_hba *hba)
4921 mutex_lock(&hba->dev_cmd.lock);
4922 for (retries = NOP_OUT_RETRIES; retries > 0; retries--) {
4923 err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_NOP,
4924 hba->nop_out_timeout);
4926 if (!err || err == -ETIMEDOUT)
4929 dev_dbg(hba->dev, "%s: error %d retrying\n", __func__, err);
4931 mutex_unlock(&hba->dev_cmd.lock);
4932 ufshcd_release(hba);
4935 dev_err(hba->dev, "%s: NOP OUT failed %d\n", __func__, err);
4940 * ufshcd_setup_links - associate link b/w device wlun and other luns
4941 * @sdev: pointer to SCSI device
4942 * @hba: pointer to ufs hba
4944 static void ufshcd_setup_links(struct ufs_hba *hba, struct scsi_device *sdev)
4946 struct device_link *link;
4949 * Device wlun is the supplier & rest of the luns are consumers.
4950 * This ensures that device wlun suspends after all other luns.
4952 if (hba->ufs_device_wlun) {
4953 link = device_link_add(&sdev->sdev_gendev,
4954 &hba->ufs_device_wlun->sdev_gendev,
4955 DL_FLAG_PM_RUNTIME | DL_FLAG_RPM_ACTIVE);
4957 dev_err(&sdev->sdev_gendev, "Failed establishing link - %s\n",
4958 dev_name(&hba->ufs_device_wlun->sdev_gendev));
4962 /* Ignore REPORT_LUN wlun probing */
4963 if (hba->luns_avail == 1) {
4964 ufshcd_rpm_put(hba);
4969 * Device wlun is probed. The assumption is that WLUNs are
4970 * scanned before other LUNs.
4977 * ufshcd_lu_init - Initialize the relevant parameters of the LU
4978 * @hba: per-adapter instance
4979 * @sdev: pointer to SCSI device
4981 static void ufshcd_lu_init(struct ufs_hba *hba, struct scsi_device *sdev)
4983 int len = QUERY_DESC_MAX_SIZE;
4984 u8 lun = ufshcd_scsi_to_upiu_lun(sdev->lun);
4985 u8 lun_qdepth = hba->nutrs;
4989 desc_buf = kzalloc(len, GFP_KERNEL);
4993 ret = ufshcd_read_unit_desc_param(hba, lun, 0, desc_buf, len);
4995 if (ret == -EOPNOTSUPP)
4996 /* If LU doesn't support unit descriptor, its queue depth is set to 1 */
5002 if (desc_buf[UNIT_DESC_PARAM_LU_Q_DEPTH]) {
5004 * In per-LU queueing architecture, bLUQueueDepth will not be 0, then we will
5005 * use the smaller between UFSHCI CAP.NUTRS and UFS LU bLUQueueDepth
5007 lun_qdepth = min_t(int, desc_buf[UNIT_DESC_PARAM_LU_Q_DEPTH], hba->nutrs);
5010 * According to UFS device specification, the write protection mode is only supported by
5011 * normal LU, not supported by WLUN.
5013 if (hba->dev_info.f_power_on_wp_en && lun < hba->dev_info.max_lu_supported &&
5014 !hba->dev_info.is_lu_power_on_wp &&
5015 desc_buf[UNIT_DESC_PARAM_LU_WR_PROTECT] == UFS_LU_POWER_ON_WP)
5016 hba->dev_info.is_lu_power_on_wp = true;
5018 /* In case of RPMB LU, check if advanced RPMB mode is enabled */
5019 if (desc_buf[UNIT_DESC_PARAM_UNIT_INDEX] == UFS_UPIU_RPMB_WLUN &&
5020 desc_buf[RPMB_UNIT_DESC_PARAM_REGION_EN] & BIT(4))
5021 hba->dev_info.b_advanced_rpmb_en = true;
5027 * For WLUNs that don't support unit descriptor, queue depth is set to 1. For LUs whose
5028 * bLUQueueDepth == 0, the queue depth is set to a maximum value that host can queue.
5030 dev_dbg(hba->dev, "Set LU %x queue depth %d\n", lun, lun_qdepth);
5031 scsi_change_queue_depth(sdev, lun_qdepth);
5035 * ufshcd_slave_alloc - handle initial SCSI device configurations
5036 * @sdev: pointer to SCSI device
5040 static int ufshcd_slave_alloc(struct scsi_device *sdev)
5042 struct ufs_hba *hba;
5044 hba = shost_priv(sdev->host);
5046 /* Mode sense(6) is not supported by UFS, so use Mode sense(10) */
5047 sdev->use_10_for_ms = 1;
5049 /* DBD field should be set to 1 in mode sense(10) */
5050 sdev->set_dbd_for_ms = 1;
5052 /* allow SCSI layer to restart the device in case of errors */
5053 sdev->allow_restart = 1;
5055 /* REPORT SUPPORTED OPERATION CODES is not supported */
5056 sdev->no_report_opcodes = 1;
5058 /* WRITE_SAME command is not supported */
5059 sdev->no_write_same = 1;
5061 ufshcd_lu_init(hba, sdev);
5063 ufshcd_setup_links(hba, sdev);
5069 * ufshcd_change_queue_depth - change queue depth
5070 * @sdev: pointer to SCSI device
5071 * @depth: required depth to set
5073 * Change queue depth and make sure the max. limits are not crossed.
5075 * Return: new queue depth.
5077 static int ufshcd_change_queue_depth(struct scsi_device *sdev, int depth)
5079 return scsi_change_queue_depth(sdev, min(depth, sdev->host->can_queue));
5083 * ufshcd_slave_configure - adjust SCSI device configurations
5084 * @sdev: pointer to SCSI device
5086 * Return: 0 (success).
5088 static int ufshcd_slave_configure(struct scsi_device *sdev)
5090 struct ufs_hba *hba = shost_priv(sdev->host);
5091 struct request_queue *q = sdev->request_queue;
5093 blk_queue_update_dma_pad(q, PRDT_DATA_BYTE_COUNT_PAD - 1);
5096 * Block runtime-pm until all consumers are added.
5097 * Refer ufshcd_setup_links().
5099 if (is_device_wlun(sdev))
5100 pm_runtime_get_noresume(&sdev->sdev_gendev);
5101 else if (ufshcd_is_rpm_autosuspend_allowed(hba))
5102 sdev->rpm_autosuspend = 1;
5104 * Do not print messages during runtime PM to avoid never-ending cycles
5105 * of messages written back to storage by user space causing runtime
5106 * resume, causing more messages and so on.
5108 sdev->silence_suspend = 1;
5110 if (hba->vops && hba->vops->config_scsi_dev)
5111 hba->vops->config_scsi_dev(sdev);
5113 ufshcd_crypto_register(hba, q);
5119 * ufshcd_slave_destroy - remove SCSI device configurations
5120 * @sdev: pointer to SCSI device
5122 static void ufshcd_slave_destroy(struct scsi_device *sdev)
5124 struct ufs_hba *hba;
5125 unsigned long flags;
5127 hba = shost_priv(sdev->host);
5129 /* Drop the reference as it won't be needed anymore */
5130 if (ufshcd_scsi_to_upiu_lun(sdev->lun) == UFS_UPIU_UFS_DEVICE_WLUN) {
5131 spin_lock_irqsave(hba->host->host_lock, flags);
5132 hba->ufs_device_wlun = NULL;
5133 spin_unlock_irqrestore(hba->host->host_lock, flags);
5134 } else if (hba->ufs_device_wlun) {
5135 struct device *supplier = NULL;
5137 /* Ensure UFS Device WLUN exists and does not disappear */
5138 spin_lock_irqsave(hba->host->host_lock, flags);
5139 if (hba->ufs_device_wlun) {
5140 supplier = &hba->ufs_device_wlun->sdev_gendev;
5141 get_device(supplier);
5143 spin_unlock_irqrestore(hba->host->host_lock, flags);
5147 * If a LUN fails to probe (e.g. absent BOOT WLUN), the
5148 * device will not have been registered but can still
5149 * have a device link holding a reference to the device.
5151 device_link_remove(&sdev->sdev_gendev, supplier);
5152 put_device(supplier);
5158 * ufshcd_scsi_cmd_status - Update SCSI command result based on SCSI status
5159 * @lrbp: pointer to local reference block of completed command
5160 * @scsi_status: SCSI command status
5162 * Return: value base on SCSI command status.
5165 ufshcd_scsi_cmd_status(struct ufshcd_lrb *lrbp, int scsi_status)
5169 switch (scsi_status) {
5170 case SAM_STAT_CHECK_CONDITION:
5171 ufshcd_copy_sense_data(lrbp);
5174 result |= DID_OK << 16 | scsi_status;
5176 case SAM_STAT_TASK_SET_FULL:
5178 case SAM_STAT_TASK_ABORTED:
5179 ufshcd_copy_sense_data(lrbp);
5180 result |= scsi_status;
5183 result |= DID_ERROR << 16;
5185 } /* end of switch */
5191 * ufshcd_transfer_rsp_status - Get overall status of the response
5192 * @hba: per adapter instance
5193 * @lrbp: pointer to local reference block of completed command
5194 * @cqe: pointer to the completion queue entry
5196 * Return: result of the command to notify SCSI midlayer.
5199 ufshcd_transfer_rsp_status(struct ufs_hba *hba, struct ufshcd_lrb *lrbp,
5200 struct cq_entry *cqe)
5208 upiu_flags = lrbp->ucd_rsp_ptr->header.flags;
5209 resid = be32_to_cpu(lrbp->ucd_rsp_ptr->sr.residual_transfer_count);
5211 * Test !overflow instead of underflow to support UFS devices that do
5212 * not set either flag.
5214 if (resid && !(upiu_flags & UPIU_RSP_FLAG_OVERFLOW))
5215 scsi_set_resid(lrbp->cmd, resid);
5217 /* overall command status of utrd */
5218 ocs = ufshcd_get_tr_ocs(lrbp, cqe);
5220 if (hba->quirks & UFSHCD_QUIRK_BROKEN_OCS_FATAL_ERROR) {
5221 if (lrbp->ucd_rsp_ptr->header.response ||
5222 lrbp->ucd_rsp_ptr->header.status)
5228 hba->ufs_stats.last_hibern8_exit_tstamp = ktime_set(0, 0);
5229 switch (ufshcd_get_req_rsp(lrbp->ucd_rsp_ptr)) {
5230 case UPIU_TRANSACTION_RESPONSE:
5232 * get the result based on SCSI status response
5233 * to notify the SCSI midlayer of the command status
5235 scsi_status = lrbp->ucd_rsp_ptr->header.status;
5236 result = ufshcd_scsi_cmd_status(lrbp, scsi_status);
5239 * Currently we are only supporting BKOPs exception
5240 * events hence we can ignore BKOPs exception event
5241 * during power management callbacks. BKOPs exception
5242 * event is not expected to be raised in runtime suspend
5243 * callback as it allows the urgent bkops.
5244 * During system suspend, we are anyway forcefully
5245 * disabling the bkops and if urgent bkops is needed
5246 * it will be enabled on system resume. Long term
5247 * solution could be to abort the system suspend if
5248 * UFS device needs urgent BKOPs.
5250 if (!hba->pm_op_in_progress &&
5251 !ufshcd_eh_in_progress(hba) &&
5252 ufshcd_is_exception_event(lrbp->ucd_rsp_ptr))
5253 /* Flushed in suspend */
5254 schedule_work(&hba->eeh_work);
5256 case UPIU_TRANSACTION_REJECT_UPIU:
5257 /* TODO: handle Reject UPIU Response */
5258 result = DID_ERROR << 16;
5260 "Reject UPIU not fully implemented\n");
5264 "Unexpected request response code = %x\n",
5266 result = DID_ERROR << 16;
5271 result |= DID_ABORT << 16;
5273 case OCS_INVALID_COMMAND_STATUS:
5274 result |= DID_REQUEUE << 16;
5276 case OCS_INVALID_CMD_TABLE_ATTR:
5277 case OCS_INVALID_PRDT_ATTR:
5278 case OCS_MISMATCH_DATA_BUF_SIZE:
5279 case OCS_MISMATCH_RESP_UPIU_SIZE:
5280 case OCS_PEER_COMM_FAILURE:
5281 case OCS_FATAL_ERROR:
5282 case OCS_DEVICE_FATAL_ERROR:
5283 case OCS_INVALID_CRYPTO_CONFIG:
5284 case OCS_GENERAL_CRYPTO_ERROR:
5286 result |= DID_ERROR << 16;
5288 "OCS error from controller = %x for tag %d\n",
5289 ocs, lrbp->task_tag);
5290 ufshcd_print_evt_hist(hba);
5291 ufshcd_print_host_state(hba);
5293 } /* end of switch */
5295 if ((host_byte(result) != DID_OK) &&
5296 (host_byte(result) != DID_REQUEUE) && !hba->silence_err_logs)
5297 ufshcd_print_tr(hba, lrbp->task_tag, true);
5301 static bool ufshcd_is_auto_hibern8_error(struct ufs_hba *hba,
5304 if (!ufshcd_is_auto_hibern8_supported(hba) ||
5305 !ufshcd_is_auto_hibern8_enabled(hba))
5308 if (!(intr_mask & UFSHCD_UIC_HIBERN8_MASK))
5311 if (hba->active_uic_cmd &&
5312 (hba->active_uic_cmd->command == UIC_CMD_DME_HIBER_ENTER ||
5313 hba->active_uic_cmd->command == UIC_CMD_DME_HIBER_EXIT))
5320 * ufshcd_uic_cmd_compl - handle completion of uic command
5321 * @hba: per adapter instance
5322 * @intr_status: interrupt status generated by the controller
5325 * IRQ_HANDLED - If interrupt is valid
5326 * IRQ_NONE - If invalid interrupt
5328 static irqreturn_t ufshcd_uic_cmd_compl(struct ufs_hba *hba, u32 intr_status)
5330 irqreturn_t retval = IRQ_NONE;
5332 spin_lock(hba->host->host_lock);
5333 if (ufshcd_is_auto_hibern8_error(hba, intr_status))
5334 hba->errors |= (UFSHCD_UIC_HIBERN8_MASK & intr_status);
5336 if ((intr_status & UIC_COMMAND_COMPL) && hba->active_uic_cmd) {
5337 hba->active_uic_cmd->argument2 |=
5338 ufshcd_get_uic_cmd_result(hba);
5339 hba->active_uic_cmd->argument3 =
5340 ufshcd_get_dme_attr_val(hba);
5341 if (!hba->uic_async_done)
5342 hba->active_uic_cmd->cmd_active = 0;
5343 complete(&hba->active_uic_cmd->done);
5344 retval = IRQ_HANDLED;
5347 if ((intr_status & UFSHCD_UIC_PWR_MASK) && hba->uic_async_done) {
5348 hba->active_uic_cmd->cmd_active = 0;
5349 complete(hba->uic_async_done);
5350 retval = IRQ_HANDLED;
5353 if (retval == IRQ_HANDLED)
5354 ufshcd_add_uic_command_trace(hba, hba->active_uic_cmd,
5356 spin_unlock(hba->host->host_lock);
5360 /* Release the resources allocated for processing a SCSI command. */
5361 void ufshcd_release_scsi_cmd(struct ufs_hba *hba,
5362 struct ufshcd_lrb *lrbp)
5364 struct scsi_cmnd *cmd = lrbp->cmd;
5366 scsi_dma_unmap(cmd);
5367 ufshcd_release(hba);
5368 ufshcd_clk_scaling_update_busy(hba);
5372 * ufshcd_compl_one_cqe - handle a completion queue entry
5373 * @hba: per adapter instance
5374 * @task_tag: the task tag of the request to be completed
5375 * @cqe: pointer to the completion queue entry
5377 void ufshcd_compl_one_cqe(struct ufs_hba *hba, int task_tag,
5378 struct cq_entry *cqe)
5380 struct ufshcd_lrb *lrbp;
5381 struct scsi_cmnd *cmd;
5384 lrbp = &hba->lrb[task_tag];
5385 lrbp->compl_time_stamp = ktime_get();
5388 if (unlikely(ufshcd_should_inform_monitor(hba, lrbp)))
5389 ufshcd_update_monitor(hba, lrbp);
5390 ufshcd_add_command_trace(hba, task_tag, UFS_CMD_COMP);
5391 cmd->result = ufshcd_transfer_rsp_status(hba, lrbp, cqe);
5392 ufshcd_release_scsi_cmd(hba, lrbp);
5393 /* Do not touch lrbp after scsi done */
5395 } else if (lrbp->command_type == UTP_CMD_TYPE_DEV_MANAGE ||
5396 lrbp->command_type == UTP_CMD_TYPE_UFS_STORAGE) {
5397 if (hba->dev_cmd.complete) {
5399 ocs = le32_to_cpu(cqe->status) & MASK_OCS;
5400 lrbp->utr_descriptor_ptr->header.ocs = ocs;
5402 complete(hba->dev_cmd.complete);
5408 * __ufshcd_transfer_req_compl - handle SCSI and query command completion
5409 * @hba: per adapter instance
5410 * @completed_reqs: bitmask that indicates which requests to complete
5412 static void __ufshcd_transfer_req_compl(struct ufs_hba *hba,
5413 unsigned long completed_reqs)
5417 for_each_set_bit(tag, &completed_reqs, hba->nutrs)
5418 ufshcd_compl_one_cqe(hba, tag, NULL);
5421 /* Any value that is not an existing queue number is fine for this constant. */
5423 UFSHCD_POLL_FROM_INTERRUPT_CONTEXT = -1
5426 static void ufshcd_clear_polled(struct ufs_hba *hba,
5427 unsigned long *completed_reqs)
5431 for_each_set_bit(tag, completed_reqs, hba->nutrs) {
5432 struct scsi_cmnd *cmd = hba->lrb[tag].cmd;
5436 if (scsi_cmd_to_rq(cmd)->cmd_flags & REQ_POLLED)
5437 __clear_bit(tag, completed_reqs);
5442 * Return: > 0 if one or more commands have been completed or 0 if no
5443 * requests have been completed.
5445 static int ufshcd_poll(struct Scsi_Host *shost, unsigned int queue_num)
5447 struct ufs_hba *hba = shost_priv(shost);
5448 unsigned long completed_reqs, flags;
5450 struct ufs_hw_queue *hwq;
5452 if (is_mcq_enabled(hba)) {
5453 hwq = &hba->uhq[queue_num];
5455 return ufshcd_mcq_poll_cqe_lock(hba, hwq);
5458 spin_lock_irqsave(&hba->outstanding_lock, flags);
5459 tr_doorbell = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
5460 completed_reqs = ~tr_doorbell & hba->outstanding_reqs;
5461 WARN_ONCE(completed_reqs & ~hba->outstanding_reqs,
5462 "completed: %#lx; outstanding: %#lx\n", completed_reqs,
5463 hba->outstanding_reqs);
5464 if (queue_num == UFSHCD_POLL_FROM_INTERRUPT_CONTEXT) {
5465 /* Do not complete polled requests from interrupt context. */
5466 ufshcd_clear_polled(hba, &completed_reqs);
5468 hba->outstanding_reqs &= ~completed_reqs;
5469 spin_unlock_irqrestore(&hba->outstanding_lock, flags);
5472 __ufshcd_transfer_req_compl(hba, completed_reqs);
5474 return completed_reqs != 0;
5478 * ufshcd_mcq_compl_pending_transfer - MCQ mode function. It is
5479 * invoked from the error handler context or ufshcd_host_reset_and_restore()
5480 * to complete the pending transfers and free the resources associated with
5483 * @hba: per adapter instance
5484 * @force_compl: This flag is set to true when invoked
5485 * from ufshcd_host_reset_and_restore() in which case it requires special
5486 * handling because the host controller has been reset by ufshcd_hba_stop().
5488 static void ufshcd_mcq_compl_pending_transfer(struct ufs_hba *hba,
5491 struct ufs_hw_queue *hwq;
5492 struct ufshcd_lrb *lrbp;
5493 struct scsi_cmnd *cmd;
5494 unsigned long flags;
5498 for (tag = 0; tag < hba->nutrs; tag++) {
5499 lrbp = &hba->lrb[tag];
5501 if (!ufshcd_cmd_inflight(cmd) ||
5502 test_bit(SCMD_STATE_COMPLETE, &cmd->state))
5505 utag = blk_mq_unique_tag(scsi_cmd_to_rq(cmd));
5506 hwq_num = blk_mq_unique_tag_to_hwq(utag);
5507 hwq = &hba->uhq[hwq_num];
5510 ufshcd_mcq_compl_all_cqes_lock(hba, hwq);
5512 * For those cmds of which the cqes are not present
5513 * in the cq, complete them explicitly.
5515 if (cmd && !test_bit(SCMD_STATE_COMPLETE, &cmd->state)) {
5516 spin_lock_irqsave(&hwq->cq_lock, flags);
5517 set_host_byte(cmd, DID_REQUEUE);
5518 ufshcd_release_scsi_cmd(hba, lrbp);
5520 spin_unlock_irqrestore(&hwq->cq_lock, flags);
5523 ufshcd_mcq_poll_cqe_lock(hba, hwq);
5529 * ufshcd_transfer_req_compl - handle SCSI and query command completion
5530 * @hba: per adapter instance
5533 * IRQ_HANDLED - If interrupt is valid
5534 * IRQ_NONE - If invalid interrupt
5536 static irqreturn_t ufshcd_transfer_req_compl(struct ufs_hba *hba)
5538 /* Resetting interrupt aggregation counters first and reading the
5539 * DOOR_BELL afterward allows us to handle all the completed requests.
5540 * In order to prevent other interrupts starvation the DB is read once
5541 * after reset. The down side of this solution is the possibility of
5542 * false interrupt if device completes another request after resetting
5543 * aggregation and before reading the DB.
5545 if (ufshcd_is_intr_aggr_allowed(hba) &&
5546 !(hba->quirks & UFSHCI_QUIRK_SKIP_RESET_INTR_AGGR))
5547 ufshcd_reset_intr_aggr(hba);
5549 if (ufs_fail_completion())
5553 * Ignore the ufshcd_poll() return value and return IRQ_HANDLED since we
5554 * do not want polling to trigger spurious interrupt complaints.
5556 ufshcd_poll(hba->host, UFSHCD_POLL_FROM_INTERRUPT_CONTEXT);
5561 int __ufshcd_write_ee_control(struct ufs_hba *hba, u32 ee_ctrl_mask)
5563 return ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_WRITE_ATTR,
5564 QUERY_ATTR_IDN_EE_CONTROL, 0, 0,
5568 int ufshcd_write_ee_control(struct ufs_hba *hba)
5572 mutex_lock(&hba->ee_ctrl_mutex);
5573 err = __ufshcd_write_ee_control(hba, hba->ee_ctrl_mask);
5574 mutex_unlock(&hba->ee_ctrl_mutex);
5576 dev_err(hba->dev, "%s: failed to write ee control %d\n",
5581 int ufshcd_update_ee_control(struct ufs_hba *hba, u16 *mask,
5582 const u16 *other_mask, u16 set, u16 clr)
5584 u16 new_mask, ee_ctrl_mask;
5587 mutex_lock(&hba->ee_ctrl_mutex);
5588 new_mask = (*mask & ~clr) | set;
5589 ee_ctrl_mask = new_mask | *other_mask;
5590 if (ee_ctrl_mask != hba->ee_ctrl_mask)
5591 err = __ufshcd_write_ee_control(hba, ee_ctrl_mask);
5592 /* Still need to update 'mask' even if 'ee_ctrl_mask' was unchanged */
5594 hba->ee_ctrl_mask = ee_ctrl_mask;
5597 mutex_unlock(&hba->ee_ctrl_mutex);
5602 * ufshcd_disable_ee - disable exception event
5603 * @hba: per-adapter instance
5604 * @mask: exception event to disable
5606 * Disables exception event in the device so that the EVENT_ALERT
5609 * Return: zero on success, non-zero error value on failure.
5611 static inline int ufshcd_disable_ee(struct ufs_hba *hba, u16 mask)
5613 return ufshcd_update_ee_drv_mask(hba, 0, mask);
5617 * ufshcd_enable_ee - enable exception event
5618 * @hba: per-adapter instance
5619 * @mask: exception event to enable
5621 * Enable corresponding exception event in the device to allow
5622 * device to alert host in critical scenarios.
5624 * Return: zero on success, non-zero error value on failure.
5626 static inline int ufshcd_enable_ee(struct ufs_hba *hba, u16 mask)
5628 return ufshcd_update_ee_drv_mask(hba, mask, 0);
5632 * ufshcd_enable_auto_bkops - Allow device managed BKOPS
5633 * @hba: per-adapter instance
5635 * Allow device to manage background operations on its own. Enabling
5636 * this might lead to inconsistent latencies during normal data transfers
5637 * as the device is allowed to manage its own way of handling background
5640 * Return: zero on success, non-zero on failure.
5642 static int ufshcd_enable_auto_bkops(struct ufs_hba *hba)
5646 if (hba->auto_bkops_enabled)
5649 err = ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_SET_FLAG,
5650 QUERY_FLAG_IDN_BKOPS_EN, 0, NULL);
5652 dev_err(hba->dev, "%s: failed to enable bkops %d\n",
5657 hba->auto_bkops_enabled = true;
5658 trace_ufshcd_auto_bkops_state(dev_name(hba->dev), "Enabled");
5660 /* No need of URGENT_BKOPS exception from the device */
5661 err = ufshcd_disable_ee(hba, MASK_EE_URGENT_BKOPS);
5663 dev_err(hba->dev, "%s: failed to disable exception event %d\n",
5670 * ufshcd_disable_auto_bkops - block device in doing background operations
5671 * @hba: per-adapter instance
5673 * Disabling background operations improves command response latency but
5674 * has drawback of device moving into critical state where the device is
5675 * not-operable. Make sure to call ufshcd_enable_auto_bkops() whenever the
5676 * host is idle so that BKOPS are managed effectively without any negative
5679 * Return: zero on success, non-zero on failure.
5681 static int ufshcd_disable_auto_bkops(struct ufs_hba *hba)
5685 if (!hba->auto_bkops_enabled)
5689 * If host assisted BKOPs is to be enabled, make sure
5690 * urgent bkops exception is allowed.
5692 err = ufshcd_enable_ee(hba, MASK_EE_URGENT_BKOPS);
5694 dev_err(hba->dev, "%s: failed to enable exception event %d\n",
5699 err = ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_CLEAR_FLAG,
5700 QUERY_FLAG_IDN_BKOPS_EN, 0, NULL);
5702 dev_err(hba->dev, "%s: failed to disable bkops %d\n",
5704 ufshcd_disable_ee(hba, MASK_EE_URGENT_BKOPS);
5708 hba->auto_bkops_enabled = false;
5709 trace_ufshcd_auto_bkops_state(dev_name(hba->dev), "Disabled");
5710 hba->is_urgent_bkops_lvl_checked = false;
5716 * ufshcd_force_reset_auto_bkops - force reset auto bkops state
5717 * @hba: per adapter instance
5719 * After a device reset the device may toggle the BKOPS_EN flag
5720 * to default value. The s/w tracking variables should be updated
5721 * as well. This function would change the auto-bkops state based on
5722 * UFSHCD_CAP_KEEP_AUTO_BKOPS_ENABLED_EXCEPT_SUSPEND.
5724 static void ufshcd_force_reset_auto_bkops(struct ufs_hba *hba)
5726 if (ufshcd_keep_autobkops_enabled_except_suspend(hba)) {
5727 hba->auto_bkops_enabled = false;
5728 hba->ee_ctrl_mask |= MASK_EE_URGENT_BKOPS;
5729 ufshcd_enable_auto_bkops(hba);
5731 hba->auto_bkops_enabled = true;
5732 hba->ee_ctrl_mask &= ~MASK_EE_URGENT_BKOPS;
5733 ufshcd_disable_auto_bkops(hba);
5735 hba->urgent_bkops_lvl = BKOPS_STATUS_PERF_IMPACT;
5736 hba->is_urgent_bkops_lvl_checked = false;
5739 static inline int ufshcd_get_bkops_status(struct ufs_hba *hba, u32 *status)
5741 return ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
5742 QUERY_ATTR_IDN_BKOPS_STATUS, 0, 0, status);
5746 * ufshcd_bkops_ctrl - control the auto bkops based on current bkops status
5747 * @hba: per-adapter instance
5748 * @status: bkops_status value
5750 * Read the bkops_status from the UFS device and Enable fBackgroundOpsEn
5751 * flag in the device to permit background operations if the device
5752 * bkops_status is greater than or equal to "status" argument passed to
5753 * this function, disable otherwise.
5755 * Return: 0 for success, non-zero in case of failure.
5757 * NOTE: Caller of this function can check the "hba->auto_bkops_enabled" flag
5758 * to know whether auto bkops is enabled or disabled after this function
5759 * returns control to it.
5761 static int ufshcd_bkops_ctrl(struct ufs_hba *hba,
5762 enum bkops_status status)
5765 u32 curr_status = 0;
5767 err = ufshcd_get_bkops_status(hba, &curr_status);
5769 dev_err(hba->dev, "%s: failed to get BKOPS status %d\n",
5772 } else if (curr_status > BKOPS_STATUS_MAX) {
5773 dev_err(hba->dev, "%s: invalid BKOPS status %d\n",
5774 __func__, curr_status);
5779 if (curr_status >= status)
5780 err = ufshcd_enable_auto_bkops(hba);
5782 err = ufshcd_disable_auto_bkops(hba);
5788 * ufshcd_urgent_bkops - handle urgent bkops exception event
5789 * @hba: per-adapter instance
5791 * Enable fBackgroundOpsEn flag in the device to permit background
5794 * If BKOPs is enabled, this function returns 0, 1 if the bkops in not enabled
5795 * and negative error value for any other failure.
5797 * Return: 0 upon success; < 0 upon failure.
5799 static int ufshcd_urgent_bkops(struct ufs_hba *hba)
5801 return ufshcd_bkops_ctrl(hba, hba->urgent_bkops_lvl);
5804 static inline int ufshcd_get_ee_status(struct ufs_hba *hba, u32 *status)
5806 return ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
5807 QUERY_ATTR_IDN_EE_STATUS, 0, 0, status);
5810 static void ufshcd_bkops_exception_event_handler(struct ufs_hba *hba)
5813 u32 curr_status = 0;
5815 if (hba->is_urgent_bkops_lvl_checked)
5816 goto enable_auto_bkops;
5818 err = ufshcd_get_bkops_status(hba, &curr_status);
5820 dev_err(hba->dev, "%s: failed to get BKOPS status %d\n",
5826 * We are seeing that some devices are raising the urgent bkops
5827 * exception events even when BKOPS status doesn't indicate performace
5828 * impacted or critical. Handle these device by determining their urgent
5829 * bkops status at runtime.
5831 if (curr_status < BKOPS_STATUS_PERF_IMPACT) {
5832 dev_err(hba->dev, "%s: device raised urgent BKOPS exception for bkops status %d\n",
5833 __func__, curr_status);
5834 /* update the current status as the urgent bkops level */
5835 hba->urgent_bkops_lvl = curr_status;
5836 hba->is_urgent_bkops_lvl_checked = true;
5840 err = ufshcd_enable_auto_bkops(hba);
5843 dev_err(hba->dev, "%s: failed to handle urgent bkops %d\n",
5847 static void ufshcd_temp_exception_event_handler(struct ufs_hba *hba, u16 status)
5851 if (ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
5852 QUERY_ATTR_IDN_CASE_ROUGH_TEMP, 0, 0, &value))
5855 dev_info(hba->dev, "exception Tcase %d\n", value - 80);
5857 ufs_hwmon_notify_event(hba, status & MASK_EE_URGENT_TEMP);
5860 * A placeholder for the platform vendors to add whatever additional
5865 static int __ufshcd_wb_toggle(struct ufs_hba *hba, bool set, enum flag_idn idn)
5868 enum query_opcode opcode = set ? UPIU_QUERY_OPCODE_SET_FLAG :
5869 UPIU_QUERY_OPCODE_CLEAR_FLAG;
5871 index = ufshcd_wb_get_query_index(hba);
5872 return ufshcd_query_flag_retry(hba, opcode, idn, index, NULL);
5875 int ufshcd_wb_toggle(struct ufs_hba *hba, bool enable)
5879 if (!ufshcd_is_wb_allowed(hba) ||
5880 hba->dev_info.wb_enabled == enable)
5883 ret = __ufshcd_wb_toggle(hba, enable, QUERY_FLAG_IDN_WB_EN);
5885 dev_err(hba->dev, "%s: Write Booster %s failed %d\n",
5886 __func__, enable ? "enabling" : "disabling", ret);
5890 hba->dev_info.wb_enabled = enable;
5891 dev_dbg(hba->dev, "%s: Write Booster %s\n",
5892 __func__, enable ? "enabled" : "disabled");
5897 static void ufshcd_wb_toggle_buf_flush_during_h8(struct ufs_hba *hba,
5902 ret = __ufshcd_wb_toggle(hba, enable,
5903 QUERY_FLAG_IDN_WB_BUFF_FLUSH_DURING_HIBERN8);
5905 dev_err(hba->dev, "%s: WB-Buf Flush during H8 %s failed %d\n",
5906 __func__, enable ? "enabling" : "disabling", ret);
5909 dev_dbg(hba->dev, "%s: WB-Buf Flush during H8 %s\n",
5910 __func__, enable ? "enabled" : "disabled");
5913 int ufshcd_wb_toggle_buf_flush(struct ufs_hba *hba, bool enable)
5917 if (!ufshcd_is_wb_allowed(hba) ||
5918 hba->dev_info.wb_buf_flush_enabled == enable)
5921 ret = __ufshcd_wb_toggle(hba, enable, QUERY_FLAG_IDN_WB_BUFF_FLUSH_EN);
5923 dev_err(hba->dev, "%s: WB-Buf Flush %s failed %d\n",
5924 __func__, enable ? "enabling" : "disabling", ret);
5928 hba->dev_info.wb_buf_flush_enabled = enable;
5929 dev_dbg(hba->dev, "%s: WB-Buf Flush %s\n",
5930 __func__, enable ? "enabled" : "disabled");
5935 static bool ufshcd_wb_presrv_usrspc_keep_vcc_on(struct ufs_hba *hba,
5942 index = ufshcd_wb_get_query_index(hba);
5943 ret = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
5944 QUERY_ATTR_IDN_CURR_WB_BUFF_SIZE,
5945 index, 0, &cur_buf);
5947 dev_err(hba->dev, "%s: dCurWriteBoosterBufferSize read failed %d\n",
5953 dev_info(hba->dev, "dCurWBBuf: %d WB disabled until free-space is available\n",
5957 /* Let it continue to flush when available buffer exceeds threshold */
5958 return avail_buf < hba->vps->wb_flush_threshold;
5961 static void ufshcd_wb_force_disable(struct ufs_hba *hba)
5963 if (ufshcd_is_wb_buf_flush_allowed(hba))
5964 ufshcd_wb_toggle_buf_flush(hba, false);
5966 ufshcd_wb_toggle_buf_flush_during_h8(hba, false);
5967 ufshcd_wb_toggle(hba, false);
5968 hba->caps &= ~UFSHCD_CAP_WB_EN;
5970 dev_info(hba->dev, "%s: WB force disabled\n", __func__);
5973 static bool ufshcd_is_wb_buf_lifetime_available(struct ufs_hba *hba)
5979 index = ufshcd_wb_get_query_index(hba);
5980 ret = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
5981 QUERY_ATTR_IDN_WB_BUFF_LIFE_TIME_EST,
5982 index, 0, &lifetime);
5985 "%s: bWriteBoosterBufferLifeTimeEst read failed %d\n",
5990 if (lifetime == UFS_WB_EXCEED_LIFETIME) {
5991 dev_err(hba->dev, "%s: WB buf lifetime is exhausted 0x%02X\n",
5992 __func__, lifetime);
5996 dev_dbg(hba->dev, "%s: WB buf lifetime is 0x%02X\n",
5997 __func__, lifetime);
6002 static bool ufshcd_wb_need_flush(struct ufs_hba *hba)
6008 if (!ufshcd_is_wb_allowed(hba))
6011 if (!ufshcd_is_wb_buf_lifetime_available(hba)) {
6012 ufshcd_wb_force_disable(hba);
6017 * The ufs device needs the vcc to be ON to flush.
6018 * With user-space reduction enabled, it's enough to enable flush
6019 * by checking only the available buffer. The threshold
6020 * defined here is > 90% full.
6021 * With user-space preserved enabled, the current-buffer
6022 * should be checked too because the wb buffer size can reduce
6023 * when disk tends to be full. This info is provided by current
6024 * buffer (dCurrentWriteBoosterBufferSize). There's no point in
6025 * keeping vcc on when current buffer is empty.
6027 index = ufshcd_wb_get_query_index(hba);
6028 ret = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
6029 QUERY_ATTR_IDN_AVAIL_WB_BUFF_SIZE,
6030 index, 0, &avail_buf);
6032 dev_warn(hba->dev, "%s: dAvailableWriteBoosterBufferSize read failed %d\n",
6037 if (!hba->dev_info.b_presrv_uspc_en)
6038 return avail_buf <= UFS_WB_BUF_REMAIN_PERCENT(10);
6040 return ufshcd_wb_presrv_usrspc_keep_vcc_on(hba, avail_buf);
6043 static void ufshcd_rpm_dev_flush_recheck_work(struct work_struct *work)
6045 struct ufs_hba *hba = container_of(to_delayed_work(work),
6047 rpm_dev_flush_recheck_work);
6049 * To prevent unnecessary VCC power drain after device finishes
6050 * WriteBooster buffer flush or Auto BKOPs, force runtime resume
6051 * after a certain delay to recheck the threshold by next runtime
6054 ufshcd_rpm_get_sync(hba);
6055 ufshcd_rpm_put_sync(hba);
6059 * ufshcd_exception_event_handler - handle exceptions raised by device
6060 * @work: pointer to work data
6062 * Read bExceptionEventStatus attribute from the device and handle the
6063 * exception event accordingly.
6065 static void ufshcd_exception_event_handler(struct work_struct *work)
6067 struct ufs_hba *hba;
6070 hba = container_of(work, struct ufs_hba, eeh_work);
6072 ufshcd_scsi_block_requests(hba);
6073 err = ufshcd_get_ee_status(hba, &status);
6075 dev_err(hba->dev, "%s: failed to get exception status %d\n",
6080 trace_ufshcd_exception_event(dev_name(hba->dev), status);
6082 if (status & hba->ee_drv_mask & MASK_EE_URGENT_BKOPS)
6083 ufshcd_bkops_exception_event_handler(hba);
6085 if (status & hba->ee_drv_mask & MASK_EE_URGENT_TEMP)
6086 ufshcd_temp_exception_event_handler(hba, status);
6088 ufs_debugfs_exception_event(hba, status);
6090 ufshcd_scsi_unblock_requests(hba);
6093 /* Complete requests that have door-bell cleared */
6094 static void ufshcd_complete_requests(struct ufs_hba *hba, bool force_compl)
6096 if (is_mcq_enabled(hba))
6097 ufshcd_mcq_compl_pending_transfer(hba, force_compl);
6099 ufshcd_transfer_req_compl(hba);
6101 ufshcd_tmc_handler(hba);
6105 * ufshcd_quirk_dl_nac_errors - This function checks if error handling is
6106 * to recover from the DL NAC errors or not.
6107 * @hba: per-adapter instance
6109 * Return: true if error handling is required, false otherwise.
6111 static bool ufshcd_quirk_dl_nac_errors(struct ufs_hba *hba)
6113 unsigned long flags;
6114 bool err_handling = true;
6116 spin_lock_irqsave(hba->host->host_lock, flags);
6118 * UFS_DEVICE_QUIRK_RECOVERY_FROM_DL_NAC_ERRORS only workaround the
6119 * device fatal error and/or DL NAC & REPLAY timeout errors.
6121 if (hba->saved_err & (CONTROLLER_FATAL_ERROR | SYSTEM_BUS_FATAL_ERROR))
6124 if ((hba->saved_err & DEVICE_FATAL_ERROR) ||
6125 ((hba->saved_err & UIC_ERROR) &&
6126 (hba->saved_uic_err & UFSHCD_UIC_DL_TCx_REPLAY_ERROR)))
6129 if ((hba->saved_err & UIC_ERROR) &&
6130 (hba->saved_uic_err & UFSHCD_UIC_DL_NAC_RECEIVED_ERROR)) {
6133 * wait for 50ms to see if we can get any other errors or not.
6135 spin_unlock_irqrestore(hba->host->host_lock, flags);
6137 spin_lock_irqsave(hba->host->host_lock, flags);
6140 * now check if we have got any other severe errors other than
6143 if ((hba->saved_err & INT_FATAL_ERRORS) ||
6144 ((hba->saved_err & UIC_ERROR) &&
6145 (hba->saved_uic_err & ~UFSHCD_UIC_DL_NAC_RECEIVED_ERROR)))
6149 * As DL NAC is the only error received so far, send out NOP
6150 * command to confirm if link is still active or not.
6151 * - If we don't get any response then do error recovery.
6152 * - If we get response then clear the DL NAC error bit.
6155 spin_unlock_irqrestore(hba->host->host_lock, flags);
6156 err = ufshcd_verify_dev_init(hba);
6157 spin_lock_irqsave(hba->host->host_lock, flags);
6162 /* Link seems to be alive hence ignore the DL NAC errors */
6163 if (hba->saved_uic_err == UFSHCD_UIC_DL_NAC_RECEIVED_ERROR)
6164 hba->saved_err &= ~UIC_ERROR;
6165 /* clear NAC error */
6166 hba->saved_uic_err &= ~UFSHCD_UIC_DL_NAC_RECEIVED_ERROR;
6167 if (!hba->saved_uic_err)
6168 err_handling = false;
6171 spin_unlock_irqrestore(hba->host->host_lock, flags);
6172 return err_handling;
6175 /* host lock must be held before calling this func */
6176 static inline bool ufshcd_is_saved_err_fatal(struct ufs_hba *hba)
6178 return (hba->saved_uic_err & UFSHCD_UIC_DL_PA_INIT_ERROR) ||
6179 (hba->saved_err & (INT_FATAL_ERRORS | UFSHCD_UIC_HIBERN8_MASK));
6182 void ufshcd_schedule_eh_work(struct ufs_hba *hba)
6184 lockdep_assert_held(hba->host->host_lock);
6186 /* handle fatal errors only when link is not in error state */
6187 if (hba->ufshcd_state != UFSHCD_STATE_ERROR) {
6188 if (hba->force_reset || ufshcd_is_link_broken(hba) ||
6189 ufshcd_is_saved_err_fatal(hba))
6190 hba->ufshcd_state = UFSHCD_STATE_EH_SCHEDULED_FATAL;
6192 hba->ufshcd_state = UFSHCD_STATE_EH_SCHEDULED_NON_FATAL;
6193 queue_work(hba->eh_wq, &hba->eh_work);
6197 static void ufshcd_force_error_recovery(struct ufs_hba *hba)
6199 spin_lock_irq(hba->host->host_lock);
6200 hba->force_reset = true;
6201 ufshcd_schedule_eh_work(hba);
6202 spin_unlock_irq(hba->host->host_lock);
6205 static void ufshcd_clk_scaling_allow(struct ufs_hba *hba, bool allow)
6207 mutex_lock(&hba->wb_mutex);
6208 down_write(&hba->clk_scaling_lock);
6209 hba->clk_scaling.is_allowed = allow;
6210 up_write(&hba->clk_scaling_lock);
6211 mutex_unlock(&hba->wb_mutex);
6214 static void ufshcd_clk_scaling_suspend(struct ufs_hba *hba, bool suspend)
6217 if (hba->clk_scaling.is_enabled)
6218 ufshcd_suspend_clkscaling(hba);
6219 ufshcd_clk_scaling_allow(hba, false);
6221 ufshcd_clk_scaling_allow(hba, true);
6222 if (hba->clk_scaling.is_enabled)
6223 ufshcd_resume_clkscaling(hba);
6227 static void ufshcd_err_handling_prepare(struct ufs_hba *hba)
6229 ufshcd_rpm_get_sync(hba);
6230 if (pm_runtime_status_suspended(&hba->ufs_device_wlun->sdev_gendev) ||
6231 hba->is_sys_suspended) {
6232 enum ufs_pm_op pm_op;
6235 * Don't assume anything of resume, if
6236 * resume fails, irq and clocks can be OFF, and powers
6237 * can be OFF or in LPM.
6239 ufshcd_setup_hba_vreg(hba, true);
6240 ufshcd_enable_irq(hba);
6241 ufshcd_setup_vreg(hba, true);
6242 ufshcd_config_vreg_hpm(hba, hba->vreg_info.vccq);
6243 ufshcd_config_vreg_hpm(hba, hba->vreg_info.vccq2);
6245 if (!ufshcd_is_clkgating_allowed(hba))
6246 ufshcd_setup_clocks(hba, true);
6247 ufshcd_release(hba);
6248 pm_op = hba->is_sys_suspended ? UFS_SYSTEM_PM : UFS_RUNTIME_PM;
6249 ufshcd_vops_resume(hba, pm_op);
6252 if (ufshcd_is_clkscaling_supported(hba) &&
6253 hba->clk_scaling.is_enabled)
6254 ufshcd_suspend_clkscaling(hba);
6255 ufshcd_clk_scaling_allow(hba, false);
6257 ufshcd_scsi_block_requests(hba);
6258 /* Wait for ongoing ufshcd_queuecommand() calls to finish. */
6259 blk_mq_wait_quiesce_done(&hba->host->tag_set);
6260 cancel_work_sync(&hba->eeh_work);
6263 static void ufshcd_err_handling_unprepare(struct ufs_hba *hba)
6265 ufshcd_scsi_unblock_requests(hba);
6266 ufshcd_release(hba);
6267 if (ufshcd_is_clkscaling_supported(hba))
6268 ufshcd_clk_scaling_suspend(hba, false);
6269 ufshcd_rpm_put(hba);
6272 static inline bool ufshcd_err_handling_should_stop(struct ufs_hba *hba)
6274 return (!hba->is_powered || hba->shutting_down ||
6275 !hba->ufs_device_wlun ||
6276 hba->ufshcd_state == UFSHCD_STATE_ERROR ||
6277 (!(hba->saved_err || hba->saved_uic_err || hba->force_reset ||
6278 ufshcd_is_link_broken(hba))));
6282 static void ufshcd_recover_pm_error(struct ufs_hba *hba)
6284 struct Scsi_Host *shost = hba->host;
6285 struct scsi_device *sdev;
6286 struct request_queue *q;
6289 hba->is_sys_suspended = false;
6291 * Set RPM status of wlun device to RPM_ACTIVE,
6292 * this also clears its runtime error.
6294 ret = pm_runtime_set_active(&hba->ufs_device_wlun->sdev_gendev);
6296 /* hba device might have a runtime error otherwise */
6298 ret = pm_runtime_set_active(hba->dev);
6300 * If wlun device had runtime error, we also need to resume those
6301 * consumer scsi devices in case any of them has failed to be
6302 * resumed due to supplier runtime resume failure. This is to unblock
6303 * blk_queue_enter in case there are bios waiting inside it.
6306 shost_for_each_device(sdev, shost) {
6307 q = sdev->request_queue;
6308 if (q->dev && (q->rpm_status == RPM_SUSPENDED ||
6309 q->rpm_status == RPM_SUSPENDING))
6310 pm_request_resume(q->dev);
6315 static inline void ufshcd_recover_pm_error(struct ufs_hba *hba)
6320 static bool ufshcd_is_pwr_mode_restore_needed(struct ufs_hba *hba)
6322 struct ufs_pa_layer_attr *pwr_info = &hba->pwr_info;
6325 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_PWRMODE), &mode);
6327 if (pwr_info->pwr_rx != ((mode >> PWRMODE_RX_OFFSET) & PWRMODE_MASK))
6330 if (pwr_info->pwr_tx != (mode & PWRMODE_MASK))
6336 static bool ufshcd_abort_one(struct request *rq, void *priv)
6340 struct scsi_cmnd *cmd = blk_mq_rq_to_pdu(rq);
6341 struct scsi_device *sdev = cmd->device;
6342 struct Scsi_Host *shost = sdev->host;
6343 struct ufs_hba *hba = shost_priv(shost);
6345 *ret = ufshcd_try_to_abort_task(hba, tag);
6346 dev_err(hba->dev, "Aborting tag %d / CDB %#02x %s\n", tag,
6347 hba->lrb[tag].cmd ? hba->lrb[tag].cmd->cmnd[0] : -1,
6348 *ret ? "failed" : "succeeded");
6353 * ufshcd_abort_all - Abort all pending commands.
6354 * @hba: Host bus adapter pointer.
6356 * Return: true if and only if the host controller needs to be reset.
6358 static bool ufshcd_abort_all(struct ufs_hba *hba)
6362 blk_mq_tagset_busy_iter(&hba->host->tag_set, ufshcd_abort_one, &ret);
6366 /* Clear pending task management requests */
6367 for_each_set_bit(tag, &hba->outstanding_tasks, hba->nutmrs) {
6368 ret = ufshcd_clear_tm_cmd(hba, tag);
6374 /* Complete the requests that are cleared by s/w */
6375 ufshcd_complete_requests(hba, false);
6381 * ufshcd_err_handler - handle UFS errors that require s/w attention
6382 * @work: pointer to work structure
6384 static void ufshcd_err_handler(struct work_struct *work)
6386 int retries = MAX_ERR_HANDLER_RETRIES;
6387 struct ufs_hba *hba;
6388 unsigned long flags;
6393 hba = container_of(work, struct ufs_hba, eh_work);
6396 "%s started; HBA state %s; powered %d; shutting down %d; saved_err = %d; saved_uic_err = %d; force_reset = %d%s\n",
6397 __func__, ufshcd_state_name[hba->ufshcd_state],
6398 hba->is_powered, hba->shutting_down, hba->saved_err,
6399 hba->saved_uic_err, hba->force_reset,
6400 ufshcd_is_link_broken(hba) ? "; link is broken" : "");
6402 down(&hba->host_sem);
6403 spin_lock_irqsave(hba->host->host_lock, flags);
6404 if (ufshcd_err_handling_should_stop(hba)) {
6405 if (hba->ufshcd_state != UFSHCD_STATE_ERROR)
6406 hba->ufshcd_state = UFSHCD_STATE_OPERATIONAL;
6407 spin_unlock_irqrestore(hba->host->host_lock, flags);
6411 ufshcd_set_eh_in_progress(hba);
6412 spin_unlock_irqrestore(hba->host->host_lock, flags);
6413 ufshcd_err_handling_prepare(hba);
6414 /* Complete requests that have door-bell cleared by h/w */
6415 ufshcd_complete_requests(hba, false);
6416 spin_lock_irqsave(hba->host->host_lock, flags);
6418 needs_restore = false;
6419 needs_reset = false;
6421 if (hba->ufshcd_state != UFSHCD_STATE_ERROR)
6422 hba->ufshcd_state = UFSHCD_STATE_RESET;
6424 * A full reset and restore might have happened after preparation
6425 * is finished, double check whether we should stop.
6427 if (ufshcd_err_handling_should_stop(hba))
6428 goto skip_err_handling;
6430 if (hba->dev_quirks & UFS_DEVICE_QUIRK_RECOVERY_FROM_DL_NAC_ERRORS) {
6433 spin_unlock_irqrestore(hba->host->host_lock, flags);
6434 /* release the lock as ufshcd_quirk_dl_nac_errors() may sleep */
6435 ret = ufshcd_quirk_dl_nac_errors(hba);
6436 spin_lock_irqsave(hba->host->host_lock, flags);
6437 if (!ret && ufshcd_err_handling_should_stop(hba))
6438 goto skip_err_handling;
6441 if ((hba->saved_err & (INT_FATAL_ERRORS | UFSHCD_UIC_HIBERN8_MASK)) ||
6442 (hba->saved_uic_err &&
6443 (hba->saved_uic_err != UFSHCD_UIC_PA_GENERIC_ERROR))) {
6444 bool pr_prdt = !!(hba->saved_err & SYSTEM_BUS_FATAL_ERROR);
6446 spin_unlock_irqrestore(hba->host->host_lock, flags);
6447 ufshcd_print_host_state(hba);
6448 ufshcd_print_pwr_info(hba);
6449 ufshcd_print_evt_hist(hba);
6450 ufshcd_print_tmrs(hba, hba->outstanding_tasks);
6451 ufshcd_print_trs_all(hba, pr_prdt);
6452 spin_lock_irqsave(hba->host->host_lock, flags);
6456 * if host reset is required then skip clearing the pending
6457 * transfers forcefully because they will get cleared during
6458 * host reset and restore
6460 if (hba->force_reset || ufshcd_is_link_broken(hba) ||
6461 ufshcd_is_saved_err_fatal(hba) ||
6462 ((hba->saved_err & UIC_ERROR) &&
6463 (hba->saved_uic_err & (UFSHCD_UIC_DL_NAC_RECEIVED_ERROR |
6464 UFSHCD_UIC_DL_TCx_REPLAY_ERROR)))) {
6470 * If LINERESET was caught, UFS might have been put to PWM mode,
6471 * check if power mode restore is needed.
6473 if (hba->saved_uic_err & UFSHCD_UIC_PA_GENERIC_ERROR) {
6474 hba->saved_uic_err &= ~UFSHCD_UIC_PA_GENERIC_ERROR;
6475 if (!hba->saved_uic_err)
6476 hba->saved_err &= ~UIC_ERROR;
6477 spin_unlock_irqrestore(hba->host->host_lock, flags);
6478 if (ufshcd_is_pwr_mode_restore_needed(hba))
6479 needs_restore = true;
6480 spin_lock_irqsave(hba->host->host_lock, flags);
6481 if (!hba->saved_err && !needs_restore)
6482 goto skip_err_handling;
6485 hba->silence_err_logs = true;
6486 /* release lock as clear command might sleep */
6487 spin_unlock_irqrestore(hba->host->host_lock, flags);
6489 needs_reset = ufshcd_abort_all(hba);
6491 spin_lock_irqsave(hba->host->host_lock, flags);
6492 hba->silence_err_logs = false;
6497 * After all reqs and tasks are cleared from doorbell,
6498 * now it is safe to retore power mode.
6500 if (needs_restore) {
6501 spin_unlock_irqrestore(hba->host->host_lock, flags);
6503 * Hold the scaling lock just in case dev cmds
6504 * are sent via bsg and/or sysfs.
6506 down_write(&hba->clk_scaling_lock);
6507 hba->force_pmc = true;
6508 pmc_err = ufshcd_config_pwr_mode(hba, &(hba->pwr_info));
6511 dev_err(hba->dev, "%s: Failed to restore power mode, err = %d\n",
6514 hba->force_pmc = false;
6515 ufshcd_print_pwr_info(hba);
6516 up_write(&hba->clk_scaling_lock);
6517 spin_lock_irqsave(hba->host->host_lock, flags);
6521 /* Fatal errors need reset */
6525 hba->force_reset = false;
6526 spin_unlock_irqrestore(hba->host->host_lock, flags);
6527 err = ufshcd_reset_and_restore(hba);
6529 dev_err(hba->dev, "%s: reset and restore failed with err %d\n",
6532 ufshcd_recover_pm_error(hba);
6533 spin_lock_irqsave(hba->host->host_lock, flags);
6538 if (hba->ufshcd_state == UFSHCD_STATE_RESET)
6539 hba->ufshcd_state = UFSHCD_STATE_OPERATIONAL;
6540 if (hba->saved_err || hba->saved_uic_err)
6541 dev_err_ratelimited(hba->dev, "%s: exit: saved_err 0x%x saved_uic_err 0x%x",
6542 __func__, hba->saved_err, hba->saved_uic_err);
6544 /* Exit in an operational state or dead */
6545 if (hba->ufshcd_state != UFSHCD_STATE_OPERATIONAL &&
6546 hba->ufshcd_state != UFSHCD_STATE_ERROR) {
6549 hba->ufshcd_state = UFSHCD_STATE_ERROR;
6551 ufshcd_clear_eh_in_progress(hba);
6552 spin_unlock_irqrestore(hba->host->host_lock, flags);
6553 ufshcd_err_handling_unprepare(hba);
6556 dev_info(hba->dev, "%s finished; HBA state %s\n", __func__,
6557 ufshcd_state_name[hba->ufshcd_state]);
6561 * ufshcd_update_uic_error - check and set fatal UIC error flags.
6562 * @hba: per-adapter instance
6565 * IRQ_HANDLED - If interrupt is valid
6566 * IRQ_NONE - If invalid interrupt
6568 static irqreturn_t ufshcd_update_uic_error(struct ufs_hba *hba)
6571 irqreturn_t retval = IRQ_NONE;
6573 /* PHY layer error */
6574 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_PHY_ADAPTER_LAYER);
6575 if ((reg & UIC_PHY_ADAPTER_LAYER_ERROR) &&
6576 (reg & UIC_PHY_ADAPTER_LAYER_ERROR_CODE_MASK)) {
6577 ufshcd_update_evt_hist(hba, UFS_EVT_PA_ERR, reg);
6579 * To know whether this error is fatal or not, DB timeout
6580 * must be checked but this error is handled separately.
6582 if (reg & UIC_PHY_ADAPTER_LAYER_LANE_ERR_MASK)
6583 dev_dbg(hba->dev, "%s: UIC Lane error reported\n",
6586 /* Got a LINERESET indication. */
6587 if (reg & UIC_PHY_ADAPTER_LAYER_GENERIC_ERROR) {
6588 struct uic_command *cmd = NULL;
6590 hba->uic_error |= UFSHCD_UIC_PA_GENERIC_ERROR;
6591 if (hba->uic_async_done && hba->active_uic_cmd)
6592 cmd = hba->active_uic_cmd;
6594 * Ignore the LINERESET during power mode change
6595 * operation via DME_SET command.
6597 if (cmd && (cmd->command == UIC_CMD_DME_SET))
6598 hba->uic_error &= ~UFSHCD_UIC_PA_GENERIC_ERROR;
6600 retval |= IRQ_HANDLED;
6603 /* PA_INIT_ERROR is fatal and needs UIC reset */
6604 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_DATA_LINK_LAYER);
6605 if ((reg & UIC_DATA_LINK_LAYER_ERROR) &&
6606 (reg & UIC_DATA_LINK_LAYER_ERROR_CODE_MASK)) {
6607 ufshcd_update_evt_hist(hba, UFS_EVT_DL_ERR, reg);
6609 if (reg & UIC_DATA_LINK_LAYER_ERROR_PA_INIT)
6610 hba->uic_error |= UFSHCD_UIC_DL_PA_INIT_ERROR;
6611 else if (hba->dev_quirks &
6612 UFS_DEVICE_QUIRK_RECOVERY_FROM_DL_NAC_ERRORS) {
6613 if (reg & UIC_DATA_LINK_LAYER_ERROR_NAC_RECEIVED)
6615 UFSHCD_UIC_DL_NAC_RECEIVED_ERROR;
6616 else if (reg & UIC_DATA_LINK_LAYER_ERROR_TCx_REPLAY_TIMEOUT)
6617 hba->uic_error |= UFSHCD_UIC_DL_TCx_REPLAY_ERROR;
6619 retval |= IRQ_HANDLED;
6622 /* UIC NL/TL/DME errors needs software retry */
6623 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_NETWORK_LAYER);
6624 if ((reg & UIC_NETWORK_LAYER_ERROR) &&
6625 (reg & UIC_NETWORK_LAYER_ERROR_CODE_MASK)) {
6626 ufshcd_update_evt_hist(hba, UFS_EVT_NL_ERR, reg);
6627 hba->uic_error |= UFSHCD_UIC_NL_ERROR;
6628 retval |= IRQ_HANDLED;
6631 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_TRANSPORT_LAYER);
6632 if ((reg & UIC_TRANSPORT_LAYER_ERROR) &&
6633 (reg & UIC_TRANSPORT_LAYER_ERROR_CODE_MASK)) {
6634 ufshcd_update_evt_hist(hba, UFS_EVT_TL_ERR, reg);
6635 hba->uic_error |= UFSHCD_UIC_TL_ERROR;
6636 retval |= IRQ_HANDLED;
6639 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_DME);
6640 if ((reg & UIC_DME_ERROR) &&
6641 (reg & UIC_DME_ERROR_CODE_MASK)) {
6642 ufshcd_update_evt_hist(hba, UFS_EVT_DME_ERR, reg);
6643 hba->uic_error |= UFSHCD_UIC_DME_ERROR;
6644 retval |= IRQ_HANDLED;
6647 dev_dbg(hba->dev, "%s: UIC error flags = 0x%08x\n",
6648 __func__, hba->uic_error);
6653 * ufshcd_check_errors - Check for errors that need s/w attention
6654 * @hba: per-adapter instance
6655 * @intr_status: interrupt status generated by the controller
6658 * IRQ_HANDLED - If interrupt is valid
6659 * IRQ_NONE - If invalid interrupt
6661 static irqreturn_t ufshcd_check_errors(struct ufs_hba *hba, u32 intr_status)
6663 bool queue_eh_work = false;
6664 irqreturn_t retval = IRQ_NONE;
6666 spin_lock(hba->host->host_lock);
6667 hba->errors |= UFSHCD_ERROR_MASK & intr_status;
6669 if (hba->errors & INT_FATAL_ERRORS) {
6670 ufshcd_update_evt_hist(hba, UFS_EVT_FATAL_ERR,
6672 queue_eh_work = true;
6675 if (hba->errors & UIC_ERROR) {
6677 retval = ufshcd_update_uic_error(hba);
6679 queue_eh_work = true;
6682 if (hba->errors & UFSHCD_UIC_HIBERN8_MASK) {
6684 "%s: Auto Hibern8 %s failed - status: 0x%08x, upmcrs: 0x%08x\n",
6685 __func__, (hba->errors & UIC_HIBERNATE_ENTER) ?
6687 hba->errors, ufshcd_get_upmcrs(hba));
6688 ufshcd_update_evt_hist(hba, UFS_EVT_AUTO_HIBERN8_ERR,
6690 ufshcd_set_link_broken(hba);
6691 queue_eh_work = true;
6694 if (queue_eh_work) {
6696 * update the transfer error masks to sticky bits, let's do this
6697 * irrespective of current ufshcd_state.
6699 hba->saved_err |= hba->errors;
6700 hba->saved_uic_err |= hba->uic_error;
6702 /* dump controller state before resetting */
6703 if ((hba->saved_err &
6704 (INT_FATAL_ERRORS | UFSHCD_UIC_HIBERN8_MASK)) ||
6705 (hba->saved_uic_err &&
6706 (hba->saved_uic_err != UFSHCD_UIC_PA_GENERIC_ERROR))) {
6707 dev_err(hba->dev, "%s: saved_err 0x%x saved_uic_err 0x%x\n",
6708 __func__, hba->saved_err,
6709 hba->saved_uic_err);
6710 ufshcd_dump_regs(hba, 0, UFSHCI_REG_SPACE_SIZE,
6712 ufshcd_print_pwr_info(hba);
6714 ufshcd_schedule_eh_work(hba);
6715 retval |= IRQ_HANDLED;
6718 * if (!queue_eh_work) -
6719 * Other errors are either non-fatal where host recovers
6720 * itself without s/w intervention or errors that will be
6721 * handled by the SCSI core layer.
6725 spin_unlock(hba->host->host_lock);
6730 * ufshcd_tmc_handler - handle task management function completion
6731 * @hba: per adapter instance
6734 * IRQ_HANDLED - If interrupt is valid
6735 * IRQ_NONE - If invalid interrupt
6737 static irqreturn_t ufshcd_tmc_handler(struct ufs_hba *hba)
6739 unsigned long flags, pending, issued;
6740 irqreturn_t ret = IRQ_NONE;
6743 spin_lock_irqsave(hba->host->host_lock, flags);
6744 pending = ufshcd_readl(hba, REG_UTP_TASK_REQ_DOOR_BELL);
6745 issued = hba->outstanding_tasks & ~pending;
6746 for_each_set_bit(tag, &issued, hba->nutmrs) {
6747 struct request *req = hba->tmf_rqs[tag];
6748 struct completion *c = req->end_io_data;
6753 spin_unlock_irqrestore(hba->host->host_lock, flags);
6759 * ufshcd_handle_mcq_cq_events - handle MCQ completion queue events
6760 * @hba: per adapter instance
6762 * Return: IRQ_HANDLED if interrupt is handled.
6764 static irqreturn_t ufshcd_handle_mcq_cq_events(struct ufs_hba *hba)
6766 struct ufs_hw_queue *hwq;
6767 unsigned long outstanding_cqs;
6768 unsigned int nr_queues;
6772 ret = ufshcd_vops_get_outstanding_cqs(hba, &outstanding_cqs);
6774 outstanding_cqs = (1U << hba->nr_hw_queues) - 1;
6776 /* Exclude the poll queues */
6777 nr_queues = hba->nr_hw_queues - hba->nr_queues[HCTX_TYPE_POLL];
6778 for_each_set_bit(i, &outstanding_cqs, nr_queues) {
6781 events = ufshcd_mcq_read_cqis(hba, i);
6783 ufshcd_mcq_write_cqis(hba, events, i);
6785 if (events & UFSHCD_MCQ_CQIS_TAIL_ENT_PUSH_STS)
6786 ufshcd_mcq_poll_cqe_lock(hba, hwq);
6793 * ufshcd_sl_intr - Interrupt service routine
6794 * @hba: per adapter instance
6795 * @intr_status: contains interrupts generated by the controller
6798 * IRQ_HANDLED - If interrupt is valid
6799 * IRQ_NONE - If invalid interrupt
6801 static irqreturn_t ufshcd_sl_intr(struct ufs_hba *hba, u32 intr_status)
6803 irqreturn_t retval = IRQ_NONE;
6805 if (intr_status & UFSHCD_UIC_MASK)
6806 retval |= ufshcd_uic_cmd_compl(hba, intr_status);
6808 if (intr_status & UFSHCD_ERROR_MASK || hba->errors)
6809 retval |= ufshcd_check_errors(hba, intr_status);
6811 if (intr_status & UTP_TASK_REQ_COMPL)
6812 retval |= ufshcd_tmc_handler(hba);
6814 if (intr_status & UTP_TRANSFER_REQ_COMPL)
6815 retval |= ufshcd_transfer_req_compl(hba);
6817 if (intr_status & MCQ_CQ_EVENT_STATUS)
6818 retval |= ufshcd_handle_mcq_cq_events(hba);
6824 * ufshcd_intr - Main interrupt service routine
6826 * @__hba: pointer to adapter instance
6829 * IRQ_HANDLED - If interrupt is valid
6830 * IRQ_NONE - If invalid interrupt
6832 static irqreturn_t ufshcd_intr(int irq, void *__hba)
6834 u32 intr_status, enabled_intr_status = 0;
6835 irqreturn_t retval = IRQ_NONE;
6836 struct ufs_hba *hba = __hba;
6837 int retries = hba->nutrs;
6839 intr_status = ufshcd_readl(hba, REG_INTERRUPT_STATUS);
6840 hba->ufs_stats.last_intr_status = intr_status;
6841 hba->ufs_stats.last_intr_ts = local_clock();
6844 * There could be max of hba->nutrs reqs in flight and in worst case
6845 * if the reqs get finished 1 by 1 after the interrupt status is
6846 * read, make sure we handle them by checking the interrupt status
6847 * again in a loop until we process all of the reqs before returning.
6849 while (intr_status && retries--) {
6850 enabled_intr_status =
6851 intr_status & ufshcd_readl(hba, REG_INTERRUPT_ENABLE);
6852 ufshcd_writel(hba, intr_status, REG_INTERRUPT_STATUS);
6853 if (enabled_intr_status)
6854 retval |= ufshcd_sl_intr(hba, enabled_intr_status);
6856 intr_status = ufshcd_readl(hba, REG_INTERRUPT_STATUS);
6859 if (enabled_intr_status && retval == IRQ_NONE &&
6860 (!(enabled_intr_status & UTP_TRANSFER_REQ_COMPL) ||
6861 hba->outstanding_reqs) && !ufshcd_eh_in_progress(hba)) {
6862 dev_err(hba->dev, "%s: Unhandled interrupt 0x%08x (0x%08x, 0x%08x)\n",
6865 hba->ufs_stats.last_intr_status,
6866 enabled_intr_status);
6867 ufshcd_dump_regs(hba, 0, UFSHCI_REG_SPACE_SIZE, "host_regs: ");
6873 static int ufshcd_clear_tm_cmd(struct ufs_hba *hba, int tag)
6876 u32 mask = 1 << tag;
6877 unsigned long flags;
6879 if (!test_bit(tag, &hba->outstanding_tasks))
6882 spin_lock_irqsave(hba->host->host_lock, flags);
6883 ufshcd_utmrl_clear(hba, tag);
6884 spin_unlock_irqrestore(hba->host->host_lock, flags);
6886 /* poll for max. 1 sec to clear door bell register by h/w */
6887 err = ufshcd_wait_for_register(hba,
6888 REG_UTP_TASK_REQ_DOOR_BELL,
6889 mask, 0, 1000, 1000);
6891 dev_err(hba->dev, "Clearing task management function with tag %d %s\n",
6892 tag, err ? "succeeded" : "failed");
6898 static int __ufshcd_issue_tm_cmd(struct ufs_hba *hba,
6899 struct utp_task_req_desc *treq, u8 tm_function)
6901 struct request_queue *q = hba->tmf_queue;
6902 struct Scsi_Host *host = hba->host;
6903 DECLARE_COMPLETION_ONSTACK(wait);
6904 struct request *req;
6905 unsigned long flags;
6909 * blk_mq_alloc_request() is used here only to get a free tag.
6911 req = blk_mq_alloc_request(q, REQ_OP_DRV_OUT, 0);
6913 return PTR_ERR(req);
6915 req->end_io_data = &wait;
6918 spin_lock_irqsave(host->host_lock, flags);
6920 task_tag = req->tag;
6921 hba->tmf_rqs[req->tag] = req;
6922 treq->upiu_req.req_header.task_tag = task_tag;
6924 memcpy(hba->utmrdl_base_addr + task_tag, treq, sizeof(*treq));
6925 ufshcd_vops_setup_task_mgmt(hba, task_tag, tm_function);
6927 /* send command to the controller */
6928 __set_bit(task_tag, &hba->outstanding_tasks);
6930 ufshcd_writel(hba, 1 << task_tag, REG_UTP_TASK_REQ_DOOR_BELL);
6931 /* Make sure that doorbell is committed immediately */
6934 spin_unlock_irqrestore(host->host_lock, flags);
6936 ufshcd_add_tm_upiu_trace(hba, task_tag, UFS_TM_SEND);
6938 /* wait until the task management command is completed */
6939 err = wait_for_completion_io_timeout(&wait,
6940 msecs_to_jiffies(TM_CMD_TIMEOUT));
6942 ufshcd_add_tm_upiu_trace(hba, task_tag, UFS_TM_ERR);
6943 dev_err(hba->dev, "%s: task management cmd 0x%.2x timed-out\n",
6944 __func__, tm_function);
6945 if (ufshcd_clear_tm_cmd(hba, task_tag))
6946 dev_WARN(hba->dev, "%s: unable to clear tm cmd (slot %d) after timeout\n",
6947 __func__, task_tag);
6951 memcpy(treq, hba->utmrdl_base_addr + task_tag, sizeof(*treq));
6953 ufshcd_add_tm_upiu_trace(hba, task_tag, UFS_TM_COMP);
6956 spin_lock_irqsave(hba->host->host_lock, flags);
6957 hba->tmf_rqs[req->tag] = NULL;
6958 __clear_bit(task_tag, &hba->outstanding_tasks);
6959 spin_unlock_irqrestore(hba->host->host_lock, flags);
6961 ufshcd_release(hba);
6962 blk_mq_free_request(req);
6968 * ufshcd_issue_tm_cmd - issues task management commands to controller
6969 * @hba: per adapter instance
6970 * @lun_id: LUN ID to which TM command is sent
6971 * @task_id: task ID to which the TM command is applicable
6972 * @tm_function: task management function opcode
6973 * @tm_response: task management service response return value
6975 * Return: non-zero value on error, zero on success.
6977 static int ufshcd_issue_tm_cmd(struct ufs_hba *hba, int lun_id, int task_id,
6978 u8 tm_function, u8 *tm_response)
6980 struct utp_task_req_desc treq = { };
6981 enum utp_ocs ocs_value;
6984 /* Configure task request descriptor */
6985 treq.header.interrupt = 1;
6986 treq.header.ocs = OCS_INVALID_COMMAND_STATUS;
6988 /* Configure task request UPIU */
6989 treq.upiu_req.req_header.transaction_code = UPIU_TRANSACTION_TASK_REQ;
6990 treq.upiu_req.req_header.lun = lun_id;
6991 treq.upiu_req.req_header.tm_function = tm_function;
6994 * The host shall provide the same value for LUN field in the basic
6995 * header and for Input Parameter.
6997 treq.upiu_req.input_param1 = cpu_to_be32(lun_id);
6998 treq.upiu_req.input_param2 = cpu_to_be32(task_id);
7000 err = __ufshcd_issue_tm_cmd(hba, &treq, tm_function);
7001 if (err == -ETIMEDOUT)
7004 ocs_value = treq.header.ocs & MASK_OCS;
7005 if (ocs_value != OCS_SUCCESS)
7006 dev_err(hba->dev, "%s: failed, ocs = 0x%x\n",
7007 __func__, ocs_value);
7008 else if (tm_response)
7009 *tm_response = be32_to_cpu(treq.upiu_rsp.output_param1) &
7010 MASK_TM_SERVICE_RESP;
7015 * ufshcd_issue_devman_upiu_cmd - API for sending "utrd" type requests
7016 * @hba: per-adapter instance
7017 * @req_upiu: upiu request
7018 * @rsp_upiu: upiu reply
7019 * @desc_buff: pointer to descriptor buffer, NULL if NA
7020 * @buff_len: descriptor size, 0 if NA
7021 * @cmd_type: specifies the type (NOP, Query...)
7022 * @desc_op: descriptor operation
7024 * Those type of requests uses UTP Transfer Request Descriptor - utrd.
7025 * Therefore, it "rides" the device management infrastructure: uses its tag and
7026 * tasks work queues.
7028 * Since there is only one available tag for device management commands,
7029 * the caller is expected to hold the hba->dev_cmd.lock mutex.
7031 * Return: 0 upon success; < 0 upon failure.
7033 static int ufshcd_issue_devman_upiu_cmd(struct ufs_hba *hba,
7034 struct utp_upiu_req *req_upiu,
7035 struct utp_upiu_req *rsp_upiu,
7036 u8 *desc_buff, int *buff_len,
7037 enum dev_cmd_type cmd_type,
7038 enum query_opcode desc_op)
7040 DECLARE_COMPLETION_ONSTACK(wait);
7041 const u32 tag = hba->reserved_slot;
7042 struct ufshcd_lrb *lrbp;
7046 /* Protects use of hba->reserved_slot. */
7047 lockdep_assert_held(&hba->dev_cmd.lock);
7049 down_read(&hba->clk_scaling_lock);
7051 lrbp = &hba->lrb[tag];
7053 lrbp->task_tag = tag;
7055 lrbp->intr_cmd = true;
7056 ufshcd_prepare_lrbp_crypto(NULL, lrbp);
7057 hba->dev_cmd.type = cmd_type;
7059 if (hba->ufs_version <= ufshci_version(1, 1))
7060 lrbp->command_type = UTP_CMD_TYPE_DEV_MANAGE;
7062 lrbp->command_type = UTP_CMD_TYPE_UFS_STORAGE;
7064 /* update the task tag in the request upiu */
7065 req_upiu->header.task_tag = tag;
7067 ufshcd_prepare_req_desc_hdr(lrbp, &upiu_flags, DMA_NONE, 0);
7069 /* just copy the upiu request as it is */
7070 memcpy(lrbp->ucd_req_ptr, req_upiu, sizeof(*lrbp->ucd_req_ptr));
7071 if (desc_buff && desc_op == UPIU_QUERY_OPCODE_WRITE_DESC) {
7072 /* The Data Segment Area is optional depending upon the query
7073 * function value. for WRITE DESCRIPTOR, the data segment
7074 * follows right after the tsf.
7076 memcpy(lrbp->ucd_req_ptr + 1, desc_buff, *buff_len);
7080 memset(lrbp->ucd_rsp_ptr, 0, sizeof(struct utp_upiu_rsp));
7082 hba->dev_cmd.complete = &wait;
7084 ufshcd_add_query_upiu_trace(hba, UFS_QUERY_SEND, lrbp->ucd_req_ptr);
7086 ufshcd_send_command(hba, tag, hba->dev_cmd_queue);
7088 * ignore the returning value here - ufshcd_check_query_response is
7089 * bound to fail since dev_cmd.query and dev_cmd.type were left empty.
7090 * read the response directly ignoring all errors.
7092 ufshcd_wait_for_dev_cmd(hba, lrbp, QUERY_REQ_TIMEOUT);
7094 /* just copy the upiu response as it is */
7095 memcpy(rsp_upiu, lrbp->ucd_rsp_ptr, sizeof(*rsp_upiu));
7096 if (desc_buff && desc_op == UPIU_QUERY_OPCODE_READ_DESC) {
7097 u8 *descp = (u8 *)lrbp->ucd_rsp_ptr + sizeof(*rsp_upiu);
7098 u16 resp_len = be16_to_cpu(lrbp->ucd_rsp_ptr->header
7099 .data_segment_length);
7101 if (*buff_len >= resp_len) {
7102 memcpy(desc_buff, descp, resp_len);
7103 *buff_len = resp_len;
7106 "%s: rsp size %d is bigger than buffer size %d",
7107 __func__, resp_len, *buff_len);
7112 ufshcd_add_query_upiu_trace(hba, err ? UFS_QUERY_ERR : UFS_QUERY_COMP,
7113 (struct utp_upiu_req *)lrbp->ucd_rsp_ptr);
7115 up_read(&hba->clk_scaling_lock);
7120 * ufshcd_exec_raw_upiu_cmd - API function for sending raw upiu commands
7121 * @hba: per-adapter instance
7122 * @req_upiu: upiu request
7123 * @rsp_upiu: upiu reply - only 8 DW as we do not support scsi commands
7124 * @msgcode: message code, one of UPIU Transaction Codes Initiator to Target
7125 * @desc_buff: pointer to descriptor buffer, NULL if NA
7126 * @buff_len: descriptor size, 0 if NA
7127 * @desc_op: descriptor operation
7129 * Supports UTP Transfer requests (nop and query), and UTP Task
7130 * Management requests.
7131 * It is up to the caller to fill the upiu conent properly, as it will
7132 * be copied without any further input validations.
7134 * Return: 0 upon success; < 0 upon failure.
7136 int ufshcd_exec_raw_upiu_cmd(struct ufs_hba *hba,
7137 struct utp_upiu_req *req_upiu,
7138 struct utp_upiu_req *rsp_upiu,
7139 enum upiu_request_transaction msgcode,
7140 u8 *desc_buff, int *buff_len,
7141 enum query_opcode desc_op)
7144 enum dev_cmd_type cmd_type = DEV_CMD_TYPE_QUERY;
7145 struct utp_task_req_desc treq = { };
7146 enum utp_ocs ocs_value;
7147 u8 tm_f = req_upiu->header.tm_function;
7150 case UPIU_TRANSACTION_NOP_OUT:
7151 cmd_type = DEV_CMD_TYPE_NOP;
7153 case UPIU_TRANSACTION_QUERY_REQ:
7155 mutex_lock(&hba->dev_cmd.lock);
7156 err = ufshcd_issue_devman_upiu_cmd(hba, req_upiu, rsp_upiu,
7157 desc_buff, buff_len,
7159 mutex_unlock(&hba->dev_cmd.lock);
7160 ufshcd_release(hba);
7163 case UPIU_TRANSACTION_TASK_REQ:
7164 treq.header.interrupt = 1;
7165 treq.header.ocs = OCS_INVALID_COMMAND_STATUS;
7167 memcpy(&treq.upiu_req, req_upiu, sizeof(*req_upiu));
7169 err = __ufshcd_issue_tm_cmd(hba, &treq, tm_f);
7170 if (err == -ETIMEDOUT)
7173 ocs_value = treq.header.ocs & MASK_OCS;
7174 if (ocs_value != OCS_SUCCESS) {
7175 dev_err(hba->dev, "%s: failed, ocs = 0x%x\n", __func__,
7180 memcpy(rsp_upiu, &treq.upiu_rsp, sizeof(*rsp_upiu));
7193 * ufshcd_advanced_rpmb_req_handler - handle advanced RPMB request
7194 * @hba: per adapter instance
7195 * @req_upiu: upiu request
7196 * @rsp_upiu: upiu reply
7197 * @req_ehs: EHS field which contains Advanced RPMB Request Message
7198 * @rsp_ehs: EHS field which returns Advanced RPMB Response Message
7199 * @sg_cnt: The number of sg lists actually used
7200 * @sg_list: Pointer to SG list when DATA IN/OUT UPIU is required in ARPMB operation
7201 * @dir: DMA direction
7203 * Return: zero on success, non-zero on failure.
7205 int ufshcd_advanced_rpmb_req_handler(struct ufs_hba *hba, struct utp_upiu_req *req_upiu,
7206 struct utp_upiu_req *rsp_upiu, struct ufs_ehs *req_ehs,
7207 struct ufs_ehs *rsp_ehs, int sg_cnt, struct scatterlist *sg_list,
7208 enum dma_data_direction dir)
7210 DECLARE_COMPLETION_ONSTACK(wait);
7211 const u32 tag = hba->reserved_slot;
7212 struct ufshcd_lrb *lrbp;
7219 /* Protects use of hba->reserved_slot. */
7221 mutex_lock(&hba->dev_cmd.lock);
7222 down_read(&hba->clk_scaling_lock);
7224 lrbp = &hba->lrb[tag];
7226 lrbp->task_tag = tag;
7227 lrbp->lun = UFS_UPIU_RPMB_WLUN;
7229 lrbp->intr_cmd = true;
7230 ufshcd_prepare_lrbp_crypto(NULL, lrbp);
7231 hba->dev_cmd.type = DEV_CMD_TYPE_RPMB;
7233 /* Advanced RPMB starts from UFS 4.0, so its command type is UTP_CMD_TYPE_UFS_STORAGE */
7234 lrbp->command_type = UTP_CMD_TYPE_UFS_STORAGE;
7237 * According to UFSHCI 4.0 specification page 24, if EHSLUTRDS is 0, host controller takes
7238 * EHS length from CMD UPIU, and SW driver use EHS Length field in CMD UPIU. if it is 1,
7239 * HW controller takes EHS length from UTRD.
7241 if (hba->capabilities & MASK_EHSLUTRD_SUPPORTED)
7242 ufshcd_prepare_req_desc_hdr(lrbp, &upiu_flags, dir, 2);
7244 ufshcd_prepare_req_desc_hdr(lrbp, &upiu_flags, dir, 0);
7246 /* update the task tag */
7247 req_upiu->header.task_tag = tag;
7249 /* copy the UPIU(contains CDB) request as it is */
7250 memcpy(lrbp->ucd_req_ptr, req_upiu, sizeof(*lrbp->ucd_req_ptr));
7251 /* Copy EHS, starting with byte32, immediately after the CDB package */
7252 memcpy(lrbp->ucd_req_ptr + 1, req_ehs, sizeof(*req_ehs));
7254 if (dir != DMA_NONE && sg_list)
7255 ufshcd_sgl_to_prdt(hba, lrbp, sg_cnt, sg_list);
7257 memset(lrbp->ucd_rsp_ptr, 0, sizeof(struct utp_upiu_rsp));
7259 hba->dev_cmd.complete = &wait;
7261 ufshcd_send_command(hba, tag, hba->dev_cmd_queue);
7263 err = ufshcd_wait_for_dev_cmd(hba, lrbp, ADVANCED_RPMB_REQ_TIMEOUT);
7266 /* Just copy the upiu response as it is */
7267 memcpy(rsp_upiu, lrbp->ucd_rsp_ptr, sizeof(*rsp_upiu));
7268 /* Get the response UPIU result */
7269 result = (lrbp->ucd_rsp_ptr->header.response << 8) |
7270 lrbp->ucd_rsp_ptr->header.status;
7272 ehs_len = lrbp->ucd_rsp_ptr->header.ehs_length;
7274 * Since the bLength in EHS indicates the total size of the EHS Header and EHS Data
7275 * in 32 Byte units, the value of the bLength Request/Response for Advanced RPMB
7278 if (ehs_len == 2 && rsp_ehs) {
7280 * ucd_rsp_ptr points to a buffer with a length of 512 bytes
7281 * (ALIGNED_UPIU_SIZE = 512), and the EHS data just starts from byte32
7283 ehs_data = (u8 *)lrbp->ucd_rsp_ptr + EHS_OFFSET_IN_RESPONSE;
7284 memcpy(rsp_ehs, ehs_data, ehs_len * 32);
7288 up_read(&hba->clk_scaling_lock);
7289 mutex_unlock(&hba->dev_cmd.lock);
7290 ufshcd_release(hba);
7291 return err ? : result;
7295 * ufshcd_eh_device_reset_handler() - Reset a single logical unit.
7296 * @cmd: SCSI command pointer
7298 * Return: SUCCESS or FAILED.
7300 static int ufshcd_eh_device_reset_handler(struct scsi_cmnd *cmd)
7302 unsigned long flags, pending_reqs = 0, not_cleared = 0;
7303 struct Scsi_Host *host;
7304 struct ufs_hba *hba;
7305 struct ufs_hw_queue *hwq;
7306 struct ufshcd_lrb *lrbp;
7307 u32 pos, not_cleared_mask = 0;
7311 host = cmd->device->host;
7312 hba = shost_priv(host);
7314 lun = ufshcd_scsi_to_upiu_lun(cmd->device->lun);
7315 err = ufshcd_issue_tm_cmd(hba, lun, 0, UFS_LOGICAL_RESET, &resp);
7316 if (err || resp != UPIU_TASK_MANAGEMENT_FUNC_COMPL) {
7322 if (is_mcq_enabled(hba)) {
7323 for (pos = 0; pos < hba->nutrs; pos++) {
7324 lrbp = &hba->lrb[pos];
7325 if (ufshcd_cmd_inflight(lrbp->cmd) &&
7327 ufshcd_clear_cmd(hba, pos);
7328 hwq = ufshcd_mcq_req_to_hwq(hba, scsi_cmd_to_rq(lrbp->cmd));
7329 ufshcd_mcq_poll_cqe_lock(hba, hwq);
7336 /* clear the commands that were pending for corresponding LUN */
7337 spin_lock_irqsave(&hba->outstanding_lock, flags);
7338 for_each_set_bit(pos, &hba->outstanding_reqs, hba->nutrs)
7339 if (hba->lrb[pos].lun == lun)
7340 __set_bit(pos, &pending_reqs);
7341 hba->outstanding_reqs &= ~pending_reqs;
7342 spin_unlock_irqrestore(&hba->outstanding_lock, flags);
7344 for_each_set_bit(pos, &pending_reqs, hba->nutrs) {
7345 if (ufshcd_clear_cmd(hba, pos) < 0) {
7346 spin_lock_irqsave(&hba->outstanding_lock, flags);
7347 not_cleared = 1U << pos &
7348 ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
7349 hba->outstanding_reqs |= not_cleared;
7350 not_cleared_mask |= not_cleared;
7351 spin_unlock_irqrestore(&hba->outstanding_lock, flags);
7353 dev_err(hba->dev, "%s: failed to clear request %d\n",
7357 __ufshcd_transfer_req_compl(hba, pending_reqs & ~not_cleared_mask);
7360 hba->req_abort_count = 0;
7361 ufshcd_update_evt_hist(hba, UFS_EVT_DEV_RESET, (u32)err);
7365 dev_err(hba->dev, "%s: failed with err %d\n", __func__, err);
7371 static void ufshcd_set_req_abort_skip(struct ufs_hba *hba, unsigned long bitmap)
7373 struct ufshcd_lrb *lrbp;
7376 for_each_set_bit(tag, &bitmap, hba->nutrs) {
7377 lrbp = &hba->lrb[tag];
7378 lrbp->req_abort_skip = true;
7383 * ufshcd_try_to_abort_task - abort a specific task
7384 * @hba: Pointer to adapter instance
7385 * @tag: Task tag/index to be aborted
7387 * Abort the pending command in device by sending UFS_ABORT_TASK task management
7388 * command, and in host controller by clearing the door-bell register. There can
7389 * be race between controller sending the command to the device while abort is
7390 * issued. To avoid that, first issue UFS_QUERY_TASK to check if the command is
7391 * really issued and then try to abort it.
7393 * Return: zero on success, non-zero on failure.
7395 int ufshcd_try_to_abort_task(struct ufs_hba *hba, int tag)
7397 struct ufshcd_lrb *lrbp = &hba->lrb[tag];
7403 for (poll_cnt = 100; poll_cnt; poll_cnt--) {
7404 err = ufshcd_issue_tm_cmd(hba, lrbp->lun, lrbp->task_tag,
7405 UFS_QUERY_TASK, &resp);
7406 if (!err && resp == UPIU_TASK_MANAGEMENT_FUNC_SUCCEEDED) {
7407 /* cmd pending in the device */
7408 dev_err(hba->dev, "%s: cmd pending in the device. tag = %d\n",
7411 } else if (!err && resp == UPIU_TASK_MANAGEMENT_FUNC_COMPL) {
7413 * cmd not pending in the device, check if it is
7416 dev_err(hba->dev, "%s: cmd at tag %d not pending in the device.\n",
7418 if (is_mcq_enabled(hba)) {
7420 if (ufshcd_cmd_inflight(lrbp->cmd)) {
7421 /* sleep for max. 200us same delay as in SDB mode */
7422 usleep_range(100, 200);
7425 /* command completed already */
7426 dev_err(hba->dev, "%s: cmd at tag=%d is cleared.\n",
7431 /* Single Doorbell Mode */
7432 reg = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
7433 if (reg & (1 << tag)) {
7434 /* sleep for max. 200us to stabilize */
7435 usleep_range(100, 200);
7438 /* command completed already */
7439 dev_err(hba->dev, "%s: cmd at tag %d successfully cleared from DB.\n",
7444 "%s: no response from device. tag = %d, err %d\n",
7445 __func__, tag, err);
7447 err = resp; /* service response error */
7457 err = ufshcd_issue_tm_cmd(hba, lrbp->lun, lrbp->task_tag,
7458 UFS_ABORT_TASK, &resp);
7459 if (err || resp != UPIU_TASK_MANAGEMENT_FUNC_COMPL) {
7461 err = resp; /* service response error */
7462 dev_err(hba->dev, "%s: issued. tag = %d, err %d\n",
7463 __func__, tag, err);
7468 err = ufshcd_clear_cmd(hba, tag);
7470 dev_err(hba->dev, "%s: Failed clearing cmd at tag %d, err %d\n",
7471 __func__, tag, err);
7478 * ufshcd_abort - scsi host template eh_abort_handler callback
7479 * @cmd: SCSI command pointer
7481 * Return: SUCCESS or FAILED.
7483 static int ufshcd_abort(struct scsi_cmnd *cmd)
7485 struct Scsi_Host *host = cmd->device->host;
7486 struct ufs_hba *hba = shost_priv(host);
7487 int tag = scsi_cmd_to_rq(cmd)->tag;
7488 struct ufshcd_lrb *lrbp = &hba->lrb[tag];
7489 unsigned long flags;
7496 if (!is_mcq_enabled(hba)) {
7497 reg = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
7498 if (!test_bit(tag, &hba->outstanding_reqs)) {
7499 /* If command is already aborted/completed, return FAILED. */
7501 "%s: cmd at tag %d already completed, outstanding=0x%lx, doorbell=0x%x\n",
7502 __func__, tag, hba->outstanding_reqs, reg);
7507 /* Print Transfer Request of aborted task */
7508 dev_info(hba->dev, "%s: Device abort task at tag %d\n", __func__, tag);
7511 * Print detailed info about aborted request.
7512 * As more than one request might get aborted at the same time,
7513 * print full information only for the first aborted request in order
7514 * to reduce repeated printouts. For other aborted requests only print
7517 scsi_print_command(cmd);
7518 if (!hba->req_abort_count) {
7519 ufshcd_update_evt_hist(hba, UFS_EVT_ABORT, tag);
7520 ufshcd_print_evt_hist(hba);
7521 ufshcd_print_host_state(hba);
7522 ufshcd_print_pwr_info(hba);
7523 ufshcd_print_tr(hba, tag, true);
7525 ufshcd_print_tr(hba, tag, false);
7527 hba->req_abort_count++;
7529 if (!is_mcq_enabled(hba) && !(reg & (1 << tag))) {
7530 /* only execute this code in single doorbell mode */
7532 "%s: cmd was completed, but without a notifying intr, tag = %d",
7534 __ufshcd_transfer_req_compl(hba, 1UL << tag);
7539 * Task abort to the device W-LUN is illegal. When this command
7540 * will fail, due to spec violation, scsi err handling next step
7541 * will be to send LU reset which, again, is a spec violation.
7542 * To avoid these unnecessary/illegal steps, first we clean up
7543 * the lrb taken by this cmd and re-set it in outstanding_reqs,
7544 * then queue the eh_work and bail.
7546 if (lrbp->lun == UFS_UPIU_UFS_DEVICE_WLUN) {
7547 ufshcd_update_evt_hist(hba, UFS_EVT_ABORT, lrbp->lun);
7549 spin_lock_irqsave(host->host_lock, flags);
7550 hba->force_reset = true;
7551 ufshcd_schedule_eh_work(hba);
7552 spin_unlock_irqrestore(host->host_lock, flags);
7556 if (is_mcq_enabled(hba)) {
7557 /* MCQ mode. Branch off to handle abort for mcq mode */
7558 err = ufshcd_mcq_abort(cmd);
7562 /* Skip task abort in case previous aborts failed and report failure */
7563 if (lrbp->req_abort_skip) {
7564 dev_err(hba->dev, "%s: skipping abort\n", __func__);
7565 ufshcd_set_req_abort_skip(hba, hba->outstanding_reqs);
7569 err = ufshcd_try_to_abort_task(hba, tag);
7571 dev_err(hba->dev, "%s: failed with err %d\n", __func__, err);
7572 ufshcd_set_req_abort_skip(hba, hba->outstanding_reqs);
7578 * Clear the corresponding bit from outstanding_reqs since the command
7579 * has been aborted successfully.
7581 spin_lock_irqsave(&hba->outstanding_lock, flags);
7582 outstanding = __test_and_clear_bit(tag, &hba->outstanding_reqs);
7583 spin_unlock_irqrestore(&hba->outstanding_lock, flags);
7586 ufshcd_release_scsi_cmd(hba, lrbp);
7591 /* Matches the ufshcd_hold() call at the start of this function. */
7592 ufshcd_release(hba);
7597 * ufshcd_host_reset_and_restore - reset and restore host controller
7598 * @hba: per-adapter instance
7600 * Note that host controller reset may issue DME_RESET to
7601 * local and remote (device) Uni-Pro stack and the attributes
7602 * are reset to default state.
7604 * Return: zero on success, non-zero on failure.
7606 static int ufshcd_host_reset_and_restore(struct ufs_hba *hba)
7611 * Stop the host controller and complete the requests
7614 ufshcd_hba_stop(hba);
7615 hba->silence_err_logs = true;
7616 ufshcd_complete_requests(hba, true);
7617 hba->silence_err_logs = false;
7619 /* scale up clocks to max frequency before full reinitialization */
7620 ufshcd_scale_clks(hba, true);
7622 err = ufshcd_hba_enable(hba);
7624 /* Establish the link again and restore the device */
7626 err = ufshcd_probe_hba(hba, false);
7629 dev_err(hba->dev, "%s: Host init failed %d\n", __func__, err);
7630 ufshcd_update_evt_hist(hba, UFS_EVT_HOST_RESET, (u32)err);
7635 * ufshcd_reset_and_restore - reset and re-initialize host/device
7636 * @hba: per-adapter instance
7638 * Reset and recover device, host and re-establish link. This
7639 * is helpful to recover the communication in fatal error conditions.
7641 * Return: zero on success, non-zero on failure.
7643 static int ufshcd_reset_and_restore(struct ufs_hba *hba)
7646 u32 saved_uic_err = 0;
7648 unsigned long flags;
7649 int retries = MAX_HOST_RESET_RETRIES;
7651 spin_lock_irqsave(hba->host->host_lock, flags);
7654 * This is a fresh start, cache and clear saved error first,
7655 * in case new error generated during reset and restore.
7657 saved_err |= hba->saved_err;
7658 saved_uic_err |= hba->saved_uic_err;
7660 hba->saved_uic_err = 0;
7661 hba->force_reset = false;
7662 hba->ufshcd_state = UFSHCD_STATE_RESET;
7663 spin_unlock_irqrestore(hba->host->host_lock, flags);
7665 /* Reset the attached device */
7666 ufshcd_device_reset(hba);
7668 err = ufshcd_host_reset_and_restore(hba);
7670 spin_lock_irqsave(hba->host->host_lock, flags);
7673 /* Do not exit unless operational or dead */
7674 if (hba->ufshcd_state != UFSHCD_STATE_OPERATIONAL &&
7675 hba->ufshcd_state != UFSHCD_STATE_ERROR &&
7676 hba->ufshcd_state != UFSHCD_STATE_EH_SCHEDULED_NON_FATAL)
7678 } while (err && --retries);
7681 * Inform scsi mid-layer that we did reset and allow to handle
7682 * Unit Attention properly.
7684 scsi_report_bus_reset(hba->host, 0);
7686 hba->ufshcd_state = UFSHCD_STATE_ERROR;
7687 hba->saved_err |= saved_err;
7688 hba->saved_uic_err |= saved_uic_err;
7690 spin_unlock_irqrestore(hba->host->host_lock, flags);
7696 * ufshcd_eh_host_reset_handler - host reset handler registered to scsi layer
7697 * @cmd: SCSI command pointer
7699 * Return: SUCCESS or FAILED.
7701 static int ufshcd_eh_host_reset_handler(struct scsi_cmnd *cmd)
7704 unsigned long flags;
7705 struct ufs_hba *hba;
7707 hba = shost_priv(cmd->device->host);
7710 * If runtime PM sent SSU and got a timeout, scsi_error_handler is
7711 * stuck in this function waiting for flush_work(&hba->eh_work). And
7712 * ufshcd_err_handler(eh_work) is stuck waiting for runtime PM. Do
7713 * ufshcd_link_recovery instead of eh_work to prevent deadlock.
7715 if (hba->pm_op_in_progress) {
7716 if (ufshcd_link_recovery(hba))
7722 spin_lock_irqsave(hba->host->host_lock, flags);
7723 hba->force_reset = true;
7724 ufshcd_schedule_eh_work(hba);
7725 dev_err(hba->dev, "%s: reset in progress - 1\n", __func__);
7726 spin_unlock_irqrestore(hba->host->host_lock, flags);
7728 flush_work(&hba->eh_work);
7730 spin_lock_irqsave(hba->host->host_lock, flags);
7731 if (hba->ufshcd_state == UFSHCD_STATE_ERROR)
7733 spin_unlock_irqrestore(hba->host->host_lock, flags);
7739 * ufshcd_get_max_icc_level - calculate the ICC level
7740 * @sup_curr_uA: max. current supported by the regulator
7741 * @start_scan: row at the desc table to start scan from
7742 * @buff: power descriptor buffer
7744 * Return: calculated max ICC level for specific regulator.
7746 static u32 ufshcd_get_max_icc_level(int sup_curr_uA, u32 start_scan,
7754 for (i = start_scan; i >= 0; i--) {
7755 data = get_unaligned_be16(&buff[2 * i]);
7756 unit = (data & ATTR_ICC_LVL_UNIT_MASK) >>
7757 ATTR_ICC_LVL_UNIT_OFFSET;
7758 curr_uA = data & ATTR_ICC_LVL_VALUE_MASK;
7760 case UFSHCD_NANO_AMP:
7761 curr_uA = curr_uA / 1000;
7763 case UFSHCD_MILI_AMP:
7764 curr_uA = curr_uA * 1000;
7767 curr_uA = curr_uA * 1000 * 1000;
7769 case UFSHCD_MICRO_AMP:
7773 if (sup_curr_uA >= curr_uA)
7778 pr_err("%s: Couldn't find valid icc_level = %d", __func__, i);
7785 * ufshcd_find_max_sup_active_icc_level - calculate the max ICC level
7786 * In case regulators are not initialized we'll return 0
7787 * @hba: per-adapter instance
7788 * @desc_buf: power descriptor buffer to extract ICC levels from.
7790 * Return: calculated ICC level.
7792 static u32 ufshcd_find_max_sup_active_icc_level(struct ufs_hba *hba,
7797 if (!hba->vreg_info.vcc || !hba->vreg_info.vccq ||
7798 !hba->vreg_info.vccq2) {
7800 * Using dev_dbg to avoid messages during runtime PM to avoid
7801 * never-ending cycles of messages written back to storage by
7802 * user space causing runtime resume, causing more messages and
7806 "%s: Regulator capability was not set, actvIccLevel=%d",
7807 __func__, icc_level);
7811 if (hba->vreg_info.vcc->max_uA)
7812 icc_level = ufshcd_get_max_icc_level(
7813 hba->vreg_info.vcc->max_uA,
7814 POWER_DESC_MAX_ACTV_ICC_LVLS - 1,
7815 &desc_buf[PWR_DESC_ACTIVE_LVLS_VCC_0]);
7817 if (hba->vreg_info.vccq->max_uA)
7818 icc_level = ufshcd_get_max_icc_level(
7819 hba->vreg_info.vccq->max_uA,
7821 &desc_buf[PWR_DESC_ACTIVE_LVLS_VCCQ_0]);
7823 if (hba->vreg_info.vccq2->max_uA)
7824 icc_level = ufshcd_get_max_icc_level(
7825 hba->vreg_info.vccq2->max_uA,
7827 &desc_buf[PWR_DESC_ACTIVE_LVLS_VCCQ2_0]);
7832 static void ufshcd_set_active_icc_lvl(struct ufs_hba *hba)
7838 desc_buf = kzalloc(QUERY_DESC_MAX_SIZE, GFP_KERNEL);
7842 ret = ufshcd_read_desc_param(hba, QUERY_DESC_IDN_POWER, 0, 0,
7843 desc_buf, QUERY_DESC_MAX_SIZE);
7846 "%s: Failed reading power descriptor ret = %d",
7851 icc_level = ufshcd_find_max_sup_active_icc_level(hba, desc_buf);
7852 dev_dbg(hba->dev, "%s: setting icc_level 0x%x", __func__, icc_level);
7854 ret = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_WRITE_ATTR,
7855 QUERY_ATTR_IDN_ACTIVE_ICC_LVL, 0, 0, &icc_level);
7859 "%s: Failed configuring bActiveICCLevel = %d ret = %d",
7860 __func__, icc_level, ret);
7866 static inline void ufshcd_blk_pm_runtime_init(struct scsi_device *sdev)
7868 scsi_autopm_get_device(sdev);
7869 blk_pm_runtime_init(sdev->request_queue, &sdev->sdev_gendev);
7870 if (sdev->rpm_autosuspend)
7871 pm_runtime_set_autosuspend_delay(&sdev->sdev_gendev,
7872 RPM_AUTOSUSPEND_DELAY_MS);
7873 scsi_autopm_put_device(sdev);
7877 * ufshcd_scsi_add_wlus - Adds required W-LUs
7878 * @hba: per-adapter instance
7880 * UFS device specification requires the UFS devices to support 4 well known
7882 * "REPORT_LUNS" (address: 01h)
7883 * "UFS Device" (address: 50h)
7884 * "RPMB" (address: 44h)
7885 * "BOOT" (address: 30h)
7886 * UFS device's power management needs to be controlled by "POWER CONDITION"
7887 * field of SSU (START STOP UNIT) command. But this "power condition" field
7888 * will take effect only when its sent to "UFS device" well known logical unit
7889 * hence we require the scsi_device instance to represent this logical unit in
7890 * order for the UFS host driver to send the SSU command for power management.
7892 * We also require the scsi_device instance for "RPMB" (Replay Protected Memory
7893 * Block) LU so user space process can control this LU. User space may also
7894 * want to have access to BOOT LU.
7896 * This function adds scsi device instances for each of all well known LUs
7897 * (except "REPORT LUNS" LU).
7899 * Return: zero on success (all required W-LUs are added successfully),
7900 * non-zero error value on failure (if failed to add any of the required W-LU).
7902 static int ufshcd_scsi_add_wlus(struct ufs_hba *hba)
7905 struct scsi_device *sdev_boot, *sdev_rpmb;
7907 hba->ufs_device_wlun = __scsi_add_device(hba->host, 0, 0,
7908 ufshcd_upiu_wlun_to_scsi_wlun(UFS_UPIU_UFS_DEVICE_WLUN), NULL);
7909 if (IS_ERR(hba->ufs_device_wlun)) {
7910 ret = PTR_ERR(hba->ufs_device_wlun);
7911 hba->ufs_device_wlun = NULL;
7914 scsi_device_put(hba->ufs_device_wlun);
7916 sdev_rpmb = __scsi_add_device(hba->host, 0, 0,
7917 ufshcd_upiu_wlun_to_scsi_wlun(UFS_UPIU_RPMB_WLUN), NULL);
7918 if (IS_ERR(sdev_rpmb)) {
7919 ret = PTR_ERR(sdev_rpmb);
7920 goto remove_ufs_device_wlun;
7922 ufshcd_blk_pm_runtime_init(sdev_rpmb);
7923 scsi_device_put(sdev_rpmb);
7925 sdev_boot = __scsi_add_device(hba->host, 0, 0,
7926 ufshcd_upiu_wlun_to_scsi_wlun(UFS_UPIU_BOOT_WLUN), NULL);
7927 if (IS_ERR(sdev_boot)) {
7928 dev_err(hba->dev, "%s: BOOT WLUN not found\n", __func__);
7930 ufshcd_blk_pm_runtime_init(sdev_boot);
7931 scsi_device_put(sdev_boot);
7935 remove_ufs_device_wlun:
7936 scsi_remove_device(hba->ufs_device_wlun);
7941 static void ufshcd_wb_probe(struct ufs_hba *hba, const u8 *desc_buf)
7943 struct ufs_dev_info *dev_info = &hba->dev_info;
7945 u32 d_lu_wb_buf_alloc;
7946 u32 ext_ufs_feature;
7948 if (!ufshcd_is_wb_allowed(hba))
7952 * Probe WB only for UFS-2.2 and UFS-3.1 (and later) devices or
7953 * UFS devices with quirk UFS_DEVICE_QUIRK_SUPPORT_EXTENDED_FEATURES
7956 if (!(dev_info->wspecversion >= 0x310 ||
7957 dev_info->wspecversion == 0x220 ||
7958 (hba->dev_quirks & UFS_DEVICE_QUIRK_SUPPORT_EXTENDED_FEATURES)))
7961 ext_ufs_feature = get_unaligned_be32(desc_buf +
7962 DEVICE_DESC_PARAM_EXT_UFS_FEATURE_SUP);
7964 if (!(ext_ufs_feature & UFS_DEV_WRITE_BOOSTER_SUP))
7968 * WB may be supported but not configured while provisioning. The spec
7969 * says, in dedicated wb buffer mode, a max of 1 lun would have wb
7970 * buffer configured.
7972 dev_info->wb_buffer_type = desc_buf[DEVICE_DESC_PARAM_WB_TYPE];
7974 dev_info->b_presrv_uspc_en =
7975 desc_buf[DEVICE_DESC_PARAM_WB_PRESRV_USRSPC_EN];
7977 if (dev_info->wb_buffer_type == WB_BUF_MODE_SHARED) {
7978 if (!get_unaligned_be32(desc_buf +
7979 DEVICE_DESC_PARAM_WB_SHARED_ALLOC_UNITS))
7982 for (lun = 0; lun < UFS_UPIU_MAX_WB_LUN_ID; lun++) {
7983 d_lu_wb_buf_alloc = 0;
7984 ufshcd_read_unit_desc_param(hba,
7986 UNIT_DESC_PARAM_WB_BUF_ALLOC_UNITS,
7987 (u8 *)&d_lu_wb_buf_alloc,
7988 sizeof(d_lu_wb_buf_alloc));
7989 if (d_lu_wb_buf_alloc) {
7990 dev_info->wb_dedicated_lu = lun;
7995 if (!d_lu_wb_buf_alloc)
7999 if (!ufshcd_is_wb_buf_lifetime_available(hba))
8005 hba->caps &= ~UFSHCD_CAP_WB_EN;
8008 static void ufshcd_temp_notif_probe(struct ufs_hba *hba, const u8 *desc_buf)
8010 struct ufs_dev_info *dev_info = &hba->dev_info;
8011 u32 ext_ufs_feature;
8014 if (!(hba->caps & UFSHCD_CAP_TEMP_NOTIF) || dev_info->wspecversion < 0x300)
8017 ext_ufs_feature = get_unaligned_be32(desc_buf + DEVICE_DESC_PARAM_EXT_UFS_FEATURE_SUP);
8019 if (ext_ufs_feature & UFS_DEV_LOW_TEMP_NOTIF)
8020 mask |= MASK_EE_TOO_LOW_TEMP;
8022 if (ext_ufs_feature & UFS_DEV_HIGH_TEMP_NOTIF)
8023 mask |= MASK_EE_TOO_HIGH_TEMP;
8026 ufshcd_enable_ee(hba, mask);
8027 ufs_hwmon_probe(hba, mask);
8031 static void ufshcd_ext_iid_probe(struct ufs_hba *hba, u8 *desc_buf)
8033 struct ufs_dev_info *dev_info = &hba->dev_info;
8034 u32 ext_ufs_feature;
8038 /* Only UFS-4.0 and above may support EXT_IID */
8039 if (dev_info->wspecversion < 0x400)
8042 ext_ufs_feature = get_unaligned_be32(desc_buf +
8043 DEVICE_DESC_PARAM_EXT_UFS_FEATURE_SUP);
8044 if (!(ext_ufs_feature & UFS_DEV_EXT_IID_SUP))
8047 err = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
8048 QUERY_ATTR_IDN_EXT_IID_EN, 0, 0, &ext_iid_en);
8050 dev_err(hba->dev, "failed reading bEXTIIDEn. err = %d\n", err);
8053 dev_info->b_ext_iid_en = ext_iid_en;
8056 void ufshcd_fixup_dev_quirks(struct ufs_hba *hba,
8057 const struct ufs_dev_quirk *fixups)
8059 const struct ufs_dev_quirk *f;
8060 struct ufs_dev_info *dev_info = &hba->dev_info;
8065 for (f = fixups; f->quirk; f++) {
8066 if ((f->wmanufacturerid == dev_info->wmanufacturerid ||
8067 f->wmanufacturerid == UFS_ANY_VENDOR) &&
8068 ((dev_info->model &&
8069 STR_PRFX_EQUAL(f->model, dev_info->model)) ||
8070 !strcmp(f->model, UFS_ANY_MODEL)))
8071 hba->dev_quirks |= f->quirk;
8074 EXPORT_SYMBOL_GPL(ufshcd_fixup_dev_quirks);
8076 static void ufs_fixup_device_setup(struct ufs_hba *hba)
8078 /* fix by general quirk table */
8079 ufshcd_fixup_dev_quirks(hba, ufs_fixups);
8081 /* allow vendors to fix quirks */
8082 ufshcd_vops_fixup_dev_quirks(hba);
8085 static int ufs_get_device_desc(struct ufs_hba *hba)
8090 struct ufs_dev_info *dev_info = &hba->dev_info;
8092 desc_buf = kzalloc(QUERY_DESC_MAX_SIZE, GFP_KERNEL);
8098 err = ufshcd_read_desc_param(hba, QUERY_DESC_IDN_DEVICE, 0, 0, desc_buf,
8099 QUERY_DESC_MAX_SIZE);
8101 dev_err(hba->dev, "%s: Failed reading Device Desc. err = %d\n",
8107 * getting vendor (manufacturerID) and Bank Index in big endian
8110 dev_info->wmanufacturerid = desc_buf[DEVICE_DESC_PARAM_MANF_ID] << 8 |
8111 desc_buf[DEVICE_DESC_PARAM_MANF_ID + 1];
8113 /* getting Specification Version in big endian format */
8114 dev_info->wspecversion = desc_buf[DEVICE_DESC_PARAM_SPEC_VER] << 8 |
8115 desc_buf[DEVICE_DESC_PARAM_SPEC_VER + 1];
8116 dev_info->bqueuedepth = desc_buf[DEVICE_DESC_PARAM_Q_DPTH];
8118 model_index = desc_buf[DEVICE_DESC_PARAM_PRDCT_NAME];
8120 err = ufshcd_read_string_desc(hba, model_index,
8121 &dev_info->model, SD_ASCII_STD);
8123 dev_err(hba->dev, "%s: Failed reading Product Name. err = %d\n",
8128 hba->luns_avail = desc_buf[DEVICE_DESC_PARAM_NUM_LU] +
8129 desc_buf[DEVICE_DESC_PARAM_NUM_WLU];
8131 ufs_fixup_device_setup(hba);
8133 ufshcd_wb_probe(hba, desc_buf);
8135 ufshcd_temp_notif_probe(hba, desc_buf);
8137 if (hba->ext_iid_sup)
8138 ufshcd_ext_iid_probe(hba, desc_buf);
8141 * ufshcd_read_string_desc returns size of the string
8142 * reset the error value
8151 static void ufs_put_device_desc(struct ufs_hba *hba)
8153 struct ufs_dev_info *dev_info = &hba->dev_info;
8155 kfree(dev_info->model);
8156 dev_info->model = NULL;
8160 * ufshcd_tune_pa_tactivate - Tunes PA_TActivate of local UniPro
8161 * @hba: per-adapter instance
8163 * PA_TActivate parameter can be tuned manually if UniPro version is less than
8164 * 1.61. PA_TActivate needs to be greater than or equal to peerM-PHY's
8165 * RX_MIN_ACTIVATETIME_CAPABILITY attribute. This optimal value can help reduce
8166 * the hibern8 exit latency.
8168 * Return: zero on success, non-zero error value on failure.
8170 static int ufshcd_tune_pa_tactivate(struct ufs_hba *hba)
8173 u32 peer_rx_min_activatetime = 0, tuned_pa_tactivate;
8175 ret = ufshcd_dme_peer_get(hba,
8177 RX_MIN_ACTIVATETIME_CAPABILITY,
8178 UIC_ARG_MPHY_RX_GEN_SEL_INDEX(0)),
8179 &peer_rx_min_activatetime);
8183 /* make sure proper unit conversion is applied */
8184 tuned_pa_tactivate =
8185 ((peer_rx_min_activatetime * RX_MIN_ACTIVATETIME_UNIT_US)
8186 / PA_TACTIVATE_TIME_UNIT_US);
8187 ret = ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TACTIVATE),
8188 tuned_pa_tactivate);
8195 * ufshcd_tune_pa_hibern8time - Tunes PA_Hibern8Time of local UniPro
8196 * @hba: per-adapter instance
8198 * PA_Hibern8Time parameter can be tuned manually if UniPro version is less than
8199 * 1.61. PA_Hibern8Time needs to be maximum of local M-PHY's
8200 * TX_HIBERN8TIME_CAPABILITY & peer M-PHY's RX_HIBERN8TIME_CAPABILITY.
8201 * This optimal value can help reduce the hibern8 exit latency.
8203 * Return: zero on success, non-zero error value on failure.
8205 static int ufshcd_tune_pa_hibern8time(struct ufs_hba *hba)
8208 u32 local_tx_hibern8_time_cap = 0, peer_rx_hibern8_time_cap = 0;
8209 u32 max_hibern8_time, tuned_pa_hibern8time;
8211 ret = ufshcd_dme_get(hba,
8212 UIC_ARG_MIB_SEL(TX_HIBERN8TIME_CAPABILITY,
8213 UIC_ARG_MPHY_TX_GEN_SEL_INDEX(0)),
8214 &local_tx_hibern8_time_cap);
8218 ret = ufshcd_dme_peer_get(hba,
8219 UIC_ARG_MIB_SEL(RX_HIBERN8TIME_CAPABILITY,
8220 UIC_ARG_MPHY_RX_GEN_SEL_INDEX(0)),
8221 &peer_rx_hibern8_time_cap);
8225 max_hibern8_time = max(local_tx_hibern8_time_cap,
8226 peer_rx_hibern8_time_cap);
8227 /* make sure proper unit conversion is applied */
8228 tuned_pa_hibern8time = ((max_hibern8_time * HIBERN8TIME_UNIT_US)
8229 / PA_HIBERN8_TIME_UNIT_US);
8230 ret = ufshcd_dme_set(hba, UIC_ARG_MIB(PA_HIBERN8TIME),
8231 tuned_pa_hibern8time);
8237 * ufshcd_quirk_tune_host_pa_tactivate - Ensures that host PA_TACTIVATE is
8238 * less than device PA_TACTIVATE time.
8239 * @hba: per-adapter instance
8241 * Some UFS devices require host PA_TACTIVATE to be lower than device
8242 * PA_TACTIVATE, we need to enable UFS_DEVICE_QUIRK_HOST_PA_TACTIVATE quirk
8245 * Return: zero on success, non-zero error value on failure.
8247 static int ufshcd_quirk_tune_host_pa_tactivate(struct ufs_hba *hba)
8250 u32 granularity, peer_granularity;
8251 u32 pa_tactivate, peer_pa_tactivate;
8252 u32 pa_tactivate_us, peer_pa_tactivate_us;
8253 static const u8 gran_to_us_table[] = {1, 4, 8, 16, 32, 100};
8255 ret = ufshcd_dme_get(hba, UIC_ARG_MIB(PA_GRANULARITY),
8260 ret = ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_GRANULARITY),
8265 if ((granularity < PA_GRANULARITY_MIN_VAL) ||
8266 (granularity > PA_GRANULARITY_MAX_VAL)) {
8267 dev_err(hba->dev, "%s: invalid host PA_GRANULARITY %d",
8268 __func__, granularity);
8272 if ((peer_granularity < PA_GRANULARITY_MIN_VAL) ||
8273 (peer_granularity > PA_GRANULARITY_MAX_VAL)) {
8274 dev_err(hba->dev, "%s: invalid device PA_GRANULARITY %d",
8275 __func__, peer_granularity);
8279 ret = ufshcd_dme_get(hba, UIC_ARG_MIB(PA_TACTIVATE), &pa_tactivate);
8283 ret = ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_TACTIVATE),
8284 &peer_pa_tactivate);
8288 pa_tactivate_us = pa_tactivate * gran_to_us_table[granularity - 1];
8289 peer_pa_tactivate_us = peer_pa_tactivate *
8290 gran_to_us_table[peer_granularity - 1];
8292 if (pa_tactivate_us >= peer_pa_tactivate_us) {
8293 u32 new_peer_pa_tactivate;
8295 new_peer_pa_tactivate = pa_tactivate_us /
8296 gran_to_us_table[peer_granularity - 1];
8297 new_peer_pa_tactivate++;
8298 ret = ufshcd_dme_peer_set(hba, UIC_ARG_MIB(PA_TACTIVATE),
8299 new_peer_pa_tactivate);
8306 static void ufshcd_tune_unipro_params(struct ufs_hba *hba)
8308 if (ufshcd_is_unipro_pa_params_tuning_req(hba)) {
8309 ufshcd_tune_pa_tactivate(hba);
8310 ufshcd_tune_pa_hibern8time(hba);
8313 ufshcd_vops_apply_dev_quirks(hba);
8315 if (hba->dev_quirks & UFS_DEVICE_QUIRK_PA_TACTIVATE)
8316 /* set 1ms timeout for PA_TACTIVATE */
8317 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TACTIVATE), 10);
8319 if (hba->dev_quirks & UFS_DEVICE_QUIRK_HOST_PA_TACTIVATE)
8320 ufshcd_quirk_tune_host_pa_tactivate(hba);
8323 static void ufshcd_clear_dbg_ufs_stats(struct ufs_hba *hba)
8325 hba->ufs_stats.hibern8_exit_cnt = 0;
8326 hba->ufs_stats.last_hibern8_exit_tstamp = ktime_set(0, 0);
8327 hba->req_abort_count = 0;
8330 static int ufshcd_device_geo_params_init(struct ufs_hba *hba)
8335 desc_buf = kzalloc(QUERY_DESC_MAX_SIZE, GFP_KERNEL);
8341 err = ufshcd_read_desc_param(hba, QUERY_DESC_IDN_GEOMETRY, 0, 0,
8342 desc_buf, QUERY_DESC_MAX_SIZE);
8344 dev_err(hba->dev, "%s: Failed reading Geometry Desc. err = %d\n",
8349 if (desc_buf[GEOMETRY_DESC_PARAM_MAX_NUM_LUN] == 1)
8350 hba->dev_info.max_lu_supported = 32;
8351 else if (desc_buf[GEOMETRY_DESC_PARAM_MAX_NUM_LUN] == 0)
8352 hba->dev_info.max_lu_supported = 8;
8359 struct ufs_ref_clk {
8360 unsigned long freq_hz;
8361 enum ufs_ref_clk_freq val;
8364 static const struct ufs_ref_clk ufs_ref_clk_freqs[] = {
8365 {19200000, REF_CLK_FREQ_19_2_MHZ},
8366 {26000000, REF_CLK_FREQ_26_MHZ},
8367 {38400000, REF_CLK_FREQ_38_4_MHZ},
8368 {52000000, REF_CLK_FREQ_52_MHZ},
8369 {0, REF_CLK_FREQ_INVAL},
8372 static enum ufs_ref_clk_freq
8373 ufs_get_bref_clk_from_hz(unsigned long freq)
8377 for (i = 0; ufs_ref_clk_freqs[i].freq_hz; i++)
8378 if (ufs_ref_clk_freqs[i].freq_hz == freq)
8379 return ufs_ref_clk_freqs[i].val;
8381 return REF_CLK_FREQ_INVAL;
8384 void ufshcd_parse_dev_ref_clk_freq(struct ufs_hba *hba, struct clk *refclk)
8388 freq = clk_get_rate(refclk);
8390 hba->dev_ref_clk_freq =
8391 ufs_get_bref_clk_from_hz(freq);
8393 if (hba->dev_ref_clk_freq == REF_CLK_FREQ_INVAL)
8395 "invalid ref_clk setting = %ld\n", freq);
8398 static int ufshcd_set_dev_ref_clk(struct ufs_hba *hba)
8402 u32 freq = hba->dev_ref_clk_freq;
8404 err = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
8405 QUERY_ATTR_IDN_REF_CLK_FREQ, 0, 0, &ref_clk);
8408 dev_err(hba->dev, "failed reading bRefClkFreq. err = %d\n",
8413 if (ref_clk == freq)
8414 goto out; /* nothing to update */
8416 err = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_WRITE_ATTR,
8417 QUERY_ATTR_IDN_REF_CLK_FREQ, 0, 0, &freq);
8420 dev_err(hba->dev, "bRefClkFreq setting to %lu Hz failed\n",
8421 ufs_ref_clk_freqs[freq].freq_hz);
8425 dev_dbg(hba->dev, "bRefClkFreq setting to %lu Hz succeeded\n",
8426 ufs_ref_clk_freqs[freq].freq_hz);
8432 static int ufshcd_device_params_init(struct ufs_hba *hba)
8437 /* Init UFS geometry descriptor related parameters */
8438 ret = ufshcd_device_geo_params_init(hba);
8442 /* Check and apply UFS device quirks */
8443 ret = ufs_get_device_desc(hba);
8445 dev_err(hba->dev, "%s: Failed getting device info. err = %d\n",
8450 ufshcd_get_ref_clk_gating_wait(hba);
8452 if (!ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_READ_FLAG,
8453 QUERY_FLAG_IDN_PWR_ON_WPE, 0, &flag))
8454 hba->dev_info.f_power_on_wp_en = flag;
8456 /* Probe maximum power mode co-supported by both UFS host and device */
8457 if (ufshcd_get_max_pwr_mode(hba))
8459 "%s: Failed getting max supported power mode\n",
8465 static void ufshcd_set_timestamp_attr(struct ufs_hba *hba)
8468 struct ufs_query_req *request = NULL;
8469 struct ufs_query_res *response = NULL;
8470 struct ufs_dev_info *dev_info = &hba->dev_info;
8471 struct utp_upiu_query_v4_0 *upiu_data;
8473 if (dev_info->wspecversion < 0x400)
8478 mutex_lock(&hba->dev_cmd.lock);
8480 ufshcd_init_query(hba, &request, &response,
8481 UPIU_QUERY_OPCODE_WRITE_ATTR,
8482 QUERY_ATTR_IDN_TIMESTAMP, 0, 0);
8484 request->query_func = UPIU_QUERY_FUNC_STANDARD_WRITE_REQUEST;
8486 upiu_data = (struct utp_upiu_query_v4_0 *)&request->upiu_req;
8488 put_unaligned_be64(ktime_get_real_ns(), &upiu_data->osf3);
8490 err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_QUERY, QUERY_REQ_TIMEOUT);
8493 dev_err(hba->dev, "%s: failed to set timestamp %d\n",
8496 mutex_unlock(&hba->dev_cmd.lock);
8497 ufshcd_release(hba);
8501 * ufshcd_add_lus - probe and add UFS logical units
8502 * @hba: per-adapter instance
8504 * Return: 0 upon success; < 0 upon failure.
8506 static int ufshcd_add_lus(struct ufs_hba *hba)
8510 /* Add required well known logical units to scsi mid layer */
8511 ret = ufshcd_scsi_add_wlus(hba);
8515 /* Initialize devfreq after UFS device is detected */
8516 if (ufshcd_is_clkscaling_supported(hba)) {
8517 memcpy(&hba->clk_scaling.saved_pwr_info,
8519 sizeof(struct ufs_pa_layer_attr));
8520 hba->clk_scaling.is_allowed = true;
8522 ret = ufshcd_devfreq_init(hba);
8526 hba->clk_scaling.is_enabled = true;
8527 ufshcd_init_clk_scaling_sysfs(hba);
8531 scsi_scan_host(hba->host);
8532 pm_runtime_put_sync(hba->dev);
8538 /* SDB - Single Doorbell */
8539 static void ufshcd_release_sdb_queue(struct ufs_hba *hba, int nutrs)
8541 size_t ucdl_size, utrdl_size;
8543 ucdl_size = ufshcd_get_ucd_size(hba) * nutrs;
8544 dmam_free_coherent(hba->dev, ucdl_size, hba->ucdl_base_addr,
8545 hba->ucdl_dma_addr);
8547 utrdl_size = sizeof(struct utp_transfer_req_desc) * nutrs;
8548 dmam_free_coherent(hba->dev, utrdl_size, hba->utrdl_base_addr,
8549 hba->utrdl_dma_addr);
8551 devm_kfree(hba->dev, hba->lrb);
8554 static int ufshcd_alloc_mcq(struct ufs_hba *hba)
8557 int old_nutrs = hba->nutrs;
8559 ret = ufshcd_mcq_decide_queue_depth(hba);
8564 ret = ufshcd_mcq_init(hba);
8569 * Previously allocated memory for nutrs may not be enough in MCQ mode.
8570 * Number of supported tags in MCQ mode may be larger than SDB mode.
8572 if (hba->nutrs != old_nutrs) {
8573 ufshcd_release_sdb_queue(hba, old_nutrs);
8574 ret = ufshcd_memory_alloc(hba);
8577 ufshcd_host_memory_configure(hba);
8580 ret = ufshcd_mcq_memory_alloc(hba);
8586 hba->nutrs = old_nutrs;
8590 static void ufshcd_config_mcq(struct ufs_hba *hba)
8595 ret = ufshcd_mcq_vops_config_esi(hba);
8596 dev_info(hba->dev, "ESI %sconfigured\n", ret ? "is not " : "");
8598 intrs = UFSHCD_ENABLE_MCQ_INTRS;
8599 if (hba->quirks & UFSHCD_QUIRK_MCQ_BROKEN_INTR)
8600 intrs &= ~MCQ_CQ_EVENT_STATUS;
8601 ufshcd_enable_intr(hba, intrs);
8602 ufshcd_mcq_make_queues_operational(hba);
8603 ufshcd_mcq_config_mac(hba, hba->nutrs);
8605 hba->host->can_queue = hba->nutrs - UFSHCD_NUM_RESERVED;
8606 hba->reserved_slot = hba->nutrs - UFSHCD_NUM_RESERVED;
8608 /* Select MCQ mode */
8609 ufshcd_writel(hba, ufshcd_readl(hba, REG_UFS_MEM_CFG) | 0x1,
8611 hba->mcq_enabled = true;
8613 dev_info(hba->dev, "MCQ configured, nr_queues=%d, io_queues=%d, read_queue=%d, poll_queues=%d, queue_depth=%d\n",
8614 hba->nr_hw_queues, hba->nr_queues[HCTX_TYPE_DEFAULT],
8615 hba->nr_queues[HCTX_TYPE_READ], hba->nr_queues[HCTX_TYPE_POLL],
8619 static int ufshcd_device_init(struct ufs_hba *hba, bool init_dev_params)
8622 struct Scsi_Host *host = hba->host;
8624 hba->ufshcd_state = UFSHCD_STATE_RESET;
8626 ret = ufshcd_link_startup(hba);
8630 if (hba->quirks & UFSHCD_QUIRK_SKIP_PH_CONFIGURATION)
8633 /* Debug counters initialization */
8634 ufshcd_clear_dbg_ufs_stats(hba);
8636 /* UniPro link is active now */
8637 ufshcd_set_link_active(hba);
8639 /* Reconfigure MCQ upon reset */
8640 if (is_mcq_enabled(hba) && !init_dev_params)
8641 ufshcd_config_mcq(hba);
8643 /* Verify device initialization by sending NOP OUT UPIU */
8644 ret = ufshcd_verify_dev_init(hba);
8648 /* Initiate UFS initialization, and waiting until completion */
8649 ret = ufshcd_complete_dev_init(hba);
8654 * Initialize UFS device parameters used by driver, these
8655 * parameters are associated with UFS descriptors.
8657 if (init_dev_params) {
8658 ret = ufshcd_device_params_init(hba);
8661 if (is_mcq_supported(hba) && !hba->scsi_host_added) {
8662 ret = ufshcd_alloc_mcq(hba);
8664 ufshcd_config_mcq(hba);
8666 /* Continue with SDB mode */
8667 use_mcq_mode = false;
8668 dev_err(hba->dev, "MCQ mode is disabled, err=%d\n",
8671 ret = scsi_add_host(host, hba->dev);
8673 dev_err(hba->dev, "scsi_add_host failed\n");
8676 hba->scsi_host_added = true;
8677 } else if (is_mcq_supported(hba)) {
8678 /* UFSHCD_QUIRK_REINIT_AFTER_MAX_GEAR_SWITCH is set */
8679 ufshcd_config_mcq(hba);
8683 ufshcd_tune_unipro_params(hba);
8685 /* UFS device is also active now */
8686 ufshcd_set_ufs_dev_active(hba);
8687 ufshcd_force_reset_auto_bkops(hba);
8689 ufshcd_set_timestamp_attr(hba);
8691 /* Gear up to HS gear if supported */
8692 if (hba->max_pwr_info.is_valid) {
8694 * Set the right value to bRefClkFreq before attempting to
8695 * switch to HS gears.
8697 if (hba->dev_ref_clk_freq != REF_CLK_FREQ_INVAL)
8698 ufshcd_set_dev_ref_clk(hba);
8699 ret = ufshcd_config_pwr_mode(hba, &hba->max_pwr_info.info);
8701 dev_err(hba->dev, "%s: Failed setting power mode, err = %d\n",
8711 * ufshcd_probe_hba - probe hba to detect device and initialize it
8712 * @hba: per-adapter instance
8713 * @init_dev_params: whether or not to call ufshcd_device_params_init().
8715 * Execute link-startup and verify device initialization
8717 * Return: 0 upon success; < 0 upon failure.
8719 static int ufshcd_probe_hba(struct ufs_hba *hba, bool init_dev_params)
8721 ktime_t start = ktime_get();
8722 unsigned long flags;
8725 ret = ufshcd_device_init(hba, init_dev_params);
8729 if (!hba->pm_op_in_progress &&
8730 (hba->quirks & UFSHCD_QUIRK_REINIT_AFTER_MAX_GEAR_SWITCH)) {
8731 /* Reset the device and controller before doing reinit */
8732 ufshcd_device_reset(hba);
8733 ufshcd_hba_stop(hba);
8734 ufshcd_vops_reinit_notify(hba);
8735 ret = ufshcd_hba_enable(hba);
8737 dev_err(hba->dev, "Host controller enable failed\n");
8738 ufshcd_print_evt_hist(hba);
8739 ufshcd_print_host_state(hba);
8743 /* Reinit the device */
8744 ret = ufshcd_device_init(hba, init_dev_params);
8749 ufshcd_print_pwr_info(hba);
8752 * bActiveICCLevel is volatile for UFS device (as per latest v2.1 spec)
8753 * and for removable UFS card as well, hence always set the parameter.
8754 * Note: Error handler may issue the device reset hence resetting
8755 * bActiveICCLevel as well so it is always safe to set this here.
8757 ufshcd_set_active_icc_lvl(hba);
8759 /* Enable UFS Write Booster if supported */
8760 ufshcd_configure_wb(hba);
8762 if (hba->ee_usr_mask)
8763 ufshcd_write_ee_control(hba);
8764 /* Enable Auto-Hibernate if configured */
8765 ufshcd_auto_hibern8_enable(hba);
8768 spin_lock_irqsave(hba->host->host_lock, flags);
8770 hba->ufshcd_state = UFSHCD_STATE_ERROR;
8771 else if (hba->ufshcd_state == UFSHCD_STATE_RESET)
8772 hba->ufshcd_state = UFSHCD_STATE_OPERATIONAL;
8773 spin_unlock_irqrestore(hba->host->host_lock, flags);
8775 trace_ufshcd_init(dev_name(hba->dev), ret,
8776 ktime_to_us(ktime_sub(ktime_get(), start)),
8777 hba->curr_dev_pwr_mode, hba->uic_link_state);
8782 * ufshcd_async_scan - asynchronous execution for probing hba
8783 * @data: data pointer to pass to this function
8784 * @cookie: cookie data
8786 static void ufshcd_async_scan(void *data, async_cookie_t cookie)
8788 struct ufs_hba *hba = (struct ufs_hba *)data;
8791 down(&hba->host_sem);
8792 /* Initialize hba, detect and initialize UFS device */
8793 ret = ufshcd_probe_hba(hba, true);
8798 /* Probe and add UFS logical units */
8799 ret = ufshcd_add_lus(hba);
8802 * If we failed to initialize the device or the device is not
8803 * present, turn off the power/clocks etc.
8806 pm_runtime_put_sync(hba->dev);
8807 ufshcd_hba_exit(hba);
8811 static enum scsi_timeout_action ufshcd_eh_timed_out(struct scsi_cmnd *scmd)
8813 struct ufs_hba *hba = shost_priv(scmd->device->host);
8815 if (!hba->system_suspending) {
8816 /* Activate the error handler in the SCSI core. */
8817 return SCSI_EH_NOT_HANDLED;
8821 * If we get here we know that no TMFs are outstanding and also that
8822 * the only pending command is a START STOP UNIT command. Handle the
8823 * timeout of that command directly to prevent a deadlock between
8824 * ufshcd_set_dev_pwr_mode() and ufshcd_err_handler().
8826 ufshcd_link_recovery(hba);
8827 dev_info(hba->dev, "%s() finished; outstanding_tasks = %#lx.\n",
8828 __func__, hba->outstanding_tasks);
8830 return hba->outstanding_reqs ? SCSI_EH_RESET_TIMER : SCSI_EH_DONE;
8833 static const struct attribute_group *ufshcd_driver_groups[] = {
8834 &ufs_sysfs_unit_descriptor_group,
8835 &ufs_sysfs_lun_attributes_group,
8839 static struct ufs_hba_variant_params ufs_hba_vps = {
8840 .hba_enable_delay_us = 1000,
8841 .wb_flush_threshold = UFS_WB_BUF_REMAIN_PERCENT(40),
8842 .devfreq_profile.polling_ms = 100,
8843 .devfreq_profile.target = ufshcd_devfreq_target,
8844 .devfreq_profile.get_dev_status = ufshcd_devfreq_get_dev_status,
8845 .ondemand_data.upthreshold = 70,
8846 .ondemand_data.downdifferential = 5,
8849 static const struct scsi_host_template ufshcd_driver_template = {
8850 .module = THIS_MODULE,
8852 .proc_name = UFSHCD,
8853 .map_queues = ufshcd_map_queues,
8854 .queuecommand = ufshcd_queuecommand,
8855 .mq_poll = ufshcd_poll,
8856 .slave_alloc = ufshcd_slave_alloc,
8857 .slave_configure = ufshcd_slave_configure,
8858 .slave_destroy = ufshcd_slave_destroy,
8859 .change_queue_depth = ufshcd_change_queue_depth,
8860 .eh_abort_handler = ufshcd_abort,
8861 .eh_device_reset_handler = ufshcd_eh_device_reset_handler,
8862 .eh_host_reset_handler = ufshcd_eh_host_reset_handler,
8863 .eh_timed_out = ufshcd_eh_timed_out,
8865 .sg_tablesize = SG_ALL,
8866 .cmd_per_lun = UFSHCD_CMD_PER_LUN,
8867 .can_queue = UFSHCD_CAN_QUEUE,
8868 .max_segment_size = PRDT_DATA_BYTE_COUNT_MAX,
8869 .max_sectors = SZ_1M / SECTOR_SIZE,
8870 .max_host_blocked = 1,
8871 .track_queue_depth = 1,
8872 .skip_settle_delay = 1,
8873 .sdev_groups = ufshcd_driver_groups,
8874 .rpm_autosuspend_delay = RPM_AUTOSUSPEND_DELAY_MS,
8877 static int ufshcd_config_vreg_load(struct device *dev, struct ufs_vreg *vreg,
8886 * "set_load" operation shall be required on those regulators
8887 * which specifically configured current limitation. Otherwise
8888 * zero max_uA may cause unexpected behavior when regulator is
8889 * enabled or set as high power mode.
8894 ret = regulator_set_load(vreg->reg, ua);
8896 dev_err(dev, "%s: %s set load (ua=%d) failed, err=%d\n",
8897 __func__, vreg->name, ua, ret);
8903 static inline int ufshcd_config_vreg_lpm(struct ufs_hba *hba,
8904 struct ufs_vreg *vreg)
8906 return ufshcd_config_vreg_load(hba->dev, vreg, UFS_VREG_LPM_LOAD_UA);
8909 static inline int ufshcd_config_vreg_hpm(struct ufs_hba *hba,
8910 struct ufs_vreg *vreg)
8915 return ufshcd_config_vreg_load(hba->dev, vreg, vreg->max_uA);
8918 static int ufshcd_config_vreg(struct device *dev,
8919 struct ufs_vreg *vreg, bool on)
8921 if (regulator_count_voltages(vreg->reg) <= 0)
8924 return ufshcd_config_vreg_load(dev, vreg, on ? vreg->max_uA : 0);
8927 static int ufshcd_enable_vreg(struct device *dev, struct ufs_vreg *vreg)
8931 if (!vreg || vreg->enabled)
8934 ret = ufshcd_config_vreg(dev, vreg, true);
8936 ret = regulator_enable(vreg->reg);
8939 vreg->enabled = true;
8941 dev_err(dev, "%s: %s enable failed, err=%d\n",
8942 __func__, vreg->name, ret);
8947 static int ufshcd_disable_vreg(struct device *dev, struct ufs_vreg *vreg)
8951 if (!vreg || !vreg->enabled || vreg->always_on)
8954 ret = regulator_disable(vreg->reg);
8957 /* ignore errors on applying disable config */
8958 ufshcd_config_vreg(dev, vreg, false);
8959 vreg->enabled = false;
8961 dev_err(dev, "%s: %s disable failed, err=%d\n",
8962 __func__, vreg->name, ret);
8968 static int ufshcd_setup_vreg(struct ufs_hba *hba, bool on)
8971 struct device *dev = hba->dev;
8972 struct ufs_vreg_info *info = &hba->vreg_info;
8974 ret = ufshcd_toggle_vreg(dev, info->vcc, on);
8978 ret = ufshcd_toggle_vreg(dev, info->vccq, on);
8982 ret = ufshcd_toggle_vreg(dev, info->vccq2, on);
8986 ufshcd_toggle_vreg(dev, info->vccq2, false);
8987 ufshcd_toggle_vreg(dev, info->vccq, false);
8988 ufshcd_toggle_vreg(dev, info->vcc, false);
8993 static int ufshcd_setup_hba_vreg(struct ufs_hba *hba, bool on)
8995 struct ufs_vreg_info *info = &hba->vreg_info;
8997 return ufshcd_toggle_vreg(hba->dev, info->vdd_hba, on);
9000 int ufshcd_get_vreg(struct device *dev, struct ufs_vreg *vreg)
9007 vreg->reg = devm_regulator_get(dev, vreg->name);
9008 if (IS_ERR(vreg->reg)) {
9009 ret = PTR_ERR(vreg->reg);
9010 dev_err(dev, "%s: %s get failed, err=%d\n",
9011 __func__, vreg->name, ret);
9016 EXPORT_SYMBOL_GPL(ufshcd_get_vreg);
9018 static int ufshcd_init_vreg(struct ufs_hba *hba)
9021 struct device *dev = hba->dev;
9022 struct ufs_vreg_info *info = &hba->vreg_info;
9024 ret = ufshcd_get_vreg(dev, info->vcc);
9028 ret = ufshcd_get_vreg(dev, info->vccq);
9030 ret = ufshcd_get_vreg(dev, info->vccq2);
9035 static int ufshcd_init_hba_vreg(struct ufs_hba *hba)
9037 struct ufs_vreg_info *info = &hba->vreg_info;
9039 return ufshcd_get_vreg(hba->dev, info->vdd_hba);
9042 static int ufshcd_setup_clocks(struct ufs_hba *hba, bool on)
9045 struct ufs_clk_info *clki;
9046 struct list_head *head = &hba->clk_list_head;
9047 unsigned long flags;
9048 ktime_t start = ktime_get();
9049 bool clk_state_changed = false;
9051 if (list_empty(head))
9054 ret = ufshcd_vops_setup_clocks(hba, on, PRE_CHANGE);
9058 list_for_each_entry(clki, head, list) {
9059 if (!IS_ERR_OR_NULL(clki->clk)) {
9061 * Don't disable clocks which are needed
9062 * to keep the link active.
9064 if (ufshcd_is_link_active(hba) &&
9065 clki->keep_link_active)
9068 clk_state_changed = on ^ clki->enabled;
9069 if (on && !clki->enabled) {
9070 ret = clk_prepare_enable(clki->clk);
9072 dev_err(hba->dev, "%s: %s prepare enable failed, %d\n",
9073 __func__, clki->name, ret);
9076 } else if (!on && clki->enabled) {
9077 clk_disable_unprepare(clki->clk);
9080 dev_dbg(hba->dev, "%s: clk: %s %sabled\n", __func__,
9081 clki->name, on ? "en" : "dis");
9085 ret = ufshcd_vops_setup_clocks(hba, on, POST_CHANGE);
9091 list_for_each_entry(clki, head, list) {
9092 if (!IS_ERR_OR_NULL(clki->clk) && clki->enabled)
9093 clk_disable_unprepare(clki->clk);
9095 } else if (!ret && on) {
9096 spin_lock_irqsave(hba->host->host_lock, flags);
9097 hba->clk_gating.state = CLKS_ON;
9098 trace_ufshcd_clk_gating(dev_name(hba->dev),
9099 hba->clk_gating.state);
9100 spin_unlock_irqrestore(hba->host->host_lock, flags);
9103 if (clk_state_changed)
9104 trace_ufshcd_profile_clk_gating(dev_name(hba->dev),
9105 (on ? "on" : "off"),
9106 ktime_to_us(ktime_sub(ktime_get(), start)), ret);
9110 static enum ufs_ref_clk_freq ufshcd_parse_ref_clk_property(struct ufs_hba *hba)
9113 int ret = device_property_read_u32(hba->dev, "ref-clk-freq", &freq);
9116 dev_dbg(hba->dev, "Cannot query 'ref-clk-freq' property = %d", ret);
9117 return REF_CLK_FREQ_INVAL;
9120 return ufs_get_bref_clk_from_hz(freq);
9123 static int ufshcd_init_clocks(struct ufs_hba *hba)
9126 struct ufs_clk_info *clki;
9127 struct device *dev = hba->dev;
9128 struct list_head *head = &hba->clk_list_head;
9130 if (list_empty(head))
9133 list_for_each_entry(clki, head, list) {
9137 clki->clk = devm_clk_get(dev, clki->name);
9138 if (IS_ERR(clki->clk)) {
9139 ret = PTR_ERR(clki->clk);
9140 dev_err(dev, "%s: %s clk get failed, %d\n",
9141 __func__, clki->name, ret);
9146 * Parse device ref clk freq as per device tree "ref_clk".
9147 * Default dev_ref_clk_freq is set to REF_CLK_FREQ_INVAL
9148 * in ufshcd_alloc_host().
9150 if (!strcmp(clki->name, "ref_clk"))
9151 ufshcd_parse_dev_ref_clk_freq(hba, clki->clk);
9153 if (clki->max_freq) {
9154 ret = clk_set_rate(clki->clk, clki->max_freq);
9156 dev_err(hba->dev, "%s: %s clk set rate(%dHz) failed, %d\n",
9157 __func__, clki->name,
9158 clki->max_freq, ret);
9161 clki->curr_freq = clki->max_freq;
9163 dev_dbg(dev, "%s: clk: %s, rate: %lu\n", __func__,
9164 clki->name, clk_get_rate(clki->clk));
9170 static int ufshcd_variant_hba_init(struct ufs_hba *hba)
9177 err = ufshcd_vops_init(hba);
9179 dev_err_probe(hba->dev, err,
9180 "%s: variant %s init failed with err %d\n",
9181 __func__, ufshcd_get_var_name(hba), err);
9186 static void ufshcd_variant_hba_exit(struct ufs_hba *hba)
9191 ufshcd_vops_exit(hba);
9194 static int ufshcd_hba_init(struct ufs_hba *hba)
9199 * Handle host controller power separately from the UFS device power
9200 * rails as it will help controlling the UFS host controller power
9201 * collapse easily which is different than UFS device power collapse.
9202 * Also, enable the host controller power before we go ahead with rest
9203 * of the initialization here.
9205 err = ufshcd_init_hba_vreg(hba);
9209 err = ufshcd_setup_hba_vreg(hba, true);
9213 err = ufshcd_init_clocks(hba);
9215 goto out_disable_hba_vreg;
9217 if (hba->dev_ref_clk_freq == REF_CLK_FREQ_INVAL)
9218 hba->dev_ref_clk_freq = ufshcd_parse_ref_clk_property(hba);
9220 err = ufshcd_setup_clocks(hba, true);
9222 goto out_disable_hba_vreg;
9224 err = ufshcd_init_vreg(hba);
9226 goto out_disable_clks;
9228 err = ufshcd_setup_vreg(hba, true);
9230 goto out_disable_clks;
9232 err = ufshcd_variant_hba_init(hba);
9234 goto out_disable_vreg;
9236 ufs_debugfs_hba_init(hba);
9238 hba->is_powered = true;
9242 ufshcd_setup_vreg(hba, false);
9244 ufshcd_setup_clocks(hba, false);
9245 out_disable_hba_vreg:
9246 ufshcd_setup_hba_vreg(hba, false);
9251 static void ufshcd_hba_exit(struct ufs_hba *hba)
9253 if (hba->is_powered) {
9254 ufshcd_exit_clk_scaling(hba);
9255 ufshcd_exit_clk_gating(hba);
9257 destroy_workqueue(hba->eh_wq);
9258 ufs_debugfs_hba_exit(hba);
9259 ufshcd_variant_hba_exit(hba);
9260 ufshcd_setup_vreg(hba, false);
9261 ufshcd_setup_clocks(hba, false);
9262 ufshcd_setup_hba_vreg(hba, false);
9263 hba->is_powered = false;
9264 ufs_put_device_desc(hba);
9268 static int ufshcd_execute_start_stop(struct scsi_device *sdev,
9269 enum ufs_dev_pwr_mode pwr_mode,
9270 struct scsi_sense_hdr *sshdr)
9272 const unsigned char cdb[6] = { START_STOP, 0, 0, 0, pwr_mode << 4, 0 };
9273 const struct scsi_exec_args args = {
9275 .req_flags = BLK_MQ_REQ_PM,
9276 .scmd_flags = SCMD_FAIL_IF_RECOVERING,
9279 return scsi_execute_cmd(sdev, cdb, REQ_OP_DRV_IN, /*buffer=*/NULL,
9280 /*bufflen=*/0, /*timeout=*/10 * HZ, /*retries=*/0,
9285 * ufshcd_set_dev_pwr_mode - sends START STOP UNIT command to set device
9287 * @hba: per adapter instance
9288 * @pwr_mode: device power mode to set
9290 * Return: 0 if requested power mode is set successfully;
9291 * < 0 if failed to set the requested power mode.
9293 static int ufshcd_set_dev_pwr_mode(struct ufs_hba *hba,
9294 enum ufs_dev_pwr_mode pwr_mode)
9296 struct scsi_sense_hdr sshdr;
9297 struct scsi_device *sdp;
9298 unsigned long flags;
9301 spin_lock_irqsave(hba->host->host_lock, flags);
9302 sdp = hba->ufs_device_wlun;
9303 if (sdp && scsi_device_online(sdp))
9304 ret = scsi_device_get(sdp);
9307 spin_unlock_irqrestore(hba->host->host_lock, flags);
9313 * If scsi commands fail, the scsi mid-layer schedules scsi error-
9314 * handling, which would wait for host to be resumed. Since we know
9315 * we are functional while we are here, skip host resume in error
9318 hba->host->eh_noresume = 1;
9321 * Current function would be generally called from the power management
9322 * callbacks hence set the RQF_PM flag so that it doesn't resume the
9323 * already suspended childs.
9325 for (retries = 3; retries > 0; --retries) {
9326 ret = ufshcd_execute_start_stop(sdp, pwr_mode, &sshdr);
9328 * scsi_execute() only returns a negative value if the request
9335 sdev_printk(KERN_WARNING, sdp,
9336 "START_STOP failed for power mode: %d, result %x\n",
9339 if (scsi_sense_valid(&sshdr))
9340 scsi_print_sense_hdr(sdp, NULL, &sshdr);
9344 hba->curr_dev_pwr_mode = pwr_mode;
9347 scsi_device_put(sdp);
9348 hba->host->eh_noresume = 0;
9352 static int ufshcd_link_state_transition(struct ufs_hba *hba,
9353 enum uic_link_state req_link_state,
9354 bool check_for_bkops)
9358 if (req_link_state == hba->uic_link_state)
9361 if (req_link_state == UIC_LINK_HIBERN8_STATE) {
9362 ret = ufshcd_uic_hibern8_enter(hba);
9364 ufshcd_set_link_hibern8(hba);
9366 dev_err(hba->dev, "%s: hibern8 enter failed %d\n",
9372 * If autobkops is enabled, link can't be turned off because
9373 * turning off the link would also turn off the device, except in the
9374 * case of DeepSleep where the device is expected to remain powered.
9376 else if ((req_link_state == UIC_LINK_OFF_STATE) &&
9377 (!check_for_bkops || !hba->auto_bkops_enabled)) {
9379 * Let's make sure that link is in low power mode, we are doing
9380 * this currently by putting the link in Hibern8. Otherway to
9381 * put the link in low power mode is to send the DME end point
9382 * to device and then send the DME reset command to local
9383 * unipro. But putting the link in hibern8 is much faster.
9385 * Note also that putting the link in Hibern8 is a requirement
9386 * for entering DeepSleep.
9388 ret = ufshcd_uic_hibern8_enter(hba);
9390 dev_err(hba->dev, "%s: hibern8 enter failed %d\n",
9395 * Change controller state to "reset state" which
9396 * should also put the link in off/reset state
9398 ufshcd_hba_stop(hba);
9400 * TODO: Check if we need any delay to make sure that
9401 * controller is reset
9403 ufshcd_set_link_off(hba);
9410 static void ufshcd_vreg_set_lpm(struct ufs_hba *hba)
9412 bool vcc_off = false;
9415 * It seems some UFS devices may keep drawing more than sleep current
9416 * (atleast for 500us) from UFS rails (especially from VCCQ rail).
9417 * To avoid this situation, add 2ms delay before putting these UFS
9418 * rails in LPM mode.
9420 if (!ufshcd_is_link_active(hba) &&
9421 hba->dev_quirks & UFS_DEVICE_QUIRK_DELAY_BEFORE_LPM)
9422 usleep_range(2000, 2100);
9425 * If UFS device is either in UFS_Sleep turn off VCC rail to save some
9428 * If UFS device and link is in OFF state, all power supplies (VCC,
9429 * VCCQ, VCCQ2) can be turned off if power on write protect is not
9430 * required. If UFS link is inactive (Hibern8 or OFF state) and device
9431 * is in sleep state, put VCCQ & VCCQ2 rails in LPM mode.
9433 * Ignore the error returned by ufshcd_toggle_vreg() as device is anyway
9434 * in low power state which would save some power.
9436 * If Write Booster is enabled and the device needs to flush the WB
9437 * buffer OR if bkops status is urgent for WB, keep Vcc on.
9439 if (ufshcd_is_ufs_dev_poweroff(hba) && ufshcd_is_link_off(hba) &&
9440 !hba->dev_info.is_lu_power_on_wp) {
9441 ufshcd_setup_vreg(hba, false);
9443 } else if (!ufshcd_is_ufs_dev_active(hba)) {
9444 ufshcd_toggle_vreg(hba->dev, hba->vreg_info.vcc, false);
9446 if (ufshcd_is_link_hibern8(hba) || ufshcd_is_link_off(hba)) {
9447 ufshcd_config_vreg_lpm(hba, hba->vreg_info.vccq);
9448 ufshcd_config_vreg_lpm(hba, hba->vreg_info.vccq2);
9453 * Some UFS devices require delay after VCC power rail is turned-off.
9455 if (vcc_off && hba->vreg_info.vcc &&
9456 hba->dev_quirks & UFS_DEVICE_QUIRK_DELAY_AFTER_LPM)
9457 usleep_range(5000, 5100);
9461 static int ufshcd_vreg_set_hpm(struct ufs_hba *hba)
9465 if (ufshcd_is_ufs_dev_poweroff(hba) && ufshcd_is_link_off(hba) &&
9466 !hba->dev_info.is_lu_power_on_wp) {
9467 ret = ufshcd_setup_vreg(hba, true);
9468 } else if (!ufshcd_is_ufs_dev_active(hba)) {
9469 if (!ufshcd_is_link_active(hba)) {
9470 ret = ufshcd_config_vreg_hpm(hba, hba->vreg_info.vccq);
9473 ret = ufshcd_config_vreg_hpm(hba, hba->vreg_info.vccq2);
9477 ret = ufshcd_toggle_vreg(hba->dev, hba->vreg_info.vcc, true);
9482 ufshcd_config_vreg_lpm(hba, hba->vreg_info.vccq);
9484 ufshcd_toggle_vreg(hba->dev, hba->vreg_info.vcc, false);
9488 #endif /* CONFIG_PM */
9490 static void ufshcd_hba_vreg_set_lpm(struct ufs_hba *hba)
9492 if (ufshcd_is_link_off(hba) || ufshcd_can_aggressive_pc(hba))
9493 ufshcd_setup_hba_vreg(hba, false);
9496 static void ufshcd_hba_vreg_set_hpm(struct ufs_hba *hba)
9498 if (ufshcd_is_link_off(hba) || ufshcd_can_aggressive_pc(hba))
9499 ufshcd_setup_hba_vreg(hba, true);
9502 static int __ufshcd_wl_suspend(struct ufs_hba *hba, enum ufs_pm_op pm_op)
9505 bool check_for_bkops;
9506 enum ufs_pm_level pm_lvl;
9507 enum ufs_dev_pwr_mode req_dev_pwr_mode;
9508 enum uic_link_state req_link_state;
9510 hba->pm_op_in_progress = true;
9511 if (pm_op != UFS_SHUTDOWN_PM) {
9512 pm_lvl = pm_op == UFS_RUNTIME_PM ?
9513 hba->rpm_lvl : hba->spm_lvl;
9514 req_dev_pwr_mode = ufs_get_pm_lvl_to_dev_pwr_mode(pm_lvl);
9515 req_link_state = ufs_get_pm_lvl_to_link_pwr_state(pm_lvl);
9517 req_dev_pwr_mode = UFS_POWERDOWN_PWR_MODE;
9518 req_link_state = UIC_LINK_OFF_STATE;
9522 * If we can't transition into any of the low power modes
9523 * just gate the clocks.
9526 hba->clk_gating.is_suspended = true;
9528 if (ufshcd_is_clkscaling_supported(hba))
9529 ufshcd_clk_scaling_suspend(hba, true);
9531 if (req_dev_pwr_mode == UFS_ACTIVE_PWR_MODE &&
9532 req_link_state == UIC_LINK_ACTIVE_STATE) {
9536 if ((req_dev_pwr_mode == hba->curr_dev_pwr_mode) &&
9537 (req_link_state == hba->uic_link_state))
9538 goto enable_scaling;
9540 /* UFS device & link must be active before we enter in this function */
9541 if (!ufshcd_is_ufs_dev_active(hba) || !ufshcd_is_link_active(hba)) {
9543 goto enable_scaling;
9546 if (pm_op == UFS_RUNTIME_PM) {
9547 if (ufshcd_can_autobkops_during_suspend(hba)) {
9549 * The device is idle with no requests in the queue,
9550 * allow background operations if bkops status shows
9551 * that performance might be impacted.
9553 ret = ufshcd_urgent_bkops(hba);
9556 * If return err in suspend flow, IO will hang.
9557 * Trigger error handler and break suspend for
9560 ufshcd_force_error_recovery(hba);
9562 goto enable_scaling;
9565 /* make sure that auto bkops is disabled */
9566 ufshcd_disable_auto_bkops(hba);
9569 * If device needs to do BKOP or WB buffer flush during
9570 * Hibern8, keep device power mode as "active power mode"
9573 hba->dev_info.b_rpm_dev_flush_capable =
9574 hba->auto_bkops_enabled ||
9575 (((req_link_state == UIC_LINK_HIBERN8_STATE) ||
9576 ((req_link_state == UIC_LINK_ACTIVE_STATE) &&
9577 ufshcd_is_auto_hibern8_enabled(hba))) &&
9578 ufshcd_wb_need_flush(hba));
9581 flush_work(&hba->eeh_work);
9583 ret = ufshcd_vops_suspend(hba, pm_op, PRE_CHANGE);
9585 goto enable_scaling;
9587 if (req_dev_pwr_mode != hba->curr_dev_pwr_mode) {
9588 if (pm_op != UFS_RUNTIME_PM)
9589 /* ensure that bkops is disabled */
9590 ufshcd_disable_auto_bkops(hba);
9592 if (!hba->dev_info.b_rpm_dev_flush_capable) {
9593 ret = ufshcd_set_dev_pwr_mode(hba, req_dev_pwr_mode);
9594 if (ret && pm_op != UFS_SHUTDOWN_PM) {
9596 * If return err in suspend flow, IO will hang.
9597 * Trigger error handler and break suspend for
9600 ufshcd_force_error_recovery(hba);
9604 goto enable_scaling;
9609 * In the case of DeepSleep, the device is expected to remain powered
9610 * with the link off, so do not check for bkops.
9612 check_for_bkops = !ufshcd_is_ufs_dev_deepsleep(hba);
9613 ret = ufshcd_link_state_transition(hba, req_link_state, check_for_bkops);
9614 if (ret && pm_op != UFS_SHUTDOWN_PM) {
9616 * If return err in suspend flow, IO will hang.
9617 * Trigger error handler and break suspend for
9620 ufshcd_force_error_recovery(hba);
9624 goto set_dev_active;
9628 * Call vendor specific suspend callback. As these callbacks may access
9629 * vendor specific host controller register space call them before the
9630 * host clocks are ON.
9632 ret = ufshcd_vops_suspend(hba, pm_op, POST_CHANGE);
9634 goto set_link_active;
9639 * Device hardware reset is required to exit DeepSleep. Also, for
9640 * DeepSleep, the link is off so host reset and restore will be done
9643 if (ufshcd_is_ufs_dev_deepsleep(hba)) {
9644 ufshcd_device_reset(hba);
9645 WARN_ON(!ufshcd_is_link_off(hba));
9647 if (ufshcd_is_link_hibern8(hba) && !ufshcd_uic_hibern8_exit(hba))
9648 ufshcd_set_link_active(hba);
9649 else if (ufshcd_is_link_off(hba))
9650 ufshcd_host_reset_and_restore(hba);
9652 /* Can also get here needing to exit DeepSleep */
9653 if (ufshcd_is_ufs_dev_deepsleep(hba)) {
9654 ufshcd_device_reset(hba);
9655 ufshcd_host_reset_and_restore(hba);
9657 if (!ufshcd_set_dev_pwr_mode(hba, UFS_ACTIVE_PWR_MODE))
9658 ufshcd_disable_auto_bkops(hba);
9660 if (ufshcd_is_clkscaling_supported(hba))
9661 ufshcd_clk_scaling_suspend(hba, false);
9663 hba->dev_info.b_rpm_dev_flush_capable = false;
9665 if (hba->dev_info.b_rpm_dev_flush_capable) {
9666 schedule_delayed_work(&hba->rpm_dev_flush_recheck_work,
9667 msecs_to_jiffies(RPM_DEV_FLUSH_RECHECK_WORK_DELAY_MS));
9671 ufshcd_update_evt_hist(hba, UFS_EVT_WL_SUSP_ERR, (u32)ret);
9672 hba->clk_gating.is_suspended = false;
9673 ufshcd_release(hba);
9675 hba->pm_op_in_progress = false;
9680 static int __ufshcd_wl_resume(struct ufs_hba *hba, enum ufs_pm_op pm_op)
9683 enum uic_link_state old_link_state = hba->uic_link_state;
9685 hba->pm_op_in_progress = true;
9688 * Call vendor specific resume callback. As these callbacks may access
9689 * vendor specific host controller register space call them when the
9690 * host clocks are ON.
9692 ret = ufshcd_vops_resume(hba, pm_op);
9696 /* For DeepSleep, the only supported option is to have the link off */
9697 WARN_ON(ufshcd_is_ufs_dev_deepsleep(hba) && !ufshcd_is_link_off(hba));
9699 if (ufshcd_is_link_hibern8(hba)) {
9700 ret = ufshcd_uic_hibern8_exit(hba);
9702 ufshcd_set_link_active(hba);
9704 dev_err(hba->dev, "%s: hibern8 exit failed %d\n",
9706 goto vendor_suspend;
9708 } else if (ufshcd_is_link_off(hba)) {
9710 * A full initialization of the host and the device is
9711 * required since the link was put to off during suspend.
9712 * Note, in the case of DeepSleep, the device will exit
9713 * DeepSleep due to device reset.
9715 ret = ufshcd_reset_and_restore(hba);
9717 * ufshcd_reset_and_restore() should have already
9718 * set the link state as active
9720 if (ret || !ufshcd_is_link_active(hba))
9721 goto vendor_suspend;
9724 if (!ufshcd_is_ufs_dev_active(hba)) {
9725 ret = ufshcd_set_dev_pwr_mode(hba, UFS_ACTIVE_PWR_MODE);
9727 goto set_old_link_state;
9728 ufshcd_set_timestamp_attr(hba);
9731 if (ufshcd_keep_autobkops_enabled_except_suspend(hba))
9732 ufshcd_enable_auto_bkops(hba);
9735 * If BKOPs operations are urgently needed at this moment then
9736 * keep auto-bkops enabled or else disable it.
9738 ufshcd_urgent_bkops(hba);
9740 if (hba->ee_usr_mask)
9741 ufshcd_write_ee_control(hba);
9743 if (ufshcd_is_clkscaling_supported(hba))
9744 ufshcd_clk_scaling_suspend(hba, false);
9746 if (hba->dev_info.b_rpm_dev_flush_capable) {
9747 hba->dev_info.b_rpm_dev_flush_capable = false;
9748 cancel_delayed_work(&hba->rpm_dev_flush_recheck_work);
9751 /* Enable Auto-Hibernate if configured */
9752 ufshcd_auto_hibern8_enable(hba);
9757 ufshcd_link_state_transition(hba, old_link_state, 0);
9759 ufshcd_vops_suspend(hba, pm_op, PRE_CHANGE);
9760 ufshcd_vops_suspend(hba, pm_op, POST_CHANGE);
9763 ufshcd_update_evt_hist(hba, UFS_EVT_WL_RES_ERR, (u32)ret);
9764 hba->clk_gating.is_suspended = false;
9765 ufshcd_release(hba);
9766 hba->pm_op_in_progress = false;
9770 static int ufshcd_wl_runtime_suspend(struct device *dev)
9772 struct scsi_device *sdev = to_scsi_device(dev);
9773 struct ufs_hba *hba;
9775 ktime_t start = ktime_get();
9777 hba = shost_priv(sdev->host);
9779 ret = __ufshcd_wl_suspend(hba, UFS_RUNTIME_PM);
9781 dev_err(&sdev->sdev_gendev, "%s failed: %d\n", __func__, ret);
9783 trace_ufshcd_wl_runtime_suspend(dev_name(dev), ret,
9784 ktime_to_us(ktime_sub(ktime_get(), start)),
9785 hba->curr_dev_pwr_mode, hba->uic_link_state);
9790 static int ufshcd_wl_runtime_resume(struct device *dev)
9792 struct scsi_device *sdev = to_scsi_device(dev);
9793 struct ufs_hba *hba;
9795 ktime_t start = ktime_get();
9797 hba = shost_priv(sdev->host);
9799 ret = __ufshcd_wl_resume(hba, UFS_RUNTIME_PM);
9801 dev_err(&sdev->sdev_gendev, "%s failed: %d\n", __func__, ret);
9803 trace_ufshcd_wl_runtime_resume(dev_name(dev), ret,
9804 ktime_to_us(ktime_sub(ktime_get(), start)),
9805 hba->curr_dev_pwr_mode, hba->uic_link_state);
9811 #ifdef CONFIG_PM_SLEEP
9812 static int ufshcd_wl_suspend(struct device *dev)
9814 struct scsi_device *sdev = to_scsi_device(dev);
9815 struct ufs_hba *hba;
9817 ktime_t start = ktime_get();
9819 hba = shost_priv(sdev->host);
9820 down(&hba->host_sem);
9821 hba->system_suspending = true;
9823 if (pm_runtime_suspended(dev))
9826 ret = __ufshcd_wl_suspend(hba, UFS_SYSTEM_PM);
9828 dev_err(&sdev->sdev_gendev, "%s failed: %d\n", __func__, ret);
9834 hba->is_sys_suspended = true;
9835 trace_ufshcd_wl_suspend(dev_name(dev), ret,
9836 ktime_to_us(ktime_sub(ktime_get(), start)),
9837 hba->curr_dev_pwr_mode, hba->uic_link_state);
9842 static int ufshcd_wl_resume(struct device *dev)
9844 struct scsi_device *sdev = to_scsi_device(dev);
9845 struct ufs_hba *hba;
9847 ktime_t start = ktime_get();
9849 hba = shost_priv(sdev->host);
9851 if (pm_runtime_suspended(dev))
9854 ret = __ufshcd_wl_resume(hba, UFS_SYSTEM_PM);
9856 dev_err(&sdev->sdev_gendev, "%s failed: %d\n", __func__, ret);
9858 trace_ufshcd_wl_resume(dev_name(dev), ret,
9859 ktime_to_us(ktime_sub(ktime_get(), start)),
9860 hba->curr_dev_pwr_mode, hba->uic_link_state);
9862 hba->is_sys_suspended = false;
9863 hba->system_suspending = false;
9870 * ufshcd_suspend - helper function for suspend operations
9871 * @hba: per adapter instance
9873 * This function will put disable irqs, turn off clocks
9874 * and set vreg and hba-vreg in lpm mode.
9876 * Return: 0 upon success; < 0 upon failure.
9878 static int ufshcd_suspend(struct ufs_hba *hba)
9882 if (!hba->is_powered)
9885 * Disable the host irq as host controller as there won't be any
9886 * host controller transaction expected till resume.
9888 ufshcd_disable_irq(hba);
9889 ret = ufshcd_setup_clocks(hba, false);
9891 ufshcd_enable_irq(hba);
9894 if (ufshcd_is_clkgating_allowed(hba)) {
9895 hba->clk_gating.state = CLKS_OFF;
9896 trace_ufshcd_clk_gating(dev_name(hba->dev),
9897 hba->clk_gating.state);
9900 ufshcd_vreg_set_lpm(hba);
9901 /* Put the host controller in low power mode if possible */
9902 ufshcd_hba_vreg_set_lpm(hba);
9908 * ufshcd_resume - helper function for resume operations
9909 * @hba: per adapter instance
9911 * This function basically turns on the regulators, clocks and
9914 * Return: 0 for success and non-zero for failure.
9916 static int ufshcd_resume(struct ufs_hba *hba)
9920 if (!hba->is_powered)
9923 ufshcd_hba_vreg_set_hpm(hba);
9924 ret = ufshcd_vreg_set_hpm(hba);
9928 /* Make sure clocks are enabled before accessing controller */
9929 ret = ufshcd_setup_clocks(hba, true);
9933 /* enable the host irq as host controller would be active soon */
9934 ufshcd_enable_irq(hba);
9939 ufshcd_vreg_set_lpm(hba);
9942 ufshcd_update_evt_hist(hba, UFS_EVT_RESUME_ERR, (u32)ret);
9945 #endif /* CONFIG_PM */
9947 #ifdef CONFIG_PM_SLEEP
9949 * ufshcd_system_suspend - system suspend callback
9950 * @dev: Device associated with the UFS controller.
9952 * Executed before putting the system into a sleep state in which the contents
9953 * of main memory are preserved.
9955 * Return: 0 for success and non-zero for failure.
9957 int ufshcd_system_suspend(struct device *dev)
9959 struct ufs_hba *hba = dev_get_drvdata(dev);
9961 ktime_t start = ktime_get();
9963 if (pm_runtime_suspended(hba->dev))
9966 ret = ufshcd_suspend(hba);
9968 trace_ufshcd_system_suspend(dev_name(hba->dev), ret,
9969 ktime_to_us(ktime_sub(ktime_get(), start)),
9970 hba->curr_dev_pwr_mode, hba->uic_link_state);
9973 EXPORT_SYMBOL(ufshcd_system_suspend);
9976 * ufshcd_system_resume - system resume callback
9977 * @dev: Device associated with the UFS controller.
9979 * Executed after waking the system up from a sleep state in which the contents
9980 * of main memory were preserved.
9982 * Return: 0 for success and non-zero for failure.
9984 int ufshcd_system_resume(struct device *dev)
9986 struct ufs_hba *hba = dev_get_drvdata(dev);
9987 ktime_t start = ktime_get();
9990 if (pm_runtime_suspended(hba->dev))
9993 ret = ufshcd_resume(hba);
9996 trace_ufshcd_system_resume(dev_name(hba->dev), ret,
9997 ktime_to_us(ktime_sub(ktime_get(), start)),
9998 hba->curr_dev_pwr_mode, hba->uic_link_state);
10002 EXPORT_SYMBOL(ufshcd_system_resume);
10003 #endif /* CONFIG_PM_SLEEP */
10007 * ufshcd_runtime_suspend - runtime suspend callback
10008 * @dev: Device associated with the UFS controller.
10010 * Check the description of ufshcd_suspend() function for more details.
10012 * Return: 0 for success and non-zero for failure.
10014 int ufshcd_runtime_suspend(struct device *dev)
10016 struct ufs_hba *hba = dev_get_drvdata(dev);
10018 ktime_t start = ktime_get();
10020 ret = ufshcd_suspend(hba);
10022 trace_ufshcd_runtime_suspend(dev_name(hba->dev), ret,
10023 ktime_to_us(ktime_sub(ktime_get(), start)),
10024 hba->curr_dev_pwr_mode, hba->uic_link_state);
10027 EXPORT_SYMBOL(ufshcd_runtime_suspend);
10030 * ufshcd_runtime_resume - runtime resume routine
10031 * @dev: Device associated with the UFS controller.
10033 * This function basically brings controller
10034 * to active state. Following operations are done in this function:
10036 * 1. Turn on all the controller related clocks
10037 * 2. Turn ON VCC rail
10039 * Return: 0 upon success; < 0 upon failure.
10041 int ufshcd_runtime_resume(struct device *dev)
10043 struct ufs_hba *hba = dev_get_drvdata(dev);
10045 ktime_t start = ktime_get();
10047 ret = ufshcd_resume(hba);
10049 trace_ufshcd_runtime_resume(dev_name(hba->dev), ret,
10050 ktime_to_us(ktime_sub(ktime_get(), start)),
10051 hba->curr_dev_pwr_mode, hba->uic_link_state);
10054 EXPORT_SYMBOL(ufshcd_runtime_resume);
10055 #endif /* CONFIG_PM */
10057 static void ufshcd_wl_shutdown(struct device *dev)
10059 struct scsi_device *sdev = to_scsi_device(dev);
10060 struct ufs_hba *hba = shost_priv(sdev->host);
10062 down(&hba->host_sem);
10063 hba->shutting_down = true;
10064 up(&hba->host_sem);
10066 /* Turn on everything while shutting down */
10067 ufshcd_rpm_get_sync(hba);
10068 scsi_device_quiesce(sdev);
10069 shost_for_each_device(sdev, hba->host) {
10070 if (sdev == hba->ufs_device_wlun)
10072 scsi_device_quiesce(sdev);
10074 __ufshcd_wl_suspend(hba, UFS_SHUTDOWN_PM);
10077 * Next, turn off the UFS controller and the UFS regulators. Disable
10080 if (ufshcd_is_ufs_dev_poweroff(hba) && ufshcd_is_link_off(hba))
10081 ufshcd_suspend(hba);
10083 hba->is_powered = false;
10087 * ufshcd_remove - de-allocate SCSI host and host memory space
10088 * data structure memory
10089 * @hba: per adapter instance
10091 void ufshcd_remove(struct ufs_hba *hba)
10093 if (hba->ufs_device_wlun)
10094 ufshcd_rpm_get_sync(hba);
10095 ufs_hwmon_remove(hba);
10096 ufs_bsg_remove(hba);
10097 ufs_sysfs_remove_nodes(hba->dev);
10098 blk_mq_destroy_queue(hba->tmf_queue);
10099 blk_put_queue(hba->tmf_queue);
10100 blk_mq_free_tag_set(&hba->tmf_tag_set);
10101 scsi_remove_host(hba->host);
10102 /* disable interrupts */
10103 ufshcd_disable_intr(hba, hba->intr_mask);
10104 ufshcd_hba_stop(hba);
10105 ufshcd_hba_exit(hba);
10107 EXPORT_SYMBOL_GPL(ufshcd_remove);
10109 #ifdef CONFIG_PM_SLEEP
10110 int ufshcd_system_freeze(struct device *dev)
10113 return ufshcd_system_suspend(dev);
10116 EXPORT_SYMBOL_GPL(ufshcd_system_freeze);
10118 int ufshcd_system_restore(struct device *dev)
10121 struct ufs_hba *hba = dev_get_drvdata(dev);
10124 ret = ufshcd_system_resume(dev);
10128 /* Configure UTRL and UTMRL base address registers */
10129 ufshcd_writel(hba, lower_32_bits(hba->utrdl_dma_addr),
10130 REG_UTP_TRANSFER_REQ_LIST_BASE_L);
10131 ufshcd_writel(hba, upper_32_bits(hba->utrdl_dma_addr),
10132 REG_UTP_TRANSFER_REQ_LIST_BASE_H);
10133 ufshcd_writel(hba, lower_32_bits(hba->utmrdl_dma_addr),
10134 REG_UTP_TASK_REQ_LIST_BASE_L);
10135 ufshcd_writel(hba, upper_32_bits(hba->utmrdl_dma_addr),
10136 REG_UTP_TASK_REQ_LIST_BASE_H);
10138 * Make sure that UTRL and UTMRL base address registers
10139 * are updated with the latest queue addresses. Only after
10140 * updating these addresses, we can queue the new commands.
10144 /* Resuming from hibernate, assume that link was OFF */
10145 ufshcd_set_link_off(hba);
10150 EXPORT_SYMBOL_GPL(ufshcd_system_restore);
10152 int ufshcd_system_thaw(struct device *dev)
10154 return ufshcd_system_resume(dev);
10156 EXPORT_SYMBOL_GPL(ufshcd_system_thaw);
10157 #endif /* CONFIG_PM_SLEEP */
10160 * ufshcd_dealloc_host - deallocate Host Bus Adapter (HBA)
10161 * @hba: pointer to Host Bus Adapter (HBA)
10163 void ufshcd_dealloc_host(struct ufs_hba *hba)
10165 scsi_host_put(hba->host);
10167 EXPORT_SYMBOL_GPL(ufshcd_dealloc_host);
10170 * ufshcd_set_dma_mask - Set dma mask based on the controller
10171 * addressing capability
10172 * @hba: per adapter instance
10174 * Return: 0 for success, non-zero for failure.
10176 static int ufshcd_set_dma_mask(struct ufs_hba *hba)
10178 if (hba->capabilities & MASK_64_ADDRESSING_SUPPORT) {
10179 if (!dma_set_mask_and_coherent(hba->dev, DMA_BIT_MASK(64)))
10182 return dma_set_mask_and_coherent(hba->dev, DMA_BIT_MASK(32));
10186 * ufshcd_alloc_host - allocate Host Bus Adapter (HBA)
10187 * @dev: pointer to device handle
10188 * @hba_handle: driver private handle
10190 * Return: 0 on success, non-zero value on failure.
10192 int ufshcd_alloc_host(struct device *dev, struct ufs_hba **hba_handle)
10194 struct Scsi_Host *host;
10195 struct ufs_hba *hba;
10200 "Invalid memory reference for dev is NULL\n");
10205 host = scsi_host_alloc(&ufshcd_driver_template,
10206 sizeof(struct ufs_hba));
10208 dev_err(dev, "scsi_host_alloc failed\n");
10212 host->nr_maps = HCTX_TYPE_POLL + 1;
10213 hba = shost_priv(host);
10216 hba->dev_ref_clk_freq = REF_CLK_FREQ_INVAL;
10217 hba->nop_out_timeout = NOP_OUT_TIMEOUT;
10218 ufshcd_set_sg_entry_size(hba, sizeof(struct ufshcd_sg_entry));
10219 INIT_LIST_HEAD(&hba->clk_list_head);
10220 spin_lock_init(&hba->outstanding_lock);
10227 EXPORT_SYMBOL(ufshcd_alloc_host);
10229 /* This function exists because blk_mq_alloc_tag_set() requires this. */
10230 static blk_status_t ufshcd_queue_tmf(struct blk_mq_hw_ctx *hctx,
10231 const struct blk_mq_queue_data *qd)
10233 WARN_ON_ONCE(true);
10234 return BLK_STS_NOTSUPP;
10237 static const struct blk_mq_ops ufshcd_tmf_ops = {
10238 .queue_rq = ufshcd_queue_tmf,
10242 * ufshcd_init - Driver initialization routine
10243 * @hba: per-adapter instance
10244 * @mmio_base: base register address
10245 * @irq: Interrupt line of device
10247 * Return: 0 on success, non-zero value on failure.
10249 int ufshcd_init(struct ufs_hba *hba, void __iomem *mmio_base, unsigned int irq)
10252 struct Scsi_Host *host = hba->host;
10253 struct device *dev = hba->dev;
10254 char eh_wq_name[sizeof("ufs_eh_wq_00")];
10257 * dev_set_drvdata() must be called before any callbacks are registered
10258 * that use dev_get_drvdata() (frequency scaling, clock scaling, hwmon,
10261 dev_set_drvdata(dev, hba);
10265 "Invalid memory reference for mmio_base is NULL\n");
10270 hba->mmio_base = mmio_base;
10272 hba->vps = &ufs_hba_vps;
10274 err = ufshcd_hba_init(hba);
10278 /* Read capabilities registers */
10279 err = ufshcd_hba_capabilities(hba);
10283 /* Get UFS version supported by the controller */
10284 hba->ufs_version = ufshcd_get_ufs_version(hba);
10286 /* Get Interrupt bit mask per version */
10287 hba->intr_mask = ufshcd_get_intr_mask(hba);
10289 err = ufshcd_set_dma_mask(hba);
10291 dev_err(hba->dev, "set dma mask failed\n");
10295 /* Allocate memory for host memory space */
10296 err = ufshcd_memory_alloc(hba);
10298 dev_err(hba->dev, "Memory allocation failed\n");
10302 /* Configure LRB */
10303 ufshcd_host_memory_configure(hba);
10305 host->can_queue = hba->nutrs - UFSHCD_NUM_RESERVED;
10306 host->cmd_per_lun = hba->nutrs - UFSHCD_NUM_RESERVED;
10307 host->max_id = UFSHCD_MAX_ID;
10308 host->max_lun = UFS_MAX_LUNS;
10309 host->max_channel = UFSHCD_MAX_CHANNEL;
10310 host->unique_id = host->host_no;
10311 host->max_cmd_len = UFS_CDB_SIZE;
10312 host->queuecommand_may_block = !!(hba->caps & UFSHCD_CAP_CLK_GATING);
10314 hba->max_pwr_info.is_valid = false;
10316 /* Initialize work queues */
10317 snprintf(eh_wq_name, sizeof(eh_wq_name), "ufs_eh_wq_%d",
10318 hba->host->host_no);
10319 hba->eh_wq = create_singlethread_workqueue(eh_wq_name);
10321 dev_err(hba->dev, "%s: failed to create eh workqueue\n",
10326 INIT_WORK(&hba->eh_work, ufshcd_err_handler);
10327 INIT_WORK(&hba->eeh_work, ufshcd_exception_event_handler);
10329 sema_init(&hba->host_sem, 1);
10331 /* Initialize UIC command mutex */
10332 mutex_init(&hba->uic_cmd_mutex);
10334 /* Initialize mutex for device management commands */
10335 mutex_init(&hba->dev_cmd.lock);
10337 /* Initialize mutex for exception event control */
10338 mutex_init(&hba->ee_ctrl_mutex);
10340 mutex_init(&hba->wb_mutex);
10341 init_rwsem(&hba->clk_scaling_lock);
10343 ufshcd_init_clk_gating(hba);
10345 ufshcd_init_clk_scaling(hba);
10348 * In order to avoid any spurious interrupt immediately after
10349 * registering UFS controller interrupt handler, clear any pending UFS
10350 * interrupt status and disable all the UFS interrupts.
10352 ufshcd_writel(hba, ufshcd_readl(hba, REG_INTERRUPT_STATUS),
10353 REG_INTERRUPT_STATUS);
10354 ufshcd_writel(hba, 0, REG_INTERRUPT_ENABLE);
10356 * Make sure that UFS interrupts are disabled and any pending interrupt
10357 * status is cleared before registering UFS interrupt handler.
10361 /* IRQ registration */
10362 err = devm_request_irq(dev, irq, ufshcd_intr, IRQF_SHARED, UFSHCD, hba);
10364 dev_err(hba->dev, "request irq failed\n");
10367 hba->is_irq_enabled = true;
10370 if (!is_mcq_supported(hba)) {
10371 err = scsi_add_host(host, hba->dev);
10373 dev_err(hba->dev, "scsi_add_host failed\n");
10378 hba->tmf_tag_set = (struct blk_mq_tag_set) {
10380 .queue_depth = hba->nutmrs,
10381 .ops = &ufshcd_tmf_ops,
10382 .flags = BLK_MQ_F_NO_SCHED,
10384 err = blk_mq_alloc_tag_set(&hba->tmf_tag_set);
10386 goto out_remove_scsi_host;
10387 hba->tmf_queue = blk_mq_init_queue(&hba->tmf_tag_set);
10388 if (IS_ERR(hba->tmf_queue)) {
10389 err = PTR_ERR(hba->tmf_queue);
10390 goto free_tmf_tag_set;
10392 hba->tmf_rqs = devm_kcalloc(hba->dev, hba->nutmrs,
10393 sizeof(*hba->tmf_rqs), GFP_KERNEL);
10394 if (!hba->tmf_rqs) {
10396 goto free_tmf_queue;
10399 /* Reset the attached device */
10400 ufshcd_device_reset(hba);
10402 ufshcd_init_crypto(hba);
10404 /* Host controller enable */
10405 err = ufshcd_hba_enable(hba);
10407 dev_err(hba->dev, "Host controller enable failed\n");
10408 ufshcd_print_evt_hist(hba);
10409 ufshcd_print_host_state(hba);
10410 goto free_tmf_queue;
10414 * Set the default power management level for runtime and system PM.
10415 * Default power saving mode is to keep UFS link in Hibern8 state
10416 * and UFS device in sleep state.
10418 hba->rpm_lvl = ufs_get_desired_pm_lvl_for_dev_link_state(
10419 UFS_SLEEP_PWR_MODE,
10420 UIC_LINK_HIBERN8_STATE);
10421 hba->spm_lvl = ufs_get_desired_pm_lvl_for_dev_link_state(
10422 UFS_SLEEP_PWR_MODE,
10423 UIC_LINK_HIBERN8_STATE);
10425 INIT_DELAYED_WORK(&hba->rpm_dev_flush_recheck_work,
10426 ufshcd_rpm_dev_flush_recheck_work);
10428 /* Set the default auto-hiberate idle timer value to 150 ms */
10429 if (ufshcd_is_auto_hibern8_supported(hba) && !hba->ahit) {
10430 hba->ahit = FIELD_PREP(UFSHCI_AHIBERN8_TIMER_MASK, 150) |
10431 FIELD_PREP(UFSHCI_AHIBERN8_SCALE_MASK, 3);
10434 /* Hold auto suspend until async scan completes */
10435 pm_runtime_get_sync(dev);
10436 atomic_set(&hba->scsi_block_reqs_cnt, 0);
10438 * We are assuming that device wasn't put in sleep/power-down
10439 * state exclusively during the boot stage before kernel.
10440 * This assumption helps avoid doing link startup twice during
10441 * ufshcd_probe_hba().
10443 ufshcd_set_ufs_dev_active(hba);
10445 async_schedule(ufshcd_async_scan, hba);
10446 ufs_sysfs_add_nodes(hba->dev);
10448 device_enable_async_suspend(dev);
10452 blk_mq_destroy_queue(hba->tmf_queue);
10453 blk_put_queue(hba->tmf_queue);
10455 blk_mq_free_tag_set(&hba->tmf_tag_set);
10456 out_remove_scsi_host:
10457 scsi_remove_host(hba->host);
10459 hba->is_irq_enabled = false;
10460 ufshcd_hba_exit(hba);
10464 EXPORT_SYMBOL_GPL(ufshcd_init);
10466 void ufshcd_resume_complete(struct device *dev)
10468 struct ufs_hba *hba = dev_get_drvdata(dev);
10470 if (hba->complete_put) {
10471 ufshcd_rpm_put(hba);
10472 hba->complete_put = false;
10475 EXPORT_SYMBOL_GPL(ufshcd_resume_complete);
10477 static bool ufshcd_rpm_ok_for_spm(struct ufs_hba *hba)
10479 struct device *dev = &hba->ufs_device_wlun->sdev_gendev;
10480 enum ufs_dev_pwr_mode dev_pwr_mode;
10481 enum uic_link_state link_state;
10482 unsigned long flags;
10485 spin_lock_irqsave(&dev->power.lock, flags);
10486 dev_pwr_mode = ufs_get_pm_lvl_to_dev_pwr_mode(hba->spm_lvl);
10487 link_state = ufs_get_pm_lvl_to_link_pwr_state(hba->spm_lvl);
10488 res = pm_runtime_suspended(dev) &&
10489 hba->curr_dev_pwr_mode == dev_pwr_mode &&
10490 hba->uic_link_state == link_state &&
10491 !hba->dev_info.b_rpm_dev_flush_capable;
10492 spin_unlock_irqrestore(&dev->power.lock, flags);
10497 int __ufshcd_suspend_prepare(struct device *dev, bool rpm_ok_for_spm)
10499 struct ufs_hba *hba = dev_get_drvdata(dev);
10503 * SCSI assumes that runtime-pm and system-pm for scsi drivers
10504 * are same. And it doesn't wake up the device for system-suspend
10505 * if it's runtime suspended. But ufs doesn't follow that.
10506 * Refer ufshcd_resume_complete()
10508 if (hba->ufs_device_wlun) {
10509 /* Prevent runtime suspend */
10510 ufshcd_rpm_get_noresume(hba);
10512 * Check if already runtime suspended in same state as system
10513 * suspend would be.
10515 if (!rpm_ok_for_spm || !ufshcd_rpm_ok_for_spm(hba)) {
10516 /* RPM state is not ok for SPM, so runtime resume */
10517 ret = ufshcd_rpm_resume(hba);
10518 if (ret < 0 && ret != -EACCES) {
10519 ufshcd_rpm_put(hba);
10523 hba->complete_put = true;
10527 EXPORT_SYMBOL_GPL(__ufshcd_suspend_prepare);
10529 int ufshcd_suspend_prepare(struct device *dev)
10531 return __ufshcd_suspend_prepare(dev, true);
10533 EXPORT_SYMBOL_GPL(ufshcd_suspend_prepare);
10535 #ifdef CONFIG_PM_SLEEP
10536 static int ufshcd_wl_poweroff(struct device *dev)
10538 struct scsi_device *sdev = to_scsi_device(dev);
10539 struct ufs_hba *hba = shost_priv(sdev->host);
10541 __ufshcd_wl_suspend(hba, UFS_SHUTDOWN_PM);
10546 static int ufshcd_wl_probe(struct device *dev)
10548 struct scsi_device *sdev = to_scsi_device(dev);
10550 if (!is_device_wlun(sdev))
10553 blk_pm_runtime_init(sdev->request_queue, dev);
10554 pm_runtime_set_autosuspend_delay(dev, 0);
10555 pm_runtime_allow(dev);
10560 static int ufshcd_wl_remove(struct device *dev)
10562 pm_runtime_forbid(dev);
10566 static const struct dev_pm_ops ufshcd_wl_pm_ops = {
10567 #ifdef CONFIG_PM_SLEEP
10568 .suspend = ufshcd_wl_suspend,
10569 .resume = ufshcd_wl_resume,
10570 .freeze = ufshcd_wl_suspend,
10571 .thaw = ufshcd_wl_resume,
10572 .poweroff = ufshcd_wl_poweroff,
10573 .restore = ufshcd_wl_resume,
10575 SET_RUNTIME_PM_OPS(ufshcd_wl_runtime_suspend, ufshcd_wl_runtime_resume, NULL)
10578 static void ufshcd_check_header_layout(void)
10581 * gcc compilers before version 10 cannot do constant-folding for
10582 * sub-byte bitfields. Hence skip the layout checks for gcc 9 and
10585 if (IS_ENABLED(CONFIG_CC_IS_GCC) && CONFIG_GCC_VERSION < 100000)
10588 BUILD_BUG_ON(((u8 *)&(struct request_desc_header){
10589 .cci = 3})[0] != 3);
10591 BUILD_BUG_ON(((u8 *)&(struct request_desc_header){
10592 .ehs_length = 2})[1] != 2);
10594 BUILD_BUG_ON(((u8 *)&(struct request_desc_header){
10595 .enable_crypto = 1})[2]
10598 BUILD_BUG_ON((((u8 *)&(struct request_desc_header){
10600 .data_direction = 3,
10602 })[3]) != ((5 << 4) | (3 << 1) | 1));
10604 BUILD_BUG_ON(((__le32 *)&(struct request_desc_header){
10605 .dunl = cpu_to_le32(0xdeadbeef)})[1] !=
10606 cpu_to_le32(0xdeadbeef));
10608 BUILD_BUG_ON(((u8 *)&(struct request_desc_header){
10609 .ocs = 4})[8] != 4);
10611 BUILD_BUG_ON(((u8 *)&(struct request_desc_header){
10612 .cds = 5})[9] != 5);
10614 BUILD_BUG_ON(((__le32 *)&(struct request_desc_header){
10615 .dunu = cpu_to_le32(0xbadcafe)})[3] !=
10616 cpu_to_le32(0xbadcafe));
10618 BUILD_BUG_ON(((u8 *)&(struct utp_upiu_header){
10619 .iid = 0xf })[4] != 0xf0);
10621 BUILD_BUG_ON(((u8 *)&(struct utp_upiu_header){
10622 .command_set_type = 0xf })[4] != 0xf);
10626 * ufs_dev_wlun_template - describes ufs device wlun
10627 * ufs-device wlun - used to send pm commands
10628 * All luns are consumers of ufs-device wlun.
10630 * Currently, no sd driver is present for wluns.
10631 * Hence the no specific pm operations are performed.
10632 * With ufs design, SSU should be sent to ufs-device wlun.
10633 * Hence register a scsi driver for ufs wluns only.
10635 static struct scsi_driver ufs_dev_wlun_template = {
10637 .name = "ufs_device_wlun",
10638 .owner = THIS_MODULE,
10639 .probe = ufshcd_wl_probe,
10640 .remove = ufshcd_wl_remove,
10641 .pm = &ufshcd_wl_pm_ops,
10642 .shutdown = ufshcd_wl_shutdown,
10646 static int __init ufshcd_core_init(void)
10650 ufshcd_check_header_layout();
10652 ufs_debugfs_init();
10654 ret = scsi_register_driver(&ufs_dev_wlun_template.gendrv);
10656 ufs_debugfs_exit();
10660 static void __exit ufshcd_core_exit(void)
10662 ufs_debugfs_exit();
10663 scsi_unregister_driver(&ufs_dev_wlun_template.gendrv);
10666 module_init(ufshcd_core_init);
10667 module_exit(ufshcd_core_exit);
10669 MODULE_AUTHOR("Santosh Yaragnavi <santosh.sy@samsung.com>");
10670 MODULE_AUTHOR("Vinayak Holikatti <h.vinayak@samsung.com>");
10671 MODULE_DESCRIPTION("Generic UFS host controller driver Core");
10672 MODULE_SOFTDEP("pre: governor_simpleondemand");
10673 MODULE_LICENSE("GPL");