1 // SPDX-License-Identifier: GPL-2.0-or-later
3 * Universal Flash Storage Host controller driver Core
4 * Copyright (C) 2011-2013 Samsung India Software Operations
5 * Copyright (c) 2013-2016, The Linux Foundation. All rights reserved.
8 * Santosh Yaraganavi <santosh.sy@samsung.com>
9 * Vinayak Holikatti <h.vinayak@samsung.com>
12 #include <linux/async.h>
13 #include <linux/devfreq.h>
14 #include <linux/nls.h>
16 #include <linux/bitfield.h>
17 #include <linux/blk-pm.h>
18 #include <linux/blkdev.h>
20 #include "ufs_quirks.h"
22 #include "ufs-sysfs.h"
24 #include "ufshcd-crypto.h"
25 #include <asm/unaligned.h>
26 #include <linux/blkdev.h>
28 #define CREATE_TRACE_POINTS
29 #include <trace/events/ufs.h>
31 #define UFSHCD_ENABLE_INTRS (UTP_TRANSFER_REQ_COMPL |\
34 /* UIC command timeout, unit: ms */
35 #define UIC_CMD_TIMEOUT 500
37 /* NOP OUT retries waiting for NOP IN response */
38 #define NOP_OUT_RETRIES 10
39 /* Timeout after 50 msecs if NOP OUT hangs without response */
40 #define NOP_OUT_TIMEOUT 50 /* msecs */
42 /* Query request retries */
43 #define QUERY_REQ_RETRIES 3
44 /* Query request timeout */
45 #define QUERY_REQ_TIMEOUT 1500 /* 1.5 seconds */
47 /* Task management command timeout */
48 #define TM_CMD_TIMEOUT 100 /* msecs */
50 /* maximum number of retries for a general UIC command */
51 #define UFS_UIC_COMMAND_RETRIES 3
53 /* maximum number of link-startup retries */
54 #define DME_LINKSTARTUP_RETRIES 3
56 /* Maximum retries for Hibern8 enter */
57 #define UIC_HIBERN8_ENTER_RETRIES 3
59 /* maximum number of reset retries before giving up */
60 #define MAX_HOST_RESET_RETRIES 5
62 /* Expose the flag value from utp_upiu_query.value */
63 #define MASK_QUERY_UPIU_FLAG_LOC 0xFF
65 /* Interrupt aggregation default timeout, unit: 40us */
66 #define INT_AGGR_DEF_TO 0x02
68 /* default delay of autosuspend: 2000 ms */
69 #define RPM_AUTOSUSPEND_DELAY_MS 2000
71 /* Default delay of RPM device flush delayed work */
72 #define RPM_DEV_FLUSH_RECHECK_WORK_DELAY_MS 5000
74 /* Default value of wait time before gating device ref clock */
75 #define UFSHCD_REF_CLK_GATING_WAIT_US 0xFF /* microsecs */
77 /* Polling time to wait for fDeviceInit */
78 #define FDEVICEINIT_COMPL_TIMEOUT 1500 /* millisecs */
80 #define ufshcd_toggle_vreg(_dev, _vreg, _on) \
84 _ret = ufshcd_enable_vreg(_dev, _vreg); \
86 _ret = ufshcd_disable_vreg(_dev, _vreg); \
90 #define ufshcd_hex_dump(prefix_str, buf, len) do { \
91 size_t __len = (len); \
92 print_hex_dump(KERN_ERR, prefix_str, \
93 __len > 4 ? DUMP_PREFIX_OFFSET : DUMP_PREFIX_NONE,\
94 16, 4, buf, __len, false); \
97 int ufshcd_dump_regs(struct ufs_hba *hba, size_t offset, size_t len,
103 if (offset % 4 != 0 || len % 4 != 0) /* keep readl happy */
106 regs = kzalloc(len, GFP_ATOMIC);
110 for (pos = 0; pos < len; pos += 4)
111 regs[pos / 4] = ufshcd_readl(hba, offset + pos);
113 ufshcd_hex_dump(prefix, regs, len);
118 EXPORT_SYMBOL_GPL(ufshcd_dump_regs);
121 UFSHCD_MAX_CHANNEL = 0,
123 UFSHCD_CMD_PER_LUN = 32,
124 UFSHCD_CAN_QUEUE = 32,
131 UFSHCD_STATE_OPERATIONAL,
132 UFSHCD_STATE_EH_SCHEDULED_FATAL,
133 UFSHCD_STATE_EH_SCHEDULED_NON_FATAL,
136 /* UFSHCD error handling flags */
138 UFSHCD_EH_IN_PROGRESS = (1 << 0),
141 /* UFSHCD UIC layer error flags */
143 UFSHCD_UIC_DL_PA_INIT_ERROR = (1 << 0), /* Data link layer error */
144 UFSHCD_UIC_DL_NAC_RECEIVED_ERROR = (1 << 1), /* Data link layer error */
145 UFSHCD_UIC_DL_TCx_REPLAY_ERROR = (1 << 2), /* Data link layer error */
146 UFSHCD_UIC_NL_ERROR = (1 << 3), /* Network layer error */
147 UFSHCD_UIC_TL_ERROR = (1 << 4), /* Transport Layer error */
148 UFSHCD_UIC_DME_ERROR = (1 << 5), /* DME error */
149 UFSHCD_UIC_PA_GENERIC_ERROR = (1 << 6), /* Generic PA error */
152 #define ufshcd_set_eh_in_progress(h) \
153 ((h)->eh_flags |= UFSHCD_EH_IN_PROGRESS)
154 #define ufshcd_eh_in_progress(h) \
155 ((h)->eh_flags & UFSHCD_EH_IN_PROGRESS)
156 #define ufshcd_clear_eh_in_progress(h) \
157 ((h)->eh_flags &= ~UFSHCD_EH_IN_PROGRESS)
159 struct ufs_pm_lvl_states ufs_pm_lvl_states[] = {
160 {UFS_ACTIVE_PWR_MODE, UIC_LINK_ACTIVE_STATE},
161 {UFS_ACTIVE_PWR_MODE, UIC_LINK_HIBERN8_STATE},
162 {UFS_SLEEP_PWR_MODE, UIC_LINK_ACTIVE_STATE},
163 {UFS_SLEEP_PWR_MODE, UIC_LINK_HIBERN8_STATE},
164 {UFS_POWERDOWN_PWR_MODE, UIC_LINK_HIBERN8_STATE},
165 {UFS_POWERDOWN_PWR_MODE, UIC_LINK_OFF_STATE},
167 * For DeepSleep, the link is first put in hibern8 and then off.
168 * Leaving the link in hibern8 is not supported.
170 {UFS_DEEPSLEEP_PWR_MODE, UIC_LINK_OFF_STATE},
173 static inline enum ufs_dev_pwr_mode
174 ufs_get_pm_lvl_to_dev_pwr_mode(enum ufs_pm_level lvl)
176 return ufs_pm_lvl_states[lvl].dev_state;
179 static inline enum uic_link_state
180 ufs_get_pm_lvl_to_link_pwr_state(enum ufs_pm_level lvl)
182 return ufs_pm_lvl_states[lvl].link_state;
185 static inline enum ufs_pm_level
186 ufs_get_desired_pm_lvl_for_dev_link_state(enum ufs_dev_pwr_mode dev_state,
187 enum uic_link_state link_state)
189 enum ufs_pm_level lvl;
191 for (lvl = UFS_PM_LVL_0; lvl < UFS_PM_LVL_MAX; lvl++) {
192 if ((ufs_pm_lvl_states[lvl].dev_state == dev_state) &&
193 (ufs_pm_lvl_states[lvl].link_state == link_state))
197 /* if no match found, return the level 0 */
201 static struct ufs_dev_fix ufs_fixups[] = {
202 /* UFS cards deviations table */
203 UFS_FIX(UFS_VENDOR_MICRON, UFS_ANY_MODEL,
204 UFS_DEVICE_QUIRK_DELAY_BEFORE_LPM),
205 UFS_FIX(UFS_VENDOR_SAMSUNG, UFS_ANY_MODEL,
206 UFS_DEVICE_QUIRK_DELAY_BEFORE_LPM |
207 UFS_DEVICE_QUIRK_HOST_PA_TACTIVATE |
208 UFS_DEVICE_QUIRK_RECOVERY_FROM_DL_NAC_ERRORS),
209 UFS_FIX(UFS_VENDOR_SKHYNIX, UFS_ANY_MODEL,
210 UFS_DEVICE_QUIRK_HOST_PA_SAVECONFIGTIME),
211 UFS_FIX(UFS_VENDOR_SKHYNIX, "hB8aL1" /*H28U62301AMR*/,
212 UFS_DEVICE_QUIRK_HOST_VS_DEBUGSAVECONFIGTIME),
213 UFS_FIX(UFS_VENDOR_TOSHIBA, UFS_ANY_MODEL,
214 UFS_DEVICE_QUIRK_DELAY_BEFORE_LPM),
215 UFS_FIX(UFS_VENDOR_TOSHIBA, "THGLF2G9C8KBADG",
216 UFS_DEVICE_QUIRK_PA_TACTIVATE),
217 UFS_FIX(UFS_VENDOR_TOSHIBA, "THGLF2G9D8KBADG",
218 UFS_DEVICE_QUIRK_PA_TACTIVATE),
222 static irqreturn_t ufshcd_tmc_handler(struct ufs_hba *hba);
223 static void ufshcd_async_scan(void *data, async_cookie_t cookie);
224 static int ufshcd_reset_and_restore(struct ufs_hba *hba);
225 static int ufshcd_eh_host_reset_handler(struct scsi_cmnd *cmd);
226 static int ufshcd_clear_tm_cmd(struct ufs_hba *hba, int tag);
227 static void ufshcd_hba_exit(struct ufs_hba *hba);
228 static int ufshcd_clear_ua_wluns(struct ufs_hba *hba);
229 static int ufshcd_probe_hba(struct ufs_hba *hba, bool async);
230 static int ufshcd_setup_clocks(struct ufs_hba *hba, bool on);
231 static int ufshcd_uic_hibern8_enter(struct ufs_hba *hba);
232 static inline void ufshcd_add_delay_before_dme_cmd(struct ufs_hba *hba);
233 static int ufshcd_host_reset_and_restore(struct ufs_hba *hba);
234 static void ufshcd_resume_clkscaling(struct ufs_hba *hba);
235 static void ufshcd_suspend_clkscaling(struct ufs_hba *hba);
236 static void __ufshcd_suspend_clkscaling(struct ufs_hba *hba);
237 static int ufshcd_scale_clks(struct ufs_hba *hba, bool scale_up);
238 static irqreturn_t ufshcd_intr(int irq, void *__hba);
239 static int ufshcd_change_power_mode(struct ufs_hba *hba,
240 struct ufs_pa_layer_attr *pwr_mode);
241 static void ufshcd_schedule_eh_work(struct ufs_hba *hba);
242 static int ufshcd_setup_hba_vreg(struct ufs_hba *hba, bool on);
243 static int ufshcd_setup_vreg(struct ufs_hba *hba, bool on);
244 static inline int ufshcd_config_vreg_hpm(struct ufs_hba *hba,
245 struct ufs_vreg *vreg);
246 static int ufshcd_try_to_abort_task(struct ufs_hba *hba, int tag);
247 static int ufshcd_wb_buf_flush_enable(struct ufs_hba *hba);
248 static int ufshcd_wb_buf_flush_disable(struct ufs_hba *hba);
249 static int ufshcd_wb_ctrl(struct ufs_hba *hba, bool enable);
250 static int ufshcd_wb_toggle_flush_during_h8(struct ufs_hba *hba, bool set);
251 static inline void ufshcd_wb_toggle_flush(struct ufs_hba *hba, bool enable);
252 static void ufshcd_hba_vreg_set_lpm(struct ufs_hba *hba);
253 static void ufshcd_hba_vreg_set_hpm(struct ufs_hba *hba);
255 static inline bool ufshcd_valid_tag(struct ufs_hba *hba, int tag)
257 return tag >= 0 && tag < hba->nutrs;
260 static inline void ufshcd_enable_irq(struct ufs_hba *hba)
262 if (!hba->is_irq_enabled) {
263 enable_irq(hba->irq);
264 hba->is_irq_enabled = true;
268 static inline void ufshcd_disable_irq(struct ufs_hba *hba)
270 if (hba->is_irq_enabled) {
271 disable_irq(hba->irq);
272 hba->is_irq_enabled = false;
276 static inline void ufshcd_wb_config(struct ufs_hba *hba)
280 if (!ufshcd_is_wb_allowed(hba))
283 ret = ufshcd_wb_ctrl(hba, true);
285 dev_err(hba->dev, "%s: Enable WB failed: %d\n", __func__, ret);
287 dev_info(hba->dev, "%s: Write Booster Configured\n", __func__);
288 ret = ufshcd_wb_toggle_flush_during_h8(hba, true);
290 dev_err(hba->dev, "%s: En WB flush during H8: failed: %d\n",
292 if (!(hba->quirks & UFSHCI_QUIRK_SKIP_MANUAL_WB_FLUSH_CTRL))
293 ufshcd_wb_toggle_flush(hba, true);
296 static void ufshcd_scsi_unblock_requests(struct ufs_hba *hba)
298 if (atomic_dec_and_test(&hba->scsi_block_reqs_cnt))
299 scsi_unblock_requests(hba->host);
302 static void ufshcd_scsi_block_requests(struct ufs_hba *hba)
304 if (atomic_inc_return(&hba->scsi_block_reqs_cnt) == 1)
305 scsi_block_requests(hba->host);
308 static void ufshcd_add_cmd_upiu_trace(struct ufs_hba *hba, unsigned int tag,
311 struct utp_upiu_req *rq = hba->lrb[tag].ucd_req_ptr;
313 trace_ufshcd_upiu(dev_name(hba->dev), str, &rq->header, &rq->sc.cdb);
316 static void ufshcd_add_query_upiu_trace(struct ufs_hba *hba, unsigned int tag,
319 struct utp_upiu_req *rq = hba->lrb[tag].ucd_req_ptr;
321 trace_ufshcd_upiu(dev_name(hba->dev), str, &rq->header, &rq->qr);
324 static void ufshcd_add_tm_upiu_trace(struct ufs_hba *hba, unsigned int tag,
327 int off = (int)tag - hba->nutrs;
328 struct utp_task_req_desc *descp = &hba->utmrdl_base_addr[off];
330 trace_ufshcd_upiu(dev_name(hba->dev), str, &descp->req_header,
331 &descp->input_param1);
334 static void ufshcd_add_uic_command_trace(struct ufs_hba *hba,
335 struct uic_command *ucmd,
340 if (!trace_ufshcd_uic_command_enabled())
343 if (!strcmp(str, "send"))
346 cmd = ufshcd_readl(hba, REG_UIC_COMMAND);
348 trace_ufshcd_uic_command(dev_name(hba->dev), str, cmd,
349 ufshcd_readl(hba, REG_UIC_COMMAND_ARG_1),
350 ufshcd_readl(hba, REG_UIC_COMMAND_ARG_2),
351 ufshcd_readl(hba, REG_UIC_COMMAND_ARG_3));
354 static void ufshcd_add_command_trace(struct ufs_hba *hba,
355 unsigned int tag, const char *str)
358 u8 opcode = 0, group_id = 0;
360 struct ufshcd_lrb *lrbp = &hba->lrb[tag];
361 struct scsi_cmnd *cmd = lrbp->cmd;
362 int transfer_len = -1;
364 if (!trace_ufshcd_command_enabled()) {
365 /* trace UPIU W/O tracing command */
367 ufshcd_add_cmd_upiu_trace(hba, tag, str);
371 if (cmd) { /* data phase exists */
372 /* trace UPIU also */
373 ufshcd_add_cmd_upiu_trace(hba, tag, str);
374 opcode = cmd->cmnd[0];
375 if ((opcode == READ_10) || (opcode == WRITE_10)) {
377 * Currently we only fully trace read(10) and write(10)
380 if (cmd->request && cmd->request->bio)
381 lba = cmd->request->bio->bi_iter.bi_sector;
382 transfer_len = be32_to_cpu(
383 lrbp->ucd_req_ptr->sc.exp_data_transfer_len);
384 if (opcode == WRITE_10)
385 group_id = lrbp->cmd->cmnd[6];
386 } else if (opcode == UNMAP) {
388 lba = scsi_get_lba(cmd);
389 transfer_len = blk_rq_bytes(cmd->request);
394 intr = ufshcd_readl(hba, REG_INTERRUPT_STATUS);
395 doorbell = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
396 trace_ufshcd_command(dev_name(hba->dev), str, tag,
397 doorbell, transfer_len, intr, lba, opcode, group_id);
400 static void ufshcd_print_clk_freqs(struct ufs_hba *hba)
402 struct ufs_clk_info *clki;
403 struct list_head *head = &hba->clk_list_head;
405 if (list_empty(head))
408 list_for_each_entry(clki, head, list) {
409 if (!IS_ERR_OR_NULL(clki->clk) && clki->min_freq &&
411 dev_err(hba->dev, "clk: %s, rate: %u\n",
412 clki->name, clki->curr_freq);
416 static void ufshcd_print_evt(struct ufs_hba *hba, u32 id,
421 struct ufs_event_hist *e;
423 if (id >= UFS_EVT_CNT)
426 e = &hba->ufs_stats.event[id];
428 for (i = 0; i < UFS_EVENT_HIST_LENGTH; i++) {
429 int p = (i + e->pos) % UFS_EVENT_HIST_LENGTH;
431 if (e->tstamp[p] == 0)
433 dev_err(hba->dev, "%s[%d] = 0x%x at %lld us\n", err_name, p,
434 e->val[p], ktime_to_us(e->tstamp[p]));
439 dev_err(hba->dev, "No record of %s\n", err_name);
442 static void ufshcd_print_evt_hist(struct ufs_hba *hba)
444 ufshcd_dump_regs(hba, 0, UFSHCI_REG_SPACE_SIZE, "host_regs: ");
446 ufshcd_print_evt(hba, UFS_EVT_PA_ERR, "pa_err");
447 ufshcd_print_evt(hba, UFS_EVT_DL_ERR, "dl_err");
448 ufshcd_print_evt(hba, UFS_EVT_NL_ERR, "nl_err");
449 ufshcd_print_evt(hba, UFS_EVT_TL_ERR, "tl_err");
450 ufshcd_print_evt(hba, UFS_EVT_DME_ERR, "dme_err");
451 ufshcd_print_evt(hba, UFS_EVT_AUTO_HIBERN8_ERR,
453 ufshcd_print_evt(hba, UFS_EVT_FATAL_ERR, "fatal_err");
454 ufshcd_print_evt(hba, UFS_EVT_LINK_STARTUP_FAIL,
455 "link_startup_fail");
456 ufshcd_print_evt(hba, UFS_EVT_RESUME_ERR, "resume_fail");
457 ufshcd_print_evt(hba, UFS_EVT_SUSPEND_ERR,
459 ufshcd_print_evt(hba, UFS_EVT_DEV_RESET, "dev_reset");
460 ufshcd_print_evt(hba, UFS_EVT_HOST_RESET, "host_reset");
461 ufshcd_print_evt(hba, UFS_EVT_ABORT, "task_abort");
463 ufshcd_vops_dbg_register_dump(hba);
467 void ufshcd_print_trs(struct ufs_hba *hba, unsigned long bitmap, bool pr_prdt)
469 struct ufshcd_lrb *lrbp;
473 for_each_set_bit(tag, &bitmap, hba->nutrs) {
474 lrbp = &hba->lrb[tag];
476 dev_err(hba->dev, "UPIU[%d] - issue time %lld us\n",
477 tag, ktime_to_us(lrbp->issue_time_stamp));
478 dev_err(hba->dev, "UPIU[%d] - complete time %lld us\n",
479 tag, ktime_to_us(lrbp->compl_time_stamp));
481 "UPIU[%d] - Transfer Request Descriptor phys@0x%llx\n",
482 tag, (u64)lrbp->utrd_dma_addr);
484 ufshcd_hex_dump("UPIU TRD: ", lrbp->utr_descriptor_ptr,
485 sizeof(struct utp_transfer_req_desc));
486 dev_err(hba->dev, "UPIU[%d] - Request UPIU phys@0x%llx\n", tag,
487 (u64)lrbp->ucd_req_dma_addr);
488 ufshcd_hex_dump("UPIU REQ: ", lrbp->ucd_req_ptr,
489 sizeof(struct utp_upiu_req));
490 dev_err(hba->dev, "UPIU[%d] - Response UPIU phys@0x%llx\n", tag,
491 (u64)lrbp->ucd_rsp_dma_addr);
492 ufshcd_hex_dump("UPIU RSP: ", lrbp->ucd_rsp_ptr,
493 sizeof(struct utp_upiu_rsp));
495 prdt_length = le16_to_cpu(
496 lrbp->utr_descriptor_ptr->prd_table_length);
497 if (hba->quirks & UFSHCD_QUIRK_PRDT_BYTE_GRAN)
498 prdt_length /= sizeof(struct ufshcd_sg_entry);
501 "UPIU[%d] - PRDT - %d entries phys@0x%llx\n",
503 (u64)lrbp->ucd_prdt_dma_addr);
506 ufshcd_hex_dump("UPIU PRDT: ", lrbp->ucd_prdt_ptr,
507 sizeof(struct ufshcd_sg_entry) * prdt_length);
511 static void ufshcd_print_tmrs(struct ufs_hba *hba, unsigned long bitmap)
515 for_each_set_bit(tag, &bitmap, hba->nutmrs) {
516 struct utp_task_req_desc *tmrdp = &hba->utmrdl_base_addr[tag];
518 dev_err(hba->dev, "TM[%d] - Task Management Header\n", tag);
519 ufshcd_hex_dump("", tmrdp, sizeof(*tmrdp));
523 static void ufshcd_print_host_state(struct ufs_hba *hba)
525 struct scsi_device *sdev_ufs = hba->sdev_ufs_device;
527 dev_err(hba->dev, "UFS Host state=%d\n", hba->ufshcd_state);
528 dev_err(hba->dev, "outstanding reqs=0x%lx tasks=0x%lx\n",
529 hba->outstanding_reqs, hba->outstanding_tasks);
530 dev_err(hba->dev, "saved_err=0x%x, saved_uic_err=0x%x\n",
531 hba->saved_err, hba->saved_uic_err);
532 dev_err(hba->dev, "Device power mode=%d, UIC link state=%d\n",
533 hba->curr_dev_pwr_mode, hba->uic_link_state);
534 dev_err(hba->dev, "PM in progress=%d, sys. suspended=%d\n",
535 hba->pm_op_in_progress, hba->is_sys_suspended);
536 dev_err(hba->dev, "Auto BKOPS=%d, Host self-block=%d\n",
537 hba->auto_bkops_enabled, hba->host->host_self_blocked);
538 dev_err(hba->dev, "Clk gate=%d\n", hba->clk_gating.state);
540 "last_hibern8_exit_tstamp at %lld us, hibern8_exit_cnt=%d\n",
541 ktime_to_us(hba->ufs_stats.last_hibern8_exit_tstamp),
542 hba->ufs_stats.hibern8_exit_cnt);
543 dev_err(hba->dev, "last intr at %lld us, last intr status=0x%x\n",
544 ktime_to_us(hba->ufs_stats.last_intr_ts),
545 hba->ufs_stats.last_intr_status);
546 dev_err(hba->dev, "error handling flags=0x%x, req. abort count=%d\n",
547 hba->eh_flags, hba->req_abort_count);
548 dev_err(hba->dev, "hba->ufs_version=0x%x, Host capabilities=0x%x, caps=0x%x\n",
549 hba->ufs_version, hba->capabilities, hba->caps);
550 dev_err(hba->dev, "quirks=0x%x, dev. quirks=0x%x\n", hba->quirks,
553 dev_err(hba->dev, "UFS dev info: %.8s %.16s rev %.4s\n",
554 sdev_ufs->vendor, sdev_ufs->model, sdev_ufs->rev);
556 ufshcd_print_clk_freqs(hba);
560 * ufshcd_print_pwr_info - print power params as saved in hba
562 * @hba: per-adapter instance
564 static void ufshcd_print_pwr_info(struct ufs_hba *hba)
566 static const char * const names[] = {
576 dev_err(hba->dev, "%s:[RX, TX]: gear=[%d, %d], lane[%d, %d], pwr[%s, %s], rate = %d\n",
578 hba->pwr_info.gear_rx, hba->pwr_info.gear_tx,
579 hba->pwr_info.lane_rx, hba->pwr_info.lane_tx,
580 names[hba->pwr_info.pwr_rx],
581 names[hba->pwr_info.pwr_tx],
582 hba->pwr_info.hs_rate);
585 static void ufshcd_device_reset(struct ufs_hba *hba)
589 err = ufshcd_vops_device_reset(hba);
592 ufshcd_set_ufs_dev_active(hba);
593 if (ufshcd_is_wb_allowed(hba)) {
594 hba->wb_enabled = false;
595 hba->wb_buf_flush_enabled = false;
598 if (err != -EOPNOTSUPP)
599 ufshcd_update_evt_hist(hba, UFS_EVT_DEV_RESET, err);
602 void ufshcd_delay_us(unsigned long us, unsigned long tolerance)
610 usleep_range(us, us + tolerance);
612 EXPORT_SYMBOL_GPL(ufshcd_delay_us);
615 * ufshcd_wait_for_register - wait for register value to change
616 * @hba: per-adapter interface
617 * @reg: mmio register offset
618 * @mask: mask to apply to the read register value
619 * @val: value to wait for
620 * @interval_us: polling interval in microseconds
621 * @timeout_ms: timeout in milliseconds
624 * -ETIMEDOUT on error, zero on success.
626 int ufshcd_wait_for_register(struct ufs_hba *hba, u32 reg, u32 mask,
627 u32 val, unsigned long interval_us,
628 unsigned long timeout_ms)
631 unsigned long timeout = jiffies + msecs_to_jiffies(timeout_ms);
633 /* ignore bits that we don't intend to wait on */
636 while ((ufshcd_readl(hba, reg) & mask) != val) {
637 usleep_range(interval_us, interval_us + 50);
638 if (time_after(jiffies, timeout)) {
639 if ((ufshcd_readl(hba, reg) & mask) != val)
649 * ufshcd_get_intr_mask - Get the interrupt bit mask
650 * @hba: Pointer to adapter instance
652 * Returns interrupt bit mask per version
654 static inline u32 ufshcd_get_intr_mask(struct ufs_hba *hba)
658 switch (hba->ufs_version) {
659 case UFSHCI_VERSION_10:
660 intr_mask = INTERRUPT_MASK_ALL_VER_10;
662 case UFSHCI_VERSION_11:
663 case UFSHCI_VERSION_20:
664 intr_mask = INTERRUPT_MASK_ALL_VER_11;
666 case UFSHCI_VERSION_21:
668 intr_mask = INTERRUPT_MASK_ALL_VER_21;
676 * ufshcd_get_ufs_version - Get the UFS version supported by the HBA
677 * @hba: Pointer to adapter instance
679 * Returns UFSHCI version supported by the controller
681 static inline u32 ufshcd_get_ufs_version(struct ufs_hba *hba)
683 if (hba->quirks & UFSHCD_QUIRK_BROKEN_UFS_HCI_VERSION)
684 return ufshcd_vops_get_ufs_hci_version(hba);
686 return ufshcd_readl(hba, REG_UFS_VERSION);
690 * ufshcd_is_device_present - Check if any device connected to
691 * the host controller
692 * @hba: pointer to adapter instance
694 * Returns true if device present, false if no device detected
696 static inline bool ufshcd_is_device_present(struct ufs_hba *hba)
698 return (ufshcd_readl(hba, REG_CONTROLLER_STATUS) &
699 DEVICE_PRESENT) ? true : false;
703 * ufshcd_get_tr_ocs - Get the UTRD Overall Command Status
704 * @lrbp: pointer to local command reference block
706 * This function is used to get the OCS field from UTRD
707 * Returns the OCS field in the UTRD
709 static inline int ufshcd_get_tr_ocs(struct ufshcd_lrb *lrbp)
711 return le32_to_cpu(lrbp->utr_descriptor_ptr->header.dword_2) & MASK_OCS;
715 * ufshcd_utrl_clear - Clear a bit in UTRLCLR register
716 * @hba: per adapter instance
717 * @pos: position of the bit to be cleared
719 static inline void ufshcd_utrl_clear(struct ufs_hba *hba, u32 pos)
721 if (hba->quirks & UFSHCI_QUIRK_BROKEN_REQ_LIST_CLR)
722 ufshcd_writel(hba, (1 << pos), REG_UTP_TRANSFER_REQ_LIST_CLEAR);
724 ufshcd_writel(hba, ~(1 << pos),
725 REG_UTP_TRANSFER_REQ_LIST_CLEAR);
729 * ufshcd_utmrl_clear - Clear a bit in UTRMLCLR register
730 * @hba: per adapter instance
731 * @pos: position of the bit to be cleared
733 static inline void ufshcd_utmrl_clear(struct ufs_hba *hba, u32 pos)
735 if (hba->quirks & UFSHCI_QUIRK_BROKEN_REQ_LIST_CLR)
736 ufshcd_writel(hba, (1 << pos), REG_UTP_TASK_REQ_LIST_CLEAR);
738 ufshcd_writel(hba, ~(1 << pos), REG_UTP_TASK_REQ_LIST_CLEAR);
742 * ufshcd_outstanding_req_clear - Clear a bit in outstanding request field
743 * @hba: per adapter instance
744 * @tag: position of the bit to be cleared
746 static inline void ufshcd_outstanding_req_clear(struct ufs_hba *hba, int tag)
748 __clear_bit(tag, &hba->outstanding_reqs);
752 * ufshcd_get_lists_status - Check UCRDY, UTRLRDY and UTMRLRDY
753 * @reg: Register value of host controller status
755 * Returns integer, 0 on Success and positive value if failed
757 static inline int ufshcd_get_lists_status(u32 reg)
759 return !((reg & UFSHCD_STATUS_READY) == UFSHCD_STATUS_READY);
763 * ufshcd_get_uic_cmd_result - Get the UIC command result
764 * @hba: Pointer to adapter instance
766 * This function gets the result of UIC command completion
767 * Returns 0 on success, non zero value on error
769 static inline int ufshcd_get_uic_cmd_result(struct ufs_hba *hba)
771 return ufshcd_readl(hba, REG_UIC_COMMAND_ARG_2) &
772 MASK_UIC_COMMAND_RESULT;
776 * ufshcd_get_dme_attr_val - Get the value of attribute returned by UIC command
777 * @hba: Pointer to adapter instance
779 * This function gets UIC command argument3
780 * Returns 0 on success, non zero value on error
782 static inline u32 ufshcd_get_dme_attr_val(struct ufs_hba *hba)
784 return ufshcd_readl(hba, REG_UIC_COMMAND_ARG_3);
788 * ufshcd_get_req_rsp - returns the TR response transaction type
789 * @ucd_rsp_ptr: pointer to response UPIU
792 ufshcd_get_req_rsp(struct utp_upiu_rsp *ucd_rsp_ptr)
794 return be32_to_cpu(ucd_rsp_ptr->header.dword_0) >> 24;
798 * ufshcd_get_rsp_upiu_result - Get the result from response UPIU
799 * @ucd_rsp_ptr: pointer to response UPIU
801 * This function gets the response status and scsi_status from response UPIU
802 * Returns the response result code.
805 ufshcd_get_rsp_upiu_result(struct utp_upiu_rsp *ucd_rsp_ptr)
807 return be32_to_cpu(ucd_rsp_ptr->header.dword_1) & MASK_RSP_UPIU_RESULT;
811 * ufshcd_get_rsp_upiu_data_seg_len - Get the data segment length
813 * @ucd_rsp_ptr: pointer to response UPIU
815 * Return the data segment length.
817 static inline unsigned int
818 ufshcd_get_rsp_upiu_data_seg_len(struct utp_upiu_rsp *ucd_rsp_ptr)
820 return be32_to_cpu(ucd_rsp_ptr->header.dword_2) &
821 MASK_RSP_UPIU_DATA_SEG_LEN;
825 * ufshcd_is_exception_event - Check if the device raised an exception event
826 * @ucd_rsp_ptr: pointer to response UPIU
828 * The function checks if the device raised an exception event indicated in
829 * the Device Information field of response UPIU.
831 * Returns true if exception is raised, false otherwise.
833 static inline bool ufshcd_is_exception_event(struct utp_upiu_rsp *ucd_rsp_ptr)
835 return be32_to_cpu(ucd_rsp_ptr->header.dword_2) &
836 MASK_RSP_EXCEPTION_EVENT ? true : false;
840 * ufshcd_reset_intr_aggr - Reset interrupt aggregation values.
841 * @hba: per adapter instance
844 ufshcd_reset_intr_aggr(struct ufs_hba *hba)
846 ufshcd_writel(hba, INT_AGGR_ENABLE |
847 INT_AGGR_COUNTER_AND_TIMER_RESET,
848 REG_UTP_TRANSFER_REQ_INT_AGG_CONTROL);
852 * ufshcd_config_intr_aggr - Configure interrupt aggregation values.
853 * @hba: per adapter instance
854 * @cnt: Interrupt aggregation counter threshold
855 * @tmout: Interrupt aggregation timeout value
858 ufshcd_config_intr_aggr(struct ufs_hba *hba, u8 cnt, u8 tmout)
860 ufshcd_writel(hba, INT_AGGR_ENABLE | INT_AGGR_PARAM_WRITE |
861 INT_AGGR_COUNTER_THLD_VAL(cnt) |
862 INT_AGGR_TIMEOUT_VAL(tmout),
863 REG_UTP_TRANSFER_REQ_INT_AGG_CONTROL);
867 * ufshcd_disable_intr_aggr - Disables interrupt aggregation.
868 * @hba: per adapter instance
870 static inline void ufshcd_disable_intr_aggr(struct ufs_hba *hba)
872 ufshcd_writel(hba, 0, REG_UTP_TRANSFER_REQ_INT_AGG_CONTROL);
876 * ufshcd_enable_run_stop_reg - Enable run-stop registers,
877 * When run-stop registers are set to 1, it indicates the
878 * host controller that it can process the requests
879 * @hba: per adapter instance
881 static void ufshcd_enable_run_stop_reg(struct ufs_hba *hba)
883 ufshcd_writel(hba, UTP_TASK_REQ_LIST_RUN_STOP_BIT,
884 REG_UTP_TASK_REQ_LIST_RUN_STOP);
885 ufshcd_writel(hba, UTP_TRANSFER_REQ_LIST_RUN_STOP_BIT,
886 REG_UTP_TRANSFER_REQ_LIST_RUN_STOP);
890 * ufshcd_hba_start - Start controller initialization sequence
891 * @hba: per adapter instance
893 static inline void ufshcd_hba_start(struct ufs_hba *hba)
895 u32 val = CONTROLLER_ENABLE;
897 if (ufshcd_crypto_enable(hba))
898 val |= CRYPTO_GENERAL_ENABLE;
900 ufshcd_writel(hba, val, REG_CONTROLLER_ENABLE);
904 * ufshcd_is_hba_active - Get controller state
905 * @hba: per adapter instance
907 * Returns false if controller is active, true otherwise
909 static inline bool ufshcd_is_hba_active(struct ufs_hba *hba)
911 return (ufshcd_readl(hba, REG_CONTROLLER_ENABLE) & CONTROLLER_ENABLE)
915 u32 ufshcd_get_local_unipro_ver(struct ufs_hba *hba)
917 /* HCI version 1.0 and 1.1 supports UniPro 1.41 */
918 if ((hba->ufs_version == UFSHCI_VERSION_10) ||
919 (hba->ufs_version == UFSHCI_VERSION_11))
920 return UFS_UNIPRO_VER_1_41;
922 return UFS_UNIPRO_VER_1_6;
924 EXPORT_SYMBOL(ufshcd_get_local_unipro_ver);
926 static bool ufshcd_is_unipro_pa_params_tuning_req(struct ufs_hba *hba)
929 * If both host and device support UniPro ver1.6 or later, PA layer
930 * parameters tuning happens during link startup itself.
932 * We can manually tune PA layer parameters if either host or device
933 * doesn't support UniPro ver 1.6 or later. But to keep manual tuning
934 * logic simple, we will only do manual tuning if local unipro version
935 * doesn't support ver1.6 or later.
937 if (ufshcd_get_local_unipro_ver(hba) < UFS_UNIPRO_VER_1_6)
944 * ufshcd_set_clk_freq - set UFS controller clock frequencies
945 * @hba: per adapter instance
946 * @scale_up: If True, set max possible frequency othewise set low frequency
948 * Returns 0 if successful
949 * Returns < 0 for any other errors
951 static int ufshcd_set_clk_freq(struct ufs_hba *hba, bool scale_up)
954 struct ufs_clk_info *clki;
955 struct list_head *head = &hba->clk_list_head;
957 if (list_empty(head))
960 list_for_each_entry(clki, head, list) {
961 if (!IS_ERR_OR_NULL(clki->clk)) {
962 if (scale_up && clki->max_freq) {
963 if (clki->curr_freq == clki->max_freq)
966 ret = clk_set_rate(clki->clk, clki->max_freq);
968 dev_err(hba->dev, "%s: %s clk set rate(%dHz) failed, %d\n",
969 __func__, clki->name,
970 clki->max_freq, ret);
973 trace_ufshcd_clk_scaling(dev_name(hba->dev),
974 "scaled up", clki->name,
978 clki->curr_freq = clki->max_freq;
980 } else if (!scale_up && clki->min_freq) {
981 if (clki->curr_freq == clki->min_freq)
984 ret = clk_set_rate(clki->clk, clki->min_freq);
986 dev_err(hba->dev, "%s: %s clk set rate(%dHz) failed, %d\n",
987 __func__, clki->name,
988 clki->min_freq, ret);
991 trace_ufshcd_clk_scaling(dev_name(hba->dev),
992 "scaled down", clki->name,
995 clki->curr_freq = clki->min_freq;
998 dev_dbg(hba->dev, "%s: clk: %s, rate: %lu\n", __func__,
999 clki->name, clk_get_rate(clki->clk));
1007 * ufshcd_scale_clks - scale up or scale down UFS controller clocks
1008 * @hba: per adapter instance
1009 * @scale_up: True if scaling up and false if scaling down
1011 * Returns 0 if successful
1012 * Returns < 0 for any other errors
1014 static int ufshcd_scale_clks(struct ufs_hba *hba, bool scale_up)
1017 ktime_t start = ktime_get();
1019 ret = ufshcd_vops_clk_scale_notify(hba, scale_up, PRE_CHANGE);
1023 ret = ufshcd_set_clk_freq(hba, scale_up);
1027 ret = ufshcd_vops_clk_scale_notify(hba, scale_up, POST_CHANGE);
1029 ufshcd_set_clk_freq(hba, !scale_up);
1032 trace_ufshcd_profile_clk_scaling(dev_name(hba->dev),
1033 (scale_up ? "up" : "down"),
1034 ktime_to_us(ktime_sub(ktime_get(), start)), ret);
1039 * ufshcd_is_devfreq_scaling_required - check if scaling is required or not
1040 * @hba: per adapter instance
1041 * @scale_up: True if scaling up and false if scaling down
1043 * Returns true if scaling is required, false otherwise.
1045 static bool ufshcd_is_devfreq_scaling_required(struct ufs_hba *hba,
1048 struct ufs_clk_info *clki;
1049 struct list_head *head = &hba->clk_list_head;
1051 if (list_empty(head))
1054 list_for_each_entry(clki, head, list) {
1055 if (!IS_ERR_OR_NULL(clki->clk)) {
1056 if (scale_up && clki->max_freq) {
1057 if (clki->curr_freq == clki->max_freq)
1060 } else if (!scale_up && clki->min_freq) {
1061 if (clki->curr_freq == clki->min_freq)
1071 static int ufshcd_wait_for_doorbell_clr(struct ufs_hba *hba,
1072 u64 wait_timeout_us)
1074 unsigned long flags;
1078 bool timeout = false, do_last_check = false;
1081 ufshcd_hold(hba, false);
1082 spin_lock_irqsave(hba->host->host_lock, flags);
1084 * Wait for all the outstanding tasks/transfer requests.
1085 * Verify by checking the doorbell registers are clear.
1087 start = ktime_get();
1089 if (hba->ufshcd_state != UFSHCD_STATE_OPERATIONAL) {
1094 tm_doorbell = ufshcd_readl(hba, REG_UTP_TASK_REQ_DOOR_BELL);
1095 tr_doorbell = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
1096 if (!tm_doorbell && !tr_doorbell) {
1099 } else if (do_last_check) {
1103 spin_unlock_irqrestore(hba->host->host_lock, flags);
1105 if (ktime_to_us(ktime_sub(ktime_get(), start)) >
1109 * We might have scheduled out for long time so make
1110 * sure to check if doorbells are cleared by this time
1113 do_last_check = true;
1115 spin_lock_irqsave(hba->host->host_lock, flags);
1116 } while (tm_doorbell || tr_doorbell);
1120 "%s: timedout waiting for doorbell to clear (tm=0x%x, tr=0x%x)\n",
1121 __func__, tm_doorbell, tr_doorbell);
1125 spin_unlock_irqrestore(hba->host->host_lock, flags);
1126 ufshcd_release(hba);
1131 * ufshcd_scale_gear - scale up/down UFS gear
1132 * @hba: per adapter instance
1133 * @scale_up: True for scaling up gear and false for scaling down
1135 * Returns 0 for success,
1136 * Returns -EBUSY if scaling can't happen at this time
1137 * Returns non-zero for any other errors
1139 static int ufshcd_scale_gear(struct ufs_hba *hba, bool scale_up)
1142 struct ufs_pa_layer_attr new_pwr_info;
1145 memcpy(&new_pwr_info, &hba->clk_scaling.saved_pwr_info.info,
1146 sizeof(struct ufs_pa_layer_attr));
1148 memcpy(&new_pwr_info, &hba->pwr_info,
1149 sizeof(struct ufs_pa_layer_attr));
1151 if (hba->pwr_info.gear_tx > hba->clk_scaling.min_gear ||
1152 hba->pwr_info.gear_rx > hba->clk_scaling.min_gear) {
1153 /* save the current power mode */
1154 memcpy(&hba->clk_scaling.saved_pwr_info.info,
1156 sizeof(struct ufs_pa_layer_attr));
1158 /* scale down gear */
1159 new_pwr_info.gear_tx = hba->clk_scaling.min_gear;
1160 new_pwr_info.gear_rx = hba->clk_scaling.min_gear;
1164 /* check if the power mode needs to be changed or not? */
1165 ret = ufshcd_config_pwr_mode(hba, &new_pwr_info);
1167 dev_err(hba->dev, "%s: failed err %d, old gear: (tx %d rx %d), new gear: (tx %d rx %d)",
1169 hba->pwr_info.gear_tx, hba->pwr_info.gear_rx,
1170 new_pwr_info.gear_tx, new_pwr_info.gear_rx);
1175 static int ufshcd_clock_scaling_prepare(struct ufs_hba *hba)
1177 #define DOORBELL_CLR_TOUT_US (1000 * 1000) /* 1 sec */
1180 * make sure that there are no outstanding requests when
1181 * clock scaling is in progress
1183 ufshcd_scsi_block_requests(hba);
1184 down_write(&hba->clk_scaling_lock);
1185 if (ufshcd_wait_for_doorbell_clr(hba, DOORBELL_CLR_TOUT_US)) {
1187 up_write(&hba->clk_scaling_lock);
1188 ufshcd_scsi_unblock_requests(hba);
1194 static void ufshcd_clock_scaling_unprepare(struct ufs_hba *hba)
1196 up_write(&hba->clk_scaling_lock);
1197 ufshcd_scsi_unblock_requests(hba);
1201 * ufshcd_devfreq_scale - scale up/down UFS clocks and gear
1202 * @hba: per adapter instance
1203 * @scale_up: True for scaling up and false for scalin down
1205 * Returns 0 for success,
1206 * Returns -EBUSY if scaling can't happen at this time
1207 * Returns non-zero for any other errors
1209 static int ufshcd_devfreq_scale(struct ufs_hba *hba, bool scale_up)
1213 /* let's not get into low power until clock scaling is completed */
1214 ufshcd_hold(hba, false);
1216 ret = ufshcd_clock_scaling_prepare(hba);
1220 /* scale down the gear before scaling down clocks */
1222 ret = ufshcd_scale_gear(hba, false);
1227 ret = ufshcd_scale_clks(hba, scale_up);
1230 ufshcd_scale_gear(hba, true);
1234 /* scale up the gear after scaling up clocks */
1236 ret = ufshcd_scale_gear(hba, true);
1238 ufshcd_scale_clks(hba, false);
1243 /* Enable Write Booster if we have scaled up else disable it */
1244 up_write(&hba->clk_scaling_lock);
1245 ufshcd_wb_ctrl(hba, scale_up);
1246 down_write(&hba->clk_scaling_lock);
1249 ufshcd_clock_scaling_unprepare(hba);
1251 ufshcd_release(hba);
1255 static void ufshcd_clk_scaling_suspend_work(struct work_struct *work)
1257 struct ufs_hba *hba = container_of(work, struct ufs_hba,
1258 clk_scaling.suspend_work);
1259 unsigned long irq_flags;
1261 spin_lock_irqsave(hba->host->host_lock, irq_flags);
1262 if (hba->clk_scaling.active_reqs || hba->clk_scaling.is_suspended) {
1263 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1266 hba->clk_scaling.is_suspended = true;
1267 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1269 __ufshcd_suspend_clkscaling(hba);
1272 static void ufshcd_clk_scaling_resume_work(struct work_struct *work)
1274 struct ufs_hba *hba = container_of(work, struct ufs_hba,
1275 clk_scaling.resume_work);
1276 unsigned long irq_flags;
1278 spin_lock_irqsave(hba->host->host_lock, irq_flags);
1279 if (!hba->clk_scaling.is_suspended) {
1280 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1283 hba->clk_scaling.is_suspended = false;
1284 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1286 devfreq_resume_device(hba->devfreq);
1289 static int ufshcd_devfreq_target(struct device *dev,
1290 unsigned long *freq, u32 flags)
1293 struct ufs_hba *hba = dev_get_drvdata(dev);
1295 bool scale_up, sched_clk_scaling_suspend_work = false;
1296 struct list_head *clk_list = &hba->clk_list_head;
1297 struct ufs_clk_info *clki;
1298 unsigned long irq_flags;
1300 if (!ufshcd_is_clkscaling_supported(hba))
1303 clki = list_first_entry(&hba->clk_list_head, struct ufs_clk_info, list);
1304 /* Override with the closest supported frequency */
1305 *freq = (unsigned long) clk_round_rate(clki->clk, *freq);
1306 spin_lock_irqsave(hba->host->host_lock, irq_flags);
1307 if (ufshcd_eh_in_progress(hba)) {
1308 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1312 if (!hba->clk_scaling.active_reqs)
1313 sched_clk_scaling_suspend_work = true;
1315 if (list_empty(clk_list)) {
1316 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1320 /* Decide based on the rounded-off frequency and update */
1321 scale_up = (*freq == clki->max_freq) ? true : false;
1323 *freq = clki->min_freq;
1324 /* Update the frequency */
1325 if (!ufshcd_is_devfreq_scaling_required(hba, scale_up)) {
1326 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1328 goto out; /* no state change required */
1330 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1332 pm_runtime_get_noresume(hba->dev);
1333 if (!pm_runtime_active(hba->dev)) {
1334 pm_runtime_put_noidle(hba->dev);
1338 start = ktime_get();
1339 ret = ufshcd_devfreq_scale(hba, scale_up);
1340 pm_runtime_put(hba->dev);
1342 trace_ufshcd_profile_clk_scaling(dev_name(hba->dev),
1343 (scale_up ? "up" : "down"),
1344 ktime_to_us(ktime_sub(ktime_get(), start)), ret);
1347 if (sched_clk_scaling_suspend_work)
1348 queue_work(hba->clk_scaling.workq,
1349 &hba->clk_scaling.suspend_work);
1354 static bool ufshcd_is_busy(struct request *req, void *priv, bool reserved)
1358 WARN_ON_ONCE(reserved);
1363 /* Whether or not any tag is in use by a request that is in progress. */
1364 static bool ufshcd_any_tag_in_use(struct ufs_hba *hba)
1366 struct request_queue *q = hba->cmd_queue;
1369 blk_mq_tagset_busy_iter(q->tag_set, ufshcd_is_busy, &busy);
1373 static int ufshcd_devfreq_get_dev_status(struct device *dev,
1374 struct devfreq_dev_status *stat)
1376 struct ufs_hba *hba = dev_get_drvdata(dev);
1377 struct ufs_clk_scaling *scaling = &hba->clk_scaling;
1378 unsigned long flags;
1379 struct list_head *clk_list = &hba->clk_list_head;
1380 struct ufs_clk_info *clki;
1383 if (!ufshcd_is_clkscaling_supported(hba))
1386 memset(stat, 0, sizeof(*stat));
1388 spin_lock_irqsave(hba->host->host_lock, flags);
1389 curr_t = ktime_get();
1390 if (!scaling->window_start_t)
1393 clki = list_first_entry(clk_list, struct ufs_clk_info, list);
1395 * If current frequency is 0, then the ondemand governor considers
1396 * there's no initial frequency set. And it always requests to set
1397 * to max. frequency.
1399 stat->current_frequency = clki->curr_freq;
1400 if (scaling->is_busy_started)
1401 scaling->tot_busy_t += ktime_us_delta(curr_t,
1402 scaling->busy_start_t);
1404 stat->total_time = ktime_us_delta(curr_t, scaling->window_start_t);
1405 stat->busy_time = scaling->tot_busy_t;
1407 scaling->window_start_t = curr_t;
1408 scaling->tot_busy_t = 0;
1410 if (hba->outstanding_reqs) {
1411 scaling->busy_start_t = curr_t;
1412 scaling->is_busy_started = true;
1414 scaling->busy_start_t = 0;
1415 scaling->is_busy_started = false;
1417 spin_unlock_irqrestore(hba->host->host_lock, flags);
1421 static int ufshcd_devfreq_init(struct ufs_hba *hba)
1423 struct list_head *clk_list = &hba->clk_list_head;
1424 struct ufs_clk_info *clki;
1425 struct devfreq *devfreq;
1428 /* Skip devfreq if we don't have any clocks in the list */
1429 if (list_empty(clk_list))
1432 clki = list_first_entry(clk_list, struct ufs_clk_info, list);
1433 dev_pm_opp_add(hba->dev, clki->min_freq, 0);
1434 dev_pm_opp_add(hba->dev, clki->max_freq, 0);
1436 ufshcd_vops_config_scaling_param(hba, &hba->vps->devfreq_profile,
1437 &hba->vps->ondemand_data);
1438 devfreq = devfreq_add_device(hba->dev,
1439 &hba->vps->devfreq_profile,
1440 DEVFREQ_GOV_SIMPLE_ONDEMAND,
1441 &hba->vps->ondemand_data);
1442 if (IS_ERR(devfreq)) {
1443 ret = PTR_ERR(devfreq);
1444 dev_err(hba->dev, "Unable to register with devfreq %d\n", ret);
1446 dev_pm_opp_remove(hba->dev, clki->min_freq);
1447 dev_pm_opp_remove(hba->dev, clki->max_freq);
1451 hba->devfreq = devfreq;
1456 static void ufshcd_devfreq_remove(struct ufs_hba *hba)
1458 struct list_head *clk_list = &hba->clk_list_head;
1459 struct ufs_clk_info *clki;
1464 devfreq_remove_device(hba->devfreq);
1465 hba->devfreq = NULL;
1467 clki = list_first_entry(clk_list, struct ufs_clk_info, list);
1468 dev_pm_opp_remove(hba->dev, clki->min_freq);
1469 dev_pm_opp_remove(hba->dev, clki->max_freq);
1472 static void __ufshcd_suspend_clkscaling(struct ufs_hba *hba)
1474 unsigned long flags;
1476 devfreq_suspend_device(hba->devfreq);
1477 spin_lock_irqsave(hba->host->host_lock, flags);
1478 hba->clk_scaling.window_start_t = 0;
1479 spin_unlock_irqrestore(hba->host->host_lock, flags);
1482 static void ufshcd_suspend_clkscaling(struct ufs_hba *hba)
1484 unsigned long flags;
1485 bool suspend = false;
1487 if (!ufshcd_is_clkscaling_supported(hba))
1490 spin_lock_irqsave(hba->host->host_lock, flags);
1491 if (!hba->clk_scaling.is_suspended) {
1493 hba->clk_scaling.is_suspended = true;
1495 spin_unlock_irqrestore(hba->host->host_lock, flags);
1498 __ufshcd_suspend_clkscaling(hba);
1501 static void ufshcd_resume_clkscaling(struct ufs_hba *hba)
1503 unsigned long flags;
1504 bool resume = false;
1506 if (!ufshcd_is_clkscaling_supported(hba))
1509 spin_lock_irqsave(hba->host->host_lock, flags);
1510 if (hba->clk_scaling.is_suspended) {
1512 hba->clk_scaling.is_suspended = false;
1514 spin_unlock_irqrestore(hba->host->host_lock, flags);
1517 devfreq_resume_device(hba->devfreq);
1520 static ssize_t ufshcd_clkscale_enable_show(struct device *dev,
1521 struct device_attribute *attr, char *buf)
1523 struct ufs_hba *hba = dev_get_drvdata(dev);
1525 return snprintf(buf, PAGE_SIZE, "%d\n", hba->clk_scaling.is_allowed);
1528 static ssize_t ufshcd_clkscale_enable_store(struct device *dev,
1529 struct device_attribute *attr, const char *buf, size_t count)
1531 struct ufs_hba *hba = dev_get_drvdata(dev);
1535 if (kstrtou32(buf, 0, &value))
1539 if (value == hba->clk_scaling.is_allowed)
1542 pm_runtime_get_sync(hba->dev);
1543 ufshcd_hold(hba, false);
1545 cancel_work_sync(&hba->clk_scaling.suspend_work);
1546 cancel_work_sync(&hba->clk_scaling.resume_work);
1548 hba->clk_scaling.is_allowed = value;
1551 ufshcd_resume_clkscaling(hba);
1553 ufshcd_suspend_clkscaling(hba);
1554 err = ufshcd_devfreq_scale(hba, true);
1556 dev_err(hba->dev, "%s: failed to scale clocks up %d\n",
1560 ufshcd_release(hba);
1561 pm_runtime_put_sync(hba->dev);
1566 static void ufshcd_clkscaling_init_sysfs(struct ufs_hba *hba)
1568 hba->clk_scaling.enable_attr.show = ufshcd_clkscale_enable_show;
1569 hba->clk_scaling.enable_attr.store = ufshcd_clkscale_enable_store;
1570 sysfs_attr_init(&hba->clk_scaling.enable_attr.attr);
1571 hba->clk_scaling.enable_attr.attr.name = "clkscale_enable";
1572 hba->clk_scaling.enable_attr.attr.mode = 0644;
1573 if (device_create_file(hba->dev, &hba->clk_scaling.enable_attr))
1574 dev_err(hba->dev, "Failed to create sysfs for clkscale_enable\n");
1577 static void ufshcd_ungate_work(struct work_struct *work)
1580 unsigned long flags;
1581 struct ufs_hba *hba = container_of(work, struct ufs_hba,
1582 clk_gating.ungate_work);
1584 cancel_delayed_work_sync(&hba->clk_gating.gate_work);
1586 spin_lock_irqsave(hba->host->host_lock, flags);
1587 if (hba->clk_gating.state == CLKS_ON) {
1588 spin_unlock_irqrestore(hba->host->host_lock, flags);
1592 spin_unlock_irqrestore(hba->host->host_lock, flags);
1593 ufshcd_hba_vreg_set_hpm(hba);
1594 ufshcd_setup_clocks(hba, true);
1596 ufshcd_enable_irq(hba);
1598 /* Exit from hibern8 */
1599 if (ufshcd_can_hibern8_during_gating(hba)) {
1600 /* Prevent gating in this path */
1601 hba->clk_gating.is_suspended = true;
1602 if (ufshcd_is_link_hibern8(hba)) {
1603 ret = ufshcd_uic_hibern8_exit(hba);
1605 dev_err(hba->dev, "%s: hibern8 exit failed %d\n",
1608 ufshcd_set_link_active(hba);
1610 hba->clk_gating.is_suspended = false;
1613 ufshcd_scsi_unblock_requests(hba);
1617 * ufshcd_hold - Enable clocks that were gated earlier due to ufshcd_release.
1618 * Also, exit from hibern8 mode and set the link as active.
1619 * @hba: per adapter instance
1620 * @async: This indicates whether caller should ungate clocks asynchronously.
1622 int ufshcd_hold(struct ufs_hba *hba, bool async)
1626 unsigned long flags;
1628 if (!ufshcd_is_clkgating_allowed(hba))
1630 spin_lock_irqsave(hba->host->host_lock, flags);
1631 hba->clk_gating.active_reqs++;
1634 switch (hba->clk_gating.state) {
1637 * Wait for the ungate work to complete if in progress.
1638 * Though the clocks may be in ON state, the link could
1639 * still be in hibner8 state if hibern8 is allowed
1640 * during clock gating.
1641 * Make sure we exit hibern8 state also in addition to
1644 if (ufshcd_can_hibern8_during_gating(hba) &&
1645 ufshcd_is_link_hibern8(hba)) {
1648 hba->clk_gating.active_reqs--;
1651 spin_unlock_irqrestore(hba->host->host_lock, flags);
1652 flush_result = flush_work(&hba->clk_gating.ungate_work);
1653 if (hba->clk_gating.is_suspended && !flush_result)
1655 spin_lock_irqsave(hba->host->host_lock, flags);
1660 if (cancel_delayed_work(&hba->clk_gating.gate_work)) {
1661 hba->clk_gating.state = CLKS_ON;
1662 trace_ufshcd_clk_gating(dev_name(hba->dev),
1663 hba->clk_gating.state);
1667 * If we are here, it means gating work is either done or
1668 * currently running. Hence, fall through to cancel gating
1669 * work and to enable clocks.
1673 hba->clk_gating.state = REQ_CLKS_ON;
1674 trace_ufshcd_clk_gating(dev_name(hba->dev),
1675 hba->clk_gating.state);
1676 if (queue_work(hba->clk_gating.clk_gating_workq,
1677 &hba->clk_gating.ungate_work))
1678 ufshcd_scsi_block_requests(hba);
1680 * fall through to check if we should wait for this
1681 * work to be done or not.
1687 hba->clk_gating.active_reqs--;
1691 spin_unlock_irqrestore(hba->host->host_lock, flags);
1692 flush_work(&hba->clk_gating.ungate_work);
1693 /* Make sure state is CLKS_ON before returning */
1694 spin_lock_irqsave(hba->host->host_lock, flags);
1697 dev_err(hba->dev, "%s: clk gating is in invalid state %d\n",
1698 __func__, hba->clk_gating.state);
1701 spin_unlock_irqrestore(hba->host->host_lock, flags);
1705 EXPORT_SYMBOL_GPL(ufshcd_hold);
1707 static void ufshcd_gate_work(struct work_struct *work)
1709 struct ufs_hba *hba = container_of(work, struct ufs_hba,
1710 clk_gating.gate_work.work);
1711 unsigned long flags;
1714 spin_lock_irqsave(hba->host->host_lock, flags);
1716 * In case you are here to cancel this work the gating state
1717 * would be marked as REQ_CLKS_ON. In this case save time by
1718 * skipping the gating work and exit after changing the clock
1721 if (hba->clk_gating.is_suspended ||
1722 (hba->clk_gating.state != REQ_CLKS_OFF)) {
1723 hba->clk_gating.state = CLKS_ON;
1724 trace_ufshcd_clk_gating(dev_name(hba->dev),
1725 hba->clk_gating.state);
1729 if (hba->clk_gating.active_reqs
1730 || hba->ufshcd_state != UFSHCD_STATE_OPERATIONAL
1731 || ufshcd_any_tag_in_use(hba) || hba->outstanding_tasks
1732 || hba->active_uic_cmd || hba->uic_async_done)
1735 spin_unlock_irqrestore(hba->host->host_lock, flags);
1737 /* put the link into hibern8 mode before turning off clocks */
1738 if (ufshcd_can_hibern8_during_gating(hba)) {
1739 ret = ufshcd_uic_hibern8_enter(hba);
1741 hba->clk_gating.state = CLKS_ON;
1742 dev_err(hba->dev, "%s: hibern8 enter failed %d\n",
1744 trace_ufshcd_clk_gating(dev_name(hba->dev),
1745 hba->clk_gating.state);
1748 ufshcd_set_link_hibern8(hba);
1751 ufshcd_disable_irq(hba);
1753 ufshcd_setup_clocks(hba, false);
1755 /* Put the host controller in low power mode if possible */
1756 ufshcd_hba_vreg_set_lpm(hba);
1758 * In case you are here to cancel this work the gating state
1759 * would be marked as REQ_CLKS_ON. In this case keep the state
1760 * as REQ_CLKS_ON which would anyway imply that clocks are off
1761 * and a request to turn them on is pending. By doing this way,
1762 * we keep the state machine in tact and this would ultimately
1763 * prevent from doing cancel work multiple times when there are
1764 * new requests arriving before the current cancel work is done.
1766 spin_lock_irqsave(hba->host->host_lock, flags);
1767 if (hba->clk_gating.state == REQ_CLKS_OFF) {
1768 hba->clk_gating.state = CLKS_OFF;
1769 trace_ufshcd_clk_gating(dev_name(hba->dev),
1770 hba->clk_gating.state);
1773 spin_unlock_irqrestore(hba->host->host_lock, flags);
1778 /* host lock must be held before calling this variant */
1779 static void __ufshcd_release(struct ufs_hba *hba)
1781 if (!ufshcd_is_clkgating_allowed(hba))
1784 hba->clk_gating.active_reqs--;
1786 if (hba->clk_gating.active_reqs || hba->clk_gating.is_suspended ||
1787 hba->ufshcd_state != UFSHCD_STATE_OPERATIONAL ||
1788 hba->outstanding_tasks ||
1789 hba->active_uic_cmd || hba->uic_async_done ||
1790 hba->clk_gating.state == CLKS_OFF)
1793 hba->clk_gating.state = REQ_CLKS_OFF;
1794 trace_ufshcd_clk_gating(dev_name(hba->dev), hba->clk_gating.state);
1795 queue_delayed_work(hba->clk_gating.clk_gating_workq,
1796 &hba->clk_gating.gate_work,
1797 msecs_to_jiffies(hba->clk_gating.delay_ms));
1800 void ufshcd_release(struct ufs_hba *hba)
1802 unsigned long flags;
1804 spin_lock_irqsave(hba->host->host_lock, flags);
1805 __ufshcd_release(hba);
1806 spin_unlock_irqrestore(hba->host->host_lock, flags);
1808 EXPORT_SYMBOL_GPL(ufshcd_release);
1810 static ssize_t ufshcd_clkgate_delay_show(struct device *dev,
1811 struct device_attribute *attr, char *buf)
1813 struct ufs_hba *hba = dev_get_drvdata(dev);
1815 return snprintf(buf, PAGE_SIZE, "%lu\n", hba->clk_gating.delay_ms);
1818 static ssize_t ufshcd_clkgate_delay_store(struct device *dev,
1819 struct device_attribute *attr, const char *buf, size_t count)
1821 struct ufs_hba *hba = dev_get_drvdata(dev);
1822 unsigned long flags, value;
1824 if (kstrtoul(buf, 0, &value))
1827 spin_lock_irqsave(hba->host->host_lock, flags);
1828 hba->clk_gating.delay_ms = value;
1829 spin_unlock_irqrestore(hba->host->host_lock, flags);
1833 static ssize_t ufshcd_clkgate_enable_show(struct device *dev,
1834 struct device_attribute *attr, char *buf)
1836 struct ufs_hba *hba = dev_get_drvdata(dev);
1838 return snprintf(buf, PAGE_SIZE, "%d\n", hba->clk_gating.is_enabled);
1841 static ssize_t ufshcd_clkgate_enable_store(struct device *dev,
1842 struct device_attribute *attr, const char *buf, size_t count)
1844 struct ufs_hba *hba = dev_get_drvdata(dev);
1845 unsigned long flags;
1848 if (kstrtou32(buf, 0, &value))
1853 spin_lock_irqsave(hba->host->host_lock, flags);
1854 if (value == hba->clk_gating.is_enabled)
1858 __ufshcd_release(hba);
1860 hba->clk_gating.active_reqs++;
1862 hba->clk_gating.is_enabled = value;
1864 spin_unlock_irqrestore(hba->host->host_lock, flags);
1868 static void ufshcd_init_clk_scaling(struct ufs_hba *hba)
1870 char wq_name[sizeof("ufs_clkscaling_00")];
1872 if (!ufshcd_is_clkscaling_supported(hba))
1875 if (!hba->clk_scaling.min_gear)
1876 hba->clk_scaling.min_gear = UFS_HS_G1;
1878 INIT_WORK(&hba->clk_scaling.suspend_work,
1879 ufshcd_clk_scaling_suspend_work);
1880 INIT_WORK(&hba->clk_scaling.resume_work,
1881 ufshcd_clk_scaling_resume_work);
1883 snprintf(wq_name, sizeof(wq_name), "ufs_clkscaling_%d",
1884 hba->host->host_no);
1885 hba->clk_scaling.workq = create_singlethread_workqueue(wq_name);
1887 ufshcd_clkscaling_init_sysfs(hba);
1890 static void ufshcd_exit_clk_scaling(struct ufs_hba *hba)
1892 if (!ufshcd_is_clkscaling_supported(hba))
1895 destroy_workqueue(hba->clk_scaling.workq);
1896 ufshcd_devfreq_remove(hba);
1899 static void ufshcd_init_clk_gating(struct ufs_hba *hba)
1901 char wq_name[sizeof("ufs_clk_gating_00")];
1903 if (!ufshcd_is_clkgating_allowed(hba))
1906 hba->clk_gating.state = CLKS_ON;
1908 hba->clk_gating.delay_ms = 150;
1909 INIT_DELAYED_WORK(&hba->clk_gating.gate_work, ufshcd_gate_work);
1910 INIT_WORK(&hba->clk_gating.ungate_work, ufshcd_ungate_work);
1912 snprintf(wq_name, ARRAY_SIZE(wq_name), "ufs_clk_gating_%d",
1913 hba->host->host_no);
1914 hba->clk_gating.clk_gating_workq = alloc_ordered_workqueue(wq_name,
1915 WQ_MEM_RECLAIM | WQ_HIGHPRI);
1917 hba->clk_gating.is_enabled = true;
1919 hba->clk_gating.delay_attr.show = ufshcd_clkgate_delay_show;
1920 hba->clk_gating.delay_attr.store = ufshcd_clkgate_delay_store;
1921 sysfs_attr_init(&hba->clk_gating.delay_attr.attr);
1922 hba->clk_gating.delay_attr.attr.name = "clkgate_delay_ms";
1923 hba->clk_gating.delay_attr.attr.mode = 0644;
1924 if (device_create_file(hba->dev, &hba->clk_gating.delay_attr))
1925 dev_err(hba->dev, "Failed to create sysfs for clkgate_delay\n");
1927 hba->clk_gating.enable_attr.show = ufshcd_clkgate_enable_show;
1928 hba->clk_gating.enable_attr.store = ufshcd_clkgate_enable_store;
1929 sysfs_attr_init(&hba->clk_gating.enable_attr.attr);
1930 hba->clk_gating.enable_attr.attr.name = "clkgate_enable";
1931 hba->clk_gating.enable_attr.attr.mode = 0644;
1932 if (device_create_file(hba->dev, &hba->clk_gating.enable_attr))
1933 dev_err(hba->dev, "Failed to create sysfs for clkgate_enable\n");
1936 static void ufshcd_exit_clk_gating(struct ufs_hba *hba)
1938 if (!ufshcd_is_clkgating_allowed(hba))
1940 device_remove_file(hba->dev, &hba->clk_gating.delay_attr);
1941 device_remove_file(hba->dev, &hba->clk_gating.enable_attr);
1942 cancel_work_sync(&hba->clk_gating.ungate_work);
1943 cancel_delayed_work_sync(&hba->clk_gating.gate_work);
1944 destroy_workqueue(hba->clk_gating.clk_gating_workq);
1947 /* Must be called with host lock acquired */
1948 static void ufshcd_clk_scaling_start_busy(struct ufs_hba *hba)
1950 bool queue_resume_work = false;
1951 ktime_t curr_t = ktime_get();
1953 if (!ufshcd_is_clkscaling_supported(hba))
1956 if (!hba->clk_scaling.active_reqs++)
1957 queue_resume_work = true;
1959 if (!hba->clk_scaling.is_allowed || hba->pm_op_in_progress)
1962 if (queue_resume_work)
1963 queue_work(hba->clk_scaling.workq,
1964 &hba->clk_scaling.resume_work);
1966 if (!hba->clk_scaling.window_start_t) {
1967 hba->clk_scaling.window_start_t = curr_t;
1968 hba->clk_scaling.tot_busy_t = 0;
1969 hba->clk_scaling.is_busy_started = false;
1972 if (!hba->clk_scaling.is_busy_started) {
1973 hba->clk_scaling.busy_start_t = curr_t;
1974 hba->clk_scaling.is_busy_started = true;
1978 static void ufshcd_clk_scaling_update_busy(struct ufs_hba *hba)
1980 struct ufs_clk_scaling *scaling = &hba->clk_scaling;
1982 if (!ufshcd_is_clkscaling_supported(hba))
1985 if (!hba->outstanding_reqs && scaling->is_busy_started) {
1986 scaling->tot_busy_t += ktime_to_us(ktime_sub(ktime_get(),
1987 scaling->busy_start_t));
1988 scaling->busy_start_t = 0;
1989 scaling->is_busy_started = false;
1993 * ufshcd_send_command - Send SCSI or device management commands
1994 * @hba: per adapter instance
1995 * @task_tag: Task tag of the command
1998 void ufshcd_send_command(struct ufs_hba *hba, unsigned int task_tag)
2000 struct ufshcd_lrb *lrbp = &hba->lrb[task_tag];
2002 lrbp->issue_time_stamp = ktime_get();
2003 lrbp->compl_time_stamp = ktime_set(0, 0);
2004 ufshcd_vops_setup_xfer_req(hba, task_tag, (lrbp->cmd ? true : false));
2005 ufshcd_add_command_trace(hba, task_tag, "send");
2006 ufshcd_clk_scaling_start_busy(hba);
2007 __set_bit(task_tag, &hba->outstanding_reqs);
2008 ufshcd_writel(hba, 1 << task_tag, REG_UTP_TRANSFER_REQ_DOOR_BELL);
2009 /* Make sure that doorbell is committed immediately */
2014 * ufshcd_copy_sense_data - Copy sense data in case of check condition
2015 * @lrbp: pointer to local reference block
2017 static inline void ufshcd_copy_sense_data(struct ufshcd_lrb *lrbp)
2020 if (lrbp->sense_buffer &&
2021 ufshcd_get_rsp_upiu_data_seg_len(lrbp->ucd_rsp_ptr)) {
2024 len = be16_to_cpu(lrbp->ucd_rsp_ptr->sr.sense_data_len);
2025 len_to_copy = min_t(int, UFS_SENSE_SIZE, len);
2027 memcpy(lrbp->sense_buffer, lrbp->ucd_rsp_ptr->sr.sense_data,
2033 * ufshcd_copy_query_response() - Copy the Query Response and the data
2035 * @hba: per adapter instance
2036 * @lrbp: pointer to local reference block
2039 int ufshcd_copy_query_response(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
2041 struct ufs_query_res *query_res = &hba->dev_cmd.query.response;
2043 memcpy(&query_res->upiu_res, &lrbp->ucd_rsp_ptr->qr, QUERY_OSF_SIZE);
2045 /* Get the descriptor */
2046 if (hba->dev_cmd.query.descriptor &&
2047 lrbp->ucd_rsp_ptr->qr.opcode == UPIU_QUERY_OPCODE_READ_DESC) {
2048 u8 *descp = (u8 *)lrbp->ucd_rsp_ptr +
2049 GENERAL_UPIU_REQUEST_SIZE;
2053 /* data segment length */
2054 resp_len = be32_to_cpu(lrbp->ucd_rsp_ptr->header.dword_2) &
2055 MASK_QUERY_DATA_SEG_LEN;
2056 buf_len = be16_to_cpu(
2057 hba->dev_cmd.query.request.upiu_req.length);
2058 if (likely(buf_len >= resp_len)) {
2059 memcpy(hba->dev_cmd.query.descriptor, descp, resp_len);
2062 "%s: rsp size %d is bigger than buffer size %d",
2063 __func__, resp_len, buf_len);
2072 * ufshcd_hba_capabilities - Read controller capabilities
2073 * @hba: per adapter instance
2075 * Return: 0 on success, negative on error.
2077 static inline int ufshcd_hba_capabilities(struct ufs_hba *hba)
2081 hba->capabilities = ufshcd_readl(hba, REG_CONTROLLER_CAPABILITIES);
2083 /* nutrs and nutmrs are 0 based values */
2084 hba->nutrs = (hba->capabilities & MASK_TRANSFER_REQUESTS_SLOTS) + 1;
2086 ((hba->capabilities & MASK_TASK_MANAGEMENT_REQUEST_SLOTS) >> 16) + 1;
2088 /* Read crypto capabilities */
2089 err = ufshcd_hba_init_crypto_capabilities(hba);
2091 dev_err(hba->dev, "crypto setup failed\n");
2097 * ufshcd_ready_for_uic_cmd - Check if controller is ready
2098 * to accept UIC commands
2099 * @hba: per adapter instance
2100 * Return true on success, else false
2102 static inline bool ufshcd_ready_for_uic_cmd(struct ufs_hba *hba)
2104 if (ufshcd_readl(hba, REG_CONTROLLER_STATUS) & UIC_COMMAND_READY)
2111 * ufshcd_get_upmcrs - Get the power mode change request status
2112 * @hba: Pointer to adapter instance
2114 * This function gets the UPMCRS field of HCS register
2115 * Returns value of UPMCRS field
2117 static inline u8 ufshcd_get_upmcrs(struct ufs_hba *hba)
2119 return (ufshcd_readl(hba, REG_CONTROLLER_STATUS) >> 8) & 0x7;
2123 * ufshcd_dispatch_uic_cmd - Dispatch UIC commands to unipro layers
2124 * @hba: per adapter instance
2125 * @uic_cmd: UIC command
2127 * Mutex must be held.
2130 ufshcd_dispatch_uic_cmd(struct ufs_hba *hba, struct uic_command *uic_cmd)
2132 WARN_ON(hba->active_uic_cmd);
2134 hba->active_uic_cmd = uic_cmd;
2137 ufshcd_writel(hba, uic_cmd->argument1, REG_UIC_COMMAND_ARG_1);
2138 ufshcd_writel(hba, uic_cmd->argument2, REG_UIC_COMMAND_ARG_2);
2139 ufshcd_writel(hba, uic_cmd->argument3, REG_UIC_COMMAND_ARG_3);
2141 ufshcd_add_uic_command_trace(hba, uic_cmd, "send");
2144 ufshcd_writel(hba, uic_cmd->command & COMMAND_OPCODE_MASK,
2149 * ufshcd_wait_for_uic_cmd - Wait complectioin of UIC command
2150 * @hba: per adapter instance
2151 * @uic_cmd: UIC command
2153 * Must be called with mutex held.
2154 * Returns 0 only if success.
2157 ufshcd_wait_for_uic_cmd(struct ufs_hba *hba, struct uic_command *uic_cmd)
2160 unsigned long flags;
2162 if (wait_for_completion_timeout(&uic_cmd->done,
2163 msecs_to_jiffies(UIC_CMD_TIMEOUT))) {
2164 ret = uic_cmd->argument2 & MASK_UIC_COMMAND_RESULT;
2168 "uic cmd 0x%x with arg3 0x%x completion timeout\n",
2169 uic_cmd->command, uic_cmd->argument3);
2171 if (!uic_cmd->cmd_active) {
2172 dev_err(hba->dev, "%s: UIC cmd has been completed, return the result\n",
2174 ret = uic_cmd->argument2 & MASK_UIC_COMMAND_RESULT;
2178 spin_lock_irqsave(hba->host->host_lock, flags);
2179 hba->active_uic_cmd = NULL;
2180 spin_unlock_irqrestore(hba->host->host_lock, flags);
2186 * __ufshcd_send_uic_cmd - Send UIC commands and retrieve the result
2187 * @hba: per adapter instance
2188 * @uic_cmd: UIC command
2189 * @completion: initialize the completion only if this is set to true
2191 * Identical to ufshcd_send_uic_cmd() expect mutex. Must be called
2192 * with mutex held and host_lock locked.
2193 * Returns 0 only if success.
2196 __ufshcd_send_uic_cmd(struct ufs_hba *hba, struct uic_command *uic_cmd,
2199 if (!ufshcd_ready_for_uic_cmd(hba)) {
2201 "Controller not ready to accept UIC commands\n");
2206 init_completion(&uic_cmd->done);
2208 uic_cmd->cmd_active = 1;
2209 ufshcd_dispatch_uic_cmd(hba, uic_cmd);
2215 * ufshcd_send_uic_cmd - Send UIC commands and retrieve the result
2216 * @hba: per adapter instance
2217 * @uic_cmd: UIC command
2219 * Returns 0 only if success.
2221 int ufshcd_send_uic_cmd(struct ufs_hba *hba, struct uic_command *uic_cmd)
2224 unsigned long flags;
2226 ufshcd_hold(hba, false);
2227 mutex_lock(&hba->uic_cmd_mutex);
2228 ufshcd_add_delay_before_dme_cmd(hba);
2230 spin_lock_irqsave(hba->host->host_lock, flags);
2231 ret = __ufshcd_send_uic_cmd(hba, uic_cmd, true);
2232 spin_unlock_irqrestore(hba->host->host_lock, flags);
2234 ret = ufshcd_wait_for_uic_cmd(hba, uic_cmd);
2236 mutex_unlock(&hba->uic_cmd_mutex);
2238 ufshcd_release(hba);
2243 * ufshcd_map_sg - Map scatter-gather list to prdt
2244 * @hba: per adapter instance
2245 * @lrbp: pointer to local reference block
2247 * Returns 0 in case of success, non-zero value in case of failure
2249 static int ufshcd_map_sg(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
2251 struct ufshcd_sg_entry *prd_table;
2252 struct scatterlist *sg;
2253 struct scsi_cmnd *cmd;
2258 sg_segments = scsi_dma_map(cmd);
2259 if (sg_segments < 0)
2264 if (hba->quirks & UFSHCD_QUIRK_PRDT_BYTE_GRAN)
2265 lrbp->utr_descriptor_ptr->prd_table_length =
2266 cpu_to_le16((sg_segments *
2267 sizeof(struct ufshcd_sg_entry)));
2269 lrbp->utr_descriptor_ptr->prd_table_length =
2270 cpu_to_le16((u16) (sg_segments));
2272 prd_table = (struct ufshcd_sg_entry *)lrbp->ucd_prdt_ptr;
2274 scsi_for_each_sg(cmd, sg, sg_segments, i) {
2276 cpu_to_le32(((u32) sg_dma_len(sg))-1);
2277 prd_table[i].base_addr =
2278 cpu_to_le32(lower_32_bits(sg->dma_address));
2279 prd_table[i].upper_addr =
2280 cpu_to_le32(upper_32_bits(sg->dma_address));
2281 prd_table[i].reserved = 0;
2284 lrbp->utr_descriptor_ptr->prd_table_length = 0;
2291 * ufshcd_enable_intr - enable interrupts
2292 * @hba: per adapter instance
2293 * @intrs: interrupt bits
2295 static void ufshcd_enable_intr(struct ufs_hba *hba, u32 intrs)
2297 u32 set = ufshcd_readl(hba, REG_INTERRUPT_ENABLE);
2299 if (hba->ufs_version == UFSHCI_VERSION_10) {
2301 rw = set & INTERRUPT_MASK_RW_VER_10;
2302 set = rw | ((set ^ intrs) & intrs);
2307 ufshcd_writel(hba, set, REG_INTERRUPT_ENABLE);
2311 * ufshcd_disable_intr - disable interrupts
2312 * @hba: per adapter instance
2313 * @intrs: interrupt bits
2315 static void ufshcd_disable_intr(struct ufs_hba *hba, u32 intrs)
2317 u32 set = ufshcd_readl(hba, REG_INTERRUPT_ENABLE);
2319 if (hba->ufs_version == UFSHCI_VERSION_10) {
2321 rw = (set & INTERRUPT_MASK_RW_VER_10) &
2322 ~(intrs & INTERRUPT_MASK_RW_VER_10);
2323 set = rw | ((set & intrs) & ~INTERRUPT_MASK_RW_VER_10);
2329 ufshcd_writel(hba, set, REG_INTERRUPT_ENABLE);
2333 * ufshcd_prepare_req_desc_hdr() - Fills the requests header
2334 * descriptor according to request
2335 * @lrbp: pointer to local reference block
2336 * @upiu_flags: flags required in the header
2337 * @cmd_dir: requests data direction
2339 static void ufshcd_prepare_req_desc_hdr(struct ufshcd_lrb *lrbp,
2340 u8 *upiu_flags, enum dma_data_direction cmd_dir)
2342 struct utp_transfer_req_desc *req_desc = lrbp->utr_descriptor_ptr;
2348 if (cmd_dir == DMA_FROM_DEVICE) {
2349 data_direction = UTP_DEVICE_TO_HOST;
2350 *upiu_flags = UPIU_CMD_FLAGS_READ;
2351 } else if (cmd_dir == DMA_TO_DEVICE) {
2352 data_direction = UTP_HOST_TO_DEVICE;
2353 *upiu_flags = UPIU_CMD_FLAGS_WRITE;
2355 data_direction = UTP_NO_DATA_TRANSFER;
2356 *upiu_flags = UPIU_CMD_FLAGS_NONE;
2359 dword_0 = data_direction | (lrbp->command_type
2360 << UPIU_COMMAND_TYPE_OFFSET);
2362 dword_0 |= UTP_REQ_DESC_INT_CMD;
2364 /* Prepare crypto related dwords */
2365 ufshcd_prepare_req_desc_hdr_crypto(lrbp, &dword_0, &dword_1, &dword_3);
2367 /* Transfer request descriptor header fields */
2368 req_desc->header.dword_0 = cpu_to_le32(dword_0);
2369 req_desc->header.dword_1 = cpu_to_le32(dword_1);
2371 * assigning invalid value for command status. Controller
2372 * updates OCS on command completion, with the command
2375 req_desc->header.dword_2 =
2376 cpu_to_le32(OCS_INVALID_COMMAND_STATUS);
2377 req_desc->header.dword_3 = cpu_to_le32(dword_3);
2379 req_desc->prd_table_length = 0;
2383 * ufshcd_prepare_utp_scsi_cmd_upiu() - fills the utp_transfer_req_desc,
2385 * @lrbp: local reference block pointer
2386 * @upiu_flags: flags
2389 void ufshcd_prepare_utp_scsi_cmd_upiu(struct ufshcd_lrb *lrbp, u8 upiu_flags)
2391 struct scsi_cmnd *cmd = lrbp->cmd;
2392 struct utp_upiu_req *ucd_req_ptr = lrbp->ucd_req_ptr;
2393 unsigned short cdb_len;
2395 /* command descriptor fields */
2396 ucd_req_ptr->header.dword_0 = UPIU_HEADER_DWORD(
2397 UPIU_TRANSACTION_COMMAND, upiu_flags,
2398 lrbp->lun, lrbp->task_tag);
2399 ucd_req_ptr->header.dword_1 = UPIU_HEADER_DWORD(
2400 UPIU_COMMAND_SET_TYPE_SCSI, 0, 0, 0);
2402 /* Total EHS length and Data segment length will be zero */
2403 ucd_req_ptr->header.dword_2 = 0;
2405 ucd_req_ptr->sc.exp_data_transfer_len = cpu_to_be32(cmd->sdb.length);
2407 cdb_len = min_t(unsigned short, cmd->cmd_len, UFS_CDB_SIZE);
2408 memset(ucd_req_ptr->sc.cdb, 0, UFS_CDB_SIZE);
2409 memcpy(ucd_req_ptr->sc.cdb, cmd->cmnd, cdb_len);
2411 memset(lrbp->ucd_rsp_ptr, 0, sizeof(struct utp_upiu_rsp));
2415 * ufshcd_prepare_utp_query_req_upiu() - fills the utp_transfer_req_desc,
2418 * @lrbp: local reference block pointer
2419 * @upiu_flags: flags
2421 static void ufshcd_prepare_utp_query_req_upiu(struct ufs_hba *hba,
2422 struct ufshcd_lrb *lrbp, u8 upiu_flags)
2424 struct utp_upiu_req *ucd_req_ptr = lrbp->ucd_req_ptr;
2425 struct ufs_query *query = &hba->dev_cmd.query;
2426 u16 len = be16_to_cpu(query->request.upiu_req.length);
2428 /* Query request header */
2429 ucd_req_ptr->header.dword_0 = UPIU_HEADER_DWORD(
2430 UPIU_TRANSACTION_QUERY_REQ, upiu_flags,
2431 lrbp->lun, lrbp->task_tag);
2432 ucd_req_ptr->header.dword_1 = UPIU_HEADER_DWORD(
2433 0, query->request.query_func, 0, 0);
2435 /* Data segment length only need for WRITE_DESC */
2436 if (query->request.upiu_req.opcode == UPIU_QUERY_OPCODE_WRITE_DESC)
2437 ucd_req_ptr->header.dword_2 =
2438 UPIU_HEADER_DWORD(0, 0, (len >> 8), (u8)len);
2440 ucd_req_ptr->header.dword_2 = 0;
2442 /* Copy the Query Request buffer as is */
2443 memcpy(&ucd_req_ptr->qr, &query->request.upiu_req,
2446 /* Copy the Descriptor */
2447 if (query->request.upiu_req.opcode == UPIU_QUERY_OPCODE_WRITE_DESC)
2448 memcpy(ucd_req_ptr + 1, query->descriptor, len);
2450 memset(lrbp->ucd_rsp_ptr, 0, sizeof(struct utp_upiu_rsp));
2453 static inline void ufshcd_prepare_utp_nop_upiu(struct ufshcd_lrb *lrbp)
2455 struct utp_upiu_req *ucd_req_ptr = lrbp->ucd_req_ptr;
2457 memset(ucd_req_ptr, 0, sizeof(struct utp_upiu_req));
2459 /* command descriptor fields */
2460 ucd_req_ptr->header.dword_0 =
2462 UPIU_TRANSACTION_NOP_OUT, 0, 0, lrbp->task_tag);
2463 /* clear rest of the fields of basic header */
2464 ucd_req_ptr->header.dword_1 = 0;
2465 ucd_req_ptr->header.dword_2 = 0;
2467 memset(lrbp->ucd_rsp_ptr, 0, sizeof(struct utp_upiu_rsp));
2471 * ufshcd_compose_devman_upiu - UFS Protocol Information Unit(UPIU)
2472 * for Device Management Purposes
2473 * @hba: per adapter instance
2474 * @lrbp: pointer to local reference block
2476 static int ufshcd_compose_devman_upiu(struct ufs_hba *hba,
2477 struct ufshcd_lrb *lrbp)
2482 if ((hba->ufs_version == UFSHCI_VERSION_10) ||
2483 (hba->ufs_version == UFSHCI_VERSION_11))
2484 lrbp->command_type = UTP_CMD_TYPE_DEV_MANAGE;
2486 lrbp->command_type = UTP_CMD_TYPE_UFS_STORAGE;
2488 ufshcd_prepare_req_desc_hdr(lrbp, &upiu_flags, DMA_NONE);
2489 if (hba->dev_cmd.type == DEV_CMD_TYPE_QUERY)
2490 ufshcd_prepare_utp_query_req_upiu(hba, lrbp, upiu_flags);
2491 else if (hba->dev_cmd.type == DEV_CMD_TYPE_NOP)
2492 ufshcd_prepare_utp_nop_upiu(lrbp);
2500 * ufshcd_comp_scsi_upiu - UFS Protocol Information Unit(UPIU)
2502 * @hba: per adapter instance
2503 * @lrbp: pointer to local reference block
2505 static int ufshcd_comp_scsi_upiu(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
2510 if ((hba->ufs_version == UFSHCI_VERSION_10) ||
2511 (hba->ufs_version == UFSHCI_VERSION_11))
2512 lrbp->command_type = UTP_CMD_TYPE_SCSI;
2514 lrbp->command_type = UTP_CMD_TYPE_UFS_STORAGE;
2516 if (likely(lrbp->cmd)) {
2517 ufshcd_prepare_req_desc_hdr(lrbp, &upiu_flags,
2518 lrbp->cmd->sc_data_direction);
2519 ufshcd_prepare_utp_scsi_cmd_upiu(lrbp, upiu_flags);
2528 * ufshcd_upiu_wlun_to_scsi_wlun - maps UPIU W-LUN id to SCSI W-LUN ID
2529 * @upiu_wlun_id: UPIU W-LUN id
2531 * Returns SCSI W-LUN id
2533 static inline u16 ufshcd_upiu_wlun_to_scsi_wlun(u8 upiu_wlun_id)
2535 return (upiu_wlun_id & ~UFS_UPIU_WLUN_ID) | SCSI_W_LUN_BASE;
2538 static void ufshcd_init_lrb(struct ufs_hba *hba, struct ufshcd_lrb *lrb, int i)
2540 struct utp_transfer_cmd_desc *cmd_descp = hba->ucdl_base_addr;
2541 struct utp_transfer_req_desc *utrdlp = hba->utrdl_base_addr;
2542 dma_addr_t cmd_desc_element_addr = hba->ucdl_dma_addr +
2543 i * sizeof(struct utp_transfer_cmd_desc);
2544 u16 response_offset = offsetof(struct utp_transfer_cmd_desc,
2546 u16 prdt_offset = offsetof(struct utp_transfer_cmd_desc, prd_table);
2548 lrb->utr_descriptor_ptr = utrdlp + i;
2549 lrb->utrd_dma_addr = hba->utrdl_dma_addr +
2550 i * sizeof(struct utp_transfer_req_desc);
2551 lrb->ucd_req_ptr = (struct utp_upiu_req *)(cmd_descp + i);
2552 lrb->ucd_req_dma_addr = cmd_desc_element_addr;
2553 lrb->ucd_rsp_ptr = (struct utp_upiu_rsp *)cmd_descp[i].response_upiu;
2554 lrb->ucd_rsp_dma_addr = cmd_desc_element_addr + response_offset;
2555 lrb->ucd_prdt_ptr = (struct ufshcd_sg_entry *)cmd_descp[i].prd_table;
2556 lrb->ucd_prdt_dma_addr = cmd_desc_element_addr + prdt_offset;
2560 * ufshcd_queuecommand - main entry point for SCSI requests
2561 * @host: SCSI host pointer
2562 * @cmd: command from SCSI Midlayer
2564 * Returns 0 for success, non-zero in case of failure
2566 static int ufshcd_queuecommand(struct Scsi_Host *host, struct scsi_cmnd *cmd)
2568 struct ufshcd_lrb *lrbp;
2569 struct ufs_hba *hba;
2570 unsigned long flags;
2574 hba = shost_priv(host);
2576 tag = cmd->request->tag;
2577 if (!ufshcd_valid_tag(hba, tag)) {
2579 "%s: invalid command tag %d: cmd=0x%p, cmd->request=0x%p",
2580 __func__, tag, cmd, cmd->request);
2584 if (!down_read_trylock(&hba->clk_scaling_lock))
2585 return SCSI_MLQUEUE_HOST_BUSY;
2587 hba->req_abort_count = 0;
2589 err = ufshcd_hold(hba, true);
2591 err = SCSI_MLQUEUE_HOST_BUSY;
2594 WARN_ON(ufshcd_is_clkgating_allowed(hba) &&
2595 (hba->clk_gating.state != CLKS_ON));
2597 lrbp = &hba->lrb[tag];
2598 if (unlikely(lrbp->in_use)) {
2599 if (hba->pm_op_in_progress)
2600 set_host_byte(cmd, DID_BAD_TARGET);
2602 err = SCSI_MLQUEUE_HOST_BUSY;
2603 ufshcd_release(hba);
2609 lrbp->sense_bufflen = UFS_SENSE_SIZE;
2610 lrbp->sense_buffer = cmd->sense_buffer;
2611 lrbp->task_tag = tag;
2612 lrbp->lun = ufshcd_scsi_to_upiu_lun(cmd->device->lun);
2613 lrbp->intr_cmd = !ufshcd_is_intr_aggr_allowed(hba) ? true : false;
2615 ufshcd_prepare_lrbp_crypto(cmd->request, lrbp);
2617 lrbp->req_abort_skip = false;
2619 ufshcd_comp_scsi_upiu(hba, lrbp);
2621 err = ufshcd_map_sg(hba, lrbp);
2624 ufshcd_release(hba);
2627 /* Make sure descriptors are ready before ringing the doorbell */
2630 spin_lock_irqsave(hba->host->host_lock, flags);
2631 switch (hba->ufshcd_state) {
2632 case UFSHCD_STATE_OPERATIONAL:
2633 case UFSHCD_STATE_EH_SCHEDULED_NON_FATAL:
2635 case UFSHCD_STATE_EH_SCHEDULED_FATAL:
2637 * pm_runtime_get_sync() is used at error handling preparation
2638 * stage. If a scsi cmd, e.g. the SSU cmd, is sent from hba's
2639 * PM ops, it can never be finished if we let SCSI layer keep
2640 * retrying it, which gets err handler stuck forever. Neither
2641 * can we let the scsi cmd pass through, because UFS is in bad
2642 * state, the scsi cmd may eventually time out, which will get
2643 * err handler blocked for too long. So, just fail the scsi cmd
2644 * sent from PM ops, err handler can recover PM error anyways.
2646 if (hba->pm_op_in_progress) {
2647 hba->force_reset = true;
2648 set_host_byte(cmd, DID_BAD_TARGET);
2652 case UFSHCD_STATE_RESET:
2653 err = SCSI_MLQUEUE_HOST_BUSY;
2655 case UFSHCD_STATE_ERROR:
2656 set_host_byte(cmd, DID_ERROR);
2659 dev_WARN_ONCE(hba->dev, 1, "%s: invalid state %d\n",
2660 __func__, hba->ufshcd_state);
2661 set_host_byte(cmd, DID_BAD_TARGET);
2664 ufshcd_send_command(hba, tag);
2665 spin_unlock_irqrestore(hba->host->host_lock, flags);
2669 scsi_dma_unmap(lrbp->cmd);
2671 spin_unlock_irqrestore(hba->host->host_lock, flags);
2672 ufshcd_release(hba);
2674 cmd->scsi_done(cmd);
2676 up_read(&hba->clk_scaling_lock);
2680 static int ufshcd_compose_dev_cmd(struct ufs_hba *hba,
2681 struct ufshcd_lrb *lrbp, enum dev_cmd_type cmd_type, int tag)
2684 lrbp->sense_bufflen = 0;
2685 lrbp->sense_buffer = NULL;
2686 lrbp->task_tag = tag;
2687 lrbp->lun = 0; /* device management cmd is not specific to any LUN */
2688 lrbp->intr_cmd = true; /* No interrupt aggregation */
2689 ufshcd_prepare_lrbp_crypto(NULL, lrbp);
2690 hba->dev_cmd.type = cmd_type;
2692 return ufshcd_compose_devman_upiu(hba, lrbp);
2696 ufshcd_clear_cmd(struct ufs_hba *hba, int tag)
2699 unsigned long flags;
2700 u32 mask = 1 << tag;
2702 /* clear outstanding transaction before retry */
2703 spin_lock_irqsave(hba->host->host_lock, flags);
2704 ufshcd_utrl_clear(hba, tag);
2705 spin_unlock_irqrestore(hba->host->host_lock, flags);
2708 * wait for for h/w to clear corresponding bit in door-bell.
2709 * max. wait is 1 sec.
2711 err = ufshcd_wait_for_register(hba,
2712 REG_UTP_TRANSFER_REQ_DOOR_BELL,
2713 mask, ~mask, 1000, 1000);
2719 ufshcd_check_query_response(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
2721 struct ufs_query_res *query_res = &hba->dev_cmd.query.response;
2723 /* Get the UPIU response */
2724 query_res->response = ufshcd_get_rsp_upiu_result(lrbp->ucd_rsp_ptr) >>
2725 UPIU_RSP_CODE_OFFSET;
2726 return query_res->response;
2730 * ufshcd_dev_cmd_completion() - handles device management command responses
2731 * @hba: per adapter instance
2732 * @lrbp: pointer to local reference block
2735 ufshcd_dev_cmd_completion(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
2740 hba->ufs_stats.last_hibern8_exit_tstamp = ktime_set(0, 0);
2741 resp = ufshcd_get_req_rsp(lrbp->ucd_rsp_ptr);
2744 case UPIU_TRANSACTION_NOP_IN:
2745 if (hba->dev_cmd.type != DEV_CMD_TYPE_NOP) {
2747 dev_err(hba->dev, "%s: unexpected response %x\n",
2751 case UPIU_TRANSACTION_QUERY_RSP:
2752 err = ufshcd_check_query_response(hba, lrbp);
2754 err = ufshcd_copy_query_response(hba, lrbp);
2756 case UPIU_TRANSACTION_REJECT_UPIU:
2757 /* TODO: handle Reject UPIU Response */
2759 dev_err(hba->dev, "%s: Reject UPIU not fully implemented\n",
2764 dev_err(hba->dev, "%s: Invalid device management cmd response: %x\n",
2772 static int ufshcd_wait_for_dev_cmd(struct ufs_hba *hba,
2773 struct ufshcd_lrb *lrbp, int max_timeout)
2776 unsigned long time_left;
2777 unsigned long flags;
2779 time_left = wait_for_completion_timeout(hba->dev_cmd.complete,
2780 msecs_to_jiffies(max_timeout));
2782 /* Make sure descriptors are ready before ringing the doorbell */
2784 spin_lock_irqsave(hba->host->host_lock, flags);
2785 hba->dev_cmd.complete = NULL;
2786 if (likely(time_left)) {
2787 err = ufshcd_get_tr_ocs(lrbp);
2789 err = ufshcd_dev_cmd_completion(hba, lrbp);
2791 spin_unlock_irqrestore(hba->host->host_lock, flags);
2795 dev_dbg(hba->dev, "%s: dev_cmd request timedout, tag %d\n",
2796 __func__, lrbp->task_tag);
2797 if (!ufshcd_clear_cmd(hba, lrbp->task_tag))
2798 /* successfully cleared the command, retry if needed */
2801 * in case of an error, after clearing the doorbell,
2802 * we also need to clear the outstanding_request
2805 ufshcd_outstanding_req_clear(hba, lrbp->task_tag);
2812 * ufshcd_exec_dev_cmd - API for sending device management requests
2814 * @cmd_type: specifies the type (NOP, Query...)
2815 * @timeout: time in seconds
2817 * NOTE: Since there is only one available tag for device management commands,
2818 * it is expected you hold the hba->dev_cmd.lock mutex.
2820 static int ufshcd_exec_dev_cmd(struct ufs_hba *hba,
2821 enum dev_cmd_type cmd_type, int timeout)
2823 struct request_queue *q = hba->cmd_queue;
2824 struct request *req;
2825 struct ufshcd_lrb *lrbp;
2828 struct completion wait;
2829 unsigned long flags;
2831 down_read(&hba->clk_scaling_lock);
2834 * Get free slot, sleep if slots are unavailable.
2835 * Even though we use wait_event() which sleeps indefinitely,
2836 * the maximum wait time is bounded by SCSI request timeout.
2838 req = blk_get_request(q, REQ_OP_DRV_OUT, 0);
2844 WARN_ON_ONCE(!ufshcd_valid_tag(hba, tag));
2846 init_completion(&wait);
2847 lrbp = &hba->lrb[tag];
2848 if (unlikely(lrbp->in_use)) {
2854 err = ufshcd_compose_dev_cmd(hba, lrbp, cmd_type, tag);
2858 hba->dev_cmd.complete = &wait;
2860 ufshcd_add_query_upiu_trace(hba, tag, "query_send");
2861 /* Make sure descriptors are ready before ringing the doorbell */
2863 spin_lock_irqsave(hba->host->host_lock, flags);
2864 ufshcd_send_command(hba, tag);
2865 spin_unlock_irqrestore(hba->host->host_lock, flags);
2867 err = ufshcd_wait_for_dev_cmd(hba, lrbp, timeout);
2870 ufshcd_add_query_upiu_trace(hba, tag,
2871 err ? "query_complete_err" : "query_complete");
2874 blk_put_request(req);
2876 up_read(&hba->clk_scaling_lock);
2881 * ufshcd_init_query() - init the query response and request parameters
2882 * @hba: per-adapter instance
2883 * @request: address of the request pointer to be initialized
2884 * @response: address of the response pointer to be initialized
2885 * @opcode: operation to perform
2886 * @idn: flag idn to access
2887 * @index: LU number to access
2888 * @selector: query/flag/descriptor further identification
2890 static inline void ufshcd_init_query(struct ufs_hba *hba,
2891 struct ufs_query_req **request, struct ufs_query_res **response,
2892 enum query_opcode opcode, u8 idn, u8 index, u8 selector)
2894 *request = &hba->dev_cmd.query.request;
2895 *response = &hba->dev_cmd.query.response;
2896 memset(*request, 0, sizeof(struct ufs_query_req));
2897 memset(*response, 0, sizeof(struct ufs_query_res));
2898 (*request)->upiu_req.opcode = opcode;
2899 (*request)->upiu_req.idn = idn;
2900 (*request)->upiu_req.index = index;
2901 (*request)->upiu_req.selector = selector;
2904 static int ufshcd_query_flag_retry(struct ufs_hba *hba,
2905 enum query_opcode opcode, enum flag_idn idn, u8 index, bool *flag_res)
2910 for (retries = 0; retries < QUERY_REQ_RETRIES; retries++) {
2911 ret = ufshcd_query_flag(hba, opcode, idn, index, flag_res);
2914 "%s: failed with error %d, retries %d\n",
2915 __func__, ret, retries);
2922 "%s: query attribute, opcode %d, idn %d, failed with error %d after %d retires\n",
2923 __func__, opcode, idn, ret, retries);
2928 * ufshcd_query_flag() - API function for sending flag query requests
2929 * @hba: per-adapter instance
2930 * @opcode: flag query to perform
2931 * @idn: flag idn to access
2932 * @index: flag index to access
2933 * @flag_res: the flag value after the query request completes
2935 * Returns 0 for success, non-zero in case of failure
2937 int ufshcd_query_flag(struct ufs_hba *hba, enum query_opcode opcode,
2938 enum flag_idn idn, u8 index, bool *flag_res)
2940 struct ufs_query_req *request = NULL;
2941 struct ufs_query_res *response = NULL;
2942 int err, selector = 0;
2943 int timeout = QUERY_REQ_TIMEOUT;
2947 ufshcd_hold(hba, false);
2948 mutex_lock(&hba->dev_cmd.lock);
2949 ufshcd_init_query(hba, &request, &response, opcode, idn, index,
2953 case UPIU_QUERY_OPCODE_SET_FLAG:
2954 case UPIU_QUERY_OPCODE_CLEAR_FLAG:
2955 case UPIU_QUERY_OPCODE_TOGGLE_FLAG:
2956 request->query_func = UPIU_QUERY_FUNC_STANDARD_WRITE_REQUEST;
2958 case UPIU_QUERY_OPCODE_READ_FLAG:
2959 request->query_func = UPIU_QUERY_FUNC_STANDARD_READ_REQUEST;
2961 /* No dummy reads */
2962 dev_err(hba->dev, "%s: Invalid argument for read request\n",
2970 "%s: Expected query flag opcode but got = %d\n",
2976 err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_QUERY, timeout);
2980 "%s: Sending flag query for idn %d failed, err = %d\n",
2981 __func__, idn, err);
2986 *flag_res = (be32_to_cpu(response->upiu_res.value) &
2987 MASK_QUERY_UPIU_FLAG_LOC) & 0x1;
2990 mutex_unlock(&hba->dev_cmd.lock);
2991 ufshcd_release(hba);
2996 * ufshcd_query_attr - API function for sending attribute requests
2997 * @hba: per-adapter instance
2998 * @opcode: attribute opcode
2999 * @idn: attribute idn to access
3000 * @index: index field
3001 * @selector: selector field
3002 * @attr_val: the attribute value after the query request completes
3004 * Returns 0 for success, non-zero in case of failure
3006 int ufshcd_query_attr(struct ufs_hba *hba, enum query_opcode opcode,
3007 enum attr_idn idn, u8 index, u8 selector, u32 *attr_val)
3009 struct ufs_query_req *request = NULL;
3010 struct ufs_query_res *response = NULL;
3016 dev_err(hba->dev, "%s: attribute value required for opcode 0x%x\n",
3021 ufshcd_hold(hba, false);
3023 mutex_lock(&hba->dev_cmd.lock);
3024 ufshcd_init_query(hba, &request, &response, opcode, idn, index,
3028 case UPIU_QUERY_OPCODE_WRITE_ATTR:
3029 request->query_func = UPIU_QUERY_FUNC_STANDARD_WRITE_REQUEST;
3030 request->upiu_req.value = cpu_to_be32(*attr_val);
3032 case UPIU_QUERY_OPCODE_READ_ATTR:
3033 request->query_func = UPIU_QUERY_FUNC_STANDARD_READ_REQUEST;
3036 dev_err(hba->dev, "%s: Expected query attr opcode but got = 0x%.2x\n",
3042 err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_QUERY, QUERY_REQ_TIMEOUT);
3045 dev_err(hba->dev, "%s: opcode 0x%.2x for idn %d failed, index %d, err = %d\n",
3046 __func__, opcode, idn, index, err);
3050 *attr_val = be32_to_cpu(response->upiu_res.value);
3053 mutex_unlock(&hba->dev_cmd.lock);
3054 ufshcd_release(hba);
3059 * ufshcd_query_attr_retry() - API function for sending query
3060 * attribute with retries
3061 * @hba: per-adapter instance
3062 * @opcode: attribute opcode
3063 * @idn: attribute idn to access
3064 * @index: index field
3065 * @selector: selector field
3066 * @attr_val: the attribute value after the query request
3069 * Returns 0 for success, non-zero in case of failure
3071 static int ufshcd_query_attr_retry(struct ufs_hba *hba,
3072 enum query_opcode opcode, enum attr_idn idn, u8 index, u8 selector,
3078 for (retries = QUERY_REQ_RETRIES; retries > 0; retries--) {
3079 ret = ufshcd_query_attr(hba, opcode, idn, index,
3080 selector, attr_val);
3082 dev_dbg(hba->dev, "%s: failed with error %d, retries %d\n",
3083 __func__, ret, retries);
3090 "%s: query attribute, idn %d, failed with error %d after %d retires\n",
3091 __func__, idn, ret, QUERY_REQ_RETRIES);
3095 static int __ufshcd_query_descriptor(struct ufs_hba *hba,
3096 enum query_opcode opcode, enum desc_idn idn, u8 index,
3097 u8 selector, u8 *desc_buf, int *buf_len)
3099 struct ufs_query_req *request = NULL;
3100 struct ufs_query_res *response = NULL;
3106 dev_err(hba->dev, "%s: descriptor buffer required for opcode 0x%x\n",
3111 if (*buf_len < QUERY_DESC_MIN_SIZE || *buf_len > QUERY_DESC_MAX_SIZE) {
3112 dev_err(hba->dev, "%s: descriptor buffer size (%d) is out of range\n",
3113 __func__, *buf_len);
3117 ufshcd_hold(hba, false);
3119 mutex_lock(&hba->dev_cmd.lock);
3120 ufshcd_init_query(hba, &request, &response, opcode, idn, index,
3122 hba->dev_cmd.query.descriptor = desc_buf;
3123 request->upiu_req.length = cpu_to_be16(*buf_len);
3126 case UPIU_QUERY_OPCODE_WRITE_DESC:
3127 request->query_func = UPIU_QUERY_FUNC_STANDARD_WRITE_REQUEST;
3129 case UPIU_QUERY_OPCODE_READ_DESC:
3130 request->query_func = UPIU_QUERY_FUNC_STANDARD_READ_REQUEST;
3134 "%s: Expected query descriptor opcode but got = 0x%.2x\n",
3140 err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_QUERY, QUERY_REQ_TIMEOUT);
3143 dev_err(hba->dev, "%s: opcode 0x%.2x for idn %d failed, index %d, err = %d\n",
3144 __func__, opcode, idn, index, err);
3148 *buf_len = be16_to_cpu(response->upiu_res.length);
3151 hba->dev_cmd.query.descriptor = NULL;
3152 mutex_unlock(&hba->dev_cmd.lock);
3153 ufshcd_release(hba);
3158 * ufshcd_query_descriptor_retry - API function for sending descriptor requests
3159 * @hba: per-adapter instance
3160 * @opcode: attribute opcode
3161 * @idn: attribute idn to access
3162 * @index: index field
3163 * @selector: selector field
3164 * @desc_buf: the buffer that contains the descriptor
3165 * @buf_len: length parameter passed to the device
3167 * Returns 0 for success, non-zero in case of failure.
3168 * The buf_len parameter will contain, on return, the length parameter
3169 * received on the response.
3171 int ufshcd_query_descriptor_retry(struct ufs_hba *hba,
3172 enum query_opcode opcode,
3173 enum desc_idn idn, u8 index,
3175 u8 *desc_buf, int *buf_len)
3180 for (retries = QUERY_REQ_RETRIES; retries > 0; retries--) {
3181 err = __ufshcd_query_descriptor(hba, opcode, idn, index,
3182 selector, desc_buf, buf_len);
3183 if (!err || err == -EINVAL)
3191 * ufshcd_map_desc_id_to_length - map descriptor IDN to its length
3192 * @hba: Pointer to adapter instance
3193 * @desc_id: descriptor idn value
3194 * @desc_len: mapped desc length (out)
3196 void ufshcd_map_desc_id_to_length(struct ufs_hba *hba, enum desc_idn desc_id,
3199 if (desc_id >= QUERY_DESC_IDN_MAX || desc_id == QUERY_DESC_IDN_RFU_0 ||
3200 desc_id == QUERY_DESC_IDN_RFU_1)
3203 *desc_len = hba->desc_size[desc_id];
3205 EXPORT_SYMBOL(ufshcd_map_desc_id_to_length);
3207 static void ufshcd_update_desc_length(struct ufs_hba *hba,
3208 enum desc_idn desc_id, int desc_index,
3209 unsigned char desc_len)
3211 if (hba->desc_size[desc_id] == QUERY_DESC_MAX_SIZE &&
3212 desc_id != QUERY_DESC_IDN_STRING && desc_index != UFS_RPMB_UNIT)
3213 /* For UFS 3.1, the normal unit descriptor is 10 bytes larger
3214 * than the RPMB unit, however, both descriptors share the same
3215 * desc_idn, to cover both unit descriptors with one length, we
3216 * choose the normal unit descriptor length by desc_index.
3218 hba->desc_size[desc_id] = desc_len;
3222 * ufshcd_read_desc_param - read the specified descriptor parameter
3223 * @hba: Pointer to adapter instance
3224 * @desc_id: descriptor idn value
3225 * @desc_index: descriptor index
3226 * @param_offset: offset of the parameter to read
3227 * @param_read_buf: pointer to buffer where parameter would be read
3228 * @param_size: sizeof(param_read_buf)
3230 * Return 0 in case of success, non-zero otherwise
3232 int ufshcd_read_desc_param(struct ufs_hba *hba,
3233 enum desc_idn desc_id,
3242 bool is_kmalloc = true;
3245 if (desc_id >= QUERY_DESC_IDN_MAX || !param_size)
3248 /* Get the length of descriptor */
3249 ufshcd_map_desc_id_to_length(hba, desc_id, &buff_len);
3251 dev_err(hba->dev, "%s: Failed to get desc length\n", __func__);
3255 if (param_offset >= buff_len) {
3256 dev_err(hba->dev, "%s: Invalid offset 0x%x in descriptor IDN 0x%x, length 0x%x\n",
3257 __func__, param_offset, desc_id, buff_len);
3261 /* Check whether we need temp memory */
3262 if (param_offset != 0 || param_size < buff_len) {
3263 desc_buf = kzalloc(buff_len, GFP_KERNEL);
3267 desc_buf = param_read_buf;
3271 /* Request for full descriptor */
3272 ret = ufshcd_query_descriptor_retry(hba, UPIU_QUERY_OPCODE_READ_DESC,
3273 desc_id, desc_index, 0,
3274 desc_buf, &buff_len);
3277 dev_err(hba->dev, "%s: Failed reading descriptor. desc_id %d, desc_index %d, param_offset %d, ret %d\n",
3278 __func__, desc_id, desc_index, param_offset, ret);
3283 if (desc_buf[QUERY_DESC_DESC_TYPE_OFFSET] != desc_id) {
3284 dev_err(hba->dev, "%s: invalid desc_id %d in descriptor header\n",
3285 __func__, desc_buf[QUERY_DESC_DESC_TYPE_OFFSET]);
3290 /* Update descriptor length */
3291 buff_len = desc_buf[QUERY_DESC_LENGTH_OFFSET];
3292 ufshcd_update_desc_length(hba, desc_id, desc_index, buff_len);
3295 /* Make sure we don't copy more data than available */
3296 if (param_offset + param_size > buff_len)
3297 param_size = buff_len - param_offset;
3298 memcpy(param_read_buf, &desc_buf[param_offset], param_size);
3307 * struct uc_string_id - unicode string
3309 * @len: size of this descriptor inclusive
3310 * @type: descriptor type
3311 * @uc: unicode string character
3313 struct uc_string_id {
3319 /* replace non-printable or non-ASCII characters with spaces */
3320 static inline char ufshcd_remove_non_printable(u8 ch)
3322 return (ch >= 0x20 && ch <= 0x7e) ? ch : ' ';
3326 * ufshcd_read_string_desc - read string descriptor
3327 * @hba: pointer to adapter instance
3328 * @desc_index: descriptor index
3329 * @buf: pointer to buffer where descriptor would be read,
3330 * the caller should free the memory.
3331 * @ascii: if true convert from unicode to ascii characters
3332 * null terminated string.
3335 * * string size on success.
3336 * * -ENOMEM: on allocation failure
3337 * * -EINVAL: on a wrong parameter
3339 int ufshcd_read_string_desc(struct ufs_hba *hba, u8 desc_index,
3340 u8 **buf, bool ascii)
3342 struct uc_string_id *uc_str;
3349 uc_str = kzalloc(QUERY_DESC_MAX_SIZE, GFP_KERNEL);
3353 ret = ufshcd_read_desc_param(hba, QUERY_DESC_IDN_STRING, desc_index, 0,
3354 (u8 *)uc_str, QUERY_DESC_MAX_SIZE);
3356 dev_err(hba->dev, "Reading String Desc failed after %d retries. err = %d\n",
3357 QUERY_REQ_RETRIES, ret);
3362 if (uc_str->len <= QUERY_DESC_HDR_SIZE) {
3363 dev_dbg(hba->dev, "String Desc is of zero length\n");
3372 /* remove header and divide by 2 to move from UTF16 to UTF8 */
3373 ascii_len = (uc_str->len - QUERY_DESC_HDR_SIZE) / 2 + 1;
3374 str = kzalloc(ascii_len, GFP_KERNEL);
3381 * the descriptor contains string in UTF16 format
3382 * we need to convert to utf-8 so it can be displayed
3384 ret = utf16s_to_utf8s(uc_str->uc,
3385 uc_str->len - QUERY_DESC_HDR_SIZE,
3386 UTF16_BIG_ENDIAN, str, ascii_len);
3388 /* replace non-printable or non-ASCII characters with spaces */
3389 for (i = 0; i < ret; i++)
3390 str[i] = ufshcd_remove_non_printable(str[i]);
3395 str = kmemdup(uc_str, uc_str->len, GFP_KERNEL);
3409 * ufshcd_read_unit_desc_param - read the specified unit descriptor parameter
3410 * @hba: Pointer to adapter instance
3412 * @param_offset: offset of the parameter to read
3413 * @param_read_buf: pointer to buffer where parameter would be read
3414 * @param_size: sizeof(param_read_buf)
3416 * Return 0 in case of success, non-zero otherwise
3418 static inline int ufshcd_read_unit_desc_param(struct ufs_hba *hba,
3420 enum unit_desc_param param_offset,
3425 * Unit descriptors are only available for general purpose LUs (LUN id
3426 * from 0 to 7) and RPMB Well known LU.
3428 if (!ufs_is_valid_unit_desc_lun(&hba->dev_info, lun))
3431 return ufshcd_read_desc_param(hba, QUERY_DESC_IDN_UNIT, lun,
3432 param_offset, param_read_buf, param_size);
3435 static int ufshcd_get_ref_clk_gating_wait(struct ufs_hba *hba)
3438 u32 gating_wait = UFSHCD_REF_CLK_GATING_WAIT_US;
3440 if (hba->dev_info.wspecversion >= 0x300) {
3441 err = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
3442 QUERY_ATTR_IDN_REF_CLK_GATING_WAIT_TIME, 0, 0,
3445 dev_err(hba->dev, "Failed reading bRefClkGatingWait. err = %d, use default %uus\n",
3448 if (gating_wait == 0) {
3449 gating_wait = UFSHCD_REF_CLK_GATING_WAIT_US;
3450 dev_err(hba->dev, "Undefined ref clk gating wait time, use default %uus\n",
3454 hba->dev_info.clk_gating_wait_us = gating_wait;
3461 * ufshcd_memory_alloc - allocate memory for host memory space data structures
3462 * @hba: per adapter instance
3464 * 1. Allocate DMA memory for Command Descriptor array
3465 * Each command descriptor consist of Command UPIU, Response UPIU and PRDT
3466 * 2. Allocate DMA memory for UTP Transfer Request Descriptor List (UTRDL).
3467 * 3. Allocate DMA memory for UTP Task Management Request Descriptor List
3469 * 4. Allocate memory for local reference block(lrb).
3471 * Returns 0 for success, non-zero in case of failure
3473 static int ufshcd_memory_alloc(struct ufs_hba *hba)
3475 size_t utmrdl_size, utrdl_size, ucdl_size;
3477 /* Allocate memory for UTP command descriptors */
3478 ucdl_size = (sizeof(struct utp_transfer_cmd_desc) * hba->nutrs);
3479 hba->ucdl_base_addr = dmam_alloc_coherent(hba->dev,
3481 &hba->ucdl_dma_addr,
3485 * UFSHCI requires UTP command descriptor to be 128 byte aligned.
3486 * make sure hba->ucdl_dma_addr is aligned to PAGE_SIZE
3487 * if hba->ucdl_dma_addr is aligned to PAGE_SIZE, then it will
3488 * be aligned to 128 bytes as well
3490 if (!hba->ucdl_base_addr ||
3491 WARN_ON(hba->ucdl_dma_addr & (PAGE_SIZE - 1))) {
3493 "Command Descriptor Memory allocation failed\n");
3498 * Allocate memory for UTP Transfer descriptors
3499 * UFSHCI requires 1024 byte alignment of UTRD
3501 utrdl_size = (sizeof(struct utp_transfer_req_desc) * hba->nutrs);
3502 hba->utrdl_base_addr = dmam_alloc_coherent(hba->dev,
3504 &hba->utrdl_dma_addr,
3506 if (!hba->utrdl_base_addr ||
3507 WARN_ON(hba->utrdl_dma_addr & (PAGE_SIZE - 1))) {
3509 "Transfer Descriptor Memory allocation failed\n");
3514 * Allocate memory for UTP Task Management descriptors
3515 * UFSHCI requires 1024 byte alignment of UTMRD
3517 utmrdl_size = sizeof(struct utp_task_req_desc) * hba->nutmrs;
3518 hba->utmrdl_base_addr = dmam_alloc_coherent(hba->dev,
3520 &hba->utmrdl_dma_addr,
3522 if (!hba->utmrdl_base_addr ||
3523 WARN_ON(hba->utmrdl_dma_addr & (PAGE_SIZE - 1))) {
3525 "Task Management Descriptor Memory allocation failed\n");
3529 /* Allocate memory for local reference block */
3530 hba->lrb = devm_kcalloc(hba->dev,
3531 hba->nutrs, sizeof(struct ufshcd_lrb),
3534 dev_err(hba->dev, "LRB Memory allocation failed\n");
3543 * ufshcd_host_memory_configure - configure local reference block with
3545 * @hba: per adapter instance
3547 * Configure Host memory space
3548 * 1. Update Corresponding UTRD.UCDBA and UTRD.UCDBAU with UCD DMA
3550 * 2. Update each UTRD with Response UPIU offset, Response UPIU length
3552 * 3. Save the corresponding addresses of UTRD, UCD.CMD, UCD.RSP and UCD.PRDT
3553 * into local reference block.
3555 static void ufshcd_host_memory_configure(struct ufs_hba *hba)
3557 struct utp_transfer_req_desc *utrdlp;
3558 dma_addr_t cmd_desc_dma_addr;
3559 dma_addr_t cmd_desc_element_addr;
3560 u16 response_offset;
3565 utrdlp = hba->utrdl_base_addr;
3568 offsetof(struct utp_transfer_cmd_desc, response_upiu);
3570 offsetof(struct utp_transfer_cmd_desc, prd_table);
3572 cmd_desc_size = sizeof(struct utp_transfer_cmd_desc);
3573 cmd_desc_dma_addr = hba->ucdl_dma_addr;
3575 for (i = 0; i < hba->nutrs; i++) {
3576 /* Configure UTRD with command descriptor base address */
3577 cmd_desc_element_addr =
3578 (cmd_desc_dma_addr + (cmd_desc_size * i));
3579 utrdlp[i].command_desc_base_addr_lo =
3580 cpu_to_le32(lower_32_bits(cmd_desc_element_addr));
3581 utrdlp[i].command_desc_base_addr_hi =
3582 cpu_to_le32(upper_32_bits(cmd_desc_element_addr));
3584 /* Response upiu and prdt offset should be in double words */
3585 if (hba->quirks & UFSHCD_QUIRK_PRDT_BYTE_GRAN) {
3586 utrdlp[i].response_upiu_offset =
3587 cpu_to_le16(response_offset);
3588 utrdlp[i].prd_table_offset =
3589 cpu_to_le16(prdt_offset);
3590 utrdlp[i].response_upiu_length =
3591 cpu_to_le16(ALIGNED_UPIU_SIZE);
3593 utrdlp[i].response_upiu_offset =
3594 cpu_to_le16(response_offset >> 2);
3595 utrdlp[i].prd_table_offset =
3596 cpu_to_le16(prdt_offset >> 2);
3597 utrdlp[i].response_upiu_length =
3598 cpu_to_le16(ALIGNED_UPIU_SIZE >> 2);
3601 ufshcd_init_lrb(hba, &hba->lrb[i], i);
3606 * ufshcd_dme_link_startup - Notify Unipro to perform link startup
3607 * @hba: per adapter instance
3609 * UIC_CMD_DME_LINK_STARTUP command must be issued to Unipro layer,
3610 * in order to initialize the Unipro link startup procedure.
3611 * Once the Unipro links are up, the device connected to the controller
3614 * Returns 0 on success, non-zero value on failure
3616 static int ufshcd_dme_link_startup(struct ufs_hba *hba)
3618 struct uic_command uic_cmd = {0};
3621 uic_cmd.command = UIC_CMD_DME_LINK_STARTUP;
3623 ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
3626 "dme-link-startup: error code %d\n", ret);
3630 * ufshcd_dme_reset - UIC command for DME_RESET
3631 * @hba: per adapter instance
3633 * DME_RESET command is issued in order to reset UniPro stack.
3634 * This function now deals with cold reset.
3636 * Returns 0 on success, non-zero value on failure
3638 static int ufshcd_dme_reset(struct ufs_hba *hba)
3640 struct uic_command uic_cmd = {0};
3643 uic_cmd.command = UIC_CMD_DME_RESET;
3645 ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
3648 "dme-reset: error code %d\n", ret);
3653 int ufshcd_dme_configure_adapt(struct ufs_hba *hba,
3659 if (agreed_gear != UFS_HS_G4)
3660 adapt_val = PA_NO_ADAPT;
3662 ret = ufshcd_dme_set(hba,
3663 UIC_ARG_MIB(PA_TXHSADAPTTYPE),
3667 EXPORT_SYMBOL_GPL(ufshcd_dme_configure_adapt);
3670 * ufshcd_dme_enable - UIC command for DME_ENABLE
3671 * @hba: per adapter instance
3673 * DME_ENABLE command is issued in order to enable UniPro stack.
3675 * Returns 0 on success, non-zero value on failure
3677 static int ufshcd_dme_enable(struct ufs_hba *hba)
3679 struct uic_command uic_cmd = {0};
3682 uic_cmd.command = UIC_CMD_DME_ENABLE;
3684 ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
3687 "dme-enable: error code %d\n", ret);
3692 static inline void ufshcd_add_delay_before_dme_cmd(struct ufs_hba *hba)
3694 #define MIN_DELAY_BEFORE_DME_CMDS_US 1000
3695 unsigned long min_sleep_time_us;
3697 if (!(hba->quirks & UFSHCD_QUIRK_DELAY_BEFORE_DME_CMDS))
3701 * last_dme_cmd_tstamp will be 0 only for 1st call to
3704 if (unlikely(!ktime_to_us(hba->last_dme_cmd_tstamp))) {
3705 min_sleep_time_us = MIN_DELAY_BEFORE_DME_CMDS_US;
3707 unsigned long delta =
3708 (unsigned long) ktime_to_us(
3709 ktime_sub(ktime_get(),
3710 hba->last_dme_cmd_tstamp));
3712 if (delta < MIN_DELAY_BEFORE_DME_CMDS_US)
3714 MIN_DELAY_BEFORE_DME_CMDS_US - delta;
3716 return; /* no more delay required */
3719 /* allow sleep for extra 50us if needed */
3720 usleep_range(min_sleep_time_us, min_sleep_time_us + 50);
3724 * ufshcd_dme_set_attr - UIC command for DME_SET, DME_PEER_SET
3725 * @hba: per adapter instance
3726 * @attr_sel: uic command argument1
3727 * @attr_set: attribute set type as uic command argument2
3728 * @mib_val: setting value as uic command argument3
3729 * @peer: indicate whether peer or local
3731 * Returns 0 on success, non-zero value on failure
3733 int ufshcd_dme_set_attr(struct ufs_hba *hba, u32 attr_sel,
3734 u8 attr_set, u32 mib_val, u8 peer)
3736 struct uic_command uic_cmd = {0};
3737 static const char *const action[] = {
3741 const char *set = action[!!peer];
3743 int retries = UFS_UIC_COMMAND_RETRIES;
3745 uic_cmd.command = peer ?
3746 UIC_CMD_DME_PEER_SET : UIC_CMD_DME_SET;
3747 uic_cmd.argument1 = attr_sel;
3748 uic_cmd.argument2 = UIC_ARG_ATTR_TYPE(attr_set);
3749 uic_cmd.argument3 = mib_val;
3752 /* for peer attributes we retry upon failure */
3753 ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
3755 dev_dbg(hba->dev, "%s: attr-id 0x%x val 0x%x error code %d\n",
3756 set, UIC_GET_ATTR_ID(attr_sel), mib_val, ret);
3757 } while (ret && peer && --retries);
3760 dev_err(hba->dev, "%s: attr-id 0x%x val 0x%x failed %d retries\n",
3761 set, UIC_GET_ATTR_ID(attr_sel), mib_val,
3762 UFS_UIC_COMMAND_RETRIES - retries);
3766 EXPORT_SYMBOL_GPL(ufshcd_dme_set_attr);
3769 * ufshcd_dme_get_attr - UIC command for DME_GET, DME_PEER_GET
3770 * @hba: per adapter instance
3771 * @attr_sel: uic command argument1
3772 * @mib_val: the value of the attribute as returned by the UIC command
3773 * @peer: indicate whether peer or local
3775 * Returns 0 on success, non-zero value on failure
3777 int ufshcd_dme_get_attr(struct ufs_hba *hba, u32 attr_sel,
3778 u32 *mib_val, u8 peer)
3780 struct uic_command uic_cmd = {0};
3781 static const char *const action[] = {
3785 const char *get = action[!!peer];
3787 int retries = UFS_UIC_COMMAND_RETRIES;
3788 struct ufs_pa_layer_attr orig_pwr_info;
3789 struct ufs_pa_layer_attr temp_pwr_info;
3790 bool pwr_mode_change = false;
3792 if (peer && (hba->quirks & UFSHCD_QUIRK_DME_PEER_ACCESS_AUTO_MODE)) {
3793 orig_pwr_info = hba->pwr_info;
3794 temp_pwr_info = orig_pwr_info;
3796 if (orig_pwr_info.pwr_tx == FAST_MODE ||
3797 orig_pwr_info.pwr_rx == FAST_MODE) {
3798 temp_pwr_info.pwr_tx = FASTAUTO_MODE;
3799 temp_pwr_info.pwr_rx = FASTAUTO_MODE;
3800 pwr_mode_change = true;
3801 } else if (orig_pwr_info.pwr_tx == SLOW_MODE ||
3802 orig_pwr_info.pwr_rx == SLOW_MODE) {
3803 temp_pwr_info.pwr_tx = SLOWAUTO_MODE;
3804 temp_pwr_info.pwr_rx = SLOWAUTO_MODE;
3805 pwr_mode_change = true;
3807 if (pwr_mode_change) {
3808 ret = ufshcd_change_power_mode(hba, &temp_pwr_info);
3814 uic_cmd.command = peer ?
3815 UIC_CMD_DME_PEER_GET : UIC_CMD_DME_GET;
3816 uic_cmd.argument1 = attr_sel;
3819 /* for peer attributes we retry upon failure */
3820 ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
3822 dev_dbg(hba->dev, "%s: attr-id 0x%x error code %d\n",
3823 get, UIC_GET_ATTR_ID(attr_sel), ret);
3824 } while (ret && peer && --retries);
3827 dev_err(hba->dev, "%s: attr-id 0x%x failed %d retries\n",
3828 get, UIC_GET_ATTR_ID(attr_sel),
3829 UFS_UIC_COMMAND_RETRIES - retries);
3831 if (mib_val && !ret)
3832 *mib_val = uic_cmd.argument3;
3834 if (peer && (hba->quirks & UFSHCD_QUIRK_DME_PEER_ACCESS_AUTO_MODE)
3836 ufshcd_change_power_mode(hba, &orig_pwr_info);
3840 EXPORT_SYMBOL_GPL(ufshcd_dme_get_attr);
3843 * ufshcd_uic_pwr_ctrl - executes UIC commands (which affects the link power
3844 * state) and waits for it to take effect.
3846 * @hba: per adapter instance
3847 * @cmd: UIC command to execute
3849 * DME operations like DME_SET(PA_PWRMODE), DME_HIBERNATE_ENTER &
3850 * DME_HIBERNATE_EXIT commands take some time to take its effect on both host
3851 * and device UniPro link and hence it's final completion would be indicated by
3852 * dedicated status bits in Interrupt Status register (UPMS, UHES, UHXS) in
3853 * addition to normal UIC command completion Status (UCCS). This function only
3854 * returns after the relevant status bits indicate the completion.
3856 * Returns 0 on success, non-zero value on failure
3858 static int ufshcd_uic_pwr_ctrl(struct ufs_hba *hba, struct uic_command *cmd)
3860 struct completion uic_async_done;
3861 unsigned long flags;
3864 bool reenable_intr = false;
3866 mutex_lock(&hba->uic_cmd_mutex);
3867 init_completion(&uic_async_done);
3868 ufshcd_add_delay_before_dme_cmd(hba);
3870 spin_lock_irqsave(hba->host->host_lock, flags);
3871 if (ufshcd_is_link_broken(hba)) {
3875 hba->uic_async_done = &uic_async_done;
3876 if (ufshcd_readl(hba, REG_INTERRUPT_ENABLE) & UIC_COMMAND_COMPL) {
3877 ufshcd_disable_intr(hba, UIC_COMMAND_COMPL);
3879 * Make sure UIC command completion interrupt is disabled before
3880 * issuing UIC command.
3883 reenable_intr = true;
3885 ret = __ufshcd_send_uic_cmd(hba, cmd, false);
3886 spin_unlock_irqrestore(hba->host->host_lock, flags);
3889 "pwr ctrl cmd 0x%x with mode 0x%x uic error %d\n",
3890 cmd->command, cmd->argument3, ret);
3894 if (!wait_for_completion_timeout(hba->uic_async_done,
3895 msecs_to_jiffies(UIC_CMD_TIMEOUT))) {
3897 "pwr ctrl cmd 0x%x with mode 0x%x completion timeout\n",
3898 cmd->command, cmd->argument3);
3900 if (!cmd->cmd_active) {
3901 dev_err(hba->dev, "%s: Power Mode Change operation has been completed, go check UPMCRS\n",
3911 status = ufshcd_get_upmcrs(hba);
3912 if (status != PWR_LOCAL) {
3914 "pwr ctrl cmd 0x%x failed, host upmcrs:0x%x\n",
3915 cmd->command, status);
3916 ret = (status != PWR_OK) ? status : -1;
3920 ufshcd_print_host_state(hba);
3921 ufshcd_print_pwr_info(hba);
3922 ufshcd_print_evt_hist(hba);
3925 spin_lock_irqsave(hba->host->host_lock, flags);
3926 hba->active_uic_cmd = NULL;
3927 hba->uic_async_done = NULL;
3929 ufshcd_enable_intr(hba, UIC_COMMAND_COMPL);
3931 ufshcd_set_link_broken(hba);
3932 ufshcd_schedule_eh_work(hba);
3935 spin_unlock_irqrestore(hba->host->host_lock, flags);
3936 mutex_unlock(&hba->uic_cmd_mutex);
3942 * ufshcd_uic_change_pwr_mode - Perform the UIC power mode chage
3943 * using DME_SET primitives.
3944 * @hba: per adapter instance
3945 * @mode: powr mode value
3947 * Returns 0 on success, non-zero value on failure
3949 static int ufshcd_uic_change_pwr_mode(struct ufs_hba *hba, u8 mode)
3951 struct uic_command uic_cmd = {0};
3954 if (hba->quirks & UFSHCD_QUIRK_BROKEN_PA_RXHSUNTERMCAP) {
3955 ret = ufshcd_dme_set(hba,
3956 UIC_ARG_MIB_SEL(PA_RXHSUNTERMCAP, 0), 1);
3958 dev_err(hba->dev, "%s: failed to enable PA_RXHSUNTERMCAP ret %d\n",
3964 uic_cmd.command = UIC_CMD_DME_SET;
3965 uic_cmd.argument1 = UIC_ARG_MIB(PA_PWRMODE);
3966 uic_cmd.argument3 = mode;
3967 ufshcd_hold(hba, false);
3968 ret = ufshcd_uic_pwr_ctrl(hba, &uic_cmd);
3969 ufshcd_release(hba);
3975 int ufshcd_link_recovery(struct ufs_hba *hba)
3978 unsigned long flags;
3980 spin_lock_irqsave(hba->host->host_lock, flags);
3981 hba->ufshcd_state = UFSHCD_STATE_RESET;
3982 ufshcd_set_eh_in_progress(hba);
3983 spin_unlock_irqrestore(hba->host->host_lock, flags);
3985 /* Reset the attached device */
3986 ufshcd_device_reset(hba);
3988 ret = ufshcd_host_reset_and_restore(hba);
3990 spin_lock_irqsave(hba->host->host_lock, flags);
3992 hba->ufshcd_state = UFSHCD_STATE_ERROR;
3993 ufshcd_clear_eh_in_progress(hba);
3994 spin_unlock_irqrestore(hba->host->host_lock, flags);
3997 dev_err(hba->dev, "%s: link recovery failed, err %d",
4000 ufshcd_clear_ua_wluns(hba);
4004 EXPORT_SYMBOL_GPL(ufshcd_link_recovery);
4006 static int ufshcd_uic_hibern8_enter(struct ufs_hba *hba)
4009 struct uic_command uic_cmd = {0};
4010 ktime_t start = ktime_get();
4012 ufshcd_vops_hibern8_notify(hba, UIC_CMD_DME_HIBER_ENTER, PRE_CHANGE);
4014 uic_cmd.command = UIC_CMD_DME_HIBER_ENTER;
4015 ret = ufshcd_uic_pwr_ctrl(hba, &uic_cmd);
4016 trace_ufshcd_profile_hibern8(dev_name(hba->dev), "enter",
4017 ktime_to_us(ktime_sub(ktime_get(), start)), ret);
4020 dev_err(hba->dev, "%s: hibern8 enter failed. ret = %d\n",
4023 ufshcd_vops_hibern8_notify(hba, UIC_CMD_DME_HIBER_ENTER,
4029 int ufshcd_uic_hibern8_exit(struct ufs_hba *hba)
4031 struct uic_command uic_cmd = {0};
4033 ktime_t start = ktime_get();
4035 ufshcd_vops_hibern8_notify(hba, UIC_CMD_DME_HIBER_EXIT, PRE_CHANGE);
4037 uic_cmd.command = UIC_CMD_DME_HIBER_EXIT;
4038 ret = ufshcd_uic_pwr_ctrl(hba, &uic_cmd);
4039 trace_ufshcd_profile_hibern8(dev_name(hba->dev), "exit",
4040 ktime_to_us(ktime_sub(ktime_get(), start)), ret);
4043 dev_err(hba->dev, "%s: hibern8 exit failed. ret = %d\n",
4046 ufshcd_vops_hibern8_notify(hba, UIC_CMD_DME_HIBER_EXIT,
4048 hba->ufs_stats.last_hibern8_exit_tstamp = ktime_get();
4049 hba->ufs_stats.hibern8_exit_cnt++;
4054 EXPORT_SYMBOL_GPL(ufshcd_uic_hibern8_exit);
4056 void ufshcd_auto_hibern8_update(struct ufs_hba *hba, u32 ahit)
4058 unsigned long flags;
4059 bool update = false;
4061 if (!ufshcd_is_auto_hibern8_supported(hba))
4064 spin_lock_irqsave(hba->host->host_lock, flags);
4065 if (hba->ahit != ahit) {
4069 spin_unlock_irqrestore(hba->host->host_lock, flags);
4071 if (update && !pm_runtime_suspended(hba->dev)) {
4072 pm_runtime_get_sync(hba->dev);
4073 ufshcd_hold(hba, false);
4074 ufshcd_auto_hibern8_enable(hba);
4075 ufshcd_release(hba);
4076 pm_runtime_put(hba->dev);
4079 EXPORT_SYMBOL_GPL(ufshcd_auto_hibern8_update);
4081 void ufshcd_auto_hibern8_enable(struct ufs_hba *hba)
4083 unsigned long flags;
4085 if (!ufshcd_is_auto_hibern8_supported(hba))
4088 spin_lock_irqsave(hba->host->host_lock, flags);
4089 ufshcd_writel(hba, hba->ahit, REG_AUTO_HIBERNATE_IDLE_TIMER);
4090 spin_unlock_irqrestore(hba->host->host_lock, flags);
4094 * ufshcd_init_pwr_info - setting the POR (power on reset)
4095 * values in hba power info
4096 * @hba: per-adapter instance
4098 static void ufshcd_init_pwr_info(struct ufs_hba *hba)
4100 hba->pwr_info.gear_rx = UFS_PWM_G1;
4101 hba->pwr_info.gear_tx = UFS_PWM_G1;
4102 hba->pwr_info.lane_rx = 1;
4103 hba->pwr_info.lane_tx = 1;
4104 hba->pwr_info.pwr_rx = SLOWAUTO_MODE;
4105 hba->pwr_info.pwr_tx = SLOWAUTO_MODE;
4106 hba->pwr_info.hs_rate = 0;
4110 * ufshcd_get_max_pwr_mode - reads the max power mode negotiated with device
4111 * @hba: per-adapter instance
4113 static int ufshcd_get_max_pwr_mode(struct ufs_hba *hba)
4115 struct ufs_pa_layer_attr *pwr_info = &hba->max_pwr_info.info;
4117 if (hba->max_pwr_info.is_valid)
4120 pwr_info->pwr_tx = FAST_MODE;
4121 pwr_info->pwr_rx = FAST_MODE;
4122 pwr_info->hs_rate = PA_HS_MODE_B;
4124 /* Get the connected lane count */
4125 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_CONNECTEDRXDATALANES),
4126 &pwr_info->lane_rx);
4127 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_CONNECTEDTXDATALANES),
4128 &pwr_info->lane_tx);
4130 if (!pwr_info->lane_rx || !pwr_info->lane_tx) {
4131 dev_err(hba->dev, "%s: invalid connected lanes value. rx=%d, tx=%d\n",
4139 * First, get the maximum gears of HS speed.
4140 * If a zero value, it means there is no HSGEAR capability.
4141 * Then, get the maximum gears of PWM speed.
4143 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_MAXRXHSGEAR), &pwr_info->gear_rx);
4144 if (!pwr_info->gear_rx) {
4145 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_MAXRXPWMGEAR),
4146 &pwr_info->gear_rx);
4147 if (!pwr_info->gear_rx) {
4148 dev_err(hba->dev, "%s: invalid max pwm rx gear read = %d\n",
4149 __func__, pwr_info->gear_rx);
4152 pwr_info->pwr_rx = SLOW_MODE;
4155 ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_MAXRXHSGEAR),
4156 &pwr_info->gear_tx);
4157 if (!pwr_info->gear_tx) {
4158 ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_MAXRXPWMGEAR),
4159 &pwr_info->gear_tx);
4160 if (!pwr_info->gear_tx) {
4161 dev_err(hba->dev, "%s: invalid max pwm tx gear read = %d\n",
4162 __func__, pwr_info->gear_tx);
4165 pwr_info->pwr_tx = SLOW_MODE;
4168 hba->max_pwr_info.is_valid = true;
4172 static int ufshcd_change_power_mode(struct ufs_hba *hba,
4173 struct ufs_pa_layer_attr *pwr_mode)
4177 /* if already configured to the requested pwr_mode */
4178 if (!hba->force_pmc &&
4179 pwr_mode->gear_rx == hba->pwr_info.gear_rx &&
4180 pwr_mode->gear_tx == hba->pwr_info.gear_tx &&
4181 pwr_mode->lane_rx == hba->pwr_info.lane_rx &&
4182 pwr_mode->lane_tx == hba->pwr_info.lane_tx &&
4183 pwr_mode->pwr_rx == hba->pwr_info.pwr_rx &&
4184 pwr_mode->pwr_tx == hba->pwr_info.pwr_tx &&
4185 pwr_mode->hs_rate == hba->pwr_info.hs_rate) {
4186 dev_dbg(hba->dev, "%s: power already configured\n", __func__);
4191 * Configure attributes for power mode change with below.
4192 * - PA_RXGEAR, PA_ACTIVERXDATALANES, PA_RXTERMINATION,
4193 * - PA_TXGEAR, PA_ACTIVETXDATALANES, PA_TXTERMINATION,
4196 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_RXGEAR), pwr_mode->gear_rx);
4197 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_ACTIVERXDATALANES),
4199 if (pwr_mode->pwr_rx == FASTAUTO_MODE ||
4200 pwr_mode->pwr_rx == FAST_MODE)
4201 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_RXTERMINATION), TRUE);
4203 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_RXTERMINATION), FALSE);
4205 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TXGEAR), pwr_mode->gear_tx);
4206 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_ACTIVETXDATALANES),
4208 if (pwr_mode->pwr_tx == FASTAUTO_MODE ||
4209 pwr_mode->pwr_tx == FAST_MODE)
4210 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TXTERMINATION), TRUE);
4212 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TXTERMINATION), FALSE);
4214 if (pwr_mode->pwr_rx == FASTAUTO_MODE ||
4215 pwr_mode->pwr_tx == FASTAUTO_MODE ||
4216 pwr_mode->pwr_rx == FAST_MODE ||
4217 pwr_mode->pwr_tx == FAST_MODE)
4218 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_HSSERIES),
4221 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_PWRMODEUSERDATA0),
4222 DL_FC0ProtectionTimeOutVal_Default);
4223 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_PWRMODEUSERDATA1),
4224 DL_TC0ReplayTimeOutVal_Default);
4225 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_PWRMODEUSERDATA2),
4226 DL_AFC0ReqTimeOutVal_Default);
4227 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_PWRMODEUSERDATA3),
4228 DL_FC1ProtectionTimeOutVal_Default);
4229 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_PWRMODEUSERDATA4),
4230 DL_TC1ReplayTimeOutVal_Default);
4231 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_PWRMODEUSERDATA5),
4232 DL_AFC1ReqTimeOutVal_Default);
4234 ufshcd_dme_set(hba, UIC_ARG_MIB(DME_LocalFC0ProtectionTimeOutVal),
4235 DL_FC0ProtectionTimeOutVal_Default);
4236 ufshcd_dme_set(hba, UIC_ARG_MIB(DME_LocalTC0ReplayTimeOutVal),
4237 DL_TC0ReplayTimeOutVal_Default);
4238 ufshcd_dme_set(hba, UIC_ARG_MIB(DME_LocalAFC0ReqTimeOutVal),
4239 DL_AFC0ReqTimeOutVal_Default);
4241 ret = ufshcd_uic_change_pwr_mode(hba, pwr_mode->pwr_rx << 4
4242 | pwr_mode->pwr_tx);
4246 "%s: power mode change failed %d\n", __func__, ret);
4248 ufshcd_vops_pwr_change_notify(hba, POST_CHANGE, NULL,
4251 memcpy(&hba->pwr_info, pwr_mode,
4252 sizeof(struct ufs_pa_layer_attr));
4259 * ufshcd_config_pwr_mode - configure a new power mode
4260 * @hba: per-adapter instance
4261 * @desired_pwr_mode: desired power configuration
4263 int ufshcd_config_pwr_mode(struct ufs_hba *hba,
4264 struct ufs_pa_layer_attr *desired_pwr_mode)
4266 struct ufs_pa_layer_attr final_params = { 0 };
4269 ret = ufshcd_vops_pwr_change_notify(hba, PRE_CHANGE,
4270 desired_pwr_mode, &final_params);
4273 memcpy(&final_params, desired_pwr_mode, sizeof(final_params));
4275 ret = ufshcd_change_power_mode(hba, &final_params);
4279 EXPORT_SYMBOL_GPL(ufshcd_config_pwr_mode);
4282 * ufshcd_complete_dev_init() - checks device readiness
4283 * @hba: per-adapter instance
4285 * Set fDeviceInit flag and poll until device toggles it.
4287 static int ufshcd_complete_dev_init(struct ufs_hba *hba)
4290 bool flag_res = true;
4293 err = ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_SET_FLAG,
4294 QUERY_FLAG_IDN_FDEVICEINIT, 0, NULL);
4297 "%s setting fDeviceInit flag failed with error %d\n",
4302 /* Poll fDeviceInit flag to be cleared */
4303 timeout = ktime_add_ms(ktime_get(), FDEVICEINIT_COMPL_TIMEOUT);
4305 err = ufshcd_query_flag(hba, UPIU_QUERY_OPCODE_READ_FLAG,
4306 QUERY_FLAG_IDN_FDEVICEINIT, 0, &flag_res);
4309 usleep_range(5000, 10000);
4310 } while (ktime_before(ktime_get(), timeout));
4314 "%s reading fDeviceInit flag failed with error %d\n",
4316 } else if (flag_res) {
4318 "%s fDeviceInit was not cleared by the device\n",
4327 * ufshcd_make_hba_operational - Make UFS controller operational
4328 * @hba: per adapter instance
4330 * To bring UFS host controller to operational state,
4331 * 1. Enable required interrupts
4332 * 2. Configure interrupt aggregation
4333 * 3. Program UTRL and UTMRL base address
4334 * 4. Configure run-stop-registers
4336 * Returns 0 on success, non-zero value on failure
4338 int ufshcd_make_hba_operational(struct ufs_hba *hba)
4343 /* Enable required interrupts */
4344 ufshcd_enable_intr(hba, UFSHCD_ENABLE_INTRS);
4346 /* Configure interrupt aggregation */
4347 if (ufshcd_is_intr_aggr_allowed(hba))
4348 ufshcd_config_intr_aggr(hba, hba->nutrs - 1, INT_AGGR_DEF_TO);
4350 ufshcd_disable_intr_aggr(hba);
4352 /* Configure UTRL and UTMRL base address registers */
4353 ufshcd_writel(hba, lower_32_bits(hba->utrdl_dma_addr),
4354 REG_UTP_TRANSFER_REQ_LIST_BASE_L);
4355 ufshcd_writel(hba, upper_32_bits(hba->utrdl_dma_addr),
4356 REG_UTP_TRANSFER_REQ_LIST_BASE_H);
4357 ufshcd_writel(hba, lower_32_bits(hba->utmrdl_dma_addr),
4358 REG_UTP_TASK_REQ_LIST_BASE_L);
4359 ufshcd_writel(hba, upper_32_bits(hba->utmrdl_dma_addr),
4360 REG_UTP_TASK_REQ_LIST_BASE_H);
4363 * Make sure base address and interrupt setup are updated before
4364 * enabling the run/stop registers below.
4369 * UCRDY, UTMRLDY and UTRLRDY bits must be 1
4371 reg = ufshcd_readl(hba, REG_CONTROLLER_STATUS);
4372 if (!(ufshcd_get_lists_status(reg))) {
4373 ufshcd_enable_run_stop_reg(hba);
4376 "Host controller not ready to process requests");
4382 EXPORT_SYMBOL_GPL(ufshcd_make_hba_operational);
4385 * ufshcd_hba_stop - Send controller to reset state
4386 * @hba: per adapter instance
4388 static inline void ufshcd_hba_stop(struct ufs_hba *hba)
4390 unsigned long flags;
4394 * Obtain the host lock to prevent that the controller is disabled
4395 * while the UFS interrupt handler is active on another CPU.
4397 spin_lock_irqsave(hba->host->host_lock, flags);
4398 ufshcd_writel(hba, CONTROLLER_DISABLE, REG_CONTROLLER_ENABLE);
4399 spin_unlock_irqrestore(hba->host->host_lock, flags);
4401 err = ufshcd_wait_for_register(hba, REG_CONTROLLER_ENABLE,
4402 CONTROLLER_ENABLE, CONTROLLER_DISABLE,
4405 dev_err(hba->dev, "%s: Controller disable failed\n", __func__);
4409 * ufshcd_hba_execute_hce - initialize the controller
4410 * @hba: per adapter instance
4412 * The controller resets itself and controller firmware initialization
4413 * sequence kicks off. When controller is ready it will set
4414 * the Host Controller Enable bit to 1.
4416 * Returns 0 on success, non-zero value on failure
4418 static int ufshcd_hba_execute_hce(struct ufs_hba *hba)
4420 int retry_outer = 3;
4424 if (!ufshcd_is_hba_active(hba))
4425 /* change controller state to "reset state" */
4426 ufshcd_hba_stop(hba);
4428 /* UniPro link is disabled at this point */
4429 ufshcd_set_link_off(hba);
4431 ufshcd_vops_hce_enable_notify(hba, PRE_CHANGE);
4433 /* start controller initialization sequence */
4434 ufshcd_hba_start(hba);
4437 * To initialize a UFS host controller HCE bit must be set to 1.
4438 * During initialization the HCE bit value changes from 1->0->1.
4439 * When the host controller completes initialization sequence
4440 * it sets the value of HCE bit to 1. The same HCE bit is read back
4441 * to check if the controller has completed initialization sequence.
4442 * So without this delay the value HCE = 1, set in the previous
4443 * instruction might be read back.
4444 * This delay can be changed based on the controller.
4446 ufshcd_delay_us(hba->vps->hba_enable_delay_us, 100);
4448 /* wait for the host controller to complete initialization */
4450 while (ufshcd_is_hba_active(hba)) {
4455 "Controller enable failed\n");
4462 usleep_range(1000, 1100);
4465 /* enable UIC related interrupts */
4466 ufshcd_enable_intr(hba, UFSHCD_UIC_MASK);
4468 ufshcd_vops_hce_enable_notify(hba, POST_CHANGE);
4473 int ufshcd_hba_enable(struct ufs_hba *hba)
4477 if (hba->quirks & UFSHCI_QUIRK_BROKEN_HCE) {
4478 ufshcd_set_link_off(hba);
4479 ufshcd_vops_hce_enable_notify(hba, PRE_CHANGE);
4481 /* enable UIC related interrupts */
4482 ufshcd_enable_intr(hba, UFSHCD_UIC_MASK);
4483 ret = ufshcd_dme_reset(hba);
4485 ret = ufshcd_dme_enable(hba);
4487 ufshcd_vops_hce_enable_notify(hba, POST_CHANGE);
4490 "Host controller enable failed with non-hce\n");
4493 ret = ufshcd_hba_execute_hce(hba);
4498 EXPORT_SYMBOL_GPL(ufshcd_hba_enable);
4500 static int ufshcd_disable_tx_lcc(struct ufs_hba *hba, bool peer)
4502 int tx_lanes = 0, i, err = 0;
4505 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_CONNECTEDTXDATALANES),
4508 ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_CONNECTEDTXDATALANES),
4510 for (i = 0; i < tx_lanes; i++) {
4512 err = ufshcd_dme_set(hba,
4513 UIC_ARG_MIB_SEL(TX_LCC_ENABLE,
4514 UIC_ARG_MPHY_TX_GEN_SEL_INDEX(i)),
4517 err = ufshcd_dme_peer_set(hba,
4518 UIC_ARG_MIB_SEL(TX_LCC_ENABLE,
4519 UIC_ARG_MPHY_TX_GEN_SEL_INDEX(i)),
4522 dev_err(hba->dev, "%s: TX LCC Disable failed, peer = %d, lane = %d, err = %d",
4523 __func__, peer, i, err);
4531 static inline int ufshcd_disable_device_tx_lcc(struct ufs_hba *hba)
4533 return ufshcd_disable_tx_lcc(hba, true);
4536 void ufshcd_update_evt_hist(struct ufs_hba *hba, u32 id, u32 val)
4538 struct ufs_event_hist *e;
4540 if (id >= UFS_EVT_CNT)
4543 e = &hba->ufs_stats.event[id];
4544 e->val[e->pos] = val;
4545 e->tstamp[e->pos] = ktime_get();
4546 e->pos = (e->pos + 1) % UFS_EVENT_HIST_LENGTH;
4548 ufshcd_vops_event_notify(hba, id, &val);
4550 EXPORT_SYMBOL_GPL(ufshcd_update_evt_hist);
4553 * ufshcd_link_startup - Initialize unipro link startup
4554 * @hba: per adapter instance
4556 * Returns 0 for success, non-zero in case of failure
4558 static int ufshcd_link_startup(struct ufs_hba *hba)
4561 int retries = DME_LINKSTARTUP_RETRIES;
4562 bool link_startup_again = false;
4565 * If UFS device isn't active then we will have to issue link startup
4566 * 2 times to make sure the device state move to active.
4568 if (!ufshcd_is_ufs_dev_active(hba))
4569 link_startup_again = true;
4573 ufshcd_vops_link_startup_notify(hba, PRE_CHANGE);
4575 ret = ufshcd_dme_link_startup(hba);
4577 /* check if device is detected by inter-connect layer */
4578 if (!ret && !ufshcd_is_device_present(hba)) {
4579 ufshcd_update_evt_hist(hba,
4580 UFS_EVT_LINK_STARTUP_FAIL,
4582 dev_err(hba->dev, "%s: Device not present\n", __func__);
4588 * DME link lost indication is only received when link is up,
4589 * but we can't be sure if the link is up until link startup
4590 * succeeds. So reset the local Uni-Pro and try again.
4592 if (ret && ufshcd_hba_enable(hba)) {
4593 ufshcd_update_evt_hist(hba,
4594 UFS_EVT_LINK_STARTUP_FAIL,
4598 } while (ret && retries--);
4601 /* failed to get the link up... retire */
4602 ufshcd_update_evt_hist(hba,
4603 UFS_EVT_LINK_STARTUP_FAIL,
4608 if (link_startup_again) {
4609 link_startup_again = false;
4610 retries = DME_LINKSTARTUP_RETRIES;
4614 /* Mark that link is up in PWM-G1, 1-lane, SLOW-AUTO mode */
4615 ufshcd_init_pwr_info(hba);
4616 ufshcd_print_pwr_info(hba);
4618 if (hba->quirks & UFSHCD_QUIRK_BROKEN_LCC) {
4619 ret = ufshcd_disable_device_tx_lcc(hba);
4624 /* Include any host controller configuration via UIC commands */
4625 ret = ufshcd_vops_link_startup_notify(hba, POST_CHANGE);
4629 /* Clear UECPA once due to LINERESET has happened during LINK_STARTUP */
4630 ufshcd_readl(hba, REG_UIC_ERROR_CODE_PHY_ADAPTER_LAYER);
4631 ret = ufshcd_make_hba_operational(hba);
4634 dev_err(hba->dev, "link startup failed %d\n", ret);
4635 ufshcd_print_host_state(hba);
4636 ufshcd_print_pwr_info(hba);
4637 ufshcd_print_evt_hist(hba);
4643 * ufshcd_verify_dev_init() - Verify device initialization
4644 * @hba: per-adapter instance
4646 * Send NOP OUT UPIU and wait for NOP IN response to check whether the
4647 * device Transport Protocol (UTP) layer is ready after a reset.
4648 * If the UTP layer at the device side is not initialized, it may
4649 * not respond with NOP IN UPIU within timeout of %NOP_OUT_TIMEOUT
4650 * and we retry sending NOP OUT for %NOP_OUT_RETRIES iterations.
4652 static int ufshcd_verify_dev_init(struct ufs_hba *hba)
4657 ufshcd_hold(hba, false);
4658 mutex_lock(&hba->dev_cmd.lock);
4659 for (retries = NOP_OUT_RETRIES; retries > 0; retries--) {
4660 err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_NOP,
4663 if (!err || err == -ETIMEDOUT)
4666 dev_dbg(hba->dev, "%s: error %d retrying\n", __func__, err);
4668 mutex_unlock(&hba->dev_cmd.lock);
4669 ufshcd_release(hba);
4672 dev_err(hba->dev, "%s: NOP OUT failed %d\n", __func__, err);
4677 * ufshcd_set_queue_depth - set lun queue depth
4678 * @sdev: pointer to SCSI device
4680 * Read bLUQueueDepth value and activate scsi tagged command
4681 * queueing. For WLUN, queue depth is set to 1. For best-effort
4682 * cases (bLUQueueDepth = 0) the queue depth is set to a maximum
4683 * value that host can queue.
4685 static void ufshcd_set_queue_depth(struct scsi_device *sdev)
4689 struct ufs_hba *hba;
4691 hba = shost_priv(sdev->host);
4693 lun_qdepth = hba->nutrs;
4694 ret = ufshcd_read_unit_desc_param(hba,
4695 ufshcd_scsi_to_upiu_lun(sdev->lun),
4696 UNIT_DESC_PARAM_LU_Q_DEPTH,
4698 sizeof(lun_qdepth));
4700 /* Some WLUN doesn't support unit descriptor */
4701 if (ret == -EOPNOTSUPP)
4703 else if (!lun_qdepth)
4704 /* eventually, we can figure out the real queue depth */
4705 lun_qdepth = hba->nutrs;
4707 lun_qdepth = min_t(int, lun_qdepth, hba->nutrs);
4709 dev_dbg(hba->dev, "%s: activate tcq with queue depth %d\n",
4710 __func__, lun_qdepth);
4711 scsi_change_queue_depth(sdev, lun_qdepth);
4715 * ufshcd_get_lu_wp - returns the "b_lu_write_protect" from UNIT DESCRIPTOR
4716 * @hba: per-adapter instance
4717 * @lun: UFS device lun id
4718 * @b_lu_write_protect: pointer to buffer to hold the LU's write protect info
4720 * Returns 0 in case of success and b_lu_write_protect status would be returned
4721 * @b_lu_write_protect parameter.
4722 * Returns -ENOTSUPP if reading b_lu_write_protect is not supported.
4723 * Returns -EINVAL in case of invalid parameters passed to this function.
4725 static int ufshcd_get_lu_wp(struct ufs_hba *hba,
4727 u8 *b_lu_write_protect)
4731 if (!b_lu_write_protect)
4734 * According to UFS device spec, RPMB LU can't be write
4735 * protected so skip reading bLUWriteProtect parameter for
4736 * it. For other W-LUs, UNIT DESCRIPTOR is not available.
4738 else if (lun >= hba->dev_info.max_lu_supported)
4741 ret = ufshcd_read_unit_desc_param(hba,
4743 UNIT_DESC_PARAM_LU_WR_PROTECT,
4745 sizeof(*b_lu_write_protect));
4750 * ufshcd_get_lu_power_on_wp_status - get LU's power on write protect
4752 * @hba: per-adapter instance
4753 * @sdev: pointer to SCSI device
4756 static inline void ufshcd_get_lu_power_on_wp_status(struct ufs_hba *hba,
4757 struct scsi_device *sdev)
4759 if (hba->dev_info.f_power_on_wp_en &&
4760 !hba->dev_info.is_lu_power_on_wp) {
4761 u8 b_lu_write_protect;
4763 if (!ufshcd_get_lu_wp(hba, ufshcd_scsi_to_upiu_lun(sdev->lun),
4764 &b_lu_write_protect) &&
4765 (b_lu_write_protect == UFS_LU_POWER_ON_WP))
4766 hba->dev_info.is_lu_power_on_wp = true;
4771 * ufshcd_slave_alloc - handle initial SCSI device configurations
4772 * @sdev: pointer to SCSI device
4776 static int ufshcd_slave_alloc(struct scsi_device *sdev)
4778 struct ufs_hba *hba;
4780 hba = shost_priv(sdev->host);
4782 /* Mode sense(6) is not supported by UFS, so use Mode sense(10) */
4783 sdev->use_10_for_ms = 1;
4785 /* DBD field should be set to 1 in mode sense(10) */
4786 sdev->set_dbd_for_ms = 1;
4788 /* allow SCSI layer to restart the device in case of errors */
4789 sdev->allow_restart = 1;
4791 /* REPORT SUPPORTED OPERATION CODES is not supported */
4792 sdev->no_report_opcodes = 1;
4794 /* WRITE_SAME command is not supported */
4795 sdev->no_write_same = 1;
4797 ufshcd_set_queue_depth(sdev);
4799 ufshcd_get_lu_power_on_wp_status(hba, sdev);
4805 * ufshcd_change_queue_depth - change queue depth
4806 * @sdev: pointer to SCSI device
4807 * @depth: required depth to set
4809 * Change queue depth and make sure the max. limits are not crossed.
4811 static int ufshcd_change_queue_depth(struct scsi_device *sdev, int depth)
4813 struct ufs_hba *hba = shost_priv(sdev->host);
4815 if (depth > hba->nutrs)
4817 return scsi_change_queue_depth(sdev, depth);
4821 * ufshcd_slave_configure - adjust SCSI device configurations
4822 * @sdev: pointer to SCSI device
4824 static int ufshcd_slave_configure(struct scsi_device *sdev)
4826 struct ufs_hba *hba = shost_priv(sdev->host);
4827 struct request_queue *q = sdev->request_queue;
4829 blk_queue_update_dma_pad(q, PRDT_DATA_BYTE_COUNT_PAD - 1);
4831 if (ufshcd_is_rpm_autosuspend_allowed(hba))
4832 sdev->rpm_autosuspend = 1;
4834 ufshcd_crypto_setup_rq_keyslot_manager(hba, q);
4840 * ufshcd_slave_destroy - remove SCSI device configurations
4841 * @sdev: pointer to SCSI device
4843 static void ufshcd_slave_destroy(struct scsi_device *sdev)
4845 struct ufs_hba *hba;
4847 hba = shost_priv(sdev->host);
4848 /* Drop the reference as it won't be needed anymore */
4849 if (ufshcd_scsi_to_upiu_lun(sdev->lun) == UFS_UPIU_UFS_DEVICE_WLUN) {
4850 unsigned long flags;
4852 spin_lock_irqsave(hba->host->host_lock, flags);
4853 hba->sdev_ufs_device = NULL;
4854 spin_unlock_irqrestore(hba->host->host_lock, flags);
4859 * ufshcd_scsi_cmd_status - Update SCSI command result based on SCSI status
4860 * @lrbp: pointer to local reference block of completed command
4861 * @scsi_status: SCSI command status
4863 * Returns value base on SCSI command status
4866 ufshcd_scsi_cmd_status(struct ufshcd_lrb *lrbp, int scsi_status)
4870 switch (scsi_status) {
4871 case SAM_STAT_CHECK_CONDITION:
4872 ufshcd_copy_sense_data(lrbp);
4875 result |= DID_OK << 16 |
4876 COMMAND_COMPLETE << 8 |
4879 case SAM_STAT_TASK_SET_FULL:
4881 case SAM_STAT_TASK_ABORTED:
4882 ufshcd_copy_sense_data(lrbp);
4883 result |= scsi_status;
4886 result |= DID_ERROR << 16;
4888 } /* end of switch */
4894 * ufshcd_transfer_rsp_status - Get overall status of the response
4895 * @hba: per adapter instance
4896 * @lrbp: pointer to local reference block of completed command
4898 * Returns result of the command to notify SCSI midlayer
4901 ufshcd_transfer_rsp_status(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
4907 /* overall command status of utrd */
4908 ocs = ufshcd_get_tr_ocs(lrbp);
4910 if (hba->quirks & UFSHCD_QUIRK_BROKEN_OCS_FATAL_ERROR) {
4911 if (be32_to_cpu(lrbp->ucd_rsp_ptr->header.dword_1) &
4912 MASK_RSP_UPIU_RESULT)
4918 result = ufshcd_get_req_rsp(lrbp->ucd_rsp_ptr);
4919 hba->ufs_stats.last_hibern8_exit_tstamp = ktime_set(0, 0);
4921 case UPIU_TRANSACTION_RESPONSE:
4923 * get the response UPIU result to extract
4924 * the SCSI command status
4926 result = ufshcd_get_rsp_upiu_result(lrbp->ucd_rsp_ptr);
4929 * get the result based on SCSI status response
4930 * to notify the SCSI midlayer of the command status
4932 scsi_status = result & MASK_SCSI_STATUS;
4933 result = ufshcd_scsi_cmd_status(lrbp, scsi_status);
4936 * Currently we are only supporting BKOPs exception
4937 * events hence we can ignore BKOPs exception event
4938 * during power management callbacks. BKOPs exception
4939 * event is not expected to be raised in runtime suspend
4940 * callback as it allows the urgent bkops.
4941 * During system suspend, we are anyway forcefully
4942 * disabling the bkops and if urgent bkops is needed
4943 * it will be enabled on system resume. Long term
4944 * solution could be to abort the system suspend if
4945 * UFS device needs urgent BKOPs.
4947 if (!hba->pm_op_in_progress &&
4948 ufshcd_is_exception_event(lrbp->ucd_rsp_ptr) &&
4949 schedule_work(&hba->eeh_work)) {
4951 * Prevent suspend once eeh_work is scheduled
4952 * to avoid deadlock between ufshcd_suspend
4953 * and exception event handler.
4955 pm_runtime_get_noresume(hba->dev);
4958 case UPIU_TRANSACTION_REJECT_UPIU:
4959 /* TODO: handle Reject UPIU Response */
4960 result = DID_ERROR << 16;
4962 "Reject UPIU not fully implemented\n");
4966 "Unexpected request response code = %x\n",
4968 result = DID_ERROR << 16;
4973 result |= DID_ABORT << 16;
4975 case OCS_INVALID_COMMAND_STATUS:
4976 result |= DID_REQUEUE << 16;
4978 case OCS_INVALID_CMD_TABLE_ATTR:
4979 case OCS_INVALID_PRDT_ATTR:
4980 case OCS_MISMATCH_DATA_BUF_SIZE:
4981 case OCS_MISMATCH_RESP_UPIU_SIZE:
4982 case OCS_PEER_COMM_FAILURE:
4983 case OCS_FATAL_ERROR:
4984 case OCS_DEVICE_FATAL_ERROR:
4985 case OCS_INVALID_CRYPTO_CONFIG:
4986 case OCS_GENERAL_CRYPTO_ERROR:
4988 result |= DID_ERROR << 16;
4990 "OCS error from controller = %x for tag %d\n",
4991 ocs, lrbp->task_tag);
4992 ufshcd_print_evt_hist(hba);
4993 ufshcd_print_host_state(hba);
4995 } /* end of switch */
4997 if ((host_byte(result) != DID_OK) &&
4998 (host_byte(result) != DID_REQUEUE) && !hba->silence_err_logs)
4999 ufshcd_print_trs(hba, 1 << lrbp->task_tag, true);
5004 * ufshcd_uic_cmd_compl - handle completion of uic command
5005 * @hba: per adapter instance
5006 * @intr_status: interrupt status generated by the controller
5009 * IRQ_HANDLED - If interrupt is valid
5010 * IRQ_NONE - If invalid interrupt
5012 static irqreturn_t ufshcd_uic_cmd_compl(struct ufs_hba *hba, u32 intr_status)
5014 irqreturn_t retval = IRQ_NONE;
5016 if ((intr_status & UIC_COMMAND_COMPL) && hba->active_uic_cmd) {
5017 hba->active_uic_cmd->argument2 |=
5018 ufshcd_get_uic_cmd_result(hba);
5019 hba->active_uic_cmd->argument3 =
5020 ufshcd_get_dme_attr_val(hba);
5021 if (!hba->uic_async_done)
5022 hba->active_uic_cmd->cmd_active = 0;
5023 complete(&hba->active_uic_cmd->done);
5024 retval = IRQ_HANDLED;
5027 if ((intr_status & UFSHCD_UIC_PWR_MASK) && hba->uic_async_done) {
5028 hba->active_uic_cmd->cmd_active = 0;
5029 complete(hba->uic_async_done);
5030 retval = IRQ_HANDLED;
5033 if (retval == IRQ_HANDLED)
5034 ufshcd_add_uic_command_trace(hba, hba->active_uic_cmd,
5040 * __ufshcd_transfer_req_compl - handle SCSI and query command completion
5041 * @hba: per adapter instance
5042 * @completed_reqs: requests to complete
5044 static void __ufshcd_transfer_req_compl(struct ufs_hba *hba,
5045 unsigned long completed_reqs)
5047 struct ufshcd_lrb *lrbp;
5048 struct scsi_cmnd *cmd;
5051 bool update_scaling = false;
5053 for_each_set_bit(index, &completed_reqs, hba->nutrs) {
5054 lrbp = &hba->lrb[index];
5055 lrbp->in_use = false;
5056 lrbp->compl_time_stamp = ktime_get();
5059 ufshcd_add_command_trace(hba, index, "complete");
5060 result = ufshcd_transfer_rsp_status(hba, lrbp);
5061 scsi_dma_unmap(cmd);
5062 cmd->result = result;
5063 /* Mark completed command as NULL in LRB */
5065 /* Do not touch lrbp after scsi done */
5066 cmd->scsi_done(cmd);
5067 __ufshcd_release(hba);
5068 update_scaling = true;
5069 } else if (lrbp->command_type == UTP_CMD_TYPE_DEV_MANAGE ||
5070 lrbp->command_type == UTP_CMD_TYPE_UFS_STORAGE) {
5071 if (hba->dev_cmd.complete) {
5072 ufshcd_add_command_trace(hba, index,
5074 complete(hba->dev_cmd.complete);
5075 update_scaling = true;
5078 if (ufshcd_is_clkscaling_supported(hba) && update_scaling)
5079 hba->clk_scaling.active_reqs--;
5082 /* clear corresponding bits of completed commands */
5083 hba->outstanding_reqs ^= completed_reqs;
5085 ufshcd_clk_scaling_update_busy(hba);
5089 * ufshcd_transfer_req_compl - handle SCSI and query command completion
5090 * @hba: per adapter instance
5093 * IRQ_HANDLED - If interrupt is valid
5094 * IRQ_NONE - If invalid interrupt
5096 static irqreturn_t ufshcd_transfer_req_compl(struct ufs_hba *hba)
5098 unsigned long completed_reqs;
5101 /* Resetting interrupt aggregation counters first and reading the
5102 * DOOR_BELL afterward allows us to handle all the completed requests.
5103 * In order to prevent other interrupts starvation the DB is read once
5104 * after reset. The down side of this solution is the possibility of
5105 * false interrupt if device completes another request after resetting
5106 * aggregation and before reading the DB.
5108 if (ufshcd_is_intr_aggr_allowed(hba) &&
5109 !(hba->quirks & UFSHCI_QUIRK_SKIP_RESET_INTR_AGGR))
5110 ufshcd_reset_intr_aggr(hba);
5112 tr_doorbell = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
5113 completed_reqs = tr_doorbell ^ hba->outstanding_reqs;
5115 if (completed_reqs) {
5116 __ufshcd_transfer_req_compl(hba, completed_reqs);
5124 * ufshcd_disable_ee - disable exception event
5125 * @hba: per-adapter instance
5126 * @mask: exception event to disable
5128 * Disables exception event in the device so that the EVENT_ALERT
5131 * Returns zero on success, non-zero error value on failure.
5133 static int ufshcd_disable_ee(struct ufs_hba *hba, u16 mask)
5138 if (!(hba->ee_ctrl_mask & mask))
5141 val = hba->ee_ctrl_mask & ~mask;
5142 val &= MASK_EE_STATUS;
5143 err = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_WRITE_ATTR,
5144 QUERY_ATTR_IDN_EE_CONTROL, 0, 0, &val);
5146 hba->ee_ctrl_mask &= ~mask;
5152 * ufshcd_enable_ee - enable exception event
5153 * @hba: per-adapter instance
5154 * @mask: exception event to enable
5156 * Enable corresponding exception event in the device to allow
5157 * device to alert host in critical scenarios.
5159 * Returns zero on success, non-zero error value on failure.
5161 static int ufshcd_enable_ee(struct ufs_hba *hba, u16 mask)
5166 if (hba->ee_ctrl_mask & mask)
5169 val = hba->ee_ctrl_mask | mask;
5170 val &= MASK_EE_STATUS;
5171 err = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_WRITE_ATTR,
5172 QUERY_ATTR_IDN_EE_CONTROL, 0, 0, &val);
5174 hba->ee_ctrl_mask |= mask;
5180 * ufshcd_enable_auto_bkops - Allow device managed BKOPS
5181 * @hba: per-adapter instance
5183 * Allow device to manage background operations on its own. Enabling
5184 * this might lead to inconsistent latencies during normal data transfers
5185 * as the device is allowed to manage its own way of handling background
5188 * Returns zero on success, non-zero on failure.
5190 static int ufshcd_enable_auto_bkops(struct ufs_hba *hba)
5194 if (hba->auto_bkops_enabled)
5197 err = ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_SET_FLAG,
5198 QUERY_FLAG_IDN_BKOPS_EN, 0, NULL);
5200 dev_err(hba->dev, "%s: failed to enable bkops %d\n",
5205 hba->auto_bkops_enabled = true;
5206 trace_ufshcd_auto_bkops_state(dev_name(hba->dev), "Enabled");
5208 /* No need of URGENT_BKOPS exception from the device */
5209 err = ufshcd_disable_ee(hba, MASK_EE_URGENT_BKOPS);
5211 dev_err(hba->dev, "%s: failed to disable exception event %d\n",
5218 * ufshcd_disable_auto_bkops - block device in doing background operations
5219 * @hba: per-adapter instance
5221 * Disabling background operations improves command response latency but
5222 * has drawback of device moving into critical state where the device is
5223 * not-operable. Make sure to call ufshcd_enable_auto_bkops() whenever the
5224 * host is idle so that BKOPS are managed effectively without any negative
5227 * Returns zero on success, non-zero on failure.
5229 static int ufshcd_disable_auto_bkops(struct ufs_hba *hba)
5233 if (!hba->auto_bkops_enabled)
5237 * If host assisted BKOPs is to be enabled, make sure
5238 * urgent bkops exception is allowed.
5240 err = ufshcd_enable_ee(hba, MASK_EE_URGENT_BKOPS);
5242 dev_err(hba->dev, "%s: failed to enable exception event %d\n",
5247 err = ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_CLEAR_FLAG,
5248 QUERY_FLAG_IDN_BKOPS_EN, 0, NULL);
5250 dev_err(hba->dev, "%s: failed to disable bkops %d\n",
5252 ufshcd_disable_ee(hba, MASK_EE_URGENT_BKOPS);
5256 hba->auto_bkops_enabled = false;
5257 trace_ufshcd_auto_bkops_state(dev_name(hba->dev), "Disabled");
5258 hba->is_urgent_bkops_lvl_checked = false;
5264 * ufshcd_force_reset_auto_bkops - force reset auto bkops state
5265 * @hba: per adapter instance
5267 * After a device reset the device may toggle the BKOPS_EN flag
5268 * to default value. The s/w tracking variables should be updated
5269 * as well. This function would change the auto-bkops state based on
5270 * UFSHCD_CAP_KEEP_AUTO_BKOPS_ENABLED_EXCEPT_SUSPEND.
5272 static void ufshcd_force_reset_auto_bkops(struct ufs_hba *hba)
5274 if (ufshcd_keep_autobkops_enabled_except_suspend(hba)) {
5275 hba->auto_bkops_enabled = false;
5276 hba->ee_ctrl_mask |= MASK_EE_URGENT_BKOPS;
5277 ufshcd_enable_auto_bkops(hba);
5279 hba->auto_bkops_enabled = true;
5280 hba->ee_ctrl_mask &= ~MASK_EE_URGENT_BKOPS;
5281 ufshcd_disable_auto_bkops(hba);
5283 hba->urgent_bkops_lvl = BKOPS_STATUS_PERF_IMPACT;
5284 hba->is_urgent_bkops_lvl_checked = false;
5287 static inline int ufshcd_get_bkops_status(struct ufs_hba *hba, u32 *status)
5289 return ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
5290 QUERY_ATTR_IDN_BKOPS_STATUS, 0, 0, status);
5294 * ufshcd_bkops_ctrl - control the auto bkops based on current bkops status
5295 * @hba: per-adapter instance
5296 * @status: bkops_status value
5298 * Read the bkops_status from the UFS device and Enable fBackgroundOpsEn
5299 * flag in the device to permit background operations if the device
5300 * bkops_status is greater than or equal to "status" argument passed to
5301 * this function, disable otherwise.
5303 * Returns 0 for success, non-zero in case of failure.
5305 * NOTE: Caller of this function can check the "hba->auto_bkops_enabled" flag
5306 * to know whether auto bkops is enabled or disabled after this function
5307 * returns control to it.
5309 static int ufshcd_bkops_ctrl(struct ufs_hba *hba,
5310 enum bkops_status status)
5313 u32 curr_status = 0;
5315 err = ufshcd_get_bkops_status(hba, &curr_status);
5317 dev_err(hba->dev, "%s: failed to get BKOPS status %d\n",
5320 } else if (curr_status > BKOPS_STATUS_MAX) {
5321 dev_err(hba->dev, "%s: invalid BKOPS status %d\n",
5322 __func__, curr_status);
5327 if (curr_status >= status)
5328 err = ufshcd_enable_auto_bkops(hba);
5330 err = ufshcd_disable_auto_bkops(hba);
5336 * ufshcd_urgent_bkops - handle urgent bkops exception event
5337 * @hba: per-adapter instance
5339 * Enable fBackgroundOpsEn flag in the device to permit background
5342 * If BKOPs is enabled, this function returns 0, 1 if the bkops in not enabled
5343 * and negative error value for any other failure.
5345 static int ufshcd_urgent_bkops(struct ufs_hba *hba)
5347 return ufshcd_bkops_ctrl(hba, hba->urgent_bkops_lvl);
5350 static inline int ufshcd_get_ee_status(struct ufs_hba *hba, u32 *status)
5352 return ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
5353 QUERY_ATTR_IDN_EE_STATUS, 0, 0, status);
5356 static void ufshcd_bkops_exception_event_handler(struct ufs_hba *hba)
5359 u32 curr_status = 0;
5361 if (hba->is_urgent_bkops_lvl_checked)
5362 goto enable_auto_bkops;
5364 err = ufshcd_get_bkops_status(hba, &curr_status);
5366 dev_err(hba->dev, "%s: failed to get BKOPS status %d\n",
5372 * We are seeing that some devices are raising the urgent bkops
5373 * exception events even when BKOPS status doesn't indicate performace
5374 * impacted or critical. Handle these device by determining their urgent
5375 * bkops status at runtime.
5377 if (curr_status < BKOPS_STATUS_PERF_IMPACT) {
5378 dev_err(hba->dev, "%s: device raised urgent BKOPS exception for bkops status %d\n",
5379 __func__, curr_status);
5380 /* update the current status as the urgent bkops level */
5381 hba->urgent_bkops_lvl = curr_status;
5382 hba->is_urgent_bkops_lvl_checked = true;
5386 err = ufshcd_enable_auto_bkops(hba);
5389 dev_err(hba->dev, "%s: failed to handle urgent bkops %d\n",
5393 static int ufshcd_wb_ctrl(struct ufs_hba *hba, bool enable)
5397 enum query_opcode opcode;
5399 if (!ufshcd_is_wb_allowed(hba))
5402 if (!(enable ^ hba->wb_enabled))
5405 opcode = UPIU_QUERY_OPCODE_SET_FLAG;
5407 opcode = UPIU_QUERY_OPCODE_CLEAR_FLAG;
5409 index = ufshcd_wb_get_query_index(hba);
5410 ret = ufshcd_query_flag_retry(hba, opcode,
5411 QUERY_FLAG_IDN_WB_EN, index, NULL);
5413 dev_err(hba->dev, "%s write booster %s failed %d\n",
5414 __func__, enable ? "enable" : "disable", ret);
5418 hba->wb_enabled = enable;
5419 dev_dbg(hba->dev, "%s write booster %s %d\n",
5420 __func__, enable ? "enable" : "disable", ret);
5425 static int ufshcd_wb_toggle_flush_during_h8(struct ufs_hba *hba, bool set)
5431 val = UPIU_QUERY_OPCODE_SET_FLAG;
5433 val = UPIU_QUERY_OPCODE_CLEAR_FLAG;
5435 index = ufshcd_wb_get_query_index(hba);
5436 return ufshcd_query_flag_retry(hba, val,
5437 QUERY_FLAG_IDN_WB_BUFF_FLUSH_DURING_HIBERN8,
5441 static inline void ufshcd_wb_toggle_flush(struct ufs_hba *hba, bool enable)
5444 ufshcd_wb_buf_flush_enable(hba);
5446 ufshcd_wb_buf_flush_disable(hba);
5450 static int ufshcd_wb_buf_flush_enable(struct ufs_hba *hba)
5455 if (!ufshcd_is_wb_allowed(hba) || hba->wb_buf_flush_enabled)
5458 index = ufshcd_wb_get_query_index(hba);
5459 ret = ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_SET_FLAG,
5460 QUERY_FLAG_IDN_WB_BUFF_FLUSH_EN,
5463 dev_err(hba->dev, "%s WB - buf flush enable failed %d\n",
5466 hba->wb_buf_flush_enabled = true;
5468 dev_dbg(hba->dev, "WB - Flush enabled: %d\n", ret);
5472 static int ufshcd_wb_buf_flush_disable(struct ufs_hba *hba)
5477 if (!ufshcd_is_wb_allowed(hba) || !hba->wb_buf_flush_enabled)
5480 index = ufshcd_wb_get_query_index(hba);
5481 ret = ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_CLEAR_FLAG,
5482 QUERY_FLAG_IDN_WB_BUFF_FLUSH_EN,
5485 dev_warn(hba->dev, "%s: WB - buf flush disable failed %d\n",
5488 hba->wb_buf_flush_enabled = false;
5489 dev_dbg(hba->dev, "WB - Flush disabled: %d\n", ret);
5495 static bool ufshcd_wb_presrv_usrspc_keep_vcc_on(struct ufs_hba *hba,
5502 index = ufshcd_wb_get_query_index(hba);
5503 ret = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
5504 QUERY_ATTR_IDN_CURR_WB_BUFF_SIZE,
5505 index, 0, &cur_buf);
5507 dev_err(hba->dev, "%s dCurWriteBoosterBufferSize read failed %d\n",
5513 dev_info(hba->dev, "dCurWBBuf: %d WB disabled until free-space is available\n",
5517 /* Let it continue to flush when available buffer exceeds threshold */
5518 if (avail_buf < hba->vps->wb_flush_threshold)
5524 static bool ufshcd_wb_need_flush(struct ufs_hba *hba)
5530 if (!ufshcd_is_wb_allowed(hba))
5533 * The ufs device needs the vcc to be ON to flush.
5534 * With user-space reduction enabled, it's enough to enable flush
5535 * by checking only the available buffer. The threshold
5536 * defined here is > 90% full.
5537 * With user-space preserved enabled, the current-buffer
5538 * should be checked too because the wb buffer size can reduce
5539 * when disk tends to be full. This info is provided by current
5540 * buffer (dCurrentWriteBoosterBufferSize). There's no point in
5541 * keeping vcc on when current buffer is empty.
5543 index = ufshcd_wb_get_query_index(hba);
5544 ret = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
5545 QUERY_ATTR_IDN_AVAIL_WB_BUFF_SIZE,
5546 index, 0, &avail_buf);
5548 dev_warn(hba->dev, "%s dAvailableWriteBoosterBufferSize read failed %d\n",
5553 if (!hba->dev_info.b_presrv_uspc_en) {
5554 if (avail_buf <= UFS_WB_BUF_REMAIN_PERCENT(10))
5559 return ufshcd_wb_presrv_usrspc_keep_vcc_on(hba, avail_buf);
5562 static void ufshcd_rpm_dev_flush_recheck_work(struct work_struct *work)
5564 struct ufs_hba *hba = container_of(to_delayed_work(work),
5566 rpm_dev_flush_recheck_work);
5568 * To prevent unnecessary VCC power drain after device finishes
5569 * WriteBooster buffer flush or Auto BKOPs, force runtime resume
5570 * after a certain delay to recheck the threshold by next runtime
5573 pm_runtime_get_sync(hba->dev);
5574 pm_runtime_put_sync(hba->dev);
5578 * ufshcd_exception_event_handler - handle exceptions raised by device
5579 * @work: pointer to work data
5581 * Read bExceptionEventStatus attribute from the device and handle the
5582 * exception event accordingly.
5584 static void ufshcd_exception_event_handler(struct work_struct *work)
5586 struct ufs_hba *hba;
5589 hba = container_of(work, struct ufs_hba, eeh_work);
5591 pm_runtime_get_sync(hba->dev);
5592 ufshcd_scsi_block_requests(hba);
5593 err = ufshcd_get_ee_status(hba, &status);
5595 dev_err(hba->dev, "%s: failed to get exception status %d\n",
5600 status &= hba->ee_ctrl_mask;
5602 if (status & MASK_EE_URGENT_BKOPS)
5603 ufshcd_bkops_exception_event_handler(hba);
5606 ufshcd_scsi_unblock_requests(hba);
5608 * pm_runtime_get_noresume is called while scheduling
5609 * eeh_work to avoid suspend racing with exception work.
5610 * Hence decrement usage counter using pm_runtime_put_noidle
5611 * to allow suspend on completion of exception event handler.
5613 pm_runtime_put_noidle(hba->dev);
5614 pm_runtime_put(hba->dev);
5618 /* Complete requests that have door-bell cleared */
5619 static void ufshcd_complete_requests(struct ufs_hba *hba)
5621 ufshcd_transfer_req_compl(hba);
5622 ufshcd_tmc_handler(hba);
5626 * ufshcd_quirk_dl_nac_errors - This function checks if error handling is
5627 * to recover from the DL NAC errors or not.
5628 * @hba: per-adapter instance
5630 * Returns true if error handling is required, false otherwise
5632 static bool ufshcd_quirk_dl_nac_errors(struct ufs_hba *hba)
5634 unsigned long flags;
5635 bool err_handling = true;
5637 spin_lock_irqsave(hba->host->host_lock, flags);
5639 * UFS_DEVICE_QUIRK_RECOVERY_FROM_DL_NAC_ERRORS only workaround the
5640 * device fatal error and/or DL NAC & REPLAY timeout errors.
5642 if (hba->saved_err & (CONTROLLER_FATAL_ERROR | SYSTEM_BUS_FATAL_ERROR))
5645 if ((hba->saved_err & DEVICE_FATAL_ERROR) ||
5646 ((hba->saved_err & UIC_ERROR) &&
5647 (hba->saved_uic_err & UFSHCD_UIC_DL_TCx_REPLAY_ERROR)))
5650 if ((hba->saved_err & UIC_ERROR) &&
5651 (hba->saved_uic_err & UFSHCD_UIC_DL_NAC_RECEIVED_ERROR)) {
5654 * wait for 50ms to see if we can get any other errors or not.
5656 spin_unlock_irqrestore(hba->host->host_lock, flags);
5658 spin_lock_irqsave(hba->host->host_lock, flags);
5661 * now check if we have got any other severe errors other than
5664 if ((hba->saved_err & INT_FATAL_ERRORS) ||
5665 ((hba->saved_err & UIC_ERROR) &&
5666 (hba->saved_uic_err & ~UFSHCD_UIC_DL_NAC_RECEIVED_ERROR)))
5670 * As DL NAC is the only error received so far, send out NOP
5671 * command to confirm if link is still active or not.
5672 * - If we don't get any response then do error recovery.
5673 * - If we get response then clear the DL NAC error bit.
5676 spin_unlock_irqrestore(hba->host->host_lock, flags);
5677 err = ufshcd_verify_dev_init(hba);
5678 spin_lock_irqsave(hba->host->host_lock, flags);
5683 /* Link seems to be alive hence ignore the DL NAC errors */
5684 if (hba->saved_uic_err == UFSHCD_UIC_DL_NAC_RECEIVED_ERROR)
5685 hba->saved_err &= ~UIC_ERROR;
5686 /* clear NAC error */
5687 hba->saved_uic_err &= ~UFSHCD_UIC_DL_NAC_RECEIVED_ERROR;
5688 if (!hba->saved_uic_err)
5689 err_handling = false;
5692 spin_unlock_irqrestore(hba->host->host_lock, flags);
5693 return err_handling;
5696 /* host lock must be held before calling this func */
5697 static inline bool ufshcd_is_saved_err_fatal(struct ufs_hba *hba)
5699 return (hba->saved_uic_err & UFSHCD_UIC_DL_PA_INIT_ERROR) ||
5700 (hba->saved_err & (INT_FATAL_ERRORS | UFSHCD_UIC_HIBERN8_MASK));
5703 /* host lock must be held before calling this func */
5704 static inline void ufshcd_schedule_eh_work(struct ufs_hba *hba)
5706 /* handle fatal errors only when link is not in error state */
5707 if (hba->ufshcd_state != UFSHCD_STATE_ERROR) {
5708 if (hba->force_reset || ufshcd_is_link_broken(hba) ||
5709 ufshcd_is_saved_err_fatal(hba))
5710 hba->ufshcd_state = UFSHCD_STATE_EH_SCHEDULED_FATAL;
5712 hba->ufshcd_state = UFSHCD_STATE_EH_SCHEDULED_NON_FATAL;
5713 queue_work(hba->eh_wq, &hba->eh_work);
5717 static void ufshcd_err_handling_prepare(struct ufs_hba *hba)
5719 pm_runtime_get_sync(hba->dev);
5720 if (pm_runtime_status_suspended(hba->dev) || hba->is_sys_suspended) {
5721 enum ufs_pm_op pm_op;
5724 * Don't assume anything of pm_runtime_get_sync(), if
5725 * resume fails, irq and clocks can be OFF, and powers
5726 * can be OFF or in LPM.
5728 ufshcd_setup_hba_vreg(hba, true);
5729 ufshcd_enable_irq(hba);
5730 ufshcd_setup_vreg(hba, true);
5731 ufshcd_config_vreg_hpm(hba, hba->vreg_info.vccq);
5732 ufshcd_config_vreg_hpm(hba, hba->vreg_info.vccq2);
5733 ufshcd_hold(hba, false);
5734 if (!ufshcd_is_clkgating_allowed(hba))
5735 ufshcd_setup_clocks(hba, true);
5736 ufshcd_release(hba);
5737 pm_op = hba->is_sys_suspended ? UFS_SYSTEM_PM : UFS_RUNTIME_PM;
5738 ufshcd_vops_resume(hba, pm_op);
5740 ufshcd_hold(hba, false);
5741 if (hba->clk_scaling.is_allowed) {
5742 cancel_work_sync(&hba->clk_scaling.suspend_work);
5743 cancel_work_sync(&hba->clk_scaling.resume_work);
5744 ufshcd_suspend_clkscaling(hba);
5749 static void ufshcd_err_handling_unprepare(struct ufs_hba *hba)
5751 ufshcd_release(hba);
5752 if (hba->clk_scaling.is_allowed)
5753 ufshcd_resume_clkscaling(hba);
5754 pm_runtime_put(hba->dev);
5757 static inline bool ufshcd_err_handling_should_stop(struct ufs_hba *hba)
5759 return (!hba->is_powered || hba->ufshcd_state == UFSHCD_STATE_ERROR ||
5760 (!(hba->saved_err || hba->saved_uic_err || hba->force_reset ||
5761 ufshcd_is_link_broken(hba))));
5765 static void ufshcd_recover_pm_error(struct ufs_hba *hba)
5767 struct Scsi_Host *shost = hba->host;
5768 struct scsi_device *sdev;
5769 struct request_queue *q;
5772 hba->is_sys_suspended = false;
5774 * Set RPM status of hba device to RPM_ACTIVE,
5775 * this also clears its runtime error.
5777 ret = pm_runtime_set_active(hba->dev);
5779 * If hba device had runtime error, we also need to resume those
5780 * scsi devices under hba in case any of them has failed to be
5781 * resumed due to hba runtime resume failure. This is to unblock
5782 * blk_queue_enter in case there are bios waiting inside it.
5785 shost_for_each_device(sdev, shost) {
5786 q = sdev->request_queue;
5787 if (q->dev && (q->rpm_status == RPM_SUSPENDED ||
5788 q->rpm_status == RPM_SUSPENDING))
5789 pm_request_resume(q->dev);
5794 static inline void ufshcd_recover_pm_error(struct ufs_hba *hba)
5799 static bool ufshcd_is_pwr_mode_restore_needed(struct ufs_hba *hba)
5801 struct ufs_pa_layer_attr *pwr_info = &hba->pwr_info;
5804 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_PWRMODE), &mode);
5806 if (pwr_info->pwr_rx != ((mode >> PWRMODE_RX_OFFSET) & PWRMODE_MASK))
5809 if (pwr_info->pwr_tx != (mode & PWRMODE_MASK))
5816 * ufshcd_err_handler - handle UFS errors that require s/w attention
5817 * @work: pointer to work structure
5819 static void ufshcd_err_handler(struct work_struct *work)
5821 struct ufs_hba *hba;
5822 unsigned long flags;
5823 bool err_xfer = false;
5824 bool err_tm = false;
5825 int err = 0, pmc_err;
5827 bool needs_reset = false, needs_restore = false;
5829 hba = container_of(work, struct ufs_hba, eh_work);
5832 spin_lock_irqsave(hba->host->host_lock, flags);
5833 if (ufshcd_err_handling_should_stop(hba)) {
5834 if (hba->ufshcd_state != UFSHCD_STATE_ERROR)
5835 hba->ufshcd_state = UFSHCD_STATE_OPERATIONAL;
5836 spin_unlock_irqrestore(hba->host->host_lock, flags);
5840 ufshcd_set_eh_in_progress(hba);
5841 spin_unlock_irqrestore(hba->host->host_lock, flags);
5842 ufshcd_err_handling_prepare(hba);
5843 spin_lock_irqsave(hba->host->host_lock, flags);
5844 ufshcd_scsi_block_requests(hba);
5845 hba->ufshcd_state = UFSHCD_STATE_RESET;
5847 /* Complete requests that have door-bell cleared by h/w */
5848 ufshcd_complete_requests(hba);
5851 * A full reset and restore might have happened after preparation
5852 * is finished, double check whether we should stop.
5854 if (ufshcd_err_handling_should_stop(hba))
5855 goto skip_err_handling;
5857 if (hba->dev_quirks & UFS_DEVICE_QUIRK_RECOVERY_FROM_DL_NAC_ERRORS) {
5860 spin_unlock_irqrestore(hba->host->host_lock, flags);
5861 /* release the lock as ufshcd_quirk_dl_nac_errors() may sleep */
5862 ret = ufshcd_quirk_dl_nac_errors(hba);
5863 spin_lock_irqsave(hba->host->host_lock, flags);
5864 if (!ret && ufshcd_err_handling_should_stop(hba))
5865 goto skip_err_handling;
5868 if ((hba->saved_err & (INT_FATAL_ERRORS | UFSHCD_UIC_HIBERN8_MASK)) ||
5869 (hba->saved_uic_err &&
5870 (hba->saved_uic_err != UFSHCD_UIC_PA_GENERIC_ERROR))) {
5871 bool pr_prdt = !!(hba->saved_err & SYSTEM_BUS_FATAL_ERROR);
5873 spin_unlock_irqrestore(hba->host->host_lock, flags);
5874 ufshcd_print_host_state(hba);
5875 ufshcd_print_pwr_info(hba);
5876 ufshcd_print_evt_hist(hba);
5877 ufshcd_print_tmrs(hba, hba->outstanding_tasks);
5878 ufshcd_print_trs(hba, hba->outstanding_reqs, pr_prdt);
5879 spin_lock_irqsave(hba->host->host_lock, flags);
5883 * if host reset is required then skip clearing the pending
5884 * transfers forcefully because they will get cleared during
5885 * host reset and restore
5887 if (hba->force_reset || ufshcd_is_link_broken(hba) ||
5888 ufshcd_is_saved_err_fatal(hba) ||
5889 ((hba->saved_err & UIC_ERROR) &&
5890 (hba->saved_uic_err & (UFSHCD_UIC_DL_NAC_RECEIVED_ERROR |
5891 UFSHCD_UIC_DL_TCx_REPLAY_ERROR)))) {
5897 * If LINERESET was caught, UFS might have been put to PWM mode,
5898 * check if power mode restore is needed.
5900 if (hba->saved_uic_err & UFSHCD_UIC_PA_GENERIC_ERROR) {
5901 hba->saved_uic_err &= ~UFSHCD_UIC_PA_GENERIC_ERROR;
5902 if (!hba->saved_uic_err)
5903 hba->saved_err &= ~UIC_ERROR;
5904 spin_unlock_irqrestore(hba->host->host_lock, flags);
5905 if (ufshcd_is_pwr_mode_restore_needed(hba))
5906 needs_restore = true;
5907 spin_lock_irqsave(hba->host->host_lock, flags);
5908 if (!hba->saved_err && !needs_restore)
5909 goto skip_err_handling;
5912 hba->silence_err_logs = true;
5913 /* release lock as clear command might sleep */
5914 spin_unlock_irqrestore(hba->host->host_lock, flags);
5915 /* Clear pending transfer requests */
5916 for_each_set_bit(tag, &hba->outstanding_reqs, hba->nutrs) {
5917 if (ufshcd_try_to_abort_task(hba, tag)) {
5919 goto lock_skip_pending_xfer_clear;
5923 /* Clear pending task management requests */
5924 for_each_set_bit(tag, &hba->outstanding_tasks, hba->nutmrs) {
5925 if (ufshcd_clear_tm_cmd(hba, tag)) {
5927 goto lock_skip_pending_xfer_clear;
5931 lock_skip_pending_xfer_clear:
5932 spin_lock_irqsave(hba->host->host_lock, flags);
5934 /* Complete the requests that are cleared by s/w */
5935 ufshcd_complete_requests(hba);
5936 hba->silence_err_logs = false;
5938 if (err_xfer || err_tm) {
5944 * After all reqs and tasks are cleared from doorbell,
5945 * now it is safe to retore power mode.
5947 if (needs_restore) {
5948 spin_unlock_irqrestore(hba->host->host_lock, flags);
5950 * Hold the scaling lock just in case dev cmds
5951 * are sent via bsg and/or sysfs.
5953 down_write(&hba->clk_scaling_lock);
5954 hba->force_pmc = true;
5955 pmc_err = ufshcd_config_pwr_mode(hba, &(hba->pwr_info));
5958 dev_err(hba->dev, "%s: Failed to restore power mode, err = %d\n",
5961 hba->force_pmc = false;
5962 ufshcd_print_pwr_info(hba);
5963 up_write(&hba->clk_scaling_lock);
5964 spin_lock_irqsave(hba->host->host_lock, flags);
5968 /* Fatal errors need reset */
5970 unsigned long max_doorbells = (1UL << hba->nutrs) - 1;
5973 * ufshcd_reset_and_restore() does the link reinitialization
5974 * which will need atleast one empty doorbell slot to send the
5975 * device management commands (NOP and query commands).
5976 * If there is no slot empty at this moment then free up last
5979 if (hba->outstanding_reqs == max_doorbells)
5980 __ufshcd_transfer_req_compl(hba,
5981 (1UL << (hba->nutrs - 1)));
5983 hba->force_reset = false;
5984 spin_unlock_irqrestore(hba->host->host_lock, flags);
5985 err = ufshcd_reset_and_restore(hba);
5987 dev_err(hba->dev, "%s: reset and restore failed with err %d\n",
5990 ufshcd_recover_pm_error(hba);
5991 spin_lock_irqsave(hba->host->host_lock, flags);
5996 if (hba->ufshcd_state == UFSHCD_STATE_RESET)
5997 hba->ufshcd_state = UFSHCD_STATE_OPERATIONAL;
5998 if (hba->saved_err || hba->saved_uic_err)
5999 dev_err_ratelimited(hba->dev, "%s: exit: saved_err 0x%x saved_uic_err 0x%x",
6000 __func__, hba->saved_err, hba->saved_uic_err);
6002 ufshcd_clear_eh_in_progress(hba);
6003 spin_unlock_irqrestore(hba->host->host_lock, flags);
6004 ufshcd_scsi_unblock_requests(hba);
6005 ufshcd_err_handling_unprepare(hba);
6008 if (!err && needs_reset)
6009 ufshcd_clear_ua_wluns(hba);
6013 * ufshcd_update_uic_error - check and set fatal UIC error flags.
6014 * @hba: per-adapter instance
6017 * IRQ_HANDLED - If interrupt is valid
6018 * IRQ_NONE - If invalid interrupt
6020 static irqreturn_t ufshcd_update_uic_error(struct ufs_hba *hba)
6023 irqreturn_t retval = IRQ_NONE;
6025 /* PHY layer error */
6026 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_PHY_ADAPTER_LAYER);
6027 if ((reg & UIC_PHY_ADAPTER_LAYER_ERROR) &&
6028 (reg & UIC_PHY_ADAPTER_LAYER_ERROR_CODE_MASK)) {
6029 ufshcd_update_evt_hist(hba, UFS_EVT_PA_ERR, reg);
6031 * To know whether this error is fatal or not, DB timeout
6032 * must be checked but this error is handled separately.
6034 if (reg & UIC_PHY_ADAPTER_LAYER_LANE_ERR_MASK)
6035 dev_dbg(hba->dev, "%s: UIC Lane error reported\n",
6038 /* Got a LINERESET indication. */
6039 if (reg & UIC_PHY_ADAPTER_LAYER_GENERIC_ERROR) {
6040 struct uic_command *cmd = NULL;
6042 hba->uic_error |= UFSHCD_UIC_PA_GENERIC_ERROR;
6043 if (hba->uic_async_done && hba->active_uic_cmd)
6044 cmd = hba->active_uic_cmd;
6046 * Ignore the LINERESET during power mode change
6047 * operation via DME_SET command.
6049 if (cmd && (cmd->command == UIC_CMD_DME_SET))
6050 hba->uic_error &= ~UFSHCD_UIC_PA_GENERIC_ERROR;
6052 retval |= IRQ_HANDLED;
6055 /* PA_INIT_ERROR is fatal and needs UIC reset */
6056 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_DATA_LINK_LAYER);
6057 if ((reg & UIC_DATA_LINK_LAYER_ERROR) &&
6058 (reg & UIC_DATA_LINK_LAYER_ERROR_CODE_MASK)) {
6059 ufshcd_update_evt_hist(hba, UFS_EVT_DL_ERR, reg);
6061 if (reg & UIC_DATA_LINK_LAYER_ERROR_PA_INIT)
6062 hba->uic_error |= UFSHCD_UIC_DL_PA_INIT_ERROR;
6063 else if (hba->dev_quirks &
6064 UFS_DEVICE_QUIRK_RECOVERY_FROM_DL_NAC_ERRORS) {
6065 if (reg & UIC_DATA_LINK_LAYER_ERROR_NAC_RECEIVED)
6067 UFSHCD_UIC_DL_NAC_RECEIVED_ERROR;
6068 else if (reg & UIC_DATA_LINK_LAYER_ERROR_TCx_REPLAY_TIMEOUT)
6069 hba->uic_error |= UFSHCD_UIC_DL_TCx_REPLAY_ERROR;
6071 retval |= IRQ_HANDLED;
6074 /* UIC NL/TL/DME errors needs software retry */
6075 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_NETWORK_LAYER);
6076 if ((reg & UIC_NETWORK_LAYER_ERROR) &&
6077 (reg & UIC_NETWORK_LAYER_ERROR_CODE_MASK)) {
6078 ufshcd_update_evt_hist(hba, UFS_EVT_NL_ERR, reg);
6079 hba->uic_error |= UFSHCD_UIC_NL_ERROR;
6080 retval |= IRQ_HANDLED;
6083 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_TRANSPORT_LAYER);
6084 if ((reg & UIC_TRANSPORT_LAYER_ERROR) &&
6085 (reg & UIC_TRANSPORT_LAYER_ERROR_CODE_MASK)) {
6086 ufshcd_update_evt_hist(hba, UFS_EVT_TL_ERR, reg);
6087 hba->uic_error |= UFSHCD_UIC_TL_ERROR;
6088 retval |= IRQ_HANDLED;
6091 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_DME);
6092 if ((reg & UIC_DME_ERROR) &&
6093 (reg & UIC_DME_ERROR_CODE_MASK)) {
6094 ufshcd_update_evt_hist(hba, UFS_EVT_DME_ERR, reg);
6095 hba->uic_error |= UFSHCD_UIC_DME_ERROR;
6096 retval |= IRQ_HANDLED;
6099 dev_dbg(hba->dev, "%s: UIC error flags = 0x%08x\n",
6100 __func__, hba->uic_error);
6104 static bool ufshcd_is_auto_hibern8_error(struct ufs_hba *hba,
6107 if (!ufshcd_is_auto_hibern8_supported(hba) ||
6108 !ufshcd_is_auto_hibern8_enabled(hba))
6111 if (!(intr_mask & UFSHCD_UIC_HIBERN8_MASK))
6114 if (hba->active_uic_cmd &&
6115 (hba->active_uic_cmd->command == UIC_CMD_DME_HIBER_ENTER ||
6116 hba->active_uic_cmd->command == UIC_CMD_DME_HIBER_EXIT))
6123 * ufshcd_check_errors - Check for errors that need s/w attention
6124 * @hba: per-adapter instance
6127 * IRQ_HANDLED - If interrupt is valid
6128 * IRQ_NONE - If invalid interrupt
6130 static irqreturn_t ufshcd_check_errors(struct ufs_hba *hba)
6132 bool queue_eh_work = false;
6133 irqreturn_t retval = IRQ_NONE;
6135 if (hba->errors & INT_FATAL_ERRORS) {
6136 ufshcd_update_evt_hist(hba, UFS_EVT_FATAL_ERR,
6138 queue_eh_work = true;
6141 if (hba->errors & UIC_ERROR) {
6143 retval = ufshcd_update_uic_error(hba);
6145 queue_eh_work = true;
6148 if (hba->errors & UFSHCD_UIC_HIBERN8_MASK) {
6150 "%s: Auto Hibern8 %s failed - status: 0x%08x, upmcrs: 0x%08x\n",
6151 __func__, (hba->errors & UIC_HIBERNATE_ENTER) ?
6153 hba->errors, ufshcd_get_upmcrs(hba));
6154 ufshcd_update_evt_hist(hba, UFS_EVT_AUTO_HIBERN8_ERR,
6156 ufshcd_set_link_broken(hba);
6157 queue_eh_work = true;
6160 if (queue_eh_work) {
6162 * update the transfer error masks to sticky bits, let's do this
6163 * irrespective of current ufshcd_state.
6165 hba->saved_err |= hba->errors;
6166 hba->saved_uic_err |= hba->uic_error;
6168 /* dump controller state before resetting */
6169 if ((hba->saved_err &
6170 (INT_FATAL_ERRORS | UFSHCD_UIC_HIBERN8_MASK)) ||
6171 (hba->saved_uic_err &&
6172 (hba->saved_uic_err != UFSHCD_UIC_PA_GENERIC_ERROR))) {
6173 dev_err(hba->dev, "%s: saved_err 0x%x saved_uic_err 0x%x\n",
6174 __func__, hba->saved_err,
6175 hba->saved_uic_err);
6176 ufshcd_dump_regs(hba, 0, UFSHCI_REG_SPACE_SIZE,
6178 ufshcd_print_pwr_info(hba);
6180 ufshcd_schedule_eh_work(hba);
6181 retval |= IRQ_HANDLED;
6184 * if (!queue_eh_work) -
6185 * Other errors are either non-fatal where host recovers
6186 * itself without s/w intervention or errors that will be
6187 * handled by the SCSI core layer.
6193 struct ufs_hba *hba;
6194 unsigned long pending;
6198 static bool ufshcd_compl_tm(struct request *req, void *priv, bool reserved)
6200 struct ctm_info *const ci = priv;
6201 struct completion *c;
6203 WARN_ON_ONCE(reserved);
6204 if (test_bit(req->tag, &ci->pending))
6207 c = req->end_io_data;
6214 * ufshcd_tmc_handler - handle task management function completion
6215 * @hba: per adapter instance
6218 * IRQ_HANDLED - If interrupt is valid
6219 * IRQ_NONE - If invalid interrupt
6221 static irqreturn_t ufshcd_tmc_handler(struct ufs_hba *hba)
6223 struct request_queue *q = hba->tmf_queue;
6224 struct ctm_info ci = {
6226 .pending = ufshcd_readl(hba, REG_UTP_TASK_REQ_DOOR_BELL),
6229 blk_mq_tagset_busy_iter(q->tag_set, ufshcd_compl_tm, &ci);
6230 return ci.ncpl ? IRQ_HANDLED : IRQ_NONE;
6234 * ufshcd_sl_intr - Interrupt service routine
6235 * @hba: per adapter instance
6236 * @intr_status: contains interrupts generated by the controller
6239 * IRQ_HANDLED - If interrupt is valid
6240 * IRQ_NONE - If invalid interrupt
6242 static irqreturn_t ufshcd_sl_intr(struct ufs_hba *hba, u32 intr_status)
6244 irqreturn_t retval = IRQ_NONE;
6246 hba->errors = UFSHCD_ERROR_MASK & intr_status;
6248 if (ufshcd_is_auto_hibern8_error(hba, intr_status))
6249 hba->errors |= (UFSHCD_UIC_HIBERN8_MASK & intr_status);
6252 retval |= ufshcd_check_errors(hba);
6254 if (intr_status & UFSHCD_UIC_MASK)
6255 retval |= ufshcd_uic_cmd_compl(hba, intr_status);
6257 if (intr_status & UTP_TASK_REQ_COMPL)
6258 retval |= ufshcd_tmc_handler(hba);
6260 if (intr_status & UTP_TRANSFER_REQ_COMPL)
6261 retval |= ufshcd_transfer_req_compl(hba);
6267 * ufshcd_intr - Main interrupt service routine
6269 * @__hba: pointer to adapter instance
6272 * IRQ_HANDLED - If interrupt is valid
6273 * IRQ_NONE - If invalid interrupt
6275 static irqreturn_t ufshcd_intr(int irq, void *__hba)
6277 u32 intr_status, enabled_intr_status = 0;
6278 irqreturn_t retval = IRQ_NONE;
6279 struct ufs_hba *hba = __hba;
6280 int retries = hba->nutrs;
6282 spin_lock(hba->host->host_lock);
6283 intr_status = ufshcd_readl(hba, REG_INTERRUPT_STATUS);
6284 hba->ufs_stats.last_intr_status = intr_status;
6285 hba->ufs_stats.last_intr_ts = ktime_get();
6288 * There could be max of hba->nutrs reqs in flight and in worst case
6289 * if the reqs get finished 1 by 1 after the interrupt status is
6290 * read, make sure we handle them by checking the interrupt status
6291 * again in a loop until we process all of the reqs before returning.
6293 while (intr_status && retries--) {
6294 enabled_intr_status =
6295 intr_status & ufshcd_readl(hba, REG_INTERRUPT_ENABLE);
6297 ufshcd_writel(hba, intr_status, REG_INTERRUPT_STATUS);
6298 if (enabled_intr_status)
6299 retval |= ufshcd_sl_intr(hba, enabled_intr_status);
6301 intr_status = ufshcd_readl(hba, REG_INTERRUPT_STATUS);
6304 if (enabled_intr_status && retval == IRQ_NONE &&
6305 !ufshcd_eh_in_progress(hba)) {
6306 dev_err(hba->dev, "%s: Unhandled interrupt 0x%08x (0x%08x, 0x%08x)\n",
6309 hba->ufs_stats.last_intr_status,
6310 enabled_intr_status);
6311 ufshcd_dump_regs(hba, 0, UFSHCI_REG_SPACE_SIZE, "host_regs: ");
6314 spin_unlock(hba->host->host_lock);
6318 static int ufshcd_clear_tm_cmd(struct ufs_hba *hba, int tag)
6321 u32 mask = 1 << tag;
6322 unsigned long flags;
6324 if (!test_bit(tag, &hba->outstanding_tasks))
6327 spin_lock_irqsave(hba->host->host_lock, flags);
6328 ufshcd_utmrl_clear(hba, tag);
6329 spin_unlock_irqrestore(hba->host->host_lock, flags);
6331 /* poll for max. 1 sec to clear door bell register by h/w */
6332 err = ufshcd_wait_for_register(hba,
6333 REG_UTP_TASK_REQ_DOOR_BELL,
6334 mask, 0, 1000, 1000);
6339 static int __ufshcd_issue_tm_cmd(struct ufs_hba *hba,
6340 struct utp_task_req_desc *treq, u8 tm_function)
6342 struct request_queue *q = hba->tmf_queue;
6343 struct Scsi_Host *host = hba->host;
6344 DECLARE_COMPLETION_ONSTACK(wait);
6345 struct request *req;
6346 unsigned long flags;
6347 int free_slot, task_tag, err;
6350 * Get free slot, sleep if slots are unavailable.
6351 * Even though we use wait_event() which sleeps indefinitely,
6352 * the maximum wait time is bounded by %TM_CMD_TIMEOUT.
6354 req = blk_get_request(q, REQ_OP_DRV_OUT, 0);
6356 return PTR_ERR(req);
6358 req->end_io_data = &wait;
6359 free_slot = req->tag;
6360 WARN_ON_ONCE(free_slot < 0 || free_slot >= hba->nutmrs);
6361 ufshcd_hold(hba, false);
6363 spin_lock_irqsave(host->host_lock, flags);
6364 task_tag = hba->nutrs + free_slot;
6366 treq->req_header.dword_0 |= cpu_to_be32(task_tag);
6368 memcpy(hba->utmrdl_base_addr + free_slot, treq, sizeof(*treq));
6369 ufshcd_vops_setup_task_mgmt(hba, free_slot, tm_function);
6371 /* send command to the controller */
6372 __set_bit(free_slot, &hba->outstanding_tasks);
6374 /* Make sure descriptors are ready before ringing the task doorbell */
6377 ufshcd_writel(hba, 1 << free_slot, REG_UTP_TASK_REQ_DOOR_BELL);
6378 /* Make sure that doorbell is committed immediately */
6381 spin_unlock_irqrestore(host->host_lock, flags);
6383 ufshcd_add_tm_upiu_trace(hba, task_tag, "tm_send");
6385 /* wait until the task management command is completed */
6386 err = wait_for_completion_io_timeout(&wait,
6387 msecs_to_jiffies(TM_CMD_TIMEOUT));
6390 * Make sure that ufshcd_compl_tm() does not trigger a
6393 req->end_io_data = NULL;
6394 ufshcd_add_tm_upiu_trace(hba, task_tag, "tm_complete_err");
6395 dev_err(hba->dev, "%s: task management cmd 0x%.2x timed-out\n",
6396 __func__, tm_function);
6397 if (ufshcd_clear_tm_cmd(hba, free_slot))
6398 dev_WARN(hba->dev, "%s: unable clear tm cmd (slot %d) after timeout\n",
6399 __func__, free_slot);
6403 memcpy(treq, hba->utmrdl_base_addr + free_slot, sizeof(*treq));
6405 ufshcd_add_tm_upiu_trace(hba, task_tag, "tm_complete");
6408 spin_lock_irqsave(hba->host->host_lock, flags);
6409 __clear_bit(free_slot, &hba->outstanding_tasks);
6410 spin_unlock_irqrestore(hba->host->host_lock, flags);
6412 blk_put_request(req);
6414 ufshcd_release(hba);
6419 * ufshcd_issue_tm_cmd - issues task management commands to controller
6420 * @hba: per adapter instance
6421 * @lun_id: LUN ID to which TM command is sent
6422 * @task_id: task ID to which the TM command is applicable
6423 * @tm_function: task management function opcode
6424 * @tm_response: task management service response return value
6426 * Returns non-zero value on error, zero on success.
6428 static int ufshcd_issue_tm_cmd(struct ufs_hba *hba, int lun_id, int task_id,
6429 u8 tm_function, u8 *tm_response)
6431 struct utp_task_req_desc treq = { { 0 }, };
6434 /* Configure task request descriptor */
6435 treq.header.dword_0 = cpu_to_le32(UTP_REQ_DESC_INT_CMD);
6436 treq.header.dword_2 = cpu_to_le32(OCS_INVALID_COMMAND_STATUS);
6438 /* Configure task request UPIU */
6439 treq.req_header.dword_0 = cpu_to_be32(lun_id << 8) |
6440 cpu_to_be32(UPIU_TRANSACTION_TASK_REQ << 24);
6441 treq.req_header.dword_1 = cpu_to_be32(tm_function << 16);
6444 * The host shall provide the same value for LUN field in the basic
6445 * header and for Input Parameter.
6447 treq.input_param1 = cpu_to_be32(lun_id);
6448 treq.input_param2 = cpu_to_be32(task_id);
6450 err = __ufshcd_issue_tm_cmd(hba, &treq, tm_function);
6451 if (err == -ETIMEDOUT)
6454 ocs_value = le32_to_cpu(treq.header.dword_2) & MASK_OCS;
6455 if (ocs_value != OCS_SUCCESS)
6456 dev_err(hba->dev, "%s: failed, ocs = 0x%x\n",
6457 __func__, ocs_value);
6458 else if (tm_response)
6459 *tm_response = be32_to_cpu(treq.output_param1) &
6460 MASK_TM_SERVICE_RESP;
6465 * ufshcd_issue_devman_upiu_cmd - API for sending "utrd" type requests
6466 * @hba: per-adapter instance
6467 * @req_upiu: upiu request
6468 * @rsp_upiu: upiu reply
6469 * @desc_buff: pointer to descriptor buffer, NULL if NA
6470 * @buff_len: descriptor size, 0 if NA
6471 * @cmd_type: specifies the type (NOP, Query...)
6472 * @desc_op: descriptor operation
6474 * Those type of requests uses UTP Transfer Request Descriptor - utrd.
6475 * Therefore, it "rides" the device management infrastructure: uses its tag and
6476 * tasks work queues.
6478 * Since there is only one available tag for device management commands,
6479 * the caller is expected to hold the hba->dev_cmd.lock mutex.
6481 static int ufshcd_issue_devman_upiu_cmd(struct ufs_hba *hba,
6482 struct utp_upiu_req *req_upiu,
6483 struct utp_upiu_req *rsp_upiu,
6484 u8 *desc_buff, int *buff_len,
6485 enum dev_cmd_type cmd_type,
6486 enum query_opcode desc_op)
6488 struct request_queue *q = hba->cmd_queue;
6489 struct request *req;
6490 struct ufshcd_lrb *lrbp;
6493 struct completion wait;
6494 unsigned long flags;
6497 down_read(&hba->clk_scaling_lock);
6499 req = blk_get_request(q, REQ_OP_DRV_OUT, 0);
6505 WARN_ON_ONCE(!ufshcd_valid_tag(hba, tag));
6507 init_completion(&wait);
6508 lrbp = &hba->lrb[tag];
6509 if (unlikely(lrbp->in_use)) {
6516 lrbp->sense_bufflen = 0;
6517 lrbp->sense_buffer = NULL;
6518 lrbp->task_tag = tag;
6520 lrbp->intr_cmd = true;
6521 ufshcd_prepare_lrbp_crypto(NULL, lrbp);
6522 hba->dev_cmd.type = cmd_type;
6524 switch (hba->ufs_version) {
6525 case UFSHCI_VERSION_10:
6526 case UFSHCI_VERSION_11:
6527 lrbp->command_type = UTP_CMD_TYPE_DEV_MANAGE;
6530 lrbp->command_type = UTP_CMD_TYPE_UFS_STORAGE;
6534 /* update the task tag in the request upiu */
6535 req_upiu->header.dword_0 |= cpu_to_be32(tag);
6537 ufshcd_prepare_req_desc_hdr(lrbp, &upiu_flags, DMA_NONE);
6539 /* just copy the upiu request as it is */
6540 memcpy(lrbp->ucd_req_ptr, req_upiu, sizeof(*lrbp->ucd_req_ptr));
6541 if (desc_buff && desc_op == UPIU_QUERY_OPCODE_WRITE_DESC) {
6542 /* The Data Segment Area is optional depending upon the query
6543 * function value. for WRITE DESCRIPTOR, the data segment
6544 * follows right after the tsf.
6546 memcpy(lrbp->ucd_req_ptr + 1, desc_buff, *buff_len);
6550 memset(lrbp->ucd_rsp_ptr, 0, sizeof(struct utp_upiu_rsp));
6552 hba->dev_cmd.complete = &wait;
6554 /* Make sure descriptors are ready before ringing the doorbell */
6556 spin_lock_irqsave(hba->host->host_lock, flags);
6557 ufshcd_send_command(hba, tag);
6558 spin_unlock_irqrestore(hba->host->host_lock, flags);
6561 * ignore the returning value here - ufshcd_check_query_response is
6562 * bound to fail since dev_cmd.query and dev_cmd.type were left empty.
6563 * read the response directly ignoring all errors.
6565 ufshcd_wait_for_dev_cmd(hba, lrbp, QUERY_REQ_TIMEOUT);
6567 /* just copy the upiu response as it is */
6568 memcpy(rsp_upiu, lrbp->ucd_rsp_ptr, sizeof(*rsp_upiu));
6569 if (desc_buff && desc_op == UPIU_QUERY_OPCODE_READ_DESC) {
6570 u8 *descp = (u8 *)lrbp->ucd_rsp_ptr + sizeof(*rsp_upiu);
6571 u16 resp_len = be32_to_cpu(lrbp->ucd_rsp_ptr->header.dword_2) &
6572 MASK_QUERY_DATA_SEG_LEN;
6574 if (*buff_len >= resp_len) {
6575 memcpy(desc_buff, descp, resp_len);
6576 *buff_len = resp_len;
6579 "%s: rsp size %d is bigger than buffer size %d",
6580 __func__, resp_len, *buff_len);
6587 blk_put_request(req);
6589 up_read(&hba->clk_scaling_lock);
6594 * ufshcd_exec_raw_upiu_cmd - API function for sending raw upiu commands
6595 * @hba: per-adapter instance
6596 * @req_upiu: upiu request
6597 * @rsp_upiu: upiu reply - only 8 DW as we do not support scsi commands
6598 * @msgcode: message code, one of UPIU Transaction Codes Initiator to Target
6599 * @desc_buff: pointer to descriptor buffer, NULL if NA
6600 * @buff_len: descriptor size, 0 if NA
6601 * @desc_op: descriptor operation
6603 * Supports UTP Transfer requests (nop and query), and UTP Task
6604 * Management requests.
6605 * It is up to the caller to fill the upiu conent properly, as it will
6606 * be copied without any further input validations.
6608 int ufshcd_exec_raw_upiu_cmd(struct ufs_hba *hba,
6609 struct utp_upiu_req *req_upiu,
6610 struct utp_upiu_req *rsp_upiu,
6612 u8 *desc_buff, int *buff_len,
6613 enum query_opcode desc_op)
6616 enum dev_cmd_type cmd_type = DEV_CMD_TYPE_QUERY;
6617 struct utp_task_req_desc treq = { { 0 }, };
6619 u8 tm_f = be32_to_cpu(req_upiu->header.dword_1) >> 16 & MASK_TM_FUNC;
6622 case UPIU_TRANSACTION_NOP_OUT:
6623 cmd_type = DEV_CMD_TYPE_NOP;
6625 case UPIU_TRANSACTION_QUERY_REQ:
6626 ufshcd_hold(hba, false);
6627 mutex_lock(&hba->dev_cmd.lock);
6628 err = ufshcd_issue_devman_upiu_cmd(hba, req_upiu, rsp_upiu,
6629 desc_buff, buff_len,
6631 mutex_unlock(&hba->dev_cmd.lock);
6632 ufshcd_release(hba);
6635 case UPIU_TRANSACTION_TASK_REQ:
6636 treq.header.dword_0 = cpu_to_le32(UTP_REQ_DESC_INT_CMD);
6637 treq.header.dword_2 = cpu_to_le32(OCS_INVALID_COMMAND_STATUS);
6639 memcpy(&treq.req_header, req_upiu, sizeof(*req_upiu));
6641 err = __ufshcd_issue_tm_cmd(hba, &treq, tm_f);
6642 if (err == -ETIMEDOUT)
6645 ocs_value = le32_to_cpu(treq.header.dword_2) & MASK_OCS;
6646 if (ocs_value != OCS_SUCCESS) {
6647 dev_err(hba->dev, "%s: failed, ocs = 0x%x\n", __func__,
6652 memcpy(rsp_upiu, &treq.rsp_header, sizeof(*rsp_upiu));
6665 * ufshcd_eh_device_reset_handler - device reset handler registered to
6667 * @cmd: SCSI command pointer
6669 * Returns SUCCESS/FAILED
6671 static int ufshcd_eh_device_reset_handler(struct scsi_cmnd *cmd)
6673 struct Scsi_Host *host;
6674 struct ufs_hba *hba;
6678 unsigned long flags;
6680 host = cmd->device->host;
6681 hba = shost_priv(host);
6683 lun = ufshcd_scsi_to_upiu_lun(cmd->device->lun);
6684 err = ufshcd_issue_tm_cmd(hba, lun, 0, UFS_LOGICAL_RESET, &resp);
6685 if (err || resp != UPIU_TASK_MANAGEMENT_FUNC_COMPL) {
6691 /* clear the commands that were pending for corresponding LUN */
6692 for_each_set_bit(pos, &hba->outstanding_reqs, hba->nutrs) {
6693 if (hba->lrb[pos].lun == lun) {
6694 err = ufshcd_clear_cmd(hba, pos);
6699 spin_lock_irqsave(host->host_lock, flags);
6700 ufshcd_transfer_req_compl(hba);
6701 spin_unlock_irqrestore(host->host_lock, flags);
6704 hba->req_abort_count = 0;
6705 ufshcd_update_evt_hist(hba, UFS_EVT_DEV_RESET, (u32)err);
6709 dev_err(hba->dev, "%s: failed with err %d\n", __func__, err);
6715 static void ufshcd_set_req_abort_skip(struct ufs_hba *hba, unsigned long bitmap)
6717 struct ufshcd_lrb *lrbp;
6720 for_each_set_bit(tag, &bitmap, hba->nutrs) {
6721 lrbp = &hba->lrb[tag];
6722 lrbp->req_abort_skip = true;
6727 * ufshcd_try_to_abort_task - abort a specific task
6728 * @hba: Pointer to adapter instance
6729 * @tag: Task tag/index to be aborted
6731 * Abort the pending command in device by sending UFS_ABORT_TASK task management
6732 * command, and in host controller by clearing the door-bell register. There can
6733 * be race between controller sending the command to the device while abort is
6734 * issued. To avoid that, first issue UFS_QUERY_TASK to check if the command is
6735 * really issued and then try to abort it.
6737 * Returns zero on success, non-zero on failure
6739 static int ufshcd_try_to_abort_task(struct ufs_hba *hba, int tag)
6741 struct ufshcd_lrb *lrbp = &hba->lrb[tag];
6747 for (poll_cnt = 100; poll_cnt; poll_cnt--) {
6748 err = ufshcd_issue_tm_cmd(hba, lrbp->lun, lrbp->task_tag,
6749 UFS_QUERY_TASK, &resp);
6750 if (!err && resp == UPIU_TASK_MANAGEMENT_FUNC_SUCCEEDED) {
6751 /* cmd pending in the device */
6752 dev_err(hba->dev, "%s: cmd pending in the device. tag = %d\n",
6755 } else if (!err && resp == UPIU_TASK_MANAGEMENT_FUNC_COMPL) {
6757 * cmd not pending in the device, check if it is
6760 dev_err(hba->dev, "%s: cmd at tag %d not pending in the device.\n",
6762 reg = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
6763 if (reg & (1 << tag)) {
6764 /* sleep for max. 200us to stabilize */
6765 usleep_range(100, 200);
6768 /* command completed already */
6769 dev_err(hba->dev, "%s: cmd at tag %d successfully cleared from DB.\n",
6774 "%s: no response from device. tag = %d, err %d\n",
6775 __func__, tag, err);
6777 err = resp; /* service response error */
6787 err = ufshcd_issue_tm_cmd(hba, lrbp->lun, lrbp->task_tag,
6788 UFS_ABORT_TASK, &resp);
6789 if (err || resp != UPIU_TASK_MANAGEMENT_FUNC_COMPL) {
6791 err = resp; /* service response error */
6792 dev_err(hba->dev, "%s: issued. tag = %d, err %d\n",
6793 __func__, tag, err);
6798 err = ufshcd_clear_cmd(hba, tag);
6800 dev_err(hba->dev, "%s: Failed clearing cmd at tag %d, err %d\n",
6801 __func__, tag, err);
6808 * ufshcd_abort - scsi host template eh_abort_handler callback
6809 * @cmd: SCSI command pointer
6811 * Returns SUCCESS/FAILED
6813 static int ufshcd_abort(struct scsi_cmnd *cmd)
6815 struct Scsi_Host *host;
6816 struct ufs_hba *hba;
6817 unsigned long flags;
6820 struct ufshcd_lrb *lrbp;
6823 host = cmd->device->host;
6824 hba = shost_priv(host);
6825 tag = cmd->request->tag;
6826 lrbp = &hba->lrb[tag];
6827 if (!ufshcd_valid_tag(hba, tag)) {
6829 "%s: invalid command tag %d: cmd=0x%p, cmd->request=0x%p",
6830 __func__, tag, cmd, cmd->request);
6834 ufshcd_hold(hba, false);
6835 reg = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
6836 /* If command is already aborted/completed, return SUCCESS */
6837 if (!(test_bit(tag, &hba->outstanding_reqs))) {
6839 "%s: cmd at tag %d already completed, outstanding=0x%lx, doorbell=0x%x\n",
6840 __func__, tag, hba->outstanding_reqs, reg);
6844 /* Print Transfer Request of aborted task */
6845 dev_info(hba->dev, "%s: Device abort task at tag %d\n", __func__, tag);
6848 * Print detailed info about aborted request.
6849 * As more than one request might get aborted at the same time,
6850 * print full information only for the first aborted request in order
6851 * to reduce repeated printouts. For other aborted requests only print
6854 scsi_print_command(cmd);
6855 if (!hba->req_abort_count) {
6856 ufshcd_update_evt_hist(hba, UFS_EVT_ABORT, tag);
6857 ufshcd_print_evt_hist(hba);
6858 ufshcd_print_host_state(hba);
6859 ufshcd_print_pwr_info(hba);
6860 ufshcd_print_trs(hba, 1 << tag, true);
6862 ufshcd_print_trs(hba, 1 << tag, false);
6864 hba->req_abort_count++;
6866 if (!(reg & (1 << tag))) {
6868 "%s: cmd was completed, but without a notifying intr, tag = %d",
6874 * Task abort to the device W-LUN is illegal. When this command
6875 * will fail, due to spec violation, scsi err handling next step
6876 * will be to send LU reset which, again, is a spec violation.
6877 * To avoid these unnecessary/illegal steps, first we clean up
6878 * the lrb taken by this cmd and mark the lrb as in_use, then
6879 * queue the eh_work and bail.
6881 if (lrbp->lun == UFS_UPIU_UFS_DEVICE_WLUN) {
6882 ufshcd_update_evt_hist(hba, UFS_EVT_ABORT, lrbp->lun);
6883 spin_lock_irqsave(host->host_lock, flags);
6885 __ufshcd_transfer_req_compl(hba, (1UL << tag));
6886 __set_bit(tag, &hba->outstanding_reqs);
6887 lrbp->in_use = true;
6888 hba->force_reset = true;
6889 ufshcd_schedule_eh_work(hba);
6892 spin_unlock_irqrestore(host->host_lock, flags);
6896 /* Skip task abort in case previous aborts failed and report failure */
6897 if (lrbp->req_abort_skip)
6900 err = ufshcd_try_to_abort_task(hba, tag);
6904 spin_lock_irqsave(host->host_lock, flags);
6905 __ufshcd_transfer_req_compl(hba, (1UL << tag));
6906 spin_unlock_irqrestore(host->host_lock, flags);
6910 dev_err(hba->dev, "%s: failed with err %d\n", __func__, err);
6911 ufshcd_set_req_abort_skip(hba, hba->outstanding_reqs);
6916 * This ufshcd_release() corresponds to the original scsi cmd that got
6917 * aborted here (as we won't get any IRQ for it).
6919 ufshcd_release(hba);
6924 * ufshcd_host_reset_and_restore - reset and restore host controller
6925 * @hba: per-adapter instance
6927 * Note that host controller reset may issue DME_RESET to
6928 * local and remote (device) Uni-Pro stack and the attributes
6929 * are reset to default state.
6931 * Returns zero on success, non-zero on failure
6933 static int ufshcd_host_reset_and_restore(struct ufs_hba *hba)
6936 unsigned long flags;
6939 * Stop the host controller and complete the requests
6942 ufshcd_hba_stop(hba);
6944 spin_lock_irqsave(hba->host->host_lock, flags);
6945 hba->silence_err_logs = true;
6946 ufshcd_complete_requests(hba);
6947 hba->silence_err_logs = false;
6948 spin_unlock_irqrestore(hba->host->host_lock, flags);
6950 /* scale up clocks to max frequency before full reinitialization */
6951 ufshcd_set_clk_freq(hba, true);
6953 err = ufshcd_hba_enable(hba);
6955 /* Establish the link again and restore the device */
6957 err = ufshcd_probe_hba(hba, false);
6960 dev_err(hba->dev, "%s: Host init failed %d\n", __func__, err);
6961 ufshcd_update_evt_hist(hba, UFS_EVT_HOST_RESET, (u32)err);
6966 * ufshcd_reset_and_restore - reset and re-initialize host/device
6967 * @hba: per-adapter instance
6969 * Reset and recover device, host and re-establish link. This
6970 * is helpful to recover the communication in fatal error conditions.
6972 * Returns zero on success, non-zero on failure
6974 static int ufshcd_reset_and_restore(struct ufs_hba *hba)
6979 unsigned long flags;
6980 int retries = MAX_HOST_RESET_RETRIES;
6983 * This is a fresh start, cache and clear saved error first,
6984 * in case new error generated during reset and restore.
6986 spin_lock_irqsave(hba->host->host_lock, flags);
6987 saved_err = hba->saved_err;
6988 saved_uic_err = hba->saved_uic_err;
6990 hba->saved_uic_err = 0;
6991 spin_unlock_irqrestore(hba->host->host_lock, flags);
6994 /* Reset the attached device */
6995 ufshcd_device_reset(hba);
6997 err = ufshcd_host_reset_and_restore(hba);
6998 } while (err && --retries);
7000 spin_lock_irqsave(hba->host->host_lock, flags);
7002 * Inform scsi mid-layer that we did reset and allow to handle
7003 * Unit Attention properly.
7005 scsi_report_bus_reset(hba->host, 0);
7007 hba->ufshcd_state = UFSHCD_STATE_ERROR;
7008 hba->saved_err |= saved_err;
7009 hba->saved_uic_err |= saved_uic_err;
7011 spin_unlock_irqrestore(hba->host->host_lock, flags);
7017 * ufshcd_eh_host_reset_handler - host reset handler registered to scsi layer
7018 * @cmd: SCSI command pointer
7020 * Returns SUCCESS/FAILED
7022 static int ufshcd_eh_host_reset_handler(struct scsi_cmnd *cmd)
7025 unsigned long flags;
7026 struct ufs_hba *hba;
7028 hba = shost_priv(cmd->device->host);
7030 spin_lock_irqsave(hba->host->host_lock, flags);
7031 hba->force_reset = true;
7032 ufshcd_schedule_eh_work(hba);
7033 dev_err(hba->dev, "%s: reset in progress - 1\n", __func__);
7034 spin_unlock_irqrestore(hba->host->host_lock, flags);
7036 flush_work(&hba->eh_work);
7038 spin_lock_irqsave(hba->host->host_lock, flags);
7039 if (hba->ufshcd_state == UFSHCD_STATE_ERROR)
7041 spin_unlock_irqrestore(hba->host->host_lock, flags);
7047 * ufshcd_get_max_icc_level - calculate the ICC level
7048 * @sup_curr_uA: max. current supported by the regulator
7049 * @start_scan: row at the desc table to start scan from
7050 * @buff: power descriptor buffer
7052 * Returns calculated max ICC level for specific regulator
7054 static u32 ufshcd_get_max_icc_level(int sup_curr_uA, u32 start_scan, char *buff)
7061 for (i = start_scan; i >= 0; i--) {
7062 data = be16_to_cpup((__be16 *)&buff[2 * i]);
7063 unit = (data & ATTR_ICC_LVL_UNIT_MASK) >>
7064 ATTR_ICC_LVL_UNIT_OFFSET;
7065 curr_uA = data & ATTR_ICC_LVL_VALUE_MASK;
7067 case UFSHCD_NANO_AMP:
7068 curr_uA = curr_uA / 1000;
7070 case UFSHCD_MILI_AMP:
7071 curr_uA = curr_uA * 1000;
7074 curr_uA = curr_uA * 1000 * 1000;
7076 case UFSHCD_MICRO_AMP:
7080 if (sup_curr_uA >= curr_uA)
7085 pr_err("%s: Couldn't find valid icc_level = %d", __func__, i);
7092 * ufshcd_calc_icc_level - calculate the max ICC level
7093 * In case regulators are not initialized we'll return 0
7094 * @hba: per-adapter instance
7095 * @desc_buf: power descriptor buffer to extract ICC levels from.
7096 * @len: length of desc_buff
7098 * Returns calculated ICC level
7100 static u32 ufshcd_find_max_sup_active_icc_level(struct ufs_hba *hba,
7101 u8 *desc_buf, int len)
7105 if (!hba->vreg_info.vcc || !hba->vreg_info.vccq ||
7106 !hba->vreg_info.vccq2) {
7108 "%s: Regulator capability was not set, actvIccLevel=%d",
7109 __func__, icc_level);
7113 if (hba->vreg_info.vcc && hba->vreg_info.vcc->max_uA)
7114 icc_level = ufshcd_get_max_icc_level(
7115 hba->vreg_info.vcc->max_uA,
7116 POWER_DESC_MAX_ACTV_ICC_LVLS - 1,
7117 &desc_buf[PWR_DESC_ACTIVE_LVLS_VCC_0]);
7119 if (hba->vreg_info.vccq && hba->vreg_info.vccq->max_uA)
7120 icc_level = ufshcd_get_max_icc_level(
7121 hba->vreg_info.vccq->max_uA,
7123 &desc_buf[PWR_DESC_ACTIVE_LVLS_VCCQ_0]);
7125 if (hba->vreg_info.vccq2 && hba->vreg_info.vccq2->max_uA)
7126 icc_level = ufshcd_get_max_icc_level(
7127 hba->vreg_info.vccq2->max_uA,
7129 &desc_buf[PWR_DESC_ACTIVE_LVLS_VCCQ2_0]);
7134 static void ufshcd_set_active_icc_lvl(struct ufs_hba *hba)
7137 int buff_len = hba->desc_size[QUERY_DESC_IDN_POWER];
7141 desc_buf = kmalloc(buff_len, GFP_KERNEL);
7145 ret = ufshcd_read_desc_param(hba, QUERY_DESC_IDN_POWER, 0, 0,
7146 desc_buf, buff_len);
7149 "%s: Failed reading power descriptor.len = %d ret = %d",
7150 __func__, buff_len, ret);
7154 icc_level = ufshcd_find_max_sup_active_icc_level(hba, desc_buf,
7156 dev_dbg(hba->dev, "%s: setting icc_level 0x%x", __func__, icc_level);
7158 ret = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_WRITE_ATTR,
7159 QUERY_ATTR_IDN_ACTIVE_ICC_LVL, 0, 0, &icc_level);
7163 "%s: Failed configuring bActiveICCLevel = %d ret = %d",
7164 __func__, icc_level, ret);
7170 static inline void ufshcd_blk_pm_runtime_init(struct scsi_device *sdev)
7172 scsi_autopm_get_device(sdev);
7173 blk_pm_runtime_init(sdev->request_queue, &sdev->sdev_gendev);
7174 if (sdev->rpm_autosuspend)
7175 pm_runtime_set_autosuspend_delay(&sdev->sdev_gendev,
7176 RPM_AUTOSUSPEND_DELAY_MS);
7177 scsi_autopm_put_device(sdev);
7181 * ufshcd_scsi_add_wlus - Adds required W-LUs
7182 * @hba: per-adapter instance
7184 * UFS device specification requires the UFS devices to support 4 well known
7186 * "REPORT_LUNS" (address: 01h)
7187 * "UFS Device" (address: 50h)
7188 * "RPMB" (address: 44h)
7189 * "BOOT" (address: 30h)
7190 * UFS device's power management needs to be controlled by "POWER CONDITION"
7191 * field of SSU (START STOP UNIT) command. But this "power condition" field
7192 * will take effect only when its sent to "UFS device" well known logical unit
7193 * hence we require the scsi_device instance to represent this logical unit in
7194 * order for the UFS host driver to send the SSU command for power management.
7196 * We also require the scsi_device instance for "RPMB" (Replay Protected Memory
7197 * Block) LU so user space process can control this LU. User space may also
7198 * want to have access to BOOT LU.
7200 * This function adds scsi device instances for each of all well known LUs
7201 * (except "REPORT LUNS" LU).
7203 * Returns zero on success (all required W-LUs are added successfully),
7204 * non-zero error value on failure (if failed to add any of the required W-LU).
7206 static int ufshcd_scsi_add_wlus(struct ufs_hba *hba)
7209 struct scsi_device *sdev_boot;
7211 hba->sdev_ufs_device = __scsi_add_device(hba->host, 0, 0,
7212 ufshcd_upiu_wlun_to_scsi_wlun(UFS_UPIU_UFS_DEVICE_WLUN), NULL);
7213 if (IS_ERR(hba->sdev_ufs_device)) {
7214 ret = PTR_ERR(hba->sdev_ufs_device);
7215 hba->sdev_ufs_device = NULL;
7218 ufshcd_blk_pm_runtime_init(hba->sdev_ufs_device);
7219 scsi_device_put(hba->sdev_ufs_device);
7221 hba->sdev_rpmb = __scsi_add_device(hba->host, 0, 0,
7222 ufshcd_upiu_wlun_to_scsi_wlun(UFS_UPIU_RPMB_WLUN), NULL);
7223 if (IS_ERR(hba->sdev_rpmb)) {
7224 ret = PTR_ERR(hba->sdev_rpmb);
7225 goto remove_sdev_ufs_device;
7227 ufshcd_blk_pm_runtime_init(hba->sdev_rpmb);
7228 scsi_device_put(hba->sdev_rpmb);
7230 sdev_boot = __scsi_add_device(hba->host, 0, 0,
7231 ufshcd_upiu_wlun_to_scsi_wlun(UFS_UPIU_BOOT_WLUN), NULL);
7232 if (IS_ERR(sdev_boot)) {
7233 dev_err(hba->dev, "%s: BOOT WLUN not found\n", __func__);
7235 ufshcd_blk_pm_runtime_init(sdev_boot);
7236 scsi_device_put(sdev_boot);
7240 remove_sdev_ufs_device:
7241 scsi_remove_device(hba->sdev_ufs_device);
7246 static void ufshcd_wb_probe(struct ufs_hba *hba, u8 *desc_buf)
7248 struct ufs_dev_info *dev_info = &hba->dev_info;
7250 u32 d_lu_wb_buf_alloc;
7252 if (!ufshcd_is_wb_allowed(hba))
7255 * Probe WB only for UFS-2.2 and UFS-3.1 (and later) devices or
7256 * UFS devices with quirk UFS_DEVICE_QUIRK_SUPPORT_EXTENDED_FEATURES
7259 if (!(dev_info->wspecversion >= 0x310 ||
7260 dev_info->wspecversion == 0x220 ||
7261 (hba->dev_quirks & UFS_DEVICE_QUIRK_SUPPORT_EXTENDED_FEATURES)))
7264 if (hba->desc_size[QUERY_DESC_IDN_DEVICE] <
7265 DEVICE_DESC_PARAM_EXT_UFS_FEATURE_SUP + 4)
7268 dev_info->d_ext_ufs_feature_sup =
7269 get_unaligned_be32(desc_buf +
7270 DEVICE_DESC_PARAM_EXT_UFS_FEATURE_SUP);
7272 if (!(dev_info->d_ext_ufs_feature_sup & UFS_DEV_WRITE_BOOSTER_SUP))
7276 * WB may be supported but not configured while provisioning.
7277 * The spec says, in dedicated wb buffer mode,
7278 * a max of 1 lun would have wb buffer configured.
7279 * Now only shared buffer mode is supported.
7281 dev_info->b_wb_buffer_type =
7282 desc_buf[DEVICE_DESC_PARAM_WB_TYPE];
7284 dev_info->b_presrv_uspc_en =
7285 desc_buf[DEVICE_DESC_PARAM_WB_PRESRV_USRSPC_EN];
7287 if (dev_info->b_wb_buffer_type == WB_BUF_MODE_SHARED) {
7288 dev_info->d_wb_alloc_units =
7289 get_unaligned_be32(desc_buf +
7290 DEVICE_DESC_PARAM_WB_SHARED_ALLOC_UNITS);
7291 if (!dev_info->d_wb_alloc_units)
7294 for (lun = 0; lun < UFS_UPIU_MAX_WB_LUN_ID; lun++) {
7295 d_lu_wb_buf_alloc = 0;
7296 ufshcd_read_unit_desc_param(hba,
7298 UNIT_DESC_PARAM_WB_BUF_ALLOC_UNITS,
7299 (u8 *)&d_lu_wb_buf_alloc,
7300 sizeof(d_lu_wb_buf_alloc));
7301 if (d_lu_wb_buf_alloc) {
7302 dev_info->wb_dedicated_lu = lun;
7307 if (!d_lu_wb_buf_alloc)
7313 hba->caps &= ~UFSHCD_CAP_WB_EN;
7316 void ufshcd_fixup_dev_quirks(struct ufs_hba *hba, struct ufs_dev_fix *fixups)
7318 struct ufs_dev_fix *f;
7319 struct ufs_dev_info *dev_info = &hba->dev_info;
7324 for (f = fixups; f->quirk; f++) {
7325 if ((f->wmanufacturerid == dev_info->wmanufacturerid ||
7326 f->wmanufacturerid == UFS_ANY_VENDOR) &&
7327 ((dev_info->model &&
7328 STR_PRFX_EQUAL(f->model, dev_info->model)) ||
7329 !strcmp(f->model, UFS_ANY_MODEL)))
7330 hba->dev_quirks |= f->quirk;
7333 EXPORT_SYMBOL_GPL(ufshcd_fixup_dev_quirks);
7335 static void ufs_fixup_device_setup(struct ufs_hba *hba)
7337 /* fix by general quirk table */
7338 ufshcd_fixup_dev_quirks(hba, ufs_fixups);
7340 /* allow vendors to fix quirks */
7341 ufshcd_vops_fixup_dev_quirks(hba);
7344 static int ufs_get_device_desc(struct ufs_hba *hba)
7349 struct ufs_dev_info *dev_info = &hba->dev_info;
7351 desc_buf = kmalloc(QUERY_DESC_MAX_SIZE, GFP_KERNEL);
7357 err = ufshcd_read_desc_param(hba, QUERY_DESC_IDN_DEVICE, 0, 0, desc_buf,
7358 hba->desc_size[QUERY_DESC_IDN_DEVICE]);
7360 dev_err(hba->dev, "%s: Failed reading Device Desc. err = %d\n",
7366 * getting vendor (manufacturerID) and Bank Index in big endian
7369 dev_info->wmanufacturerid = desc_buf[DEVICE_DESC_PARAM_MANF_ID] << 8 |
7370 desc_buf[DEVICE_DESC_PARAM_MANF_ID + 1];
7372 /* getting Specification Version in big endian format */
7373 dev_info->wspecversion = desc_buf[DEVICE_DESC_PARAM_SPEC_VER] << 8 |
7374 desc_buf[DEVICE_DESC_PARAM_SPEC_VER + 1];
7376 model_index = desc_buf[DEVICE_DESC_PARAM_PRDCT_NAME];
7378 err = ufshcd_read_string_desc(hba, model_index,
7379 &dev_info->model, SD_ASCII_STD);
7381 dev_err(hba->dev, "%s: Failed reading Product Name. err = %d\n",
7386 ufs_fixup_device_setup(hba);
7388 ufshcd_wb_probe(hba, desc_buf);
7391 * ufshcd_read_string_desc returns size of the string
7392 * reset the error value
7401 static void ufs_put_device_desc(struct ufs_hba *hba)
7403 struct ufs_dev_info *dev_info = &hba->dev_info;
7405 kfree(dev_info->model);
7406 dev_info->model = NULL;
7410 * ufshcd_tune_pa_tactivate - Tunes PA_TActivate of local UniPro
7411 * @hba: per-adapter instance
7413 * PA_TActivate parameter can be tuned manually if UniPro version is less than
7414 * 1.61. PA_TActivate needs to be greater than or equal to peerM-PHY's
7415 * RX_MIN_ACTIVATETIME_CAPABILITY attribute. This optimal value can help reduce
7416 * the hibern8 exit latency.
7418 * Returns zero on success, non-zero error value on failure.
7420 static int ufshcd_tune_pa_tactivate(struct ufs_hba *hba)
7423 u32 peer_rx_min_activatetime = 0, tuned_pa_tactivate;
7425 ret = ufshcd_dme_peer_get(hba,
7427 RX_MIN_ACTIVATETIME_CAPABILITY,
7428 UIC_ARG_MPHY_RX_GEN_SEL_INDEX(0)),
7429 &peer_rx_min_activatetime);
7433 /* make sure proper unit conversion is applied */
7434 tuned_pa_tactivate =
7435 ((peer_rx_min_activatetime * RX_MIN_ACTIVATETIME_UNIT_US)
7436 / PA_TACTIVATE_TIME_UNIT_US);
7437 ret = ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TACTIVATE),
7438 tuned_pa_tactivate);
7445 * ufshcd_tune_pa_hibern8time - Tunes PA_Hibern8Time of local UniPro
7446 * @hba: per-adapter instance
7448 * PA_Hibern8Time parameter can be tuned manually if UniPro version is less than
7449 * 1.61. PA_Hibern8Time needs to be maximum of local M-PHY's
7450 * TX_HIBERN8TIME_CAPABILITY & peer M-PHY's RX_HIBERN8TIME_CAPABILITY.
7451 * This optimal value can help reduce the hibern8 exit latency.
7453 * Returns zero on success, non-zero error value on failure.
7455 static int ufshcd_tune_pa_hibern8time(struct ufs_hba *hba)
7458 u32 local_tx_hibern8_time_cap = 0, peer_rx_hibern8_time_cap = 0;
7459 u32 max_hibern8_time, tuned_pa_hibern8time;
7461 ret = ufshcd_dme_get(hba,
7462 UIC_ARG_MIB_SEL(TX_HIBERN8TIME_CAPABILITY,
7463 UIC_ARG_MPHY_TX_GEN_SEL_INDEX(0)),
7464 &local_tx_hibern8_time_cap);
7468 ret = ufshcd_dme_peer_get(hba,
7469 UIC_ARG_MIB_SEL(RX_HIBERN8TIME_CAPABILITY,
7470 UIC_ARG_MPHY_RX_GEN_SEL_INDEX(0)),
7471 &peer_rx_hibern8_time_cap);
7475 max_hibern8_time = max(local_tx_hibern8_time_cap,
7476 peer_rx_hibern8_time_cap);
7477 /* make sure proper unit conversion is applied */
7478 tuned_pa_hibern8time = ((max_hibern8_time * HIBERN8TIME_UNIT_US)
7479 / PA_HIBERN8_TIME_UNIT_US);
7480 ret = ufshcd_dme_set(hba, UIC_ARG_MIB(PA_HIBERN8TIME),
7481 tuned_pa_hibern8time);
7487 * ufshcd_quirk_tune_host_pa_tactivate - Ensures that host PA_TACTIVATE is
7488 * less than device PA_TACTIVATE time.
7489 * @hba: per-adapter instance
7491 * Some UFS devices require host PA_TACTIVATE to be lower than device
7492 * PA_TACTIVATE, we need to enable UFS_DEVICE_QUIRK_HOST_PA_TACTIVATE quirk
7495 * Returns zero on success, non-zero error value on failure.
7497 static int ufshcd_quirk_tune_host_pa_tactivate(struct ufs_hba *hba)
7500 u32 granularity, peer_granularity;
7501 u32 pa_tactivate, peer_pa_tactivate;
7502 u32 pa_tactivate_us, peer_pa_tactivate_us;
7503 u8 gran_to_us_table[] = {1, 4, 8, 16, 32, 100};
7505 ret = ufshcd_dme_get(hba, UIC_ARG_MIB(PA_GRANULARITY),
7510 ret = ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_GRANULARITY),
7515 if ((granularity < PA_GRANULARITY_MIN_VAL) ||
7516 (granularity > PA_GRANULARITY_MAX_VAL)) {
7517 dev_err(hba->dev, "%s: invalid host PA_GRANULARITY %d",
7518 __func__, granularity);
7522 if ((peer_granularity < PA_GRANULARITY_MIN_VAL) ||
7523 (peer_granularity > PA_GRANULARITY_MAX_VAL)) {
7524 dev_err(hba->dev, "%s: invalid device PA_GRANULARITY %d",
7525 __func__, peer_granularity);
7529 ret = ufshcd_dme_get(hba, UIC_ARG_MIB(PA_TACTIVATE), &pa_tactivate);
7533 ret = ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_TACTIVATE),
7534 &peer_pa_tactivate);
7538 pa_tactivate_us = pa_tactivate * gran_to_us_table[granularity - 1];
7539 peer_pa_tactivate_us = peer_pa_tactivate *
7540 gran_to_us_table[peer_granularity - 1];
7542 if (pa_tactivate_us > peer_pa_tactivate_us) {
7543 u32 new_peer_pa_tactivate;
7545 new_peer_pa_tactivate = pa_tactivate_us /
7546 gran_to_us_table[peer_granularity - 1];
7547 new_peer_pa_tactivate++;
7548 ret = ufshcd_dme_peer_set(hba, UIC_ARG_MIB(PA_TACTIVATE),
7549 new_peer_pa_tactivate);
7556 static void ufshcd_tune_unipro_params(struct ufs_hba *hba)
7558 if (ufshcd_is_unipro_pa_params_tuning_req(hba)) {
7559 ufshcd_tune_pa_tactivate(hba);
7560 ufshcd_tune_pa_hibern8time(hba);
7563 ufshcd_vops_apply_dev_quirks(hba);
7565 if (hba->dev_quirks & UFS_DEVICE_QUIRK_PA_TACTIVATE)
7566 /* set 1ms timeout for PA_TACTIVATE */
7567 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TACTIVATE), 10);
7569 if (hba->dev_quirks & UFS_DEVICE_QUIRK_HOST_PA_TACTIVATE)
7570 ufshcd_quirk_tune_host_pa_tactivate(hba);
7573 static void ufshcd_clear_dbg_ufs_stats(struct ufs_hba *hba)
7575 hba->ufs_stats.hibern8_exit_cnt = 0;
7576 hba->ufs_stats.last_hibern8_exit_tstamp = ktime_set(0, 0);
7577 hba->req_abort_count = 0;
7580 static int ufshcd_device_geo_params_init(struct ufs_hba *hba)
7586 buff_len = hba->desc_size[QUERY_DESC_IDN_GEOMETRY];
7587 desc_buf = kmalloc(buff_len, GFP_KERNEL);
7593 err = ufshcd_read_desc_param(hba, QUERY_DESC_IDN_GEOMETRY, 0, 0,
7594 desc_buf, buff_len);
7596 dev_err(hba->dev, "%s: Failed reading Geometry Desc. err = %d\n",
7601 if (desc_buf[GEOMETRY_DESC_PARAM_MAX_NUM_LUN] == 1)
7602 hba->dev_info.max_lu_supported = 32;
7603 else if (desc_buf[GEOMETRY_DESC_PARAM_MAX_NUM_LUN] == 0)
7604 hba->dev_info.max_lu_supported = 8;
7611 static struct ufs_ref_clk ufs_ref_clk_freqs[] = {
7612 {19200000, REF_CLK_FREQ_19_2_MHZ},
7613 {26000000, REF_CLK_FREQ_26_MHZ},
7614 {38400000, REF_CLK_FREQ_38_4_MHZ},
7615 {52000000, REF_CLK_FREQ_52_MHZ},
7616 {0, REF_CLK_FREQ_INVAL},
7619 static enum ufs_ref_clk_freq
7620 ufs_get_bref_clk_from_hz(unsigned long freq)
7624 for (i = 0; ufs_ref_clk_freqs[i].freq_hz; i++)
7625 if (ufs_ref_clk_freqs[i].freq_hz == freq)
7626 return ufs_ref_clk_freqs[i].val;
7628 return REF_CLK_FREQ_INVAL;
7631 void ufshcd_parse_dev_ref_clk_freq(struct ufs_hba *hba, struct clk *refclk)
7635 freq = clk_get_rate(refclk);
7637 hba->dev_ref_clk_freq =
7638 ufs_get_bref_clk_from_hz(freq);
7640 if (hba->dev_ref_clk_freq == REF_CLK_FREQ_INVAL)
7642 "invalid ref_clk setting = %ld\n", freq);
7645 static int ufshcd_set_dev_ref_clk(struct ufs_hba *hba)
7649 u32 freq = hba->dev_ref_clk_freq;
7651 err = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
7652 QUERY_ATTR_IDN_REF_CLK_FREQ, 0, 0, &ref_clk);
7655 dev_err(hba->dev, "failed reading bRefClkFreq. err = %d\n",
7660 if (ref_clk == freq)
7661 goto out; /* nothing to update */
7663 err = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_WRITE_ATTR,
7664 QUERY_ATTR_IDN_REF_CLK_FREQ, 0, 0, &freq);
7667 dev_err(hba->dev, "bRefClkFreq setting to %lu Hz failed\n",
7668 ufs_ref_clk_freqs[freq].freq_hz);
7672 dev_dbg(hba->dev, "bRefClkFreq setting to %lu Hz succeeded\n",
7673 ufs_ref_clk_freqs[freq].freq_hz);
7679 static int ufshcd_device_params_init(struct ufs_hba *hba)
7684 /* Init device descriptor sizes */
7685 for (i = 0; i < QUERY_DESC_IDN_MAX; i++)
7686 hba->desc_size[i] = QUERY_DESC_MAX_SIZE;
7688 /* Init UFS geometry descriptor related parameters */
7689 ret = ufshcd_device_geo_params_init(hba);
7693 /* Check and apply UFS device quirks */
7694 ret = ufs_get_device_desc(hba);
7696 dev_err(hba->dev, "%s: Failed getting device info. err = %d\n",
7701 ufshcd_get_ref_clk_gating_wait(hba);
7703 if (!ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_READ_FLAG,
7704 QUERY_FLAG_IDN_PWR_ON_WPE, 0, &flag))
7705 hba->dev_info.f_power_on_wp_en = flag;
7707 /* Probe maximum power mode co-supported by both UFS host and device */
7708 if (ufshcd_get_max_pwr_mode(hba))
7710 "%s: Failed getting max supported power mode\n",
7717 * ufshcd_add_lus - probe and add UFS logical units
7718 * @hba: per-adapter instance
7720 static int ufshcd_add_lus(struct ufs_hba *hba)
7724 /* Add required well known logical units to scsi mid layer */
7725 ret = ufshcd_scsi_add_wlus(hba);
7729 ufshcd_clear_ua_wluns(hba);
7731 /* Initialize devfreq after UFS device is detected */
7732 if (ufshcd_is_clkscaling_supported(hba)) {
7733 memcpy(&hba->clk_scaling.saved_pwr_info.info,
7735 sizeof(struct ufs_pa_layer_attr));
7736 hba->clk_scaling.saved_pwr_info.is_valid = true;
7737 if (!hba->devfreq) {
7738 ret = ufshcd_devfreq_init(hba);
7743 hba->clk_scaling.is_allowed = true;
7747 scsi_scan_host(hba->host);
7748 pm_runtime_put_sync(hba->dev);
7755 ufshcd_send_request_sense(struct ufs_hba *hba, struct scsi_device *sdp);
7757 static int ufshcd_clear_ua_wlun(struct ufs_hba *hba, u8 wlun)
7759 struct scsi_device *sdp;
7760 unsigned long flags;
7763 spin_lock_irqsave(hba->host->host_lock, flags);
7764 if (wlun == UFS_UPIU_UFS_DEVICE_WLUN)
7765 sdp = hba->sdev_ufs_device;
7766 else if (wlun == UFS_UPIU_RPMB_WLUN)
7767 sdp = hba->sdev_rpmb;
7771 ret = scsi_device_get(sdp);
7772 if (!ret && !scsi_device_online(sdp)) {
7774 scsi_device_put(sdp);
7779 spin_unlock_irqrestore(hba->host->host_lock, flags);
7783 ret = ufshcd_send_request_sense(hba, sdp);
7784 scsi_device_put(sdp);
7787 dev_err(hba->dev, "%s: UAC clear LU=%x ret = %d\n",
7788 __func__, wlun, ret);
7792 static int ufshcd_clear_ua_wluns(struct ufs_hba *hba)
7796 if (!hba->wlun_dev_clr_ua)
7799 ret = ufshcd_clear_ua_wlun(hba, UFS_UPIU_UFS_DEVICE_WLUN);
7801 ret = ufshcd_clear_ua_wlun(hba, UFS_UPIU_RPMB_WLUN);
7803 hba->wlun_dev_clr_ua = false;
7806 dev_err(hba->dev, "%s: Failed to clear UAC WLUNS ret = %d\n",
7812 * ufshcd_probe_hba - probe hba to detect device and initialize
7813 * @hba: per-adapter instance
7814 * @async: asynchronous execution or not
7816 * Execute link-startup and verify device initialization
7818 static int ufshcd_probe_hba(struct ufs_hba *hba, bool async)
7821 unsigned long flags;
7822 ktime_t start = ktime_get();
7824 ret = ufshcd_link_startup(hba);
7828 /* Debug counters initialization */
7829 ufshcd_clear_dbg_ufs_stats(hba);
7831 /* UniPro link is active now */
7832 ufshcd_set_link_active(hba);
7834 /* Verify device initialization by sending NOP OUT UPIU */
7835 ret = ufshcd_verify_dev_init(hba);
7839 /* Initiate UFS initialization, and waiting until completion */
7840 ret = ufshcd_complete_dev_init(hba);
7845 * Initialize UFS device parameters used by driver, these
7846 * parameters are associated with UFS descriptors.
7849 ret = ufshcd_device_params_init(hba);
7854 ufshcd_tune_unipro_params(hba);
7856 /* UFS device is also active now */
7857 ufshcd_set_ufs_dev_active(hba);
7858 ufshcd_force_reset_auto_bkops(hba);
7859 hba->wlun_dev_clr_ua = true;
7861 /* Gear up to HS gear if supported */
7862 if (hba->max_pwr_info.is_valid) {
7864 * Set the right value to bRefClkFreq before attempting to
7865 * switch to HS gears.
7867 if (hba->dev_ref_clk_freq != REF_CLK_FREQ_INVAL)
7868 ufshcd_set_dev_ref_clk(hba);
7869 ret = ufshcd_config_pwr_mode(hba, &hba->max_pwr_info.info);
7871 dev_err(hba->dev, "%s: Failed setting power mode, err = %d\n",
7875 ufshcd_print_pwr_info(hba);
7879 * bActiveICCLevel is volatile for UFS device (as per latest v2.1 spec)
7880 * and for removable UFS card as well, hence always set the parameter.
7881 * Note: Error handler may issue the device reset hence resetting
7882 * bActiveICCLevel as well so it is always safe to set this here.
7884 ufshcd_set_active_icc_lvl(hba);
7886 ufshcd_wb_config(hba);
7887 /* Enable Auto-Hibernate if configured */
7888 ufshcd_auto_hibern8_enable(hba);
7891 spin_lock_irqsave(hba->host->host_lock, flags);
7893 hba->ufshcd_state = UFSHCD_STATE_ERROR;
7894 else if (hba->ufshcd_state == UFSHCD_STATE_RESET)
7895 hba->ufshcd_state = UFSHCD_STATE_OPERATIONAL;
7896 spin_unlock_irqrestore(hba->host->host_lock, flags);
7898 trace_ufshcd_init(dev_name(hba->dev), ret,
7899 ktime_to_us(ktime_sub(ktime_get(), start)),
7900 hba->curr_dev_pwr_mode, hba->uic_link_state);
7905 * ufshcd_async_scan - asynchronous execution for probing hba
7906 * @data: data pointer to pass to this function
7907 * @cookie: cookie data
7909 static void ufshcd_async_scan(void *data, async_cookie_t cookie)
7911 struct ufs_hba *hba = (struct ufs_hba *)data;
7915 /* Initialize hba, detect and initialize UFS device */
7916 ret = ufshcd_probe_hba(hba, true);
7921 /* Probe and add UFS logical units */
7922 ret = ufshcd_add_lus(hba);
7925 * If we failed to initialize the device or the device is not
7926 * present, turn off the power/clocks etc.
7929 pm_runtime_put_sync(hba->dev);
7930 ufshcd_exit_clk_scaling(hba);
7931 ufshcd_hba_exit(hba);
7935 static const struct attribute_group *ufshcd_driver_groups[] = {
7936 &ufs_sysfs_unit_descriptor_group,
7937 &ufs_sysfs_lun_attributes_group,
7941 static struct ufs_hba_variant_params ufs_hba_vps = {
7942 .hba_enable_delay_us = 1000,
7943 .wb_flush_threshold = UFS_WB_BUF_REMAIN_PERCENT(40),
7944 .devfreq_profile.polling_ms = 100,
7945 .devfreq_profile.target = ufshcd_devfreq_target,
7946 .devfreq_profile.get_dev_status = ufshcd_devfreq_get_dev_status,
7947 .ondemand_data.upthreshold = 70,
7948 .ondemand_data.downdifferential = 5,
7951 static struct scsi_host_template ufshcd_driver_template = {
7952 .module = THIS_MODULE,
7954 .proc_name = UFSHCD,
7955 .queuecommand = ufshcd_queuecommand,
7956 .slave_alloc = ufshcd_slave_alloc,
7957 .slave_configure = ufshcd_slave_configure,
7958 .slave_destroy = ufshcd_slave_destroy,
7959 .change_queue_depth = ufshcd_change_queue_depth,
7960 .eh_abort_handler = ufshcd_abort,
7961 .eh_device_reset_handler = ufshcd_eh_device_reset_handler,
7962 .eh_host_reset_handler = ufshcd_eh_host_reset_handler,
7964 .sg_tablesize = SG_ALL,
7965 .cmd_per_lun = UFSHCD_CMD_PER_LUN,
7966 .can_queue = UFSHCD_CAN_QUEUE,
7967 .max_segment_size = PRDT_DATA_BYTE_COUNT_MAX,
7968 .max_host_blocked = 1,
7969 .track_queue_depth = 1,
7970 .sdev_groups = ufshcd_driver_groups,
7971 .dma_boundary = PAGE_SIZE - 1,
7972 .rpm_autosuspend_delay = RPM_AUTOSUSPEND_DELAY_MS,
7975 static int ufshcd_config_vreg_load(struct device *dev, struct ufs_vreg *vreg,
7984 * "set_load" operation shall be required on those regulators
7985 * which specifically configured current limitation. Otherwise
7986 * zero max_uA may cause unexpected behavior when regulator is
7987 * enabled or set as high power mode.
7992 ret = regulator_set_load(vreg->reg, ua);
7994 dev_err(dev, "%s: %s set load (ua=%d) failed, err=%d\n",
7995 __func__, vreg->name, ua, ret);
8001 static inline int ufshcd_config_vreg_lpm(struct ufs_hba *hba,
8002 struct ufs_vreg *vreg)
8004 return ufshcd_config_vreg_load(hba->dev, vreg, UFS_VREG_LPM_LOAD_UA);
8007 static inline int ufshcd_config_vreg_hpm(struct ufs_hba *hba,
8008 struct ufs_vreg *vreg)
8013 return ufshcd_config_vreg_load(hba->dev, vreg, vreg->max_uA);
8016 static int ufshcd_config_vreg(struct device *dev,
8017 struct ufs_vreg *vreg, bool on)
8020 struct regulator *reg;
8022 int min_uV, uA_load;
8029 if (regulator_count_voltages(reg) > 0) {
8030 uA_load = on ? vreg->max_uA : 0;
8031 ret = ufshcd_config_vreg_load(dev, vreg, uA_load);
8035 if (vreg->min_uV && vreg->max_uV) {
8036 min_uV = on ? vreg->min_uV : 0;
8037 ret = regulator_set_voltage(reg, min_uV, vreg->max_uV);
8040 "%s: %s set voltage failed, err=%d\n",
8041 __func__, name, ret);
8048 static int ufshcd_enable_vreg(struct device *dev, struct ufs_vreg *vreg)
8052 if (!vreg || vreg->enabled)
8055 ret = ufshcd_config_vreg(dev, vreg, true);
8057 ret = regulator_enable(vreg->reg);
8060 vreg->enabled = true;
8062 dev_err(dev, "%s: %s enable failed, err=%d\n",
8063 __func__, vreg->name, ret);
8068 static int ufshcd_disable_vreg(struct device *dev, struct ufs_vreg *vreg)
8072 if (!vreg || !vreg->enabled || vreg->always_on)
8075 ret = regulator_disable(vreg->reg);
8078 /* ignore errors on applying disable config */
8079 ufshcd_config_vreg(dev, vreg, false);
8080 vreg->enabled = false;
8082 dev_err(dev, "%s: %s disable failed, err=%d\n",
8083 __func__, vreg->name, ret);
8089 static int ufshcd_setup_vreg(struct ufs_hba *hba, bool on)
8092 struct device *dev = hba->dev;
8093 struct ufs_vreg_info *info = &hba->vreg_info;
8095 ret = ufshcd_toggle_vreg(dev, info->vcc, on);
8099 ret = ufshcd_toggle_vreg(dev, info->vccq, on);
8103 ret = ufshcd_toggle_vreg(dev, info->vccq2, on);
8107 ufshcd_toggle_vreg(dev, info->vccq2, false);
8108 ufshcd_toggle_vreg(dev, info->vccq, false);
8109 ufshcd_toggle_vreg(dev, info->vcc, false);
8114 static int ufshcd_setup_hba_vreg(struct ufs_hba *hba, bool on)
8116 struct ufs_vreg_info *info = &hba->vreg_info;
8118 return ufshcd_toggle_vreg(hba->dev, info->vdd_hba, on);
8121 static int ufshcd_get_vreg(struct device *dev, struct ufs_vreg *vreg)
8128 vreg->reg = devm_regulator_get(dev, vreg->name);
8129 if (IS_ERR(vreg->reg)) {
8130 ret = PTR_ERR(vreg->reg);
8131 dev_err(dev, "%s: %s get failed, err=%d\n",
8132 __func__, vreg->name, ret);
8138 static int ufshcd_init_vreg(struct ufs_hba *hba)
8141 struct device *dev = hba->dev;
8142 struct ufs_vreg_info *info = &hba->vreg_info;
8144 ret = ufshcd_get_vreg(dev, info->vcc);
8148 ret = ufshcd_get_vreg(dev, info->vccq);
8150 ret = ufshcd_get_vreg(dev, info->vccq2);
8155 static int ufshcd_init_hba_vreg(struct ufs_hba *hba)
8157 struct ufs_vreg_info *info = &hba->vreg_info;
8160 return ufshcd_get_vreg(hba->dev, info->vdd_hba);
8165 static int ufshcd_setup_clocks(struct ufs_hba *hba, bool on)
8168 struct ufs_clk_info *clki;
8169 struct list_head *head = &hba->clk_list_head;
8170 unsigned long flags;
8171 ktime_t start = ktime_get();
8172 bool clk_state_changed = false;
8174 if (list_empty(head))
8177 ret = ufshcd_vops_setup_clocks(hba, on, PRE_CHANGE);
8181 list_for_each_entry(clki, head, list) {
8182 if (!IS_ERR_OR_NULL(clki->clk)) {
8184 * Don't disable clocks which are needed
8185 * to keep the link active.
8187 if (ufshcd_is_link_active(hba) &&
8188 clki->keep_link_active)
8191 clk_state_changed = on ^ clki->enabled;
8192 if (on && !clki->enabled) {
8193 ret = clk_prepare_enable(clki->clk);
8195 dev_err(hba->dev, "%s: %s prepare enable failed, %d\n",
8196 __func__, clki->name, ret);
8199 } else if (!on && clki->enabled) {
8200 clk_disable_unprepare(clki->clk);
8203 dev_dbg(hba->dev, "%s: clk: %s %sabled\n", __func__,
8204 clki->name, on ? "en" : "dis");
8208 ret = ufshcd_vops_setup_clocks(hba, on, POST_CHANGE);
8214 list_for_each_entry(clki, head, list) {
8215 if (!IS_ERR_OR_NULL(clki->clk) && clki->enabled)
8216 clk_disable_unprepare(clki->clk);
8218 } else if (!ret && on) {
8219 spin_lock_irqsave(hba->host->host_lock, flags);
8220 hba->clk_gating.state = CLKS_ON;
8221 trace_ufshcd_clk_gating(dev_name(hba->dev),
8222 hba->clk_gating.state);
8223 spin_unlock_irqrestore(hba->host->host_lock, flags);
8226 if (clk_state_changed)
8227 trace_ufshcd_profile_clk_gating(dev_name(hba->dev),
8228 (on ? "on" : "off"),
8229 ktime_to_us(ktime_sub(ktime_get(), start)), ret);
8233 static int ufshcd_init_clocks(struct ufs_hba *hba)
8236 struct ufs_clk_info *clki;
8237 struct device *dev = hba->dev;
8238 struct list_head *head = &hba->clk_list_head;
8240 if (list_empty(head))
8243 list_for_each_entry(clki, head, list) {
8247 clki->clk = devm_clk_get(dev, clki->name);
8248 if (IS_ERR(clki->clk)) {
8249 ret = PTR_ERR(clki->clk);
8250 dev_err(dev, "%s: %s clk get failed, %d\n",
8251 __func__, clki->name, ret);
8256 * Parse device ref clk freq as per device tree "ref_clk".
8257 * Default dev_ref_clk_freq is set to REF_CLK_FREQ_INVAL
8258 * in ufshcd_alloc_host().
8260 if (!strcmp(clki->name, "ref_clk"))
8261 ufshcd_parse_dev_ref_clk_freq(hba, clki->clk);
8263 if (clki->max_freq) {
8264 ret = clk_set_rate(clki->clk, clki->max_freq);
8266 dev_err(hba->dev, "%s: %s clk set rate(%dHz) failed, %d\n",
8267 __func__, clki->name,
8268 clki->max_freq, ret);
8271 clki->curr_freq = clki->max_freq;
8273 dev_dbg(dev, "%s: clk: %s, rate: %lu\n", __func__,
8274 clki->name, clk_get_rate(clki->clk));
8280 static int ufshcd_variant_hba_init(struct ufs_hba *hba)
8287 err = ufshcd_vops_init(hba);
8289 dev_err(hba->dev, "%s: variant %s init failed err %d\n",
8290 __func__, ufshcd_get_var_name(hba), err);
8295 static void ufshcd_variant_hba_exit(struct ufs_hba *hba)
8300 ufshcd_vops_exit(hba);
8303 static int ufshcd_hba_init(struct ufs_hba *hba)
8308 * Handle host controller power separately from the UFS device power
8309 * rails as it will help controlling the UFS host controller power
8310 * collapse easily which is different than UFS device power collapse.
8311 * Also, enable the host controller power before we go ahead with rest
8312 * of the initialization here.
8314 err = ufshcd_init_hba_vreg(hba);
8318 err = ufshcd_setup_hba_vreg(hba, true);
8322 err = ufshcd_init_clocks(hba);
8324 goto out_disable_hba_vreg;
8326 err = ufshcd_setup_clocks(hba, true);
8328 goto out_disable_hba_vreg;
8330 err = ufshcd_init_vreg(hba);
8332 goto out_disable_clks;
8334 err = ufshcd_setup_vreg(hba, true);
8336 goto out_disable_clks;
8338 err = ufshcd_variant_hba_init(hba);
8340 goto out_disable_vreg;
8342 hba->is_powered = true;
8346 ufshcd_setup_vreg(hba, false);
8348 ufshcd_setup_clocks(hba, false);
8349 out_disable_hba_vreg:
8350 ufshcd_setup_hba_vreg(hba, false);
8355 static void ufshcd_hba_exit(struct ufs_hba *hba)
8357 if (hba->is_powered) {
8358 ufshcd_variant_hba_exit(hba);
8359 ufshcd_setup_vreg(hba, false);
8360 ufshcd_suspend_clkscaling(hba);
8361 if (ufshcd_is_clkscaling_supported(hba))
8363 ufshcd_suspend_clkscaling(hba);
8364 ufshcd_setup_clocks(hba, false);
8365 ufshcd_setup_hba_vreg(hba, false);
8366 hba->is_powered = false;
8367 ufs_put_device_desc(hba);
8372 ufshcd_send_request_sense(struct ufs_hba *hba, struct scsi_device *sdp)
8374 unsigned char cmd[6] = {REQUEST_SENSE,
8383 buffer = kzalloc(UFS_SENSE_SIZE, GFP_KERNEL);
8389 ret = scsi_execute(sdp, cmd, DMA_FROM_DEVICE, buffer,
8390 UFS_SENSE_SIZE, NULL, NULL,
8391 msecs_to_jiffies(1000), 3, 0, RQF_PM, NULL);
8393 pr_err("%s: failed with err %d\n", __func__, ret);
8401 * ufshcd_set_dev_pwr_mode - sends START STOP UNIT command to set device
8403 * @hba: per adapter instance
8404 * @pwr_mode: device power mode to set
8406 * Returns 0 if requested power mode is set successfully
8407 * Returns non-zero if failed to set the requested power mode
8409 static int ufshcd_set_dev_pwr_mode(struct ufs_hba *hba,
8410 enum ufs_dev_pwr_mode pwr_mode)
8412 unsigned char cmd[6] = { START_STOP };
8413 struct scsi_sense_hdr sshdr;
8414 struct scsi_device *sdp;
8415 unsigned long flags;
8418 spin_lock_irqsave(hba->host->host_lock, flags);
8419 sdp = hba->sdev_ufs_device;
8421 ret = scsi_device_get(sdp);
8422 if (!ret && !scsi_device_online(sdp)) {
8424 scsi_device_put(sdp);
8429 spin_unlock_irqrestore(hba->host->host_lock, flags);
8435 * If scsi commands fail, the scsi mid-layer schedules scsi error-
8436 * handling, which would wait for host to be resumed. Since we know
8437 * we are functional while we are here, skip host resume in error
8440 hba->host->eh_noresume = 1;
8441 ufshcd_clear_ua_wluns(hba);
8443 cmd[4] = pwr_mode << 4;
8446 * Current function would be generally called from the power management
8447 * callbacks hence set the RQF_PM flag so that it doesn't resume the
8448 * already suspended childs.
8450 ret = scsi_execute(sdp, cmd, DMA_NONE, NULL, 0, NULL, &sshdr,
8451 START_STOP_TIMEOUT, 0, 0, RQF_PM, NULL);
8453 sdev_printk(KERN_WARNING, sdp,
8454 "START_STOP failed for power mode: %d, result %x\n",
8456 if (driver_byte(ret) == DRIVER_SENSE)
8457 scsi_print_sense_hdr(sdp, NULL, &sshdr);
8461 hba->curr_dev_pwr_mode = pwr_mode;
8463 scsi_device_put(sdp);
8464 hba->host->eh_noresume = 0;
8468 static int ufshcd_link_state_transition(struct ufs_hba *hba,
8469 enum uic_link_state req_link_state,
8470 int check_for_bkops)
8474 if (req_link_state == hba->uic_link_state)
8477 if (req_link_state == UIC_LINK_HIBERN8_STATE) {
8478 ret = ufshcd_uic_hibern8_enter(hba);
8480 ufshcd_set_link_hibern8(hba);
8482 dev_err(hba->dev, "%s: hibern8 enter failed %d\n",
8488 * If autobkops is enabled, link can't be turned off because
8489 * turning off the link would also turn off the device, except in the
8490 * case of DeepSleep where the device is expected to remain powered.
8492 else if ((req_link_state == UIC_LINK_OFF_STATE) &&
8493 (!check_for_bkops || !hba->auto_bkops_enabled)) {
8495 * Let's make sure that link is in low power mode, we are doing
8496 * this currently by putting the link in Hibern8. Otherway to
8497 * put the link in low power mode is to send the DME end point
8498 * to device and then send the DME reset command to local
8499 * unipro. But putting the link in hibern8 is much faster.
8501 * Note also that putting the link in Hibern8 is a requirement
8502 * for entering DeepSleep.
8504 ret = ufshcd_uic_hibern8_enter(hba);
8506 dev_err(hba->dev, "%s: hibern8 enter failed %d\n",
8511 * Change controller state to "reset state" which
8512 * should also put the link in off/reset state
8514 ufshcd_hba_stop(hba);
8516 * TODO: Check if we need any delay to make sure that
8517 * controller is reset
8519 ufshcd_set_link_off(hba);
8526 static void ufshcd_vreg_set_lpm(struct ufs_hba *hba)
8528 bool vcc_off = false;
8531 * It seems some UFS devices may keep drawing more than sleep current
8532 * (atleast for 500us) from UFS rails (especially from VCCQ rail).
8533 * To avoid this situation, add 2ms delay before putting these UFS
8534 * rails in LPM mode.
8536 if (!ufshcd_is_link_active(hba) &&
8537 hba->dev_quirks & UFS_DEVICE_QUIRK_DELAY_BEFORE_LPM)
8538 usleep_range(2000, 2100);
8541 * If UFS device is either in UFS_Sleep turn off VCC rail to save some
8544 * If UFS device and link is in OFF state, all power supplies (VCC,
8545 * VCCQ, VCCQ2) can be turned off if power on write protect is not
8546 * required. If UFS link is inactive (Hibern8 or OFF state) and device
8547 * is in sleep state, put VCCQ & VCCQ2 rails in LPM mode.
8549 * Ignore the error returned by ufshcd_toggle_vreg() as device is anyway
8550 * in low power state which would save some power.
8552 * If Write Booster is enabled and the device needs to flush the WB
8553 * buffer OR if bkops status is urgent for WB, keep Vcc on.
8555 if (ufshcd_is_ufs_dev_poweroff(hba) && ufshcd_is_link_off(hba) &&
8556 !hba->dev_info.is_lu_power_on_wp) {
8557 ufshcd_setup_vreg(hba, false);
8559 } else if (!ufshcd_is_ufs_dev_active(hba)) {
8560 ufshcd_toggle_vreg(hba->dev, hba->vreg_info.vcc, false);
8562 if (!ufshcd_is_link_active(hba)) {
8563 ufshcd_config_vreg_lpm(hba, hba->vreg_info.vccq);
8564 ufshcd_config_vreg_lpm(hba, hba->vreg_info.vccq2);
8569 * Some UFS devices require delay after VCC power rail is turned-off.
8571 if (vcc_off && hba->vreg_info.vcc &&
8572 hba->dev_quirks & UFS_DEVICE_QUIRK_DELAY_AFTER_LPM)
8573 usleep_range(5000, 5100);
8576 static int ufshcd_vreg_set_hpm(struct ufs_hba *hba)
8580 if (ufshcd_is_ufs_dev_poweroff(hba) && ufshcd_is_link_off(hba) &&
8581 !hba->dev_info.is_lu_power_on_wp) {
8582 ret = ufshcd_setup_vreg(hba, true);
8583 } else if (!ufshcd_is_ufs_dev_active(hba)) {
8584 if (!ret && !ufshcd_is_link_active(hba)) {
8585 ret = ufshcd_config_vreg_hpm(hba, hba->vreg_info.vccq);
8588 ret = ufshcd_config_vreg_hpm(hba, hba->vreg_info.vccq2);
8592 ret = ufshcd_toggle_vreg(hba->dev, hba->vreg_info.vcc, true);
8597 ufshcd_config_vreg_lpm(hba, hba->vreg_info.vccq);
8599 ufshcd_toggle_vreg(hba->dev, hba->vreg_info.vcc, false);
8604 static void ufshcd_hba_vreg_set_lpm(struct ufs_hba *hba)
8606 if (ufshcd_is_link_off(hba) || ufshcd_can_aggressive_pc(hba))
8607 ufshcd_setup_hba_vreg(hba, false);
8610 static void ufshcd_hba_vreg_set_hpm(struct ufs_hba *hba)
8612 if (ufshcd_is_link_off(hba) || ufshcd_can_aggressive_pc(hba))
8613 ufshcd_setup_hba_vreg(hba, true);
8617 * ufshcd_suspend - helper function for suspend operations
8618 * @hba: per adapter instance
8619 * @pm_op: desired low power operation type
8621 * This function will try to put the UFS device and link into low power
8622 * mode based on the "rpm_lvl" (Runtime PM level) or "spm_lvl"
8623 * (System PM level).
8625 * If this function is called during shutdown, it will make sure that
8626 * both UFS device and UFS link is powered off.
8628 * NOTE: UFS device & link must be active before we enter in this function.
8630 * Returns 0 for success and non-zero for failure
8632 static int ufshcd_suspend(struct ufs_hba *hba, enum ufs_pm_op pm_op)
8635 int check_for_bkops;
8636 enum ufs_pm_level pm_lvl;
8637 enum ufs_dev_pwr_mode req_dev_pwr_mode;
8638 enum uic_link_state req_link_state;
8640 hba->pm_op_in_progress = 1;
8641 if (!ufshcd_is_shutdown_pm(pm_op)) {
8642 pm_lvl = ufshcd_is_runtime_pm(pm_op) ?
8643 hba->rpm_lvl : hba->spm_lvl;
8644 req_dev_pwr_mode = ufs_get_pm_lvl_to_dev_pwr_mode(pm_lvl);
8645 req_link_state = ufs_get_pm_lvl_to_link_pwr_state(pm_lvl);
8647 req_dev_pwr_mode = UFS_POWERDOWN_PWR_MODE;
8648 req_link_state = UIC_LINK_OFF_STATE;
8652 * If we can't transition into any of the low power modes
8653 * just gate the clocks.
8655 ufshcd_hold(hba, false);
8656 hba->clk_gating.is_suspended = true;
8658 if (hba->clk_scaling.is_allowed) {
8659 cancel_work_sync(&hba->clk_scaling.suspend_work);
8660 cancel_work_sync(&hba->clk_scaling.resume_work);
8661 ufshcd_suspend_clkscaling(hba);
8664 if (req_dev_pwr_mode == UFS_ACTIVE_PWR_MODE &&
8665 req_link_state == UIC_LINK_ACTIVE_STATE) {
8669 if ((req_dev_pwr_mode == hba->curr_dev_pwr_mode) &&
8670 (req_link_state == hba->uic_link_state))
8673 /* UFS device & link must be active before we enter in this function */
8674 if (!ufshcd_is_ufs_dev_active(hba) || !ufshcd_is_link_active(hba)) {
8679 if (ufshcd_is_runtime_pm(pm_op)) {
8680 if (ufshcd_can_autobkops_during_suspend(hba)) {
8682 * The device is idle with no requests in the queue,
8683 * allow background operations if bkops status shows
8684 * that performance might be impacted.
8686 ret = ufshcd_urgent_bkops(hba);
8690 /* make sure that auto bkops is disabled */
8691 ufshcd_disable_auto_bkops(hba);
8694 * If device needs to do BKOP or WB buffer flush during
8695 * Hibern8, keep device power mode as "active power mode"
8698 hba->dev_info.b_rpm_dev_flush_capable =
8699 hba->auto_bkops_enabled ||
8700 (((req_link_state == UIC_LINK_HIBERN8_STATE) ||
8701 ((req_link_state == UIC_LINK_ACTIVE_STATE) &&
8702 ufshcd_is_auto_hibern8_enabled(hba))) &&
8703 ufshcd_wb_need_flush(hba));
8706 flush_work(&hba->eeh_work);
8708 if (req_dev_pwr_mode != hba->curr_dev_pwr_mode) {
8709 if (!ufshcd_is_runtime_pm(pm_op))
8710 /* ensure that bkops is disabled */
8711 ufshcd_disable_auto_bkops(hba);
8713 if (!hba->dev_info.b_rpm_dev_flush_capable) {
8714 ret = ufshcd_set_dev_pwr_mode(hba, req_dev_pwr_mode);
8721 * In the case of DeepSleep, the device is expected to remain powered
8722 * with the link off, so do not check for bkops.
8724 check_for_bkops = !ufshcd_is_ufs_dev_deepsleep(hba);
8725 ret = ufshcd_link_state_transition(hba, req_link_state, check_for_bkops);
8727 goto set_dev_active;
8729 ufshcd_vreg_set_lpm(hba);
8733 * Call vendor specific suspend callback. As these callbacks may access
8734 * vendor specific host controller register space call them before the
8735 * host clocks are ON.
8737 ret = ufshcd_vops_suspend(hba, pm_op);
8739 goto set_link_active;
8741 * Disable the host irq as host controller as there won't be any
8742 * host controller transaction expected till resume.
8744 ufshcd_disable_irq(hba);
8746 ufshcd_setup_clocks(hba, false);
8748 if (ufshcd_is_clkgating_allowed(hba)) {
8749 hba->clk_gating.state = CLKS_OFF;
8750 trace_ufshcd_clk_gating(dev_name(hba->dev),
8751 hba->clk_gating.state);
8754 /* Put the host controller in low power mode if possible */
8755 ufshcd_hba_vreg_set_lpm(hba);
8759 if (hba->clk_scaling.is_allowed)
8760 ufshcd_resume_clkscaling(hba);
8761 ufshcd_vreg_set_hpm(hba);
8763 * Device hardware reset is required to exit DeepSleep. Also, for
8764 * DeepSleep, the link is off so host reset and restore will be done
8767 if (ufshcd_is_ufs_dev_deepsleep(hba)) {
8768 ufshcd_device_reset(hba);
8769 WARN_ON(!ufshcd_is_link_off(hba));
8771 if (ufshcd_is_link_hibern8(hba) && !ufshcd_uic_hibern8_exit(hba))
8772 ufshcd_set_link_active(hba);
8773 else if (ufshcd_is_link_off(hba))
8774 ufshcd_host_reset_and_restore(hba);
8776 /* Can also get here needing to exit DeepSleep */
8777 if (ufshcd_is_ufs_dev_deepsleep(hba)) {
8778 ufshcd_device_reset(hba);
8779 ufshcd_host_reset_and_restore(hba);
8781 if (!ufshcd_set_dev_pwr_mode(hba, UFS_ACTIVE_PWR_MODE))
8782 ufshcd_disable_auto_bkops(hba);
8784 if (hba->clk_scaling.is_allowed)
8785 ufshcd_resume_clkscaling(hba);
8786 hba->clk_gating.is_suspended = false;
8787 hba->dev_info.b_rpm_dev_flush_capable = false;
8788 ufshcd_clear_ua_wluns(hba);
8789 ufshcd_release(hba);
8791 if (hba->dev_info.b_rpm_dev_flush_capable) {
8792 schedule_delayed_work(&hba->rpm_dev_flush_recheck_work,
8793 msecs_to_jiffies(RPM_DEV_FLUSH_RECHECK_WORK_DELAY_MS));
8796 hba->pm_op_in_progress = 0;
8799 ufshcd_update_evt_hist(hba, UFS_EVT_SUSPEND_ERR, (u32)ret);
8804 * ufshcd_resume - helper function for resume operations
8805 * @hba: per adapter instance
8806 * @pm_op: runtime PM or system PM
8808 * This function basically brings the UFS device, UniPro link and controller
8811 * Returns 0 for success and non-zero for failure
8813 static int ufshcd_resume(struct ufs_hba *hba, enum ufs_pm_op pm_op)
8816 enum uic_link_state old_link_state;
8818 hba->pm_op_in_progress = 1;
8819 old_link_state = hba->uic_link_state;
8821 ufshcd_hba_vreg_set_hpm(hba);
8822 /* Make sure clocks are enabled before accessing controller */
8823 ret = ufshcd_setup_clocks(hba, true);
8827 /* enable the host irq as host controller would be active soon */
8828 ufshcd_enable_irq(hba);
8830 ret = ufshcd_vreg_set_hpm(hba);
8832 goto disable_irq_and_vops_clks;
8835 * Call vendor specific resume callback. As these callbacks may access
8836 * vendor specific host controller register space call them when the
8837 * host clocks are ON.
8839 ret = ufshcd_vops_resume(hba, pm_op);
8843 /* For DeepSleep, the only supported option is to have the link off */
8844 WARN_ON(ufshcd_is_ufs_dev_deepsleep(hba) && !ufshcd_is_link_off(hba));
8846 if (ufshcd_is_link_hibern8(hba)) {
8847 ret = ufshcd_uic_hibern8_exit(hba);
8849 ufshcd_set_link_active(hba);
8851 dev_err(hba->dev, "%s: hibern8 exit failed %d\n",
8853 goto vendor_suspend;
8855 } else if (ufshcd_is_link_off(hba)) {
8857 * A full initialization of the host and the device is
8858 * required since the link was put to off during suspend.
8859 * Note, in the case of DeepSleep, the device will exit
8860 * DeepSleep due to device reset.
8862 ret = ufshcd_reset_and_restore(hba);
8864 * ufshcd_reset_and_restore() should have already
8865 * set the link state as active
8867 if (ret || !ufshcd_is_link_active(hba))
8868 goto vendor_suspend;
8871 if (!ufshcd_is_ufs_dev_active(hba)) {
8872 ret = ufshcd_set_dev_pwr_mode(hba, UFS_ACTIVE_PWR_MODE);
8874 goto set_old_link_state;
8877 if (ufshcd_keep_autobkops_enabled_except_suspend(hba))
8878 ufshcd_enable_auto_bkops(hba);
8881 * If BKOPs operations are urgently needed at this moment then
8882 * keep auto-bkops enabled or else disable it.
8884 ufshcd_urgent_bkops(hba);
8886 hba->clk_gating.is_suspended = false;
8888 if (hba->clk_scaling.is_allowed)
8889 ufshcd_resume_clkscaling(hba);
8891 /* Enable Auto-Hibernate if configured */
8892 ufshcd_auto_hibern8_enable(hba);
8894 if (hba->dev_info.b_rpm_dev_flush_capable) {
8895 hba->dev_info.b_rpm_dev_flush_capable = false;
8896 cancel_delayed_work(&hba->rpm_dev_flush_recheck_work);
8899 ufshcd_clear_ua_wluns(hba);
8901 /* Schedule clock gating in case of no access to UFS device yet */
8902 ufshcd_release(hba);
8907 ufshcd_link_state_transition(hba, old_link_state, 0);
8909 ufshcd_vops_suspend(hba, pm_op);
8911 ufshcd_vreg_set_lpm(hba);
8912 disable_irq_and_vops_clks:
8913 ufshcd_disable_irq(hba);
8914 if (hba->clk_scaling.is_allowed)
8915 ufshcd_suspend_clkscaling(hba);
8916 ufshcd_setup_clocks(hba, false);
8917 if (ufshcd_is_clkgating_allowed(hba)) {
8918 hba->clk_gating.state = CLKS_OFF;
8919 trace_ufshcd_clk_gating(dev_name(hba->dev),
8920 hba->clk_gating.state);
8923 hba->pm_op_in_progress = 0;
8925 ufshcd_update_evt_hist(hba, UFS_EVT_RESUME_ERR, (u32)ret);
8930 * ufshcd_system_suspend - system suspend routine
8931 * @hba: per adapter instance
8933 * Check the description of ufshcd_suspend() function for more details.
8935 * Returns 0 for success and non-zero for failure
8937 int ufshcd_system_suspend(struct ufs_hba *hba)
8940 ktime_t start = ktime_get();
8943 if (!hba || !hba->is_powered)
8946 if ((ufs_get_pm_lvl_to_dev_pwr_mode(hba->spm_lvl) ==
8947 hba->curr_dev_pwr_mode) &&
8948 (ufs_get_pm_lvl_to_link_pwr_state(hba->spm_lvl) ==
8949 hba->uic_link_state) &&
8950 !hba->dev_info.b_rpm_dev_flush_capable)
8953 if (pm_runtime_suspended(hba->dev)) {
8955 * UFS device and/or UFS link low power states during runtime
8956 * suspend seems to be different than what is expected during
8957 * system suspend. Hence runtime resume the devic & link and
8958 * let the system suspend low power states to take effect.
8959 * TODO: If resume takes longer time, we might have optimize
8960 * it in future by not resuming everything if possible.
8962 ret = ufshcd_runtime_resume(hba);
8967 ret = ufshcd_suspend(hba, UFS_SYSTEM_PM);
8969 trace_ufshcd_system_suspend(dev_name(hba->dev), ret,
8970 ktime_to_us(ktime_sub(ktime_get(), start)),
8971 hba->curr_dev_pwr_mode, hba->uic_link_state);
8973 hba->is_sys_suspended = true;
8978 EXPORT_SYMBOL(ufshcd_system_suspend);
8981 * ufshcd_system_resume - system resume routine
8982 * @hba: per adapter instance
8984 * Returns 0 for success and non-zero for failure
8987 int ufshcd_system_resume(struct ufs_hba *hba)
8990 ktime_t start = ktime_get();
8997 if (!hba->is_powered || pm_runtime_suspended(hba->dev))
8999 * Let the runtime resume take care of resuming
9000 * if runtime suspended.
9004 ret = ufshcd_resume(hba, UFS_SYSTEM_PM);
9006 trace_ufshcd_system_resume(dev_name(hba->dev), ret,
9007 ktime_to_us(ktime_sub(ktime_get(), start)),
9008 hba->curr_dev_pwr_mode, hba->uic_link_state);
9010 hba->is_sys_suspended = false;
9014 EXPORT_SYMBOL(ufshcd_system_resume);
9017 * ufshcd_runtime_suspend - runtime suspend routine
9018 * @hba: per adapter instance
9020 * Check the description of ufshcd_suspend() function for more details.
9022 * Returns 0 for success and non-zero for failure
9024 int ufshcd_runtime_suspend(struct ufs_hba *hba)
9027 ktime_t start = ktime_get();
9032 if (!hba->is_powered)
9035 ret = ufshcd_suspend(hba, UFS_RUNTIME_PM);
9037 trace_ufshcd_runtime_suspend(dev_name(hba->dev), ret,
9038 ktime_to_us(ktime_sub(ktime_get(), start)),
9039 hba->curr_dev_pwr_mode, hba->uic_link_state);
9042 EXPORT_SYMBOL(ufshcd_runtime_suspend);
9045 * ufshcd_runtime_resume - runtime resume routine
9046 * @hba: per adapter instance
9048 * This function basically brings the UFS device, UniPro link and controller
9049 * to active state. Following operations are done in this function:
9051 * 1. Turn on all the controller related clocks
9052 * 2. Bring the UniPro link out of Hibernate state
9053 * 3. If UFS device is in sleep state, turn ON VCC rail and bring the UFS device
9055 * 4. If auto-bkops is enabled on the device, disable it.
9057 * So following would be the possible power state after this function return
9059 * S1: UFS device in Active state with VCC rail ON
9060 * UniPro link in Active state
9061 * All the UFS/UniPro controller clocks are ON
9063 * Returns 0 for success and non-zero for failure
9065 int ufshcd_runtime_resume(struct ufs_hba *hba)
9068 ktime_t start = ktime_get();
9073 if (!hba->is_powered)
9076 ret = ufshcd_resume(hba, UFS_RUNTIME_PM);
9078 trace_ufshcd_runtime_resume(dev_name(hba->dev), ret,
9079 ktime_to_us(ktime_sub(ktime_get(), start)),
9080 hba->curr_dev_pwr_mode, hba->uic_link_state);
9083 EXPORT_SYMBOL(ufshcd_runtime_resume);
9085 int ufshcd_runtime_idle(struct ufs_hba *hba)
9089 EXPORT_SYMBOL(ufshcd_runtime_idle);
9092 * ufshcd_shutdown - shutdown routine
9093 * @hba: per adapter instance
9095 * This function would power off both UFS device and UFS link.
9097 * Returns 0 always to allow force shutdown even in case of errors.
9099 int ufshcd_shutdown(struct ufs_hba *hba)
9104 if (!hba->is_powered)
9107 if (ufshcd_is_ufs_dev_poweroff(hba) && ufshcd_is_link_off(hba))
9110 pm_runtime_get_sync(hba->dev);
9112 ret = ufshcd_suspend(hba, UFS_SHUTDOWN_PM);
9115 dev_err(hba->dev, "%s failed, err %d\n", __func__, ret);
9116 hba->is_powered = false;
9118 /* allow force shutdown even in case of errors */
9121 EXPORT_SYMBOL(ufshcd_shutdown);
9124 * ufshcd_remove - de-allocate SCSI host and host memory space
9125 * data structure memory
9126 * @hba: per adapter instance
9128 void ufshcd_remove(struct ufs_hba *hba)
9130 ufs_bsg_remove(hba);
9131 ufs_sysfs_remove_nodes(hba->dev);
9132 blk_cleanup_queue(hba->tmf_queue);
9133 blk_mq_free_tag_set(&hba->tmf_tag_set);
9134 blk_cleanup_queue(hba->cmd_queue);
9135 scsi_remove_host(hba->host);
9136 destroy_workqueue(hba->eh_wq);
9137 /* disable interrupts */
9138 ufshcd_disable_intr(hba, hba->intr_mask);
9139 ufshcd_hba_stop(hba);
9141 ufshcd_exit_clk_scaling(hba);
9142 ufshcd_exit_clk_gating(hba);
9143 if (ufshcd_is_clkscaling_supported(hba))
9144 device_remove_file(hba->dev, &hba->clk_scaling.enable_attr);
9145 ufshcd_hba_exit(hba);
9147 EXPORT_SYMBOL_GPL(ufshcd_remove);
9150 * ufshcd_dealloc_host - deallocate Host Bus Adapter (HBA)
9151 * @hba: pointer to Host Bus Adapter (HBA)
9153 void ufshcd_dealloc_host(struct ufs_hba *hba)
9155 ufshcd_crypto_destroy_keyslot_manager(hba);
9156 scsi_host_put(hba->host);
9158 EXPORT_SYMBOL_GPL(ufshcd_dealloc_host);
9161 * ufshcd_set_dma_mask - Set dma mask based on the controller
9162 * addressing capability
9163 * @hba: per adapter instance
9165 * Returns 0 for success, non-zero for failure
9167 static int ufshcd_set_dma_mask(struct ufs_hba *hba)
9169 if (hba->capabilities & MASK_64_ADDRESSING_SUPPORT) {
9170 if (!dma_set_mask_and_coherent(hba->dev, DMA_BIT_MASK(64)))
9173 return dma_set_mask_and_coherent(hba->dev, DMA_BIT_MASK(32));
9177 * ufshcd_alloc_host - allocate Host Bus Adapter (HBA)
9178 * @dev: pointer to device handle
9179 * @hba_handle: driver private handle
9180 * Returns 0 on success, non-zero value on failure
9182 int ufshcd_alloc_host(struct device *dev, struct ufs_hba **hba_handle)
9184 struct Scsi_Host *host;
9185 struct ufs_hba *hba;
9190 "Invalid memory reference for dev is NULL\n");
9195 host = scsi_host_alloc(&ufshcd_driver_template,
9196 sizeof(struct ufs_hba));
9198 dev_err(dev, "scsi_host_alloc failed\n");
9202 hba = shost_priv(host);
9206 hba->dev_ref_clk_freq = REF_CLK_FREQ_INVAL;
9208 INIT_LIST_HEAD(&hba->clk_list_head);
9213 EXPORT_SYMBOL(ufshcd_alloc_host);
9215 /* This function exists because blk_mq_alloc_tag_set() requires this. */
9216 static blk_status_t ufshcd_queue_tmf(struct blk_mq_hw_ctx *hctx,
9217 const struct blk_mq_queue_data *qd)
9220 return BLK_STS_NOTSUPP;
9223 static const struct blk_mq_ops ufshcd_tmf_ops = {
9224 .queue_rq = ufshcd_queue_tmf,
9228 * ufshcd_init - Driver initialization routine
9229 * @hba: per-adapter instance
9230 * @mmio_base: base register address
9231 * @irq: Interrupt line of device
9232 * Returns 0 on success, non-zero value on failure
9234 int ufshcd_init(struct ufs_hba *hba, void __iomem *mmio_base, unsigned int irq)
9237 struct Scsi_Host *host = hba->host;
9238 struct device *dev = hba->dev;
9239 char eh_wq_name[sizeof("ufs_eh_wq_00")];
9243 "Invalid memory reference for mmio_base is NULL\n");
9248 hba->mmio_base = mmio_base;
9250 hba->vps = &ufs_hba_vps;
9252 err = ufshcd_hba_init(hba);
9256 /* Read capabilities registers */
9257 err = ufshcd_hba_capabilities(hba);
9261 /* Get UFS version supported by the controller */
9262 hba->ufs_version = ufshcd_get_ufs_version(hba);
9264 if ((hba->ufs_version != UFSHCI_VERSION_10) &&
9265 (hba->ufs_version != UFSHCI_VERSION_11) &&
9266 (hba->ufs_version != UFSHCI_VERSION_20) &&
9267 (hba->ufs_version != UFSHCI_VERSION_21))
9268 dev_err(hba->dev, "invalid UFS version 0x%x\n",
9271 /* Get Interrupt bit mask per version */
9272 hba->intr_mask = ufshcd_get_intr_mask(hba);
9274 err = ufshcd_set_dma_mask(hba);
9276 dev_err(hba->dev, "set dma mask failed\n");
9280 /* Allocate memory for host memory space */
9281 err = ufshcd_memory_alloc(hba);
9283 dev_err(hba->dev, "Memory allocation failed\n");
9288 ufshcd_host_memory_configure(hba);
9290 host->can_queue = hba->nutrs;
9291 host->cmd_per_lun = hba->nutrs;
9292 host->max_id = UFSHCD_MAX_ID;
9293 host->max_lun = UFS_MAX_LUNS;
9294 host->max_channel = UFSHCD_MAX_CHANNEL;
9295 host->unique_id = host->host_no;
9296 host->max_cmd_len = UFS_CDB_SIZE;
9298 hba->max_pwr_info.is_valid = false;
9300 /* Initialize work queues */
9301 snprintf(eh_wq_name, sizeof(eh_wq_name), "ufs_eh_wq_%d",
9302 hba->host->host_no);
9303 hba->eh_wq = create_singlethread_workqueue(eh_wq_name);
9305 dev_err(hba->dev, "%s: failed to create eh workqueue\n",
9310 INIT_WORK(&hba->eh_work, ufshcd_err_handler);
9311 INIT_WORK(&hba->eeh_work, ufshcd_exception_event_handler);
9313 sema_init(&hba->eh_sem, 1);
9315 /* Initialize UIC command mutex */
9316 mutex_init(&hba->uic_cmd_mutex);
9318 /* Initialize mutex for device management commands */
9319 mutex_init(&hba->dev_cmd.lock);
9321 init_rwsem(&hba->clk_scaling_lock);
9323 ufshcd_init_clk_gating(hba);
9325 ufshcd_init_clk_scaling(hba);
9328 * In order to avoid any spurious interrupt immediately after
9329 * registering UFS controller interrupt handler, clear any pending UFS
9330 * interrupt status and disable all the UFS interrupts.
9332 ufshcd_writel(hba, ufshcd_readl(hba, REG_INTERRUPT_STATUS),
9333 REG_INTERRUPT_STATUS);
9334 ufshcd_writel(hba, 0, REG_INTERRUPT_ENABLE);
9336 * Make sure that UFS interrupts are disabled and any pending interrupt
9337 * status is cleared before registering UFS interrupt handler.
9341 /* IRQ registration */
9342 err = devm_request_irq(dev, irq, ufshcd_intr, IRQF_SHARED, UFSHCD, hba);
9344 dev_err(hba->dev, "request irq failed\n");
9347 hba->is_irq_enabled = true;
9350 err = scsi_add_host(host, hba->dev);
9352 dev_err(hba->dev, "scsi_add_host failed\n");
9356 hba->cmd_queue = blk_mq_init_queue(&hba->host->tag_set);
9357 if (IS_ERR(hba->cmd_queue)) {
9358 err = PTR_ERR(hba->cmd_queue);
9359 goto out_remove_scsi_host;
9362 hba->tmf_tag_set = (struct blk_mq_tag_set) {
9364 .queue_depth = hba->nutmrs,
9365 .ops = &ufshcd_tmf_ops,
9366 .flags = BLK_MQ_F_NO_SCHED,
9368 err = blk_mq_alloc_tag_set(&hba->tmf_tag_set);
9370 goto free_cmd_queue;
9371 hba->tmf_queue = blk_mq_init_queue(&hba->tmf_tag_set);
9372 if (IS_ERR(hba->tmf_queue)) {
9373 err = PTR_ERR(hba->tmf_queue);
9374 goto free_tmf_tag_set;
9377 /* Reset the attached device */
9378 ufshcd_device_reset(hba);
9380 ufshcd_init_crypto(hba);
9382 /* Host controller enable */
9383 err = ufshcd_hba_enable(hba);
9385 dev_err(hba->dev, "Host controller enable failed\n");
9386 ufshcd_print_evt_hist(hba);
9387 ufshcd_print_host_state(hba);
9388 goto free_tmf_queue;
9392 * Set the default power management level for runtime and system PM.
9393 * Default power saving mode is to keep UFS link in Hibern8 state
9394 * and UFS device in sleep state.
9396 hba->rpm_lvl = ufs_get_desired_pm_lvl_for_dev_link_state(
9398 UIC_LINK_HIBERN8_STATE);
9399 hba->spm_lvl = ufs_get_desired_pm_lvl_for_dev_link_state(
9401 UIC_LINK_HIBERN8_STATE);
9403 INIT_DELAYED_WORK(&hba->rpm_dev_flush_recheck_work,
9404 ufshcd_rpm_dev_flush_recheck_work);
9406 /* Set the default auto-hiberate idle timer value to 150 ms */
9407 if (ufshcd_is_auto_hibern8_supported(hba) && !hba->ahit) {
9408 hba->ahit = FIELD_PREP(UFSHCI_AHIBERN8_TIMER_MASK, 150) |
9409 FIELD_PREP(UFSHCI_AHIBERN8_SCALE_MASK, 3);
9412 /* Hold auto suspend until async scan completes */
9413 pm_runtime_get_sync(dev);
9414 atomic_set(&hba->scsi_block_reqs_cnt, 0);
9416 * We are assuming that device wasn't put in sleep/power-down
9417 * state exclusively during the boot stage before kernel.
9418 * This assumption helps avoid doing link startup twice during
9419 * ufshcd_probe_hba().
9421 ufshcd_set_ufs_dev_active(hba);
9423 async_schedule(ufshcd_async_scan, hba);
9424 ufs_sysfs_add_nodes(hba->dev);
9429 blk_cleanup_queue(hba->tmf_queue);
9431 blk_mq_free_tag_set(&hba->tmf_tag_set);
9433 blk_cleanup_queue(hba->cmd_queue);
9434 out_remove_scsi_host:
9435 scsi_remove_host(hba->host);
9437 ufshcd_exit_clk_scaling(hba);
9438 ufshcd_exit_clk_gating(hba);
9439 destroy_workqueue(hba->eh_wq);
9441 hba->is_irq_enabled = false;
9442 ufshcd_hba_exit(hba);
9446 EXPORT_SYMBOL_GPL(ufshcd_init);
9448 MODULE_AUTHOR("Santosh Yaragnavi <santosh.sy@samsung.com>");
9449 MODULE_AUTHOR("Vinayak Holikatti <h.vinayak@samsung.com>");
9450 MODULE_DESCRIPTION("Generic UFS host controller driver Core");
9451 MODULE_LICENSE("GPL");
9452 MODULE_VERSION(UFSHCD_DRIVER_VERSION);