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"
23 #include "ufs-debugfs.h"
25 #include "ufshcd-crypto.h"
26 #include <asm/unaligned.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 static bool early_suspend;
99 int ufshcd_dump_regs(struct ufs_hba *hba, size_t offset, size_t len,
105 if (offset % 4 != 0 || len % 4 != 0) /* keep readl happy */
108 regs = kzalloc(len, GFP_ATOMIC);
112 for (pos = 0; pos < len; pos += 4)
113 regs[pos / 4] = ufshcd_readl(hba, offset + pos);
115 ufshcd_hex_dump(prefix, regs, len);
120 EXPORT_SYMBOL_GPL(ufshcd_dump_regs);
123 UFSHCD_MAX_CHANNEL = 0,
125 UFSHCD_CMD_PER_LUN = 32,
126 UFSHCD_CAN_QUEUE = 32,
133 UFSHCD_STATE_OPERATIONAL,
134 UFSHCD_STATE_EH_SCHEDULED_FATAL,
135 UFSHCD_STATE_EH_SCHEDULED_NON_FATAL,
138 /* UFSHCD error handling flags */
140 UFSHCD_EH_IN_PROGRESS = (1 << 0),
143 /* UFSHCD UIC layer error flags */
145 UFSHCD_UIC_DL_PA_INIT_ERROR = (1 << 0), /* Data link layer error */
146 UFSHCD_UIC_DL_NAC_RECEIVED_ERROR = (1 << 1), /* Data link layer error */
147 UFSHCD_UIC_DL_TCx_REPLAY_ERROR = (1 << 2), /* Data link layer error */
148 UFSHCD_UIC_NL_ERROR = (1 << 3), /* Network layer error */
149 UFSHCD_UIC_TL_ERROR = (1 << 4), /* Transport Layer error */
150 UFSHCD_UIC_DME_ERROR = (1 << 5), /* DME error */
151 UFSHCD_UIC_PA_GENERIC_ERROR = (1 << 6), /* Generic PA error */
154 #define ufshcd_set_eh_in_progress(h) \
155 ((h)->eh_flags |= UFSHCD_EH_IN_PROGRESS)
156 #define ufshcd_eh_in_progress(h) \
157 ((h)->eh_flags & UFSHCD_EH_IN_PROGRESS)
158 #define ufshcd_clear_eh_in_progress(h) \
159 ((h)->eh_flags &= ~UFSHCD_EH_IN_PROGRESS)
161 struct ufs_pm_lvl_states ufs_pm_lvl_states[] = {
162 {UFS_ACTIVE_PWR_MODE, UIC_LINK_ACTIVE_STATE},
163 {UFS_ACTIVE_PWR_MODE, UIC_LINK_HIBERN8_STATE},
164 {UFS_SLEEP_PWR_MODE, UIC_LINK_ACTIVE_STATE},
165 {UFS_SLEEP_PWR_MODE, UIC_LINK_HIBERN8_STATE},
166 {UFS_POWERDOWN_PWR_MODE, UIC_LINK_HIBERN8_STATE},
167 {UFS_POWERDOWN_PWR_MODE, UIC_LINK_OFF_STATE},
169 * For DeepSleep, the link is first put in hibern8 and then off.
170 * Leaving the link in hibern8 is not supported.
172 {UFS_DEEPSLEEP_PWR_MODE, UIC_LINK_OFF_STATE},
175 static inline enum ufs_dev_pwr_mode
176 ufs_get_pm_lvl_to_dev_pwr_mode(enum ufs_pm_level lvl)
178 return ufs_pm_lvl_states[lvl].dev_state;
181 static inline enum uic_link_state
182 ufs_get_pm_lvl_to_link_pwr_state(enum ufs_pm_level lvl)
184 return ufs_pm_lvl_states[lvl].link_state;
187 static inline enum ufs_pm_level
188 ufs_get_desired_pm_lvl_for_dev_link_state(enum ufs_dev_pwr_mode dev_state,
189 enum uic_link_state link_state)
191 enum ufs_pm_level lvl;
193 for (lvl = UFS_PM_LVL_0; lvl < UFS_PM_LVL_MAX; lvl++) {
194 if ((ufs_pm_lvl_states[lvl].dev_state == dev_state) &&
195 (ufs_pm_lvl_states[lvl].link_state == link_state))
199 /* if no match found, return the level 0 */
203 static struct ufs_dev_fix ufs_fixups[] = {
204 /* UFS cards deviations table */
205 UFS_FIX(UFS_VENDOR_MICRON, UFS_ANY_MODEL,
206 UFS_DEVICE_QUIRK_DELAY_BEFORE_LPM),
207 UFS_FIX(UFS_VENDOR_SAMSUNG, UFS_ANY_MODEL,
208 UFS_DEVICE_QUIRK_DELAY_BEFORE_LPM |
209 UFS_DEVICE_QUIRK_HOST_PA_TACTIVATE |
210 UFS_DEVICE_QUIRK_RECOVERY_FROM_DL_NAC_ERRORS),
211 UFS_FIX(UFS_VENDOR_SKHYNIX, UFS_ANY_MODEL,
212 UFS_DEVICE_QUIRK_HOST_PA_SAVECONFIGTIME),
213 UFS_FIX(UFS_VENDOR_SKHYNIX, "hB8aL1" /*H28U62301AMR*/,
214 UFS_DEVICE_QUIRK_HOST_VS_DEBUGSAVECONFIGTIME),
215 UFS_FIX(UFS_VENDOR_TOSHIBA, UFS_ANY_MODEL,
216 UFS_DEVICE_QUIRK_DELAY_BEFORE_LPM),
217 UFS_FIX(UFS_VENDOR_TOSHIBA, "THGLF2G9C8KBADG",
218 UFS_DEVICE_QUIRK_PA_TACTIVATE),
219 UFS_FIX(UFS_VENDOR_TOSHIBA, "THGLF2G9D8KBADG",
220 UFS_DEVICE_QUIRK_PA_TACTIVATE),
224 static irqreturn_t ufshcd_tmc_handler(struct ufs_hba *hba);
225 static void ufshcd_async_scan(void *data, async_cookie_t cookie);
226 static int ufshcd_reset_and_restore(struct ufs_hba *hba);
227 static int ufshcd_eh_host_reset_handler(struct scsi_cmnd *cmd);
228 static int ufshcd_clear_tm_cmd(struct ufs_hba *hba, int tag);
229 static void ufshcd_hba_exit(struct ufs_hba *hba);
230 static int ufshcd_clear_ua_wluns(struct ufs_hba *hba);
231 static int ufshcd_probe_hba(struct ufs_hba *hba, bool async);
232 static int ufshcd_setup_clocks(struct ufs_hba *hba, bool on);
233 static int ufshcd_uic_hibern8_enter(struct ufs_hba *hba);
234 static inline void ufshcd_add_delay_before_dme_cmd(struct ufs_hba *hba);
235 static int ufshcd_host_reset_and_restore(struct ufs_hba *hba);
236 static void ufshcd_resume_clkscaling(struct ufs_hba *hba);
237 static void ufshcd_suspend_clkscaling(struct ufs_hba *hba);
238 static void __ufshcd_suspend_clkscaling(struct ufs_hba *hba);
239 static int ufshcd_scale_clks(struct ufs_hba *hba, bool scale_up);
240 static irqreturn_t ufshcd_intr(int irq, void *__hba);
241 static int ufshcd_change_power_mode(struct ufs_hba *hba,
242 struct ufs_pa_layer_attr *pwr_mode);
243 static void ufshcd_schedule_eh_work(struct ufs_hba *hba);
244 static int ufshcd_setup_hba_vreg(struct ufs_hba *hba, bool on);
245 static int ufshcd_setup_vreg(struct ufs_hba *hba, bool on);
246 static inline int ufshcd_config_vreg_hpm(struct ufs_hba *hba,
247 struct ufs_vreg *vreg);
248 static int ufshcd_try_to_abort_task(struct ufs_hba *hba, int tag);
249 static int ufshcd_wb_toggle_flush_during_h8(struct ufs_hba *hba, bool set);
250 static inline int 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 if (!(hba->quirks & UFSHCI_QUIRK_SKIP_MANUAL_WB_FLUSH_CTRL))
292 ufshcd_wb_toggle_flush(hba, true);
295 static void ufshcd_scsi_unblock_requests(struct ufs_hba *hba)
297 if (atomic_dec_and_test(&hba->scsi_block_reqs_cnt))
298 scsi_unblock_requests(hba->host);
301 static void ufshcd_scsi_block_requests(struct ufs_hba *hba)
303 if (atomic_inc_return(&hba->scsi_block_reqs_cnt) == 1)
304 scsi_block_requests(hba->host);
307 static void ufshcd_add_cmd_upiu_trace(struct ufs_hba *hba, unsigned int tag,
308 enum ufs_trace_str_t str_t)
310 struct utp_upiu_req *rq = hba->lrb[tag].ucd_req_ptr;
312 if (!trace_ufshcd_upiu_enabled())
315 trace_ufshcd_upiu(dev_name(hba->dev), str_t, &rq->header, &rq->sc.cdb,
319 static void ufshcd_add_query_upiu_trace(struct ufs_hba *hba,
320 enum ufs_trace_str_t str_t,
321 struct utp_upiu_req *rq_rsp)
323 if (!trace_ufshcd_upiu_enabled())
326 trace_ufshcd_upiu(dev_name(hba->dev), str_t, &rq_rsp->header,
327 &rq_rsp->qr, UFS_TSF_OSF);
330 static void ufshcd_add_tm_upiu_trace(struct ufs_hba *hba, unsigned int tag,
331 enum ufs_trace_str_t str_t)
333 int off = (int)tag - hba->nutrs;
334 struct utp_task_req_desc *descp = &hba->utmrdl_base_addr[off];
336 if (!trace_ufshcd_upiu_enabled())
339 if (str_t == UFS_TM_SEND)
340 trace_ufshcd_upiu(dev_name(hba->dev), str_t, &descp->req_header,
341 &descp->input_param1, UFS_TSF_TM_INPUT);
343 trace_ufshcd_upiu(dev_name(hba->dev), str_t, &descp->rsp_header,
344 &descp->output_param1, UFS_TSF_TM_OUTPUT);
347 static void ufshcd_add_uic_command_trace(struct ufs_hba *hba,
348 struct uic_command *ucmd,
349 enum ufs_trace_str_t str_t)
353 if (!trace_ufshcd_uic_command_enabled())
356 if (str_t == UFS_CMD_SEND)
359 cmd = ufshcd_readl(hba, REG_UIC_COMMAND);
361 trace_ufshcd_uic_command(dev_name(hba->dev), str_t, cmd,
362 ufshcd_readl(hba, REG_UIC_COMMAND_ARG_1),
363 ufshcd_readl(hba, REG_UIC_COMMAND_ARG_2),
364 ufshcd_readl(hba, REG_UIC_COMMAND_ARG_3));
367 static void ufshcd_add_command_trace(struct ufs_hba *hba, unsigned int tag,
368 enum ufs_trace_str_t str_t)
371 u8 opcode = 0, group_id = 0;
373 struct ufshcd_lrb *lrbp = &hba->lrb[tag];
374 struct scsi_cmnd *cmd = lrbp->cmd;
375 int transfer_len = -1;
377 if (!trace_ufshcd_command_enabled()) {
378 /* trace UPIU W/O tracing command */
380 ufshcd_add_cmd_upiu_trace(hba, tag, str_t);
384 if (cmd) { /* data phase exists */
385 /* trace UPIU also */
386 ufshcd_add_cmd_upiu_trace(hba, tag, str_t);
387 opcode = cmd->cmnd[0];
388 if ((opcode == READ_10) || (opcode == WRITE_10)) {
390 * Currently we only fully trace read(10) and write(10)
393 if (cmd->request && cmd->request->bio)
394 lba = cmd->request->bio->bi_iter.bi_sector;
395 transfer_len = be32_to_cpu(
396 lrbp->ucd_req_ptr->sc.exp_data_transfer_len);
397 if (opcode == WRITE_10)
398 group_id = lrbp->cmd->cmnd[6];
399 } else if (opcode == UNMAP) {
401 lba = scsi_get_lba(cmd);
402 transfer_len = blk_rq_bytes(cmd->request);
407 intr = ufshcd_readl(hba, REG_INTERRUPT_STATUS);
408 doorbell = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
409 trace_ufshcd_command(dev_name(hba->dev), str_t, tag,
410 doorbell, transfer_len, intr, lba, opcode, group_id);
413 static void ufshcd_print_clk_freqs(struct ufs_hba *hba)
415 struct ufs_clk_info *clki;
416 struct list_head *head = &hba->clk_list_head;
418 if (list_empty(head))
421 list_for_each_entry(clki, head, list) {
422 if (!IS_ERR_OR_NULL(clki->clk) && clki->min_freq &&
424 dev_err(hba->dev, "clk: %s, rate: %u\n",
425 clki->name, clki->curr_freq);
429 static void ufshcd_print_evt(struct ufs_hba *hba, u32 id,
434 struct ufs_event_hist *e;
436 if (id >= UFS_EVT_CNT)
439 e = &hba->ufs_stats.event[id];
441 for (i = 0; i < UFS_EVENT_HIST_LENGTH; i++) {
442 int p = (i + e->pos) % UFS_EVENT_HIST_LENGTH;
444 if (e->tstamp[p] == 0)
446 dev_err(hba->dev, "%s[%d] = 0x%x at %lld us\n", err_name, p,
447 e->val[p], ktime_to_us(e->tstamp[p]));
452 dev_err(hba->dev, "No record of %s\n", err_name);
454 dev_err(hba->dev, "%s: total cnt=%llu\n", err_name, e->cnt);
457 static void ufshcd_print_evt_hist(struct ufs_hba *hba)
459 ufshcd_dump_regs(hba, 0, UFSHCI_REG_SPACE_SIZE, "host_regs: ");
461 ufshcd_print_evt(hba, UFS_EVT_PA_ERR, "pa_err");
462 ufshcd_print_evt(hba, UFS_EVT_DL_ERR, "dl_err");
463 ufshcd_print_evt(hba, UFS_EVT_NL_ERR, "nl_err");
464 ufshcd_print_evt(hba, UFS_EVT_TL_ERR, "tl_err");
465 ufshcd_print_evt(hba, UFS_EVT_DME_ERR, "dme_err");
466 ufshcd_print_evt(hba, UFS_EVT_AUTO_HIBERN8_ERR,
468 ufshcd_print_evt(hba, UFS_EVT_FATAL_ERR, "fatal_err");
469 ufshcd_print_evt(hba, UFS_EVT_LINK_STARTUP_FAIL,
470 "link_startup_fail");
471 ufshcd_print_evt(hba, UFS_EVT_RESUME_ERR, "resume_fail");
472 ufshcd_print_evt(hba, UFS_EVT_SUSPEND_ERR,
474 ufshcd_print_evt(hba, UFS_EVT_DEV_RESET, "dev_reset");
475 ufshcd_print_evt(hba, UFS_EVT_HOST_RESET, "host_reset");
476 ufshcd_print_evt(hba, UFS_EVT_ABORT, "task_abort");
478 ufshcd_vops_dbg_register_dump(hba);
482 void ufshcd_print_trs(struct ufs_hba *hba, unsigned long bitmap, bool pr_prdt)
484 struct ufshcd_lrb *lrbp;
488 for_each_set_bit(tag, &bitmap, hba->nutrs) {
489 lrbp = &hba->lrb[tag];
491 dev_err(hba->dev, "UPIU[%d] - issue time %lld us\n",
492 tag, ktime_to_us(lrbp->issue_time_stamp));
493 dev_err(hba->dev, "UPIU[%d] - complete time %lld us\n",
494 tag, ktime_to_us(lrbp->compl_time_stamp));
496 "UPIU[%d] - Transfer Request Descriptor phys@0x%llx\n",
497 tag, (u64)lrbp->utrd_dma_addr);
499 ufshcd_hex_dump("UPIU TRD: ", lrbp->utr_descriptor_ptr,
500 sizeof(struct utp_transfer_req_desc));
501 dev_err(hba->dev, "UPIU[%d] - Request UPIU phys@0x%llx\n", tag,
502 (u64)lrbp->ucd_req_dma_addr);
503 ufshcd_hex_dump("UPIU REQ: ", lrbp->ucd_req_ptr,
504 sizeof(struct utp_upiu_req));
505 dev_err(hba->dev, "UPIU[%d] - Response UPIU phys@0x%llx\n", tag,
506 (u64)lrbp->ucd_rsp_dma_addr);
507 ufshcd_hex_dump("UPIU RSP: ", lrbp->ucd_rsp_ptr,
508 sizeof(struct utp_upiu_rsp));
510 prdt_length = le16_to_cpu(
511 lrbp->utr_descriptor_ptr->prd_table_length);
512 if (hba->quirks & UFSHCD_QUIRK_PRDT_BYTE_GRAN)
513 prdt_length /= sizeof(struct ufshcd_sg_entry);
516 "UPIU[%d] - PRDT - %d entries phys@0x%llx\n",
518 (u64)lrbp->ucd_prdt_dma_addr);
521 ufshcd_hex_dump("UPIU PRDT: ", lrbp->ucd_prdt_ptr,
522 sizeof(struct ufshcd_sg_entry) * prdt_length);
526 static void ufshcd_print_tmrs(struct ufs_hba *hba, unsigned long bitmap)
530 for_each_set_bit(tag, &bitmap, hba->nutmrs) {
531 struct utp_task_req_desc *tmrdp = &hba->utmrdl_base_addr[tag];
533 dev_err(hba->dev, "TM[%d] - Task Management Header\n", tag);
534 ufshcd_hex_dump("", tmrdp, sizeof(*tmrdp));
538 static void ufshcd_print_host_state(struct ufs_hba *hba)
540 struct scsi_device *sdev_ufs = hba->sdev_ufs_device;
542 dev_err(hba->dev, "UFS Host state=%d\n", hba->ufshcd_state);
543 dev_err(hba->dev, "outstanding reqs=0x%lx tasks=0x%lx\n",
544 hba->outstanding_reqs, hba->outstanding_tasks);
545 dev_err(hba->dev, "saved_err=0x%x, saved_uic_err=0x%x\n",
546 hba->saved_err, hba->saved_uic_err);
547 dev_err(hba->dev, "Device power mode=%d, UIC link state=%d\n",
548 hba->curr_dev_pwr_mode, hba->uic_link_state);
549 dev_err(hba->dev, "PM in progress=%d, sys. suspended=%d\n",
550 hba->pm_op_in_progress, hba->is_sys_suspended);
551 dev_err(hba->dev, "Auto BKOPS=%d, Host self-block=%d\n",
552 hba->auto_bkops_enabled, hba->host->host_self_blocked);
553 dev_err(hba->dev, "Clk gate=%d\n", hba->clk_gating.state);
555 "last_hibern8_exit_tstamp at %lld us, hibern8_exit_cnt=%d\n",
556 ktime_to_us(hba->ufs_stats.last_hibern8_exit_tstamp),
557 hba->ufs_stats.hibern8_exit_cnt);
558 dev_err(hba->dev, "last intr at %lld us, last intr status=0x%x\n",
559 ktime_to_us(hba->ufs_stats.last_intr_ts),
560 hba->ufs_stats.last_intr_status);
561 dev_err(hba->dev, "error handling flags=0x%x, req. abort count=%d\n",
562 hba->eh_flags, hba->req_abort_count);
563 dev_err(hba->dev, "hba->ufs_version=0x%x, Host capabilities=0x%x, caps=0x%x\n",
564 hba->ufs_version, hba->capabilities, hba->caps);
565 dev_err(hba->dev, "quirks=0x%x, dev. quirks=0x%x\n", hba->quirks,
568 dev_err(hba->dev, "UFS dev info: %.8s %.16s rev %.4s\n",
569 sdev_ufs->vendor, sdev_ufs->model, sdev_ufs->rev);
571 ufshcd_print_clk_freqs(hba);
575 * ufshcd_print_pwr_info - print power params as saved in hba
577 * @hba: per-adapter instance
579 static void ufshcd_print_pwr_info(struct ufs_hba *hba)
581 static const char * const names[] = {
591 dev_err(hba->dev, "%s:[RX, TX]: gear=[%d, %d], lane[%d, %d], pwr[%s, %s], rate = %d\n",
593 hba->pwr_info.gear_rx, hba->pwr_info.gear_tx,
594 hba->pwr_info.lane_rx, hba->pwr_info.lane_tx,
595 names[hba->pwr_info.pwr_rx],
596 names[hba->pwr_info.pwr_tx],
597 hba->pwr_info.hs_rate);
600 static void ufshcd_device_reset(struct ufs_hba *hba)
604 err = ufshcd_vops_device_reset(hba);
607 ufshcd_set_ufs_dev_active(hba);
608 if (ufshcd_is_wb_allowed(hba)) {
609 hba->dev_info.wb_enabled = false;
610 hba->dev_info.wb_buf_flush_enabled = false;
613 if (err != -EOPNOTSUPP)
614 ufshcd_update_evt_hist(hba, UFS_EVT_DEV_RESET, err);
617 void ufshcd_delay_us(unsigned long us, unsigned long tolerance)
625 usleep_range(us, us + tolerance);
627 EXPORT_SYMBOL_GPL(ufshcd_delay_us);
630 * ufshcd_wait_for_register - wait for register value to change
631 * @hba: per-adapter interface
632 * @reg: mmio register offset
633 * @mask: mask to apply to the read register value
634 * @val: value to wait for
635 * @interval_us: polling interval in microseconds
636 * @timeout_ms: timeout in milliseconds
639 * -ETIMEDOUT on error, zero on success.
641 int ufshcd_wait_for_register(struct ufs_hba *hba, u32 reg, u32 mask,
642 u32 val, unsigned long interval_us,
643 unsigned long timeout_ms)
646 unsigned long timeout = jiffies + msecs_to_jiffies(timeout_ms);
648 /* ignore bits that we don't intend to wait on */
651 while ((ufshcd_readl(hba, reg) & mask) != val) {
652 usleep_range(interval_us, interval_us + 50);
653 if (time_after(jiffies, timeout)) {
654 if ((ufshcd_readl(hba, reg) & mask) != val)
664 * ufshcd_get_intr_mask - Get the interrupt bit mask
665 * @hba: Pointer to adapter instance
667 * Returns interrupt bit mask per version
669 static inline u32 ufshcd_get_intr_mask(struct ufs_hba *hba)
673 switch (hba->ufs_version) {
674 case UFSHCI_VERSION_10:
675 intr_mask = INTERRUPT_MASK_ALL_VER_10;
677 case UFSHCI_VERSION_11:
678 case UFSHCI_VERSION_20:
679 intr_mask = INTERRUPT_MASK_ALL_VER_11;
681 case UFSHCI_VERSION_21:
683 intr_mask = INTERRUPT_MASK_ALL_VER_21;
691 * ufshcd_get_ufs_version - Get the UFS version supported by the HBA
692 * @hba: Pointer to adapter instance
694 * Returns UFSHCI version supported by the controller
696 static inline u32 ufshcd_get_ufs_version(struct ufs_hba *hba)
698 if (hba->quirks & UFSHCD_QUIRK_BROKEN_UFS_HCI_VERSION)
699 return ufshcd_vops_get_ufs_hci_version(hba);
701 return ufshcd_readl(hba, REG_UFS_VERSION);
705 * ufshcd_is_device_present - Check if any device connected to
706 * the host controller
707 * @hba: pointer to adapter instance
709 * Returns true if device present, false if no device detected
711 static inline bool ufshcd_is_device_present(struct ufs_hba *hba)
713 return (ufshcd_readl(hba, REG_CONTROLLER_STATUS) &
714 DEVICE_PRESENT) ? true : false;
718 * ufshcd_get_tr_ocs - Get the UTRD Overall Command Status
719 * @lrbp: pointer to local command reference block
721 * This function is used to get the OCS field from UTRD
722 * Returns the OCS field in the UTRD
724 static inline int ufshcd_get_tr_ocs(struct ufshcd_lrb *lrbp)
726 return le32_to_cpu(lrbp->utr_descriptor_ptr->header.dword_2) & MASK_OCS;
730 * ufshcd_utrl_clear - Clear a bit in UTRLCLR register
731 * @hba: per adapter instance
732 * @pos: position of the bit to be cleared
734 static inline void ufshcd_utrl_clear(struct ufs_hba *hba, u32 pos)
736 if (hba->quirks & UFSHCI_QUIRK_BROKEN_REQ_LIST_CLR)
737 ufshcd_writel(hba, (1 << pos), REG_UTP_TRANSFER_REQ_LIST_CLEAR);
739 ufshcd_writel(hba, ~(1 << pos),
740 REG_UTP_TRANSFER_REQ_LIST_CLEAR);
744 * ufshcd_utmrl_clear - Clear a bit in UTRMLCLR register
745 * @hba: per adapter instance
746 * @pos: position of the bit to be cleared
748 static inline void ufshcd_utmrl_clear(struct ufs_hba *hba, u32 pos)
750 if (hba->quirks & UFSHCI_QUIRK_BROKEN_REQ_LIST_CLR)
751 ufshcd_writel(hba, (1 << pos), REG_UTP_TASK_REQ_LIST_CLEAR);
753 ufshcd_writel(hba, ~(1 << pos), REG_UTP_TASK_REQ_LIST_CLEAR);
757 * ufshcd_outstanding_req_clear - Clear a bit in outstanding request field
758 * @hba: per adapter instance
759 * @tag: position of the bit to be cleared
761 static inline void ufshcd_outstanding_req_clear(struct ufs_hba *hba, int tag)
763 __clear_bit(tag, &hba->outstanding_reqs);
767 * ufshcd_get_lists_status - Check UCRDY, UTRLRDY and UTMRLRDY
768 * @reg: Register value of host controller status
770 * Returns integer, 0 on Success and positive value if failed
772 static inline int ufshcd_get_lists_status(u32 reg)
774 return !((reg & UFSHCD_STATUS_READY) == UFSHCD_STATUS_READY);
778 * ufshcd_get_uic_cmd_result - Get the UIC command result
779 * @hba: Pointer to adapter instance
781 * This function gets the result of UIC command completion
782 * Returns 0 on success, non zero value on error
784 static inline int ufshcd_get_uic_cmd_result(struct ufs_hba *hba)
786 return ufshcd_readl(hba, REG_UIC_COMMAND_ARG_2) &
787 MASK_UIC_COMMAND_RESULT;
791 * ufshcd_get_dme_attr_val - Get the value of attribute returned by UIC command
792 * @hba: Pointer to adapter instance
794 * This function gets UIC command argument3
795 * Returns 0 on success, non zero value on error
797 static inline u32 ufshcd_get_dme_attr_val(struct ufs_hba *hba)
799 return ufshcd_readl(hba, REG_UIC_COMMAND_ARG_3);
803 * ufshcd_get_req_rsp - returns the TR response transaction type
804 * @ucd_rsp_ptr: pointer to response UPIU
807 ufshcd_get_req_rsp(struct utp_upiu_rsp *ucd_rsp_ptr)
809 return be32_to_cpu(ucd_rsp_ptr->header.dword_0) >> 24;
813 * ufshcd_get_rsp_upiu_result - Get the result from response UPIU
814 * @ucd_rsp_ptr: pointer to response UPIU
816 * This function gets the response status and scsi_status from response UPIU
817 * Returns the response result code.
820 ufshcd_get_rsp_upiu_result(struct utp_upiu_rsp *ucd_rsp_ptr)
822 return be32_to_cpu(ucd_rsp_ptr->header.dword_1) & MASK_RSP_UPIU_RESULT;
826 * ufshcd_get_rsp_upiu_data_seg_len - Get the data segment length
828 * @ucd_rsp_ptr: pointer to response UPIU
830 * Return the data segment length.
832 static inline unsigned int
833 ufshcd_get_rsp_upiu_data_seg_len(struct utp_upiu_rsp *ucd_rsp_ptr)
835 return be32_to_cpu(ucd_rsp_ptr->header.dword_2) &
836 MASK_RSP_UPIU_DATA_SEG_LEN;
840 * ufshcd_is_exception_event - Check if the device raised an exception event
841 * @ucd_rsp_ptr: pointer to response UPIU
843 * The function checks if the device raised an exception event indicated in
844 * the Device Information field of response UPIU.
846 * Returns true if exception is raised, false otherwise.
848 static inline bool ufshcd_is_exception_event(struct utp_upiu_rsp *ucd_rsp_ptr)
850 return be32_to_cpu(ucd_rsp_ptr->header.dword_2) &
851 MASK_RSP_EXCEPTION_EVENT ? true : false;
855 * ufshcd_reset_intr_aggr - Reset interrupt aggregation values.
856 * @hba: per adapter instance
859 ufshcd_reset_intr_aggr(struct ufs_hba *hba)
861 ufshcd_writel(hba, INT_AGGR_ENABLE |
862 INT_AGGR_COUNTER_AND_TIMER_RESET,
863 REG_UTP_TRANSFER_REQ_INT_AGG_CONTROL);
867 * ufshcd_config_intr_aggr - Configure interrupt aggregation values.
868 * @hba: per adapter instance
869 * @cnt: Interrupt aggregation counter threshold
870 * @tmout: Interrupt aggregation timeout value
873 ufshcd_config_intr_aggr(struct ufs_hba *hba, u8 cnt, u8 tmout)
875 ufshcd_writel(hba, INT_AGGR_ENABLE | INT_AGGR_PARAM_WRITE |
876 INT_AGGR_COUNTER_THLD_VAL(cnt) |
877 INT_AGGR_TIMEOUT_VAL(tmout),
878 REG_UTP_TRANSFER_REQ_INT_AGG_CONTROL);
882 * ufshcd_disable_intr_aggr - Disables interrupt aggregation.
883 * @hba: per adapter instance
885 static inline void ufshcd_disable_intr_aggr(struct ufs_hba *hba)
887 ufshcd_writel(hba, 0, REG_UTP_TRANSFER_REQ_INT_AGG_CONTROL);
891 * ufshcd_enable_run_stop_reg - Enable run-stop registers,
892 * When run-stop registers are set to 1, it indicates the
893 * host controller that it can process the requests
894 * @hba: per adapter instance
896 static void ufshcd_enable_run_stop_reg(struct ufs_hba *hba)
898 ufshcd_writel(hba, UTP_TASK_REQ_LIST_RUN_STOP_BIT,
899 REG_UTP_TASK_REQ_LIST_RUN_STOP);
900 ufshcd_writel(hba, UTP_TRANSFER_REQ_LIST_RUN_STOP_BIT,
901 REG_UTP_TRANSFER_REQ_LIST_RUN_STOP);
905 * ufshcd_hba_start - Start controller initialization sequence
906 * @hba: per adapter instance
908 static inline void ufshcd_hba_start(struct ufs_hba *hba)
910 u32 val = CONTROLLER_ENABLE;
912 if (ufshcd_crypto_enable(hba))
913 val |= CRYPTO_GENERAL_ENABLE;
915 ufshcd_writel(hba, val, REG_CONTROLLER_ENABLE);
919 * ufshcd_is_hba_active - Get controller state
920 * @hba: per adapter instance
922 * Returns false if controller is active, true otherwise
924 static inline bool ufshcd_is_hba_active(struct ufs_hba *hba)
926 return (ufshcd_readl(hba, REG_CONTROLLER_ENABLE) & CONTROLLER_ENABLE)
930 u32 ufshcd_get_local_unipro_ver(struct ufs_hba *hba)
932 /* HCI version 1.0 and 1.1 supports UniPro 1.41 */
933 if ((hba->ufs_version == UFSHCI_VERSION_10) ||
934 (hba->ufs_version == UFSHCI_VERSION_11))
935 return UFS_UNIPRO_VER_1_41;
937 return UFS_UNIPRO_VER_1_6;
939 EXPORT_SYMBOL(ufshcd_get_local_unipro_ver);
941 static bool ufshcd_is_unipro_pa_params_tuning_req(struct ufs_hba *hba)
944 * If both host and device support UniPro ver1.6 or later, PA layer
945 * parameters tuning happens during link startup itself.
947 * We can manually tune PA layer parameters if either host or device
948 * doesn't support UniPro ver 1.6 or later. But to keep manual tuning
949 * logic simple, we will only do manual tuning if local unipro version
950 * doesn't support ver1.6 or later.
952 if (ufshcd_get_local_unipro_ver(hba) < UFS_UNIPRO_VER_1_6)
959 * ufshcd_set_clk_freq - set UFS controller clock frequencies
960 * @hba: per adapter instance
961 * @scale_up: If True, set max possible frequency othewise set low frequency
963 * Returns 0 if successful
964 * Returns < 0 for any other errors
966 static int ufshcd_set_clk_freq(struct ufs_hba *hba, bool scale_up)
969 struct ufs_clk_info *clki;
970 struct list_head *head = &hba->clk_list_head;
972 if (list_empty(head))
975 list_for_each_entry(clki, head, list) {
976 if (!IS_ERR_OR_NULL(clki->clk)) {
977 if (scale_up && clki->max_freq) {
978 if (clki->curr_freq == clki->max_freq)
981 ret = clk_set_rate(clki->clk, clki->max_freq);
983 dev_err(hba->dev, "%s: %s clk set rate(%dHz) failed, %d\n",
984 __func__, clki->name,
985 clki->max_freq, ret);
988 trace_ufshcd_clk_scaling(dev_name(hba->dev),
989 "scaled up", clki->name,
993 clki->curr_freq = clki->max_freq;
995 } else if (!scale_up && clki->min_freq) {
996 if (clki->curr_freq == clki->min_freq)
999 ret = clk_set_rate(clki->clk, clki->min_freq);
1001 dev_err(hba->dev, "%s: %s clk set rate(%dHz) failed, %d\n",
1002 __func__, clki->name,
1003 clki->min_freq, ret);
1006 trace_ufshcd_clk_scaling(dev_name(hba->dev),
1007 "scaled down", clki->name,
1010 clki->curr_freq = clki->min_freq;
1013 dev_dbg(hba->dev, "%s: clk: %s, rate: %lu\n", __func__,
1014 clki->name, clk_get_rate(clki->clk));
1022 * ufshcd_scale_clks - scale up or scale down UFS controller clocks
1023 * @hba: per adapter instance
1024 * @scale_up: True if scaling up and false if scaling down
1026 * Returns 0 if successful
1027 * Returns < 0 for any other errors
1029 static int ufshcd_scale_clks(struct ufs_hba *hba, bool scale_up)
1032 ktime_t start = ktime_get();
1034 ret = ufshcd_vops_clk_scale_notify(hba, scale_up, PRE_CHANGE);
1038 ret = ufshcd_set_clk_freq(hba, scale_up);
1042 ret = ufshcd_vops_clk_scale_notify(hba, scale_up, POST_CHANGE);
1044 ufshcd_set_clk_freq(hba, !scale_up);
1047 trace_ufshcd_profile_clk_scaling(dev_name(hba->dev),
1048 (scale_up ? "up" : "down"),
1049 ktime_to_us(ktime_sub(ktime_get(), start)), ret);
1054 * ufshcd_is_devfreq_scaling_required - check if scaling is required or not
1055 * @hba: per adapter instance
1056 * @scale_up: True if scaling up and false if scaling down
1058 * Returns true if scaling is required, false otherwise.
1060 static bool ufshcd_is_devfreq_scaling_required(struct ufs_hba *hba,
1063 struct ufs_clk_info *clki;
1064 struct list_head *head = &hba->clk_list_head;
1066 if (list_empty(head))
1069 list_for_each_entry(clki, head, list) {
1070 if (!IS_ERR_OR_NULL(clki->clk)) {
1071 if (scale_up && clki->max_freq) {
1072 if (clki->curr_freq == clki->max_freq)
1075 } else if (!scale_up && clki->min_freq) {
1076 if (clki->curr_freq == clki->min_freq)
1086 static int ufshcd_wait_for_doorbell_clr(struct ufs_hba *hba,
1087 u64 wait_timeout_us)
1089 unsigned long flags;
1093 bool timeout = false, do_last_check = false;
1096 ufshcd_hold(hba, false);
1097 spin_lock_irqsave(hba->host->host_lock, flags);
1099 * Wait for all the outstanding tasks/transfer requests.
1100 * Verify by checking the doorbell registers are clear.
1102 start = ktime_get();
1104 if (hba->ufshcd_state != UFSHCD_STATE_OPERATIONAL) {
1109 tm_doorbell = ufshcd_readl(hba, REG_UTP_TASK_REQ_DOOR_BELL);
1110 tr_doorbell = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
1111 if (!tm_doorbell && !tr_doorbell) {
1114 } else if (do_last_check) {
1118 spin_unlock_irqrestore(hba->host->host_lock, flags);
1120 if (ktime_to_us(ktime_sub(ktime_get(), start)) >
1124 * We might have scheduled out for long time so make
1125 * sure to check if doorbells are cleared by this time
1128 do_last_check = true;
1130 spin_lock_irqsave(hba->host->host_lock, flags);
1131 } while (tm_doorbell || tr_doorbell);
1135 "%s: timedout waiting for doorbell to clear (tm=0x%x, tr=0x%x)\n",
1136 __func__, tm_doorbell, tr_doorbell);
1140 spin_unlock_irqrestore(hba->host->host_lock, flags);
1141 ufshcd_release(hba);
1146 * ufshcd_scale_gear - scale up/down UFS gear
1147 * @hba: per adapter instance
1148 * @scale_up: True for scaling up gear and false for scaling down
1150 * Returns 0 for success,
1151 * Returns -EBUSY if scaling can't happen at this time
1152 * Returns non-zero for any other errors
1154 static int ufshcd_scale_gear(struct ufs_hba *hba, bool scale_up)
1157 struct ufs_pa_layer_attr new_pwr_info;
1160 memcpy(&new_pwr_info, &hba->clk_scaling.saved_pwr_info.info,
1161 sizeof(struct ufs_pa_layer_attr));
1163 memcpy(&new_pwr_info, &hba->pwr_info,
1164 sizeof(struct ufs_pa_layer_attr));
1166 if (hba->pwr_info.gear_tx > hba->clk_scaling.min_gear ||
1167 hba->pwr_info.gear_rx > hba->clk_scaling.min_gear) {
1168 /* save the current power mode */
1169 memcpy(&hba->clk_scaling.saved_pwr_info.info,
1171 sizeof(struct ufs_pa_layer_attr));
1173 /* scale down gear */
1174 new_pwr_info.gear_tx = hba->clk_scaling.min_gear;
1175 new_pwr_info.gear_rx = hba->clk_scaling.min_gear;
1179 /* check if the power mode needs to be changed or not? */
1180 ret = ufshcd_config_pwr_mode(hba, &new_pwr_info);
1182 dev_err(hba->dev, "%s: failed err %d, old gear: (tx %d rx %d), new gear: (tx %d rx %d)",
1184 hba->pwr_info.gear_tx, hba->pwr_info.gear_rx,
1185 new_pwr_info.gear_tx, new_pwr_info.gear_rx);
1190 static int ufshcd_clock_scaling_prepare(struct ufs_hba *hba)
1192 #define DOORBELL_CLR_TOUT_US (1000 * 1000) /* 1 sec */
1195 * make sure that there are no outstanding requests when
1196 * clock scaling is in progress
1198 ufshcd_scsi_block_requests(hba);
1199 down_write(&hba->clk_scaling_lock);
1201 if (!hba->clk_scaling.is_allowed ||
1202 ufshcd_wait_for_doorbell_clr(hba, DOORBELL_CLR_TOUT_US)) {
1204 up_write(&hba->clk_scaling_lock);
1205 ufshcd_scsi_unblock_requests(hba);
1209 /* let's not get into low power until clock scaling is completed */
1210 ufshcd_hold(hba, false);
1216 static void ufshcd_clock_scaling_unprepare(struct ufs_hba *hba, bool writelock)
1219 up_write(&hba->clk_scaling_lock);
1221 up_read(&hba->clk_scaling_lock);
1222 ufshcd_scsi_unblock_requests(hba);
1223 ufshcd_release(hba);
1227 * ufshcd_devfreq_scale - scale up/down UFS clocks and gear
1228 * @hba: per adapter instance
1229 * @scale_up: True for scaling up and false for scalin down
1231 * Returns 0 for success,
1232 * Returns -EBUSY if scaling can't happen at this time
1233 * Returns non-zero for any other errors
1235 static int ufshcd_devfreq_scale(struct ufs_hba *hba, bool scale_up)
1238 bool is_writelock = true;
1240 ret = ufshcd_clock_scaling_prepare(hba);
1244 /* scale down the gear before scaling down clocks */
1246 ret = ufshcd_scale_gear(hba, false);
1251 ret = ufshcd_scale_clks(hba, scale_up);
1254 ufshcd_scale_gear(hba, true);
1258 /* scale up the gear after scaling up clocks */
1260 ret = ufshcd_scale_gear(hba, true);
1262 ufshcd_scale_clks(hba, false);
1267 /* Enable Write Booster if we have scaled up else disable it */
1268 downgrade_write(&hba->clk_scaling_lock);
1269 is_writelock = false;
1270 ufshcd_wb_ctrl(hba, scale_up);
1273 ufshcd_clock_scaling_unprepare(hba, is_writelock);
1277 static void ufshcd_clk_scaling_suspend_work(struct work_struct *work)
1279 struct ufs_hba *hba = container_of(work, struct ufs_hba,
1280 clk_scaling.suspend_work);
1281 unsigned long irq_flags;
1283 spin_lock_irqsave(hba->host->host_lock, irq_flags);
1284 if (hba->clk_scaling.active_reqs || hba->clk_scaling.is_suspended) {
1285 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1288 hba->clk_scaling.is_suspended = true;
1289 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1291 __ufshcd_suspend_clkscaling(hba);
1294 static void ufshcd_clk_scaling_resume_work(struct work_struct *work)
1296 struct ufs_hba *hba = container_of(work, struct ufs_hba,
1297 clk_scaling.resume_work);
1298 unsigned long irq_flags;
1300 spin_lock_irqsave(hba->host->host_lock, irq_flags);
1301 if (!hba->clk_scaling.is_suspended) {
1302 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1305 hba->clk_scaling.is_suspended = false;
1306 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1308 devfreq_resume_device(hba->devfreq);
1311 static int ufshcd_devfreq_target(struct device *dev,
1312 unsigned long *freq, u32 flags)
1315 struct ufs_hba *hba = dev_get_drvdata(dev);
1317 bool scale_up, sched_clk_scaling_suspend_work = false;
1318 struct list_head *clk_list = &hba->clk_list_head;
1319 struct ufs_clk_info *clki;
1320 unsigned long irq_flags;
1322 if (!ufshcd_is_clkscaling_supported(hba))
1325 clki = list_first_entry(&hba->clk_list_head, struct ufs_clk_info, list);
1326 /* Override with the closest supported frequency */
1327 *freq = (unsigned long) clk_round_rate(clki->clk, *freq);
1328 spin_lock_irqsave(hba->host->host_lock, irq_flags);
1329 if (ufshcd_eh_in_progress(hba)) {
1330 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1334 if (!hba->clk_scaling.active_reqs)
1335 sched_clk_scaling_suspend_work = true;
1337 if (list_empty(clk_list)) {
1338 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1342 /* Decide based on the rounded-off frequency and update */
1343 scale_up = (*freq == clki->max_freq) ? true : false;
1345 *freq = clki->min_freq;
1346 /* Update the frequency */
1347 if (!ufshcd_is_devfreq_scaling_required(hba, scale_up)) {
1348 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1350 goto out; /* no state change required */
1352 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1354 start = ktime_get();
1355 ret = ufshcd_devfreq_scale(hba, scale_up);
1357 trace_ufshcd_profile_clk_scaling(dev_name(hba->dev),
1358 (scale_up ? "up" : "down"),
1359 ktime_to_us(ktime_sub(ktime_get(), start)), ret);
1362 if (sched_clk_scaling_suspend_work)
1363 queue_work(hba->clk_scaling.workq,
1364 &hba->clk_scaling.suspend_work);
1369 static bool ufshcd_is_busy(struct request *req, void *priv, bool reserved)
1373 WARN_ON_ONCE(reserved);
1378 /* Whether or not any tag is in use by a request that is in progress. */
1379 static bool ufshcd_any_tag_in_use(struct ufs_hba *hba)
1381 struct request_queue *q = hba->cmd_queue;
1384 blk_mq_tagset_busy_iter(q->tag_set, ufshcd_is_busy, &busy);
1388 static int ufshcd_devfreq_get_dev_status(struct device *dev,
1389 struct devfreq_dev_status *stat)
1391 struct ufs_hba *hba = dev_get_drvdata(dev);
1392 struct ufs_clk_scaling *scaling = &hba->clk_scaling;
1393 unsigned long flags;
1394 struct list_head *clk_list = &hba->clk_list_head;
1395 struct ufs_clk_info *clki;
1398 if (!ufshcd_is_clkscaling_supported(hba))
1401 memset(stat, 0, sizeof(*stat));
1403 spin_lock_irqsave(hba->host->host_lock, flags);
1404 curr_t = ktime_get();
1405 if (!scaling->window_start_t)
1408 clki = list_first_entry(clk_list, struct ufs_clk_info, list);
1410 * If current frequency is 0, then the ondemand governor considers
1411 * there's no initial frequency set. And it always requests to set
1412 * to max. frequency.
1414 stat->current_frequency = clki->curr_freq;
1415 if (scaling->is_busy_started)
1416 scaling->tot_busy_t += ktime_us_delta(curr_t,
1417 scaling->busy_start_t);
1419 stat->total_time = ktime_us_delta(curr_t, scaling->window_start_t);
1420 stat->busy_time = scaling->tot_busy_t;
1422 scaling->window_start_t = curr_t;
1423 scaling->tot_busy_t = 0;
1425 if (hba->outstanding_reqs) {
1426 scaling->busy_start_t = curr_t;
1427 scaling->is_busy_started = true;
1429 scaling->busy_start_t = 0;
1430 scaling->is_busy_started = false;
1432 spin_unlock_irqrestore(hba->host->host_lock, flags);
1436 static int ufshcd_devfreq_init(struct ufs_hba *hba)
1438 struct list_head *clk_list = &hba->clk_list_head;
1439 struct ufs_clk_info *clki;
1440 struct devfreq *devfreq;
1443 /* Skip devfreq if we don't have any clocks in the list */
1444 if (list_empty(clk_list))
1447 clki = list_first_entry(clk_list, struct ufs_clk_info, list);
1448 dev_pm_opp_add(hba->dev, clki->min_freq, 0);
1449 dev_pm_opp_add(hba->dev, clki->max_freq, 0);
1451 ufshcd_vops_config_scaling_param(hba, &hba->vps->devfreq_profile,
1452 &hba->vps->ondemand_data);
1453 devfreq = devfreq_add_device(hba->dev,
1454 &hba->vps->devfreq_profile,
1455 DEVFREQ_GOV_SIMPLE_ONDEMAND,
1456 &hba->vps->ondemand_data);
1457 if (IS_ERR(devfreq)) {
1458 ret = PTR_ERR(devfreq);
1459 dev_err(hba->dev, "Unable to register with devfreq %d\n", ret);
1461 dev_pm_opp_remove(hba->dev, clki->min_freq);
1462 dev_pm_opp_remove(hba->dev, clki->max_freq);
1466 hba->devfreq = devfreq;
1471 static void ufshcd_devfreq_remove(struct ufs_hba *hba)
1473 struct list_head *clk_list = &hba->clk_list_head;
1474 struct ufs_clk_info *clki;
1479 devfreq_remove_device(hba->devfreq);
1480 hba->devfreq = NULL;
1482 clki = list_first_entry(clk_list, struct ufs_clk_info, list);
1483 dev_pm_opp_remove(hba->dev, clki->min_freq);
1484 dev_pm_opp_remove(hba->dev, clki->max_freq);
1487 static void __ufshcd_suspend_clkscaling(struct ufs_hba *hba)
1489 unsigned long flags;
1491 devfreq_suspend_device(hba->devfreq);
1492 spin_lock_irqsave(hba->host->host_lock, flags);
1493 hba->clk_scaling.window_start_t = 0;
1494 spin_unlock_irqrestore(hba->host->host_lock, flags);
1497 static void ufshcd_suspend_clkscaling(struct ufs_hba *hba)
1499 unsigned long flags;
1500 bool suspend = false;
1502 cancel_work_sync(&hba->clk_scaling.suspend_work);
1503 cancel_work_sync(&hba->clk_scaling.resume_work);
1505 spin_lock_irqsave(hba->host->host_lock, flags);
1506 if (!hba->clk_scaling.is_suspended) {
1508 hba->clk_scaling.is_suspended = true;
1510 spin_unlock_irqrestore(hba->host->host_lock, flags);
1513 __ufshcd_suspend_clkscaling(hba);
1516 static void ufshcd_resume_clkscaling(struct ufs_hba *hba)
1518 unsigned long flags;
1519 bool resume = false;
1521 spin_lock_irqsave(hba->host->host_lock, flags);
1522 if (hba->clk_scaling.is_suspended) {
1524 hba->clk_scaling.is_suspended = false;
1526 spin_unlock_irqrestore(hba->host->host_lock, flags);
1529 devfreq_resume_device(hba->devfreq);
1532 static ssize_t ufshcd_clkscale_enable_show(struct device *dev,
1533 struct device_attribute *attr, char *buf)
1535 struct ufs_hba *hba = dev_get_drvdata(dev);
1537 return snprintf(buf, PAGE_SIZE, "%d\n", hba->clk_scaling.is_enabled);
1540 static ssize_t ufshcd_clkscale_enable_store(struct device *dev,
1541 struct device_attribute *attr, const char *buf, size_t count)
1543 struct ufs_hba *hba = dev_get_drvdata(dev);
1547 if (kstrtou32(buf, 0, &value))
1550 down(&hba->host_sem);
1551 if (!ufshcd_is_user_access_allowed(hba)) {
1557 if (value == hba->clk_scaling.is_enabled)
1560 pm_runtime_get_sync(hba->dev);
1561 ufshcd_hold(hba, false);
1563 hba->clk_scaling.is_enabled = value;
1566 ufshcd_resume_clkscaling(hba);
1568 ufshcd_suspend_clkscaling(hba);
1569 err = ufshcd_devfreq_scale(hba, true);
1571 dev_err(hba->dev, "%s: failed to scale clocks up %d\n",
1575 ufshcd_release(hba);
1576 pm_runtime_put_sync(hba->dev);
1579 return err ? err : count;
1582 static void ufshcd_init_clk_scaling_sysfs(struct ufs_hba *hba)
1584 hba->clk_scaling.enable_attr.show = ufshcd_clkscale_enable_show;
1585 hba->clk_scaling.enable_attr.store = ufshcd_clkscale_enable_store;
1586 sysfs_attr_init(&hba->clk_scaling.enable_attr.attr);
1587 hba->clk_scaling.enable_attr.attr.name = "clkscale_enable";
1588 hba->clk_scaling.enable_attr.attr.mode = 0644;
1589 if (device_create_file(hba->dev, &hba->clk_scaling.enable_attr))
1590 dev_err(hba->dev, "Failed to create sysfs for clkscale_enable\n");
1593 static void ufshcd_remove_clk_scaling_sysfs(struct ufs_hba *hba)
1595 if (hba->clk_scaling.enable_attr.attr.name)
1596 device_remove_file(hba->dev, &hba->clk_scaling.enable_attr);
1599 static void ufshcd_init_clk_scaling(struct ufs_hba *hba)
1601 char wq_name[sizeof("ufs_clkscaling_00")];
1603 if (!ufshcd_is_clkscaling_supported(hba))
1606 if (!hba->clk_scaling.min_gear)
1607 hba->clk_scaling.min_gear = UFS_HS_G1;
1609 INIT_WORK(&hba->clk_scaling.suspend_work,
1610 ufshcd_clk_scaling_suspend_work);
1611 INIT_WORK(&hba->clk_scaling.resume_work,
1612 ufshcd_clk_scaling_resume_work);
1614 snprintf(wq_name, sizeof(wq_name), "ufs_clkscaling_%d",
1615 hba->host->host_no);
1616 hba->clk_scaling.workq = create_singlethread_workqueue(wq_name);
1618 hba->clk_scaling.is_initialized = true;
1621 static void ufshcd_exit_clk_scaling(struct ufs_hba *hba)
1623 if (!hba->clk_scaling.is_initialized)
1626 ufshcd_remove_clk_scaling_sysfs(hba);
1627 destroy_workqueue(hba->clk_scaling.workq);
1628 ufshcd_devfreq_remove(hba);
1629 hba->clk_scaling.is_initialized = false;
1632 static void ufshcd_ungate_work(struct work_struct *work)
1635 unsigned long flags;
1636 struct ufs_hba *hba = container_of(work, struct ufs_hba,
1637 clk_gating.ungate_work);
1639 cancel_delayed_work_sync(&hba->clk_gating.gate_work);
1641 spin_lock_irqsave(hba->host->host_lock, flags);
1642 if (hba->clk_gating.state == CLKS_ON) {
1643 spin_unlock_irqrestore(hba->host->host_lock, flags);
1647 spin_unlock_irqrestore(hba->host->host_lock, flags);
1648 ufshcd_hba_vreg_set_hpm(hba);
1649 ufshcd_setup_clocks(hba, true);
1651 ufshcd_enable_irq(hba);
1653 /* Exit from hibern8 */
1654 if (ufshcd_can_hibern8_during_gating(hba)) {
1655 /* Prevent gating in this path */
1656 hba->clk_gating.is_suspended = true;
1657 if (ufshcd_is_link_hibern8(hba)) {
1658 ret = ufshcd_uic_hibern8_exit(hba);
1660 dev_err(hba->dev, "%s: hibern8 exit failed %d\n",
1663 ufshcd_set_link_active(hba);
1665 hba->clk_gating.is_suspended = false;
1668 ufshcd_scsi_unblock_requests(hba);
1672 * ufshcd_hold - Enable clocks that were gated earlier due to ufshcd_release.
1673 * Also, exit from hibern8 mode and set the link as active.
1674 * @hba: per adapter instance
1675 * @async: This indicates whether caller should ungate clocks asynchronously.
1677 int ufshcd_hold(struct ufs_hba *hba, bool async)
1681 unsigned long flags;
1683 if (!ufshcd_is_clkgating_allowed(hba))
1685 spin_lock_irqsave(hba->host->host_lock, flags);
1686 hba->clk_gating.active_reqs++;
1689 switch (hba->clk_gating.state) {
1692 * Wait for the ungate work to complete if in progress.
1693 * Though the clocks may be in ON state, the link could
1694 * still be in hibner8 state if hibern8 is allowed
1695 * during clock gating.
1696 * Make sure we exit hibern8 state also in addition to
1699 if (ufshcd_can_hibern8_during_gating(hba) &&
1700 ufshcd_is_link_hibern8(hba)) {
1703 hba->clk_gating.active_reqs--;
1706 spin_unlock_irqrestore(hba->host->host_lock, flags);
1707 flush_result = flush_work(&hba->clk_gating.ungate_work);
1708 if (hba->clk_gating.is_suspended && !flush_result)
1710 spin_lock_irqsave(hba->host->host_lock, flags);
1715 if (cancel_delayed_work(&hba->clk_gating.gate_work)) {
1716 hba->clk_gating.state = CLKS_ON;
1717 trace_ufshcd_clk_gating(dev_name(hba->dev),
1718 hba->clk_gating.state);
1722 * If we are here, it means gating work is either done or
1723 * currently running. Hence, fall through to cancel gating
1724 * work and to enable clocks.
1728 hba->clk_gating.state = REQ_CLKS_ON;
1729 trace_ufshcd_clk_gating(dev_name(hba->dev),
1730 hba->clk_gating.state);
1731 if (queue_work(hba->clk_gating.clk_gating_workq,
1732 &hba->clk_gating.ungate_work))
1733 ufshcd_scsi_block_requests(hba);
1735 * fall through to check if we should wait for this
1736 * work to be done or not.
1742 hba->clk_gating.active_reqs--;
1746 spin_unlock_irqrestore(hba->host->host_lock, flags);
1747 flush_work(&hba->clk_gating.ungate_work);
1748 /* Make sure state is CLKS_ON before returning */
1749 spin_lock_irqsave(hba->host->host_lock, flags);
1752 dev_err(hba->dev, "%s: clk gating is in invalid state %d\n",
1753 __func__, hba->clk_gating.state);
1756 spin_unlock_irqrestore(hba->host->host_lock, flags);
1760 EXPORT_SYMBOL_GPL(ufshcd_hold);
1762 static void ufshcd_gate_work(struct work_struct *work)
1764 struct ufs_hba *hba = container_of(work, struct ufs_hba,
1765 clk_gating.gate_work.work);
1766 unsigned long flags;
1769 spin_lock_irqsave(hba->host->host_lock, flags);
1771 * In case you are here to cancel this work the gating state
1772 * would be marked as REQ_CLKS_ON. In this case save time by
1773 * skipping the gating work and exit after changing the clock
1776 if (hba->clk_gating.is_suspended ||
1777 (hba->clk_gating.state != REQ_CLKS_OFF)) {
1778 hba->clk_gating.state = CLKS_ON;
1779 trace_ufshcd_clk_gating(dev_name(hba->dev),
1780 hba->clk_gating.state);
1784 if (hba->clk_gating.active_reqs
1785 || hba->ufshcd_state != UFSHCD_STATE_OPERATIONAL
1786 || ufshcd_any_tag_in_use(hba) || hba->outstanding_tasks
1787 || hba->active_uic_cmd || hba->uic_async_done)
1790 spin_unlock_irqrestore(hba->host->host_lock, flags);
1792 /* put the link into hibern8 mode before turning off clocks */
1793 if (ufshcd_can_hibern8_during_gating(hba)) {
1794 ret = ufshcd_uic_hibern8_enter(hba);
1796 hba->clk_gating.state = CLKS_ON;
1797 dev_err(hba->dev, "%s: hibern8 enter failed %d\n",
1799 trace_ufshcd_clk_gating(dev_name(hba->dev),
1800 hba->clk_gating.state);
1803 ufshcd_set_link_hibern8(hba);
1806 ufshcd_disable_irq(hba);
1808 ufshcd_setup_clocks(hba, false);
1810 /* Put the host controller in low power mode if possible */
1811 ufshcd_hba_vreg_set_lpm(hba);
1813 * In case you are here to cancel this work the gating state
1814 * would be marked as REQ_CLKS_ON. In this case keep the state
1815 * as REQ_CLKS_ON which would anyway imply that clocks are off
1816 * and a request to turn them on is pending. By doing this way,
1817 * we keep the state machine in tact and this would ultimately
1818 * prevent from doing cancel work multiple times when there are
1819 * new requests arriving before the current cancel work is done.
1821 spin_lock_irqsave(hba->host->host_lock, flags);
1822 if (hba->clk_gating.state == REQ_CLKS_OFF) {
1823 hba->clk_gating.state = CLKS_OFF;
1824 trace_ufshcd_clk_gating(dev_name(hba->dev),
1825 hba->clk_gating.state);
1828 spin_unlock_irqrestore(hba->host->host_lock, flags);
1833 /* host lock must be held before calling this variant */
1834 static void __ufshcd_release(struct ufs_hba *hba)
1836 if (!ufshcd_is_clkgating_allowed(hba))
1839 hba->clk_gating.active_reqs--;
1841 if (hba->clk_gating.active_reqs || hba->clk_gating.is_suspended ||
1842 hba->ufshcd_state != UFSHCD_STATE_OPERATIONAL ||
1843 hba->outstanding_tasks ||
1844 hba->active_uic_cmd || hba->uic_async_done ||
1845 hba->clk_gating.state == CLKS_OFF)
1848 hba->clk_gating.state = REQ_CLKS_OFF;
1849 trace_ufshcd_clk_gating(dev_name(hba->dev), hba->clk_gating.state);
1850 queue_delayed_work(hba->clk_gating.clk_gating_workq,
1851 &hba->clk_gating.gate_work,
1852 msecs_to_jiffies(hba->clk_gating.delay_ms));
1855 void ufshcd_release(struct ufs_hba *hba)
1857 unsigned long flags;
1859 spin_lock_irqsave(hba->host->host_lock, flags);
1860 __ufshcd_release(hba);
1861 spin_unlock_irqrestore(hba->host->host_lock, flags);
1863 EXPORT_SYMBOL_GPL(ufshcd_release);
1865 static ssize_t ufshcd_clkgate_delay_show(struct device *dev,
1866 struct device_attribute *attr, char *buf)
1868 struct ufs_hba *hba = dev_get_drvdata(dev);
1870 return sysfs_emit(buf, "%lu\n", hba->clk_gating.delay_ms);
1873 static ssize_t ufshcd_clkgate_delay_store(struct device *dev,
1874 struct device_attribute *attr, const char *buf, size_t count)
1876 struct ufs_hba *hba = dev_get_drvdata(dev);
1877 unsigned long flags, value;
1879 if (kstrtoul(buf, 0, &value))
1882 spin_lock_irqsave(hba->host->host_lock, flags);
1883 hba->clk_gating.delay_ms = value;
1884 spin_unlock_irqrestore(hba->host->host_lock, flags);
1888 static ssize_t ufshcd_clkgate_enable_show(struct device *dev,
1889 struct device_attribute *attr, char *buf)
1891 struct ufs_hba *hba = dev_get_drvdata(dev);
1893 return sysfs_emit(buf, "%d\n", hba->clk_gating.is_enabled);
1896 static ssize_t ufshcd_clkgate_enable_store(struct device *dev,
1897 struct device_attribute *attr, const char *buf, size_t count)
1899 struct ufs_hba *hba = dev_get_drvdata(dev);
1900 unsigned long flags;
1903 if (kstrtou32(buf, 0, &value))
1908 spin_lock_irqsave(hba->host->host_lock, flags);
1909 if (value == hba->clk_gating.is_enabled)
1913 __ufshcd_release(hba);
1915 hba->clk_gating.active_reqs++;
1917 hba->clk_gating.is_enabled = value;
1919 spin_unlock_irqrestore(hba->host->host_lock, flags);
1923 static void ufshcd_init_clk_gating_sysfs(struct ufs_hba *hba)
1925 hba->clk_gating.delay_attr.show = ufshcd_clkgate_delay_show;
1926 hba->clk_gating.delay_attr.store = ufshcd_clkgate_delay_store;
1927 sysfs_attr_init(&hba->clk_gating.delay_attr.attr);
1928 hba->clk_gating.delay_attr.attr.name = "clkgate_delay_ms";
1929 hba->clk_gating.delay_attr.attr.mode = 0644;
1930 if (device_create_file(hba->dev, &hba->clk_gating.delay_attr))
1931 dev_err(hba->dev, "Failed to create sysfs for clkgate_delay\n");
1933 hba->clk_gating.enable_attr.show = ufshcd_clkgate_enable_show;
1934 hba->clk_gating.enable_attr.store = ufshcd_clkgate_enable_store;
1935 sysfs_attr_init(&hba->clk_gating.enable_attr.attr);
1936 hba->clk_gating.enable_attr.attr.name = "clkgate_enable";
1937 hba->clk_gating.enable_attr.attr.mode = 0644;
1938 if (device_create_file(hba->dev, &hba->clk_gating.enable_attr))
1939 dev_err(hba->dev, "Failed to create sysfs for clkgate_enable\n");
1942 static void ufshcd_remove_clk_gating_sysfs(struct ufs_hba *hba)
1944 if (hba->clk_gating.delay_attr.attr.name)
1945 device_remove_file(hba->dev, &hba->clk_gating.delay_attr);
1946 if (hba->clk_gating.enable_attr.attr.name)
1947 device_remove_file(hba->dev, &hba->clk_gating.enable_attr);
1950 static void ufshcd_init_clk_gating(struct ufs_hba *hba)
1952 char wq_name[sizeof("ufs_clk_gating_00")];
1954 if (!ufshcd_is_clkgating_allowed(hba))
1957 hba->clk_gating.state = CLKS_ON;
1959 hba->clk_gating.delay_ms = 150;
1960 INIT_DELAYED_WORK(&hba->clk_gating.gate_work, ufshcd_gate_work);
1961 INIT_WORK(&hba->clk_gating.ungate_work, ufshcd_ungate_work);
1963 snprintf(wq_name, ARRAY_SIZE(wq_name), "ufs_clk_gating_%d",
1964 hba->host->host_no);
1965 hba->clk_gating.clk_gating_workq = alloc_ordered_workqueue(wq_name,
1966 WQ_MEM_RECLAIM | WQ_HIGHPRI);
1968 ufshcd_init_clk_gating_sysfs(hba);
1970 hba->clk_gating.is_enabled = true;
1971 hba->clk_gating.is_initialized = true;
1974 static void ufshcd_exit_clk_gating(struct ufs_hba *hba)
1976 if (!hba->clk_gating.is_initialized)
1978 ufshcd_remove_clk_gating_sysfs(hba);
1979 cancel_work_sync(&hba->clk_gating.ungate_work);
1980 cancel_delayed_work_sync(&hba->clk_gating.gate_work);
1981 destroy_workqueue(hba->clk_gating.clk_gating_workq);
1982 hba->clk_gating.is_initialized = false;
1985 /* Must be called with host lock acquired */
1986 static void ufshcd_clk_scaling_start_busy(struct ufs_hba *hba)
1988 bool queue_resume_work = false;
1989 ktime_t curr_t = ktime_get();
1991 if (!ufshcd_is_clkscaling_supported(hba))
1994 if (!hba->clk_scaling.active_reqs++)
1995 queue_resume_work = true;
1997 if (!hba->clk_scaling.is_enabled || hba->pm_op_in_progress)
2000 if (queue_resume_work)
2001 queue_work(hba->clk_scaling.workq,
2002 &hba->clk_scaling.resume_work);
2004 if (!hba->clk_scaling.window_start_t) {
2005 hba->clk_scaling.window_start_t = curr_t;
2006 hba->clk_scaling.tot_busy_t = 0;
2007 hba->clk_scaling.is_busy_started = false;
2010 if (!hba->clk_scaling.is_busy_started) {
2011 hba->clk_scaling.busy_start_t = curr_t;
2012 hba->clk_scaling.is_busy_started = true;
2016 static void ufshcd_clk_scaling_update_busy(struct ufs_hba *hba)
2018 struct ufs_clk_scaling *scaling = &hba->clk_scaling;
2020 if (!ufshcd_is_clkscaling_supported(hba))
2023 if (!hba->outstanding_reqs && scaling->is_busy_started) {
2024 scaling->tot_busy_t += ktime_to_us(ktime_sub(ktime_get(),
2025 scaling->busy_start_t));
2026 scaling->busy_start_t = 0;
2027 scaling->is_busy_started = false;
2031 * ufshcd_send_command - Send SCSI or device management commands
2032 * @hba: per adapter instance
2033 * @task_tag: Task tag of the command
2036 void ufshcd_send_command(struct ufs_hba *hba, unsigned int task_tag)
2038 struct ufshcd_lrb *lrbp = &hba->lrb[task_tag];
2040 lrbp->issue_time_stamp = ktime_get();
2041 lrbp->compl_time_stamp = ktime_set(0, 0);
2042 ufshcd_vops_setup_xfer_req(hba, task_tag, (lrbp->cmd ? true : false));
2043 ufshcd_add_command_trace(hba, task_tag, UFS_CMD_SEND);
2044 ufshcd_clk_scaling_start_busy(hba);
2045 __set_bit(task_tag, &hba->outstanding_reqs);
2046 ufshcd_writel(hba, 1 << task_tag, REG_UTP_TRANSFER_REQ_DOOR_BELL);
2047 /* Make sure that doorbell is committed immediately */
2052 * ufshcd_copy_sense_data - Copy sense data in case of check condition
2053 * @lrbp: pointer to local reference block
2055 static inline void ufshcd_copy_sense_data(struct ufshcd_lrb *lrbp)
2058 if (lrbp->sense_buffer &&
2059 ufshcd_get_rsp_upiu_data_seg_len(lrbp->ucd_rsp_ptr)) {
2062 len = be16_to_cpu(lrbp->ucd_rsp_ptr->sr.sense_data_len);
2063 len_to_copy = min_t(int, UFS_SENSE_SIZE, len);
2065 memcpy(lrbp->sense_buffer, lrbp->ucd_rsp_ptr->sr.sense_data,
2071 * ufshcd_copy_query_response() - Copy the Query Response and the data
2073 * @hba: per adapter instance
2074 * @lrbp: pointer to local reference block
2077 int ufshcd_copy_query_response(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
2079 struct ufs_query_res *query_res = &hba->dev_cmd.query.response;
2081 memcpy(&query_res->upiu_res, &lrbp->ucd_rsp_ptr->qr, QUERY_OSF_SIZE);
2083 /* Get the descriptor */
2084 if (hba->dev_cmd.query.descriptor &&
2085 lrbp->ucd_rsp_ptr->qr.opcode == UPIU_QUERY_OPCODE_READ_DESC) {
2086 u8 *descp = (u8 *)lrbp->ucd_rsp_ptr +
2087 GENERAL_UPIU_REQUEST_SIZE;
2091 /* data segment length */
2092 resp_len = be32_to_cpu(lrbp->ucd_rsp_ptr->header.dword_2) &
2093 MASK_QUERY_DATA_SEG_LEN;
2094 buf_len = be16_to_cpu(
2095 hba->dev_cmd.query.request.upiu_req.length);
2096 if (likely(buf_len >= resp_len)) {
2097 memcpy(hba->dev_cmd.query.descriptor, descp, resp_len);
2100 "%s: rsp size %d is bigger than buffer size %d",
2101 __func__, resp_len, buf_len);
2110 * ufshcd_hba_capabilities - Read controller capabilities
2111 * @hba: per adapter instance
2113 * Return: 0 on success, negative on error.
2115 static inline int ufshcd_hba_capabilities(struct ufs_hba *hba)
2119 hba->capabilities = ufshcd_readl(hba, REG_CONTROLLER_CAPABILITIES);
2121 /* nutrs and nutmrs are 0 based values */
2122 hba->nutrs = (hba->capabilities & MASK_TRANSFER_REQUESTS_SLOTS) + 1;
2124 ((hba->capabilities & MASK_TASK_MANAGEMENT_REQUEST_SLOTS) >> 16) + 1;
2126 /* Read crypto capabilities */
2127 err = ufshcd_hba_init_crypto_capabilities(hba);
2129 dev_err(hba->dev, "crypto setup failed\n");
2135 * ufshcd_ready_for_uic_cmd - Check if controller is ready
2136 * to accept UIC commands
2137 * @hba: per adapter instance
2138 * Return true on success, else false
2140 static inline bool ufshcd_ready_for_uic_cmd(struct ufs_hba *hba)
2142 if (ufshcd_readl(hba, REG_CONTROLLER_STATUS) & UIC_COMMAND_READY)
2149 * ufshcd_get_upmcrs - Get the power mode change request status
2150 * @hba: Pointer to adapter instance
2152 * This function gets the UPMCRS field of HCS register
2153 * Returns value of UPMCRS field
2155 static inline u8 ufshcd_get_upmcrs(struct ufs_hba *hba)
2157 return (ufshcd_readl(hba, REG_CONTROLLER_STATUS) >> 8) & 0x7;
2161 * ufshcd_dispatch_uic_cmd - Dispatch UIC commands to unipro layers
2162 * @hba: per adapter instance
2163 * @uic_cmd: UIC command
2165 * Mutex must be held.
2168 ufshcd_dispatch_uic_cmd(struct ufs_hba *hba, struct uic_command *uic_cmd)
2170 WARN_ON(hba->active_uic_cmd);
2172 hba->active_uic_cmd = uic_cmd;
2175 ufshcd_writel(hba, uic_cmd->argument1, REG_UIC_COMMAND_ARG_1);
2176 ufshcd_writel(hba, uic_cmd->argument2, REG_UIC_COMMAND_ARG_2);
2177 ufshcd_writel(hba, uic_cmd->argument3, REG_UIC_COMMAND_ARG_3);
2179 ufshcd_add_uic_command_trace(hba, uic_cmd, UFS_CMD_SEND);
2182 ufshcd_writel(hba, uic_cmd->command & COMMAND_OPCODE_MASK,
2187 * ufshcd_wait_for_uic_cmd - Wait complectioin of UIC command
2188 * @hba: per adapter instance
2189 * @uic_cmd: UIC command
2191 * Must be called with mutex held.
2192 * Returns 0 only if success.
2195 ufshcd_wait_for_uic_cmd(struct ufs_hba *hba, struct uic_command *uic_cmd)
2198 unsigned long flags;
2200 if (wait_for_completion_timeout(&uic_cmd->done,
2201 msecs_to_jiffies(UIC_CMD_TIMEOUT))) {
2202 ret = uic_cmd->argument2 & MASK_UIC_COMMAND_RESULT;
2206 "uic cmd 0x%x with arg3 0x%x completion timeout\n",
2207 uic_cmd->command, uic_cmd->argument3);
2209 if (!uic_cmd->cmd_active) {
2210 dev_err(hba->dev, "%s: UIC cmd has been completed, return the result\n",
2212 ret = uic_cmd->argument2 & MASK_UIC_COMMAND_RESULT;
2216 spin_lock_irqsave(hba->host->host_lock, flags);
2217 hba->active_uic_cmd = NULL;
2218 spin_unlock_irqrestore(hba->host->host_lock, flags);
2224 * __ufshcd_send_uic_cmd - Send UIC commands and retrieve the result
2225 * @hba: per adapter instance
2226 * @uic_cmd: UIC command
2227 * @completion: initialize the completion only if this is set to true
2229 * Identical to ufshcd_send_uic_cmd() expect mutex. Must be called
2230 * with mutex held and host_lock locked.
2231 * Returns 0 only if success.
2234 __ufshcd_send_uic_cmd(struct ufs_hba *hba, struct uic_command *uic_cmd,
2237 if (!ufshcd_ready_for_uic_cmd(hba)) {
2239 "Controller not ready to accept UIC commands\n");
2244 init_completion(&uic_cmd->done);
2246 uic_cmd->cmd_active = 1;
2247 ufshcd_dispatch_uic_cmd(hba, uic_cmd);
2253 * ufshcd_send_uic_cmd - Send UIC commands and retrieve the result
2254 * @hba: per adapter instance
2255 * @uic_cmd: UIC command
2257 * Returns 0 only if success.
2259 int ufshcd_send_uic_cmd(struct ufs_hba *hba, struct uic_command *uic_cmd)
2262 unsigned long flags;
2264 ufshcd_hold(hba, false);
2265 mutex_lock(&hba->uic_cmd_mutex);
2266 ufshcd_add_delay_before_dme_cmd(hba);
2268 spin_lock_irqsave(hba->host->host_lock, flags);
2269 ret = __ufshcd_send_uic_cmd(hba, uic_cmd, true);
2270 spin_unlock_irqrestore(hba->host->host_lock, flags);
2272 ret = ufshcd_wait_for_uic_cmd(hba, uic_cmd);
2274 mutex_unlock(&hba->uic_cmd_mutex);
2276 ufshcd_release(hba);
2281 * ufshcd_map_sg - Map scatter-gather list to prdt
2282 * @hba: per adapter instance
2283 * @lrbp: pointer to local reference block
2285 * Returns 0 in case of success, non-zero value in case of failure
2287 static int ufshcd_map_sg(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
2289 struct ufshcd_sg_entry *prd_table;
2290 struct scatterlist *sg;
2291 struct scsi_cmnd *cmd;
2296 sg_segments = scsi_dma_map(cmd);
2297 if (sg_segments < 0)
2302 if (hba->quirks & UFSHCD_QUIRK_PRDT_BYTE_GRAN)
2303 lrbp->utr_descriptor_ptr->prd_table_length =
2304 cpu_to_le16((sg_segments *
2305 sizeof(struct ufshcd_sg_entry)));
2307 lrbp->utr_descriptor_ptr->prd_table_length =
2308 cpu_to_le16((u16) (sg_segments));
2310 prd_table = (struct ufshcd_sg_entry *)lrbp->ucd_prdt_ptr;
2312 scsi_for_each_sg(cmd, sg, sg_segments, i) {
2314 cpu_to_le32(((u32) sg_dma_len(sg))-1);
2315 prd_table[i].base_addr =
2316 cpu_to_le32(lower_32_bits(sg->dma_address));
2317 prd_table[i].upper_addr =
2318 cpu_to_le32(upper_32_bits(sg->dma_address));
2319 prd_table[i].reserved = 0;
2322 lrbp->utr_descriptor_ptr->prd_table_length = 0;
2329 * ufshcd_enable_intr - enable interrupts
2330 * @hba: per adapter instance
2331 * @intrs: interrupt bits
2333 static void ufshcd_enable_intr(struct ufs_hba *hba, u32 intrs)
2335 u32 set = ufshcd_readl(hba, REG_INTERRUPT_ENABLE);
2337 if (hba->ufs_version == UFSHCI_VERSION_10) {
2339 rw = set & INTERRUPT_MASK_RW_VER_10;
2340 set = rw | ((set ^ intrs) & intrs);
2345 ufshcd_writel(hba, set, REG_INTERRUPT_ENABLE);
2349 * ufshcd_disable_intr - disable interrupts
2350 * @hba: per adapter instance
2351 * @intrs: interrupt bits
2353 static void ufshcd_disable_intr(struct ufs_hba *hba, u32 intrs)
2355 u32 set = ufshcd_readl(hba, REG_INTERRUPT_ENABLE);
2357 if (hba->ufs_version == UFSHCI_VERSION_10) {
2359 rw = (set & INTERRUPT_MASK_RW_VER_10) &
2360 ~(intrs & INTERRUPT_MASK_RW_VER_10);
2361 set = rw | ((set & intrs) & ~INTERRUPT_MASK_RW_VER_10);
2367 ufshcd_writel(hba, set, REG_INTERRUPT_ENABLE);
2371 * ufshcd_prepare_req_desc_hdr() - Fills the requests header
2372 * descriptor according to request
2373 * @lrbp: pointer to local reference block
2374 * @upiu_flags: flags required in the header
2375 * @cmd_dir: requests data direction
2377 static void ufshcd_prepare_req_desc_hdr(struct ufshcd_lrb *lrbp,
2378 u8 *upiu_flags, enum dma_data_direction cmd_dir)
2380 struct utp_transfer_req_desc *req_desc = lrbp->utr_descriptor_ptr;
2386 if (cmd_dir == DMA_FROM_DEVICE) {
2387 data_direction = UTP_DEVICE_TO_HOST;
2388 *upiu_flags = UPIU_CMD_FLAGS_READ;
2389 } else if (cmd_dir == DMA_TO_DEVICE) {
2390 data_direction = UTP_HOST_TO_DEVICE;
2391 *upiu_flags = UPIU_CMD_FLAGS_WRITE;
2393 data_direction = UTP_NO_DATA_TRANSFER;
2394 *upiu_flags = UPIU_CMD_FLAGS_NONE;
2397 dword_0 = data_direction | (lrbp->command_type
2398 << UPIU_COMMAND_TYPE_OFFSET);
2400 dword_0 |= UTP_REQ_DESC_INT_CMD;
2402 /* Prepare crypto related dwords */
2403 ufshcd_prepare_req_desc_hdr_crypto(lrbp, &dword_0, &dword_1, &dword_3);
2405 /* Transfer request descriptor header fields */
2406 req_desc->header.dword_0 = cpu_to_le32(dword_0);
2407 req_desc->header.dword_1 = cpu_to_le32(dword_1);
2409 * assigning invalid value for command status. Controller
2410 * updates OCS on command completion, with the command
2413 req_desc->header.dword_2 =
2414 cpu_to_le32(OCS_INVALID_COMMAND_STATUS);
2415 req_desc->header.dword_3 = cpu_to_le32(dword_3);
2417 req_desc->prd_table_length = 0;
2421 * ufshcd_prepare_utp_scsi_cmd_upiu() - fills the utp_transfer_req_desc,
2423 * @lrbp: local reference block pointer
2424 * @upiu_flags: flags
2427 void ufshcd_prepare_utp_scsi_cmd_upiu(struct ufshcd_lrb *lrbp, u8 upiu_flags)
2429 struct scsi_cmnd *cmd = lrbp->cmd;
2430 struct utp_upiu_req *ucd_req_ptr = lrbp->ucd_req_ptr;
2431 unsigned short cdb_len;
2433 /* command descriptor fields */
2434 ucd_req_ptr->header.dword_0 = UPIU_HEADER_DWORD(
2435 UPIU_TRANSACTION_COMMAND, upiu_flags,
2436 lrbp->lun, lrbp->task_tag);
2437 ucd_req_ptr->header.dword_1 = UPIU_HEADER_DWORD(
2438 UPIU_COMMAND_SET_TYPE_SCSI, 0, 0, 0);
2440 /* Total EHS length and Data segment length will be zero */
2441 ucd_req_ptr->header.dword_2 = 0;
2443 ucd_req_ptr->sc.exp_data_transfer_len = cpu_to_be32(cmd->sdb.length);
2445 cdb_len = min_t(unsigned short, cmd->cmd_len, UFS_CDB_SIZE);
2446 memset(ucd_req_ptr->sc.cdb, 0, UFS_CDB_SIZE);
2447 memcpy(ucd_req_ptr->sc.cdb, cmd->cmnd, cdb_len);
2449 memset(lrbp->ucd_rsp_ptr, 0, sizeof(struct utp_upiu_rsp));
2453 * ufshcd_prepare_utp_query_req_upiu() - fills the utp_transfer_req_desc,
2456 * @lrbp: local reference block pointer
2457 * @upiu_flags: flags
2459 static void ufshcd_prepare_utp_query_req_upiu(struct ufs_hba *hba,
2460 struct ufshcd_lrb *lrbp, u8 upiu_flags)
2462 struct utp_upiu_req *ucd_req_ptr = lrbp->ucd_req_ptr;
2463 struct ufs_query *query = &hba->dev_cmd.query;
2464 u16 len = be16_to_cpu(query->request.upiu_req.length);
2466 /* Query request header */
2467 ucd_req_ptr->header.dword_0 = UPIU_HEADER_DWORD(
2468 UPIU_TRANSACTION_QUERY_REQ, upiu_flags,
2469 lrbp->lun, lrbp->task_tag);
2470 ucd_req_ptr->header.dword_1 = UPIU_HEADER_DWORD(
2471 0, query->request.query_func, 0, 0);
2473 /* Data segment length only need for WRITE_DESC */
2474 if (query->request.upiu_req.opcode == UPIU_QUERY_OPCODE_WRITE_DESC)
2475 ucd_req_ptr->header.dword_2 =
2476 UPIU_HEADER_DWORD(0, 0, (len >> 8), (u8)len);
2478 ucd_req_ptr->header.dword_2 = 0;
2480 /* Copy the Query Request buffer as is */
2481 memcpy(&ucd_req_ptr->qr, &query->request.upiu_req,
2484 /* Copy the Descriptor */
2485 if (query->request.upiu_req.opcode == UPIU_QUERY_OPCODE_WRITE_DESC)
2486 memcpy(ucd_req_ptr + 1, query->descriptor, len);
2488 memset(lrbp->ucd_rsp_ptr, 0, sizeof(struct utp_upiu_rsp));
2491 static inline void ufshcd_prepare_utp_nop_upiu(struct ufshcd_lrb *lrbp)
2493 struct utp_upiu_req *ucd_req_ptr = lrbp->ucd_req_ptr;
2495 memset(ucd_req_ptr, 0, sizeof(struct utp_upiu_req));
2497 /* command descriptor fields */
2498 ucd_req_ptr->header.dword_0 =
2500 UPIU_TRANSACTION_NOP_OUT, 0, 0, lrbp->task_tag);
2501 /* clear rest of the fields of basic header */
2502 ucd_req_ptr->header.dword_1 = 0;
2503 ucd_req_ptr->header.dword_2 = 0;
2505 memset(lrbp->ucd_rsp_ptr, 0, sizeof(struct utp_upiu_rsp));
2509 * ufshcd_compose_devman_upiu - UFS Protocol Information Unit(UPIU)
2510 * for Device Management Purposes
2511 * @hba: per adapter instance
2512 * @lrbp: pointer to local reference block
2514 static int ufshcd_compose_devman_upiu(struct ufs_hba *hba,
2515 struct ufshcd_lrb *lrbp)
2520 if ((hba->ufs_version == UFSHCI_VERSION_10) ||
2521 (hba->ufs_version == UFSHCI_VERSION_11))
2522 lrbp->command_type = UTP_CMD_TYPE_DEV_MANAGE;
2524 lrbp->command_type = UTP_CMD_TYPE_UFS_STORAGE;
2526 ufshcd_prepare_req_desc_hdr(lrbp, &upiu_flags, DMA_NONE);
2527 if (hba->dev_cmd.type == DEV_CMD_TYPE_QUERY)
2528 ufshcd_prepare_utp_query_req_upiu(hba, lrbp, upiu_flags);
2529 else if (hba->dev_cmd.type == DEV_CMD_TYPE_NOP)
2530 ufshcd_prepare_utp_nop_upiu(lrbp);
2538 * ufshcd_comp_scsi_upiu - UFS Protocol Information Unit(UPIU)
2540 * @hba: per adapter instance
2541 * @lrbp: pointer to local reference block
2543 static int ufshcd_comp_scsi_upiu(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
2548 if ((hba->ufs_version == UFSHCI_VERSION_10) ||
2549 (hba->ufs_version == UFSHCI_VERSION_11))
2550 lrbp->command_type = UTP_CMD_TYPE_SCSI;
2552 lrbp->command_type = UTP_CMD_TYPE_UFS_STORAGE;
2554 if (likely(lrbp->cmd)) {
2555 ufshcd_prepare_req_desc_hdr(lrbp, &upiu_flags,
2556 lrbp->cmd->sc_data_direction);
2557 ufshcd_prepare_utp_scsi_cmd_upiu(lrbp, upiu_flags);
2566 * ufshcd_upiu_wlun_to_scsi_wlun - maps UPIU W-LUN id to SCSI W-LUN ID
2567 * @upiu_wlun_id: UPIU W-LUN id
2569 * Returns SCSI W-LUN id
2571 static inline u16 ufshcd_upiu_wlun_to_scsi_wlun(u8 upiu_wlun_id)
2573 return (upiu_wlun_id & ~UFS_UPIU_WLUN_ID) | SCSI_W_LUN_BASE;
2576 static void ufshcd_init_lrb(struct ufs_hba *hba, struct ufshcd_lrb *lrb, int i)
2578 struct utp_transfer_cmd_desc *cmd_descp = hba->ucdl_base_addr;
2579 struct utp_transfer_req_desc *utrdlp = hba->utrdl_base_addr;
2580 dma_addr_t cmd_desc_element_addr = hba->ucdl_dma_addr +
2581 i * sizeof(struct utp_transfer_cmd_desc);
2582 u16 response_offset = offsetof(struct utp_transfer_cmd_desc,
2584 u16 prdt_offset = offsetof(struct utp_transfer_cmd_desc, prd_table);
2586 lrb->utr_descriptor_ptr = utrdlp + i;
2587 lrb->utrd_dma_addr = hba->utrdl_dma_addr +
2588 i * sizeof(struct utp_transfer_req_desc);
2589 lrb->ucd_req_ptr = (struct utp_upiu_req *)(cmd_descp + i);
2590 lrb->ucd_req_dma_addr = cmd_desc_element_addr;
2591 lrb->ucd_rsp_ptr = (struct utp_upiu_rsp *)cmd_descp[i].response_upiu;
2592 lrb->ucd_rsp_dma_addr = cmd_desc_element_addr + response_offset;
2593 lrb->ucd_prdt_ptr = (struct ufshcd_sg_entry *)cmd_descp[i].prd_table;
2594 lrb->ucd_prdt_dma_addr = cmd_desc_element_addr + prdt_offset;
2598 * ufshcd_queuecommand - main entry point for SCSI requests
2599 * @host: SCSI host pointer
2600 * @cmd: command from SCSI Midlayer
2602 * Returns 0 for success, non-zero in case of failure
2604 static int ufshcd_queuecommand(struct Scsi_Host *host, struct scsi_cmnd *cmd)
2606 struct ufshcd_lrb *lrbp;
2607 struct ufs_hba *hba;
2608 unsigned long flags;
2612 hba = shost_priv(host);
2614 tag = cmd->request->tag;
2615 if (!ufshcd_valid_tag(hba, tag)) {
2617 "%s: invalid command tag %d: cmd=0x%p, cmd->request=0x%p",
2618 __func__, tag, cmd, cmd->request);
2622 if (!down_read_trylock(&hba->clk_scaling_lock))
2623 return SCSI_MLQUEUE_HOST_BUSY;
2625 hba->req_abort_count = 0;
2627 err = ufshcd_hold(hba, true);
2629 err = SCSI_MLQUEUE_HOST_BUSY;
2632 WARN_ON(ufshcd_is_clkgating_allowed(hba) &&
2633 (hba->clk_gating.state != CLKS_ON));
2635 lrbp = &hba->lrb[tag];
2636 if (unlikely(lrbp->in_use)) {
2637 if (hba->pm_op_in_progress)
2638 set_host_byte(cmd, DID_BAD_TARGET);
2640 err = SCSI_MLQUEUE_HOST_BUSY;
2641 ufshcd_release(hba);
2647 lrbp->sense_bufflen = UFS_SENSE_SIZE;
2648 lrbp->sense_buffer = cmd->sense_buffer;
2649 lrbp->task_tag = tag;
2650 lrbp->lun = ufshcd_scsi_to_upiu_lun(cmd->device->lun);
2651 lrbp->intr_cmd = !ufshcd_is_intr_aggr_allowed(hba) ? true : false;
2653 ufshcd_prepare_lrbp_crypto(cmd->request, lrbp);
2655 lrbp->req_abort_skip = false;
2657 ufshcd_comp_scsi_upiu(hba, lrbp);
2659 err = ufshcd_map_sg(hba, lrbp);
2662 ufshcd_release(hba);
2665 /* Make sure descriptors are ready before ringing the doorbell */
2668 spin_lock_irqsave(hba->host->host_lock, flags);
2669 switch (hba->ufshcd_state) {
2670 case UFSHCD_STATE_OPERATIONAL:
2671 case UFSHCD_STATE_EH_SCHEDULED_NON_FATAL:
2673 case UFSHCD_STATE_EH_SCHEDULED_FATAL:
2675 * pm_runtime_get_sync() is used at error handling preparation
2676 * stage. If a scsi cmd, e.g. the SSU cmd, is sent from hba's
2677 * PM ops, it can never be finished if we let SCSI layer keep
2678 * retrying it, which gets err handler stuck forever. Neither
2679 * can we let the scsi cmd pass through, because UFS is in bad
2680 * state, the scsi cmd may eventually time out, which will get
2681 * err handler blocked for too long. So, just fail the scsi cmd
2682 * sent from PM ops, err handler can recover PM error anyways.
2684 if (hba->pm_op_in_progress) {
2685 hba->force_reset = true;
2686 set_host_byte(cmd, DID_BAD_TARGET);
2690 case UFSHCD_STATE_RESET:
2691 err = SCSI_MLQUEUE_HOST_BUSY;
2693 case UFSHCD_STATE_ERROR:
2694 set_host_byte(cmd, DID_ERROR);
2697 dev_WARN_ONCE(hba->dev, 1, "%s: invalid state %d\n",
2698 __func__, hba->ufshcd_state);
2699 set_host_byte(cmd, DID_BAD_TARGET);
2702 ufshcd_send_command(hba, tag);
2703 spin_unlock_irqrestore(hba->host->host_lock, flags);
2707 scsi_dma_unmap(lrbp->cmd);
2709 spin_unlock_irqrestore(hba->host->host_lock, flags);
2710 ufshcd_release(hba);
2712 cmd->scsi_done(cmd);
2714 up_read(&hba->clk_scaling_lock);
2718 static int ufshcd_compose_dev_cmd(struct ufs_hba *hba,
2719 struct ufshcd_lrb *lrbp, enum dev_cmd_type cmd_type, int tag)
2722 lrbp->sense_bufflen = 0;
2723 lrbp->sense_buffer = NULL;
2724 lrbp->task_tag = tag;
2725 lrbp->lun = 0; /* device management cmd is not specific to any LUN */
2726 lrbp->intr_cmd = true; /* No interrupt aggregation */
2727 ufshcd_prepare_lrbp_crypto(NULL, lrbp);
2728 hba->dev_cmd.type = cmd_type;
2730 return ufshcd_compose_devman_upiu(hba, lrbp);
2734 ufshcd_clear_cmd(struct ufs_hba *hba, int tag)
2737 unsigned long flags;
2738 u32 mask = 1 << tag;
2740 /* clear outstanding transaction before retry */
2741 spin_lock_irqsave(hba->host->host_lock, flags);
2742 ufshcd_utrl_clear(hba, tag);
2743 spin_unlock_irqrestore(hba->host->host_lock, flags);
2746 * wait for for h/w to clear corresponding bit in door-bell.
2747 * max. wait is 1 sec.
2749 err = ufshcd_wait_for_register(hba,
2750 REG_UTP_TRANSFER_REQ_DOOR_BELL,
2751 mask, ~mask, 1000, 1000);
2757 ufshcd_check_query_response(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
2759 struct ufs_query_res *query_res = &hba->dev_cmd.query.response;
2761 /* Get the UPIU response */
2762 query_res->response = ufshcd_get_rsp_upiu_result(lrbp->ucd_rsp_ptr) >>
2763 UPIU_RSP_CODE_OFFSET;
2764 return query_res->response;
2768 * ufshcd_dev_cmd_completion() - handles device management command responses
2769 * @hba: per adapter instance
2770 * @lrbp: pointer to local reference block
2773 ufshcd_dev_cmd_completion(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
2778 hba->ufs_stats.last_hibern8_exit_tstamp = ktime_set(0, 0);
2779 resp = ufshcd_get_req_rsp(lrbp->ucd_rsp_ptr);
2782 case UPIU_TRANSACTION_NOP_IN:
2783 if (hba->dev_cmd.type != DEV_CMD_TYPE_NOP) {
2785 dev_err(hba->dev, "%s: unexpected response %x\n",
2789 case UPIU_TRANSACTION_QUERY_RSP:
2790 err = ufshcd_check_query_response(hba, lrbp);
2792 err = ufshcd_copy_query_response(hba, lrbp);
2794 case UPIU_TRANSACTION_REJECT_UPIU:
2795 /* TODO: handle Reject UPIU Response */
2797 dev_err(hba->dev, "%s: Reject UPIU not fully implemented\n",
2802 dev_err(hba->dev, "%s: Invalid device management cmd response: %x\n",
2810 static int ufshcd_wait_for_dev_cmd(struct ufs_hba *hba,
2811 struct ufshcd_lrb *lrbp, int max_timeout)
2814 unsigned long time_left;
2815 unsigned long flags;
2817 time_left = wait_for_completion_timeout(hba->dev_cmd.complete,
2818 msecs_to_jiffies(max_timeout));
2820 /* Make sure descriptors are ready before ringing the doorbell */
2822 spin_lock_irqsave(hba->host->host_lock, flags);
2823 hba->dev_cmd.complete = NULL;
2824 if (likely(time_left)) {
2825 err = ufshcd_get_tr_ocs(lrbp);
2827 err = ufshcd_dev_cmd_completion(hba, lrbp);
2829 spin_unlock_irqrestore(hba->host->host_lock, flags);
2833 dev_dbg(hba->dev, "%s: dev_cmd request timedout, tag %d\n",
2834 __func__, lrbp->task_tag);
2835 if (!ufshcd_clear_cmd(hba, lrbp->task_tag))
2836 /* successfully cleared the command, retry if needed */
2839 * in case of an error, after clearing the doorbell,
2840 * we also need to clear the outstanding_request
2843 ufshcd_outstanding_req_clear(hba, lrbp->task_tag);
2850 * ufshcd_exec_dev_cmd - API for sending device management requests
2852 * @cmd_type: specifies the type (NOP, Query...)
2853 * @timeout: time in seconds
2855 * NOTE: Since there is only one available tag for device management commands,
2856 * it is expected you hold the hba->dev_cmd.lock mutex.
2858 static int ufshcd_exec_dev_cmd(struct ufs_hba *hba,
2859 enum dev_cmd_type cmd_type, int timeout)
2861 struct request_queue *q = hba->cmd_queue;
2862 struct request *req;
2863 struct ufshcd_lrb *lrbp;
2866 struct completion wait;
2867 unsigned long flags;
2869 down_read(&hba->clk_scaling_lock);
2872 * Get free slot, sleep if slots are unavailable.
2873 * Even though we use wait_event() which sleeps indefinitely,
2874 * the maximum wait time is bounded by SCSI request timeout.
2876 req = blk_get_request(q, REQ_OP_DRV_OUT, 0);
2882 WARN_ON_ONCE(!ufshcd_valid_tag(hba, tag));
2884 init_completion(&wait);
2885 lrbp = &hba->lrb[tag];
2886 if (unlikely(lrbp->in_use)) {
2892 err = ufshcd_compose_dev_cmd(hba, lrbp, cmd_type, tag);
2896 hba->dev_cmd.complete = &wait;
2898 ufshcd_add_query_upiu_trace(hba, UFS_QUERY_SEND, lrbp->ucd_req_ptr);
2899 /* Make sure descriptors are ready before ringing the doorbell */
2901 spin_lock_irqsave(hba->host->host_lock, flags);
2902 ufshcd_send_command(hba, tag);
2903 spin_unlock_irqrestore(hba->host->host_lock, flags);
2905 err = ufshcd_wait_for_dev_cmd(hba, lrbp, timeout);
2908 ufshcd_add_query_upiu_trace(hba, err ? UFS_QUERY_ERR : UFS_QUERY_COMP,
2909 (struct utp_upiu_req *)lrbp->ucd_rsp_ptr);
2912 blk_put_request(req);
2914 up_read(&hba->clk_scaling_lock);
2919 * ufshcd_init_query() - init the query response and request parameters
2920 * @hba: per-adapter instance
2921 * @request: address of the request pointer to be initialized
2922 * @response: address of the response pointer to be initialized
2923 * @opcode: operation to perform
2924 * @idn: flag idn to access
2925 * @index: LU number to access
2926 * @selector: query/flag/descriptor further identification
2928 static inline void ufshcd_init_query(struct ufs_hba *hba,
2929 struct ufs_query_req **request, struct ufs_query_res **response,
2930 enum query_opcode opcode, u8 idn, u8 index, u8 selector)
2932 *request = &hba->dev_cmd.query.request;
2933 *response = &hba->dev_cmd.query.response;
2934 memset(*request, 0, sizeof(struct ufs_query_req));
2935 memset(*response, 0, sizeof(struct ufs_query_res));
2936 (*request)->upiu_req.opcode = opcode;
2937 (*request)->upiu_req.idn = idn;
2938 (*request)->upiu_req.index = index;
2939 (*request)->upiu_req.selector = selector;
2942 static int ufshcd_query_flag_retry(struct ufs_hba *hba,
2943 enum query_opcode opcode, enum flag_idn idn, u8 index, bool *flag_res)
2948 for (retries = 0; retries < QUERY_REQ_RETRIES; retries++) {
2949 ret = ufshcd_query_flag(hba, opcode, idn, index, flag_res);
2952 "%s: failed with error %d, retries %d\n",
2953 __func__, ret, retries);
2960 "%s: query attribute, opcode %d, idn %d, failed with error %d after %d retires\n",
2961 __func__, opcode, idn, ret, retries);
2966 * ufshcd_query_flag() - API function for sending flag query requests
2967 * @hba: per-adapter instance
2968 * @opcode: flag query to perform
2969 * @idn: flag idn to access
2970 * @index: flag index to access
2971 * @flag_res: the flag value after the query request completes
2973 * Returns 0 for success, non-zero in case of failure
2975 int ufshcd_query_flag(struct ufs_hba *hba, enum query_opcode opcode,
2976 enum flag_idn idn, u8 index, bool *flag_res)
2978 struct ufs_query_req *request = NULL;
2979 struct ufs_query_res *response = NULL;
2980 int err, selector = 0;
2981 int timeout = QUERY_REQ_TIMEOUT;
2985 ufshcd_hold(hba, false);
2986 mutex_lock(&hba->dev_cmd.lock);
2987 ufshcd_init_query(hba, &request, &response, opcode, idn, index,
2991 case UPIU_QUERY_OPCODE_SET_FLAG:
2992 case UPIU_QUERY_OPCODE_CLEAR_FLAG:
2993 case UPIU_QUERY_OPCODE_TOGGLE_FLAG:
2994 request->query_func = UPIU_QUERY_FUNC_STANDARD_WRITE_REQUEST;
2996 case UPIU_QUERY_OPCODE_READ_FLAG:
2997 request->query_func = UPIU_QUERY_FUNC_STANDARD_READ_REQUEST;
2999 /* No dummy reads */
3000 dev_err(hba->dev, "%s: Invalid argument for read request\n",
3008 "%s: Expected query flag opcode but got = %d\n",
3014 err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_QUERY, timeout);
3018 "%s: Sending flag query for idn %d failed, err = %d\n",
3019 __func__, idn, err);
3024 *flag_res = (be32_to_cpu(response->upiu_res.value) &
3025 MASK_QUERY_UPIU_FLAG_LOC) & 0x1;
3028 mutex_unlock(&hba->dev_cmd.lock);
3029 ufshcd_release(hba);
3034 * ufshcd_query_attr - API function for sending attribute requests
3035 * @hba: per-adapter instance
3036 * @opcode: attribute opcode
3037 * @idn: attribute idn to access
3038 * @index: index field
3039 * @selector: selector field
3040 * @attr_val: the attribute value after the query request completes
3042 * Returns 0 for success, non-zero in case of failure
3044 int ufshcd_query_attr(struct ufs_hba *hba, enum query_opcode opcode,
3045 enum attr_idn idn, u8 index, u8 selector, u32 *attr_val)
3047 struct ufs_query_req *request = NULL;
3048 struct ufs_query_res *response = NULL;
3054 dev_err(hba->dev, "%s: attribute value required for opcode 0x%x\n",
3059 ufshcd_hold(hba, false);
3061 mutex_lock(&hba->dev_cmd.lock);
3062 ufshcd_init_query(hba, &request, &response, opcode, idn, index,
3066 case UPIU_QUERY_OPCODE_WRITE_ATTR:
3067 request->query_func = UPIU_QUERY_FUNC_STANDARD_WRITE_REQUEST;
3068 request->upiu_req.value = cpu_to_be32(*attr_val);
3070 case UPIU_QUERY_OPCODE_READ_ATTR:
3071 request->query_func = UPIU_QUERY_FUNC_STANDARD_READ_REQUEST;
3074 dev_err(hba->dev, "%s: Expected query attr opcode but got = 0x%.2x\n",
3080 err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_QUERY, QUERY_REQ_TIMEOUT);
3083 dev_err(hba->dev, "%s: opcode 0x%.2x for idn %d failed, index %d, err = %d\n",
3084 __func__, opcode, idn, index, err);
3088 *attr_val = be32_to_cpu(response->upiu_res.value);
3091 mutex_unlock(&hba->dev_cmd.lock);
3092 ufshcd_release(hba);
3097 * ufshcd_query_attr_retry() - API function for sending query
3098 * attribute with retries
3099 * @hba: per-adapter instance
3100 * @opcode: attribute opcode
3101 * @idn: attribute idn to access
3102 * @index: index field
3103 * @selector: selector field
3104 * @attr_val: the attribute value after the query request
3107 * Returns 0 for success, non-zero in case of failure
3109 static int ufshcd_query_attr_retry(struct ufs_hba *hba,
3110 enum query_opcode opcode, enum attr_idn idn, u8 index, u8 selector,
3116 for (retries = QUERY_REQ_RETRIES; retries > 0; retries--) {
3117 ret = ufshcd_query_attr(hba, opcode, idn, index,
3118 selector, attr_val);
3120 dev_dbg(hba->dev, "%s: failed with error %d, retries %d\n",
3121 __func__, ret, retries);
3128 "%s: query attribute, idn %d, failed with error %d after %d retires\n",
3129 __func__, idn, ret, QUERY_REQ_RETRIES);
3133 static int __ufshcd_query_descriptor(struct ufs_hba *hba,
3134 enum query_opcode opcode, enum desc_idn idn, u8 index,
3135 u8 selector, u8 *desc_buf, int *buf_len)
3137 struct ufs_query_req *request = NULL;
3138 struct ufs_query_res *response = NULL;
3144 dev_err(hba->dev, "%s: descriptor buffer required for opcode 0x%x\n",
3149 if (*buf_len < QUERY_DESC_MIN_SIZE || *buf_len > QUERY_DESC_MAX_SIZE) {
3150 dev_err(hba->dev, "%s: descriptor buffer size (%d) is out of range\n",
3151 __func__, *buf_len);
3155 ufshcd_hold(hba, false);
3157 mutex_lock(&hba->dev_cmd.lock);
3158 ufshcd_init_query(hba, &request, &response, opcode, idn, index,
3160 hba->dev_cmd.query.descriptor = desc_buf;
3161 request->upiu_req.length = cpu_to_be16(*buf_len);
3164 case UPIU_QUERY_OPCODE_WRITE_DESC:
3165 request->query_func = UPIU_QUERY_FUNC_STANDARD_WRITE_REQUEST;
3167 case UPIU_QUERY_OPCODE_READ_DESC:
3168 request->query_func = UPIU_QUERY_FUNC_STANDARD_READ_REQUEST;
3172 "%s: Expected query descriptor opcode but got = 0x%.2x\n",
3178 err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_QUERY, QUERY_REQ_TIMEOUT);
3181 dev_err(hba->dev, "%s: opcode 0x%.2x for idn %d failed, index %d, err = %d\n",
3182 __func__, opcode, idn, index, err);
3186 *buf_len = be16_to_cpu(response->upiu_res.length);
3189 hba->dev_cmd.query.descriptor = NULL;
3190 mutex_unlock(&hba->dev_cmd.lock);
3191 ufshcd_release(hba);
3196 * ufshcd_query_descriptor_retry - API function for sending descriptor requests
3197 * @hba: per-adapter instance
3198 * @opcode: attribute opcode
3199 * @idn: attribute idn to access
3200 * @index: index field
3201 * @selector: selector field
3202 * @desc_buf: the buffer that contains the descriptor
3203 * @buf_len: length parameter passed to the device
3205 * Returns 0 for success, non-zero in case of failure.
3206 * The buf_len parameter will contain, on return, the length parameter
3207 * received on the response.
3209 int ufshcd_query_descriptor_retry(struct ufs_hba *hba,
3210 enum query_opcode opcode,
3211 enum desc_idn idn, u8 index,
3213 u8 *desc_buf, int *buf_len)
3218 for (retries = QUERY_REQ_RETRIES; retries > 0; retries--) {
3219 err = __ufshcd_query_descriptor(hba, opcode, idn, index,
3220 selector, desc_buf, buf_len);
3221 if (!err || err == -EINVAL)
3229 * ufshcd_map_desc_id_to_length - map descriptor IDN to its length
3230 * @hba: Pointer to adapter instance
3231 * @desc_id: descriptor idn value
3232 * @desc_len: mapped desc length (out)
3234 void ufshcd_map_desc_id_to_length(struct ufs_hba *hba, enum desc_idn desc_id,
3237 if (desc_id >= QUERY_DESC_IDN_MAX || desc_id == QUERY_DESC_IDN_RFU_0 ||
3238 desc_id == QUERY_DESC_IDN_RFU_1)
3241 *desc_len = hba->desc_size[desc_id];
3243 EXPORT_SYMBOL(ufshcd_map_desc_id_to_length);
3245 static void ufshcd_update_desc_length(struct ufs_hba *hba,
3246 enum desc_idn desc_id, int desc_index,
3247 unsigned char desc_len)
3249 if (hba->desc_size[desc_id] == QUERY_DESC_MAX_SIZE &&
3250 desc_id != QUERY_DESC_IDN_STRING && desc_index != UFS_RPMB_UNIT)
3251 /* For UFS 3.1, the normal unit descriptor is 10 bytes larger
3252 * than the RPMB unit, however, both descriptors share the same
3253 * desc_idn, to cover both unit descriptors with one length, we
3254 * choose the normal unit descriptor length by desc_index.
3256 hba->desc_size[desc_id] = desc_len;
3260 * ufshcd_read_desc_param - read the specified descriptor parameter
3261 * @hba: Pointer to adapter instance
3262 * @desc_id: descriptor idn value
3263 * @desc_index: descriptor index
3264 * @param_offset: offset of the parameter to read
3265 * @param_read_buf: pointer to buffer where parameter would be read
3266 * @param_size: sizeof(param_read_buf)
3268 * Return 0 in case of success, non-zero otherwise
3270 int ufshcd_read_desc_param(struct ufs_hba *hba,
3271 enum desc_idn desc_id,
3280 bool is_kmalloc = true;
3283 if (desc_id >= QUERY_DESC_IDN_MAX || !param_size)
3286 /* Get the length of descriptor */
3287 ufshcd_map_desc_id_to_length(hba, desc_id, &buff_len);
3289 dev_err(hba->dev, "%s: Failed to get desc length\n", __func__);
3293 if (param_offset >= buff_len) {
3294 dev_err(hba->dev, "%s: Invalid offset 0x%x in descriptor IDN 0x%x, length 0x%x\n",
3295 __func__, param_offset, desc_id, buff_len);
3299 /* Check whether we need temp memory */
3300 if (param_offset != 0 || param_size < buff_len) {
3301 desc_buf = kzalloc(buff_len, GFP_KERNEL);
3305 desc_buf = param_read_buf;
3309 /* Request for full descriptor */
3310 ret = ufshcd_query_descriptor_retry(hba, UPIU_QUERY_OPCODE_READ_DESC,
3311 desc_id, desc_index, 0,
3312 desc_buf, &buff_len);
3315 dev_err(hba->dev, "%s: Failed reading descriptor. desc_id %d, desc_index %d, param_offset %d, ret %d\n",
3316 __func__, desc_id, desc_index, param_offset, ret);
3321 if (desc_buf[QUERY_DESC_DESC_TYPE_OFFSET] != desc_id) {
3322 dev_err(hba->dev, "%s: invalid desc_id %d in descriptor header\n",
3323 __func__, desc_buf[QUERY_DESC_DESC_TYPE_OFFSET]);
3328 /* Update descriptor length */
3329 buff_len = desc_buf[QUERY_DESC_LENGTH_OFFSET];
3330 ufshcd_update_desc_length(hba, desc_id, desc_index, buff_len);
3333 /* Make sure we don't copy more data than available */
3334 if (param_offset + param_size > buff_len)
3335 param_size = buff_len - param_offset;
3336 memcpy(param_read_buf, &desc_buf[param_offset], param_size);
3345 * struct uc_string_id - unicode string
3347 * @len: size of this descriptor inclusive
3348 * @type: descriptor type
3349 * @uc: unicode string character
3351 struct uc_string_id {
3357 /* replace non-printable or non-ASCII characters with spaces */
3358 static inline char ufshcd_remove_non_printable(u8 ch)
3360 return (ch >= 0x20 && ch <= 0x7e) ? ch : ' ';
3364 * ufshcd_read_string_desc - read string descriptor
3365 * @hba: pointer to adapter instance
3366 * @desc_index: descriptor index
3367 * @buf: pointer to buffer where descriptor would be read,
3368 * the caller should free the memory.
3369 * @ascii: if true convert from unicode to ascii characters
3370 * null terminated string.
3373 * * string size on success.
3374 * * -ENOMEM: on allocation failure
3375 * * -EINVAL: on a wrong parameter
3377 int ufshcd_read_string_desc(struct ufs_hba *hba, u8 desc_index,
3378 u8 **buf, bool ascii)
3380 struct uc_string_id *uc_str;
3387 uc_str = kzalloc(QUERY_DESC_MAX_SIZE, GFP_KERNEL);
3391 ret = ufshcd_read_desc_param(hba, QUERY_DESC_IDN_STRING, desc_index, 0,
3392 (u8 *)uc_str, QUERY_DESC_MAX_SIZE);
3394 dev_err(hba->dev, "Reading String Desc failed after %d retries. err = %d\n",
3395 QUERY_REQ_RETRIES, ret);
3400 if (uc_str->len <= QUERY_DESC_HDR_SIZE) {
3401 dev_dbg(hba->dev, "String Desc is of zero length\n");
3410 /* remove header and divide by 2 to move from UTF16 to UTF8 */
3411 ascii_len = (uc_str->len - QUERY_DESC_HDR_SIZE) / 2 + 1;
3412 str = kzalloc(ascii_len, GFP_KERNEL);
3419 * the descriptor contains string in UTF16 format
3420 * we need to convert to utf-8 so it can be displayed
3422 ret = utf16s_to_utf8s(uc_str->uc,
3423 uc_str->len - QUERY_DESC_HDR_SIZE,
3424 UTF16_BIG_ENDIAN, str, ascii_len);
3426 /* replace non-printable or non-ASCII characters with spaces */
3427 for (i = 0; i < ret; i++)
3428 str[i] = ufshcd_remove_non_printable(str[i]);
3433 str = kmemdup(uc_str, uc_str->len, GFP_KERNEL);
3447 * ufshcd_read_unit_desc_param - read the specified unit descriptor parameter
3448 * @hba: Pointer to adapter instance
3450 * @param_offset: offset of the parameter to read
3451 * @param_read_buf: pointer to buffer where parameter would be read
3452 * @param_size: sizeof(param_read_buf)
3454 * Return 0 in case of success, non-zero otherwise
3456 static inline int ufshcd_read_unit_desc_param(struct ufs_hba *hba,
3458 enum unit_desc_param param_offset,
3463 * Unit descriptors are only available for general purpose LUs (LUN id
3464 * from 0 to 7) and RPMB Well known LU.
3466 if (!ufs_is_valid_unit_desc_lun(&hba->dev_info, lun, param_offset))
3469 return ufshcd_read_desc_param(hba, QUERY_DESC_IDN_UNIT, lun,
3470 param_offset, param_read_buf, param_size);
3473 static int ufshcd_get_ref_clk_gating_wait(struct ufs_hba *hba)
3476 u32 gating_wait = UFSHCD_REF_CLK_GATING_WAIT_US;
3478 if (hba->dev_info.wspecversion >= 0x300) {
3479 err = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
3480 QUERY_ATTR_IDN_REF_CLK_GATING_WAIT_TIME, 0, 0,
3483 dev_err(hba->dev, "Failed reading bRefClkGatingWait. err = %d, use default %uus\n",
3486 if (gating_wait == 0) {
3487 gating_wait = UFSHCD_REF_CLK_GATING_WAIT_US;
3488 dev_err(hba->dev, "Undefined ref clk gating wait time, use default %uus\n",
3492 hba->dev_info.clk_gating_wait_us = gating_wait;
3499 * ufshcd_memory_alloc - allocate memory for host memory space data structures
3500 * @hba: per adapter instance
3502 * 1. Allocate DMA memory for Command Descriptor array
3503 * Each command descriptor consist of Command UPIU, Response UPIU and PRDT
3504 * 2. Allocate DMA memory for UTP Transfer Request Descriptor List (UTRDL).
3505 * 3. Allocate DMA memory for UTP Task Management Request Descriptor List
3507 * 4. Allocate memory for local reference block(lrb).
3509 * Returns 0 for success, non-zero in case of failure
3511 static int ufshcd_memory_alloc(struct ufs_hba *hba)
3513 size_t utmrdl_size, utrdl_size, ucdl_size;
3515 /* Allocate memory for UTP command descriptors */
3516 ucdl_size = (sizeof(struct utp_transfer_cmd_desc) * hba->nutrs);
3517 hba->ucdl_base_addr = dmam_alloc_coherent(hba->dev,
3519 &hba->ucdl_dma_addr,
3523 * UFSHCI requires UTP command descriptor to be 128 byte aligned.
3524 * make sure hba->ucdl_dma_addr is aligned to PAGE_SIZE
3525 * if hba->ucdl_dma_addr is aligned to PAGE_SIZE, then it will
3526 * be aligned to 128 bytes as well
3528 if (!hba->ucdl_base_addr ||
3529 WARN_ON(hba->ucdl_dma_addr & (PAGE_SIZE - 1))) {
3531 "Command Descriptor Memory allocation failed\n");
3536 * Allocate memory for UTP Transfer descriptors
3537 * UFSHCI requires 1024 byte alignment of UTRD
3539 utrdl_size = (sizeof(struct utp_transfer_req_desc) * hba->nutrs);
3540 hba->utrdl_base_addr = dmam_alloc_coherent(hba->dev,
3542 &hba->utrdl_dma_addr,
3544 if (!hba->utrdl_base_addr ||
3545 WARN_ON(hba->utrdl_dma_addr & (PAGE_SIZE - 1))) {
3547 "Transfer Descriptor Memory allocation failed\n");
3552 * Allocate memory for UTP Task Management descriptors
3553 * UFSHCI requires 1024 byte alignment of UTMRD
3555 utmrdl_size = sizeof(struct utp_task_req_desc) * hba->nutmrs;
3556 hba->utmrdl_base_addr = dmam_alloc_coherent(hba->dev,
3558 &hba->utmrdl_dma_addr,
3560 if (!hba->utmrdl_base_addr ||
3561 WARN_ON(hba->utmrdl_dma_addr & (PAGE_SIZE - 1))) {
3563 "Task Management Descriptor Memory allocation failed\n");
3567 /* Allocate memory for local reference block */
3568 hba->lrb = devm_kcalloc(hba->dev,
3569 hba->nutrs, sizeof(struct ufshcd_lrb),
3572 dev_err(hba->dev, "LRB Memory allocation failed\n");
3581 * ufshcd_host_memory_configure - configure local reference block with
3583 * @hba: per adapter instance
3585 * Configure Host memory space
3586 * 1. Update Corresponding UTRD.UCDBA and UTRD.UCDBAU with UCD DMA
3588 * 2. Update each UTRD with Response UPIU offset, Response UPIU length
3590 * 3. Save the corresponding addresses of UTRD, UCD.CMD, UCD.RSP and UCD.PRDT
3591 * into local reference block.
3593 static void ufshcd_host_memory_configure(struct ufs_hba *hba)
3595 struct utp_transfer_req_desc *utrdlp;
3596 dma_addr_t cmd_desc_dma_addr;
3597 dma_addr_t cmd_desc_element_addr;
3598 u16 response_offset;
3603 utrdlp = hba->utrdl_base_addr;
3606 offsetof(struct utp_transfer_cmd_desc, response_upiu);
3608 offsetof(struct utp_transfer_cmd_desc, prd_table);
3610 cmd_desc_size = sizeof(struct utp_transfer_cmd_desc);
3611 cmd_desc_dma_addr = hba->ucdl_dma_addr;
3613 for (i = 0; i < hba->nutrs; i++) {
3614 /* Configure UTRD with command descriptor base address */
3615 cmd_desc_element_addr =
3616 (cmd_desc_dma_addr + (cmd_desc_size * i));
3617 utrdlp[i].command_desc_base_addr_lo =
3618 cpu_to_le32(lower_32_bits(cmd_desc_element_addr));
3619 utrdlp[i].command_desc_base_addr_hi =
3620 cpu_to_le32(upper_32_bits(cmd_desc_element_addr));
3622 /* Response upiu and prdt offset should be in double words */
3623 if (hba->quirks & UFSHCD_QUIRK_PRDT_BYTE_GRAN) {
3624 utrdlp[i].response_upiu_offset =
3625 cpu_to_le16(response_offset);
3626 utrdlp[i].prd_table_offset =
3627 cpu_to_le16(prdt_offset);
3628 utrdlp[i].response_upiu_length =
3629 cpu_to_le16(ALIGNED_UPIU_SIZE);
3631 utrdlp[i].response_upiu_offset =
3632 cpu_to_le16(response_offset >> 2);
3633 utrdlp[i].prd_table_offset =
3634 cpu_to_le16(prdt_offset >> 2);
3635 utrdlp[i].response_upiu_length =
3636 cpu_to_le16(ALIGNED_UPIU_SIZE >> 2);
3639 ufshcd_init_lrb(hba, &hba->lrb[i], i);
3644 * ufshcd_dme_link_startup - Notify Unipro to perform link startup
3645 * @hba: per adapter instance
3647 * UIC_CMD_DME_LINK_STARTUP command must be issued to Unipro layer,
3648 * in order to initialize the Unipro link startup procedure.
3649 * Once the Unipro links are up, the device connected to the controller
3652 * Returns 0 on success, non-zero value on failure
3654 static int ufshcd_dme_link_startup(struct ufs_hba *hba)
3656 struct uic_command uic_cmd = {0};
3659 uic_cmd.command = UIC_CMD_DME_LINK_STARTUP;
3661 ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
3664 "dme-link-startup: error code %d\n", ret);
3668 * ufshcd_dme_reset - UIC command for DME_RESET
3669 * @hba: per adapter instance
3671 * DME_RESET command is issued in order to reset UniPro stack.
3672 * This function now deals with cold reset.
3674 * Returns 0 on success, non-zero value on failure
3676 static int ufshcd_dme_reset(struct ufs_hba *hba)
3678 struct uic_command uic_cmd = {0};
3681 uic_cmd.command = UIC_CMD_DME_RESET;
3683 ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
3686 "dme-reset: error code %d\n", ret);
3691 int ufshcd_dme_configure_adapt(struct ufs_hba *hba,
3697 if (agreed_gear != UFS_HS_G4)
3698 adapt_val = PA_NO_ADAPT;
3700 ret = ufshcd_dme_set(hba,
3701 UIC_ARG_MIB(PA_TXHSADAPTTYPE),
3705 EXPORT_SYMBOL_GPL(ufshcd_dme_configure_adapt);
3708 * ufshcd_dme_enable - UIC command for DME_ENABLE
3709 * @hba: per adapter instance
3711 * DME_ENABLE command is issued in order to enable UniPro stack.
3713 * Returns 0 on success, non-zero value on failure
3715 static int ufshcd_dme_enable(struct ufs_hba *hba)
3717 struct uic_command uic_cmd = {0};
3720 uic_cmd.command = UIC_CMD_DME_ENABLE;
3722 ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
3725 "dme-enable: error code %d\n", ret);
3730 static inline void ufshcd_add_delay_before_dme_cmd(struct ufs_hba *hba)
3732 #define MIN_DELAY_BEFORE_DME_CMDS_US 1000
3733 unsigned long min_sleep_time_us;
3735 if (!(hba->quirks & UFSHCD_QUIRK_DELAY_BEFORE_DME_CMDS))
3739 * last_dme_cmd_tstamp will be 0 only for 1st call to
3742 if (unlikely(!ktime_to_us(hba->last_dme_cmd_tstamp))) {
3743 min_sleep_time_us = MIN_DELAY_BEFORE_DME_CMDS_US;
3745 unsigned long delta =
3746 (unsigned long) ktime_to_us(
3747 ktime_sub(ktime_get(),
3748 hba->last_dme_cmd_tstamp));
3750 if (delta < MIN_DELAY_BEFORE_DME_CMDS_US)
3752 MIN_DELAY_BEFORE_DME_CMDS_US - delta;
3754 return; /* no more delay required */
3757 /* allow sleep for extra 50us if needed */
3758 usleep_range(min_sleep_time_us, min_sleep_time_us + 50);
3762 * ufshcd_dme_set_attr - UIC command for DME_SET, DME_PEER_SET
3763 * @hba: per adapter instance
3764 * @attr_sel: uic command argument1
3765 * @attr_set: attribute set type as uic command argument2
3766 * @mib_val: setting value as uic command argument3
3767 * @peer: indicate whether peer or local
3769 * Returns 0 on success, non-zero value on failure
3771 int ufshcd_dme_set_attr(struct ufs_hba *hba, u32 attr_sel,
3772 u8 attr_set, u32 mib_val, u8 peer)
3774 struct uic_command uic_cmd = {0};
3775 static const char *const action[] = {
3779 const char *set = action[!!peer];
3781 int retries = UFS_UIC_COMMAND_RETRIES;
3783 uic_cmd.command = peer ?
3784 UIC_CMD_DME_PEER_SET : UIC_CMD_DME_SET;
3785 uic_cmd.argument1 = attr_sel;
3786 uic_cmd.argument2 = UIC_ARG_ATTR_TYPE(attr_set);
3787 uic_cmd.argument3 = mib_val;
3790 /* for peer attributes we retry upon failure */
3791 ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
3793 dev_dbg(hba->dev, "%s: attr-id 0x%x val 0x%x error code %d\n",
3794 set, UIC_GET_ATTR_ID(attr_sel), mib_val, ret);
3795 } while (ret && peer && --retries);
3798 dev_err(hba->dev, "%s: attr-id 0x%x val 0x%x failed %d retries\n",
3799 set, UIC_GET_ATTR_ID(attr_sel), mib_val,
3800 UFS_UIC_COMMAND_RETRIES - retries);
3804 EXPORT_SYMBOL_GPL(ufshcd_dme_set_attr);
3807 * ufshcd_dme_get_attr - UIC command for DME_GET, DME_PEER_GET
3808 * @hba: per adapter instance
3809 * @attr_sel: uic command argument1
3810 * @mib_val: the value of the attribute as returned by the UIC command
3811 * @peer: indicate whether peer or local
3813 * Returns 0 on success, non-zero value on failure
3815 int ufshcd_dme_get_attr(struct ufs_hba *hba, u32 attr_sel,
3816 u32 *mib_val, u8 peer)
3818 struct uic_command uic_cmd = {0};
3819 static const char *const action[] = {
3823 const char *get = action[!!peer];
3825 int retries = UFS_UIC_COMMAND_RETRIES;
3826 struct ufs_pa_layer_attr orig_pwr_info;
3827 struct ufs_pa_layer_attr temp_pwr_info;
3828 bool pwr_mode_change = false;
3830 if (peer && (hba->quirks & UFSHCD_QUIRK_DME_PEER_ACCESS_AUTO_MODE)) {
3831 orig_pwr_info = hba->pwr_info;
3832 temp_pwr_info = orig_pwr_info;
3834 if (orig_pwr_info.pwr_tx == FAST_MODE ||
3835 orig_pwr_info.pwr_rx == FAST_MODE) {
3836 temp_pwr_info.pwr_tx = FASTAUTO_MODE;
3837 temp_pwr_info.pwr_rx = FASTAUTO_MODE;
3838 pwr_mode_change = true;
3839 } else if (orig_pwr_info.pwr_tx == SLOW_MODE ||
3840 orig_pwr_info.pwr_rx == SLOW_MODE) {
3841 temp_pwr_info.pwr_tx = SLOWAUTO_MODE;
3842 temp_pwr_info.pwr_rx = SLOWAUTO_MODE;
3843 pwr_mode_change = true;
3845 if (pwr_mode_change) {
3846 ret = ufshcd_change_power_mode(hba, &temp_pwr_info);
3852 uic_cmd.command = peer ?
3853 UIC_CMD_DME_PEER_GET : UIC_CMD_DME_GET;
3854 uic_cmd.argument1 = attr_sel;
3857 /* for peer attributes we retry upon failure */
3858 ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
3860 dev_dbg(hba->dev, "%s: attr-id 0x%x error code %d\n",
3861 get, UIC_GET_ATTR_ID(attr_sel), ret);
3862 } while (ret && peer && --retries);
3865 dev_err(hba->dev, "%s: attr-id 0x%x failed %d retries\n",
3866 get, UIC_GET_ATTR_ID(attr_sel),
3867 UFS_UIC_COMMAND_RETRIES - retries);
3869 if (mib_val && !ret)
3870 *mib_val = uic_cmd.argument3;
3872 if (peer && (hba->quirks & UFSHCD_QUIRK_DME_PEER_ACCESS_AUTO_MODE)
3874 ufshcd_change_power_mode(hba, &orig_pwr_info);
3878 EXPORT_SYMBOL_GPL(ufshcd_dme_get_attr);
3881 * ufshcd_uic_pwr_ctrl - executes UIC commands (which affects the link power
3882 * state) and waits for it to take effect.
3884 * @hba: per adapter instance
3885 * @cmd: UIC command to execute
3887 * DME operations like DME_SET(PA_PWRMODE), DME_HIBERNATE_ENTER &
3888 * DME_HIBERNATE_EXIT commands take some time to take its effect on both host
3889 * and device UniPro link and hence it's final completion would be indicated by
3890 * dedicated status bits in Interrupt Status register (UPMS, UHES, UHXS) in
3891 * addition to normal UIC command completion Status (UCCS). This function only
3892 * returns after the relevant status bits indicate the completion.
3894 * Returns 0 on success, non-zero value on failure
3896 static int ufshcd_uic_pwr_ctrl(struct ufs_hba *hba, struct uic_command *cmd)
3898 struct completion uic_async_done;
3899 unsigned long flags;
3902 bool reenable_intr = false;
3904 mutex_lock(&hba->uic_cmd_mutex);
3905 init_completion(&uic_async_done);
3906 ufshcd_add_delay_before_dme_cmd(hba);
3908 spin_lock_irqsave(hba->host->host_lock, flags);
3909 if (ufshcd_is_link_broken(hba)) {
3913 hba->uic_async_done = &uic_async_done;
3914 if (ufshcd_readl(hba, REG_INTERRUPT_ENABLE) & UIC_COMMAND_COMPL) {
3915 ufshcd_disable_intr(hba, UIC_COMMAND_COMPL);
3917 * Make sure UIC command completion interrupt is disabled before
3918 * issuing UIC command.
3921 reenable_intr = true;
3923 ret = __ufshcd_send_uic_cmd(hba, cmd, false);
3924 spin_unlock_irqrestore(hba->host->host_lock, flags);
3927 "pwr ctrl cmd 0x%x with mode 0x%x uic error %d\n",
3928 cmd->command, cmd->argument3, ret);
3932 if (!wait_for_completion_timeout(hba->uic_async_done,
3933 msecs_to_jiffies(UIC_CMD_TIMEOUT))) {
3935 "pwr ctrl cmd 0x%x with mode 0x%x completion timeout\n",
3936 cmd->command, cmd->argument3);
3938 if (!cmd->cmd_active) {
3939 dev_err(hba->dev, "%s: Power Mode Change operation has been completed, go check UPMCRS\n",
3949 status = ufshcd_get_upmcrs(hba);
3950 if (status != PWR_LOCAL) {
3952 "pwr ctrl cmd 0x%x failed, host upmcrs:0x%x\n",
3953 cmd->command, status);
3954 ret = (status != PWR_OK) ? status : -1;
3958 ufshcd_print_host_state(hba);
3959 ufshcd_print_pwr_info(hba);
3960 ufshcd_print_evt_hist(hba);
3963 spin_lock_irqsave(hba->host->host_lock, flags);
3964 hba->active_uic_cmd = NULL;
3965 hba->uic_async_done = NULL;
3967 ufshcd_enable_intr(hba, UIC_COMMAND_COMPL);
3969 ufshcd_set_link_broken(hba);
3970 ufshcd_schedule_eh_work(hba);
3973 spin_unlock_irqrestore(hba->host->host_lock, flags);
3974 mutex_unlock(&hba->uic_cmd_mutex);
3980 * ufshcd_uic_change_pwr_mode - Perform the UIC power mode chage
3981 * using DME_SET primitives.
3982 * @hba: per adapter instance
3983 * @mode: powr mode value
3985 * Returns 0 on success, non-zero value on failure
3987 static int ufshcd_uic_change_pwr_mode(struct ufs_hba *hba, u8 mode)
3989 struct uic_command uic_cmd = {0};
3992 if (hba->quirks & UFSHCD_QUIRK_BROKEN_PA_RXHSUNTERMCAP) {
3993 ret = ufshcd_dme_set(hba,
3994 UIC_ARG_MIB_SEL(PA_RXHSUNTERMCAP, 0), 1);
3996 dev_err(hba->dev, "%s: failed to enable PA_RXHSUNTERMCAP ret %d\n",
4002 uic_cmd.command = UIC_CMD_DME_SET;
4003 uic_cmd.argument1 = UIC_ARG_MIB(PA_PWRMODE);
4004 uic_cmd.argument3 = mode;
4005 ufshcd_hold(hba, false);
4006 ret = ufshcd_uic_pwr_ctrl(hba, &uic_cmd);
4007 ufshcd_release(hba);
4013 int ufshcd_link_recovery(struct ufs_hba *hba)
4016 unsigned long flags;
4018 spin_lock_irqsave(hba->host->host_lock, flags);
4019 hba->ufshcd_state = UFSHCD_STATE_RESET;
4020 ufshcd_set_eh_in_progress(hba);
4021 spin_unlock_irqrestore(hba->host->host_lock, flags);
4023 /* Reset the attached device */
4024 ufshcd_device_reset(hba);
4026 ret = ufshcd_host_reset_and_restore(hba);
4028 spin_lock_irqsave(hba->host->host_lock, flags);
4030 hba->ufshcd_state = UFSHCD_STATE_ERROR;
4031 ufshcd_clear_eh_in_progress(hba);
4032 spin_unlock_irqrestore(hba->host->host_lock, flags);
4035 dev_err(hba->dev, "%s: link recovery failed, err %d",
4038 ufshcd_clear_ua_wluns(hba);
4042 EXPORT_SYMBOL_GPL(ufshcd_link_recovery);
4044 static int ufshcd_uic_hibern8_enter(struct ufs_hba *hba)
4047 struct uic_command uic_cmd = {0};
4048 ktime_t start = ktime_get();
4050 ufshcd_vops_hibern8_notify(hba, UIC_CMD_DME_HIBER_ENTER, PRE_CHANGE);
4052 uic_cmd.command = UIC_CMD_DME_HIBER_ENTER;
4053 ret = ufshcd_uic_pwr_ctrl(hba, &uic_cmd);
4054 trace_ufshcd_profile_hibern8(dev_name(hba->dev), "enter",
4055 ktime_to_us(ktime_sub(ktime_get(), start)), ret);
4058 dev_err(hba->dev, "%s: hibern8 enter failed. ret = %d\n",
4061 ufshcd_vops_hibern8_notify(hba, UIC_CMD_DME_HIBER_ENTER,
4067 int ufshcd_uic_hibern8_exit(struct ufs_hba *hba)
4069 struct uic_command uic_cmd = {0};
4071 ktime_t start = ktime_get();
4073 ufshcd_vops_hibern8_notify(hba, UIC_CMD_DME_HIBER_EXIT, PRE_CHANGE);
4075 uic_cmd.command = UIC_CMD_DME_HIBER_EXIT;
4076 ret = ufshcd_uic_pwr_ctrl(hba, &uic_cmd);
4077 trace_ufshcd_profile_hibern8(dev_name(hba->dev), "exit",
4078 ktime_to_us(ktime_sub(ktime_get(), start)), ret);
4081 dev_err(hba->dev, "%s: hibern8 exit failed. ret = %d\n",
4084 ufshcd_vops_hibern8_notify(hba, UIC_CMD_DME_HIBER_EXIT,
4086 hba->ufs_stats.last_hibern8_exit_tstamp = ktime_get();
4087 hba->ufs_stats.hibern8_exit_cnt++;
4092 EXPORT_SYMBOL_GPL(ufshcd_uic_hibern8_exit);
4094 void ufshcd_auto_hibern8_update(struct ufs_hba *hba, u32 ahit)
4096 unsigned long flags;
4097 bool update = false;
4099 if (!ufshcd_is_auto_hibern8_supported(hba))
4102 spin_lock_irqsave(hba->host->host_lock, flags);
4103 if (hba->ahit != ahit) {
4107 spin_unlock_irqrestore(hba->host->host_lock, flags);
4109 if (update && !pm_runtime_suspended(hba->dev)) {
4110 pm_runtime_get_sync(hba->dev);
4111 ufshcd_hold(hba, false);
4112 ufshcd_auto_hibern8_enable(hba);
4113 ufshcd_release(hba);
4114 pm_runtime_put(hba->dev);
4117 EXPORT_SYMBOL_GPL(ufshcd_auto_hibern8_update);
4119 void ufshcd_auto_hibern8_enable(struct ufs_hba *hba)
4121 unsigned long flags;
4123 if (!ufshcd_is_auto_hibern8_supported(hba))
4126 spin_lock_irqsave(hba->host->host_lock, flags);
4127 ufshcd_writel(hba, hba->ahit, REG_AUTO_HIBERNATE_IDLE_TIMER);
4128 spin_unlock_irqrestore(hba->host->host_lock, flags);
4132 * ufshcd_init_pwr_info - setting the POR (power on reset)
4133 * values in hba power info
4134 * @hba: per-adapter instance
4136 static void ufshcd_init_pwr_info(struct ufs_hba *hba)
4138 hba->pwr_info.gear_rx = UFS_PWM_G1;
4139 hba->pwr_info.gear_tx = UFS_PWM_G1;
4140 hba->pwr_info.lane_rx = 1;
4141 hba->pwr_info.lane_tx = 1;
4142 hba->pwr_info.pwr_rx = SLOWAUTO_MODE;
4143 hba->pwr_info.pwr_tx = SLOWAUTO_MODE;
4144 hba->pwr_info.hs_rate = 0;
4148 * ufshcd_get_max_pwr_mode - reads the max power mode negotiated with device
4149 * @hba: per-adapter instance
4151 static int ufshcd_get_max_pwr_mode(struct ufs_hba *hba)
4153 struct ufs_pa_layer_attr *pwr_info = &hba->max_pwr_info.info;
4155 if (hba->max_pwr_info.is_valid)
4158 pwr_info->pwr_tx = FAST_MODE;
4159 pwr_info->pwr_rx = FAST_MODE;
4160 pwr_info->hs_rate = PA_HS_MODE_B;
4162 /* Get the connected lane count */
4163 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_CONNECTEDRXDATALANES),
4164 &pwr_info->lane_rx);
4165 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_CONNECTEDTXDATALANES),
4166 &pwr_info->lane_tx);
4168 if (!pwr_info->lane_rx || !pwr_info->lane_tx) {
4169 dev_err(hba->dev, "%s: invalid connected lanes value. rx=%d, tx=%d\n",
4177 * First, get the maximum gears of HS speed.
4178 * If a zero value, it means there is no HSGEAR capability.
4179 * Then, get the maximum gears of PWM speed.
4181 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_MAXRXHSGEAR), &pwr_info->gear_rx);
4182 if (!pwr_info->gear_rx) {
4183 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_MAXRXPWMGEAR),
4184 &pwr_info->gear_rx);
4185 if (!pwr_info->gear_rx) {
4186 dev_err(hba->dev, "%s: invalid max pwm rx gear read = %d\n",
4187 __func__, pwr_info->gear_rx);
4190 pwr_info->pwr_rx = SLOW_MODE;
4193 ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_MAXRXHSGEAR),
4194 &pwr_info->gear_tx);
4195 if (!pwr_info->gear_tx) {
4196 ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_MAXRXPWMGEAR),
4197 &pwr_info->gear_tx);
4198 if (!pwr_info->gear_tx) {
4199 dev_err(hba->dev, "%s: invalid max pwm tx gear read = %d\n",
4200 __func__, pwr_info->gear_tx);
4203 pwr_info->pwr_tx = SLOW_MODE;
4206 hba->max_pwr_info.is_valid = true;
4210 static int ufshcd_change_power_mode(struct ufs_hba *hba,
4211 struct ufs_pa_layer_attr *pwr_mode)
4215 /* if already configured to the requested pwr_mode */
4216 if (!hba->force_pmc &&
4217 pwr_mode->gear_rx == hba->pwr_info.gear_rx &&
4218 pwr_mode->gear_tx == hba->pwr_info.gear_tx &&
4219 pwr_mode->lane_rx == hba->pwr_info.lane_rx &&
4220 pwr_mode->lane_tx == hba->pwr_info.lane_tx &&
4221 pwr_mode->pwr_rx == hba->pwr_info.pwr_rx &&
4222 pwr_mode->pwr_tx == hba->pwr_info.pwr_tx &&
4223 pwr_mode->hs_rate == hba->pwr_info.hs_rate) {
4224 dev_dbg(hba->dev, "%s: power already configured\n", __func__);
4229 * Configure attributes for power mode change with below.
4230 * - PA_RXGEAR, PA_ACTIVERXDATALANES, PA_RXTERMINATION,
4231 * - PA_TXGEAR, PA_ACTIVETXDATALANES, PA_TXTERMINATION,
4234 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_RXGEAR), pwr_mode->gear_rx);
4235 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_ACTIVERXDATALANES),
4237 if (pwr_mode->pwr_rx == FASTAUTO_MODE ||
4238 pwr_mode->pwr_rx == FAST_MODE)
4239 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_RXTERMINATION), TRUE);
4241 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_RXTERMINATION), FALSE);
4243 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TXGEAR), pwr_mode->gear_tx);
4244 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_ACTIVETXDATALANES),
4246 if (pwr_mode->pwr_tx == FASTAUTO_MODE ||
4247 pwr_mode->pwr_tx == FAST_MODE)
4248 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TXTERMINATION), TRUE);
4250 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TXTERMINATION), FALSE);
4252 if (pwr_mode->pwr_rx == FASTAUTO_MODE ||
4253 pwr_mode->pwr_tx == FASTAUTO_MODE ||
4254 pwr_mode->pwr_rx == FAST_MODE ||
4255 pwr_mode->pwr_tx == FAST_MODE)
4256 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_HSSERIES),
4259 if (!(hba->quirks & UFSHCD_QUIRK_SKIP_DEF_UNIPRO_TIMEOUT_SETTING)) {
4260 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_PWRMODEUSERDATA0),
4261 DL_FC0ProtectionTimeOutVal_Default);
4262 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_PWRMODEUSERDATA1),
4263 DL_TC0ReplayTimeOutVal_Default);
4264 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_PWRMODEUSERDATA2),
4265 DL_AFC0ReqTimeOutVal_Default);
4266 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_PWRMODEUSERDATA3),
4267 DL_FC1ProtectionTimeOutVal_Default);
4268 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_PWRMODEUSERDATA4),
4269 DL_TC1ReplayTimeOutVal_Default);
4270 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_PWRMODEUSERDATA5),
4271 DL_AFC1ReqTimeOutVal_Default);
4273 ufshcd_dme_set(hba, UIC_ARG_MIB(DME_LocalFC0ProtectionTimeOutVal),
4274 DL_FC0ProtectionTimeOutVal_Default);
4275 ufshcd_dme_set(hba, UIC_ARG_MIB(DME_LocalTC0ReplayTimeOutVal),
4276 DL_TC0ReplayTimeOutVal_Default);
4277 ufshcd_dme_set(hba, UIC_ARG_MIB(DME_LocalAFC0ReqTimeOutVal),
4278 DL_AFC0ReqTimeOutVal_Default);
4281 ret = ufshcd_uic_change_pwr_mode(hba, pwr_mode->pwr_rx << 4
4282 | pwr_mode->pwr_tx);
4286 "%s: power mode change failed %d\n", __func__, ret);
4288 ufshcd_vops_pwr_change_notify(hba, POST_CHANGE, NULL,
4291 memcpy(&hba->pwr_info, pwr_mode,
4292 sizeof(struct ufs_pa_layer_attr));
4299 * ufshcd_config_pwr_mode - configure a new power mode
4300 * @hba: per-adapter instance
4301 * @desired_pwr_mode: desired power configuration
4303 int ufshcd_config_pwr_mode(struct ufs_hba *hba,
4304 struct ufs_pa_layer_attr *desired_pwr_mode)
4306 struct ufs_pa_layer_attr final_params = { 0 };
4309 ret = ufshcd_vops_pwr_change_notify(hba, PRE_CHANGE,
4310 desired_pwr_mode, &final_params);
4313 memcpy(&final_params, desired_pwr_mode, sizeof(final_params));
4315 ret = ufshcd_change_power_mode(hba, &final_params);
4319 EXPORT_SYMBOL_GPL(ufshcd_config_pwr_mode);
4322 * ufshcd_complete_dev_init() - checks device readiness
4323 * @hba: per-adapter instance
4325 * Set fDeviceInit flag and poll until device toggles it.
4327 static int ufshcd_complete_dev_init(struct ufs_hba *hba)
4330 bool flag_res = true;
4333 err = ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_SET_FLAG,
4334 QUERY_FLAG_IDN_FDEVICEINIT, 0, NULL);
4337 "%s setting fDeviceInit flag failed with error %d\n",
4342 /* Poll fDeviceInit flag to be cleared */
4343 timeout = ktime_add_ms(ktime_get(), FDEVICEINIT_COMPL_TIMEOUT);
4345 err = ufshcd_query_flag(hba, UPIU_QUERY_OPCODE_READ_FLAG,
4346 QUERY_FLAG_IDN_FDEVICEINIT, 0, &flag_res);
4349 usleep_range(5000, 10000);
4350 } while (ktime_before(ktime_get(), timeout));
4354 "%s reading fDeviceInit flag failed with error %d\n",
4356 } else if (flag_res) {
4358 "%s fDeviceInit was not cleared by the device\n",
4367 * ufshcd_make_hba_operational - Make UFS controller operational
4368 * @hba: per adapter instance
4370 * To bring UFS host controller to operational state,
4371 * 1. Enable required interrupts
4372 * 2. Configure interrupt aggregation
4373 * 3. Program UTRL and UTMRL base address
4374 * 4. Configure run-stop-registers
4376 * Returns 0 on success, non-zero value on failure
4378 int ufshcd_make_hba_operational(struct ufs_hba *hba)
4383 /* Enable required interrupts */
4384 ufshcd_enable_intr(hba, UFSHCD_ENABLE_INTRS);
4386 /* Configure interrupt aggregation */
4387 if (ufshcd_is_intr_aggr_allowed(hba))
4388 ufshcd_config_intr_aggr(hba, hba->nutrs - 1, INT_AGGR_DEF_TO);
4390 ufshcd_disable_intr_aggr(hba);
4392 /* Configure UTRL and UTMRL base address registers */
4393 ufshcd_writel(hba, lower_32_bits(hba->utrdl_dma_addr),
4394 REG_UTP_TRANSFER_REQ_LIST_BASE_L);
4395 ufshcd_writel(hba, upper_32_bits(hba->utrdl_dma_addr),
4396 REG_UTP_TRANSFER_REQ_LIST_BASE_H);
4397 ufshcd_writel(hba, lower_32_bits(hba->utmrdl_dma_addr),
4398 REG_UTP_TASK_REQ_LIST_BASE_L);
4399 ufshcd_writel(hba, upper_32_bits(hba->utmrdl_dma_addr),
4400 REG_UTP_TASK_REQ_LIST_BASE_H);
4403 * Make sure base address and interrupt setup are updated before
4404 * enabling the run/stop registers below.
4409 * UCRDY, UTMRLDY and UTRLRDY bits must be 1
4411 reg = ufshcd_readl(hba, REG_CONTROLLER_STATUS);
4412 if (!(ufshcd_get_lists_status(reg))) {
4413 ufshcd_enable_run_stop_reg(hba);
4416 "Host controller not ready to process requests");
4422 EXPORT_SYMBOL_GPL(ufshcd_make_hba_operational);
4425 * ufshcd_hba_stop - Send controller to reset state
4426 * @hba: per adapter instance
4428 static inline void ufshcd_hba_stop(struct ufs_hba *hba)
4430 unsigned long flags;
4434 * Obtain the host lock to prevent that the controller is disabled
4435 * while the UFS interrupt handler is active on another CPU.
4437 spin_lock_irqsave(hba->host->host_lock, flags);
4438 ufshcd_writel(hba, CONTROLLER_DISABLE, REG_CONTROLLER_ENABLE);
4439 spin_unlock_irqrestore(hba->host->host_lock, flags);
4441 err = ufshcd_wait_for_register(hba, REG_CONTROLLER_ENABLE,
4442 CONTROLLER_ENABLE, CONTROLLER_DISABLE,
4445 dev_err(hba->dev, "%s: Controller disable failed\n", __func__);
4449 * ufshcd_hba_execute_hce - initialize the controller
4450 * @hba: per adapter instance
4452 * The controller resets itself and controller firmware initialization
4453 * sequence kicks off. When controller is ready it will set
4454 * the Host Controller Enable bit to 1.
4456 * Returns 0 on success, non-zero value on failure
4458 static int ufshcd_hba_execute_hce(struct ufs_hba *hba)
4460 int retry_outer = 3;
4464 if (!ufshcd_is_hba_active(hba))
4465 /* change controller state to "reset state" */
4466 ufshcd_hba_stop(hba);
4468 /* UniPro link is disabled at this point */
4469 ufshcd_set_link_off(hba);
4471 ufshcd_vops_hce_enable_notify(hba, PRE_CHANGE);
4473 /* start controller initialization sequence */
4474 ufshcd_hba_start(hba);
4477 * To initialize a UFS host controller HCE bit must be set to 1.
4478 * During initialization the HCE bit value changes from 1->0->1.
4479 * When the host controller completes initialization sequence
4480 * it sets the value of HCE bit to 1. The same HCE bit is read back
4481 * to check if the controller has completed initialization sequence.
4482 * So without this delay the value HCE = 1, set in the previous
4483 * instruction might be read back.
4484 * This delay can be changed based on the controller.
4486 ufshcd_delay_us(hba->vps->hba_enable_delay_us, 100);
4488 /* wait for the host controller to complete initialization */
4490 while (ufshcd_is_hba_active(hba)) {
4495 "Controller enable failed\n");
4502 usleep_range(1000, 1100);
4505 /* enable UIC related interrupts */
4506 ufshcd_enable_intr(hba, UFSHCD_UIC_MASK);
4508 ufshcd_vops_hce_enable_notify(hba, POST_CHANGE);
4513 int ufshcd_hba_enable(struct ufs_hba *hba)
4517 if (hba->quirks & UFSHCI_QUIRK_BROKEN_HCE) {
4518 ufshcd_set_link_off(hba);
4519 ufshcd_vops_hce_enable_notify(hba, PRE_CHANGE);
4521 /* enable UIC related interrupts */
4522 ufshcd_enable_intr(hba, UFSHCD_UIC_MASK);
4523 ret = ufshcd_dme_reset(hba);
4525 ret = ufshcd_dme_enable(hba);
4527 ufshcd_vops_hce_enable_notify(hba, POST_CHANGE);
4530 "Host controller enable failed with non-hce\n");
4533 ret = ufshcd_hba_execute_hce(hba);
4538 EXPORT_SYMBOL_GPL(ufshcd_hba_enable);
4540 static int ufshcd_disable_tx_lcc(struct ufs_hba *hba, bool peer)
4542 int tx_lanes = 0, i, err = 0;
4545 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_CONNECTEDTXDATALANES),
4548 ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_CONNECTEDTXDATALANES),
4550 for (i = 0; i < tx_lanes; i++) {
4552 err = ufshcd_dme_set(hba,
4553 UIC_ARG_MIB_SEL(TX_LCC_ENABLE,
4554 UIC_ARG_MPHY_TX_GEN_SEL_INDEX(i)),
4557 err = ufshcd_dme_peer_set(hba,
4558 UIC_ARG_MIB_SEL(TX_LCC_ENABLE,
4559 UIC_ARG_MPHY_TX_GEN_SEL_INDEX(i)),
4562 dev_err(hba->dev, "%s: TX LCC Disable failed, peer = %d, lane = %d, err = %d",
4563 __func__, peer, i, err);
4571 static inline int ufshcd_disable_device_tx_lcc(struct ufs_hba *hba)
4573 return ufshcd_disable_tx_lcc(hba, true);
4576 void ufshcd_update_evt_hist(struct ufs_hba *hba, u32 id, u32 val)
4578 struct ufs_event_hist *e;
4580 if (id >= UFS_EVT_CNT)
4583 e = &hba->ufs_stats.event[id];
4584 e->val[e->pos] = val;
4585 e->tstamp[e->pos] = ktime_get();
4587 e->pos = (e->pos + 1) % UFS_EVENT_HIST_LENGTH;
4589 ufshcd_vops_event_notify(hba, id, &val);
4591 EXPORT_SYMBOL_GPL(ufshcd_update_evt_hist);
4594 * ufshcd_link_startup - Initialize unipro link startup
4595 * @hba: per adapter instance
4597 * Returns 0 for success, non-zero in case of failure
4599 static int ufshcd_link_startup(struct ufs_hba *hba)
4602 int retries = DME_LINKSTARTUP_RETRIES;
4603 bool link_startup_again = false;
4606 * If UFS device isn't active then we will have to issue link startup
4607 * 2 times to make sure the device state move to active.
4609 if (!ufshcd_is_ufs_dev_active(hba))
4610 link_startup_again = true;
4614 ufshcd_vops_link_startup_notify(hba, PRE_CHANGE);
4616 ret = ufshcd_dme_link_startup(hba);
4618 /* check if device is detected by inter-connect layer */
4619 if (!ret && !ufshcd_is_device_present(hba)) {
4620 ufshcd_update_evt_hist(hba,
4621 UFS_EVT_LINK_STARTUP_FAIL,
4623 dev_err(hba->dev, "%s: Device not present\n", __func__);
4629 * DME link lost indication is only received when link is up,
4630 * but we can't be sure if the link is up until link startup
4631 * succeeds. So reset the local Uni-Pro and try again.
4633 if (ret && ufshcd_hba_enable(hba)) {
4634 ufshcd_update_evt_hist(hba,
4635 UFS_EVT_LINK_STARTUP_FAIL,
4639 } while (ret && retries--);
4642 /* failed to get the link up... retire */
4643 ufshcd_update_evt_hist(hba,
4644 UFS_EVT_LINK_STARTUP_FAIL,
4649 if (link_startup_again) {
4650 link_startup_again = false;
4651 retries = DME_LINKSTARTUP_RETRIES;
4655 /* Mark that link is up in PWM-G1, 1-lane, SLOW-AUTO mode */
4656 ufshcd_init_pwr_info(hba);
4657 ufshcd_print_pwr_info(hba);
4659 if (hba->quirks & UFSHCD_QUIRK_BROKEN_LCC) {
4660 ret = ufshcd_disable_device_tx_lcc(hba);
4665 /* Include any host controller configuration via UIC commands */
4666 ret = ufshcd_vops_link_startup_notify(hba, POST_CHANGE);
4670 /* Clear UECPA once due to LINERESET has happened during LINK_STARTUP */
4671 ufshcd_readl(hba, REG_UIC_ERROR_CODE_PHY_ADAPTER_LAYER);
4672 ret = ufshcd_make_hba_operational(hba);
4675 dev_err(hba->dev, "link startup failed %d\n", ret);
4676 ufshcd_print_host_state(hba);
4677 ufshcd_print_pwr_info(hba);
4678 ufshcd_print_evt_hist(hba);
4684 * ufshcd_verify_dev_init() - Verify device initialization
4685 * @hba: per-adapter instance
4687 * Send NOP OUT UPIU and wait for NOP IN response to check whether the
4688 * device Transport Protocol (UTP) layer is ready after a reset.
4689 * If the UTP layer at the device side is not initialized, it may
4690 * not respond with NOP IN UPIU within timeout of %NOP_OUT_TIMEOUT
4691 * and we retry sending NOP OUT for %NOP_OUT_RETRIES iterations.
4693 static int ufshcd_verify_dev_init(struct ufs_hba *hba)
4698 ufshcd_hold(hba, false);
4699 mutex_lock(&hba->dev_cmd.lock);
4700 for (retries = NOP_OUT_RETRIES; retries > 0; retries--) {
4701 err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_NOP,
4704 if (!err || err == -ETIMEDOUT)
4707 dev_dbg(hba->dev, "%s: error %d retrying\n", __func__, err);
4709 mutex_unlock(&hba->dev_cmd.lock);
4710 ufshcd_release(hba);
4713 dev_err(hba->dev, "%s: NOP OUT failed %d\n", __func__, err);
4718 * ufshcd_set_queue_depth - set lun queue depth
4719 * @sdev: pointer to SCSI device
4721 * Read bLUQueueDepth value and activate scsi tagged command
4722 * queueing. For WLUN, queue depth is set to 1. For best-effort
4723 * cases (bLUQueueDepth = 0) the queue depth is set to a maximum
4724 * value that host can queue.
4726 static void ufshcd_set_queue_depth(struct scsi_device *sdev)
4730 struct ufs_hba *hba;
4732 hba = shost_priv(sdev->host);
4734 lun_qdepth = hba->nutrs;
4735 ret = ufshcd_read_unit_desc_param(hba,
4736 ufshcd_scsi_to_upiu_lun(sdev->lun),
4737 UNIT_DESC_PARAM_LU_Q_DEPTH,
4739 sizeof(lun_qdepth));
4741 /* Some WLUN doesn't support unit descriptor */
4742 if (ret == -EOPNOTSUPP)
4744 else if (!lun_qdepth)
4745 /* eventually, we can figure out the real queue depth */
4746 lun_qdepth = hba->nutrs;
4748 lun_qdepth = min_t(int, lun_qdepth, hba->nutrs);
4750 dev_dbg(hba->dev, "%s: activate tcq with queue depth %d\n",
4751 __func__, lun_qdepth);
4752 scsi_change_queue_depth(sdev, lun_qdepth);
4756 * ufshcd_get_lu_wp - returns the "b_lu_write_protect" from UNIT DESCRIPTOR
4757 * @hba: per-adapter instance
4758 * @lun: UFS device lun id
4759 * @b_lu_write_protect: pointer to buffer to hold the LU's write protect info
4761 * Returns 0 in case of success and b_lu_write_protect status would be returned
4762 * @b_lu_write_protect parameter.
4763 * Returns -ENOTSUPP if reading b_lu_write_protect is not supported.
4764 * Returns -EINVAL in case of invalid parameters passed to this function.
4766 static int ufshcd_get_lu_wp(struct ufs_hba *hba,
4768 u8 *b_lu_write_protect)
4772 if (!b_lu_write_protect)
4775 * According to UFS device spec, RPMB LU can't be write
4776 * protected so skip reading bLUWriteProtect parameter for
4777 * it. For other W-LUs, UNIT DESCRIPTOR is not available.
4779 else if (lun >= hba->dev_info.max_lu_supported)
4782 ret = ufshcd_read_unit_desc_param(hba,
4784 UNIT_DESC_PARAM_LU_WR_PROTECT,
4786 sizeof(*b_lu_write_protect));
4791 * ufshcd_get_lu_power_on_wp_status - get LU's power on write protect
4793 * @hba: per-adapter instance
4794 * @sdev: pointer to SCSI device
4797 static inline void ufshcd_get_lu_power_on_wp_status(struct ufs_hba *hba,
4798 struct scsi_device *sdev)
4800 if (hba->dev_info.f_power_on_wp_en &&
4801 !hba->dev_info.is_lu_power_on_wp) {
4802 u8 b_lu_write_protect;
4804 if (!ufshcd_get_lu_wp(hba, ufshcd_scsi_to_upiu_lun(sdev->lun),
4805 &b_lu_write_protect) &&
4806 (b_lu_write_protect == UFS_LU_POWER_ON_WP))
4807 hba->dev_info.is_lu_power_on_wp = true;
4812 * ufshcd_slave_alloc - handle initial SCSI device configurations
4813 * @sdev: pointer to SCSI device
4817 static int ufshcd_slave_alloc(struct scsi_device *sdev)
4819 struct ufs_hba *hba;
4821 hba = shost_priv(sdev->host);
4823 /* Mode sense(6) is not supported by UFS, so use Mode sense(10) */
4824 sdev->use_10_for_ms = 1;
4826 /* DBD field should be set to 1 in mode sense(10) */
4827 sdev->set_dbd_for_ms = 1;
4829 /* allow SCSI layer to restart the device in case of errors */
4830 sdev->allow_restart = 1;
4832 /* REPORT SUPPORTED OPERATION CODES is not supported */
4833 sdev->no_report_opcodes = 1;
4835 /* WRITE_SAME command is not supported */
4836 sdev->no_write_same = 1;
4838 ufshcd_set_queue_depth(sdev);
4840 ufshcd_get_lu_power_on_wp_status(hba, sdev);
4846 * ufshcd_change_queue_depth - change queue depth
4847 * @sdev: pointer to SCSI device
4848 * @depth: required depth to set
4850 * Change queue depth and make sure the max. limits are not crossed.
4852 static int ufshcd_change_queue_depth(struct scsi_device *sdev, int depth)
4854 struct ufs_hba *hba = shost_priv(sdev->host);
4856 if (depth > hba->nutrs)
4858 return scsi_change_queue_depth(sdev, depth);
4862 * ufshcd_slave_configure - adjust SCSI device configurations
4863 * @sdev: pointer to SCSI device
4865 static int ufshcd_slave_configure(struct scsi_device *sdev)
4867 struct ufs_hba *hba = shost_priv(sdev->host);
4868 struct request_queue *q = sdev->request_queue;
4870 blk_queue_update_dma_pad(q, PRDT_DATA_BYTE_COUNT_PAD - 1);
4871 if (hba->quirks & UFSHCD_QUIRK_ALIGN_SG_WITH_PAGE_SIZE)
4872 blk_queue_update_dma_alignment(q, PAGE_SIZE - 1);
4874 if (ufshcd_is_rpm_autosuspend_allowed(hba))
4875 sdev->rpm_autosuspend = 1;
4877 ufshcd_crypto_setup_rq_keyslot_manager(hba, q);
4883 * ufshcd_slave_destroy - remove SCSI device configurations
4884 * @sdev: pointer to SCSI device
4886 static void ufshcd_slave_destroy(struct scsi_device *sdev)
4888 struct ufs_hba *hba;
4890 hba = shost_priv(sdev->host);
4891 /* Drop the reference as it won't be needed anymore */
4892 if (ufshcd_scsi_to_upiu_lun(sdev->lun) == UFS_UPIU_UFS_DEVICE_WLUN) {
4893 unsigned long flags;
4895 spin_lock_irqsave(hba->host->host_lock, flags);
4896 hba->sdev_ufs_device = NULL;
4897 spin_unlock_irqrestore(hba->host->host_lock, flags);
4902 * ufshcd_scsi_cmd_status - Update SCSI command result based on SCSI status
4903 * @lrbp: pointer to local reference block of completed command
4904 * @scsi_status: SCSI command status
4906 * Returns value base on SCSI command status
4909 ufshcd_scsi_cmd_status(struct ufshcd_lrb *lrbp, int scsi_status)
4913 switch (scsi_status) {
4914 case SAM_STAT_CHECK_CONDITION:
4915 ufshcd_copy_sense_data(lrbp);
4918 result |= DID_OK << 16 | scsi_status;
4920 case SAM_STAT_TASK_SET_FULL:
4922 case SAM_STAT_TASK_ABORTED:
4923 ufshcd_copy_sense_data(lrbp);
4924 result |= scsi_status;
4927 result |= DID_ERROR << 16;
4929 } /* end of switch */
4935 * ufshcd_transfer_rsp_status - Get overall status of the response
4936 * @hba: per adapter instance
4937 * @lrbp: pointer to local reference block of completed command
4939 * Returns result of the command to notify SCSI midlayer
4942 ufshcd_transfer_rsp_status(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
4948 /* overall command status of utrd */
4949 ocs = ufshcd_get_tr_ocs(lrbp);
4951 if (hba->quirks & UFSHCD_QUIRK_BROKEN_OCS_FATAL_ERROR) {
4952 if (be32_to_cpu(lrbp->ucd_rsp_ptr->header.dword_1) &
4953 MASK_RSP_UPIU_RESULT)
4959 result = ufshcd_get_req_rsp(lrbp->ucd_rsp_ptr);
4960 hba->ufs_stats.last_hibern8_exit_tstamp = ktime_set(0, 0);
4962 case UPIU_TRANSACTION_RESPONSE:
4964 * get the response UPIU result to extract
4965 * the SCSI command status
4967 result = ufshcd_get_rsp_upiu_result(lrbp->ucd_rsp_ptr);
4970 * get the result based on SCSI status response
4971 * to notify the SCSI midlayer of the command status
4973 scsi_status = result & MASK_SCSI_STATUS;
4974 result = ufshcd_scsi_cmd_status(lrbp, scsi_status);
4977 * Currently we are only supporting BKOPs exception
4978 * events hence we can ignore BKOPs exception event
4979 * during power management callbacks. BKOPs exception
4980 * event is not expected to be raised in runtime suspend
4981 * callback as it allows the urgent bkops.
4982 * During system suspend, we are anyway forcefully
4983 * disabling the bkops and if urgent bkops is needed
4984 * it will be enabled on system resume. Long term
4985 * solution could be to abort the system suspend if
4986 * UFS device needs urgent BKOPs.
4988 if (!hba->pm_op_in_progress &&
4989 ufshcd_is_exception_event(lrbp->ucd_rsp_ptr) &&
4990 schedule_work(&hba->eeh_work)) {
4992 * Prevent suspend once eeh_work is scheduled
4993 * to avoid deadlock between ufshcd_suspend
4994 * and exception event handler.
4996 pm_runtime_get_noresume(hba->dev);
4999 case UPIU_TRANSACTION_REJECT_UPIU:
5000 /* TODO: handle Reject UPIU Response */
5001 result = DID_ERROR << 16;
5003 "Reject UPIU not fully implemented\n");
5007 "Unexpected request response code = %x\n",
5009 result = DID_ERROR << 16;
5014 result |= DID_ABORT << 16;
5016 case OCS_INVALID_COMMAND_STATUS:
5017 result |= DID_REQUEUE << 16;
5019 case OCS_INVALID_CMD_TABLE_ATTR:
5020 case OCS_INVALID_PRDT_ATTR:
5021 case OCS_MISMATCH_DATA_BUF_SIZE:
5022 case OCS_MISMATCH_RESP_UPIU_SIZE:
5023 case OCS_PEER_COMM_FAILURE:
5024 case OCS_FATAL_ERROR:
5025 case OCS_DEVICE_FATAL_ERROR:
5026 case OCS_INVALID_CRYPTO_CONFIG:
5027 case OCS_GENERAL_CRYPTO_ERROR:
5029 result |= DID_ERROR << 16;
5031 "OCS error from controller = %x for tag %d\n",
5032 ocs, lrbp->task_tag);
5033 ufshcd_print_evt_hist(hba);
5034 ufshcd_print_host_state(hba);
5036 } /* end of switch */
5038 if ((host_byte(result) != DID_OK) &&
5039 (host_byte(result) != DID_REQUEUE) && !hba->silence_err_logs)
5040 ufshcd_print_trs(hba, 1 << lrbp->task_tag, true);
5045 * ufshcd_uic_cmd_compl - handle completion of uic command
5046 * @hba: per adapter instance
5047 * @intr_status: interrupt status generated by the controller
5050 * IRQ_HANDLED - If interrupt is valid
5051 * IRQ_NONE - If invalid interrupt
5053 static irqreturn_t ufshcd_uic_cmd_compl(struct ufs_hba *hba, u32 intr_status)
5055 irqreturn_t retval = IRQ_NONE;
5057 if ((intr_status & UIC_COMMAND_COMPL) && hba->active_uic_cmd) {
5058 hba->active_uic_cmd->argument2 |=
5059 ufshcd_get_uic_cmd_result(hba);
5060 hba->active_uic_cmd->argument3 =
5061 ufshcd_get_dme_attr_val(hba);
5062 if (!hba->uic_async_done)
5063 hba->active_uic_cmd->cmd_active = 0;
5064 complete(&hba->active_uic_cmd->done);
5065 retval = IRQ_HANDLED;
5068 if ((intr_status & UFSHCD_UIC_PWR_MASK) && hba->uic_async_done) {
5069 hba->active_uic_cmd->cmd_active = 0;
5070 complete(hba->uic_async_done);
5071 retval = IRQ_HANDLED;
5074 if (retval == IRQ_HANDLED)
5075 ufshcd_add_uic_command_trace(hba, hba->active_uic_cmd,
5081 * __ufshcd_transfer_req_compl - handle SCSI and query command completion
5082 * @hba: per adapter instance
5083 * @completed_reqs: requests to complete
5085 static void __ufshcd_transfer_req_compl(struct ufs_hba *hba,
5086 unsigned long completed_reqs)
5088 struct ufshcd_lrb *lrbp;
5089 struct scsi_cmnd *cmd;
5092 bool update_scaling = false;
5094 for_each_set_bit(index, &completed_reqs, hba->nutrs) {
5095 lrbp = &hba->lrb[index];
5096 lrbp->in_use = false;
5097 lrbp->compl_time_stamp = ktime_get();
5100 ufshcd_add_command_trace(hba, index, UFS_CMD_COMP);
5101 result = ufshcd_transfer_rsp_status(hba, lrbp);
5102 scsi_dma_unmap(cmd);
5103 cmd->result = result;
5104 /* Mark completed command as NULL in LRB */
5106 /* Do not touch lrbp after scsi done */
5107 cmd->scsi_done(cmd);
5108 __ufshcd_release(hba);
5109 update_scaling = true;
5110 } else if (lrbp->command_type == UTP_CMD_TYPE_DEV_MANAGE ||
5111 lrbp->command_type == UTP_CMD_TYPE_UFS_STORAGE) {
5112 if (hba->dev_cmd.complete) {
5113 ufshcd_add_command_trace(hba, index,
5115 complete(hba->dev_cmd.complete);
5116 update_scaling = true;
5119 if (ufshcd_is_clkscaling_supported(hba) && update_scaling)
5120 hba->clk_scaling.active_reqs--;
5123 /* clear corresponding bits of completed commands */
5124 hba->outstanding_reqs ^= completed_reqs;
5126 ufshcd_clk_scaling_update_busy(hba);
5130 * ufshcd_transfer_req_compl - handle SCSI and query command completion
5131 * @hba: per adapter instance
5134 * IRQ_HANDLED - If interrupt is valid
5135 * IRQ_NONE - If invalid interrupt
5137 static irqreturn_t ufshcd_transfer_req_compl(struct ufs_hba *hba)
5139 unsigned long completed_reqs;
5142 /* Resetting interrupt aggregation counters first and reading the
5143 * DOOR_BELL afterward allows us to handle all the completed requests.
5144 * In order to prevent other interrupts starvation the DB is read once
5145 * after reset. The down side of this solution is the possibility of
5146 * false interrupt if device completes another request after resetting
5147 * aggregation and before reading the DB.
5149 if (ufshcd_is_intr_aggr_allowed(hba) &&
5150 !(hba->quirks & UFSHCI_QUIRK_SKIP_RESET_INTR_AGGR))
5151 ufshcd_reset_intr_aggr(hba);
5153 tr_doorbell = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
5154 completed_reqs = tr_doorbell ^ hba->outstanding_reqs;
5156 if (completed_reqs) {
5157 __ufshcd_transfer_req_compl(hba, completed_reqs);
5164 int __ufshcd_write_ee_control(struct ufs_hba *hba, u32 ee_ctrl_mask)
5166 return ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_WRITE_ATTR,
5167 QUERY_ATTR_IDN_EE_CONTROL, 0, 0,
5171 int ufshcd_write_ee_control(struct ufs_hba *hba)
5175 mutex_lock(&hba->ee_ctrl_mutex);
5176 err = __ufshcd_write_ee_control(hba, hba->ee_ctrl_mask);
5177 mutex_unlock(&hba->ee_ctrl_mutex);
5179 dev_err(hba->dev, "%s: failed to write ee control %d\n",
5184 int ufshcd_update_ee_control(struct ufs_hba *hba, u16 *mask, u16 *other_mask,
5187 u16 new_mask, ee_ctrl_mask;
5190 mutex_lock(&hba->ee_ctrl_mutex);
5191 new_mask = (*mask & ~clr) | set;
5192 ee_ctrl_mask = new_mask | *other_mask;
5193 if (ee_ctrl_mask != hba->ee_ctrl_mask)
5194 err = __ufshcd_write_ee_control(hba, ee_ctrl_mask);
5195 /* Still need to update 'mask' even if 'ee_ctrl_mask' was unchanged */
5197 hba->ee_ctrl_mask = ee_ctrl_mask;
5200 mutex_unlock(&hba->ee_ctrl_mutex);
5205 * ufshcd_disable_ee - disable exception event
5206 * @hba: per-adapter instance
5207 * @mask: exception event to disable
5209 * Disables exception event in the device so that the EVENT_ALERT
5212 * Returns zero on success, non-zero error value on failure.
5214 static inline int ufshcd_disable_ee(struct ufs_hba *hba, u16 mask)
5216 return ufshcd_update_ee_drv_mask(hba, 0, mask);
5220 * ufshcd_enable_ee - enable exception event
5221 * @hba: per-adapter instance
5222 * @mask: exception event to enable
5224 * Enable corresponding exception event in the device to allow
5225 * device to alert host in critical scenarios.
5227 * Returns zero on success, non-zero error value on failure.
5229 static inline int ufshcd_enable_ee(struct ufs_hba *hba, u16 mask)
5231 return ufshcd_update_ee_drv_mask(hba, mask, 0);
5235 * ufshcd_enable_auto_bkops - Allow device managed BKOPS
5236 * @hba: per-adapter instance
5238 * Allow device to manage background operations on its own. Enabling
5239 * this might lead to inconsistent latencies during normal data transfers
5240 * as the device is allowed to manage its own way of handling background
5243 * Returns zero on success, non-zero on failure.
5245 static int ufshcd_enable_auto_bkops(struct ufs_hba *hba)
5249 if (hba->auto_bkops_enabled)
5252 err = ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_SET_FLAG,
5253 QUERY_FLAG_IDN_BKOPS_EN, 0, NULL);
5255 dev_err(hba->dev, "%s: failed to enable bkops %d\n",
5260 hba->auto_bkops_enabled = true;
5261 trace_ufshcd_auto_bkops_state(dev_name(hba->dev), "Enabled");
5263 /* No need of URGENT_BKOPS exception from the device */
5264 err = ufshcd_disable_ee(hba, MASK_EE_URGENT_BKOPS);
5266 dev_err(hba->dev, "%s: failed to disable exception event %d\n",
5273 * ufshcd_disable_auto_bkops - block device in doing background operations
5274 * @hba: per-adapter instance
5276 * Disabling background operations improves command response latency but
5277 * has drawback of device moving into critical state where the device is
5278 * not-operable. Make sure to call ufshcd_enable_auto_bkops() whenever the
5279 * host is idle so that BKOPS are managed effectively without any negative
5282 * Returns zero on success, non-zero on failure.
5284 static int ufshcd_disable_auto_bkops(struct ufs_hba *hba)
5288 if (!hba->auto_bkops_enabled)
5292 * If host assisted BKOPs is to be enabled, make sure
5293 * urgent bkops exception is allowed.
5295 err = ufshcd_enable_ee(hba, MASK_EE_URGENT_BKOPS);
5297 dev_err(hba->dev, "%s: failed to enable exception event %d\n",
5302 err = ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_CLEAR_FLAG,
5303 QUERY_FLAG_IDN_BKOPS_EN, 0, NULL);
5305 dev_err(hba->dev, "%s: failed to disable bkops %d\n",
5307 ufshcd_disable_ee(hba, MASK_EE_URGENT_BKOPS);
5311 hba->auto_bkops_enabled = false;
5312 trace_ufshcd_auto_bkops_state(dev_name(hba->dev), "Disabled");
5313 hba->is_urgent_bkops_lvl_checked = false;
5319 * ufshcd_force_reset_auto_bkops - force reset auto bkops state
5320 * @hba: per adapter instance
5322 * After a device reset the device may toggle the BKOPS_EN flag
5323 * to default value. The s/w tracking variables should be updated
5324 * as well. This function would change the auto-bkops state based on
5325 * UFSHCD_CAP_KEEP_AUTO_BKOPS_ENABLED_EXCEPT_SUSPEND.
5327 static void ufshcd_force_reset_auto_bkops(struct ufs_hba *hba)
5329 if (ufshcd_keep_autobkops_enabled_except_suspend(hba)) {
5330 hba->auto_bkops_enabled = false;
5331 hba->ee_ctrl_mask |= MASK_EE_URGENT_BKOPS;
5332 ufshcd_enable_auto_bkops(hba);
5334 hba->auto_bkops_enabled = true;
5335 hba->ee_ctrl_mask &= ~MASK_EE_URGENT_BKOPS;
5336 ufshcd_disable_auto_bkops(hba);
5338 hba->urgent_bkops_lvl = BKOPS_STATUS_PERF_IMPACT;
5339 hba->is_urgent_bkops_lvl_checked = false;
5342 static inline int ufshcd_get_bkops_status(struct ufs_hba *hba, u32 *status)
5344 return ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
5345 QUERY_ATTR_IDN_BKOPS_STATUS, 0, 0, status);
5349 * ufshcd_bkops_ctrl - control the auto bkops based on current bkops status
5350 * @hba: per-adapter instance
5351 * @status: bkops_status value
5353 * Read the bkops_status from the UFS device and Enable fBackgroundOpsEn
5354 * flag in the device to permit background operations if the device
5355 * bkops_status is greater than or equal to "status" argument passed to
5356 * this function, disable otherwise.
5358 * Returns 0 for success, non-zero in case of failure.
5360 * NOTE: Caller of this function can check the "hba->auto_bkops_enabled" flag
5361 * to know whether auto bkops is enabled or disabled after this function
5362 * returns control to it.
5364 static int ufshcd_bkops_ctrl(struct ufs_hba *hba,
5365 enum bkops_status status)
5368 u32 curr_status = 0;
5370 err = ufshcd_get_bkops_status(hba, &curr_status);
5372 dev_err(hba->dev, "%s: failed to get BKOPS status %d\n",
5375 } else if (curr_status > BKOPS_STATUS_MAX) {
5376 dev_err(hba->dev, "%s: invalid BKOPS status %d\n",
5377 __func__, curr_status);
5382 if (curr_status >= status)
5383 err = ufshcd_enable_auto_bkops(hba);
5385 err = ufshcd_disable_auto_bkops(hba);
5391 * ufshcd_urgent_bkops - handle urgent bkops exception event
5392 * @hba: per-adapter instance
5394 * Enable fBackgroundOpsEn flag in the device to permit background
5397 * If BKOPs is enabled, this function returns 0, 1 if the bkops in not enabled
5398 * and negative error value for any other failure.
5400 static int ufshcd_urgent_bkops(struct ufs_hba *hba)
5402 return ufshcd_bkops_ctrl(hba, hba->urgent_bkops_lvl);
5405 static inline int ufshcd_get_ee_status(struct ufs_hba *hba, u32 *status)
5407 return ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
5408 QUERY_ATTR_IDN_EE_STATUS, 0, 0, status);
5411 static void ufshcd_bkops_exception_event_handler(struct ufs_hba *hba)
5414 u32 curr_status = 0;
5416 if (hba->is_urgent_bkops_lvl_checked)
5417 goto enable_auto_bkops;
5419 err = ufshcd_get_bkops_status(hba, &curr_status);
5421 dev_err(hba->dev, "%s: failed to get BKOPS status %d\n",
5427 * We are seeing that some devices are raising the urgent bkops
5428 * exception events even when BKOPS status doesn't indicate performace
5429 * impacted or critical. Handle these device by determining their urgent
5430 * bkops status at runtime.
5432 if (curr_status < BKOPS_STATUS_PERF_IMPACT) {
5433 dev_err(hba->dev, "%s: device raised urgent BKOPS exception for bkops status %d\n",
5434 __func__, curr_status);
5435 /* update the current status as the urgent bkops level */
5436 hba->urgent_bkops_lvl = curr_status;
5437 hba->is_urgent_bkops_lvl_checked = true;
5441 err = ufshcd_enable_auto_bkops(hba);
5444 dev_err(hba->dev, "%s: failed to handle urgent bkops %d\n",
5448 int ufshcd_wb_ctrl(struct ufs_hba *hba, bool enable)
5452 enum query_opcode opcode;
5454 if (!ufshcd_is_wb_allowed(hba))
5457 if (!(enable ^ hba->dev_info.wb_enabled))
5460 opcode = UPIU_QUERY_OPCODE_SET_FLAG;
5462 opcode = UPIU_QUERY_OPCODE_CLEAR_FLAG;
5464 index = ufshcd_wb_get_query_index(hba);
5465 ret = ufshcd_query_flag_retry(hba, opcode,
5466 QUERY_FLAG_IDN_WB_EN, index, NULL);
5468 dev_err(hba->dev, "%s write booster %s failed %d\n",
5469 __func__, enable ? "enable" : "disable", ret);
5473 hba->dev_info.wb_enabled = enable;
5474 dev_dbg(hba->dev, "%s write booster %s %d\n",
5475 __func__, enable ? "enable" : "disable", ret);
5480 static int ufshcd_wb_toggle_flush_during_h8(struct ufs_hba *hba, bool set)
5486 val = UPIU_QUERY_OPCODE_SET_FLAG;
5488 val = UPIU_QUERY_OPCODE_CLEAR_FLAG;
5490 index = ufshcd_wb_get_query_index(hba);
5491 return ufshcd_query_flag_retry(hba, val,
5492 QUERY_FLAG_IDN_WB_BUFF_FLUSH_DURING_HIBERN8,
5496 static inline int ufshcd_wb_toggle_flush(struct ufs_hba *hba, bool enable)
5500 enum query_opcode opcode;
5502 if (!ufshcd_is_wb_allowed(hba) ||
5503 hba->dev_info.wb_buf_flush_enabled == enable)
5507 opcode = UPIU_QUERY_OPCODE_SET_FLAG;
5509 opcode = UPIU_QUERY_OPCODE_CLEAR_FLAG;
5511 index = ufshcd_wb_get_query_index(hba);
5512 ret = ufshcd_query_flag_retry(hba, opcode,
5513 QUERY_FLAG_IDN_WB_BUFF_FLUSH_EN, index,
5516 dev_err(hba->dev, "%s WB-Buf Flush %s failed %d\n", __func__,
5517 enable ? "enable" : "disable", ret);
5521 hba->dev_info.wb_buf_flush_enabled = enable;
5523 dev_dbg(hba->dev, "WB-Buf Flush %s\n", enable ? "enabled" : "disabled");
5529 static bool ufshcd_wb_presrv_usrspc_keep_vcc_on(struct ufs_hba *hba,
5536 index = ufshcd_wb_get_query_index(hba);
5537 ret = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
5538 QUERY_ATTR_IDN_CURR_WB_BUFF_SIZE,
5539 index, 0, &cur_buf);
5541 dev_err(hba->dev, "%s dCurWriteBoosterBufferSize read failed %d\n",
5547 dev_info(hba->dev, "dCurWBBuf: %d WB disabled until free-space is available\n",
5551 /* Let it continue to flush when available buffer exceeds threshold */
5552 if (avail_buf < hba->vps->wb_flush_threshold)
5558 static bool ufshcd_wb_need_flush(struct ufs_hba *hba)
5564 if (!ufshcd_is_wb_allowed(hba))
5567 * The ufs device needs the vcc to be ON to flush.
5568 * With user-space reduction enabled, it's enough to enable flush
5569 * by checking only the available buffer. The threshold
5570 * defined here is > 90% full.
5571 * With user-space preserved enabled, the current-buffer
5572 * should be checked too because the wb buffer size can reduce
5573 * when disk tends to be full. This info is provided by current
5574 * buffer (dCurrentWriteBoosterBufferSize). There's no point in
5575 * keeping vcc on when current buffer is empty.
5577 index = ufshcd_wb_get_query_index(hba);
5578 ret = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
5579 QUERY_ATTR_IDN_AVAIL_WB_BUFF_SIZE,
5580 index, 0, &avail_buf);
5582 dev_warn(hba->dev, "%s dAvailableWriteBoosterBufferSize read failed %d\n",
5587 if (!hba->dev_info.b_presrv_uspc_en) {
5588 if (avail_buf <= UFS_WB_BUF_REMAIN_PERCENT(10))
5593 return ufshcd_wb_presrv_usrspc_keep_vcc_on(hba, avail_buf);
5596 static void ufshcd_rpm_dev_flush_recheck_work(struct work_struct *work)
5598 struct ufs_hba *hba = container_of(to_delayed_work(work),
5600 rpm_dev_flush_recheck_work);
5602 * To prevent unnecessary VCC power drain after device finishes
5603 * WriteBooster buffer flush or Auto BKOPs, force runtime resume
5604 * after a certain delay to recheck the threshold by next runtime
5607 pm_runtime_get_sync(hba->dev);
5608 pm_runtime_put_sync(hba->dev);
5612 * ufshcd_exception_event_handler - handle exceptions raised by device
5613 * @work: pointer to work data
5615 * Read bExceptionEventStatus attribute from the device and handle the
5616 * exception event accordingly.
5618 static void ufshcd_exception_event_handler(struct work_struct *work)
5620 struct ufs_hba *hba;
5623 hba = container_of(work, struct ufs_hba, eeh_work);
5625 pm_runtime_get_sync(hba->dev);
5626 ufshcd_scsi_block_requests(hba);
5627 err = ufshcd_get_ee_status(hba, &status);
5629 dev_err(hba->dev, "%s: failed to get exception status %d\n",
5634 trace_ufshcd_exception_event(dev_name(hba->dev), status);
5636 if (status & hba->ee_drv_mask & MASK_EE_URGENT_BKOPS)
5637 ufshcd_bkops_exception_event_handler(hba);
5639 ufs_debugfs_exception_event(hba, status);
5641 ufshcd_scsi_unblock_requests(hba);
5643 * pm_runtime_get_noresume is called while scheduling
5644 * eeh_work to avoid suspend racing with exception work.
5645 * Hence decrement usage counter using pm_runtime_put_noidle
5646 * to allow suspend on completion of exception event handler.
5648 pm_runtime_put_noidle(hba->dev);
5649 pm_runtime_put(hba->dev);
5653 /* Complete requests that have door-bell cleared */
5654 static void ufshcd_complete_requests(struct ufs_hba *hba)
5656 ufshcd_transfer_req_compl(hba);
5657 ufshcd_tmc_handler(hba);
5661 * ufshcd_quirk_dl_nac_errors - This function checks if error handling is
5662 * to recover from the DL NAC errors or not.
5663 * @hba: per-adapter instance
5665 * Returns true if error handling is required, false otherwise
5667 static bool ufshcd_quirk_dl_nac_errors(struct ufs_hba *hba)
5669 unsigned long flags;
5670 bool err_handling = true;
5672 spin_lock_irqsave(hba->host->host_lock, flags);
5674 * UFS_DEVICE_QUIRK_RECOVERY_FROM_DL_NAC_ERRORS only workaround the
5675 * device fatal error and/or DL NAC & REPLAY timeout errors.
5677 if (hba->saved_err & (CONTROLLER_FATAL_ERROR | SYSTEM_BUS_FATAL_ERROR))
5680 if ((hba->saved_err & DEVICE_FATAL_ERROR) ||
5681 ((hba->saved_err & UIC_ERROR) &&
5682 (hba->saved_uic_err & UFSHCD_UIC_DL_TCx_REPLAY_ERROR)))
5685 if ((hba->saved_err & UIC_ERROR) &&
5686 (hba->saved_uic_err & UFSHCD_UIC_DL_NAC_RECEIVED_ERROR)) {
5689 * wait for 50ms to see if we can get any other errors or not.
5691 spin_unlock_irqrestore(hba->host->host_lock, flags);
5693 spin_lock_irqsave(hba->host->host_lock, flags);
5696 * now check if we have got any other severe errors other than
5699 if ((hba->saved_err & INT_FATAL_ERRORS) ||
5700 ((hba->saved_err & UIC_ERROR) &&
5701 (hba->saved_uic_err & ~UFSHCD_UIC_DL_NAC_RECEIVED_ERROR)))
5705 * As DL NAC is the only error received so far, send out NOP
5706 * command to confirm if link is still active or not.
5707 * - If we don't get any response then do error recovery.
5708 * - If we get response then clear the DL NAC error bit.
5711 spin_unlock_irqrestore(hba->host->host_lock, flags);
5712 err = ufshcd_verify_dev_init(hba);
5713 spin_lock_irqsave(hba->host->host_lock, flags);
5718 /* Link seems to be alive hence ignore the DL NAC errors */
5719 if (hba->saved_uic_err == UFSHCD_UIC_DL_NAC_RECEIVED_ERROR)
5720 hba->saved_err &= ~UIC_ERROR;
5721 /* clear NAC error */
5722 hba->saved_uic_err &= ~UFSHCD_UIC_DL_NAC_RECEIVED_ERROR;
5723 if (!hba->saved_uic_err)
5724 err_handling = false;
5727 spin_unlock_irqrestore(hba->host->host_lock, flags);
5728 return err_handling;
5731 /* host lock must be held before calling this func */
5732 static inline bool ufshcd_is_saved_err_fatal(struct ufs_hba *hba)
5734 return (hba->saved_uic_err & UFSHCD_UIC_DL_PA_INIT_ERROR) ||
5735 (hba->saved_err & (INT_FATAL_ERRORS | UFSHCD_UIC_HIBERN8_MASK));
5738 /* host lock must be held before calling this func */
5739 static inline void ufshcd_schedule_eh_work(struct ufs_hba *hba)
5741 /* handle fatal errors only when link is not in error state */
5742 if (hba->ufshcd_state != UFSHCD_STATE_ERROR) {
5743 if (hba->force_reset || ufshcd_is_link_broken(hba) ||
5744 ufshcd_is_saved_err_fatal(hba))
5745 hba->ufshcd_state = UFSHCD_STATE_EH_SCHEDULED_FATAL;
5747 hba->ufshcd_state = UFSHCD_STATE_EH_SCHEDULED_NON_FATAL;
5748 queue_work(hba->eh_wq, &hba->eh_work);
5752 static void ufshcd_clk_scaling_allow(struct ufs_hba *hba, bool allow)
5754 down_write(&hba->clk_scaling_lock);
5755 hba->clk_scaling.is_allowed = allow;
5756 up_write(&hba->clk_scaling_lock);
5759 static void ufshcd_clk_scaling_suspend(struct ufs_hba *hba, bool suspend)
5762 if (hba->clk_scaling.is_enabled)
5763 ufshcd_suspend_clkscaling(hba);
5764 ufshcd_clk_scaling_allow(hba, false);
5766 ufshcd_clk_scaling_allow(hba, true);
5767 if (hba->clk_scaling.is_enabled)
5768 ufshcd_resume_clkscaling(hba);
5772 static void ufshcd_err_handling_prepare(struct ufs_hba *hba)
5774 pm_runtime_get_sync(hba->dev);
5775 if (pm_runtime_status_suspended(hba->dev) || hba->is_sys_suspended) {
5776 enum ufs_pm_op pm_op;
5779 * Don't assume anything of pm_runtime_get_sync(), if
5780 * resume fails, irq and clocks can be OFF, and powers
5781 * can be OFF or in LPM.
5783 ufshcd_setup_hba_vreg(hba, true);
5784 ufshcd_enable_irq(hba);
5785 ufshcd_setup_vreg(hba, true);
5786 ufshcd_config_vreg_hpm(hba, hba->vreg_info.vccq);
5787 ufshcd_config_vreg_hpm(hba, hba->vreg_info.vccq2);
5788 ufshcd_hold(hba, false);
5789 if (!ufshcd_is_clkgating_allowed(hba))
5790 ufshcd_setup_clocks(hba, true);
5791 ufshcd_release(hba);
5792 pm_op = hba->is_sys_suspended ? UFS_SYSTEM_PM : UFS_RUNTIME_PM;
5793 ufshcd_vops_resume(hba, pm_op);
5795 ufshcd_hold(hba, false);
5796 if (ufshcd_is_clkscaling_supported(hba) &&
5797 hba->clk_scaling.is_enabled)
5798 ufshcd_suspend_clkscaling(hba);
5799 ufshcd_clk_scaling_allow(hba, false);
5803 static void ufshcd_err_handling_unprepare(struct ufs_hba *hba)
5805 ufshcd_release(hba);
5806 if (ufshcd_is_clkscaling_supported(hba))
5807 ufshcd_clk_scaling_suspend(hba, false);
5808 pm_runtime_put(hba->dev);
5811 static inline bool ufshcd_err_handling_should_stop(struct ufs_hba *hba)
5813 return (!hba->is_powered || hba->shutting_down ||
5814 hba->ufshcd_state == UFSHCD_STATE_ERROR ||
5815 (!(hba->saved_err || hba->saved_uic_err || hba->force_reset ||
5816 ufshcd_is_link_broken(hba))));
5820 static void ufshcd_recover_pm_error(struct ufs_hba *hba)
5822 struct Scsi_Host *shost = hba->host;
5823 struct scsi_device *sdev;
5824 struct request_queue *q;
5827 hba->is_sys_suspended = false;
5829 * Set RPM status of hba device to RPM_ACTIVE,
5830 * this also clears its runtime error.
5832 ret = pm_runtime_set_active(hba->dev);
5834 * If hba device had runtime error, we also need to resume those
5835 * scsi devices under hba in case any of them has failed to be
5836 * resumed due to hba runtime resume failure. This is to unblock
5837 * blk_queue_enter in case there are bios waiting inside it.
5840 shost_for_each_device(sdev, shost) {
5841 q = sdev->request_queue;
5842 if (q->dev && (q->rpm_status == RPM_SUSPENDED ||
5843 q->rpm_status == RPM_SUSPENDING))
5844 pm_request_resume(q->dev);
5849 static inline void ufshcd_recover_pm_error(struct ufs_hba *hba)
5854 static bool ufshcd_is_pwr_mode_restore_needed(struct ufs_hba *hba)
5856 struct ufs_pa_layer_attr *pwr_info = &hba->pwr_info;
5859 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_PWRMODE), &mode);
5861 if (pwr_info->pwr_rx != ((mode >> PWRMODE_RX_OFFSET) & PWRMODE_MASK))
5864 if (pwr_info->pwr_tx != (mode & PWRMODE_MASK))
5871 * ufshcd_err_handler - handle UFS errors that require s/w attention
5872 * @work: pointer to work structure
5874 static void ufshcd_err_handler(struct work_struct *work)
5876 struct ufs_hba *hba;
5877 unsigned long flags;
5878 bool err_xfer = false;
5879 bool err_tm = false;
5880 int err = 0, pmc_err;
5882 bool needs_reset = false, needs_restore = false;
5884 hba = container_of(work, struct ufs_hba, eh_work);
5886 down(&hba->host_sem);
5887 spin_lock_irqsave(hba->host->host_lock, flags);
5888 if (ufshcd_err_handling_should_stop(hba)) {
5889 if (hba->ufshcd_state != UFSHCD_STATE_ERROR)
5890 hba->ufshcd_state = UFSHCD_STATE_OPERATIONAL;
5891 spin_unlock_irqrestore(hba->host->host_lock, flags);
5895 ufshcd_set_eh_in_progress(hba);
5896 spin_unlock_irqrestore(hba->host->host_lock, flags);
5897 ufshcd_err_handling_prepare(hba);
5898 spin_lock_irqsave(hba->host->host_lock, flags);
5899 ufshcd_scsi_block_requests(hba);
5900 hba->ufshcd_state = UFSHCD_STATE_RESET;
5902 /* Complete requests that have door-bell cleared by h/w */
5903 ufshcd_complete_requests(hba);
5906 * A full reset and restore might have happened after preparation
5907 * is finished, double check whether we should stop.
5909 if (ufshcd_err_handling_should_stop(hba))
5910 goto skip_err_handling;
5912 if (hba->dev_quirks & UFS_DEVICE_QUIRK_RECOVERY_FROM_DL_NAC_ERRORS) {
5915 spin_unlock_irqrestore(hba->host->host_lock, flags);
5916 /* release the lock as ufshcd_quirk_dl_nac_errors() may sleep */
5917 ret = ufshcd_quirk_dl_nac_errors(hba);
5918 spin_lock_irqsave(hba->host->host_lock, flags);
5919 if (!ret && ufshcd_err_handling_should_stop(hba))
5920 goto skip_err_handling;
5923 if ((hba->saved_err & (INT_FATAL_ERRORS | UFSHCD_UIC_HIBERN8_MASK)) ||
5924 (hba->saved_uic_err &&
5925 (hba->saved_uic_err != UFSHCD_UIC_PA_GENERIC_ERROR))) {
5926 bool pr_prdt = !!(hba->saved_err & SYSTEM_BUS_FATAL_ERROR);
5928 spin_unlock_irqrestore(hba->host->host_lock, flags);
5929 ufshcd_print_host_state(hba);
5930 ufshcd_print_pwr_info(hba);
5931 ufshcd_print_evt_hist(hba);
5932 ufshcd_print_tmrs(hba, hba->outstanding_tasks);
5933 ufshcd_print_trs(hba, hba->outstanding_reqs, pr_prdt);
5934 spin_lock_irqsave(hba->host->host_lock, flags);
5938 * if host reset is required then skip clearing the pending
5939 * transfers forcefully because they will get cleared during
5940 * host reset and restore
5942 if (hba->force_reset || ufshcd_is_link_broken(hba) ||
5943 ufshcd_is_saved_err_fatal(hba) ||
5944 ((hba->saved_err & UIC_ERROR) &&
5945 (hba->saved_uic_err & (UFSHCD_UIC_DL_NAC_RECEIVED_ERROR |
5946 UFSHCD_UIC_DL_TCx_REPLAY_ERROR)))) {
5952 * If LINERESET was caught, UFS might have been put to PWM mode,
5953 * check if power mode restore is needed.
5955 if (hba->saved_uic_err & UFSHCD_UIC_PA_GENERIC_ERROR) {
5956 hba->saved_uic_err &= ~UFSHCD_UIC_PA_GENERIC_ERROR;
5957 if (!hba->saved_uic_err)
5958 hba->saved_err &= ~UIC_ERROR;
5959 spin_unlock_irqrestore(hba->host->host_lock, flags);
5960 if (ufshcd_is_pwr_mode_restore_needed(hba))
5961 needs_restore = true;
5962 spin_lock_irqsave(hba->host->host_lock, flags);
5963 if (!hba->saved_err && !needs_restore)
5964 goto skip_err_handling;
5967 hba->silence_err_logs = true;
5968 /* release lock as clear command might sleep */
5969 spin_unlock_irqrestore(hba->host->host_lock, flags);
5970 /* Clear pending transfer requests */
5971 for_each_set_bit(tag, &hba->outstanding_reqs, hba->nutrs) {
5972 if (ufshcd_try_to_abort_task(hba, tag)) {
5974 goto lock_skip_pending_xfer_clear;
5978 /* Clear pending task management requests */
5979 for_each_set_bit(tag, &hba->outstanding_tasks, hba->nutmrs) {
5980 if (ufshcd_clear_tm_cmd(hba, tag)) {
5982 goto lock_skip_pending_xfer_clear;
5986 lock_skip_pending_xfer_clear:
5987 spin_lock_irqsave(hba->host->host_lock, flags);
5989 /* Complete the requests that are cleared by s/w */
5990 ufshcd_complete_requests(hba);
5991 hba->silence_err_logs = false;
5993 if (err_xfer || err_tm) {
5999 * After all reqs and tasks are cleared from doorbell,
6000 * now it is safe to retore power mode.
6002 if (needs_restore) {
6003 spin_unlock_irqrestore(hba->host->host_lock, flags);
6005 * Hold the scaling lock just in case dev cmds
6006 * are sent via bsg and/or sysfs.
6008 down_write(&hba->clk_scaling_lock);
6009 hba->force_pmc = true;
6010 pmc_err = ufshcd_config_pwr_mode(hba, &(hba->pwr_info));
6013 dev_err(hba->dev, "%s: Failed to restore power mode, err = %d\n",
6016 hba->force_pmc = false;
6017 ufshcd_print_pwr_info(hba);
6018 up_write(&hba->clk_scaling_lock);
6019 spin_lock_irqsave(hba->host->host_lock, flags);
6023 /* Fatal errors need reset */
6025 unsigned long max_doorbells = (1UL << hba->nutrs) - 1;
6028 * ufshcd_reset_and_restore() does the link reinitialization
6029 * which will need atleast one empty doorbell slot to send the
6030 * device management commands (NOP and query commands).
6031 * If there is no slot empty at this moment then free up last
6034 if (hba->outstanding_reqs == max_doorbells)
6035 __ufshcd_transfer_req_compl(hba,
6036 (1UL << (hba->nutrs - 1)));
6038 hba->force_reset = false;
6039 spin_unlock_irqrestore(hba->host->host_lock, flags);
6040 err = ufshcd_reset_and_restore(hba);
6042 dev_err(hba->dev, "%s: reset and restore failed with err %d\n",
6045 ufshcd_recover_pm_error(hba);
6046 spin_lock_irqsave(hba->host->host_lock, flags);
6051 if (hba->ufshcd_state == UFSHCD_STATE_RESET)
6052 hba->ufshcd_state = UFSHCD_STATE_OPERATIONAL;
6053 if (hba->saved_err || hba->saved_uic_err)
6054 dev_err_ratelimited(hba->dev, "%s: exit: saved_err 0x%x saved_uic_err 0x%x",
6055 __func__, hba->saved_err, hba->saved_uic_err);
6057 ufshcd_clear_eh_in_progress(hba);
6058 spin_unlock_irqrestore(hba->host->host_lock, flags);
6059 ufshcd_scsi_unblock_requests(hba);
6060 ufshcd_err_handling_unprepare(hba);
6063 if (!err && needs_reset)
6064 ufshcd_clear_ua_wluns(hba);
6068 * ufshcd_update_uic_error - check and set fatal UIC error flags.
6069 * @hba: per-adapter instance
6072 * IRQ_HANDLED - If interrupt is valid
6073 * IRQ_NONE - If invalid interrupt
6075 static irqreturn_t ufshcd_update_uic_error(struct ufs_hba *hba)
6078 irqreturn_t retval = IRQ_NONE;
6080 /* PHY layer error */
6081 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_PHY_ADAPTER_LAYER);
6082 if ((reg & UIC_PHY_ADAPTER_LAYER_ERROR) &&
6083 (reg & UIC_PHY_ADAPTER_LAYER_ERROR_CODE_MASK)) {
6084 ufshcd_update_evt_hist(hba, UFS_EVT_PA_ERR, reg);
6086 * To know whether this error is fatal or not, DB timeout
6087 * must be checked but this error is handled separately.
6089 if (reg & UIC_PHY_ADAPTER_LAYER_LANE_ERR_MASK)
6090 dev_dbg(hba->dev, "%s: UIC Lane error reported\n",
6093 /* Got a LINERESET indication. */
6094 if (reg & UIC_PHY_ADAPTER_LAYER_GENERIC_ERROR) {
6095 struct uic_command *cmd = NULL;
6097 hba->uic_error |= UFSHCD_UIC_PA_GENERIC_ERROR;
6098 if (hba->uic_async_done && hba->active_uic_cmd)
6099 cmd = hba->active_uic_cmd;
6101 * Ignore the LINERESET during power mode change
6102 * operation via DME_SET command.
6104 if (cmd && (cmd->command == UIC_CMD_DME_SET))
6105 hba->uic_error &= ~UFSHCD_UIC_PA_GENERIC_ERROR;
6107 retval |= IRQ_HANDLED;
6110 /* PA_INIT_ERROR is fatal and needs UIC reset */
6111 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_DATA_LINK_LAYER);
6112 if ((reg & UIC_DATA_LINK_LAYER_ERROR) &&
6113 (reg & UIC_DATA_LINK_LAYER_ERROR_CODE_MASK)) {
6114 ufshcd_update_evt_hist(hba, UFS_EVT_DL_ERR, reg);
6116 if (reg & UIC_DATA_LINK_LAYER_ERROR_PA_INIT)
6117 hba->uic_error |= UFSHCD_UIC_DL_PA_INIT_ERROR;
6118 else if (hba->dev_quirks &
6119 UFS_DEVICE_QUIRK_RECOVERY_FROM_DL_NAC_ERRORS) {
6120 if (reg & UIC_DATA_LINK_LAYER_ERROR_NAC_RECEIVED)
6122 UFSHCD_UIC_DL_NAC_RECEIVED_ERROR;
6123 else if (reg & UIC_DATA_LINK_LAYER_ERROR_TCx_REPLAY_TIMEOUT)
6124 hba->uic_error |= UFSHCD_UIC_DL_TCx_REPLAY_ERROR;
6126 retval |= IRQ_HANDLED;
6129 /* UIC NL/TL/DME errors needs software retry */
6130 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_NETWORK_LAYER);
6131 if ((reg & UIC_NETWORK_LAYER_ERROR) &&
6132 (reg & UIC_NETWORK_LAYER_ERROR_CODE_MASK)) {
6133 ufshcd_update_evt_hist(hba, UFS_EVT_NL_ERR, reg);
6134 hba->uic_error |= UFSHCD_UIC_NL_ERROR;
6135 retval |= IRQ_HANDLED;
6138 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_TRANSPORT_LAYER);
6139 if ((reg & UIC_TRANSPORT_LAYER_ERROR) &&
6140 (reg & UIC_TRANSPORT_LAYER_ERROR_CODE_MASK)) {
6141 ufshcd_update_evt_hist(hba, UFS_EVT_TL_ERR, reg);
6142 hba->uic_error |= UFSHCD_UIC_TL_ERROR;
6143 retval |= IRQ_HANDLED;
6146 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_DME);
6147 if ((reg & UIC_DME_ERROR) &&
6148 (reg & UIC_DME_ERROR_CODE_MASK)) {
6149 ufshcd_update_evt_hist(hba, UFS_EVT_DME_ERR, reg);
6150 hba->uic_error |= UFSHCD_UIC_DME_ERROR;
6151 retval |= IRQ_HANDLED;
6154 dev_dbg(hba->dev, "%s: UIC error flags = 0x%08x\n",
6155 __func__, hba->uic_error);
6159 static bool ufshcd_is_auto_hibern8_error(struct ufs_hba *hba,
6162 if (!ufshcd_is_auto_hibern8_supported(hba) ||
6163 !ufshcd_is_auto_hibern8_enabled(hba))
6166 if (!(intr_mask & UFSHCD_UIC_HIBERN8_MASK))
6169 if (hba->active_uic_cmd &&
6170 (hba->active_uic_cmd->command == UIC_CMD_DME_HIBER_ENTER ||
6171 hba->active_uic_cmd->command == UIC_CMD_DME_HIBER_EXIT))
6178 * ufshcd_check_errors - Check for errors that need s/w attention
6179 * @hba: per-adapter instance
6182 * IRQ_HANDLED - If interrupt is valid
6183 * IRQ_NONE - If invalid interrupt
6185 static irqreturn_t ufshcd_check_errors(struct ufs_hba *hba)
6187 bool queue_eh_work = false;
6188 irqreturn_t retval = IRQ_NONE;
6190 if (hba->errors & INT_FATAL_ERRORS) {
6191 ufshcd_update_evt_hist(hba, UFS_EVT_FATAL_ERR,
6193 queue_eh_work = true;
6196 if (hba->errors & UIC_ERROR) {
6198 retval = ufshcd_update_uic_error(hba);
6200 queue_eh_work = true;
6203 if (hba->errors & UFSHCD_UIC_HIBERN8_MASK) {
6205 "%s: Auto Hibern8 %s failed - status: 0x%08x, upmcrs: 0x%08x\n",
6206 __func__, (hba->errors & UIC_HIBERNATE_ENTER) ?
6208 hba->errors, ufshcd_get_upmcrs(hba));
6209 ufshcd_update_evt_hist(hba, UFS_EVT_AUTO_HIBERN8_ERR,
6211 ufshcd_set_link_broken(hba);
6212 queue_eh_work = true;
6215 if (queue_eh_work) {
6217 * update the transfer error masks to sticky bits, let's do this
6218 * irrespective of current ufshcd_state.
6220 hba->saved_err |= hba->errors;
6221 hba->saved_uic_err |= hba->uic_error;
6223 /* dump controller state before resetting */
6224 if ((hba->saved_err &
6225 (INT_FATAL_ERRORS | UFSHCD_UIC_HIBERN8_MASK)) ||
6226 (hba->saved_uic_err &&
6227 (hba->saved_uic_err != UFSHCD_UIC_PA_GENERIC_ERROR))) {
6228 dev_err(hba->dev, "%s: saved_err 0x%x saved_uic_err 0x%x\n",
6229 __func__, hba->saved_err,
6230 hba->saved_uic_err);
6231 ufshcd_dump_regs(hba, 0, UFSHCI_REG_SPACE_SIZE,
6233 ufshcd_print_pwr_info(hba);
6235 ufshcd_schedule_eh_work(hba);
6236 retval |= IRQ_HANDLED;
6239 * if (!queue_eh_work) -
6240 * Other errors are either non-fatal where host recovers
6241 * itself without s/w intervention or errors that will be
6242 * handled by the SCSI core layer.
6248 struct ufs_hba *hba;
6249 unsigned long pending;
6253 static bool ufshcd_compl_tm(struct request *req, void *priv, bool reserved)
6255 struct ctm_info *const ci = priv;
6256 struct completion *c;
6258 WARN_ON_ONCE(reserved);
6259 if (test_bit(req->tag, &ci->pending))
6262 c = req->end_io_data;
6269 * ufshcd_tmc_handler - handle task management function completion
6270 * @hba: per adapter instance
6273 * IRQ_HANDLED - If interrupt is valid
6274 * IRQ_NONE - If invalid interrupt
6276 static irqreturn_t ufshcd_tmc_handler(struct ufs_hba *hba)
6278 struct request_queue *q = hba->tmf_queue;
6279 struct ctm_info ci = {
6281 .pending = ufshcd_readl(hba, REG_UTP_TASK_REQ_DOOR_BELL),
6284 blk_mq_tagset_busy_iter(q->tag_set, ufshcd_compl_tm, &ci);
6285 return ci.ncpl ? IRQ_HANDLED : IRQ_NONE;
6289 * ufshcd_sl_intr - Interrupt service routine
6290 * @hba: per adapter instance
6291 * @intr_status: contains interrupts generated by the controller
6294 * IRQ_HANDLED - If interrupt is valid
6295 * IRQ_NONE - If invalid interrupt
6297 static irqreturn_t ufshcd_sl_intr(struct ufs_hba *hba, u32 intr_status)
6299 irqreturn_t retval = IRQ_NONE;
6301 hba->errors = UFSHCD_ERROR_MASK & intr_status;
6303 if (ufshcd_is_auto_hibern8_error(hba, intr_status))
6304 hba->errors |= (UFSHCD_UIC_HIBERN8_MASK & intr_status);
6307 retval |= ufshcd_check_errors(hba);
6309 if (intr_status & UFSHCD_UIC_MASK)
6310 retval |= ufshcd_uic_cmd_compl(hba, intr_status);
6312 if (intr_status & UTP_TASK_REQ_COMPL)
6313 retval |= ufshcd_tmc_handler(hba);
6315 if (intr_status & UTP_TRANSFER_REQ_COMPL)
6316 retval |= ufshcd_transfer_req_compl(hba);
6322 * ufshcd_intr - Main interrupt service routine
6324 * @__hba: pointer to adapter instance
6327 * IRQ_HANDLED - If interrupt is valid
6328 * IRQ_NONE - If invalid interrupt
6330 static irqreturn_t ufshcd_intr(int irq, void *__hba)
6332 u32 intr_status, enabled_intr_status = 0;
6333 irqreturn_t retval = IRQ_NONE;
6334 struct ufs_hba *hba = __hba;
6335 int retries = hba->nutrs;
6337 spin_lock(hba->host->host_lock);
6338 intr_status = ufshcd_readl(hba, REG_INTERRUPT_STATUS);
6339 hba->ufs_stats.last_intr_status = intr_status;
6340 hba->ufs_stats.last_intr_ts = ktime_get();
6343 * There could be max of hba->nutrs reqs in flight and in worst case
6344 * if the reqs get finished 1 by 1 after the interrupt status is
6345 * read, make sure we handle them by checking the interrupt status
6346 * again in a loop until we process all of the reqs before returning.
6348 while (intr_status && retries--) {
6349 enabled_intr_status =
6350 intr_status & ufshcd_readl(hba, REG_INTERRUPT_ENABLE);
6351 ufshcd_writel(hba, intr_status, REG_INTERRUPT_STATUS);
6352 if (enabled_intr_status)
6353 retval |= ufshcd_sl_intr(hba, enabled_intr_status);
6355 intr_status = ufshcd_readl(hba, REG_INTERRUPT_STATUS);
6358 if (enabled_intr_status && retval == IRQ_NONE &&
6359 !ufshcd_eh_in_progress(hba)) {
6360 dev_err(hba->dev, "%s: Unhandled interrupt 0x%08x (0x%08x, 0x%08x)\n",
6363 hba->ufs_stats.last_intr_status,
6364 enabled_intr_status);
6365 ufshcd_dump_regs(hba, 0, UFSHCI_REG_SPACE_SIZE, "host_regs: ");
6368 spin_unlock(hba->host->host_lock);
6372 static int ufshcd_clear_tm_cmd(struct ufs_hba *hba, int tag)
6375 u32 mask = 1 << tag;
6376 unsigned long flags;
6378 if (!test_bit(tag, &hba->outstanding_tasks))
6381 spin_lock_irqsave(hba->host->host_lock, flags);
6382 ufshcd_utmrl_clear(hba, tag);
6383 spin_unlock_irqrestore(hba->host->host_lock, flags);
6385 /* poll for max. 1 sec to clear door bell register by h/w */
6386 err = ufshcd_wait_for_register(hba,
6387 REG_UTP_TASK_REQ_DOOR_BELL,
6388 mask, 0, 1000, 1000);
6393 static int __ufshcd_issue_tm_cmd(struct ufs_hba *hba,
6394 struct utp_task_req_desc *treq, u8 tm_function)
6396 struct request_queue *q = hba->tmf_queue;
6397 struct Scsi_Host *host = hba->host;
6398 DECLARE_COMPLETION_ONSTACK(wait);
6399 struct request *req;
6400 unsigned long flags;
6401 int free_slot, task_tag, err;
6404 * Get free slot, sleep if slots are unavailable.
6405 * Even though we use wait_event() which sleeps indefinitely,
6406 * the maximum wait time is bounded by %TM_CMD_TIMEOUT.
6408 req = blk_get_request(q, REQ_OP_DRV_OUT, 0);
6410 return PTR_ERR(req);
6412 req->end_io_data = &wait;
6413 free_slot = req->tag;
6414 WARN_ON_ONCE(free_slot < 0 || free_slot >= hba->nutmrs);
6415 ufshcd_hold(hba, false);
6417 spin_lock_irqsave(host->host_lock, flags);
6418 task_tag = hba->nutrs + free_slot;
6420 treq->req_header.dword_0 |= cpu_to_be32(task_tag);
6422 memcpy(hba->utmrdl_base_addr + free_slot, treq, sizeof(*treq));
6423 ufshcd_vops_setup_task_mgmt(hba, free_slot, tm_function);
6425 /* send command to the controller */
6426 __set_bit(free_slot, &hba->outstanding_tasks);
6428 /* Make sure descriptors are ready before ringing the task doorbell */
6431 ufshcd_writel(hba, 1 << free_slot, REG_UTP_TASK_REQ_DOOR_BELL);
6432 /* Make sure that doorbell is committed immediately */
6435 spin_unlock_irqrestore(host->host_lock, flags);
6437 ufshcd_add_tm_upiu_trace(hba, task_tag, UFS_TM_SEND);
6439 /* wait until the task management command is completed */
6440 err = wait_for_completion_io_timeout(&wait,
6441 msecs_to_jiffies(TM_CMD_TIMEOUT));
6444 * Make sure that ufshcd_compl_tm() does not trigger a
6447 req->end_io_data = NULL;
6448 ufshcd_add_tm_upiu_trace(hba, task_tag, UFS_TM_ERR);
6449 dev_err(hba->dev, "%s: task management cmd 0x%.2x timed-out\n",
6450 __func__, tm_function);
6451 if (ufshcd_clear_tm_cmd(hba, free_slot))
6452 dev_WARN(hba->dev, "%s: unable clear tm cmd (slot %d) after timeout\n",
6453 __func__, free_slot);
6457 memcpy(treq, hba->utmrdl_base_addr + free_slot, sizeof(*treq));
6459 ufshcd_add_tm_upiu_trace(hba, task_tag, UFS_TM_COMP);
6462 spin_lock_irqsave(hba->host->host_lock, flags);
6463 __clear_bit(free_slot, &hba->outstanding_tasks);
6464 spin_unlock_irqrestore(hba->host->host_lock, flags);
6466 blk_put_request(req);
6468 ufshcd_release(hba);
6473 * ufshcd_issue_tm_cmd - issues task management commands to controller
6474 * @hba: per adapter instance
6475 * @lun_id: LUN ID to which TM command is sent
6476 * @task_id: task ID to which the TM command is applicable
6477 * @tm_function: task management function opcode
6478 * @tm_response: task management service response return value
6480 * Returns non-zero value on error, zero on success.
6482 static int ufshcd_issue_tm_cmd(struct ufs_hba *hba, int lun_id, int task_id,
6483 u8 tm_function, u8 *tm_response)
6485 struct utp_task_req_desc treq = { { 0 }, };
6488 /* Configure task request descriptor */
6489 treq.header.dword_0 = cpu_to_le32(UTP_REQ_DESC_INT_CMD);
6490 treq.header.dword_2 = cpu_to_le32(OCS_INVALID_COMMAND_STATUS);
6492 /* Configure task request UPIU */
6493 treq.req_header.dword_0 = cpu_to_be32(lun_id << 8) |
6494 cpu_to_be32(UPIU_TRANSACTION_TASK_REQ << 24);
6495 treq.req_header.dword_1 = cpu_to_be32(tm_function << 16);
6498 * The host shall provide the same value for LUN field in the basic
6499 * header and for Input Parameter.
6501 treq.input_param1 = cpu_to_be32(lun_id);
6502 treq.input_param2 = cpu_to_be32(task_id);
6504 err = __ufshcd_issue_tm_cmd(hba, &treq, tm_function);
6505 if (err == -ETIMEDOUT)
6508 ocs_value = le32_to_cpu(treq.header.dword_2) & MASK_OCS;
6509 if (ocs_value != OCS_SUCCESS)
6510 dev_err(hba->dev, "%s: failed, ocs = 0x%x\n",
6511 __func__, ocs_value);
6512 else if (tm_response)
6513 *tm_response = be32_to_cpu(treq.output_param1) &
6514 MASK_TM_SERVICE_RESP;
6519 * ufshcd_issue_devman_upiu_cmd - API for sending "utrd" type requests
6520 * @hba: per-adapter instance
6521 * @req_upiu: upiu request
6522 * @rsp_upiu: upiu reply
6523 * @desc_buff: pointer to descriptor buffer, NULL if NA
6524 * @buff_len: descriptor size, 0 if NA
6525 * @cmd_type: specifies the type (NOP, Query...)
6526 * @desc_op: descriptor operation
6528 * Those type of requests uses UTP Transfer Request Descriptor - utrd.
6529 * Therefore, it "rides" the device management infrastructure: uses its tag and
6530 * tasks work queues.
6532 * Since there is only one available tag for device management commands,
6533 * the caller is expected to hold the hba->dev_cmd.lock mutex.
6535 static int ufshcd_issue_devman_upiu_cmd(struct ufs_hba *hba,
6536 struct utp_upiu_req *req_upiu,
6537 struct utp_upiu_req *rsp_upiu,
6538 u8 *desc_buff, int *buff_len,
6539 enum dev_cmd_type cmd_type,
6540 enum query_opcode desc_op)
6542 struct request_queue *q = hba->cmd_queue;
6543 struct request *req;
6544 struct ufshcd_lrb *lrbp;
6547 struct completion wait;
6548 unsigned long flags;
6551 down_read(&hba->clk_scaling_lock);
6553 req = blk_get_request(q, REQ_OP_DRV_OUT, 0);
6559 WARN_ON_ONCE(!ufshcd_valid_tag(hba, tag));
6561 init_completion(&wait);
6562 lrbp = &hba->lrb[tag];
6563 if (unlikely(lrbp->in_use)) {
6570 lrbp->sense_bufflen = 0;
6571 lrbp->sense_buffer = NULL;
6572 lrbp->task_tag = tag;
6574 lrbp->intr_cmd = true;
6575 ufshcd_prepare_lrbp_crypto(NULL, lrbp);
6576 hba->dev_cmd.type = cmd_type;
6578 switch (hba->ufs_version) {
6579 case UFSHCI_VERSION_10:
6580 case UFSHCI_VERSION_11:
6581 lrbp->command_type = UTP_CMD_TYPE_DEV_MANAGE;
6584 lrbp->command_type = UTP_CMD_TYPE_UFS_STORAGE;
6588 /* update the task tag in the request upiu */
6589 req_upiu->header.dword_0 |= cpu_to_be32(tag);
6591 ufshcd_prepare_req_desc_hdr(lrbp, &upiu_flags, DMA_NONE);
6593 /* just copy the upiu request as it is */
6594 memcpy(lrbp->ucd_req_ptr, req_upiu, sizeof(*lrbp->ucd_req_ptr));
6595 if (desc_buff && desc_op == UPIU_QUERY_OPCODE_WRITE_DESC) {
6596 /* The Data Segment Area is optional depending upon the query
6597 * function value. for WRITE DESCRIPTOR, the data segment
6598 * follows right after the tsf.
6600 memcpy(lrbp->ucd_req_ptr + 1, desc_buff, *buff_len);
6604 memset(lrbp->ucd_rsp_ptr, 0, sizeof(struct utp_upiu_rsp));
6606 hba->dev_cmd.complete = &wait;
6608 /* Make sure descriptors are ready before ringing the doorbell */
6610 spin_lock_irqsave(hba->host->host_lock, flags);
6611 ufshcd_send_command(hba, tag);
6612 spin_unlock_irqrestore(hba->host->host_lock, flags);
6615 * ignore the returning value here - ufshcd_check_query_response is
6616 * bound to fail since dev_cmd.query and dev_cmd.type were left empty.
6617 * read the response directly ignoring all errors.
6619 ufshcd_wait_for_dev_cmd(hba, lrbp, QUERY_REQ_TIMEOUT);
6621 /* just copy the upiu response as it is */
6622 memcpy(rsp_upiu, lrbp->ucd_rsp_ptr, sizeof(*rsp_upiu));
6623 if (desc_buff && desc_op == UPIU_QUERY_OPCODE_READ_DESC) {
6624 u8 *descp = (u8 *)lrbp->ucd_rsp_ptr + sizeof(*rsp_upiu);
6625 u16 resp_len = be32_to_cpu(lrbp->ucd_rsp_ptr->header.dword_2) &
6626 MASK_QUERY_DATA_SEG_LEN;
6628 if (*buff_len >= resp_len) {
6629 memcpy(desc_buff, descp, resp_len);
6630 *buff_len = resp_len;
6633 "%s: rsp size %d is bigger than buffer size %d",
6634 __func__, resp_len, *buff_len);
6641 blk_put_request(req);
6643 up_read(&hba->clk_scaling_lock);
6648 * ufshcd_exec_raw_upiu_cmd - API function for sending raw upiu commands
6649 * @hba: per-adapter instance
6650 * @req_upiu: upiu request
6651 * @rsp_upiu: upiu reply - only 8 DW as we do not support scsi commands
6652 * @msgcode: message code, one of UPIU Transaction Codes Initiator to Target
6653 * @desc_buff: pointer to descriptor buffer, NULL if NA
6654 * @buff_len: descriptor size, 0 if NA
6655 * @desc_op: descriptor operation
6657 * Supports UTP Transfer requests (nop and query), and UTP Task
6658 * Management requests.
6659 * It is up to the caller to fill the upiu conent properly, as it will
6660 * be copied without any further input validations.
6662 int ufshcd_exec_raw_upiu_cmd(struct ufs_hba *hba,
6663 struct utp_upiu_req *req_upiu,
6664 struct utp_upiu_req *rsp_upiu,
6666 u8 *desc_buff, int *buff_len,
6667 enum query_opcode desc_op)
6670 enum dev_cmd_type cmd_type = DEV_CMD_TYPE_QUERY;
6671 struct utp_task_req_desc treq = { { 0 }, };
6673 u8 tm_f = be32_to_cpu(req_upiu->header.dword_1) >> 16 & MASK_TM_FUNC;
6676 case UPIU_TRANSACTION_NOP_OUT:
6677 cmd_type = DEV_CMD_TYPE_NOP;
6679 case UPIU_TRANSACTION_QUERY_REQ:
6680 ufshcd_hold(hba, false);
6681 mutex_lock(&hba->dev_cmd.lock);
6682 err = ufshcd_issue_devman_upiu_cmd(hba, req_upiu, rsp_upiu,
6683 desc_buff, buff_len,
6685 mutex_unlock(&hba->dev_cmd.lock);
6686 ufshcd_release(hba);
6689 case UPIU_TRANSACTION_TASK_REQ:
6690 treq.header.dword_0 = cpu_to_le32(UTP_REQ_DESC_INT_CMD);
6691 treq.header.dword_2 = cpu_to_le32(OCS_INVALID_COMMAND_STATUS);
6693 memcpy(&treq.req_header, req_upiu, sizeof(*req_upiu));
6695 err = __ufshcd_issue_tm_cmd(hba, &treq, tm_f);
6696 if (err == -ETIMEDOUT)
6699 ocs_value = le32_to_cpu(treq.header.dword_2) & MASK_OCS;
6700 if (ocs_value != OCS_SUCCESS) {
6701 dev_err(hba->dev, "%s: failed, ocs = 0x%x\n", __func__,
6706 memcpy(rsp_upiu, &treq.rsp_header, sizeof(*rsp_upiu));
6719 * ufshcd_eh_device_reset_handler - device reset handler registered to
6721 * @cmd: SCSI command pointer
6723 * Returns SUCCESS/FAILED
6725 static int ufshcd_eh_device_reset_handler(struct scsi_cmnd *cmd)
6727 struct Scsi_Host *host;
6728 struct ufs_hba *hba;
6732 unsigned long flags;
6734 host = cmd->device->host;
6735 hba = shost_priv(host);
6737 lun = ufshcd_scsi_to_upiu_lun(cmd->device->lun);
6738 err = ufshcd_issue_tm_cmd(hba, lun, 0, UFS_LOGICAL_RESET, &resp);
6739 if (err || resp != UPIU_TASK_MANAGEMENT_FUNC_COMPL) {
6745 /* clear the commands that were pending for corresponding LUN */
6746 for_each_set_bit(pos, &hba->outstanding_reqs, hba->nutrs) {
6747 if (hba->lrb[pos].lun == lun) {
6748 err = ufshcd_clear_cmd(hba, pos);
6753 spin_lock_irqsave(host->host_lock, flags);
6754 ufshcd_transfer_req_compl(hba);
6755 spin_unlock_irqrestore(host->host_lock, flags);
6758 hba->req_abort_count = 0;
6759 ufshcd_update_evt_hist(hba, UFS_EVT_DEV_RESET, (u32)err);
6763 dev_err(hba->dev, "%s: failed with err %d\n", __func__, err);
6769 static void ufshcd_set_req_abort_skip(struct ufs_hba *hba, unsigned long bitmap)
6771 struct ufshcd_lrb *lrbp;
6774 for_each_set_bit(tag, &bitmap, hba->nutrs) {
6775 lrbp = &hba->lrb[tag];
6776 lrbp->req_abort_skip = true;
6781 * ufshcd_try_to_abort_task - abort a specific task
6782 * @hba: Pointer to adapter instance
6783 * @tag: Task tag/index to be aborted
6785 * Abort the pending command in device by sending UFS_ABORT_TASK task management
6786 * command, and in host controller by clearing the door-bell register. There can
6787 * be race between controller sending the command to the device while abort is
6788 * issued. To avoid that, first issue UFS_QUERY_TASK to check if the command is
6789 * really issued and then try to abort it.
6791 * Returns zero on success, non-zero on failure
6793 static int ufshcd_try_to_abort_task(struct ufs_hba *hba, int tag)
6795 struct ufshcd_lrb *lrbp = &hba->lrb[tag];
6801 for (poll_cnt = 100; poll_cnt; poll_cnt--) {
6802 err = ufshcd_issue_tm_cmd(hba, lrbp->lun, lrbp->task_tag,
6803 UFS_QUERY_TASK, &resp);
6804 if (!err && resp == UPIU_TASK_MANAGEMENT_FUNC_SUCCEEDED) {
6805 /* cmd pending in the device */
6806 dev_err(hba->dev, "%s: cmd pending in the device. tag = %d\n",
6809 } else if (!err && resp == UPIU_TASK_MANAGEMENT_FUNC_COMPL) {
6811 * cmd not pending in the device, check if it is
6814 dev_err(hba->dev, "%s: cmd at tag %d not pending in the device.\n",
6816 reg = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
6817 if (reg & (1 << tag)) {
6818 /* sleep for max. 200us to stabilize */
6819 usleep_range(100, 200);
6822 /* command completed already */
6823 dev_err(hba->dev, "%s: cmd at tag %d successfully cleared from DB.\n",
6828 "%s: no response from device. tag = %d, err %d\n",
6829 __func__, tag, err);
6831 err = resp; /* service response error */
6841 err = ufshcd_issue_tm_cmd(hba, lrbp->lun, lrbp->task_tag,
6842 UFS_ABORT_TASK, &resp);
6843 if (err || resp != UPIU_TASK_MANAGEMENT_FUNC_COMPL) {
6845 err = resp; /* service response error */
6846 dev_err(hba->dev, "%s: issued. tag = %d, err %d\n",
6847 __func__, tag, err);
6852 err = ufshcd_clear_cmd(hba, tag);
6854 dev_err(hba->dev, "%s: Failed clearing cmd at tag %d, err %d\n",
6855 __func__, tag, err);
6862 * ufshcd_abort - scsi host template eh_abort_handler callback
6863 * @cmd: SCSI command pointer
6865 * Returns SUCCESS/FAILED
6867 static int ufshcd_abort(struct scsi_cmnd *cmd)
6869 struct Scsi_Host *host;
6870 struct ufs_hba *hba;
6871 unsigned long flags;
6874 struct ufshcd_lrb *lrbp;
6877 host = cmd->device->host;
6878 hba = shost_priv(host);
6879 tag = cmd->request->tag;
6880 lrbp = &hba->lrb[tag];
6881 if (!ufshcd_valid_tag(hba, tag)) {
6883 "%s: invalid command tag %d: cmd=0x%p, cmd->request=0x%p",
6884 __func__, tag, cmd, cmd->request);
6888 ufshcd_hold(hba, false);
6889 reg = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
6890 /* If command is already aborted/completed, return SUCCESS */
6891 if (!(test_bit(tag, &hba->outstanding_reqs))) {
6893 "%s: cmd at tag %d already completed, outstanding=0x%lx, doorbell=0x%x\n",
6894 __func__, tag, hba->outstanding_reqs, reg);
6898 /* Print Transfer Request of aborted task */
6899 dev_info(hba->dev, "%s: Device abort task at tag %d\n", __func__, tag);
6902 * Print detailed info about aborted request.
6903 * As more than one request might get aborted at the same time,
6904 * print full information only for the first aborted request in order
6905 * to reduce repeated printouts. For other aborted requests only print
6908 scsi_print_command(cmd);
6909 if (!hba->req_abort_count) {
6910 ufshcd_update_evt_hist(hba, UFS_EVT_ABORT, tag);
6911 ufshcd_print_evt_hist(hba);
6912 ufshcd_print_host_state(hba);
6913 ufshcd_print_pwr_info(hba);
6914 ufshcd_print_trs(hba, 1 << tag, true);
6916 ufshcd_print_trs(hba, 1 << tag, false);
6918 hba->req_abort_count++;
6920 if (!(reg & (1 << tag))) {
6922 "%s: cmd was completed, but without a notifying intr, tag = %d",
6928 * Task abort to the device W-LUN is illegal. When this command
6929 * will fail, due to spec violation, scsi err handling next step
6930 * will be to send LU reset which, again, is a spec violation.
6931 * To avoid these unnecessary/illegal steps, first we clean up
6932 * the lrb taken by this cmd and mark the lrb as in_use, then
6933 * queue the eh_work and bail.
6935 if (lrbp->lun == UFS_UPIU_UFS_DEVICE_WLUN) {
6936 ufshcd_update_evt_hist(hba, UFS_EVT_ABORT, lrbp->lun);
6937 spin_lock_irqsave(host->host_lock, flags);
6939 __ufshcd_transfer_req_compl(hba, (1UL << tag));
6940 __set_bit(tag, &hba->outstanding_reqs);
6941 lrbp->in_use = true;
6942 hba->force_reset = true;
6943 ufshcd_schedule_eh_work(hba);
6946 spin_unlock_irqrestore(host->host_lock, flags);
6950 /* Skip task abort in case previous aborts failed and report failure */
6951 if (lrbp->req_abort_skip)
6954 err = ufshcd_try_to_abort_task(hba, tag);
6958 spin_lock_irqsave(host->host_lock, flags);
6959 __ufshcd_transfer_req_compl(hba, (1UL << tag));
6960 spin_unlock_irqrestore(host->host_lock, flags);
6964 dev_err(hba->dev, "%s: failed with err %d\n", __func__, err);
6965 ufshcd_set_req_abort_skip(hba, hba->outstanding_reqs);
6970 * This ufshcd_release() corresponds to the original scsi cmd that got
6971 * aborted here (as we won't get any IRQ for it).
6973 ufshcd_release(hba);
6978 * ufshcd_host_reset_and_restore - reset and restore host controller
6979 * @hba: per-adapter instance
6981 * Note that host controller reset may issue DME_RESET to
6982 * local and remote (device) Uni-Pro stack and the attributes
6983 * are reset to default state.
6985 * Returns zero on success, non-zero on failure
6987 static int ufshcd_host_reset_and_restore(struct ufs_hba *hba)
6990 unsigned long flags;
6993 * Stop the host controller and complete the requests
6996 ufshcd_hba_stop(hba);
6998 spin_lock_irqsave(hba->host->host_lock, flags);
6999 hba->silence_err_logs = true;
7000 ufshcd_complete_requests(hba);
7001 hba->silence_err_logs = false;
7002 spin_unlock_irqrestore(hba->host->host_lock, flags);
7004 /* scale up clocks to max frequency before full reinitialization */
7005 ufshcd_set_clk_freq(hba, true);
7007 err = ufshcd_hba_enable(hba);
7009 /* Establish the link again and restore the device */
7011 err = ufshcd_probe_hba(hba, false);
7014 dev_err(hba->dev, "%s: Host init failed %d\n", __func__, err);
7015 ufshcd_update_evt_hist(hba, UFS_EVT_HOST_RESET, (u32)err);
7020 * ufshcd_reset_and_restore - reset and re-initialize host/device
7021 * @hba: per-adapter instance
7023 * Reset and recover device, host and re-establish link. This
7024 * is helpful to recover the communication in fatal error conditions.
7026 * Returns zero on success, non-zero on failure
7028 static int ufshcd_reset_and_restore(struct ufs_hba *hba)
7033 unsigned long flags;
7034 int retries = MAX_HOST_RESET_RETRIES;
7037 * This is a fresh start, cache and clear saved error first,
7038 * in case new error generated during reset and restore.
7040 spin_lock_irqsave(hba->host->host_lock, flags);
7041 saved_err = hba->saved_err;
7042 saved_uic_err = hba->saved_uic_err;
7044 hba->saved_uic_err = 0;
7045 spin_unlock_irqrestore(hba->host->host_lock, flags);
7048 /* Reset the attached device */
7049 ufshcd_device_reset(hba);
7051 err = ufshcd_host_reset_and_restore(hba);
7052 } while (err && --retries);
7054 spin_lock_irqsave(hba->host->host_lock, flags);
7056 * Inform scsi mid-layer that we did reset and allow to handle
7057 * Unit Attention properly.
7059 scsi_report_bus_reset(hba->host, 0);
7061 hba->ufshcd_state = UFSHCD_STATE_ERROR;
7062 hba->saved_err |= saved_err;
7063 hba->saved_uic_err |= saved_uic_err;
7065 spin_unlock_irqrestore(hba->host->host_lock, flags);
7071 * ufshcd_eh_host_reset_handler - host reset handler registered to scsi layer
7072 * @cmd: SCSI command pointer
7074 * Returns SUCCESS/FAILED
7076 static int ufshcd_eh_host_reset_handler(struct scsi_cmnd *cmd)
7079 unsigned long flags;
7080 struct ufs_hba *hba;
7082 hba = shost_priv(cmd->device->host);
7084 spin_lock_irqsave(hba->host->host_lock, flags);
7085 hba->force_reset = true;
7086 ufshcd_schedule_eh_work(hba);
7087 dev_err(hba->dev, "%s: reset in progress - 1\n", __func__);
7088 spin_unlock_irqrestore(hba->host->host_lock, flags);
7090 flush_work(&hba->eh_work);
7092 spin_lock_irqsave(hba->host->host_lock, flags);
7093 if (hba->ufshcd_state == UFSHCD_STATE_ERROR)
7095 spin_unlock_irqrestore(hba->host->host_lock, flags);
7101 * ufshcd_get_max_icc_level - calculate the ICC level
7102 * @sup_curr_uA: max. current supported by the regulator
7103 * @start_scan: row at the desc table to start scan from
7104 * @buff: power descriptor buffer
7106 * Returns calculated max ICC level for specific regulator
7108 static u32 ufshcd_get_max_icc_level(int sup_curr_uA, u32 start_scan, char *buff)
7115 for (i = start_scan; i >= 0; i--) {
7116 data = be16_to_cpup((__be16 *)&buff[2 * i]);
7117 unit = (data & ATTR_ICC_LVL_UNIT_MASK) >>
7118 ATTR_ICC_LVL_UNIT_OFFSET;
7119 curr_uA = data & ATTR_ICC_LVL_VALUE_MASK;
7121 case UFSHCD_NANO_AMP:
7122 curr_uA = curr_uA / 1000;
7124 case UFSHCD_MILI_AMP:
7125 curr_uA = curr_uA * 1000;
7128 curr_uA = curr_uA * 1000 * 1000;
7130 case UFSHCD_MICRO_AMP:
7134 if (sup_curr_uA >= curr_uA)
7139 pr_err("%s: Couldn't find valid icc_level = %d", __func__, i);
7146 * ufshcd_find_max_sup_active_icc_level - calculate the max ICC level
7147 * In case regulators are not initialized we'll return 0
7148 * @hba: per-adapter instance
7149 * @desc_buf: power descriptor buffer to extract ICC levels from.
7150 * @len: length of desc_buff
7152 * Returns calculated ICC level
7154 static u32 ufshcd_find_max_sup_active_icc_level(struct ufs_hba *hba,
7155 u8 *desc_buf, int len)
7159 if (!hba->vreg_info.vcc || !hba->vreg_info.vccq ||
7160 !hba->vreg_info.vccq2) {
7162 "%s: Regulator capability was not set, actvIccLevel=%d",
7163 __func__, icc_level);
7167 if (hba->vreg_info.vcc && hba->vreg_info.vcc->max_uA)
7168 icc_level = ufshcd_get_max_icc_level(
7169 hba->vreg_info.vcc->max_uA,
7170 POWER_DESC_MAX_ACTV_ICC_LVLS - 1,
7171 &desc_buf[PWR_DESC_ACTIVE_LVLS_VCC_0]);
7173 if (hba->vreg_info.vccq && hba->vreg_info.vccq->max_uA)
7174 icc_level = ufshcd_get_max_icc_level(
7175 hba->vreg_info.vccq->max_uA,
7177 &desc_buf[PWR_DESC_ACTIVE_LVLS_VCCQ_0]);
7179 if (hba->vreg_info.vccq2 && hba->vreg_info.vccq2->max_uA)
7180 icc_level = ufshcd_get_max_icc_level(
7181 hba->vreg_info.vccq2->max_uA,
7183 &desc_buf[PWR_DESC_ACTIVE_LVLS_VCCQ2_0]);
7188 static void ufshcd_set_active_icc_lvl(struct ufs_hba *hba)
7191 int buff_len = hba->desc_size[QUERY_DESC_IDN_POWER];
7195 desc_buf = kmalloc(buff_len, GFP_KERNEL);
7199 ret = ufshcd_read_desc_param(hba, QUERY_DESC_IDN_POWER, 0, 0,
7200 desc_buf, buff_len);
7203 "%s: Failed reading power descriptor.len = %d ret = %d",
7204 __func__, buff_len, ret);
7208 icc_level = ufshcd_find_max_sup_active_icc_level(hba, desc_buf,
7210 dev_dbg(hba->dev, "%s: setting icc_level 0x%x", __func__, icc_level);
7212 ret = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_WRITE_ATTR,
7213 QUERY_ATTR_IDN_ACTIVE_ICC_LVL, 0, 0, &icc_level);
7217 "%s: Failed configuring bActiveICCLevel = %d ret = %d",
7218 __func__, icc_level, ret);
7224 static inline void ufshcd_blk_pm_runtime_init(struct scsi_device *sdev)
7226 scsi_autopm_get_device(sdev);
7227 blk_pm_runtime_init(sdev->request_queue, &sdev->sdev_gendev);
7228 if (sdev->rpm_autosuspend)
7229 pm_runtime_set_autosuspend_delay(&sdev->sdev_gendev,
7230 RPM_AUTOSUSPEND_DELAY_MS);
7231 scsi_autopm_put_device(sdev);
7235 * ufshcd_scsi_add_wlus - Adds required W-LUs
7236 * @hba: per-adapter instance
7238 * UFS device specification requires the UFS devices to support 4 well known
7240 * "REPORT_LUNS" (address: 01h)
7241 * "UFS Device" (address: 50h)
7242 * "RPMB" (address: 44h)
7243 * "BOOT" (address: 30h)
7244 * UFS device's power management needs to be controlled by "POWER CONDITION"
7245 * field of SSU (START STOP UNIT) command. But this "power condition" field
7246 * will take effect only when its sent to "UFS device" well known logical unit
7247 * hence we require the scsi_device instance to represent this logical unit in
7248 * order for the UFS host driver to send the SSU command for power management.
7250 * We also require the scsi_device instance for "RPMB" (Replay Protected Memory
7251 * Block) LU so user space process can control this LU. User space may also
7252 * want to have access to BOOT LU.
7254 * This function adds scsi device instances for each of all well known LUs
7255 * (except "REPORT LUNS" LU).
7257 * Returns zero on success (all required W-LUs are added successfully),
7258 * non-zero error value on failure (if failed to add any of the required W-LU).
7260 static int ufshcd_scsi_add_wlus(struct ufs_hba *hba)
7263 struct scsi_device *sdev_boot;
7265 hba->sdev_ufs_device = __scsi_add_device(hba->host, 0, 0,
7266 ufshcd_upiu_wlun_to_scsi_wlun(UFS_UPIU_UFS_DEVICE_WLUN), NULL);
7267 if (IS_ERR(hba->sdev_ufs_device)) {
7268 ret = PTR_ERR(hba->sdev_ufs_device);
7269 hba->sdev_ufs_device = NULL;
7272 ufshcd_blk_pm_runtime_init(hba->sdev_ufs_device);
7273 scsi_device_put(hba->sdev_ufs_device);
7275 hba->sdev_rpmb = __scsi_add_device(hba->host, 0, 0,
7276 ufshcd_upiu_wlun_to_scsi_wlun(UFS_UPIU_RPMB_WLUN), NULL);
7277 if (IS_ERR(hba->sdev_rpmb)) {
7278 ret = PTR_ERR(hba->sdev_rpmb);
7279 goto remove_sdev_ufs_device;
7281 ufshcd_blk_pm_runtime_init(hba->sdev_rpmb);
7282 scsi_device_put(hba->sdev_rpmb);
7284 sdev_boot = __scsi_add_device(hba->host, 0, 0,
7285 ufshcd_upiu_wlun_to_scsi_wlun(UFS_UPIU_BOOT_WLUN), NULL);
7286 if (IS_ERR(sdev_boot)) {
7287 dev_err(hba->dev, "%s: BOOT WLUN not found\n", __func__);
7289 ufshcd_blk_pm_runtime_init(sdev_boot);
7290 scsi_device_put(sdev_boot);
7294 remove_sdev_ufs_device:
7295 scsi_remove_device(hba->sdev_ufs_device);
7300 static void ufshcd_wb_probe(struct ufs_hba *hba, u8 *desc_buf)
7302 struct ufs_dev_info *dev_info = &hba->dev_info;
7304 u32 d_lu_wb_buf_alloc;
7305 u32 ext_ufs_feature;
7307 if (!ufshcd_is_wb_allowed(hba))
7310 * Probe WB only for UFS-2.2 and UFS-3.1 (and later) devices or
7311 * UFS devices with quirk UFS_DEVICE_QUIRK_SUPPORT_EXTENDED_FEATURES
7314 if (!(dev_info->wspecversion >= 0x310 ||
7315 dev_info->wspecversion == 0x220 ||
7316 (hba->dev_quirks & UFS_DEVICE_QUIRK_SUPPORT_EXTENDED_FEATURES)))
7319 if (hba->desc_size[QUERY_DESC_IDN_DEVICE] <
7320 DEVICE_DESC_PARAM_EXT_UFS_FEATURE_SUP + 4)
7323 ext_ufs_feature = get_unaligned_be32(desc_buf +
7324 DEVICE_DESC_PARAM_EXT_UFS_FEATURE_SUP);
7326 if (!(ext_ufs_feature & UFS_DEV_WRITE_BOOSTER_SUP))
7330 * WB may be supported but not configured while provisioning. The spec
7331 * says, in dedicated wb buffer mode, a max of 1 lun would have wb
7332 * buffer configured.
7334 dev_info->wb_buffer_type = desc_buf[DEVICE_DESC_PARAM_WB_TYPE];
7336 dev_info->b_presrv_uspc_en =
7337 desc_buf[DEVICE_DESC_PARAM_WB_PRESRV_USRSPC_EN];
7339 if (dev_info->wb_buffer_type == WB_BUF_MODE_SHARED) {
7340 if (!get_unaligned_be32(desc_buf +
7341 DEVICE_DESC_PARAM_WB_SHARED_ALLOC_UNITS))
7344 for (lun = 0; lun < UFS_UPIU_MAX_WB_LUN_ID; lun++) {
7345 d_lu_wb_buf_alloc = 0;
7346 ufshcd_read_unit_desc_param(hba,
7348 UNIT_DESC_PARAM_WB_BUF_ALLOC_UNITS,
7349 (u8 *)&d_lu_wb_buf_alloc,
7350 sizeof(d_lu_wb_buf_alloc));
7351 if (d_lu_wb_buf_alloc) {
7352 dev_info->wb_dedicated_lu = lun;
7357 if (!d_lu_wb_buf_alloc)
7363 hba->caps &= ~UFSHCD_CAP_WB_EN;
7366 void ufshcd_fixup_dev_quirks(struct ufs_hba *hba, struct ufs_dev_fix *fixups)
7368 struct ufs_dev_fix *f;
7369 struct ufs_dev_info *dev_info = &hba->dev_info;
7374 for (f = fixups; f->quirk; f++) {
7375 if ((f->wmanufacturerid == dev_info->wmanufacturerid ||
7376 f->wmanufacturerid == UFS_ANY_VENDOR) &&
7377 ((dev_info->model &&
7378 STR_PRFX_EQUAL(f->model, dev_info->model)) ||
7379 !strcmp(f->model, UFS_ANY_MODEL)))
7380 hba->dev_quirks |= f->quirk;
7383 EXPORT_SYMBOL_GPL(ufshcd_fixup_dev_quirks);
7385 static void ufs_fixup_device_setup(struct ufs_hba *hba)
7387 /* fix by general quirk table */
7388 ufshcd_fixup_dev_quirks(hba, ufs_fixups);
7390 /* allow vendors to fix quirks */
7391 ufshcd_vops_fixup_dev_quirks(hba);
7394 static int ufs_get_device_desc(struct ufs_hba *hba)
7399 struct ufs_dev_info *dev_info = &hba->dev_info;
7401 desc_buf = kmalloc(QUERY_DESC_MAX_SIZE, GFP_KERNEL);
7407 err = ufshcd_read_desc_param(hba, QUERY_DESC_IDN_DEVICE, 0, 0, desc_buf,
7408 hba->desc_size[QUERY_DESC_IDN_DEVICE]);
7410 dev_err(hba->dev, "%s: Failed reading Device Desc. err = %d\n",
7416 * getting vendor (manufacturerID) and Bank Index in big endian
7419 dev_info->wmanufacturerid = desc_buf[DEVICE_DESC_PARAM_MANF_ID] << 8 |
7420 desc_buf[DEVICE_DESC_PARAM_MANF_ID + 1];
7422 /* getting Specification Version in big endian format */
7423 dev_info->wspecversion = desc_buf[DEVICE_DESC_PARAM_SPEC_VER] << 8 |
7424 desc_buf[DEVICE_DESC_PARAM_SPEC_VER + 1];
7426 model_index = desc_buf[DEVICE_DESC_PARAM_PRDCT_NAME];
7428 err = ufshcd_read_string_desc(hba, model_index,
7429 &dev_info->model, SD_ASCII_STD);
7431 dev_err(hba->dev, "%s: Failed reading Product Name. err = %d\n",
7436 ufs_fixup_device_setup(hba);
7438 ufshcd_wb_probe(hba, desc_buf);
7441 * ufshcd_read_string_desc returns size of the string
7442 * reset the error value
7451 static void ufs_put_device_desc(struct ufs_hba *hba)
7453 struct ufs_dev_info *dev_info = &hba->dev_info;
7455 kfree(dev_info->model);
7456 dev_info->model = NULL;
7460 * ufshcd_tune_pa_tactivate - Tunes PA_TActivate of local UniPro
7461 * @hba: per-adapter instance
7463 * PA_TActivate parameter can be tuned manually if UniPro version is less than
7464 * 1.61. PA_TActivate needs to be greater than or equal to peerM-PHY's
7465 * RX_MIN_ACTIVATETIME_CAPABILITY attribute. This optimal value can help reduce
7466 * the hibern8 exit latency.
7468 * Returns zero on success, non-zero error value on failure.
7470 static int ufshcd_tune_pa_tactivate(struct ufs_hba *hba)
7473 u32 peer_rx_min_activatetime = 0, tuned_pa_tactivate;
7475 ret = ufshcd_dme_peer_get(hba,
7477 RX_MIN_ACTIVATETIME_CAPABILITY,
7478 UIC_ARG_MPHY_RX_GEN_SEL_INDEX(0)),
7479 &peer_rx_min_activatetime);
7483 /* make sure proper unit conversion is applied */
7484 tuned_pa_tactivate =
7485 ((peer_rx_min_activatetime * RX_MIN_ACTIVATETIME_UNIT_US)
7486 / PA_TACTIVATE_TIME_UNIT_US);
7487 ret = ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TACTIVATE),
7488 tuned_pa_tactivate);
7495 * ufshcd_tune_pa_hibern8time - Tunes PA_Hibern8Time of local UniPro
7496 * @hba: per-adapter instance
7498 * PA_Hibern8Time parameter can be tuned manually if UniPro version is less than
7499 * 1.61. PA_Hibern8Time needs to be maximum of local M-PHY's
7500 * TX_HIBERN8TIME_CAPABILITY & peer M-PHY's RX_HIBERN8TIME_CAPABILITY.
7501 * This optimal value can help reduce the hibern8 exit latency.
7503 * Returns zero on success, non-zero error value on failure.
7505 static int ufshcd_tune_pa_hibern8time(struct ufs_hba *hba)
7508 u32 local_tx_hibern8_time_cap = 0, peer_rx_hibern8_time_cap = 0;
7509 u32 max_hibern8_time, tuned_pa_hibern8time;
7511 ret = ufshcd_dme_get(hba,
7512 UIC_ARG_MIB_SEL(TX_HIBERN8TIME_CAPABILITY,
7513 UIC_ARG_MPHY_TX_GEN_SEL_INDEX(0)),
7514 &local_tx_hibern8_time_cap);
7518 ret = ufshcd_dme_peer_get(hba,
7519 UIC_ARG_MIB_SEL(RX_HIBERN8TIME_CAPABILITY,
7520 UIC_ARG_MPHY_RX_GEN_SEL_INDEX(0)),
7521 &peer_rx_hibern8_time_cap);
7525 max_hibern8_time = max(local_tx_hibern8_time_cap,
7526 peer_rx_hibern8_time_cap);
7527 /* make sure proper unit conversion is applied */
7528 tuned_pa_hibern8time = ((max_hibern8_time * HIBERN8TIME_UNIT_US)
7529 / PA_HIBERN8_TIME_UNIT_US);
7530 ret = ufshcd_dme_set(hba, UIC_ARG_MIB(PA_HIBERN8TIME),
7531 tuned_pa_hibern8time);
7537 * ufshcd_quirk_tune_host_pa_tactivate - Ensures that host PA_TACTIVATE is
7538 * less than device PA_TACTIVATE time.
7539 * @hba: per-adapter instance
7541 * Some UFS devices require host PA_TACTIVATE to be lower than device
7542 * PA_TACTIVATE, we need to enable UFS_DEVICE_QUIRK_HOST_PA_TACTIVATE quirk
7545 * Returns zero on success, non-zero error value on failure.
7547 static int ufshcd_quirk_tune_host_pa_tactivate(struct ufs_hba *hba)
7550 u32 granularity, peer_granularity;
7551 u32 pa_tactivate, peer_pa_tactivate;
7552 u32 pa_tactivate_us, peer_pa_tactivate_us;
7553 u8 gran_to_us_table[] = {1, 4, 8, 16, 32, 100};
7555 ret = ufshcd_dme_get(hba, UIC_ARG_MIB(PA_GRANULARITY),
7560 ret = ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_GRANULARITY),
7565 if ((granularity < PA_GRANULARITY_MIN_VAL) ||
7566 (granularity > PA_GRANULARITY_MAX_VAL)) {
7567 dev_err(hba->dev, "%s: invalid host PA_GRANULARITY %d",
7568 __func__, granularity);
7572 if ((peer_granularity < PA_GRANULARITY_MIN_VAL) ||
7573 (peer_granularity > PA_GRANULARITY_MAX_VAL)) {
7574 dev_err(hba->dev, "%s: invalid device PA_GRANULARITY %d",
7575 __func__, peer_granularity);
7579 ret = ufshcd_dme_get(hba, UIC_ARG_MIB(PA_TACTIVATE), &pa_tactivate);
7583 ret = ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_TACTIVATE),
7584 &peer_pa_tactivate);
7588 pa_tactivate_us = pa_tactivate * gran_to_us_table[granularity - 1];
7589 peer_pa_tactivate_us = peer_pa_tactivate *
7590 gran_to_us_table[peer_granularity - 1];
7592 if (pa_tactivate_us > peer_pa_tactivate_us) {
7593 u32 new_peer_pa_tactivate;
7595 new_peer_pa_tactivate = pa_tactivate_us /
7596 gran_to_us_table[peer_granularity - 1];
7597 new_peer_pa_tactivate++;
7598 ret = ufshcd_dme_peer_set(hba, UIC_ARG_MIB(PA_TACTIVATE),
7599 new_peer_pa_tactivate);
7606 static void ufshcd_tune_unipro_params(struct ufs_hba *hba)
7608 if (ufshcd_is_unipro_pa_params_tuning_req(hba)) {
7609 ufshcd_tune_pa_tactivate(hba);
7610 ufshcd_tune_pa_hibern8time(hba);
7613 ufshcd_vops_apply_dev_quirks(hba);
7615 if (hba->dev_quirks & UFS_DEVICE_QUIRK_PA_TACTIVATE)
7616 /* set 1ms timeout for PA_TACTIVATE */
7617 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TACTIVATE), 10);
7619 if (hba->dev_quirks & UFS_DEVICE_QUIRK_HOST_PA_TACTIVATE)
7620 ufshcd_quirk_tune_host_pa_tactivate(hba);
7623 static void ufshcd_clear_dbg_ufs_stats(struct ufs_hba *hba)
7625 hba->ufs_stats.hibern8_exit_cnt = 0;
7626 hba->ufs_stats.last_hibern8_exit_tstamp = ktime_set(0, 0);
7627 hba->req_abort_count = 0;
7630 static int ufshcd_device_geo_params_init(struct ufs_hba *hba)
7636 buff_len = hba->desc_size[QUERY_DESC_IDN_GEOMETRY];
7637 desc_buf = kmalloc(buff_len, GFP_KERNEL);
7643 err = ufshcd_read_desc_param(hba, QUERY_DESC_IDN_GEOMETRY, 0, 0,
7644 desc_buf, buff_len);
7646 dev_err(hba->dev, "%s: Failed reading Geometry Desc. err = %d\n",
7651 if (desc_buf[GEOMETRY_DESC_PARAM_MAX_NUM_LUN] == 1)
7652 hba->dev_info.max_lu_supported = 32;
7653 else if (desc_buf[GEOMETRY_DESC_PARAM_MAX_NUM_LUN] == 0)
7654 hba->dev_info.max_lu_supported = 8;
7661 static struct ufs_ref_clk ufs_ref_clk_freqs[] = {
7662 {19200000, REF_CLK_FREQ_19_2_MHZ},
7663 {26000000, REF_CLK_FREQ_26_MHZ},
7664 {38400000, REF_CLK_FREQ_38_4_MHZ},
7665 {52000000, REF_CLK_FREQ_52_MHZ},
7666 {0, REF_CLK_FREQ_INVAL},
7669 static enum ufs_ref_clk_freq
7670 ufs_get_bref_clk_from_hz(unsigned long freq)
7674 for (i = 0; ufs_ref_clk_freqs[i].freq_hz; i++)
7675 if (ufs_ref_clk_freqs[i].freq_hz == freq)
7676 return ufs_ref_clk_freqs[i].val;
7678 return REF_CLK_FREQ_INVAL;
7681 void ufshcd_parse_dev_ref_clk_freq(struct ufs_hba *hba, struct clk *refclk)
7685 freq = clk_get_rate(refclk);
7687 hba->dev_ref_clk_freq =
7688 ufs_get_bref_clk_from_hz(freq);
7690 if (hba->dev_ref_clk_freq == REF_CLK_FREQ_INVAL)
7692 "invalid ref_clk setting = %ld\n", freq);
7695 static int ufshcd_set_dev_ref_clk(struct ufs_hba *hba)
7699 u32 freq = hba->dev_ref_clk_freq;
7701 err = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
7702 QUERY_ATTR_IDN_REF_CLK_FREQ, 0, 0, &ref_clk);
7705 dev_err(hba->dev, "failed reading bRefClkFreq. err = %d\n",
7710 if (ref_clk == freq)
7711 goto out; /* nothing to update */
7713 err = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_WRITE_ATTR,
7714 QUERY_ATTR_IDN_REF_CLK_FREQ, 0, 0, &freq);
7717 dev_err(hba->dev, "bRefClkFreq setting to %lu Hz failed\n",
7718 ufs_ref_clk_freqs[freq].freq_hz);
7722 dev_dbg(hba->dev, "bRefClkFreq setting to %lu Hz succeeded\n",
7723 ufs_ref_clk_freqs[freq].freq_hz);
7729 static int ufshcd_device_params_init(struct ufs_hba *hba)
7734 /* Init device descriptor sizes */
7735 for (i = 0; i < QUERY_DESC_IDN_MAX; i++)
7736 hba->desc_size[i] = QUERY_DESC_MAX_SIZE;
7738 /* Init UFS geometry descriptor related parameters */
7739 ret = ufshcd_device_geo_params_init(hba);
7743 /* Check and apply UFS device quirks */
7744 ret = ufs_get_device_desc(hba);
7746 dev_err(hba->dev, "%s: Failed getting device info. err = %d\n",
7751 ufshcd_get_ref_clk_gating_wait(hba);
7753 if (!ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_READ_FLAG,
7754 QUERY_FLAG_IDN_PWR_ON_WPE, 0, &flag))
7755 hba->dev_info.f_power_on_wp_en = flag;
7757 /* Probe maximum power mode co-supported by both UFS host and device */
7758 if (ufshcd_get_max_pwr_mode(hba))
7760 "%s: Failed getting max supported power mode\n",
7767 * ufshcd_add_lus - probe and add UFS logical units
7768 * @hba: per-adapter instance
7770 static int ufshcd_add_lus(struct ufs_hba *hba)
7774 /* Add required well known logical units to scsi mid layer */
7775 ret = ufshcd_scsi_add_wlus(hba);
7779 ufshcd_clear_ua_wluns(hba);
7781 /* Initialize devfreq after UFS device is detected */
7782 if (ufshcd_is_clkscaling_supported(hba)) {
7783 memcpy(&hba->clk_scaling.saved_pwr_info.info,
7785 sizeof(struct ufs_pa_layer_attr));
7786 hba->clk_scaling.saved_pwr_info.is_valid = true;
7787 hba->clk_scaling.is_allowed = true;
7789 ret = ufshcd_devfreq_init(hba);
7793 hba->clk_scaling.is_enabled = true;
7794 ufshcd_init_clk_scaling_sysfs(hba);
7798 scsi_scan_host(hba->host);
7799 pm_runtime_put_sync(hba->dev);
7806 ufshcd_send_request_sense(struct ufs_hba *hba, struct scsi_device *sdp);
7808 static int ufshcd_clear_ua_wlun(struct ufs_hba *hba, u8 wlun)
7810 struct scsi_device *sdp;
7811 unsigned long flags;
7814 spin_lock_irqsave(hba->host->host_lock, flags);
7815 if (wlun == UFS_UPIU_UFS_DEVICE_WLUN)
7816 sdp = hba->sdev_ufs_device;
7817 else if (wlun == UFS_UPIU_RPMB_WLUN)
7818 sdp = hba->sdev_rpmb;
7822 ret = scsi_device_get(sdp);
7823 if (!ret && !scsi_device_online(sdp)) {
7825 scsi_device_put(sdp);
7830 spin_unlock_irqrestore(hba->host->host_lock, flags);
7834 ret = ufshcd_send_request_sense(hba, sdp);
7835 scsi_device_put(sdp);
7838 dev_err(hba->dev, "%s: UAC clear LU=%x ret = %d\n",
7839 __func__, wlun, ret);
7843 static int ufshcd_clear_ua_wluns(struct ufs_hba *hba)
7847 if (!hba->wlun_dev_clr_ua)
7850 ret = ufshcd_clear_ua_wlun(hba, UFS_UPIU_UFS_DEVICE_WLUN);
7852 ret = ufshcd_clear_ua_wlun(hba, UFS_UPIU_RPMB_WLUN);
7854 hba->wlun_dev_clr_ua = false;
7857 dev_err(hba->dev, "%s: Failed to clear UAC WLUNS ret = %d\n",
7863 * ufshcd_probe_hba - probe hba to detect device and initialize
7864 * @hba: per-adapter instance
7865 * @async: asynchronous execution or not
7867 * Execute link-startup and verify device initialization
7869 static int ufshcd_probe_hba(struct ufs_hba *hba, bool async)
7872 unsigned long flags;
7873 ktime_t start = ktime_get();
7875 ret = ufshcd_link_startup(hba);
7879 /* Debug counters initialization */
7880 ufshcd_clear_dbg_ufs_stats(hba);
7882 /* UniPro link is active now */
7883 ufshcd_set_link_active(hba);
7885 /* Verify device initialization by sending NOP OUT UPIU */
7886 ret = ufshcd_verify_dev_init(hba);
7890 /* Initiate UFS initialization, and waiting until completion */
7891 ret = ufshcd_complete_dev_init(hba);
7896 * Initialize UFS device parameters used by driver, these
7897 * parameters are associated with UFS descriptors.
7900 ret = ufshcd_device_params_init(hba);
7905 ufshcd_tune_unipro_params(hba);
7907 /* UFS device is also active now */
7908 ufshcd_set_ufs_dev_active(hba);
7909 ufshcd_force_reset_auto_bkops(hba);
7910 hba->wlun_dev_clr_ua = true;
7912 /* Gear up to HS gear if supported */
7913 if (hba->max_pwr_info.is_valid) {
7915 * Set the right value to bRefClkFreq before attempting to
7916 * switch to HS gears.
7918 if (hba->dev_ref_clk_freq != REF_CLK_FREQ_INVAL)
7919 ufshcd_set_dev_ref_clk(hba);
7920 ret = ufshcd_config_pwr_mode(hba, &hba->max_pwr_info.info);
7922 dev_err(hba->dev, "%s: Failed setting power mode, err = %d\n",
7926 ufshcd_print_pwr_info(hba);
7930 * bActiveICCLevel is volatile for UFS device (as per latest v2.1 spec)
7931 * and for removable UFS card as well, hence always set the parameter.
7932 * Note: Error handler may issue the device reset hence resetting
7933 * bActiveICCLevel as well so it is always safe to set this here.
7935 ufshcd_set_active_icc_lvl(hba);
7937 ufshcd_wb_config(hba);
7938 if (hba->ee_usr_mask)
7939 ufshcd_write_ee_control(hba);
7940 /* Enable Auto-Hibernate if configured */
7941 ufshcd_auto_hibern8_enable(hba);
7944 spin_lock_irqsave(hba->host->host_lock, flags);
7946 hba->ufshcd_state = UFSHCD_STATE_ERROR;
7947 else if (hba->ufshcd_state == UFSHCD_STATE_RESET)
7948 hba->ufshcd_state = UFSHCD_STATE_OPERATIONAL;
7949 spin_unlock_irqrestore(hba->host->host_lock, flags);
7951 trace_ufshcd_init(dev_name(hba->dev), ret,
7952 ktime_to_us(ktime_sub(ktime_get(), start)),
7953 hba->curr_dev_pwr_mode, hba->uic_link_state);
7958 * ufshcd_async_scan - asynchronous execution for probing hba
7959 * @data: data pointer to pass to this function
7960 * @cookie: cookie data
7962 static void ufshcd_async_scan(void *data, async_cookie_t cookie)
7964 struct ufs_hba *hba = (struct ufs_hba *)data;
7967 down(&hba->host_sem);
7968 /* Initialize hba, detect and initialize UFS device */
7969 ret = ufshcd_probe_hba(hba, true);
7974 /* Probe and add UFS logical units */
7975 ret = ufshcd_add_lus(hba);
7978 * If we failed to initialize the device or the device is not
7979 * present, turn off the power/clocks etc.
7982 pm_runtime_put_sync(hba->dev);
7983 ufshcd_hba_exit(hba);
7987 static const struct attribute_group *ufshcd_driver_groups[] = {
7988 &ufs_sysfs_unit_descriptor_group,
7989 &ufs_sysfs_lun_attributes_group,
7993 static struct ufs_hba_variant_params ufs_hba_vps = {
7994 .hba_enable_delay_us = 1000,
7995 .wb_flush_threshold = UFS_WB_BUF_REMAIN_PERCENT(40),
7996 .devfreq_profile.polling_ms = 100,
7997 .devfreq_profile.target = ufshcd_devfreq_target,
7998 .devfreq_profile.get_dev_status = ufshcd_devfreq_get_dev_status,
7999 .ondemand_data.upthreshold = 70,
8000 .ondemand_data.downdifferential = 5,
8003 static struct scsi_host_template ufshcd_driver_template = {
8004 .module = THIS_MODULE,
8006 .proc_name = UFSHCD,
8007 .queuecommand = ufshcd_queuecommand,
8008 .slave_alloc = ufshcd_slave_alloc,
8009 .slave_configure = ufshcd_slave_configure,
8010 .slave_destroy = ufshcd_slave_destroy,
8011 .change_queue_depth = ufshcd_change_queue_depth,
8012 .eh_abort_handler = ufshcd_abort,
8013 .eh_device_reset_handler = ufshcd_eh_device_reset_handler,
8014 .eh_host_reset_handler = ufshcd_eh_host_reset_handler,
8016 .sg_tablesize = SG_ALL,
8017 .cmd_per_lun = UFSHCD_CMD_PER_LUN,
8018 .can_queue = UFSHCD_CAN_QUEUE,
8019 .max_segment_size = PRDT_DATA_BYTE_COUNT_MAX,
8020 .max_host_blocked = 1,
8021 .track_queue_depth = 1,
8022 .sdev_groups = ufshcd_driver_groups,
8023 .dma_boundary = PAGE_SIZE - 1,
8024 .rpm_autosuspend_delay = RPM_AUTOSUSPEND_DELAY_MS,
8027 static int ufshcd_config_vreg_load(struct device *dev, struct ufs_vreg *vreg,
8036 * "set_load" operation shall be required on those regulators
8037 * which specifically configured current limitation. Otherwise
8038 * zero max_uA may cause unexpected behavior when regulator is
8039 * enabled or set as high power mode.
8044 ret = regulator_set_load(vreg->reg, ua);
8046 dev_err(dev, "%s: %s set load (ua=%d) failed, err=%d\n",
8047 __func__, vreg->name, ua, ret);
8053 static inline int ufshcd_config_vreg_lpm(struct ufs_hba *hba,
8054 struct ufs_vreg *vreg)
8056 return ufshcd_config_vreg_load(hba->dev, vreg, UFS_VREG_LPM_LOAD_UA);
8059 static inline int ufshcd_config_vreg_hpm(struct ufs_hba *hba,
8060 struct ufs_vreg *vreg)
8065 return ufshcd_config_vreg_load(hba->dev, vreg, vreg->max_uA);
8068 static int ufshcd_config_vreg(struct device *dev,
8069 struct ufs_vreg *vreg, bool on)
8072 struct regulator *reg;
8074 int min_uV, uA_load;
8081 if (regulator_count_voltages(reg) > 0) {
8082 uA_load = on ? vreg->max_uA : 0;
8083 ret = ufshcd_config_vreg_load(dev, vreg, uA_load);
8087 if (vreg->min_uV && vreg->max_uV) {
8088 min_uV = on ? vreg->min_uV : 0;
8089 ret = regulator_set_voltage(reg, min_uV, vreg->max_uV);
8092 "%s: %s set voltage failed, err=%d\n",
8093 __func__, name, ret);
8100 static int ufshcd_enable_vreg(struct device *dev, struct ufs_vreg *vreg)
8104 if (!vreg || vreg->enabled)
8107 ret = ufshcd_config_vreg(dev, vreg, true);
8109 ret = regulator_enable(vreg->reg);
8112 vreg->enabled = true;
8114 dev_err(dev, "%s: %s enable failed, err=%d\n",
8115 __func__, vreg->name, ret);
8120 static int ufshcd_disable_vreg(struct device *dev, struct ufs_vreg *vreg)
8124 if (!vreg || !vreg->enabled || vreg->always_on)
8127 ret = regulator_disable(vreg->reg);
8130 /* ignore errors on applying disable config */
8131 ufshcd_config_vreg(dev, vreg, false);
8132 vreg->enabled = false;
8134 dev_err(dev, "%s: %s disable failed, err=%d\n",
8135 __func__, vreg->name, ret);
8141 static int ufshcd_setup_vreg(struct ufs_hba *hba, bool on)
8144 struct device *dev = hba->dev;
8145 struct ufs_vreg_info *info = &hba->vreg_info;
8147 ret = ufshcd_toggle_vreg(dev, info->vcc, on);
8151 ret = ufshcd_toggle_vreg(dev, info->vccq, on);
8155 ret = ufshcd_toggle_vreg(dev, info->vccq2, on);
8159 ufshcd_toggle_vreg(dev, info->vccq2, false);
8160 ufshcd_toggle_vreg(dev, info->vccq, false);
8161 ufshcd_toggle_vreg(dev, info->vcc, false);
8166 static int ufshcd_setup_hba_vreg(struct ufs_hba *hba, bool on)
8168 struct ufs_vreg_info *info = &hba->vreg_info;
8170 return ufshcd_toggle_vreg(hba->dev, info->vdd_hba, on);
8173 static int ufshcd_get_vreg(struct device *dev, struct ufs_vreg *vreg)
8180 vreg->reg = devm_regulator_get(dev, vreg->name);
8181 if (IS_ERR(vreg->reg)) {
8182 ret = PTR_ERR(vreg->reg);
8183 dev_err(dev, "%s: %s get failed, err=%d\n",
8184 __func__, vreg->name, ret);
8190 static int ufshcd_init_vreg(struct ufs_hba *hba)
8193 struct device *dev = hba->dev;
8194 struct ufs_vreg_info *info = &hba->vreg_info;
8196 ret = ufshcd_get_vreg(dev, info->vcc);
8200 ret = ufshcd_get_vreg(dev, info->vccq);
8202 ret = ufshcd_get_vreg(dev, info->vccq2);
8207 static int ufshcd_init_hba_vreg(struct ufs_hba *hba)
8209 struct ufs_vreg_info *info = &hba->vreg_info;
8212 return ufshcd_get_vreg(hba->dev, info->vdd_hba);
8217 static int ufshcd_setup_clocks(struct ufs_hba *hba, bool on)
8220 struct ufs_clk_info *clki;
8221 struct list_head *head = &hba->clk_list_head;
8222 unsigned long flags;
8223 ktime_t start = ktime_get();
8224 bool clk_state_changed = false;
8226 if (list_empty(head))
8229 ret = ufshcd_vops_setup_clocks(hba, on, PRE_CHANGE);
8233 list_for_each_entry(clki, head, list) {
8234 if (!IS_ERR_OR_NULL(clki->clk)) {
8236 * Don't disable clocks which are needed
8237 * to keep the link active.
8239 if (ufshcd_is_link_active(hba) &&
8240 clki->keep_link_active)
8243 clk_state_changed = on ^ clki->enabled;
8244 if (on && !clki->enabled) {
8245 ret = clk_prepare_enable(clki->clk);
8247 dev_err(hba->dev, "%s: %s prepare enable failed, %d\n",
8248 __func__, clki->name, ret);
8251 } else if (!on && clki->enabled) {
8252 clk_disable_unprepare(clki->clk);
8255 dev_dbg(hba->dev, "%s: clk: %s %sabled\n", __func__,
8256 clki->name, on ? "en" : "dis");
8260 ret = ufshcd_vops_setup_clocks(hba, on, POST_CHANGE);
8266 list_for_each_entry(clki, head, list) {
8267 if (!IS_ERR_OR_NULL(clki->clk) && clki->enabled)
8268 clk_disable_unprepare(clki->clk);
8270 } else if (!ret && on) {
8271 spin_lock_irqsave(hba->host->host_lock, flags);
8272 hba->clk_gating.state = CLKS_ON;
8273 trace_ufshcd_clk_gating(dev_name(hba->dev),
8274 hba->clk_gating.state);
8275 spin_unlock_irqrestore(hba->host->host_lock, flags);
8278 if (clk_state_changed)
8279 trace_ufshcd_profile_clk_gating(dev_name(hba->dev),
8280 (on ? "on" : "off"),
8281 ktime_to_us(ktime_sub(ktime_get(), start)), ret);
8285 static int ufshcd_init_clocks(struct ufs_hba *hba)
8288 struct ufs_clk_info *clki;
8289 struct device *dev = hba->dev;
8290 struct list_head *head = &hba->clk_list_head;
8292 if (list_empty(head))
8295 list_for_each_entry(clki, head, list) {
8299 clki->clk = devm_clk_get(dev, clki->name);
8300 if (IS_ERR(clki->clk)) {
8301 ret = PTR_ERR(clki->clk);
8302 dev_err(dev, "%s: %s clk get failed, %d\n",
8303 __func__, clki->name, ret);
8308 * Parse device ref clk freq as per device tree "ref_clk".
8309 * Default dev_ref_clk_freq is set to REF_CLK_FREQ_INVAL
8310 * in ufshcd_alloc_host().
8312 if (!strcmp(clki->name, "ref_clk"))
8313 ufshcd_parse_dev_ref_clk_freq(hba, clki->clk);
8315 if (clki->max_freq) {
8316 ret = clk_set_rate(clki->clk, clki->max_freq);
8318 dev_err(hba->dev, "%s: %s clk set rate(%dHz) failed, %d\n",
8319 __func__, clki->name,
8320 clki->max_freq, ret);
8323 clki->curr_freq = clki->max_freq;
8325 dev_dbg(dev, "%s: clk: %s, rate: %lu\n", __func__,
8326 clki->name, clk_get_rate(clki->clk));
8332 static int ufshcd_variant_hba_init(struct ufs_hba *hba)
8339 err = ufshcd_vops_init(hba);
8341 dev_err(hba->dev, "%s: variant %s init failed err %d\n",
8342 __func__, ufshcd_get_var_name(hba), err);
8347 static void ufshcd_variant_hba_exit(struct ufs_hba *hba)
8352 ufshcd_vops_exit(hba);
8355 static int ufshcd_hba_init(struct ufs_hba *hba)
8360 * Handle host controller power separately from the UFS device power
8361 * rails as it will help controlling the UFS host controller power
8362 * collapse easily which is different than UFS device power collapse.
8363 * Also, enable the host controller power before we go ahead with rest
8364 * of the initialization here.
8366 err = ufshcd_init_hba_vreg(hba);
8370 err = ufshcd_setup_hba_vreg(hba, true);
8374 err = ufshcd_init_clocks(hba);
8376 goto out_disable_hba_vreg;
8378 err = ufshcd_setup_clocks(hba, true);
8380 goto out_disable_hba_vreg;
8382 err = ufshcd_init_vreg(hba);
8384 goto out_disable_clks;
8386 err = ufshcd_setup_vreg(hba, true);
8388 goto out_disable_clks;
8390 err = ufshcd_variant_hba_init(hba);
8392 goto out_disable_vreg;
8394 ufs_debugfs_hba_init(hba);
8396 hba->is_powered = true;
8400 ufshcd_setup_vreg(hba, false);
8402 ufshcd_setup_clocks(hba, false);
8403 out_disable_hba_vreg:
8404 ufshcd_setup_hba_vreg(hba, false);
8409 static void ufshcd_hba_exit(struct ufs_hba *hba)
8411 if (hba->is_powered) {
8412 ufshcd_exit_clk_scaling(hba);
8413 ufshcd_exit_clk_gating(hba);
8415 destroy_workqueue(hba->eh_wq);
8416 ufs_debugfs_hba_exit(hba);
8417 ufshcd_variant_hba_exit(hba);
8418 ufshcd_setup_vreg(hba, false);
8419 ufshcd_setup_clocks(hba, false);
8420 ufshcd_setup_hba_vreg(hba, false);
8421 hba->is_powered = false;
8422 ufs_put_device_desc(hba);
8427 ufshcd_send_request_sense(struct ufs_hba *hba, struct scsi_device *sdp)
8429 unsigned char cmd[6] = {REQUEST_SENSE,
8438 buffer = kzalloc(UFS_SENSE_SIZE, GFP_KERNEL);
8444 ret = scsi_execute(sdp, cmd, DMA_FROM_DEVICE, buffer,
8445 UFS_SENSE_SIZE, NULL, NULL,
8446 msecs_to_jiffies(1000), 3, 0, RQF_PM, NULL);
8448 pr_err("%s: failed with err %d\n", __func__, ret);
8456 * ufshcd_set_dev_pwr_mode - sends START STOP UNIT command to set device
8458 * @hba: per adapter instance
8459 * @pwr_mode: device power mode to set
8461 * Returns 0 if requested power mode is set successfully
8462 * Returns non-zero if failed to set the requested power mode
8464 static int ufshcd_set_dev_pwr_mode(struct ufs_hba *hba,
8465 enum ufs_dev_pwr_mode pwr_mode)
8467 unsigned char cmd[6] = { START_STOP };
8468 struct scsi_sense_hdr sshdr;
8469 struct scsi_device *sdp;
8470 unsigned long flags;
8473 spin_lock_irqsave(hba->host->host_lock, flags);
8474 sdp = hba->sdev_ufs_device;
8476 ret = scsi_device_get(sdp);
8477 if (!ret && !scsi_device_online(sdp)) {
8479 scsi_device_put(sdp);
8484 spin_unlock_irqrestore(hba->host->host_lock, flags);
8490 * If scsi commands fail, the scsi mid-layer schedules scsi error-
8491 * handling, which would wait for host to be resumed. Since we know
8492 * we are functional while we are here, skip host resume in error
8495 hba->host->eh_noresume = 1;
8496 ufshcd_clear_ua_wluns(hba);
8498 cmd[4] = pwr_mode << 4;
8501 * Current function would be generally called from the power management
8502 * callbacks hence set the RQF_PM flag so that it doesn't resume the
8503 * already suspended childs.
8505 ret = scsi_execute(sdp, cmd, DMA_NONE, NULL, 0, NULL, &sshdr,
8506 START_STOP_TIMEOUT, 0, 0, RQF_PM, NULL);
8508 sdev_printk(KERN_WARNING, sdp,
8509 "START_STOP failed for power mode: %d, result %x\n",
8511 if (driver_byte(ret) == DRIVER_SENSE)
8512 scsi_print_sense_hdr(sdp, NULL, &sshdr);
8516 hba->curr_dev_pwr_mode = pwr_mode;
8518 scsi_device_put(sdp);
8519 hba->host->eh_noresume = 0;
8523 static int ufshcd_link_state_transition(struct ufs_hba *hba,
8524 enum uic_link_state req_link_state,
8525 int check_for_bkops)
8529 if (req_link_state == hba->uic_link_state)
8532 if (req_link_state == UIC_LINK_HIBERN8_STATE) {
8533 ret = ufshcd_uic_hibern8_enter(hba);
8535 ufshcd_set_link_hibern8(hba);
8537 dev_err(hba->dev, "%s: hibern8 enter failed %d\n",
8543 * If autobkops is enabled, link can't be turned off because
8544 * turning off the link would also turn off the device, except in the
8545 * case of DeepSleep where the device is expected to remain powered.
8547 else if ((req_link_state == UIC_LINK_OFF_STATE) &&
8548 (!check_for_bkops || !hba->auto_bkops_enabled)) {
8550 * Let's make sure that link is in low power mode, we are doing
8551 * this currently by putting the link in Hibern8. Otherway to
8552 * put the link in low power mode is to send the DME end point
8553 * to device and then send the DME reset command to local
8554 * unipro. But putting the link in hibern8 is much faster.
8556 * Note also that putting the link in Hibern8 is a requirement
8557 * for entering DeepSleep.
8559 ret = ufshcd_uic_hibern8_enter(hba);
8561 dev_err(hba->dev, "%s: hibern8 enter failed %d\n",
8566 * Change controller state to "reset state" which
8567 * should also put the link in off/reset state
8569 ufshcd_hba_stop(hba);
8571 * TODO: Check if we need any delay to make sure that
8572 * controller is reset
8574 ufshcd_set_link_off(hba);
8581 static void ufshcd_vreg_set_lpm(struct ufs_hba *hba)
8583 bool vcc_off = false;
8586 * It seems some UFS devices may keep drawing more than sleep current
8587 * (atleast for 500us) from UFS rails (especially from VCCQ rail).
8588 * To avoid this situation, add 2ms delay before putting these UFS
8589 * rails in LPM mode.
8591 if (!ufshcd_is_link_active(hba) &&
8592 hba->dev_quirks & UFS_DEVICE_QUIRK_DELAY_BEFORE_LPM)
8593 usleep_range(2000, 2100);
8596 * If UFS device is either in UFS_Sleep turn off VCC rail to save some
8599 * If UFS device and link is in OFF state, all power supplies (VCC,
8600 * VCCQ, VCCQ2) can be turned off if power on write protect is not
8601 * required. If UFS link is inactive (Hibern8 or OFF state) and device
8602 * is in sleep state, put VCCQ & VCCQ2 rails in LPM mode.
8604 * Ignore the error returned by ufshcd_toggle_vreg() as device is anyway
8605 * in low power state which would save some power.
8607 * If Write Booster is enabled and the device needs to flush the WB
8608 * buffer OR if bkops status is urgent for WB, keep Vcc on.
8610 if (ufshcd_is_ufs_dev_poweroff(hba) && ufshcd_is_link_off(hba) &&
8611 !hba->dev_info.is_lu_power_on_wp) {
8612 ufshcd_setup_vreg(hba, false);
8614 } else if (!ufshcd_is_ufs_dev_active(hba)) {
8615 ufshcd_toggle_vreg(hba->dev, hba->vreg_info.vcc, false);
8617 if (!ufshcd_is_link_active(hba)) {
8618 ufshcd_config_vreg_lpm(hba, hba->vreg_info.vccq);
8619 ufshcd_config_vreg_lpm(hba, hba->vreg_info.vccq2);
8624 * Some UFS devices require delay after VCC power rail is turned-off.
8626 if (vcc_off && hba->vreg_info.vcc &&
8627 hba->dev_quirks & UFS_DEVICE_QUIRK_DELAY_AFTER_LPM)
8628 usleep_range(5000, 5100);
8631 static int ufshcd_vreg_set_hpm(struct ufs_hba *hba)
8635 if (ufshcd_is_ufs_dev_poweroff(hba) && ufshcd_is_link_off(hba) &&
8636 !hba->dev_info.is_lu_power_on_wp) {
8637 ret = ufshcd_setup_vreg(hba, true);
8638 } else if (!ufshcd_is_ufs_dev_active(hba)) {
8639 if (!ret && !ufshcd_is_link_active(hba)) {
8640 ret = ufshcd_config_vreg_hpm(hba, hba->vreg_info.vccq);
8643 ret = ufshcd_config_vreg_hpm(hba, hba->vreg_info.vccq2);
8647 ret = ufshcd_toggle_vreg(hba->dev, hba->vreg_info.vcc, true);
8652 ufshcd_config_vreg_lpm(hba, hba->vreg_info.vccq);
8654 ufshcd_toggle_vreg(hba->dev, hba->vreg_info.vcc, false);
8659 static void ufshcd_hba_vreg_set_lpm(struct ufs_hba *hba)
8661 if (ufshcd_is_link_off(hba) || ufshcd_can_aggressive_pc(hba))
8662 ufshcd_setup_hba_vreg(hba, false);
8665 static void ufshcd_hba_vreg_set_hpm(struct ufs_hba *hba)
8667 if (ufshcd_is_link_off(hba) || ufshcd_can_aggressive_pc(hba))
8668 ufshcd_setup_hba_vreg(hba, true);
8672 * ufshcd_suspend - helper function for suspend operations
8673 * @hba: per adapter instance
8674 * @pm_op: desired low power operation type
8676 * This function will try to put the UFS device and link into low power
8677 * mode based on the "rpm_lvl" (Runtime PM level) or "spm_lvl"
8678 * (System PM level).
8680 * If this function is called during shutdown, it will make sure that
8681 * both UFS device and UFS link is powered off.
8683 * NOTE: UFS device & link must be active before we enter in this function.
8685 * Returns 0 for success and non-zero for failure
8687 static int ufshcd_suspend(struct ufs_hba *hba, enum ufs_pm_op pm_op)
8690 int check_for_bkops;
8691 enum ufs_pm_level pm_lvl;
8692 enum ufs_dev_pwr_mode req_dev_pwr_mode;
8693 enum uic_link_state req_link_state;
8695 hba->pm_op_in_progress = 1;
8696 if (!ufshcd_is_shutdown_pm(pm_op)) {
8697 pm_lvl = ufshcd_is_runtime_pm(pm_op) ?
8698 hba->rpm_lvl : hba->spm_lvl;
8699 req_dev_pwr_mode = ufs_get_pm_lvl_to_dev_pwr_mode(pm_lvl);
8700 req_link_state = ufs_get_pm_lvl_to_link_pwr_state(pm_lvl);
8702 req_dev_pwr_mode = UFS_POWERDOWN_PWR_MODE;
8703 req_link_state = UIC_LINK_OFF_STATE;
8707 * If we can't transition into any of the low power modes
8708 * just gate the clocks.
8710 ufshcd_hold(hba, false);
8711 hba->clk_gating.is_suspended = true;
8713 if (ufshcd_is_clkscaling_supported(hba))
8714 ufshcd_clk_scaling_suspend(hba, true);
8716 if (req_dev_pwr_mode == UFS_ACTIVE_PWR_MODE &&
8717 req_link_state == UIC_LINK_ACTIVE_STATE) {
8721 if ((req_dev_pwr_mode == hba->curr_dev_pwr_mode) &&
8722 (req_link_state == hba->uic_link_state))
8725 /* UFS device & link must be active before we enter in this function */
8726 if (!ufshcd_is_ufs_dev_active(hba) || !ufshcd_is_link_active(hba)) {
8731 if (ufshcd_is_runtime_pm(pm_op)) {
8732 if (ufshcd_can_autobkops_during_suspend(hba)) {
8734 * The device is idle with no requests in the queue,
8735 * allow background operations if bkops status shows
8736 * that performance might be impacted.
8738 ret = ufshcd_urgent_bkops(hba);
8742 /* make sure that auto bkops is disabled */
8743 ufshcd_disable_auto_bkops(hba);
8746 * If device needs to do BKOP or WB buffer flush during
8747 * Hibern8, keep device power mode as "active power mode"
8750 hba->dev_info.b_rpm_dev_flush_capable =
8751 hba->auto_bkops_enabled ||
8752 (((req_link_state == UIC_LINK_HIBERN8_STATE) ||
8753 ((req_link_state == UIC_LINK_ACTIVE_STATE) &&
8754 ufshcd_is_auto_hibern8_enabled(hba))) &&
8755 ufshcd_wb_need_flush(hba));
8758 flush_work(&hba->eeh_work);
8760 if (req_dev_pwr_mode != hba->curr_dev_pwr_mode) {
8761 if (!ufshcd_is_runtime_pm(pm_op))
8762 /* ensure that bkops is disabled */
8763 ufshcd_disable_auto_bkops(hba);
8765 if (!hba->dev_info.b_rpm_dev_flush_capable) {
8766 ret = ufshcd_set_dev_pwr_mode(hba, req_dev_pwr_mode);
8773 * In the case of DeepSleep, the device is expected to remain powered
8774 * with the link off, so do not check for bkops.
8776 check_for_bkops = !ufshcd_is_ufs_dev_deepsleep(hba);
8777 ret = ufshcd_link_state_transition(hba, req_link_state, check_for_bkops);
8779 goto set_dev_active;
8783 * Call vendor specific suspend callback. As these callbacks may access
8784 * vendor specific host controller register space call them before the
8785 * host clocks are ON.
8787 ret = ufshcd_vops_suspend(hba, pm_op);
8789 goto set_link_active;
8791 * Disable the host irq as host controller as there won't be any
8792 * host controller transaction expected till resume.
8794 ufshcd_disable_irq(hba);
8796 ufshcd_setup_clocks(hba, false);
8798 if (ufshcd_is_clkgating_allowed(hba)) {
8799 hba->clk_gating.state = CLKS_OFF;
8800 trace_ufshcd_clk_gating(dev_name(hba->dev),
8801 hba->clk_gating.state);
8804 ufshcd_vreg_set_lpm(hba);
8806 /* Put the host controller in low power mode if possible */
8807 ufshcd_hba_vreg_set_lpm(hba);
8811 ufshcd_vreg_set_hpm(hba);
8813 * Device hardware reset is required to exit DeepSleep. Also, for
8814 * DeepSleep, the link is off so host reset and restore will be done
8817 if (ufshcd_is_ufs_dev_deepsleep(hba)) {
8818 ufshcd_device_reset(hba);
8819 WARN_ON(!ufshcd_is_link_off(hba));
8821 if (ufshcd_is_link_hibern8(hba) && !ufshcd_uic_hibern8_exit(hba))
8822 ufshcd_set_link_active(hba);
8823 else if (ufshcd_is_link_off(hba))
8824 ufshcd_host_reset_and_restore(hba);
8826 /* Can also get here needing to exit DeepSleep */
8827 if (ufshcd_is_ufs_dev_deepsleep(hba)) {
8828 ufshcd_device_reset(hba);
8829 ufshcd_host_reset_and_restore(hba);
8831 if (!ufshcd_set_dev_pwr_mode(hba, UFS_ACTIVE_PWR_MODE))
8832 ufshcd_disable_auto_bkops(hba);
8834 if (ufshcd_is_clkscaling_supported(hba))
8835 ufshcd_clk_scaling_suspend(hba, false);
8837 hba->clk_gating.is_suspended = false;
8838 hba->dev_info.b_rpm_dev_flush_capable = false;
8839 ufshcd_clear_ua_wluns(hba);
8840 ufshcd_release(hba);
8842 if (hba->dev_info.b_rpm_dev_flush_capable) {
8843 schedule_delayed_work(&hba->rpm_dev_flush_recheck_work,
8844 msecs_to_jiffies(RPM_DEV_FLUSH_RECHECK_WORK_DELAY_MS));
8847 hba->pm_op_in_progress = 0;
8850 ufshcd_update_evt_hist(hba, UFS_EVT_SUSPEND_ERR, (u32)ret);
8855 * ufshcd_resume - helper function for resume operations
8856 * @hba: per adapter instance
8857 * @pm_op: runtime PM or system PM
8859 * This function basically brings the UFS device, UniPro link and controller
8862 * Returns 0 for success and non-zero for failure
8864 static int ufshcd_resume(struct ufs_hba *hba, enum ufs_pm_op pm_op)
8867 enum uic_link_state old_link_state;
8869 hba->pm_op_in_progress = 1;
8870 old_link_state = hba->uic_link_state;
8872 ufshcd_hba_vreg_set_hpm(hba);
8873 ret = ufshcd_vreg_set_hpm(hba);
8877 /* Make sure clocks are enabled before accessing controller */
8878 ret = ufshcd_setup_clocks(hba, true);
8882 /* enable the host irq as host controller would be active soon */
8883 ufshcd_enable_irq(hba);
8886 * Call vendor specific resume callback. As these callbacks may access
8887 * vendor specific host controller register space call them when the
8888 * host clocks are ON.
8890 ret = ufshcd_vops_resume(hba, pm_op);
8892 goto disable_irq_and_vops_clks;
8894 /* For DeepSleep, the only supported option is to have the link off */
8895 WARN_ON(ufshcd_is_ufs_dev_deepsleep(hba) && !ufshcd_is_link_off(hba));
8897 if (ufshcd_is_link_hibern8(hba)) {
8898 ret = ufshcd_uic_hibern8_exit(hba);
8900 ufshcd_set_link_active(hba);
8902 dev_err(hba->dev, "%s: hibern8 exit failed %d\n",
8904 goto vendor_suspend;
8906 } else if (ufshcd_is_link_off(hba)) {
8908 * A full initialization of the host and the device is
8909 * required since the link was put to off during suspend.
8910 * Note, in the case of DeepSleep, the device will exit
8911 * DeepSleep due to device reset.
8913 ret = ufshcd_reset_and_restore(hba);
8915 * ufshcd_reset_and_restore() should have already
8916 * set the link state as active
8918 if (ret || !ufshcd_is_link_active(hba))
8919 goto vendor_suspend;
8922 if (!ufshcd_is_ufs_dev_active(hba)) {
8923 ret = ufshcd_set_dev_pwr_mode(hba, UFS_ACTIVE_PWR_MODE);
8925 goto set_old_link_state;
8928 if (ufshcd_keep_autobkops_enabled_except_suspend(hba))
8929 ufshcd_enable_auto_bkops(hba);
8932 * If BKOPs operations are urgently needed at this moment then
8933 * keep auto-bkops enabled or else disable it.
8935 ufshcd_urgent_bkops(hba);
8937 if (hba->ee_usr_mask)
8938 ufshcd_write_ee_control(hba);
8940 hba->clk_gating.is_suspended = false;
8942 if (ufshcd_is_clkscaling_supported(hba))
8943 ufshcd_clk_scaling_suspend(hba, false);
8945 /* Enable Auto-Hibernate if configured */
8946 ufshcd_auto_hibern8_enable(hba);
8948 if (hba->dev_info.b_rpm_dev_flush_capable) {
8949 hba->dev_info.b_rpm_dev_flush_capable = false;
8950 cancel_delayed_work(&hba->rpm_dev_flush_recheck_work);
8953 ufshcd_clear_ua_wluns(hba);
8955 /* Schedule clock gating in case of no access to UFS device yet */
8956 ufshcd_release(hba);
8961 ufshcd_link_state_transition(hba, old_link_state, 0);
8963 ufshcd_vops_suspend(hba, pm_op);
8964 disable_irq_and_vops_clks:
8965 ufshcd_disable_irq(hba);
8966 ufshcd_setup_clocks(hba, false);
8967 if (ufshcd_is_clkgating_allowed(hba)) {
8968 hba->clk_gating.state = CLKS_OFF;
8969 trace_ufshcd_clk_gating(dev_name(hba->dev),
8970 hba->clk_gating.state);
8973 ufshcd_vreg_set_lpm(hba);
8975 hba->pm_op_in_progress = 0;
8977 ufshcd_update_evt_hist(hba, UFS_EVT_RESUME_ERR, (u32)ret);
8982 * ufshcd_system_suspend - system suspend routine
8983 * @hba: per adapter instance
8985 * Check the description of ufshcd_suspend() function for more details.
8987 * Returns 0 for success and non-zero for failure
8989 int ufshcd_system_suspend(struct ufs_hba *hba)
8992 ktime_t start = ktime_get();
8995 early_suspend = true;
8999 down(&hba->host_sem);
9001 if (!hba->is_powered)
9004 if ((ufs_get_pm_lvl_to_dev_pwr_mode(hba->spm_lvl) ==
9005 hba->curr_dev_pwr_mode) &&
9006 (ufs_get_pm_lvl_to_link_pwr_state(hba->spm_lvl) ==
9007 hba->uic_link_state) &&
9008 !hba->dev_info.b_rpm_dev_flush_capable)
9011 if (pm_runtime_suspended(hba->dev)) {
9013 * UFS device and/or UFS link low power states during runtime
9014 * suspend seems to be different than what is expected during
9015 * system suspend. Hence runtime resume the devic & link and
9016 * let the system suspend low power states to take effect.
9017 * TODO: If resume takes longer time, we might have optimize
9018 * it in future by not resuming everything if possible.
9020 ret = ufshcd_runtime_resume(hba);
9025 ret = ufshcd_suspend(hba, UFS_SYSTEM_PM);
9027 trace_ufshcd_system_suspend(dev_name(hba->dev), ret,
9028 ktime_to_us(ktime_sub(ktime_get(), start)),
9029 hba->curr_dev_pwr_mode, hba->uic_link_state);
9031 hba->is_sys_suspended = true;
9036 EXPORT_SYMBOL(ufshcd_system_suspend);
9039 * ufshcd_system_resume - system resume routine
9040 * @hba: per adapter instance
9042 * Returns 0 for success and non-zero for failure
9045 int ufshcd_system_resume(struct ufs_hba *hba)
9048 ktime_t start = ktime_get();
9053 if (unlikely(early_suspend)) {
9054 early_suspend = false;
9055 down(&hba->host_sem);
9058 if (!hba->is_powered || pm_runtime_suspended(hba->dev))
9060 * Let the runtime resume take care of resuming
9061 * if runtime suspended.
9065 ret = ufshcd_resume(hba, UFS_SYSTEM_PM);
9067 trace_ufshcd_system_resume(dev_name(hba->dev), ret,
9068 ktime_to_us(ktime_sub(ktime_get(), start)),
9069 hba->curr_dev_pwr_mode, hba->uic_link_state);
9071 hba->is_sys_suspended = false;
9075 EXPORT_SYMBOL(ufshcd_system_resume);
9078 * ufshcd_runtime_suspend - runtime suspend routine
9079 * @hba: per adapter instance
9081 * Check the description of ufshcd_suspend() function for more details.
9083 * Returns 0 for success and non-zero for failure
9085 int ufshcd_runtime_suspend(struct ufs_hba *hba)
9088 ktime_t start = ktime_get();
9093 if (!hba->is_powered)
9096 ret = ufshcd_suspend(hba, UFS_RUNTIME_PM);
9098 trace_ufshcd_runtime_suspend(dev_name(hba->dev), ret,
9099 ktime_to_us(ktime_sub(ktime_get(), start)),
9100 hba->curr_dev_pwr_mode, hba->uic_link_state);
9103 EXPORT_SYMBOL(ufshcd_runtime_suspend);
9106 * ufshcd_runtime_resume - runtime resume routine
9107 * @hba: per adapter instance
9109 * This function basically brings the UFS device, UniPro link and controller
9110 * to active state. Following operations are done in this function:
9112 * 1. Turn on all the controller related clocks
9113 * 2. Bring the UniPro link out of Hibernate state
9114 * 3. If UFS device is in sleep state, turn ON VCC rail and bring the UFS device
9116 * 4. If auto-bkops is enabled on the device, disable it.
9118 * So following would be the possible power state after this function return
9120 * S1: UFS device in Active state with VCC rail ON
9121 * UniPro link in Active state
9122 * All the UFS/UniPro controller clocks are ON
9124 * Returns 0 for success and non-zero for failure
9126 int ufshcd_runtime_resume(struct ufs_hba *hba)
9129 ktime_t start = ktime_get();
9134 if (!hba->is_powered)
9137 ret = ufshcd_resume(hba, UFS_RUNTIME_PM);
9139 trace_ufshcd_runtime_resume(dev_name(hba->dev), ret,
9140 ktime_to_us(ktime_sub(ktime_get(), start)),
9141 hba->curr_dev_pwr_mode, hba->uic_link_state);
9144 EXPORT_SYMBOL(ufshcd_runtime_resume);
9146 int ufshcd_runtime_idle(struct ufs_hba *hba)
9150 EXPORT_SYMBOL(ufshcd_runtime_idle);
9153 * ufshcd_shutdown - shutdown routine
9154 * @hba: per adapter instance
9156 * This function would power off both UFS device and UFS link.
9158 * Returns 0 always to allow force shutdown even in case of errors.
9160 int ufshcd_shutdown(struct ufs_hba *hba)
9164 down(&hba->host_sem);
9165 hba->shutting_down = true;
9168 if (!hba->is_powered)
9171 if (ufshcd_is_ufs_dev_poweroff(hba) && ufshcd_is_link_off(hba))
9174 pm_runtime_get_sync(hba->dev);
9176 ret = ufshcd_suspend(hba, UFS_SHUTDOWN_PM);
9179 dev_err(hba->dev, "%s failed, err %d\n", __func__, ret);
9180 hba->is_powered = false;
9181 /* allow force shutdown even in case of errors */
9184 EXPORT_SYMBOL(ufshcd_shutdown);
9187 * ufshcd_remove - de-allocate SCSI host and host memory space
9188 * data structure memory
9189 * @hba: per adapter instance
9191 void ufshcd_remove(struct ufs_hba *hba)
9193 ufs_bsg_remove(hba);
9194 ufs_sysfs_remove_nodes(hba->dev);
9195 blk_cleanup_queue(hba->tmf_queue);
9196 blk_mq_free_tag_set(&hba->tmf_tag_set);
9197 blk_cleanup_queue(hba->cmd_queue);
9198 scsi_remove_host(hba->host);
9199 /* disable interrupts */
9200 ufshcd_disable_intr(hba, hba->intr_mask);
9201 ufshcd_hba_stop(hba);
9202 ufshcd_hba_exit(hba);
9204 EXPORT_SYMBOL_GPL(ufshcd_remove);
9207 * ufshcd_dealloc_host - deallocate Host Bus Adapter (HBA)
9208 * @hba: pointer to Host Bus Adapter (HBA)
9210 void ufshcd_dealloc_host(struct ufs_hba *hba)
9212 scsi_host_put(hba->host);
9214 EXPORT_SYMBOL_GPL(ufshcd_dealloc_host);
9217 * ufshcd_set_dma_mask - Set dma mask based on the controller
9218 * addressing capability
9219 * @hba: per adapter instance
9221 * Returns 0 for success, non-zero for failure
9223 static int ufshcd_set_dma_mask(struct ufs_hba *hba)
9225 if (hba->capabilities & MASK_64_ADDRESSING_SUPPORT) {
9226 if (!dma_set_mask_and_coherent(hba->dev, DMA_BIT_MASK(64)))
9229 return dma_set_mask_and_coherent(hba->dev, DMA_BIT_MASK(32));
9233 * ufshcd_alloc_host - allocate Host Bus Adapter (HBA)
9234 * @dev: pointer to device handle
9235 * @hba_handle: driver private handle
9236 * Returns 0 on success, non-zero value on failure
9238 int ufshcd_alloc_host(struct device *dev, struct ufs_hba **hba_handle)
9240 struct Scsi_Host *host;
9241 struct ufs_hba *hba;
9246 "Invalid memory reference for dev is NULL\n");
9251 host = scsi_host_alloc(&ufshcd_driver_template,
9252 sizeof(struct ufs_hba));
9254 dev_err(dev, "scsi_host_alloc failed\n");
9258 hba = shost_priv(host);
9262 hba->dev_ref_clk_freq = REF_CLK_FREQ_INVAL;
9264 INIT_LIST_HEAD(&hba->clk_list_head);
9269 EXPORT_SYMBOL(ufshcd_alloc_host);
9271 /* This function exists because blk_mq_alloc_tag_set() requires this. */
9272 static blk_status_t ufshcd_queue_tmf(struct blk_mq_hw_ctx *hctx,
9273 const struct blk_mq_queue_data *qd)
9276 return BLK_STS_NOTSUPP;
9279 static const struct blk_mq_ops ufshcd_tmf_ops = {
9280 .queue_rq = ufshcd_queue_tmf,
9284 * ufshcd_init - Driver initialization routine
9285 * @hba: per-adapter instance
9286 * @mmio_base: base register address
9287 * @irq: Interrupt line of device
9288 * Returns 0 on success, non-zero value on failure
9290 int ufshcd_init(struct ufs_hba *hba, void __iomem *mmio_base, unsigned int irq)
9293 struct Scsi_Host *host = hba->host;
9294 struct device *dev = hba->dev;
9295 char eh_wq_name[sizeof("ufs_eh_wq_00")];
9299 "Invalid memory reference for mmio_base is NULL\n");
9304 hba->mmio_base = mmio_base;
9306 hba->vps = &ufs_hba_vps;
9308 err = ufshcd_hba_init(hba);
9312 /* Read capabilities registers */
9313 err = ufshcd_hba_capabilities(hba);
9317 /* Get UFS version supported by the controller */
9318 hba->ufs_version = ufshcd_get_ufs_version(hba);
9320 if ((hba->ufs_version != UFSHCI_VERSION_10) &&
9321 (hba->ufs_version != UFSHCI_VERSION_11) &&
9322 (hba->ufs_version != UFSHCI_VERSION_20) &&
9323 (hba->ufs_version != UFSHCI_VERSION_21))
9324 dev_err(hba->dev, "invalid UFS version 0x%x\n",
9327 /* Get Interrupt bit mask per version */
9328 hba->intr_mask = ufshcd_get_intr_mask(hba);
9330 err = ufshcd_set_dma_mask(hba);
9332 dev_err(hba->dev, "set dma mask failed\n");
9336 /* Allocate memory for host memory space */
9337 err = ufshcd_memory_alloc(hba);
9339 dev_err(hba->dev, "Memory allocation failed\n");
9344 ufshcd_host_memory_configure(hba);
9346 host->can_queue = hba->nutrs;
9347 host->cmd_per_lun = hba->nutrs;
9348 host->max_id = UFSHCD_MAX_ID;
9349 host->max_lun = UFS_MAX_LUNS;
9350 host->max_channel = UFSHCD_MAX_CHANNEL;
9351 host->unique_id = host->host_no;
9352 host->max_cmd_len = UFS_CDB_SIZE;
9354 hba->max_pwr_info.is_valid = false;
9356 /* Initialize work queues */
9357 snprintf(eh_wq_name, sizeof(eh_wq_name), "ufs_eh_wq_%d",
9358 hba->host->host_no);
9359 hba->eh_wq = create_singlethread_workqueue(eh_wq_name);
9361 dev_err(hba->dev, "%s: failed to create eh workqueue\n",
9366 INIT_WORK(&hba->eh_work, ufshcd_err_handler);
9367 INIT_WORK(&hba->eeh_work, ufshcd_exception_event_handler);
9369 sema_init(&hba->host_sem, 1);
9371 /* Initialize UIC command mutex */
9372 mutex_init(&hba->uic_cmd_mutex);
9374 /* Initialize mutex for device management commands */
9375 mutex_init(&hba->dev_cmd.lock);
9377 /* Initialize mutex for exception event control */
9378 mutex_init(&hba->ee_ctrl_mutex);
9380 init_rwsem(&hba->clk_scaling_lock);
9382 ufshcd_init_clk_gating(hba);
9384 ufshcd_init_clk_scaling(hba);
9387 * In order to avoid any spurious interrupt immediately after
9388 * registering UFS controller interrupt handler, clear any pending UFS
9389 * interrupt status and disable all the UFS interrupts.
9391 ufshcd_writel(hba, ufshcd_readl(hba, REG_INTERRUPT_STATUS),
9392 REG_INTERRUPT_STATUS);
9393 ufshcd_writel(hba, 0, REG_INTERRUPT_ENABLE);
9395 * Make sure that UFS interrupts are disabled and any pending interrupt
9396 * status is cleared before registering UFS interrupt handler.
9400 /* IRQ registration */
9401 err = devm_request_irq(dev, irq, ufshcd_intr, IRQF_SHARED, UFSHCD, hba);
9403 dev_err(hba->dev, "request irq failed\n");
9406 hba->is_irq_enabled = true;
9409 err = scsi_add_host(host, hba->dev);
9411 dev_err(hba->dev, "scsi_add_host failed\n");
9415 hba->cmd_queue = blk_mq_init_queue(&hba->host->tag_set);
9416 if (IS_ERR(hba->cmd_queue)) {
9417 err = PTR_ERR(hba->cmd_queue);
9418 goto out_remove_scsi_host;
9421 hba->tmf_tag_set = (struct blk_mq_tag_set) {
9423 .queue_depth = hba->nutmrs,
9424 .ops = &ufshcd_tmf_ops,
9425 .flags = BLK_MQ_F_NO_SCHED,
9427 err = blk_mq_alloc_tag_set(&hba->tmf_tag_set);
9429 goto free_cmd_queue;
9430 hba->tmf_queue = blk_mq_init_queue(&hba->tmf_tag_set);
9431 if (IS_ERR(hba->tmf_queue)) {
9432 err = PTR_ERR(hba->tmf_queue);
9433 goto free_tmf_tag_set;
9436 /* Reset the attached device */
9437 ufshcd_device_reset(hba);
9439 ufshcd_init_crypto(hba);
9441 /* Host controller enable */
9442 err = ufshcd_hba_enable(hba);
9444 dev_err(hba->dev, "Host controller enable failed\n");
9445 ufshcd_print_evt_hist(hba);
9446 ufshcd_print_host_state(hba);
9447 goto free_tmf_queue;
9451 * Set the default power management level for runtime and system PM.
9452 * Default power saving mode is to keep UFS link in Hibern8 state
9453 * and UFS device in sleep state.
9455 hba->rpm_lvl = ufs_get_desired_pm_lvl_for_dev_link_state(
9457 UIC_LINK_HIBERN8_STATE);
9458 hba->spm_lvl = ufs_get_desired_pm_lvl_for_dev_link_state(
9460 UIC_LINK_HIBERN8_STATE);
9462 INIT_DELAYED_WORK(&hba->rpm_dev_flush_recheck_work,
9463 ufshcd_rpm_dev_flush_recheck_work);
9465 /* Set the default auto-hiberate idle timer value to 150 ms */
9466 if (ufshcd_is_auto_hibern8_supported(hba) && !hba->ahit) {
9467 hba->ahit = FIELD_PREP(UFSHCI_AHIBERN8_TIMER_MASK, 150) |
9468 FIELD_PREP(UFSHCI_AHIBERN8_SCALE_MASK, 3);
9471 /* Hold auto suspend until async scan completes */
9472 pm_runtime_get_sync(dev);
9473 atomic_set(&hba->scsi_block_reqs_cnt, 0);
9475 * We are assuming that device wasn't put in sleep/power-down
9476 * state exclusively during the boot stage before kernel.
9477 * This assumption helps avoid doing link startup twice during
9478 * ufshcd_probe_hba().
9480 ufshcd_set_ufs_dev_active(hba);
9482 async_schedule(ufshcd_async_scan, hba);
9483 ufs_sysfs_add_nodes(hba->dev);
9488 blk_cleanup_queue(hba->tmf_queue);
9490 blk_mq_free_tag_set(&hba->tmf_tag_set);
9492 blk_cleanup_queue(hba->cmd_queue);
9493 out_remove_scsi_host:
9494 scsi_remove_host(hba->host);
9496 hba->is_irq_enabled = false;
9497 ufshcd_hba_exit(hba);
9501 EXPORT_SYMBOL_GPL(ufshcd_init);
9503 static int __init ufshcd_core_init(void)
9509 static void __exit ufshcd_core_exit(void)
9514 module_init(ufshcd_core_init);
9515 module_exit(ufshcd_core_exit);
9517 MODULE_AUTHOR("Santosh Yaragnavi <santosh.sy@samsung.com>");
9518 MODULE_AUTHOR("Vinayak Holikatti <h.vinayak@samsung.com>");
9519 MODULE_DESCRIPTION("Generic UFS host controller driver Core");
9520 MODULE_LICENSE("GPL");
9521 MODULE_VERSION(UFSHCD_DRIVER_VERSION);