1 // SPDX-License-Identifier: GPL-2.0-or-later
3 * Universal Flash Storage Host controller driver Core
4 * Copyright (C) 2011-2013 Samsung India Software Operations
5 * Copyright (c) 2013-2016, The Linux Foundation. All rights reserved.
8 * Santosh Yaraganavi <santosh.sy@samsung.com>
9 * Vinayak Holikatti <h.vinayak@samsung.com>
12 #include <linux/async.h>
13 #include <linux/devfreq.h>
14 #include <linux/nls.h>
16 #include <linux/bitfield.h>
17 #include <linux/blk-pm.h>
18 #include <linux/blkdev.h>
19 #include <linux/clk.h>
20 #include <linux/delay.h>
21 #include <linux/interrupt.h>
22 #include <linux/module.h>
23 #include <linux/regulator/consumer.h>
24 #include <linux/sched/clock.h>
25 #include <scsi/scsi_cmnd.h>
26 #include <scsi/scsi_dbg.h>
27 #include <scsi/scsi_driver.h>
28 #include <scsi/scsi_eh.h>
29 #include "ufshcd-priv.h"
30 #include <ufs/ufs_quirks.h>
31 #include <ufs/unipro.h>
32 #include "ufs-sysfs.h"
33 #include "ufs-debugfs.h"
34 #include "ufs-fault-injection.h"
36 #include "ufshcd-crypto.h"
38 #include <asm/unaligned.h>
40 #define CREATE_TRACE_POINTS
41 #include <trace/events/ufs.h>
43 #define UFSHCD_ENABLE_INTRS (UTP_TRANSFER_REQ_COMPL |\
47 #define UFSHCD_ENABLE_MCQ_INTRS (UTP_TASK_REQ_COMPL |\
52 /* UIC command timeout, unit: ms */
53 #define UIC_CMD_TIMEOUT 500
55 /* NOP OUT retries waiting for NOP IN response */
56 #define NOP_OUT_RETRIES 10
57 /* Timeout after 50 msecs if NOP OUT hangs without response */
58 #define NOP_OUT_TIMEOUT 50 /* msecs */
60 /* Query request retries */
61 #define QUERY_REQ_RETRIES 3
62 /* Query request timeout */
63 #define QUERY_REQ_TIMEOUT 1500 /* 1.5 seconds */
65 /* Advanced RPMB request timeout */
66 #define ADVANCED_RPMB_REQ_TIMEOUT 3000 /* 3 seconds */
68 /* Task management command timeout */
69 #define TM_CMD_TIMEOUT 100 /* msecs */
71 /* maximum number of retries for a general UIC command */
72 #define UFS_UIC_COMMAND_RETRIES 3
74 /* maximum number of link-startup retries */
75 #define DME_LINKSTARTUP_RETRIES 3
77 /* maximum number of reset retries before giving up */
78 #define MAX_HOST_RESET_RETRIES 5
80 /* Maximum number of error handler retries before giving up */
81 #define MAX_ERR_HANDLER_RETRIES 5
83 /* Expose the flag value from utp_upiu_query.value */
84 #define MASK_QUERY_UPIU_FLAG_LOC 0xFF
86 /* Interrupt aggregation default timeout, unit: 40us */
87 #define INT_AGGR_DEF_TO 0x02
89 /* default delay of autosuspend: 2000 ms */
90 #define RPM_AUTOSUSPEND_DELAY_MS 2000
92 /* Default delay of RPM device flush delayed work */
93 #define RPM_DEV_FLUSH_RECHECK_WORK_DELAY_MS 5000
95 /* Default value of wait time before gating device ref clock */
96 #define UFSHCD_REF_CLK_GATING_WAIT_US 0xFF /* microsecs */
98 /* Polling time to wait for fDeviceInit */
99 #define FDEVICEINIT_COMPL_TIMEOUT 1500 /* millisecs */
101 /* UFSHC 4.0 compliant HC support this mode. */
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 UFS_DEVICE_QUIRK_SWAP_L2P_ENTRY_FOR_HPB_READ },
243 { .wmanufacturerid = UFS_VENDOR_SAMSUNG,
244 .model = UFS_ANY_MODEL,
245 .quirk = UFS_DEVICE_QUIRK_DELAY_BEFORE_LPM |
246 UFS_DEVICE_QUIRK_HOST_PA_TACTIVATE |
247 UFS_DEVICE_QUIRK_RECOVERY_FROM_DL_NAC_ERRORS },
248 { .wmanufacturerid = UFS_VENDOR_SKHYNIX,
249 .model = UFS_ANY_MODEL,
250 .quirk = UFS_DEVICE_QUIRK_HOST_PA_SAVECONFIGTIME },
251 { .wmanufacturerid = UFS_VENDOR_SKHYNIX,
252 .model = "hB8aL1" /*H28U62301AMR*/,
253 .quirk = UFS_DEVICE_QUIRK_HOST_VS_DEBUGSAVECONFIGTIME },
254 { .wmanufacturerid = UFS_VENDOR_TOSHIBA,
255 .model = UFS_ANY_MODEL,
256 .quirk = UFS_DEVICE_QUIRK_DELAY_BEFORE_LPM },
257 { .wmanufacturerid = UFS_VENDOR_TOSHIBA,
258 .model = "THGLF2G9C8KBADG",
259 .quirk = UFS_DEVICE_QUIRK_PA_TACTIVATE },
260 { .wmanufacturerid = UFS_VENDOR_TOSHIBA,
261 .model = "THGLF2G9D8KBADG",
262 .quirk = UFS_DEVICE_QUIRK_PA_TACTIVATE },
266 static irqreturn_t ufshcd_tmc_handler(struct ufs_hba *hba);
267 static void ufshcd_async_scan(void *data, async_cookie_t cookie);
268 static int ufshcd_reset_and_restore(struct ufs_hba *hba);
269 static int ufshcd_eh_host_reset_handler(struct scsi_cmnd *cmd);
270 static int ufshcd_clear_tm_cmd(struct ufs_hba *hba, int tag);
271 static void ufshcd_hba_exit(struct ufs_hba *hba);
272 static int ufshcd_probe_hba(struct ufs_hba *hba, bool init_dev_params);
273 static int ufshcd_setup_clocks(struct ufs_hba *hba, bool on);
274 static inline void ufshcd_add_delay_before_dme_cmd(struct ufs_hba *hba);
275 static int ufshcd_host_reset_and_restore(struct ufs_hba *hba);
276 static void ufshcd_resume_clkscaling(struct ufs_hba *hba);
277 static void ufshcd_suspend_clkscaling(struct ufs_hba *hba);
278 static void __ufshcd_suspend_clkscaling(struct ufs_hba *hba);
279 static int ufshcd_scale_clks(struct ufs_hba *hba, bool scale_up);
280 static irqreturn_t ufshcd_intr(int irq, void *__hba);
281 static int ufshcd_change_power_mode(struct ufs_hba *hba,
282 struct ufs_pa_layer_attr *pwr_mode);
283 static int ufshcd_setup_hba_vreg(struct ufs_hba *hba, bool on);
284 static int ufshcd_setup_vreg(struct ufs_hba *hba, bool on);
285 static inline int ufshcd_config_vreg_hpm(struct ufs_hba *hba,
286 struct ufs_vreg *vreg);
287 static void ufshcd_wb_toggle_buf_flush_during_h8(struct ufs_hba *hba,
289 static void ufshcd_hba_vreg_set_lpm(struct ufs_hba *hba);
290 static void ufshcd_hba_vreg_set_hpm(struct ufs_hba *hba);
292 static inline void ufshcd_enable_irq(struct ufs_hba *hba)
294 if (!hba->is_irq_enabled) {
295 enable_irq(hba->irq);
296 hba->is_irq_enabled = true;
300 static inline void ufshcd_disable_irq(struct ufs_hba *hba)
302 if (hba->is_irq_enabled) {
303 disable_irq(hba->irq);
304 hba->is_irq_enabled = false;
308 static void ufshcd_configure_wb(struct ufs_hba *hba)
310 if (!ufshcd_is_wb_allowed(hba))
313 ufshcd_wb_toggle(hba, true);
315 ufshcd_wb_toggle_buf_flush_during_h8(hba, true);
317 if (ufshcd_is_wb_buf_flush_allowed(hba))
318 ufshcd_wb_toggle_buf_flush(hba, true);
321 static void ufshcd_scsi_unblock_requests(struct ufs_hba *hba)
323 if (atomic_dec_and_test(&hba->scsi_block_reqs_cnt))
324 scsi_unblock_requests(hba->host);
327 static void ufshcd_scsi_block_requests(struct ufs_hba *hba)
329 if (atomic_inc_return(&hba->scsi_block_reqs_cnt) == 1)
330 scsi_block_requests(hba->host);
333 static void ufshcd_add_cmd_upiu_trace(struct ufs_hba *hba, unsigned int tag,
334 enum ufs_trace_str_t str_t)
336 struct utp_upiu_req *rq = hba->lrb[tag].ucd_req_ptr;
337 struct utp_upiu_header *header;
339 if (!trace_ufshcd_upiu_enabled())
342 if (str_t == UFS_CMD_SEND)
343 header = &rq->header;
345 header = &hba->lrb[tag].ucd_rsp_ptr->header;
347 trace_ufshcd_upiu(dev_name(hba->dev), str_t, header, &rq->sc.cdb,
351 static void ufshcd_add_query_upiu_trace(struct ufs_hba *hba,
352 enum ufs_trace_str_t str_t,
353 struct utp_upiu_req *rq_rsp)
355 if (!trace_ufshcd_upiu_enabled())
358 trace_ufshcd_upiu(dev_name(hba->dev), str_t, &rq_rsp->header,
359 &rq_rsp->qr, UFS_TSF_OSF);
362 static void ufshcd_add_tm_upiu_trace(struct ufs_hba *hba, unsigned int tag,
363 enum ufs_trace_str_t str_t)
365 struct utp_task_req_desc *descp = &hba->utmrdl_base_addr[tag];
367 if (!trace_ufshcd_upiu_enabled())
370 if (str_t == UFS_TM_SEND)
371 trace_ufshcd_upiu(dev_name(hba->dev), str_t,
372 &descp->upiu_req.req_header,
373 &descp->upiu_req.input_param1,
376 trace_ufshcd_upiu(dev_name(hba->dev), str_t,
377 &descp->upiu_rsp.rsp_header,
378 &descp->upiu_rsp.output_param1,
382 static void ufshcd_add_uic_command_trace(struct ufs_hba *hba,
383 const struct uic_command *ucmd,
384 enum ufs_trace_str_t str_t)
388 if (!trace_ufshcd_uic_command_enabled())
391 if (str_t == UFS_CMD_SEND)
394 cmd = ufshcd_readl(hba, REG_UIC_COMMAND);
396 trace_ufshcd_uic_command(dev_name(hba->dev), str_t, cmd,
397 ufshcd_readl(hba, REG_UIC_COMMAND_ARG_1),
398 ufshcd_readl(hba, REG_UIC_COMMAND_ARG_2),
399 ufshcd_readl(hba, REG_UIC_COMMAND_ARG_3));
402 static void ufshcd_add_command_trace(struct ufs_hba *hba, unsigned int tag,
403 enum ufs_trace_str_t str_t)
406 u8 opcode = 0, group_id = 0;
410 struct ufshcd_lrb *lrbp = &hba->lrb[tag];
411 struct scsi_cmnd *cmd = lrbp->cmd;
412 struct request *rq = scsi_cmd_to_rq(cmd);
413 int transfer_len = -1;
418 /* trace UPIU also */
419 ufshcd_add_cmd_upiu_trace(hba, tag, str_t);
420 if (!trace_ufshcd_command_enabled())
423 opcode = cmd->cmnd[0];
425 if (opcode == READ_10 || opcode == WRITE_10) {
427 * Currently we only fully trace read(10) and write(10) commands
430 be32_to_cpu(lrbp->ucd_req_ptr->sc.exp_data_transfer_len);
431 lba = scsi_get_lba(cmd);
432 if (opcode == WRITE_10)
433 group_id = lrbp->cmd->cmnd[6];
434 } else if (opcode == UNMAP) {
436 * The number of Bytes to be unmapped beginning with the lba.
438 transfer_len = blk_rq_bytes(rq);
439 lba = scsi_get_lba(cmd);
442 intr = ufshcd_readl(hba, REG_INTERRUPT_STATUS);
444 if (is_mcq_enabled(hba)) {
445 struct ufs_hw_queue *hwq = ufshcd_mcq_req_to_hwq(hba, rq);
449 doorbell = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
451 trace_ufshcd_command(dev_name(hba->dev), str_t, tag,
452 doorbell, hwq_id, transfer_len, intr, lba, opcode, group_id);
455 static void ufshcd_print_clk_freqs(struct ufs_hba *hba)
457 struct ufs_clk_info *clki;
458 struct list_head *head = &hba->clk_list_head;
460 if (list_empty(head))
463 list_for_each_entry(clki, head, list) {
464 if (!IS_ERR_OR_NULL(clki->clk) && clki->min_freq &&
466 dev_err(hba->dev, "clk: %s, rate: %u\n",
467 clki->name, clki->curr_freq);
471 static void ufshcd_print_evt(struct ufs_hba *hba, u32 id,
472 const char *err_name)
476 const struct ufs_event_hist *e;
478 if (id >= UFS_EVT_CNT)
481 e = &hba->ufs_stats.event[id];
483 for (i = 0; i < UFS_EVENT_HIST_LENGTH; i++) {
484 int p = (i + e->pos) % UFS_EVENT_HIST_LENGTH;
486 if (e->tstamp[p] == 0)
488 dev_err(hba->dev, "%s[%d] = 0x%x at %lld us\n", err_name, p,
489 e->val[p], div_u64(e->tstamp[p], 1000));
494 dev_err(hba->dev, "No record of %s\n", err_name);
496 dev_err(hba->dev, "%s: total cnt=%llu\n", err_name, e->cnt);
499 static void ufshcd_print_evt_hist(struct ufs_hba *hba)
501 ufshcd_dump_regs(hba, 0, UFSHCI_REG_SPACE_SIZE, "host_regs: ");
503 ufshcd_print_evt(hba, UFS_EVT_PA_ERR, "pa_err");
504 ufshcd_print_evt(hba, UFS_EVT_DL_ERR, "dl_err");
505 ufshcd_print_evt(hba, UFS_EVT_NL_ERR, "nl_err");
506 ufshcd_print_evt(hba, UFS_EVT_TL_ERR, "tl_err");
507 ufshcd_print_evt(hba, UFS_EVT_DME_ERR, "dme_err");
508 ufshcd_print_evt(hba, UFS_EVT_AUTO_HIBERN8_ERR,
510 ufshcd_print_evt(hba, UFS_EVT_FATAL_ERR, "fatal_err");
511 ufshcd_print_evt(hba, UFS_EVT_LINK_STARTUP_FAIL,
512 "link_startup_fail");
513 ufshcd_print_evt(hba, UFS_EVT_RESUME_ERR, "resume_fail");
514 ufshcd_print_evt(hba, UFS_EVT_SUSPEND_ERR,
516 ufshcd_print_evt(hba, UFS_EVT_WL_RES_ERR, "wlun resume_fail");
517 ufshcd_print_evt(hba, UFS_EVT_WL_SUSP_ERR,
518 "wlun suspend_fail");
519 ufshcd_print_evt(hba, UFS_EVT_DEV_RESET, "dev_reset");
520 ufshcd_print_evt(hba, UFS_EVT_HOST_RESET, "host_reset");
521 ufshcd_print_evt(hba, UFS_EVT_ABORT, "task_abort");
523 ufshcd_vops_dbg_register_dump(hba);
527 void ufshcd_print_tr(struct ufs_hba *hba, int tag, bool pr_prdt)
529 const struct ufshcd_lrb *lrbp;
532 lrbp = &hba->lrb[tag];
534 dev_err(hba->dev, "UPIU[%d] - issue time %lld us\n",
535 tag, div_u64(lrbp->issue_time_stamp_local_clock, 1000));
536 dev_err(hba->dev, "UPIU[%d] - complete time %lld us\n",
537 tag, div_u64(lrbp->compl_time_stamp_local_clock, 1000));
539 "UPIU[%d] - Transfer Request Descriptor phys@0x%llx\n",
540 tag, (u64)lrbp->utrd_dma_addr);
542 ufshcd_hex_dump("UPIU TRD: ", lrbp->utr_descriptor_ptr,
543 sizeof(struct utp_transfer_req_desc));
544 dev_err(hba->dev, "UPIU[%d] - Request UPIU phys@0x%llx\n", tag,
545 (u64)lrbp->ucd_req_dma_addr);
546 ufshcd_hex_dump("UPIU REQ: ", lrbp->ucd_req_ptr,
547 sizeof(struct utp_upiu_req));
548 dev_err(hba->dev, "UPIU[%d] - Response UPIU phys@0x%llx\n", tag,
549 (u64)lrbp->ucd_rsp_dma_addr);
550 ufshcd_hex_dump("UPIU RSP: ", lrbp->ucd_rsp_ptr,
551 sizeof(struct utp_upiu_rsp));
553 prdt_length = le16_to_cpu(
554 lrbp->utr_descriptor_ptr->prd_table_length);
555 if (hba->quirks & UFSHCD_QUIRK_PRDT_BYTE_GRAN)
556 prdt_length /= ufshcd_sg_entry_size(hba);
559 "UPIU[%d] - PRDT - %d entries phys@0x%llx\n",
561 (u64)lrbp->ucd_prdt_dma_addr);
564 ufshcd_hex_dump("UPIU PRDT: ", lrbp->ucd_prdt_ptr,
565 ufshcd_sg_entry_size(hba) * prdt_length);
568 static bool ufshcd_print_tr_iter(struct request *req, void *priv)
570 struct scsi_device *sdev = req->q->queuedata;
571 struct Scsi_Host *shost = sdev->host;
572 struct ufs_hba *hba = shost_priv(shost);
574 ufshcd_print_tr(hba, req->tag, *(bool *)priv);
580 * ufshcd_print_trs_all - print trs for all started requests.
581 * @hba: per-adapter instance.
582 * @pr_prdt: need to print prdt or not.
584 static void ufshcd_print_trs_all(struct ufs_hba *hba, bool pr_prdt)
586 blk_mq_tagset_busy_iter(&hba->host->tag_set, ufshcd_print_tr_iter, &pr_prdt);
589 static void ufshcd_print_tmrs(struct ufs_hba *hba, unsigned long bitmap)
593 for_each_set_bit(tag, &bitmap, hba->nutmrs) {
594 struct utp_task_req_desc *tmrdp = &hba->utmrdl_base_addr[tag];
596 dev_err(hba->dev, "TM[%d] - Task Management Header\n", tag);
597 ufshcd_hex_dump("", tmrdp, sizeof(*tmrdp));
601 static void ufshcd_print_host_state(struct ufs_hba *hba)
603 const struct scsi_device *sdev_ufs = hba->ufs_device_wlun;
605 dev_err(hba->dev, "UFS Host state=%d\n", hba->ufshcd_state);
606 dev_err(hba->dev, "outstanding reqs=0x%lx tasks=0x%lx\n",
607 hba->outstanding_reqs, hba->outstanding_tasks);
608 dev_err(hba->dev, "saved_err=0x%x, saved_uic_err=0x%x\n",
609 hba->saved_err, hba->saved_uic_err);
610 dev_err(hba->dev, "Device power mode=%d, UIC link state=%d\n",
611 hba->curr_dev_pwr_mode, hba->uic_link_state);
612 dev_err(hba->dev, "PM in progress=%d, sys. suspended=%d\n",
613 hba->pm_op_in_progress, hba->is_sys_suspended);
614 dev_err(hba->dev, "Auto BKOPS=%d, Host self-block=%d\n",
615 hba->auto_bkops_enabled, hba->host->host_self_blocked);
616 dev_err(hba->dev, "Clk gate=%d\n", hba->clk_gating.state);
618 "last_hibern8_exit_tstamp at %lld us, hibern8_exit_cnt=%d\n",
619 div_u64(hba->ufs_stats.last_hibern8_exit_tstamp, 1000),
620 hba->ufs_stats.hibern8_exit_cnt);
621 dev_err(hba->dev, "last intr at %lld us, last intr status=0x%x\n",
622 div_u64(hba->ufs_stats.last_intr_ts, 1000),
623 hba->ufs_stats.last_intr_status);
624 dev_err(hba->dev, "error handling flags=0x%x, req. abort count=%d\n",
625 hba->eh_flags, hba->req_abort_count);
626 dev_err(hba->dev, "hba->ufs_version=0x%x, Host capabilities=0x%x, caps=0x%x\n",
627 hba->ufs_version, hba->capabilities, hba->caps);
628 dev_err(hba->dev, "quirks=0x%x, dev. quirks=0x%x\n", hba->quirks,
631 dev_err(hba->dev, "UFS dev info: %.8s %.16s rev %.4s\n",
632 sdev_ufs->vendor, sdev_ufs->model, sdev_ufs->rev);
634 ufshcd_print_clk_freqs(hba);
638 * ufshcd_print_pwr_info - print power params as saved in hba
640 * @hba: per-adapter instance
642 static void ufshcd_print_pwr_info(struct ufs_hba *hba)
644 static const char * const names[] = {
655 * Using dev_dbg to avoid messages during runtime PM to avoid
656 * never-ending cycles of messages written back to storage by user space
657 * causing runtime resume, causing more messages and so on.
659 dev_dbg(hba->dev, "%s:[RX, TX]: gear=[%d, %d], lane[%d, %d], pwr[%s, %s], rate = %d\n",
661 hba->pwr_info.gear_rx, hba->pwr_info.gear_tx,
662 hba->pwr_info.lane_rx, hba->pwr_info.lane_tx,
663 names[hba->pwr_info.pwr_rx],
664 names[hba->pwr_info.pwr_tx],
665 hba->pwr_info.hs_rate);
668 static void ufshcd_device_reset(struct ufs_hba *hba)
672 err = ufshcd_vops_device_reset(hba);
675 ufshcd_set_ufs_dev_active(hba);
676 if (ufshcd_is_wb_allowed(hba)) {
677 hba->dev_info.wb_enabled = false;
678 hba->dev_info.wb_buf_flush_enabled = false;
681 if (err != -EOPNOTSUPP)
682 ufshcd_update_evt_hist(hba, UFS_EVT_DEV_RESET, err);
685 void ufshcd_delay_us(unsigned long us, unsigned long tolerance)
693 usleep_range(us, us + tolerance);
695 EXPORT_SYMBOL_GPL(ufshcd_delay_us);
698 * ufshcd_wait_for_register - wait for register value to change
699 * @hba: per-adapter interface
700 * @reg: mmio register offset
701 * @mask: mask to apply to the read register value
702 * @val: value to wait for
703 * @interval_us: polling interval in microseconds
704 * @timeout_ms: timeout in milliseconds
707 * -ETIMEDOUT on error, zero on success.
709 static int ufshcd_wait_for_register(struct ufs_hba *hba, u32 reg, u32 mask,
710 u32 val, unsigned long interval_us,
711 unsigned long timeout_ms)
714 unsigned long timeout = jiffies + msecs_to_jiffies(timeout_ms);
716 /* ignore bits that we don't intend to wait on */
719 while ((ufshcd_readl(hba, reg) & mask) != val) {
720 usleep_range(interval_us, interval_us + 50);
721 if (time_after(jiffies, timeout)) {
722 if ((ufshcd_readl(hba, reg) & mask) != val)
732 * ufshcd_get_intr_mask - Get the interrupt bit mask
733 * @hba: Pointer to adapter instance
735 * Returns interrupt bit mask per version
737 static inline u32 ufshcd_get_intr_mask(struct ufs_hba *hba)
739 if (hba->ufs_version == ufshci_version(1, 0))
740 return INTERRUPT_MASK_ALL_VER_10;
741 if (hba->ufs_version <= ufshci_version(2, 0))
742 return INTERRUPT_MASK_ALL_VER_11;
744 return INTERRUPT_MASK_ALL_VER_21;
748 * ufshcd_get_ufs_version - Get the UFS version supported by the HBA
749 * @hba: Pointer to adapter instance
751 * Returns UFSHCI version supported by the controller
753 static inline u32 ufshcd_get_ufs_version(struct ufs_hba *hba)
757 if (hba->quirks & UFSHCD_QUIRK_BROKEN_UFS_HCI_VERSION)
758 ufshci_ver = ufshcd_vops_get_ufs_hci_version(hba);
760 ufshci_ver = ufshcd_readl(hba, REG_UFS_VERSION);
763 * UFSHCI v1.x uses a different version scheme, in order
764 * to allow the use of comparisons with the ufshci_version
765 * function, we convert it to the same scheme as ufs 2.0+.
767 if (ufshci_ver & 0x00010000)
768 return ufshci_version(1, ufshci_ver & 0x00000100);
774 * ufshcd_is_device_present - Check if any device connected to
775 * the host controller
776 * @hba: pointer to adapter instance
778 * Returns true if device present, false if no device detected
780 static inline bool ufshcd_is_device_present(struct ufs_hba *hba)
782 return ufshcd_readl(hba, REG_CONTROLLER_STATUS) & DEVICE_PRESENT;
786 * ufshcd_get_tr_ocs - Get the UTRD Overall Command Status
787 * @lrbp: pointer to local command reference block
788 * @cqe: pointer to the completion queue entry
790 * This function is used to get the OCS field from UTRD
791 * Returns the OCS field in the UTRD
793 static enum utp_ocs ufshcd_get_tr_ocs(struct ufshcd_lrb *lrbp,
794 struct cq_entry *cqe)
797 return le32_to_cpu(cqe->status) & MASK_OCS;
799 return le32_to_cpu(lrbp->utr_descriptor_ptr->header.dword_2) & MASK_OCS;
803 * ufshcd_utrl_clear() - Clear requests from the controller request list.
804 * @hba: per adapter instance
805 * @mask: mask with one bit set for each request to be cleared
807 static inline void ufshcd_utrl_clear(struct ufs_hba *hba, u32 mask)
809 if (hba->quirks & UFSHCI_QUIRK_BROKEN_REQ_LIST_CLR)
812 * From the UFSHCI specification: "UTP Transfer Request List CLear
813 * Register (UTRLCLR): This field is bit significant. Each bit
814 * corresponds to a slot in the UTP Transfer Request List, where bit 0
815 * corresponds to request slot 0. A bit in this field is set to ‘0’
816 * by host software to indicate to the host controller that a transfer
817 * request slot is cleared. The host controller
818 * shall free up any resources associated to the request slot
819 * immediately, and shall set the associated bit in UTRLDBR to ‘0’. The
820 * host software indicates no change to request slots by setting the
821 * associated bits in this field to ‘1’. Bits in this field shall only
822 * be set ‘1’ or ‘0’ by host software when UTRLRSR is set to ‘1’."
824 ufshcd_writel(hba, ~mask, REG_UTP_TRANSFER_REQ_LIST_CLEAR);
828 * ufshcd_utmrl_clear - Clear a bit in UTMRLCLR register
829 * @hba: per adapter instance
830 * @pos: position of the bit to be cleared
832 static inline void ufshcd_utmrl_clear(struct ufs_hba *hba, u32 pos)
834 if (hba->quirks & UFSHCI_QUIRK_BROKEN_REQ_LIST_CLR)
835 ufshcd_writel(hba, (1 << pos), REG_UTP_TASK_REQ_LIST_CLEAR);
837 ufshcd_writel(hba, ~(1 << pos), REG_UTP_TASK_REQ_LIST_CLEAR);
841 * ufshcd_get_lists_status - Check UCRDY, UTRLRDY and UTMRLRDY
842 * @reg: Register value of host controller status
844 * Returns integer, 0 on Success and positive value if failed
846 static inline int ufshcd_get_lists_status(u32 reg)
848 return !((reg & UFSHCD_STATUS_READY) == UFSHCD_STATUS_READY);
852 * ufshcd_get_uic_cmd_result - Get the UIC command result
853 * @hba: Pointer to adapter instance
855 * This function gets the result of UIC command completion
856 * Returns 0 on success, non zero value on error
858 static inline int ufshcd_get_uic_cmd_result(struct ufs_hba *hba)
860 return ufshcd_readl(hba, REG_UIC_COMMAND_ARG_2) &
861 MASK_UIC_COMMAND_RESULT;
865 * ufshcd_get_dme_attr_val - Get the value of attribute returned by UIC command
866 * @hba: Pointer to adapter instance
868 * This function gets UIC command argument3
869 * Returns 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
881 ufshcd_get_req_rsp(struct utp_upiu_rsp *ucd_rsp_ptr)
883 return be32_to_cpu(ucd_rsp_ptr->header.dword_0) >> 24;
887 * ufshcd_get_rsp_upiu_result - Get the result from response UPIU
888 * @ucd_rsp_ptr: pointer to response UPIU
890 * This function gets the response status and scsi_status from response UPIU
891 * Returns the response result code.
894 ufshcd_get_rsp_upiu_result(struct utp_upiu_rsp *ucd_rsp_ptr)
896 return be32_to_cpu(ucd_rsp_ptr->header.dword_1) & MASK_RSP_UPIU_RESULT;
900 * ufshcd_get_rsp_upiu_data_seg_len - Get the data segment length
902 * @ucd_rsp_ptr: pointer to response UPIU
904 * Return the data segment length.
906 static inline unsigned int
907 ufshcd_get_rsp_upiu_data_seg_len(struct utp_upiu_rsp *ucd_rsp_ptr)
909 return be32_to_cpu(ucd_rsp_ptr->header.dword_2) &
910 MASK_RSP_UPIU_DATA_SEG_LEN;
914 * ufshcd_is_exception_event - Check if the device raised an exception event
915 * @ucd_rsp_ptr: pointer to response UPIU
917 * The function checks if the device raised an exception event indicated in
918 * the Device Information field of response UPIU.
920 * Returns true if exception is raised, false otherwise.
922 static inline bool ufshcd_is_exception_event(struct utp_upiu_rsp *ucd_rsp_ptr)
924 return be32_to_cpu(ucd_rsp_ptr->header.dword_2) &
925 MASK_RSP_EXCEPTION_EVENT;
929 * ufshcd_reset_intr_aggr - Reset interrupt aggregation values.
930 * @hba: per adapter instance
933 ufshcd_reset_intr_aggr(struct ufs_hba *hba)
935 ufshcd_writel(hba, INT_AGGR_ENABLE |
936 INT_AGGR_COUNTER_AND_TIMER_RESET,
937 REG_UTP_TRANSFER_REQ_INT_AGG_CONTROL);
941 * ufshcd_config_intr_aggr - Configure interrupt aggregation values.
942 * @hba: per adapter instance
943 * @cnt: Interrupt aggregation counter threshold
944 * @tmout: Interrupt aggregation timeout value
947 ufshcd_config_intr_aggr(struct ufs_hba *hba, u8 cnt, u8 tmout)
949 ufshcd_writel(hba, INT_AGGR_ENABLE | INT_AGGR_PARAM_WRITE |
950 INT_AGGR_COUNTER_THLD_VAL(cnt) |
951 INT_AGGR_TIMEOUT_VAL(tmout),
952 REG_UTP_TRANSFER_REQ_INT_AGG_CONTROL);
956 * ufshcd_disable_intr_aggr - Disables interrupt aggregation.
957 * @hba: per adapter instance
959 static inline void ufshcd_disable_intr_aggr(struct ufs_hba *hba)
961 ufshcd_writel(hba, 0, REG_UTP_TRANSFER_REQ_INT_AGG_CONTROL);
965 * ufshcd_enable_run_stop_reg - Enable run-stop registers,
966 * When run-stop registers are set to 1, it indicates the
967 * host controller that it can process the requests
968 * @hba: per adapter instance
970 static void ufshcd_enable_run_stop_reg(struct ufs_hba *hba)
972 ufshcd_writel(hba, UTP_TASK_REQ_LIST_RUN_STOP_BIT,
973 REG_UTP_TASK_REQ_LIST_RUN_STOP);
974 ufshcd_writel(hba, UTP_TRANSFER_REQ_LIST_RUN_STOP_BIT,
975 REG_UTP_TRANSFER_REQ_LIST_RUN_STOP);
979 * ufshcd_hba_start - Start controller initialization sequence
980 * @hba: per adapter instance
982 static inline void ufshcd_hba_start(struct ufs_hba *hba)
984 u32 val = CONTROLLER_ENABLE;
986 if (ufshcd_crypto_enable(hba))
987 val |= CRYPTO_GENERAL_ENABLE;
989 ufshcd_writel(hba, val, REG_CONTROLLER_ENABLE);
993 * ufshcd_is_hba_active - Get controller state
994 * @hba: per adapter instance
996 * Returns true if and only if the controller is active.
998 static inline bool ufshcd_is_hba_active(struct ufs_hba *hba)
1000 return ufshcd_readl(hba, REG_CONTROLLER_ENABLE) & CONTROLLER_ENABLE;
1003 u32 ufshcd_get_local_unipro_ver(struct ufs_hba *hba)
1005 /* HCI version 1.0 and 1.1 supports UniPro 1.41 */
1006 if (hba->ufs_version <= ufshci_version(1, 1))
1007 return UFS_UNIPRO_VER_1_41;
1009 return UFS_UNIPRO_VER_1_6;
1011 EXPORT_SYMBOL(ufshcd_get_local_unipro_ver);
1013 static bool ufshcd_is_unipro_pa_params_tuning_req(struct ufs_hba *hba)
1016 * If both host and device support UniPro ver1.6 or later, PA layer
1017 * parameters tuning happens during link startup itself.
1019 * We can manually tune PA layer parameters if either host or device
1020 * doesn't support UniPro ver 1.6 or later. But to keep manual tuning
1021 * logic simple, we will only do manual tuning if local unipro version
1022 * doesn't support ver1.6 or later.
1024 return ufshcd_get_local_unipro_ver(hba) < UFS_UNIPRO_VER_1_6;
1028 * ufshcd_set_clk_freq - set UFS controller clock frequencies
1029 * @hba: per adapter instance
1030 * @scale_up: If True, set max possible frequency othewise set low frequency
1032 * Returns 0 if successful
1033 * Returns < 0 for any other errors
1035 static int ufshcd_set_clk_freq(struct ufs_hba *hba, bool scale_up)
1038 struct ufs_clk_info *clki;
1039 struct list_head *head = &hba->clk_list_head;
1041 if (list_empty(head))
1044 list_for_each_entry(clki, head, list) {
1045 if (!IS_ERR_OR_NULL(clki->clk)) {
1046 if (scale_up && clki->max_freq) {
1047 if (clki->curr_freq == clki->max_freq)
1050 ret = clk_set_rate(clki->clk, clki->max_freq);
1052 dev_err(hba->dev, "%s: %s clk set rate(%dHz) failed, %d\n",
1053 __func__, clki->name,
1054 clki->max_freq, ret);
1057 trace_ufshcd_clk_scaling(dev_name(hba->dev),
1058 "scaled up", clki->name,
1062 clki->curr_freq = clki->max_freq;
1064 } else if (!scale_up && clki->min_freq) {
1065 if (clki->curr_freq == clki->min_freq)
1068 ret = clk_set_rate(clki->clk, clki->min_freq);
1070 dev_err(hba->dev, "%s: %s clk set rate(%dHz) failed, %d\n",
1071 __func__, clki->name,
1072 clki->min_freq, ret);
1075 trace_ufshcd_clk_scaling(dev_name(hba->dev),
1076 "scaled down", clki->name,
1079 clki->curr_freq = clki->min_freq;
1082 dev_dbg(hba->dev, "%s: clk: %s, rate: %lu\n", __func__,
1083 clki->name, clk_get_rate(clki->clk));
1091 * ufshcd_scale_clks - scale up or scale down UFS controller clocks
1092 * @hba: per adapter instance
1093 * @scale_up: True if scaling up and false if scaling down
1095 * Returns 0 if successful
1096 * Returns < 0 for any other errors
1098 static int ufshcd_scale_clks(struct ufs_hba *hba, bool scale_up)
1101 ktime_t start = ktime_get();
1103 ret = ufshcd_vops_clk_scale_notify(hba, scale_up, PRE_CHANGE);
1107 ret = ufshcd_set_clk_freq(hba, scale_up);
1111 ret = ufshcd_vops_clk_scale_notify(hba, scale_up, POST_CHANGE);
1113 ufshcd_set_clk_freq(hba, !scale_up);
1116 trace_ufshcd_profile_clk_scaling(dev_name(hba->dev),
1117 (scale_up ? "up" : "down"),
1118 ktime_to_us(ktime_sub(ktime_get(), start)), ret);
1123 * ufshcd_is_devfreq_scaling_required - check if scaling is required or not
1124 * @hba: per adapter instance
1125 * @scale_up: True if scaling up and false if scaling down
1127 * Returns true if scaling is required, false otherwise.
1129 static bool ufshcd_is_devfreq_scaling_required(struct ufs_hba *hba,
1132 struct ufs_clk_info *clki;
1133 struct list_head *head = &hba->clk_list_head;
1135 if (list_empty(head))
1138 list_for_each_entry(clki, head, list) {
1139 if (!IS_ERR_OR_NULL(clki->clk)) {
1140 if (scale_up && clki->max_freq) {
1141 if (clki->curr_freq == clki->max_freq)
1144 } else if (!scale_up && clki->min_freq) {
1145 if (clki->curr_freq == clki->min_freq)
1156 * Determine the number of pending commands by counting the bits in the SCSI
1157 * device budget maps. This approach has been selected because a bit is set in
1158 * the budget map before scsi_host_queue_ready() checks the host_self_blocked
1159 * flag. The host_self_blocked flag can be modified by calling
1160 * scsi_block_requests() or scsi_unblock_requests().
1162 static u32 ufshcd_pending_cmds(struct ufs_hba *hba)
1164 const struct scsi_device *sdev;
1167 lockdep_assert_held(hba->host->host_lock);
1168 __shost_for_each_device(sdev, hba->host)
1169 pending += sbitmap_weight(&sdev->budget_map);
1175 * Wait until all pending SCSI commands and TMFs have finished or the timeout
1178 * Return: 0 upon success; -EBUSY upon timeout.
1180 static int ufshcd_wait_for_doorbell_clr(struct ufs_hba *hba,
1181 u64 wait_timeout_us)
1183 unsigned long flags;
1187 bool timeout = false, do_last_check = false;
1191 spin_lock_irqsave(hba->host->host_lock, flags);
1193 * Wait for all the outstanding tasks/transfer requests.
1194 * Verify by checking the doorbell registers are clear.
1196 start = ktime_get();
1198 if (hba->ufshcd_state != UFSHCD_STATE_OPERATIONAL) {
1203 tm_doorbell = ufshcd_readl(hba, REG_UTP_TASK_REQ_DOOR_BELL);
1204 tr_pending = ufshcd_pending_cmds(hba);
1205 if (!tm_doorbell && !tr_pending) {
1208 } else if (do_last_check) {
1212 spin_unlock_irqrestore(hba->host->host_lock, flags);
1213 io_schedule_timeout(msecs_to_jiffies(20));
1214 if (ktime_to_us(ktime_sub(ktime_get(), start)) >
1218 * We might have scheduled out for long time so make
1219 * sure to check if doorbells are cleared by this time
1222 do_last_check = true;
1224 spin_lock_irqsave(hba->host->host_lock, flags);
1225 } while (tm_doorbell || tr_pending);
1229 "%s: timedout waiting for doorbell to clear (tm=0x%x, tr=0x%x)\n",
1230 __func__, tm_doorbell, tr_pending);
1234 spin_unlock_irqrestore(hba->host->host_lock, flags);
1235 ufshcd_release(hba);
1240 * ufshcd_scale_gear - scale up/down UFS gear
1241 * @hba: per adapter instance
1242 * @scale_up: True for scaling up gear and false for scaling down
1244 * Returns 0 for success,
1245 * Returns -EBUSY if scaling can't happen at this time
1246 * Returns non-zero for any other errors
1248 static int ufshcd_scale_gear(struct ufs_hba *hba, bool scale_up)
1251 struct ufs_pa_layer_attr new_pwr_info;
1254 memcpy(&new_pwr_info, &hba->clk_scaling.saved_pwr_info,
1255 sizeof(struct ufs_pa_layer_attr));
1257 memcpy(&new_pwr_info, &hba->pwr_info,
1258 sizeof(struct ufs_pa_layer_attr));
1260 if (hba->pwr_info.gear_tx > hba->clk_scaling.min_gear ||
1261 hba->pwr_info.gear_rx > hba->clk_scaling.min_gear) {
1262 /* save the current power mode */
1263 memcpy(&hba->clk_scaling.saved_pwr_info,
1265 sizeof(struct ufs_pa_layer_attr));
1267 /* scale down gear */
1268 new_pwr_info.gear_tx = hba->clk_scaling.min_gear;
1269 new_pwr_info.gear_rx = hba->clk_scaling.min_gear;
1273 /* check if the power mode needs to be changed or not? */
1274 ret = ufshcd_config_pwr_mode(hba, &new_pwr_info);
1276 dev_err(hba->dev, "%s: failed err %d, old gear: (tx %d rx %d), new gear: (tx %d rx %d)",
1278 hba->pwr_info.gear_tx, hba->pwr_info.gear_rx,
1279 new_pwr_info.gear_tx, new_pwr_info.gear_rx);
1285 * Wait until all pending SCSI commands and TMFs have finished or the timeout
1288 * Return: 0 upon success; -EBUSY upon timeout.
1290 static int ufshcd_clock_scaling_prepare(struct ufs_hba *hba, u64 timeout_us)
1294 * make sure that there are no outstanding requests when
1295 * clock scaling is in progress
1297 ufshcd_scsi_block_requests(hba);
1298 mutex_lock(&hba->wb_mutex);
1299 down_write(&hba->clk_scaling_lock);
1301 if (!hba->clk_scaling.is_allowed ||
1302 ufshcd_wait_for_doorbell_clr(hba, timeout_us)) {
1304 up_write(&hba->clk_scaling_lock);
1305 mutex_unlock(&hba->wb_mutex);
1306 ufshcd_scsi_unblock_requests(hba);
1310 /* let's not get into low power until clock scaling is completed */
1317 static void ufshcd_clock_scaling_unprepare(struct ufs_hba *hba, int err, bool scale_up)
1319 up_write(&hba->clk_scaling_lock);
1321 /* Enable Write Booster if we have scaled up else disable it */
1322 if (ufshcd_enable_wb_if_scaling_up(hba) && !err)
1323 ufshcd_wb_toggle(hba, scale_up);
1325 mutex_unlock(&hba->wb_mutex);
1327 ufshcd_scsi_unblock_requests(hba);
1328 ufshcd_release(hba);
1332 * ufshcd_devfreq_scale - scale up/down UFS clocks and gear
1333 * @hba: per adapter instance
1334 * @scale_up: True for scaling up and false for scalin down
1336 * Returns 0 for success,
1337 * Returns -EBUSY if scaling can't happen at this time
1338 * Returns non-zero for any other errors
1340 static int ufshcd_devfreq_scale(struct ufs_hba *hba, bool scale_up)
1344 ret = ufshcd_clock_scaling_prepare(hba, 1 * USEC_PER_SEC);
1348 /* scale down the gear before scaling down clocks */
1350 ret = ufshcd_scale_gear(hba, false);
1355 ret = ufshcd_scale_clks(hba, scale_up);
1358 ufshcd_scale_gear(hba, true);
1362 /* scale up the gear after scaling up clocks */
1364 ret = ufshcd_scale_gear(hba, true);
1366 ufshcd_scale_clks(hba, false);
1372 ufshcd_clock_scaling_unprepare(hba, ret, scale_up);
1376 static void ufshcd_clk_scaling_suspend_work(struct work_struct *work)
1378 struct ufs_hba *hba = container_of(work, struct ufs_hba,
1379 clk_scaling.suspend_work);
1380 unsigned long irq_flags;
1382 spin_lock_irqsave(hba->host->host_lock, irq_flags);
1383 if (hba->clk_scaling.active_reqs || hba->clk_scaling.is_suspended) {
1384 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1387 hba->clk_scaling.is_suspended = true;
1388 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1390 __ufshcd_suspend_clkscaling(hba);
1393 static void ufshcd_clk_scaling_resume_work(struct work_struct *work)
1395 struct ufs_hba *hba = container_of(work, struct ufs_hba,
1396 clk_scaling.resume_work);
1397 unsigned long irq_flags;
1399 spin_lock_irqsave(hba->host->host_lock, irq_flags);
1400 if (!hba->clk_scaling.is_suspended) {
1401 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1404 hba->clk_scaling.is_suspended = false;
1405 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1407 devfreq_resume_device(hba->devfreq);
1410 static int ufshcd_devfreq_target(struct device *dev,
1411 unsigned long *freq, u32 flags)
1414 struct ufs_hba *hba = dev_get_drvdata(dev);
1416 bool scale_up, sched_clk_scaling_suspend_work = false;
1417 struct list_head *clk_list = &hba->clk_list_head;
1418 struct ufs_clk_info *clki;
1419 unsigned long irq_flags;
1421 if (!ufshcd_is_clkscaling_supported(hba))
1424 clki = list_first_entry(&hba->clk_list_head, struct ufs_clk_info, list);
1425 /* Override with the closest supported frequency */
1426 *freq = (unsigned long) clk_round_rate(clki->clk, *freq);
1427 spin_lock_irqsave(hba->host->host_lock, irq_flags);
1428 if (ufshcd_eh_in_progress(hba)) {
1429 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1433 if (!hba->clk_scaling.active_reqs)
1434 sched_clk_scaling_suspend_work = true;
1436 if (list_empty(clk_list)) {
1437 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1441 /* Decide based on the rounded-off frequency and update */
1442 scale_up = *freq == clki->max_freq;
1444 *freq = clki->min_freq;
1445 /* Update the frequency */
1446 if (!ufshcd_is_devfreq_scaling_required(hba, scale_up)) {
1447 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1449 goto out; /* no state change required */
1451 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1453 start = ktime_get();
1454 ret = ufshcd_devfreq_scale(hba, scale_up);
1456 trace_ufshcd_profile_clk_scaling(dev_name(hba->dev),
1457 (scale_up ? "up" : "down"),
1458 ktime_to_us(ktime_sub(ktime_get(), start)), ret);
1461 if (sched_clk_scaling_suspend_work)
1462 queue_work(hba->clk_scaling.workq,
1463 &hba->clk_scaling.suspend_work);
1468 static int ufshcd_devfreq_get_dev_status(struct device *dev,
1469 struct devfreq_dev_status *stat)
1471 struct ufs_hba *hba = dev_get_drvdata(dev);
1472 struct ufs_clk_scaling *scaling = &hba->clk_scaling;
1473 unsigned long flags;
1474 struct list_head *clk_list = &hba->clk_list_head;
1475 struct ufs_clk_info *clki;
1478 if (!ufshcd_is_clkscaling_supported(hba))
1481 memset(stat, 0, sizeof(*stat));
1483 spin_lock_irqsave(hba->host->host_lock, flags);
1484 curr_t = ktime_get();
1485 if (!scaling->window_start_t)
1488 clki = list_first_entry(clk_list, struct ufs_clk_info, list);
1490 * If current frequency is 0, then the ondemand governor considers
1491 * there's no initial frequency set. And it always requests to set
1492 * to max. frequency.
1494 stat->current_frequency = clki->curr_freq;
1495 if (scaling->is_busy_started)
1496 scaling->tot_busy_t += ktime_us_delta(curr_t,
1497 scaling->busy_start_t);
1499 stat->total_time = ktime_us_delta(curr_t, scaling->window_start_t);
1500 stat->busy_time = scaling->tot_busy_t;
1502 scaling->window_start_t = curr_t;
1503 scaling->tot_busy_t = 0;
1505 if (scaling->active_reqs) {
1506 scaling->busy_start_t = curr_t;
1507 scaling->is_busy_started = true;
1509 scaling->busy_start_t = 0;
1510 scaling->is_busy_started = false;
1512 spin_unlock_irqrestore(hba->host->host_lock, flags);
1516 static int ufshcd_devfreq_init(struct ufs_hba *hba)
1518 struct list_head *clk_list = &hba->clk_list_head;
1519 struct ufs_clk_info *clki;
1520 struct devfreq *devfreq;
1523 /* Skip devfreq if we don't have any clocks in the list */
1524 if (list_empty(clk_list))
1527 clki = list_first_entry(clk_list, struct ufs_clk_info, list);
1528 dev_pm_opp_add(hba->dev, clki->min_freq, 0);
1529 dev_pm_opp_add(hba->dev, clki->max_freq, 0);
1531 ufshcd_vops_config_scaling_param(hba, &hba->vps->devfreq_profile,
1532 &hba->vps->ondemand_data);
1533 devfreq = devfreq_add_device(hba->dev,
1534 &hba->vps->devfreq_profile,
1535 DEVFREQ_GOV_SIMPLE_ONDEMAND,
1536 &hba->vps->ondemand_data);
1537 if (IS_ERR(devfreq)) {
1538 ret = PTR_ERR(devfreq);
1539 dev_err(hba->dev, "Unable to register with devfreq %d\n", ret);
1541 dev_pm_opp_remove(hba->dev, clki->min_freq);
1542 dev_pm_opp_remove(hba->dev, clki->max_freq);
1546 hba->devfreq = devfreq;
1551 static void ufshcd_devfreq_remove(struct ufs_hba *hba)
1553 struct list_head *clk_list = &hba->clk_list_head;
1554 struct ufs_clk_info *clki;
1559 devfreq_remove_device(hba->devfreq);
1560 hba->devfreq = NULL;
1562 clki = list_first_entry(clk_list, struct ufs_clk_info, list);
1563 dev_pm_opp_remove(hba->dev, clki->min_freq);
1564 dev_pm_opp_remove(hba->dev, clki->max_freq);
1567 static void __ufshcd_suspend_clkscaling(struct ufs_hba *hba)
1569 unsigned long flags;
1571 devfreq_suspend_device(hba->devfreq);
1572 spin_lock_irqsave(hba->host->host_lock, flags);
1573 hba->clk_scaling.window_start_t = 0;
1574 spin_unlock_irqrestore(hba->host->host_lock, flags);
1577 static void ufshcd_suspend_clkscaling(struct ufs_hba *hba)
1579 unsigned long flags;
1580 bool suspend = false;
1582 cancel_work_sync(&hba->clk_scaling.suspend_work);
1583 cancel_work_sync(&hba->clk_scaling.resume_work);
1585 spin_lock_irqsave(hba->host->host_lock, flags);
1586 if (!hba->clk_scaling.is_suspended) {
1588 hba->clk_scaling.is_suspended = true;
1590 spin_unlock_irqrestore(hba->host->host_lock, flags);
1593 __ufshcd_suspend_clkscaling(hba);
1596 static void ufshcd_resume_clkscaling(struct ufs_hba *hba)
1598 unsigned long flags;
1599 bool resume = false;
1601 spin_lock_irqsave(hba->host->host_lock, flags);
1602 if (hba->clk_scaling.is_suspended) {
1604 hba->clk_scaling.is_suspended = false;
1606 spin_unlock_irqrestore(hba->host->host_lock, flags);
1609 devfreq_resume_device(hba->devfreq);
1612 static ssize_t ufshcd_clkscale_enable_show(struct device *dev,
1613 struct device_attribute *attr, char *buf)
1615 struct ufs_hba *hba = dev_get_drvdata(dev);
1617 return sysfs_emit(buf, "%d\n", hba->clk_scaling.is_enabled);
1620 static ssize_t ufshcd_clkscale_enable_store(struct device *dev,
1621 struct device_attribute *attr, const char *buf, size_t count)
1623 struct ufs_hba *hba = dev_get_drvdata(dev);
1627 if (kstrtou32(buf, 0, &value))
1630 down(&hba->host_sem);
1631 if (!ufshcd_is_user_access_allowed(hba)) {
1637 if (value == hba->clk_scaling.is_enabled)
1640 ufshcd_rpm_get_sync(hba);
1643 hba->clk_scaling.is_enabled = value;
1646 ufshcd_resume_clkscaling(hba);
1648 ufshcd_suspend_clkscaling(hba);
1649 err = ufshcd_devfreq_scale(hba, true);
1651 dev_err(hba->dev, "%s: failed to scale clocks up %d\n",
1655 ufshcd_release(hba);
1656 ufshcd_rpm_put_sync(hba);
1659 return err ? err : count;
1662 static void ufshcd_init_clk_scaling_sysfs(struct ufs_hba *hba)
1664 hba->clk_scaling.enable_attr.show = ufshcd_clkscale_enable_show;
1665 hba->clk_scaling.enable_attr.store = ufshcd_clkscale_enable_store;
1666 sysfs_attr_init(&hba->clk_scaling.enable_attr.attr);
1667 hba->clk_scaling.enable_attr.attr.name = "clkscale_enable";
1668 hba->clk_scaling.enable_attr.attr.mode = 0644;
1669 if (device_create_file(hba->dev, &hba->clk_scaling.enable_attr))
1670 dev_err(hba->dev, "Failed to create sysfs for clkscale_enable\n");
1673 static void ufshcd_remove_clk_scaling_sysfs(struct ufs_hba *hba)
1675 if (hba->clk_scaling.enable_attr.attr.name)
1676 device_remove_file(hba->dev, &hba->clk_scaling.enable_attr);
1679 static void ufshcd_init_clk_scaling(struct ufs_hba *hba)
1681 char wq_name[sizeof("ufs_clkscaling_00")];
1683 if (!ufshcd_is_clkscaling_supported(hba))
1686 if (!hba->clk_scaling.min_gear)
1687 hba->clk_scaling.min_gear = UFS_HS_G1;
1689 INIT_WORK(&hba->clk_scaling.suspend_work,
1690 ufshcd_clk_scaling_suspend_work);
1691 INIT_WORK(&hba->clk_scaling.resume_work,
1692 ufshcd_clk_scaling_resume_work);
1694 snprintf(wq_name, sizeof(wq_name), "ufs_clkscaling_%d",
1695 hba->host->host_no);
1696 hba->clk_scaling.workq = create_singlethread_workqueue(wq_name);
1698 hba->clk_scaling.is_initialized = true;
1701 static void ufshcd_exit_clk_scaling(struct ufs_hba *hba)
1703 if (!hba->clk_scaling.is_initialized)
1706 ufshcd_remove_clk_scaling_sysfs(hba);
1707 destroy_workqueue(hba->clk_scaling.workq);
1708 ufshcd_devfreq_remove(hba);
1709 hba->clk_scaling.is_initialized = false;
1712 static void ufshcd_ungate_work(struct work_struct *work)
1715 unsigned long flags;
1716 struct ufs_hba *hba = container_of(work, struct ufs_hba,
1717 clk_gating.ungate_work);
1719 cancel_delayed_work_sync(&hba->clk_gating.gate_work);
1721 spin_lock_irqsave(hba->host->host_lock, flags);
1722 if (hba->clk_gating.state == CLKS_ON) {
1723 spin_unlock_irqrestore(hba->host->host_lock, flags);
1727 spin_unlock_irqrestore(hba->host->host_lock, flags);
1728 ufshcd_hba_vreg_set_hpm(hba);
1729 ufshcd_setup_clocks(hba, true);
1731 ufshcd_enable_irq(hba);
1733 /* Exit from hibern8 */
1734 if (ufshcd_can_hibern8_during_gating(hba)) {
1735 /* Prevent gating in this path */
1736 hba->clk_gating.is_suspended = true;
1737 if (ufshcd_is_link_hibern8(hba)) {
1738 ret = ufshcd_uic_hibern8_exit(hba);
1740 dev_err(hba->dev, "%s: hibern8 exit failed %d\n",
1743 ufshcd_set_link_active(hba);
1745 hba->clk_gating.is_suspended = false;
1750 * ufshcd_hold - Enable clocks that were gated earlier due to ufshcd_release.
1751 * Also, exit from hibern8 mode and set the link as active.
1752 * @hba: per adapter instance
1754 void ufshcd_hold(struct ufs_hba *hba)
1757 unsigned long flags;
1759 if (!ufshcd_is_clkgating_allowed(hba) ||
1760 !hba->clk_gating.is_initialized)
1762 spin_lock_irqsave(hba->host->host_lock, flags);
1763 hba->clk_gating.active_reqs++;
1766 switch (hba->clk_gating.state) {
1769 * Wait for the ungate work to complete if in progress.
1770 * Though the clocks may be in ON state, the link could
1771 * still be in hibner8 state if hibern8 is allowed
1772 * during clock gating.
1773 * Make sure we exit hibern8 state also in addition to
1776 if (ufshcd_can_hibern8_during_gating(hba) &&
1777 ufshcd_is_link_hibern8(hba)) {
1778 spin_unlock_irqrestore(hba->host->host_lock, flags);
1779 flush_result = flush_work(&hba->clk_gating.ungate_work);
1780 if (hba->clk_gating.is_suspended && !flush_result)
1782 spin_lock_irqsave(hba->host->host_lock, flags);
1787 if (cancel_delayed_work(&hba->clk_gating.gate_work)) {
1788 hba->clk_gating.state = CLKS_ON;
1789 trace_ufshcd_clk_gating(dev_name(hba->dev),
1790 hba->clk_gating.state);
1794 * If we are here, it means gating work is either done or
1795 * currently running. Hence, fall through to cancel gating
1796 * work and to enable clocks.
1800 hba->clk_gating.state = REQ_CLKS_ON;
1801 trace_ufshcd_clk_gating(dev_name(hba->dev),
1802 hba->clk_gating.state);
1803 queue_work(hba->clk_gating.clk_gating_workq,
1804 &hba->clk_gating.ungate_work);
1806 * fall through to check if we should wait for this
1807 * work to be done or not.
1811 spin_unlock_irqrestore(hba->host->host_lock, flags);
1812 flush_work(&hba->clk_gating.ungate_work);
1813 /* Make sure state is CLKS_ON before returning */
1814 spin_lock_irqsave(hba->host->host_lock, flags);
1817 dev_err(hba->dev, "%s: clk gating is in invalid state %d\n",
1818 __func__, hba->clk_gating.state);
1821 spin_unlock_irqrestore(hba->host->host_lock, flags);
1823 EXPORT_SYMBOL_GPL(ufshcd_hold);
1825 static void ufshcd_gate_work(struct work_struct *work)
1827 struct ufs_hba *hba = container_of(work, struct ufs_hba,
1828 clk_gating.gate_work.work);
1829 unsigned long flags;
1832 spin_lock_irqsave(hba->host->host_lock, flags);
1834 * In case you are here to cancel this work the gating state
1835 * would be marked as REQ_CLKS_ON. In this case save time by
1836 * skipping the gating work and exit after changing the clock
1839 if (hba->clk_gating.is_suspended ||
1840 (hba->clk_gating.state != REQ_CLKS_OFF)) {
1841 hba->clk_gating.state = CLKS_ON;
1842 trace_ufshcd_clk_gating(dev_name(hba->dev),
1843 hba->clk_gating.state);
1847 if (hba->clk_gating.active_reqs
1848 || hba->ufshcd_state != UFSHCD_STATE_OPERATIONAL
1849 || hba->outstanding_reqs || hba->outstanding_tasks
1850 || hba->active_uic_cmd || hba->uic_async_done)
1853 spin_unlock_irqrestore(hba->host->host_lock, flags);
1855 /* put the link into hibern8 mode before turning off clocks */
1856 if (ufshcd_can_hibern8_during_gating(hba)) {
1857 ret = ufshcd_uic_hibern8_enter(hba);
1859 hba->clk_gating.state = CLKS_ON;
1860 dev_err(hba->dev, "%s: hibern8 enter failed %d\n",
1862 trace_ufshcd_clk_gating(dev_name(hba->dev),
1863 hba->clk_gating.state);
1866 ufshcd_set_link_hibern8(hba);
1869 ufshcd_disable_irq(hba);
1871 ufshcd_setup_clocks(hba, false);
1873 /* Put the host controller in low power mode if possible */
1874 ufshcd_hba_vreg_set_lpm(hba);
1876 * In case you are here to cancel this work the gating state
1877 * would be marked as REQ_CLKS_ON. In this case keep the state
1878 * as REQ_CLKS_ON which would anyway imply that clocks are off
1879 * and a request to turn them on is pending. By doing this way,
1880 * we keep the state machine in tact and this would ultimately
1881 * prevent from doing cancel work multiple times when there are
1882 * new requests arriving before the current cancel work is done.
1884 spin_lock_irqsave(hba->host->host_lock, flags);
1885 if (hba->clk_gating.state == REQ_CLKS_OFF) {
1886 hba->clk_gating.state = CLKS_OFF;
1887 trace_ufshcd_clk_gating(dev_name(hba->dev),
1888 hba->clk_gating.state);
1891 spin_unlock_irqrestore(hba->host->host_lock, flags);
1896 /* host lock must be held before calling this variant */
1897 static void __ufshcd_release(struct ufs_hba *hba)
1899 if (!ufshcd_is_clkgating_allowed(hba))
1902 hba->clk_gating.active_reqs--;
1904 if (hba->clk_gating.active_reqs || hba->clk_gating.is_suspended ||
1905 hba->ufshcd_state != UFSHCD_STATE_OPERATIONAL ||
1906 hba->outstanding_tasks || !hba->clk_gating.is_initialized ||
1907 hba->active_uic_cmd || hba->uic_async_done ||
1908 hba->clk_gating.state == CLKS_OFF)
1911 hba->clk_gating.state = REQ_CLKS_OFF;
1912 trace_ufshcd_clk_gating(dev_name(hba->dev), hba->clk_gating.state);
1913 queue_delayed_work(hba->clk_gating.clk_gating_workq,
1914 &hba->clk_gating.gate_work,
1915 msecs_to_jiffies(hba->clk_gating.delay_ms));
1918 void ufshcd_release(struct ufs_hba *hba)
1920 unsigned long flags;
1922 spin_lock_irqsave(hba->host->host_lock, flags);
1923 __ufshcd_release(hba);
1924 spin_unlock_irqrestore(hba->host->host_lock, flags);
1926 EXPORT_SYMBOL_GPL(ufshcd_release);
1928 static ssize_t ufshcd_clkgate_delay_show(struct device *dev,
1929 struct device_attribute *attr, char *buf)
1931 struct ufs_hba *hba = dev_get_drvdata(dev);
1933 return sysfs_emit(buf, "%lu\n", hba->clk_gating.delay_ms);
1936 void ufshcd_clkgate_delay_set(struct device *dev, unsigned long value)
1938 struct ufs_hba *hba = dev_get_drvdata(dev);
1939 unsigned long flags;
1941 spin_lock_irqsave(hba->host->host_lock, flags);
1942 hba->clk_gating.delay_ms = value;
1943 spin_unlock_irqrestore(hba->host->host_lock, flags);
1945 EXPORT_SYMBOL_GPL(ufshcd_clkgate_delay_set);
1947 static ssize_t ufshcd_clkgate_delay_store(struct device *dev,
1948 struct device_attribute *attr, const char *buf, size_t count)
1950 unsigned long value;
1952 if (kstrtoul(buf, 0, &value))
1955 ufshcd_clkgate_delay_set(dev, value);
1959 static ssize_t ufshcd_clkgate_enable_show(struct device *dev,
1960 struct device_attribute *attr, char *buf)
1962 struct ufs_hba *hba = dev_get_drvdata(dev);
1964 return sysfs_emit(buf, "%d\n", hba->clk_gating.is_enabled);
1967 static ssize_t ufshcd_clkgate_enable_store(struct device *dev,
1968 struct device_attribute *attr, const char *buf, size_t count)
1970 struct ufs_hba *hba = dev_get_drvdata(dev);
1971 unsigned long flags;
1974 if (kstrtou32(buf, 0, &value))
1979 spin_lock_irqsave(hba->host->host_lock, flags);
1980 if (value == hba->clk_gating.is_enabled)
1984 __ufshcd_release(hba);
1986 hba->clk_gating.active_reqs++;
1988 hba->clk_gating.is_enabled = value;
1990 spin_unlock_irqrestore(hba->host->host_lock, flags);
1994 static void ufshcd_init_clk_gating_sysfs(struct ufs_hba *hba)
1996 hba->clk_gating.delay_attr.show = ufshcd_clkgate_delay_show;
1997 hba->clk_gating.delay_attr.store = ufshcd_clkgate_delay_store;
1998 sysfs_attr_init(&hba->clk_gating.delay_attr.attr);
1999 hba->clk_gating.delay_attr.attr.name = "clkgate_delay_ms";
2000 hba->clk_gating.delay_attr.attr.mode = 0644;
2001 if (device_create_file(hba->dev, &hba->clk_gating.delay_attr))
2002 dev_err(hba->dev, "Failed to create sysfs for clkgate_delay\n");
2004 hba->clk_gating.enable_attr.show = ufshcd_clkgate_enable_show;
2005 hba->clk_gating.enable_attr.store = ufshcd_clkgate_enable_store;
2006 sysfs_attr_init(&hba->clk_gating.enable_attr.attr);
2007 hba->clk_gating.enable_attr.attr.name = "clkgate_enable";
2008 hba->clk_gating.enable_attr.attr.mode = 0644;
2009 if (device_create_file(hba->dev, &hba->clk_gating.enable_attr))
2010 dev_err(hba->dev, "Failed to create sysfs for clkgate_enable\n");
2013 static void ufshcd_remove_clk_gating_sysfs(struct ufs_hba *hba)
2015 if (hba->clk_gating.delay_attr.attr.name)
2016 device_remove_file(hba->dev, &hba->clk_gating.delay_attr);
2017 if (hba->clk_gating.enable_attr.attr.name)
2018 device_remove_file(hba->dev, &hba->clk_gating.enable_attr);
2021 static void ufshcd_init_clk_gating(struct ufs_hba *hba)
2023 char wq_name[sizeof("ufs_clk_gating_00")];
2025 if (!ufshcd_is_clkgating_allowed(hba))
2028 hba->clk_gating.state = CLKS_ON;
2030 hba->clk_gating.delay_ms = 150;
2031 INIT_DELAYED_WORK(&hba->clk_gating.gate_work, ufshcd_gate_work);
2032 INIT_WORK(&hba->clk_gating.ungate_work, ufshcd_ungate_work);
2034 snprintf(wq_name, ARRAY_SIZE(wq_name), "ufs_clk_gating_%d",
2035 hba->host->host_no);
2036 hba->clk_gating.clk_gating_workq = alloc_ordered_workqueue(wq_name,
2037 WQ_MEM_RECLAIM | WQ_HIGHPRI);
2039 ufshcd_init_clk_gating_sysfs(hba);
2041 hba->clk_gating.is_enabled = true;
2042 hba->clk_gating.is_initialized = true;
2045 static void ufshcd_exit_clk_gating(struct ufs_hba *hba)
2047 if (!hba->clk_gating.is_initialized)
2050 ufshcd_remove_clk_gating_sysfs(hba);
2052 /* Ungate the clock if necessary. */
2054 hba->clk_gating.is_initialized = false;
2055 ufshcd_release(hba);
2057 destroy_workqueue(hba->clk_gating.clk_gating_workq);
2060 static void ufshcd_clk_scaling_start_busy(struct ufs_hba *hba)
2062 bool queue_resume_work = false;
2063 ktime_t curr_t = ktime_get();
2064 unsigned long flags;
2066 if (!ufshcd_is_clkscaling_supported(hba))
2069 spin_lock_irqsave(hba->host->host_lock, flags);
2070 if (!hba->clk_scaling.active_reqs++)
2071 queue_resume_work = true;
2073 if (!hba->clk_scaling.is_enabled || hba->pm_op_in_progress) {
2074 spin_unlock_irqrestore(hba->host->host_lock, flags);
2078 if (queue_resume_work)
2079 queue_work(hba->clk_scaling.workq,
2080 &hba->clk_scaling.resume_work);
2082 if (!hba->clk_scaling.window_start_t) {
2083 hba->clk_scaling.window_start_t = curr_t;
2084 hba->clk_scaling.tot_busy_t = 0;
2085 hba->clk_scaling.is_busy_started = false;
2088 if (!hba->clk_scaling.is_busy_started) {
2089 hba->clk_scaling.busy_start_t = curr_t;
2090 hba->clk_scaling.is_busy_started = true;
2092 spin_unlock_irqrestore(hba->host->host_lock, flags);
2095 static void ufshcd_clk_scaling_update_busy(struct ufs_hba *hba)
2097 struct ufs_clk_scaling *scaling = &hba->clk_scaling;
2098 unsigned long flags;
2100 if (!ufshcd_is_clkscaling_supported(hba))
2103 spin_lock_irqsave(hba->host->host_lock, flags);
2104 hba->clk_scaling.active_reqs--;
2105 if (!scaling->active_reqs && scaling->is_busy_started) {
2106 scaling->tot_busy_t += ktime_to_us(ktime_sub(ktime_get(),
2107 scaling->busy_start_t));
2108 scaling->busy_start_t = 0;
2109 scaling->is_busy_started = false;
2111 spin_unlock_irqrestore(hba->host->host_lock, flags);
2114 static inline int ufshcd_monitor_opcode2dir(u8 opcode)
2116 if (opcode == READ_6 || opcode == READ_10 || opcode == READ_16)
2118 else if (opcode == WRITE_6 || opcode == WRITE_10 || opcode == WRITE_16)
2124 static inline bool ufshcd_should_inform_monitor(struct ufs_hba *hba,
2125 struct ufshcd_lrb *lrbp)
2127 const struct ufs_hba_monitor *m = &hba->monitor;
2129 return (m->enabled && lrbp && lrbp->cmd &&
2130 (!m->chunk_size || m->chunk_size == lrbp->cmd->sdb.length) &&
2131 ktime_before(hba->monitor.enabled_ts, lrbp->issue_time_stamp));
2134 static void ufshcd_start_monitor(struct ufs_hba *hba,
2135 const struct ufshcd_lrb *lrbp)
2137 int dir = ufshcd_monitor_opcode2dir(*lrbp->cmd->cmnd);
2138 unsigned long flags;
2140 spin_lock_irqsave(hba->host->host_lock, flags);
2141 if (dir >= 0 && hba->monitor.nr_queued[dir]++ == 0)
2142 hba->monitor.busy_start_ts[dir] = ktime_get();
2143 spin_unlock_irqrestore(hba->host->host_lock, flags);
2146 static void ufshcd_update_monitor(struct ufs_hba *hba, const struct ufshcd_lrb *lrbp)
2148 int dir = ufshcd_monitor_opcode2dir(*lrbp->cmd->cmnd);
2149 unsigned long flags;
2151 spin_lock_irqsave(hba->host->host_lock, flags);
2152 if (dir >= 0 && hba->monitor.nr_queued[dir] > 0) {
2153 const struct request *req = scsi_cmd_to_rq(lrbp->cmd);
2154 struct ufs_hba_monitor *m = &hba->monitor;
2155 ktime_t now, inc, lat;
2157 now = lrbp->compl_time_stamp;
2158 inc = ktime_sub(now, m->busy_start_ts[dir]);
2159 m->total_busy[dir] = ktime_add(m->total_busy[dir], inc);
2160 m->nr_sec_rw[dir] += blk_rq_sectors(req);
2162 /* Update latencies */
2164 lat = ktime_sub(now, lrbp->issue_time_stamp);
2165 m->lat_sum[dir] += lat;
2166 if (m->lat_max[dir] < lat || !m->lat_max[dir])
2167 m->lat_max[dir] = lat;
2168 if (m->lat_min[dir] > lat || !m->lat_min[dir])
2169 m->lat_min[dir] = lat;
2171 m->nr_queued[dir]--;
2172 /* Push forward the busy start of monitor */
2173 m->busy_start_ts[dir] = now;
2175 spin_unlock_irqrestore(hba->host->host_lock, flags);
2179 * ufshcd_send_command - Send SCSI or device management commands
2180 * @hba: per adapter instance
2181 * @task_tag: Task tag of the command
2182 * @hwq: pointer to hardware queue instance
2185 void ufshcd_send_command(struct ufs_hba *hba, unsigned int task_tag,
2186 struct ufs_hw_queue *hwq)
2188 struct ufshcd_lrb *lrbp = &hba->lrb[task_tag];
2189 unsigned long flags;
2191 lrbp->issue_time_stamp = ktime_get();
2192 lrbp->issue_time_stamp_local_clock = local_clock();
2193 lrbp->compl_time_stamp = ktime_set(0, 0);
2194 lrbp->compl_time_stamp_local_clock = 0;
2195 ufshcd_add_command_trace(hba, task_tag, UFS_CMD_SEND);
2196 ufshcd_clk_scaling_start_busy(hba);
2197 if (unlikely(ufshcd_should_inform_monitor(hba, lrbp)))
2198 ufshcd_start_monitor(hba, lrbp);
2200 if (is_mcq_enabled(hba)) {
2201 int utrd_size = sizeof(struct utp_transfer_req_desc);
2202 struct utp_transfer_req_desc *src = lrbp->utr_descriptor_ptr;
2203 struct utp_transfer_req_desc *dest = hwq->sqe_base_addr + hwq->sq_tail_slot;
2205 spin_lock(&hwq->sq_lock);
2206 memcpy(dest, src, utrd_size);
2207 ufshcd_inc_sq_tail(hwq);
2208 spin_unlock(&hwq->sq_lock);
2210 spin_lock_irqsave(&hba->outstanding_lock, flags);
2211 if (hba->vops && hba->vops->setup_xfer_req)
2212 hba->vops->setup_xfer_req(hba, lrbp->task_tag,
2214 __set_bit(lrbp->task_tag, &hba->outstanding_reqs);
2215 ufshcd_writel(hba, 1 << lrbp->task_tag,
2216 REG_UTP_TRANSFER_REQ_DOOR_BELL);
2217 spin_unlock_irqrestore(&hba->outstanding_lock, flags);
2222 * ufshcd_copy_sense_data - Copy sense data in case of check condition
2223 * @lrbp: pointer to local reference block
2225 static inline void ufshcd_copy_sense_data(struct ufshcd_lrb *lrbp)
2227 u8 *const sense_buffer = lrbp->cmd->sense_buffer;
2231 ufshcd_get_rsp_upiu_data_seg_len(lrbp->ucd_rsp_ptr)) {
2234 len = be16_to_cpu(lrbp->ucd_rsp_ptr->sr.sense_data_len);
2235 len_to_copy = min_t(int, UFS_SENSE_SIZE, len);
2237 memcpy(sense_buffer, lrbp->ucd_rsp_ptr->sr.sense_data,
2243 * ufshcd_copy_query_response() - Copy the Query Response and the data
2245 * @hba: per adapter instance
2246 * @lrbp: pointer to local reference block
2249 int ufshcd_copy_query_response(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
2251 struct ufs_query_res *query_res = &hba->dev_cmd.query.response;
2253 memcpy(&query_res->upiu_res, &lrbp->ucd_rsp_ptr->qr, QUERY_OSF_SIZE);
2255 /* Get the descriptor */
2256 if (hba->dev_cmd.query.descriptor &&
2257 lrbp->ucd_rsp_ptr->qr.opcode == UPIU_QUERY_OPCODE_READ_DESC) {
2258 u8 *descp = (u8 *)lrbp->ucd_rsp_ptr +
2259 GENERAL_UPIU_REQUEST_SIZE;
2263 /* data segment length */
2264 resp_len = be32_to_cpu(lrbp->ucd_rsp_ptr->header.dword_2) &
2265 MASK_QUERY_DATA_SEG_LEN;
2266 buf_len = be16_to_cpu(
2267 hba->dev_cmd.query.request.upiu_req.length);
2268 if (likely(buf_len >= resp_len)) {
2269 memcpy(hba->dev_cmd.query.descriptor, descp, resp_len);
2272 "%s: rsp size %d is bigger than buffer size %d",
2273 __func__, resp_len, buf_len);
2282 * ufshcd_hba_capabilities - Read controller capabilities
2283 * @hba: per adapter instance
2285 * Return: 0 on success, negative on error.
2287 static inline int ufshcd_hba_capabilities(struct ufs_hba *hba)
2291 hba->capabilities = ufshcd_readl(hba, REG_CONTROLLER_CAPABILITIES);
2292 if (hba->quirks & UFSHCD_QUIRK_BROKEN_64BIT_ADDRESS)
2293 hba->capabilities &= ~MASK_64_ADDRESSING_SUPPORT;
2295 /* nutrs and nutmrs are 0 based values */
2296 hba->nutrs = (hba->capabilities & MASK_TRANSFER_REQUESTS_SLOTS) + 1;
2298 ((hba->capabilities & MASK_TASK_MANAGEMENT_REQUEST_SLOTS) >> 16) + 1;
2299 hba->reserved_slot = hba->nutrs - 1;
2301 /* Read crypto capabilities */
2302 err = ufshcd_hba_init_crypto_capabilities(hba);
2304 dev_err(hba->dev, "crypto setup failed\n");
2308 hba->mcq_sup = FIELD_GET(MASK_MCQ_SUPPORT, hba->capabilities);
2312 hba->mcq_capabilities = ufshcd_readl(hba, REG_MCQCAP);
2313 hba->ext_iid_sup = FIELD_GET(MASK_EXT_IID_SUPPORT,
2314 hba->mcq_capabilities);
2320 * ufshcd_ready_for_uic_cmd - Check if controller is ready
2321 * to accept UIC commands
2322 * @hba: per adapter instance
2323 * Return true on success, else false
2325 static inline bool ufshcd_ready_for_uic_cmd(struct ufs_hba *hba)
2327 return ufshcd_readl(hba, REG_CONTROLLER_STATUS) & UIC_COMMAND_READY;
2331 * ufshcd_get_upmcrs - Get the power mode change request status
2332 * @hba: Pointer to adapter instance
2334 * This function gets the UPMCRS field of HCS register
2335 * Returns value of UPMCRS field
2337 static inline u8 ufshcd_get_upmcrs(struct ufs_hba *hba)
2339 return (ufshcd_readl(hba, REG_CONTROLLER_STATUS) >> 8) & 0x7;
2343 * ufshcd_dispatch_uic_cmd - Dispatch an UIC command to the Unipro layer
2344 * @hba: per adapter instance
2345 * @uic_cmd: UIC command
2348 ufshcd_dispatch_uic_cmd(struct ufs_hba *hba, struct uic_command *uic_cmd)
2350 lockdep_assert_held(&hba->uic_cmd_mutex);
2352 WARN_ON(hba->active_uic_cmd);
2354 hba->active_uic_cmd = uic_cmd;
2357 ufshcd_writel(hba, uic_cmd->argument1, REG_UIC_COMMAND_ARG_1);
2358 ufshcd_writel(hba, uic_cmd->argument2, REG_UIC_COMMAND_ARG_2);
2359 ufshcd_writel(hba, uic_cmd->argument3, REG_UIC_COMMAND_ARG_3);
2361 ufshcd_add_uic_command_trace(hba, uic_cmd, UFS_CMD_SEND);
2364 ufshcd_writel(hba, uic_cmd->command & COMMAND_OPCODE_MASK,
2369 * ufshcd_wait_for_uic_cmd - Wait for completion of an UIC command
2370 * @hba: per adapter instance
2371 * @uic_cmd: UIC command
2373 * Returns 0 only if success.
2376 ufshcd_wait_for_uic_cmd(struct ufs_hba *hba, struct uic_command *uic_cmd)
2379 unsigned long flags;
2381 lockdep_assert_held(&hba->uic_cmd_mutex);
2383 if (wait_for_completion_timeout(&uic_cmd->done,
2384 msecs_to_jiffies(UIC_CMD_TIMEOUT))) {
2385 ret = uic_cmd->argument2 & MASK_UIC_COMMAND_RESULT;
2389 "uic cmd 0x%x with arg3 0x%x completion timeout\n",
2390 uic_cmd->command, uic_cmd->argument3);
2392 if (!uic_cmd->cmd_active) {
2393 dev_err(hba->dev, "%s: UIC cmd has been completed, return the result\n",
2395 ret = uic_cmd->argument2 & MASK_UIC_COMMAND_RESULT;
2399 spin_lock_irqsave(hba->host->host_lock, flags);
2400 hba->active_uic_cmd = NULL;
2401 spin_unlock_irqrestore(hba->host->host_lock, flags);
2407 * __ufshcd_send_uic_cmd - Send UIC commands and retrieve the result
2408 * @hba: per adapter instance
2409 * @uic_cmd: UIC command
2410 * @completion: initialize the completion only if this is set to true
2412 * Returns 0 only if success.
2415 __ufshcd_send_uic_cmd(struct ufs_hba *hba, struct uic_command *uic_cmd,
2418 lockdep_assert_held(&hba->uic_cmd_mutex);
2419 lockdep_assert_held(hba->host->host_lock);
2421 if (!ufshcd_ready_for_uic_cmd(hba)) {
2423 "Controller not ready to accept UIC commands\n");
2428 init_completion(&uic_cmd->done);
2430 uic_cmd->cmd_active = 1;
2431 ufshcd_dispatch_uic_cmd(hba, uic_cmd);
2437 * ufshcd_send_uic_cmd - Send UIC commands and retrieve the result
2438 * @hba: per adapter instance
2439 * @uic_cmd: UIC command
2441 * Returns 0 only if success.
2443 int ufshcd_send_uic_cmd(struct ufs_hba *hba, struct uic_command *uic_cmd)
2446 unsigned long flags;
2448 if (hba->quirks & UFSHCD_QUIRK_BROKEN_UIC_CMD)
2452 mutex_lock(&hba->uic_cmd_mutex);
2453 ufshcd_add_delay_before_dme_cmd(hba);
2455 spin_lock_irqsave(hba->host->host_lock, flags);
2456 ret = __ufshcd_send_uic_cmd(hba, uic_cmd, true);
2457 spin_unlock_irqrestore(hba->host->host_lock, flags);
2459 ret = ufshcd_wait_for_uic_cmd(hba, uic_cmd);
2461 mutex_unlock(&hba->uic_cmd_mutex);
2463 ufshcd_release(hba);
2468 * ufshcd_sgl_to_prdt - SG list to PRTD (Physical Region Description Table, 4DW format)
2469 * @hba: per-adapter instance
2470 * @lrbp: pointer to local reference block
2471 * @sg_entries: The number of sg lists actually used
2472 * @sg_list: Pointer to SG list
2474 static void ufshcd_sgl_to_prdt(struct ufs_hba *hba, struct ufshcd_lrb *lrbp, int sg_entries,
2475 struct scatterlist *sg_list)
2477 struct ufshcd_sg_entry *prd;
2478 struct scatterlist *sg;
2483 if (hba->quirks & UFSHCD_QUIRK_PRDT_BYTE_GRAN)
2484 lrbp->utr_descriptor_ptr->prd_table_length =
2485 cpu_to_le16(sg_entries * ufshcd_sg_entry_size(hba));
2487 lrbp->utr_descriptor_ptr->prd_table_length = cpu_to_le16(sg_entries);
2489 prd = lrbp->ucd_prdt_ptr;
2491 for_each_sg(sg_list, sg, sg_entries, i) {
2492 const unsigned int len = sg_dma_len(sg);
2495 * From the UFSHCI spec: "Data Byte Count (DBC): A '0'
2496 * based value that indicates the length, in bytes, of
2497 * the data block. A maximum of length of 256KB may
2498 * exist for any entry. Bits 1:0 of this field shall be
2499 * 11b to indicate Dword granularity. A value of '3'
2500 * indicates 4 bytes, '7' indicates 8 bytes, etc."
2502 WARN_ONCE(len > SZ_256K, "len = %#x\n", len);
2503 prd->size = cpu_to_le32(len - 1);
2504 prd->addr = cpu_to_le64(sg->dma_address);
2506 prd = (void *)prd + ufshcd_sg_entry_size(hba);
2509 lrbp->utr_descriptor_ptr->prd_table_length = 0;
2514 * ufshcd_map_sg - Map scatter-gather list to prdt
2515 * @hba: per adapter instance
2516 * @lrbp: pointer to local reference block
2518 * Returns 0 in case of success, non-zero value in case of failure
2520 static int ufshcd_map_sg(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
2522 struct scsi_cmnd *cmd = lrbp->cmd;
2523 int sg_segments = scsi_dma_map(cmd);
2525 if (sg_segments < 0)
2528 ufshcd_sgl_to_prdt(hba, lrbp, sg_segments, scsi_sglist(cmd));
2534 * ufshcd_enable_intr - enable interrupts
2535 * @hba: per adapter instance
2536 * @intrs: interrupt bits
2538 static void ufshcd_enable_intr(struct ufs_hba *hba, u32 intrs)
2540 u32 set = ufshcd_readl(hba, REG_INTERRUPT_ENABLE);
2542 if (hba->ufs_version == ufshci_version(1, 0)) {
2544 rw = set & INTERRUPT_MASK_RW_VER_10;
2545 set = rw | ((set ^ intrs) & intrs);
2550 ufshcd_writel(hba, set, REG_INTERRUPT_ENABLE);
2554 * ufshcd_disable_intr - disable interrupts
2555 * @hba: per adapter instance
2556 * @intrs: interrupt bits
2558 static void ufshcd_disable_intr(struct ufs_hba *hba, u32 intrs)
2560 u32 set = ufshcd_readl(hba, REG_INTERRUPT_ENABLE);
2562 if (hba->ufs_version == ufshci_version(1, 0)) {
2564 rw = (set & INTERRUPT_MASK_RW_VER_10) &
2565 ~(intrs & INTERRUPT_MASK_RW_VER_10);
2566 set = rw | ((set & intrs) & ~INTERRUPT_MASK_RW_VER_10);
2572 ufshcd_writel(hba, set, REG_INTERRUPT_ENABLE);
2576 * ufshcd_prepare_req_desc_hdr - Fill UTP Transfer request descriptor header according to request
2577 * descriptor according to request
2578 * @lrbp: pointer to local reference block
2579 * @upiu_flags: flags required in the header
2580 * @cmd_dir: requests data direction
2581 * @ehs_length: Total EHS Length (in 32‐bytes units of all Extra Header Segments)
2583 static void ufshcd_prepare_req_desc_hdr(struct ufshcd_lrb *lrbp, u8 *upiu_flags,
2584 enum dma_data_direction cmd_dir, int ehs_length)
2586 struct utp_transfer_req_desc *req_desc = lrbp->utr_descriptor_ptr;
2592 if (cmd_dir == DMA_FROM_DEVICE) {
2593 data_direction = UTP_DEVICE_TO_HOST;
2594 *upiu_flags = UPIU_CMD_FLAGS_READ;
2595 } else if (cmd_dir == DMA_TO_DEVICE) {
2596 data_direction = UTP_HOST_TO_DEVICE;
2597 *upiu_flags = UPIU_CMD_FLAGS_WRITE;
2599 data_direction = UTP_NO_DATA_TRANSFER;
2600 *upiu_flags = UPIU_CMD_FLAGS_NONE;
2603 dword_0 = data_direction | (lrbp->command_type << UPIU_COMMAND_TYPE_OFFSET) |
2606 dword_0 |= UTP_REQ_DESC_INT_CMD;
2608 /* Prepare crypto related dwords */
2609 ufshcd_prepare_req_desc_hdr_crypto(lrbp, &dword_0, &dword_1, &dword_3);
2611 /* Transfer request descriptor header fields */
2612 req_desc->header.dword_0 = cpu_to_le32(dword_0);
2613 req_desc->header.dword_1 = cpu_to_le32(dword_1);
2615 * assigning invalid value for command status. Controller
2616 * updates OCS on command completion, with the command
2619 req_desc->header.dword_2 =
2620 cpu_to_le32(OCS_INVALID_COMMAND_STATUS);
2621 req_desc->header.dword_3 = cpu_to_le32(dword_3);
2623 req_desc->prd_table_length = 0;
2627 * ufshcd_prepare_utp_scsi_cmd_upiu() - fills the utp_transfer_req_desc,
2629 * @lrbp: local reference block pointer
2630 * @upiu_flags: flags
2633 void ufshcd_prepare_utp_scsi_cmd_upiu(struct ufshcd_lrb *lrbp, u8 upiu_flags)
2635 struct scsi_cmnd *cmd = lrbp->cmd;
2636 struct utp_upiu_req *ucd_req_ptr = lrbp->ucd_req_ptr;
2637 unsigned short cdb_len;
2639 /* command descriptor fields */
2640 ucd_req_ptr->header.dword_0 = UPIU_HEADER_DWORD(
2641 UPIU_TRANSACTION_COMMAND, upiu_flags,
2642 lrbp->lun, lrbp->task_tag);
2643 ucd_req_ptr->header.dword_1 = UPIU_HEADER_DWORD(
2644 UPIU_COMMAND_SET_TYPE_SCSI, 0, 0, 0);
2646 /* Total EHS length and Data segment length will be zero */
2647 ucd_req_ptr->header.dword_2 = 0;
2649 ucd_req_ptr->sc.exp_data_transfer_len = cpu_to_be32(cmd->sdb.length);
2651 cdb_len = min_t(unsigned short, cmd->cmd_len, UFS_CDB_SIZE);
2652 memset(ucd_req_ptr->sc.cdb, 0, UFS_CDB_SIZE);
2653 memcpy(ucd_req_ptr->sc.cdb, cmd->cmnd, cdb_len);
2655 memset(lrbp->ucd_rsp_ptr, 0, sizeof(struct utp_upiu_rsp));
2659 * ufshcd_prepare_utp_query_req_upiu() - fill the utp_transfer_req_desc for query request
2661 * @lrbp: local reference block pointer
2662 * @upiu_flags: flags
2664 static void ufshcd_prepare_utp_query_req_upiu(struct ufs_hba *hba,
2665 struct ufshcd_lrb *lrbp, u8 upiu_flags)
2667 struct utp_upiu_req *ucd_req_ptr = lrbp->ucd_req_ptr;
2668 struct ufs_query *query = &hba->dev_cmd.query;
2669 u16 len = be16_to_cpu(query->request.upiu_req.length);
2671 /* Query request header */
2672 ucd_req_ptr->header.dword_0 = UPIU_HEADER_DWORD(
2673 UPIU_TRANSACTION_QUERY_REQ, upiu_flags,
2674 lrbp->lun, lrbp->task_tag);
2675 ucd_req_ptr->header.dword_1 = UPIU_HEADER_DWORD(
2676 0, query->request.query_func, 0, 0);
2678 /* Data segment length only need for WRITE_DESC */
2679 if (query->request.upiu_req.opcode == UPIU_QUERY_OPCODE_WRITE_DESC)
2680 ucd_req_ptr->header.dword_2 =
2681 UPIU_HEADER_DWORD(0, 0, (len >> 8), (u8)len);
2683 ucd_req_ptr->header.dword_2 = 0;
2685 /* Copy the Query Request buffer as is */
2686 memcpy(&ucd_req_ptr->qr, &query->request.upiu_req,
2689 /* Copy the Descriptor */
2690 if (query->request.upiu_req.opcode == UPIU_QUERY_OPCODE_WRITE_DESC)
2691 memcpy(ucd_req_ptr + 1, query->descriptor, len);
2693 memset(lrbp->ucd_rsp_ptr, 0, sizeof(struct utp_upiu_rsp));
2696 static inline void ufshcd_prepare_utp_nop_upiu(struct ufshcd_lrb *lrbp)
2698 struct utp_upiu_req *ucd_req_ptr = lrbp->ucd_req_ptr;
2700 memset(ucd_req_ptr, 0, sizeof(struct utp_upiu_req));
2702 /* command descriptor fields */
2703 ucd_req_ptr->header.dword_0 =
2705 UPIU_TRANSACTION_NOP_OUT, 0, 0, lrbp->task_tag);
2706 /* clear rest of the fields of basic header */
2707 ucd_req_ptr->header.dword_1 = 0;
2708 ucd_req_ptr->header.dword_2 = 0;
2710 memset(lrbp->ucd_rsp_ptr, 0, sizeof(struct utp_upiu_rsp));
2714 * ufshcd_compose_devman_upiu - UFS Protocol Information Unit(UPIU)
2715 * for Device Management Purposes
2716 * @hba: per adapter instance
2717 * @lrbp: pointer to local reference block
2719 static int ufshcd_compose_devman_upiu(struct ufs_hba *hba,
2720 struct ufshcd_lrb *lrbp)
2725 if (hba->ufs_version <= ufshci_version(1, 1))
2726 lrbp->command_type = UTP_CMD_TYPE_DEV_MANAGE;
2728 lrbp->command_type = UTP_CMD_TYPE_UFS_STORAGE;
2730 ufshcd_prepare_req_desc_hdr(lrbp, &upiu_flags, DMA_NONE, 0);
2731 if (hba->dev_cmd.type == DEV_CMD_TYPE_QUERY)
2732 ufshcd_prepare_utp_query_req_upiu(hba, lrbp, upiu_flags);
2733 else if (hba->dev_cmd.type == DEV_CMD_TYPE_NOP)
2734 ufshcd_prepare_utp_nop_upiu(lrbp);
2742 * ufshcd_comp_scsi_upiu - UFS Protocol Information Unit(UPIU)
2744 * @hba: per adapter instance
2745 * @lrbp: pointer to local reference block
2747 static int ufshcd_comp_scsi_upiu(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
2752 if (hba->ufs_version <= ufshci_version(1, 1))
2753 lrbp->command_type = UTP_CMD_TYPE_SCSI;
2755 lrbp->command_type = UTP_CMD_TYPE_UFS_STORAGE;
2757 if (likely(lrbp->cmd)) {
2758 ufshcd_prepare_req_desc_hdr(lrbp, &upiu_flags, lrbp->cmd->sc_data_direction, 0);
2759 ufshcd_prepare_utp_scsi_cmd_upiu(lrbp, upiu_flags);
2768 * ufshcd_upiu_wlun_to_scsi_wlun - maps UPIU W-LUN id to SCSI W-LUN ID
2769 * @upiu_wlun_id: UPIU W-LUN id
2771 * Returns SCSI W-LUN id
2773 static inline u16 ufshcd_upiu_wlun_to_scsi_wlun(u8 upiu_wlun_id)
2775 return (upiu_wlun_id & ~UFS_UPIU_WLUN_ID) | SCSI_W_LUN_BASE;
2778 static inline bool is_device_wlun(struct scsi_device *sdev)
2781 ufshcd_upiu_wlun_to_scsi_wlun(UFS_UPIU_UFS_DEVICE_WLUN);
2785 * Associate the UFS controller queue with the default and poll HCTX types.
2786 * Initialize the mq_map[] arrays.
2788 static void ufshcd_map_queues(struct Scsi_Host *shost)
2790 struct ufs_hba *hba = shost_priv(shost);
2791 int i, queue_offset = 0;
2793 if (!is_mcq_supported(hba)) {
2794 hba->nr_queues[HCTX_TYPE_DEFAULT] = 1;
2795 hba->nr_queues[HCTX_TYPE_READ] = 0;
2796 hba->nr_queues[HCTX_TYPE_POLL] = 1;
2797 hba->nr_hw_queues = 1;
2800 for (i = 0; i < shost->nr_maps; i++) {
2801 struct blk_mq_queue_map *map = &shost->tag_set.map[i];
2803 map->nr_queues = hba->nr_queues[i];
2804 if (!map->nr_queues)
2806 map->queue_offset = queue_offset;
2807 if (i == HCTX_TYPE_POLL && !is_mcq_supported(hba))
2808 map->queue_offset = 0;
2810 blk_mq_map_queues(map);
2811 queue_offset += map->nr_queues;
2815 static void ufshcd_init_lrb(struct ufs_hba *hba, struct ufshcd_lrb *lrb, int i)
2817 struct utp_transfer_cmd_desc *cmd_descp = (void *)hba->ucdl_base_addr +
2818 i * ufshcd_get_ucd_size(hba);
2819 struct utp_transfer_req_desc *utrdlp = hba->utrdl_base_addr;
2820 dma_addr_t cmd_desc_element_addr = hba->ucdl_dma_addr +
2821 i * ufshcd_get_ucd_size(hba);
2822 u16 response_offset = offsetof(struct utp_transfer_cmd_desc,
2824 u16 prdt_offset = offsetof(struct utp_transfer_cmd_desc, prd_table);
2826 lrb->utr_descriptor_ptr = utrdlp + i;
2827 lrb->utrd_dma_addr = hba->utrdl_dma_addr +
2828 i * sizeof(struct utp_transfer_req_desc);
2829 lrb->ucd_req_ptr = (struct utp_upiu_req *)cmd_descp->command_upiu;
2830 lrb->ucd_req_dma_addr = cmd_desc_element_addr;
2831 lrb->ucd_rsp_ptr = (struct utp_upiu_rsp *)cmd_descp->response_upiu;
2832 lrb->ucd_rsp_dma_addr = cmd_desc_element_addr + response_offset;
2833 lrb->ucd_prdt_ptr = (struct ufshcd_sg_entry *)cmd_descp->prd_table;
2834 lrb->ucd_prdt_dma_addr = cmd_desc_element_addr + prdt_offset;
2838 * ufshcd_queuecommand - main entry point for SCSI requests
2839 * @host: SCSI host pointer
2840 * @cmd: command from SCSI Midlayer
2842 * Returns 0 for success, non-zero in case of failure
2844 static int ufshcd_queuecommand(struct Scsi_Host *host, struct scsi_cmnd *cmd)
2846 struct ufs_hba *hba = shost_priv(host);
2847 int tag = scsi_cmd_to_rq(cmd)->tag;
2848 struct ufshcd_lrb *lrbp;
2850 struct ufs_hw_queue *hwq = NULL;
2852 WARN_ONCE(tag < 0 || tag >= hba->nutrs, "Invalid tag %d\n", tag);
2854 switch (hba->ufshcd_state) {
2855 case UFSHCD_STATE_OPERATIONAL:
2857 case UFSHCD_STATE_EH_SCHEDULED_NON_FATAL:
2859 * SCSI error handler can call ->queuecommand() while UFS error
2860 * handler is in progress. Error interrupts could change the
2861 * state from UFSHCD_STATE_RESET to
2862 * UFSHCD_STATE_EH_SCHEDULED_NON_FATAL. Prevent requests
2863 * being issued in that case.
2865 if (ufshcd_eh_in_progress(hba)) {
2866 err = SCSI_MLQUEUE_HOST_BUSY;
2870 case UFSHCD_STATE_EH_SCHEDULED_FATAL:
2872 * pm_runtime_get_sync() is used at error handling preparation
2873 * stage. If a scsi cmd, e.g. the SSU cmd, is sent from hba's
2874 * PM ops, it can never be finished if we let SCSI layer keep
2875 * retrying it, which gets err handler stuck forever. Neither
2876 * can we let the scsi cmd pass through, because UFS is in bad
2877 * state, the scsi cmd may eventually time out, which will get
2878 * err handler blocked for too long. So, just fail the scsi cmd
2879 * sent from PM ops, err handler can recover PM error anyways.
2881 if (hba->pm_op_in_progress) {
2882 hba->force_reset = true;
2883 set_host_byte(cmd, DID_BAD_TARGET);
2888 case UFSHCD_STATE_RESET:
2889 err = SCSI_MLQUEUE_HOST_BUSY;
2891 case UFSHCD_STATE_ERROR:
2892 set_host_byte(cmd, DID_ERROR);
2897 hba->req_abort_count = 0;
2901 lrbp = &hba->lrb[tag];
2903 lrbp->task_tag = tag;
2904 lrbp->lun = ufshcd_scsi_to_upiu_lun(cmd->device->lun);
2905 lrbp->intr_cmd = !ufshcd_is_intr_aggr_allowed(hba);
2907 ufshcd_prepare_lrbp_crypto(scsi_cmd_to_rq(cmd), lrbp);
2909 lrbp->req_abort_skip = false;
2911 ufshpb_prep(hba, lrbp);
2913 ufshcd_comp_scsi_upiu(hba, lrbp);
2915 err = ufshcd_map_sg(hba, lrbp);
2917 ufshcd_release(hba);
2921 if (is_mcq_enabled(hba))
2922 hwq = ufshcd_mcq_req_to_hwq(hba, scsi_cmd_to_rq(cmd));
2924 ufshcd_send_command(hba, tag, hwq);
2927 if (ufs_trigger_eh()) {
2928 unsigned long flags;
2930 spin_lock_irqsave(hba->host->host_lock, flags);
2931 ufshcd_schedule_eh_work(hba);
2932 spin_unlock_irqrestore(hba->host->host_lock, flags);
2938 static int ufshcd_compose_dev_cmd(struct ufs_hba *hba,
2939 struct ufshcd_lrb *lrbp, enum dev_cmd_type cmd_type, int tag)
2942 lrbp->task_tag = tag;
2943 lrbp->lun = 0; /* device management cmd is not specific to any LUN */
2944 lrbp->intr_cmd = true; /* No interrupt aggregation */
2945 ufshcd_prepare_lrbp_crypto(NULL, lrbp);
2946 hba->dev_cmd.type = cmd_type;
2948 return ufshcd_compose_devman_upiu(hba, lrbp);
2952 * Check with the block layer if the command is inflight
2953 * @cmd: command to check.
2955 * Returns true if command is inflight; false if not.
2957 bool ufshcd_cmd_inflight(struct scsi_cmnd *cmd)
2964 rq = scsi_cmd_to_rq(cmd);
2965 if (!blk_mq_request_started(rq))
2972 * Clear the pending command in the controller and wait until
2973 * the controller confirms that the command has been cleared.
2974 * @hba: per adapter instance
2975 * @task_tag: The tag number of the command to be cleared.
2977 static int ufshcd_clear_cmd(struct ufs_hba *hba, u32 task_tag)
2979 u32 mask = 1U << task_tag;
2980 unsigned long flags;
2983 if (is_mcq_enabled(hba)) {
2985 * MCQ mode. Clean up the MCQ resources similar to
2986 * what the ufshcd_utrl_clear() does for SDB mode.
2988 err = ufshcd_mcq_sq_cleanup(hba, task_tag);
2990 dev_err(hba->dev, "%s: failed tag=%d. err=%d\n",
2991 __func__, task_tag, err);
2997 /* clear outstanding transaction before retry */
2998 spin_lock_irqsave(hba->host->host_lock, flags);
2999 ufshcd_utrl_clear(hba, mask);
3000 spin_unlock_irqrestore(hba->host->host_lock, flags);
3003 * wait for h/w to clear corresponding bit in door-bell.
3004 * max. wait is 1 sec.
3006 return ufshcd_wait_for_register(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL,
3007 mask, ~mask, 1000, 1000);
3011 ufshcd_check_query_response(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
3013 struct ufs_query_res *query_res = &hba->dev_cmd.query.response;
3015 /* Get the UPIU response */
3016 query_res->response = ufshcd_get_rsp_upiu_result(lrbp->ucd_rsp_ptr) >>
3017 UPIU_RSP_CODE_OFFSET;
3018 return query_res->response;
3022 * ufshcd_dev_cmd_completion() - handles device management command responses
3023 * @hba: per adapter instance
3024 * @lrbp: pointer to local reference block
3027 ufshcd_dev_cmd_completion(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
3032 hba->ufs_stats.last_hibern8_exit_tstamp = ktime_set(0, 0);
3033 resp = ufshcd_get_req_rsp(lrbp->ucd_rsp_ptr);
3036 case UPIU_TRANSACTION_NOP_IN:
3037 if (hba->dev_cmd.type != DEV_CMD_TYPE_NOP) {
3039 dev_err(hba->dev, "%s: unexpected response %x\n",
3043 case UPIU_TRANSACTION_QUERY_RSP:
3044 err = ufshcd_check_query_response(hba, lrbp);
3046 err = ufshcd_copy_query_response(hba, lrbp);
3048 case UPIU_TRANSACTION_REJECT_UPIU:
3049 /* TODO: handle Reject UPIU Response */
3051 dev_err(hba->dev, "%s: Reject UPIU not fully implemented\n",
3054 case UPIU_TRANSACTION_RESPONSE:
3055 if (hba->dev_cmd.type != DEV_CMD_TYPE_RPMB) {
3057 dev_err(hba->dev, "%s: unexpected response %x\n", __func__, resp);
3062 dev_err(hba->dev, "%s: Invalid device management cmd response: %x\n",
3070 static int ufshcd_wait_for_dev_cmd(struct ufs_hba *hba,
3071 struct ufshcd_lrb *lrbp, int max_timeout)
3073 unsigned long time_left = msecs_to_jiffies(max_timeout);
3074 unsigned long flags;
3079 time_left = wait_for_completion_timeout(hba->dev_cmd.complete,
3082 if (likely(time_left)) {
3084 * The completion handler called complete() and the caller of
3085 * this function still owns the @lrbp tag so the code below does
3086 * not trigger any race conditions.
3088 hba->dev_cmd.complete = NULL;
3089 err = ufshcd_get_tr_ocs(lrbp, NULL);
3091 err = ufshcd_dev_cmd_completion(hba, lrbp);
3094 dev_dbg(hba->dev, "%s: dev_cmd request timedout, tag %d\n",
3095 __func__, lrbp->task_tag);
3098 if (is_mcq_enabled(hba)) {
3099 err = ufshcd_clear_cmd(hba, lrbp->task_tag);
3100 hba->dev_cmd.complete = NULL;
3105 if (ufshcd_clear_cmd(hba, lrbp->task_tag) == 0) {
3106 /* successfully cleared the command, retry if needed */
3109 * Since clearing the command succeeded we also need to
3110 * clear the task tag bit from the outstanding_reqs
3113 spin_lock_irqsave(&hba->outstanding_lock, flags);
3114 pending = test_bit(lrbp->task_tag,
3115 &hba->outstanding_reqs);
3117 hba->dev_cmd.complete = NULL;
3118 __clear_bit(lrbp->task_tag,
3119 &hba->outstanding_reqs);
3121 spin_unlock_irqrestore(&hba->outstanding_lock, flags);
3125 * The completion handler ran while we tried to
3126 * clear the command.
3132 dev_err(hba->dev, "%s: failed to clear tag %d\n",
3133 __func__, lrbp->task_tag);
3135 spin_lock_irqsave(&hba->outstanding_lock, flags);
3136 pending = test_bit(lrbp->task_tag,
3137 &hba->outstanding_reqs);
3139 hba->dev_cmd.complete = NULL;
3140 spin_unlock_irqrestore(&hba->outstanding_lock, flags);
3144 * The completion handler ran while we tried to
3145 * clear the command.
3157 * ufshcd_exec_dev_cmd - API for sending device management requests
3159 * @cmd_type: specifies the type (NOP, Query...)
3160 * @timeout: timeout in milliseconds
3162 * NOTE: Since there is only one available tag for device management commands,
3163 * it is expected you hold the hba->dev_cmd.lock mutex.
3165 static int ufshcd_exec_dev_cmd(struct ufs_hba *hba,
3166 enum dev_cmd_type cmd_type, int timeout)
3168 DECLARE_COMPLETION_ONSTACK(wait);
3169 const u32 tag = hba->reserved_slot;
3170 struct ufshcd_lrb *lrbp;
3173 /* Protects use of hba->reserved_slot. */
3174 lockdep_assert_held(&hba->dev_cmd.lock);
3176 down_read(&hba->clk_scaling_lock);
3178 lrbp = &hba->lrb[tag];
3180 err = ufshcd_compose_dev_cmd(hba, lrbp, cmd_type, tag);
3184 hba->dev_cmd.complete = &wait;
3186 ufshcd_add_query_upiu_trace(hba, UFS_QUERY_SEND, lrbp->ucd_req_ptr);
3188 ufshcd_send_command(hba, tag, hba->dev_cmd_queue);
3189 err = ufshcd_wait_for_dev_cmd(hba, lrbp, timeout);
3190 ufshcd_add_query_upiu_trace(hba, err ? UFS_QUERY_ERR : UFS_QUERY_COMP,
3191 (struct utp_upiu_req *)lrbp->ucd_rsp_ptr);
3194 up_read(&hba->clk_scaling_lock);
3199 * ufshcd_init_query() - init the query response and request parameters
3200 * @hba: per-adapter instance
3201 * @request: address of the request pointer to be initialized
3202 * @response: address of the response pointer to be initialized
3203 * @opcode: operation to perform
3204 * @idn: flag idn to access
3205 * @index: LU number to access
3206 * @selector: query/flag/descriptor further identification
3208 static inline void ufshcd_init_query(struct ufs_hba *hba,
3209 struct ufs_query_req **request, struct ufs_query_res **response,
3210 enum query_opcode opcode, u8 idn, u8 index, u8 selector)
3212 *request = &hba->dev_cmd.query.request;
3213 *response = &hba->dev_cmd.query.response;
3214 memset(*request, 0, sizeof(struct ufs_query_req));
3215 memset(*response, 0, sizeof(struct ufs_query_res));
3216 (*request)->upiu_req.opcode = opcode;
3217 (*request)->upiu_req.idn = idn;
3218 (*request)->upiu_req.index = index;
3219 (*request)->upiu_req.selector = selector;
3222 static int ufshcd_query_flag_retry(struct ufs_hba *hba,
3223 enum query_opcode opcode, enum flag_idn idn, u8 index, bool *flag_res)
3228 for (retries = 0; retries < QUERY_REQ_RETRIES; retries++) {
3229 ret = ufshcd_query_flag(hba, opcode, idn, index, flag_res);
3232 "%s: failed with error %d, retries %d\n",
3233 __func__, ret, retries);
3240 "%s: query flag, opcode %d, idn %d, failed with error %d after %d retries\n",
3241 __func__, opcode, idn, ret, retries);
3246 * ufshcd_query_flag() - API function for sending flag query requests
3247 * @hba: per-adapter instance
3248 * @opcode: flag query to perform
3249 * @idn: flag idn to access
3250 * @index: flag index to access
3251 * @flag_res: the flag value after the query request completes
3253 * Returns 0 for success, non-zero in case of failure
3255 int ufshcd_query_flag(struct ufs_hba *hba, enum query_opcode opcode,
3256 enum flag_idn idn, u8 index, bool *flag_res)
3258 struct ufs_query_req *request = NULL;
3259 struct ufs_query_res *response = NULL;
3260 int err, selector = 0;
3261 int timeout = QUERY_REQ_TIMEOUT;
3266 mutex_lock(&hba->dev_cmd.lock);
3267 ufshcd_init_query(hba, &request, &response, opcode, idn, index,
3271 case UPIU_QUERY_OPCODE_SET_FLAG:
3272 case UPIU_QUERY_OPCODE_CLEAR_FLAG:
3273 case UPIU_QUERY_OPCODE_TOGGLE_FLAG:
3274 request->query_func = UPIU_QUERY_FUNC_STANDARD_WRITE_REQUEST;
3276 case UPIU_QUERY_OPCODE_READ_FLAG:
3277 request->query_func = UPIU_QUERY_FUNC_STANDARD_READ_REQUEST;
3279 /* No dummy reads */
3280 dev_err(hba->dev, "%s: Invalid argument for read request\n",
3288 "%s: Expected query flag opcode but got = %d\n",
3294 err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_QUERY, timeout);
3298 "%s: Sending flag query for idn %d failed, err = %d\n",
3299 __func__, idn, err);
3304 *flag_res = (be32_to_cpu(response->upiu_res.value) &
3305 MASK_QUERY_UPIU_FLAG_LOC) & 0x1;
3308 mutex_unlock(&hba->dev_cmd.lock);
3309 ufshcd_release(hba);
3314 * ufshcd_query_attr - API function for sending attribute requests
3315 * @hba: per-adapter instance
3316 * @opcode: attribute opcode
3317 * @idn: attribute idn to access
3318 * @index: index field
3319 * @selector: selector field
3320 * @attr_val: the attribute value after the query request completes
3322 * Returns 0 for success, non-zero in case of failure
3324 int ufshcd_query_attr(struct ufs_hba *hba, enum query_opcode opcode,
3325 enum attr_idn idn, u8 index, u8 selector, u32 *attr_val)
3327 struct ufs_query_req *request = NULL;
3328 struct ufs_query_res *response = NULL;
3334 dev_err(hba->dev, "%s: attribute value required for opcode 0x%x\n",
3341 mutex_lock(&hba->dev_cmd.lock);
3342 ufshcd_init_query(hba, &request, &response, opcode, idn, index,
3346 case UPIU_QUERY_OPCODE_WRITE_ATTR:
3347 request->query_func = UPIU_QUERY_FUNC_STANDARD_WRITE_REQUEST;
3348 request->upiu_req.value = cpu_to_be32(*attr_val);
3350 case UPIU_QUERY_OPCODE_READ_ATTR:
3351 request->query_func = UPIU_QUERY_FUNC_STANDARD_READ_REQUEST;
3354 dev_err(hba->dev, "%s: Expected query attr opcode but got = 0x%.2x\n",
3360 err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_QUERY, QUERY_REQ_TIMEOUT);
3363 dev_err(hba->dev, "%s: opcode 0x%.2x for idn %d failed, index %d, err = %d\n",
3364 __func__, opcode, idn, index, err);
3368 *attr_val = be32_to_cpu(response->upiu_res.value);
3371 mutex_unlock(&hba->dev_cmd.lock);
3372 ufshcd_release(hba);
3377 * ufshcd_query_attr_retry() - API function for sending query
3378 * attribute with retries
3379 * @hba: per-adapter instance
3380 * @opcode: attribute opcode
3381 * @idn: attribute idn to access
3382 * @index: index field
3383 * @selector: selector field
3384 * @attr_val: the attribute value after the query request
3387 * Returns 0 for success, non-zero in case of failure
3389 int ufshcd_query_attr_retry(struct ufs_hba *hba,
3390 enum query_opcode opcode, enum attr_idn idn, u8 index, u8 selector,
3396 for (retries = QUERY_REQ_RETRIES; retries > 0; retries--) {
3397 ret = ufshcd_query_attr(hba, opcode, idn, index,
3398 selector, attr_val);
3400 dev_dbg(hba->dev, "%s: failed with error %d, retries %d\n",
3401 __func__, ret, retries);
3408 "%s: query attribute, idn %d, failed with error %d after %d retries\n",
3409 __func__, idn, ret, QUERY_REQ_RETRIES);
3413 static int __ufshcd_query_descriptor(struct ufs_hba *hba,
3414 enum query_opcode opcode, enum desc_idn idn, u8 index,
3415 u8 selector, u8 *desc_buf, int *buf_len)
3417 struct ufs_query_req *request = NULL;
3418 struct ufs_query_res *response = NULL;
3424 dev_err(hba->dev, "%s: descriptor buffer required for opcode 0x%x\n",
3429 if (*buf_len < QUERY_DESC_MIN_SIZE || *buf_len > QUERY_DESC_MAX_SIZE) {
3430 dev_err(hba->dev, "%s: descriptor buffer size (%d) is out of range\n",
3431 __func__, *buf_len);
3437 mutex_lock(&hba->dev_cmd.lock);
3438 ufshcd_init_query(hba, &request, &response, opcode, idn, index,
3440 hba->dev_cmd.query.descriptor = desc_buf;
3441 request->upiu_req.length = cpu_to_be16(*buf_len);
3444 case UPIU_QUERY_OPCODE_WRITE_DESC:
3445 request->query_func = UPIU_QUERY_FUNC_STANDARD_WRITE_REQUEST;
3447 case UPIU_QUERY_OPCODE_READ_DESC:
3448 request->query_func = UPIU_QUERY_FUNC_STANDARD_READ_REQUEST;
3452 "%s: Expected query descriptor opcode but got = 0x%.2x\n",
3458 err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_QUERY, QUERY_REQ_TIMEOUT);
3461 dev_err(hba->dev, "%s: opcode 0x%.2x for idn %d failed, index %d, err = %d\n",
3462 __func__, opcode, idn, index, err);
3466 *buf_len = be16_to_cpu(response->upiu_res.length);
3469 hba->dev_cmd.query.descriptor = NULL;
3470 mutex_unlock(&hba->dev_cmd.lock);
3471 ufshcd_release(hba);
3476 * ufshcd_query_descriptor_retry - API function for sending descriptor requests
3477 * @hba: per-adapter instance
3478 * @opcode: attribute opcode
3479 * @idn: attribute idn to access
3480 * @index: index field
3481 * @selector: selector field
3482 * @desc_buf: the buffer that contains the descriptor
3483 * @buf_len: length parameter passed to the device
3485 * Returns 0 for success, non-zero in case of failure.
3486 * The buf_len parameter will contain, on return, the length parameter
3487 * received on the response.
3489 int ufshcd_query_descriptor_retry(struct ufs_hba *hba,
3490 enum query_opcode opcode,
3491 enum desc_idn idn, u8 index,
3493 u8 *desc_buf, int *buf_len)
3498 for (retries = QUERY_REQ_RETRIES; retries > 0; retries--) {
3499 err = __ufshcd_query_descriptor(hba, opcode, idn, index,
3500 selector, desc_buf, buf_len);
3501 if (!err || err == -EINVAL)
3509 * ufshcd_read_desc_param - read the specified descriptor parameter
3510 * @hba: Pointer to adapter instance
3511 * @desc_id: descriptor idn value
3512 * @desc_index: descriptor index
3513 * @param_offset: offset of the parameter to read
3514 * @param_read_buf: pointer to buffer where parameter would be read
3515 * @param_size: sizeof(param_read_buf)
3517 * Return 0 in case of success, non-zero otherwise
3519 int ufshcd_read_desc_param(struct ufs_hba *hba,
3520 enum desc_idn desc_id,
3528 int buff_len = QUERY_DESC_MAX_SIZE;
3529 bool is_kmalloc = true;
3532 if (desc_id >= QUERY_DESC_IDN_MAX || !param_size)
3535 /* Check whether we need temp memory */
3536 if (param_offset != 0 || param_size < buff_len) {
3537 desc_buf = kzalloc(buff_len, GFP_KERNEL);
3541 desc_buf = param_read_buf;
3545 /* Request for full descriptor */
3546 ret = ufshcd_query_descriptor_retry(hba, UPIU_QUERY_OPCODE_READ_DESC,
3547 desc_id, desc_index, 0,
3548 desc_buf, &buff_len);
3550 dev_err(hba->dev, "%s: Failed reading descriptor. desc_id %d, desc_index %d, param_offset %d, ret %d\n",
3551 __func__, desc_id, desc_index, param_offset, ret);
3555 /* Update descriptor length */
3556 buff_len = desc_buf[QUERY_DESC_LENGTH_OFFSET];
3558 if (param_offset >= buff_len) {
3559 dev_err(hba->dev, "%s: Invalid offset 0x%x in descriptor IDN 0x%x, length 0x%x\n",
3560 __func__, param_offset, desc_id, buff_len);
3566 if (desc_buf[QUERY_DESC_DESC_TYPE_OFFSET] != desc_id) {
3567 dev_err(hba->dev, "%s: invalid desc_id %d in descriptor header\n",
3568 __func__, desc_buf[QUERY_DESC_DESC_TYPE_OFFSET]);
3574 /* Make sure we don't copy more data than available */
3575 if (param_offset >= buff_len)
3578 memcpy(param_read_buf, &desc_buf[param_offset],
3579 min_t(u32, param_size, buff_len - param_offset));
3588 * struct uc_string_id - unicode string
3590 * @len: size of this descriptor inclusive
3591 * @type: descriptor type
3592 * @uc: unicode string character
3594 struct uc_string_id {
3600 /* replace non-printable or non-ASCII characters with spaces */
3601 static inline char ufshcd_remove_non_printable(u8 ch)
3603 return (ch >= 0x20 && ch <= 0x7e) ? ch : ' ';
3607 * ufshcd_read_string_desc - read string descriptor
3608 * @hba: pointer to adapter instance
3609 * @desc_index: descriptor index
3610 * @buf: pointer to buffer where descriptor would be read,
3611 * the caller should free the memory.
3612 * @ascii: if true convert from unicode to ascii characters
3613 * null terminated string.
3616 * * string size on success.
3617 * * -ENOMEM: on allocation failure
3618 * * -EINVAL: on a wrong parameter
3620 int ufshcd_read_string_desc(struct ufs_hba *hba, u8 desc_index,
3621 u8 **buf, bool ascii)
3623 struct uc_string_id *uc_str;
3630 uc_str = kzalloc(QUERY_DESC_MAX_SIZE, GFP_KERNEL);
3634 ret = ufshcd_read_desc_param(hba, QUERY_DESC_IDN_STRING, desc_index, 0,
3635 (u8 *)uc_str, QUERY_DESC_MAX_SIZE);
3637 dev_err(hba->dev, "Reading String Desc failed after %d retries. err = %d\n",
3638 QUERY_REQ_RETRIES, ret);
3643 if (uc_str->len <= QUERY_DESC_HDR_SIZE) {
3644 dev_dbg(hba->dev, "String Desc is of zero length\n");
3653 /* remove header and divide by 2 to move from UTF16 to UTF8 */
3654 ascii_len = (uc_str->len - QUERY_DESC_HDR_SIZE) / 2 + 1;
3655 str = kzalloc(ascii_len, GFP_KERNEL);
3662 * the descriptor contains string in UTF16 format
3663 * we need to convert to utf-8 so it can be displayed
3665 ret = utf16s_to_utf8s(uc_str->uc,
3666 uc_str->len - QUERY_DESC_HDR_SIZE,
3667 UTF16_BIG_ENDIAN, str, ascii_len);
3669 /* replace non-printable or non-ASCII characters with spaces */
3670 for (i = 0; i < ret; i++)
3671 str[i] = ufshcd_remove_non_printable(str[i]);
3676 str = kmemdup(uc_str, uc_str->len, GFP_KERNEL);
3690 * ufshcd_read_unit_desc_param - read the specified unit descriptor parameter
3691 * @hba: Pointer to adapter instance
3693 * @param_offset: offset of the parameter to read
3694 * @param_read_buf: pointer to buffer where parameter would be read
3695 * @param_size: sizeof(param_read_buf)
3697 * Return 0 in case of success, non-zero otherwise
3699 static inline int ufshcd_read_unit_desc_param(struct ufs_hba *hba,
3701 enum unit_desc_param param_offset,
3706 * Unit descriptors are only available for general purpose LUs (LUN id
3707 * from 0 to 7) and RPMB Well known LU.
3709 if (!ufs_is_valid_unit_desc_lun(&hba->dev_info, lun))
3712 return ufshcd_read_desc_param(hba, QUERY_DESC_IDN_UNIT, lun,
3713 param_offset, param_read_buf, param_size);
3716 static int ufshcd_get_ref_clk_gating_wait(struct ufs_hba *hba)
3719 u32 gating_wait = UFSHCD_REF_CLK_GATING_WAIT_US;
3721 if (hba->dev_info.wspecversion >= 0x300) {
3722 err = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
3723 QUERY_ATTR_IDN_REF_CLK_GATING_WAIT_TIME, 0, 0,
3726 dev_err(hba->dev, "Failed reading bRefClkGatingWait. err = %d, use default %uus\n",
3729 if (gating_wait == 0) {
3730 gating_wait = UFSHCD_REF_CLK_GATING_WAIT_US;
3731 dev_err(hba->dev, "Undefined ref clk gating wait time, use default %uus\n",
3735 hba->dev_info.clk_gating_wait_us = gating_wait;
3742 * ufshcd_memory_alloc - allocate memory for host memory space data structures
3743 * @hba: per adapter instance
3745 * 1. Allocate DMA memory for Command Descriptor array
3746 * Each command descriptor consist of Command UPIU, Response UPIU and PRDT
3747 * 2. Allocate DMA memory for UTP Transfer Request Descriptor List (UTRDL).
3748 * 3. Allocate DMA memory for UTP Task Management Request Descriptor List
3750 * 4. Allocate memory for local reference block(lrb).
3752 * Returns 0 for success, non-zero in case of failure
3754 static int ufshcd_memory_alloc(struct ufs_hba *hba)
3756 size_t utmrdl_size, utrdl_size, ucdl_size;
3758 /* Allocate memory for UTP command descriptors */
3759 ucdl_size = ufshcd_get_ucd_size(hba) * hba->nutrs;
3760 hba->ucdl_base_addr = dmam_alloc_coherent(hba->dev,
3762 &hba->ucdl_dma_addr,
3766 * UFSHCI requires UTP command descriptor to be 128 byte aligned.
3768 if (!hba->ucdl_base_addr ||
3769 WARN_ON(hba->ucdl_dma_addr & (128 - 1))) {
3771 "Command Descriptor Memory allocation failed\n");
3776 * Allocate memory for UTP Transfer descriptors
3777 * UFSHCI requires 1KB alignment of UTRD
3779 utrdl_size = (sizeof(struct utp_transfer_req_desc) * hba->nutrs);
3780 hba->utrdl_base_addr = dmam_alloc_coherent(hba->dev,
3782 &hba->utrdl_dma_addr,
3784 if (!hba->utrdl_base_addr ||
3785 WARN_ON(hba->utrdl_dma_addr & (SZ_1K - 1))) {
3787 "Transfer Descriptor Memory allocation failed\n");
3792 * Skip utmrdl allocation; it may have been
3793 * allocated during first pass and not released during
3794 * MCQ memory allocation.
3795 * See ufshcd_release_sdb_queue() and ufshcd_config_mcq()
3797 if (hba->utmrdl_base_addr)
3800 * Allocate memory for UTP Task Management descriptors
3801 * UFSHCI requires 1KB alignment of UTMRD
3803 utmrdl_size = sizeof(struct utp_task_req_desc) * hba->nutmrs;
3804 hba->utmrdl_base_addr = dmam_alloc_coherent(hba->dev,
3806 &hba->utmrdl_dma_addr,
3808 if (!hba->utmrdl_base_addr ||
3809 WARN_ON(hba->utmrdl_dma_addr & (SZ_1K - 1))) {
3811 "Task Management Descriptor Memory allocation failed\n");
3816 /* Allocate memory for local reference block */
3817 hba->lrb = devm_kcalloc(hba->dev,
3818 hba->nutrs, sizeof(struct ufshcd_lrb),
3821 dev_err(hba->dev, "LRB Memory allocation failed\n");
3830 * ufshcd_host_memory_configure - configure local reference block with
3832 * @hba: per adapter instance
3834 * Configure Host memory space
3835 * 1. Update Corresponding UTRD.UCDBA and UTRD.UCDBAU with UCD DMA
3837 * 2. Update each UTRD with Response UPIU offset, Response UPIU length
3839 * 3. Save the corresponding addresses of UTRD, UCD.CMD, UCD.RSP and UCD.PRDT
3840 * into local reference block.
3842 static void ufshcd_host_memory_configure(struct ufs_hba *hba)
3844 struct utp_transfer_req_desc *utrdlp;
3845 dma_addr_t cmd_desc_dma_addr;
3846 dma_addr_t cmd_desc_element_addr;
3847 u16 response_offset;
3852 utrdlp = hba->utrdl_base_addr;
3855 offsetof(struct utp_transfer_cmd_desc, response_upiu);
3857 offsetof(struct utp_transfer_cmd_desc, prd_table);
3859 cmd_desc_size = ufshcd_get_ucd_size(hba);
3860 cmd_desc_dma_addr = hba->ucdl_dma_addr;
3862 for (i = 0; i < hba->nutrs; i++) {
3863 /* Configure UTRD with command descriptor base address */
3864 cmd_desc_element_addr =
3865 (cmd_desc_dma_addr + (cmd_desc_size * i));
3866 utrdlp[i].command_desc_base_addr =
3867 cpu_to_le64(cmd_desc_element_addr);
3869 /* Response upiu and prdt offset should be in double words */
3870 if (hba->quirks & UFSHCD_QUIRK_PRDT_BYTE_GRAN) {
3871 utrdlp[i].response_upiu_offset =
3872 cpu_to_le16(response_offset);
3873 utrdlp[i].prd_table_offset =
3874 cpu_to_le16(prdt_offset);
3875 utrdlp[i].response_upiu_length =
3876 cpu_to_le16(ALIGNED_UPIU_SIZE);
3878 utrdlp[i].response_upiu_offset =
3879 cpu_to_le16(response_offset >> 2);
3880 utrdlp[i].prd_table_offset =
3881 cpu_to_le16(prdt_offset >> 2);
3882 utrdlp[i].response_upiu_length =
3883 cpu_to_le16(ALIGNED_UPIU_SIZE >> 2);
3886 ufshcd_init_lrb(hba, &hba->lrb[i], i);
3891 * ufshcd_dme_link_startup - Notify Unipro to perform link startup
3892 * @hba: per adapter instance
3894 * UIC_CMD_DME_LINK_STARTUP command must be issued to Unipro layer,
3895 * in order to initialize the Unipro link startup procedure.
3896 * Once the Unipro links are up, the device connected to the controller
3899 * Returns 0 on success, non-zero value on failure
3901 static int ufshcd_dme_link_startup(struct ufs_hba *hba)
3903 struct uic_command uic_cmd = {0};
3906 uic_cmd.command = UIC_CMD_DME_LINK_STARTUP;
3908 ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
3911 "dme-link-startup: error code %d\n", ret);
3915 * ufshcd_dme_reset - UIC command for DME_RESET
3916 * @hba: per adapter instance
3918 * DME_RESET command is issued in order to reset UniPro stack.
3919 * This function now deals with cold reset.
3921 * Returns 0 on success, non-zero value on failure
3923 static int ufshcd_dme_reset(struct ufs_hba *hba)
3925 struct uic_command uic_cmd = {0};
3928 uic_cmd.command = UIC_CMD_DME_RESET;
3930 ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
3933 "dme-reset: error code %d\n", ret);
3938 int ufshcd_dme_configure_adapt(struct ufs_hba *hba,
3944 if (agreed_gear < UFS_HS_G4)
3945 adapt_val = PA_NO_ADAPT;
3947 ret = ufshcd_dme_set(hba,
3948 UIC_ARG_MIB(PA_TXHSADAPTTYPE),
3952 EXPORT_SYMBOL_GPL(ufshcd_dme_configure_adapt);
3955 * ufshcd_dme_enable - UIC command for DME_ENABLE
3956 * @hba: per adapter instance
3958 * DME_ENABLE command is issued in order to enable UniPro stack.
3960 * Returns 0 on success, non-zero value on failure
3962 static int ufshcd_dme_enable(struct ufs_hba *hba)
3964 struct uic_command uic_cmd = {0};
3967 uic_cmd.command = UIC_CMD_DME_ENABLE;
3969 ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
3972 "dme-enable: error code %d\n", ret);
3977 static inline void ufshcd_add_delay_before_dme_cmd(struct ufs_hba *hba)
3979 #define MIN_DELAY_BEFORE_DME_CMDS_US 1000
3980 unsigned long min_sleep_time_us;
3982 if (!(hba->quirks & UFSHCD_QUIRK_DELAY_BEFORE_DME_CMDS))
3986 * last_dme_cmd_tstamp will be 0 only for 1st call to
3989 if (unlikely(!ktime_to_us(hba->last_dme_cmd_tstamp))) {
3990 min_sleep_time_us = MIN_DELAY_BEFORE_DME_CMDS_US;
3992 unsigned long delta =
3993 (unsigned long) ktime_to_us(
3994 ktime_sub(ktime_get(),
3995 hba->last_dme_cmd_tstamp));
3997 if (delta < MIN_DELAY_BEFORE_DME_CMDS_US)
3999 MIN_DELAY_BEFORE_DME_CMDS_US - delta;
4001 return; /* no more delay required */
4004 /* allow sleep for extra 50us if needed */
4005 usleep_range(min_sleep_time_us, min_sleep_time_us + 50);
4009 * ufshcd_dme_set_attr - UIC command for DME_SET, DME_PEER_SET
4010 * @hba: per adapter instance
4011 * @attr_sel: uic command argument1
4012 * @attr_set: attribute set type as uic command argument2
4013 * @mib_val: setting value as uic command argument3
4014 * @peer: indicate whether peer or local
4016 * Returns 0 on success, non-zero value on failure
4018 int ufshcd_dme_set_attr(struct ufs_hba *hba, u32 attr_sel,
4019 u8 attr_set, u32 mib_val, u8 peer)
4021 struct uic_command uic_cmd = {0};
4022 static const char *const action[] = {
4026 const char *set = action[!!peer];
4028 int retries = UFS_UIC_COMMAND_RETRIES;
4030 uic_cmd.command = peer ?
4031 UIC_CMD_DME_PEER_SET : UIC_CMD_DME_SET;
4032 uic_cmd.argument1 = attr_sel;
4033 uic_cmd.argument2 = UIC_ARG_ATTR_TYPE(attr_set);
4034 uic_cmd.argument3 = mib_val;
4037 /* for peer attributes we retry upon failure */
4038 ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
4040 dev_dbg(hba->dev, "%s: attr-id 0x%x val 0x%x error code %d\n",
4041 set, UIC_GET_ATTR_ID(attr_sel), mib_val, ret);
4042 } while (ret && peer && --retries);
4045 dev_err(hba->dev, "%s: attr-id 0x%x val 0x%x failed %d retries\n",
4046 set, UIC_GET_ATTR_ID(attr_sel), mib_val,
4047 UFS_UIC_COMMAND_RETRIES - retries);
4051 EXPORT_SYMBOL_GPL(ufshcd_dme_set_attr);
4054 * ufshcd_dme_get_attr - UIC command for DME_GET, DME_PEER_GET
4055 * @hba: per adapter instance
4056 * @attr_sel: uic command argument1
4057 * @mib_val: the value of the attribute as returned by the UIC command
4058 * @peer: indicate whether peer or local
4060 * Returns 0 on success, non-zero value on failure
4062 int ufshcd_dme_get_attr(struct ufs_hba *hba, u32 attr_sel,
4063 u32 *mib_val, u8 peer)
4065 struct uic_command uic_cmd = {0};
4066 static const char *const action[] = {
4070 const char *get = action[!!peer];
4072 int retries = UFS_UIC_COMMAND_RETRIES;
4073 struct ufs_pa_layer_attr orig_pwr_info;
4074 struct ufs_pa_layer_attr temp_pwr_info;
4075 bool pwr_mode_change = false;
4077 if (peer && (hba->quirks & UFSHCD_QUIRK_DME_PEER_ACCESS_AUTO_MODE)) {
4078 orig_pwr_info = hba->pwr_info;
4079 temp_pwr_info = orig_pwr_info;
4081 if (orig_pwr_info.pwr_tx == FAST_MODE ||
4082 orig_pwr_info.pwr_rx == FAST_MODE) {
4083 temp_pwr_info.pwr_tx = FASTAUTO_MODE;
4084 temp_pwr_info.pwr_rx = FASTAUTO_MODE;
4085 pwr_mode_change = true;
4086 } else if (orig_pwr_info.pwr_tx == SLOW_MODE ||
4087 orig_pwr_info.pwr_rx == SLOW_MODE) {
4088 temp_pwr_info.pwr_tx = SLOWAUTO_MODE;
4089 temp_pwr_info.pwr_rx = SLOWAUTO_MODE;
4090 pwr_mode_change = true;
4092 if (pwr_mode_change) {
4093 ret = ufshcd_change_power_mode(hba, &temp_pwr_info);
4099 uic_cmd.command = peer ?
4100 UIC_CMD_DME_PEER_GET : UIC_CMD_DME_GET;
4101 uic_cmd.argument1 = attr_sel;
4104 /* for peer attributes we retry upon failure */
4105 ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
4107 dev_dbg(hba->dev, "%s: attr-id 0x%x error code %d\n",
4108 get, UIC_GET_ATTR_ID(attr_sel), ret);
4109 } while (ret && peer && --retries);
4112 dev_err(hba->dev, "%s: attr-id 0x%x failed %d retries\n",
4113 get, UIC_GET_ATTR_ID(attr_sel),
4114 UFS_UIC_COMMAND_RETRIES - retries);
4116 if (mib_val && !ret)
4117 *mib_val = uic_cmd.argument3;
4119 if (peer && (hba->quirks & UFSHCD_QUIRK_DME_PEER_ACCESS_AUTO_MODE)
4121 ufshcd_change_power_mode(hba, &orig_pwr_info);
4125 EXPORT_SYMBOL_GPL(ufshcd_dme_get_attr);
4128 * ufshcd_uic_pwr_ctrl - executes UIC commands (which affects the link power
4129 * state) and waits for it to take effect.
4131 * @hba: per adapter instance
4132 * @cmd: UIC command to execute
4134 * DME operations like DME_SET(PA_PWRMODE), DME_HIBERNATE_ENTER &
4135 * DME_HIBERNATE_EXIT commands take some time to take its effect on both host
4136 * and device UniPro link and hence it's final completion would be indicated by
4137 * dedicated status bits in Interrupt Status register (UPMS, UHES, UHXS) in
4138 * addition to normal UIC command completion Status (UCCS). This function only
4139 * returns after the relevant status bits indicate the completion.
4141 * Returns 0 on success, non-zero value on failure
4143 static int ufshcd_uic_pwr_ctrl(struct ufs_hba *hba, struct uic_command *cmd)
4145 DECLARE_COMPLETION_ONSTACK(uic_async_done);
4146 unsigned long flags;
4149 bool reenable_intr = false;
4151 mutex_lock(&hba->uic_cmd_mutex);
4152 ufshcd_add_delay_before_dme_cmd(hba);
4154 spin_lock_irqsave(hba->host->host_lock, flags);
4155 if (ufshcd_is_link_broken(hba)) {
4159 hba->uic_async_done = &uic_async_done;
4160 if (ufshcd_readl(hba, REG_INTERRUPT_ENABLE) & UIC_COMMAND_COMPL) {
4161 ufshcd_disable_intr(hba, UIC_COMMAND_COMPL);
4163 * Make sure UIC command completion interrupt is disabled before
4164 * issuing UIC command.
4167 reenable_intr = true;
4169 ret = __ufshcd_send_uic_cmd(hba, cmd, false);
4170 spin_unlock_irqrestore(hba->host->host_lock, flags);
4173 "pwr ctrl cmd 0x%x with mode 0x%x uic error %d\n",
4174 cmd->command, cmd->argument3, ret);
4178 if (!wait_for_completion_timeout(hba->uic_async_done,
4179 msecs_to_jiffies(UIC_CMD_TIMEOUT))) {
4181 "pwr ctrl cmd 0x%x with mode 0x%x completion timeout\n",
4182 cmd->command, cmd->argument3);
4184 if (!cmd->cmd_active) {
4185 dev_err(hba->dev, "%s: Power Mode Change operation has been completed, go check UPMCRS\n",
4195 status = ufshcd_get_upmcrs(hba);
4196 if (status != PWR_LOCAL) {
4198 "pwr ctrl cmd 0x%x failed, host upmcrs:0x%x\n",
4199 cmd->command, status);
4200 ret = (status != PWR_OK) ? status : -1;
4204 ufshcd_print_host_state(hba);
4205 ufshcd_print_pwr_info(hba);
4206 ufshcd_print_evt_hist(hba);
4209 spin_lock_irqsave(hba->host->host_lock, flags);
4210 hba->active_uic_cmd = NULL;
4211 hba->uic_async_done = NULL;
4213 ufshcd_enable_intr(hba, UIC_COMMAND_COMPL);
4215 ufshcd_set_link_broken(hba);
4216 ufshcd_schedule_eh_work(hba);
4219 spin_unlock_irqrestore(hba->host->host_lock, flags);
4220 mutex_unlock(&hba->uic_cmd_mutex);
4226 * ufshcd_uic_change_pwr_mode - Perform the UIC power mode chage
4227 * using DME_SET primitives.
4228 * @hba: per adapter instance
4229 * @mode: powr mode value
4231 * Returns 0 on success, non-zero value on failure
4233 int ufshcd_uic_change_pwr_mode(struct ufs_hba *hba, u8 mode)
4235 struct uic_command uic_cmd = {0};
4238 if (hba->quirks & UFSHCD_QUIRK_BROKEN_PA_RXHSUNTERMCAP) {
4239 ret = ufshcd_dme_set(hba,
4240 UIC_ARG_MIB_SEL(PA_RXHSUNTERMCAP, 0), 1);
4242 dev_err(hba->dev, "%s: failed to enable PA_RXHSUNTERMCAP ret %d\n",
4248 uic_cmd.command = UIC_CMD_DME_SET;
4249 uic_cmd.argument1 = UIC_ARG_MIB(PA_PWRMODE);
4250 uic_cmd.argument3 = mode;
4252 ret = ufshcd_uic_pwr_ctrl(hba, &uic_cmd);
4253 ufshcd_release(hba);
4258 EXPORT_SYMBOL_GPL(ufshcd_uic_change_pwr_mode);
4260 int ufshcd_link_recovery(struct ufs_hba *hba)
4263 unsigned long flags;
4265 spin_lock_irqsave(hba->host->host_lock, flags);
4266 hba->ufshcd_state = UFSHCD_STATE_RESET;
4267 ufshcd_set_eh_in_progress(hba);
4268 spin_unlock_irqrestore(hba->host->host_lock, flags);
4270 /* Reset the attached device */
4271 ufshcd_device_reset(hba);
4273 ret = ufshcd_host_reset_and_restore(hba);
4275 spin_lock_irqsave(hba->host->host_lock, flags);
4277 hba->ufshcd_state = UFSHCD_STATE_ERROR;
4278 ufshcd_clear_eh_in_progress(hba);
4279 spin_unlock_irqrestore(hba->host->host_lock, flags);
4282 dev_err(hba->dev, "%s: link recovery failed, err %d",
4287 EXPORT_SYMBOL_GPL(ufshcd_link_recovery);
4289 int ufshcd_uic_hibern8_enter(struct ufs_hba *hba)
4292 struct uic_command uic_cmd = {0};
4293 ktime_t start = ktime_get();
4295 ufshcd_vops_hibern8_notify(hba, UIC_CMD_DME_HIBER_ENTER, PRE_CHANGE);
4297 uic_cmd.command = UIC_CMD_DME_HIBER_ENTER;
4298 ret = ufshcd_uic_pwr_ctrl(hba, &uic_cmd);
4299 trace_ufshcd_profile_hibern8(dev_name(hba->dev), "enter",
4300 ktime_to_us(ktime_sub(ktime_get(), start)), ret);
4303 dev_err(hba->dev, "%s: hibern8 enter failed. ret = %d\n",
4306 ufshcd_vops_hibern8_notify(hba, UIC_CMD_DME_HIBER_ENTER,
4311 EXPORT_SYMBOL_GPL(ufshcd_uic_hibern8_enter);
4313 int ufshcd_uic_hibern8_exit(struct ufs_hba *hba)
4315 struct uic_command uic_cmd = {0};
4317 ktime_t start = ktime_get();
4319 ufshcd_vops_hibern8_notify(hba, UIC_CMD_DME_HIBER_EXIT, PRE_CHANGE);
4321 uic_cmd.command = UIC_CMD_DME_HIBER_EXIT;
4322 ret = ufshcd_uic_pwr_ctrl(hba, &uic_cmd);
4323 trace_ufshcd_profile_hibern8(dev_name(hba->dev), "exit",
4324 ktime_to_us(ktime_sub(ktime_get(), start)), ret);
4327 dev_err(hba->dev, "%s: hibern8 exit failed. ret = %d\n",
4330 ufshcd_vops_hibern8_notify(hba, UIC_CMD_DME_HIBER_EXIT,
4332 hba->ufs_stats.last_hibern8_exit_tstamp = local_clock();
4333 hba->ufs_stats.hibern8_exit_cnt++;
4338 EXPORT_SYMBOL_GPL(ufshcd_uic_hibern8_exit);
4340 void ufshcd_auto_hibern8_update(struct ufs_hba *hba, u32 ahit)
4342 unsigned long flags;
4343 bool update = false;
4345 if (!ufshcd_is_auto_hibern8_supported(hba))
4348 spin_lock_irqsave(hba->host->host_lock, flags);
4349 if (hba->ahit != ahit) {
4353 spin_unlock_irqrestore(hba->host->host_lock, flags);
4356 !pm_runtime_suspended(&hba->ufs_device_wlun->sdev_gendev)) {
4357 ufshcd_rpm_get_sync(hba);
4359 ufshcd_auto_hibern8_enable(hba);
4360 ufshcd_release(hba);
4361 ufshcd_rpm_put_sync(hba);
4364 EXPORT_SYMBOL_GPL(ufshcd_auto_hibern8_update);
4366 void ufshcd_auto_hibern8_enable(struct ufs_hba *hba)
4368 if (!ufshcd_is_auto_hibern8_supported(hba))
4371 ufshcd_writel(hba, hba->ahit, REG_AUTO_HIBERNATE_IDLE_TIMER);
4375 * ufshcd_init_pwr_info - setting the POR (power on reset)
4376 * values in hba power info
4377 * @hba: per-adapter instance
4379 static void ufshcd_init_pwr_info(struct ufs_hba *hba)
4381 hba->pwr_info.gear_rx = UFS_PWM_G1;
4382 hba->pwr_info.gear_tx = UFS_PWM_G1;
4383 hba->pwr_info.lane_rx = 1;
4384 hba->pwr_info.lane_tx = 1;
4385 hba->pwr_info.pwr_rx = SLOWAUTO_MODE;
4386 hba->pwr_info.pwr_tx = SLOWAUTO_MODE;
4387 hba->pwr_info.hs_rate = 0;
4391 * ufshcd_get_max_pwr_mode - reads the max power mode negotiated with device
4392 * @hba: per-adapter instance
4394 static int ufshcd_get_max_pwr_mode(struct ufs_hba *hba)
4396 struct ufs_pa_layer_attr *pwr_info = &hba->max_pwr_info.info;
4398 if (hba->max_pwr_info.is_valid)
4401 if (hba->quirks & UFSHCD_QUIRK_HIBERN_FASTAUTO) {
4402 pwr_info->pwr_tx = FASTAUTO_MODE;
4403 pwr_info->pwr_rx = FASTAUTO_MODE;
4405 pwr_info->pwr_tx = FAST_MODE;
4406 pwr_info->pwr_rx = FAST_MODE;
4408 pwr_info->hs_rate = PA_HS_MODE_B;
4410 /* Get the connected lane count */
4411 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_CONNECTEDRXDATALANES),
4412 &pwr_info->lane_rx);
4413 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_CONNECTEDTXDATALANES),
4414 &pwr_info->lane_tx);
4416 if (!pwr_info->lane_rx || !pwr_info->lane_tx) {
4417 dev_err(hba->dev, "%s: invalid connected lanes value. rx=%d, tx=%d\n",
4425 * First, get the maximum gears of HS speed.
4426 * If a zero value, it means there is no HSGEAR capability.
4427 * Then, get the maximum gears of PWM speed.
4429 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_MAXRXHSGEAR), &pwr_info->gear_rx);
4430 if (!pwr_info->gear_rx) {
4431 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_MAXRXPWMGEAR),
4432 &pwr_info->gear_rx);
4433 if (!pwr_info->gear_rx) {
4434 dev_err(hba->dev, "%s: invalid max pwm rx gear read = %d\n",
4435 __func__, pwr_info->gear_rx);
4438 pwr_info->pwr_rx = SLOW_MODE;
4441 ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_MAXRXHSGEAR),
4442 &pwr_info->gear_tx);
4443 if (!pwr_info->gear_tx) {
4444 ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_MAXRXPWMGEAR),
4445 &pwr_info->gear_tx);
4446 if (!pwr_info->gear_tx) {
4447 dev_err(hba->dev, "%s: invalid max pwm tx gear read = %d\n",
4448 __func__, pwr_info->gear_tx);
4451 pwr_info->pwr_tx = SLOW_MODE;
4454 hba->max_pwr_info.is_valid = true;
4458 static int ufshcd_change_power_mode(struct ufs_hba *hba,
4459 struct ufs_pa_layer_attr *pwr_mode)
4463 /* if already configured to the requested pwr_mode */
4464 if (!hba->force_pmc &&
4465 pwr_mode->gear_rx == hba->pwr_info.gear_rx &&
4466 pwr_mode->gear_tx == hba->pwr_info.gear_tx &&
4467 pwr_mode->lane_rx == hba->pwr_info.lane_rx &&
4468 pwr_mode->lane_tx == hba->pwr_info.lane_tx &&
4469 pwr_mode->pwr_rx == hba->pwr_info.pwr_rx &&
4470 pwr_mode->pwr_tx == hba->pwr_info.pwr_tx &&
4471 pwr_mode->hs_rate == hba->pwr_info.hs_rate) {
4472 dev_dbg(hba->dev, "%s: power already configured\n", __func__);
4477 * Configure attributes for power mode change with below.
4478 * - PA_RXGEAR, PA_ACTIVERXDATALANES, PA_RXTERMINATION,
4479 * - PA_TXGEAR, PA_ACTIVETXDATALANES, PA_TXTERMINATION,
4482 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_RXGEAR), pwr_mode->gear_rx);
4483 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_ACTIVERXDATALANES),
4485 if (pwr_mode->pwr_rx == FASTAUTO_MODE ||
4486 pwr_mode->pwr_rx == FAST_MODE)
4487 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_RXTERMINATION), true);
4489 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_RXTERMINATION), false);
4491 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TXGEAR), pwr_mode->gear_tx);
4492 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_ACTIVETXDATALANES),
4494 if (pwr_mode->pwr_tx == FASTAUTO_MODE ||
4495 pwr_mode->pwr_tx == FAST_MODE)
4496 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TXTERMINATION), true);
4498 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TXTERMINATION), false);
4500 if (pwr_mode->pwr_rx == FASTAUTO_MODE ||
4501 pwr_mode->pwr_tx == FASTAUTO_MODE ||
4502 pwr_mode->pwr_rx == FAST_MODE ||
4503 pwr_mode->pwr_tx == FAST_MODE)
4504 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_HSSERIES),
4507 if (!(hba->quirks & UFSHCD_QUIRK_SKIP_DEF_UNIPRO_TIMEOUT_SETTING)) {
4508 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_PWRMODEUSERDATA0),
4509 DL_FC0ProtectionTimeOutVal_Default);
4510 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_PWRMODEUSERDATA1),
4511 DL_TC0ReplayTimeOutVal_Default);
4512 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_PWRMODEUSERDATA2),
4513 DL_AFC0ReqTimeOutVal_Default);
4514 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_PWRMODEUSERDATA3),
4515 DL_FC1ProtectionTimeOutVal_Default);
4516 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_PWRMODEUSERDATA4),
4517 DL_TC1ReplayTimeOutVal_Default);
4518 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_PWRMODEUSERDATA5),
4519 DL_AFC1ReqTimeOutVal_Default);
4521 ufshcd_dme_set(hba, UIC_ARG_MIB(DME_LocalFC0ProtectionTimeOutVal),
4522 DL_FC0ProtectionTimeOutVal_Default);
4523 ufshcd_dme_set(hba, UIC_ARG_MIB(DME_LocalTC0ReplayTimeOutVal),
4524 DL_TC0ReplayTimeOutVal_Default);
4525 ufshcd_dme_set(hba, UIC_ARG_MIB(DME_LocalAFC0ReqTimeOutVal),
4526 DL_AFC0ReqTimeOutVal_Default);
4529 ret = ufshcd_uic_change_pwr_mode(hba, pwr_mode->pwr_rx << 4
4530 | pwr_mode->pwr_tx);
4534 "%s: power mode change failed %d\n", __func__, ret);
4536 ufshcd_vops_pwr_change_notify(hba, POST_CHANGE, NULL,
4539 memcpy(&hba->pwr_info, pwr_mode,
4540 sizeof(struct ufs_pa_layer_attr));
4547 * ufshcd_config_pwr_mode - configure a new power mode
4548 * @hba: per-adapter instance
4549 * @desired_pwr_mode: desired power configuration
4551 int ufshcd_config_pwr_mode(struct ufs_hba *hba,
4552 struct ufs_pa_layer_attr *desired_pwr_mode)
4554 struct ufs_pa_layer_attr final_params = { 0 };
4557 ret = ufshcd_vops_pwr_change_notify(hba, PRE_CHANGE,
4558 desired_pwr_mode, &final_params);
4561 memcpy(&final_params, desired_pwr_mode, sizeof(final_params));
4563 ret = ufshcd_change_power_mode(hba, &final_params);
4567 EXPORT_SYMBOL_GPL(ufshcd_config_pwr_mode);
4570 * ufshcd_complete_dev_init() - checks device readiness
4571 * @hba: per-adapter instance
4573 * Set fDeviceInit flag and poll until device toggles it.
4575 static int ufshcd_complete_dev_init(struct ufs_hba *hba)
4578 bool flag_res = true;
4581 err = ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_SET_FLAG,
4582 QUERY_FLAG_IDN_FDEVICEINIT, 0, NULL);
4585 "%s: setting fDeviceInit flag failed with error %d\n",
4590 /* Poll fDeviceInit flag to be cleared */
4591 timeout = ktime_add_ms(ktime_get(), FDEVICEINIT_COMPL_TIMEOUT);
4593 err = ufshcd_query_flag(hba, UPIU_QUERY_OPCODE_READ_FLAG,
4594 QUERY_FLAG_IDN_FDEVICEINIT, 0, &flag_res);
4597 usleep_range(500, 1000);
4598 } while (ktime_before(ktime_get(), timeout));
4602 "%s: reading fDeviceInit flag failed with error %d\n",
4604 } else if (flag_res) {
4606 "%s: fDeviceInit was not cleared by the device\n",
4615 * ufshcd_make_hba_operational - Make UFS controller operational
4616 * @hba: per adapter instance
4618 * To bring UFS host controller to operational state,
4619 * 1. Enable required interrupts
4620 * 2. Configure interrupt aggregation
4621 * 3. Program UTRL and UTMRL base address
4622 * 4. Configure run-stop-registers
4624 * Returns 0 on success, non-zero value on failure
4626 int ufshcd_make_hba_operational(struct ufs_hba *hba)
4631 /* Enable required interrupts */
4632 ufshcd_enable_intr(hba, UFSHCD_ENABLE_INTRS);
4634 /* Configure interrupt aggregation */
4635 if (ufshcd_is_intr_aggr_allowed(hba))
4636 ufshcd_config_intr_aggr(hba, hba->nutrs - 1, INT_AGGR_DEF_TO);
4638 ufshcd_disable_intr_aggr(hba);
4640 /* Configure UTRL and UTMRL base address registers */
4641 ufshcd_writel(hba, lower_32_bits(hba->utrdl_dma_addr),
4642 REG_UTP_TRANSFER_REQ_LIST_BASE_L);
4643 ufshcd_writel(hba, upper_32_bits(hba->utrdl_dma_addr),
4644 REG_UTP_TRANSFER_REQ_LIST_BASE_H);
4645 ufshcd_writel(hba, lower_32_bits(hba->utmrdl_dma_addr),
4646 REG_UTP_TASK_REQ_LIST_BASE_L);
4647 ufshcd_writel(hba, upper_32_bits(hba->utmrdl_dma_addr),
4648 REG_UTP_TASK_REQ_LIST_BASE_H);
4651 * Make sure base address and interrupt setup are updated before
4652 * enabling the run/stop registers below.
4657 * UCRDY, UTMRLDY and UTRLRDY bits must be 1
4659 reg = ufshcd_readl(hba, REG_CONTROLLER_STATUS);
4660 if (!(ufshcd_get_lists_status(reg))) {
4661 ufshcd_enable_run_stop_reg(hba);
4664 "Host controller not ready to process requests");
4670 EXPORT_SYMBOL_GPL(ufshcd_make_hba_operational);
4673 * ufshcd_hba_stop - Send controller to reset state
4674 * @hba: per adapter instance
4676 void ufshcd_hba_stop(struct ufs_hba *hba)
4678 unsigned long flags;
4682 * Obtain the host lock to prevent that the controller is disabled
4683 * while the UFS interrupt handler is active on another CPU.
4685 spin_lock_irqsave(hba->host->host_lock, flags);
4686 ufshcd_writel(hba, CONTROLLER_DISABLE, REG_CONTROLLER_ENABLE);
4687 spin_unlock_irqrestore(hba->host->host_lock, flags);
4689 err = ufshcd_wait_for_register(hba, REG_CONTROLLER_ENABLE,
4690 CONTROLLER_ENABLE, CONTROLLER_DISABLE,
4693 dev_err(hba->dev, "%s: Controller disable failed\n", __func__);
4695 EXPORT_SYMBOL_GPL(ufshcd_hba_stop);
4698 * ufshcd_hba_execute_hce - initialize the controller
4699 * @hba: per adapter instance
4701 * The controller resets itself and controller firmware initialization
4702 * sequence kicks off. When controller is ready it will set
4703 * the Host Controller Enable bit to 1.
4705 * Returns 0 on success, non-zero value on failure
4707 static int ufshcd_hba_execute_hce(struct ufs_hba *hba)
4709 int retry_outer = 3;
4713 if (ufshcd_is_hba_active(hba))
4714 /* change controller state to "reset state" */
4715 ufshcd_hba_stop(hba);
4717 /* UniPro link is disabled at this point */
4718 ufshcd_set_link_off(hba);
4720 ufshcd_vops_hce_enable_notify(hba, PRE_CHANGE);
4722 /* start controller initialization sequence */
4723 ufshcd_hba_start(hba);
4726 * To initialize a UFS host controller HCE bit must be set to 1.
4727 * During initialization the HCE bit value changes from 1->0->1.
4728 * When the host controller completes initialization sequence
4729 * it sets the value of HCE bit to 1. The same HCE bit is read back
4730 * to check if the controller has completed initialization sequence.
4731 * So without this delay the value HCE = 1, set in the previous
4732 * instruction might be read back.
4733 * This delay can be changed based on the controller.
4735 ufshcd_delay_us(hba->vps->hba_enable_delay_us, 100);
4737 /* wait for the host controller to complete initialization */
4739 while (!ufshcd_is_hba_active(hba)) {
4744 "Controller enable failed\n");
4751 usleep_range(1000, 1100);
4754 /* enable UIC related interrupts */
4755 ufshcd_enable_intr(hba, UFSHCD_UIC_MASK);
4757 ufshcd_vops_hce_enable_notify(hba, POST_CHANGE);
4762 int ufshcd_hba_enable(struct ufs_hba *hba)
4766 if (hba->quirks & UFSHCI_QUIRK_BROKEN_HCE) {
4767 ufshcd_set_link_off(hba);
4768 ufshcd_vops_hce_enable_notify(hba, PRE_CHANGE);
4770 /* enable UIC related interrupts */
4771 ufshcd_enable_intr(hba, UFSHCD_UIC_MASK);
4772 ret = ufshcd_dme_reset(hba);
4774 dev_err(hba->dev, "DME_RESET failed\n");
4778 ret = ufshcd_dme_enable(hba);
4780 dev_err(hba->dev, "Enabling DME failed\n");
4784 ufshcd_vops_hce_enable_notify(hba, POST_CHANGE);
4786 ret = ufshcd_hba_execute_hce(hba);
4791 EXPORT_SYMBOL_GPL(ufshcd_hba_enable);
4793 static int ufshcd_disable_tx_lcc(struct ufs_hba *hba, bool peer)
4795 int tx_lanes = 0, i, err = 0;
4798 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_CONNECTEDTXDATALANES),
4801 ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_CONNECTEDTXDATALANES),
4803 for (i = 0; i < tx_lanes; i++) {
4805 err = ufshcd_dme_set(hba,
4806 UIC_ARG_MIB_SEL(TX_LCC_ENABLE,
4807 UIC_ARG_MPHY_TX_GEN_SEL_INDEX(i)),
4810 err = ufshcd_dme_peer_set(hba,
4811 UIC_ARG_MIB_SEL(TX_LCC_ENABLE,
4812 UIC_ARG_MPHY_TX_GEN_SEL_INDEX(i)),
4815 dev_err(hba->dev, "%s: TX LCC Disable failed, peer = %d, lane = %d, err = %d",
4816 __func__, peer, i, err);
4824 static inline int ufshcd_disable_device_tx_lcc(struct ufs_hba *hba)
4826 return ufshcd_disable_tx_lcc(hba, true);
4829 void ufshcd_update_evt_hist(struct ufs_hba *hba, u32 id, u32 val)
4831 struct ufs_event_hist *e;
4833 if (id >= UFS_EVT_CNT)
4836 e = &hba->ufs_stats.event[id];
4837 e->val[e->pos] = val;
4838 e->tstamp[e->pos] = local_clock();
4840 e->pos = (e->pos + 1) % UFS_EVENT_HIST_LENGTH;
4842 ufshcd_vops_event_notify(hba, id, &val);
4844 EXPORT_SYMBOL_GPL(ufshcd_update_evt_hist);
4847 * ufshcd_link_startup - Initialize unipro link startup
4848 * @hba: per adapter instance
4850 * Returns 0 for success, non-zero in case of failure
4852 static int ufshcd_link_startup(struct ufs_hba *hba)
4855 int retries = DME_LINKSTARTUP_RETRIES;
4856 bool link_startup_again = false;
4859 * If UFS device isn't active then we will have to issue link startup
4860 * 2 times to make sure the device state move to active.
4862 if (!ufshcd_is_ufs_dev_active(hba))
4863 link_startup_again = true;
4867 ufshcd_vops_link_startup_notify(hba, PRE_CHANGE);
4869 ret = ufshcd_dme_link_startup(hba);
4871 /* check if device is detected by inter-connect layer */
4872 if (!ret && !ufshcd_is_device_present(hba)) {
4873 ufshcd_update_evt_hist(hba,
4874 UFS_EVT_LINK_STARTUP_FAIL,
4876 dev_err(hba->dev, "%s: Device not present\n", __func__);
4882 * DME link lost indication is only received when link is up,
4883 * but we can't be sure if the link is up until link startup
4884 * succeeds. So reset the local Uni-Pro and try again.
4886 if (ret && retries && ufshcd_hba_enable(hba)) {
4887 ufshcd_update_evt_hist(hba,
4888 UFS_EVT_LINK_STARTUP_FAIL,
4892 } while (ret && retries--);
4895 /* failed to get the link up... retire */
4896 ufshcd_update_evt_hist(hba,
4897 UFS_EVT_LINK_STARTUP_FAIL,
4902 if (link_startup_again) {
4903 link_startup_again = false;
4904 retries = DME_LINKSTARTUP_RETRIES;
4908 /* Mark that link is up in PWM-G1, 1-lane, SLOW-AUTO mode */
4909 ufshcd_init_pwr_info(hba);
4910 ufshcd_print_pwr_info(hba);
4912 if (hba->quirks & UFSHCD_QUIRK_BROKEN_LCC) {
4913 ret = ufshcd_disable_device_tx_lcc(hba);
4918 /* Include any host controller configuration via UIC commands */
4919 ret = ufshcd_vops_link_startup_notify(hba, POST_CHANGE);
4923 /* Clear UECPA once due to LINERESET has happened during LINK_STARTUP */
4924 ufshcd_readl(hba, REG_UIC_ERROR_CODE_PHY_ADAPTER_LAYER);
4925 ret = ufshcd_make_hba_operational(hba);
4928 dev_err(hba->dev, "link startup failed %d\n", ret);
4929 ufshcd_print_host_state(hba);
4930 ufshcd_print_pwr_info(hba);
4931 ufshcd_print_evt_hist(hba);
4937 * ufshcd_verify_dev_init() - Verify device initialization
4938 * @hba: per-adapter instance
4940 * Send NOP OUT UPIU and wait for NOP IN response to check whether the
4941 * device Transport Protocol (UTP) layer is ready after a reset.
4942 * If the UTP layer at the device side is not initialized, it may
4943 * not respond with NOP IN UPIU within timeout of %NOP_OUT_TIMEOUT
4944 * and we retry sending NOP OUT for %NOP_OUT_RETRIES iterations.
4946 static int ufshcd_verify_dev_init(struct ufs_hba *hba)
4952 mutex_lock(&hba->dev_cmd.lock);
4953 for (retries = NOP_OUT_RETRIES; retries > 0; retries--) {
4954 err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_NOP,
4955 hba->nop_out_timeout);
4957 if (!err || err == -ETIMEDOUT)
4960 dev_dbg(hba->dev, "%s: error %d retrying\n", __func__, err);
4962 mutex_unlock(&hba->dev_cmd.lock);
4963 ufshcd_release(hba);
4966 dev_err(hba->dev, "%s: NOP OUT failed %d\n", __func__, err);
4971 * ufshcd_setup_links - associate link b/w device wlun and other luns
4972 * @sdev: pointer to SCSI device
4973 * @hba: pointer to ufs hba
4975 static void ufshcd_setup_links(struct ufs_hba *hba, struct scsi_device *sdev)
4977 struct device_link *link;
4980 * Device wlun is the supplier & rest of the luns are consumers.
4981 * This ensures that device wlun suspends after all other luns.
4983 if (hba->ufs_device_wlun) {
4984 link = device_link_add(&sdev->sdev_gendev,
4985 &hba->ufs_device_wlun->sdev_gendev,
4986 DL_FLAG_PM_RUNTIME | DL_FLAG_RPM_ACTIVE);
4988 dev_err(&sdev->sdev_gendev, "Failed establishing link - %s\n",
4989 dev_name(&hba->ufs_device_wlun->sdev_gendev));
4993 /* Ignore REPORT_LUN wlun probing */
4994 if (hba->luns_avail == 1) {
4995 ufshcd_rpm_put(hba);
5000 * Device wlun is probed. The assumption is that WLUNs are
5001 * scanned before other LUNs.
5008 * ufshcd_lu_init - Initialize the relevant parameters of the LU
5009 * @hba: per-adapter instance
5010 * @sdev: pointer to SCSI device
5012 static void ufshcd_lu_init(struct ufs_hba *hba, struct scsi_device *sdev)
5014 int len = QUERY_DESC_MAX_SIZE;
5015 u8 lun = ufshcd_scsi_to_upiu_lun(sdev->lun);
5016 u8 lun_qdepth = hba->nutrs;
5020 desc_buf = kzalloc(len, GFP_KERNEL);
5024 ret = ufshcd_read_unit_desc_param(hba, lun, 0, desc_buf, len);
5026 if (ret == -EOPNOTSUPP)
5027 /* If LU doesn't support unit descriptor, its queue depth is set to 1 */
5033 if (desc_buf[UNIT_DESC_PARAM_LU_Q_DEPTH]) {
5035 * In per-LU queueing architecture, bLUQueueDepth will not be 0, then we will
5036 * use the smaller between UFSHCI CAP.NUTRS and UFS LU bLUQueueDepth
5038 lun_qdepth = min_t(int, desc_buf[UNIT_DESC_PARAM_LU_Q_DEPTH], hba->nutrs);
5041 * According to UFS device specification, the write protection mode is only supported by
5042 * normal LU, not supported by WLUN.
5044 if (hba->dev_info.f_power_on_wp_en && lun < hba->dev_info.max_lu_supported &&
5045 !hba->dev_info.is_lu_power_on_wp &&
5046 desc_buf[UNIT_DESC_PARAM_LU_WR_PROTECT] == UFS_LU_POWER_ON_WP)
5047 hba->dev_info.is_lu_power_on_wp = true;
5049 /* In case of RPMB LU, check if advanced RPMB mode is enabled */
5050 if (desc_buf[UNIT_DESC_PARAM_UNIT_INDEX] == UFS_UPIU_RPMB_WLUN &&
5051 desc_buf[RPMB_UNIT_DESC_PARAM_REGION_EN] & BIT(4))
5052 hba->dev_info.b_advanced_rpmb_en = true;
5058 * For WLUNs that don't support unit descriptor, queue depth is set to 1. For LUs whose
5059 * bLUQueueDepth == 0, the queue depth is set to a maximum value that host can queue.
5061 dev_dbg(hba->dev, "Set LU %x queue depth %d\n", lun, lun_qdepth);
5062 scsi_change_queue_depth(sdev, lun_qdepth);
5066 * ufshcd_slave_alloc - handle initial SCSI device configurations
5067 * @sdev: pointer to SCSI device
5071 static int ufshcd_slave_alloc(struct scsi_device *sdev)
5073 struct ufs_hba *hba;
5075 hba = shost_priv(sdev->host);
5077 /* Mode sense(6) is not supported by UFS, so use Mode sense(10) */
5078 sdev->use_10_for_ms = 1;
5080 /* DBD field should be set to 1 in mode sense(10) */
5081 sdev->set_dbd_for_ms = 1;
5083 /* allow SCSI layer to restart the device in case of errors */
5084 sdev->allow_restart = 1;
5086 /* REPORT SUPPORTED OPERATION CODES is not supported */
5087 sdev->no_report_opcodes = 1;
5089 /* WRITE_SAME command is not supported */
5090 sdev->no_write_same = 1;
5092 ufshcd_lu_init(hba, sdev);
5094 ufshcd_setup_links(hba, sdev);
5100 * ufshcd_change_queue_depth - change queue depth
5101 * @sdev: pointer to SCSI device
5102 * @depth: required depth to set
5104 * Change queue depth and make sure the max. limits are not crossed.
5106 static int ufshcd_change_queue_depth(struct scsi_device *sdev, int depth)
5108 return scsi_change_queue_depth(sdev, min(depth, sdev->host->can_queue));
5111 static void ufshcd_hpb_destroy(struct ufs_hba *hba, struct scsi_device *sdev)
5113 /* skip well-known LU */
5114 if ((sdev->lun >= UFS_UPIU_MAX_UNIT_NUM_ID) ||
5115 !(hba->dev_info.hpb_enabled) || !ufshpb_is_allowed(hba))
5118 ufshpb_destroy_lu(hba, sdev);
5121 static void ufshcd_hpb_configure(struct ufs_hba *hba, struct scsi_device *sdev)
5123 /* skip well-known LU */
5124 if ((sdev->lun >= UFS_UPIU_MAX_UNIT_NUM_ID) ||
5125 !(hba->dev_info.hpb_enabled) || !ufshpb_is_allowed(hba))
5128 ufshpb_init_hpb_lu(hba, sdev);
5132 * ufshcd_slave_configure - adjust SCSI device configurations
5133 * @sdev: pointer to SCSI device
5135 static int ufshcd_slave_configure(struct scsi_device *sdev)
5137 struct ufs_hba *hba = shost_priv(sdev->host);
5138 struct request_queue *q = sdev->request_queue;
5140 ufshcd_hpb_configure(hba, sdev);
5142 blk_queue_update_dma_pad(q, PRDT_DATA_BYTE_COUNT_PAD - 1);
5143 if (hba->quirks & UFSHCD_QUIRK_4KB_DMA_ALIGNMENT)
5144 blk_queue_update_dma_alignment(q, SZ_4K - 1);
5146 * Block runtime-pm until all consumers are added.
5147 * Refer ufshcd_setup_links().
5149 if (is_device_wlun(sdev))
5150 pm_runtime_get_noresume(&sdev->sdev_gendev);
5151 else if (ufshcd_is_rpm_autosuspend_allowed(hba))
5152 sdev->rpm_autosuspend = 1;
5154 * Do not print messages during runtime PM to avoid never-ending cycles
5155 * of messages written back to storage by user space causing runtime
5156 * resume, causing more messages and so on.
5158 sdev->silence_suspend = 1;
5160 ufshcd_crypto_register(hba, q);
5166 * ufshcd_slave_destroy - remove SCSI device configurations
5167 * @sdev: pointer to SCSI device
5169 static void ufshcd_slave_destroy(struct scsi_device *sdev)
5171 struct ufs_hba *hba;
5172 unsigned long flags;
5174 hba = shost_priv(sdev->host);
5176 ufshcd_hpb_destroy(hba, sdev);
5178 /* Drop the reference as it won't be needed anymore */
5179 if (ufshcd_scsi_to_upiu_lun(sdev->lun) == UFS_UPIU_UFS_DEVICE_WLUN) {
5180 spin_lock_irqsave(hba->host->host_lock, flags);
5181 hba->ufs_device_wlun = NULL;
5182 spin_unlock_irqrestore(hba->host->host_lock, flags);
5183 } else if (hba->ufs_device_wlun) {
5184 struct device *supplier = NULL;
5186 /* Ensure UFS Device WLUN exists and does not disappear */
5187 spin_lock_irqsave(hba->host->host_lock, flags);
5188 if (hba->ufs_device_wlun) {
5189 supplier = &hba->ufs_device_wlun->sdev_gendev;
5190 get_device(supplier);
5192 spin_unlock_irqrestore(hba->host->host_lock, flags);
5196 * If a LUN fails to probe (e.g. absent BOOT WLUN), the
5197 * device will not have been registered but can still
5198 * have a device link holding a reference to the device.
5200 device_link_remove(&sdev->sdev_gendev, supplier);
5201 put_device(supplier);
5207 * ufshcd_scsi_cmd_status - Update SCSI command result based on SCSI status
5208 * @lrbp: pointer to local reference block of completed command
5209 * @scsi_status: SCSI command status
5211 * Returns value base on SCSI command status
5214 ufshcd_scsi_cmd_status(struct ufshcd_lrb *lrbp, int scsi_status)
5218 switch (scsi_status) {
5219 case SAM_STAT_CHECK_CONDITION:
5220 ufshcd_copy_sense_data(lrbp);
5223 result |= DID_OK << 16 | scsi_status;
5225 case SAM_STAT_TASK_SET_FULL:
5227 case SAM_STAT_TASK_ABORTED:
5228 ufshcd_copy_sense_data(lrbp);
5229 result |= scsi_status;
5232 result |= DID_ERROR << 16;
5234 } /* end of switch */
5240 * ufshcd_transfer_rsp_status - Get overall status of the response
5241 * @hba: per adapter instance
5242 * @lrbp: pointer to local reference block of completed command
5243 * @cqe: pointer to the completion queue entry
5245 * Returns result of the command to notify SCSI midlayer
5248 ufshcd_transfer_rsp_status(struct ufs_hba *hba, struct ufshcd_lrb *lrbp,
5249 struct cq_entry *cqe)
5255 scsi_set_resid(lrbp->cmd,
5256 be32_to_cpu(lrbp->ucd_rsp_ptr->sr.residual_transfer_count));
5258 /* overall command status of utrd */
5259 ocs = ufshcd_get_tr_ocs(lrbp, cqe);
5261 if (hba->quirks & UFSHCD_QUIRK_BROKEN_OCS_FATAL_ERROR) {
5262 if (be32_to_cpu(lrbp->ucd_rsp_ptr->header.dword_1) &
5263 MASK_RSP_UPIU_RESULT)
5269 result = ufshcd_get_req_rsp(lrbp->ucd_rsp_ptr);
5270 hba->ufs_stats.last_hibern8_exit_tstamp = ktime_set(0, 0);
5272 case UPIU_TRANSACTION_RESPONSE:
5274 * get the response UPIU result to extract
5275 * the SCSI command status
5277 result = ufshcd_get_rsp_upiu_result(lrbp->ucd_rsp_ptr);
5280 * get the result based on SCSI status response
5281 * to notify the SCSI midlayer of the command status
5283 scsi_status = result & MASK_SCSI_STATUS;
5284 result = ufshcd_scsi_cmd_status(lrbp, scsi_status);
5287 * Currently we are only supporting BKOPs exception
5288 * events hence we can ignore BKOPs exception event
5289 * during power management callbacks. BKOPs exception
5290 * event is not expected to be raised in runtime suspend
5291 * callback as it allows the urgent bkops.
5292 * During system suspend, we are anyway forcefully
5293 * disabling the bkops and if urgent bkops is needed
5294 * it will be enabled on system resume. Long term
5295 * solution could be to abort the system suspend if
5296 * UFS device needs urgent BKOPs.
5298 if (!hba->pm_op_in_progress &&
5299 !ufshcd_eh_in_progress(hba) &&
5300 ufshcd_is_exception_event(lrbp->ucd_rsp_ptr))
5301 /* Flushed in suspend */
5302 schedule_work(&hba->eeh_work);
5304 if (scsi_status == SAM_STAT_GOOD)
5305 ufshpb_rsp_upiu(hba, lrbp);
5307 case UPIU_TRANSACTION_REJECT_UPIU:
5308 /* TODO: handle Reject UPIU Response */
5309 result = DID_ERROR << 16;
5311 "Reject UPIU not fully implemented\n");
5315 "Unexpected request response code = %x\n",
5317 result = DID_ERROR << 16;
5322 result |= DID_ABORT << 16;
5324 case OCS_INVALID_COMMAND_STATUS:
5325 result |= DID_REQUEUE << 16;
5327 case OCS_INVALID_CMD_TABLE_ATTR:
5328 case OCS_INVALID_PRDT_ATTR:
5329 case OCS_MISMATCH_DATA_BUF_SIZE:
5330 case OCS_MISMATCH_RESP_UPIU_SIZE:
5331 case OCS_PEER_COMM_FAILURE:
5332 case OCS_FATAL_ERROR:
5333 case OCS_DEVICE_FATAL_ERROR:
5334 case OCS_INVALID_CRYPTO_CONFIG:
5335 case OCS_GENERAL_CRYPTO_ERROR:
5337 result |= DID_ERROR << 16;
5339 "OCS error from controller = %x for tag %d\n",
5340 ocs, lrbp->task_tag);
5341 ufshcd_print_evt_hist(hba);
5342 ufshcd_print_host_state(hba);
5344 } /* end of switch */
5346 if ((host_byte(result) != DID_OK) &&
5347 (host_byte(result) != DID_REQUEUE) && !hba->silence_err_logs)
5348 ufshcd_print_tr(hba, lrbp->task_tag, true);
5352 static bool ufshcd_is_auto_hibern8_error(struct ufs_hba *hba,
5355 if (!ufshcd_is_auto_hibern8_supported(hba) ||
5356 !ufshcd_is_auto_hibern8_enabled(hba))
5359 if (!(intr_mask & UFSHCD_UIC_HIBERN8_MASK))
5362 if (hba->active_uic_cmd &&
5363 (hba->active_uic_cmd->command == UIC_CMD_DME_HIBER_ENTER ||
5364 hba->active_uic_cmd->command == UIC_CMD_DME_HIBER_EXIT))
5371 * ufshcd_uic_cmd_compl - handle completion of uic command
5372 * @hba: per adapter instance
5373 * @intr_status: interrupt status generated by the controller
5376 * IRQ_HANDLED - If interrupt is valid
5377 * IRQ_NONE - If invalid interrupt
5379 static irqreturn_t ufshcd_uic_cmd_compl(struct ufs_hba *hba, u32 intr_status)
5381 irqreturn_t retval = IRQ_NONE;
5383 spin_lock(hba->host->host_lock);
5384 if (ufshcd_is_auto_hibern8_error(hba, intr_status))
5385 hba->errors |= (UFSHCD_UIC_HIBERN8_MASK & intr_status);
5387 if ((intr_status & UIC_COMMAND_COMPL) && hba->active_uic_cmd) {
5388 hba->active_uic_cmd->argument2 |=
5389 ufshcd_get_uic_cmd_result(hba);
5390 hba->active_uic_cmd->argument3 =
5391 ufshcd_get_dme_attr_val(hba);
5392 if (!hba->uic_async_done)
5393 hba->active_uic_cmd->cmd_active = 0;
5394 complete(&hba->active_uic_cmd->done);
5395 retval = IRQ_HANDLED;
5398 if ((intr_status & UFSHCD_UIC_PWR_MASK) && hba->uic_async_done) {
5399 hba->active_uic_cmd->cmd_active = 0;
5400 complete(hba->uic_async_done);
5401 retval = IRQ_HANDLED;
5404 if (retval == IRQ_HANDLED)
5405 ufshcd_add_uic_command_trace(hba, hba->active_uic_cmd,
5407 spin_unlock(hba->host->host_lock);
5411 /* Release the resources allocated for processing a SCSI command. */
5412 void ufshcd_release_scsi_cmd(struct ufs_hba *hba,
5413 struct ufshcd_lrb *lrbp)
5415 struct scsi_cmnd *cmd = lrbp->cmd;
5417 scsi_dma_unmap(cmd);
5418 ufshcd_release(hba);
5419 ufshcd_clk_scaling_update_busy(hba);
5423 * ufshcd_compl_one_cqe - handle a completion queue entry
5424 * @hba: per adapter instance
5425 * @task_tag: the task tag of the request to be completed
5426 * @cqe: pointer to the completion queue entry
5428 void ufshcd_compl_one_cqe(struct ufs_hba *hba, int task_tag,
5429 struct cq_entry *cqe)
5431 struct ufshcd_lrb *lrbp;
5432 struct scsi_cmnd *cmd;
5435 lrbp = &hba->lrb[task_tag];
5436 lrbp->compl_time_stamp = ktime_get();
5439 if (unlikely(ufshcd_should_inform_monitor(hba, lrbp)))
5440 ufshcd_update_monitor(hba, lrbp);
5441 ufshcd_add_command_trace(hba, task_tag, UFS_CMD_COMP);
5442 cmd->result = ufshcd_transfer_rsp_status(hba, lrbp, cqe);
5443 ufshcd_release_scsi_cmd(hba, lrbp);
5444 /* Do not touch lrbp after scsi done */
5446 } else if (lrbp->command_type == UTP_CMD_TYPE_DEV_MANAGE ||
5447 lrbp->command_type == UTP_CMD_TYPE_UFS_STORAGE) {
5448 if (hba->dev_cmd.complete) {
5450 ocs = le32_to_cpu(cqe->status) & MASK_OCS;
5451 lrbp->utr_descriptor_ptr->header.dword_2 =
5454 complete(hba->dev_cmd.complete);
5455 ufshcd_clk_scaling_update_busy(hba);
5461 * __ufshcd_transfer_req_compl - handle SCSI and query command completion
5462 * @hba: per adapter instance
5463 * @completed_reqs: bitmask that indicates which requests to complete
5465 static void __ufshcd_transfer_req_compl(struct ufs_hba *hba,
5466 unsigned long completed_reqs)
5470 for_each_set_bit(tag, &completed_reqs, hba->nutrs)
5471 ufshcd_compl_one_cqe(hba, tag, NULL);
5474 /* Any value that is not an existing queue number is fine for this constant. */
5476 UFSHCD_POLL_FROM_INTERRUPT_CONTEXT = -1
5479 static void ufshcd_clear_polled(struct ufs_hba *hba,
5480 unsigned long *completed_reqs)
5484 for_each_set_bit(tag, completed_reqs, hba->nutrs) {
5485 struct scsi_cmnd *cmd = hba->lrb[tag].cmd;
5489 if (scsi_cmd_to_rq(cmd)->cmd_flags & REQ_POLLED)
5490 __clear_bit(tag, completed_reqs);
5495 * Returns > 0 if one or more commands have been completed or 0 if no
5496 * requests have been completed.
5498 static int ufshcd_poll(struct Scsi_Host *shost, unsigned int queue_num)
5500 struct ufs_hba *hba = shost_priv(shost);
5501 unsigned long completed_reqs, flags;
5503 struct ufs_hw_queue *hwq;
5505 if (is_mcq_enabled(hba)) {
5506 hwq = &hba->uhq[queue_num];
5508 return ufshcd_mcq_poll_cqe_lock(hba, hwq);
5511 spin_lock_irqsave(&hba->outstanding_lock, flags);
5512 tr_doorbell = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
5513 completed_reqs = ~tr_doorbell & hba->outstanding_reqs;
5514 WARN_ONCE(completed_reqs & ~hba->outstanding_reqs,
5515 "completed: %#lx; outstanding: %#lx\n", completed_reqs,
5516 hba->outstanding_reqs);
5517 if (queue_num == UFSHCD_POLL_FROM_INTERRUPT_CONTEXT) {
5518 /* Do not complete polled requests from interrupt context. */
5519 ufshcd_clear_polled(hba, &completed_reqs);
5521 hba->outstanding_reqs &= ~completed_reqs;
5522 spin_unlock_irqrestore(&hba->outstanding_lock, flags);
5525 __ufshcd_transfer_req_compl(hba, completed_reqs);
5527 return completed_reqs != 0;
5531 * ufshcd_mcq_compl_pending_transfer - MCQ mode function. It is
5532 * invoked from the error handler context or ufshcd_host_reset_and_restore()
5533 * to complete the pending transfers and free the resources associated with
5536 * @hba: per adapter instance
5537 * @force_compl: This flag is set to true when invoked
5538 * from ufshcd_host_reset_and_restore() in which case it requires special
5539 * handling because the host controller has been reset by ufshcd_hba_stop().
5541 static void ufshcd_mcq_compl_pending_transfer(struct ufs_hba *hba,
5544 struct ufs_hw_queue *hwq;
5545 struct ufshcd_lrb *lrbp;
5546 struct scsi_cmnd *cmd;
5547 unsigned long flags;
5551 for (tag = 0; tag < hba->nutrs; tag++) {
5552 lrbp = &hba->lrb[tag];
5554 if (!ufshcd_cmd_inflight(cmd) ||
5555 test_bit(SCMD_STATE_COMPLETE, &cmd->state))
5558 utag = blk_mq_unique_tag(scsi_cmd_to_rq(cmd));
5559 hwq_num = blk_mq_unique_tag_to_hwq(utag);
5560 hwq = &hba->uhq[hwq_num];
5563 ufshcd_mcq_compl_all_cqes_lock(hba, hwq);
5565 * For those cmds of which the cqes are not present
5566 * in the cq, complete them explicitly.
5568 if (cmd && !test_bit(SCMD_STATE_COMPLETE, &cmd->state)) {
5569 spin_lock_irqsave(&hwq->cq_lock, flags);
5570 set_host_byte(cmd, DID_REQUEUE);
5571 ufshcd_release_scsi_cmd(hba, lrbp);
5573 spin_unlock_irqrestore(&hwq->cq_lock, flags);
5576 ufshcd_mcq_poll_cqe_lock(hba, hwq);
5582 * ufshcd_transfer_req_compl - handle SCSI and query command completion
5583 * @hba: per adapter instance
5586 * IRQ_HANDLED - If interrupt is valid
5587 * IRQ_NONE - If invalid interrupt
5589 static irqreturn_t ufshcd_transfer_req_compl(struct ufs_hba *hba)
5591 /* Resetting interrupt aggregation counters first and reading the
5592 * DOOR_BELL afterward allows us to handle all the completed requests.
5593 * In order to prevent other interrupts starvation the DB is read once
5594 * after reset. The down side of this solution is the possibility of
5595 * false interrupt if device completes another request after resetting
5596 * aggregation and before reading the DB.
5598 if (ufshcd_is_intr_aggr_allowed(hba) &&
5599 !(hba->quirks & UFSHCI_QUIRK_SKIP_RESET_INTR_AGGR))
5600 ufshcd_reset_intr_aggr(hba);
5602 if (ufs_fail_completion())
5606 * Ignore the ufshcd_poll() return value and return IRQ_HANDLED since we
5607 * do not want polling to trigger spurious interrupt complaints.
5609 ufshcd_poll(hba->host, UFSHCD_POLL_FROM_INTERRUPT_CONTEXT);
5614 int __ufshcd_write_ee_control(struct ufs_hba *hba, u32 ee_ctrl_mask)
5616 return ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_WRITE_ATTR,
5617 QUERY_ATTR_IDN_EE_CONTROL, 0, 0,
5621 int ufshcd_write_ee_control(struct ufs_hba *hba)
5625 mutex_lock(&hba->ee_ctrl_mutex);
5626 err = __ufshcd_write_ee_control(hba, hba->ee_ctrl_mask);
5627 mutex_unlock(&hba->ee_ctrl_mutex);
5629 dev_err(hba->dev, "%s: failed to write ee control %d\n",
5634 int ufshcd_update_ee_control(struct ufs_hba *hba, u16 *mask,
5635 const u16 *other_mask, u16 set, u16 clr)
5637 u16 new_mask, ee_ctrl_mask;
5640 mutex_lock(&hba->ee_ctrl_mutex);
5641 new_mask = (*mask & ~clr) | set;
5642 ee_ctrl_mask = new_mask | *other_mask;
5643 if (ee_ctrl_mask != hba->ee_ctrl_mask)
5644 err = __ufshcd_write_ee_control(hba, ee_ctrl_mask);
5645 /* Still need to update 'mask' even if 'ee_ctrl_mask' was unchanged */
5647 hba->ee_ctrl_mask = ee_ctrl_mask;
5650 mutex_unlock(&hba->ee_ctrl_mutex);
5655 * ufshcd_disable_ee - disable exception event
5656 * @hba: per-adapter instance
5657 * @mask: exception event to disable
5659 * Disables exception event in the device so that the EVENT_ALERT
5662 * Returns zero on success, non-zero error value on failure.
5664 static inline int ufshcd_disable_ee(struct ufs_hba *hba, u16 mask)
5666 return ufshcd_update_ee_drv_mask(hba, 0, mask);
5670 * ufshcd_enable_ee - enable exception event
5671 * @hba: per-adapter instance
5672 * @mask: exception event to enable
5674 * Enable corresponding exception event in the device to allow
5675 * device to alert host in critical scenarios.
5677 * Returns zero on success, non-zero error value on failure.
5679 static inline int ufshcd_enable_ee(struct ufs_hba *hba, u16 mask)
5681 return ufshcd_update_ee_drv_mask(hba, mask, 0);
5685 * ufshcd_enable_auto_bkops - Allow device managed BKOPS
5686 * @hba: per-adapter instance
5688 * Allow device to manage background operations on its own. Enabling
5689 * this might lead to inconsistent latencies during normal data transfers
5690 * as the device is allowed to manage its own way of handling background
5693 * Returns zero on success, non-zero on failure.
5695 static int ufshcd_enable_auto_bkops(struct ufs_hba *hba)
5699 if (hba->auto_bkops_enabled)
5702 err = ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_SET_FLAG,
5703 QUERY_FLAG_IDN_BKOPS_EN, 0, NULL);
5705 dev_err(hba->dev, "%s: failed to enable bkops %d\n",
5710 hba->auto_bkops_enabled = true;
5711 trace_ufshcd_auto_bkops_state(dev_name(hba->dev), "Enabled");
5713 /* No need of URGENT_BKOPS exception from the device */
5714 err = ufshcd_disable_ee(hba, MASK_EE_URGENT_BKOPS);
5716 dev_err(hba->dev, "%s: failed to disable exception event %d\n",
5723 * ufshcd_disable_auto_bkops - block device in doing background operations
5724 * @hba: per-adapter instance
5726 * Disabling background operations improves command response latency but
5727 * has drawback of device moving into critical state where the device is
5728 * not-operable. Make sure to call ufshcd_enable_auto_bkops() whenever the
5729 * host is idle so that BKOPS are managed effectively without any negative
5732 * Returns zero on success, non-zero on failure.
5734 static int ufshcd_disable_auto_bkops(struct ufs_hba *hba)
5738 if (!hba->auto_bkops_enabled)
5742 * If host assisted BKOPs is to be enabled, make sure
5743 * urgent bkops exception is allowed.
5745 err = ufshcd_enable_ee(hba, MASK_EE_URGENT_BKOPS);
5747 dev_err(hba->dev, "%s: failed to enable exception event %d\n",
5752 err = ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_CLEAR_FLAG,
5753 QUERY_FLAG_IDN_BKOPS_EN, 0, NULL);
5755 dev_err(hba->dev, "%s: failed to disable bkops %d\n",
5757 ufshcd_disable_ee(hba, MASK_EE_URGENT_BKOPS);
5761 hba->auto_bkops_enabled = false;
5762 trace_ufshcd_auto_bkops_state(dev_name(hba->dev), "Disabled");
5763 hba->is_urgent_bkops_lvl_checked = false;
5769 * ufshcd_force_reset_auto_bkops - force reset auto bkops state
5770 * @hba: per adapter instance
5772 * After a device reset the device may toggle the BKOPS_EN flag
5773 * to default value. The s/w tracking variables should be updated
5774 * as well. This function would change the auto-bkops state based on
5775 * UFSHCD_CAP_KEEP_AUTO_BKOPS_ENABLED_EXCEPT_SUSPEND.
5777 static void ufshcd_force_reset_auto_bkops(struct ufs_hba *hba)
5779 if (ufshcd_keep_autobkops_enabled_except_suspend(hba)) {
5780 hba->auto_bkops_enabled = false;
5781 hba->ee_ctrl_mask |= MASK_EE_URGENT_BKOPS;
5782 ufshcd_enable_auto_bkops(hba);
5784 hba->auto_bkops_enabled = true;
5785 hba->ee_ctrl_mask &= ~MASK_EE_URGENT_BKOPS;
5786 ufshcd_disable_auto_bkops(hba);
5788 hba->urgent_bkops_lvl = BKOPS_STATUS_PERF_IMPACT;
5789 hba->is_urgent_bkops_lvl_checked = false;
5792 static inline int ufshcd_get_bkops_status(struct ufs_hba *hba, u32 *status)
5794 return ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
5795 QUERY_ATTR_IDN_BKOPS_STATUS, 0, 0, status);
5799 * ufshcd_bkops_ctrl - control the auto bkops based on current bkops status
5800 * @hba: per-adapter instance
5801 * @status: bkops_status value
5803 * Read the bkops_status from the UFS device and Enable fBackgroundOpsEn
5804 * flag in the device to permit background operations if the device
5805 * bkops_status is greater than or equal to "status" argument passed to
5806 * this function, disable otherwise.
5808 * Returns 0 for success, non-zero in case of failure.
5810 * NOTE: Caller of this function can check the "hba->auto_bkops_enabled" flag
5811 * to know whether auto bkops is enabled or disabled after this function
5812 * returns control to it.
5814 static int ufshcd_bkops_ctrl(struct ufs_hba *hba,
5815 enum bkops_status status)
5818 u32 curr_status = 0;
5820 err = ufshcd_get_bkops_status(hba, &curr_status);
5822 dev_err(hba->dev, "%s: failed to get BKOPS status %d\n",
5825 } else if (curr_status > BKOPS_STATUS_MAX) {
5826 dev_err(hba->dev, "%s: invalid BKOPS status %d\n",
5827 __func__, curr_status);
5832 if (curr_status >= status)
5833 err = ufshcd_enable_auto_bkops(hba);
5835 err = ufshcd_disable_auto_bkops(hba);
5841 * ufshcd_urgent_bkops - handle urgent bkops exception event
5842 * @hba: per-adapter instance
5844 * Enable fBackgroundOpsEn flag in the device to permit background
5847 * If BKOPs is enabled, this function returns 0, 1 if the bkops in not enabled
5848 * and negative error value for any other failure.
5850 static int ufshcd_urgent_bkops(struct ufs_hba *hba)
5852 return ufshcd_bkops_ctrl(hba, hba->urgent_bkops_lvl);
5855 static inline int ufshcd_get_ee_status(struct ufs_hba *hba, u32 *status)
5857 return ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
5858 QUERY_ATTR_IDN_EE_STATUS, 0, 0, status);
5861 static void ufshcd_bkops_exception_event_handler(struct ufs_hba *hba)
5864 u32 curr_status = 0;
5866 if (hba->is_urgent_bkops_lvl_checked)
5867 goto enable_auto_bkops;
5869 err = ufshcd_get_bkops_status(hba, &curr_status);
5871 dev_err(hba->dev, "%s: failed to get BKOPS status %d\n",
5877 * We are seeing that some devices are raising the urgent bkops
5878 * exception events even when BKOPS status doesn't indicate performace
5879 * impacted or critical. Handle these device by determining their urgent
5880 * bkops status at runtime.
5882 if (curr_status < BKOPS_STATUS_PERF_IMPACT) {
5883 dev_err(hba->dev, "%s: device raised urgent BKOPS exception for bkops status %d\n",
5884 __func__, curr_status);
5885 /* update the current status as the urgent bkops level */
5886 hba->urgent_bkops_lvl = curr_status;
5887 hba->is_urgent_bkops_lvl_checked = true;
5891 err = ufshcd_enable_auto_bkops(hba);
5894 dev_err(hba->dev, "%s: failed to handle urgent bkops %d\n",
5898 static void ufshcd_temp_exception_event_handler(struct ufs_hba *hba, u16 status)
5902 if (ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
5903 QUERY_ATTR_IDN_CASE_ROUGH_TEMP, 0, 0, &value))
5906 dev_info(hba->dev, "exception Tcase %d\n", value - 80);
5908 ufs_hwmon_notify_event(hba, status & MASK_EE_URGENT_TEMP);
5911 * A placeholder for the platform vendors to add whatever additional
5916 static int __ufshcd_wb_toggle(struct ufs_hba *hba, bool set, enum flag_idn idn)
5919 enum query_opcode opcode = set ? UPIU_QUERY_OPCODE_SET_FLAG :
5920 UPIU_QUERY_OPCODE_CLEAR_FLAG;
5922 index = ufshcd_wb_get_query_index(hba);
5923 return ufshcd_query_flag_retry(hba, opcode, idn, index, NULL);
5926 int ufshcd_wb_toggle(struct ufs_hba *hba, bool enable)
5930 if (!ufshcd_is_wb_allowed(hba) ||
5931 hba->dev_info.wb_enabled == enable)
5934 ret = __ufshcd_wb_toggle(hba, enable, QUERY_FLAG_IDN_WB_EN);
5936 dev_err(hba->dev, "%s: Write Booster %s failed %d\n",
5937 __func__, enable ? "enabling" : "disabling", ret);
5941 hba->dev_info.wb_enabled = enable;
5942 dev_dbg(hba->dev, "%s: Write Booster %s\n",
5943 __func__, enable ? "enabled" : "disabled");
5948 static void ufshcd_wb_toggle_buf_flush_during_h8(struct ufs_hba *hba,
5953 ret = __ufshcd_wb_toggle(hba, enable,
5954 QUERY_FLAG_IDN_WB_BUFF_FLUSH_DURING_HIBERN8);
5956 dev_err(hba->dev, "%s: WB-Buf Flush during H8 %s failed %d\n",
5957 __func__, enable ? "enabling" : "disabling", ret);
5960 dev_dbg(hba->dev, "%s: WB-Buf Flush during H8 %s\n",
5961 __func__, enable ? "enabled" : "disabled");
5964 int ufshcd_wb_toggle_buf_flush(struct ufs_hba *hba, bool enable)
5968 if (!ufshcd_is_wb_allowed(hba) ||
5969 hba->dev_info.wb_buf_flush_enabled == enable)
5972 ret = __ufshcd_wb_toggle(hba, enable, QUERY_FLAG_IDN_WB_BUFF_FLUSH_EN);
5974 dev_err(hba->dev, "%s: WB-Buf Flush %s failed %d\n",
5975 __func__, enable ? "enabling" : "disabling", ret);
5979 hba->dev_info.wb_buf_flush_enabled = enable;
5980 dev_dbg(hba->dev, "%s: WB-Buf Flush %s\n",
5981 __func__, enable ? "enabled" : "disabled");
5986 static bool ufshcd_wb_presrv_usrspc_keep_vcc_on(struct ufs_hba *hba,
5993 index = ufshcd_wb_get_query_index(hba);
5994 ret = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
5995 QUERY_ATTR_IDN_CURR_WB_BUFF_SIZE,
5996 index, 0, &cur_buf);
5998 dev_err(hba->dev, "%s: dCurWriteBoosterBufferSize read failed %d\n",
6004 dev_info(hba->dev, "dCurWBBuf: %d WB disabled until free-space is available\n",
6008 /* Let it continue to flush when available buffer exceeds threshold */
6009 return avail_buf < hba->vps->wb_flush_threshold;
6012 static void ufshcd_wb_force_disable(struct ufs_hba *hba)
6014 if (ufshcd_is_wb_buf_flush_allowed(hba))
6015 ufshcd_wb_toggle_buf_flush(hba, false);
6017 ufshcd_wb_toggle_buf_flush_during_h8(hba, false);
6018 ufshcd_wb_toggle(hba, false);
6019 hba->caps &= ~UFSHCD_CAP_WB_EN;
6021 dev_info(hba->dev, "%s: WB force disabled\n", __func__);
6024 static bool ufshcd_is_wb_buf_lifetime_available(struct ufs_hba *hba)
6030 index = ufshcd_wb_get_query_index(hba);
6031 ret = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
6032 QUERY_ATTR_IDN_WB_BUFF_LIFE_TIME_EST,
6033 index, 0, &lifetime);
6036 "%s: bWriteBoosterBufferLifeTimeEst read failed %d\n",
6041 if (lifetime == UFS_WB_EXCEED_LIFETIME) {
6042 dev_err(hba->dev, "%s: WB buf lifetime is exhausted 0x%02X\n",
6043 __func__, lifetime);
6047 dev_dbg(hba->dev, "%s: WB buf lifetime is 0x%02X\n",
6048 __func__, lifetime);
6053 static bool ufshcd_wb_need_flush(struct ufs_hba *hba)
6059 if (!ufshcd_is_wb_allowed(hba))
6062 if (!ufshcd_is_wb_buf_lifetime_available(hba)) {
6063 ufshcd_wb_force_disable(hba);
6068 * The ufs device needs the vcc to be ON to flush.
6069 * With user-space reduction enabled, it's enough to enable flush
6070 * by checking only the available buffer. The threshold
6071 * defined here is > 90% full.
6072 * With user-space preserved enabled, the current-buffer
6073 * should be checked too because the wb buffer size can reduce
6074 * when disk tends to be full. This info is provided by current
6075 * buffer (dCurrentWriteBoosterBufferSize). There's no point in
6076 * keeping vcc on when current buffer is empty.
6078 index = ufshcd_wb_get_query_index(hba);
6079 ret = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
6080 QUERY_ATTR_IDN_AVAIL_WB_BUFF_SIZE,
6081 index, 0, &avail_buf);
6083 dev_warn(hba->dev, "%s: dAvailableWriteBoosterBufferSize read failed %d\n",
6088 if (!hba->dev_info.b_presrv_uspc_en)
6089 return avail_buf <= UFS_WB_BUF_REMAIN_PERCENT(10);
6091 return ufshcd_wb_presrv_usrspc_keep_vcc_on(hba, avail_buf);
6094 static void ufshcd_rpm_dev_flush_recheck_work(struct work_struct *work)
6096 struct ufs_hba *hba = container_of(to_delayed_work(work),
6098 rpm_dev_flush_recheck_work);
6100 * To prevent unnecessary VCC power drain after device finishes
6101 * WriteBooster buffer flush or Auto BKOPs, force runtime resume
6102 * after a certain delay to recheck the threshold by next runtime
6105 ufshcd_rpm_get_sync(hba);
6106 ufshcd_rpm_put_sync(hba);
6110 * ufshcd_exception_event_handler - handle exceptions raised by device
6111 * @work: pointer to work data
6113 * Read bExceptionEventStatus attribute from the device and handle the
6114 * exception event accordingly.
6116 static void ufshcd_exception_event_handler(struct work_struct *work)
6118 struct ufs_hba *hba;
6121 hba = container_of(work, struct ufs_hba, eeh_work);
6123 ufshcd_scsi_block_requests(hba);
6124 err = ufshcd_get_ee_status(hba, &status);
6126 dev_err(hba->dev, "%s: failed to get exception status %d\n",
6131 trace_ufshcd_exception_event(dev_name(hba->dev), status);
6133 if (status & hba->ee_drv_mask & MASK_EE_URGENT_BKOPS)
6134 ufshcd_bkops_exception_event_handler(hba);
6136 if (status & hba->ee_drv_mask & MASK_EE_URGENT_TEMP)
6137 ufshcd_temp_exception_event_handler(hba, status);
6139 ufs_debugfs_exception_event(hba, status);
6141 ufshcd_scsi_unblock_requests(hba);
6144 /* Complete requests that have door-bell cleared */
6145 static void ufshcd_complete_requests(struct ufs_hba *hba, bool force_compl)
6147 if (is_mcq_enabled(hba))
6148 ufshcd_mcq_compl_pending_transfer(hba, force_compl);
6150 ufshcd_transfer_req_compl(hba);
6152 ufshcd_tmc_handler(hba);
6156 * ufshcd_quirk_dl_nac_errors - This function checks if error handling is
6157 * to recover from the DL NAC errors or not.
6158 * @hba: per-adapter instance
6160 * Returns true if error handling is required, false otherwise
6162 static bool ufshcd_quirk_dl_nac_errors(struct ufs_hba *hba)
6164 unsigned long flags;
6165 bool err_handling = true;
6167 spin_lock_irqsave(hba->host->host_lock, flags);
6169 * UFS_DEVICE_QUIRK_RECOVERY_FROM_DL_NAC_ERRORS only workaround the
6170 * device fatal error and/or DL NAC & REPLAY timeout errors.
6172 if (hba->saved_err & (CONTROLLER_FATAL_ERROR | SYSTEM_BUS_FATAL_ERROR))
6175 if ((hba->saved_err & DEVICE_FATAL_ERROR) ||
6176 ((hba->saved_err & UIC_ERROR) &&
6177 (hba->saved_uic_err & UFSHCD_UIC_DL_TCx_REPLAY_ERROR)))
6180 if ((hba->saved_err & UIC_ERROR) &&
6181 (hba->saved_uic_err & UFSHCD_UIC_DL_NAC_RECEIVED_ERROR)) {
6184 * wait for 50ms to see if we can get any other errors or not.
6186 spin_unlock_irqrestore(hba->host->host_lock, flags);
6188 spin_lock_irqsave(hba->host->host_lock, flags);
6191 * now check if we have got any other severe errors other than
6194 if ((hba->saved_err & INT_FATAL_ERRORS) ||
6195 ((hba->saved_err & UIC_ERROR) &&
6196 (hba->saved_uic_err & ~UFSHCD_UIC_DL_NAC_RECEIVED_ERROR)))
6200 * As DL NAC is the only error received so far, send out NOP
6201 * command to confirm if link is still active or not.
6202 * - If we don't get any response then do error recovery.
6203 * - If we get response then clear the DL NAC error bit.
6206 spin_unlock_irqrestore(hba->host->host_lock, flags);
6207 err = ufshcd_verify_dev_init(hba);
6208 spin_lock_irqsave(hba->host->host_lock, flags);
6213 /* Link seems to be alive hence ignore the DL NAC errors */
6214 if (hba->saved_uic_err == UFSHCD_UIC_DL_NAC_RECEIVED_ERROR)
6215 hba->saved_err &= ~UIC_ERROR;
6216 /* clear NAC error */
6217 hba->saved_uic_err &= ~UFSHCD_UIC_DL_NAC_RECEIVED_ERROR;
6218 if (!hba->saved_uic_err)
6219 err_handling = false;
6222 spin_unlock_irqrestore(hba->host->host_lock, flags);
6223 return err_handling;
6226 /* host lock must be held before calling this func */
6227 static inline bool ufshcd_is_saved_err_fatal(struct ufs_hba *hba)
6229 return (hba->saved_uic_err & UFSHCD_UIC_DL_PA_INIT_ERROR) ||
6230 (hba->saved_err & (INT_FATAL_ERRORS | UFSHCD_UIC_HIBERN8_MASK));
6233 void ufshcd_schedule_eh_work(struct ufs_hba *hba)
6235 lockdep_assert_held(hba->host->host_lock);
6237 /* handle fatal errors only when link is not in error state */
6238 if (hba->ufshcd_state != UFSHCD_STATE_ERROR) {
6239 if (hba->force_reset || ufshcd_is_link_broken(hba) ||
6240 ufshcd_is_saved_err_fatal(hba))
6241 hba->ufshcd_state = UFSHCD_STATE_EH_SCHEDULED_FATAL;
6243 hba->ufshcd_state = UFSHCD_STATE_EH_SCHEDULED_NON_FATAL;
6244 queue_work(hba->eh_wq, &hba->eh_work);
6248 static void ufshcd_force_error_recovery(struct ufs_hba *hba)
6250 spin_lock_irq(hba->host->host_lock);
6251 hba->force_reset = true;
6252 ufshcd_schedule_eh_work(hba);
6253 spin_unlock_irq(hba->host->host_lock);
6256 static void ufshcd_clk_scaling_allow(struct ufs_hba *hba, bool allow)
6258 mutex_lock(&hba->wb_mutex);
6259 down_write(&hba->clk_scaling_lock);
6260 hba->clk_scaling.is_allowed = allow;
6261 up_write(&hba->clk_scaling_lock);
6262 mutex_unlock(&hba->wb_mutex);
6265 static void ufshcd_clk_scaling_suspend(struct ufs_hba *hba, bool suspend)
6268 if (hba->clk_scaling.is_enabled)
6269 ufshcd_suspend_clkscaling(hba);
6270 ufshcd_clk_scaling_allow(hba, false);
6272 ufshcd_clk_scaling_allow(hba, true);
6273 if (hba->clk_scaling.is_enabled)
6274 ufshcd_resume_clkscaling(hba);
6278 static void ufshcd_err_handling_prepare(struct ufs_hba *hba)
6280 ufshcd_rpm_get_sync(hba);
6281 if (pm_runtime_status_suspended(&hba->ufs_device_wlun->sdev_gendev) ||
6282 hba->is_sys_suspended) {
6283 enum ufs_pm_op pm_op;
6286 * Don't assume anything of resume, if
6287 * resume fails, irq and clocks can be OFF, and powers
6288 * can be OFF or in LPM.
6290 ufshcd_setup_hba_vreg(hba, true);
6291 ufshcd_enable_irq(hba);
6292 ufshcd_setup_vreg(hba, true);
6293 ufshcd_config_vreg_hpm(hba, hba->vreg_info.vccq);
6294 ufshcd_config_vreg_hpm(hba, hba->vreg_info.vccq2);
6296 if (!ufshcd_is_clkgating_allowed(hba))
6297 ufshcd_setup_clocks(hba, true);
6298 ufshcd_release(hba);
6299 pm_op = hba->is_sys_suspended ? UFS_SYSTEM_PM : UFS_RUNTIME_PM;
6300 ufshcd_vops_resume(hba, pm_op);
6303 if (ufshcd_is_clkscaling_supported(hba) &&
6304 hba->clk_scaling.is_enabled)
6305 ufshcd_suspend_clkscaling(hba);
6306 ufshcd_clk_scaling_allow(hba, false);
6308 ufshcd_scsi_block_requests(hba);
6309 /* Wait for ongoing ufshcd_queuecommand() calls to finish. */
6310 blk_mq_wait_quiesce_done(&hba->host->tag_set);
6311 cancel_work_sync(&hba->eeh_work);
6314 static void ufshcd_err_handling_unprepare(struct ufs_hba *hba)
6316 ufshcd_scsi_unblock_requests(hba);
6317 ufshcd_release(hba);
6318 if (ufshcd_is_clkscaling_supported(hba))
6319 ufshcd_clk_scaling_suspend(hba, false);
6320 ufshcd_rpm_put(hba);
6323 static inline bool ufshcd_err_handling_should_stop(struct ufs_hba *hba)
6325 return (!hba->is_powered || hba->shutting_down ||
6326 !hba->ufs_device_wlun ||
6327 hba->ufshcd_state == UFSHCD_STATE_ERROR ||
6328 (!(hba->saved_err || hba->saved_uic_err || hba->force_reset ||
6329 ufshcd_is_link_broken(hba))));
6333 static void ufshcd_recover_pm_error(struct ufs_hba *hba)
6335 struct Scsi_Host *shost = hba->host;
6336 struct scsi_device *sdev;
6337 struct request_queue *q;
6340 hba->is_sys_suspended = false;
6342 * Set RPM status of wlun device to RPM_ACTIVE,
6343 * this also clears its runtime error.
6345 ret = pm_runtime_set_active(&hba->ufs_device_wlun->sdev_gendev);
6347 /* hba device might have a runtime error otherwise */
6349 ret = pm_runtime_set_active(hba->dev);
6351 * If wlun device had runtime error, we also need to resume those
6352 * consumer scsi devices in case any of them has failed to be
6353 * resumed due to supplier runtime resume failure. This is to unblock
6354 * blk_queue_enter in case there are bios waiting inside it.
6357 shost_for_each_device(sdev, shost) {
6358 q = sdev->request_queue;
6359 if (q->dev && (q->rpm_status == RPM_SUSPENDED ||
6360 q->rpm_status == RPM_SUSPENDING))
6361 pm_request_resume(q->dev);
6366 static inline void ufshcd_recover_pm_error(struct ufs_hba *hba)
6371 static bool ufshcd_is_pwr_mode_restore_needed(struct ufs_hba *hba)
6373 struct ufs_pa_layer_attr *pwr_info = &hba->pwr_info;
6376 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_PWRMODE), &mode);
6378 if (pwr_info->pwr_rx != ((mode >> PWRMODE_RX_OFFSET) & PWRMODE_MASK))
6381 if (pwr_info->pwr_tx != (mode & PWRMODE_MASK))
6387 static bool ufshcd_abort_all(struct ufs_hba *hba)
6389 bool needs_reset = false;
6392 if (is_mcq_enabled(hba)) {
6393 struct ufshcd_lrb *lrbp;
6396 for (tag = 0; tag < hba->nutrs; tag++) {
6397 lrbp = &hba->lrb[tag];
6398 if (!ufshcd_cmd_inflight(lrbp->cmd))
6400 ret = ufshcd_try_to_abort_task(hba, tag);
6401 dev_err(hba->dev, "Aborting tag %d / CDB %#02x %s\n", tag,
6402 hba->lrb[tag].cmd ? hba->lrb[tag].cmd->cmnd[0] : -1,
6403 ret ? "failed" : "succeeded");
6410 /* Clear pending transfer requests */
6411 for_each_set_bit(tag, &hba->outstanding_reqs, hba->nutrs) {
6412 ret = ufshcd_try_to_abort_task(hba, tag);
6413 dev_err(hba->dev, "Aborting tag %d / CDB %#02x %s\n", tag,
6414 hba->lrb[tag].cmd ? hba->lrb[tag].cmd->cmnd[0] : -1,
6415 ret ? "failed" : "succeeded");
6422 /* Clear pending task management requests */
6423 for_each_set_bit(tag, &hba->outstanding_tasks, hba->nutmrs) {
6424 if (ufshcd_clear_tm_cmd(hba, tag)) {
6431 /* Complete the requests that are cleared by s/w */
6432 ufshcd_complete_requests(hba, false);
6438 * ufshcd_err_handler - handle UFS errors that require s/w attention
6439 * @work: pointer to work structure
6441 static void ufshcd_err_handler(struct work_struct *work)
6443 int retries = MAX_ERR_HANDLER_RETRIES;
6444 struct ufs_hba *hba;
6445 unsigned long flags;
6450 hba = container_of(work, struct ufs_hba, eh_work);
6453 "%s started; HBA state %s; powered %d; shutting down %d; saved_err = %d; saved_uic_err = %d; force_reset = %d%s\n",
6454 __func__, ufshcd_state_name[hba->ufshcd_state],
6455 hba->is_powered, hba->shutting_down, hba->saved_err,
6456 hba->saved_uic_err, hba->force_reset,
6457 ufshcd_is_link_broken(hba) ? "; link is broken" : "");
6459 down(&hba->host_sem);
6460 spin_lock_irqsave(hba->host->host_lock, flags);
6461 if (ufshcd_err_handling_should_stop(hba)) {
6462 if (hba->ufshcd_state != UFSHCD_STATE_ERROR)
6463 hba->ufshcd_state = UFSHCD_STATE_OPERATIONAL;
6464 spin_unlock_irqrestore(hba->host->host_lock, flags);
6468 ufshcd_set_eh_in_progress(hba);
6469 spin_unlock_irqrestore(hba->host->host_lock, flags);
6470 ufshcd_err_handling_prepare(hba);
6471 /* Complete requests that have door-bell cleared by h/w */
6472 ufshcd_complete_requests(hba, false);
6473 spin_lock_irqsave(hba->host->host_lock, flags);
6475 needs_restore = false;
6476 needs_reset = false;
6478 if (hba->ufshcd_state != UFSHCD_STATE_ERROR)
6479 hba->ufshcd_state = UFSHCD_STATE_RESET;
6481 * A full reset and restore might have happened after preparation
6482 * is finished, double check whether we should stop.
6484 if (ufshcd_err_handling_should_stop(hba))
6485 goto skip_err_handling;
6487 if (hba->dev_quirks & UFS_DEVICE_QUIRK_RECOVERY_FROM_DL_NAC_ERRORS) {
6490 spin_unlock_irqrestore(hba->host->host_lock, flags);
6491 /* release the lock as ufshcd_quirk_dl_nac_errors() may sleep */
6492 ret = ufshcd_quirk_dl_nac_errors(hba);
6493 spin_lock_irqsave(hba->host->host_lock, flags);
6494 if (!ret && ufshcd_err_handling_should_stop(hba))
6495 goto skip_err_handling;
6498 if ((hba->saved_err & (INT_FATAL_ERRORS | UFSHCD_UIC_HIBERN8_MASK)) ||
6499 (hba->saved_uic_err &&
6500 (hba->saved_uic_err != UFSHCD_UIC_PA_GENERIC_ERROR))) {
6501 bool pr_prdt = !!(hba->saved_err & SYSTEM_BUS_FATAL_ERROR);
6503 spin_unlock_irqrestore(hba->host->host_lock, flags);
6504 ufshcd_print_host_state(hba);
6505 ufshcd_print_pwr_info(hba);
6506 ufshcd_print_evt_hist(hba);
6507 ufshcd_print_tmrs(hba, hba->outstanding_tasks);
6508 ufshcd_print_trs_all(hba, pr_prdt);
6509 spin_lock_irqsave(hba->host->host_lock, flags);
6513 * if host reset is required then skip clearing the pending
6514 * transfers forcefully because they will get cleared during
6515 * host reset and restore
6517 if (hba->force_reset || ufshcd_is_link_broken(hba) ||
6518 ufshcd_is_saved_err_fatal(hba) ||
6519 ((hba->saved_err & UIC_ERROR) &&
6520 (hba->saved_uic_err & (UFSHCD_UIC_DL_NAC_RECEIVED_ERROR |
6521 UFSHCD_UIC_DL_TCx_REPLAY_ERROR)))) {
6527 * If LINERESET was caught, UFS might have been put to PWM mode,
6528 * check if power mode restore is needed.
6530 if (hba->saved_uic_err & UFSHCD_UIC_PA_GENERIC_ERROR) {
6531 hba->saved_uic_err &= ~UFSHCD_UIC_PA_GENERIC_ERROR;
6532 if (!hba->saved_uic_err)
6533 hba->saved_err &= ~UIC_ERROR;
6534 spin_unlock_irqrestore(hba->host->host_lock, flags);
6535 if (ufshcd_is_pwr_mode_restore_needed(hba))
6536 needs_restore = true;
6537 spin_lock_irqsave(hba->host->host_lock, flags);
6538 if (!hba->saved_err && !needs_restore)
6539 goto skip_err_handling;
6542 hba->silence_err_logs = true;
6543 /* release lock as clear command might sleep */
6544 spin_unlock_irqrestore(hba->host->host_lock, flags);
6546 needs_reset = ufshcd_abort_all(hba);
6548 spin_lock_irqsave(hba->host->host_lock, flags);
6549 hba->silence_err_logs = false;
6554 * After all reqs and tasks are cleared from doorbell,
6555 * now it is safe to retore power mode.
6557 if (needs_restore) {
6558 spin_unlock_irqrestore(hba->host->host_lock, flags);
6560 * Hold the scaling lock just in case dev cmds
6561 * are sent via bsg and/or sysfs.
6563 down_write(&hba->clk_scaling_lock);
6564 hba->force_pmc = true;
6565 pmc_err = ufshcd_config_pwr_mode(hba, &(hba->pwr_info));
6568 dev_err(hba->dev, "%s: Failed to restore power mode, err = %d\n",
6571 hba->force_pmc = false;
6572 ufshcd_print_pwr_info(hba);
6573 up_write(&hba->clk_scaling_lock);
6574 spin_lock_irqsave(hba->host->host_lock, flags);
6578 /* Fatal errors need reset */
6582 hba->force_reset = false;
6583 spin_unlock_irqrestore(hba->host->host_lock, flags);
6584 err = ufshcd_reset_and_restore(hba);
6586 dev_err(hba->dev, "%s: reset and restore failed with err %d\n",
6589 ufshcd_recover_pm_error(hba);
6590 spin_lock_irqsave(hba->host->host_lock, flags);
6595 if (hba->ufshcd_state == UFSHCD_STATE_RESET)
6596 hba->ufshcd_state = UFSHCD_STATE_OPERATIONAL;
6597 if (hba->saved_err || hba->saved_uic_err)
6598 dev_err_ratelimited(hba->dev, "%s: exit: saved_err 0x%x saved_uic_err 0x%x",
6599 __func__, hba->saved_err, hba->saved_uic_err);
6601 /* Exit in an operational state or dead */
6602 if (hba->ufshcd_state != UFSHCD_STATE_OPERATIONAL &&
6603 hba->ufshcd_state != UFSHCD_STATE_ERROR) {
6606 hba->ufshcd_state = UFSHCD_STATE_ERROR;
6608 ufshcd_clear_eh_in_progress(hba);
6609 spin_unlock_irqrestore(hba->host->host_lock, flags);
6610 ufshcd_err_handling_unprepare(hba);
6613 dev_info(hba->dev, "%s finished; HBA state %s\n", __func__,
6614 ufshcd_state_name[hba->ufshcd_state]);
6618 * ufshcd_update_uic_error - check and set fatal UIC error flags.
6619 * @hba: per-adapter instance
6622 * IRQ_HANDLED - If interrupt is valid
6623 * IRQ_NONE - If invalid interrupt
6625 static irqreturn_t ufshcd_update_uic_error(struct ufs_hba *hba)
6628 irqreturn_t retval = IRQ_NONE;
6630 /* PHY layer error */
6631 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_PHY_ADAPTER_LAYER);
6632 if ((reg & UIC_PHY_ADAPTER_LAYER_ERROR) &&
6633 (reg & UIC_PHY_ADAPTER_LAYER_ERROR_CODE_MASK)) {
6634 ufshcd_update_evt_hist(hba, UFS_EVT_PA_ERR, reg);
6636 * To know whether this error is fatal or not, DB timeout
6637 * must be checked but this error is handled separately.
6639 if (reg & UIC_PHY_ADAPTER_LAYER_LANE_ERR_MASK)
6640 dev_dbg(hba->dev, "%s: UIC Lane error reported\n",
6643 /* Got a LINERESET indication. */
6644 if (reg & UIC_PHY_ADAPTER_LAYER_GENERIC_ERROR) {
6645 struct uic_command *cmd = NULL;
6647 hba->uic_error |= UFSHCD_UIC_PA_GENERIC_ERROR;
6648 if (hba->uic_async_done && hba->active_uic_cmd)
6649 cmd = hba->active_uic_cmd;
6651 * Ignore the LINERESET during power mode change
6652 * operation via DME_SET command.
6654 if (cmd && (cmd->command == UIC_CMD_DME_SET))
6655 hba->uic_error &= ~UFSHCD_UIC_PA_GENERIC_ERROR;
6657 retval |= IRQ_HANDLED;
6660 /* PA_INIT_ERROR is fatal and needs UIC reset */
6661 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_DATA_LINK_LAYER);
6662 if ((reg & UIC_DATA_LINK_LAYER_ERROR) &&
6663 (reg & UIC_DATA_LINK_LAYER_ERROR_CODE_MASK)) {
6664 ufshcd_update_evt_hist(hba, UFS_EVT_DL_ERR, reg);
6666 if (reg & UIC_DATA_LINK_LAYER_ERROR_PA_INIT)
6667 hba->uic_error |= UFSHCD_UIC_DL_PA_INIT_ERROR;
6668 else if (hba->dev_quirks &
6669 UFS_DEVICE_QUIRK_RECOVERY_FROM_DL_NAC_ERRORS) {
6670 if (reg & UIC_DATA_LINK_LAYER_ERROR_NAC_RECEIVED)
6672 UFSHCD_UIC_DL_NAC_RECEIVED_ERROR;
6673 else if (reg & UIC_DATA_LINK_LAYER_ERROR_TCx_REPLAY_TIMEOUT)
6674 hba->uic_error |= UFSHCD_UIC_DL_TCx_REPLAY_ERROR;
6676 retval |= IRQ_HANDLED;
6679 /* UIC NL/TL/DME errors needs software retry */
6680 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_NETWORK_LAYER);
6681 if ((reg & UIC_NETWORK_LAYER_ERROR) &&
6682 (reg & UIC_NETWORK_LAYER_ERROR_CODE_MASK)) {
6683 ufshcd_update_evt_hist(hba, UFS_EVT_NL_ERR, reg);
6684 hba->uic_error |= UFSHCD_UIC_NL_ERROR;
6685 retval |= IRQ_HANDLED;
6688 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_TRANSPORT_LAYER);
6689 if ((reg & UIC_TRANSPORT_LAYER_ERROR) &&
6690 (reg & UIC_TRANSPORT_LAYER_ERROR_CODE_MASK)) {
6691 ufshcd_update_evt_hist(hba, UFS_EVT_TL_ERR, reg);
6692 hba->uic_error |= UFSHCD_UIC_TL_ERROR;
6693 retval |= IRQ_HANDLED;
6696 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_DME);
6697 if ((reg & UIC_DME_ERROR) &&
6698 (reg & UIC_DME_ERROR_CODE_MASK)) {
6699 ufshcd_update_evt_hist(hba, UFS_EVT_DME_ERR, reg);
6700 hba->uic_error |= UFSHCD_UIC_DME_ERROR;
6701 retval |= IRQ_HANDLED;
6704 dev_dbg(hba->dev, "%s: UIC error flags = 0x%08x\n",
6705 __func__, hba->uic_error);
6710 * ufshcd_check_errors - Check for errors that need s/w attention
6711 * @hba: per-adapter instance
6712 * @intr_status: interrupt status generated by the controller
6715 * IRQ_HANDLED - If interrupt is valid
6716 * IRQ_NONE - If invalid interrupt
6718 static irqreturn_t ufshcd_check_errors(struct ufs_hba *hba, u32 intr_status)
6720 bool queue_eh_work = false;
6721 irqreturn_t retval = IRQ_NONE;
6723 spin_lock(hba->host->host_lock);
6724 hba->errors |= UFSHCD_ERROR_MASK & intr_status;
6726 if (hba->errors & INT_FATAL_ERRORS) {
6727 ufshcd_update_evt_hist(hba, UFS_EVT_FATAL_ERR,
6729 queue_eh_work = true;
6732 if (hba->errors & UIC_ERROR) {
6734 retval = ufshcd_update_uic_error(hba);
6736 queue_eh_work = true;
6739 if (hba->errors & UFSHCD_UIC_HIBERN8_MASK) {
6741 "%s: Auto Hibern8 %s failed - status: 0x%08x, upmcrs: 0x%08x\n",
6742 __func__, (hba->errors & UIC_HIBERNATE_ENTER) ?
6744 hba->errors, ufshcd_get_upmcrs(hba));
6745 ufshcd_update_evt_hist(hba, UFS_EVT_AUTO_HIBERN8_ERR,
6747 ufshcd_set_link_broken(hba);
6748 queue_eh_work = true;
6751 if (queue_eh_work) {
6753 * update the transfer error masks to sticky bits, let's do this
6754 * irrespective of current ufshcd_state.
6756 hba->saved_err |= hba->errors;
6757 hba->saved_uic_err |= hba->uic_error;
6759 /* dump controller state before resetting */
6760 if ((hba->saved_err &
6761 (INT_FATAL_ERRORS | UFSHCD_UIC_HIBERN8_MASK)) ||
6762 (hba->saved_uic_err &&
6763 (hba->saved_uic_err != UFSHCD_UIC_PA_GENERIC_ERROR))) {
6764 dev_err(hba->dev, "%s: saved_err 0x%x saved_uic_err 0x%x\n",
6765 __func__, hba->saved_err,
6766 hba->saved_uic_err);
6767 ufshcd_dump_regs(hba, 0, UFSHCI_REG_SPACE_SIZE,
6769 ufshcd_print_pwr_info(hba);
6771 ufshcd_schedule_eh_work(hba);
6772 retval |= IRQ_HANDLED;
6775 * if (!queue_eh_work) -
6776 * Other errors are either non-fatal where host recovers
6777 * itself without s/w intervention or errors that will be
6778 * handled by the SCSI core layer.
6782 spin_unlock(hba->host->host_lock);
6787 * ufshcd_tmc_handler - handle task management function completion
6788 * @hba: per adapter instance
6791 * IRQ_HANDLED - If interrupt is valid
6792 * IRQ_NONE - If invalid interrupt
6794 static irqreturn_t ufshcd_tmc_handler(struct ufs_hba *hba)
6796 unsigned long flags, pending, issued;
6797 irqreturn_t ret = IRQ_NONE;
6800 spin_lock_irqsave(hba->host->host_lock, flags);
6801 pending = ufshcd_readl(hba, REG_UTP_TASK_REQ_DOOR_BELL);
6802 issued = hba->outstanding_tasks & ~pending;
6803 for_each_set_bit(tag, &issued, hba->nutmrs) {
6804 struct request *req = hba->tmf_rqs[tag];
6805 struct completion *c = req->end_io_data;
6810 spin_unlock_irqrestore(hba->host->host_lock, flags);
6816 * ufshcd_handle_mcq_cq_events - handle MCQ completion queue events
6817 * @hba: per adapter instance
6819 * Returns IRQ_HANDLED if interrupt is handled
6821 static irqreturn_t ufshcd_handle_mcq_cq_events(struct ufs_hba *hba)
6823 struct ufs_hw_queue *hwq;
6824 unsigned long outstanding_cqs;
6825 unsigned int nr_queues;
6829 ret = ufshcd_vops_get_outstanding_cqs(hba, &outstanding_cqs);
6831 outstanding_cqs = (1U << hba->nr_hw_queues) - 1;
6833 /* Exclude the poll queues */
6834 nr_queues = hba->nr_hw_queues - hba->nr_queues[HCTX_TYPE_POLL];
6835 for_each_set_bit(i, &outstanding_cqs, nr_queues) {
6838 events = ufshcd_mcq_read_cqis(hba, i);
6840 ufshcd_mcq_write_cqis(hba, events, i);
6842 if (events & UFSHCD_MCQ_CQIS_TAIL_ENT_PUSH_STS)
6843 ufshcd_mcq_poll_cqe_lock(hba, hwq);
6850 * ufshcd_sl_intr - Interrupt service routine
6851 * @hba: per adapter instance
6852 * @intr_status: contains interrupts generated by the controller
6855 * IRQ_HANDLED - If interrupt is valid
6856 * IRQ_NONE - If invalid interrupt
6858 static irqreturn_t ufshcd_sl_intr(struct ufs_hba *hba, u32 intr_status)
6860 irqreturn_t retval = IRQ_NONE;
6862 if (intr_status & UFSHCD_UIC_MASK)
6863 retval |= ufshcd_uic_cmd_compl(hba, intr_status);
6865 if (intr_status & UFSHCD_ERROR_MASK || hba->errors)
6866 retval |= ufshcd_check_errors(hba, intr_status);
6868 if (intr_status & UTP_TASK_REQ_COMPL)
6869 retval |= ufshcd_tmc_handler(hba);
6871 if (intr_status & UTP_TRANSFER_REQ_COMPL)
6872 retval |= ufshcd_transfer_req_compl(hba);
6874 if (intr_status & MCQ_CQ_EVENT_STATUS)
6875 retval |= ufshcd_handle_mcq_cq_events(hba);
6881 * ufshcd_intr - Main interrupt service routine
6883 * @__hba: pointer to adapter instance
6886 * IRQ_HANDLED - If interrupt is valid
6887 * IRQ_NONE - If invalid interrupt
6889 static irqreturn_t ufshcd_intr(int irq, void *__hba)
6891 u32 intr_status, enabled_intr_status = 0;
6892 irqreturn_t retval = IRQ_NONE;
6893 struct ufs_hba *hba = __hba;
6894 int retries = hba->nutrs;
6896 intr_status = ufshcd_readl(hba, REG_INTERRUPT_STATUS);
6897 hba->ufs_stats.last_intr_status = intr_status;
6898 hba->ufs_stats.last_intr_ts = local_clock();
6901 * There could be max of hba->nutrs reqs in flight and in worst case
6902 * if the reqs get finished 1 by 1 after the interrupt status is
6903 * read, make sure we handle them by checking the interrupt status
6904 * again in a loop until we process all of the reqs before returning.
6906 while (intr_status && retries--) {
6907 enabled_intr_status =
6908 intr_status & ufshcd_readl(hba, REG_INTERRUPT_ENABLE);
6909 ufshcd_writel(hba, intr_status, REG_INTERRUPT_STATUS);
6910 if (enabled_intr_status)
6911 retval |= ufshcd_sl_intr(hba, enabled_intr_status);
6913 intr_status = ufshcd_readl(hba, REG_INTERRUPT_STATUS);
6916 if (enabled_intr_status && retval == IRQ_NONE &&
6917 (!(enabled_intr_status & UTP_TRANSFER_REQ_COMPL) ||
6918 hba->outstanding_reqs) && !ufshcd_eh_in_progress(hba)) {
6919 dev_err(hba->dev, "%s: Unhandled interrupt 0x%08x (0x%08x, 0x%08x)\n",
6922 hba->ufs_stats.last_intr_status,
6923 enabled_intr_status);
6924 ufshcd_dump_regs(hba, 0, UFSHCI_REG_SPACE_SIZE, "host_regs: ");
6930 static int ufshcd_clear_tm_cmd(struct ufs_hba *hba, int tag)
6933 u32 mask = 1 << tag;
6934 unsigned long flags;
6936 if (!test_bit(tag, &hba->outstanding_tasks))
6939 spin_lock_irqsave(hba->host->host_lock, flags);
6940 ufshcd_utmrl_clear(hba, tag);
6941 spin_unlock_irqrestore(hba->host->host_lock, flags);
6943 /* poll for max. 1 sec to clear door bell register by h/w */
6944 err = ufshcd_wait_for_register(hba,
6945 REG_UTP_TASK_REQ_DOOR_BELL,
6946 mask, 0, 1000, 1000);
6948 dev_err(hba->dev, "Clearing task management function with tag %d %s\n",
6949 tag, err ? "succeeded" : "failed");
6955 static int __ufshcd_issue_tm_cmd(struct ufs_hba *hba,
6956 struct utp_task_req_desc *treq, u8 tm_function)
6958 struct request_queue *q = hba->tmf_queue;
6959 struct Scsi_Host *host = hba->host;
6960 DECLARE_COMPLETION_ONSTACK(wait);
6961 struct request *req;
6962 unsigned long flags;
6966 * blk_mq_alloc_request() is used here only to get a free tag.
6968 req = blk_mq_alloc_request(q, REQ_OP_DRV_OUT, 0);
6970 return PTR_ERR(req);
6972 req->end_io_data = &wait;
6975 spin_lock_irqsave(host->host_lock, flags);
6977 task_tag = req->tag;
6978 WARN_ONCE(task_tag < 0 || task_tag >= hba->nutmrs, "Invalid tag %d\n",
6980 hba->tmf_rqs[req->tag] = req;
6981 treq->upiu_req.req_header.dword_0 |= cpu_to_be32(task_tag);
6983 memcpy(hba->utmrdl_base_addr + task_tag, treq, sizeof(*treq));
6984 ufshcd_vops_setup_task_mgmt(hba, task_tag, tm_function);
6986 /* send command to the controller */
6987 __set_bit(task_tag, &hba->outstanding_tasks);
6989 ufshcd_writel(hba, 1 << task_tag, REG_UTP_TASK_REQ_DOOR_BELL);
6990 /* Make sure that doorbell is committed immediately */
6993 spin_unlock_irqrestore(host->host_lock, flags);
6995 ufshcd_add_tm_upiu_trace(hba, task_tag, UFS_TM_SEND);
6997 /* wait until the task management command is completed */
6998 err = wait_for_completion_io_timeout(&wait,
6999 msecs_to_jiffies(TM_CMD_TIMEOUT));
7001 ufshcd_add_tm_upiu_trace(hba, task_tag, UFS_TM_ERR);
7002 dev_err(hba->dev, "%s: task management cmd 0x%.2x timed-out\n",
7003 __func__, tm_function);
7004 if (ufshcd_clear_tm_cmd(hba, task_tag))
7005 dev_WARN(hba->dev, "%s: unable to clear tm cmd (slot %d) after timeout\n",
7006 __func__, task_tag);
7010 memcpy(treq, hba->utmrdl_base_addr + task_tag, sizeof(*treq));
7012 ufshcd_add_tm_upiu_trace(hba, task_tag, UFS_TM_COMP);
7015 spin_lock_irqsave(hba->host->host_lock, flags);
7016 hba->tmf_rqs[req->tag] = NULL;
7017 __clear_bit(task_tag, &hba->outstanding_tasks);
7018 spin_unlock_irqrestore(hba->host->host_lock, flags);
7020 ufshcd_release(hba);
7021 blk_mq_free_request(req);
7027 * ufshcd_issue_tm_cmd - issues task management commands to controller
7028 * @hba: per adapter instance
7029 * @lun_id: LUN ID to which TM command is sent
7030 * @task_id: task ID to which the TM command is applicable
7031 * @tm_function: task management function opcode
7032 * @tm_response: task management service response return value
7034 * Returns non-zero value on error, zero on success.
7036 static int ufshcd_issue_tm_cmd(struct ufs_hba *hba, int lun_id, int task_id,
7037 u8 tm_function, u8 *tm_response)
7039 struct utp_task_req_desc treq = { { 0 }, };
7040 enum utp_ocs ocs_value;
7043 /* Configure task request descriptor */
7044 treq.header.dword_0 = cpu_to_le32(UTP_REQ_DESC_INT_CMD);
7045 treq.header.dword_2 = cpu_to_le32(OCS_INVALID_COMMAND_STATUS);
7047 /* Configure task request UPIU */
7048 treq.upiu_req.req_header.dword_0 = cpu_to_be32(lun_id << 8) |
7049 cpu_to_be32(UPIU_TRANSACTION_TASK_REQ << 24);
7050 treq.upiu_req.req_header.dword_1 = cpu_to_be32(tm_function << 16);
7053 * The host shall provide the same value for LUN field in the basic
7054 * header and for Input Parameter.
7056 treq.upiu_req.input_param1 = cpu_to_be32(lun_id);
7057 treq.upiu_req.input_param2 = cpu_to_be32(task_id);
7059 err = __ufshcd_issue_tm_cmd(hba, &treq, tm_function);
7060 if (err == -ETIMEDOUT)
7063 ocs_value = le32_to_cpu(treq.header.dword_2) & MASK_OCS;
7064 if (ocs_value != OCS_SUCCESS)
7065 dev_err(hba->dev, "%s: failed, ocs = 0x%x\n",
7066 __func__, ocs_value);
7067 else if (tm_response)
7068 *tm_response = be32_to_cpu(treq.upiu_rsp.output_param1) &
7069 MASK_TM_SERVICE_RESP;
7074 * ufshcd_issue_devman_upiu_cmd - API for sending "utrd" type requests
7075 * @hba: per-adapter instance
7076 * @req_upiu: upiu request
7077 * @rsp_upiu: upiu reply
7078 * @desc_buff: pointer to descriptor buffer, NULL if NA
7079 * @buff_len: descriptor size, 0 if NA
7080 * @cmd_type: specifies the type (NOP, Query...)
7081 * @desc_op: descriptor operation
7083 * Those type of requests uses UTP Transfer Request Descriptor - utrd.
7084 * Therefore, it "rides" the device management infrastructure: uses its tag and
7085 * tasks work queues.
7087 * Since there is only one available tag for device management commands,
7088 * the caller is expected to hold the hba->dev_cmd.lock mutex.
7090 static int ufshcd_issue_devman_upiu_cmd(struct ufs_hba *hba,
7091 struct utp_upiu_req *req_upiu,
7092 struct utp_upiu_req *rsp_upiu,
7093 u8 *desc_buff, int *buff_len,
7094 enum dev_cmd_type cmd_type,
7095 enum query_opcode desc_op)
7097 DECLARE_COMPLETION_ONSTACK(wait);
7098 const u32 tag = hba->reserved_slot;
7099 struct ufshcd_lrb *lrbp;
7103 /* Protects use of hba->reserved_slot. */
7104 lockdep_assert_held(&hba->dev_cmd.lock);
7106 down_read(&hba->clk_scaling_lock);
7108 lrbp = &hba->lrb[tag];
7110 lrbp->task_tag = tag;
7112 lrbp->intr_cmd = true;
7113 ufshcd_prepare_lrbp_crypto(NULL, lrbp);
7114 hba->dev_cmd.type = cmd_type;
7116 if (hba->ufs_version <= ufshci_version(1, 1))
7117 lrbp->command_type = UTP_CMD_TYPE_DEV_MANAGE;
7119 lrbp->command_type = UTP_CMD_TYPE_UFS_STORAGE;
7121 /* update the task tag in the request upiu */
7122 req_upiu->header.dword_0 |= cpu_to_be32(tag);
7124 ufshcd_prepare_req_desc_hdr(lrbp, &upiu_flags, DMA_NONE, 0);
7126 /* just copy the upiu request as it is */
7127 memcpy(lrbp->ucd_req_ptr, req_upiu, sizeof(*lrbp->ucd_req_ptr));
7128 if (desc_buff && desc_op == UPIU_QUERY_OPCODE_WRITE_DESC) {
7129 /* The Data Segment Area is optional depending upon the query
7130 * function value. for WRITE DESCRIPTOR, the data segment
7131 * follows right after the tsf.
7133 memcpy(lrbp->ucd_req_ptr + 1, desc_buff, *buff_len);
7137 memset(lrbp->ucd_rsp_ptr, 0, sizeof(struct utp_upiu_rsp));
7139 hba->dev_cmd.complete = &wait;
7141 ufshcd_add_query_upiu_trace(hba, UFS_QUERY_SEND, lrbp->ucd_req_ptr);
7143 ufshcd_send_command(hba, tag, hba->dev_cmd_queue);
7145 * ignore the returning value here - ufshcd_check_query_response is
7146 * bound to fail since dev_cmd.query and dev_cmd.type were left empty.
7147 * read the response directly ignoring all errors.
7149 ufshcd_wait_for_dev_cmd(hba, lrbp, QUERY_REQ_TIMEOUT);
7151 /* just copy the upiu response as it is */
7152 memcpy(rsp_upiu, lrbp->ucd_rsp_ptr, sizeof(*rsp_upiu));
7153 if (desc_buff && desc_op == UPIU_QUERY_OPCODE_READ_DESC) {
7154 u8 *descp = (u8 *)lrbp->ucd_rsp_ptr + sizeof(*rsp_upiu);
7155 u16 resp_len = be32_to_cpu(lrbp->ucd_rsp_ptr->header.dword_2) &
7156 MASK_QUERY_DATA_SEG_LEN;
7158 if (*buff_len >= resp_len) {
7159 memcpy(desc_buff, descp, resp_len);
7160 *buff_len = resp_len;
7163 "%s: rsp size %d is bigger than buffer size %d",
7164 __func__, resp_len, *buff_len);
7169 ufshcd_add_query_upiu_trace(hba, err ? UFS_QUERY_ERR : UFS_QUERY_COMP,
7170 (struct utp_upiu_req *)lrbp->ucd_rsp_ptr);
7172 up_read(&hba->clk_scaling_lock);
7177 * ufshcd_exec_raw_upiu_cmd - API function for sending raw upiu commands
7178 * @hba: per-adapter instance
7179 * @req_upiu: upiu request
7180 * @rsp_upiu: upiu reply - only 8 DW as we do not support scsi commands
7181 * @msgcode: message code, one of UPIU Transaction Codes Initiator to Target
7182 * @desc_buff: pointer to descriptor buffer, NULL if NA
7183 * @buff_len: descriptor size, 0 if NA
7184 * @desc_op: descriptor operation
7186 * Supports UTP Transfer requests (nop and query), and UTP Task
7187 * Management requests.
7188 * It is up to the caller to fill the upiu conent properly, as it will
7189 * be copied without any further input validations.
7191 int ufshcd_exec_raw_upiu_cmd(struct ufs_hba *hba,
7192 struct utp_upiu_req *req_upiu,
7193 struct utp_upiu_req *rsp_upiu,
7195 u8 *desc_buff, int *buff_len,
7196 enum query_opcode desc_op)
7199 enum dev_cmd_type cmd_type = DEV_CMD_TYPE_QUERY;
7200 struct utp_task_req_desc treq = { { 0 }, };
7201 enum utp_ocs ocs_value;
7202 u8 tm_f = be32_to_cpu(req_upiu->header.dword_1) >> 16 & MASK_TM_FUNC;
7205 case UPIU_TRANSACTION_NOP_OUT:
7206 cmd_type = DEV_CMD_TYPE_NOP;
7208 case UPIU_TRANSACTION_QUERY_REQ:
7210 mutex_lock(&hba->dev_cmd.lock);
7211 err = ufshcd_issue_devman_upiu_cmd(hba, req_upiu, rsp_upiu,
7212 desc_buff, buff_len,
7214 mutex_unlock(&hba->dev_cmd.lock);
7215 ufshcd_release(hba);
7218 case UPIU_TRANSACTION_TASK_REQ:
7219 treq.header.dword_0 = cpu_to_le32(UTP_REQ_DESC_INT_CMD);
7220 treq.header.dword_2 = cpu_to_le32(OCS_INVALID_COMMAND_STATUS);
7222 memcpy(&treq.upiu_req, req_upiu, sizeof(*req_upiu));
7224 err = __ufshcd_issue_tm_cmd(hba, &treq, tm_f);
7225 if (err == -ETIMEDOUT)
7228 ocs_value = le32_to_cpu(treq.header.dword_2) & MASK_OCS;
7229 if (ocs_value != OCS_SUCCESS) {
7230 dev_err(hba->dev, "%s: failed, ocs = 0x%x\n", __func__,
7235 memcpy(rsp_upiu, &treq.upiu_rsp, sizeof(*rsp_upiu));
7248 * ufshcd_advanced_rpmb_req_handler - handle advanced RPMB request
7249 * @hba: per adapter instance
7250 * @req_upiu: upiu request
7251 * @rsp_upiu: upiu reply
7252 * @req_ehs: EHS field which contains Advanced RPMB Request Message
7253 * @rsp_ehs: EHS field which returns Advanced RPMB Response Message
7254 * @sg_cnt: The number of sg lists actually used
7255 * @sg_list: Pointer to SG list when DATA IN/OUT UPIU is required in ARPMB operation
7256 * @dir: DMA direction
7258 * Returns zero on success, non-zero on failure
7260 int ufshcd_advanced_rpmb_req_handler(struct ufs_hba *hba, struct utp_upiu_req *req_upiu,
7261 struct utp_upiu_req *rsp_upiu, struct ufs_ehs *req_ehs,
7262 struct ufs_ehs *rsp_ehs, int sg_cnt, struct scatterlist *sg_list,
7263 enum dma_data_direction dir)
7265 DECLARE_COMPLETION_ONSTACK(wait);
7266 const u32 tag = hba->reserved_slot;
7267 struct ufshcd_lrb *lrbp;
7274 /* Protects use of hba->reserved_slot. */
7276 mutex_lock(&hba->dev_cmd.lock);
7277 down_read(&hba->clk_scaling_lock);
7279 lrbp = &hba->lrb[tag];
7281 lrbp->task_tag = tag;
7282 lrbp->lun = UFS_UPIU_RPMB_WLUN;
7284 lrbp->intr_cmd = true;
7285 ufshcd_prepare_lrbp_crypto(NULL, lrbp);
7286 hba->dev_cmd.type = DEV_CMD_TYPE_RPMB;
7288 /* Advanced RPMB starts from UFS 4.0, so its command type is UTP_CMD_TYPE_UFS_STORAGE */
7289 lrbp->command_type = UTP_CMD_TYPE_UFS_STORAGE;
7291 ufshcd_prepare_req_desc_hdr(lrbp, &upiu_flags, dir, 2);
7293 /* update the task tag and LUN in the request upiu */
7294 req_upiu->header.dword_0 |= cpu_to_be32(upiu_flags << 16 | UFS_UPIU_RPMB_WLUN << 8 | tag);
7296 /* copy the UPIU(contains CDB) request as it is */
7297 memcpy(lrbp->ucd_req_ptr, req_upiu, sizeof(*lrbp->ucd_req_ptr));
7298 /* Copy EHS, starting with byte32, immediately after the CDB package */
7299 memcpy(lrbp->ucd_req_ptr + 1, req_ehs, sizeof(*req_ehs));
7301 if (dir != DMA_NONE && sg_list)
7302 ufshcd_sgl_to_prdt(hba, lrbp, sg_cnt, sg_list);
7304 memset(lrbp->ucd_rsp_ptr, 0, sizeof(struct utp_upiu_rsp));
7306 hba->dev_cmd.complete = &wait;
7308 ufshcd_send_command(hba, tag, hba->dev_cmd_queue);
7310 err = ufshcd_wait_for_dev_cmd(hba, lrbp, ADVANCED_RPMB_REQ_TIMEOUT);
7313 /* Just copy the upiu response as it is */
7314 memcpy(rsp_upiu, lrbp->ucd_rsp_ptr, sizeof(*rsp_upiu));
7315 /* Get the response UPIU result */
7316 result = ufshcd_get_rsp_upiu_result(lrbp->ucd_rsp_ptr);
7318 ehs_len = be32_to_cpu(lrbp->ucd_rsp_ptr->header.dword_2) >> 24;
7320 * Since the bLength in EHS indicates the total size of the EHS Header and EHS Data
7321 * in 32 Byte units, the value of the bLength Request/Response for Advanced RPMB
7324 if (ehs_len == 2 && rsp_ehs) {
7326 * ucd_rsp_ptr points to a buffer with a length of 512 bytes
7327 * (ALIGNED_UPIU_SIZE = 512), and the EHS data just starts from byte32
7329 ehs_data = (u8 *)lrbp->ucd_rsp_ptr + EHS_OFFSET_IN_RESPONSE;
7330 memcpy(rsp_ehs, ehs_data, ehs_len * 32);
7334 up_read(&hba->clk_scaling_lock);
7335 mutex_unlock(&hba->dev_cmd.lock);
7336 ufshcd_release(hba);
7337 return err ? : result;
7341 * ufshcd_eh_device_reset_handler() - Reset a single logical unit.
7342 * @cmd: SCSI command pointer
7344 * Returns SUCCESS/FAILED
7346 static int ufshcd_eh_device_reset_handler(struct scsi_cmnd *cmd)
7348 unsigned long flags, pending_reqs = 0, not_cleared = 0;
7349 struct Scsi_Host *host;
7350 struct ufs_hba *hba;
7351 struct ufs_hw_queue *hwq;
7352 struct ufshcd_lrb *lrbp;
7353 u32 pos, not_cleared_mask = 0;
7357 host = cmd->device->host;
7358 hba = shost_priv(host);
7360 lun = ufshcd_scsi_to_upiu_lun(cmd->device->lun);
7361 err = ufshcd_issue_tm_cmd(hba, lun, 0, UFS_LOGICAL_RESET, &resp);
7362 if (err || resp != UPIU_TASK_MANAGEMENT_FUNC_COMPL) {
7368 if (is_mcq_enabled(hba)) {
7369 for (pos = 0; pos < hba->nutrs; pos++) {
7370 lrbp = &hba->lrb[pos];
7371 if (ufshcd_cmd_inflight(lrbp->cmd) &&
7373 ufshcd_clear_cmd(hba, pos);
7374 hwq = ufshcd_mcq_req_to_hwq(hba, scsi_cmd_to_rq(lrbp->cmd));
7375 ufshcd_mcq_poll_cqe_lock(hba, hwq);
7382 /* clear the commands that were pending for corresponding LUN */
7383 spin_lock_irqsave(&hba->outstanding_lock, flags);
7384 for_each_set_bit(pos, &hba->outstanding_reqs, hba->nutrs)
7385 if (hba->lrb[pos].lun == lun)
7386 __set_bit(pos, &pending_reqs);
7387 hba->outstanding_reqs &= ~pending_reqs;
7388 spin_unlock_irqrestore(&hba->outstanding_lock, flags);
7390 for_each_set_bit(pos, &pending_reqs, hba->nutrs) {
7391 if (ufshcd_clear_cmd(hba, pos) < 0) {
7392 spin_lock_irqsave(&hba->outstanding_lock, flags);
7393 not_cleared = 1U << pos &
7394 ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
7395 hba->outstanding_reqs |= not_cleared;
7396 not_cleared_mask |= not_cleared;
7397 spin_unlock_irqrestore(&hba->outstanding_lock, flags);
7399 dev_err(hba->dev, "%s: failed to clear request %d\n",
7403 __ufshcd_transfer_req_compl(hba, pending_reqs & ~not_cleared_mask);
7406 hba->req_abort_count = 0;
7407 ufshcd_update_evt_hist(hba, UFS_EVT_DEV_RESET, (u32)err);
7411 dev_err(hba->dev, "%s: failed with err %d\n", __func__, err);
7417 static void ufshcd_set_req_abort_skip(struct ufs_hba *hba, unsigned long bitmap)
7419 struct ufshcd_lrb *lrbp;
7422 for_each_set_bit(tag, &bitmap, hba->nutrs) {
7423 lrbp = &hba->lrb[tag];
7424 lrbp->req_abort_skip = true;
7429 * ufshcd_try_to_abort_task - abort a specific task
7430 * @hba: Pointer to adapter instance
7431 * @tag: Task tag/index to be aborted
7433 * Abort the pending command in device by sending UFS_ABORT_TASK task management
7434 * command, and in host controller by clearing the door-bell register. There can
7435 * be race between controller sending the command to the device while abort is
7436 * issued. To avoid that, first issue UFS_QUERY_TASK to check if the command is
7437 * really issued and then try to abort it.
7439 * Returns zero on success, non-zero on failure
7441 int ufshcd_try_to_abort_task(struct ufs_hba *hba, int tag)
7443 struct ufshcd_lrb *lrbp = &hba->lrb[tag];
7449 for (poll_cnt = 100; poll_cnt; poll_cnt--) {
7450 err = ufshcd_issue_tm_cmd(hba, lrbp->lun, lrbp->task_tag,
7451 UFS_QUERY_TASK, &resp);
7452 if (!err && resp == UPIU_TASK_MANAGEMENT_FUNC_SUCCEEDED) {
7453 /* cmd pending in the device */
7454 dev_err(hba->dev, "%s: cmd pending in the device. tag = %d\n",
7457 } else if (!err && resp == UPIU_TASK_MANAGEMENT_FUNC_COMPL) {
7459 * cmd not pending in the device, check if it is
7462 dev_err(hba->dev, "%s: cmd at tag %d not pending in the device.\n",
7464 if (is_mcq_enabled(hba)) {
7466 if (ufshcd_cmd_inflight(lrbp->cmd)) {
7467 /* sleep for max. 200us same delay as in SDB mode */
7468 usleep_range(100, 200);
7471 /* command completed already */
7472 dev_err(hba->dev, "%s: cmd at tag=%d is cleared.\n",
7477 /* Single Doorbell Mode */
7478 reg = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
7479 if (reg & (1 << tag)) {
7480 /* sleep for max. 200us to stabilize */
7481 usleep_range(100, 200);
7484 /* command completed already */
7485 dev_err(hba->dev, "%s: cmd at tag %d successfully cleared from DB.\n",
7490 "%s: no response from device. tag = %d, err %d\n",
7491 __func__, tag, err);
7493 err = resp; /* service response error */
7503 err = ufshcd_issue_tm_cmd(hba, lrbp->lun, lrbp->task_tag,
7504 UFS_ABORT_TASK, &resp);
7505 if (err || resp != UPIU_TASK_MANAGEMENT_FUNC_COMPL) {
7507 err = resp; /* service response error */
7508 dev_err(hba->dev, "%s: issued. tag = %d, err %d\n",
7509 __func__, tag, err);
7514 err = ufshcd_clear_cmd(hba, tag);
7516 dev_err(hba->dev, "%s: Failed clearing cmd at tag %d, err %d\n",
7517 __func__, tag, err);
7524 * ufshcd_abort - scsi host template eh_abort_handler callback
7525 * @cmd: SCSI command pointer
7527 * Returns SUCCESS/FAILED
7529 static int ufshcd_abort(struct scsi_cmnd *cmd)
7531 struct Scsi_Host *host = cmd->device->host;
7532 struct ufs_hba *hba = shost_priv(host);
7533 int tag = scsi_cmd_to_rq(cmd)->tag;
7534 struct ufshcd_lrb *lrbp = &hba->lrb[tag];
7535 unsigned long flags;
7540 WARN_ONCE(tag < 0, "Invalid tag %d\n", tag);
7544 if (!is_mcq_enabled(hba)) {
7545 reg = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
7546 if (!test_bit(tag, &hba->outstanding_reqs)) {
7547 /* If command is already aborted/completed, return FAILED. */
7549 "%s: cmd at tag %d already completed, outstanding=0x%lx, doorbell=0x%x\n",
7550 __func__, tag, hba->outstanding_reqs, reg);
7555 /* Print Transfer Request of aborted task */
7556 dev_info(hba->dev, "%s: Device abort task at tag %d\n", __func__, tag);
7559 * Print detailed info about aborted request.
7560 * As more than one request might get aborted at the same time,
7561 * print full information only for the first aborted request in order
7562 * to reduce repeated printouts. For other aborted requests only print
7565 scsi_print_command(cmd);
7566 if (!hba->req_abort_count) {
7567 ufshcd_update_evt_hist(hba, UFS_EVT_ABORT, tag);
7568 ufshcd_print_evt_hist(hba);
7569 ufshcd_print_host_state(hba);
7570 ufshcd_print_pwr_info(hba);
7571 ufshcd_print_tr(hba, tag, true);
7573 ufshcd_print_tr(hba, tag, false);
7575 hba->req_abort_count++;
7577 if (!is_mcq_enabled(hba) && !(reg & (1 << tag))) {
7578 /* only execute this code in single doorbell mode */
7580 "%s: cmd was completed, but without a notifying intr, tag = %d",
7582 __ufshcd_transfer_req_compl(hba, 1UL << tag);
7587 * Task abort to the device W-LUN is illegal. When this command
7588 * will fail, due to spec violation, scsi err handling next step
7589 * will be to send LU reset which, again, is a spec violation.
7590 * To avoid these unnecessary/illegal steps, first we clean up
7591 * the lrb taken by this cmd and re-set it in outstanding_reqs,
7592 * then queue the eh_work and bail.
7594 if (lrbp->lun == UFS_UPIU_UFS_DEVICE_WLUN) {
7595 ufshcd_update_evt_hist(hba, UFS_EVT_ABORT, lrbp->lun);
7597 spin_lock_irqsave(host->host_lock, flags);
7598 hba->force_reset = true;
7599 ufshcd_schedule_eh_work(hba);
7600 spin_unlock_irqrestore(host->host_lock, flags);
7604 if (is_mcq_enabled(hba)) {
7605 /* MCQ mode. Branch off to handle abort for mcq mode */
7606 err = ufshcd_mcq_abort(cmd);
7610 /* Skip task abort in case previous aborts failed and report failure */
7611 if (lrbp->req_abort_skip) {
7612 dev_err(hba->dev, "%s: skipping abort\n", __func__);
7613 ufshcd_set_req_abort_skip(hba, hba->outstanding_reqs);
7617 err = ufshcd_try_to_abort_task(hba, tag);
7619 dev_err(hba->dev, "%s: failed with err %d\n", __func__, err);
7620 ufshcd_set_req_abort_skip(hba, hba->outstanding_reqs);
7626 * Clear the corresponding bit from outstanding_reqs since the command
7627 * has been aborted successfully.
7629 spin_lock_irqsave(&hba->outstanding_lock, flags);
7630 outstanding = __test_and_clear_bit(tag, &hba->outstanding_reqs);
7631 spin_unlock_irqrestore(&hba->outstanding_lock, flags);
7634 ufshcd_release_scsi_cmd(hba, lrbp);
7639 /* Matches the ufshcd_hold() call at the start of this function. */
7640 ufshcd_release(hba);
7645 * ufshcd_host_reset_and_restore - reset and restore host controller
7646 * @hba: per-adapter instance
7648 * Note that host controller reset may issue DME_RESET to
7649 * local and remote (device) Uni-Pro stack and the attributes
7650 * are reset to default state.
7652 * Returns zero on success, non-zero on failure
7654 static int ufshcd_host_reset_and_restore(struct ufs_hba *hba)
7659 * Stop the host controller and complete the requests
7662 ufshpb_toggle_state(hba, HPB_PRESENT, HPB_RESET);
7663 ufshcd_hba_stop(hba);
7664 hba->silence_err_logs = true;
7665 ufshcd_complete_requests(hba, true);
7666 hba->silence_err_logs = false;
7668 /* scale up clocks to max frequency before full reinitialization */
7669 ufshcd_scale_clks(hba, true);
7671 err = ufshcd_hba_enable(hba);
7673 /* Establish the link again and restore the device */
7675 err = ufshcd_probe_hba(hba, false);
7678 dev_err(hba->dev, "%s: Host init failed %d\n", __func__, err);
7679 ufshcd_update_evt_hist(hba, UFS_EVT_HOST_RESET, (u32)err);
7684 * ufshcd_reset_and_restore - reset and re-initialize host/device
7685 * @hba: per-adapter instance
7687 * Reset and recover device, host and re-establish link. This
7688 * is helpful to recover the communication in fatal error conditions.
7690 * Returns zero on success, non-zero on failure
7692 static int ufshcd_reset_and_restore(struct ufs_hba *hba)
7695 u32 saved_uic_err = 0;
7697 unsigned long flags;
7698 int retries = MAX_HOST_RESET_RETRIES;
7700 spin_lock_irqsave(hba->host->host_lock, flags);
7703 * This is a fresh start, cache and clear saved error first,
7704 * in case new error generated during reset and restore.
7706 saved_err |= hba->saved_err;
7707 saved_uic_err |= hba->saved_uic_err;
7709 hba->saved_uic_err = 0;
7710 hba->force_reset = false;
7711 hba->ufshcd_state = UFSHCD_STATE_RESET;
7712 spin_unlock_irqrestore(hba->host->host_lock, flags);
7714 /* Reset the attached device */
7715 ufshcd_device_reset(hba);
7717 err = ufshcd_host_reset_and_restore(hba);
7719 spin_lock_irqsave(hba->host->host_lock, flags);
7722 /* Do not exit unless operational or dead */
7723 if (hba->ufshcd_state != UFSHCD_STATE_OPERATIONAL &&
7724 hba->ufshcd_state != UFSHCD_STATE_ERROR &&
7725 hba->ufshcd_state != UFSHCD_STATE_EH_SCHEDULED_NON_FATAL)
7727 } while (err && --retries);
7730 * Inform scsi mid-layer that we did reset and allow to handle
7731 * Unit Attention properly.
7733 scsi_report_bus_reset(hba->host, 0);
7735 hba->ufshcd_state = UFSHCD_STATE_ERROR;
7736 hba->saved_err |= saved_err;
7737 hba->saved_uic_err |= saved_uic_err;
7739 spin_unlock_irqrestore(hba->host->host_lock, flags);
7745 * ufshcd_eh_host_reset_handler - host reset handler registered to scsi layer
7746 * @cmd: SCSI command pointer
7748 * Returns SUCCESS/FAILED
7750 static int ufshcd_eh_host_reset_handler(struct scsi_cmnd *cmd)
7753 unsigned long flags;
7754 struct ufs_hba *hba;
7756 hba = shost_priv(cmd->device->host);
7758 spin_lock_irqsave(hba->host->host_lock, flags);
7759 hba->force_reset = true;
7760 ufshcd_schedule_eh_work(hba);
7761 dev_err(hba->dev, "%s: reset in progress - 1\n", __func__);
7762 spin_unlock_irqrestore(hba->host->host_lock, flags);
7764 flush_work(&hba->eh_work);
7766 spin_lock_irqsave(hba->host->host_lock, flags);
7767 if (hba->ufshcd_state == UFSHCD_STATE_ERROR)
7769 spin_unlock_irqrestore(hba->host->host_lock, flags);
7775 * ufshcd_get_max_icc_level - calculate the ICC level
7776 * @sup_curr_uA: max. current supported by the regulator
7777 * @start_scan: row at the desc table to start scan from
7778 * @buff: power descriptor buffer
7780 * Returns calculated max ICC level for specific regulator
7782 static u32 ufshcd_get_max_icc_level(int sup_curr_uA, u32 start_scan,
7790 for (i = start_scan; i >= 0; i--) {
7791 data = get_unaligned_be16(&buff[2 * i]);
7792 unit = (data & ATTR_ICC_LVL_UNIT_MASK) >>
7793 ATTR_ICC_LVL_UNIT_OFFSET;
7794 curr_uA = data & ATTR_ICC_LVL_VALUE_MASK;
7796 case UFSHCD_NANO_AMP:
7797 curr_uA = curr_uA / 1000;
7799 case UFSHCD_MILI_AMP:
7800 curr_uA = curr_uA * 1000;
7803 curr_uA = curr_uA * 1000 * 1000;
7805 case UFSHCD_MICRO_AMP:
7809 if (sup_curr_uA >= curr_uA)
7814 pr_err("%s: Couldn't find valid icc_level = %d", __func__, i);
7821 * ufshcd_find_max_sup_active_icc_level - calculate the max ICC level
7822 * In case regulators are not initialized we'll return 0
7823 * @hba: per-adapter instance
7824 * @desc_buf: power descriptor buffer to extract ICC levels from.
7826 * Returns calculated ICC level
7828 static u32 ufshcd_find_max_sup_active_icc_level(struct ufs_hba *hba,
7833 if (!hba->vreg_info.vcc || !hba->vreg_info.vccq ||
7834 !hba->vreg_info.vccq2) {
7836 * Using dev_dbg to avoid messages during runtime PM to avoid
7837 * never-ending cycles of messages written back to storage by
7838 * user space causing runtime resume, causing more messages and
7842 "%s: Regulator capability was not set, actvIccLevel=%d",
7843 __func__, icc_level);
7847 if (hba->vreg_info.vcc->max_uA)
7848 icc_level = ufshcd_get_max_icc_level(
7849 hba->vreg_info.vcc->max_uA,
7850 POWER_DESC_MAX_ACTV_ICC_LVLS - 1,
7851 &desc_buf[PWR_DESC_ACTIVE_LVLS_VCC_0]);
7853 if (hba->vreg_info.vccq->max_uA)
7854 icc_level = ufshcd_get_max_icc_level(
7855 hba->vreg_info.vccq->max_uA,
7857 &desc_buf[PWR_DESC_ACTIVE_LVLS_VCCQ_0]);
7859 if (hba->vreg_info.vccq2->max_uA)
7860 icc_level = ufshcd_get_max_icc_level(
7861 hba->vreg_info.vccq2->max_uA,
7863 &desc_buf[PWR_DESC_ACTIVE_LVLS_VCCQ2_0]);
7868 static void ufshcd_set_active_icc_lvl(struct ufs_hba *hba)
7874 desc_buf = kzalloc(QUERY_DESC_MAX_SIZE, GFP_KERNEL);
7878 ret = ufshcd_read_desc_param(hba, QUERY_DESC_IDN_POWER, 0, 0,
7879 desc_buf, QUERY_DESC_MAX_SIZE);
7882 "%s: Failed reading power descriptor ret = %d",
7887 icc_level = ufshcd_find_max_sup_active_icc_level(hba, desc_buf);
7888 dev_dbg(hba->dev, "%s: setting icc_level 0x%x", __func__, icc_level);
7890 ret = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_WRITE_ATTR,
7891 QUERY_ATTR_IDN_ACTIVE_ICC_LVL, 0, 0, &icc_level);
7895 "%s: Failed configuring bActiveICCLevel = %d ret = %d",
7896 __func__, icc_level, ret);
7902 static inline void ufshcd_blk_pm_runtime_init(struct scsi_device *sdev)
7904 scsi_autopm_get_device(sdev);
7905 blk_pm_runtime_init(sdev->request_queue, &sdev->sdev_gendev);
7906 if (sdev->rpm_autosuspend)
7907 pm_runtime_set_autosuspend_delay(&sdev->sdev_gendev,
7908 RPM_AUTOSUSPEND_DELAY_MS);
7909 scsi_autopm_put_device(sdev);
7913 * ufshcd_scsi_add_wlus - Adds required W-LUs
7914 * @hba: per-adapter instance
7916 * UFS device specification requires the UFS devices to support 4 well known
7918 * "REPORT_LUNS" (address: 01h)
7919 * "UFS Device" (address: 50h)
7920 * "RPMB" (address: 44h)
7921 * "BOOT" (address: 30h)
7922 * UFS device's power management needs to be controlled by "POWER CONDITION"
7923 * field of SSU (START STOP UNIT) command. But this "power condition" field
7924 * will take effect only when its sent to "UFS device" well known logical unit
7925 * hence we require the scsi_device instance to represent this logical unit in
7926 * order for the UFS host driver to send the SSU command for power management.
7928 * We also require the scsi_device instance for "RPMB" (Replay Protected Memory
7929 * Block) LU so user space process can control this LU. User space may also
7930 * want to have access to BOOT LU.
7932 * This function adds scsi device instances for each of all well known LUs
7933 * (except "REPORT LUNS" LU).
7935 * Returns zero on success (all required W-LUs are added successfully),
7936 * non-zero error value on failure (if failed to add any of the required W-LU).
7938 static int ufshcd_scsi_add_wlus(struct ufs_hba *hba)
7941 struct scsi_device *sdev_boot, *sdev_rpmb;
7943 hba->ufs_device_wlun = __scsi_add_device(hba->host, 0, 0,
7944 ufshcd_upiu_wlun_to_scsi_wlun(UFS_UPIU_UFS_DEVICE_WLUN), NULL);
7945 if (IS_ERR(hba->ufs_device_wlun)) {
7946 ret = PTR_ERR(hba->ufs_device_wlun);
7947 hba->ufs_device_wlun = NULL;
7950 scsi_device_put(hba->ufs_device_wlun);
7952 sdev_rpmb = __scsi_add_device(hba->host, 0, 0,
7953 ufshcd_upiu_wlun_to_scsi_wlun(UFS_UPIU_RPMB_WLUN), NULL);
7954 if (IS_ERR(sdev_rpmb)) {
7955 ret = PTR_ERR(sdev_rpmb);
7956 goto remove_ufs_device_wlun;
7958 ufshcd_blk_pm_runtime_init(sdev_rpmb);
7959 scsi_device_put(sdev_rpmb);
7961 sdev_boot = __scsi_add_device(hba->host, 0, 0,
7962 ufshcd_upiu_wlun_to_scsi_wlun(UFS_UPIU_BOOT_WLUN), NULL);
7963 if (IS_ERR(sdev_boot)) {
7964 dev_err(hba->dev, "%s: BOOT WLUN not found\n", __func__);
7966 ufshcd_blk_pm_runtime_init(sdev_boot);
7967 scsi_device_put(sdev_boot);
7971 remove_ufs_device_wlun:
7972 scsi_remove_device(hba->ufs_device_wlun);
7977 static void ufshcd_wb_probe(struct ufs_hba *hba, const u8 *desc_buf)
7979 struct ufs_dev_info *dev_info = &hba->dev_info;
7981 u32 d_lu_wb_buf_alloc;
7982 u32 ext_ufs_feature;
7984 if (!ufshcd_is_wb_allowed(hba))
7988 * Probe WB only for UFS-2.2 and UFS-3.1 (and later) devices or
7989 * UFS devices with quirk UFS_DEVICE_QUIRK_SUPPORT_EXTENDED_FEATURES
7992 if (!(dev_info->wspecversion >= 0x310 ||
7993 dev_info->wspecversion == 0x220 ||
7994 (hba->dev_quirks & UFS_DEVICE_QUIRK_SUPPORT_EXTENDED_FEATURES)))
7997 ext_ufs_feature = get_unaligned_be32(desc_buf +
7998 DEVICE_DESC_PARAM_EXT_UFS_FEATURE_SUP);
8000 if (!(ext_ufs_feature & UFS_DEV_WRITE_BOOSTER_SUP))
8004 * WB may be supported but not configured while provisioning. The spec
8005 * says, in dedicated wb buffer mode, a max of 1 lun would have wb
8006 * buffer configured.
8008 dev_info->wb_buffer_type = desc_buf[DEVICE_DESC_PARAM_WB_TYPE];
8010 dev_info->b_presrv_uspc_en =
8011 desc_buf[DEVICE_DESC_PARAM_WB_PRESRV_USRSPC_EN];
8013 if (dev_info->wb_buffer_type == WB_BUF_MODE_SHARED) {
8014 if (!get_unaligned_be32(desc_buf +
8015 DEVICE_DESC_PARAM_WB_SHARED_ALLOC_UNITS))
8018 for (lun = 0; lun < UFS_UPIU_MAX_WB_LUN_ID; lun++) {
8019 d_lu_wb_buf_alloc = 0;
8020 ufshcd_read_unit_desc_param(hba,
8022 UNIT_DESC_PARAM_WB_BUF_ALLOC_UNITS,
8023 (u8 *)&d_lu_wb_buf_alloc,
8024 sizeof(d_lu_wb_buf_alloc));
8025 if (d_lu_wb_buf_alloc) {
8026 dev_info->wb_dedicated_lu = lun;
8031 if (!d_lu_wb_buf_alloc)
8035 if (!ufshcd_is_wb_buf_lifetime_available(hba))
8041 hba->caps &= ~UFSHCD_CAP_WB_EN;
8044 static void ufshcd_temp_notif_probe(struct ufs_hba *hba, const u8 *desc_buf)
8046 struct ufs_dev_info *dev_info = &hba->dev_info;
8047 u32 ext_ufs_feature;
8050 if (!(hba->caps & UFSHCD_CAP_TEMP_NOTIF) || dev_info->wspecversion < 0x300)
8053 ext_ufs_feature = get_unaligned_be32(desc_buf + DEVICE_DESC_PARAM_EXT_UFS_FEATURE_SUP);
8055 if (ext_ufs_feature & UFS_DEV_LOW_TEMP_NOTIF)
8056 mask |= MASK_EE_TOO_LOW_TEMP;
8058 if (ext_ufs_feature & UFS_DEV_HIGH_TEMP_NOTIF)
8059 mask |= MASK_EE_TOO_HIGH_TEMP;
8062 ufshcd_enable_ee(hba, mask);
8063 ufs_hwmon_probe(hba, mask);
8067 static void ufshcd_ext_iid_probe(struct ufs_hba *hba, u8 *desc_buf)
8069 struct ufs_dev_info *dev_info = &hba->dev_info;
8070 u32 ext_ufs_feature;
8074 /* Only UFS-4.0 and above may support EXT_IID */
8075 if (dev_info->wspecversion < 0x400)
8078 ext_ufs_feature = get_unaligned_be32(desc_buf +
8079 DEVICE_DESC_PARAM_EXT_UFS_FEATURE_SUP);
8080 if (!(ext_ufs_feature & UFS_DEV_EXT_IID_SUP))
8083 err = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
8084 QUERY_ATTR_IDN_EXT_IID_EN, 0, 0, &ext_iid_en);
8086 dev_err(hba->dev, "failed reading bEXTIIDEn. err = %d\n", err);
8089 dev_info->b_ext_iid_en = ext_iid_en;
8092 void ufshcd_fixup_dev_quirks(struct ufs_hba *hba,
8093 const struct ufs_dev_quirk *fixups)
8095 const struct ufs_dev_quirk *f;
8096 struct ufs_dev_info *dev_info = &hba->dev_info;
8101 for (f = fixups; f->quirk; f++) {
8102 if ((f->wmanufacturerid == dev_info->wmanufacturerid ||
8103 f->wmanufacturerid == UFS_ANY_VENDOR) &&
8104 ((dev_info->model &&
8105 STR_PRFX_EQUAL(f->model, dev_info->model)) ||
8106 !strcmp(f->model, UFS_ANY_MODEL)))
8107 hba->dev_quirks |= f->quirk;
8110 EXPORT_SYMBOL_GPL(ufshcd_fixup_dev_quirks);
8112 static void ufs_fixup_device_setup(struct ufs_hba *hba)
8114 /* fix by general quirk table */
8115 ufshcd_fixup_dev_quirks(hba, ufs_fixups);
8117 /* allow vendors to fix quirks */
8118 ufshcd_vops_fixup_dev_quirks(hba);
8121 static int ufs_get_device_desc(struct ufs_hba *hba)
8125 u8 b_ufs_feature_sup;
8127 struct ufs_dev_info *dev_info = &hba->dev_info;
8129 desc_buf = kzalloc(QUERY_DESC_MAX_SIZE, GFP_KERNEL);
8135 err = ufshcd_read_desc_param(hba, QUERY_DESC_IDN_DEVICE, 0, 0, desc_buf,
8136 QUERY_DESC_MAX_SIZE);
8138 dev_err(hba->dev, "%s: Failed reading Device Desc. err = %d\n",
8144 * getting vendor (manufacturerID) and Bank Index in big endian
8147 dev_info->wmanufacturerid = desc_buf[DEVICE_DESC_PARAM_MANF_ID] << 8 |
8148 desc_buf[DEVICE_DESC_PARAM_MANF_ID + 1];
8150 /* getting Specification Version in big endian format */
8151 dev_info->wspecversion = desc_buf[DEVICE_DESC_PARAM_SPEC_VER] << 8 |
8152 desc_buf[DEVICE_DESC_PARAM_SPEC_VER + 1];
8153 dev_info->bqueuedepth = desc_buf[DEVICE_DESC_PARAM_Q_DPTH];
8154 b_ufs_feature_sup = desc_buf[DEVICE_DESC_PARAM_UFS_FEAT];
8156 model_index = desc_buf[DEVICE_DESC_PARAM_PRDCT_NAME];
8158 if (dev_info->wspecversion >= UFS_DEV_HPB_SUPPORT_VERSION &&
8159 (b_ufs_feature_sup & UFS_DEV_HPB_SUPPORT)) {
8160 bool hpb_en = false;
8162 ufshpb_get_dev_info(hba, desc_buf);
8164 if (!ufshpb_is_legacy(hba))
8165 err = ufshcd_query_flag_retry(hba,
8166 UPIU_QUERY_OPCODE_READ_FLAG,
8167 QUERY_FLAG_IDN_HPB_EN, 0,
8170 if (ufshpb_is_legacy(hba) || (!err && hpb_en))
8171 dev_info->hpb_enabled = true;
8174 err = ufshcd_read_string_desc(hba, model_index,
8175 &dev_info->model, SD_ASCII_STD);
8177 dev_err(hba->dev, "%s: Failed reading Product Name. err = %d\n",
8182 hba->luns_avail = desc_buf[DEVICE_DESC_PARAM_NUM_LU] +
8183 desc_buf[DEVICE_DESC_PARAM_NUM_WLU];
8185 ufs_fixup_device_setup(hba);
8187 ufshcd_wb_probe(hba, desc_buf);
8189 ufshcd_temp_notif_probe(hba, desc_buf);
8191 if (hba->ext_iid_sup)
8192 ufshcd_ext_iid_probe(hba, desc_buf);
8195 * ufshcd_read_string_desc returns size of the string
8196 * reset the error value
8205 static void ufs_put_device_desc(struct ufs_hba *hba)
8207 struct ufs_dev_info *dev_info = &hba->dev_info;
8209 kfree(dev_info->model);
8210 dev_info->model = NULL;
8214 * ufshcd_tune_pa_tactivate - Tunes PA_TActivate of local UniPro
8215 * @hba: per-adapter instance
8217 * PA_TActivate parameter can be tuned manually if UniPro version is less than
8218 * 1.61. PA_TActivate needs to be greater than or equal to peerM-PHY's
8219 * RX_MIN_ACTIVATETIME_CAPABILITY attribute. This optimal value can help reduce
8220 * the hibern8 exit latency.
8222 * Returns zero on success, non-zero error value on failure.
8224 static int ufshcd_tune_pa_tactivate(struct ufs_hba *hba)
8227 u32 peer_rx_min_activatetime = 0, tuned_pa_tactivate;
8229 ret = ufshcd_dme_peer_get(hba,
8231 RX_MIN_ACTIVATETIME_CAPABILITY,
8232 UIC_ARG_MPHY_RX_GEN_SEL_INDEX(0)),
8233 &peer_rx_min_activatetime);
8237 /* make sure proper unit conversion is applied */
8238 tuned_pa_tactivate =
8239 ((peer_rx_min_activatetime * RX_MIN_ACTIVATETIME_UNIT_US)
8240 / PA_TACTIVATE_TIME_UNIT_US);
8241 ret = ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TACTIVATE),
8242 tuned_pa_tactivate);
8249 * ufshcd_tune_pa_hibern8time - Tunes PA_Hibern8Time of local UniPro
8250 * @hba: per-adapter instance
8252 * PA_Hibern8Time parameter can be tuned manually if UniPro version is less than
8253 * 1.61. PA_Hibern8Time needs to be maximum of local M-PHY's
8254 * TX_HIBERN8TIME_CAPABILITY & peer M-PHY's RX_HIBERN8TIME_CAPABILITY.
8255 * This optimal value can help reduce the hibern8 exit latency.
8257 * Returns zero on success, non-zero error value on failure.
8259 static int ufshcd_tune_pa_hibern8time(struct ufs_hba *hba)
8262 u32 local_tx_hibern8_time_cap = 0, peer_rx_hibern8_time_cap = 0;
8263 u32 max_hibern8_time, tuned_pa_hibern8time;
8265 ret = ufshcd_dme_get(hba,
8266 UIC_ARG_MIB_SEL(TX_HIBERN8TIME_CAPABILITY,
8267 UIC_ARG_MPHY_TX_GEN_SEL_INDEX(0)),
8268 &local_tx_hibern8_time_cap);
8272 ret = ufshcd_dme_peer_get(hba,
8273 UIC_ARG_MIB_SEL(RX_HIBERN8TIME_CAPABILITY,
8274 UIC_ARG_MPHY_RX_GEN_SEL_INDEX(0)),
8275 &peer_rx_hibern8_time_cap);
8279 max_hibern8_time = max(local_tx_hibern8_time_cap,
8280 peer_rx_hibern8_time_cap);
8281 /* make sure proper unit conversion is applied */
8282 tuned_pa_hibern8time = ((max_hibern8_time * HIBERN8TIME_UNIT_US)
8283 / PA_HIBERN8_TIME_UNIT_US);
8284 ret = ufshcd_dme_set(hba, UIC_ARG_MIB(PA_HIBERN8TIME),
8285 tuned_pa_hibern8time);
8291 * ufshcd_quirk_tune_host_pa_tactivate - Ensures that host PA_TACTIVATE is
8292 * less than device PA_TACTIVATE time.
8293 * @hba: per-adapter instance
8295 * Some UFS devices require host PA_TACTIVATE to be lower than device
8296 * PA_TACTIVATE, we need to enable UFS_DEVICE_QUIRK_HOST_PA_TACTIVATE quirk
8299 * Returns zero on success, non-zero error value on failure.
8301 static int ufshcd_quirk_tune_host_pa_tactivate(struct ufs_hba *hba)
8304 u32 granularity, peer_granularity;
8305 u32 pa_tactivate, peer_pa_tactivate;
8306 u32 pa_tactivate_us, peer_pa_tactivate_us;
8307 static const u8 gran_to_us_table[] = {1, 4, 8, 16, 32, 100};
8309 ret = ufshcd_dme_get(hba, UIC_ARG_MIB(PA_GRANULARITY),
8314 ret = ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_GRANULARITY),
8319 if ((granularity < PA_GRANULARITY_MIN_VAL) ||
8320 (granularity > PA_GRANULARITY_MAX_VAL)) {
8321 dev_err(hba->dev, "%s: invalid host PA_GRANULARITY %d",
8322 __func__, granularity);
8326 if ((peer_granularity < PA_GRANULARITY_MIN_VAL) ||
8327 (peer_granularity > PA_GRANULARITY_MAX_VAL)) {
8328 dev_err(hba->dev, "%s: invalid device PA_GRANULARITY %d",
8329 __func__, peer_granularity);
8333 ret = ufshcd_dme_get(hba, UIC_ARG_MIB(PA_TACTIVATE), &pa_tactivate);
8337 ret = ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_TACTIVATE),
8338 &peer_pa_tactivate);
8342 pa_tactivate_us = pa_tactivate * gran_to_us_table[granularity - 1];
8343 peer_pa_tactivate_us = peer_pa_tactivate *
8344 gran_to_us_table[peer_granularity - 1];
8346 if (pa_tactivate_us >= peer_pa_tactivate_us) {
8347 u32 new_peer_pa_tactivate;
8349 new_peer_pa_tactivate = pa_tactivate_us /
8350 gran_to_us_table[peer_granularity - 1];
8351 new_peer_pa_tactivate++;
8352 ret = ufshcd_dme_peer_set(hba, UIC_ARG_MIB(PA_TACTIVATE),
8353 new_peer_pa_tactivate);
8360 static void ufshcd_tune_unipro_params(struct ufs_hba *hba)
8362 if (ufshcd_is_unipro_pa_params_tuning_req(hba)) {
8363 ufshcd_tune_pa_tactivate(hba);
8364 ufshcd_tune_pa_hibern8time(hba);
8367 ufshcd_vops_apply_dev_quirks(hba);
8369 if (hba->dev_quirks & UFS_DEVICE_QUIRK_PA_TACTIVATE)
8370 /* set 1ms timeout for PA_TACTIVATE */
8371 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TACTIVATE), 10);
8373 if (hba->dev_quirks & UFS_DEVICE_QUIRK_HOST_PA_TACTIVATE)
8374 ufshcd_quirk_tune_host_pa_tactivate(hba);
8377 static void ufshcd_clear_dbg_ufs_stats(struct ufs_hba *hba)
8379 hba->ufs_stats.hibern8_exit_cnt = 0;
8380 hba->ufs_stats.last_hibern8_exit_tstamp = ktime_set(0, 0);
8381 hba->req_abort_count = 0;
8384 static int ufshcd_device_geo_params_init(struct ufs_hba *hba)
8389 desc_buf = kzalloc(QUERY_DESC_MAX_SIZE, GFP_KERNEL);
8395 err = ufshcd_read_desc_param(hba, QUERY_DESC_IDN_GEOMETRY, 0, 0,
8396 desc_buf, QUERY_DESC_MAX_SIZE);
8398 dev_err(hba->dev, "%s: Failed reading Geometry Desc. err = %d\n",
8403 if (desc_buf[GEOMETRY_DESC_PARAM_MAX_NUM_LUN] == 1)
8404 hba->dev_info.max_lu_supported = 32;
8405 else if (desc_buf[GEOMETRY_DESC_PARAM_MAX_NUM_LUN] == 0)
8406 hba->dev_info.max_lu_supported = 8;
8408 if (desc_buf[QUERY_DESC_LENGTH_OFFSET] >=
8409 GEOMETRY_DESC_PARAM_HPB_MAX_ACTIVE_REGS)
8410 ufshpb_get_geo_info(hba, desc_buf);
8417 struct ufs_ref_clk {
8418 unsigned long freq_hz;
8419 enum ufs_ref_clk_freq val;
8422 static const struct ufs_ref_clk ufs_ref_clk_freqs[] = {
8423 {19200000, REF_CLK_FREQ_19_2_MHZ},
8424 {26000000, REF_CLK_FREQ_26_MHZ},
8425 {38400000, REF_CLK_FREQ_38_4_MHZ},
8426 {52000000, REF_CLK_FREQ_52_MHZ},
8427 {0, REF_CLK_FREQ_INVAL},
8430 static enum ufs_ref_clk_freq
8431 ufs_get_bref_clk_from_hz(unsigned long freq)
8435 for (i = 0; ufs_ref_clk_freqs[i].freq_hz; i++)
8436 if (ufs_ref_clk_freqs[i].freq_hz == freq)
8437 return ufs_ref_clk_freqs[i].val;
8439 return REF_CLK_FREQ_INVAL;
8442 void ufshcd_parse_dev_ref_clk_freq(struct ufs_hba *hba, struct clk *refclk)
8446 freq = clk_get_rate(refclk);
8448 hba->dev_ref_clk_freq =
8449 ufs_get_bref_clk_from_hz(freq);
8451 if (hba->dev_ref_clk_freq == REF_CLK_FREQ_INVAL)
8453 "invalid ref_clk setting = %ld\n", freq);
8456 static int ufshcd_set_dev_ref_clk(struct ufs_hba *hba)
8460 u32 freq = hba->dev_ref_clk_freq;
8462 err = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
8463 QUERY_ATTR_IDN_REF_CLK_FREQ, 0, 0, &ref_clk);
8466 dev_err(hba->dev, "failed reading bRefClkFreq. err = %d\n",
8471 if (ref_clk == freq)
8472 goto out; /* nothing to update */
8474 err = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_WRITE_ATTR,
8475 QUERY_ATTR_IDN_REF_CLK_FREQ, 0, 0, &freq);
8478 dev_err(hba->dev, "bRefClkFreq setting to %lu Hz failed\n",
8479 ufs_ref_clk_freqs[freq].freq_hz);
8483 dev_dbg(hba->dev, "bRefClkFreq setting to %lu Hz succeeded\n",
8484 ufs_ref_clk_freqs[freq].freq_hz);
8490 static int ufshcd_device_params_init(struct ufs_hba *hba)
8495 /* Init UFS geometry descriptor related parameters */
8496 ret = ufshcd_device_geo_params_init(hba);
8500 /* Check and apply UFS device quirks */
8501 ret = ufs_get_device_desc(hba);
8503 dev_err(hba->dev, "%s: Failed getting device info. err = %d\n",
8508 ufshcd_get_ref_clk_gating_wait(hba);
8510 if (!ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_READ_FLAG,
8511 QUERY_FLAG_IDN_PWR_ON_WPE, 0, &flag))
8512 hba->dev_info.f_power_on_wp_en = flag;
8514 /* Probe maximum power mode co-supported by both UFS host and device */
8515 if (ufshcd_get_max_pwr_mode(hba))
8517 "%s: Failed getting max supported power mode\n",
8524 * ufshcd_add_lus - probe and add UFS logical units
8525 * @hba: per-adapter instance
8527 static int ufshcd_add_lus(struct ufs_hba *hba)
8531 /* Add required well known logical units to scsi mid layer */
8532 ret = ufshcd_scsi_add_wlus(hba);
8536 /* Initialize devfreq after UFS device is detected */
8537 if (ufshcd_is_clkscaling_supported(hba)) {
8538 memcpy(&hba->clk_scaling.saved_pwr_info,
8540 sizeof(struct ufs_pa_layer_attr));
8541 hba->clk_scaling.is_allowed = true;
8543 ret = ufshcd_devfreq_init(hba);
8547 hba->clk_scaling.is_enabled = true;
8548 ufshcd_init_clk_scaling_sysfs(hba);
8553 scsi_scan_host(hba->host);
8554 pm_runtime_put_sync(hba->dev);
8560 /* SDB - Single Doorbell */
8561 static void ufshcd_release_sdb_queue(struct ufs_hba *hba, int nutrs)
8563 size_t ucdl_size, utrdl_size;
8565 ucdl_size = ufshcd_get_ucd_size(hba) * nutrs;
8566 dmam_free_coherent(hba->dev, ucdl_size, hba->ucdl_base_addr,
8567 hba->ucdl_dma_addr);
8569 utrdl_size = sizeof(struct utp_transfer_req_desc) * nutrs;
8570 dmam_free_coherent(hba->dev, utrdl_size, hba->utrdl_base_addr,
8571 hba->utrdl_dma_addr);
8573 devm_kfree(hba->dev, hba->lrb);
8576 static int ufshcd_alloc_mcq(struct ufs_hba *hba)
8579 int old_nutrs = hba->nutrs;
8581 ret = ufshcd_mcq_decide_queue_depth(hba);
8586 ret = ufshcd_mcq_init(hba);
8591 * Previously allocated memory for nutrs may not be enough in MCQ mode.
8592 * Number of supported tags in MCQ mode may be larger than SDB mode.
8594 if (hba->nutrs != old_nutrs) {
8595 ufshcd_release_sdb_queue(hba, old_nutrs);
8596 ret = ufshcd_memory_alloc(hba);
8599 ufshcd_host_memory_configure(hba);
8602 ret = ufshcd_mcq_memory_alloc(hba);
8608 hba->nutrs = old_nutrs;
8612 static void ufshcd_config_mcq(struct ufs_hba *hba)
8617 ret = ufshcd_mcq_vops_config_esi(hba);
8618 dev_info(hba->dev, "ESI %sconfigured\n", ret ? "is not " : "");
8620 intrs = UFSHCD_ENABLE_MCQ_INTRS;
8621 if (hba->quirks & UFSHCD_QUIRK_MCQ_BROKEN_INTR)
8622 intrs &= ~MCQ_CQ_EVENT_STATUS;
8623 ufshcd_enable_intr(hba, intrs);
8624 ufshcd_mcq_make_queues_operational(hba);
8625 ufshcd_mcq_config_mac(hba, hba->nutrs);
8627 hba->host->can_queue = hba->nutrs - UFSHCD_NUM_RESERVED;
8628 hba->reserved_slot = hba->nutrs - UFSHCD_NUM_RESERVED;
8630 /* Select MCQ mode */
8631 ufshcd_writel(hba, ufshcd_readl(hba, REG_UFS_MEM_CFG) | 0x1,
8633 hba->mcq_enabled = true;
8635 dev_info(hba->dev, "MCQ configured, nr_queues=%d, io_queues=%d, read_queue=%d, poll_queues=%d, queue_depth=%d\n",
8636 hba->nr_hw_queues, hba->nr_queues[HCTX_TYPE_DEFAULT],
8637 hba->nr_queues[HCTX_TYPE_READ], hba->nr_queues[HCTX_TYPE_POLL],
8641 static int ufshcd_device_init(struct ufs_hba *hba, bool init_dev_params)
8644 struct Scsi_Host *host = hba->host;
8646 hba->ufshcd_state = UFSHCD_STATE_RESET;
8648 ret = ufshcd_link_startup(hba);
8652 if (hba->quirks & UFSHCD_QUIRK_SKIP_PH_CONFIGURATION)
8655 /* Debug counters initialization */
8656 ufshcd_clear_dbg_ufs_stats(hba);
8658 /* UniPro link is active now */
8659 ufshcd_set_link_active(hba);
8661 /* Reconfigure MCQ upon reset */
8662 if (is_mcq_enabled(hba) && !init_dev_params)
8663 ufshcd_config_mcq(hba);
8665 /* Verify device initialization by sending NOP OUT UPIU */
8666 ret = ufshcd_verify_dev_init(hba);
8670 /* Initiate UFS initialization, and waiting until completion */
8671 ret = ufshcd_complete_dev_init(hba);
8676 * Initialize UFS device parameters used by driver, these
8677 * parameters are associated with UFS descriptors.
8679 if (init_dev_params) {
8680 ret = ufshcd_device_params_init(hba);
8683 if (is_mcq_supported(hba) && !hba->scsi_host_added) {
8684 ret = ufshcd_alloc_mcq(hba);
8686 ufshcd_config_mcq(hba);
8688 /* Continue with SDB mode */
8689 use_mcq_mode = false;
8690 dev_err(hba->dev, "MCQ mode is disabled, err=%d\n",
8693 ret = scsi_add_host(host, hba->dev);
8695 dev_err(hba->dev, "scsi_add_host failed\n");
8698 hba->scsi_host_added = true;
8699 } else if (is_mcq_supported(hba)) {
8700 /* UFSHCD_QUIRK_REINIT_AFTER_MAX_GEAR_SWITCH is set */
8701 ufshcd_config_mcq(hba);
8705 ufshcd_tune_unipro_params(hba);
8707 /* UFS device is also active now */
8708 ufshcd_set_ufs_dev_active(hba);
8709 ufshcd_force_reset_auto_bkops(hba);
8711 /* Gear up to HS gear if supported */
8712 if (hba->max_pwr_info.is_valid) {
8714 * Set the right value to bRefClkFreq before attempting to
8715 * switch to HS gears.
8717 if (hba->dev_ref_clk_freq != REF_CLK_FREQ_INVAL)
8718 ufshcd_set_dev_ref_clk(hba);
8719 ret = ufshcd_config_pwr_mode(hba, &hba->max_pwr_info.info);
8721 dev_err(hba->dev, "%s: Failed setting power mode, err = %d\n",
8731 * ufshcd_probe_hba - probe hba to detect device and initialize it
8732 * @hba: per-adapter instance
8733 * @init_dev_params: whether or not to call ufshcd_device_params_init().
8735 * Execute link-startup and verify device initialization
8737 static int ufshcd_probe_hba(struct ufs_hba *hba, bool init_dev_params)
8739 ktime_t start = ktime_get();
8740 unsigned long flags;
8743 ret = ufshcd_device_init(hba, init_dev_params);
8747 if (hba->quirks & UFSHCD_QUIRK_REINIT_AFTER_MAX_GEAR_SWITCH) {
8748 /* Reset the device and controller before doing reinit */
8749 ufshcd_device_reset(hba);
8750 ufshcd_hba_stop(hba);
8751 ufshcd_vops_reinit_notify(hba);
8752 ret = ufshcd_hba_enable(hba);
8754 dev_err(hba->dev, "Host controller enable failed\n");
8755 ufshcd_print_evt_hist(hba);
8756 ufshcd_print_host_state(hba);
8760 /* Reinit the device */
8761 ret = ufshcd_device_init(hba, init_dev_params);
8766 ufshcd_print_pwr_info(hba);
8769 * bActiveICCLevel is volatile for UFS device (as per latest v2.1 spec)
8770 * and for removable UFS card as well, hence always set the parameter.
8771 * Note: Error handler may issue the device reset hence resetting
8772 * bActiveICCLevel as well so it is always safe to set this here.
8774 ufshcd_set_active_icc_lvl(hba);
8776 /* Enable UFS Write Booster if supported */
8777 ufshcd_configure_wb(hba);
8779 if (hba->ee_usr_mask)
8780 ufshcd_write_ee_control(hba);
8781 /* Enable Auto-Hibernate if configured */
8782 ufshcd_auto_hibern8_enable(hba);
8784 ufshpb_toggle_state(hba, HPB_RESET, HPB_PRESENT);
8786 spin_lock_irqsave(hba->host->host_lock, flags);
8788 hba->ufshcd_state = UFSHCD_STATE_ERROR;
8789 else if (hba->ufshcd_state == UFSHCD_STATE_RESET)
8790 hba->ufshcd_state = UFSHCD_STATE_OPERATIONAL;
8791 spin_unlock_irqrestore(hba->host->host_lock, flags);
8793 trace_ufshcd_init(dev_name(hba->dev), ret,
8794 ktime_to_us(ktime_sub(ktime_get(), start)),
8795 hba->curr_dev_pwr_mode, hba->uic_link_state);
8800 * ufshcd_async_scan - asynchronous execution for probing hba
8801 * @data: data pointer to pass to this function
8802 * @cookie: cookie data
8804 static void ufshcd_async_scan(void *data, async_cookie_t cookie)
8806 struct ufs_hba *hba = (struct ufs_hba *)data;
8809 down(&hba->host_sem);
8810 /* Initialize hba, detect and initialize UFS device */
8811 ret = ufshcd_probe_hba(hba, true);
8816 /* Probe and add UFS logical units */
8817 ret = ufshcd_add_lus(hba);
8820 * If we failed to initialize the device or the device is not
8821 * present, turn off the power/clocks etc.
8824 pm_runtime_put_sync(hba->dev);
8825 ufshcd_hba_exit(hba);
8829 static enum scsi_timeout_action ufshcd_eh_timed_out(struct scsi_cmnd *scmd)
8831 struct ufs_hba *hba = shost_priv(scmd->device->host);
8833 if (!hba->system_suspending) {
8834 /* Activate the error handler in the SCSI core. */
8835 return SCSI_EH_NOT_HANDLED;
8839 * If we get here we know that no TMFs are outstanding and also that
8840 * the only pending command is a START STOP UNIT command. Handle the
8841 * timeout of that command directly to prevent a deadlock between
8842 * ufshcd_set_dev_pwr_mode() and ufshcd_err_handler().
8844 ufshcd_link_recovery(hba);
8845 dev_info(hba->dev, "%s() finished; outstanding_tasks = %#lx.\n",
8846 __func__, hba->outstanding_tasks);
8848 return hba->outstanding_reqs ? SCSI_EH_RESET_TIMER : SCSI_EH_DONE;
8851 static const struct attribute_group *ufshcd_driver_groups[] = {
8852 &ufs_sysfs_unit_descriptor_group,
8853 &ufs_sysfs_lun_attributes_group,
8854 #ifdef CONFIG_SCSI_UFS_HPB
8855 &ufs_sysfs_hpb_stat_group,
8856 &ufs_sysfs_hpb_param_group,
8861 static struct ufs_hba_variant_params ufs_hba_vps = {
8862 .hba_enable_delay_us = 1000,
8863 .wb_flush_threshold = UFS_WB_BUF_REMAIN_PERCENT(40),
8864 .devfreq_profile.polling_ms = 100,
8865 .devfreq_profile.target = ufshcd_devfreq_target,
8866 .devfreq_profile.get_dev_status = ufshcd_devfreq_get_dev_status,
8867 .ondemand_data.upthreshold = 70,
8868 .ondemand_data.downdifferential = 5,
8871 static const struct scsi_host_template ufshcd_driver_template = {
8872 .module = THIS_MODULE,
8874 .proc_name = UFSHCD,
8875 .map_queues = ufshcd_map_queues,
8876 .queuecommand = ufshcd_queuecommand,
8877 .mq_poll = ufshcd_poll,
8878 .slave_alloc = ufshcd_slave_alloc,
8879 .slave_configure = ufshcd_slave_configure,
8880 .slave_destroy = ufshcd_slave_destroy,
8881 .change_queue_depth = ufshcd_change_queue_depth,
8882 .eh_abort_handler = ufshcd_abort,
8883 .eh_device_reset_handler = ufshcd_eh_device_reset_handler,
8884 .eh_host_reset_handler = ufshcd_eh_host_reset_handler,
8885 .eh_timed_out = ufshcd_eh_timed_out,
8887 .sg_tablesize = SG_ALL,
8888 .cmd_per_lun = UFSHCD_CMD_PER_LUN,
8889 .can_queue = UFSHCD_CAN_QUEUE,
8890 .max_segment_size = PRDT_DATA_BYTE_COUNT_MAX,
8891 .max_sectors = SZ_1M / SECTOR_SIZE,
8892 .max_host_blocked = 1,
8893 .track_queue_depth = 1,
8894 .skip_settle_delay = 1,
8895 .sdev_groups = ufshcd_driver_groups,
8896 .rpm_autosuspend_delay = RPM_AUTOSUSPEND_DELAY_MS,
8899 static int ufshcd_config_vreg_load(struct device *dev, struct ufs_vreg *vreg,
8908 * "set_load" operation shall be required on those regulators
8909 * which specifically configured current limitation. Otherwise
8910 * zero max_uA may cause unexpected behavior when regulator is
8911 * enabled or set as high power mode.
8916 ret = regulator_set_load(vreg->reg, ua);
8918 dev_err(dev, "%s: %s set load (ua=%d) failed, err=%d\n",
8919 __func__, vreg->name, ua, ret);
8925 static inline int ufshcd_config_vreg_lpm(struct ufs_hba *hba,
8926 struct ufs_vreg *vreg)
8928 return ufshcd_config_vreg_load(hba->dev, vreg, UFS_VREG_LPM_LOAD_UA);
8931 static inline int ufshcd_config_vreg_hpm(struct ufs_hba *hba,
8932 struct ufs_vreg *vreg)
8937 return ufshcd_config_vreg_load(hba->dev, vreg, vreg->max_uA);
8940 static int ufshcd_config_vreg(struct device *dev,
8941 struct ufs_vreg *vreg, bool on)
8943 if (regulator_count_voltages(vreg->reg) <= 0)
8946 return ufshcd_config_vreg_load(dev, vreg, on ? vreg->max_uA : 0);
8949 static int ufshcd_enable_vreg(struct device *dev, struct ufs_vreg *vreg)
8953 if (!vreg || vreg->enabled)
8956 ret = ufshcd_config_vreg(dev, vreg, true);
8958 ret = regulator_enable(vreg->reg);
8961 vreg->enabled = true;
8963 dev_err(dev, "%s: %s enable failed, err=%d\n",
8964 __func__, vreg->name, ret);
8969 static int ufshcd_disable_vreg(struct device *dev, struct ufs_vreg *vreg)
8973 if (!vreg || !vreg->enabled || vreg->always_on)
8976 ret = regulator_disable(vreg->reg);
8979 /* ignore errors on applying disable config */
8980 ufshcd_config_vreg(dev, vreg, false);
8981 vreg->enabled = false;
8983 dev_err(dev, "%s: %s disable failed, err=%d\n",
8984 __func__, vreg->name, ret);
8990 static int ufshcd_setup_vreg(struct ufs_hba *hba, bool on)
8993 struct device *dev = hba->dev;
8994 struct ufs_vreg_info *info = &hba->vreg_info;
8996 ret = ufshcd_toggle_vreg(dev, info->vcc, on);
9000 ret = ufshcd_toggle_vreg(dev, info->vccq, on);
9004 ret = ufshcd_toggle_vreg(dev, info->vccq2, on);
9008 ufshcd_toggle_vreg(dev, info->vccq2, false);
9009 ufshcd_toggle_vreg(dev, info->vccq, false);
9010 ufshcd_toggle_vreg(dev, info->vcc, false);
9015 static int ufshcd_setup_hba_vreg(struct ufs_hba *hba, bool on)
9017 struct ufs_vreg_info *info = &hba->vreg_info;
9019 return ufshcd_toggle_vreg(hba->dev, info->vdd_hba, on);
9022 int ufshcd_get_vreg(struct device *dev, struct ufs_vreg *vreg)
9029 vreg->reg = devm_regulator_get(dev, vreg->name);
9030 if (IS_ERR(vreg->reg)) {
9031 ret = PTR_ERR(vreg->reg);
9032 dev_err(dev, "%s: %s get failed, err=%d\n",
9033 __func__, vreg->name, ret);
9038 EXPORT_SYMBOL_GPL(ufshcd_get_vreg);
9040 static int ufshcd_init_vreg(struct ufs_hba *hba)
9043 struct device *dev = hba->dev;
9044 struct ufs_vreg_info *info = &hba->vreg_info;
9046 ret = ufshcd_get_vreg(dev, info->vcc);
9050 ret = ufshcd_get_vreg(dev, info->vccq);
9052 ret = ufshcd_get_vreg(dev, info->vccq2);
9057 static int ufshcd_init_hba_vreg(struct ufs_hba *hba)
9059 struct ufs_vreg_info *info = &hba->vreg_info;
9061 return ufshcd_get_vreg(hba->dev, info->vdd_hba);
9064 static int ufshcd_setup_clocks(struct ufs_hba *hba, bool on)
9067 struct ufs_clk_info *clki;
9068 struct list_head *head = &hba->clk_list_head;
9069 unsigned long flags;
9070 ktime_t start = ktime_get();
9071 bool clk_state_changed = false;
9073 if (list_empty(head))
9076 ret = ufshcd_vops_setup_clocks(hba, on, PRE_CHANGE);
9080 list_for_each_entry(clki, head, list) {
9081 if (!IS_ERR_OR_NULL(clki->clk)) {
9083 * Don't disable clocks which are needed
9084 * to keep the link active.
9086 if (ufshcd_is_link_active(hba) &&
9087 clki->keep_link_active)
9090 clk_state_changed = on ^ clki->enabled;
9091 if (on && !clki->enabled) {
9092 ret = clk_prepare_enable(clki->clk);
9094 dev_err(hba->dev, "%s: %s prepare enable failed, %d\n",
9095 __func__, clki->name, ret);
9098 } else if (!on && clki->enabled) {
9099 clk_disable_unprepare(clki->clk);
9102 dev_dbg(hba->dev, "%s: clk: %s %sabled\n", __func__,
9103 clki->name, on ? "en" : "dis");
9107 ret = ufshcd_vops_setup_clocks(hba, on, POST_CHANGE);
9113 list_for_each_entry(clki, head, list) {
9114 if (!IS_ERR_OR_NULL(clki->clk) && clki->enabled)
9115 clk_disable_unprepare(clki->clk);
9117 } else if (!ret && on) {
9118 spin_lock_irqsave(hba->host->host_lock, flags);
9119 hba->clk_gating.state = CLKS_ON;
9120 trace_ufshcd_clk_gating(dev_name(hba->dev),
9121 hba->clk_gating.state);
9122 spin_unlock_irqrestore(hba->host->host_lock, flags);
9125 if (clk_state_changed)
9126 trace_ufshcd_profile_clk_gating(dev_name(hba->dev),
9127 (on ? "on" : "off"),
9128 ktime_to_us(ktime_sub(ktime_get(), start)), ret);
9132 static enum ufs_ref_clk_freq ufshcd_parse_ref_clk_property(struct ufs_hba *hba)
9135 int ret = device_property_read_u32(hba->dev, "ref-clk-freq", &freq);
9138 dev_dbg(hba->dev, "Cannot query 'ref-clk-freq' property = %d", ret);
9139 return REF_CLK_FREQ_INVAL;
9142 return ufs_get_bref_clk_from_hz(freq);
9145 static int ufshcd_init_clocks(struct ufs_hba *hba)
9148 struct ufs_clk_info *clki;
9149 struct device *dev = hba->dev;
9150 struct list_head *head = &hba->clk_list_head;
9152 if (list_empty(head))
9155 list_for_each_entry(clki, head, list) {
9159 clki->clk = devm_clk_get(dev, clki->name);
9160 if (IS_ERR(clki->clk)) {
9161 ret = PTR_ERR(clki->clk);
9162 dev_err(dev, "%s: %s clk get failed, %d\n",
9163 __func__, clki->name, ret);
9168 * Parse device ref clk freq as per device tree "ref_clk".
9169 * Default dev_ref_clk_freq is set to REF_CLK_FREQ_INVAL
9170 * in ufshcd_alloc_host().
9172 if (!strcmp(clki->name, "ref_clk"))
9173 ufshcd_parse_dev_ref_clk_freq(hba, clki->clk);
9175 if (clki->max_freq) {
9176 ret = clk_set_rate(clki->clk, clki->max_freq);
9178 dev_err(hba->dev, "%s: %s clk set rate(%dHz) failed, %d\n",
9179 __func__, clki->name,
9180 clki->max_freq, ret);
9183 clki->curr_freq = clki->max_freq;
9185 dev_dbg(dev, "%s: clk: %s, rate: %lu\n", __func__,
9186 clki->name, clk_get_rate(clki->clk));
9192 static int ufshcd_variant_hba_init(struct ufs_hba *hba)
9199 err = ufshcd_vops_init(hba);
9201 dev_err(hba->dev, "%s: variant %s init failed err %d\n",
9202 __func__, ufshcd_get_var_name(hba), err);
9207 static void ufshcd_variant_hba_exit(struct ufs_hba *hba)
9212 ufshcd_vops_exit(hba);
9215 static int ufshcd_hba_init(struct ufs_hba *hba)
9220 * Handle host controller power separately from the UFS device power
9221 * rails as it will help controlling the UFS host controller power
9222 * collapse easily which is different than UFS device power collapse.
9223 * Also, enable the host controller power before we go ahead with rest
9224 * of the initialization here.
9226 err = ufshcd_init_hba_vreg(hba);
9230 err = ufshcd_setup_hba_vreg(hba, true);
9234 err = ufshcd_init_clocks(hba);
9236 goto out_disable_hba_vreg;
9238 if (hba->dev_ref_clk_freq == REF_CLK_FREQ_INVAL)
9239 hba->dev_ref_clk_freq = ufshcd_parse_ref_clk_property(hba);
9241 err = ufshcd_setup_clocks(hba, true);
9243 goto out_disable_hba_vreg;
9245 err = ufshcd_init_vreg(hba);
9247 goto out_disable_clks;
9249 err = ufshcd_setup_vreg(hba, true);
9251 goto out_disable_clks;
9253 err = ufshcd_variant_hba_init(hba);
9255 goto out_disable_vreg;
9257 ufs_debugfs_hba_init(hba);
9259 hba->is_powered = true;
9263 ufshcd_setup_vreg(hba, false);
9265 ufshcd_setup_clocks(hba, false);
9266 out_disable_hba_vreg:
9267 ufshcd_setup_hba_vreg(hba, false);
9272 static void ufshcd_hba_exit(struct ufs_hba *hba)
9274 if (hba->is_powered) {
9275 ufshcd_exit_clk_scaling(hba);
9276 ufshcd_exit_clk_gating(hba);
9278 destroy_workqueue(hba->eh_wq);
9279 ufs_debugfs_hba_exit(hba);
9280 ufshcd_variant_hba_exit(hba);
9281 ufshcd_setup_vreg(hba, false);
9282 ufshcd_setup_clocks(hba, false);
9283 ufshcd_setup_hba_vreg(hba, false);
9284 hba->is_powered = false;
9285 ufs_put_device_desc(hba);
9289 static int ufshcd_execute_start_stop(struct scsi_device *sdev,
9290 enum ufs_dev_pwr_mode pwr_mode,
9291 struct scsi_sense_hdr *sshdr)
9293 const unsigned char cdb[6] = { START_STOP, 0, 0, 0, pwr_mode << 4, 0 };
9294 const struct scsi_exec_args args = {
9296 .req_flags = BLK_MQ_REQ_PM,
9297 .scmd_flags = SCMD_FAIL_IF_RECOVERING,
9300 return scsi_execute_cmd(sdev, cdb, REQ_OP_DRV_IN, /*buffer=*/NULL,
9301 /*bufflen=*/0, /*timeout=*/10 * HZ, /*retries=*/0,
9306 * ufshcd_set_dev_pwr_mode - sends START STOP UNIT command to set device
9308 * @hba: per adapter instance
9309 * @pwr_mode: device power mode to set
9311 * Returns 0 if requested power mode is set successfully
9312 * Returns < 0 if failed to set the requested power mode
9314 static int ufshcd_set_dev_pwr_mode(struct ufs_hba *hba,
9315 enum ufs_dev_pwr_mode pwr_mode)
9317 struct scsi_sense_hdr sshdr;
9318 struct scsi_device *sdp;
9319 unsigned long flags;
9322 spin_lock_irqsave(hba->host->host_lock, flags);
9323 sdp = hba->ufs_device_wlun;
9324 if (sdp && scsi_device_online(sdp))
9325 ret = scsi_device_get(sdp);
9328 spin_unlock_irqrestore(hba->host->host_lock, flags);
9334 * If scsi commands fail, the scsi mid-layer schedules scsi error-
9335 * handling, which would wait for host to be resumed. Since we know
9336 * we are functional while we are here, skip host resume in error
9339 hba->host->eh_noresume = 1;
9342 * Current function would be generally called from the power management
9343 * callbacks hence set the RQF_PM flag so that it doesn't resume the
9344 * already suspended childs.
9346 for (retries = 3; retries > 0; --retries) {
9347 ret = ufshcd_execute_start_stop(sdp, pwr_mode, &sshdr);
9349 * scsi_execute() only returns a negative value if the request
9356 sdev_printk(KERN_WARNING, sdp,
9357 "START_STOP failed for power mode: %d, result %x\n",
9360 if (scsi_sense_valid(&sshdr))
9361 scsi_print_sense_hdr(sdp, NULL, &sshdr);
9365 hba->curr_dev_pwr_mode = pwr_mode;
9368 scsi_device_put(sdp);
9369 hba->host->eh_noresume = 0;
9373 static int ufshcd_link_state_transition(struct ufs_hba *hba,
9374 enum uic_link_state req_link_state,
9375 bool check_for_bkops)
9379 if (req_link_state == hba->uic_link_state)
9382 if (req_link_state == UIC_LINK_HIBERN8_STATE) {
9383 ret = ufshcd_uic_hibern8_enter(hba);
9385 ufshcd_set_link_hibern8(hba);
9387 dev_err(hba->dev, "%s: hibern8 enter failed %d\n",
9393 * If autobkops is enabled, link can't be turned off because
9394 * turning off the link would also turn off the device, except in the
9395 * case of DeepSleep where the device is expected to remain powered.
9397 else if ((req_link_state == UIC_LINK_OFF_STATE) &&
9398 (!check_for_bkops || !hba->auto_bkops_enabled)) {
9400 * Let's make sure that link is in low power mode, we are doing
9401 * this currently by putting the link in Hibern8. Otherway to
9402 * put the link in low power mode is to send the DME end point
9403 * to device and then send the DME reset command to local
9404 * unipro. But putting the link in hibern8 is much faster.
9406 * Note also that putting the link in Hibern8 is a requirement
9407 * for entering DeepSleep.
9409 ret = ufshcd_uic_hibern8_enter(hba);
9411 dev_err(hba->dev, "%s: hibern8 enter failed %d\n",
9416 * Change controller state to "reset state" which
9417 * should also put the link in off/reset state
9419 ufshcd_hba_stop(hba);
9421 * TODO: Check if we need any delay to make sure that
9422 * controller is reset
9424 ufshcd_set_link_off(hba);
9431 static void ufshcd_vreg_set_lpm(struct ufs_hba *hba)
9433 bool vcc_off = false;
9436 * It seems some UFS devices may keep drawing more than sleep current
9437 * (atleast for 500us) from UFS rails (especially from VCCQ rail).
9438 * To avoid this situation, add 2ms delay before putting these UFS
9439 * rails in LPM mode.
9441 if (!ufshcd_is_link_active(hba) &&
9442 hba->dev_quirks & UFS_DEVICE_QUIRK_DELAY_BEFORE_LPM)
9443 usleep_range(2000, 2100);
9446 * If UFS device is either in UFS_Sleep turn off VCC rail to save some
9449 * If UFS device and link is in OFF state, all power supplies (VCC,
9450 * VCCQ, VCCQ2) can be turned off if power on write protect is not
9451 * required. If UFS link is inactive (Hibern8 or OFF state) and device
9452 * is in sleep state, put VCCQ & VCCQ2 rails in LPM mode.
9454 * Ignore the error returned by ufshcd_toggle_vreg() as device is anyway
9455 * in low power state which would save some power.
9457 * If Write Booster is enabled and the device needs to flush the WB
9458 * buffer OR if bkops status is urgent for WB, keep Vcc on.
9460 if (ufshcd_is_ufs_dev_poweroff(hba) && ufshcd_is_link_off(hba) &&
9461 !hba->dev_info.is_lu_power_on_wp) {
9462 ufshcd_setup_vreg(hba, false);
9464 } else if (!ufshcd_is_ufs_dev_active(hba)) {
9465 ufshcd_toggle_vreg(hba->dev, hba->vreg_info.vcc, false);
9467 if (ufshcd_is_link_hibern8(hba) || ufshcd_is_link_off(hba)) {
9468 ufshcd_config_vreg_lpm(hba, hba->vreg_info.vccq);
9469 ufshcd_config_vreg_lpm(hba, hba->vreg_info.vccq2);
9474 * Some UFS devices require delay after VCC power rail is turned-off.
9476 if (vcc_off && hba->vreg_info.vcc &&
9477 hba->dev_quirks & UFS_DEVICE_QUIRK_DELAY_AFTER_LPM)
9478 usleep_range(5000, 5100);
9482 static int ufshcd_vreg_set_hpm(struct ufs_hba *hba)
9486 if (ufshcd_is_ufs_dev_poweroff(hba) && ufshcd_is_link_off(hba) &&
9487 !hba->dev_info.is_lu_power_on_wp) {
9488 ret = ufshcd_setup_vreg(hba, true);
9489 } else if (!ufshcd_is_ufs_dev_active(hba)) {
9490 if (!ufshcd_is_link_active(hba)) {
9491 ret = ufshcd_config_vreg_hpm(hba, hba->vreg_info.vccq);
9494 ret = ufshcd_config_vreg_hpm(hba, hba->vreg_info.vccq2);
9498 ret = ufshcd_toggle_vreg(hba->dev, hba->vreg_info.vcc, true);
9503 ufshcd_config_vreg_lpm(hba, hba->vreg_info.vccq);
9505 ufshcd_toggle_vreg(hba->dev, hba->vreg_info.vcc, false);
9509 #endif /* CONFIG_PM */
9511 static void ufshcd_hba_vreg_set_lpm(struct ufs_hba *hba)
9513 if (ufshcd_is_link_off(hba) || ufshcd_can_aggressive_pc(hba))
9514 ufshcd_setup_hba_vreg(hba, false);
9517 static void ufshcd_hba_vreg_set_hpm(struct ufs_hba *hba)
9519 if (ufshcd_is_link_off(hba) || ufshcd_can_aggressive_pc(hba))
9520 ufshcd_setup_hba_vreg(hba, true);
9523 static int __ufshcd_wl_suspend(struct ufs_hba *hba, enum ufs_pm_op pm_op)
9526 bool check_for_bkops;
9527 enum ufs_pm_level pm_lvl;
9528 enum ufs_dev_pwr_mode req_dev_pwr_mode;
9529 enum uic_link_state req_link_state;
9531 hba->pm_op_in_progress = true;
9532 if (pm_op != UFS_SHUTDOWN_PM) {
9533 pm_lvl = pm_op == UFS_RUNTIME_PM ?
9534 hba->rpm_lvl : hba->spm_lvl;
9535 req_dev_pwr_mode = ufs_get_pm_lvl_to_dev_pwr_mode(pm_lvl);
9536 req_link_state = ufs_get_pm_lvl_to_link_pwr_state(pm_lvl);
9538 req_dev_pwr_mode = UFS_POWERDOWN_PWR_MODE;
9539 req_link_state = UIC_LINK_OFF_STATE;
9542 ufshpb_suspend(hba);
9545 * If we can't transition into any of the low power modes
9546 * just gate the clocks.
9549 hba->clk_gating.is_suspended = true;
9551 if (ufshcd_is_clkscaling_supported(hba))
9552 ufshcd_clk_scaling_suspend(hba, true);
9554 if (req_dev_pwr_mode == UFS_ACTIVE_PWR_MODE &&
9555 req_link_state == UIC_LINK_ACTIVE_STATE) {
9559 if ((req_dev_pwr_mode == hba->curr_dev_pwr_mode) &&
9560 (req_link_state == hba->uic_link_state))
9561 goto enable_scaling;
9563 /* UFS device & link must be active before we enter in this function */
9564 if (!ufshcd_is_ufs_dev_active(hba) || !ufshcd_is_link_active(hba)) {
9566 goto enable_scaling;
9569 if (pm_op == UFS_RUNTIME_PM) {
9570 if (ufshcd_can_autobkops_during_suspend(hba)) {
9572 * The device is idle with no requests in the queue,
9573 * allow background operations if bkops status shows
9574 * that performance might be impacted.
9576 ret = ufshcd_urgent_bkops(hba);
9579 * If return err in suspend flow, IO will hang.
9580 * Trigger error handler and break suspend for
9583 ufshcd_force_error_recovery(hba);
9585 goto enable_scaling;
9588 /* make sure that auto bkops is disabled */
9589 ufshcd_disable_auto_bkops(hba);
9592 * If device needs to do BKOP or WB buffer flush during
9593 * Hibern8, keep device power mode as "active power mode"
9596 hba->dev_info.b_rpm_dev_flush_capable =
9597 hba->auto_bkops_enabled ||
9598 (((req_link_state == UIC_LINK_HIBERN8_STATE) ||
9599 ((req_link_state == UIC_LINK_ACTIVE_STATE) &&
9600 ufshcd_is_auto_hibern8_enabled(hba))) &&
9601 ufshcd_wb_need_flush(hba));
9604 flush_work(&hba->eeh_work);
9606 ret = ufshcd_vops_suspend(hba, pm_op, PRE_CHANGE);
9608 goto enable_scaling;
9610 if (req_dev_pwr_mode != hba->curr_dev_pwr_mode) {
9611 if (pm_op != UFS_RUNTIME_PM)
9612 /* ensure that bkops is disabled */
9613 ufshcd_disable_auto_bkops(hba);
9615 if (!hba->dev_info.b_rpm_dev_flush_capable) {
9616 ret = ufshcd_set_dev_pwr_mode(hba, req_dev_pwr_mode);
9617 if (ret && pm_op != UFS_SHUTDOWN_PM) {
9619 * If return err in suspend flow, IO will hang.
9620 * Trigger error handler and break suspend for
9623 ufshcd_force_error_recovery(hba);
9627 goto enable_scaling;
9632 * In the case of DeepSleep, the device is expected to remain powered
9633 * with the link off, so do not check for bkops.
9635 check_for_bkops = !ufshcd_is_ufs_dev_deepsleep(hba);
9636 ret = ufshcd_link_state_transition(hba, req_link_state, check_for_bkops);
9637 if (ret && pm_op != UFS_SHUTDOWN_PM) {
9639 * If return err in suspend flow, IO will hang.
9640 * Trigger error handler and break suspend for
9643 ufshcd_force_error_recovery(hba);
9647 goto set_dev_active;
9651 * Call vendor specific suspend callback. As these callbacks may access
9652 * vendor specific host controller register space call them before the
9653 * host clocks are ON.
9655 ret = ufshcd_vops_suspend(hba, pm_op, POST_CHANGE);
9657 goto set_link_active;
9662 * Device hardware reset is required to exit DeepSleep. Also, for
9663 * DeepSleep, the link is off so host reset and restore will be done
9666 if (ufshcd_is_ufs_dev_deepsleep(hba)) {
9667 ufshcd_device_reset(hba);
9668 WARN_ON(!ufshcd_is_link_off(hba));
9670 if (ufshcd_is_link_hibern8(hba) && !ufshcd_uic_hibern8_exit(hba))
9671 ufshcd_set_link_active(hba);
9672 else if (ufshcd_is_link_off(hba))
9673 ufshcd_host_reset_and_restore(hba);
9675 /* Can also get here needing to exit DeepSleep */
9676 if (ufshcd_is_ufs_dev_deepsleep(hba)) {
9677 ufshcd_device_reset(hba);
9678 ufshcd_host_reset_and_restore(hba);
9680 if (!ufshcd_set_dev_pwr_mode(hba, UFS_ACTIVE_PWR_MODE))
9681 ufshcd_disable_auto_bkops(hba);
9683 if (ufshcd_is_clkscaling_supported(hba))
9684 ufshcd_clk_scaling_suspend(hba, false);
9686 hba->dev_info.b_rpm_dev_flush_capable = false;
9688 if (hba->dev_info.b_rpm_dev_flush_capable) {
9689 schedule_delayed_work(&hba->rpm_dev_flush_recheck_work,
9690 msecs_to_jiffies(RPM_DEV_FLUSH_RECHECK_WORK_DELAY_MS));
9694 ufshcd_update_evt_hist(hba, UFS_EVT_WL_SUSP_ERR, (u32)ret);
9695 hba->clk_gating.is_suspended = false;
9696 ufshcd_release(hba);
9699 hba->pm_op_in_progress = false;
9704 static int __ufshcd_wl_resume(struct ufs_hba *hba, enum ufs_pm_op pm_op)
9707 enum uic_link_state old_link_state = hba->uic_link_state;
9709 hba->pm_op_in_progress = true;
9712 * Call vendor specific resume callback. As these callbacks may access
9713 * vendor specific host controller register space call them when the
9714 * host clocks are ON.
9716 ret = ufshcd_vops_resume(hba, pm_op);
9720 /* For DeepSleep, the only supported option is to have the link off */
9721 WARN_ON(ufshcd_is_ufs_dev_deepsleep(hba) && !ufshcd_is_link_off(hba));
9723 if (ufshcd_is_link_hibern8(hba)) {
9724 ret = ufshcd_uic_hibern8_exit(hba);
9726 ufshcd_set_link_active(hba);
9728 dev_err(hba->dev, "%s: hibern8 exit failed %d\n",
9730 goto vendor_suspend;
9732 } else if (ufshcd_is_link_off(hba)) {
9734 * A full initialization of the host and the device is
9735 * required since the link was put to off during suspend.
9736 * Note, in the case of DeepSleep, the device will exit
9737 * DeepSleep due to device reset.
9739 ret = ufshcd_reset_and_restore(hba);
9741 * ufshcd_reset_and_restore() should have already
9742 * set the link state as active
9744 if (ret || !ufshcd_is_link_active(hba))
9745 goto vendor_suspend;
9748 if (!ufshcd_is_ufs_dev_active(hba)) {
9749 ret = ufshcd_set_dev_pwr_mode(hba, UFS_ACTIVE_PWR_MODE);
9751 goto set_old_link_state;
9754 if (ufshcd_keep_autobkops_enabled_except_suspend(hba))
9755 ufshcd_enable_auto_bkops(hba);
9758 * If BKOPs operations are urgently needed at this moment then
9759 * keep auto-bkops enabled or else disable it.
9761 ufshcd_urgent_bkops(hba);
9763 if (hba->ee_usr_mask)
9764 ufshcd_write_ee_control(hba);
9766 if (ufshcd_is_clkscaling_supported(hba))
9767 ufshcd_clk_scaling_suspend(hba, false);
9769 if (hba->dev_info.b_rpm_dev_flush_capable) {
9770 hba->dev_info.b_rpm_dev_flush_capable = false;
9771 cancel_delayed_work(&hba->rpm_dev_flush_recheck_work);
9774 /* Enable Auto-Hibernate if configured */
9775 ufshcd_auto_hibern8_enable(hba);
9781 ufshcd_link_state_transition(hba, old_link_state, 0);
9783 ufshcd_vops_suspend(hba, pm_op, PRE_CHANGE);
9784 ufshcd_vops_suspend(hba, pm_op, POST_CHANGE);
9787 ufshcd_update_evt_hist(hba, UFS_EVT_WL_RES_ERR, (u32)ret);
9788 hba->clk_gating.is_suspended = false;
9789 ufshcd_release(hba);
9790 hba->pm_op_in_progress = false;
9794 static int ufshcd_wl_runtime_suspend(struct device *dev)
9796 struct scsi_device *sdev = to_scsi_device(dev);
9797 struct ufs_hba *hba;
9799 ktime_t start = ktime_get();
9801 hba = shost_priv(sdev->host);
9803 ret = __ufshcd_wl_suspend(hba, UFS_RUNTIME_PM);
9805 dev_err(&sdev->sdev_gendev, "%s failed: %d\n", __func__, ret);
9807 trace_ufshcd_wl_runtime_suspend(dev_name(dev), ret,
9808 ktime_to_us(ktime_sub(ktime_get(), start)),
9809 hba->curr_dev_pwr_mode, hba->uic_link_state);
9814 static int ufshcd_wl_runtime_resume(struct device *dev)
9816 struct scsi_device *sdev = to_scsi_device(dev);
9817 struct ufs_hba *hba;
9819 ktime_t start = ktime_get();
9821 hba = shost_priv(sdev->host);
9823 ret = __ufshcd_wl_resume(hba, UFS_RUNTIME_PM);
9825 dev_err(&sdev->sdev_gendev, "%s failed: %d\n", __func__, ret);
9827 trace_ufshcd_wl_runtime_resume(dev_name(dev), ret,
9828 ktime_to_us(ktime_sub(ktime_get(), start)),
9829 hba->curr_dev_pwr_mode, hba->uic_link_state);
9835 #ifdef CONFIG_PM_SLEEP
9836 static int ufshcd_wl_suspend(struct device *dev)
9838 struct scsi_device *sdev = to_scsi_device(dev);
9839 struct ufs_hba *hba;
9841 ktime_t start = ktime_get();
9843 hba = shost_priv(sdev->host);
9844 down(&hba->host_sem);
9845 hba->system_suspending = true;
9847 if (pm_runtime_suspended(dev))
9850 ret = __ufshcd_wl_suspend(hba, UFS_SYSTEM_PM);
9852 dev_err(&sdev->sdev_gendev, "%s failed: %d\n", __func__, ret);
9858 hba->is_sys_suspended = true;
9859 trace_ufshcd_wl_suspend(dev_name(dev), ret,
9860 ktime_to_us(ktime_sub(ktime_get(), start)),
9861 hba->curr_dev_pwr_mode, hba->uic_link_state);
9866 static int ufshcd_wl_resume(struct device *dev)
9868 struct scsi_device *sdev = to_scsi_device(dev);
9869 struct ufs_hba *hba;
9871 ktime_t start = ktime_get();
9873 hba = shost_priv(sdev->host);
9875 if (pm_runtime_suspended(dev))
9878 ret = __ufshcd_wl_resume(hba, UFS_SYSTEM_PM);
9880 dev_err(&sdev->sdev_gendev, "%s failed: %d\n", __func__, ret);
9882 trace_ufshcd_wl_resume(dev_name(dev), ret,
9883 ktime_to_us(ktime_sub(ktime_get(), start)),
9884 hba->curr_dev_pwr_mode, hba->uic_link_state);
9886 hba->is_sys_suspended = false;
9887 hba->system_suspending = false;
9894 * ufshcd_suspend - helper function for suspend operations
9895 * @hba: per adapter instance
9897 * This function will put disable irqs, turn off clocks
9898 * and set vreg and hba-vreg in lpm mode.
9900 static int ufshcd_suspend(struct ufs_hba *hba)
9904 if (!hba->is_powered)
9907 * Disable the host irq as host controller as there won't be any
9908 * host controller transaction expected till resume.
9910 ufshcd_disable_irq(hba);
9911 ret = ufshcd_setup_clocks(hba, false);
9913 ufshcd_enable_irq(hba);
9916 if (ufshcd_is_clkgating_allowed(hba)) {
9917 hba->clk_gating.state = CLKS_OFF;
9918 trace_ufshcd_clk_gating(dev_name(hba->dev),
9919 hba->clk_gating.state);
9922 ufshcd_vreg_set_lpm(hba);
9923 /* Put the host controller in low power mode if possible */
9924 ufshcd_hba_vreg_set_lpm(hba);
9930 * ufshcd_resume - helper function for resume operations
9931 * @hba: per adapter instance
9933 * This function basically turns on the regulators, clocks and
9936 * Returns 0 for success and non-zero for failure
9938 static int ufshcd_resume(struct ufs_hba *hba)
9942 if (!hba->is_powered)
9945 ufshcd_hba_vreg_set_hpm(hba);
9946 ret = ufshcd_vreg_set_hpm(hba);
9950 /* Make sure clocks are enabled before accessing controller */
9951 ret = ufshcd_setup_clocks(hba, true);
9955 /* enable the host irq as host controller would be active soon */
9956 ufshcd_enable_irq(hba);
9961 ufshcd_vreg_set_lpm(hba);
9964 ufshcd_update_evt_hist(hba, UFS_EVT_RESUME_ERR, (u32)ret);
9967 #endif /* CONFIG_PM */
9969 #ifdef CONFIG_PM_SLEEP
9971 * ufshcd_system_suspend - system suspend callback
9972 * @dev: Device associated with the UFS controller.
9974 * Executed before putting the system into a sleep state in which the contents
9975 * of main memory are preserved.
9977 * Returns 0 for success and non-zero for failure
9979 int ufshcd_system_suspend(struct device *dev)
9981 struct ufs_hba *hba = dev_get_drvdata(dev);
9983 ktime_t start = ktime_get();
9985 if (pm_runtime_suspended(hba->dev))
9988 ret = ufshcd_suspend(hba);
9990 trace_ufshcd_system_suspend(dev_name(hba->dev), ret,
9991 ktime_to_us(ktime_sub(ktime_get(), start)),
9992 hba->curr_dev_pwr_mode, hba->uic_link_state);
9995 EXPORT_SYMBOL(ufshcd_system_suspend);
9998 * ufshcd_system_resume - system resume callback
9999 * @dev: Device associated with the UFS controller.
10001 * Executed after waking the system up from a sleep state in which the contents
10002 * of main memory were preserved.
10004 * Returns 0 for success and non-zero for failure
10006 int ufshcd_system_resume(struct device *dev)
10008 struct ufs_hba *hba = dev_get_drvdata(dev);
10009 ktime_t start = ktime_get();
10012 if (pm_runtime_suspended(hba->dev))
10015 ret = ufshcd_resume(hba);
10018 trace_ufshcd_system_resume(dev_name(hba->dev), ret,
10019 ktime_to_us(ktime_sub(ktime_get(), start)),
10020 hba->curr_dev_pwr_mode, hba->uic_link_state);
10024 EXPORT_SYMBOL(ufshcd_system_resume);
10025 #endif /* CONFIG_PM_SLEEP */
10029 * ufshcd_runtime_suspend - runtime suspend callback
10030 * @dev: Device associated with the UFS controller.
10032 * Check the description of ufshcd_suspend() function for more details.
10034 * Returns 0 for success and non-zero for failure
10036 int ufshcd_runtime_suspend(struct device *dev)
10038 struct ufs_hba *hba = dev_get_drvdata(dev);
10040 ktime_t start = ktime_get();
10042 ret = ufshcd_suspend(hba);
10044 trace_ufshcd_runtime_suspend(dev_name(hba->dev), ret,
10045 ktime_to_us(ktime_sub(ktime_get(), start)),
10046 hba->curr_dev_pwr_mode, hba->uic_link_state);
10049 EXPORT_SYMBOL(ufshcd_runtime_suspend);
10052 * ufshcd_runtime_resume - runtime resume routine
10053 * @dev: Device associated with the UFS controller.
10055 * This function basically brings controller
10056 * to active state. Following operations are done in this function:
10058 * 1. Turn on all the controller related clocks
10059 * 2. Turn ON VCC rail
10061 int ufshcd_runtime_resume(struct device *dev)
10063 struct ufs_hba *hba = dev_get_drvdata(dev);
10065 ktime_t start = ktime_get();
10067 ret = ufshcd_resume(hba);
10069 trace_ufshcd_runtime_resume(dev_name(hba->dev), ret,
10070 ktime_to_us(ktime_sub(ktime_get(), start)),
10071 hba->curr_dev_pwr_mode, hba->uic_link_state);
10074 EXPORT_SYMBOL(ufshcd_runtime_resume);
10075 #endif /* CONFIG_PM */
10077 static void ufshcd_wl_shutdown(struct device *dev)
10079 struct scsi_device *sdev = to_scsi_device(dev);
10080 struct ufs_hba *hba = shost_priv(sdev->host);
10082 down(&hba->host_sem);
10083 hba->shutting_down = true;
10084 up(&hba->host_sem);
10086 /* Turn on everything while shutting down */
10087 ufshcd_rpm_get_sync(hba);
10088 scsi_device_quiesce(sdev);
10089 shost_for_each_device(sdev, hba->host) {
10090 if (sdev == hba->ufs_device_wlun)
10092 scsi_device_quiesce(sdev);
10094 __ufshcd_wl_suspend(hba, UFS_SHUTDOWN_PM);
10097 * Next, turn off the UFS controller and the UFS regulators. Disable
10100 if (ufshcd_is_ufs_dev_poweroff(hba) && ufshcd_is_link_off(hba))
10101 ufshcd_suspend(hba);
10103 hba->is_powered = false;
10107 * ufshcd_remove - de-allocate SCSI host and host memory space
10108 * data structure memory
10109 * @hba: per adapter instance
10111 void ufshcd_remove(struct ufs_hba *hba)
10113 if (hba->ufs_device_wlun)
10114 ufshcd_rpm_get_sync(hba);
10115 ufs_hwmon_remove(hba);
10116 ufs_bsg_remove(hba);
10117 ufshpb_remove(hba);
10118 ufs_sysfs_remove_nodes(hba->dev);
10119 blk_mq_destroy_queue(hba->tmf_queue);
10120 blk_put_queue(hba->tmf_queue);
10121 blk_mq_free_tag_set(&hba->tmf_tag_set);
10122 scsi_remove_host(hba->host);
10123 /* disable interrupts */
10124 ufshcd_disable_intr(hba, hba->intr_mask);
10125 ufshcd_hba_stop(hba);
10126 ufshcd_hba_exit(hba);
10128 EXPORT_SYMBOL_GPL(ufshcd_remove);
10130 #ifdef CONFIG_PM_SLEEP
10131 int ufshcd_system_freeze(struct device *dev)
10134 return ufshcd_system_suspend(dev);
10137 EXPORT_SYMBOL_GPL(ufshcd_system_freeze);
10139 int ufshcd_system_restore(struct device *dev)
10142 struct ufs_hba *hba = dev_get_drvdata(dev);
10145 ret = ufshcd_system_resume(dev);
10149 /* Configure UTRL and UTMRL base address registers */
10150 ufshcd_writel(hba, lower_32_bits(hba->utrdl_dma_addr),
10151 REG_UTP_TRANSFER_REQ_LIST_BASE_L);
10152 ufshcd_writel(hba, upper_32_bits(hba->utrdl_dma_addr),
10153 REG_UTP_TRANSFER_REQ_LIST_BASE_H);
10154 ufshcd_writel(hba, lower_32_bits(hba->utmrdl_dma_addr),
10155 REG_UTP_TASK_REQ_LIST_BASE_L);
10156 ufshcd_writel(hba, upper_32_bits(hba->utmrdl_dma_addr),
10157 REG_UTP_TASK_REQ_LIST_BASE_H);
10159 * Make sure that UTRL and UTMRL base address registers
10160 * are updated with the latest queue addresses. Only after
10161 * updating these addresses, we can queue the new commands.
10165 /* Resuming from hibernate, assume that link was OFF */
10166 ufshcd_set_link_off(hba);
10171 EXPORT_SYMBOL_GPL(ufshcd_system_restore);
10173 int ufshcd_system_thaw(struct device *dev)
10175 return ufshcd_system_resume(dev);
10177 EXPORT_SYMBOL_GPL(ufshcd_system_thaw);
10178 #endif /* CONFIG_PM_SLEEP */
10181 * ufshcd_dealloc_host - deallocate Host Bus Adapter (HBA)
10182 * @hba: pointer to Host Bus Adapter (HBA)
10184 void ufshcd_dealloc_host(struct ufs_hba *hba)
10186 scsi_host_put(hba->host);
10188 EXPORT_SYMBOL_GPL(ufshcd_dealloc_host);
10191 * ufshcd_set_dma_mask - Set dma mask based on the controller
10192 * addressing capability
10193 * @hba: per adapter instance
10195 * Returns 0 for success, non-zero for failure
10197 static int ufshcd_set_dma_mask(struct ufs_hba *hba)
10199 if (hba->capabilities & MASK_64_ADDRESSING_SUPPORT) {
10200 if (!dma_set_mask_and_coherent(hba->dev, DMA_BIT_MASK(64)))
10203 return dma_set_mask_and_coherent(hba->dev, DMA_BIT_MASK(32));
10207 * ufshcd_alloc_host - allocate Host Bus Adapter (HBA)
10208 * @dev: pointer to device handle
10209 * @hba_handle: driver private handle
10210 * Returns 0 on success, non-zero value on failure
10212 int ufshcd_alloc_host(struct device *dev, struct ufs_hba **hba_handle)
10214 struct Scsi_Host *host;
10215 struct ufs_hba *hba;
10220 "Invalid memory reference for dev is NULL\n");
10225 host = scsi_host_alloc(&ufshcd_driver_template,
10226 sizeof(struct ufs_hba));
10228 dev_err(dev, "scsi_host_alloc failed\n");
10232 host->nr_maps = HCTX_TYPE_POLL + 1;
10233 hba = shost_priv(host);
10236 hba->dev_ref_clk_freq = REF_CLK_FREQ_INVAL;
10237 hba->nop_out_timeout = NOP_OUT_TIMEOUT;
10238 ufshcd_set_sg_entry_size(hba, sizeof(struct ufshcd_sg_entry));
10239 INIT_LIST_HEAD(&hba->clk_list_head);
10240 spin_lock_init(&hba->outstanding_lock);
10247 EXPORT_SYMBOL(ufshcd_alloc_host);
10249 /* This function exists because blk_mq_alloc_tag_set() requires this. */
10250 static blk_status_t ufshcd_queue_tmf(struct blk_mq_hw_ctx *hctx,
10251 const struct blk_mq_queue_data *qd)
10253 WARN_ON_ONCE(true);
10254 return BLK_STS_NOTSUPP;
10257 static const struct blk_mq_ops ufshcd_tmf_ops = {
10258 .queue_rq = ufshcd_queue_tmf,
10262 * ufshcd_init - Driver initialization routine
10263 * @hba: per-adapter instance
10264 * @mmio_base: base register address
10265 * @irq: Interrupt line of device
10266 * Returns 0 on success, non-zero value on failure
10268 int ufshcd_init(struct ufs_hba *hba, void __iomem *mmio_base, unsigned int irq)
10271 struct Scsi_Host *host = hba->host;
10272 struct device *dev = hba->dev;
10273 char eh_wq_name[sizeof("ufs_eh_wq_00")];
10276 * dev_set_drvdata() must be called before any callbacks are registered
10277 * that use dev_get_drvdata() (frequency scaling, clock scaling, hwmon,
10280 dev_set_drvdata(dev, hba);
10284 "Invalid memory reference for mmio_base is NULL\n");
10289 hba->mmio_base = mmio_base;
10291 hba->vps = &ufs_hba_vps;
10293 err = ufshcd_hba_init(hba);
10297 /* Read capabilities registers */
10298 err = ufshcd_hba_capabilities(hba);
10302 /* Get UFS version supported by the controller */
10303 hba->ufs_version = ufshcd_get_ufs_version(hba);
10305 /* Get Interrupt bit mask per version */
10306 hba->intr_mask = ufshcd_get_intr_mask(hba);
10308 err = ufshcd_set_dma_mask(hba);
10310 dev_err(hba->dev, "set dma mask failed\n");
10314 /* Allocate memory for host memory space */
10315 err = ufshcd_memory_alloc(hba);
10317 dev_err(hba->dev, "Memory allocation failed\n");
10321 /* Configure LRB */
10322 ufshcd_host_memory_configure(hba);
10324 host->can_queue = hba->nutrs - UFSHCD_NUM_RESERVED;
10325 host->cmd_per_lun = hba->nutrs - UFSHCD_NUM_RESERVED;
10326 host->max_id = UFSHCD_MAX_ID;
10327 host->max_lun = UFS_MAX_LUNS;
10328 host->max_channel = UFSHCD_MAX_CHANNEL;
10329 host->unique_id = host->host_no;
10330 host->max_cmd_len = UFS_CDB_SIZE;
10331 host->queuecommand_may_block = !!(hba->caps & UFSHCD_CAP_CLK_GATING);
10333 hba->max_pwr_info.is_valid = false;
10335 /* Initialize work queues */
10336 snprintf(eh_wq_name, sizeof(eh_wq_name), "ufs_eh_wq_%d",
10337 hba->host->host_no);
10338 hba->eh_wq = create_singlethread_workqueue(eh_wq_name);
10340 dev_err(hba->dev, "%s: failed to create eh workqueue\n",
10345 INIT_WORK(&hba->eh_work, ufshcd_err_handler);
10346 INIT_WORK(&hba->eeh_work, ufshcd_exception_event_handler);
10348 sema_init(&hba->host_sem, 1);
10350 /* Initialize UIC command mutex */
10351 mutex_init(&hba->uic_cmd_mutex);
10353 /* Initialize mutex for device management commands */
10354 mutex_init(&hba->dev_cmd.lock);
10356 /* Initialize mutex for exception event control */
10357 mutex_init(&hba->ee_ctrl_mutex);
10359 mutex_init(&hba->wb_mutex);
10360 init_rwsem(&hba->clk_scaling_lock);
10362 ufshcd_init_clk_gating(hba);
10364 ufshcd_init_clk_scaling(hba);
10367 * In order to avoid any spurious interrupt immediately after
10368 * registering UFS controller interrupt handler, clear any pending UFS
10369 * interrupt status and disable all the UFS interrupts.
10371 ufshcd_writel(hba, ufshcd_readl(hba, REG_INTERRUPT_STATUS),
10372 REG_INTERRUPT_STATUS);
10373 ufshcd_writel(hba, 0, REG_INTERRUPT_ENABLE);
10375 * Make sure that UFS interrupts are disabled and any pending interrupt
10376 * status is cleared before registering UFS interrupt handler.
10380 /* IRQ registration */
10381 err = devm_request_irq(dev, irq, ufshcd_intr, IRQF_SHARED, UFSHCD, hba);
10383 dev_err(hba->dev, "request irq failed\n");
10386 hba->is_irq_enabled = true;
10389 if (!is_mcq_supported(hba)) {
10390 err = scsi_add_host(host, hba->dev);
10392 dev_err(hba->dev, "scsi_add_host failed\n");
10397 hba->tmf_tag_set = (struct blk_mq_tag_set) {
10399 .queue_depth = hba->nutmrs,
10400 .ops = &ufshcd_tmf_ops,
10401 .flags = BLK_MQ_F_NO_SCHED,
10403 err = blk_mq_alloc_tag_set(&hba->tmf_tag_set);
10405 goto out_remove_scsi_host;
10406 hba->tmf_queue = blk_mq_init_queue(&hba->tmf_tag_set);
10407 if (IS_ERR(hba->tmf_queue)) {
10408 err = PTR_ERR(hba->tmf_queue);
10409 goto free_tmf_tag_set;
10411 hba->tmf_rqs = devm_kcalloc(hba->dev, hba->nutmrs,
10412 sizeof(*hba->tmf_rqs), GFP_KERNEL);
10413 if (!hba->tmf_rqs) {
10415 goto free_tmf_queue;
10418 /* Reset the attached device */
10419 ufshcd_device_reset(hba);
10421 ufshcd_init_crypto(hba);
10423 /* Host controller enable */
10424 err = ufshcd_hba_enable(hba);
10426 dev_err(hba->dev, "Host controller enable failed\n");
10427 ufshcd_print_evt_hist(hba);
10428 ufshcd_print_host_state(hba);
10429 goto free_tmf_queue;
10433 * Set the default power management level for runtime and system PM.
10434 * Default power saving mode is to keep UFS link in Hibern8 state
10435 * and UFS device in sleep state.
10437 hba->rpm_lvl = ufs_get_desired_pm_lvl_for_dev_link_state(
10438 UFS_SLEEP_PWR_MODE,
10439 UIC_LINK_HIBERN8_STATE);
10440 hba->spm_lvl = ufs_get_desired_pm_lvl_for_dev_link_state(
10441 UFS_SLEEP_PWR_MODE,
10442 UIC_LINK_HIBERN8_STATE);
10444 INIT_DELAYED_WORK(&hba->rpm_dev_flush_recheck_work,
10445 ufshcd_rpm_dev_flush_recheck_work);
10447 /* Set the default auto-hiberate idle timer value to 150 ms */
10448 if (ufshcd_is_auto_hibern8_supported(hba) && !hba->ahit) {
10449 hba->ahit = FIELD_PREP(UFSHCI_AHIBERN8_TIMER_MASK, 150) |
10450 FIELD_PREP(UFSHCI_AHIBERN8_SCALE_MASK, 3);
10453 /* Hold auto suspend until async scan completes */
10454 pm_runtime_get_sync(dev);
10455 atomic_set(&hba->scsi_block_reqs_cnt, 0);
10457 * We are assuming that device wasn't put in sleep/power-down
10458 * state exclusively during the boot stage before kernel.
10459 * This assumption helps avoid doing link startup twice during
10460 * ufshcd_probe_hba().
10462 ufshcd_set_ufs_dev_active(hba);
10464 async_schedule(ufshcd_async_scan, hba);
10465 ufs_sysfs_add_nodes(hba->dev);
10467 device_enable_async_suspend(dev);
10471 blk_mq_destroy_queue(hba->tmf_queue);
10472 blk_put_queue(hba->tmf_queue);
10474 blk_mq_free_tag_set(&hba->tmf_tag_set);
10475 out_remove_scsi_host:
10476 scsi_remove_host(hba->host);
10478 hba->is_irq_enabled = false;
10479 ufshcd_hba_exit(hba);
10483 EXPORT_SYMBOL_GPL(ufshcd_init);
10485 void ufshcd_resume_complete(struct device *dev)
10487 struct ufs_hba *hba = dev_get_drvdata(dev);
10489 if (hba->complete_put) {
10490 ufshcd_rpm_put(hba);
10491 hba->complete_put = false;
10494 EXPORT_SYMBOL_GPL(ufshcd_resume_complete);
10496 static bool ufshcd_rpm_ok_for_spm(struct ufs_hba *hba)
10498 struct device *dev = &hba->ufs_device_wlun->sdev_gendev;
10499 enum ufs_dev_pwr_mode dev_pwr_mode;
10500 enum uic_link_state link_state;
10501 unsigned long flags;
10504 spin_lock_irqsave(&dev->power.lock, flags);
10505 dev_pwr_mode = ufs_get_pm_lvl_to_dev_pwr_mode(hba->spm_lvl);
10506 link_state = ufs_get_pm_lvl_to_link_pwr_state(hba->spm_lvl);
10507 res = pm_runtime_suspended(dev) &&
10508 hba->curr_dev_pwr_mode == dev_pwr_mode &&
10509 hba->uic_link_state == link_state &&
10510 !hba->dev_info.b_rpm_dev_flush_capable;
10511 spin_unlock_irqrestore(&dev->power.lock, flags);
10516 int __ufshcd_suspend_prepare(struct device *dev, bool rpm_ok_for_spm)
10518 struct ufs_hba *hba = dev_get_drvdata(dev);
10522 * SCSI assumes that runtime-pm and system-pm for scsi drivers
10523 * are same. And it doesn't wake up the device for system-suspend
10524 * if it's runtime suspended. But ufs doesn't follow that.
10525 * Refer ufshcd_resume_complete()
10527 if (hba->ufs_device_wlun) {
10528 /* Prevent runtime suspend */
10529 ufshcd_rpm_get_noresume(hba);
10531 * Check if already runtime suspended in same state as system
10532 * suspend would be.
10534 if (!rpm_ok_for_spm || !ufshcd_rpm_ok_for_spm(hba)) {
10535 /* RPM state is not ok for SPM, so runtime resume */
10536 ret = ufshcd_rpm_resume(hba);
10537 if (ret < 0 && ret != -EACCES) {
10538 ufshcd_rpm_put(hba);
10542 hba->complete_put = true;
10546 EXPORT_SYMBOL_GPL(__ufshcd_suspend_prepare);
10548 int ufshcd_suspend_prepare(struct device *dev)
10550 return __ufshcd_suspend_prepare(dev, true);
10552 EXPORT_SYMBOL_GPL(ufshcd_suspend_prepare);
10554 #ifdef CONFIG_PM_SLEEP
10555 static int ufshcd_wl_poweroff(struct device *dev)
10557 struct scsi_device *sdev = to_scsi_device(dev);
10558 struct ufs_hba *hba = shost_priv(sdev->host);
10560 __ufshcd_wl_suspend(hba, UFS_SHUTDOWN_PM);
10565 static int ufshcd_wl_probe(struct device *dev)
10567 struct scsi_device *sdev = to_scsi_device(dev);
10569 if (!is_device_wlun(sdev))
10572 blk_pm_runtime_init(sdev->request_queue, dev);
10573 pm_runtime_set_autosuspend_delay(dev, 0);
10574 pm_runtime_allow(dev);
10579 static int ufshcd_wl_remove(struct device *dev)
10581 pm_runtime_forbid(dev);
10585 static const struct dev_pm_ops ufshcd_wl_pm_ops = {
10586 #ifdef CONFIG_PM_SLEEP
10587 .suspend = ufshcd_wl_suspend,
10588 .resume = ufshcd_wl_resume,
10589 .freeze = ufshcd_wl_suspend,
10590 .thaw = ufshcd_wl_resume,
10591 .poweroff = ufshcd_wl_poweroff,
10592 .restore = ufshcd_wl_resume,
10594 SET_RUNTIME_PM_OPS(ufshcd_wl_runtime_suspend, ufshcd_wl_runtime_resume, NULL)
10598 * ufs_dev_wlun_template - describes ufs device wlun
10599 * ufs-device wlun - used to send pm commands
10600 * All luns are consumers of ufs-device wlun.
10602 * Currently, no sd driver is present for wluns.
10603 * Hence the no specific pm operations are performed.
10604 * With ufs design, SSU should be sent to ufs-device wlun.
10605 * Hence register a scsi driver for ufs wluns only.
10607 static struct scsi_driver ufs_dev_wlun_template = {
10609 .name = "ufs_device_wlun",
10610 .owner = THIS_MODULE,
10611 .probe = ufshcd_wl_probe,
10612 .remove = ufshcd_wl_remove,
10613 .pm = &ufshcd_wl_pm_ops,
10614 .shutdown = ufshcd_wl_shutdown,
10618 static int __init ufshcd_core_init(void)
10622 ufs_debugfs_init();
10624 ret = scsi_register_driver(&ufs_dev_wlun_template.gendrv);
10626 ufs_debugfs_exit();
10630 static void __exit ufshcd_core_exit(void)
10632 ufs_debugfs_exit();
10633 scsi_unregister_driver(&ufs_dev_wlun_template.gendrv);
10636 module_init(ufshcd_core_init);
10637 module_exit(ufshcd_core_exit);
10639 MODULE_AUTHOR("Santosh Yaragnavi <santosh.sy@samsung.com>");
10640 MODULE_AUTHOR("Vinayak Holikatti <h.vinayak@samsung.com>");
10641 MODULE_DESCRIPTION("Generic UFS host controller driver Core");
10642 MODULE_SOFTDEP("pre: governor_simpleondemand");
10643 MODULE_LICENSE("GPL");