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>
20 #include "ufs_quirks.h"
22 #include "ufs-sysfs.h"
24 #include "ufshcd-crypto.h"
25 #include <asm/unaligned.h>
26 #include <linux/blkdev.h>
28 #define CREATE_TRACE_POINTS
29 #include <trace/events/ufs.h>
31 #define UFSHCD_ENABLE_INTRS (UTP_TRANSFER_REQ_COMPL |\
34 /* UIC command timeout, unit: ms */
35 #define UIC_CMD_TIMEOUT 500
37 /* NOP OUT retries waiting for NOP IN response */
38 #define NOP_OUT_RETRIES 10
39 /* Timeout after 50 msecs if NOP OUT hangs without response */
40 #define NOP_OUT_TIMEOUT 50 /* msecs */
42 /* Query request retries */
43 #define QUERY_REQ_RETRIES 3
44 /* Query request timeout */
45 #define QUERY_REQ_TIMEOUT 1500 /* 1.5 seconds */
47 /* Task management command timeout */
48 #define TM_CMD_TIMEOUT 100 /* msecs */
50 /* maximum number of retries for a general UIC command */
51 #define UFS_UIC_COMMAND_RETRIES 3
53 /* maximum number of link-startup retries */
54 #define DME_LINKSTARTUP_RETRIES 3
56 /* Maximum retries for Hibern8 enter */
57 #define UIC_HIBERN8_ENTER_RETRIES 3
59 /* maximum number of reset retries before giving up */
60 #define MAX_HOST_RESET_RETRIES 5
62 /* Expose the flag value from utp_upiu_query.value */
63 #define MASK_QUERY_UPIU_FLAG_LOC 0xFF
65 /* Interrupt aggregation default timeout, unit: 40us */
66 #define INT_AGGR_DEF_TO 0x02
68 /* default delay of autosuspend: 2000 ms */
69 #define RPM_AUTOSUSPEND_DELAY_MS 2000
71 /* Default delay of RPM device flush delayed work */
72 #define RPM_DEV_FLUSH_RECHECK_WORK_DELAY_MS 5000
74 /* Default value of wait time before gating device ref clock */
75 #define UFSHCD_REF_CLK_GATING_WAIT_US 0xFF /* microsecs */
77 /* Polling time to wait for fDeviceInit */
78 #define FDEVICEINIT_COMPL_TIMEOUT 1500 /* millisecs */
80 #define ufshcd_toggle_vreg(_dev, _vreg, _on) \
84 _ret = ufshcd_enable_vreg(_dev, _vreg); \
86 _ret = ufshcd_disable_vreg(_dev, _vreg); \
90 #define ufshcd_hex_dump(prefix_str, buf, len) do { \
91 size_t __len = (len); \
92 print_hex_dump(KERN_ERR, prefix_str, \
93 __len > 4 ? DUMP_PREFIX_OFFSET : DUMP_PREFIX_NONE,\
94 16, 4, buf, __len, false); \
97 int ufshcd_dump_regs(struct ufs_hba *hba, size_t offset, size_t len,
103 if (offset % 4 != 0 || len % 4 != 0) /* keep readl happy */
106 regs = kzalloc(len, GFP_ATOMIC);
110 for (pos = 0; pos < len; pos += 4)
111 regs[pos / 4] = ufshcd_readl(hba, offset + pos);
113 ufshcd_hex_dump(prefix, regs, len);
118 EXPORT_SYMBOL_GPL(ufshcd_dump_regs);
121 UFSHCD_MAX_CHANNEL = 0,
123 UFSHCD_CMD_PER_LUN = 32,
124 UFSHCD_CAN_QUEUE = 32,
131 UFSHCD_STATE_OPERATIONAL,
132 UFSHCD_STATE_EH_SCHEDULED_FATAL,
133 UFSHCD_STATE_EH_SCHEDULED_NON_FATAL,
136 /* UFSHCD error handling flags */
138 UFSHCD_EH_IN_PROGRESS = (1 << 0),
141 /* UFSHCD UIC layer error flags */
143 UFSHCD_UIC_DL_PA_INIT_ERROR = (1 << 0), /* Data link layer error */
144 UFSHCD_UIC_DL_NAC_RECEIVED_ERROR = (1 << 1), /* Data link layer error */
145 UFSHCD_UIC_DL_TCx_REPLAY_ERROR = (1 << 2), /* Data link layer error */
146 UFSHCD_UIC_NL_ERROR = (1 << 3), /* Network layer error */
147 UFSHCD_UIC_TL_ERROR = (1 << 4), /* Transport Layer error */
148 UFSHCD_UIC_DME_ERROR = (1 << 5), /* DME error */
149 UFSHCD_UIC_PA_GENERIC_ERROR = (1 << 6), /* Generic PA error */
152 #define ufshcd_set_eh_in_progress(h) \
153 ((h)->eh_flags |= UFSHCD_EH_IN_PROGRESS)
154 #define ufshcd_eh_in_progress(h) \
155 ((h)->eh_flags & UFSHCD_EH_IN_PROGRESS)
156 #define ufshcd_clear_eh_in_progress(h) \
157 ((h)->eh_flags &= ~UFSHCD_EH_IN_PROGRESS)
159 struct ufs_pm_lvl_states ufs_pm_lvl_states[] = {
160 {UFS_ACTIVE_PWR_MODE, UIC_LINK_ACTIVE_STATE},
161 {UFS_ACTIVE_PWR_MODE, UIC_LINK_HIBERN8_STATE},
162 {UFS_SLEEP_PWR_MODE, UIC_LINK_ACTIVE_STATE},
163 {UFS_SLEEP_PWR_MODE, UIC_LINK_HIBERN8_STATE},
164 {UFS_POWERDOWN_PWR_MODE, UIC_LINK_HIBERN8_STATE},
165 {UFS_POWERDOWN_PWR_MODE, UIC_LINK_OFF_STATE},
167 * For DeepSleep, the link is first put in hibern8 and then off.
168 * Leaving the link in hibern8 is not supported.
170 {UFS_DEEPSLEEP_PWR_MODE, UIC_LINK_OFF_STATE},
173 static inline enum ufs_dev_pwr_mode
174 ufs_get_pm_lvl_to_dev_pwr_mode(enum ufs_pm_level lvl)
176 return ufs_pm_lvl_states[lvl].dev_state;
179 static inline enum uic_link_state
180 ufs_get_pm_lvl_to_link_pwr_state(enum ufs_pm_level lvl)
182 return ufs_pm_lvl_states[lvl].link_state;
185 static inline enum ufs_pm_level
186 ufs_get_desired_pm_lvl_for_dev_link_state(enum ufs_dev_pwr_mode dev_state,
187 enum uic_link_state link_state)
189 enum ufs_pm_level lvl;
191 for (lvl = UFS_PM_LVL_0; lvl < UFS_PM_LVL_MAX; lvl++) {
192 if ((ufs_pm_lvl_states[lvl].dev_state == dev_state) &&
193 (ufs_pm_lvl_states[lvl].link_state == link_state))
197 /* if no match found, return the level 0 */
201 static struct ufs_dev_fix ufs_fixups[] = {
202 /* UFS cards deviations table */
203 UFS_FIX(UFS_VENDOR_MICRON, UFS_ANY_MODEL,
204 UFS_DEVICE_QUIRK_DELAY_BEFORE_LPM),
205 UFS_FIX(UFS_VENDOR_SAMSUNG, UFS_ANY_MODEL,
206 UFS_DEVICE_QUIRK_DELAY_BEFORE_LPM |
207 UFS_DEVICE_QUIRK_HOST_PA_TACTIVATE |
208 UFS_DEVICE_QUIRK_RECOVERY_FROM_DL_NAC_ERRORS),
209 UFS_FIX(UFS_VENDOR_SKHYNIX, UFS_ANY_MODEL,
210 UFS_DEVICE_QUIRK_HOST_PA_SAVECONFIGTIME),
211 UFS_FIX(UFS_VENDOR_SKHYNIX, "hB8aL1" /*H28U62301AMR*/,
212 UFS_DEVICE_QUIRK_HOST_VS_DEBUGSAVECONFIGTIME),
213 UFS_FIX(UFS_VENDOR_TOSHIBA, UFS_ANY_MODEL,
214 UFS_DEVICE_QUIRK_DELAY_BEFORE_LPM),
215 UFS_FIX(UFS_VENDOR_TOSHIBA, "THGLF2G9C8KBADG",
216 UFS_DEVICE_QUIRK_PA_TACTIVATE),
217 UFS_FIX(UFS_VENDOR_TOSHIBA, "THGLF2G9D8KBADG",
218 UFS_DEVICE_QUIRK_PA_TACTIVATE),
222 static irqreturn_t ufshcd_tmc_handler(struct ufs_hba *hba);
223 static void ufshcd_async_scan(void *data, async_cookie_t cookie);
224 static int ufshcd_reset_and_restore(struct ufs_hba *hba);
225 static int ufshcd_eh_host_reset_handler(struct scsi_cmnd *cmd);
226 static int ufshcd_clear_tm_cmd(struct ufs_hba *hba, int tag);
227 static void ufshcd_hba_exit(struct ufs_hba *hba);
228 static int ufshcd_probe_hba(struct ufs_hba *hba, bool async);
229 static int ufshcd_setup_clocks(struct ufs_hba *hba, bool on);
230 static int ufshcd_uic_hibern8_enter(struct ufs_hba *hba);
231 static inline void ufshcd_add_delay_before_dme_cmd(struct ufs_hba *hba);
232 static int ufshcd_host_reset_and_restore(struct ufs_hba *hba);
233 static void ufshcd_resume_clkscaling(struct ufs_hba *hba);
234 static void ufshcd_suspend_clkscaling(struct ufs_hba *hba);
235 static void __ufshcd_suspend_clkscaling(struct ufs_hba *hba);
236 static int ufshcd_scale_clks(struct ufs_hba *hba, bool scale_up);
237 static irqreturn_t ufshcd_intr(int irq, void *__hba);
238 static int ufshcd_change_power_mode(struct ufs_hba *hba,
239 struct ufs_pa_layer_attr *pwr_mode);
240 static void ufshcd_schedule_eh_work(struct ufs_hba *hba);
241 static int ufshcd_setup_hba_vreg(struct ufs_hba *hba, bool on);
242 static int ufshcd_setup_vreg(struct ufs_hba *hba, bool on);
243 static inline int ufshcd_config_vreg_hpm(struct ufs_hba *hba,
244 struct ufs_vreg *vreg);
245 static int ufshcd_try_to_abort_task(struct ufs_hba *hba, int tag);
246 static int ufshcd_wb_buf_flush_enable(struct ufs_hba *hba);
247 static int ufshcd_wb_buf_flush_disable(struct ufs_hba *hba);
248 static int ufshcd_wb_ctrl(struct ufs_hba *hba, bool enable);
249 static int ufshcd_wb_toggle_flush_during_h8(struct ufs_hba *hba, bool set);
250 static inline void ufshcd_wb_toggle_flush(struct ufs_hba *hba, bool enable);
251 static void ufshcd_hba_vreg_set_lpm(struct ufs_hba *hba);
252 static void ufshcd_hba_vreg_set_hpm(struct ufs_hba *hba);
254 static inline bool ufshcd_valid_tag(struct ufs_hba *hba, int tag)
256 return tag >= 0 && tag < hba->nutrs;
259 static inline void ufshcd_enable_irq(struct ufs_hba *hba)
261 if (!hba->is_irq_enabled) {
262 enable_irq(hba->irq);
263 hba->is_irq_enabled = true;
267 static inline void ufshcd_disable_irq(struct ufs_hba *hba)
269 if (hba->is_irq_enabled) {
270 disable_irq(hba->irq);
271 hba->is_irq_enabled = false;
275 static inline void ufshcd_wb_config(struct ufs_hba *hba)
279 if (!ufshcd_is_wb_allowed(hba))
282 ret = ufshcd_wb_ctrl(hba, true);
284 dev_err(hba->dev, "%s: Enable WB failed: %d\n", __func__, ret);
286 dev_info(hba->dev, "%s: Write Booster Configured\n", __func__);
287 ret = ufshcd_wb_toggle_flush_during_h8(hba, true);
289 dev_err(hba->dev, "%s: En WB flush during H8: failed: %d\n",
291 ufshcd_wb_toggle_flush(hba, true);
294 static void ufshcd_scsi_unblock_requests(struct ufs_hba *hba)
296 if (atomic_dec_and_test(&hba->scsi_block_reqs_cnt))
297 scsi_unblock_requests(hba->host);
300 static void ufshcd_scsi_block_requests(struct ufs_hba *hba)
302 if (atomic_inc_return(&hba->scsi_block_reqs_cnt) == 1)
303 scsi_block_requests(hba->host);
306 static void ufshcd_add_cmd_upiu_trace(struct ufs_hba *hba, unsigned int tag,
309 struct utp_upiu_req *rq = hba->lrb[tag].ucd_req_ptr;
311 trace_ufshcd_upiu(dev_name(hba->dev), str, &rq->header, &rq->sc.cdb);
314 static void ufshcd_add_query_upiu_trace(struct ufs_hba *hba, unsigned int tag,
317 struct utp_upiu_req *rq = hba->lrb[tag].ucd_req_ptr;
319 trace_ufshcd_upiu(dev_name(hba->dev), str, &rq->header, &rq->qr);
322 static void ufshcd_add_tm_upiu_trace(struct ufs_hba *hba, unsigned int tag,
325 int off = (int)tag - hba->nutrs;
326 struct utp_task_req_desc *descp = &hba->utmrdl_base_addr[off];
328 trace_ufshcd_upiu(dev_name(hba->dev), str, &descp->req_header,
329 &descp->input_param1);
332 static void ufshcd_add_uic_command_trace(struct ufs_hba *hba,
333 struct uic_command *ucmd,
338 if (!trace_ufshcd_uic_command_enabled())
341 if (!strcmp(str, "send"))
344 cmd = ufshcd_readl(hba, REG_UIC_COMMAND);
346 trace_ufshcd_uic_command(dev_name(hba->dev), str, cmd,
347 ufshcd_readl(hba, REG_UIC_COMMAND_ARG_1),
348 ufshcd_readl(hba, REG_UIC_COMMAND_ARG_2),
349 ufshcd_readl(hba, REG_UIC_COMMAND_ARG_3));
352 static void ufshcd_add_command_trace(struct ufs_hba *hba,
353 unsigned int tag, const char *str)
356 u8 opcode = 0, group_id = 0;
358 struct ufshcd_lrb *lrbp = &hba->lrb[tag];
359 struct scsi_cmnd *cmd = lrbp->cmd;
360 int transfer_len = -1;
362 if (!trace_ufshcd_command_enabled()) {
363 /* trace UPIU W/O tracing command */
365 ufshcd_add_cmd_upiu_trace(hba, tag, str);
369 if (cmd) { /* data phase exists */
370 /* trace UPIU also */
371 ufshcd_add_cmd_upiu_trace(hba, tag, str);
372 opcode = cmd->cmnd[0];
373 if ((opcode == READ_10) || (opcode == WRITE_10)) {
375 * Currently we only fully trace read(10) and write(10)
378 if (cmd->request && cmd->request->bio)
379 lba = cmd->request->bio->bi_iter.bi_sector;
380 transfer_len = be32_to_cpu(
381 lrbp->ucd_req_ptr->sc.exp_data_transfer_len);
382 if (opcode == WRITE_10)
383 group_id = lrbp->cmd->cmnd[6];
384 } else if (opcode == UNMAP) {
386 lba = scsi_get_lba(cmd);
387 transfer_len = blk_rq_bytes(cmd->request);
392 intr = ufshcd_readl(hba, REG_INTERRUPT_STATUS);
393 doorbell = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
394 trace_ufshcd_command(dev_name(hba->dev), str, tag,
395 doorbell, transfer_len, intr, lba, opcode, group_id);
398 static void ufshcd_print_clk_freqs(struct ufs_hba *hba)
400 struct ufs_clk_info *clki;
401 struct list_head *head = &hba->clk_list_head;
403 if (list_empty(head))
406 list_for_each_entry(clki, head, list) {
407 if (!IS_ERR_OR_NULL(clki->clk) && clki->min_freq &&
409 dev_err(hba->dev, "clk: %s, rate: %u\n",
410 clki->name, clki->curr_freq);
414 static void ufshcd_print_evt(struct ufs_hba *hba, u32 id,
419 struct ufs_event_hist *e;
421 if (id >= UFS_EVT_CNT)
424 e = &hba->ufs_stats.event[id];
426 for (i = 0; i < UFS_EVENT_HIST_LENGTH; i++) {
427 int p = (i + e->pos) % UFS_EVENT_HIST_LENGTH;
429 if (e->tstamp[p] == 0)
431 dev_err(hba->dev, "%s[%d] = 0x%x at %lld us\n", err_name, p,
432 e->val[p], ktime_to_us(e->tstamp[p]));
437 dev_err(hba->dev, "No record of %s\n", err_name);
440 static void ufshcd_print_evt_hist(struct ufs_hba *hba)
442 ufshcd_dump_regs(hba, 0, UFSHCI_REG_SPACE_SIZE, "host_regs: ");
444 ufshcd_print_evt(hba, UFS_EVT_PA_ERR, "pa_err");
445 ufshcd_print_evt(hba, UFS_EVT_DL_ERR, "dl_err");
446 ufshcd_print_evt(hba, UFS_EVT_NL_ERR, "nl_err");
447 ufshcd_print_evt(hba, UFS_EVT_TL_ERR, "tl_err");
448 ufshcd_print_evt(hba, UFS_EVT_DME_ERR, "dme_err");
449 ufshcd_print_evt(hba, UFS_EVT_AUTO_HIBERN8_ERR,
451 ufshcd_print_evt(hba, UFS_EVT_FATAL_ERR, "fatal_err");
452 ufshcd_print_evt(hba, UFS_EVT_LINK_STARTUP_FAIL,
453 "link_startup_fail");
454 ufshcd_print_evt(hba, UFS_EVT_RESUME_ERR, "resume_fail");
455 ufshcd_print_evt(hba, UFS_EVT_SUSPEND_ERR,
457 ufshcd_print_evt(hba, UFS_EVT_DEV_RESET, "dev_reset");
458 ufshcd_print_evt(hba, UFS_EVT_HOST_RESET, "host_reset");
459 ufshcd_print_evt(hba, UFS_EVT_ABORT, "task_abort");
461 ufshcd_vops_dbg_register_dump(hba);
465 void ufshcd_print_trs(struct ufs_hba *hba, unsigned long bitmap, bool pr_prdt)
467 struct ufshcd_lrb *lrbp;
471 for_each_set_bit(tag, &bitmap, hba->nutrs) {
472 lrbp = &hba->lrb[tag];
474 dev_err(hba->dev, "UPIU[%d] - issue time %lld us\n",
475 tag, ktime_to_us(lrbp->issue_time_stamp));
476 dev_err(hba->dev, "UPIU[%d] - complete time %lld us\n",
477 tag, ktime_to_us(lrbp->compl_time_stamp));
479 "UPIU[%d] - Transfer Request Descriptor phys@0x%llx\n",
480 tag, (u64)lrbp->utrd_dma_addr);
482 ufshcd_hex_dump("UPIU TRD: ", lrbp->utr_descriptor_ptr,
483 sizeof(struct utp_transfer_req_desc));
484 dev_err(hba->dev, "UPIU[%d] - Request UPIU phys@0x%llx\n", tag,
485 (u64)lrbp->ucd_req_dma_addr);
486 ufshcd_hex_dump("UPIU REQ: ", lrbp->ucd_req_ptr,
487 sizeof(struct utp_upiu_req));
488 dev_err(hba->dev, "UPIU[%d] - Response UPIU phys@0x%llx\n", tag,
489 (u64)lrbp->ucd_rsp_dma_addr);
490 ufshcd_hex_dump("UPIU RSP: ", lrbp->ucd_rsp_ptr,
491 sizeof(struct utp_upiu_rsp));
493 prdt_length = le16_to_cpu(
494 lrbp->utr_descriptor_ptr->prd_table_length);
495 if (hba->quirks & UFSHCD_QUIRK_PRDT_BYTE_GRAN)
496 prdt_length /= sizeof(struct ufshcd_sg_entry);
499 "UPIU[%d] - PRDT - %d entries phys@0x%llx\n",
501 (u64)lrbp->ucd_prdt_dma_addr);
504 ufshcd_hex_dump("UPIU PRDT: ", lrbp->ucd_prdt_ptr,
505 sizeof(struct ufshcd_sg_entry) * prdt_length);
509 static void ufshcd_print_tmrs(struct ufs_hba *hba, unsigned long bitmap)
513 for_each_set_bit(tag, &bitmap, hba->nutmrs) {
514 struct utp_task_req_desc *tmrdp = &hba->utmrdl_base_addr[tag];
516 dev_err(hba->dev, "TM[%d] - Task Management Header\n", tag);
517 ufshcd_hex_dump("", tmrdp, sizeof(*tmrdp));
521 static void ufshcd_print_host_state(struct ufs_hba *hba)
523 struct scsi_device *sdev_ufs = hba->sdev_ufs_device;
525 dev_err(hba->dev, "UFS Host state=%d\n", hba->ufshcd_state);
526 dev_err(hba->dev, "outstanding reqs=0x%lx tasks=0x%lx\n",
527 hba->outstanding_reqs, hba->outstanding_tasks);
528 dev_err(hba->dev, "saved_err=0x%x, saved_uic_err=0x%x\n",
529 hba->saved_err, hba->saved_uic_err);
530 dev_err(hba->dev, "Device power mode=%d, UIC link state=%d\n",
531 hba->curr_dev_pwr_mode, hba->uic_link_state);
532 dev_err(hba->dev, "PM in progress=%d, sys. suspended=%d\n",
533 hba->pm_op_in_progress, hba->is_sys_suspended);
534 dev_err(hba->dev, "Auto BKOPS=%d, Host self-block=%d\n",
535 hba->auto_bkops_enabled, hba->host->host_self_blocked);
536 dev_err(hba->dev, "Clk gate=%d\n", hba->clk_gating.state);
538 "last_hibern8_exit_tstamp at %lld us, hibern8_exit_cnt=%d\n",
539 ktime_to_us(hba->ufs_stats.last_hibern8_exit_tstamp),
540 hba->ufs_stats.hibern8_exit_cnt);
541 dev_err(hba->dev, "last intr at %lld us, last intr status=0x%x\n",
542 ktime_to_us(hba->ufs_stats.last_intr_ts),
543 hba->ufs_stats.last_intr_status);
544 dev_err(hba->dev, "error handling flags=0x%x, req. abort count=%d\n",
545 hba->eh_flags, hba->req_abort_count);
546 dev_err(hba->dev, "hba->ufs_version=0x%x, Host capabilities=0x%x, caps=0x%x\n",
547 hba->ufs_version, hba->capabilities, hba->caps);
548 dev_err(hba->dev, "quirks=0x%x, dev. quirks=0x%x\n", hba->quirks,
551 dev_err(hba->dev, "UFS dev info: %.8s %.16s rev %.4s\n",
552 sdev_ufs->vendor, sdev_ufs->model, sdev_ufs->rev);
554 ufshcd_print_clk_freqs(hba);
558 * ufshcd_print_pwr_info - print power params as saved in hba
560 * @hba: per-adapter instance
562 static void ufshcd_print_pwr_info(struct ufs_hba *hba)
564 static const char * const names[] = {
574 dev_err(hba->dev, "%s:[RX, TX]: gear=[%d, %d], lane[%d, %d], pwr[%s, %s], rate = %d\n",
576 hba->pwr_info.gear_rx, hba->pwr_info.gear_tx,
577 hba->pwr_info.lane_rx, hba->pwr_info.lane_tx,
578 names[hba->pwr_info.pwr_rx],
579 names[hba->pwr_info.pwr_tx],
580 hba->pwr_info.hs_rate);
583 void ufshcd_delay_us(unsigned long us, unsigned long tolerance)
591 usleep_range(us, us + tolerance);
593 EXPORT_SYMBOL_GPL(ufshcd_delay_us);
596 * ufshcd_wait_for_register - wait for register value to change
597 * @hba: per-adapter interface
598 * @reg: mmio register offset
599 * @mask: mask to apply to the read register value
600 * @val: value to wait for
601 * @interval_us: polling interval in microseconds
602 * @timeout_ms: timeout in milliseconds
605 * -ETIMEDOUT on error, zero on success.
607 int ufshcd_wait_for_register(struct ufs_hba *hba, u32 reg, u32 mask,
608 u32 val, unsigned long interval_us,
609 unsigned long timeout_ms)
612 unsigned long timeout = jiffies + msecs_to_jiffies(timeout_ms);
614 /* ignore bits that we don't intend to wait on */
617 while ((ufshcd_readl(hba, reg) & mask) != val) {
618 usleep_range(interval_us, interval_us + 50);
619 if (time_after(jiffies, timeout)) {
620 if ((ufshcd_readl(hba, reg) & mask) != val)
630 * ufshcd_get_intr_mask - Get the interrupt bit mask
631 * @hba: Pointer to adapter instance
633 * Returns interrupt bit mask per version
635 static inline u32 ufshcd_get_intr_mask(struct ufs_hba *hba)
639 switch (hba->ufs_version) {
640 case UFSHCI_VERSION_10:
641 intr_mask = INTERRUPT_MASK_ALL_VER_10;
643 case UFSHCI_VERSION_11:
644 case UFSHCI_VERSION_20:
645 intr_mask = INTERRUPT_MASK_ALL_VER_11;
647 case UFSHCI_VERSION_21:
649 intr_mask = INTERRUPT_MASK_ALL_VER_21;
657 * ufshcd_get_ufs_version - Get the UFS version supported by the HBA
658 * @hba: Pointer to adapter instance
660 * Returns UFSHCI version supported by the controller
662 static inline u32 ufshcd_get_ufs_version(struct ufs_hba *hba)
664 if (hba->quirks & UFSHCD_QUIRK_BROKEN_UFS_HCI_VERSION)
665 return ufshcd_vops_get_ufs_hci_version(hba);
667 return ufshcd_readl(hba, REG_UFS_VERSION);
671 * ufshcd_is_device_present - Check if any device connected to
672 * the host controller
673 * @hba: pointer to adapter instance
675 * Returns true if device present, false if no device detected
677 static inline bool ufshcd_is_device_present(struct ufs_hba *hba)
679 return (ufshcd_readl(hba, REG_CONTROLLER_STATUS) &
680 DEVICE_PRESENT) ? true : false;
684 * ufshcd_get_tr_ocs - Get the UTRD Overall Command Status
685 * @lrbp: pointer to local command reference block
687 * This function is used to get the OCS field from UTRD
688 * Returns the OCS field in the UTRD
690 static inline int ufshcd_get_tr_ocs(struct ufshcd_lrb *lrbp)
692 return le32_to_cpu(lrbp->utr_descriptor_ptr->header.dword_2) & MASK_OCS;
696 * ufshcd_utrl_clear - Clear a bit in UTRLCLR register
697 * @hba: per adapter instance
698 * @pos: position of the bit to be cleared
700 static inline void ufshcd_utrl_clear(struct ufs_hba *hba, u32 pos)
702 if (hba->quirks & UFSHCI_QUIRK_BROKEN_REQ_LIST_CLR)
703 ufshcd_writel(hba, (1 << pos), REG_UTP_TRANSFER_REQ_LIST_CLEAR);
705 ufshcd_writel(hba, ~(1 << pos),
706 REG_UTP_TRANSFER_REQ_LIST_CLEAR);
710 * ufshcd_utmrl_clear - Clear a bit in UTRMLCLR register
711 * @hba: per adapter instance
712 * @pos: position of the bit to be cleared
714 static inline void ufshcd_utmrl_clear(struct ufs_hba *hba, u32 pos)
716 if (hba->quirks & UFSHCI_QUIRK_BROKEN_REQ_LIST_CLR)
717 ufshcd_writel(hba, (1 << pos), REG_UTP_TASK_REQ_LIST_CLEAR);
719 ufshcd_writel(hba, ~(1 << pos), REG_UTP_TASK_REQ_LIST_CLEAR);
723 * ufshcd_outstanding_req_clear - Clear a bit in outstanding request field
724 * @hba: per adapter instance
725 * @tag: position of the bit to be cleared
727 static inline void ufshcd_outstanding_req_clear(struct ufs_hba *hba, int tag)
729 __clear_bit(tag, &hba->outstanding_reqs);
733 * ufshcd_get_lists_status - Check UCRDY, UTRLRDY and UTMRLRDY
734 * @reg: Register value of host controller status
736 * Returns integer, 0 on Success and positive value if failed
738 static inline int ufshcd_get_lists_status(u32 reg)
740 return !((reg & UFSHCD_STATUS_READY) == UFSHCD_STATUS_READY);
744 * ufshcd_get_uic_cmd_result - Get the UIC command result
745 * @hba: Pointer to adapter instance
747 * This function gets the result of UIC command completion
748 * Returns 0 on success, non zero value on error
750 static inline int ufshcd_get_uic_cmd_result(struct ufs_hba *hba)
752 return ufshcd_readl(hba, REG_UIC_COMMAND_ARG_2) &
753 MASK_UIC_COMMAND_RESULT;
757 * ufshcd_get_dme_attr_val - Get the value of attribute returned by UIC command
758 * @hba: Pointer to adapter instance
760 * This function gets UIC command argument3
761 * Returns 0 on success, non zero value on error
763 static inline u32 ufshcd_get_dme_attr_val(struct ufs_hba *hba)
765 return ufshcd_readl(hba, REG_UIC_COMMAND_ARG_3);
769 * ufshcd_get_req_rsp - returns the TR response transaction type
770 * @ucd_rsp_ptr: pointer to response UPIU
773 ufshcd_get_req_rsp(struct utp_upiu_rsp *ucd_rsp_ptr)
775 return be32_to_cpu(ucd_rsp_ptr->header.dword_0) >> 24;
779 * ufshcd_get_rsp_upiu_result - Get the result from response UPIU
780 * @ucd_rsp_ptr: pointer to response UPIU
782 * This function gets the response status and scsi_status from response UPIU
783 * Returns the response result code.
786 ufshcd_get_rsp_upiu_result(struct utp_upiu_rsp *ucd_rsp_ptr)
788 return be32_to_cpu(ucd_rsp_ptr->header.dword_1) & MASK_RSP_UPIU_RESULT;
792 * ufshcd_get_rsp_upiu_data_seg_len - Get the data segment length
794 * @ucd_rsp_ptr: pointer to response UPIU
796 * Return the data segment length.
798 static inline unsigned int
799 ufshcd_get_rsp_upiu_data_seg_len(struct utp_upiu_rsp *ucd_rsp_ptr)
801 return be32_to_cpu(ucd_rsp_ptr->header.dword_2) &
802 MASK_RSP_UPIU_DATA_SEG_LEN;
806 * ufshcd_is_exception_event - Check if the device raised an exception event
807 * @ucd_rsp_ptr: pointer to response UPIU
809 * The function checks if the device raised an exception event indicated in
810 * the Device Information field of response UPIU.
812 * Returns true if exception is raised, false otherwise.
814 static inline bool ufshcd_is_exception_event(struct utp_upiu_rsp *ucd_rsp_ptr)
816 return be32_to_cpu(ucd_rsp_ptr->header.dword_2) &
817 MASK_RSP_EXCEPTION_EVENT ? true : false;
821 * ufshcd_reset_intr_aggr - Reset interrupt aggregation values.
822 * @hba: per adapter instance
825 ufshcd_reset_intr_aggr(struct ufs_hba *hba)
827 ufshcd_writel(hba, INT_AGGR_ENABLE |
828 INT_AGGR_COUNTER_AND_TIMER_RESET,
829 REG_UTP_TRANSFER_REQ_INT_AGG_CONTROL);
833 * ufshcd_config_intr_aggr - Configure interrupt aggregation values.
834 * @hba: per adapter instance
835 * @cnt: Interrupt aggregation counter threshold
836 * @tmout: Interrupt aggregation timeout value
839 ufshcd_config_intr_aggr(struct ufs_hba *hba, u8 cnt, u8 tmout)
841 ufshcd_writel(hba, INT_AGGR_ENABLE | INT_AGGR_PARAM_WRITE |
842 INT_AGGR_COUNTER_THLD_VAL(cnt) |
843 INT_AGGR_TIMEOUT_VAL(tmout),
844 REG_UTP_TRANSFER_REQ_INT_AGG_CONTROL);
848 * ufshcd_disable_intr_aggr - Disables interrupt aggregation.
849 * @hba: per adapter instance
851 static inline void ufshcd_disable_intr_aggr(struct ufs_hba *hba)
853 ufshcd_writel(hba, 0, REG_UTP_TRANSFER_REQ_INT_AGG_CONTROL);
857 * ufshcd_enable_run_stop_reg - Enable run-stop registers,
858 * When run-stop registers are set to 1, it indicates the
859 * host controller that it can process the requests
860 * @hba: per adapter instance
862 static void ufshcd_enable_run_stop_reg(struct ufs_hba *hba)
864 ufshcd_writel(hba, UTP_TASK_REQ_LIST_RUN_STOP_BIT,
865 REG_UTP_TASK_REQ_LIST_RUN_STOP);
866 ufshcd_writel(hba, UTP_TRANSFER_REQ_LIST_RUN_STOP_BIT,
867 REG_UTP_TRANSFER_REQ_LIST_RUN_STOP);
871 * ufshcd_hba_start - Start controller initialization sequence
872 * @hba: per adapter instance
874 static inline void ufshcd_hba_start(struct ufs_hba *hba)
876 u32 val = CONTROLLER_ENABLE;
878 if (ufshcd_crypto_enable(hba))
879 val |= CRYPTO_GENERAL_ENABLE;
881 ufshcd_writel(hba, val, REG_CONTROLLER_ENABLE);
885 * ufshcd_is_hba_active - Get controller state
886 * @hba: per adapter instance
888 * Returns false if controller is active, true otherwise
890 static inline bool ufshcd_is_hba_active(struct ufs_hba *hba)
892 return (ufshcd_readl(hba, REG_CONTROLLER_ENABLE) & CONTROLLER_ENABLE)
896 u32 ufshcd_get_local_unipro_ver(struct ufs_hba *hba)
898 /* HCI version 1.0 and 1.1 supports UniPro 1.41 */
899 if ((hba->ufs_version == UFSHCI_VERSION_10) ||
900 (hba->ufs_version == UFSHCI_VERSION_11))
901 return UFS_UNIPRO_VER_1_41;
903 return UFS_UNIPRO_VER_1_6;
905 EXPORT_SYMBOL(ufshcd_get_local_unipro_ver);
907 static bool ufshcd_is_unipro_pa_params_tuning_req(struct ufs_hba *hba)
910 * If both host and device support UniPro ver1.6 or later, PA layer
911 * parameters tuning happens during link startup itself.
913 * We can manually tune PA layer parameters if either host or device
914 * doesn't support UniPro ver 1.6 or later. But to keep manual tuning
915 * logic simple, we will only do manual tuning if local unipro version
916 * doesn't support ver1.6 or later.
918 if (ufshcd_get_local_unipro_ver(hba) < UFS_UNIPRO_VER_1_6)
925 * ufshcd_set_clk_freq - set UFS controller clock frequencies
926 * @hba: per adapter instance
927 * @scale_up: If True, set max possible frequency othewise set low frequency
929 * Returns 0 if successful
930 * Returns < 0 for any other errors
932 static int ufshcd_set_clk_freq(struct ufs_hba *hba, bool scale_up)
935 struct ufs_clk_info *clki;
936 struct list_head *head = &hba->clk_list_head;
938 if (list_empty(head))
941 list_for_each_entry(clki, head, list) {
942 if (!IS_ERR_OR_NULL(clki->clk)) {
943 if (scale_up && clki->max_freq) {
944 if (clki->curr_freq == clki->max_freq)
947 ret = clk_set_rate(clki->clk, clki->max_freq);
949 dev_err(hba->dev, "%s: %s clk set rate(%dHz) failed, %d\n",
950 __func__, clki->name,
951 clki->max_freq, ret);
954 trace_ufshcd_clk_scaling(dev_name(hba->dev),
955 "scaled up", clki->name,
959 clki->curr_freq = clki->max_freq;
961 } else if (!scale_up && clki->min_freq) {
962 if (clki->curr_freq == clki->min_freq)
965 ret = clk_set_rate(clki->clk, clki->min_freq);
967 dev_err(hba->dev, "%s: %s clk set rate(%dHz) failed, %d\n",
968 __func__, clki->name,
969 clki->min_freq, ret);
972 trace_ufshcd_clk_scaling(dev_name(hba->dev),
973 "scaled down", clki->name,
976 clki->curr_freq = clki->min_freq;
979 dev_dbg(hba->dev, "%s: clk: %s, rate: %lu\n", __func__,
980 clki->name, clk_get_rate(clki->clk));
988 * ufshcd_scale_clks - scale up or scale down UFS controller clocks
989 * @hba: per adapter instance
990 * @scale_up: True if scaling up and false if scaling down
992 * Returns 0 if successful
993 * Returns < 0 for any other errors
995 static int ufshcd_scale_clks(struct ufs_hba *hba, bool scale_up)
998 ktime_t start = ktime_get();
1000 ret = ufshcd_vops_clk_scale_notify(hba, scale_up, PRE_CHANGE);
1004 ret = ufshcd_set_clk_freq(hba, scale_up);
1008 ret = ufshcd_vops_clk_scale_notify(hba, scale_up, POST_CHANGE);
1010 ufshcd_set_clk_freq(hba, !scale_up);
1013 trace_ufshcd_profile_clk_scaling(dev_name(hba->dev),
1014 (scale_up ? "up" : "down"),
1015 ktime_to_us(ktime_sub(ktime_get(), start)), ret);
1020 * ufshcd_is_devfreq_scaling_required - check if scaling is required or not
1021 * @hba: per adapter instance
1022 * @scale_up: True if scaling up and false if scaling down
1024 * Returns true if scaling is required, false otherwise.
1026 static bool ufshcd_is_devfreq_scaling_required(struct ufs_hba *hba,
1029 struct ufs_clk_info *clki;
1030 struct list_head *head = &hba->clk_list_head;
1032 if (list_empty(head))
1035 list_for_each_entry(clki, head, list) {
1036 if (!IS_ERR_OR_NULL(clki->clk)) {
1037 if (scale_up && clki->max_freq) {
1038 if (clki->curr_freq == clki->max_freq)
1041 } else if (!scale_up && clki->min_freq) {
1042 if (clki->curr_freq == clki->min_freq)
1052 static int ufshcd_wait_for_doorbell_clr(struct ufs_hba *hba,
1053 u64 wait_timeout_us)
1055 unsigned long flags;
1059 bool timeout = false, do_last_check = false;
1062 ufshcd_hold(hba, false);
1063 spin_lock_irqsave(hba->host->host_lock, flags);
1065 * Wait for all the outstanding tasks/transfer requests.
1066 * Verify by checking the doorbell registers are clear.
1068 start = ktime_get();
1070 if (hba->ufshcd_state != UFSHCD_STATE_OPERATIONAL) {
1075 tm_doorbell = ufshcd_readl(hba, REG_UTP_TASK_REQ_DOOR_BELL);
1076 tr_doorbell = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
1077 if (!tm_doorbell && !tr_doorbell) {
1080 } else if (do_last_check) {
1084 spin_unlock_irqrestore(hba->host->host_lock, flags);
1086 if (ktime_to_us(ktime_sub(ktime_get(), start)) >
1090 * We might have scheduled out for long time so make
1091 * sure to check if doorbells are cleared by this time
1094 do_last_check = true;
1096 spin_lock_irqsave(hba->host->host_lock, flags);
1097 } while (tm_doorbell || tr_doorbell);
1101 "%s: timedout waiting for doorbell to clear (tm=0x%x, tr=0x%x)\n",
1102 __func__, tm_doorbell, tr_doorbell);
1106 spin_unlock_irqrestore(hba->host->host_lock, flags);
1107 ufshcd_release(hba);
1112 * ufshcd_scale_gear - scale up/down UFS gear
1113 * @hba: per adapter instance
1114 * @scale_up: True for scaling up gear and false for scaling down
1116 * Returns 0 for success,
1117 * Returns -EBUSY if scaling can't happen at this time
1118 * Returns non-zero for any other errors
1120 static int ufshcd_scale_gear(struct ufs_hba *hba, bool scale_up)
1123 struct ufs_pa_layer_attr new_pwr_info;
1126 memcpy(&new_pwr_info, &hba->clk_scaling.saved_pwr_info.info,
1127 sizeof(struct ufs_pa_layer_attr));
1129 memcpy(&new_pwr_info, &hba->pwr_info,
1130 sizeof(struct ufs_pa_layer_attr));
1132 if (hba->pwr_info.gear_tx > hba->clk_scaling.min_gear ||
1133 hba->pwr_info.gear_rx > hba->clk_scaling.min_gear) {
1134 /* save the current power mode */
1135 memcpy(&hba->clk_scaling.saved_pwr_info.info,
1137 sizeof(struct ufs_pa_layer_attr));
1139 /* scale down gear */
1140 new_pwr_info.gear_tx = hba->clk_scaling.min_gear;
1141 new_pwr_info.gear_rx = hba->clk_scaling.min_gear;
1145 /* check if the power mode needs to be changed or not? */
1146 ret = ufshcd_config_pwr_mode(hba, &new_pwr_info);
1148 dev_err(hba->dev, "%s: failed err %d, old gear: (tx %d rx %d), new gear: (tx %d rx %d)",
1150 hba->pwr_info.gear_tx, hba->pwr_info.gear_rx,
1151 new_pwr_info.gear_tx, new_pwr_info.gear_rx);
1156 static int ufshcd_clock_scaling_prepare(struct ufs_hba *hba)
1158 #define DOORBELL_CLR_TOUT_US (1000 * 1000) /* 1 sec */
1161 * make sure that there are no outstanding requests when
1162 * clock scaling is in progress
1164 ufshcd_scsi_block_requests(hba);
1165 down_write(&hba->clk_scaling_lock);
1166 if (ufshcd_wait_for_doorbell_clr(hba, DOORBELL_CLR_TOUT_US)) {
1168 up_write(&hba->clk_scaling_lock);
1169 ufshcd_scsi_unblock_requests(hba);
1175 static void ufshcd_clock_scaling_unprepare(struct ufs_hba *hba)
1177 up_write(&hba->clk_scaling_lock);
1178 ufshcd_scsi_unblock_requests(hba);
1182 * ufshcd_devfreq_scale - scale up/down UFS clocks and gear
1183 * @hba: per adapter instance
1184 * @scale_up: True for scaling up and false for scalin down
1186 * Returns 0 for success,
1187 * Returns -EBUSY if scaling can't happen at this time
1188 * Returns non-zero for any other errors
1190 static int ufshcd_devfreq_scale(struct ufs_hba *hba, bool scale_up)
1194 /* let's not get into low power until clock scaling is completed */
1195 ufshcd_hold(hba, false);
1197 ret = ufshcd_clock_scaling_prepare(hba);
1201 /* scale down the gear before scaling down clocks */
1203 ret = ufshcd_scale_gear(hba, false);
1208 ret = ufshcd_scale_clks(hba, scale_up);
1211 ufshcd_scale_gear(hba, true);
1215 /* scale up the gear after scaling up clocks */
1217 ret = ufshcd_scale_gear(hba, true);
1219 ufshcd_scale_clks(hba, false);
1224 /* Enable Write Booster if we have scaled up else disable it */
1225 up_write(&hba->clk_scaling_lock);
1226 ufshcd_wb_ctrl(hba, scale_up);
1227 down_write(&hba->clk_scaling_lock);
1230 ufshcd_clock_scaling_unprepare(hba);
1232 ufshcd_release(hba);
1236 static void ufshcd_clk_scaling_suspend_work(struct work_struct *work)
1238 struct ufs_hba *hba = container_of(work, struct ufs_hba,
1239 clk_scaling.suspend_work);
1240 unsigned long irq_flags;
1242 spin_lock_irqsave(hba->host->host_lock, irq_flags);
1243 if (hba->clk_scaling.active_reqs || hba->clk_scaling.is_suspended) {
1244 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1247 hba->clk_scaling.is_suspended = true;
1248 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1250 __ufshcd_suspend_clkscaling(hba);
1253 static void ufshcd_clk_scaling_resume_work(struct work_struct *work)
1255 struct ufs_hba *hba = container_of(work, struct ufs_hba,
1256 clk_scaling.resume_work);
1257 unsigned long irq_flags;
1259 spin_lock_irqsave(hba->host->host_lock, irq_flags);
1260 if (!hba->clk_scaling.is_suspended) {
1261 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1264 hba->clk_scaling.is_suspended = false;
1265 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1267 devfreq_resume_device(hba->devfreq);
1270 static int ufshcd_devfreq_target(struct device *dev,
1271 unsigned long *freq, u32 flags)
1274 struct ufs_hba *hba = dev_get_drvdata(dev);
1276 bool scale_up, sched_clk_scaling_suspend_work = false;
1277 struct list_head *clk_list = &hba->clk_list_head;
1278 struct ufs_clk_info *clki;
1279 unsigned long irq_flags;
1281 if (!ufshcd_is_clkscaling_supported(hba))
1284 clki = list_first_entry(&hba->clk_list_head, struct ufs_clk_info, list);
1285 /* Override with the closest supported frequency */
1286 *freq = (unsigned long) clk_round_rate(clki->clk, *freq);
1287 spin_lock_irqsave(hba->host->host_lock, irq_flags);
1288 if (ufshcd_eh_in_progress(hba)) {
1289 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1293 if (!hba->clk_scaling.active_reqs)
1294 sched_clk_scaling_suspend_work = true;
1296 if (list_empty(clk_list)) {
1297 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1301 /* Decide based on the rounded-off frequency and update */
1302 scale_up = (*freq == clki->max_freq) ? true : false;
1304 *freq = clki->min_freq;
1305 /* Update the frequency */
1306 if (!ufshcd_is_devfreq_scaling_required(hba, scale_up)) {
1307 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1309 goto out; /* no state change required */
1311 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1313 pm_runtime_get_noresume(hba->dev);
1314 if (!pm_runtime_active(hba->dev)) {
1315 pm_runtime_put_noidle(hba->dev);
1319 start = ktime_get();
1320 ret = ufshcd_devfreq_scale(hba, scale_up);
1321 pm_runtime_put(hba->dev);
1323 trace_ufshcd_profile_clk_scaling(dev_name(hba->dev),
1324 (scale_up ? "up" : "down"),
1325 ktime_to_us(ktime_sub(ktime_get(), start)), ret);
1328 if (sched_clk_scaling_suspend_work)
1329 queue_work(hba->clk_scaling.workq,
1330 &hba->clk_scaling.suspend_work);
1335 static bool ufshcd_is_busy(struct request *req, void *priv, bool reserved)
1339 WARN_ON_ONCE(reserved);
1344 /* Whether or not any tag is in use by a request that is in progress. */
1345 static bool ufshcd_any_tag_in_use(struct ufs_hba *hba)
1347 struct request_queue *q = hba->cmd_queue;
1350 blk_mq_tagset_busy_iter(q->tag_set, ufshcd_is_busy, &busy);
1354 static int ufshcd_devfreq_get_dev_status(struct device *dev,
1355 struct devfreq_dev_status *stat)
1357 struct ufs_hba *hba = dev_get_drvdata(dev);
1358 struct ufs_clk_scaling *scaling = &hba->clk_scaling;
1359 unsigned long flags;
1360 struct list_head *clk_list = &hba->clk_list_head;
1361 struct ufs_clk_info *clki;
1364 if (!ufshcd_is_clkscaling_supported(hba))
1367 memset(stat, 0, sizeof(*stat));
1369 spin_lock_irqsave(hba->host->host_lock, flags);
1370 curr_t = ktime_get();
1371 if (!scaling->window_start_t)
1374 clki = list_first_entry(clk_list, struct ufs_clk_info, list);
1376 * If current frequency is 0, then the ondemand governor considers
1377 * there's no initial frequency set. And it always requests to set
1378 * to max. frequency.
1380 stat->current_frequency = clki->curr_freq;
1381 if (scaling->is_busy_started)
1382 scaling->tot_busy_t += ktime_us_delta(curr_t,
1383 scaling->busy_start_t);
1385 stat->total_time = ktime_us_delta(curr_t, scaling->window_start_t);
1386 stat->busy_time = scaling->tot_busy_t;
1388 scaling->window_start_t = curr_t;
1389 scaling->tot_busy_t = 0;
1391 if (hba->outstanding_reqs) {
1392 scaling->busy_start_t = curr_t;
1393 scaling->is_busy_started = true;
1395 scaling->busy_start_t = 0;
1396 scaling->is_busy_started = false;
1398 spin_unlock_irqrestore(hba->host->host_lock, flags);
1402 static int ufshcd_devfreq_init(struct ufs_hba *hba)
1404 struct list_head *clk_list = &hba->clk_list_head;
1405 struct ufs_clk_info *clki;
1406 struct devfreq *devfreq;
1409 /* Skip devfreq if we don't have any clocks in the list */
1410 if (list_empty(clk_list))
1413 clki = list_first_entry(clk_list, struct ufs_clk_info, list);
1414 dev_pm_opp_add(hba->dev, clki->min_freq, 0);
1415 dev_pm_opp_add(hba->dev, clki->max_freq, 0);
1417 ufshcd_vops_config_scaling_param(hba, &hba->vps->devfreq_profile,
1418 &hba->vps->ondemand_data);
1419 devfreq = devfreq_add_device(hba->dev,
1420 &hba->vps->devfreq_profile,
1421 DEVFREQ_GOV_SIMPLE_ONDEMAND,
1422 &hba->vps->ondemand_data);
1423 if (IS_ERR(devfreq)) {
1424 ret = PTR_ERR(devfreq);
1425 dev_err(hba->dev, "Unable to register with devfreq %d\n", ret);
1427 dev_pm_opp_remove(hba->dev, clki->min_freq);
1428 dev_pm_opp_remove(hba->dev, clki->max_freq);
1432 hba->devfreq = devfreq;
1437 static void ufshcd_devfreq_remove(struct ufs_hba *hba)
1439 struct list_head *clk_list = &hba->clk_list_head;
1440 struct ufs_clk_info *clki;
1445 devfreq_remove_device(hba->devfreq);
1446 hba->devfreq = NULL;
1448 clki = list_first_entry(clk_list, struct ufs_clk_info, list);
1449 dev_pm_opp_remove(hba->dev, clki->min_freq);
1450 dev_pm_opp_remove(hba->dev, clki->max_freq);
1453 static void __ufshcd_suspend_clkscaling(struct ufs_hba *hba)
1455 unsigned long flags;
1457 devfreq_suspend_device(hba->devfreq);
1458 spin_lock_irqsave(hba->host->host_lock, flags);
1459 hba->clk_scaling.window_start_t = 0;
1460 spin_unlock_irqrestore(hba->host->host_lock, flags);
1463 static void ufshcd_suspend_clkscaling(struct ufs_hba *hba)
1465 unsigned long flags;
1466 bool suspend = false;
1468 if (!ufshcd_is_clkscaling_supported(hba))
1471 spin_lock_irqsave(hba->host->host_lock, flags);
1472 if (!hba->clk_scaling.is_suspended) {
1474 hba->clk_scaling.is_suspended = true;
1476 spin_unlock_irqrestore(hba->host->host_lock, flags);
1479 __ufshcd_suspend_clkscaling(hba);
1482 static void ufshcd_resume_clkscaling(struct ufs_hba *hba)
1484 unsigned long flags;
1485 bool resume = false;
1487 if (!ufshcd_is_clkscaling_supported(hba))
1490 spin_lock_irqsave(hba->host->host_lock, flags);
1491 if (hba->clk_scaling.is_suspended) {
1493 hba->clk_scaling.is_suspended = false;
1495 spin_unlock_irqrestore(hba->host->host_lock, flags);
1498 devfreq_resume_device(hba->devfreq);
1501 static ssize_t ufshcd_clkscale_enable_show(struct device *dev,
1502 struct device_attribute *attr, char *buf)
1504 struct ufs_hba *hba = dev_get_drvdata(dev);
1506 return snprintf(buf, PAGE_SIZE, "%d\n", hba->clk_scaling.is_allowed);
1509 static ssize_t ufshcd_clkscale_enable_store(struct device *dev,
1510 struct device_attribute *attr, const char *buf, size_t count)
1512 struct ufs_hba *hba = dev_get_drvdata(dev);
1516 if (kstrtou32(buf, 0, &value))
1520 if (value == hba->clk_scaling.is_allowed)
1523 pm_runtime_get_sync(hba->dev);
1524 ufshcd_hold(hba, false);
1526 cancel_work_sync(&hba->clk_scaling.suspend_work);
1527 cancel_work_sync(&hba->clk_scaling.resume_work);
1529 hba->clk_scaling.is_allowed = value;
1532 ufshcd_resume_clkscaling(hba);
1534 ufshcd_suspend_clkscaling(hba);
1535 err = ufshcd_devfreq_scale(hba, true);
1537 dev_err(hba->dev, "%s: failed to scale clocks up %d\n",
1541 ufshcd_release(hba);
1542 pm_runtime_put_sync(hba->dev);
1547 static void ufshcd_clkscaling_init_sysfs(struct ufs_hba *hba)
1549 hba->clk_scaling.enable_attr.show = ufshcd_clkscale_enable_show;
1550 hba->clk_scaling.enable_attr.store = ufshcd_clkscale_enable_store;
1551 sysfs_attr_init(&hba->clk_scaling.enable_attr.attr);
1552 hba->clk_scaling.enable_attr.attr.name = "clkscale_enable";
1553 hba->clk_scaling.enable_attr.attr.mode = 0644;
1554 if (device_create_file(hba->dev, &hba->clk_scaling.enable_attr))
1555 dev_err(hba->dev, "Failed to create sysfs for clkscale_enable\n");
1558 static void ufshcd_ungate_work(struct work_struct *work)
1561 unsigned long flags;
1562 struct ufs_hba *hba = container_of(work, struct ufs_hba,
1563 clk_gating.ungate_work);
1565 cancel_delayed_work_sync(&hba->clk_gating.gate_work);
1567 spin_lock_irqsave(hba->host->host_lock, flags);
1568 if (hba->clk_gating.state == CLKS_ON) {
1569 spin_unlock_irqrestore(hba->host->host_lock, flags);
1573 spin_unlock_irqrestore(hba->host->host_lock, flags);
1574 ufshcd_hba_vreg_set_hpm(hba);
1575 ufshcd_setup_clocks(hba, true);
1577 ufshcd_enable_irq(hba);
1579 /* Exit from hibern8 */
1580 if (ufshcd_can_hibern8_during_gating(hba)) {
1581 /* Prevent gating in this path */
1582 hba->clk_gating.is_suspended = true;
1583 if (ufshcd_is_link_hibern8(hba)) {
1584 ret = ufshcd_uic_hibern8_exit(hba);
1586 dev_err(hba->dev, "%s: hibern8 exit failed %d\n",
1589 ufshcd_set_link_active(hba);
1591 hba->clk_gating.is_suspended = false;
1594 ufshcd_scsi_unblock_requests(hba);
1598 * ufshcd_hold - Enable clocks that were gated earlier due to ufshcd_release.
1599 * Also, exit from hibern8 mode and set the link as active.
1600 * @hba: per adapter instance
1601 * @async: This indicates whether caller should ungate clocks asynchronously.
1603 int ufshcd_hold(struct ufs_hba *hba, bool async)
1607 unsigned long flags;
1609 if (!ufshcd_is_clkgating_allowed(hba))
1611 spin_lock_irqsave(hba->host->host_lock, flags);
1612 hba->clk_gating.active_reqs++;
1615 switch (hba->clk_gating.state) {
1618 * Wait for the ungate work to complete if in progress.
1619 * Though the clocks may be in ON state, the link could
1620 * still be in hibner8 state if hibern8 is allowed
1621 * during clock gating.
1622 * Make sure we exit hibern8 state also in addition to
1625 if (ufshcd_can_hibern8_during_gating(hba) &&
1626 ufshcd_is_link_hibern8(hba)) {
1629 hba->clk_gating.active_reqs--;
1632 spin_unlock_irqrestore(hba->host->host_lock, flags);
1633 flush_result = flush_work(&hba->clk_gating.ungate_work);
1634 if (hba->clk_gating.is_suspended && !flush_result)
1636 spin_lock_irqsave(hba->host->host_lock, flags);
1641 if (cancel_delayed_work(&hba->clk_gating.gate_work)) {
1642 hba->clk_gating.state = CLKS_ON;
1643 trace_ufshcd_clk_gating(dev_name(hba->dev),
1644 hba->clk_gating.state);
1648 * If we are here, it means gating work is either done or
1649 * currently running. Hence, fall through to cancel gating
1650 * work and to enable clocks.
1654 hba->clk_gating.state = REQ_CLKS_ON;
1655 trace_ufshcd_clk_gating(dev_name(hba->dev),
1656 hba->clk_gating.state);
1657 if (queue_work(hba->clk_gating.clk_gating_workq,
1658 &hba->clk_gating.ungate_work))
1659 ufshcd_scsi_block_requests(hba);
1661 * fall through to check if we should wait for this
1662 * work to be done or not.
1668 hba->clk_gating.active_reqs--;
1672 spin_unlock_irqrestore(hba->host->host_lock, flags);
1673 flush_work(&hba->clk_gating.ungate_work);
1674 /* Make sure state is CLKS_ON before returning */
1675 spin_lock_irqsave(hba->host->host_lock, flags);
1678 dev_err(hba->dev, "%s: clk gating is in invalid state %d\n",
1679 __func__, hba->clk_gating.state);
1682 spin_unlock_irqrestore(hba->host->host_lock, flags);
1686 EXPORT_SYMBOL_GPL(ufshcd_hold);
1688 static void ufshcd_gate_work(struct work_struct *work)
1690 struct ufs_hba *hba = container_of(work, struct ufs_hba,
1691 clk_gating.gate_work.work);
1692 unsigned long flags;
1695 spin_lock_irqsave(hba->host->host_lock, flags);
1697 * In case you are here to cancel this work the gating state
1698 * would be marked as REQ_CLKS_ON. In this case save time by
1699 * skipping the gating work and exit after changing the clock
1702 if (hba->clk_gating.is_suspended ||
1703 (hba->clk_gating.state != REQ_CLKS_OFF)) {
1704 hba->clk_gating.state = CLKS_ON;
1705 trace_ufshcd_clk_gating(dev_name(hba->dev),
1706 hba->clk_gating.state);
1710 if (hba->clk_gating.active_reqs
1711 || hba->ufshcd_state != UFSHCD_STATE_OPERATIONAL
1712 || ufshcd_any_tag_in_use(hba) || hba->outstanding_tasks
1713 || hba->active_uic_cmd || hba->uic_async_done)
1716 spin_unlock_irqrestore(hba->host->host_lock, flags);
1718 /* put the link into hibern8 mode before turning off clocks */
1719 if (ufshcd_can_hibern8_during_gating(hba)) {
1720 ret = ufshcd_uic_hibern8_enter(hba);
1722 hba->clk_gating.state = CLKS_ON;
1723 dev_err(hba->dev, "%s: hibern8 enter failed %d\n",
1725 trace_ufshcd_clk_gating(dev_name(hba->dev),
1726 hba->clk_gating.state);
1729 ufshcd_set_link_hibern8(hba);
1732 ufshcd_disable_irq(hba);
1734 ufshcd_setup_clocks(hba, false);
1736 /* Put the host controller in low power mode if possible */
1737 ufshcd_hba_vreg_set_lpm(hba);
1739 * In case you are here to cancel this work the gating state
1740 * would be marked as REQ_CLKS_ON. In this case keep the state
1741 * as REQ_CLKS_ON which would anyway imply that clocks are off
1742 * and a request to turn them on is pending. By doing this way,
1743 * we keep the state machine in tact and this would ultimately
1744 * prevent from doing cancel work multiple times when there are
1745 * new requests arriving before the current cancel work is done.
1747 spin_lock_irqsave(hba->host->host_lock, flags);
1748 if (hba->clk_gating.state == REQ_CLKS_OFF) {
1749 hba->clk_gating.state = CLKS_OFF;
1750 trace_ufshcd_clk_gating(dev_name(hba->dev),
1751 hba->clk_gating.state);
1754 spin_unlock_irqrestore(hba->host->host_lock, flags);
1759 /* host lock must be held before calling this variant */
1760 static void __ufshcd_release(struct ufs_hba *hba)
1762 if (!ufshcd_is_clkgating_allowed(hba))
1765 hba->clk_gating.active_reqs--;
1767 if (hba->clk_gating.active_reqs || hba->clk_gating.is_suspended ||
1768 hba->ufshcd_state != UFSHCD_STATE_OPERATIONAL ||
1769 hba->outstanding_tasks ||
1770 hba->active_uic_cmd || hba->uic_async_done ||
1771 hba->clk_gating.state == CLKS_OFF)
1774 hba->clk_gating.state = REQ_CLKS_OFF;
1775 trace_ufshcd_clk_gating(dev_name(hba->dev), hba->clk_gating.state);
1776 queue_delayed_work(hba->clk_gating.clk_gating_workq,
1777 &hba->clk_gating.gate_work,
1778 msecs_to_jiffies(hba->clk_gating.delay_ms));
1781 void ufshcd_release(struct ufs_hba *hba)
1783 unsigned long flags;
1785 spin_lock_irqsave(hba->host->host_lock, flags);
1786 __ufshcd_release(hba);
1787 spin_unlock_irqrestore(hba->host->host_lock, flags);
1789 EXPORT_SYMBOL_GPL(ufshcd_release);
1791 static ssize_t ufshcd_clkgate_delay_show(struct device *dev,
1792 struct device_attribute *attr, char *buf)
1794 struct ufs_hba *hba = dev_get_drvdata(dev);
1796 return snprintf(buf, PAGE_SIZE, "%lu\n", hba->clk_gating.delay_ms);
1799 static ssize_t ufshcd_clkgate_delay_store(struct device *dev,
1800 struct device_attribute *attr, const char *buf, size_t count)
1802 struct ufs_hba *hba = dev_get_drvdata(dev);
1803 unsigned long flags, value;
1805 if (kstrtoul(buf, 0, &value))
1808 spin_lock_irqsave(hba->host->host_lock, flags);
1809 hba->clk_gating.delay_ms = value;
1810 spin_unlock_irqrestore(hba->host->host_lock, flags);
1814 static ssize_t ufshcd_clkgate_enable_show(struct device *dev,
1815 struct device_attribute *attr, char *buf)
1817 struct ufs_hba *hba = dev_get_drvdata(dev);
1819 return snprintf(buf, PAGE_SIZE, "%d\n", hba->clk_gating.is_enabled);
1822 static ssize_t ufshcd_clkgate_enable_store(struct device *dev,
1823 struct device_attribute *attr, const char *buf, size_t count)
1825 struct ufs_hba *hba = dev_get_drvdata(dev);
1826 unsigned long flags;
1829 if (kstrtou32(buf, 0, &value))
1834 spin_lock_irqsave(hba->host->host_lock, flags);
1835 if (value == hba->clk_gating.is_enabled)
1839 __ufshcd_release(hba);
1841 hba->clk_gating.active_reqs++;
1843 hba->clk_gating.is_enabled = value;
1845 spin_unlock_irqrestore(hba->host->host_lock, flags);
1849 static void ufshcd_init_clk_scaling(struct ufs_hba *hba)
1851 char wq_name[sizeof("ufs_clkscaling_00")];
1853 if (!ufshcd_is_clkscaling_supported(hba))
1856 if (!hba->clk_scaling.min_gear)
1857 hba->clk_scaling.min_gear = UFS_HS_G1;
1859 INIT_WORK(&hba->clk_scaling.suspend_work,
1860 ufshcd_clk_scaling_suspend_work);
1861 INIT_WORK(&hba->clk_scaling.resume_work,
1862 ufshcd_clk_scaling_resume_work);
1864 snprintf(wq_name, sizeof(wq_name), "ufs_clkscaling_%d",
1865 hba->host->host_no);
1866 hba->clk_scaling.workq = create_singlethread_workqueue(wq_name);
1868 ufshcd_clkscaling_init_sysfs(hba);
1871 static void ufshcd_exit_clk_scaling(struct ufs_hba *hba)
1873 if (!ufshcd_is_clkscaling_supported(hba))
1876 destroy_workqueue(hba->clk_scaling.workq);
1877 ufshcd_devfreq_remove(hba);
1880 static void ufshcd_init_clk_gating(struct ufs_hba *hba)
1882 char wq_name[sizeof("ufs_clk_gating_00")];
1884 if (!ufshcd_is_clkgating_allowed(hba))
1887 hba->clk_gating.state = CLKS_ON;
1889 hba->clk_gating.delay_ms = 150;
1890 INIT_DELAYED_WORK(&hba->clk_gating.gate_work, ufshcd_gate_work);
1891 INIT_WORK(&hba->clk_gating.ungate_work, ufshcd_ungate_work);
1893 snprintf(wq_name, ARRAY_SIZE(wq_name), "ufs_clk_gating_%d",
1894 hba->host->host_no);
1895 hba->clk_gating.clk_gating_workq = alloc_ordered_workqueue(wq_name,
1896 WQ_MEM_RECLAIM | WQ_HIGHPRI);
1898 hba->clk_gating.is_enabled = true;
1900 hba->clk_gating.delay_attr.show = ufshcd_clkgate_delay_show;
1901 hba->clk_gating.delay_attr.store = ufshcd_clkgate_delay_store;
1902 sysfs_attr_init(&hba->clk_gating.delay_attr.attr);
1903 hba->clk_gating.delay_attr.attr.name = "clkgate_delay_ms";
1904 hba->clk_gating.delay_attr.attr.mode = 0644;
1905 if (device_create_file(hba->dev, &hba->clk_gating.delay_attr))
1906 dev_err(hba->dev, "Failed to create sysfs for clkgate_delay\n");
1908 hba->clk_gating.enable_attr.show = ufshcd_clkgate_enable_show;
1909 hba->clk_gating.enable_attr.store = ufshcd_clkgate_enable_store;
1910 sysfs_attr_init(&hba->clk_gating.enable_attr.attr);
1911 hba->clk_gating.enable_attr.attr.name = "clkgate_enable";
1912 hba->clk_gating.enable_attr.attr.mode = 0644;
1913 if (device_create_file(hba->dev, &hba->clk_gating.enable_attr))
1914 dev_err(hba->dev, "Failed to create sysfs for clkgate_enable\n");
1917 static void ufshcd_exit_clk_gating(struct ufs_hba *hba)
1919 if (!ufshcd_is_clkgating_allowed(hba))
1921 device_remove_file(hba->dev, &hba->clk_gating.delay_attr);
1922 device_remove_file(hba->dev, &hba->clk_gating.enable_attr);
1923 cancel_work_sync(&hba->clk_gating.ungate_work);
1924 cancel_delayed_work_sync(&hba->clk_gating.gate_work);
1925 destroy_workqueue(hba->clk_gating.clk_gating_workq);
1928 /* Must be called with host lock acquired */
1929 static void ufshcd_clk_scaling_start_busy(struct ufs_hba *hba)
1931 bool queue_resume_work = false;
1932 ktime_t curr_t = ktime_get();
1934 if (!ufshcd_is_clkscaling_supported(hba))
1937 if (!hba->clk_scaling.active_reqs++)
1938 queue_resume_work = true;
1940 if (!hba->clk_scaling.is_allowed || hba->pm_op_in_progress)
1943 if (queue_resume_work)
1944 queue_work(hba->clk_scaling.workq,
1945 &hba->clk_scaling.resume_work);
1947 if (!hba->clk_scaling.window_start_t) {
1948 hba->clk_scaling.window_start_t = curr_t;
1949 hba->clk_scaling.tot_busy_t = 0;
1950 hba->clk_scaling.is_busy_started = false;
1953 if (!hba->clk_scaling.is_busy_started) {
1954 hba->clk_scaling.busy_start_t = curr_t;
1955 hba->clk_scaling.is_busy_started = true;
1959 static void ufshcd_clk_scaling_update_busy(struct ufs_hba *hba)
1961 struct ufs_clk_scaling *scaling = &hba->clk_scaling;
1963 if (!ufshcd_is_clkscaling_supported(hba))
1966 if (!hba->outstanding_reqs && scaling->is_busy_started) {
1967 scaling->tot_busy_t += ktime_to_us(ktime_sub(ktime_get(),
1968 scaling->busy_start_t));
1969 scaling->busy_start_t = 0;
1970 scaling->is_busy_started = false;
1974 * ufshcd_send_command - Send SCSI or device management commands
1975 * @hba: per adapter instance
1976 * @task_tag: Task tag of the command
1979 void ufshcd_send_command(struct ufs_hba *hba, unsigned int task_tag)
1981 struct ufshcd_lrb *lrbp = &hba->lrb[task_tag];
1983 lrbp->issue_time_stamp = ktime_get();
1984 lrbp->compl_time_stamp = ktime_set(0, 0);
1985 ufshcd_vops_setup_xfer_req(hba, task_tag, (lrbp->cmd ? true : false));
1986 ufshcd_add_command_trace(hba, task_tag, "send");
1987 ufshcd_clk_scaling_start_busy(hba);
1988 __set_bit(task_tag, &hba->outstanding_reqs);
1989 ufshcd_writel(hba, 1 << task_tag, REG_UTP_TRANSFER_REQ_DOOR_BELL);
1990 /* Make sure that doorbell is committed immediately */
1995 * ufshcd_copy_sense_data - Copy sense data in case of check condition
1996 * @lrbp: pointer to local reference block
1998 static inline void ufshcd_copy_sense_data(struct ufshcd_lrb *lrbp)
2001 if (lrbp->sense_buffer &&
2002 ufshcd_get_rsp_upiu_data_seg_len(lrbp->ucd_rsp_ptr)) {
2005 len = be16_to_cpu(lrbp->ucd_rsp_ptr->sr.sense_data_len);
2006 len_to_copy = min_t(int, UFS_SENSE_SIZE, len);
2008 memcpy(lrbp->sense_buffer, lrbp->ucd_rsp_ptr->sr.sense_data,
2014 * ufshcd_copy_query_response() - Copy the Query Response and the data
2016 * @hba: per adapter instance
2017 * @lrbp: pointer to local reference block
2020 int ufshcd_copy_query_response(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
2022 struct ufs_query_res *query_res = &hba->dev_cmd.query.response;
2024 memcpy(&query_res->upiu_res, &lrbp->ucd_rsp_ptr->qr, QUERY_OSF_SIZE);
2026 /* Get the descriptor */
2027 if (hba->dev_cmd.query.descriptor &&
2028 lrbp->ucd_rsp_ptr->qr.opcode == UPIU_QUERY_OPCODE_READ_DESC) {
2029 u8 *descp = (u8 *)lrbp->ucd_rsp_ptr +
2030 GENERAL_UPIU_REQUEST_SIZE;
2034 /* data segment length */
2035 resp_len = be32_to_cpu(lrbp->ucd_rsp_ptr->header.dword_2) &
2036 MASK_QUERY_DATA_SEG_LEN;
2037 buf_len = be16_to_cpu(
2038 hba->dev_cmd.query.request.upiu_req.length);
2039 if (likely(buf_len >= resp_len)) {
2040 memcpy(hba->dev_cmd.query.descriptor, descp, resp_len);
2043 "%s: rsp size %d is bigger than buffer size %d",
2044 __func__, resp_len, buf_len);
2053 * ufshcd_hba_capabilities - Read controller capabilities
2054 * @hba: per adapter instance
2056 * Return: 0 on success, negative on error.
2058 static inline int ufshcd_hba_capabilities(struct ufs_hba *hba)
2062 hba->capabilities = ufshcd_readl(hba, REG_CONTROLLER_CAPABILITIES);
2064 /* nutrs and nutmrs are 0 based values */
2065 hba->nutrs = (hba->capabilities & MASK_TRANSFER_REQUESTS_SLOTS) + 1;
2067 ((hba->capabilities & MASK_TASK_MANAGEMENT_REQUEST_SLOTS) >> 16) + 1;
2069 /* Read crypto capabilities */
2070 err = ufshcd_hba_init_crypto_capabilities(hba);
2072 dev_err(hba->dev, "crypto setup failed\n");
2078 * ufshcd_ready_for_uic_cmd - Check if controller is ready
2079 * to accept UIC commands
2080 * @hba: per adapter instance
2081 * Return true on success, else false
2083 static inline bool ufshcd_ready_for_uic_cmd(struct ufs_hba *hba)
2085 if (ufshcd_readl(hba, REG_CONTROLLER_STATUS) & UIC_COMMAND_READY)
2092 * ufshcd_get_upmcrs - Get the power mode change request status
2093 * @hba: Pointer to adapter instance
2095 * This function gets the UPMCRS field of HCS register
2096 * Returns value of UPMCRS field
2098 static inline u8 ufshcd_get_upmcrs(struct ufs_hba *hba)
2100 return (ufshcd_readl(hba, REG_CONTROLLER_STATUS) >> 8) & 0x7;
2104 * ufshcd_dispatch_uic_cmd - Dispatch UIC commands to unipro layers
2105 * @hba: per adapter instance
2106 * @uic_cmd: UIC command
2108 * Mutex must be held.
2111 ufshcd_dispatch_uic_cmd(struct ufs_hba *hba, struct uic_command *uic_cmd)
2113 WARN_ON(hba->active_uic_cmd);
2115 hba->active_uic_cmd = uic_cmd;
2118 ufshcd_writel(hba, uic_cmd->argument1, REG_UIC_COMMAND_ARG_1);
2119 ufshcd_writel(hba, uic_cmd->argument2, REG_UIC_COMMAND_ARG_2);
2120 ufshcd_writel(hba, uic_cmd->argument3, REG_UIC_COMMAND_ARG_3);
2122 ufshcd_add_uic_command_trace(hba, uic_cmd, "send");
2125 ufshcd_writel(hba, uic_cmd->command & COMMAND_OPCODE_MASK,
2130 * ufshcd_wait_for_uic_cmd - Wait complectioin of UIC command
2131 * @hba: per adapter instance
2132 * @uic_cmd: UIC command
2134 * Must be called with mutex held.
2135 * Returns 0 only if success.
2138 ufshcd_wait_for_uic_cmd(struct ufs_hba *hba, struct uic_command *uic_cmd)
2141 unsigned long flags;
2143 if (wait_for_completion_timeout(&uic_cmd->done,
2144 msecs_to_jiffies(UIC_CMD_TIMEOUT))) {
2145 ret = uic_cmd->argument2 & MASK_UIC_COMMAND_RESULT;
2149 "uic cmd 0x%x with arg3 0x%x completion timeout\n",
2150 uic_cmd->command, uic_cmd->argument3);
2152 if (!uic_cmd->cmd_active) {
2153 dev_err(hba->dev, "%s: UIC cmd has been completed, return the result\n",
2155 ret = uic_cmd->argument2 & MASK_UIC_COMMAND_RESULT;
2159 spin_lock_irqsave(hba->host->host_lock, flags);
2160 hba->active_uic_cmd = NULL;
2161 spin_unlock_irqrestore(hba->host->host_lock, flags);
2167 * __ufshcd_send_uic_cmd - Send UIC commands and retrieve the result
2168 * @hba: per adapter instance
2169 * @uic_cmd: UIC command
2170 * @completion: initialize the completion only if this is set to true
2172 * Identical to ufshcd_send_uic_cmd() expect mutex. Must be called
2173 * with mutex held and host_lock locked.
2174 * Returns 0 only if success.
2177 __ufshcd_send_uic_cmd(struct ufs_hba *hba, struct uic_command *uic_cmd,
2180 if (!ufshcd_ready_for_uic_cmd(hba)) {
2182 "Controller not ready to accept UIC commands\n");
2187 init_completion(&uic_cmd->done);
2189 uic_cmd->cmd_active = 1;
2190 ufshcd_dispatch_uic_cmd(hba, uic_cmd);
2196 * ufshcd_send_uic_cmd - Send UIC commands and retrieve the result
2197 * @hba: per adapter instance
2198 * @uic_cmd: UIC command
2200 * Returns 0 only if success.
2202 int ufshcd_send_uic_cmd(struct ufs_hba *hba, struct uic_command *uic_cmd)
2205 unsigned long flags;
2207 ufshcd_hold(hba, false);
2208 mutex_lock(&hba->uic_cmd_mutex);
2209 ufshcd_add_delay_before_dme_cmd(hba);
2211 spin_lock_irqsave(hba->host->host_lock, flags);
2212 ret = __ufshcd_send_uic_cmd(hba, uic_cmd, true);
2213 spin_unlock_irqrestore(hba->host->host_lock, flags);
2215 ret = ufshcd_wait_for_uic_cmd(hba, uic_cmd);
2217 mutex_unlock(&hba->uic_cmd_mutex);
2219 ufshcd_release(hba);
2224 * ufshcd_map_sg - Map scatter-gather list to prdt
2225 * @hba: per adapter instance
2226 * @lrbp: pointer to local reference block
2228 * Returns 0 in case of success, non-zero value in case of failure
2230 static int ufshcd_map_sg(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
2232 struct ufshcd_sg_entry *prd_table;
2233 struct scatterlist *sg;
2234 struct scsi_cmnd *cmd;
2239 sg_segments = scsi_dma_map(cmd);
2240 if (sg_segments < 0)
2245 if (hba->quirks & UFSHCD_QUIRK_PRDT_BYTE_GRAN)
2246 lrbp->utr_descriptor_ptr->prd_table_length =
2247 cpu_to_le16((sg_segments *
2248 sizeof(struct ufshcd_sg_entry)));
2250 lrbp->utr_descriptor_ptr->prd_table_length =
2251 cpu_to_le16((u16) (sg_segments));
2253 prd_table = (struct ufshcd_sg_entry *)lrbp->ucd_prdt_ptr;
2255 scsi_for_each_sg(cmd, sg, sg_segments, i) {
2257 cpu_to_le32(((u32) sg_dma_len(sg))-1);
2258 prd_table[i].base_addr =
2259 cpu_to_le32(lower_32_bits(sg->dma_address));
2260 prd_table[i].upper_addr =
2261 cpu_to_le32(upper_32_bits(sg->dma_address));
2262 prd_table[i].reserved = 0;
2265 lrbp->utr_descriptor_ptr->prd_table_length = 0;
2272 * ufshcd_enable_intr - enable interrupts
2273 * @hba: per adapter instance
2274 * @intrs: interrupt bits
2276 static void ufshcd_enable_intr(struct ufs_hba *hba, u32 intrs)
2278 u32 set = ufshcd_readl(hba, REG_INTERRUPT_ENABLE);
2280 if (hba->ufs_version == UFSHCI_VERSION_10) {
2282 rw = set & INTERRUPT_MASK_RW_VER_10;
2283 set = rw | ((set ^ intrs) & intrs);
2288 ufshcd_writel(hba, set, REG_INTERRUPT_ENABLE);
2292 * ufshcd_disable_intr - disable interrupts
2293 * @hba: per adapter instance
2294 * @intrs: interrupt bits
2296 static void ufshcd_disable_intr(struct ufs_hba *hba, u32 intrs)
2298 u32 set = ufshcd_readl(hba, REG_INTERRUPT_ENABLE);
2300 if (hba->ufs_version == UFSHCI_VERSION_10) {
2302 rw = (set & INTERRUPT_MASK_RW_VER_10) &
2303 ~(intrs & INTERRUPT_MASK_RW_VER_10);
2304 set = rw | ((set & intrs) & ~INTERRUPT_MASK_RW_VER_10);
2310 ufshcd_writel(hba, set, REG_INTERRUPT_ENABLE);
2314 * ufshcd_prepare_req_desc_hdr() - Fills the requests header
2315 * descriptor according to request
2316 * @lrbp: pointer to local reference block
2317 * @upiu_flags: flags required in the header
2318 * @cmd_dir: requests data direction
2320 static void ufshcd_prepare_req_desc_hdr(struct ufshcd_lrb *lrbp,
2321 u8 *upiu_flags, enum dma_data_direction cmd_dir)
2323 struct utp_transfer_req_desc *req_desc = lrbp->utr_descriptor_ptr;
2329 if (cmd_dir == DMA_FROM_DEVICE) {
2330 data_direction = UTP_DEVICE_TO_HOST;
2331 *upiu_flags = UPIU_CMD_FLAGS_READ;
2332 } else if (cmd_dir == DMA_TO_DEVICE) {
2333 data_direction = UTP_HOST_TO_DEVICE;
2334 *upiu_flags = UPIU_CMD_FLAGS_WRITE;
2336 data_direction = UTP_NO_DATA_TRANSFER;
2337 *upiu_flags = UPIU_CMD_FLAGS_NONE;
2340 dword_0 = data_direction | (lrbp->command_type
2341 << UPIU_COMMAND_TYPE_OFFSET);
2343 dword_0 |= UTP_REQ_DESC_INT_CMD;
2345 /* Prepare crypto related dwords */
2346 ufshcd_prepare_req_desc_hdr_crypto(lrbp, &dword_0, &dword_1, &dword_3);
2348 /* Transfer request descriptor header fields */
2349 req_desc->header.dword_0 = cpu_to_le32(dword_0);
2350 req_desc->header.dword_1 = cpu_to_le32(dword_1);
2352 * assigning invalid value for command status. Controller
2353 * updates OCS on command completion, with the command
2356 req_desc->header.dword_2 =
2357 cpu_to_le32(OCS_INVALID_COMMAND_STATUS);
2358 req_desc->header.dword_3 = cpu_to_le32(dword_3);
2360 req_desc->prd_table_length = 0;
2364 * ufshcd_prepare_utp_scsi_cmd_upiu() - fills the utp_transfer_req_desc,
2366 * @lrbp: local reference block pointer
2367 * @upiu_flags: flags
2370 void ufshcd_prepare_utp_scsi_cmd_upiu(struct ufshcd_lrb *lrbp, u8 upiu_flags)
2372 struct scsi_cmnd *cmd = lrbp->cmd;
2373 struct utp_upiu_req *ucd_req_ptr = lrbp->ucd_req_ptr;
2374 unsigned short cdb_len;
2376 /* command descriptor fields */
2377 ucd_req_ptr->header.dword_0 = UPIU_HEADER_DWORD(
2378 UPIU_TRANSACTION_COMMAND, upiu_flags,
2379 lrbp->lun, lrbp->task_tag);
2380 ucd_req_ptr->header.dword_1 = UPIU_HEADER_DWORD(
2381 UPIU_COMMAND_SET_TYPE_SCSI, 0, 0, 0);
2383 /* Total EHS length and Data segment length will be zero */
2384 ucd_req_ptr->header.dword_2 = 0;
2386 ucd_req_ptr->sc.exp_data_transfer_len = cpu_to_be32(cmd->sdb.length);
2388 cdb_len = min_t(unsigned short, cmd->cmd_len, UFS_CDB_SIZE);
2389 memset(ucd_req_ptr->sc.cdb, 0, UFS_CDB_SIZE);
2390 memcpy(ucd_req_ptr->sc.cdb, cmd->cmnd, cdb_len);
2392 memset(lrbp->ucd_rsp_ptr, 0, sizeof(struct utp_upiu_rsp));
2396 * ufshcd_prepare_utp_query_req_upiu() - fills the utp_transfer_req_desc,
2399 * @lrbp: local reference block pointer
2400 * @upiu_flags: flags
2402 static void ufshcd_prepare_utp_query_req_upiu(struct ufs_hba *hba,
2403 struct ufshcd_lrb *lrbp, u8 upiu_flags)
2405 struct utp_upiu_req *ucd_req_ptr = lrbp->ucd_req_ptr;
2406 struct ufs_query *query = &hba->dev_cmd.query;
2407 u16 len = be16_to_cpu(query->request.upiu_req.length);
2409 /* Query request header */
2410 ucd_req_ptr->header.dword_0 = UPIU_HEADER_DWORD(
2411 UPIU_TRANSACTION_QUERY_REQ, upiu_flags,
2412 lrbp->lun, lrbp->task_tag);
2413 ucd_req_ptr->header.dword_1 = UPIU_HEADER_DWORD(
2414 0, query->request.query_func, 0, 0);
2416 /* Data segment length only need for WRITE_DESC */
2417 if (query->request.upiu_req.opcode == UPIU_QUERY_OPCODE_WRITE_DESC)
2418 ucd_req_ptr->header.dword_2 =
2419 UPIU_HEADER_DWORD(0, 0, (len >> 8), (u8)len);
2421 ucd_req_ptr->header.dword_2 = 0;
2423 /* Copy the Query Request buffer as is */
2424 memcpy(&ucd_req_ptr->qr, &query->request.upiu_req,
2427 /* Copy the Descriptor */
2428 if (query->request.upiu_req.opcode == UPIU_QUERY_OPCODE_WRITE_DESC)
2429 memcpy(ucd_req_ptr + 1, query->descriptor, len);
2431 memset(lrbp->ucd_rsp_ptr, 0, sizeof(struct utp_upiu_rsp));
2434 static inline void ufshcd_prepare_utp_nop_upiu(struct ufshcd_lrb *lrbp)
2436 struct utp_upiu_req *ucd_req_ptr = lrbp->ucd_req_ptr;
2438 memset(ucd_req_ptr, 0, sizeof(struct utp_upiu_req));
2440 /* command descriptor fields */
2441 ucd_req_ptr->header.dword_0 =
2443 UPIU_TRANSACTION_NOP_OUT, 0, 0, lrbp->task_tag);
2444 /* clear rest of the fields of basic header */
2445 ucd_req_ptr->header.dword_1 = 0;
2446 ucd_req_ptr->header.dword_2 = 0;
2448 memset(lrbp->ucd_rsp_ptr, 0, sizeof(struct utp_upiu_rsp));
2452 * ufshcd_compose_devman_upiu - UFS Protocol Information Unit(UPIU)
2453 * for Device Management Purposes
2454 * @hba: per adapter instance
2455 * @lrbp: pointer to local reference block
2457 static int ufshcd_compose_devman_upiu(struct ufs_hba *hba,
2458 struct ufshcd_lrb *lrbp)
2463 if ((hba->ufs_version == UFSHCI_VERSION_10) ||
2464 (hba->ufs_version == UFSHCI_VERSION_11))
2465 lrbp->command_type = UTP_CMD_TYPE_DEV_MANAGE;
2467 lrbp->command_type = UTP_CMD_TYPE_UFS_STORAGE;
2469 ufshcd_prepare_req_desc_hdr(lrbp, &upiu_flags, DMA_NONE);
2470 if (hba->dev_cmd.type == DEV_CMD_TYPE_QUERY)
2471 ufshcd_prepare_utp_query_req_upiu(hba, lrbp, upiu_flags);
2472 else if (hba->dev_cmd.type == DEV_CMD_TYPE_NOP)
2473 ufshcd_prepare_utp_nop_upiu(lrbp);
2481 * ufshcd_comp_scsi_upiu - UFS Protocol Information Unit(UPIU)
2483 * @hba: per adapter instance
2484 * @lrbp: pointer to local reference block
2486 static int ufshcd_comp_scsi_upiu(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
2491 if ((hba->ufs_version == UFSHCI_VERSION_10) ||
2492 (hba->ufs_version == UFSHCI_VERSION_11))
2493 lrbp->command_type = UTP_CMD_TYPE_SCSI;
2495 lrbp->command_type = UTP_CMD_TYPE_UFS_STORAGE;
2497 if (likely(lrbp->cmd)) {
2498 ufshcd_prepare_req_desc_hdr(lrbp, &upiu_flags,
2499 lrbp->cmd->sc_data_direction);
2500 ufshcd_prepare_utp_scsi_cmd_upiu(lrbp, upiu_flags);
2509 * ufshcd_upiu_wlun_to_scsi_wlun - maps UPIU W-LUN id to SCSI W-LUN ID
2510 * @upiu_wlun_id: UPIU W-LUN id
2512 * Returns SCSI W-LUN id
2514 static inline u16 ufshcd_upiu_wlun_to_scsi_wlun(u8 upiu_wlun_id)
2516 return (upiu_wlun_id & ~UFS_UPIU_WLUN_ID) | SCSI_W_LUN_BASE;
2519 static void ufshcd_init_lrb(struct ufs_hba *hba, struct ufshcd_lrb *lrb, int i)
2521 struct utp_transfer_cmd_desc *cmd_descp = hba->ucdl_base_addr;
2522 struct utp_transfer_req_desc *utrdlp = hba->utrdl_base_addr;
2523 dma_addr_t cmd_desc_element_addr = hba->ucdl_dma_addr +
2524 i * sizeof(struct utp_transfer_cmd_desc);
2525 u16 response_offset = offsetof(struct utp_transfer_cmd_desc,
2527 u16 prdt_offset = offsetof(struct utp_transfer_cmd_desc, prd_table);
2529 lrb->utr_descriptor_ptr = utrdlp + i;
2530 lrb->utrd_dma_addr = hba->utrdl_dma_addr +
2531 i * sizeof(struct utp_transfer_req_desc);
2532 lrb->ucd_req_ptr = (struct utp_upiu_req *)(cmd_descp + i);
2533 lrb->ucd_req_dma_addr = cmd_desc_element_addr;
2534 lrb->ucd_rsp_ptr = (struct utp_upiu_rsp *)cmd_descp[i].response_upiu;
2535 lrb->ucd_rsp_dma_addr = cmd_desc_element_addr + response_offset;
2536 lrb->ucd_prdt_ptr = (struct ufshcd_sg_entry *)cmd_descp[i].prd_table;
2537 lrb->ucd_prdt_dma_addr = cmd_desc_element_addr + prdt_offset;
2541 * ufshcd_queuecommand - main entry point for SCSI requests
2542 * @host: SCSI host pointer
2543 * @cmd: command from SCSI Midlayer
2545 * Returns 0 for success, non-zero in case of failure
2547 static int ufshcd_queuecommand(struct Scsi_Host *host, struct scsi_cmnd *cmd)
2549 struct ufshcd_lrb *lrbp;
2550 struct ufs_hba *hba;
2551 unsigned long flags;
2555 hba = shost_priv(host);
2557 tag = cmd->request->tag;
2558 if (!ufshcd_valid_tag(hba, tag)) {
2560 "%s: invalid command tag %d: cmd=0x%p, cmd->request=0x%p",
2561 __func__, tag, cmd, cmd->request);
2565 if (!down_read_trylock(&hba->clk_scaling_lock))
2566 return SCSI_MLQUEUE_HOST_BUSY;
2568 hba->req_abort_count = 0;
2570 err = ufshcd_hold(hba, true);
2572 err = SCSI_MLQUEUE_HOST_BUSY;
2575 WARN_ON(ufshcd_is_clkgating_allowed(hba) &&
2576 (hba->clk_gating.state != CLKS_ON));
2578 lrbp = &hba->lrb[tag];
2579 if (unlikely(lrbp->in_use)) {
2580 if (hba->pm_op_in_progress)
2581 set_host_byte(cmd, DID_BAD_TARGET);
2583 err = SCSI_MLQUEUE_HOST_BUSY;
2584 ufshcd_release(hba);
2590 lrbp->sense_bufflen = UFS_SENSE_SIZE;
2591 lrbp->sense_buffer = cmd->sense_buffer;
2592 lrbp->task_tag = tag;
2593 lrbp->lun = ufshcd_scsi_to_upiu_lun(cmd->device->lun);
2594 lrbp->intr_cmd = !ufshcd_is_intr_aggr_allowed(hba) ? true : false;
2596 ufshcd_prepare_lrbp_crypto(cmd->request, lrbp);
2598 lrbp->req_abort_skip = false;
2600 ufshcd_comp_scsi_upiu(hba, lrbp);
2602 err = ufshcd_map_sg(hba, lrbp);
2605 ufshcd_release(hba);
2608 /* Make sure descriptors are ready before ringing the doorbell */
2611 spin_lock_irqsave(hba->host->host_lock, flags);
2612 switch (hba->ufshcd_state) {
2613 case UFSHCD_STATE_OPERATIONAL:
2614 case UFSHCD_STATE_EH_SCHEDULED_NON_FATAL:
2616 case UFSHCD_STATE_EH_SCHEDULED_FATAL:
2618 * pm_runtime_get_sync() is used at error handling preparation
2619 * stage. If a scsi cmd, e.g. the SSU cmd, is sent from hba's
2620 * PM ops, it can never be finished if we let SCSI layer keep
2621 * retrying it, which gets err handler stuck forever. Neither
2622 * can we let the scsi cmd pass through, because UFS is in bad
2623 * state, the scsi cmd may eventually time out, which will get
2624 * err handler blocked for too long. So, just fail the scsi cmd
2625 * sent from PM ops, err handler can recover PM error anyways.
2627 if (hba->pm_op_in_progress) {
2628 hba->force_reset = true;
2629 set_host_byte(cmd, DID_BAD_TARGET);
2633 case UFSHCD_STATE_RESET:
2634 err = SCSI_MLQUEUE_HOST_BUSY;
2636 case UFSHCD_STATE_ERROR:
2637 set_host_byte(cmd, DID_ERROR);
2640 dev_WARN_ONCE(hba->dev, 1, "%s: invalid state %d\n",
2641 __func__, hba->ufshcd_state);
2642 set_host_byte(cmd, DID_BAD_TARGET);
2645 ufshcd_send_command(hba, tag);
2646 spin_unlock_irqrestore(hba->host->host_lock, flags);
2650 scsi_dma_unmap(lrbp->cmd);
2652 spin_unlock_irqrestore(hba->host->host_lock, flags);
2653 ufshcd_release(hba);
2655 cmd->scsi_done(cmd);
2657 up_read(&hba->clk_scaling_lock);
2661 static int ufshcd_compose_dev_cmd(struct ufs_hba *hba,
2662 struct ufshcd_lrb *lrbp, enum dev_cmd_type cmd_type, int tag)
2665 lrbp->sense_bufflen = 0;
2666 lrbp->sense_buffer = NULL;
2667 lrbp->task_tag = tag;
2668 lrbp->lun = 0; /* device management cmd is not specific to any LUN */
2669 lrbp->intr_cmd = true; /* No interrupt aggregation */
2670 ufshcd_prepare_lrbp_crypto(NULL, lrbp);
2671 hba->dev_cmd.type = cmd_type;
2673 return ufshcd_compose_devman_upiu(hba, lrbp);
2677 ufshcd_clear_cmd(struct ufs_hba *hba, int tag)
2680 unsigned long flags;
2681 u32 mask = 1 << tag;
2683 /* clear outstanding transaction before retry */
2684 spin_lock_irqsave(hba->host->host_lock, flags);
2685 ufshcd_utrl_clear(hba, tag);
2686 spin_unlock_irqrestore(hba->host->host_lock, flags);
2689 * wait for for h/w to clear corresponding bit in door-bell.
2690 * max. wait is 1 sec.
2692 err = ufshcd_wait_for_register(hba,
2693 REG_UTP_TRANSFER_REQ_DOOR_BELL,
2694 mask, ~mask, 1000, 1000);
2700 ufshcd_check_query_response(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
2702 struct ufs_query_res *query_res = &hba->dev_cmd.query.response;
2704 /* Get the UPIU response */
2705 query_res->response = ufshcd_get_rsp_upiu_result(lrbp->ucd_rsp_ptr) >>
2706 UPIU_RSP_CODE_OFFSET;
2707 return query_res->response;
2711 * ufshcd_dev_cmd_completion() - handles device management command responses
2712 * @hba: per adapter instance
2713 * @lrbp: pointer to local reference block
2716 ufshcd_dev_cmd_completion(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
2721 hba->ufs_stats.last_hibern8_exit_tstamp = ktime_set(0, 0);
2722 resp = ufshcd_get_req_rsp(lrbp->ucd_rsp_ptr);
2725 case UPIU_TRANSACTION_NOP_IN:
2726 if (hba->dev_cmd.type != DEV_CMD_TYPE_NOP) {
2728 dev_err(hba->dev, "%s: unexpected response %x\n",
2732 case UPIU_TRANSACTION_QUERY_RSP:
2733 err = ufshcd_check_query_response(hba, lrbp);
2735 err = ufshcd_copy_query_response(hba, lrbp);
2737 case UPIU_TRANSACTION_REJECT_UPIU:
2738 /* TODO: handle Reject UPIU Response */
2740 dev_err(hba->dev, "%s: Reject UPIU not fully implemented\n",
2745 dev_err(hba->dev, "%s: Invalid device management cmd response: %x\n",
2753 static int ufshcd_wait_for_dev_cmd(struct ufs_hba *hba,
2754 struct ufshcd_lrb *lrbp, int max_timeout)
2757 unsigned long time_left;
2758 unsigned long flags;
2760 time_left = wait_for_completion_timeout(hba->dev_cmd.complete,
2761 msecs_to_jiffies(max_timeout));
2763 /* Make sure descriptors are ready before ringing the doorbell */
2765 spin_lock_irqsave(hba->host->host_lock, flags);
2766 hba->dev_cmd.complete = NULL;
2767 if (likely(time_left)) {
2768 err = ufshcd_get_tr_ocs(lrbp);
2770 err = ufshcd_dev_cmd_completion(hba, lrbp);
2772 spin_unlock_irqrestore(hba->host->host_lock, flags);
2776 dev_dbg(hba->dev, "%s: dev_cmd request timedout, tag %d\n",
2777 __func__, lrbp->task_tag);
2778 if (!ufshcd_clear_cmd(hba, lrbp->task_tag))
2779 /* successfully cleared the command, retry if needed */
2782 * in case of an error, after clearing the doorbell,
2783 * we also need to clear the outstanding_request
2786 ufshcd_outstanding_req_clear(hba, lrbp->task_tag);
2793 * ufshcd_exec_dev_cmd - API for sending device management requests
2795 * @cmd_type: specifies the type (NOP, Query...)
2796 * @timeout: time in seconds
2798 * NOTE: Since there is only one available tag for device management commands,
2799 * it is expected you hold the hba->dev_cmd.lock mutex.
2801 static int ufshcd_exec_dev_cmd(struct ufs_hba *hba,
2802 enum dev_cmd_type cmd_type, int timeout)
2804 struct request_queue *q = hba->cmd_queue;
2805 struct request *req;
2806 struct ufshcd_lrb *lrbp;
2809 struct completion wait;
2810 unsigned long flags;
2812 down_read(&hba->clk_scaling_lock);
2815 * Get free slot, sleep if slots are unavailable.
2816 * Even though we use wait_event() which sleeps indefinitely,
2817 * the maximum wait time is bounded by SCSI request timeout.
2819 req = blk_get_request(q, REQ_OP_DRV_OUT, 0);
2825 WARN_ON_ONCE(!ufshcd_valid_tag(hba, tag));
2827 init_completion(&wait);
2828 lrbp = &hba->lrb[tag];
2829 if (unlikely(lrbp->in_use)) {
2835 err = ufshcd_compose_dev_cmd(hba, lrbp, cmd_type, tag);
2839 hba->dev_cmd.complete = &wait;
2841 ufshcd_add_query_upiu_trace(hba, tag, "query_send");
2842 /* Make sure descriptors are ready before ringing the doorbell */
2844 spin_lock_irqsave(hba->host->host_lock, flags);
2845 ufshcd_send_command(hba, tag);
2846 spin_unlock_irqrestore(hba->host->host_lock, flags);
2848 err = ufshcd_wait_for_dev_cmd(hba, lrbp, timeout);
2851 ufshcd_add_query_upiu_trace(hba, tag,
2852 err ? "query_complete_err" : "query_complete");
2855 blk_put_request(req);
2857 up_read(&hba->clk_scaling_lock);
2862 * ufshcd_init_query() - init the query response and request parameters
2863 * @hba: per-adapter instance
2864 * @request: address of the request pointer to be initialized
2865 * @response: address of the response pointer to be initialized
2866 * @opcode: operation to perform
2867 * @idn: flag idn to access
2868 * @index: LU number to access
2869 * @selector: query/flag/descriptor further identification
2871 static inline void ufshcd_init_query(struct ufs_hba *hba,
2872 struct ufs_query_req **request, struct ufs_query_res **response,
2873 enum query_opcode opcode, u8 idn, u8 index, u8 selector)
2875 *request = &hba->dev_cmd.query.request;
2876 *response = &hba->dev_cmd.query.response;
2877 memset(*request, 0, sizeof(struct ufs_query_req));
2878 memset(*response, 0, sizeof(struct ufs_query_res));
2879 (*request)->upiu_req.opcode = opcode;
2880 (*request)->upiu_req.idn = idn;
2881 (*request)->upiu_req.index = index;
2882 (*request)->upiu_req.selector = selector;
2885 static int ufshcd_query_flag_retry(struct ufs_hba *hba,
2886 enum query_opcode opcode, enum flag_idn idn, u8 index, bool *flag_res)
2891 for (retries = 0; retries < QUERY_REQ_RETRIES; retries++) {
2892 ret = ufshcd_query_flag(hba, opcode, idn, index, flag_res);
2895 "%s: failed with error %d, retries %d\n",
2896 __func__, ret, retries);
2903 "%s: query attribute, opcode %d, idn %d, failed with error %d after %d retires\n",
2904 __func__, opcode, idn, ret, retries);
2909 * ufshcd_query_flag() - API function for sending flag query requests
2910 * @hba: per-adapter instance
2911 * @opcode: flag query to perform
2912 * @idn: flag idn to access
2913 * @index: flag index to access
2914 * @flag_res: the flag value after the query request completes
2916 * Returns 0 for success, non-zero in case of failure
2918 int ufshcd_query_flag(struct ufs_hba *hba, enum query_opcode opcode,
2919 enum flag_idn idn, u8 index, bool *flag_res)
2921 struct ufs_query_req *request = NULL;
2922 struct ufs_query_res *response = NULL;
2923 int err, selector = 0;
2924 int timeout = QUERY_REQ_TIMEOUT;
2928 ufshcd_hold(hba, false);
2929 mutex_lock(&hba->dev_cmd.lock);
2930 ufshcd_init_query(hba, &request, &response, opcode, idn, index,
2934 case UPIU_QUERY_OPCODE_SET_FLAG:
2935 case UPIU_QUERY_OPCODE_CLEAR_FLAG:
2936 case UPIU_QUERY_OPCODE_TOGGLE_FLAG:
2937 request->query_func = UPIU_QUERY_FUNC_STANDARD_WRITE_REQUEST;
2939 case UPIU_QUERY_OPCODE_READ_FLAG:
2940 request->query_func = UPIU_QUERY_FUNC_STANDARD_READ_REQUEST;
2942 /* No dummy reads */
2943 dev_err(hba->dev, "%s: Invalid argument for read request\n",
2951 "%s: Expected query flag opcode but got = %d\n",
2957 err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_QUERY, timeout);
2961 "%s: Sending flag query for idn %d failed, err = %d\n",
2962 __func__, idn, err);
2967 *flag_res = (be32_to_cpu(response->upiu_res.value) &
2968 MASK_QUERY_UPIU_FLAG_LOC) & 0x1;
2971 mutex_unlock(&hba->dev_cmd.lock);
2972 ufshcd_release(hba);
2977 * ufshcd_query_attr - API function for sending attribute requests
2978 * @hba: per-adapter instance
2979 * @opcode: attribute opcode
2980 * @idn: attribute idn to access
2981 * @index: index field
2982 * @selector: selector field
2983 * @attr_val: the attribute value after the query request completes
2985 * Returns 0 for success, non-zero in case of failure
2987 int ufshcd_query_attr(struct ufs_hba *hba, enum query_opcode opcode,
2988 enum attr_idn idn, u8 index, u8 selector, u32 *attr_val)
2990 struct ufs_query_req *request = NULL;
2991 struct ufs_query_res *response = NULL;
2997 dev_err(hba->dev, "%s: attribute value required for opcode 0x%x\n",
3002 ufshcd_hold(hba, false);
3004 mutex_lock(&hba->dev_cmd.lock);
3005 ufshcd_init_query(hba, &request, &response, opcode, idn, index,
3009 case UPIU_QUERY_OPCODE_WRITE_ATTR:
3010 request->query_func = UPIU_QUERY_FUNC_STANDARD_WRITE_REQUEST;
3011 request->upiu_req.value = cpu_to_be32(*attr_val);
3013 case UPIU_QUERY_OPCODE_READ_ATTR:
3014 request->query_func = UPIU_QUERY_FUNC_STANDARD_READ_REQUEST;
3017 dev_err(hba->dev, "%s: Expected query attr opcode but got = 0x%.2x\n",
3023 err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_QUERY, QUERY_REQ_TIMEOUT);
3026 dev_err(hba->dev, "%s: opcode 0x%.2x for idn %d failed, index %d, err = %d\n",
3027 __func__, opcode, idn, index, err);
3031 *attr_val = be32_to_cpu(response->upiu_res.value);
3034 mutex_unlock(&hba->dev_cmd.lock);
3035 ufshcd_release(hba);
3040 * ufshcd_query_attr_retry() - API function for sending query
3041 * attribute with retries
3042 * @hba: per-adapter instance
3043 * @opcode: attribute opcode
3044 * @idn: attribute idn to access
3045 * @index: index field
3046 * @selector: selector field
3047 * @attr_val: the attribute value after the query request
3050 * Returns 0 for success, non-zero in case of failure
3052 static int ufshcd_query_attr_retry(struct ufs_hba *hba,
3053 enum query_opcode opcode, enum attr_idn idn, u8 index, u8 selector,
3059 for (retries = QUERY_REQ_RETRIES; retries > 0; retries--) {
3060 ret = ufshcd_query_attr(hba, opcode, idn, index,
3061 selector, attr_val);
3063 dev_dbg(hba->dev, "%s: failed with error %d, retries %d\n",
3064 __func__, ret, retries);
3071 "%s: query attribute, idn %d, failed with error %d after %d retires\n",
3072 __func__, idn, ret, QUERY_REQ_RETRIES);
3076 static int __ufshcd_query_descriptor(struct ufs_hba *hba,
3077 enum query_opcode opcode, enum desc_idn idn, u8 index,
3078 u8 selector, u8 *desc_buf, int *buf_len)
3080 struct ufs_query_req *request = NULL;
3081 struct ufs_query_res *response = NULL;
3087 dev_err(hba->dev, "%s: descriptor buffer required for opcode 0x%x\n",
3092 if (*buf_len < QUERY_DESC_MIN_SIZE || *buf_len > QUERY_DESC_MAX_SIZE) {
3093 dev_err(hba->dev, "%s: descriptor buffer size (%d) is out of range\n",
3094 __func__, *buf_len);
3098 ufshcd_hold(hba, false);
3100 mutex_lock(&hba->dev_cmd.lock);
3101 ufshcd_init_query(hba, &request, &response, opcode, idn, index,
3103 hba->dev_cmd.query.descriptor = desc_buf;
3104 request->upiu_req.length = cpu_to_be16(*buf_len);
3107 case UPIU_QUERY_OPCODE_WRITE_DESC:
3108 request->query_func = UPIU_QUERY_FUNC_STANDARD_WRITE_REQUEST;
3110 case UPIU_QUERY_OPCODE_READ_DESC:
3111 request->query_func = UPIU_QUERY_FUNC_STANDARD_READ_REQUEST;
3115 "%s: Expected query descriptor opcode but got = 0x%.2x\n",
3121 err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_QUERY, QUERY_REQ_TIMEOUT);
3124 dev_err(hba->dev, "%s: opcode 0x%.2x for idn %d failed, index %d, err = %d\n",
3125 __func__, opcode, idn, index, err);
3129 *buf_len = be16_to_cpu(response->upiu_res.length);
3132 hba->dev_cmd.query.descriptor = NULL;
3133 mutex_unlock(&hba->dev_cmd.lock);
3134 ufshcd_release(hba);
3139 * ufshcd_query_descriptor_retry - API function for sending descriptor requests
3140 * @hba: per-adapter instance
3141 * @opcode: attribute opcode
3142 * @idn: attribute idn to access
3143 * @index: index field
3144 * @selector: selector field
3145 * @desc_buf: the buffer that contains the descriptor
3146 * @buf_len: length parameter passed to the device
3148 * Returns 0 for success, non-zero in case of failure.
3149 * The buf_len parameter will contain, on return, the length parameter
3150 * received on the response.
3152 int ufshcd_query_descriptor_retry(struct ufs_hba *hba,
3153 enum query_opcode opcode,
3154 enum desc_idn idn, u8 index,
3156 u8 *desc_buf, int *buf_len)
3161 for (retries = QUERY_REQ_RETRIES; retries > 0; retries--) {
3162 err = __ufshcd_query_descriptor(hba, opcode, idn, index,
3163 selector, desc_buf, buf_len);
3164 if (!err || err == -EINVAL)
3172 * ufshcd_map_desc_id_to_length - map descriptor IDN to its length
3173 * @hba: Pointer to adapter instance
3174 * @desc_id: descriptor idn value
3175 * @desc_len: mapped desc length (out)
3177 void ufshcd_map_desc_id_to_length(struct ufs_hba *hba, enum desc_idn desc_id,
3180 if (desc_id >= QUERY_DESC_IDN_MAX || desc_id == QUERY_DESC_IDN_RFU_0 ||
3181 desc_id == QUERY_DESC_IDN_RFU_1)
3184 *desc_len = hba->desc_size[desc_id];
3186 EXPORT_SYMBOL(ufshcd_map_desc_id_to_length);
3188 static void ufshcd_update_desc_length(struct ufs_hba *hba,
3189 enum desc_idn desc_id, int desc_index,
3190 unsigned char desc_len)
3192 if (hba->desc_size[desc_id] == QUERY_DESC_MAX_SIZE &&
3193 desc_id != QUERY_DESC_IDN_STRING && desc_index != UFS_RPMB_UNIT)
3194 /* For UFS 3.1, the normal unit descriptor is 10 bytes larger
3195 * than the RPMB unit, however, both descriptors share the same
3196 * desc_idn, to cover both unit descriptors with one length, we
3197 * choose the normal unit descriptor length by desc_index.
3199 hba->desc_size[desc_id] = desc_len;
3203 * ufshcd_read_desc_param - read the specified descriptor parameter
3204 * @hba: Pointer to adapter instance
3205 * @desc_id: descriptor idn value
3206 * @desc_index: descriptor index
3207 * @param_offset: offset of the parameter to read
3208 * @param_read_buf: pointer to buffer where parameter would be read
3209 * @param_size: sizeof(param_read_buf)
3211 * Return 0 in case of success, non-zero otherwise
3213 int ufshcd_read_desc_param(struct ufs_hba *hba,
3214 enum desc_idn desc_id,
3223 bool is_kmalloc = true;
3226 if (desc_id >= QUERY_DESC_IDN_MAX || !param_size)
3229 /* Get the length of descriptor */
3230 ufshcd_map_desc_id_to_length(hba, desc_id, &buff_len);
3232 dev_err(hba->dev, "%s: Failed to get desc length\n", __func__);
3236 if (param_offset >= buff_len) {
3237 dev_err(hba->dev, "%s: Invalid offset 0x%x in descriptor IDN 0x%x, length 0x%x\n",
3238 __func__, param_offset, desc_id, buff_len);
3242 /* Check whether we need temp memory */
3243 if (param_offset != 0 || param_size < buff_len) {
3244 desc_buf = kzalloc(buff_len, GFP_KERNEL);
3248 desc_buf = param_read_buf;
3252 /* Request for full descriptor */
3253 ret = ufshcd_query_descriptor_retry(hba, UPIU_QUERY_OPCODE_READ_DESC,
3254 desc_id, desc_index, 0,
3255 desc_buf, &buff_len);
3258 dev_err(hba->dev, "%s: Failed reading descriptor. desc_id %d, desc_index %d, param_offset %d, ret %d\n",
3259 __func__, desc_id, desc_index, param_offset, ret);
3264 if (desc_buf[QUERY_DESC_DESC_TYPE_OFFSET] != desc_id) {
3265 dev_err(hba->dev, "%s: invalid desc_id %d in descriptor header\n",
3266 __func__, desc_buf[QUERY_DESC_DESC_TYPE_OFFSET]);
3271 /* Update descriptor length */
3272 buff_len = desc_buf[QUERY_DESC_LENGTH_OFFSET];
3273 ufshcd_update_desc_length(hba, desc_id, desc_index, buff_len);
3276 /* Make sure we don't copy more data than available */
3277 if (param_offset + param_size > buff_len)
3278 param_size = buff_len - param_offset;
3279 memcpy(param_read_buf, &desc_buf[param_offset], param_size);
3288 * struct uc_string_id - unicode string
3290 * @len: size of this descriptor inclusive
3291 * @type: descriptor type
3292 * @uc: unicode string character
3294 struct uc_string_id {
3300 /* replace non-printable or non-ASCII characters with spaces */
3301 static inline char ufshcd_remove_non_printable(u8 ch)
3303 return (ch >= 0x20 && ch <= 0x7e) ? ch : ' ';
3307 * ufshcd_read_string_desc - read string descriptor
3308 * @hba: pointer to adapter instance
3309 * @desc_index: descriptor index
3310 * @buf: pointer to buffer where descriptor would be read,
3311 * the caller should free the memory.
3312 * @ascii: if true convert from unicode to ascii characters
3313 * null terminated string.
3316 * * string size on success.
3317 * * -ENOMEM: on allocation failure
3318 * * -EINVAL: on a wrong parameter
3320 int ufshcd_read_string_desc(struct ufs_hba *hba, u8 desc_index,
3321 u8 **buf, bool ascii)
3323 struct uc_string_id *uc_str;
3330 uc_str = kzalloc(QUERY_DESC_MAX_SIZE, GFP_KERNEL);
3334 ret = ufshcd_read_desc_param(hba, QUERY_DESC_IDN_STRING, desc_index, 0,
3335 (u8 *)uc_str, QUERY_DESC_MAX_SIZE);
3337 dev_err(hba->dev, "Reading String Desc failed after %d retries. err = %d\n",
3338 QUERY_REQ_RETRIES, ret);
3343 if (uc_str->len <= QUERY_DESC_HDR_SIZE) {
3344 dev_dbg(hba->dev, "String Desc is of zero length\n");
3353 /* remove header and divide by 2 to move from UTF16 to UTF8 */
3354 ascii_len = (uc_str->len - QUERY_DESC_HDR_SIZE) / 2 + 1;
3355 str = kzalloc(ascii_len, GFP_KERNEL);
3362 * the descriptor contains string in UTF16 format
3363 * we need to convert to utf-8 so it can be displayed
3365 ret = utf16s_to_utf8s(uc_str->uc,
3366 uc_str->len - QUERY_DESC_HDR_SIZE,
3367 UTF16_BIG_ENDIAN, str, ascii_len);
3369 /* replace non-printable or non-ASCII characters with spaces */
3370 for (i = 0; i < ret; i++)
3371 str[i] = ufshcd_remove_non_printable(str[i]);
3376 str = kmemdup(uc_str, uc_str->len, GFP_KERNEL);
3390 * ufshcd_read_unit_desc_param - read the specified unit descriptor parameter
3391 * @hba: Pointer to adapter instance
3393 * @param_offset: offset of the parameter to read
3394 * @param_read_buf: pointer to buffer where parameter would be read
3395 * @param_size: sizeof(param_read_buf)
3397 * Return 0 in case of success, non-zero otherwise
3399 static inline int ufshcd_read_unit_desc_param(struct ufs_hba *hba,
3401 enum unit_desc_param param_offset,
3406 * Unit descriptors are only available for general purpose LUs (LUN id
3407 * from 0 to 7) and RPMB Well known LU.
3409 if (!ufs_is_valid_unit_desc_lun(&hba->dev_info, lun))
3412 return ufshcd_read_desc_param(hba, QUERY_DESC_IDN_UNIT, lun,
3413 param_offset, param_read_buf, param_size);
3416 static int ufshcd_get_ref_clk_gating_wait(struct ufs_hba *hba)
3419 u32 gating_wait = UFSHCD_REF_CLK_GATING_WAIT_US;
3421 if (hba->dev_info.wspecversion >= 0x300) {
3422 err = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
3423 QUERY_ATTR_IDN_REF_CLK_GATING_WAIT_TIME, 0, 0,
3426 dev_err(hba->dev, "Failed reading bRefClkGatingWait. err = %d, use default %uus\n",
3429 if (gating_wait == 0) {
3430 gating_wait = UFSHCD_REF_CLK_GATING_WAIT_US;
3431 dev_err(hba->dev, "Undefined ref clk gating wait time, use default %uus\n",
3435 hba->dev_info.clk_gating_wait_us = gating_wait;
3442 * ufshcd_memory_alloc - allocate memory for host memory space data structures
3443 * @hba: per adapter instance
3445 * 1. Allocate DMA memory for Command Descriptor array
3446 * Each command descriptor consist of Command UPIU, Response UPIU and PRDT
3447 * 2. Allocate DMA memory for UTP Transfer Request Descriptor List (UTRDL).
3448 * 3. Allocate DMA memory for UTP Task Management Request Descriptor List
3450 * 4. Allocate memory for local reference block(lrb).
3452 * Returns 0 for success, non-zero in case of failure
3454 static int ufshcd_memory_alloc(struct ufs_hba *hba)
3456 size_t utmrdl_size, utrdl_size, ucdl_size;
3458 /* Allocate memory for UTP command descriptors */
3459 ucdl_size = (sizeof(struct utp_transfer_cmd_desc) * hba->nutrs);
3460 hba->ucdl_base_addr = dmam_alloc_coherent(hba->dev,
3462 &hba->ucdl_dma_addr,
3466 * UFSHCI requires UTP command descriptor to be 128 byte aligned.
3467 * make sure hba->ucdl_dma_addr is aligned to PAGE_SIZE
3468 * if hba->ucdl_dma_addr is aligned to PAGE_SIZE, then it will
3469 * be aligned to 128 bytes as well
3471 if (!hba->ucdl_base_addr ||
3472 WARN_ON(hba->ucdl_dma_addr & (PAGE_SIZE - 1))) {
3474 "Command Descriptor Memory allocation failed\n");
3479 * Allocate memory for UTP Transfer descriptors
3480 * UFSHCI requires 1024 byte alignment of UTRD
3482 utrdl_size = (sizeof(struct utp_transfer_req_desc) * hba->nutrs);
3483 hba->utrdl_base_addr = dmam_alloc_coherent(hba->dev,
3485 &hba->utrdl_dma_addr,
3487 if (!hba->utrdl_base_addr ||
3488 WARN_ON(hba->utrdl_dma_addr & (PAGE_SIZE - 1))) {
3490 "Transfer Descriptor Memory allocation failed\n");
3495 * Allocate memory for UTP Task Management descriptors
3496 * UFSHCI requires 1024 byte alignment of UTMRD
3498 utmrdl_size = sizeof(struct utp_task_req_desc) * hba->nutmrs;
3499 hba->utmrdl_base_addr = dmam_alloc_coherent(hba->dev,
3501 &hba->utmrdl_dma_addr,
3503 if (!hba->utmrdl_base_addr ||
3504 WARN_ON(hba->utmrdl_dma_addr & (PAGE_SIZE - 1))) {
3506 "Task Management Descriptor Memory allocation failed\n");
3510 /* Allocate memory for local reference block */
3511 hba->lrb = devm_kcalloc(hba->dev,
3512 hba->nutrs, sizeof(struct ufshcd_lrb),
3515 dev_err(hba->dev, "LRB Memory allocation failed\n");
3524 * ufshcd_host_memory_configure - configure local reference block with
3526 * @hba: per adapter instance
3528 * Configure Host memory space
3529 * 1. Update Corresponding UTRD.UCDBA and UTRD.UCDBAU with UCD DMA
3531 * 2. Update each UTRD with Response UPIU offset, Response UPIU length
3533 * 3. Save the corresponding addresses of UTRD, UCD.CMD, UCD.RSP and UCD.PRDT
3534 * into local reference block.
3536 static void ufshcd_host_memory_configure(struct ufs_hba *hba)
3538 struct utp_transfer_req_desc *utrdlp;
3539 dma_addr_t cmd_desc_dma_addr;
3540 dma_addr_t cmd_desc_element_addr;
3541 u16 response_offset;
3546 utrdlp = hba->utrdl_base_addr;
3549 offsetof(struct utp_transfer_cmd_desc, response_upiu);
3551 offsetof(struct utp_transfer_cmd_desc, prd_table);
3553 cmd_desc_size = sizeof(struct utp_transfer_cmd_desc);
3554 cmd_desc_dma_addr = hba->ucdl_dma_addr;
3556 for (i = 0; i < hba->nutrs; i++) {
3557 /* Configure UTRD with command descriptor base address */
3558 cmd_desc_element_addr =
3559 (cmd_desc_dma_addr + (cmd_desc_size * i));
3560 utrdlp[i].command_desc_base_addr_lo =
3561 cpu_to_le32(lower_32_bits(cmd_desc_element_addr));
3562 utrdlp[i].command_desc_base_addr_hi =
3563 cpu_to_le32(upper_32_bits(cmd_desc_element_addr));
3565 /* Response upiu and prdt offset should be in double words */
3566 if (hba->quirks & UFSHCD_QUIRK_PRDT_BYTE_GRAN) {
3567 utrdlp[i].response_upiu_offset =
3568 cpu_to_le16(response_offset);
3569 utrdlp[i].prd_table_offset =
3570 cpu_to_le16(prdt_offset);
3571 utrdlp[i].response_upiu_length =
3572 cpu_to_le16(ALIGNED_UPIU_SIZE);
3574 utrdlp[i].response_upiu_offset =
3575 cpu_to_le16(response_offset >> 2);
3576 utrdlp[i].prd_table_offset =
3577 cpu_to_le16(prdt_offset >> 2);
3578 utrdlp[i].response_upiu_length =
3579 cpu_to_le16(ALIGNED_UPIU_SIZE >> 2);
3582 ufshcd_init_lrb(hba, &hba->lrb[i], i);
3587 * ufshcd_dme_link_startup - Notify Unipro to perform link startup
3588 * @hba: per adapter instance
3590 * UIC_CMD_DME_LINK_STARTUP command must be issued to Unipro layer,
3591 * in order to initialize the Unipro link startup procedure.
3592 * Once the Unipro links are up, the device connected to the controller
3595 * Returns 0 on success, non-zero value on failure
3597 static int ufshcd_dme_link_startup(struct ufs_hba *hba)
3599 struct uic_command uic_cmd = {0};
3602 uic_cmd.command = UIC_CMD_DME_LINK_STARTUP;
3604 ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
3607 "dme-link-startup: error code %d\n", ret);
3611 * ufshcd_dme_reset - UIC command for DME_RESET
3612 * @hba: per adapter instance
3614 * DME_RESET command is issued in order to reset UniPro stack.
3615 * This function now deals with cold reset.
3617 * Returns 0 on success, non-zero value on failure
3619 static int ufshcd_dme_reset(struct ufs_hba *hba)
3621 struct uic_command uic_cmd = {0};
3624 uic_cmd.command = UIC_CMD_DME_RESET;
3626 ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
3629 "dme-reset: error code %d\n", ret);
3634 int ufshcd_dme_configure_adapt(struct ufs_hba *hba,
3640 if (agreed_gear != UFS_HS_G4)
3641 adapt_val = PA_NO_ADAPT;
3643 ret = ufshcd_dme_set(hba,
3644 UIC_ARG_MIB(PA_TXHSADAPTTYPE),
3648 EXPORT_SYMBOL_GPL(ufshcd_dme_configure_adapt);
3651 * ufshcd_dme_enable - UIC command for DME_ENABLE
3652 * @hba: per adapter instance
3654 * DME_ENABLE command is issued in order to enable UniPro stack.
3656 * Returns 0 on success, non-zero value on failure
3658 static int ufshcd_dme_enable(struct ufs_hba *hba)
3660 struct uic_command uic_cmd = {0};
3663 uic_cmd.command = UIC_CMD_DME_ENABLE;
3665 ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
3668 "dme-reset: error code %d\n", ret);
3673 static inline void ufshcd_add_delay_before_dme_cmd(struct ufs_hba *hba)
3675 #define MIN_DELAY_BEFORE_DME_CMDS_US 1000
3676 unsigned long min_sleep_time_us;
3678 if (!(hba->quirks & UFSHCD_QUIRK_DELAY_BEFORE_DME_CMDS))
3682 * last_dme_cmd_tstamp will be 0 only for 1st call to
3685 if (unlikely(!ktime_to_us(hba->last_dme_cmd_tstamp))) {
3686 min_sleep_time_us = MIN_DELAY_BEFORE_DME_CMDS_US;
3688 unsigned long delta =
3689 (unsigned long) ktime_to_us(
3690 ktime_sub(ktime_get(),
3691 hba->last_dme_cmd_tstamp));
3693 if (delta < MIN_DELAY_BEFORE_DME_CMDS_US)
3695 MIN_DELAY_BEFORE_DME_CMDS_US - delta;
3697 return; /* no more delay required */
3700 /* allow sleep for extra 50us if needed */
3701 usleep_range(min_sleep_time_us, min_sleep_time_us + 50);
3705 * ufshcd_dme_set_attr - UIC command for DME_SET, DME_PEER_SET
3706 * @hba: per adapter instance
3707 * @attr_sel: uic command argument1
3708 * @attr_set: attribute set type as uic command argument2
3709 * @mib_val: setting value as uic command argument3
3710 * @peer: indicate whether peer or local
3712 * Returns 0 on success, non-zero value on failure
3714 int ufshcd_dme_set_attr(struct ufs_hba *hba, u32 attr_sel,
3715 u8 attr_set, u32 mib_val, u8 peer)
3717 struct uic_command uic_cmd = {0};
3718 static const char *const action[] = {
3722 const char *set = action[!!peer];
3724 int retries = UFS_UIC_COMMAND_RETRIES;
3726 uic_cmd.command = peer ?
3727 UIC_CMD_DME_PEER_SET : UIC_CMD_DME_SET;
3728 uic_cmd.argument1 = attr_sel;
3729 uic_cmd.argument2 = UIC_ARG_ATTR_TYPE(attr_set);
3730 uic_cmd.argument3 = mib_val;
3733 /* for peer attributes we retry upon failure */
3734 ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
3736 dev_dbg(hba->dev, "%s: attr-id 0x%x val 0x%x error code %d\n",
3737 set, UIC_GET_ATTR_ID(attr_sel), mib_val, ret);
3738 } while (ret && peer && --retries);
3741 dev_err(hba->dev, "%s: attr-id 0x%x val 0x%x failed %d retries\n",
3742 set, UIC_GET_ATTR_ID(attr_sel), mib_val,
3743 UFS_UIC_COMMAND_RETRIES - retries);
3747 EXPORT_SYMBOL_GPL(ufshcd_dme_set_attr);
3750 * ufshcd_dme_get_attr - UIC command for DME_GET, DME_PEER_GET
3751 * @hba: per adapter instance
3752 * @attr_sel: uic command argument1
3753 * @mib_val: the value of the attribute as returned by the UIC command
3754 * @peer: indicate whether peer or local
3756 * Returns 0 on success, non-zero value on failure
3758 int ufshcd_dme_get_attr(struct ufs_hba *hba, u32 attr_sel,
3759 u32 *mib_val, u8 peer)
3761 struct uic_command uic_cmd = {0};
3762 static const char *const action[] = {
3766 const char *get = action[!!peer];
3768 int retries = UFS_UIC_COMMAND_RETRIES;
3769 struct ufs_pa_layer_attr orig_pwr_info;
3770 struct ufs_pa_layer_attr temp_pwr_info;
3771 bool pwr_mode_change = false;
3773 if (peer && (hba->quirks & UFSHCD_QUIRK_DME_PEER_ACCESS_AUTO_MODE)) {
3774 orig_pwr_info = hba->pwr_info;
3775 temp_pwr_info = orig_pwr_info;
3777 if (orig_pwr_info.pwr_tx == FAST_MODE ||
3778 orig_pwr_info.pwr_rx == FAST_MODE) {
3779 temp_pwr_info.pwr_tx = FASTAUTO_MODE;
3780 temp_pwr_info.pwr_rx = FASTAUTO_MODE;
3781 pwr_mode_change = true;
3782 } else if (orig_pwr_info.pwr_tx == SLOW_MODE ||
3783 orig_pwr_info.pwr_rx == SLOW_MODE) {
3784 temp_pwr_info.pwr_tx = SLOWAUTO_MODE;
3785 temp_pwr_info.pwr_rx = SLOWAUTO_MODE;
3786 pwr_mode_change = true;
3788 if (pwr_mode_change) {
3789 ret = ufshcd_change_power_mode(hba, &temp_pwr_info);
3795 uic_cmd.command = peer ?
3796 UIC_CMD_DME_PEER_GET : UIC_CMD_DME_GET;
3797 uic_cmd.argument1 = attr_sel;
3800 /* for peer attributes we retry upon failure */
3801 ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
3803 dev_dbg(hba->dev, "%s: attr-id 0x%x error code %d\n",
3804 get, UIC_GET_ATTR_ID(attr_sel), ret);
3805 } while (ret && peer && --retries);
3808 dev_err(hba->dev, "%s: attr-id 0x%x failed %d retries\n",
3809 get, UIC_GET_ATTR_ID(attr_sel),
3810 UFS_UIC_COMMAND_RETRIES - retries);
3812 if (mib_val && !ret)
3813 *mib_val = uic_cmd.argument3;
3815 if (peer && (hba->quirks & UFSHCD_QUIRK_DME_PEER_ACCESS_AUTO_MODE)
3817 ufshcd_change_power_mode(hba, &orig_pwr_info);
3821 EXPORT_SYMBOL_GPL(ufshcd_dme_get_attr);
3824 * ufshcd_uic_pwr_ctrl - executes UIC commands (which affects the link power
3825 * state) and waits for it to take effect.
3827 * @hba: per adapter instance
3828 * @cmd: UIC command to execute
3830 * DME operations like DME_SET(PA_PWRMODE), DME_HIBERNATE_ENTER &
3831 * DME_HIBERNATE_EXIT commands take some time to take its effect on both host
3832 * and device UniPro link and hence it's final completion would be indicated by
3833 * dedicated status bits in Interrupt Status register (UPMS, UHES, UHXS) in
3834 * addition to normal UIC command completion Status (UCCS). This function only
3835 * returns after the relevant status bits indicate the completion.
3837 * Returns 0 on success, non-zero value on failure
3839 static int ufshcd_uic_pwr_ctrl(struct ufs_hba *hba, struct uic_command *cmd)
3841 struct completion uic_async_done;
3842 unsigned long flags;
3845 bool reenable_intr = false;
3847 mutex_lock(&hba->uic_cmd_mutex);
3848 init_completion(&uic_async_done);
3849 ufshcd_add_delay_before_dme_cmd(hba);
3851 spin_lock_irqsave(hba->host->host_lock, flags);
3852 if (ufshcd_is_link_broken(hba)) {
3856 hba->uic_async_done = &uic_async_done;
3857 if (ufshcd_readl(hba, REG_INTERRUPT_ENABLE) & UIC_COMMAND_COMPL) {
3858 ufshcd_disable_intr(hba, UIC_COMMAND_COMPL);
3860 * Make sure UIC command completion interrupt is disabled before
3861 * issuing UIC command.
3864 reenable_intr = true;
3866 ret = __ufshcd_send_uic_cmd(hba, cmd, false);
3867 spin_unlock_irqrestore(hba->host->host_lock, flags);
3870 "pwr ctrl cmd 0x%x with mode 0x%x uic error %d\n",
3871 cmd->command, cmd->argument3, ret);
3875 if (!wait_for_completion_timeout(hba->uic_async_done,
3876 msecs_to_jiffies(UIC_CMD_TIMEOUT))) {
3878 "pwr ctrl cmd 0x%x with mode 0x%x completion timeout\n",
3879 cmd->command, cmd->argument3);
3881 if (!cmd->cmd_active) {
3882 dev_err(hba->dev, "%s: Power Mode Change operation has been completed, go check UPMCRS\n",
3892 status = ufshcd_get_upmcrs(hba);
3893 if (status != PWR_LOCAL) {
3895 "pwr ctrl cmd 0x%x failed, host upmcrs:0x%x\n",
3896 cmd->command, status);
3897 ret = (status != PWR_OK) ? status : -1;
3901 ufshcd_print_host_state(hba);
3902 ufshcd_print_pwr_info(hba);
3903 ufshcd_print_evt_hist(hba);
3906 spin_lock_irqsave(hba->host->host_lock, flags);
3907 hba->active_uic_cmd = NULL;
3908 hba->uic_async_done = NULL;
3910 ufshcd_enable_intr(hba, UIC_COMMAND_COMPL);
3912 ufshcd_set_link_broken(hba);
3913 ufshcd_schedule_eh_work(hba);
3916 spin_unlock_irqrestore(hba->host->host_lock, flags);
3917 mutex_unlock(&hba->uic_cmd_mutex);
3923 * ufshcd_uic_change_pwr_mode - Perform the UIC power mode chage
3924 * using DME_SET primitives.
3925 * @hba: per adapter instance
3926 * @mode: powr mode value
3928 * Returns 0 on success, non-zero value on failure
3930 static int ufshcd_uic_change_pwr_mode(struct ufs_hba *hba, u8 mode)
3932 struct uic_command uic_cmd = {0};
3935 if (hba->quirks & UFSHCD_QUIRK_BROKEN_PA_RXHSUNTERMCAP) {
3936 ret = ufshcd_dme_set(hba,
3937 UIC_ARG_MIB_SEL(PA_RXHSUNTERMCAP, 0), 1);
3939 dev_err(hba->dev, "%s: failed to enable PA_RXHSUNTERMCAP ret %d\n",
3945 uic_cmd.command = UIC_CMD_DME_SET;
3946 uic_cmd.argument1 = UIC_ARG_MIB(PA_PWRMODE);
3947 uic_cmd.argument3 = mode;
3948 ufshcd_hold(hba, false);
3949 ret = ufshcd_uic_pwr_ctrl(hba, &uic_cmd);
3950 ufshcd_release(hba);
3956 int ufshcd_link_recovery(struct ufs_hba *hba)
3959 unsigned long flags;
3961 spin_lock_irqsave(hba->host->host_lock, flags);
3962 hba->ufshcd_state = UFSHCD_STATE_RESET;
3963 ufshcd_set_eh_in_progress(hba);
3964 spin_unlock_irqrestore(hba->host->host_lock, flags);
3966 /* Reset the attached device */
3967 ufshcd_vops_device_reset(hba);
3969 ret = ufshcd_host_reset_and_restore(hba);
3971 spin_lock_irqsave(hba->host->host_lock, flags);
3973 hba->ufshcd_state = UFSHCD_STATE_ERROR;
3974 ufshcd_clear_eh_in_progress(hba);
3975 spin_unlock_irqrestore(hba->host->host_lock, flags);
3978 dev_err(hba->dev, "%s: link recovery failed, err %d",
3983 EXPORT_SYMBOL_GPL(ufshcd_link_recovery);
3985 static int ufshcd_uic_hibern8_enter(struct ufs_hba *hba)
3988 struct uic_command uic_cmd = {0};
3989 ktime_t start = ktime_get();
3991 ufshcd_vops_hibern8_notify(hba, UIC_CMD_DME_HIBER_ENTER, PRE_CHANGE);
3993 uic_cmd.command = UIC_CMD_DME_HIBER_ENTER;
3994 ret = ufshcd_uic_pwr_ctrl(hba, &uic_cmd);
3995 trace_ufshcd_profile_hibern8(dev_name(hba->dev), "enter",
3996 ktime_to_us(ktime_sub(ktime_get(), start)), ret);
3999 dev_err(hba->dev, "%s: hibern8 enter failed. ret = %d\n",
4002 ufshcd_vops_hibern8_notify(hba, UIC_CMD_DME_HIBER_ENTER,
4008 int ufshcd_uic_hibern8_exit(struct ufs_hba *hba)
4010 struct uic_command uic_cmd = {0};
4012 ktime_t start = ktime_get();
4014 ufshcd_vops_hibern8_notify(hba, UIC_CMD_DME_HIBER_EXIT, PRE_CHANGE);
4016 uic_cmd.command = UIC_CMD_DME_HIBER_EXIT;
4017 ret = ufshcd_uic_pwr_ctrl(hba, &uic_cmd);
4018 trace_ufshcd_profile_hibern8(dev_name(hba->dev), "exit",
4019 ktime_to_us(ktime_sub(ktime_get(), start)), ret);
4022 dev_err(hba->dev, "%s: hibern8 exit failed. ret = %d\n",
4025 ufshcd_vops_hibern8_notify(hba, UIC_CMD_DME_HIBER_EXIT,
4027 hba->ufs_stats.last_hibern8_exit_tstamp = ktime_get();
4028 hba->ufs_stats.hibern8_exit_cnt++;
4033 EXPORT_SYMBOL_GPL(ufshcd_uic_hibern8_exit);
4035 void ufshcd_auto_hibern8_update(struct ufs_hba *hba, u32 ahit)
4037 unsigned long flags;
4038 bool update = false;
4040 if (!ufshcd_is_auto_hibern8_supported(hba))
4043 spin_lock_irqsave(hba->host->host_lock, flags);
4044 if (hba->ahit != ahit) {
4048 spin_unlock_irqrestore(hba->host->host_lock, flags);
4050 if (update && !pm_runtime_suspended(hba->dev)) {
4051 pm_runtime_get_sync(hba->dev);
4052 ufshcd_hold(hba, false);
4053 ufshcd_auto_hibern8_enable(hba);
4054 ufshcd_release(hba);
4055 pm_runtime_put(hba->dev);
4058 EXPORT_SYMBOL_GPL(ufshcd_auto_hibern8_update);
4060 void ufshcd_auto_hibern8_enable(struct ufs_hba *hba)
4062 unsigned long flags;
4064 if (!ufshcd_is_auto_hibern8_supported(hba))
4067 spin_lock_irqsave(hba->host->host_lock, flags);
4068 ufshcd_writel(hba, hba->ahit, REG_AUTO_HIBERNATE_IDLE_TIMER);
4069 spin_unlock_irqrestore(hba->host->host_lock, flags);
4073 * ufshcd_init_pwr_info - setting the POR (power on reset)
4074 * values in hba power info
4075 * @hba: per-adapter instance
4077 static void ufshcd_init_pwr_info(struct ufs_hba *hba)
4079 hba->pwr_info.gear_rx = UFS_PWM_G1;
4080 hba->pwr_info.gear_tx = UFS_PWM_G1;
4081 hba->pwr_info.lane_rx = 1;
4082 hba->pwr_info.lane_tx = 1;
4083 hba->pwr_info.pwr_rx = SLOWAUTO_MODE;
4084 hba->pwr_info.pwr_tx = SLOWAUTO_MODE;
4085 hba->pwr_info.hs_rate = 0;
4089 * ufshcd_get_max_pwr_mode - reads the max power mode negotiated with device
4090 * @hba: per-adapter instance
4092 static int ufshcd_get_max_pwr_mode(struct ufs_hba *hba)
4094 struct ufs_pa_layer_attr *pwr_info = &hba->max_pwr_info.info;
4096 if (hba->max_pwr_info.is_valid)
4099 pwr_info->pwr_tx = FAST_MODE;
4100 pwr_info->pwr_rx = FAST_MODE;
4101 pwr_info->hs_rate = PA_HS_MODE_B;
4103 /* Get the connected lane count */
4104 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_CONNECTEDRXDATALANES),
4105 &pwr_info->lane_rx);
4106 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_CONNECTEDTXDATALANES),
4107 &pwr_info->lane_tx);
4109 if (!pwr_info->lane_rx || !pwr_info->lane_tx) {
4110 dev_err(hba->dev, "%s: invalid connected lanes value. rx=%d, tx=%d\n",
4118 * First, get the maximum gears of HS speed.
4119 * If a zero value, it means there is no HSGEAR capability.
4120 * Then, get the maximum gears of PWM speed.
4122 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_MAXRXHSGEAR), &pwr_info->gear_rx);
4123 if (!pwr_info->gear_rx) {
4124 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_MAXRXPWMGEAR),
4125 &pwr_info->gear_rx);
4126 if (!pwr_info->gear_rx) {
4127 dev_err(hba->dev, "%s: invalid max pwm rx gear read = %d\n",
4128 __func__, pwr_info->gear_rx);
4131 pwr_info->pwr_rx = SLOW_MODE;
4134 ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_MAXRXHSGEAR),
4135 &pwr_info->gear_tx);
4136 if (!pwr_info->gear_tx) {
4137 ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_MAXRXPWMGEAR),
4138 &pwr_info->gear_tx);
4139 if (!pwr_info->gear_tx) {
4140 dev_err(hba->dev, "%s: invalid max pwm tx gear read = %d\n",
4141 __func__, pwr_info->gear_tx);
4144 pwr_info->pwr_tx = SLOW_MODE;
4147 hba->max_pwr_info.is_valid = true;
4151 static int ufshcd_change_power_mode(struct ufs_hba *hba,
4152 struct ufs_pa_layer_attr *pwr_mode)
4156 /* if already configured to the requested pwr_mode */
4157 if (!hba->force_pmc &&
4158 pwr_mode->gear_rx == hba->pwr_info.gear_rx &&
4159 pwr_mode->gear_tx == hba->pwr_info.gear_tx &&
4160 pwr_mode->lane_rx == hba->pwr_info.lane_rx &&
4161 pwr_mode->lane_tx == hba->pwr_info.lane_tx &&
4162 pwr_mode->pwr_rx == hba->pwr_info.pwr_rx &&
4163 pwr_mode->pwr_tx == hba->pwr_info.pwr_tx &&
4164 pwr_mode->hs_rate == hba->pwr_info.hs_rate) {
4165 dev_dbg(hba->dev, "%s: power already configured\n", __func__);
4170 * Configure attributes for power mode change with below.
4171 * - PA_RXGEAR, PA_ACTIVERXDATALANES, PA_RXTERMINATION,
4172 * - PA_TXGEAR, PA_ACTIVETXDATALANES, PA_TXTERMINATION,
4175 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_RXGEAR), pwr_mode->gear_rx);
4176 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_ACTIVERXDATALANES),
4178 if (pwr_mode->pwr_rx == FASTAUTO_MODE ||
4179 pwr_mode->pwr_rx == FAST_MODE)
4180 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_RXTERMINATION), TRUE);
4182 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_RXTERMINATION), FALSE);
4184 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TXGEAR), pwr_mode->gear_tx);
4185 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_ACTIVETXDATALANES),
4187 if (pwr_mode->pwr_tx == FASTAUTO_MODE ||
4188 pwr_mode->pwr_tx == FAST_MODE)
4189 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TXTERMINATION), TRUE);
4191 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TXTERMINATION), FALSE);
4193 if (pwr_mode->pwr_rx == FASTAUTO_MODE ||
4194 pwr_mode->pwr_tx == FASTAUTO_MODE ||
4195 pwr_mode->pwr_rx == FAST_MODE ||
4196 pwr_mode->pwr_tx == FAST_MODE)
4197 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_HSSERIES),
4200 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_PWRMODEUSERDATA0),
4201 DL_FC0ProtectionTimeOutVal_Default);
4202 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_PWRMODEUSERDATA1),
4203 DL_TC0ReplayTimeOutVal_Default);
4204 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_PWRMODEUSERDATA2),
4205 DL_AFC0ReqTimeOutVal_Default);
4206 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_PWRMODEUSERDATA3),
4207 DL_FC1ProtectionTimeOutVal_Default);
4208 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_PWRMODEUSERDATA4),
4209 DL_TC1ReplayTimeOutVal_Default);
4210 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_PWRMODEUSERDATA5),
4211 DL_AFC1ReqTimeOutVal_Default);
4213 ufshcd_dme_set(hba, UIC_ARG_MIB(DME_LocalFC0ProtectionTimeOutVal),
4214 DL_FC0ProtectionTimeOutVal_Default);
4215 ufshcd_dme_set(hba, UIC_ARG_MIB(DME_LocalTC0ReplayTimeOutVal),
4216 DL_TC0ReplayTimeOutVal_Default);
4217 ufshcd_dme_set(hba, UIC_ARG_MIB(DME_LocalAFC0ReqTimeOutVal),
4218 DL_AFC0ReqTimeOutVal_Default);
4220 ret = ufshcd_uic_change_pwr_mode(hba, pwr_mode->pwr_rx << 4
4221 | pwr_mode->pwr_tx);
4225 "%s: power mode change failed %d\n", __func__, ret);
4227 ufshcd_vops_pwr_change_notify(hba, POST_CHANGE, NULL,
4230 memcpy(&hba->pwr_info, pwr_mode,
4231 sizeof(struct ufs_pa_layer_attr));
4238 * ufshcd_config_pwr_mode - configure a new power mode
4239 * @hba: per-adapter instance
4240 * @desired_pwr_mode: desired power configuration
4242 int ufshcd_config_pwr_mode(struct ufs_hba *hba,
4243 struct ufs_pa_layer_attr *desired_pwr_mode)
4245 struct ufs_pa_layer_attr final_params = { 0 };
4248 ret = ufshcd_vops_pwr_change_notify(hba, PRE_CHANGE,
4249 desired_pwr_mode, &final_params);
4252 memcpy(&final_params, desired_pwr_mode, sizeof(final_params));
4254 ret = ufshcd_change_power_mode(hba, &final_params);
4258 EXPORT_SYMBOL_GPL(ufshcd_config_pwr_mode);
4261 * ufshcd_complete_dev_init() - checks device readiness
4262 * @hba: per-adapter instance
4264 * Set fDeviceInit flag and poll until device toggles it.
4266 static int ufshcd_complete_dev_init(struct ufs_hba *hba)
4269 bool flag_res = true;
4272 err = ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_SET_FLAG,
4273 QUERY_FLAG_IDN_FDEVICEINIT, 0, NULL);
4276 "%s setting fDeviceInit flag failed with error %d\n",
4281 /* Poll fDeviceInit flag to be cleared */
4282 timeout = ktime_add_ms(ktime_get(), FDEVICEINIT_COMPL_TIMEOUT);
4284 err = ufshcd_query_flag(hba, UPIU_QUERY_OPCODE_READ_FLAG,
4285 QUERY_FLAG_IDN_FDEVICEINIT, 0, &flag_res);
4288 usleep_range(5000, 10000);
4289 } while (ktime_before(ktime_get(), timeout));
4293 "%s reading fDeviceInit flag failed with error %d\n",
4295 } else if (flag_res) {
4297 "%s fDeviceInit was not cleared by the device\n",
4306 * ufshcd_make_hba_operational - Make UFS controller operational
4307 * @hba: per adapter instance
4309 * To bring UFS host controller to operational state,
4310 * 1. Enable required interrupts
4311 * 2. Configure interrupt aggregation
4312 * 3. Program UTRL and UTMRL base address
4313 * 4. Configure run-stop-registers
4315 * Returns 0 on success, non-zero value on failure
4317 int ufshcd_make_hba_operational(struct ufs_hba *hba)
4322 /* Enable required interrupts */
4323 ufshcd_enable_intr(hba, UFSHCD_ENABLE_INTRS);
4325 /* Configure interrupt aggregation */
4326 if (ufshcd_is_intr_aggr_allowed(hba))
4327 ufshcd_config_intr_aggr(hba, hba->nutrs - 1, INT_AGGR_DEF_TO);
4329 ufshcd_disable_intr_aggr(hba);
4331 /* Configure UTRL and UTMRL base address registers */
4332 ufshcd_writel(hba, lower_32_bits(hba->utrdl_dma_addr),
4333 REG_UTP_TRANSFER_REQ_LIST_BASE_L);
4334 ufshcd_writel(hba, upper_32_bits(hba->utrdl_dma_addr),
4335 REG_UTP_TRANSFER_REQ_LIST_BASE_H);
4336 ufshcd_writel(hba, lower_32_bits(hba->utmrdl_dma_addr),
4337 REG_UTP_TASK_REQ_LIST_BASE_L);
4338 ufshcd_writel(hba, upper_32_bits(hba->utmrdl_dma_addr),
4339 REG_UTP_TASK_REQ_LIST_BASE_H);
4342 * Make sure base address and interrupt setup are updated before
4343 * enabling the run/stop registers below.
4348 * UCRDY, UTMRLDY and UTRLRDY bits must be 1
4350 reg = ufshcd_readl(hba, REG_CONTROLLER_STATUS);
4351 if (!(ufshcd_get_lists_status(reg))) {
4352 ufshcd_enable_run_stop_reg(hba);
4355 "Host controller not ready to process requests");
4361 EXPORT_SYMBOL_GPL(ufshcd_make_hba_operational);
4364 * ufshcd_hba_stop - Send controller to reset state
4365 * @hba: per adapter instance
4367 static inline void ufshcd_hba_stop(struct ufs_hba *hba)
4369 unsigned long flags;
4373 * Obtain the host lock to prevent that the controller is disabled
4374 * while the UFS interrupt handler is active on another CPU.
4376 spin_lock_irqsave(hba->host->host_lock, flags);
4377 ufshcd_writel(hba, CONTROLLER_DISABLE, REG_CONTROLLER_ENABLE);
4378 spin_unlock_irqrestore(hba->host->host_lock, flags);
4380 err = ufshcd_wait_for_register(hba, REG_CONTROLLER_ENABLE,
4381 CONTROLLER_ENABLE, CONTROLLER_DISABLE,
4384 dev_err(hba->dev, "%s: Controller disable failed\n", __func__);
4388 * ufshcd_hba_execute_hce - initialize the controller
4389 * @hba: per adapter instance
4391 * The controller resets itself and controller firmware initialization
4392 * sequence kicks off. When controller is ready it will set
4393 * the Host Controller Enable bit to 1.
4395 * Returns 0 on success, non-zero value on failure
4397 static int ufshcd_hba_execute_hce(struct ufs_hba *hba)
4399 int retry_outer = 3;
4403 if (!ufshcd_is_hba_active(hba))
4404 /* change controller state to "reset state" */
4405 ufshcd_hba_stop(hba);
4407 /* UniPro link is disabled at this point */
4408 ufshcd_set_link_off(hba);
4410 ufshcd_vops_hce_enable_notify(hba, PRE_CHANGE);
4412 /* start controller initialization sequence */
4413 ufshcd_hba_start(hba);
4416 * To initialize a UFS host controller HCE bit must be set to 1.
4417 * During initialization the HCE bit value changes from 1->0->1.
4418 * When the host controller completes initialization sequence
4419 * it sets the value of HCE bit to 1. The same HCE bit is read back
4420 * to check if the controller has completed initialization sequence.
4421 * So without this delay the value HCE = 1, set in the previous
4422 * instruction might be read back.
4423 * This delay can be changed based on the controller.
4425 ufshcd_delay_us(hba->vps->hba_enable_delay_us, 100);
4427 /* wait for the host controller to complete initialization */
4429 while (ufshcd_is_hba_active(hba)) {
4434 "Controller enable failed\n");
4441 usleep_range(1000, 1100);
4444 /* enable UIC related interrupts */
4445 ufshcd_enable_intr(hba, UFSHCD_UIC_MASK);
4447 ufshcd_vops_hce_enable_notify(hba, POST_CHANGE);
4452 int ufshcd_hba_enable(struct ufs_hba *hba)
4456 if (hba->quirks & UFSHCI_QUIRK_BROKEN_HCE) {
4457 ufshcd_set_link_off(hba);
4458 ufshcd_vops_hce_enable_notify(hba, PRE_CHANGE);
4460 /* enable UIC related interrupts */
4461 ufshcd_enable_intr(hba, UFSHCD_UIC_MASK);
4462 ret = ufshcd_dme_reset(hba);
4464 ret = ufshcd_dme_enable(hba);
4466 ufshcd_vops_hce_enable_notify(hba, POST_CHANGE);
4469 "Host controller enable failed with non-hce\n");
4472 ret = ufshcd_hba_execute_hce(hba);
4477 EXPORT_SYMBOL_GPL(ufshcd_hba_enable);
4479 static int ufshcd_disable_tx_lcc(struct ufs_hba *hba, bool peer)
4481 int tx_lanes = 0, i, err = 0;
4484 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_CONNECTEDTXDATALANES),
4487 ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_CONNECTEDTXDATALANES),
4489 for (i = 0; i < tx_lanes; i++) {
4491 err = ufshcd_dme_set(hba,
4492 UIC_ARG_MIB_SEL(TX_LCC_ENABLE,
4493 UIC_ARG_MPHY_TX_GEN_SEL_INDEX(i)),
4496 err = ufshcd_dme_peer_set(hba,
4497 UIC_ARG_MIB_SEL(TX_LCC_ENABLE,
4498 UIC_ARG_MPHY_TX_GEN_SEL_INDEX(i)),
4501 dev_err(hba->dev, "%s: TX LCC Disable failed, peer = %d, lane = %d, err = %d",
4502 __func__, peer, i, err);
4510 static inline int ufshcd_disable_device_tx_lcc(struct ufs_hba *hba)
4512 return ufshcd_disable_tx_lcc(hba, true);
4515 void ufshcd_update_evt_hist(struct ufs_hba *hba, u32 id, u32 val)
4517 struct ufs_event_hist *e;
4519 if (id >= UFS_EVT_CNT)
4522 e = &hba->ufs_stats.event[id];
4523 e->val[e->pos] = val;
4524 e->tstamp[e->pos] = ktime_get();
4525 e->pos = (e->pos + 1) % UFS_EVENT_HIST_LENGTH;
4527 ufshcd_vops_event_notify(hba, id, &val);
4529 EXPORT_SYMBOL_GPL(ufshcd_update_evt_hist);
4532 * ufshcd_link_startup - Initialize unipro link startup
4533 * @hba: per adapter instance
4535 * Returns 0 for success, non-zero in case of failure
4537 static int ufshcd_link_startup(struct ufs_hba *hba)
4540 int retries = DME_LINKSTARTUP_RETRIES;
4541 bool link_startup_again = false;
4544 * If UFS device isn't active then we will have to issue link startup
4545 * 2 times to make sure the device state move to active.
4547 if (!ufshcd_is_ufs_dev_active(hba))
4548 link_startup_again = true;
4552 ufshcd_vops_link_startup_notify(hba, PRE_CHANGE);
4554 ret = ufshcd_dme_link_startup(hba);
4556 /* check if device is detected by inter-connect layer */
4557 if (!ret && !ufshcd_is_device_present(hba)) {
4558 ufshcd_update_evt_hist(hba,
4559 UFS_EVT_LINK_STARTUP_FAIL,
4561 dev_err(hba->dev, "%s: Device not present\n", __func__);
4567 * DME link lost indication is only received when link is up,
4568 * but we can't be sure if the link is up until link startup
4569 * succeeds. So reset the local Uni-Pro and try again.
4571 if (ret && ufshcd_hba_enable(hba)) {
4572 ufshcd_update_evt_hist(hba,
4573 UFS_EVT_LINK_STARTUP_FAIL,
4577 } while (ret && retries--);
4580 /* failed to get the link up... retire */
4581 ufshcd_update_evt_hist(hba,
4582 UFS_EVT_LINK_STARTUP_FAIL,
4587 if (link_startup_again) {
4588 link_startup_again = false;
4589 retries = DME_LINKSTARTUP_RETRIES;
4593 /* Mark that link is up in PWM-G1, 1-lane, SLOW-AUTO mode */
4594 ufshcd_init_pwr_info(hba);
4595 ufshcd_print_pwr_info(hba);
4597 if (hba->quirks & UFSHCD_QUIRK_BROKEN_LCC) {
4598 ret = ufshcd_disable_device_tx_lcc(hba);
4603 /* Include any host controller configuration via UIC commands */
4604 ret = ufshcd_vops_link_startup_notify(hba, POST_CHANGE);
4608 /* Clear UECPA once due to LINERESET has happened during LINK_STARTUP */
4609 ufshcd_readl(hba, REG_UIC_ERROR_CODE_PHY_ADAPTER_LAYER);
4610 ret = ufshcd_make_hba_operational(hba);
4613 dev_err(hba->dev, "link startup failed %d\n", ret);
4614 ufshcd_print_host_state(hba);
4615 ufshcd_print_pwr_info(hba);
4616 ufshcd_print_evt_hist(hba);
4622 * ufshcd_verify_dev_init() - Verify device initialization
4623 * @hba: per-adapter instance
4625 * Send NOP OUT UPIU and wait for NOP IN response to check whether the
4626 * device Transport Protocol (UTP) layer is ready after a reset.
4627 * If the UTP layer at the device side is not initialized, it may
4628 * not respond with NOP IN UPIU within timeout of %NOP_OUT_TIMEOUT
4629 * and we retry sending NOP OUT for %NOP_OUT_RETRIES iterations.
4631 static int ufshcd_verify_dev_init(struct ufs_hba *hba)
4636 ufshcd_hold(hba, false);
4637 mutex_lock(&hba->dev_cmd.lock);
4638 for (retries = NOP_OUT_RETRIES; retries > 0; retries--) {
4639 err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_NOP,
4642 if (!err || err == -ETIMEDOUT)
4645 dev_dbg(hba->dev, "%s: error %d retrying\n", __func__, err);
4647 mutex_unlock(&hba->dev_cmd.lock);
4648 ufshcd_release(hba);
4651 dev_err(hba->dev, "%s: NOP OUT failed %d\n", __func__, err);
4656 * ufshcd_set_queue_depth - set lun queue depth
4657 * @sdev: pointer to SCSI device
4659 * Read bLUQueueDepth value and activate scsi tagged command
4660 * queueing. For WLUN, queue depth is set to 1. For best-effort
4661 * cases (bLUQueueDepth = 0) the queue depth is set to a maximum
4662 * value that host can queue.
4664 static void ufshcd_set_queue_depth(struct scsi_device *sdev)
4668 struct ufs_hba *hba;
4670 hba = shost_priv(sdev->host);
4672 lun_qdepth = hba->nutrs;
4673 ret = ufshcd_read_unit_desc_param(hba,
4674 ufshcd_scsi_to_upiu_lun(sdev->lun),
4675 UNIT_DESC_PARAM_LU_Q_DEPTH,
4677 sizeof(lun_qdepth));
4679 /* Some WLUN doesn't support unit descriptor */
4680 if (ret == -EOPNOTSUPP)
4682 else if (!lun_qdepth)
4683 /* eventually, we can figure out the real queue depth */
4684 lun_qdepth = hba->nutrs;
4686 lun_qdepth = min_t(int, lun_qdepth, hba->nutrs);
4688 dev_dbg(hba->dev, "%s: activate tcq with queue depth %d\n",
4689 __func__, lun_qdepth);
4690 scsi_change_queue_depth(sdev, lun_qdepth);
4694 * ufshcd_get_lu_wp - returns the "b_lu_write_protect" from UNIT DESCRIPTOR
4695 * @hba: per-adapter instance
4696 * @lun: UFS device lun id
4697 * @b_lu_write_protect: pointer to buffer to hold the LU's write protect info
4699 * Returns 0 in case of success and b_lu_write_protect status would be returned
4700 * @b_lu_write_protect parameter.
4701 * Returns -ENOTSUPP if reading b_lu_write_protect is not supported.
4702 * Returns -EINVAL in case of invalid parameters passed to this function.
4704 static int ufshcd_get_lu_wp(struct ufs_hba *hba,
4706 u8 *b_lu_write_protect)
4710 if (!b_lu_write_protect)
4713 * According to UFS device spec, RPMB LU can't be write
4714 * protected so skip reading bLUWriteProtect parameter for
4715 * it. For other W-LUs, UNIT DESCRIPTOR is not available.
4717 else if (lun >= hba->dev_info.max_lu_supported)
4720 ret = ufshcd_read_unit_desc_param(hba,
4722 UNIT_DESC_PARAM_LU_WR_PROTECT,
4724 sizeof(*b_lu_write_protect));
4729 * ufshcd_get_lu_power_on_wp_status - get LU's power on write protect
4731 * @hba: per-adapter instance
4732 * @sdev: pointer to SCSI device
4735 static inline void ufshcd_get_lu_power_on_wp_status(struct ufs_hba *hba,
4736 struct scsi_device *sdev)
4738 if (hba->dev_info.f_power_on_wp_en &&
4739 !hba->dev_info.is_lu_power_on_wp) {
4740 u8 b_lu_write_protect;
4742 if (!ufshcd_get_lu_wp(hba, ufshcd_scsi_to_upiu_lun(sdev->lun),
4743 &b_lu_write_protect) &&
4744 (b_lu_write_protect == UFS_LU_POWER_ON_WP))
4745 hba->dev_info.is_lu_power_on_wp = true;
4750 * ufshcd_slave_alloc - handle initial SCSI device configurations
4751 * @sdev: pointer to SCSI device
4755 static int ufshcd_slave_alloc(struct scsi_device *sdev)
4757 struct ufs_hba *hba;
4759 hba = shost_priv(sdev->host);
4761 /* Mode sense(6) is not supported by UFS, so use Mode sense(10) */
4762 sdev->use_10_for_ms = 1;
4764 /* DBD field should be set to 1 in mode sense(10) */
4765 sdev->set_dbd_for_ms = 1;
4767 /* allow SCSI layer to restart the device in case of errors */
4768 sdev->allow_restart = 1;
4770 /* REPORT SUPPORTED OPERATION CODES is not supported */
4771 sdev->no_report_opcodes = 1;
4773 /* WRITE_SAME command is not supported */
4774 sdev->no_write_same = 1;
4776 ufshcd_set_queue_depth(sdev);
4778 ufshcd_get_lu_power_on_wp_status(hba, sdev);
4784 * ufshcd_change_queue_depth - change queue depth
4785 * @sdev: pointer to SCSI device
4786 * @depth: required depth to set
4788 * Change queue depth and make sure the max. limits are not crossed.
4790 static int ufshcd_change_queue_depth(struct scsi_device *sdev, int depth)
4792 struct ufs_hba *hba = shost_priv(sdev->host);
4794 if (depth > hba->nutrs)
4796 return scsi_change_queue_depth(sdev, depth);
4800 * ufshcd_slave_configure - adjust SCSI device configurations
4801 * @sdev: pointer to SCSI device
4803 static int ufshcd_slave_configure(struct scsi_device *sdev)
4805 struct ufs_hba *hba = shost_priv(sdev->host);
4806 struct request_queue *q = sdev->request_queue;
4808 blk_queue_update_dma_pad(q, PRDT_DATA_BYTE_COUNT_PAD - 1);
4810 if (ufshcd_is_rpm_autosuspend_allowed(hba))
4811 sdev->rpm_autosuspend = 1;
4813 ufshcd_crypto_setup_rq_keyslot_manager(hba, q);
4819 * ufshcd_slave_destroy - remove SCSI device configurations
4820 * @sdev: pointer to SCSI device
4822 static void ufshcd_slave_destroy(struct scsi_device *sdev)
4824 struct ufs_hba *hba;
4826 hba = shost_priv(sdev->host);
4827 /* Drop the reference as it won't be needed anymore */
4828 if (ufshcd_scsi_to_upiu_lun(sdev->lun) == UFS_UPIU_UFS_DEVICE_WLUN) {
4829 unsigned long flags;
4831 spin_lock_irqsave(hba->host->host_lock, flags);
4832 hba->sdev_ufs_device = NULL;
4833 spin_unlock_irqrestore(hba->host->host_lock, flags);
4838 * ufshcd_scsi_cmd_status - Update SCSI command result based on SCSI status
4839 * @lrbp: pointer to local reference block of completed command
4840 * @scsi_status: SCSI command status
4842 * Returns value base on SCSI command status
4845 ufshcd_scsi_cmd_status(struct ufshcd_lrb *lrbp, int scsi_status)
4849 switch (scsi_status) {
4850 case SAM_STAT_CHECK_CONDITION:
4851 ufshcd_copy_sense_data(lrbp);
4854 result |= DID_OK << 16 |
4855 COMMAND_COMPLETE << 8 |
4858 case SAM_STAT_TASK_SET_FULL:
4860 case SAM_STAT_TASK_ABORTED:
4861 ufshcd_copy_sense_data(lrbp);
4862 result |= scsi_status;
4865 result |= DID_ERROR << 16;
4867 } /* end of switch */
4873 * ufshcd_transfer_rsp_status - Get overall status of the response
4874 * @hba: per adapter instance
4875 * @lrbp: pointer to local reference block of completed command
4877 * Returns result of the command to notify SCSI midlayer
4880 ufshcd_transfer_rsp_status(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
4886 /* overall command status of utrd */
4887 ocs = ufshcd_get_tr_ocs(lrbp);
4889 if (hba->quirks & UFSHCD_QUIRK_BROKEN_OCS_FATAL_ERROR) {
4890 if (be32_to_cpu(lrbp->ucd_rsp_ptr->header.dword_1) &
4891 MASK_RSP_UPIU_RESULT)
4897 result = ufshcd_get_req_rsp(lrbp->ucd_rsp_ptr);
4898 hba->ufs_stats.last_hibern8_exit_tstamp = ktime_set(0, 0);
4900 case UPIU_TRANSACTION_RESPONSE:
4902 * get the response UPIU result to extract
4903 * the SCSI command status
4905 result = ufshcd_get_rsp_upiu_result(lrbp->ucd_rsp_ptr);
4908 * get the result based on SCSI status response
4909 * to notify the SCSI midlayer of the command status
4911 scsi_status = result & MASK_SCSI_STATUS;
4912 result = ufshcd_scsi_cmd_status(lrbp, scsi_status);
4915 * Currently we are only supporting BKOPs exception
4916 * events hence we can ignore BKOPs exception event
4917 * during power management callbacks. BKOPs exception
4918 * event is not expected to be raised in runtime suspend
4919 * callback as it allows the urgent bkops.
4920 * During system suspend, we are anyway forcefully
4921 * disabling the bkops and if urgent bkops is needed
4922 * it will be enabled on system resume. Long term
4923 * solution could be to abort the system suspend if
4924 * UFS device needs urgent BKOPs.
4926 if (!hba->pm_op_in_progress &&
4927 ufshcd_is_exception_event(lrbp->ucd_rsp_ptr) &&
4928 schedule_work(&hba->eeh_work)) {
4930 * Prevent suspend once eeh_work is scheduled
4931 * to avoid deadlock between ufshcd_suspend
4932 * and exception event handler.
4934 pm_runtime_get_noresume(hba->dev);
4937 case UPIU_TRANSACTION_REJECT_UPIU:
4938 /* TODO: handle Reject UPIU Response */
4939 result = DID_ERROR << 16;
4941 "Reject UPIU not fully implemented\n");
4945 "Unexpected request response code = %x\n",
4947 result = DID_ERROR << 16;
4952 result |= DID_ABORT << 16;
4954 case OCS_INVALID_COMMAND_STATUS:
4955 result |= DID_REQUEUE << 16;
4957 case OCS_INVALID_CMD_TABLE_ATTR:
4958 case OCS_INVALID_PRDT_ATTR:
4959 case OCS_MISMATCH_DATA_BUF_SIZE:
4960 case OCS_MISMATCH_RESP_UPIU_SIZE:
4961 case OCS_PEER_COMM_FAILURE:
4962 case OCS_FATAL_ERROR:
4963 case OCS_DEVICE_FATAL_ERROR:
4964 case OCS_INVALID_CRYPTO_CONFIG:
4965 case OCS_GENERAL_CRYPTO_ERROR:
4967 result |= DID_ERROR << 16;
4969 "OCS error from controller = %x for tag %d\n",
4970 ocs, lrbp->task_tag);
4971 ufshcd_print_evt_hist(hba);
4972 ufshcd_print_host_state(hba);
4974 } /* end of switch */
4976 if ((host_byte(result) != DID_OK) && !hba->silence_err_logs)
4977 ufshcd_print_trs(hba, 1 << lrbp->task_tag, true);
4982 * ufshcd_uic_cmd_compl - handle completion of uic command
4983 * @hba: per adapter instance
4984 * @intr_status: interrupt status generated by the controller
4987 * IRQ_HANDLED - If interrupt is valid
4988 * IRQ_NONE - If invalid interrupt
4990 static irqreturn_t ufshcd_uic_cmd_compl(struct ufs_hba *hba, u32 intr_status)
4992 irqreturn_t retval = IRQ_NONE;
4994 if ((intr_status & UIC_COMMAND_COMPL) && hba->active_uic_cmd) {
4995 hba->active_uic_cmd->argument2 |=
4996 ufshcd_get_uic_cmd_result(hba);
4997 hba->active_uic_cmd->argument3 =
4998 ufshcd_get_dme_attr_val(hba);
4999 if (!hba->uic_async_done)
5000 hba->active_uic_cmd->cmd_active = 0;
5001 complete(&hba->active_uic_cmd->done);
5002 retval = IRQ_HANDLED;
5005 if ((intr_status & UFSHCD_UIC_PWR_MASK) && hba->uic_async_done) {
5006 hba->active_uic_cmd->cmd_active = 0;
5007 complete(hba->uic_async_done);
5008 retval = IRQ_HANDLED;
5011 if (retval == IRQ_HANDLED)
5012 ufshcd_add_uic_command_trace(hba, hba->active_uic_cmd,
5018 * __ufshcd_transfer_req_compl - handle SCSI and query command completion
5019 * @hba: per adapter instance
5020 * @completed_reqs: requests to complete
5022 static void __ufshcd_transfer_req_compl(struct ufs_hba *hba,
5023 unsigned long completed_reqs)
5025 struct ufshcd_lrb *lrbp;
5026 struct scsi_cmnd *cmd;
5029 bool update_scaling = false;
5031 for_each_set_bit(index, &completed_reqs, hba->nutrs) {
5032 lrbp = &hba->lrb[index];
5033 lrbp->in_use = false;
5034 lrbp->compl_time_stamp = ktime_get();
5037 ufshcd_add_command_trace(hba, index, "complete");
5038 result = ufshcd_transfer_rsp_status(hba, lrbp);
5039 scsi_dma_unmap(cmd);
5040 cmd->result = result;
5041 /* Mark completed command as NULL in LRB */
5043 /* Do not touch lrbp after scsi done */
5044 cmd->scsi_done(cmd);
5045 __ufshcd_release(hba);
5046 update_scaling = true;
5047 } else if (lrbp->command_type == UTP_CMD_TYPE_DEV_MANAGE ||
5048 lrbp->command_type == UTP_CMD_TYPE_UFS_STORAGE) {
5049 if (hba->dev_cmd.complete) {
5050 ufshcd_add_command_trace(hba, index,
5052 complete(hba->dev_cmd.complete);
5053 update_scaling = true;
5056 if (ufshcd_is_clkscaling_supported(hba) && update_scaling)
5057 hba->clk_scaling.active_reqs--;
5060 /* clear corresponding bits of completed commands */
5061 hba->outstanding_reqs ^= completed_reqs;
5063 ufshcd_clk_scaling_update_busy(hba);
5067 * ufshcd_transfer_req_compl - handle SCSI and query command completion
5068 * @hba: per adapter instance
5071 * IRQ_HANDLED - If interrupt is valid
5072 * IRQ_NONE - If invalid interrupt
5074 static irqreturn_t ufshcd_transfer_req_compl(struct ufs_hba *hba)
5076 unsigned long completed_reqs;
5079 /* Resetting interrupt aggregation counters first and reading the
5080 * DOOR_BELL afterward allows us to handle all the completed requests.
5081 * In order to prevent other interrupts starvation the DB is read once
5082 * after reset. The down side of this solution is the possibility of
5083 * false interrupt if device completes another request after resetting
5084 * aggregation and before reading the DB.
5086 if (ufshcd_is_intr_aggr_allowed(hba) &&
5087 !(hba->quirks & UFSHCI_QUIRK_SKIP_RESET_INTR_AGGR))
5088 ufshcd_reset_intr_aggr(hba);
5090 tr_doorbell = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
5091 completed_reqs = tr_doorbell ^ hba->outstanding_reqs;
5093 if (completed_reqs) {
5094 __ufshcd_transfer_req_compl(hba, completed_reqs);
5102 * ufshcd_disable_ee - disable exception event
5103 * @hba: per-adapter instance
5104 * @mask: exception event to disable
5106 * Disables exception event in the device so that the EVENT_ALERT
5109 * Returns zero on success, non-zero error value on failure.
5111 static int ufshcd_disable_ee(struct ufs_hba *hba, u16 mask)
5116 if (!(hba->ee_ctrl_mask & mask))
5119 val = hba->ee_ctrl_mask & ~mask;
5120 val &= MASK_EE_STATUS;
5121 err = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_WRITE_ATTR,
5122 QUERY_ATTR_IDN_EE_CONTROL, 0, 0, &val);
5124 hba->ee_ctrl_mask &= ~mask;
5130 * ufshcd_enable_ee - enable exception event
5131 * @hba: per-adapter instance
5132 * @mask: exception event to enable
5134 * Enable corresponding exception event in the device to allow
5135 * device to alert host in critical scenarios.
5137 * Returns zero on success, non-zero error value on failure.
5139 static int ufshcd_enable_ee(struct ufs_hba *hba, u16 mask)
5144 if (hba->ee_ctrl_mask & mask)
5147 val = hba->ee_ctrl_mask | mask;
5148 val &= MASK_EE_STATUS;
5149 err = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_WRITE_ATTR,
5150 QUERY_ATTR_IDN_EE_CONTROL, 0, 0, &val);
5152 hba->ee_ctrl_mask |= mask;
5158 * ufshcd_enable_auto_bkops - Allow device managed BKOPS
5159 * @hba: per-adapter instance
5161 * Allow device to manage background operations on its own. Enabling
5162 * this might lead to inconsistent latencies during normal data transfers
5163 * as the device is allowed to manage its own way of handling background
5166 * Returns zero on success, non-zero on failure.
5168 static int ufshcd_enable_auto_bkops(struct ufs_hba *hba)
5172 if (hba->auto_bkops_enabled)
5175 err = ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_SET_FLAG,
5176 QUERY_FLAG_IDN_BKOPS_EN, 0, NULL);
5178 dev_err(hba->dev, "%s: failed to enable bkops %d\n",
5183 hba->auto_bkops_enabled = true;
5184 trace_ufshcd_auto_bkops_state(dev_name(hba->dev), "Enabled");
5186 /* No need of URGENT_BKOPS exception from the device */
5187 err = ufshcd_disable_ee(hba, MASK_EE_URGENT_BKOPS);
5189 dev_err(hba->dev, "%s: failed to disable exception event %d\n",
5196 * ufshcd_disable_auto_bkops - block device in doing background operations
5197 * @hba: per-adapter instance
5199 * Disabling background operations improves command response latency but
5200 * has drawback of device moving into critical state where the device is
5201 * not-operable. Make sure to call ufshcd_enable_auto_bkops() whenever the
5202 * host is idle so that BKOPS are managed effectively without any negative
5205 * Returns zero on success, non-zero on failure.
5207 static int ufshcd_disable_auto_bkops(struct ufs_hba *hba)
5211 if (!hba->auto_bkops_enabled)
5215 * If host assisted BKOPs is to be enabled, make sure
5216 * urgent bkops exception is allowed.
5218 err = ufshcd_enable_ee(hba, MASK_EE_URGENT_BKOPS);
5220 dev_err(hba->dev, "%s: failed to enable exception event %d\n",
5225 err = ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_CLEAR_FLAG,
5226 QUERY_FLAG_IDN_BKOPS_EN, 0, NULL);
5228 dev_err(hba->dev, "%s: failed to disable bkops %d\n",
5230 ufshcd_disable_ee(hba, MASK_EE_URGENT_BKOPS);
5234 hba->auto_bkops_enabled = false;
5235 trace_ufshcd_auto_bkops_state(dev_name(hba->dev), "Disabled");
5236 hba->is_urgent_bkops_lvl_checked = false;
5242 * ufshcd_force_reset_auto_bkops - force reset auto bkops state
5243 * @hba: per adapter instance
5245 * After a device reset the device may toggle the BKOPS_EN flag
5246 * to default value. The s/w tracking variables should be updated
5247 * as well. This function would change the auto-bkops state based on
5248 * UFSHCD_CAP_KEEP_AUTO_BKOPS_ENABLED_EXCEPT_SUSPEND.
5250 static void ufshcd_force_reset_auto_bkops(struct ufs_hba *hba)
5252 if (ufshcd_keep_autobkops_enabled_except_suspend(hba)) {
5253 hba->auto_bkops_enabled = false;
5254 hba->ee_ctrl_mask |= MASK_EE_URGENT_BKOPS;
5255 ufshcd_enable_auto_bkops(hba);
5257 hba->auto_bkops_enabled = true;
5258 hba->ee_ctrl_mask &= ~MASK_EE_URGENT_BKOPS;
5259 ufshcd_disable_auto_bkops(hba);
5261 hba->urgent_bkops_lvl = BKOPS_STATUS_PERF_IMPACT;
5262 hba->is_urgent_bkops_lvl_checked = false;
5265 static inline int ufshcd_get_bkops_status(struct ufs_hba *hba, u32 *status)
5267 return ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
5268 QUERY_ATTR_IDN_BKOPS_STATUS, 0, 0, status);
5272 * ufshcd_bkops_ctrl - control the auto bkops based on current bkops status
5273 * @hba: per-adapter instance
5274 * @status: bkops_status value
5276 * Read the bkops_status from the UFS device and Enable fBackgroundOpsEn
5277 * flag in the device to permit background operations if the device
5278 * bkops_status is greater than or equal to "status" argument passed to
5279 * this function, disable otherwise.
5281 * Returns 0 for success, non-zero in case of failure.
5283 * NOTE: Caller of this function can check the "hba->auto_bkops_enabled" flag
5284 * to know whether auto bkops is enabled or disabled after this function
5285 * returns control to it.
5287 static int ufshcd_bkops_ctrl(struct ufs_hba *hba,
5288 enum bkops_status status)
5291 u32 curr_status = 0;
5293 err = ufshcd_get_bkops_status(hba, &curr_status);
5295 dev_err(hba->dev, "%s: failed to get BKOPS status %d\n",
5298 } else if (curr_status > BKOPS_STATUS_MAX) {
5299 dev_err(hba->dev, "%s: invalid BKOPS status %d\n",
5300 __func__, curr_status);
5305 if (curr_status >= status)
5306 err = ufshcd_enable_auto_bkops(hba);
5308 err = ufshcd_disable_auto_bkops(hba);
5314 * ufshcd_urgent_bkops - handle urgent bkops exception event
5315 * @hba: per-adapter instance
5317 * Enable fBackgroundOpsEn flag in the device to permit background
5320 * If BKOPs is enabled, this function returns 0, 1 if the bkops in not enabled
5321 * and negative error value for any other failure.
5323 static int ufshcd_urgent_bkops(struct ufs_hba *hba)
5325 return ufshcd_bkops_ctrl(hba, hba->urgent_bkops_lvl);
5328 static inline int ufshcd_get_ee_status(struct ufs_hba *hba, u32 *status)
5330 return ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
5331 QUERY_ATTR_IDN_EE_STATUS, 0, 0, status);
5334 static void ufshcd_bkops_exception_event_handler(struct ufs_hba *hba)
5337 u32 curr_status = 0;
5339 if (hba->is_urgent_bkops_lvl_checked)
5340 goto enable_auto_bkops;
5342 err = ufshcd_get_bkops_status(hba, &curr_status);
5344 dev_err(hba->dev, "%s: failed to get BKOPS status %d\n",
5350 * We are seeing that some devices are raising the urgent bkops
5351 * exception events even when BKOPS status doesn't indicate performace
5352 * impacted or critical. Handle these device by determining their urgent
5353 * bkops status at runtime.
5355 if (curr_status < BKOPS_STATUS_PERF_IMPACT) {
5356 dev_err(hba->dev, "%s: device raised urgent BKOPS exception for bkops status %d\n",
5357 __func__, curr_status);
5358 /* update the current status as the urgent bkops level */
5359 hba->urgent_bkops_lvl = curr_status;
5360 hba->is_urgent_bkops_lvl_checked = true;
5364 err = ufshcd_enable_auto_bkops(hba);
5367 dev_err(hba->dev, "%s: failed to handle urgent bkops %d\n",
5371 static int ufshcd_wb_ctrl(struct ufs_hba *hba, bool enable)
5375 enum query_opcode opcode;
5377 if (!ufshcd_is_wb_allowed(hba))
5380 if (!(enable ^ hba->wb_enabled))
5383 opcode = UPIU_QUERY_OPCODE_SET_FLAG;
5385 opcode = UPIU_QUERY_OPCODE_CLEAR_FLAG;
5387 index = ufshcd_wb_get_query_index(hba);
5388 ret = ufshcd_query_flag_retry(hba, opcode,
5389 QUERY_FLAG_IDN_WB_EN, index, NULL);
5391 dev_err(hba->dev, "%s write booster %s failed %d\n",
5392 __func__, enable ? "enable" : "disable", ret);
5396 hba->wb_enabled = enable;
5397 dev_dbg(hba->dev, "%s write booster %s %d\n",
5398 __func__, enable ? "enable" : "disable", ret);
5403 static int ufshcd_wb_toggle_flush_during_h8(struct ufs_hba *hba, bool set)
5409 val = UPIU_QUERY_OPCODE_SET_FLAG;
5411 val = UPIU_QUERY_OPCODE_CLEAR_FLAG;
5413 index = ufshcd_wb_get_query_index(hba);
5414 return ufshcd_query_flag_retry(hba, val,
5415 QUERY_FLAG_IDN_WB_BUFF_FLUSH_DURING_HIBERN8,
5419 static inline void ufshcd_wb_toggle_flush(struct ufs_hba *hba, bool enable)
5421 if (hba->quirks & UFSHCI_QUIRK_SKIP_MANUAL_WB_FLUSH_CTRL)
5425 ufshcd_wb_buf_flush_enable(hba);
5427 ufshcd_wb_buf_flush_disable(hba);
5431 static int ufshcd_wb_buf_flush_enable(struct ufs_hba *hba)
5436 if (!ufshcd_is_wb_allowed(hba) || hba->wb_buf_flush_enabled)
5439 index = ufshcd_wb_get_query_index(hba);
5440 ret = ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_SET_FLAG,
5441 QUERY_FLAG_IDN_WB_BUFF_FLUSH_EN,
5444 dev_err(hba->dev, "%s WB - buf flush enable failed %d\n",
5447 hba->wb_buf_flush_enabled = true;
5449 dev_dbg(hba->dev, "WB - Flush enabled: %d\n", ret);
5453 static int ufshcd_wb_buf_flush_disable(struct ufs_hba *hba)
5458 if (!ufshcd_is_wb_allowed(hba) || !hba->wb_buf_flush_enabled)
5461 index = ufshcd_wb_get_query_index(hba);
5462 ret = ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_CLEAR_FLAG,
5463 QUERY_FLAG_IDN_WB_BUFF_FLUSH_EN,
5466 dev_warn(hba->dev, "%s: WB - buf flush disable failed %d\n",
5469 hba->wb_buf_flush_enabled = false;
5470 dev_dbg(hba->dev, "WB - Flush disabled: %d\n", ret);
5476 static bool ufshcd_wb_presrv_usrspc_keep_vcc_on(struct ufs_hba *hba,
5483 index = ufshcd_wb_get_query_index(hba);
5484 ret = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
5485 QUERY_ATTR_IDN_CURR_WB_BUFF_SIZE,
5486 index, 0, &cur_buf);
5488 dev_err(hba->dev, "%s dCurWriteBoosterBufferSize read failed %d\n",
5494 dev_info(hba->dev, "dCurWBBuf: %d WB disabled until free-space is available\n",
5498 /* Let it continue to flush when available buffer exceeds threshold */
5499 if (avail_buf < hba->vps->wb_flush_threshold)
5505 static bool ufshcd_wb_need_flush(struct ufs_hba *hba)
5511 if (!ufshcd_is_wb_allowed(hba))
5514 * The ufs device needs the vcc to be ON to flush.
5515 * With user-space reduction enabled, it's enough to enable flush
5516 * by checking only the available buffer. The threshold
5517 * defined here is > 90% full.
5518 * With user-space preserved enabled, the current-buffer
5519 * should be checked too because the wb buffer size can reduce
5520 * when disk tends to be full. This info is provided by current
5521 * buffer (dCurrentWriteBoosterBufferSize). There's no point in
5522 * keeping vcc on when current buffer is empty.
5524 index = ufshcd_wb_get_query_index(hba);
5525 ret = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
5526 QUERY_ATTR_IDN_AVAIL_WB_BUFF_SIZE,
5527 index, 0, &avail_buf);
5529 dev_warn(hba->dev, "%s dAvailableWriteBoosterBufferSize read failed %d\n",
5534 if (!hba->dev_info.b_presrv_uspc_en) {
5535 if (avail_buf <= UFS_WB_BUF_REMAIN_PERCENT(10))
5540 return ufshcd_wb_presrv_usrspc_keep_vcc_on(hba, avail_buf);
5543 static void ufshcd_rpm_dev_flush_recheck_work(struct work_struct *work)
5545 struct ufs_hba *hba = container_of(to_delayed_work(work),
5547 rpm_dev_flush_recheck_work);
5549 * To prevent unnecessary VCC power drain after device finishes
5550 * WriteBooster buffer flush or Auto BKOPs, force runtime resume
5551 * after a certain delay to recheck the threshold by next runtime
5554 pm_runtime_get_sync(hba->dev);
5555 pm_runtime_put_sync(hba->dev);
5559 * ufshcd_exception_event_handler - handle exceptions raised by device
5560 * @work: pointer to work data
5562 * Read bExceptionEventStatus attribute from the device and handle the
5563 * exception event accordingly.
5565 static void ufshcd_exception_event_handler(struct work_struct *work)
5567 struct ufs_hba *hba;
5570 hba = container_of(work, struct ufs_hba, eeh_work);
5572 pm_runtime_get_sync(hba->dev);
5573 ufshcd_scsi_block_requests(hba);
5574 err = ufshcd_get_ee_status(hba, &status);
5576 dev_err(hba->dev, "%s: failed to get exception status %d\n",
5581 status &= hba->ee_ctrl_mask;
5583 if (status & MASK_EE_URGENT_BKOPS)
5584 ufshcd_bkops_exception_event_handler(hba);
5587 ufshcd_scsi_unblock_requests(hba);
5589 * pm_runtime_get_noresume is called while scheduling
5590 * eeh_work to avoid suspend racing with exception work.
5591 * Hence decrement usage counter using pm_runtime_put_noidle
5592 * to allow suspend on completion of exception event handler.
5594 pm_runtime_put_noidle(hba->dev);
5595 pm_runtime_put(hba->dev);
5599 /* Complete requests that have door-bell cleared */
5600 static void ufshcd_complete_requests(struct ufs_hba *hba)
5602 ufshcd_transfer_req_compl(hba);
5603 ufshcd_tmc_handler(hba);
5607 * ufshcd_quirk_dl_nac_errors - This function checks if error handling is
5608 * to recover from the DL NAC errors or not.
5609 * @hba: per-adapter instance
5611 * Returns true if error handling is required, false otherwise
5613 static bool ufshcd_quirk_dl_nac_errors(struct ufs_hba *hba)
5615 unsigned long flags;
5616 bool err_handling = true;
5618 spin_lock_irqsave(hba->host->host_lock, flags);
5620 * UFS_DEVICE_QUIRK_RECOVERY_FROM_DL_NAC_ERRORS only workaround the
5621 * device fatal error and/or DL NAC & REPLAY timeout errors.
5623 if (hba->saved_err & (CONTROLLER_FATAL_ERROR | SYSTEM_BUS_FATAL_ERROR))
5626 if ((hba->saved_err & DEVICE_FATAL_ERROR) ||
5627 ((hba->saved_err & UIC_ERROR) &&
5628 (hba->saved_uic_err & UFSHCD_UIC_DL_TCx_REPLAY_ERROR)))
5631 if ((hba->saved_err & UIC_ERROR) &&
5632 (hba->saved_uic_err & UFSHCD_UIC_DL_NAC_RECEIVED_ERROR)) {
5635 * wait for 50ms to see if we can get any other errors or not.
5637 spin_unlock_irqrestore(hba->host->host_lock, flags);
5639 spin_lock_irqsave(hba->host->host_lock, flags);
5642 * now check if we have got any other severe errors other than
5645 if ((hba->saved_err & INT_FATAL_ERRORS) ||
5646 ((hba->saved_err & UIC_ERROR) &&
5647 (hba->saved_uic_err & ~UFSHCD_UIC_DL_NAC_RECEIVED_ERROR)))
5651 * As DL NAC is the only error received so far, send out NOP
5652 * command to confirm if link is still active or not.
5653 * - If we don't get any response then do error recovery.
5654 * - If we get response then clear the DL NAC error bit.
5657 spin_unlock_irqrestore(hba->host->host_lock, flags);
5658 err = ufshcd_verify_dev_init(hba);
5659 spin_lock_irqsave(hba->host->host_lock, flags);
5664 /* Link seems to be alive hence ignore the DL NAC errors */
5665 if (hba->saved_uic_err == UFSHCD_UIC_DL_NAC_RECEIVED_ERROR)
5666 hba->saved_err &= ~UIC_ERROR;
5667 /* clear NAC error */
5668 hba->saved_uic_err &= ~UFSHCD_UIC_DL_NAC_RECEIVED_ERROR;
5669 if (!hba->saved_uic_err)
5670 err_handling = false;
5673 spin_unlock_irqrestore(hba->host->host_lock, flags);
5674 return err_handling;
5677 /* host lock must be held before calling this func */
5678 static inline bool ufshcd_is_saved_err_fatal(struct ufs_hba *hba)
5680 return (hba->saved_uic_err & UFSHCD_UIC_DL_PA_INIT_ERROR) ||
5681 (hba->saved_err & (INT_FATAL_ERRORS | UFSHCD_UIC_HIBERN8_MASK));
5684 /* host lock must be held before calling this func */
5685 static inline void ufshcd_schedule_eh_work(struct ufs_hba *hba)
5687 /* handle fatal errors only when link is not in error state */
5688 if (hba->ufshcd_state != UFSHCD_STATE_ERROR) {
5689 if (hba->force_reset || ufshcd_is_link_broken(hba) ||
5690 ufshcd_is_saved_err_fatal(hba))
5691 hba->ufshcd_state = UFSHCD_STATE_EH_SCHEDULED_FATAL;
5693 hba->ufshcd_state = UFSHCD_STATE_EH_SCHEDULED_NON_FATAL;
5694 queue_work(hba->eh_wq, &hba->eh_work);
5698 static void ufshcd_err_handling_prepare(struct ufs_hba *hba)
5700 pm_runtime_get_sync(hba->dev);
5701 if (pm_runtime_status_suspended(hba->dev) || hba->is_sys_suspended) {
5702 enum ufs_pm_op pm_op;
5705 * Don't assume anything of pm_runtime_get_sync(), if
5706 * resume fails, irq and clocks can be OFF, and powers
5707 * can be OFF or in LPM.
5709 ufshcd_setup_hba_vreg(hba, true);
5710 ufshcd_enable_irq(hba);
5711 ufshcd_setup_vreg(hba, true);
5712 ufshcd_config_vreg_hpm(hba, hba->vreg_info.vccq);
5713 ufshcd_config_vreg_hpm(hba, hba->vreg_info.vccq2);
5714 ufshcd_hold(hba, false);
5715 if (!ufshcd_is_clkgating_allowed(hba))
5716 ufshcd_setup_clocks(hba, true);
5717 ufshcd_release(hba);
5718 pm_op = hba->is_sys_suspended ? UFS_SYSTEM_PM : UFS_RUNTIME_PM;
5719 ufshcd_vops_resume(hba, pm_op);
5721 ufshcd_hold(hba, false);
5722 if (hba->clk_scaling.is_allowed) {
5723 cancel_work_sync(&hba->clk_scaling.suspend_work);
5724 cancel_work_sync(&hba->clk_scaling.resume_work);
5725 ufshcd_suspend_clkscaling(hba);
5730 static void ufshcd_err_handling_unprepare(struct ufs_hba *hba)
5732 ufshcd_release(hba);
5733 if (hba->clk_scaling.is_allowed)
5734 ufshcd_resume_clkscaling(hba);
5735 pm_runtime_put(hba->dev);
5738 static inline bool ufshcd_err_handling_should_stop(struct ufs_hba *hba)
5740 return (!hba->is_powered || hba->ufshcd_state == UFSHCD_STATE_ERROR ||
5741 (!(hba->saved_err || hba->saved_uic_err || hba->force_reset ||
5742 ufshcd_is_link_broken(hba))));
5746 static void ufshcd_recover_pm_error(struct ufs_hba *hba)
5748 struct Scsi_Host *shost = hba->host;
5749 struct scsi_device *sdev;
5750 struct request_queue *q;
5753 hba->is_sys_suspended = false;
5755 * Set RPM status of hba device to RPM_ACTIVE,
5756 * this also clears its runtime error.
5758 ret = pm_runtime_set_active(hba->dev);
5760 * If hba device had runtime error, we also need to resume those
5761 * scsi devices under hba in case any of them has failed to be
5762 * resumed due to hba runtime resume failure. This is to unblock
5763 * blk_queue_enter in case there are bios waiting inside it.
5766 shost_for_each_device(sdev, shost) {
5767 q = sdev->request_queue;
5768 if (q->dev && (q->rpm_status == RPM_SUSPENDED ||
5769 q->rpm_status == RPM_SUSPENDING))
5770 pm_request_resume(q->dev);
5775 static inline void ufshcd_recover_pm_error(struct ufs_hba *hba)
5780 static bool ufshcd_is_pwr_mode_restore_needed(struct ufs_hba *hba)
5782 struct ufs_pa_layer_attr *pwr_info = &hba->pwr_info;
5785 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_PWRMODE), &mode);
5787 if (pwr_info->pwr_rx != ((mode >> PWRMODE_RX_OFFSET) & PWRMODE_MASK))
5790 if (pwr_info->pwr_tx != (mode & PWRMODE_MASK))
5797 * ufshcd_err_handler - handle UFS errors that require s/w attention
5798 * @work: pointer to work structure
5800 static void ufshcd_err_handler(struct work_struct *work)
5802 struct ufs_hba *hba;
5803 unsigned long flags;
5804 bool err_xfer = false;
5805 bool err_tm = false;
5806 int err = 0, pmc_err;
5808 bool needs_reset = false, needs_restore = false;
5810 hba = container_of(work, struct ufs_hba, eh_work);
5813 spin_lock_irqsave(hba->host->host_lock, flags);
5814 if (ufshcd_err_handling_should_stop(hba)) {
5815 if (hba->ufshcd_state != UFSHCD_STATE_ERROR)
5816 hba->ufshcd_state = UFSHCD_STATE_OPERATIONAL;
5817 spin_unlock_irqrestore(hba->host->host_lock, flags);
5821 ufshcd_set_eh_in_progress(hba);
5822 spin_unlock_irqrestore(hba->host->host_lock, flags);
5823 ufshcd_err_handling_prepare(hba);
5824 spin_lock_irqsave(hba->host->host_lock, flags);
5825 ufshcd_scsi_block_requests(hba);
5826 hba->ufshcd_state = UFSHCD_STATE_RESET;
5828 /* Complete requests that have door-bell cleared by h/w */
5829 ufshcd_complete_requests(hba);
5832 * A full reset and restore might have happened after preparation
5833 * is finished, double check whether we should stop.
5835 if (ufshcd_err_handling_should_stop(hba))
5836 goto skip_err_handling;
5838 if (hba->dev_quirks & UFS_DEVICE_QUIRK_RECOVERY_FROM_DL_NAC_ERRORS) {
5841 spin_unlock_irqrestore(hba->host->host_lock, flags);
5842 /* release the lock as ufshcd_quirk_dl_nac_errors() may sleep */
5843 ret = ufshcd_quirk_dl_nac_errors(hba);
5844 spin_lock_irqsave(hba->host->host_lock, flags);
5845 if (!ret && ufshcd_err_handling_should_stop(hba))
5846 goto skip_err_handling;
5849 if ((hba->saved_err & (INT_FATAL_ERRORS | UFSHCD_UIC_HIBERN8_MASK)) ||
5850 (hba->saved_uic_err &&
5851 (hba->saved_uic_err != UFSHCD_UIC_PA_GENERIC_ERROR))) {
5852 bool pr_prdt = !!(hba->saved_err & SYSTEM_BUS_FATAL_ERROR);
5854 spin_unlock_irqrestore(hba->host->host_lock, flags);
5855 ufshcd_print_host_state(hba);
5856 ufshcd_print_pwr_info(hba);
5857 ufshcd_print_evt_hist(hba);
5858 ufshcd_print_tmrs(hba, hba->outstanding_tasks);
5859 ufshcd_print_trs(hba, hba->outstanding_reqs, pr_prdt);
5860 spin_lock_irqsave(hba->host->host_lock, flags);
5864 * if host reset is required then skip clearing the pending
5865 * transfers forcefully because they will get cleared during
5866 * host reset and restore
5868 if (hba->force_reset || ufshcd_is_link_broken(hba) ||
5869 ufshcd_is_saved_err_fatal(hba) ||
5870 ((hba->saved_err & UIC_ERROR) &&
5871 (hba->saved_uic_err & (UFSHCD_UIC_DL_NAC_RECEIVED_ERROR |
5872 UFSHCD_UIC_DL_TCx_REPLAY_ERROR)))) {
5878 * If LINERESET was caught, UFS might have been put to PWM mode,
5879 * check if power mode restore is needed.
5881 if (hba->saved_uic_err & UFSHCD_UIC_PA_GENERIC_ERROR) {
5882 hba->saved_uic_err &= ~UFSHCD_UIC_PA_GENERIC_ERROR;
5883 if (!hba->saved_uic_err)
5884 hba->saved_err &= ~UIC_ERROR;
5885 spin_unlock_irqrestore(hba->host->host_lock, flags);
5886 if (ufshcd_is_pwr_mode_restore_needed(hba))
5887 needs_restore = true;
5888 spin_lock_irqsave(hba->host->host_lock, flags);
5889 if (!hba->saved_err && !needs_restore)
5890 goto skip_err_handling;
5893 hba->silence_err_logs = true;
5894 /* release lock as clear command might sleep */
5895 spin_unlock_irqrestore(hba->host->host_lock, flags);
5896 /* Clear pending transfer requests */
5897 for_each_set_bit(tag, &hba->outstanding_reqs, hba->nutrs) {
5898 if (ufshcd_try_to_abort_task(hba, tag)) {
5900 goto lock_skip_pending_xfer_clear;
5904 /* Clear pending task management requests */
5905 for_each_set_bit(tag, &hba->outstanding_tasks, hba->nutmrs) {
5906 if (ufshcd_clear_tm_cmd(hba, tag)) {
5908 goto lock_skip_pending_xfer_clear;
5912 lock_skip_pending_xfer_clear:
5913 spin_lock_irqsave(hba->host->host_lock, flags);
5915 /* Complete the requests that are cleared by s/w */
5916 ufshcd_complete_requests(hba);
5917 hba->silence_err_logs = false;
5919 if (err_xfer || err_tm) {
5925 * After all reqs and tasks are cleared from doorbell,
5926 * now it is safe to retore power mode.
5928 if (needs_restore) {
5929 spin_unlock_irqrestore(hba->host->host_lock, flags);
5931 * Hold the scaling lock just in case dev cmds
5932 * are sent via bsg and/or sysfs.
5934 down_write(&hba->clk_scaling_lock);
5935 hba->force_pmc = true;
5936 pmc_err = ufshcd_config_pwr_mode(hba, &(hba->pwr_info));
5939 dev_err(hba->dev, "%s: Failed to restore power mode, err = %d\n",
5942 hba->force_pmc = false;
5943 ufshcd_print_pwr_info(hba);
5944 up_write(&hba->clk_scaling_lock);
5945 spin_lock_irqsave(hba->host->host_lock, flags);
5949 /* Fatal errors need reset */
5951 unsigned long max_doorbells = (1UL << hba->nutrs) - 1;
5954 * ufshcd_reset_and_restore() does the link reinitialization
5955 * which will need atleast one empty doorbell slot to send the
5956 * device management commands (NOP and query commands).
5957 * If there is no slot empty at this moment then free up last
5960 if (hba->outstanding_reqs == max_doorbells)
5961 __ufshcd_transfer_req_compl(hba,
5962 (1UL << (hba->nutrs - 1)));
5964 hba->force_reset = false;
5965 spin_unlock_irqrestore(hba->host->host_lock, flags);
5966 err = ufshcd_reset_and_restore(hba);
5968 dev_err(hba->dev, "%s: reset and restore failed with err %d\n",
5971 ufshcd_recover_pm_error(hba);
5972 spin_lock_irqsave(hba->host->host_lock, flags);
5977 if (hba->ufshcd_state == UFSHCD_STATE_RESET)
5978 hba->ufshcd_state = UFSHCD_STATE_OPERATIONAL;
5979 if (hba->saved_err || hba->saved_uic_err)
5980 dev_err_ratelimited(hba->dev, "%s: exit: saved_err 0x%x saved_uic_err 0x%x",
5981 __func__, hba->saved_err, hba->saved_uic_err);
5983 ufshcd_clear_eh_in_progress(hba);
5984 spin_unlock_irqrestore(hba->host->host_lock, flags);
5985 ufshcd_scsi_unblock_requests(hba);
5986 ufshcd_err_handling_unprepare(hba);
5991 * ufshcd_update_uic_error - check and set fatal UIC error flags.
5992 * @hba: per-adapter instance
5995 * IRQ_HANDLED - If interrupt is valid
5996 * IRQ_NONE - If invalid interrupt
5998 static irqreturn_t ufshcd_update_uic_error(struct ufs_hba *hba)
6001 irqreturn_t retval = IRQ_NONE;
6003 /* PHY layer error */
6004 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_PHY_ADAPTER_LAYER);
6005 if ((reg & UIC_PHY_ADAPTER_LAYER_ERROR) &&
6006 (reg & UIC_PHY_ADAPTER_LAYER_ERROR_CODE_MASK)) {
6007 ufshcd_update_evt_hist(hba, UFS_EVT_PA_ERR, reg);
6009 * To know whether this error is fatal or not, DB timeout
6010 * must be checked but this error is handled separately.
6012 if (reg & UIC_PHY_ADAPTER_LAYER_LANE_ERR_MASK)
6013 dev_dbg(hba->dev, "%s: UIC Lane error reported\n",
6016 /* Got a LINERESET indication. */
6017 if (reg & UIC_PHY_ADAPTER_LAYER_GENERIC_ERROR) {
6018 struct uic_command *cmd = NULL;
6020 hba->uic_error |= UFSHCD_UIC_PA_GENERIC_ERROR;
6021 if (hba->uic_async_done && hba->active_uic_cmd)
6022 cmd = hba->active_uic_cmd;
6024 * Ignore the LINERESET during power mode change
6025 * operation via DME_SET command.
6027 if (cmd && (cmd->command == UIC_CMD_DME_SET))
6028 hba->uic_error &= ~UFSHCD_UIC_PA_GENERIC_ERROR;
6030 retval |= IRQ_HANDLED;
6033 /* PA_INIT_ERROR is fatal and needs UIC reset */
6034 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_DATA_LINK_LAYER);
6035 if ((reg & UIC_DATA_LINK_LAYER_ERROR) &&
6036 (reg & UIC_DATA_LINK_LAYER_ERROR_CODE_MASK)) {
6037 ufshcd_update_evt_hist(hba, UFS_EVT_DL_ERR, reg);
6039 if (reg & UIC_DATA_LINK_LAYER_ERROR_PA_INIT)
6040 hba->uic_error |= UFSHCD_UIC_DL_PA_INIT_ERROR;
6041 else if (hba->dev_quirks &
6042 UFS_DEVICE_QUIRK_RECOVERY_FROM_DL_NAC_ERRORS) {
6043 if (reg & UIC_DATA_LINK_LAYER_ERROR_NAC_RECEIVED)
6045 UFSHCD_UIC_DL_NAC_RECEIVED_ERROR;
6046 else if (reg & UIC_DATA_LINK_LAYER_ERROR_TCx_REPLAY_TIMEOUT)
6047 hba->uic_error |= UFSHCD_UIC_DL_TCx_REPLAY_ERROR;
6049 retval |= IRQ_HANDLED;
6052 /* UIC NL/TL/DME errors needs software retry */
6053 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_NETWORK_LAYER);
6054 if ((reg & UIC_NETWORK_LAYER_ERROR) &&
6055 (reg & UIC_NETWORK_LAYER_ERROR_CODE_MASK)) {
6056 ufshcd_update_evt_hist(hba, UFS_EVT_NL_ERR, reg);
6057 hba->uic_error |= UFSHCD_UIC_NL_ERROR;
6058 retval |= IRQ_HANDLED;
6061 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_TRANSPORT_LAYER);
6062 if ((reg & UIC_TRANSPORT_LAYER_ERROR) &&
6063 (reg & UIC_TRANSPORT_LAYER_ERROR_CODE_MASK)) {
6064 ufshcd_update_evt_hist(hba, UFS_EVT_TL_ERR, reg);
6065 hba->uic_error |= UFSHCD_UIC_TL_ERROR;
6066 retval |= IRQ_HANDLED;
6069 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_DME);
6070 if ((reg & UIC_DME_ERROR) &&
6071 (reg & UIC_DME_ERROR_CODE_MASK)) {
6072 ufshcd_update_evt_hist(hba, UFS_EVT_DME_ERR, reg);
6073 hba->uic_error |= UFSHCD_UIC_DME_ERROR;
6074 retval |= IRQ_HANDLED;
6077 dev_dbg(hba->dev, "%s: UIC error flags = 0x%08x\n",
6078 __func__, hba->uic_error);
6082 static bool ufshcd_is_auto_hibern8_error(struct ufs_hba *hba,
6085 if (!ufshcd_is_auto_hibern8_supported(hba) ||
6086 !ufshcd_is_auto_hibern8_enabled(hba))
6089 if (!(intr_mask & UFSHCD_UIC_HIBERN8_MASK))
6092 if (hba->active_uic_cmd &&
6093 (hba->active_uic_cmd->command == UIC_CMD_DME_HIBER_ENTER ||
6094 hba->active_uic_cmd->command == UIC_CMD_DME_HIBER_EXIT))
6101 * ufshcd_check_errors - Check for errors that need s/w attention
6102 * @hba: per-adapter instance
6105 * IRQ_HANDLED - If interrupt is valid
6106 * IRQ_NONE - If invalid interrupt
6108 static irqreturn_t ufshcd_check_errors(struct ufs_hba *hba)
6110 bool queue_eh_work = false;
6111 irqreturn_t retval = IRQ_NONE;
6113 if (hba->errors & INT_FATAL_ERRORS) {
6114 ufshcd_update_evt_hist(hba, UFS_EVT_FATAL_ERR,
6116 queue_eh_work = true;
6119 if (hba->errors & UIC_ERROR) {
6121 retval = ufshcd_update_uic_error(hba);
6123 queue_eh_work = true;
6126 if (hba->errors & UFSHCD_UIC_HIBERN8_MASK) {
6128 "%s: Auto Hibern8 %s failed - status: 0x%08x, upmcrs: 0x%08x\n",
6129 __func__, (hba->errors & UIC_HIBERNATE_ENTER) ?
6131 hba->errors, ufshcd_get_upmcrs(hba));
6132 ufshcd_update_evt_hist(hba, UFS_EVT_AUTO_HIBERN8_ERR,
6134 ufshcd_set_link_broken(hba);
6135 queue_eh_work = true;
6138 if (queue_eh_work) {
6140 * update the transfer error masks to sticky bits, let's do this
6141 * irrespective of current ufshcd_state.
6143 hba->saved_err |= hba->errors;
6144 hba->saved_uic_err |= hba->uic_error;
6146 /* dump controller state before resetting */
6147 if ((hba->saved_err &
6148 (INT_FATAL_ERRORS | UFSHCD_UIC_HIBERN8_MASK)) ||
6149 (hba->saved_uic_err &&
6150 (hba->saved_uic_err != UFSHCD_UIC_PA_GENERIC_ERROR))) {
6151 dev_err(hba->dev, "%s: saved_err 0x%x saved_uic_err 0x%x\n",
6152 __func__, hba->saved_err,
6153 hba->saved_uic_err);
6154 ufshcd_dump_regs(hba, 0, UFSHCI_REG_SPACE_SIZE,
6156 ufshcd_print_pwr_info(hba);
6158 ufshcd_schedule_eh_work(hba);
6159 retval |= IRQ_HANDLED;
6162 * if (!queue_eh_work) -
6163 * Other errors are either non-fatal where host recovers
6164 * itself without s/w intervention or errors that will be
6165 * handled by the SCSI core layer.
6171 struct ufs_hba *hba;
6172 unsigned long pending;
6176 static bool ufshcd_compl_tm(struct request *req, void *priv, bool reserved)
6178 struct ctm_info *const ci = priv;
6179 struct completion *c;
6181 WARN_ON_ONCE(reserved);
6182 if (test_bit(req->tag, &ci->pending))
6185 c = req->end_io_data;
6192 * ufshcd_tmc_handler - handle task management function completion
6193 * @hba: per adapter instance
6196 * IRQ_HANDLED - If interrupt is valid
6197 * IRQ_NONE - If invalid interrupt
6199 static irqreturn_t ufshcd_tmc_handler(struct ufs_hba *hba)
6201 struct request_queue *q = hba->tmf_queue;
6202 struct ctm_info ci = {
6204 .pending = ufshcd_readl(hba, REG_UTP_TASK_REQ_DOOR_BELL),
6207 blk_mq_tagset_busy_iter(q->tag_set, ufshcd_compl_tm, &ci);
6208 return ci.ncpl ? IRQ_HANDLED : IRQ_NONE;
6212 * ufshcd_sl_intr - Interrupt service routine
6213 * @hba: per adapter instance
6214 * @intr_status: contains interrupts generated by the controller
6217 * IRQ_HANDLED - If interrupt is valid
6218 * IRQ_NONE - If invalid interrupt
6220 static irqreturn_t ufshcd_sl_intr(struct ufs_hba *hba, u32 intr_status)
6222 irqreturn_t retval = IRQ_NONE;
6224 hba->errors = UFSHCD_ERROR_MASK & intr_status;
6226 if (ufshcd_is_auto_hibern8_error(hba, intr_status))
6227 hba->errors |= (UFSHCD_UIC_HIBERN8_MASK & intr_status);
6230 retval |= ufshcd_check_errors(hba);
6232 if (intr_status & UFSHCD_UIC_MASK)
6233 retval |= ufshcd_uic_cmd_compl(hba, intr_status);
6235 if (intr_status & UTP_TASK_REQ_COMPL)
6236 retval |= ufshcd_tmc_handler(hba);
6238 if (intr_status & UTP_TRANSFER_REQ_COMPL)
6239 retval |= ufshcd_transfer_req_compl(hba);
6245 * ufshcd_intr - Main interrupt service routine
6247 * @__hba: pointer to adapter instance
6250 * IRQ_HANDLED - If interrupt is valid
6251 * IRQ_NONE - If invalid interrupt
6253 static irqreturn_t ufshcd_intr(int irq, void *__hba)
6255 u32 intr_status, enabled_intr_status = 0;
6256 irqreturn_t retval = IRQ_NONE;
6257 struct ufs_hba *hba = __hba;
6258 int retries = hba->nutrs;
6260 spin_lock(hba->host->host_lock);
6261 intr_status = ufshcd_readl(hba, REG_INTERRUPT_STATUS);
6262 hba->ufs_stats.last_intr_status = intr_status;
6263 hba->ufs_stats.last_intr_ts = ktime_get();
6266 * There could be max of hba->nutrs reqs in flight and in worst case
6267 * if the reqs get finished 1 by 1 after the interrupt status is
6268 * read, make sure we handle them by checking the interrupt status
6269 * again in a loop until we process all of the reqs before returning.
6271 while (intr_status && retries--) {
6272 enabled_intr_status =
6273 intr_status & ufshcd_readl(hba, REG_INTERRUPT_ENABLE);
6275 ufshcd_writel(hba, intr_status, REG_INTERRUPT_STATUS);
6276 if (enabled_intr_status)
6277 retval |= ufshcd_sl_intr(hba, enabled_intr_status);
6279 intr_status = ufshcd_readl(hba, REG_INTERRUPT_STATUS);
6282 if (enabled_intr_status && retval == IRQ_NONE) {
6283 dev_err(hba->dev, "%s: Unhandled interrupt 0x%08x\n",
6284 __func__, intr_status);
6285 ufshcd_dump_regs(hba, 0, UFSHCI_REG_SPACE_SIZE, "host_regs: ");
6288 spin_unlock(hba->host->host_lock);
6292 static int ufshcd_clear_tm_cmd(struct ufs_hba *hba, int tag)
6295 u32 mask = 1 << tag;
6296 unsigned long flags;
6298 if (!test_bit(tag, &hba->outstanding_tasks))
6301 spin_lock_irqsave(hba->host->host_lock, flags);
6302 ufshcd_utmrl_clear(hba, tag);
6303 spin_unlock_irqrestore(hba->host->host_lock, flags);
6305 /* poll for max. 1 sec to clear door bell register by h/w */
6306 err = ufshcd_wait_for_register(hba,
6307 REG_UTP_TASK_REQ_DOOR_BELL,
6308 mask, 0, 1000, 1000);
6313 static int __ufshcd_issue_tm_cmd(struct ufs_hba *hba,
6314 struct utp_task_req_desc *treq, u8 tm_function)
6316 struct request_queue *q = hba->tmf_queue;
6317 struct Scsi_Host *host = hba->host;
6318 DECLARE_COMPLETION_ONSTACK(wait);
6319 struct request *req;
6320 unsigned long flags;
6321 int free_slot, task_tag, err;
6324 * Get free slot, sleep if slots are unavailable.
6325 * Even though we use wait_event() which sleeps indefinitely,
6326 * the maximum wait time is bounded by %TM_CMD_TIMEOUT.
6328 req = blk_get_request(q, REQ_OP_DRV_OUT, BLK_MQ_REQ_RESERVED);
6329 req->end_io_data = &wait;
6330 free_slot = req->tag;
6331 WARN_ON_ONCE(free_slot < 0 || free_slot >= hba->nutmrs);
6332 ufshcd_hold(hba, false);
6334 spin_lock_irqsave(host->host_lock, flags);
6335 task_tag = hba->nutrs + free_slot;
6337 treq->req_header.dword_0 |= cpu_to_be32(task_tag);
6339 memcpy(hba->utmrdl_base_addr + free_slot, treq, sizeof(*treq));
6340 ufshcd_vops_setup_task_mgmt(hba, free_slot, tm_function);
6342 /* send command to the controller */
6343 __set_bit(free_slot, &hba->outstanding_tasks);
6345 /* Make sure descriptors are ready before ringing the task doorbell */
6348 ufshcd_writel(hba, 1 << free_slot, REG_UTP_TASK_REQ_DOOR_BELL);
6349 /* Make sure that doorbell is committed immediately */
6352 spin_unlock_irqrestore(host->host_lock, flags);
6354 ufshcd_add_tm_upiu_trace(hba, task_tag, "tm_send");
6356 /* wait until the task management command is completed */
6357 err = wait_for_completion_io_timeout(&wait,
6358 msecs_to_jiffies(TM_CMD_TIMEOUT));
6361 * Make sure that ufshcd_compl_tm() does not trigger a
6364 req->end_io_data = NULL;
6365 ufshcd_add_tm_upiu_trace(hba, task_tag, "tm_complete_err");
6366 dev_err(hba->dev, "%s: task management cmd 0x%.2x timed-out\n",
6367 __func__, tm_function);
6368 if (ufshcd_clear_tm_cmd(hba, free_slot))
6369 dev_WARN(hba->dev, "%s: unable clear tm cmd (slot %d) after timeout\n",
6370 __func__, free_slot);
6374 memcpy(treq, hba->utmrdl_base_addr + free_slot, sizeof(*treq));
6376 ufshcd_add_tm_upiu_trace(hba, task_tag, "tm_complete");
6379 spin_lock_irqsave(hba->host->host_lock, flags);
6380 __clear_bit(free_slot, &hba->outstanding_tasks);
6381 spin_unlock_irqrestore(hba->host->host_lock, flags);
6383 blk_put_request(req);
6385 ufshcd_release(hba);
6390 * ufshcd_issue_tm_cmd - issues task management commands to controller
6391 * @hba: per adapter instance
6392 * @lun_id: LUN ID to which TM command is sent
6393 * @task_id: task ID to which the TM command is applicable
6394 * @tm_function: task management function opcode
6395 * @tm_response: task management service response return value
6397 * Returns non-zero value on error, zero on success.
6399 static int ufshcd_issue_tm_cmd(struct ufs_hba *hba, int lun_id, int task_id,
6400 u8 tm_function, u8 *tm_response)
6402 struct utp_task_req_desc treq = { { 0 }, };
6405 /* Configure task request descriptor */
6406 treq.header.dword_0 = cpu_to_le32(UTP_REQ_DESC_INT_CMD);
6407 treq.header.dword_2 = cpu_to_le32(OCS_INVALID_COMMAND_STATUS);
6409 /* Configure task request UPIU */
6410 treq.req_header.dword_0 = cpu_to_be32(lun_id << 8) |
6411 cpu_to_be32(UPIU_TRANSACTION_TASK_REQ << 24);
6412 treq.req_header.dword_1 = cpu_to_be32(tm_function << 16);
6415 * The host shall provide the same value for LUN field in the basic
6416 * header and for Input Parameter.
6418 treq.input_param1 = cpu_to_be32(lun_id);
6419 treq.input_param2 = cpu_to_be32(task_id);
6421 err = __ufshcd_issue_tm_cmd(hba, &treq, tm_function);
6422 if (err == -ETIMEDOUT)
6425 ocs_value = le32_to_cpu(treq.header.dword_2) & MASK_OCS;
6426 if (ocs_value != OCS_SUCCESS)
6427 dev_err(hba->dev, "%s: failed, ocs = 0x%x\n",
6428 __func__, ocs_value);
6429 else if (tm_response)
6430 *tm_response = be32_to_cpu(treq.output_param1) &
6431 MASK_TM_SERVICE_RESP;
6436 * ufshcd_issue_devman_upiu_cmd - API for sending "utrd" type requests
6437 * @hba: per-adapter instance
6438 * @req_upiu: upiu request
6439 * @rsp_upiu: upiu reply
6440 * @desc_buff: pointer to descriptor buffer, NULL if NA
6441 * @buff_len: descriptor size, 0 if NA
6442 * @cmd_type: specifies the type (NOP, Query...)
6443 * @desc_op: descriptor operation
6445 * Those type of requests uses UTP Transfer Request Descriptor - utrd.
6446 * Therefore, it "rides" the device management infrastructure: uses its tag and
6447 * tasks work queues.
6449 * Since there is only one available tag for device management commands,
6450 * the caller is expected to hold the hba->dev_cmd.lock mutex.
6452 static int ufshcd_issue_devman_upiu_cmd(struct ufs_hba *hba,
6453 struct utp_upiu_req *req_upiu,
6454 struct utp_upiu_req *rsp_upiu,
6455 u8 *desc_buff, int *buff_len,
6456 enum dev_cmd_type cmd_type,
6457 enum query_opcode desc_op)
6459 struct request_queue *q = hba->cmd_queue;
6460 struct request *req;
6461 struct ufshcd_lrb *lrbp;
6464 struct completion wait;
6465 unsigned long flags;
6468 down_read(&hba->clk_scaling_lock);
6470 req = blk_get_request(q, REQ_OP_DRV_OUT, 0);
6476 WARN_ON_ONCE(!ufshcd_valid_tag(hba, tag));
6478 init_completion(&wait);
6479 lrbp = &hba->lrb[tag];
6480 if (unlikely(lrbp->in_use)) {
6487 lrbp->sense_bufflen = 0;
6488 lrbp->sense_buffer = NULL;
6489 lrbp->task_tag = tag;
6491 lrbp->intr_cmd = true;
6492 ufshcd_prepare_lrbp_crypto(NULL, lrbp);
6493 hba->dev_cmd.type = cmd_type;
6495 switch (hba->ufs_version) {
6496 case UFSHCI_VERSION_10:
6497 case UFSHCI_VERSION_11:
6498 lrbp->command_type = UTP_CMD_TYPE_DEV_MANAGE;
6501 lrbp->command_type = UTP_CMD_TYPE_UFS_STORAGE;
6505 /* update the task tag in the request upiu */
6506 req_upiu->header.dword_0 |= cpu_to_be32(tag);
6508 ufshcd_prepare_req_desc_hdr(lrbp, &upiu_flags, DMA_NONE);
6510 /* just copy the upiu request as it is */
6511 memcpy(lrbp->ucd_req_ptr, req_upiu, sizeof(*lrbp->ucd_req_ptr));
6512 if (desc_buff && desc_op == UPIU_QUERY_OPCODE_WRITE_DESC) {
6513 /* The Data Segment Area is optional depending upon the query
6514 * function value. for WRITE DESCRIPTOR, the data segment
6515 * follows right after the tsf.
6517 memcpy(lrbp->ucd_req_ptr + 1, desc_buff, *buff_len);
6521 memset(lrbp->ucd_rsp_ptr, 0, sizeof(struct utp_upiu_rsp));
6523 hba->dev_cmd.complete = &wait;
6525 /* Make sure descriptors are ready before ringing the doorbell */
6527 spin_lock_irqsave(hba->host->host_lock, flags);
6528 ufshcd_send_command(hba, tag);
6529 spin_unlock_irqrestore(hba->host->host_lock, flags);
6532 * ignore the returning value here - ufshcd_check_query_response is
6533 * bound to fail since dev_cmd.query and dev_cmd.type were left empty.
6534 * read the response directly ignoring all errors.
6536 ufshcd_wait_for_dev_cmd(hba, lrbp, QUERY_REQ_TIMEOUT);
6538 /* just copy the upiu response as it is */
6539 memcpy(rsp_upiu, lrbp->ucd_rsp_ptr, sizeof(*rsp_upiu));
6540 if (desc_buff && desc_op == UPIU_QUERY_OPCODE_READ_DESC) {
6541 u8 *descp = (u8 *)lrbp->ucd_rsp_ptr + sizeof(*rsp_upiu);
6542 u16 resp_len = be32_to_cpu(lrbp->ucd_rsp_ptr->header.dword_2) &
6543 MASK_QUERY_DATA_SEG_LEN;
6545 if (*buff_len >= resp_len) {
6546 memcpy(desc_buff, descp, resp_len);
6547 *buff_len = resp_len;
6550 "%s: rsp size %d is bigger than buffer size %d",
6551 __func__, resp_len, *buff_len);
6558 blk_put_request(req);
6560 up_read(&hba->clk_scaling_lock);
6565 * ufshcd_exec_raw_upiu_cmd - API function for sending raw upiu commands
6566 * @hba: per-adapter instance
6567 * @req_upiu: upiu request
6568 * @rsp_upiu: upiu reply - only 8 DW as we do not support scsi commands
6569 * @msgcode: message code, one of UPIU Transaction Codes Initiator to Target
6570 * @desc_buff: pointer to descriptor buffer, NULL if NA
6571 * @buff_len: descriptor size, 0 if NA
6572 * @desc_op: descriptor operation
6574 * Supports UTP Transfer requests (nop and query), and UTP Task
6575 * Management requests.
6576 * It is up to the caller to fill the upiu conent properly, as it will
6577 * be copied without any further input validations.
6579 int ufshcd_exec_raw_upiu_cmd(struct ufs_hba *hba,
6580 struct utp_upiu_req *req_upiu,
6581 struct utp_upiu_req *rsp_upiu,
6583 u8 *desc_buff, int *buff_len,
6584 enum query_opcode desc_op)
6587 enum dev_cmd_type cmd_type = DEV_CMD_TYPE_QUERY;
6588 struct utp_task_req_desc treq = { { 0 }, };
6590 u8 tm_f = be32_to_cpu(req_upiu->header.dword_1) >> 16 & MASK_TM_FUNC;
6593 case UPIU_TRANSACTION_NOP_OUT:
6594 cmd_type = DEV_CMD_TYPE_NOP;
6596 case UPIU_TRANSACTION_QUERY_REQ:
6597 ufshcd_hold(hba, false);
6598 mutex_lock(&hba->dev_cmd.lock);
6599 err = ufshcd_issue_devman_upiu_cmd(hba, req_upiu, rsp_upiu,
6600 desc_buff, buff_len,
6602 mutex_unlock(&hba->dev_cmd.lock);
6603 ufshcd_release(hba);
6606 case UPIU_TRANSACTION_TASK_REQ:
6607 treq.header.dword_0 = cpu_to_le32(UTP_REQ_DESC_INT_CMD);
6608 treq.header.dword_2 = cpu_to_le32(OCS_INVALID_COMMAND_STATUS);
6610 memcpy(&treq.req_header, req_upiu, sizeof(*req_upiu));
6612 err = __ufshcd_issue_tm_cmd(hba, &treq, tm_f);
6613 if (err == -ETIMEDOUT)
6616 ocs_value = le32_to_cpu(treq.header.dword_2) & MASK_OCS;
6617 if (ocs_value != OCS_SUCCESS) {
6618 dev_err(hba->dev, "%s: failed, ocs = 0x%x\n", __func__,
6623 memcpy(rsp_upiu, &treq.rsp_header, sizeof(*rsp_upiu));
6636 * ufshcd_eh_device_reset_handler - device reset handler registered to
6638 * @cmd: SCSI command pointer
6640 * Returns SUCCESS/FAILED
6642 static int ufshcd_eh_device_reset_handler(struct scsi_cmnd *cmd)
6644 struct Scsi_Host *host;
6645 struct ufs_hba *hba;
6650 struct ufshcd_lrb *lrbp;
6651 unsigned long flags;
6653 host = cmd->device->host;
6654 hba = shost_priv(host);
6655 tag = cmd->request->tag;
6657 lrbp = &hba->lrb[tag];
6658 err = ufshcd_issue_tm_cmd(hba, lrbp->lun, 0, UFS_LOGICAL_RESET, &resp);
6659 if (err || resp != UPIU_TASK_MANAGEMENT_FUNC_COMPL) {
6665 /* clear the commands that were pending for corresponding LUN */
6666 for_each_set_bit(pos, &hba->outstanding_reqs, hba->nutrs) {
6667 if (hba->lrb[pos].lun == lrbp->lun) {
6668 err = ufshcd_clear_cmd(hba, pos);
6673 spin_lock_irqsave(host->host_lock, flags);
6674 ufshcd_transfer_req_compl(hba);
6675 spin_unlock_irqrestore(host->host_lock, flags);
6678 hba->req_abort_count = 0;
6679 ufshcd_update_evt_hist(hba, UFS_EVT_DEV_RESET, (u32)err);
6683 dev_err(hba->dev, "%s: failed with err %d\n", __func__, err);
6689 static void ufshcd_set_req_abort_skip(struct ufs_hba *hba, unsigned long bitmap)
6691 struct ufshcd_lrb *lrbp;
6694 for_each_set_bit(tag, &bitmap, hba->nutrs) {
6695 lrbp = &hba->lrb[tag];
6696 lrbp->req_abort_skip = true;
6701 * ufshcd_try_to_abort_task - abort a specific task
6702 * @hba: Pointer to adapter instance
6703 * @tag: Task tag/index to be aborted
6705 * Abort the pending command in device by sending UFS_ABORT_TASK task management
6706 * command, and in host controller by clearing the door-bell register. There can
6707 * be race between controller sending the command to the device while abort is
6708 * issued. To avoid that, first issue UFS_QUERY_TASK to check if the command is
6709 * really issued and then try to abort it.
6711 * Returns zero on success, non-zero on failure
6713 static int ufshcd_try_to_abort_task(struct ufs_hba *hba, int tag)
6715 struct ufshcd_lrb *lrbp = &hba->lrb[tag];
6721 for (poll_cnt = 100; poll_cnt; poll_cnt--) {
6722 err = ufshcd_issue_tm_cmd(hba, lrbp->lun, lrbp->task_tag,
6723 UFS_QUERY_TASK, &resp);
6724 if (!err && resp == UPIU_TASK_MANAGEMENT_FUNC_SUCCEEDED) {
6725 /* cmd pending in the device */
6726 dev_err(hba->dev, "%s: cmd pending in the device. tag = %d\n",
6729 } else if (!err && resp == UPIU_TASK_MANAGEMENT_FUNC_COMPL) {
6731 * cmd not pending in the device, check if it is
6734 dev_err(hba->dev, "%s: cmd at tag %d not pending in the device.\n",
6736 reg = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
6737 if (reg & (1 << tag)) {
6738 /* sleep for max. 200us to stabilize */
6739 usleep_range(100, 200);
6742 /* command completed already */
6743 dev_err(hba->dev, "%s: cmd at tag %d successfully cleared from DB.\n",
6748 "%s: no response from device. tag = %d, err %d\n",
6749 __func__, tag, err);
6751 err = resp; /* service response error */
6761 err = ufshcd_issue_tm_cmd(hba, lrbp->lun, lrbp->task_tag,
6762 UFS_ABORT_TASK, &resp);
6763 if (err || resp != UPIU_TASK_MANAGEMENT_FUNC_COMPL) {
6765 err = resp; /* service response error */
6766 dev_err(hba->dev, "%s: issued. tag = %d, err %d\n",
6767 __func__, tag, err);
6772 err = ufshcd_clear_cmd(hba, tag);
6774 dev_err(hba->dev, "%s: Failed clearing cmd at tag %d, err %d\n",
6775 __func__, tag, err);
6782 * ufshcd_abort - scsi host template eh_abort_handler callback
6783 * @cmd: SCSI command pointer
6785 * Returns SUCCESS/FAILED
6787 static int ufshcd_abort(struct scsi_cmnd *cmd)
6789 struct Scsi_Host *host;
6790 struct ufs_hba *hba;
6791 unsigned long flags;
6794 struct ufshcd_lrb *lrbp;
6797 host = cmd->device->host;
6798 hba = shost_priv(host);
6799 tag = cmd->request->tag;
6800 lrbp = &hba->lrb[tag];
6801 if (!ufshcd_valid_tag(hba, tag)) {
6803 "%s: invalid command tag %d: cmd=0x%p, cmd->request=0x%p",
6804 __func__, tag, cmd, cmd->request);
6808 ufshcd_hold(hba, false);
6809 reg = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
6810 /* If command is already aborted/completed, return SUCCESS */
6811 if (!(test_bit(tag, &hba->outstanding_reqs))) {
6813 "%s: cmd at tag %d already completed, outstanding=0x%lx, doorbell=0x%x\n",
6814 __func__, tag, hba->outstanding_reqs, reg);
6818 /* Print Transfer Request of aborted task */
6819 dev_info(hba->dev, "%s: Device abort task at tag %d\n", __func__, tag);
6822 * Print detailed info about aborted request.
6823 * As more than one request might get aborted at the same time,
6824 * print full information only for the first aborted request in order
6825 * to reduce repeated printouts. For other aborted requests only print
6828 scsi_print_command(cmd);
6829 if (!hba->req_abort_count) {
6830 ufshcd_update_evt_hist(hba, UFS_EVT_ABORT, tag);
6831 ufshcd_print_evt_hist(hba);
6832 ufshcd_print_host_state(hba);
6833 ufshcd_print_pwr_info(hba);
6834 ufshcd_print_trs(hba, 1 << tag, true);
6836 ufshcd_print_trs(hba, 1 << tag, false);
6838 hba->req_abort_count++;
6840 if (!(reg & (1 << tag))) {
6842 "%s: cmd was completed, but without a notifying intr, tag = %d",
6848 * Task abort to the device W-LUN is illegal. When this command
6849 * will fail, due to spec violation, scsi err handling next step
6850 * will be to send LU reset which, again, is a spec violation.
6851 * To avoid these unnecessary/illegal steps, first we clean up
6852 * the lrb taken by this cmd and mark the lrb as in_use, then
6853 * queue the eh_work and bail.
6855 if (lrbp->lun == UFS_UPIU_UFS_DEVICE_WLUN) {
6856 ufshcd_update_evt_hist(hba, UFS_EVT_ABORT, lrbp->lun);
6857 spin_lock_irqsave(host->host_lock, flags);
6859 __ufshcd_transfer_req_compl(hba, (1UL << tag));
6860 __set_bit(tag, &hba->outstanding_reqs);
6861 lrbp->in_use = true;
6862 hba->force_reset = true;
6863 ufshcd_schedule_eh_work(hba);
6866 spin_unlock_irqrestore(host->host_lock, flags);
6870 /* Skip task abort in case previous aborts failed and report failure */
6871 if (lrbp->req_abort_skip)
6874 err = ufshcd_try_to_abort_task(hba, tag);
6878 spin_lock_irqsave(host->host_lock, flags);
6879 __ufshcd_transfer_req_compl(hba, (1UL << tag));
6880 spin_unlock_irqrestore(host->host_lock, flags);
6884 dev_err(hba->dev, "%s: failed with err %d\n", __func__, err);
6885 ufshcd_set_req_abort_skip(hba, hba->outstanding_reqs);
6890 * This ufshcd_release() corresponds to the original scsi cmd that got
6891 * aborted here (as we won't get any IRQ for it).
6893 ufshcd_release(hba);
6898 * ufshcd_host_reset_and_restore - reset and restore host controller
6899 * @hba: per-adapter instance
6901 * Note that host controller reset may issue DME_RESET to
6902 * local and remote (device) Uni-Pro stack and the attributes
6903 * are reset to default state.
6905 * Returns zero on success, non-zero on failure
6907 static int ufshcd_host_reset_and_restore(struct ufs_hba *hba)
6910 unsigned long flags;
6913 * Stop the host controller and complete the requests
6916 ufshcd_hba_stop(hba);
6918 spin_lock_irqsave(hba->host->host_lock, flags);
6919 hba->silence_err_logs = true;
6920 ufshcd_complete_requests(hba);
6921 hba->silence_err_logs = false;
6922 spin_unlock_irqrestore(hba->host->host_lock, flags);
6924 /* scale up clocks to max frequency before full reinitialization */
6925 ufshcd_set_clk_freq(hba, true);
6927 err = ufshcd_hba_enable(hba);
6931 /* Establish the link again and restore the device */
6932 err = ufshcd_probe_hba(hba, false);
6936 dev_err(hba->dev, "%s: Host init failed %d\n", __func__, err);
6937 ufshcd_update_evt_hist(hba, UFS_EVT_HOST_RESET, (u32)err);
6942 * ufshcd_reset_and_restore - reset and re-initialize host/device
6943 * @hba: per-adapter instance
6945 * Reset and recover device, host and re-establish link. This
6946 * is helpful to recover the communication in fatal error conditions.
6948 * Returns zero on success, non-zero on failure
6950 static int ufshcd_reset_and_restore(struct ufs_hba *hba)
6955 unsigned long flags;
6956 int retries = MAX_HOST_RESET_RETRIES;
6959 * This is a fresh start, cache and clear saved error first,
6960 * in case new error generated during reset and restore.
6962 spin_lock_irqsave(hba->host->host_lock, flags);
6963 saved_err = hba->saved_err;
6964 saved_uic_err = hba->saved_uic_err;
6966 hba->saved_uic_err = 0;
6967 spin_unlock_irqrestore(hba->host->host_lock, flags);
6970 /* Reset the attached device */
6971 ufshcd_vops_device_reset(hba);
6973 err = ufshcd_host_reset_and_restore(hba);
6974 } while (err && --retries);
6976 spin_lock_irqsave(hba->host->host_lock, flags);
6978 * Inform scsi mid-layer that we did reset and allow to handle
6979 * Unit Attention properly.
6981 scsi_report_bus_reset(hba->host, 0);
6983 hba->ufshcd_state = UFSHCD_STATE_ERROR;
6984 hba->saved_err |= saved_err;
6985 hba->saved_uic_err |= saved_uic_err;
6987 spin_unlock_irqrestore(hba->host->host_lock, flags);
6993 * ufshcd_eh_host_reset_handler - host reset handler registered to scsi layer
6994 * @cmd: SCSI command pointer
6996 * Returns SUCCESS/FAILED
6998 static int ufshcd_eh_host_reset_handler(struct scsi_cmnd *cmd)
7001 unsigned long flags;
7002 struct ufs_hba *hba;
7004 hba = shost_priv(cmd->device->host);
7006 spin_lock_irqsave(hba->host->host_lock, flags);
7007 hba->force_reset = true;
7008 ufshcd_schedule_eh_work(hba);
7009 dev_err(hba->dev, "%s: reset in progress - 1\n", __func__);
7010 spin_unlock_irqrestore(hba->host->host_lock, flags);
7012 flush_work(&hba->eh_work);
7014 spin_lock_irqsave(hba->host->host_lock, flags);
7015 if (hba->ufshcd_state == UFSHCD_STATE_ERROR)
7017 spin_unlock_irqrestore(hba->host->host_lock, flags);
7023 * ufshcd_get_max_icc_level - calculate the ICC level
7024 * @sup_curr_uA: max. current supported by the regulator
7025 * @start_scan: row at the desc table to start scan from
7026 * @buff: power descriptor buffer
7028 * Returns calculated max ICC level for specific regulator
7030 static u32 ufshcd_get_max_icc_level(int sup_curr_uA, u32 start_scan, char *buff)
7037 for (i = start_scan; i >= 0; i--) {
7038 data = be16_to_cpup((__be16 *)&buff[2 * i]);
7039 unit = (data & ATTR_ICC_LVL_UNIT_MASK) >>
7040 ATTR_ICC_LVL_UNIT_OFFSET;
7041 curr_uA = data & ATTR_ICC_LVL_VALUE_MASK;
7043 case UFSHCD_NANO_AMP:
7044 curr_uA = curr_uA / 1000;
7046 case UFSHCD_MILI_AMP:
7047 curr_uA = curr_uA * 1000;
7050 curr_uA = curr_uA * 1000 * 1000;
7052 case UFSHCD_MICRO_AMP:
7056 if (sup_curr_uA >= curr_uA)
7061 pr_err("%s: Couldn't find valid icc_level = %d", __func__, i);
7068 * ufshcd_calc_icc_level - calculate the max ICC level
7069 * In case regulators are not initialized we'll return 0
7070 * @hba: per-adapter instance
7071 * @desc_buf: power descriptor buffer to extract ICC levels from.
7072 * @len: length of desc_buff
7074 * Returns calculated ICC level
7076 static u32 ufshcd_find_max_sup_active_icc_level(struct ufs_hba *hba,
7077 u8 *desc_buf, int len)
7081 if (!hba->vreg_info.vcc || !hba->vreg_info.vccq ||
7082 !hba->vreg_info.vccq2) {
7084 "%s: Regulator capability was not set, actvIccLevel=%d",
7085 __func__, icc_level);
7089 if (hba->vreg_info.vcc && hba->vreg_info.vcc->max_uA)
7090 icc_level = ufshcd_get_max_icc_level(
7091 hba->vreg_info.vcc->max_uA,
7092 POWER_DESC_MAX_ACTV_ICC_LVLS - 1,
7093 &desc_buf[PWR_DESC_ACTIVE_LVLS_VCC_0]);
7095 if (hba->vreg_info.vccq && hba->vreg_info.vccq->max_uA)
7096 icc_level = ufshcd_get_max_icc_level(
7097 hba->vreg_info.vccq->max_uA,
7099 &desc_buf[PWR_DESC_ACTIVE_LVLS_VCCQ_0]);
7101 if (hba->vreg_info.vccq2 && hba->vreg_info.vccq2->max_uA)
7102 icc_level = ufshcd_get_max_icc_level(
7103 hba->vreg_info.vccq2->max_uA,
7105 &desc_buf[PWR_DESC_ACTIVE_LVLS_VCCQ2_0]);
7110 static void ufshcd_set_active_icc_lvl(struct ufs_hba *hba)
7113 int buff_len = hba->desc_size[QUERY_DESC_IDN_POWER];
7117 desc_buf = kmalloc(buff_len, GFP_KERNEL);
7121 ret = ufshcd_read_desc_param(hba, QUERY_DESC_IDN_POWER, 0, 0,
7122 desc_buf, buff_len);
7125 "%s: Failed reading power descriptor.len = %d ret = %d",
7126 __func__, buff_len, ret);
7130 icc_level = ufshcd_find_max_sup_active_icc_level(hba, desc_buf,
7132 dev_dbg(hba->dev, "%s: setting icc_level 0x%x", __func__, icc_level);
7134 ret = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_WRITE_ATTR,
7135 QUERY_ATTR_IDN_ACTIVE_ICC_LVL, 0, 0, &icc_level);
7139 "%s: Failed configuring bActiveICCLevel = %d ret = %d",
7140 __func__, icc_level, ret);
7146 static inline void ufshcd_blk_pm_runtime_init(struct scsi_device *sdev)
7148 scsi_autopm_get_device(sdev);
7149 blk_pm_runtime_init(sdev->request_queue, &sdev->sdev_gendev);
7150 if (sdev->rpm_autosuspend)
7151 pm_runtime_set_autosuspend_delay(&sdev->sdev_gendev,
7152 RPM_AUTOSUSPEND_DELAY_MS);
7153 scsi_autopm_put_device(sdev);
7157 * ufshcd_scsi_add_wlus - Adds required W-LUs
7158 * @hba: per-adapter instance
7160 * UFS device specification requires the UFS devices to support 4 well known
7162 * "REPORT_LUNS" (address: 01h)
7163 * "UFS Device" (address: 50h)
7164 * "RPMB" (address: 44h)
7165 * "BOOT" (address: 30h)
7166 * UFS device's power management needs to be controlled by "POWER CONDITION"
7167 * field of SSU (START STOP UNIT) command. But this "power condition" field
7168 * will take effect only when its sent to "UFS device" well known logical unit
7169 * hence we require the scsi_device instance to represent this logical unit in
7170 * order for the UFS host driver to send the SSU command for power management.
7172 * We also require the scsi_device instance for "RPMB" (Replay Protected Memory
7173 * Block) LU so user space process can control this LU. User space may also
7174 * want to have access to BOOT LU.
7176 * This function adds scsi device instances for each of all well known LUs
7177 * (except "REPORT LUNS" LU).
7179 * Returns zero on success (all required W-LUs are added successfully),
7180 * non-zero error value on failure (if failed to add any of the required W-LU).
7182 static int ufshcd_scsi_add_wlus(struct ufs_hba *hba)
7185 struct scsi_device *sdev_boot;
7187 hba->sdev_ufs_device = __scsi_add_device(hba->host, 0, 0,
7188 ufshcd_upiu_wlun_to_scsi_wlun(UFS_UPIU_UFS_DEVICE_WLUN), NULL);
7189 if (IS_ERR(hba->sdev_ufs_device)) {
7190 ret = PTR_ERR(hba->sdev_ufs_device);
7191 hba->sdev_ufs_device = NULL;
7194 ufshcd_blk_pm_runtime_init(hba->sdev_ufs_device);
7195 scsi_device_put(hba->sdev_ufs_device);
7197 hba->sdev_rpmb = __scsi_add_device(hba->host, 0, 0,
7198 ufshcd_upiu_wlun_to_scsi_wlun(UFS_UPIU_RPMB_WLUN), NULL);
7199 if (IS_ERR(hba->sdev_rpmb)) {
7200 ret = PTR_ERR(hba->sdev_rpmb);
7201 goto remove_sdev_ufs_device;
7203 ufshcd_blk_pm_runtime_init(hba->sdev_rpmb);
7204 scsi_device_put(hba->sdev_rpmb);
7206 sdev_boot = __scsi_add_device(hba->host, 0, 0,
7207 ufshcd_upiu_wlun_to_scsi_wlun(UFS_UPIU_BOOT_WLUN), NULL);
7208 if (IS_ERR(sdev_boot)) {
7209 dev_err(hba->dev, "%s: BOOT WLUN not found\n", __func__);
7211 ufshcd_blk_pm_runtime_init(sdev_boot);
7212 scsi_device_put(sdev_boot);
7216 remove_sdev_ufs_device:
7217 scsi_remove_device(hba->sdev_ufs_device);
7222 static void ufshcd_wb_probe(struct ufs_hba *hba, u8 *desc_buf)
7224 struct ufs_dev_info *dev_info = &hba->dev_info;
7226 u32 d_lu_wb_buf_alloc;
7228 if (!ufshcd_is_wb_allowed(hba))
7231 * Probe WB only for UFS-2.2 and UFS-3.1 (and later) devices or
7232 * UFS devices with quirk UFS_DEVICE_QUIRK_SUPPORT_EXTENDED_FEATURES
7235 if (!(dev_info->wspecversion >= 0x310 ||
7236 dev_info->wspecversion == 0x220 ||
7237 (hba->dev_quirks & UFS_DEVICE_QUIRK_SUPPORT_EXTENDED_FEATURES)))
7240 if (hba->desc_size[QUERY_DESC_IDN_DEVICE] <
7241 DEVICE_DESC_PARAM_EXT_UFS_FEATURE_SUP + 4)
7244 dev_info->d_ext_ufs_feature_sup =
7245 get_unaligned_be32(desc_buf +
7246 DEVICE_DESC_PARAM_EXT_UFS_FEATURE_SUP);
7248 if (!(dev_info->d_ext_ufs_feature_sup & UFS_DEV_WRITE_BOOSTER_SUP))
7252 * WB may be supported but not configured while provisioning.
7253 * The spec says, in dedicated wb buffer mode,
7254 * a max of 1 lun would have wb buffer configured.
7255 * Now only shared buffer mode is supported.
7257 dev_info->b_wb_buffer_type =
7258 desc_buf[DEVICE_DESC_PARAM_WB_TYPE];
7260 dev_info->b_presrv_uspc_en =
7261 desc_buf[DEVICE_DESC_PARAM_WB_PRESRV_USRSPC_EN];
7263 if (dev_info->b_wb_buffer_type == WB_BUF_MODE_SHARED) {
7264 dev_info->d_wb_alloc_units =
7265 get_unaligned_be32(desc_buf +
7266 DEVICE_DESC_PARAM_WB_SHARED_ALLOC_UNITS);
7267 if (!dev_info->d_wb_alloc_units)
7270 for (lun = 0; lun < UFS_UPIU_MAX_WB_LUN_ID; lun++) {
7271 d_lu_wb_buf_alloc = 0;
7272 ufshcd_read_unit_desc_param(hba,
7274 UNIT_DESC_PARAM_WB_BUF_ALLOC_UNITS,
7275 (u8 *)&d_lu_wb_buf_alloc,
7276 sizeof(d_lu_wb_buf_alloc));
7277 if (d_lu_wb_buf_alloc) {
7278 dev_info->wb_dedicated_lu = lun;
7283 if (!d_lu_wb_buf_alloc)
7289 hba->caps &= ~UFSHCD_CAP_WB_EN;
7292 void ufshcd_fixup_dev_quirks(struct ufs_hba *hba, struct ufs_dev_fix *fixups)
7294 struct ufs_dev_fix *f;
7295 struct ufs_dev_info *dev_info = &hba->dev_info;
7300 for (f = fixups; f->quirk; f++) {
7301 if ((f->wmanufacturerid == dev_info->wmanufacturerid ||
7302 f->wmanufacturerid == UFS_ANY_VENDOR) &&
7303 ((dev_info->model &&
7304 STR_PRFX_EQUAL(f->model, dev_info->model)) ||
7305 !strcmp(f->model, UFS_ANY_MODEL)))
7306 hba->dev_quirks |= f->quirk;
7309 EXPORT_SYMBOL_GPL(ufshcd_fixup_dev_quirks);
7311 static void ufs_fixup_device_setup(struct ufs_hba *hba)
7313 /* fix by general quirk table */
7314 ufshcd_fixup_dev_quirks(hba, ufs_fixups);
7316 /* allow vendors to fix quirks */
7317 ufshcd_vops_fixup_dev_quirks(hba);
7320 static int ufs_get_device_desc(struct ufs_hba *hba)
7325 struct ufs_dev_info *dev_info = &hba->dev_info;
7327 desc_buf = kmalloc(QUERY_DESC_MAX_SIZE, GFP_KERNEL);
7333 err = ufshcd_read_desc_param(hba, QUERY_DESC_IDN_DEVICE, 0, 0, desc_buf,
7334 hba->desc_size[QUERY_DESC_IDN_DEVICE]);
7336 dev_err(hba->dev, "%s: Failed reading Device Desc. err = %d\n",
7342 * getting vendor (manufacturerID) and Bank Index in big endian
7345 dev_info->wmanufacturerid = desc_buf[DEVICE_DESC_PARAM_MANF_ID] << 8 |
7346 desc_buf[DEVICE_DESC_PARAM_MANF_ID + 1];
7348 /* getting Specification Version in big endian format */
7349 dev_info->wspecversion = desc_buf[DEVICE_DESC_PARAM_SPEC_VER] << 8 |
7350 desc_buf[DEVICE_DESC_PARAM_SPEC_VER + 1];
7352 model_index = desc_buf[DEVICE_DESC_PARAM_PRDCT_NAME];
7354 err = ufshcd_read_string_desc(hba, model_index,
7355 &dev_info->model, SD_ASCII_STD);
7357 dev_err(hba->dev, "%s: Failed reading Product Name. err = %d\n",
7362 ufs_fixup_device_setup(hba);
7364 ufshcd_wb_probe(hba, desc_buf);
7367 * ufshcd_read_string_desc returns size of the string
7368 * reset the error value
7377 static void ufs_put_device_desc(struct ufs_hba *hba)
7379 struct ufs_dev_info *dev_info = &hba->dev_info;
7381 kfree(dev_info->model);
7382 dev_info->model = NULL;
7386 * ufshcd_tune_pa_tactivate - Tunes PA_TActivate of local UniPro
7387 * @hba: per-adapter instance
7389 * PA_TActivate parameter can be tuned manually if UniPro version is less than
7390 * 1.61. PA_TActivate needs to be greater than or equal to peerM-PHY's
7391 * RX_MIN_ACTIVATETIME_CAPABILITY attribute. This optimal value can help reduce
7392 * the hibern8 exit latency.
7394 * Returns zero on success, non-zero error value on failure.
7396 static int ufshcd_tune_pa_tactivate(struct ufs_hba *hba)
7399 u32 peer_rx_min_activatetime = 0, tuned_pa_tactivate;
7401 ret = ufshcd_dme_peer_get(hba,
7403 RX_MIN_ACTIVATETIME_CAPABILITY,
7404 UIC_ARG_MPHY_RX_GEN_SEL_INDEX(0)),
7405 &peer_rx_min_activatetime);
7409 /* make sure proper unit conversion is applied */
7410 tuned_pa_tactivate =
7411 ((peer_rx_min_activatetime * RX_MIN_ACTIVATETIME_UNIT_US)
7412 / PA_TACTIVATE_TIME_UNIT_US);
7413 ret = ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TACTIVATE),
7414 tuned_pa_tactivate);
7421 * ufshcd_tune_pa_hibern8time - Tunes PA_Hibern8Time of local UniPro
7422 * @hba: per-adapter instance
7424 * PA_Hibern8Time parameter can be tuned manually if UniPro version is less than
7425 * 1.61. PA_Hibern8Time needs to be maximum of local M-PHY's
7426 * TX_HIBERN8TIME_CAPABILITY & peer M-PHY's RX_HIBERN8TIME_CAPABILITY.
7427 * This optimal value can help reduce the hibern8 exit latency.
7429 * Returns zero on success, non-zero error value on failure.
7431 static int ufshcd_tune_pa_hibern8time(struct ufs_hba *hba)
7434 u32 local_tx_hibern8_time_cap = 0, peer_rx_hibern8_time_cap = 0;
7435 u32 max_hibern8_time, tuned_pa_hibern8time;
7437 ret = ufshcd_dme_get(hba,
7438 UIC_ARG_MIB_SEL(TX_HIBERN8TIME_CAPABILITY,
7439 UIC_ARG_MPHY_TX_GEN_SEL_INDEX(0)),
7440 &local_tx_hibern8_time_cap);
7444 ret = ufshcd_dme_peer_get(hba,
7445 UIC_ARG_MIB_SEL(RX_HIBERN8TIME_CAPABILITY,
7446 UIC_ARG_MPHY_RX_GEN_SEL_INDEX(0)),
7447 &peer_rx_hibern8_time_cap);
7451 max_hibern8_time = max(local_tx_hibern8_time_cap,
7452 peer_rx_hibern8_time_cap);
7453 /* make sure proper unit conversion is applied */
7454 tuned_pa_hibern8time = ((max_hibern8_time * HIBERN8TIME_UNIT_US)
7455 / PA_HIBERN8_TIME_UNIT_US);
7456 ret = ufshcd_dme_set(hba, UIC_ARG_MIB(PA_HIBERN8TIME),
7457 tuned_pa_hibern8time);
7463 * ufshcd_quirk_tune_host_pa_tactivate - Ensures that host PA_TACTIVATE is
7464 * less than device PA_TACTIVATE time.
7465 * @hba: per-adapter instance
7467 * Some UFS devices require host PA_TACTIVATE to be lower than device
7468 * PA_TACTIVATE, we need to enable UFS_DEVICE_QUIRK_HOST_PA_TACTIVATE quirk
7471 * Returns zero on success, non-zero error value on failure.
7473 static int ufshcd_quirk_tune_host_pa_tactivate(struct ufs_hba *hba)
7476 u32 granularity, peer_granularity;
7477 u32 pa_tactivate, peer_pa_tactivate;
7478 u32 pa_tactivate_us, peer_pa_tactivate_us;
7479 u8 gran_to_us_table[] = {1, 4, 8, 16, 32, 100};
7481 ret = ufshcd_dme_get(hba, UIC_ARG_MIB(PA_GRANULARITY),
7486 ret = ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_GRANULARITY),
7491 if ((granularity < PA_GRANULARITY_MIN_VAL) ||
7492 (granularity > PA_GRANULARITY_MAX_VAL)) {
7493 dev_err(hba->dev, "%s: invalid host PA_GRANULARITY %d",
7494 __func__, granularity);
7498 if ((peer_granularity < PA_GRANULARITY_MIN_VAL) ||
7499 (peer_granularity > PA_GRANULARITY_MAX_VAL)) {
7500 dev_err(hba->dev, "%s: invalid device PA_GRANULARITY %d",
7501 __func__, peer_granularity);
7505 ret = ufshcd_dme_get(hba, UIC_ARG_MIB(PA_TACTIVATE), &pa_tactivate);
7509 ret = ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_TACTIVATE),
7510 &peer_pa_tactivate);
7514 pa_tactivate_us = pa_tactivate * gran_to_us_table[granularity - 1];
7515 peer_pa_tactivate_us = peer_pa_tactivate *
7516 gran_to_us_table[peer_granularity - 1];
7518 if (pa_tactivate_us > peer_pa_tactivate_us) {
7519 u32 new_peer_pa_tactivate;
7521 new_peer_pa_tactivate = pa_tactivate_us /
7522 gran_to_us_table[peer_granularity - 1];
7523 new_peer_pa_tactivate++;
7524 ret = ufshcd_dme_peer_set(hba, UIC_ARG_MIB(PA_TACTIVATE),
7525 new_peer_pa_tactivate);
7532 static void ufshcd_tune_unipro_params(struct ufs_hba *hba)
7534 if (ufshcd_is_unipro_pa_params_tuning_req(hba)) {
7535 ufshcd_tune_pa_tactivate(hba);
7536 ufshcd_tune_pa_hibern8time(hba);
7539 ufshcd_vops_apply_dev_quirks(hba);
7541 if (hba->dev_quirks & UFS_DEVICE_QUIRK_PA_TACTIVATE)
7542 /* set 1ms timeout for PA_TACTIVATE */
7543 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TACTIVATE), 10);
7545 if (hba->dev_quirks & UFS_DEVICE_QUIRK_HOST_PA_TACTIVATE)
7546 ufshcd_quirk_tune_host_pa_tactivate(hba);
7549 static void ufshcd_clear_dbg_ufs_stats(struct ufs_hba *hba)
7551 hba->ufs_stats.hibern8_exit_cnt = 0;
7552 hba->ufs_stats.last_hibern8_exit_tstamp = ktime_set(0, 0);
7553 hba->req_abort_count = 0;
7556 static int ufshcd_device_geo_params_init(struct ufs_hba *hba)
7562 buff_len = hba->desc_size[QUERY_DESC_IDN_GEOMETRY];
7563 desc_buf = kmalloc(buff_len, GFP_KERNEL);
7569 err = ufshcd_read_desc_param(hba, QUERY_DESC_IDN_GEOMETRY, 0, 0,
7570 desc_buf, buff_len);
7572 dev_err(hba->dev, "%s: Failed reading Geometry Desc. err = %d\n",
7577 if (desc_buf[GEOMETRY_DESC_PARAM_MAX_NUM_LUN] == 1)
7578 hba->dev_info.max_lu_supported = 32;
7579 else if (desc_buf[GEOMETRY_DESC_PARAM_MAX_NUM_LUN] == 0)
7580 hba->dev_info.max_lu_supported = 8;
7587 static struct ufs_ref_clk ufs_ref_clk_freqs[] = {
7588 {19200000, REF_CLK_FREQ_19_2_MHZ},
7589 {26000000, REF_CLK_FREQ_26_MHZ},
7590 {38400000, REF_CLK_FREQ_38_4_MHZ},
7591 {52000000, REF_CLK_FREQ_52_MHZ},
7592 {0, REF_CLK_FREQ_INVAL},
7595 static enum ufs_ref_clk_freq
7596 ufs_get_bref_clk_from_hz(unsigned long freq)
7600 for (i = 0; ufs_ref_clk_freqs[i].freq_hz; i++)
7601 if (ufs_ref_clk_freqs[i].freq_hz == freq)
7602 return ufs_ref_clk_freqs[i].val;
7604 return REF_CLK_FREQ_INVAL;
7607 void ufshcd_parse_dev_ref_clk_freq(struct ufs_hba *hba, struct clk *refclk)
7611 freq = clk_get_rate(refclk);
7613 hba->dev_ref_clk_freq =
7614 ufs_get_bref_clk_from_hz(freq);
7616 if (hba->dev_ref_clk_freq == REF_CLK_FREQ_INVAL)
7618 "invalid ref_clk setting = %ld\n", freq);
7621 static int ufshcd_set_dev_ref_clk(struct ufs_hba *hba)
7625 u32 freq = hba->dev_ref_clk_freq;
7627 err = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
7628 QUERY_ATTR_IDN_REF_CLK_FREQ, 0, 0, &ref_clk);
7631 dev_err(hba->dev, "failed reading bRefClkFreq. err = %d\n",
7636 if (ref_clk == freq)
7637 goto out; /* nothing to update */
7639 err = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_WRITE_ATTR,
7640 QUERY_ATTR_IDN_REF_CLK_FREQ, 0, 0, &freq);
7643 dev_err(hba->dev, "bRefClkFreq setting to %lu Hz failed\n",
7644 ufs_ref_clk_freqs[freq].freq_hz);
7648 dev_dbg(hba->dev, "bRefClkFreq setting to %lu Hz succeeded\n",
7649 ufs_ref_clk_freqs[freq].freq_hz);
7655 static int ufshcd_device_params_init(struct ufs_hba *hba)
7660 /* Init device descriptor sizes */
7661 for (i = 0; i < QUERY_DESC_IDN_MAX; i++)
7662 hba->desc_size[i] = QUERY_DESC_MAX_SIZE;
7664 /* Init UFS geometry descriptor related parameters */
7665 ret = ufshcd_device_geo_params_init(hba);
7669 /* Check and apply UFS device quirks */
7670 ret = ufs_get_device_desc(hba);
7672 dev_err(hba->dev, "%s: Failed getting device info. err = %d\n",
7677 ufshcd_get_ref_clk_gating_wait(hba);
7679 if (!ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_READ_FLAG,
7680 QUERY_FLAG_IDN_PWR_ON_WPE, 0, &flag))
7681 hba->dev_info.f_power_on_wp_en = flag;
7683 /* Probe maximum power mode co-supported by both UFS host and device */
7684 if (ufshcd_get_max_pwr_mode(hba))
7686 "%s: Failed getting max supported power mode\n",
7693 * ufshcd_add_lus - probe and add UFS logical units
7694 * @hba: per-adapter instance
7696 static int ufshcd_add_lus(struct ufs_hba *hba)
7700 /* Add required well known logical units to scsi mid layer */
7701 ret = ufshcd_scsi_add_wlus(hba);
7705 /* Initialize devfreq after UFS device is detected */
7706 if (ufshcd_is_clkscaling_supported(hba)) {
7707 memcpy(&hba->clk_scaling.saved_pwr_info.info,
7709 sizeof(struct ufs_pa_layer_attr));
7710 hba->clk_scaling.saved_pwr_info.is_valid = true;
7711 if (!hba->devfreq) {
7712 ret = ufshcd_devfreq_init(hba);
7717 hba->clk_scaling.is_allowed = true;
7721 scsi_scan_host(hba->host);
7722 pm_runtime_put_sync(hba->dev);
7729 ufshcd_send_request_sense(struct ufs_hba *hba, struct scsi_device *sdp);
7731 static int ufshcd_clear_ua_wlun(struct ufs_hba *hba, u8 wlun)
7733 struct scsi_device *sdp;
7734 unsigned long flags;
7737 spin_lock_irqsave(hba->host->host_lock, flags);
7738 if (wlun == UFS_UPIU_UFS_DEVICE_WLUN)
7739 sdp = hba->sdev_ufs_device;
7740 else if (wlun == UFS_UPIU_RPMB_WLUN)
7741 sdp = hba->sdev_rpmb;
7745 ret = scsi_device_get(sdp);
7746 if (!ret && !scsi_device_online(sdp)) {
7748 scsi_device_put(sdp);
7753 spin_unlock_irqrestore(hba->host->host_lock, flags);
7757 ret = ufshcd_send_request_sense(hba, sdp);
7758 scsi_device_put(sdp);
7761 dev_err(hba->dev, "%s: UAC clear LU=%x ret = %d\n",
7762 __func__, wlun, ret);
7766 static int ufshcd_clear_ua_wluns(struct ufs_hba *hba)
7770 if (!hba->wlun_dev_clr_ua)
7773 ret = ufshcd_clear_ua_wlun(hba, UFS_UPIU_UFS_DEVICE_WLUN);
7775 ret = ufshcd_clear_ua_wlun(hba, UFS_UPIU_RPMB_WLUN);
7777 hba->wlun_dev_clr_ua = false;
7780 dev_err(hba->dev, "%s: Failed to clear UAC WLUNS ret = %d\n",
7786 * ufshcd_probe_hba - probe hba to detect device and initialize
7787 * @hba: per-adapter instance
7788 * @async: asynchronous execution or not
7790 * Execute link-startup and verify device initialization
7792 static int ufshcd_probe_hba(struct ufs_hba *hba, bool async)
7795 unsigned long flags;
7796 ktime_t start = ktime_get();
7798 ret = ufshcd_link_startup(hba);
7802 /* Debug counters initialization */
7803 ufshcd_clear_dbg_ufs_stats(hba);
7805 /* UniPro link is active now */
7806 ufshcd_set_link_active(hba);
7808 /* Verify device initialization by sending NOP OUT UPIU */
7809 ret = ufshcd_verify_dev_init(hba);
7813 /* Initiate UFS initialization, and waiting until completion */
7814 ret = ufshcd_complete_dev_init(hba);
7819 * Initialize UFS device parameters used by driver, these
7820 * parameters are associated with UFS descriptors.
7823 ret = ufshcd_device_params_init(hba);
7828 ufshcd_tune_unipro_params(hba);
7830 /* UFS device is also active now */
7831 ufshcd_set_ufs_dev_active(hba);
7832 ufshcd_force_reset_auto_bkops(hba);
7833 hba->wlun_dev_clr_ua = true;
7835 /* Gear up to HS gear if supported */
7836 if (hba->max_pwr_info.is_valid) {
7838 * Set the right value to bRefClkFreq before attempting to
7839 * switch to HS gears.
7841 if (hba->dev_ref_clk_freq != REF_CLK_FREQ_INVAL)
7842 ufshcd_set_dev_ref_clk(hba);
7843 ret = ufshcd_config_pwr_mode(hba, &hba->max_pwr_info.info);
7845 dev_err(hba->dev, "%s: Failed setting power mode, err = %d\n",
7849 ufshcd_print_pwr_info(hba);
7853 * bActiveICCLevel is volatile for UFS device (as per latest v2.1 spec)
7854 * and for removable UFS card as well, hence always set the parameter.
7855 * Note: Error handler may issue the device reset hence resetting
7856 * bActiveICCLevel as well so it is always safe to set this here.
7858 ufshcd_set_active_icc_lvl(hba);
7860 ufshcd_wb_config(hba);
7861 /* Enable Auto-Hibernate if configured */
7862 ufshcd_auto_hibern8_enable(hba);
7865 spin_lock_irqsave(hba->host->host_lock, flags);
7867 hba->ufshcd_state = UFSHCD_STATE_ERROR;
7868 else if (hba->ufshcd_state == UFSHCD_STATE_RESET)
7869 hba->ufshcd_state = UFSHCD_STATE_OPERATIONAL;
7870 spin_unlock_irqrestore(hba->host->host_lock, flags);
7872 trace_ufshcd_init(dev_name(hba->dev), ret,
7873 ktime_to_us(ktime_sub(ktime_get(), start)),
7874 hba->curr_dev_pwr_mode, hba->uic_link_state);
7879 * ufshcd_async_scan - asynchronous execution for probing hba
7880 * @data: data pointer to pass to this function
7881 * @cookie: cookie data
7883 static void ufshcd_async_scan(void *data, async_cookie_t cookie)
7885 struct ufs_hba *hba = (struct ufs_hba *)data;
7889 /* Initialize hba, detect and initialize UFS device */
7890 ret = ufshcd_probe_hba(hba, true);
7895 /* Probe and add UFS logical units */
7896 ret = ufshcd_add_lus(hba);
7899 * If we failed to initialize the device or the device is not
7900 * present, turn off the power/clocks etc.
7903 pm_runtime_put_sync(hba->dev);
7904 ufshcd_exit_clk_scaling(hba);
7905 ufshcd_hba_exit(hba);
7907 ufshcd_clear_ua_wluns(hba);
7911 static const struct attribute_group *ufshcd_driver_groups[] = {
7912 &ufs_sysfs_unit_descriptor_group,
7913 &ufs_sysfs_lun_attributes_group,
7917 static struct ufs_hba_variant_params ufs_hba_vps = {
7918 .hba_enable_delay_us = 1000,
7919 .wb_flush_threshold = UFS_WB_BUF_REMAIN_PERCENT(40),
7920 .devfreq_profile.polling_ms = 100,
7921 .devfreq_profile.target = ufshcd_devfreq_target,
7922 .devfreq_profile.get_dev_status = ufshcd_devfreq_get_dev_status,
7923 .ondemand_data.upthreshold = 70,
7924 .ondemand_data.downdifferential = 5,
7927 static struct scsi_host_template ufshcd_driver_template = {
7928 .module = THIS_MODULE,
7930 .proc_name = UFSHCD,
7931 .queuecommand = ufshcd_queuecommand,
7932 .slave_alloc = ufshcd_slave_alloc,
7933 .slave_configure = ufshcd_slave_configure,
7934 .slave_destroy = ufshcd_slave_destroy,
7935 .change_queue_depth = ufshcd_change_queue_depth,
7936 .eh_abort_handler = ufshcd_abort,
7937 .eh_device_reset_handler = ufshcd_eh_device_reset_handler,
7938 .eh_host_reset_handler = ufshcd_eh_host_reset_handler,
7940 .sg_tablesize = SG_ALL,
7941 .cmd_per_lun = UFSHCD_CMD_PER_LUN,
7942 .can_queue = UFSHCD_CAN_QUEUE,
7943 .max_segment_size = PRDT_DATA_BYTE_COUNT_MAX,
7944 .max_host_blocked = 1,
7945 .track_queue_depth = 1,
7946 .sdev_groups = ufshcd_driver_groups,
7947 .dma_boundary = PAGE_SIZE - 1,
7948 .rpm_autosuspend_delay = RPM_AUTOSUSPEND_DELAY_MS,
7951 static int ufshcd_config_vreg_load(struct device *dev, struct ufs_vreg *vreg,
7960 * "set_load" operation shall be required on those regulators
7961 * which specifically configured current limitation. Otherwise
7962 * zero max_uA may cause unexpected behavior when regulator is
7963 * enabled or set as high power mode.
7968 ret = regulator_set_load(vreg->reg, ua);
7970 dev_err(dev, "%s: %s set load (ua=%d) failed, err=%d\n",
7971 __func__, vreg->name, ua, ret);
7977 static inline int ufshcd_config_vreg_lpm(struct ufs_hba *hba,
7978 struct ufs_vreg *vreg)
7980 return ufshcd_config_vreg_load(hba->dev, vreg, UFS_VREG_LPM_LOAD_UA);
7983 static inline int ufshcd_config_vreg_hpm(struct ufs_hba *hba,
7984 struct ufs_vreg *vreg)
7989 return ufshcd_config_vreg_load(hba->dev, vreg, vreg->max_uA);
7992 static int ufshcd_config_vreg(struct device *dev,
7993 struct ufs_vreg *vreg, bool on)
7996 struct regulator *reg;
7998 int min_uV, uA_load;
8005 if (regulator_count_voltages(reg) > 0) {
8006 uA_load = on ? vreg->max_uA : 0;
8007 ret = ufshcd_config_vreg_load(dev, vreg, uA_load);
8011 if (vreg->min_uV && vreg->max_uV) {
8012 min_uV = on ? vreg->min_uV : 0;
8013 ret = regulator_set_voltage(reg, min_uV, vreg->max_uV);
8016 "%s: %s set voltage failed, err=%d\n",
8017 __func__, name, ret);
8024 static int ufshcd_enable_vreg(struct device *dev, struct ufs_vreg *vreg)
8028 if (!vreg || vreg->enabled)
8031 ret = ufshcd_config_vreg(dev, vreg, true);
8033 ret = regulator_enable(vreg->reg);
8036 vreg->enabled = true;
8038 dev_err(dev, "%s: %s enable failed, err=%d\n",
8039 __func__, vreg->name, ret);
8044 static int ufshcd_disable_vreg(struct device *dev, struct ufs_vreg *vreg)
8048 if (!vreg || !vreg->enabled)
8051 ret = regulator_disable(vreg->reg);
8054 /* ignore errors on applying disable config */
8055 ufshcd_config_vreg(dev, vreg, false);
8056 vreg->enabled = false;
8058 dev_err(dev, "%s: %s disable failed, err=%d\n",
8059 __func__, vreg->name, ret);
8065 static int ufshcd_setup_vreg(struct ufs_hba *hba, bool on)
8068 struct device *dev = hba->dev;
8069 struct ufs_vreg_info *info = &hba->vreg_info;
8071 ret = ufshcd_toggle_vreg(dev, info->vcc, on);
8075 ret = ufshcd_toggle_vreg(dev, info->vccq, on);
8079 ret = ufshcd_toggle_vreg(dev, info->vccq2, on);
8083 ufshcd_toggle_vreg(dev, info->vccq2, false);
8084 ufshcd_toggle_vreg(dev, info->vccq, false);
8085 ufshcd_toggle_vreg(dev, info->vcc, false);
8090 static int ufshcd_setup_hba_vreg(struct ufs_hba *hba, bool on)
8092 struct ufs_vreg_info *info = &hba->vreg_info;
8094 return ufshcd_toggle_vreg(hba->dev, info->vdd_hba, on);
8097 static int ufshcd_get_vreg(struct device *dev, struct ufs_vreg *vreg)
8104 vreg->reg = devm_regulator_get(dev, vreg->name);
8105 if (IS_ERR(vreg->reg)) {
8106 ret = PTR_ERR(vreg->reg);
8107 dev_err(dev, "%s: %s get failed, err=%d\n",
8108 __func__, vreg->name, ret);
8114 static int ufshcd_init_vreg(struct ufs_hba *hba)
8117 struct device *dev = hba->dev;
8118 struct ufs_vreg_info *info = &hba->vreg_info;
8120 ret = ufshcd_get_vreg(dev, info->vcc);
8124 ret = ufshcd_get_vreg(dev, info->vccq);
8126 ret = ufshcd_get_vreg(dev, info->vccq2);
8131 static int ufshcd_init_hba_vreg(struct ufs_hba *hba)
8133 struct ufs_vreg_info *info = &hba->vreg_info;
8136 return ufshcd_get_vreg(hba->dev, info->vdd_hba);
8141 static int ufshcd_setup_clocks(struct ufs_hba *hba, bool on)
8144 struct ufs_clk_info *clki;
8145 struct list_head *head = &hba->clk_list_head;
8146 unsigned long flags;
8147 ktime_t start = ktime_get();
8148 bool clk_state_changed = false;
8150 if (list_empty(head))
8153 ret = ufshcd_vops_setup_clocks(hba, on, PRE_CHANGE);
8157 list_for_each_entry(clki, head, list) {
8158 if (!IS_ERR_OR_NULL(clki->clk)) {
8160 * Don't disable clocks which are needed
8161 * to keep the link active.
8163 if (ufshcd_is_link_active(hba) &&
8164 clki->keep_link_active)
8167 clk_state_changed = on ^ clki->enabled;
8168 if (on && !clki->enabled) {
8169 ret = clk_prepare_enable(clki->clk);
8171 dev_err(hba->dev, "%s: %s prepare enable failed, %d\n",
8172 __func__, clki->name, ret);
8175 } else if (!on && clki->enabled) {
8176 clk_disable_unprepare(clki->clk);
8179 dev_dbg(hba->dev, "%s: clk: %s %sabled\n", __func__,
8180 clki->name, on ? "en" : "dis");
8184 ret = ufshcd_vops_setup_clocks(hba, on, POST_CHANGE);
8190 list_for_each_entry(clki, head, list) {
8191 if (!IS_ERR_OR_NULL(clki->clk) && clki->enabled)
8192 clk_disable_unprepare(clki->clk);
8194 } else if (!ret && on) {
8195 spin_lock_irqsave(hba->host->host_lock, flags);
8196 hba->clk_gating.state = CLKS_ON;
8197 trace_ufshcd_clk_gating(dev_name(hba->dev),
8198 hba->clk_gating.state);
8199 spin_unlock_irqrestore(hba->host->host_lock, flags);
8202 if (clk_state_changed)
8203 trace_ufshcd_profile_clk_gating(dev_name(hba->dev),
8204 (on ? "on" : "off"),
8205 ktime_to_us(ktime_sub(ktime_get(), start)), ret);
8209 static int ufshcd_init_clocks(struct ufs_hba *hba)
8212 struct ufs_clk_info *clki;
8213 struct device *dev = hba->dev;
8214 struct list_head *head = &hba->clk_list_head;
8216 if (list_empty(head))
8219 list_for_each_entry(clki, head, list) {
8223 clki->clk = devm_clk_get(dev, clki->name);
8224 if (IS_ERR(clki->clk)) {
8225 ret = PTR_ERR(clki->clk);
8226 dev_err(dev, "%s: %s clk get failed, %d\n",
8227 __func__, clki->name, ret);
8232 * Parse device ref clk freq as per device tree "ref_clk".
8233 * Default dev_ref_clk_freq is set to REF_CLK_FREQ_INVAL
8234 * in ufshcd_alloc_host().
8236 if (!strcmp(clki->name, "ref_clk"))
8237 ufshcd_parse_dev_ref_clk_freq(hba, clki->clk);
8239 if (clki->max_freq) {
8240 ret = clk_set_rate(clki->clk, clki->max_freq);
8242 dev_err(hba->dev, "%s: %s clk set rate(%dHz) failed, %d\n",
8243 __func__, clki->name,
8244 clki->max_freq, ret);
8247 clki->curr_freq = clki->max_freq;
8249 dev_dbg(dev, "%s: clk: %s, rate: %lu\n", __func__,
8250 clki->name, clk_get_rate(clki->clk));
8256 static int ufshcd_variant_hba_init(struct ufs_hba *hba)
8263 err = ufshcd_vops_init(hba);
8265 dev_err(hba->dev, "%s: variant %s init failed err %d\n",
8266 __func__, ufshcd_get_var_name(hba), err);
8271 static void ufshcd_variant_hba_exit(struct ufs_hba *hba)
8276 ufshcd_vops_exit(hba);
8279 static int ufshcd_hba_init(struct ufs_hba *hba)
8284 * Handle host controller power separately from the UFS device power
8285 * rails as it will help controlling the UFS host controller power
8286 * collapse easily which is different than UFS device power collapse.
8287 * Also, enable the host controller power before we go ahead with rest
8288 * of the initialization here.
8290 err = ufshcd_init_hba_vreg(hba);
8294 err = ufshcd_setup_hba_vreg(hba, true);
8298 err = ufshcd_init_clocks(hba);
8300 goto out_disable_hba_vreg;
8302 err = ufshcd_setup_clocks(hba, true);
8304 goto out_disable_hba_vreg;
8306 err = ufshcd_init_vreg(hba);
8308 goto out_disable_clks;
8310 err = ufshcd_setup_vreg(hba, true);
8312 goto out_disable_clks;
8314 err = ufshcd_variant_hba_init(hba);
8316 goto out_disable_vreg;
8318 hba->is_powered = true;
8322 ufshcd_setup_vreg(hba, false);
8324 ufshcd_setup_clocks(hba, false);
8325 out_disable_hba_vreg:
8326 ufshcd_setup_hba_vreg(hba, false);
8331 static void ufshcd_hba_exit(struct ufs_hba *hba)
8333 if (hba->is_powered) {
8334 ufshcd_variant_hba_exit(hba);
8335 ufshcd_setup_vreg(hba, false);
8336 ufshcd_suspend_clkscaling(hba);
8337 if (ufshcd_is_clkscaling_supported(hba))
8339 ufshcd_suspend_clkscaling(hba);
8340 ufshcd_setup_clocks(hba, false);
8341 ufshcd_setup_hba_vreg(hba, false);
8342 hba->is_powered = false;
8343 ufs_put_device_desc(hba);
8348 ufshcd_send_request_sense(struct ufs_hba *hba, struct scsi_device *sdp)
8350 unsigned char cmd[6] = {REQUEST_SENSE,
8359 buffer = kzalloc(UFS_SENSE_SIZE, GFP_KERNEL);
8365 ret = scsi_execute(sdp, cmd, DMA_FROM_DEVICE, buffer,
8366 UFS_SENSE_SIZE, NULL, NULL,
8367 msecs_to_jiffies(1000), 3, 0, RQF_PM, NULL);
8369 pr_err("%s: failed with err %d\n", __func__, ret);
8377 * ufshcd_set_dev_pwr_mode - sends START STOP UNIT command to set device
8379 * @hba: per adapter instance
8380 * @pwr_mode: device power mode to set
8382 * Returns 0 if requested power mode is set successfully
8383 * Returns non-zero if failed to set the requested power mode
8385 static int ufshcd_set_dev_pwr_mode(struct ufs_hba *hba,
8386 enum ufs_dev_pwr_mode pwr_mode)
8388 unsigned char cmd[6] = { START_STOP };
8389 struct scsi_sense_hdr sshdr;
8390 struct scsi_device *sdp;
8391 unsigned long flags;
8394 spin_lock_irqsave(hba->host->host_lock, flags);
8395 sdp = hba->sdev_ufs_device;
8397 ret = scsi_device_get(sdp);
8398 if (!ret && !scsi_device_online(sdp)) {
8400 scsi_device_put(sdp);
8405 spin_unlock_irqrestore(hba->host->host_lock, flags);
8411 * If scsi commands fail, the scsi mid-layer schedules scsi error-
8412 * handling, which would wait for host to be resumed. Since we know
8413 * we are functional while we are here, skip host resume in error
8416 hba->host->eh_noresume = 1;
8417 if (hba->wlun_dev_clr_ua) {
8418 ret = ufshcd_send_request_sense(hba, sdp);
8421 /* Unit attention condition is cleared now */
8422 hba->wlun_dev_clr_ua = false;
8425 cmd[4] = pwr_mode << 4;
8428 * Current function would be generally called from the power management
8429 * callbacks hence set the RQF_PM flag so that it doesn't resume the
8430 * already suspended childs.
8432 ret = scsi_execute(sdp, cmd, DMA_NONE, NULL, 0, NULL, &sshdr,
8433 START_STOP_TIMEOUT, 0, 0, RQF_PM, NULL);
8435 sdev_printk(KERN_WARNING, sdp,
8436 "START_STOP failed for power mode: %d, result %x\n",
8438 if (driver_byte(ret) == DRIVER_SENSE)
8439 scsi_print_sense_hdr(sdp, NULL, &sshdr);
8443 hba->curr_dev_pwr_mode = pwr_mode;
8445 scsi_device_put(sdp);
8446 hba->host->eh_noresume = 0;
8450 static int ufshcd_link_state_transition(struct ufs_hba *hba,
8451 enum uic_link_state req_link_state,
8452 int check_for_bkops)
8456 if (req_link_state == hba->uic_link_state)
8459 if (req_link_state == UIC_LINK_HIBERN8_STATE) {
8460 ret = ufshcd_uic_hibern8_enter(hba);
8462 ufshcd_set_link_hibern8(hba);
8464 dev_err(hba->dev, "%s: hibern8 enter failed %d\n",
8470 * If autobkops is enabled, link can't be turned off because
8471 * turning off the link would also turn off the device, except in the
8472 * case of DeepSleep where the device is expected to remain powered.
8474 else if ((req_link_state == UIC_LINK_OFF_STATE) &&
8475 (!check_for_bkops || !hba->auto_bkops_enabled)) {
8477 * Let's make sure that link is in low power mode, we are doing
8478 * this currently by putting the link in Hibern8. Otherway to
8479 * put the link in low power mode is to send the DME end point
8480 * to device and then send the DME reset command to local
8481 * unipro. But putting the link in hibern8 is much faster.
8483 * Note also that putting the link in Hibern8 is a requirement
8484 * for entering DeepSleep.
8486 ret = ufshcd_uic_hibern8_enter(hba);
8488 dev_err(hba->dev, "%s: hibern8 enter failed %d\n",
8493 * Change controller state to "reset state" which
8494 * should also put the link in off/reset state
8496 ufshcd_hba_stop(hba);
8498 * TODO: Check if we need any delay to make sure that
8499 * controller is reset
8501 ufshcd_set_link_off(hba);
8508 static void ufshcd_vreg_set_lpm(struct ufs_hba *hba)
8510 bool vcc_off = false;
8513 * It seems some UFS devices may keep drawing more than sleep current
8514 * (atleast for 500us) from UFS rails (especially from VCCQ rail).
8515 * To avoid this situation, add 2ms delay before putting these UFS
8516 * rails in LPM mode.
8518 if (!ufshcd_is_link_active(hba) &&
8519 hba->dev_quirks & UFS_DEVICE_QUIRK_DELAY_BEFORE_LPM)
8520 usleep_range(2000, 2100);
8523 * If UFS device is either in UFS_Sleep turn off VCC rail to save some
8526 * If UFS device and link is in OFF state, all power supplies (VCC,
8527 * VCCQ, VCCQ2) can be turned off if power on write protect is not
8528 * required. If UFS link is inactive (Hibern8 or OFF state) and device
8529 * is in sleep state, put VCCQ & VCCQ2 rails in LPM mode.
8531 * Ignore the error returned by ufshcd_toggle_vreg() as device is anyway
8532 * in low power state which would save some power.
8534 * If Write Booster is enabled and the device needs to flush the WB
8535 * buffer OR if bkops status is urgent for WB, keep Vcc on.
8537 if (ufshcd_is_ufs_dev_poweroff(hba) && ufshcd_is_link_off(hba) &&
8538 !hba->dev_info.is_lu_power_on_wp) {
8539 ufshcd_setup_vreg(hba, false);
8541 } else if (!ufshcd_is_ufs_dev_active(hba)) {
8542 ufshcd_toggle_vreg(hba->dev, hba->vreg_info.vcc, false);
8544 if (!ufshcd_is_link_active(hba)) {
8545 ufshcd_config_vreg_lpm(hba, hba->vreg_info.vccq);
8546 ufshcd_config_vreg_lpm(hba, hba->vreg_info.vccq2);
8551 * Some UFS devices require delay after VCC power rail is turned-off.
8553 if (vcc_off && hba->vreg_info.vcc &&
8554 hba->dev_quirks & UFS_DEVICE_QUIRK_DELAY_AFTER_LPM)
8555 usleep_range(5000, 5100);
8558 static int ufshcd_vreg_set_hpm(struct ufs_hba *hba)
8562 if (ufshcd_is_ufs_dev_poweroff(hba) && ufshcd_is_link_off(hba) &&
8563 !hba->dev_info.is_lu_power_on_wp) {
8564 ret = ufshcd_setup_vreg(hba, true);
8565 } else if (!ufshcd_is_ufs_dev_active(hba)) {
8566 if (!ret && !ufshcd_is_link_active(hba)) {
8567 ret = ufshcd_config_vreg_hpm(hba, hba->vreg_info.vccq);
8570 ret = ufshcd_config_vreg_hpm(hba, hba->vreg_info.vccq2);
8574 ret = ufshcd_toggle_vreg(hba->dev, hba->vreg_info.vcc, true);
8579 ufshcd_config_vreg_lpm(hba, hba->vreg_info.vccq);
8581 ufshcd_toggle_vreg(hba->dev, hba->vreg_info.vcc, false);
8586 static void ufshcd_hba_vreg_set_lpm(struct ufs_hba *hba)
8588 if (ufshcd_is_link_off(hba) || ufshcd_can_aggressive_pc(hba))
8589 ufshcd_setup_hba_vreg(hba, false);
8592 static void ufshcd_hba_vreg_set_hpm(struct ufs_hba *hba)
8594 if (ufshcd_is_link_off(hba) || ufshcd_can_aggressive_pc(hba))
8595 ufshcd_setup_hba_vreg(hba, true);
8599 * ufshcd_suspend - helper function for suspend operations
8600 * @hba: per adapter instance
8601 * @pm_op: desired low power operation type
8603 * This function will try to put the UFS device and link into low power
8604 * mode based on the "rpm_lvl" (Runtime PM level) or "spm_lvl"
8605 * (System PM level).
8607 * If this function is called during shutdown, it will make sure that
8608 * both UFS device and UFS link is powered off.
8610 * NOTE: UFS device & link must be active before we enter in this function.
8612 * Returns 0 for success and non-zero for failure
8614 static int ufshcd_suspend(struct ufs_hba *hba, enum ufs_pm_op pm_op)
8617 int check_for_bkops;
8618 enum ufs_pm_level pm_lvl;
8619 enum ufs_dev_pwr_mode req_dev_pwr_mode;
8620 enum uic_link_state req_link_state;
8622 hba->pm_op_in_progress = 1;
8623 if (!ufshcd_is_shutdown_pm(pm_op)) {
8624 pm_lvl = ufshcd_is_runtime_pm(pm_op) ?
8625 hba->rpm_lvl : hba->spm_lvl;
8626 req_dev_pwr_mode = ufs_get_pm_lvl_to_dev_pwr_mode(pm_lvl);
8627 req_link_state = ufs_get_pm_lvl_to_link_pwr_state(pm_lvl);
8629 req_dev_pwr_mode = UFS_POWERDOWN_PWR_MODE;
8630 req_link_state = UIC_LINK_OFF_STATE;
8634 * If we can't transition into any of the low power modes
8635 * just gate the clocks.
8637 ufshcd_hold(hba, false);
8638 hba->clk_gating.is_suspended = true;
8640 if (hba->clk_scaling.is_allowed) {
8641 cancel_work_sync(&hba->clk_scaling.suspend_work);
8642 cancel_work_sync(&hba->clk_scaling.resume_work);
8643 ufshcd_suspend_clkscaling(hba);
8646 if (req_dev_pwr_mode == UFS_ACTIVE_PWR_MODE &&
8647 req_link_state == UIC_LINK_ACTIVE_STATE) {
8651 if ((req_dev_pwr_mode == hba->curr_dev_pwr_mode) &&
8652 (req_link_state == hba->uic_link_state))
8655 /* UFS device & link must be active before we enter in this function */
8656 if (!ufshcd_is_ufs_dev_active(hba) || !ufshcd_is_link_active(hba)) {
8661 if (ufshcd_is_runtime_pm(pm_op)) {
8662 if (ufshcd_can_autobkops_during_suspend(hba)) {
8664 * The device is idle with no requests in the queue,
8665 * allow background operations if bkops status shows
8666 * that performance might be impacted.
8668 ret = ufshcd_urgent_bkops(hba);
8672 /* make sure that auto bkops is disabled */
8673 ufshcd_disable_auto_bkops(hba);
8676 * If device needs to do BKOP or WB buffer flush during
8677 * Hibern8, keep device power mode as "active power mode"
8680 hba->dev_info.b_rpm_dev_flush_capable =
8681 hba->auto_bkops_enabled ||
8682 (((req_link_state == UIC_LINK_HIBERN8_STATE) ||
8683 ((req_link_state == UIC_LINK_ACTIVE_STATE) &&
8684 ufshcd_is_auto_hibern8_enabled(hba))) &&
8685 ufshcd_wb_need_flush(hba));
8688 if (req_dev_pwr_mode != hba->curr_dev_pwr_mode) {
8689 if (!ufshcd_is_runtime_pm(pm_op))
8690 /* ensure that bkops is disabled */
8691 ufshcd_disable_auto_bkops(hba);
8693 if (!hba->dev_info.b_rpm_dev_flush_capable) {
8694 ret = ufshcd_set_dev_pwr_mode(hba, req_dev_pwr_mode);
8700 flush_work(&hba->eeh_work);
8703 * In the case of DeepSleep, the device is expected to remain powered
8704 * with the link off, so do not check for bkops.
8706 check_for_bkops = !ufshcd_is_ufs_dev_deepsleep(hba);
8707 ret = ufshcd_link_state_transition(hba, req_link_state, check_for_bkops);
8709 goto set_dev_active;
8711 ufshcd_vreg_set_lpm(hba);
8715 * Call vendor specific suspend callback. As these callbacks may access
8716 * vendor specific host controller register space call them before the
8717 * host clocks are ON.
8719 ret = ufshcd_vops_suspend(hba, pm_op);
8721 goto set_link_active;
8723 * Disable the host irq as host controller as there won't be any
8724 * host controller transaction expected till resume.
8726 ufshcd_disable_irq(hba);
8728 ufshcd_setup_clocks(hba, false);
8730 if (ufshcd_is_clkgating_allowed(hba)) {
8731 hba->clk_gating.state = CLKS_OFF;
8732 trace_ufshcd_clk_gating(dev_name(hba->dev),
8733 hba->clk_gating.state);
8736 /* Put the host controller in low power mode if possible */
8737 ufshcd_hba_vreg_set_lpm(hba);
8741 if (hba->clk_scaling.is_allowed)
8742 ufshcd_resume_clkscaling(hba);
8743 ufshcd_vreg_set_hpm(hba);
8745 * Device hardware reset is required to exit DeepSleep. Also, for
8746 * DeepSleep, the link is off so host reset and restore will be done
8749 if (ufshcd_is_ufs_dev_deepsleep(hba)) {
8750 ufshcd_vops_device_reset(hba);
8751 WARN_ON(!ufshcd_is_link_off(hba));
8753 if (ufshcd_is_link_hibern8(hba) && !ufshcd_uic_hibern8_exit(hba))
8754 ufshcd_set_link_active(hba);
8755 else if (ufshcd_is_link_off(hba))
8756 ufshcd_host_reset_and_restore(hba);
8758 /* Can also get here needing to exit DeepSleep */
8759 if (ufshcd_is_ufs_dev_deepsleep(hba)) {
8760 ufshcd_vops_device_reset(hba);
8761 ufshcd_host_reset_and_restore(hba);
8763 if (!ufshcd_set_dev_pwr_mode(hba, UFS_ACTIVE_PWR_MODE))
8764 ufshcd_disable_auto_bkops(hba);
8766 if (hba->clk_scaling.is_allowed)
8767 ufshcd_resume_clkscaling(hba);
8768 hba->clk_gating.is_suspended = false;
8769 hba->dev_info.b_rpm_dev_flush_capable = false;
8770 ufshcd_release(hba);
8772 if (hba->dev_info.b_rpm_dev_flush_capable) {
8773 schedule_delayed_work(&hba->rpm_dev_flush_recheck_work,
8774 msecs_to_jiffies(RPM_DEV_FLUSH_RECHECK_WORK_DELAY_MS));
8777 hba->pm_op_in_progress = 0;
8780 ufshcd_update_evt_hist(hba, UFS_EVT_SUSPEND_ERR, (u32)ret);
8785 * ufshcd_resume - helper function for resume operations
8786 * @hba: per adapter instance
8787 * @pm_op: runtime PM or system PM
8789 * This function basically brings the UFS device, UniPro link and controller
8792 * Returns 0 for success and non-zero for failure
8794 static int ufshcd_resume(struct ufs_hba *hba, enum ufs_pm_op pm_op)
8797 enum uic_link_state old_link_state;
8799 hba->pm_op_in_progress = 1;
8800 old_link_state = hba->uic_link_state;
8802 ufshcd_hba_vreg_set_hpm(hba);
8803 /* Make sure clocks are enabled before accessing controller */
8804 ret = ufshcd_setup_clocks(hba, true);
8808 /* enable the host irq as host controller would be active soon */
8809 ufshcd_enable_irq(hba);
8811 ret = ufshcd_vreg_set_hpm(hba);
8813 goto disable_irq_and_vops_clks;
8816 * Call vendor specific resume callback. As these callbacks may access
8817 * vendor specific host controller register space call them when the
8818 * host clocks are ON.
8820 ret = ufshcd_vops_resume(hba, pm_op);
8824 /* For DeepSleep, the only supported option is to have the link off */
8825 WARN_ON(ufshcd_is_ufs_dev_deepsleep(hba) && !ufshcd_is_link_off(hba));
8827 if (ufshcd_is_link_hibern8(hba)) {
8828 ret = ufshcd_uic_hibern8_exit(hba);
8830 ufshcd_set_link_active(hba);
8832 dev_err(hba->dev, "%s: hibern8 exit failed %d\n",
8834 goto vendor_suspend;
8836 } else if (ufshcd_is_link_off(hba)) {
8838 * A full initialization of the host and the device is
8839 * required since the link was put to off during suspend.
8840 * Note, in the case of DeepSleep, the device will exit
8841 * DeepSleep due to device reset.
8843 ret = ufshcd_reset_and_restore(hba);
8845 * ufshcd_reset_and_restore() should have already
8846 * set the link state as active
8848 if (ret || !ufshcd_is_link_active(hba))
8849 goto vendor_suspend;
8852 if (!ufshcd_is_ufs_dev_active(hba)) {
8853 ret = ufshcd_set_dev_pwr_mode(hba, UFS_ACTIVE_PWR_MODE);
8855 goto set_old_link_state;
8858 if (ufshcd_keep_autobkops_enabled_except_suspend(hba))
8859 ufshcd_enable_auto_bkops(hba);
8862 * If BKOPs operations are urgently needed at this moment then
8863 * keep auto-bkops enabled or else disable it.
8865 ufshcd_urgent_bkops(hba);
8867 hba->clk_gating.is_suspended = false;
8869 if (hba->clk_scaling.is_allowed)
8870 ufshcd_resume_clkscaling(hba);
8872 /* Enable Auto-Hibernate if configured */
8873 ufshcd_auto_hibern8_enable(hba);
8875 if (hba->dev_info.b_rpm_dev_flush_capable) {
8876 hba->dev_info.b_rpm_dev_flush_capable = false;
8877 cancel_delayed_work(&hba->rpm_dev_flush_recheck_work);
8880 /* Schedule clock gating in case of no access to UFS device yet */
8881 ufshcd_release(hba);
8886 ufshcd_link_state_transition(hba, old_link_state, 0);
8888 ufshcd_vops_suspend(hba, pm_op);
8890 ufshcd_vreg_set_lpm(hba);
8891 disable_irq_and_vops_clks:
8892 ufshcd_disable_irq(hba);
8893 if (hba->clk_scaling.is_allowed)
8894 ufshcd_suspend_clkscaling(hba);
8895 ufshcd_setup_clocks(hba, false);
8896 if (ufshcd_is_clkgating_allowed(hba)) {
8897 hba->clk_gating.state = CLKS_OFF;
8898 trace_ufshcd_clk_gating(dev_name(hba->dev),
8899 hba->clk_gating.state);
8902 hba->pm_op_in_progress = 0;
8904 ufshcd_update_evt_hist(hba, UFS_EVT_RESUME_ERR, (u32)ret);
8909 * ufshcd_system_suspend - system suspend routine
8910 * @hba: per adapter instance
8912 * Check the description of ufshcd_suspend() function for more details.
8914 * Returns 0 for success and non-zero for failure
8916 int ufshcd_system_suspend(struct ufs_hba *hba)
8919 ktime_t start = ktime_get();
8922 if (!hba || !hba->is_powered)
8925 if ((ufs_get_pm_lvl_to_dev_pwr_mode(hba->spm_lvl) ==
8926 hba->curr_dev_pwr_mode) &&
8927 (ufs_get_pm_lvl_to_link_pwr_state(hba->spm_lvl) ==
8928 hba->uic_link_state))
8931 if (pm_runtime_suspended(hba->dev)) {
8933 * UFS device and/or UFS link low power states during runtime
8934 * suspend seems to be different than what is expected during
8935 * system suspend. Hence runtime resume the devic & link and
8936 * let the system suspend low power states to take effect.
8937 * TODO: If resume takes longer time, we might have optimize
8938 * it in future by not resuming everything if possible.
8940 ret = ufshcd_runtime_resume(hba);
8945 ret = ufshcd_suspend(hba, UFS_SYSTEM_PM);
8947 trace_ufshcd_system_suspend(dev_name(hba->dev), ret,
8948 ktime_to_us(ktime_sub(ktime_get(), start)),
8949 hba->curr_dev_pwr_mode, hba->uic_link_state);
8951 hba->is_sys_suspended = true;
8956 EXPORT_SYMBOL(ufshcd_system_suspend);
8959 * ufshcd_system_resume - system resume routine
8960 * @hba: per adapter instance
8962 * Returns 0 for success and non-zero for failure
8965 int ufshcd_system_resume(struct ufs_hba *hba)
8968 ktime_t start = ktime_get();
8975 if (!hba->is_powered || pm_runtime_suspended(hba->dev))
8977 * Let the runtime resume take care of resuming
8978 * if runtime suspended.
8982 ret = ufshcd_resume(hba, UFS_SYSTEM_PM);
8984 trace_ufshcd_system_resume(dev_name(hba->dev), ret,
8985 ktime_to_us(ktime_sub(ktime_get(), start)),
8986 hba->curr_dev_pwr_mode, hba->uic_link_state);
8988 hba->is_sys_suspended = false;
8992 EXPORT_SYMBOL(ufshcd_system_resume);
8995 * ufshcd_runtime_suspend - runtime suspend routine
8996 * @hba: per adapter instance
8998 * Check the description of ufshcd_suspend() function for more details.
9000 * Returns 0 for success and non-zero for failure
9002 int ufshcd_runtime_suspend(struct ufs_hba *hba)
9005 ktime_t start = ktime_get();
9010 if (!hba->is_powered)
9013 ret = ufshcd_suspend(hba, UFS_RUNTIME_PM);
9015 trace_ufshcd_runtime_suspend(dev_name(hba->dev), ret,
9016 ktime_to_us(ktime_sub(ktime_get(), start)),
9017 hba->curr_dev_pwr_mode, hba->uic_link_state);
9020 EXPORT_SYMBOL(ufshcd_runtime_suspend);
9023 * ufshcd_runtime_resume - runtime resume routine
9024 * @hba: per adapter instance
9026 * This function basically brings the UFS device, UniPro link and controller
9027 * to active state. Following operations are done in this function:
9029 * 1. Turn on all the controller related clocks
9030 * 2. Bring the UniPro link out of Hibernate state
9031 * 3. If UFS device is in sleep state, turn ON VCC rail and bring the UFS device
9033 * 4. If auto-bkops is enabled on the device, disable it.
9035 * So following would be the possible power state after this function return
9037 * S1: UFS device in Active state with VCC rail ON
9038 * UniPro link in Active state
9039 * All the UFS/UniPro controller clocks are ON
9041 * Returns 0 for success and non-zero for failure
9043 int ufshcd_runtime_resume(struct ufs_hba *hba)
9046 ktime_t start = ktime_get();
9051 if (!hba->is_powered)
9054 ret = ufshcd_resume(hba, UFS_RUNTIME_PM);
9056 trace_ufshcd_runtime_resume(dev_name(hba->dev), ret,
9057 ktime_to_us(ktime_sub(ktime_get(), start)),
9058 hba->curr_dev_pwr_mode, hba->uic_link_state);
9061 EXPORT_SYMBOL(ufshcd_runtime_resume);
9063 int ufshcd_runtime_idle(struct ufs_hba *hba)
9067 EXPORT_SYMBOL(ufshcd_runtime_idle);
9070 * ufshcd_shutdown - shutdown routine
9071 * @hba: per adapter instance
9073 * This function would power off both UFS device and UFS link.
9075 * Returns 0 always to allow force shutdown even in case of errors.
9077 int ufshcd_shutdown(struct ufs_hba *hba)
9082 if (!hba->is_powered)
9085 if (ufshcd_is_ufs_dev_poweroff(hba) && ufshcd_is_link_off(hba))
9088 pm_runtime_get_sync(hba->dev);
9090 ret = ufshcd_suspend(hba, UFS_SHUTDOWN_PM);
9093 dev_err(hba->dev, "%s failed, err %d\n", __func__, ret);
9094 hba->is_powered = false;
9096 /* allow force shutdown even in case of errors */
9099 EXPORT_SYMBOL(ufshcd_shutdown);
9102 * ufshcd_remove - de-allocate SCSI host and host memory space
9103 * data structure memory
9104 * @hba: per adapter instance
9106 void ufshcd_remove(struct ufs_hba *hba)
9108 ufs_bsg_remove(hba);
9109 ufs_sysfs_remove_nodes(hba->dev);
9110 blk_cleanup_queue(hba->tmf_queue);
9111 blk_mq_free_tag_set(&hba->tmf_tag_set);
9112 blk_cleanup_queue(hba->cmd_queue);
9113 scsi_remove_host(hba->host);
9114 destroy_workqueue(hba->eh_wq);
9115 /* disable interrupts */
9116 ufshcd_disable_intr(hba, hba->intr_mask);
9117 ufshcd_hba_stop(hba);
9119 ufshcd_exit_clk_scaling(hba);
9120 ufshcd_exit_clk_gating(hba);
9121 if (ufshcd_is_clkscaling_supported(hba))
9122 device_remove_file(hba->dev, &hba->clk_scaling.enable_attr);
9123 ufshcd_hba_exit(hba);
9125 EXPORT_SYMBOL_GPL(ufshcd_remove);
9128 * ufshcd_dealloc_host - deallocate Host Bus Adapter (HBA)
9129 * @hba: pointer to Host Bus Adapter (HBA)
9131 void ufshcd_dealloc_host(struct ufs_hba *hba)
9133 ufshcd_crypto_destroy_keyslot_manager(hba);
9134 scsi_host_put(hba->host);
9136 EXPORT_SYMBOL_GPL(ufshcd_dealloc_host);
9139 * ufshcd_set_dma_mask - Set dma mask based on the controller
9140 * addressing capability
9141 * @hba: per adapter instance
9143 * Returns 0 for success, non-zero for failure
9145 static int ufshcd_set_dma_mask(struct ufs_hba *hba)
9147 if (hba->capabilities & MASK_64_ADDRESSING_SUPPORT) {
9148 if (!dma_set_mask_and_coherent(hba->dev, DMA_BIT_MASK(64)))
9151 return dma_set_mask_and_coherent(hba->dev, DMA_BIT_MASK(32));
9155 * ufshcd_alloc_host - allocate Host Bus Adapter (HBA)
9156 * @dev: pointer to device handle
9157 * @hba_handle: driver private handle
9158 * Returns 0 on success, non-zero value on failure
9160 int ufshcd_alloc_host(struct device *dev, struct ufs_hba **hba_handle)
9162 struct Scsi_Host *host;
9163 struct ufs_hba *hba;
9168 "Invalid memory reference for dev is NULL\n");
9173 host = scsi_host_alloc(&ufshcd_driver_template,
9174 sizeof(struct ufs_hba));
9176 dev_err(dev, "scsi_host_alloc failed\n");
9180 hba = shost_priv(host);
9184 hba->dev_ref_clk_freq = REF_CLK_FREQ_INVAL;
9186 INIT_LIST_HEAD(&hba->clk_list_head);
9191 EXPORT_SYMBOL(ufshcd_alloc_host);
9193 /* This function exists because blk_mq_alloc_tag_set() requires this. */
9194 static blk_status_t ufshcd_queue_tmf(struct blk_mq_hw_ctx *hctx,
9195 const struct blk_mq_queue_data *qd)
9198 return BLK_STS_NOTSUPP;
9201 static const struct blk_mq_ops ufshcd_tmf_ops = {
9202 .queue_rq = ufshcd_queue_tmf,
9206 * ufshcd_init - Driver initialization routine
9207 * @hba: per-adapter instance
9208 * @mmio_base: base register address
9209 * @irq: Interrupt line of device
9210 * Returns 0 on success, non-zero value on failure
9212 int ufshcd_init(struct ufs_hba *hba, void __iomem *mmio_base, unsigned int irq)
9215 struct Scsi_Host *host = hba->host;
9216 struct device *dev = hba->dev;
9217 char eh_wq_name[sizeof("ufs_eh_wq_00")];
9221 "Invalid memory reference for mmio_base is NULL\n");
9226 hba->mmio_base = mmio_base;
9228 hba->vps = &ufs_hba_vps;
9230 err = ufshcd_hba_init(hba);
9234 /* Read capabilities registers */
9235 err = ufshcd_hba_capabilities(hba);
9239 /* Get UFS version supported by the controller */
9240 hba->ufs_version = ufshcd_get_ufs_version(hba);
9242 if ((hba->ufs_version != UFSHCI_VERSION_10) &&
9243 (hba->ufs_version != UFSHCI_VERSION_11) &&
9244 (hba->ufs_version != UFSHCI_VERSION_20) &&
9245 (hba->ufs_version != UFSHCI_VERSION_21))
9246 dev_err(hba->dev, "invalid UFS version 0x%x\n",
9249 /* Get Interrupt bit mask per version */
9250 hba->intr_mask = ufshcd_get_intr_mask(hba);
9252 err = ufshcd_set_dma_mask(hba);
9254 dev_err(hba->dev, "set dma mask failed\n");
9258 /* Allocate memory for host memory space */
9259 err = ufshcd_memory_alloc(hba);
9261 dev_err(hba->dev, "Memory allocation failed\n");
9266 ufshcd_host_memory_configure(hba);
9268 host->can_queue = hba->nutrs;
9269 host->cmd_per_lun = hba->nutrs;
9270 host->max_id = UFSHCD_MAX_ID;
9271 host->max_lun = UFS_MAX_LUNS;
9272 host->max_channel = UFSHCD_MAX_CHANNEL;
9273 host->unique_id = host->host_no;
9274 host->max_cmd_len = UFS_CDB_SIZE;
9276 hba->max_pwr_info.is_valid = false;
9278 /* Initialize work queues */
9279 snprintf(eh_wq_name, sizeof(eh_wq_name), "ufs_eh_wq_%d",
9280 hba->host->host_no);
9281 hba->eh_wq = create_singlethread_workqueue(eh_wq_name);
9283 dev_err(hba->dev, "%s: failed to create eh workqueue\n",
9288 INIT_WORK(&hba->eh_work, ufshcd_err_handler);
9289 INIT_WORK(&hba->eeh_work, ufshcd_exception_event_handler);
9291 sema_init(&hba->eh_sem, 1);
9293 /* Initialize UIC command mutex */
9294 mutex_init(&hba->uic_cmd_mutex);
9296 /* Initialize mutex for device management commands */
9297 mutex_init(&hba->dev_cmd.lock);
9299 init_rwsem(&hba->clk_scaling_lock);
9301 ufshcd_init_clk_gating(hba);
9303 ufshcd_init_clk_scaling(hba);
9306 * In order to avoid any spurious interrupt immediately after
9307 * registering UFS controller interrupt handler, clear any pending UFS
9308 * interrupt status and disable all the UFS interrupts.
9310 ufshcd_writel(hba, ufshcd_readl(hba, REG_INTERRUPT_STATUS),
9311 REG_INTERRUPT_STATUS);
9312 ufshcd_writel(hba, 0, REG_INTERRUPT_ENABLE);
9314 * Make sure that UFS interrupts are disabled and any pending interrupt
9315 * status is cleared before registering UFS interrupt handler.
9319 /* IRQ registration */
9320 err = devm_request_irq(dev, irq, ufshcd_intr, IRQF_SHARED, UFSHCD, hba);
9322 dev_err(hba->dev, "request irq failed\n");
9325 hba->is_irq_enabled = true;
9328 err = scsi_add_host(host, hba->dev);
9330 dev_err(hba->dev, "scsi_add_host failed\n");
9334 hba->cmd_queue = blk_mq_init_queue(&hba->host->tag_set);
9335 if (IS_ERR(hba->cmd_queue)) {
9336 err = PTR_ERR(hba->cmd_queue);
9337 goto out_remove_scsi_host;
9340 hba->tmf_tag_set = (struct blk_mq_tag_set) {
9342 .queue_depth = hba->nutmrs,
9343 .ops = &ufshcd_tmf_ops,
9344 .flags = BLK_MQ_F_NO_SCHED,
9346 err = blk_mq_alloc_tag_set(&hba->tmf_tag_set);
9348 goto free_cmd_queue;
9349 hba->tmf_queue = blk_mq_init_queue(&hba->tmf_tag_set);
9350 if (IS_ERR(hba->tmf_queue)) {
9351 err = PTR_ERR(hba->tmf_queue);
9352 goto free_tmf_tag_set;
9355 /* Reset the attached device */
9356 ufshcd_vops_device_reset(hba);
9358 ufshcd_init_crypto(hba);
9360 /* Host controller enable */
9361 err = ufshcd_hba_enable(hba);
9363 dev_err(hba->dev, "Host controller enable failed\n");
9364 ufshcd_print_evt_hist(hba);
9365 ufshcd_print_host_state(hba);
9366 goto free_tmf_queue;
9370 * Set the default power management level for runtime and system PM.
9371 * Default power saving mode is to keep UFS link in Hibern8 state
9372 * and UFS device in sleep state.
9374 hba->rpm_lvl = ufs_get_desired_pm_lvl_for_dev_link_state(
9376 UIC_LINK_HIBERN8_STATE);
9377 hba->spm_lvl = ufs_get_desired_pm_lvl_for_dev_link_state(
9379 UIC_LINK_HIBERN8_STATE);
9381 INIT_DELAYED_WORK(&hba->rpm_dev_flush_recheck_work,
9382 ufshcd_rpm_dev_flush_recheck_work);
9384 /* Set the default auto-hiberate idle timer value to 150 ms */
9385 if (ufshcd_is_auto_hibern8_supported(hba) && !hba->ahit) {
9386 hba->ahit = FIELD_PREP(UFSHCI_AHIBERN8_TIMER_MASK, 150) |
9387 FIELD_PREP(UFSHCI_AHIBERN8_SCALE_MASK, 3);
9390 /* Hold auto suspend until async scan completes */
9391 pm_runtime_get_sync(dev);
9392 atomic_set(&hba->scsi_block_reqs_cnt, 0);
9394 * We are assuming that device wasn't put in sleep/power-down
9395 * state exclusively during the boot stage before kernel.
9396 * This assumption helps avoid doing link startup twice during
9397 * ufshcd_probe_hba().
9399 ufshcd_set_ufs_dev_active(hba);
9401 async_schedule(ufshcd_async_scan, hba);
9402 ufs_sysfs_add_nodes(hba->dev);
9407 blk_cleanup_queue(hba->tmf_queue);
9409 blk_mq_free_tag_set(&hba->tmf_tag_set);
9411 blk_cleanup_queue(hba->cmd_queue);
9412 out_remove_scsi_host:
9413 scsi_remove_host(hba->host);
9415 ufshcd_exit_clk_scaling(hba);
9416 ufshcd_exit_clk_gating(hba);
9417 destroy_workqueue(hba->eh_wq);
9419 hba->is_irq_enabled = false;
9420 ufshcd_hba_exit(hba);
9424 EXPORT_SYMBOL_GPL(ufshcd_init);
9426 MODULE_AUTHOR("Santosh Yaragnavi <santosh.sy@samsung.com>");
9427 MODULE_AUTHOR("Vinayak Holikatti <h.vinayak@samsung.com>");
9428 MODULE_DESCRIPTION("Generic UFS host controller driver Core");
9429 MODULE_LICENSE("GPL");
9430 MODULE_VERSION(UFSHCD_DRIVER_VERSION);