1 // SPDX-License-Identifier: GPL-2.0-or-later
3 * Universal Flash Storage Host controller driver Core
4 * Copyright (C) 2011-2013 Samsung India Software Operations
5 * Copyright (c) 2013-2016, The Linux Foundation. All rights reserved.
8 * Santosh Yaraganavi <santosh.sy@samsung.com>
9 * Vinayak Holikatti <h.vinayak@samsung.com>
12 #include <linux/async.h>
13 #include <linux/devfreq.h>
14 #include <linux/nls.h>
16 #include <linux/bitfield.h>
17 #include <linux/blk-pm.h>
18 #include <linux/blkdev.h>
19 #include <scsi/scsi_driver.h>
21 #include "ufs_quirks.h"
23 #include "ufs-sysfs.h"
24 #include "ufs-debugfs.h"
26 #include "ufshcd-crypto.h"
27 #include <asm/unaligned.h>
30 #define CREATE_TRACE_POINTS
31 #include <trace/events/ufs.h>
33 #define UFSHCD_ENABLE_INTRS (UTP_TRANSFER_REQ_COMPL |\
36 /* UIC command timeout, unit: ms */
37 #define UIC_CMD_TIMEOUT 500
39 /* NOP OUT retries waiting for NOP IN response */
40 #define NOP_OUT_RETRIES 10
41 /* Timeout after 50 msecs if NOP OUT hangs without response */
42 #define NOP_OUT_TIMEOUT 50 /* msecs */
44 /* Query request retries */
45 #define QUERY_REQ_RETRIES 3
46 /* Query request timeout */
47 #define QUERY_REQ_TIMEOUT 1500 /* 1.5 seconds */
49 /* Task management command timeout */
50 #define TM_CMD_TIMEOUT 100 /* msecs */
52 /* maximum number of retries for a general UIC command */
53 #define UFS_UIC_COMMAND_RETRIES 3
55 /* maximum number of link-startup retries */
56 #define DME_LINKSTARTUP_RETRIES 3
58 /* Maximum retries for Hibern8 enter */
59 #define UIC_HIBERN8_ENTER_RETRIES 3
61 /* maximum number of reset retries before giving up */
62 #define MAX_HOST_RESET_RETRIES 5
64 /* Expose the flag value from utp_upiu_query.value */
65 #define MASK_QUERY_UPIU_FLAG_LOC 0xFF
67 /* Interrupt aggregation default timeout, unit: 40us */
68 #define INT_AGGR_DEF_TO 0x02
70 /* default delay of autosuspend: 2000 ms */
71 #define RPM_AUTOSUSPEND_DELAY_MS 2000
73 /* Default delay of RPM device flush delayed work */
74 #define RPM_DEV_FLUSH_RECHECK_WORK_DELAY_MS 5000
76 /* Default value of wait time before gating device ref clock */
77 #define UFSHCD_REF_CLK_GATING_WAIT_US 0xFF /* microsecs */
79 /* Polling time to wait for fDeviceInit */
80 #define FDEVICEINIT_COMPL_TIMEOUT 1500 /* millisecs */
82 #define wlun_dev_to_hba(dv) shost_priv(to_scsi_device(dv)->host)
84 #define ufshcd_toggle_vreg(_dev, _vreg, _on) \
88 _ret = ufshcd_enable_vreg(_dev, _vreg); \
90 _ret = ufshcd_disable_vreg(_dev, _vreg); \
94 #define ufshcd_hex_dump(prefix_str, buf, len) do { \
95 size_t __len = (len); \
96 print_hex_dump(KERN_ERR, prefix_str, \
97 __len > 4 ? DUMP_PREFIX_OFFSET : DUMP_PREFIX_NONE,\
98 16, 4, buf, __len, false); \
101 int ufshcd_dump_regs(struct ufs_hba *hba, size_t offset, size_t len,
107 if (offset % 4 != 0 || len % 4 != 0) /* keep readl happy */
110 regs = kzalloc(len, GFP_ATOMIC);
114 for (pos = 0; pos < len; pos += 4)
115 regs[pos / 4] = ufshcd_readl(hba, offset + pos);
117 ufshcd_hex_dump(prefix, regs, len);
122 EXPORT_SYMBOL_GPL(ufshcd_dump_regs);
125 UFSHCD_MAX_CHANNEL = 0,
127 UFSHCD_CMD_PER_LUN = 32,
128 UFSHCD_CAN_QUEUE = 32,
135 UFSHCD_STATE_OPERATIONAL,
136 UFSHCD_STATE_EH_SCHEDULED_FATAL,
137 UFSHCD_STATE_EH_SCHEDULED_NON_FATAL,
140 /* UFSHCD error handling flags */
142 UFSHCD_EH_IN_PROGRESS = (1 << 0),
145 /* UFSHCD UIC layer error flags */
147 UFSHCD_UIC_DL_PA_INIT_ERROR = (1 << 0), /* Data link layer error */
148 UFSHCD_UIC_DL_NAC_RECEIVED_ERROR = (1 << 1), /* Data link layer error */
149 UFSHCD_UIC_DL_TCx_REPLAY_ERROR = (1 << 2), /* Data link layer error */
150 UFSHCD_UIC_NL_ERROR = (1 << 3), /* Network layer error */
151 UFSHCD_UIC_TL_ERROR = (1 << 4), /* Transport Layer error */
152 UFSHCD_UIC_DME_ERROR = (1 << 5), /* DME error */
153 UFSHCD_UIC_PA_GENERIC_ERROR = (1 << 6), /* Generic PA error */
156 #define ufshcd_set_eh_in_progress(h) \
157 ((h)->eh_flags |= UFSHCD_EH_IN_PROGRESS)
158 #define ufshcd_eh_in_progress(h) \
159 ((h)->eh_flags & UFSHCD_EH_IN_PROGRESS)
160 #define ufshcd_clear_eh_in_progress(h) \
161 ((h)->eh_flags &= ~UFSHCD_EH_IN_PROGRESS)
163 struct ufs_pm_lvl_states ufs_pm_lvl_states[] = {
164 [UFS_PM_LVL_0] = {UFS_ACTIVE_PWR_MODE, UIC_LINK_ACTIVE_STATE},
165 [UFS_PM_LVL_1] = {UFS_ACTIVE_PWR_MODE, UIC_LINK_HIBERN8_STATE},
166 [UFS_PM_LVL_2] = {UFS_SLEEP_PWR_MODE, UIC_LINK_ACTIVE_STATE},
167 [UFS_PM_LVL_3] = {UFS_SLEEP_PWR_MODE, UIC_LINK_HIBERN8_STATE},
168 [UFS_PM_LVL_4] = {UFS_POWERDOWN_PWR_MODE, UIC_LINK_HIBERN8_STATE},
169 [UFS_PM_LVL_5] = {UFS_POWERDOWN_PWR_MODE, UIC_LINK_OFF_STATE},
171 * For DeepSleep, the link is first put in hibern8 and then off.
172 * Leaving the link in hibern8 is not supported.
174 [UFS_PM_LVL_6] = {UFS_DEEPSLEEP_PWR_MODE, UIC_LINK_OFF_STATE},
177 static inline enum ufs_dev_pwr_mode
178 ufs_get_pm_lvl_to_dev_pwr_mode(enum ufs_pm_level lvl)
180 return ufs_pm_lvl_states[lvl].dev_state;
183 static inline enum uic_link_state
184 ufs_get_pm_lvl_to_link_pwr_state(enum ufs_pm_level lvl)
186 return ufs_pm_lvl_states[lvl].link_state;
189 static inline enum ufs_pm_level
190 ufs_get_desired_pm_lvl_for_dev_link_state(enum ufs_dev_pwr_mode dev_state,
191 enum uic_link_state link_state)
193 enum ufs_pm_level lvl;
195 for (lvl = UFS_PM_LVL_0; lvl < UFS_PM_LVL_MAX; lvl++) {
196 if ((ufs_pm_lvl_states[lvl].dev_state == dev_state) &&
197 (ufs_pm_lvl_states[lvl].link_state == link_state))
201 /* if no match found, return the level 0 */
205 static struct ufs_dev_fix ufs_fixups[] = {
206 /* UFS cards deviations table */
207 UFS_FIX(UFS_VENDOR_MICRON, UFS_ANY_MODEL,
208 UFS_DEVICE_QUIRK_DELAY_BEFORE_LPM),
209 UFS_FIX(UFS_VENDOR_SAMSUNG, UFS_ANY_MODEL,
210 UFS_DEVICE_QUIRK_DELAY_BEFORE_LPM |
211 UFS_DEVICE_QUIRK_HOST_PA_TACTIVATE |
212 UFS_DEVICE_QUIRK_RECOVERY_FROM_DL_NAC_ERRORS),
213 UFS_FIX(UFS_VENDOR_SKHYNIX, UFS_ANY_MODEL,
214 UFS_DEVICE_QUIRK_HOST_PA_SAVECONFIGTIME),
215 UFS_FIX(UFS_VENDOR_SKHYNIX, "hB8aL1" /*H28U62301AMR*/,
216 UFS_DEVICE_QUIRK_HOST_VS_DEBUGSAVECONFIGTIME),
217 UFS_FIX(UFS_VENDOR_TOSHIBA, UFS_ANY_MODEL,
218 UFS_DEVICE_QUIRK_DELAY_BEFORE_LPM),
219 UFS_FIX(UFS_VENDOR_TOSHIBA, "THGLF2G9C8KBADG",
220 UFS_DEVICE_QUIRK_PA_TACTIVATE),
221 UFS_FIX(UFS_VENDOR_TOSHIBA, "THGLF2G9D8KBADG",
222 UFS_DEVICE_QUIRK_PA_TACTIVATE),
226 static irqreturn_t ufshcd_tmc_handler(struct ufs_hba *hba);
227 static void ufshcd_async_scan(void *data, async_cookie_t cookie);
228 static int ufshcd_reset_and_restore(struct ufs_hba *hba);
229 static int ufshcd_eh_host_reset_handler(struct scsi_cmnd *cmd);
230 static int ufshcd_clear_tm_cmd(struct ufs_hba *hba, int tag);
231 static void ufshcd_hba_exit(struct ufs_hba *hba);
232 static int ufshcd_clear_ua_wluns(struct ufs_hba *hba);
233 static int ufshcd_probe_hba(struct ufs_hba *hba, bool async);
234 static int ufshcd_setup_clocks(struct ufs_hba *hba, bool on);
235 static int ufshcd_uic_hibern8_enter(struct ufs_hba *hba);
236 static inline void ufshcd_add_delay_before_dme_cmd(struct ufs_hba *hba);
237 static int ufshcd_host_reset_and_restore(struct ufs_hba *hba);
238 static void ufshcd_resume_clkscaling(struct ufs_hba *hba);
239 static void ufshcd_suspend_clkscaling(struct ufs_hba *hba);
240 static void __ufshcd_suspend_clkscaling(struct ufs_hba *hba);
241 static int ufshcd_scale_clks(struct ufs_hba *hba, bool scale_up);
242 static irqreturn_t ufshcd_intr(int irq, void *__hba);
243 static int ufshcd_change_power_mode(struct ufs_hba *hba,
244 struct ufs_pa_layer_attr *pwr_mode);
245 static void ufshcd_schedule_eh_work(struct ufs_hba *hba);
246 static int ufshcd_setup_hba_vreg(struct ufs_hba *hba, bool on);
247 static int ufshcd_setup_vreg(struct ufs_hba *hba, bool on);
248 static inline int ufshcd_config_vreg_hpm(struct ufs_hba *hba,
249 struct ufs_vreg *vreg);
250 static int ufshcd_try_to_abort_task(struct ufs_hba *hba, int tag);
251 static void ufshcd_wb_toggle_flush_during_h8(struct ufs_hba *hba, bool set);
252 static inline void ufshcd_wb_toggle_flush(struct ufs_hba *hba, bool enable);
253 static void ufshcd_hba_vreg_set_lpm(struct ufs_hba *hba);
254 static void ufshcd_hba_vreg_set_hpm(struct ufs_hba *hba);
256 static inline bool ufshcd_valid_tag(struct ufs_hba *hba, int tag)
258 return tag >= 0 && tag < hba->nutrs;
261 static inline void ufshcd_enable_irq(struct ufs_hba *hba)
263 if (!hba->is_irq_enabled) {
264 enable_irq(hba->irq);
265 hba->is_irq_enabled = true;
269 static inline void ufshcd_disable_irq(struct ufs_hba *hba)
271 if (hba->is_irq_enabled) {
272 disable_irq(hba->irq);
273 hba->is_irq_enabled = false;
277 static inline void ufshcd_wb_config(struct ufs_hba *hba)
279 if (!ufshcd_is_wb_allowed(hba))
282 ufshcd_wb_toggle(hba, true);
284 ufshcd_wb_toggle_flush_during_h8(hba, true);
285 if (!(hba->quirks & UFSHCI_QUIRK_SKIP_MANUAL_WB_FLUSH_CTRL))
286 ufshcd_wb_toggle_flush(hba, true);
289 static void ufshcd_scsi_unblock_requests(struct ufs_hba *hba)
291 if (atomic_dec_and_test(&hba->scsi_block_reqs_cnt))
292 scsi_unblock_requests(hba->host);
295 static void ufshcd_scsi_block_requests(struct ufs_hba *hba)
297 if (atomic_inc_return(&hba->scsi_block_reqs_cnt) == 1)
298 scsi_block_requests(hba->host);
301 static void ufshcd_add_cmd_upiu_trace(struct ufs_hba *hba, unsigned int tag,
302 enum ufs_trace_str_t str_t)
304 struct utp_upiu_req *rq = hba->lrb[tag].ucd_req_ptr;
305 struct utp_upiu_header *header;
307 if (!trace_ufshcd_upiu_enabled())
310 if (str_t == UFS_CMD_SEND)
311 header = &rq->header;
313 header = &hba->lrb[tag].ucd_rsp_ptr->header;
315 trace_ufshcd_upiu(dev_name(hba->dev), str_t, header, &rq->sc.cdb,
319 static void ufshcd_add_query_upiu_trace(struct ufs_hba *hba,
320 enum ufs_trace_str_t str_t,
321 struct utp_upiu_req *rq_rsp)
323 if (!trace_ufshcd_upiu_enabled())
326 trace_ufshcd_upiu(dev_name(hba->dev), str_t, &rq_rsp->header,
327 &rq_rsp->qr, UFS_TSF_OSF);
330 static void ufshcd_add_tm_upiu_trace(struct ufs_hba *hba, unsigned int tag,
331 enum ufs_trace_str_t str_t)
333 int off = (int)tag - hba->nutrs;
334 struct utp_task_req_desc *descp = &hba->utmrdl_base_addr[off];
336 if (!trace_ufshcd_upiu_enabled())
339 if (str_t == UFS_TM_SEND)
340 trace_ufshcd_upiu(dev_name(hba->dev), str_t,
341 &descp->upiu_req.req_header,
342 &descp->upiu_req.input_param1,
345 trace_ufshcd_upiu(dev_name(hba->dev), str_t,
346 &descp->upiu_rsp.rsp_header,
347 &descp->upiu_rsp.output_param1,
351 static void ufshcd_add_uic_command_trace(struct ufs_hba *hba,
352 struct uic_command *ucmd,
353 enum ufs_trace_str_t str_t)
357 if (!trace_ufshcd_uic_command_enabled())
360 if (str_t == UFS_CMD_SEND)
363 cmd = ufshcd_readl(hba, REG_UIC_COMMAND);
365 trace_ufshcd_uic_command(dev_name(hba->dev), str_t, cmd,
366 ufshcd_readl(hba, REG_UIC_COMMAND_ARG_1),
367 ufshcd_readl(hba, REG_UIC_COMMAND_ARG_2),
368 ufshcd_readl(hba, REG_UIC_COMMAND_ARG_3));
371 static void ufshcd_add_command_trace(struct ufs_hba *hba, unsigned int tag,
372 enum ufs_trace_str_t str_t)
375 u8 opcode = 0, group_id = 0;
377 struct ufshcd_lrb *lrbp = &hba->lrb[tag];
378 struct scsi_cmnd *cmd = lrbp->cmd;
379 int transfer_len = -1;
384 if (!trace_ufshcd_command_enabled()) {
385 /* trace UPIU W/O tracing command */
386 ufshcd_add_cmd_upiu_trace(hba, tag, str_t);
390 /* trace UPIU also */
391 ufshcd_add_cmd_upiu_trace(hba, tag, str_t);
392 opcode = cmd->cmnd[0];
393 lba = sectors_to_logical(cmd->device, blk_rq_pos(cmd->request));
395 if (opcode == READ_10 || opcode == WRITE_10) {
397 * Currently we only fully trace read(10) and write(10) commands
400 be32_to_cpu(lrbp->ucd_req_ptr->sc.exp_data_transfer_len);
401 if (opcode == WRITE_10)
402 group_id = lrbp->cmd->cmnd[6];
403 } else if (opcode == UNMAP) {
405 * The number of Bytes to be unmapped beginning with the lba.
407 transfer_len = blk_rq_bytes(cmd->request);
410 intr = ufshcd_readl(hba, REG_INTERRUPT_STATUS);
411 doorbell = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
412 trace_ufshcd_command(dev_name(hba->dev), str_t, tag,
413 doorbell, transfer_len, intr, lba, opcode, group_id);
416 static void ufshcd_print_clk_freqs(struct ufs_hba *hba)
418 struct ufs_clk_info *clki;
419 struct list_head *head = &hba->clk_list_head;
421 if (list_empty(head))
424 list_for_each_entry(clki, head, list) {
425 if (!IS_ERR_OR_NULL(clki->clk) && clki->min_freq &&
427 dev_err(hba->dev, "clk: %s, rate: %u\n",
428 clki->name, clki->curr_freq);
432 static void ufshcd_print_evt(struct ufs_hba *hba, u32 id,
437 struct ufs_event_hist *e;
439 if (id >= UFS_EVT_CNT)
442 e = &hba->ufs_stats.event[id];
444 for (i = 0; i < UFS_EVENT_HIST_LENGTH; i++) {
445 int p = (i + e->pos) % UFS_EVENT_HIST_LENGTH;
447 if (e->tstamp[p] == 0)
449 dev_err(hba->dev, "%s[%d] = 0x%x at %lld us\n", err_name, p,
450 e->val[p], ktime_to_us(e->tstamp[p]));
455 dev_err(hba->dev, "No record of %s\n", err_name);
457 dev_err(hba->dev, "%s: total cnt=%llu\n", err_name, e->cnt);
460 static void ufshcd_print_evt_hist(struct ufs_hba *hba)
462 ufshcd_dump_regs(hba, 0, UFSHCI_REG_SPACE_SIZE, "host_regs: ");
464 ufshcd_print_evt(hba, UFS_EVT_PA_ERR, "pa_err");
465 ufshcd_print_evt(hba, UFS_EVT_DL_ERR, "dl_err");
466 ufshcd_print_evt(hba, UFS_EVT_NL_ERR, "nl_err");
467 ufshcd_print_evt(hba, UFS_EVT_TL_ERR, "tl_err");
468 ufshcd_print_evt(hba, UFS_EVT_DME_ERR, "dme_err");
469 ufshcd_print_evt(hba, UFS_EVT_AUTO_HIBERN8_ERR,
471 ufshcd_print_evt(hba, UFS_EVT_FATAL_ERR, "fatal_err");
472 ufshcd_print_evt(hba, UFS_EVT_LINK_STARTUP_FAIL,
473 "link_startup_fail");
474 ufshcd_print_evt(hba, UFS_EVT_RESUME_ERR, "resume_fail");
475 ufshcd_print_evt(hba, UFS_EVT_SUSPEND_ERR,
477 ufshcd_print_evt(hba, UFS_EVT_DEV_RESET, "dev_reset");
478 ufshcd_print_evt(hba, UFS_EVT_HOST_RESET, "host_reset");
479 ufshcd_print_evt(hba, UFS_EVT_ABORT, "task_abort");
481 ufshcd_vops_dbg_register_dump(hba);
485 void ufshcd_print_trs(struct ufs_hba *hba, unsigned long bitmap, bool pr_prdt)
487 struct ufshcd_lrb *lrbp;
491 for_each_set_bit(tag, &bitmap, hba->nutrs) {
492 lrbp = &hba->lrb[tag];
494 dev_err(hba->dev, "UPIU[%d] - issue time %lld us\n",
495 tag, ktime_to_us(lrbp->issue_time_stamp));
496 dev_err(hba->dev, "UPIU[%d] - complete time %lld us\n",
497 tag, ktime_to_us(lrbp->compl_time_stamp));
499 "UPIU[%d] - Transfer Request Descriptor phys@0x%llx\n",
500 tag, (u64)lrbp->utrd_dma_addr);
502 ufshcd_hex_dump("UPIU TRD: ", lrbp->utr_descriptor_ptr,
503 sizeof(struct utp_transfer_req_desc));
504 dev_err(hba->dev, "UPIU[%d] - Request UPIU phys@0x%llx\n", tag,
505 (u64)lrbp->ucd_req_dma_addr);
506 ufshcd_hex_dump("UPIU REQ: ", lrbp->ucd_req_ptr,
507 sizeof(struct utp_upiu_req));
508 dev_err(hba->dev, "UPIU[%d] - Response UPIU phys@0x%llx\n", tag,
509 (u64)lrbp->ucd_rsp_dma_addr);
510 ufshcd_hex_dump("UPIU RSP: ", lrbp->ucd_rsp_ptr,
511 sizeof(struct utp_upiu_rsp));
513 prdt_length = le16_to_cpu(
514 lrbp->utr_descriptor_ptr->prd_table_length);
515 if (hba->quirks & UFSHCD_QUIRK_PRDT_BYTE_GRAN)
516 prdt_length /= sizeof(struct ufshcd_sg_entry);
519 "UPIU[%d] - PRDT - %d entries phys@0x%llx\n",
521 (u64)lrbp->ucd_prdt_dma_addr);
524 ufshcd_hex_dump("UPIU PRDT: ", lrbp->ucd_prdt_ptr,
525 sizeof(struct ufshcd_sg_entry) * prdt_length);
529 static void ufshcd_print_tmrs(struct ufs_hba *hba, unsigned long bitmap)
533 for_each_set_bit(tag, &bitmap, hba->nutmrs) {
534 struct utp_task_req_desc *tmrdp = &hba->utmrdl_base_addr[tag];
536 dev_err(hba->dev, "TM[%d] - Task Management Header\n", tag);
537 ufshcd_hex_dump("", tmrdp, sizeof(*tmrdp));
541 static void ufshcd_print_host_state(struct ufs_hba *hba)
543 struct scsi_device *sdev_ufs = hba->sdev_ufs_device;
545 dev_err(hba->dev, "UFS Host state=%d\n", hba->ufshcd_state);
546 dev_err(hba->dev, "outstanding reqs=0x%lx tasks=0x%lx\n",
547 hba->outstanding_reqs, hba->outstanding_tasks);
548 dev_err(hba->dev, "saved_err=0x%x, saved_uic_err=0x%x\n",
549 hba->saved_err, hba->saved_uic_err);
550 dev_err(hba->dev, "Device power mode=%d, UIC link state=%d\n",
551 hba->curr_dev_pwr_mode, hba->uic_link_state);
552 dev_err(hba->dev, "PM in progress=%d, sys. suspended=%d\n",
553 hba->pm_op_in_progress, hba->is_sys_suspended);
554 dev_err(hba->dev, "Auto BKOPS=%d, Host self-block=%d\n",
555 hba->auto_bkops_enabled, hba->host->host_self_blocked);
556 dev_err(hba->dev, "Clk gate=%d\n", hba->clk_gating.state);
558 "last_hibern8_exit_tstamp at %lld us, hibern8_exit_cnt=%d\n",
559 ktime_to_us(hba->ufs_stats.last_hibern8_exit_tstamp),
560 hba->ufs_stats.hibern8_exit_cnt);
561 dev_err(hba->dev, "last intr at %lld us, last intr status=0x%x\n",
562 ktime_to_us(hba->ufs_stats.last_intr_ts),
563 hba->ufs_stats.last_intr_status);
564 dev_err(hba->dev, "error handling flags=0x%x, req. abort count=%d\n",
565 hba->eh_flags, hba->req_abort_count);
566 dev_err(hba->dev, "hba->ufs_version=0x%x, Host capabilities=0x%x, caps=0x%x\n",
567 hba->ufs_version, hba->capabilities, hba->caps);
568 dev_err(hba->dev, "quirks=0x%x, dev. quirks=0x%x\n", hba->quirks,
571 dev_err(hba->dev, "UFS dev info: %.8s %.16s rev %.4s\n",
572 sdev_ufs->vendor, sdev_ufs->model, sdev_ufs->rev);
574 ufshcd_print_clk_freqs(hba);
578 * ufshcd_print_pwr_info - print power params as saved in hba
580 * @hba: per-adapter instance
582 static void ufshcd_print_pwr_info(struct ufs_hba *hba)
584 static const char * const names[] = {
594 dev_err(hba->dev, "%s:[RX, TX]: gear=[%d, %d], lane[%d, %d], pwr[%s, %s], rate = %d\n",
596 hba->pwr_info.gear_rx, hba->pwr_info.gear_tx,
597 hba->pwr_info.lane_rx, hba->pwr_info.lane_tx,
598 names[hba->pwr_info.pwr_rx],
599 names[hba->pwr_info.pwr_tx],
600 hba->pwr_info.hs_rate);
603 static void ufshcd_device_reset(struct ufs_hba *hba)
607 err = ufshcd_vops_device_reset(hba);
610 ufshcd_set_ufs_dev_active(hba);
611 if (ufshcd_is_wb_allowed(hba)) {
612 hba->dev_info.wb_enabled = false;
613 hba->dev_info.wb_buf_flush_enabled = false;
616 if (err != -EOPNOTSUPP)
617 ufshcd_update_evt_hist(hba, UFS_EVT_DEV_RESET, err);
620 void ufshcd_delay_us(unsigned long us, unsigned long tolerance)
628 usleep_range(us, us + tolerance);
630 EXPORT_SYMBOL_GPL(ufshcd_delay_us);
633 * ufshcd_wait_for_register - wait for register value to change
634 * @hba: per-adapter interface
635 * @reg: mmio register offset
636 * @mask: mask to apply to the read register value
637 * @val: value to wait for
638 * @interval_us: polling interval in microseconds
639 * @timeout_ms: timeout in milliseconds
642 * -ETIMEDOUT on error, zero on success.
644 int ufshcd_wait_for_register(struct ufs_hba *hba, u32 reg, u32 mask,
645 u32 val, unsigned long interval_us,
646 unsigned long timeout_ms)
649 unsigned long timeout = jiffies + msecs_to_jiffies(timeout_ms);
651 /* ignore bits that we don't intend to wait on */
654 while ((ufshcd_readl(hba, reg) & mask) != val) {
655 usleep_range(interval_us, interval_us + 50);
656 if (time_after(jiffies, timeout)) {
657 if ((ufshcd_readl(hba, reg) & mask) != val)
667 * ufshcd_get_intr_mask - Get the interrupt bit mask
668 * @hba: Pointer to adapter instance
670 * Returns interrupt bit mask per version
672 static inline u32 ufshcd_get_intr_mask(struct ufs_hba *hba)
674 if (hba->ufs_version == ufshci_version(1, 0))
675 return INTERRUPT_MASK_ALL_VER_10;
676 if (hba->ufs_version <= ufshci_version(2, 0))
677 return INTERRUPT_MASK_ALL_VER_11;
679 return INTERRUPT_MASK_ALL_VER_21;
683 * ufshcd_get_ufs_version - Get the UFS version supported by the HBA
684 * @hba: Pointer to adapter instance
686 * Returns UFSHCI version supported by the controller
688 static inline u32 ufshcd_get_ufs_version(struct ufs_hba *hba)
692 if (hba->quirks & UFSHCD_QUIRK_BROKEN_UFS_HCI_VERSION)
693 ufshci_ver = ufshcd_vops_get_ufs_hci_version(hba);
695 ufshci_ver = ufshcd_readl(hba, REG_UFS_VERSION);
698 * UFSHCI v1.x uses a different version scheme, in order
699 * to allow the use of comparisons with the ufshci_version
700 * function, we convert it to the same scheme as ufs 2.0+.
702 if (ufshci_ver & 0x00010000)
703 return ufshci_version(1, ufshci_ver & 0x00000100);
709 * ufshcd_is_device_present - Check if any device connected to
710 * the host controller
711 * @hba: pointer to adapter instance
713 * Returns true if device present, false if no device detected
715 static inline bool ufshcd_is_device_present(struct ufs_hba *hba)
717 return (ufshcd_readl(hba, REG_CONTROLLER_STATUS) &
718 DEVICE_PRESENT) ? true : false;
722 * ufshcd_get_tr_ocs - Get the UTRD Overall Command Status
723 * @lrbp: pointer to local command reference block
725 * This function is used to get the OCS field from UTRD
726 * Returns the OCS field in the UTRD
728 static inline int ufshcd_get_tr_ocs(struct ufshcd_lrb *lrbp)
730 return le32_to_cpu(lrbp->utr_descriptor_ptr->header.dword_2) & MASK_OCS;
734 * ufshcd_utrl_clear - Clear a bit in UTRLCLR register
735 * @hba: per adapter instance
736 * @pos: position of the bit to be cleared
738 static inline void ufshcd_utrl_clear(struct ufs_hba *hba, u32 pos)
740 if (hba->quirks & UFSHCI_QUIRK_BROKEN_REQ_LIST_CLR)
741 ufshcd_writel(hba, (1 << pos), REG_UTP_TRANSFER_REQ_LIST_CLEAR);
743 ufshcd_writel(hba, ~(1 << pos),
744 REG_UTP_TRANSFER_REQ_LIST_CLEAR);
748 * ufshcd_utmrl_clear - Clear a bit in UTRMLCLR register
749 * @hba: per adapter instance
750 * @pos: position of the bit to be cleared
752 static inline void ufshcd_utmrl_clear(struct ufs_hba *hba, u32 pos)
754 if (hba->quirks & UFSHCI_QUIRK_BROKEN_REQ_LIST_CLR)
755 ufshcd_writel(hba, (1 << pos), REG_UTP_TASK_REQ_LIST_CLEAR);
757 ufshcd_writel(hba, ~(1 << pos), REG_UTP_TASK_REQ_LIST_CLEAR);
761 * ufshcd_outstanding_req_clear - Clear a bit in outstanding request field
762 * @hba: per adapter instance
763 * @tag: position of the bit to be cleared
765 static inline void ufshcd_outstanding_req_clear(struct ufs_hba *hba, int tag)
767 clear_bit(tag, &hba->outstanding_reqs);
771 * ufshcd_get_lists_status - Check UCRDY, UTRLRDY and UTMRLRDY
772 * @reg: Register value of host controller status
774 * Returns integer, 0 on Success and positive value if failed
776 static inline int ufshcd_get_lists_status(u32 reg)
778 return !((reg & UFSHCD_STATUS_READY) == UFSHCD_STATUS_READY);
782 * ufshcd_get_uic_cmd_result - Get the UIC command result
783 * @hba: Pointer to adapter instance
785 * This function gets the result of UIC command completion
786 * Returns 0 on success, non zero value on error
788 static inline int ufshcd_get_uic_cmd_result(struct ufs_hba *hba)
790 return ufshcd_readl(hba, REG_UIC_COMMAND_ARG_2) &
791 MASK_UIC_COMMAND_RESULT;
795 * ufshcd_get_dme_attr_val - Get the value of attribute returned by UIC command
796 * @hba: Pointer to adapter instance
798 * This function gets UIC command argument3
799 * Returns 0 on success, non zero value on error
801 static inline u32 ufshcd_get_dme_attr_val(struct ufs_hba *hba)
803 return ufshcd_readl(hba, REG_UIC_COMMAND_ARG_3);
807 * ufshcd_get_req_rsp - returns the TR response transaction type
808 * @ucd_rsp_ptr: pointer to response UPIU
811 ufshcd_get_req_rsp(struct utp_upiu_rsp *ucd_rsp_ptr)
813 return be32_to_cpu(ucd_rsp_ptr->header.dword_0) >> 24;
817 * ufshcd_get_rsp_upiu_result - Get the result from response UPIU
818 * @ucd_rsp_ptr: pointer to response UPIU
820 * This function gets the response status and scsi_status from response UPIU
821 * Returns the response result code.
824 ufshcd_get_rsp_upiu_result(struct utp_upiu_rsp *ucd_rsp_ptr)
826 return be32_to_cpu(ucd_rsp_ptr->header.dword_1) & MASK_RSP_UPIU_RESULT;
830 * ufshcd_get_rsp_upiu_data_seg_len - Get the data segment length
832 * @ucd_rsp_ptr: pointer to response UPIU
834 * Return the data segment length.
836 static inline unsigned int
837 ufshcd_get_rsp_upiu_data_seg_len(struct utp_upiu_rsp *ucd_rsp_ptr)
839 return be32_to_cpu(ucd_rsp_ptr->header.dword_2) &
840 MASK_RSP_UPIU_DATA_SEG_LEN;
844 * ufshcd_is_exception_event - Check if the device raised an exception event
845 * @ucd_rsp_ptr: pointer to response UPIU
847 * The function checks if the device raised an exception event indicated in
848 * the Device Information field of response UPIU.
850 * Returns true if exception is raised, false otherwise.
852 static inline bool ufshcd_is_exception_event(struct utp_upiu_rsp *ucd_rsp_ptr)
854 return be32_to_cpu(ucd_rsp_ptr->header.dword_2) &
855 MASK_RSP_EXCEPTION_EVENT ? true : false;
859 * ufshcd_reset_intr_aggr - Reset interrupt aggregation values.
860 * @hba: per adapter instance
863 ufshcd_reset_intr_aggr(struct ufs_hba *hba)
865 ufshcd_writel(hba, INT_AGGR_ENABLE |
866 INT_AGGR_COUNTER_AND_TIMER_RESET,
867 REG_UTP_TRANSFER_REQ_INT_AGG_CONTROL);
871 * ufshcd_config_intr_aggr - Configure interrupt aggregation values.
872 * @hba: per adapter instance
873 * @cnt: Interrupt aggregation counter threshold
874 * @tmout: Interrupt aggregation timeout value
877 ufshcd_config_intr_aggr(struct ufs_hba *hba, u8 cnt, u8 tmout)
879 ufshcd_writel(hba, INT_AGGR_ENABLE | INT_AGGR_PARAM_WRITE |
880 INT_AGGR_COUNTER_THLD_VAL(cnt) |
881 INT_AGGR_TIMEOUT_VAL(tmout),
882 REG_UTP_TRANSFER_REQ_INT_AGG_CONTROL);
886 * ufshcd_disable_intr_aggr - Disables interrupt aggregation.
887 * @hba: per adapter instance
889 static inline void ufshcd_disable_intr_aggr(struct ufs_hba *hba)
891 ufshcd_writel(hba, 0, REG_UTP_TRANSFER_REQ_INT_AGG_CONTROL);
895 * ufshcd_enable_run_stop_reg - Enable run-stop registers,
896 * When run-stop registers are set to 1, it indicates the
897 * host controller that it can process the requests
898 * @hba: per adapter instance
900 static void ufshcd_enable_run_stop_reg(struct ufs_hba *hba)
902 ufshcd_writel(hba, UTP_TASK_REQ_LIST_RUN_STOP_BIT,
903 REG_UTP_TASK_REQ_LIST_RUN_STOP);
904 ufshcd_writel(hba, UTP_TRANSFER_REQ_LIST_RUN_STOP_BIT,
905 REG_UTP_TRANSFER_REQ_LIST_RUN_STOP);
909 * ufshcd_hba_start - Start controller initialization sequence
910 * @hba: per adapter instance
912 static inline void ufshcd_hba_start(struct ufs_hba *hba)
914 u32 val = CONTROLLER_ENABLE;
916 if (ufshcd_crypto_enable(hba))
917 val |= CRYPTO_GENERAL_ENABLE;
919 ufshcd_writel(hba, val, REG_CONTROLLER_ENABLE);
923 * ufshcd_is_hba_active - Get controller state
924 * @hba: per adapter instance
926 * Returns false if controller is active, true otherwise
928 static inline bool ufshcd_is_hba_active(struct ufs_hba *hba)
930 return (ufshcd_readl(hba, REG_CONTROLLER_ENABLE) & CONTROLLER_ENABLE)
934 u32 ufshcd_get_local_unipro_ver(struct ufs_hba *hba)
936 /* HCI version 1.0 and 1.1 supports UniPro 1.41 */
937 if (hba->ufs_version <= ufshci_version(1, 1))
938 return UFS_UNIPRO_VER_1_41;
940 return UFS_UNIPRO_VER_1_6;
942 EXPORT_SYMBOL(ufshcd_get_local_unipro_ver);
944 static bool ufshcd_is_unipro_pa_params_tuning_req(struct ufs_hba *hba)
947 * If both host and device support UniPro ver1.6 or later, PA layer
948 * parameters tuning happens during link startup itself.
950 * We can manually tune PA layer parameters if either host or device
951 * doesn't support UniPro ver 1.6 or later. But to keep manual tuning
952 * logic simple, we will only do manual tuning if local unipro version
953 * doesn't support ver1.6 or later.
955 if (ufshcd_get_local_unipro_ver(hba) < UFS_UNIPRO_VER_1_6)
962 * ufshcd_set_clk_freq - set UFS controller clock frequencies
963 * @hba: per adapter instance
964 * @scale_up: If True, set max possible frequency othewise set low frequency
966 * Returns 0 if successful
967 * Returns < 0 for any other errors
969 static int ufshcd_set_clk_freq(struct ufs_hba *hba, bool scale_up)
972 struct ufs_clk_info *clki;
973 struct list_head *head = &hba->clk_list_head;
975 if (list_empty(head))
978 list_for_each_entry(clki, head, list) {
979 if (!IS_ERR_OR_NULL(clki->clk)) {
980 if (scale_up && clki->max_freq) {
981 if (clki->curr_freq == clki->max_freq)
984 ret = clk_set_rate(clki->clk, clki->max_freq);
986 dev_err(hba->dev, "%s: %s clk set rate(%dHz) failed, %d\n",
987 __func__, clki->name,
988 clki->max_freq, ret);
991 trace_ufshcd_clk_scaling(dev_name(hba->dev),
992 "scaled up", clki->name,
996 clki->curr_freq = clki->max_freq;
998 } else if (!scale_up && clki->min_freq) {
999 if (clki->curr_freq == clki->min_freq)
1002 ret = clk_set_rate(clki->clk, clki->min_freq);
1004 dev_err(hba->dev, "%s: %s clk set rate(%dHz) failed, %d\n",
1005 __func__, clki->name,
1006 clki->min_freq, ret);
1009 trace_ufshcd_clk_scaling(dev_name(hba->dev),
1010 "scaled down", clki->name,
1013 clki->curr_freq = clki->min_freq;
1016 dev_dbg(hba->dev, "%s: clk: %s, rate: %lu\n", __func__,
1017 clki->name, clk_get_rate(clki->clk));
1025 * ufshcd_scale_clks - scale up or scale down UFS controller clocks
1026 * @hba: per adapter instance
1027 * @scale_up: True if scaling up and false if scaling down
1029 * Returns 0 if successful
1030 * Returns < 0 for any other errors
1032 static int ufshcd_scale_clks(struct ufs_hba *hba, bool scale_up)
1035 ktime_t start = ktime_get();
1037 ret = ufshcd_vops_clk_scale_notify(hba, scale_up, PRE_CHANGE);
1041 ret = ufshcd_set_clk_freq(hba, scale_up);
1045 ret = ufshcd_vops_clk_scale_notify(hba, scale_up, POST_CHANGE);
1047 ufshcd_set_clk_freq(hba, !scale_up);
1050 trace_ufshcd_profile_clk_scaling(dev_name(hba->dev),
1051 (scale_up ? "up" : "down"),
1052 ktime_to_us(ktime_sub(ktime_get(), start)), ret);
1057 * ufshcd_is_devfreq_scaling_required - check if scaling is required or not
1058 * @hba: per adapter instance
1059 * @scale_up: True if scaling up and false if scaling down
1061 * Returns true if scaling is required, false otherwise.
1063 static bool ufshcd_is_devfreq_scaling_required(struct ufs_hba *hba,
1066 struct ufs_clk_info *clki;
1067 struct list_head *head = &hba->clk_list_head;
1069 if (list_empty(head))
1072 list_for_each_entry(clki, head, list) {
1073 if (!IS_ERR_OR_NULL(clki->clk)) {
1074 if (scale_up && clki->max_freq) {
1075 if (clki->curr_freq == clki->max_freq)
1078 } else if (!scale_up && clki->min_freq) {
1079 if (clki->curr_freq == clki->min_freq)
1089 static int ufshcd_wait_for_doorbell_clr(struct ufs_hba *hba,
1090 u64 wait_timeout_us)
1092 unsigned long flags;
1096 bool timeout = false, do_last_check = false;
1099 ufshcd_hold(hba, false);
1100 spin_lock_irqsave(hba->host->host_lock, flags);
1102 * Wait for all the outstanding tasks/transfer requests.
1103 * Verify by checking the doorbell registers are clear.
1105 start = ktime_get();
1107 if (hba->ufshcd_state != UFSHCD_STATE_OPERATIONAL) {
1112 tm_doorbell = ufshcd_readl(hba, REG_UTP_TASK_REQ_DOOR_BELL);
1113 tr_doorbell = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
1114 if (!tm_doorbell && !tr_doorbell) {
1117 } else if (do_last_check) {
1121 spin_unlock_irqrestore(hba->host->host_lock, flags);
1123 if (ktime_to_us(ktime_sub(ktime_get(), start)) >
1127 * We might have scheduled out for long time so make
1128 * sure to check if doorbells are cleared by this time
1131 do_last_check = true;
1133 spin_lock_irqsave(hba->host->host_lock, flags);
1134 } while (tm_doorbell || tr_doorbell);
1138 "%s: timedout waiting for doorbell to clear (tm=0x%x, tr=0x%x)\n",
1139 __func__, tm_doorbell, tr_doorbell);
1143 spin_unlock_irqrestore(hba->host->host_lock, flags);
1144 ufshcd_release(hba);
1149 * ufshcd_scale_gear - scale up/down UFS gear
1150 * @hba: per adapter instance
1151 * @scale_up: True for scaling up gear and false for scaling down
1153 * Returns 0 for success,
1154 * Returns -EBUSY if scaling can't happen at this time
1155 * Returns non-zero for any other errors
1157 static int ufshcd_scale_gear(struct ufs_hba *hba, bool scale_up)
1160 struct ufs_pa_layer_attr new_pwr_info;
1163 memcpy(&new_pwr_info, &hba->clk_scaling.saved_pwr_info.info,
1164 sizeof(struct ufs_pa_layer_attr));
1166 memcpy(&new_pwr_info, &hba->pwr_info,
1167 sizeof(struct ufs_pa_layer_attr));
1169 if (hba->pwr_info.gear_tx > hba->clk_scaling.min_gear ||
1170 hba->pwr_info.gear_rx > hba->clk_scaling.min_gear) {
1171 /* save the current power mode */
1172 memcpy(&hba->clk_scaling.saved_pwr_info.info,
1174 sizeof(struct ufs_pa_layer_attr));
1176 /* scale down gear */
1177 new_pwr_info.gear_tx = hba->clk_scaling.min_gear;
1178 new_pwr_info.gear_rx = hba->clk_scaling.min_gear;
1182 /* check if the power mode needs to be changed or not? */
1183 ret = ufshcd_config_pwr_mode(hba, &new_pwr_info);
1185 dev_err(hba->dev, "%s: failed err %d, old gear: (tx %d rx %d), new gear: (tx %d rx %d)",
1187 hba->pwr_info.gear_tx, hba->pwr_info.gear_rx,
1188 new_pwr_info.gear_tx, new_pwr_info.gear_rx);
1193 static int ufshcd_clock_scaling_prepare(struct ufs_hba *hba)
1195 #define DOORBELL_CLR_TOUT_US (1000 * 1000) /* 1 sec */
1198 * make sure that there are no outstanding requests when
1199 * clock scaling is in progress
1201 ufshcd_scsi_block_requests(hba);
1202 down_write(&hba->clk_scaling_lock);
1204 if (!hba->clk_scaling.is_allowed ||
1205 ufshcd_wait_for_doorbell_clr(hba, DOORBELL_CLR_TOUT_US)) {
1207 up_write(&hba->clk_scaling_lock);
1208 ufshcd_scsi_unblock_requests(hba);
1212 /* let's not get into low power until clock scaling is completed */
1213 ufshcd_hold(hba, false);
1219 static void ufshcd_clock_scaling_unprepare(struct ufs_hba *hba, bool writelock)
1222 up_write(&hba->clk_scaling_lock);
1224 up_read(&hba->clk_scaling_lock);
1225 ufshcd_scsi_unblock_requests(hba);
1226 ufshcd_release(hba);
1230 * ufshcd_devfreq_scale - scale up/down UFS clocks and gear
1231 * @hba: per adapter instance
1232 * @scale_up: True for scaling up and false for scalin down
1234 * Returns 0 for success,
1235 * Returns -EBUSY if scaling can't happen at this time
1236 * Returns non-zero for any other errors
1238 static int ufshcd_devfreq_scale(struct ufs_hba *hba, bool scale_up)
1241 bool is_writelock = true;
1243 ret = ufshcd_clock_scaling_prepare(hba);
1247 /* scale down the gear before scaling down clocks */
1249 ret = ufshcd_scale_gear(hba, false);
1254 ret = ufshcd_scale_clks(hba, scale_up);
1257 ufshcd_scale_gear(hba, true);
1261 /* scale up the gear after scaling up clocks */
1263 ret = ufshcd_scale_gear(hba, true);
1265 ufshcd_scale_clks(hba, false);
1270 /* Enable Write Booster if we have scaled up else disable it */
1271 downgrade_write(&hba->clk_scaling_lock);
1272 is_writelock = false;
1273 ufshcd_wb_toggle(hba, scale_up);
1276 ufshcd_clock_scaling_unprepare(hba, is_writelock);
1280 static void ufshcd_clk_scaling_suspend_work(struct work_struct *work)
1282 struct ufs_hba *hba = container_of(work, struct ufs_hba,
1283 clk_scaling.suspend_work);
1284 unsigned long irq_flags;
1286 spin_lock_irqsave(hba->host->host_lock, irq_flags);
1287 if (hba->clk_scaling.active_reqs || hba->clk_scaling.is_suspended) {
1288 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1291 hba->clk_scaling.is_suspended = true;
1292 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1294 __ufshcd_suspend_clkscaling(hba);
1297 static void ufshcd_clk_scaling_resume_work(struct work_struct *work)
1299 struct ufs_hba *hba = container_of(work, struct ufs_hba,
1300 clk_scaling.resume_work);
1301 unsigned long irq_flags;
1303 spin_lock_irqsave(hba->host->host_lock, irq_flags);
1304 if (!hba->clk_scaling.is_suspended) {
1305 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1308 hba->clk_scaling.is_suspended = false;
1309 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1311 devfreq_resume_device(hba->devfreq);
1314 static int ufshcd_devfreq_target(struct device *dev,
1315 unsigned long *freq, u32 flags)
1318 struct ufs_hba *hba = dev_get_drvdata(dev);
1320 bool scale_up, sched_clk_scaling_suspend_work = false;
1321 struct list_head *clk_list = &hba->clk_list_head;
1322 struct ufs_clk_info *clki;
1323 unsigned long irq_flags;
1325 if (!ufshcd_is_clkscaling_supported(hba))
1328 clki = list_first_entry(&hba->clk_list_head, struct ufs_clk_info, list);
1329 /* Override with the closest supported frequency */
1330 *freq = (unsigned long) clk_round_rate(clki->clk, *freq);
1331 spin_lock_irqsave(hba->host->host_lock, irq_flags);
1332 if (ufshcd_eh_in_progress(hba)) {
1333 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1337 if (!hba->clk_scaling.active_reqs)
1338 sched_clk_scaling_suspend_work = true;
1340 if (list_empty(clk_list)) {
1341 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1345 /* Decide based on the rounded-off frequency and update */
1346 scale_up = (*freq == clki->max_freq) ? true : false;
1348 *freq = clki->min_freq;
1349 /* Update the frequency */
1350 if (!ufshcd_is_devfreq_scaling_required(hba, scale_up)) {
1351 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1353 goto out; /* no state change required */
1355 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1357 start = ktime_get();
1358 ret = ufshcd_devfreq_scale(hba, scale_up);
1360 trace_ufshcd_profile_clk_scaling(dev_name(hba->dev),
1361 (scale_up ? "up" : "down"),
1362 ktime_to_us(ktime_sub(ktime_get(), start)), ret);
1365 if (sched_clk_scaling_suspend_work)
1366 queue_work(hba->clk_scaling.workq,
1367 &hba->clk_scaling.suspend_work);
1372 static bool ufshcd_is_busy(struct request *req, void *priv, bool reserved)
1376 WARN_ON_ONCE(reserved);
1381 /* Whether or not any tag is in use by a request that is in progress. */
1382 static bool ufshcd_any_tag_in_use(struct ufs_hba *hba)
1384 struct request_queue *q = hba->cmd_queue;
1387 blk_mq_tagset_busy_iter(q->tag_set, ufshcd_is_busy, &busy);
1391 static int ufshcd_devfreq_get_dev_status(struct device *dev,
1392 struct devfreq_dev_status *stat)
1394 struct ufs_hba *hba = dev_get_drvdata(dev);
1395 struct ufs_clk_scaling *scaling = &hba->clk_scaling;
1396 unsigned long flags;
1397 struct list_head *clk_list = &hba->clk_list_head;
1398 struct ufs_clk_info *clki;
1401 if (!ufshcd_is_clkscaling_supported(hba))
1404 memset(stat, 0, sizeof(*stat));
1406 spin_lock_irqsave(hba->host->host_lock, flags);
1407 curr_t = ktime_get();
1408 if (!scaling->window_start_t)
1411 clki = list_first_entry(clk_list, struct ufs_clk_info, list);
1413 * If current frequency is 0, then the ondemand governor considers
1414 * there's no initial frequency set. And it always requests to set
1415 * to max. frequency.
1417 stat->current_frequency = clki->curr_freq;
1418 if (scaling->is_busy_started)
1419 scaling->tot_busy_t += ktime_us_delta(curr_t,
1420 scaling->busy_start_t);
1422 stat->total_time = ktime_us_delta(curr_t, scaling->window_start_t);
1423 stat->busy_time = scaling->tot_busy_t;
1425 scaling->window_start_t = curr_t;
1426 scaling->tot_busy_t = 0;
1428 if (hba->outstanding_reqs) {
1429 scaling->busy_start_t = curr_t;
1430 scaling->is_busy_started = true;
1432 scaling->busy_start_t = 0;
1433 scaling->is_busy_started = false;
1435 spin_unlock_irqrestore(hba->host->host_lock, flags);
1439 static int ufshcd_devfreq_init(struct ufs_hba *hba)
1441 struct list_head *clk_list = &hba->clk_list_head;
1442 struct ufs_clk_info *clki;
1443 struct devfreq *devfreq;
1446 /* Skip devfreq if we don't have any clocks in the list */
1447 if (list_empty(clk_list))
1450 clki = list_first_entry(clk_list, struct ufs_clk_info, list);
1451 dev_pm_opp_add(hba->dev, clki->min_freq, 0);
1452 dev_pm_opp_add(hba->dev, clki->max_freq, 0);
1454 ufshcd_vops_config_scaling_param(hba, &hba->vps->devfreq_profile,
1455 &hba->vps->ondemand_data);
1456 devfreq = devfreq_add_device(hba->dev,
1457 &hba->vps->devfreq_profile,
1458 DEVFREQ_GOV_SIMPLE_ONDEMAND,
1459 &hba->vps->ondemand_data);
1460 if (IS_ERR(devfreq)) {
1461 ret = PTR_ERR(devfreq);
1462 dev_err(hba->dev, "Unable to register with devfreq %d\n", ret);
1464 dev_pm_opp_remove(hba->dev, clki->min_freq);
1465 dev_pm_opp_remove(hba->dev, clki->max_freq);
1469 hba->devfreq = devfreq;
1474 static void ufshcd_devfreq_remove(struct ufs_hba *hba)
1476 struct list_head *clk_list = &hba->clk_list_head;
1477 struct ufs_clk_info *clki;
1482 devfreq_remove_device(hba->devfreq);
1483 hba->devfreq = NULL;
1485 clki = list_first_entry(clk_list, struct ufs_clk_info, list);
1486 dev_pm_opp_remove(hba->dev, clki->min_freq);
1487 dev_pm_opp_remove(hba->dev, clki->max_freq);
1490 static void __ufshcd_suspend_clkscaling(struct ufs_hba *hba)
1492 unsigned long flags;
1494 devfreq_suspend_device(hba->devfreq);
1495 spin_lock_irqsave(hba->host->host_lock, flags);
1496 hba->clk_scaling.window_start_t = 0;
1497 spin_unlock_irqrestore(hba->host->host_lock, flags);
1500 static void ufshcd_suspend_clkscaling(struct ufs_hba *hba)
1502 unsigned long flags;
1503 bool suspend = false;
1505 cancel_work_sync(&hba->clk_scaling.suspend_work);
1506 cancel_work_sync(&hba->clk_scaling.resume_work);
1508 spin_lock_irqsave(hba->host->host_lock, flags);
1509 if (!hba->clk_scaling.is_suspended) {
1511 hba->clk_scaling.is_suspended = true;
1513 spin_unlock_irqrestore(hba->host->host_lock, flags);
1516 __ufshcd_suspend_clkscaling(hba);
1519 static void ufshcd_resume_clkscaling(struct ufs_hba *hba)
1521 unsigned long flags;
1522 bool resume = false;
1524 spin_lock_irqsave(hba->host->host_lock, flags);
1525 if (hba->clk_scaling.is_suspended) {
1527 hba->clk_scaling.is_suspended = false;
1529 spin_unlock_irqrestore(hba->host->host_lock, flags);
1532 devfreq_resume_device(hba->devfreq);
1535 static ssize_t ufshcd_clkscale_enable_show(struct device *dev,
1536 struct device_attribute *attr, char *buf)
1538 struct ufs_hba *hba = dev_get_drvdata(dev);
1540 return sysfs_emit(buf, "%d\n", hba->clk_scaling.is_enabled);
1543 static ssize_t ufshcd_clkscale_enable_store(struct device *dev,
1544 struct device_attribute *attr, const char *buf, size_t count)
1546 struct ufs_hba *hba = dev_get_drvdata(dev);
1550 if (kstrtou32(buf, 0, &value))
1553 down(&hba->host_sem);
1554 if (!ufshcd_is_user_access_allowed(hba)) {
1560 if (value == hba->clk_scaling.is_enabled)
1563 ufshcd_rpm_get_sync(hba);
1564 ufshcd_hold(hba, false);
1566 hba->clk_scaling.is_enabled = value;
1569 ufshcd_resume_clkscaling(hba);
1571 ufshcd_suspend_clkscaling(hba);
1572 err = ufshcd_devfreq_scale(hba, true);
1574 dev_err(hba->dev, "%s: failed to scale clocks up %d\n",
1578 ufshcd_release(hba);
1579 ufshcd_rpm_put_sync(hba);
1582 return err ? err : count;
1585 static void ufshcd_init_clk_scaling_sysfs(struct ufs_hba *hba)
1587 hba->clk_scaling.enable_attr.show = ufshcd_clkscale_enable_show;
1588 hba->clk_scaling.enable_attr.store = ufshcd_clkscale_enable_store;
1589 sysfs_attr_init(&hba->clk_scaling.enable_attr.attr);
1590 hba->clk_scaling.enable_attr.attr.name = "clkscale_enable";
1591 hba->clk_scaling.enable_attr.attr.mode = 0644;
1592 if (device_create_file(hba->dev, &hba->clk_scaling.enable_attr))
1593 dev_err(hba->dev, "Failed to create sysfs for clkscale_enable\n");
1596 static void ufshcd_remove_clk_scaling_sysfs(struct ufs_hba *hba)
1598 if (hba->clk_scaling.enable_attr.attr.name)
1599 device_remove_file(hba->dev, &hba->clk_scaling.enable_attr);
1602 static void ufshcd_init_clk_scaling(struct ufs_hba *hba)
1604 char wq_name[sizeof("ufs_clkscaling_00")];
1606 if (!ufshcd_is_clkscaling_supported(hba))
1609 if (!hba->clk_scaling.min_gear)
1610 hba->clk_scaling.min_gear = UFS_HS_G1;
1612 INIT_WORK(&hba->clk_scaling.suspend_work,
1613 ufshcd_clk_scaling_suspend_work);
1614 INIT_WORK(&hba->clk_scaling.resume_work,
1615 ufshcd_clk_scaling_resume_work);
1617 snprintf(wq_name, sizeof(wq_name), "ufs_clkscaling_%d",
1618 hba->host->host_no);
1619 hba->clk_scaling.workq = create_singlethread_workqueue(wq_name);
1621 hba->clk_scaling.is_initialized = true;
1624 static void ufshcd_exit_clk_scaling(struct ufs_hba *hba)
1626 if (!hba->clk_scaling.is_initialized)
1629 ufshcd_remove_clk_scaling_sysfs(hba);
1630 destroy_workqueue(hba->clk_scaling.workq);
1631 ufshcd_devfreq_remove(hba);
1632 hba->clk_scaling.is_initialized = false;
1635 static void ufshcd_ungate_work(struct work_struct *work)
1638 unsigned long flags;
1639 struct ufs_hba *hba = container_of(work, struct ufs_hba,
1640 clk_gating.ungate_work);
1642 cancel_delayed_work_sync(&hba->clk_gating.gate_work);
1644 spin_lock_irqsave(hba->host->host_lock, flags);
1645 if (hba->clk_gating.state == CLKS_ON) {
1646 spin_unlock_irqrestore(hba->host->host_lock, flags);
1650 spin_unlock_irqrestore(hba->host->host_lock, flags);
1651 ufshcd_hba_vreg_set_hpm(hba);
1652 ufshcd_setup_clocks(hba, true);
1654 ufshcd_enable_irq(hba);
1656 /* Exit from hibern8 */
1657 if (ufshcd_can_hibern8_during_gating(hba)) {
1658 /* Prevent gating in this path */
1659 hba->clk_gating.is_suspended = true;
1660 if (ufshcd_is_link_hibern8(hba)) {
1661 ret = ufshcd_uic_hibern8_exit(hba);
1663 dev_err(hba->dev, "%s: hibern8 exit failed %d\n",
1666 ufshcd_set_link_active(hba);
1668 hba->clk_gating.is_suspended = false;
1671 ufshcd_scsi_unblock_requests(hba);
1675 * ufshcd_hold - Enable clocks that were gated earlier due to ufshcd_release.
1676 * Also, exit from hibern8 mode and set the link as active.
1677 * @hba: per adapter instance
1678 * @async: This indicates whether caller should ungate clocks asynchronously.
1680 int ufshcd_hold(struct ufs_hba *hba, bool async)
1684 unsigned long flags;
1686 if (!ufshcd_is_clkgating_allowed(hba))
1688 spin_lock_irqsave(hba->host->host_lock, flags);
1689 hba->clk_gating.active_reqs++;
1692 switch (hba->clk_gating.state) {
1695 * Wait for the ungate work to complete if in progress.
1696 * Though the clocks may be in ON state, the link could
1697 * still be in hibner8 state if hibern8 is allowed
1698 * during clock gating.
1699 * Make sure we exit hibern8 state also in addition to
1702 if (ufshcd_can_hibern8_during_gating(hba) &&
1703 ufshcd_is_link_hibern8(hba)) {
1706 hba->clk_gating.active_reqs--;
1709 spin_unlock_irqrestore(hba->host->host_lock, flags);
1710 flush_result = flush_work(&hba->clk_gating.ungate_work);
1711 if (hba->clk_gating.is_suspended && !flush_result)
1713 spin_lock_irqsave(hba->host->host_lock, flags);
1718 if (cancel_delayed_work(&hba->clk_gating.gate_work)) {
1719 hba->clk_gating.state = CLKS_ON;
1720 trace_ufshcd_clk_gating(dev_name(hba->dev),
1721 hba->clk_gating.state);
1725 * If we are here, it means gating work is either done or
1726 * currently running. Hence, fall through to cancel gating
1727 * work and to enable clocks.
1731 hba->clk_gating.state = REQ_CLKS_ON;
1732 trace_ufshcd_clk_gating(dev_name(hba->dev),
1733 hba->clk_gating.state);
1734 if (queue_work(hba->clk_gating.clk_gating_workq,
1735 &hba->clk_gating.ungate_work))
1736 ufshcd_scsi_block_requests(hba);
1738 * fall through to check if we should wait for this
1739 * work to be done or not.
1745 hba->clk_gating.active_reqs--;
1749 spin_unlock_irqrestore(hba->host->host_lock, flags);
1750 flush_work(&hba->clk_gating.ungate_work);
1751 /* Make sure state is CLKS_ON before returning */
1752 spin_lock_irqsave(hba->host->host_lock, flags);
1755 dev_err(hba->dev, "%s: clk gating is in invalid state %d\n",
1756 __func__, hba->clk_gating.state);
1759 spin_unlock_irqrestore(hba->host->host_lock, flags);
1763 EXPORT_SYMBOL_GPL(ufshcd_hold);
1765 static void ufshcd_gate_work(struct work_struct *work)
1767 struct ufs_hba *hba = container_of(work, struct ufs_hba,
1768 clk_gating.gate_work.work);
1769 unsigned long flags;
1772 spin_lock_irqsave(hba->host->host_lock, flags);
1774 * In case you are here to cancel this work the gating state
1775 * would be marked as REQ_CLKS_ON. In this case save time by
1776 * skipping the gating work and exit after changing the clock
1779 if (hba->clk_gating.is_suspended ||
1780 (hba->clk_gating.state != REQ_CLKS_OFF)) {
1781 hba->clk_gating.state = CLKS_ON;
1782 trace_ufshcd_clk_gating(dev_name(hba->dev),
1783 hba->clk_gating.state);
1787 if (hba->clk_gating.active_reqs
1788 || hba->ufshcd_state != UFSHCD_STATE_OPERATIONAL
1789 || ufshcd_any_tag_in_use(hba) || hba->outstanding_tasks
1790 || hba->active_uic_cmd || hba->uic_async_done)
1793 spin_unlock_irqrestore(hba->host->host_lock, flags);
1795 /* put the link into hibern8 mode before turning off clocks */
1796 if (ufshcd_can_hibern8_during_gating(hba)) {
1797 ret = ufshcd_uic_hibern8_enter(hba);
1799 hba->clk_gating.state = CLKS_ON;
1800 dev_err(hba->dev, "%s: hibern8 enter failed %d\n",
1802 trace_ufshcd_clk_gating(dev_name(hba->dev),
1803 hba->clk_gating.state);
1806 ufshcd_set_link_hibern8(hba);
1809 ufshcd_disable_irq(hba);
1811 ufshcd_setup_clocks(hba, false);
1813 /* Put the host controller in low power mode if possible */
1814 ufshcd_hba_vreg_set_lpm(hba);
1816 * In case you are here to cancel this work the gating state
1817 * would be marked as REQ_CLKS_ON. In this case keep the state
1818 * as REQ_CLKS_ON which would anyway imply that clocks are off
1819 * and a request to turn them on is pending. By doing this way,
1820 * we keep the state machine in tact and this would ultimately
1821 * prevent from doing cancel work multiple times when there are
1822 * new requests arriving before the current cancel work is done.
1824 spin_lock_irqsave(hba->host->host_lock, flags);
1825 if (hba->clk_gating.state == REQ_CLKS_OFF) {
1826 hba->clk_gating.state = CLKS_OFF;
1827 trace_ufshcd_clk_gating(dev_name(hba->dev),
1828 hba->clk_gating.state);
1831 spin_unlock_irqrestore(hba->host->host_lock, flags);
1836 /* host lock must be held before calling this variant */
1837 static void __ufshcd_release(struct ufs_hba *hba)
1839 if (!ufshcd_is_clkgating_allowed(hba))
1842 hba->clk_gating.active_reqs--;
1844 if (hba->clk_gating.active_reqs || hba->clk_gating.is_suspended ||
1845 hba->ufshcd_state != UFSHCD_STATE_OPERATIONAL ||
1846 hba->outstanding_tasks ||
1847 hba->active_uic_cmd || hba->uic_async_done ||
1848 hba->clk_gating.state == CLKS_OFF)
1851 hba->clk_gating.state = REQ_CLKS_OFF;
1852 trace_ufshcd_clk_gating(dev_name(hba->dev), hba->clk_gating.state);
1853 queue_delayed_work(hba->clk_gating.clk_gating_workq,
1854 &hba->clk_gating.gate_work,
1855 msecs_to_jiffies(hba->clk_gating.delay_ms));
1858 void ufshcd_release(struct ufs_hba *hba)
1860 unsigned long flags;
1862 spin_lock_irqsave(hba->host->host_lock, flags);
1863 __ufshcd_release(hba);
1864 spin_unlock_irqrestore(hba->host->host_lock, flags);
1866 EXPORT_SYMBOL_GPL(ufshcd_release);
1868 static ssize_t ufshcd_clkgate_delay_show(struct device *dev,
1869 struct device_attribute *attr, char *buf)
1871 struct ufs_hba *hba = dev_get_drvdata(dev);
1873 return sysfs_emit(buf, "%lu\n", hba->clk_gating.delay_ms);
1876 static ssize_t ufshcd_clkgate_delay_store(struct device *dev,
1877 struct device_attribute *attr, const char *buf, size_t count)
1879 struct ufs_hba *hba = dev_get_drvdata(dev);
1880 unsigned long flags, value;
1882 if (kstrtoul(buf, 0, &value))
1885 spin_lock_irqsave(hba->host->host_lock, flags);
1886 hba->clk_gating.delay_ms = value;
1887 spin_unlock_irqrestore(hba->host->host_lock, flags);
1891 static ssize_t ufshcd_clkgate_enable_show(struct device *dev,
1892 struct device_attribute *attr, char *buf)
1894 struct ufs_hba *hba = dev_get_drvdata(dev);
1896 return sysfs_emit(buf, "%d\n", hba->clk_gating.is_enabled);
1899 static ssize_t ufshcd_clkgate_enable_store(struct device *dev,
1900 struct device_attribute *attr, const char *buf, size_t count)
1902 struct ufs_hba *hba = dev_get_drvdata(dev);
1903 unsigned long flags;
1906 if (kstrtou32(buf, 0, &value))
1911 spin_lock_irqsave(hba->host->host_lock, flags);
1912 if (value == hba->clk_gating.is_enabled)
1916 __ufshcd_release(hba);
1918 hba->clk_gating.active_reqs++;
1920 hba->clk_gating.is_enabled = value;
1922 spin_unlock_irqrestore(hba->host->host_lock, flags);
1926 static void ufshcd_init_clk_gating_sysfs(struct ufs_hba *hba)
1928 hba->clk_gating.delay_attr.show = ufshcd_clkgate_delay_show;
1929 hba->clk_gating.delay_attr.store = ufshcd_clkgate_delay_store;
1930 sysfs_attr_init(&hba->clk_gating.delay_attr.attr);
1931 hba->clk_gating.delay_attr.attr.name = "clkgate_delay_ms";
1932 hba->clk_gating.delay_attr.attr.mode = 0644;
1933 if (device_create_file(hba->dev, &hba->clk_gating.delay_attr))
1934 dev_err(hba->dev, "Failed to create sysfs for clkgate_delay\n");
1936 hba->clk_gating.enable_attr.show = ufshcd_clkgate_enable_show;
1937 hba->clk_gating.enable_attr.store = ufshcd_clkgate_enable_store;
1938 sysfs_attr_init(&hba->clk_gating.enable_attr.attr);
1939 hba->clk_gating.enable_attr.attr.name = "clkgate_enable";
1940 hba->clk_gating.enable_attr.attr.mode = 0644;
1941 if (device_create_file(hba->dev, &hba->clk_gating.enable_attr))
1942 dev_err(hba->dev, "Failed to create sysfs for clkgate_enable\n");
1945 static void ufshcd_remove_clk_gating_sysfs(struct ufs_hba *hba)
1947 if (hba->clk_gating.delay_attr.attr.name)
1948 device_remove_file(hba->dev, &hba->clk_gating.delay_attr);
1949 if (hba->clk_gating.enable_attr.attr.name)
1950 device_remove_file(hba->dev, &hba->clk_gating.enable_attr);
1953 static void ufshcd_init_clk_gating(struct ufs_hba *hba)
1955 char wq_name[sizeof("ufs_clk_gating_00")];
1957 if (!ufshcd_is_clkgating_allowed(hba))
1960 hba->clk_gating.state = CLKS_ON;
1962 hba->clk_gating.delay_ms = 150;
1963 INIT_DELAYED_WORK(&hba->clk_gating.gate_work, ufshcd_gate_work);
1964 INIT_WORK(&hba->clk_gating.ungate_work, ufshcd_ungate_work);
1966 snprintf(wq_name, ARRAY_SIZE(wq_name), "ufs_clk_gating_%d",
1967 hba->host->host_no);
1968 hba->clk_gating.clk_gating_workq = alloc_ordered_workqueue(wq_name,
1969 WQ_MEM_RECLAIM | WQ_HIGHPRI);
1971 ufshcd_init_clk_gating_sysfs(hba);
1973 hba->clk_gating.is_enabled = true;
1974 hba->clk_gating.is_initialized = true;
1977 static void ufshcd_exit_clk_gating(struct ufs_hba *hba)
1979 if (!hba->clk_gating.is_initialized)
1981 ufshcd_remove_clk_gating_sysfs(hba);
1982 cancel_work_sync(&hba->clk_gating.ungate_work);
1983 cancel_delayed_work_sync(&hba->clk_gating.gate_work);
1984 destroy_workqueue(hba->clk_gating.clk_gating_workq);
1985 hba->clk_gating.is_initialized = false;
1988 /* Must be called with host lock acquired */
1989 static void ufshcd_clk_scaling_start_busy(struct ufs_hba *hba)
1991 bool queue_resume_work = false;
1992 ktime_t curr_t = ktime_get();
1993 unsigned long flags;
1995 if (!ufshcd_is_clkscaling_supported(hba))
1998 spin_lock_irqsave(hba->host->host_lock, flags);
1999 if (!hba->clk_scaling.active_reqs++)
2000 queue_resume_work = true;
2002 if (!hba->clk_scaling.is_enabled || hba->pm_op_in_progress) {
2003 spin_unlock_irqrestore(hba->host->host_lock, flags);
2007 if (queue_resume_work)
2008 queue_work(hba->clk_scaling.workq,
2009 &hba->clk_scaling.resume_work);
2011 if (!hba->clk_scaling.window_start_t) {
2012 hba->clk_scaling.window_start_t = curr_t;
2013 hba->clk_scaling.tot_busy_t = 0;
2014 hba->clk_scaling.is_busy_started = false;
2017 if (!hba->clk_scaling.is_busy_started) {
2018 hba->clk_scaling.busy_start_t = curr_t;
2019 hba->clk_scaling.is_busy_started = true;
2021 spin_unlock_irqrestore(hba->host->host_lock, flags);
2024 static void ufshcd_clk_scaling_update_busy(struct ufs_hba *hba)
2026 struct ufs_clk_scaling *scaling = &hba->clk_scaling;
2027 unsigned long flags;
2029 if (!ufshcd_is_clkscaling_supported(hba))
2032 spin_lock_irqsave(hba->host->host_lock, flags);
2033 hba->clk_scaling.active_reqs--;
2034 if (!hba->outstanding_reqs && scaling->is_busy_started) {
2035 scaling->tot_busy_t += ktime_to_us(ktime_sub(ktime_get(),
2036 scaling->busy_start_t));
2037 scaling->busy_start_t = 0;
2038 scaling->is_busy_started = false;
2040 spin_unlock_irqrestore(hba->host->host_lock, flags);
2043 static inline int ufshcd_monitor_opcode2dir(u8 opcode)
2045 if (opcode == READ_6 || opcode == READ_10 || opcode == READ_16)
2047 else if (opcode == WRITE_6 || opcode == WRITE_10 || opcode == WRITE_16)
2053 static inline bool ufshcd_should_inform_monitor(struct ufs_hba *hba,
2054 struct ufshcd_lrb *lrbp)
2056 struct ufs_hba_monitor *m = &hba->monitor;
2058 return (m->enabled && lrbp && lrbp->cmd &&
2059 (!m->chunk_size || m->chunk_size == lrbp->cmd->sdb.length) &&
2060 ktime_before(hba->monitor.enabled_ts, lrbp->issue_time_stamp));
2063 static void ufshcd_start_monitor(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
2065 int dir = ufshcd_monitor_opcode2dir(*lrbp->cmd->cmnd);
2066 unsigned long flags;
2068 spin_lock_irqsave(hba->host->host_lock, flags);
2069 if (dir >= 0 && hba->monitor.nr_queued[dir]++ == 0)
2070 hba->monitor.busy_start_ts[dir] = ktime_get();
2071 spin_unlock_irqrestore(hba->host->host_lock, flags);
2074 static void ufshcd_update_monitor(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
2076 int dir = ufshcd_monitor_opcode2dir(*lrbp->cmd->cmnd);
2077 unsigned long flags;
2079 spin_lock_irqsave(hba->host->host_lock, flags);
2080 if (dir >= 0 && hba->monitor.nr_queued[dir] > 0) {
2081 struct request *req = lrbp->cmd->request;
2082 struct ufs_hba_monitor *m = &hba->monitor;
2083 ktime_t now, inc, lat;
2085 now = lrbp->compl_time_stamp;
2086 inc = ktime_sub(now, m->busy_start_ts[dir]);
2087 m->total_busy[dir] = ktime_add(m->total_busy[dir], inc);
2088 m->nr_sec_rw[dir] += blk_rq_sectors(req);
2090 /* Update latencies */
2092 lat = ktime_sub(now, lrbp->issue_time_stamp);
2093 m->lat_sum[dir] += lat;
2094 if (m->lat_max[dir] < lat || !m->lat_max[dir])
2095 m->lat_max[dir] = lat;
2096 if (m->lat_min[dir] > lat || !m->lat_min[dir])
2097 m->lat_min[dir] = lat;
2099 m->nr_queued[dir]--;
2100 /* Push forward the busy start of monitor */
2101 m->busy_start_ts[dir] = now;
2103 spin_unlock_irqrestore(hba->host->host_lock, flags);
2107 * ufshcd_send_command - Send SCSI or device management commands
2108 * @hba: per adapter instance
2109 * @task_tag: Task tag of the command
2112 void ufshcd_send_command(struct ufs_hba *hba, unsigned int task_tag)
2114 struct ufshcd_lrb *lrbp = &hba->lrb[task_tag];
2116 lrbp->issue_time_stamp = ktime_get();
2117 lrbp->compl_time_stamp = ktime_set(0, 0);
2118 ufshcd_vops_setup_xfer_req(hba, task_tag, (lrbp->cmd ? true : false));
2119 ufshcd_add_command_trace(hba, task_tag, UFS_CMD_SEND);
2120 ufshcd_clk_scaling_start_busy(hba);
2121 if (unlikely(ufshcd_should_inform_monitor(hba, lrbp)))
2122 ufshcd_start_monitor(hba, lrbp);
2123 if (ufshcd_has_utrlcnr(hba)) {
2124 set_bit(task_tag, &hba->outstanding_reqs);
2125 ufshcd_writel(hba, 1 << task_tag,
2126 REG_UTP_TRANSFER_REQ_DOOR_BELL);
2128 unsigned long flags;
2130 spin_lock_irqsave(hba->host->host_lock, flags);
2131 set_bit(task_tag, &hba->outstanding_reqs);
2132 ufshcd_writel(hba, 1 << task_tag,
2133 REG_UTP_TRANSFER_REQ_DOOR_BELL);
2134 spin_unlock_irqrestore(hba->host->host_lock, flags);
2136 /* Make sure that doorbell is committed immediately */
2141 * ufshcd_copy_sense_data - Copy sense data in case of check condition
2142 * @lrbp: pointer to local reference block
2144 static inline void ufshcd_copy_sense_data(struct ufshcd_lrb *lrbp)
2147 if (lrbp->sense_buffer &&
2148 ufshcd_get_rsp_upiu_data_seg_len(lrbp->ucd_rsp_ptr)) {
2151 len = be16_to_cpu(lrbp->ucd_rsp_ptr->sr.sense_data_len);
2152 len_to_copy = min_t(int, UFS_SENSE_SIZE, len);
2154 memcpy(lrbp->sense_buffer, lrbp->ucd_rsp_ptr->sr.sense_data,
2160 * ufshcd_copy_query_response() - Copy the Query Response and the data
2162 * @hba: per adapter instance
2163 * @lrbp: pointer to local reference block
2166 int ufshcd_copy_query_response(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
2168 struct ufs_query_res *query_res = &hba->dev_cmd.query.response;
2170 memcpy(&query_res->upiu_res, &lrbp->ucd_rsp_ptr->qr, QUERY_OSF_SIZE);
2172 /* Get the descriptor */
2173 if (hba->dev_cmd.query.descriptor &&
2174 lrbp->ucd_rsp_ptr->qr.opcode == UPIU_QUERY_OPCODE_READ_DESC) {
2175 u8 *descp = (u8 *)lrbp->ucd_rsp_ptr +
2176 GENERAL_UPIU_REQUEST_SIZE;
2180 /* data segment length */
2181 resp_len = be32_to_cpu(lrbp->ucd_rsp_ptr->header.dword_2) &
2182 MASK_QUERY_DATA_SEG_LEN;
2183 buf_len = be16_to_cpu(
2184 hba->dev_cmd.query.request.upiu_req.length);
2185 if (likely(buf_len >= resp_len)) {
2186 memcpy(hba->dev_cmd.query.descriptor, descp, resp_len);
2189 "%s: rsp size %d is bigger than buffer size %d",
2190 __func__, resp_len, buf_len);
2199 * ufshcd_hba_capabilities - Read controller capabilities
2200 * @hba: per adapter instance
2202 * Return: 0 on success, negative on error.
2204 static inline int ufshcd_hba_capabilities(struct ufs_hba *hba)
2208 hba->capabilities = ufshcd_readl(hba, REG_CONTROLLER_CAPABILITIES);
2210 /* nutrs and nutmrs are 0 based values */
2211 hba->nutrs = (hba->capabilities & MASK_TRANSFER_REQUESTS_SLOTS) + 1;
2213 ((hba->capabilities & MASK_TASK_MANAGEMENT_REQUEST_SLOTS) >> 16) + 1;
2215 /* Read crypto capabilities */
2216 err = ufshcd_hba_init_crypto_capabilities(hba);
2218 dev_err(hba->dev, "crypto setup failed\n");
2224 * ufshcd_ready_for_uic_cmd - Check if controller is ready
2225 * to accept UIC commands
2226 * @hba: per adapter instance
2227 * Return true on success, else false
2229 static inline bool ufshcd_ready_for_uic_cmd(struct ufs_hba *hba)
2231 if (ufshcd_readl(hba, REG_CONTROLLER_STATUS) & UIC_COMMAND_READY)
2238 * ufshcd_get_upmcrs - Get the power mode change request status
2239 * @hba: Pointer to adapter instance
2241 * This function gets the UPMCRS field of HCS register
2242 * Returns value of UPMCRS field
2244 static inline u8 ufshcd_get_upmcrs(struct ufs_hba *hba)
2246 return (ufshcd_readl(hba, REG_CONTROLLER_STATUS) >> 8) & 0x7;
2250 * ufshcd_dispatch_uic_cmd - Dispatch UIC commands to unipro layers
2251 * @hba: per adapter instance
2252 * @uic_cmd: UIC command
2254 * Mutex must be held.
2257 ufshcd_dispatch_uic_cmd(struct ufs_hba *hba, struct uic_command *uic_cmd)
2259 WARN_ON(hba->active_uic_cmd);
2261 hba->active_uic_cmd = uic_cmd;
2264 ufshcd_writel(hba, uic_cmd->argument1, REG_UIC_COMMAND_ARG_1);
2265 ufshcd_writel(hba, uic_cmd->argument2, REG_UIC_COMMAND_ARG_2);
2266 ufshcd_writel(hba, uic_cmd->argument3, REG_UIC_COMMAND_ARG_3);
2268 ufshcd_add_uic_command_trace(hba, uic_cmd, UFS_CMD_SEND);
2271 ufshcd_writel(hba, uic_cmd->command & COMMAND_OPCODE_MASK,
2276 * ufshcd_wait_for_uic_cmd - Wait complectioin of UIC command
2277 * @hba: per adapter instance
2278 * @uic_cmd: UIC command
2280 * Must be called with mutex held.
2281 * Returns 0 only if success.
2284 ufshcd_wait_for_uic_cmd(struct ufs_hba *hba, struct uic_command *uic_cmd)
2287 unsigned long flags;
2289 if (wait_for_completion_timeout(&uic_cmd->done,
2290 msecs_to_jiffies(UIC_CMD_TIMEOUT))) {
2291 ret = uic_cmd->argument2 & MASK_UIC_COMMAND_RESULT;
2295 "uic cmd 0x%x with arg3 0x%x completion timeout\n",
2296 uic_cmd->command, uic_cmd->argument3);
2298 if (!uic_cmd->cmd_active) {
2299 dev_err(hba->dev, "%s: UIC cmd has been completed, return the result\n",
2301 ret = uic_cmd->argument2 & MASK_UIC_COMMAND_RESULT;
2305 spin_lock_irqsave(hba->host->host_lock, flags);
2306 hba->active_uic_cmd = NULL;
2307 spin_unlock_irqrestore(hba->host->host_lock, flags);
2313 * __ufshcd_send_uic_cmd - Send UIC commands and retrieve the result
2314 * @hba: per adapter instance
2315 * @uic_cmd: UIC command
2316 * @completion: initialize the completion only if this is set to true
2318 * Identical to ufshcd_send_uic_cmd() expect mutex. Must be called
2319 * with mutex held and host_lock locked.
2320 * Returns 0 only if success.
2323 __ufshcd_send_uic_cmd(struct ufs_hba *hba, struct uic_command *uic_cmd,
2326 if (!ufshcd_ready_for_uic_cmd(hba)) {
2328 "Controller not ready to accept UIC commands\n");
2333 init_completion(&uic_cmd->done);
2335 uic_cmd->cmd_active = 1;
2336 ufshcd_dispatch_uic_cmd(hba, uic_cmd);
2342 * ufshcd_send_uic_cmd - Send UIC commands and retrieve the result
2343 * @hba: per adapter instance
2344 * @uic_cmd: UIC command
2346 * Returns 0 only if success.
2348 int ufshcd_send_uic_cmd(struct ufs_hba *hba, struct uic_command *uic_cmd)
2351 unsigned long flags;
2353 ufshcd_hold(hba, false);
2354 mutex_lock(&hba->uic_cmd_mutex);
2355 ufshcd_add_delay_before_dme_cmd(hba);
2357 spin_lock_irqsave(hba->host->host_lock, flags);
2358 ret = __ufshcd_send_uic_cmd(hba, uic_cmd, true);
2359 spin_unlock_irqrestore(hba->host->host_lock, flags);
2361 ret = ufshcd_wait_for_uic_cmd(hba, uic_cmd);
2363 mutex_unlock(&hba->uic_cmd_mutex);
2365 ufshcd_release(hba);
2370 * ufshcd_map_sg - Map scatter-gather list to prdt
2371 * @hba: per adapter instance
2372 * @lrbp: pointer to local reference block
2374 * Returns 0 in case of success, non-zero value in case of failure
2376 static int ufshcd_map_sg(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
2378 struct ufshcd_sg_entry *prd_table;
2379 struct scatterlist *sg;
2380 struct scsi_cmnd *cmd;
2385 sg_segments = scsi_dma_map(cmd);
2386 if (sg_segments < 0)
2391 if (hba->quirks & UFSHCD_QUIRK_PRDT_BYTE_GRAN)
2392 lrbp->utr_descriptor_ptr->prd_table_length =
2393 cpu_to_le16((sg_segments *
2394 sizeof(struct ufshcd_sg_entry)));
2396 lrbp->utr_descriptor_ptr->prd_table_length =
2397 cpu_to_le16((u16) (sg_segments));
2399 prd_table = (struct ufshcd_sg_entry *)lrbp->ucd_prdt_ptr;
2401 scsi_for_each_sg(cmd, sg, sg_segments, i) {
2403 cpu_to_le32(((u32) sg_dma_len(sg))-1);
2404 prd_table[i].base_addr =
2405 cpu_to_le32(lower_32_bits(sg->dma_address));
2406 prd_table[i].upper_addr =
2407 cpu_to_le32(upper_32_bits(sg->dma_address));
2408 prd_table[i].reserved = 0;
2411 lrbp->utr_descriptor_ptr->prd_table_length = 0;
2418 * ufshcd_enable_intr - enable interrupts
2419 * @hba: per adapter instance
2420 * @intrs: interrupt bits
2422 static void ufshcd_enable_intr(struct ufs_hba *hba, u32 intrs)
2424 u32 set = ufshcd_readl(hba, REG_INTERRUPT_ENABLE);
2426 if (hba->ufs_version == ufshci_version(1, 0)) {
2428 rw = set & INTERRUPT_MASK_RW_VER_10;
2429 set = rw | ((set ^ intrs) & intrs);
2434 ufshcd_writel(hba, set, REG_INTERRUPT_ENABLE);
2438 * ufshcd_disable_intr - disable interrupts
2439 * @hba: per adapter instance
2440 * @intrs: interrupt bits
2442 static void ufshcd_disable_intr(struct ufs_hba *hba, u32 intrs)
2444 u32 set = ufshcd_readl(hba, REG_INTERRUPT_ENABLE);
2446 if (hba->ufs_version == ufshci_version(1, 0)) {
2448 rw = (set & INTERRUPT_MASK_RW_VER_10) &
2449 ~(intrs & INTERRUPT_MASK_RW_VER_10);
2450 set = rw | ((set & intrs) & ~INTERRUPT_MASK_RW_VER_10);
2456 ufshcd_writel(hba, set, REG_INTERRUPT_ENABLE);
2460 * ufshcd_prepare_req_desc_hdr() - Fills the requests header
2461 * descriptor according to request
2462 * @lrbp: pointer to local reference block
2463 * @upiu_flags: flags required in the header
2464 * @cmd_dir: requests data direction
2466 static void ufshcd_prepare_req_desc_hdr(struct ufshcd_lrb *lrbp,
2467 u8 *upiu_flags, enum dma_data_direction cmd_dir)
2469 struct utp_transfer_req_desc *req_desc = lrbp->utr_descriptor_ptr;
2475 if (cmd_dir == DMA_FROM_DEVICE) {
2476 data_direction = UTP_DEVICE_TO_HOST;
2477 *upiu_flags = UPIU_CMD_FLAGS_READ;
2478 } else if (cmd_dir == DMA_TO_DEVICE) {
2479 data_direction = UTP_HOST_TO_DEVICE;
2480 *upiu_flags = UPIU_CMD_FLAGS_WRITE;
2482 data_direction = UTP_NO_DATA_TRANSFER;
2483 *upiu_flags = UPIU_CMD_FLAGS_NONE;
2486 dword_0 = data_direction | (lrbp->command_type
2487 << UPIU_COMMAND_TYPE_OFFSET);
2489 dword_0 |= UTP_REQ_DESC_INT_CMD;
2491 /* Prepare crypto related dwords */
2492 ufshcd_prepare_req_desc_hdr_crypto(lrbp, &dword_0, &dword_1, &dword_3);
2494 /* Transfer request descriptor header fields */
2495 req_desc->header.dword_0 = cpu_to_le32(dword_0);
2496 req_desc->header.dword_1 = cpu_to_le32(dword_1);
2498 * assigning invalid value for command status. Controller
2499 * updates OCS on command completion, with the command
2502 req_desc->header.dword_2 =
2503 cpu_to_le32(OCS_INVALID_COMMAND_STATUS);
2504 req_desc->header.dword_3 = cpu_to_le32(dword_3);
2506 req_desc->prd_table_length = 0;
2510 * ufshcd_prepare_utp_scsi_cmd_upiu() - fills the utp_transfer_req_desc,
2512 * @lrbp: local reference block pointer
2513 * @upiu_flags: flags
2516 void ufshcd_prepare_utp_scsi_cmd_upiu(struct ufshcd_lrb *lrbp, u8 upiu_flags)
2518 struct scsi_cmnd *cmd = lrbp->cmd;
2519 struct utp_upiu_req *ucd_req_ptr = lrbp->ucd_req_ptr;
2520 unsigned short cdb_len;
2522 /* command descriptor fields */
2523 ucd_req_ptr->header.dword_0 = UPIU_HEADER_DWORD(
2524 UPIU_TRANSACTION_COMMAND, upiu_flags,
2525 lrbp->lun, lrbp->task_tag);
2526 ucd_req_ptr->header.dword_1 = UPIU_HEADER_DWORD(
2527 UPIU_COMMAND_SET_TYPE_SCSI, 0, 0, 0);
2529 /* Total EHS length and Data segment length will be zero */
2530 ucd_req_ptr->header.dword_2 = 0;
2532 ucd_req_ptr->sc.exp_data_transfer_len = cpu_to_be32(cmd->sdb.length);
2534 cdb_len = min_t(unsigned short, cmd->cmd_len, UFS_CDB_SIZE);
2535 memset(ucd_req_ptr->sc.cdb, 0, UFS_CDB_SIZE);
2536 memcpy(ucd_req_ptr->sc.cdb, cmd->cmnd, cdb_len);
2538 memset(lrbp->ucd_rsp_ptr, 0, sizeof(struct utp_upiu_rsp));
2542 * ufshcd_prepare_utp_query_req_upiu() - fills the utp_transfer_req_desc,
2545 * @lrbp: local reference block pointer
2546 * @upiu_flags: flags
2548 static void ufshcd_prepare_utp_query_req_upiu(struct ufs_hba *hba,
2549 struct ufshcd_lrb *lrbp, u8 upiu_flags)
2551 struct utp_upiu_req *ucd_req_ptr = lrbp->ucd_req_ptr;
2552 struct ufs_query *query = &hba->dev_cmd.query;
2553 u16 len = be16_to_cpu(query->request.upiu_req.length);
2555 /* Query request header */
2556 ucd_req_ptr->header.dword_0 = UPIU_HEADER_DWORD(
2557 UPIU_TRANSACTION_QUERY_REQ, upiu_flags,
2558 lrbp->lun, lrbp->task_tag);
2559 ucd_req_ptr->header.dword_1 = UPIU_HEADER_DWORD(
2560 0, query->request.query_func, 0, 0);
2562 /* Data segment length only need for WRITE_DESC */
2563 if (query->request.upiu_req.opcode == UPIU_QUERY_OPCODE_WRITE_DESC)
2564 ucd_req_ptr->header.dword_2 =
2565 UPIU_HEADER_DWORD(0, 0, (len >> 8), (u8)len);
2567 ucd_req_ptr->header.dword_2 = 0;
2569 /* Copy the Query Request buffer as is */
2570 memcpy(&ucd_req_ptr->qr, &query->request.upiu_req,
2573 /* Copy the Descriptor */
2574 if (query->request.upiu_req.opcode == UPIU_QUERY_OPCODE_WRITE_DESC)
2575 memcpy(ucd_req_ptr + 1, query->descriptor, len);
2577 memset(lrbp->ucd_rsp_ptr, 0, sizeof(struct utp_upiu_rsp));
2580 static inline void ufshcd_prepare_utp_nop_upiu(struct ufshcd_lrb *lrbp)
2582 struct utp_upiu_req *ucd_req_ptr = lrbp->ucd_req_ptr;
2584 memset(ucd_req_ptr, 0, sizeof(struct utp_upiu_req));
2586 /* command descriptor fields */
2587 ucd_req_ptr->header.dword_0 =
2589 UPIU_TRANSACTION_NOP_OUT, 0, 0, lrbp->task_tag);
2590 /* clear rest of the fields of basic header */
2591 ucd_req_ptr->header.dword_1 = 0;
2592 ucd_req_ptr->header.dword_2 = 0;
2594 memset(lrbp->ucd_rsp_ptr, 0, sizeof(struct utp_upiu_rsp));
2598 * ufshcd_compose_devman_upiu - UFS Protocol Information Unit(UPIU)
2599 * for Device Management Purposes
2600 * @hba: per adapter instance
2601 * @lrbp: pointer to local reference block
2603 static int ufshcd_compose_devman_upiu(struct ufs_hba *hba,
2604 struct ufshcd_lrb *lrbp)
2609 if (hba->ufs_version <= ufshci_version(1, 1))
2610 lrbp->command_type = UTP_CMD_TYPE_DEV_MANAGE;
2612 lrbp->command_type = UTP_CMD_TYPE_UFS_STORAGE;
2614 ufshcd_prepare_req_desc_hdr(lrbp, &upiu_flags, DMA_NONE);
2615 if (hba->dev_cmd.type == DEV_CMD_TYPE_QUERY)
2616 ufshcd_prepare_utp_query_req_upiu(hba, lrbp, upiu_flags);
2617 else if (hba->dev_cmd.type == DEV_CMD_TYPE_NOP)
2618 ufshcd_prepare_utp_nop_upiu(lrbp);
2626 * ufshcd_comp_scsi_upiu - UFS Protocol Information Unit(UPIU)
2628 * @hba: per adapter instance
2629 * @lrbp: pointer to local reference block
2631 static int ufshcd_comp_scsi_upiu(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
2636 if (hba->ufs_version <= ufshci_version(1, 1))
2637 lrbp->command_type = UTP_CMD_TYPE_SCSI;
2639 lrbp->command_type = UTP_CMD_TYPE_UFS_STORAGE;
2641 if (likely(lrbp->cmd)) {
2642 ufshcd_prepare_req_desc_hdr(lrbp, &upiu_flags,
2643 lrbp->cmd->sc_data_direction);
2644 ufshcd_prepare_utp_scsi_cmd_upiu(lrbp, upiu_flags);
2653 * ufshcd_upiu_wlun_to_scsi_wlun - maps UPIU W-LUN id to SCSI W-LUN ID
2654 * @upiu_wlun_id: UPIU W-LUN id
2656 * Returns SCSI W-LUN id
2658 static inline u16 ufshcd_upiu_wlun_to_scsi_wlun(u8 upiu_wlun_id)
2660 return (upiu_wlun_id & ~UFS_UPIU_WLUN_ID) | SCSI_W_LUN_BASE;
2663 static inline bool is_rpmb_wlun(struct scsi_device *sdev)
2665 return sdev->lun == ufshcd_upiu_wlun_to_scsi_wlun(UFS_UPIU_RPMB_WLUN);
2668 static inline bool is_device_wlun(struct scsi_device *sdev)
2671 ufshcd_upiu_wlun_to_scsi_wlun(UFS_UPIU_UFS_DEVICE_WLUN);
2674 static void ufshcd_init_lrb(struct ufs_hba *hba, struct ufshcd_lrb *lrb, int i)
2676 struct utp_transfer_cmd_desc *cmd_descp = hba->ucdl_base_addr;
2677 struct utp_transfer_req_desc *utrdlp = hba->utrdl_base_addr;
2678 dma_addr_t cmd_desc_element_addr = hba->ucdl_dma_addr +
2679 i * sizeof(struct utp_transfer_cmd_desc);
2680 u16 response_offset = offsetof(struct utp_transfer_cmd_desc,
2682 u16 prdt_offset = offsetof(struct utp_transfer_cmd_desc, prd_table);
2684 lrb->utr_descriptor_ptr = utrdlp + i;
2685 lrb->utrd_dma_addr = hba->utrdl_dma_addr +
2686 i * sizeof(struct utp_transfer_req_desc);
2687 lrb->ucd_req_ptr = (struct utp_upiu_req *)(cmd_descp + i);
2688 lrb->ucd_req_dma_addr = cmd_desc_element_addr;
2689 lrb->ucd_rsp_ptr = (struct utp_upiu_rsp *)cmd_descp[i].response_upiu;
2690 lrb->ucd_rsp_dma_addr = cmd_desc_element_addr + response_offset;
2691 lrb->ucd_prdt_ptr = (struct ufshcd_sg_entry *)cmd_descp[i].prd_table;
2692 lrb->ucd_prdt_dma_addr = cmd_desc_element_addr + prdt_offset;
2696 * ufshcd_queuecommand - main entry point for SCSI requests
2697 * @host: SCSI host pointer
2698 * @cmd: command from SCSI Midlayer
2700 * Returns 0 for success, non-zero in case of failure
2702 static int ufshcd_queuecommand(struct Scsi_Host *host, struct scsi_cmnd *cmd)
2704 struct ufshcd_lrb *lrbp;
2705 struct ufs_hba *hba;
2709 hba = shost_priv(host);
2711 tag = cmd->request->tag;
2712 if (!ufshcd_valid_tag(hba, tag)) {
2714 "%s: invalid command tag %d: cmd=0x%p, cmd->request=0x%p",
2715 __func__, tag, cmd, cmd->request);
2719 if (!down_read_trylock(&hba->clk_scaling_lock))
2720 return SCSI_MLQUEUE_HOST_BUSY;
2722 switch (hba->ufshcd_state) {
2723 case UFSHCD_STATE_OPERATIONAL:
2724 case UFSHCD_STATE_EH_SCHEDULED_NON_FATAL:
2726 case UFSHCD_STATE_EH_SCHEDULED_FATAL:
2728 * pm_runtime_get_sync() is used at error handling preparation
2729 * stage. If a scsi cmd, e.g. the SSU cmd, is sent from hba's
2730 * PM ops, it can never be finished if we let SCSI layer keep
2731 * retrying it, which gets err handler stuck forever. Neither
2732 * can we let the scsi cmd pass through, because UFS is in bad
2733 * state, the scsi cmd may eventually time out, which will get
2734 * err handler blocked for too long. So, just fail the scsi cmd
2735 * sent from PM ops, err handler can recover PM error anyways.
2737 if (hba->pm_op_in_progress) {
2738 hba->force_reset = true;
2739 set_host_byte(cmd, DID_BAD_TARGET);
2740 cmd->scsi_done(cmd);
2744 case UFSHCD_STATE_RESET:
2745 err = SCSI_MLQUEUE_HOST_BUSY;
2747 case UFSHCD_STATE_ERROR:
2748 set_host_byte(cmd, DID_ERROR);
2749 cmd->scsi_done(cmd);
2752 dev_WARN_ONCE(hba->dev, 1, "%s: invalid state %d\n",
2753 __func__, hba->ufshcd_state);
2754 set_host_byte(cmd, DID_BAD_TARGET);
2755 cmd->scsi_done(cmd);
2759 hba->req_abort_count = 0;
2761 err = ufshcd_hold(hba, true);
2763 err = SCSI_MLQUEUE_HOST_BUSY;
2766 WARN_ON(ufshcd_is_clkgating_allowed(hba) &&
2767 (hba->clk_gating.state != CLKS_ON));
2769 if (unlikely(test_bit(tag, &hba->outstanding_reqs))) {
2770 if (hba->pm_op_in_progress)
2771 set_host_byte(cmd, DID_BAD_TARGET);
2773 err = SCSI_MLQUEUE_HOST_BUSY;
2774 ufshcd_release(hba);
2778 lrbp = &hba->lrb[tag];
2781 lrbp->sense_bufflen = UFS_SENSE_SIZE;
2782 lrbp->sense_buffer = cmd->sense_buffer;
2783 lrbp->task_tag = tag;
2784 lrbp->lun = ufshcd_scsi_to_upiu_lun(cmd->device->lun);
2785 lrbp->intr_cmd = !ufshcd_is_intr_aggr_allowed(hba) ? true : false;
2787 ufshcd_prepare_lrbp_crypto(cmd->request, lrbp);
2789 lrbp->req_abort_skip = false;
2791 ufshcd_comp_scsi_upiu(hba, lrbp);
2793 err = ufshcd_map_sg(hba, lrbp);
2796 ufshcd_release(hba);
2799 /* Make sure descriptors are ready before ringing the doorbell */
2802 ufshcd_send_command(hba, tag);
2804 up_read(&hba->clk_scaling_lock);
2808 static int ufshcd_compose_dev_cmd(struct ufs_hba *hba,
2809 struct ufshcd_lrb *lrbp, enum dev_cmd_type cmd_type, int tag)
2812 lrbp->sense_bufflen = 0;
2813 lrbp->sense_buffer = NULL;
2814 lrbp->task_tag = tag;
2815 lrbp->lun = 0; /* device management cmd is not specific to any LUN */
2816 lrbp->intr_cmd = true; /* No interrupt aggregation */
2817 ufshcd_prepare_lrbp_crypto(NULL, lrbp);
2818 hba->dev_cmd.type = cmd_type;
2820 return ufshcd_compose_devman_upiu(hba, lrbp);
2824 ufshcd_clear_cmd(struct ufs_hba *hba, int tag)
2827 unsigned long flags;
2828 u32 mask = 1 << tag;
2830 /* clear outstanding transaction before retry */
2831 spin_lock_irqsave(hba->host->host_lock, flags);
2832 ufshcd_utrl_clear(hba, tag);
2833 spin_unlock_irqrestore(hba->host->host_lock, flags);
2836 * wait for h/w to clear corresponding bit in door-bell.
2837 * max. wait is 1 sec.
2839 err = ufshcd_wait_for_register(hba,
2840 REG_UTP_TRANSFER_REQ_DOOR_BELL,
2841 mask, ~mask, 1000, 1000);
2847 ufshcd_check_query_response(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
2849 struct ufs_query_res *query_res = &hba->dev_cmd.query.response;
2851 /* Get the UPIU response */
2852 query_res->response = ufshcd_get_rsp_upiu_result(lrbp->ucd_rsp_ptr) >>
2853 UPIU_RSP_CODE_OFFSET;
2854 return query_res->response;
2858 * ufshcd_dev_cmd_completion() - handles device management command responses
2859 * @hba: per adapter instance
2860 * @lrbp: pointer to local reference block
2863 ufshcd_dev_cmd_completion(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
2868 hba->ufs_stats.last_hibern8_exit_tstamp = ktime_set(0, 0);
2869 resp = ufshcd_get_req_rsp(lrbp->ucd_rsp_ptr);
2872 case UPIU_TRANSACTION_NOP_IN:
2873 if (hba->dev_cmd.type != DEV_CMD_TYPE_NOP) {
2875 dev_err(hba->dev, "%s: unexpected response %x\n",
2879 case UPIU_TRANSACTION_QUERY_RSP:
2880 err = ufshcd_check_query_response(hba, lrbp);
2882 err = ufshcd_copy_query_response(hba, lrbp);
2884 case UPIU_TRANSACTION_REJECT_UPIU:
2885 /* TODO: handle Reject UPIU Response */
2887 dev_err(hba->dev, "%s: Reject UPIU not fully implemented\n",
2892 dev_err(hba->dev, "%s: Invalid device management cmd response: %x\n",
2900 static int ufshcd_wait_for_dev_cmd(struct ufs_hba *hba,
2901 struct ufshcd_lrb *lrbp, int max_timeout)
2904 unsigned long time_left;
2905 unsigned long flags;
2907 time_left = wait_for_completion_timeout(hba->dev_cmd.complete,
2908 msecs_to_jiffies(max_timeout));
2910 /* Make sure descriptors are ready before ringing the doorbell */
2912 spin_lock_irqsave(hba->host->host_lock, flags);
2913 hba->dev_cmd.complete = NULL;
2914 if (likely(time_left)) {
2915 err = ufshcd_get_tr_ocs(lrbp);
2917 err = ufshcd_dev_cmd_completion(hba, lrbp);
2919 spin_unlock_irqrestore(hba->host->host_lock, flags);
2923 dev_dbg(hba->dev, "%s: dev_cmd request timedout, tag %d\n",
2924 __func__, lrbp->task_tag);
2925 if (!ufshcd_clear_cmd(hba, lrbp->task_tag))
2926 /* successfully cleared the command, retry if needed */
2929 * in case of an error, after clearing the doorbell,
2930 * we also need to clear the outstanding_request
2933 ufshcd_outstanding_req_clear(hba, lrbp->task_tag);
2940 * ufshcd_exec_dev_cmd - API for sending device management requests
2942 * @cmd_type: specifies the type (NOP, Query...)
2943 * @timeout: time in seconds
2945 * NOTE: Since there is only one available tag for device management commands,
2946 * it is expected you hold the hba->dev_cmd.lock mutex.
2948 static int ufshcd_exec_dev_cmd(struct ufs_hba *hba,
2949 enum dev_cmd_type cmd_type, int timeout)
2951 struct request_queue *q = hba->cmd_queue;
2952 struct request *req;
2953 struct ufshcd_lrb *lrbp;
2956 struct completion wait;
2958 down_read(&hba->clk_scaling_lock);
2961 * Get free slot, sleep if slots are unavailable.
2962 * Even though we use wait_event() which sleeps indefinitely,
2963 * the maximum wait time is bounded by SCSI request timeout.
2965 req = blk_get_request(q, REQ_OP_DRV_OUT, 0);
2971 WARN_ON_ONCE(!ufshcd_valid_tag(hba, tag));
2973 if (unlikely(test_bit(tag, &hba->outstanding_reqs))) {
2978 init_completion(&wait);
2979 lrbp = &hba->lrb[tag];
2981 err = ufshcd_compose_dev_cmd(hba, lrbp, cmd_type, tag);
2985 hba->dev_cmd.complete = &wait;
2987 ufshcd_add_query_upiu_trace(hba, UFS_QUERY_SEND, lrbp->ucd_req_ptr);
2988 /* Make sure descriptors are ready before ringing the doorbell */
2991 ufshcd_send_command(hba, tag);
2992 err = ufshcd_wait_for_dev_cmd(hba, lrbp, timeout);
2994 ufshcd_add_query_upiu_trace(hba, err ? UFS_QUERY_ERR : UFS_QUERY_COMP,
2995 (struct utp_upiu_req *)lrbp->ucd_rsp_ptr);
2998 blk_put_request(req);
3000 up_read(&hba->clk_scaling_lock);
3005 * ufshcd_init_query() - init the query response and request parameters
3006 * @hba: per-adapter instance
3007 * @request: address of the request pointer to be initialized
3008 * @response: address of the response pointer to be initialized
3009 * @opcode: operation to perform
3010 * @idn: flag idn to access
3011 * @index: LU number to access
3012 * @selector: query/flag/descriptor further identification
3014 static inline void ufshcd_init_query(struct ufs_hba *hba,
3015 struct ufs_query_req **request, struct ufs_query_res **response,
3016 enum query_opcode opcode, u8 idn, u8 index, u8 selector)
3018 *request = &hba->dev_cmd.query.request;
3019 *response = &hba->dev_cmd.query.response;
3020 memset(*request, 0, sizeof(struct ufs_query_req));
3021 memset(*response, 0, sizeof(struct ufs_query_res));
3022 (*request)->upiu_req.opcode = opcode;
3023 (*request)->upiu_req.idn = idn;
3024 (*request)->upiu_req.index = index;
3025 (*request)->upiu_req.selector = selector;
3028 static int ufshcd_query_flag_retry(struct ufs_hba *hba,
3029 enum query_opcode opcode, enum flag_idn idn, u8 index, bool *flag_res)
3034 for (retries = 0; retries < QUERY_REQ_RETRIES; retries++) {
3035 ret = ufshcd_query_flag(hba, opcode, idn, index, flag_res);
3038 "%s: failed with error %d, retries %d\n",
3039 __func__, ret, retries);
3046 "%s: query attribute, opcode %d, idn %d, failed with error %d after %d retires\n",
3047 __func__, opcode, idn, ret, retries);
3052 * ufshcd_query_flag() - API function for sending flag query requests
3053 * @hba: per-adapter instance
3054 * @opcode: flag query to perform
3055 * @idn: flag idn to access
3056 * @index: flag index to access
3057 * @flag_res: the flag value after the query request completes
3059 * Returns 0 for success, non-zero in case of failure
3061 int ufshcd_query_flag(struct ufs_hba *hba, enum query_opcode opcode,
3062 enum flag_idn idn, u8 index, bool *flag_res)
3064 struct ufs_query_req *request = NULL;
3065 struct ufs_query_res *response = NULL;
3066 int err, selector = 0;
3067 int timeout = QUERY_REQ_TIMEOUT;
3071 ufshcd_hold(hba, false);
3072 mutex_lock(&hba->dev_cmd.lock);
3073 ufshcd_init_query(hba, &request, &response, opcode, idn, index,
3077 case UPIU_QUERY_OPCODE_SET_FLAG:
3078 case UPIU_QUERY_OPCODE_CLEAR_FLAG:
3079 case UPIU_QUERY_OPCODE_TOGGLE_FLAG:
3080 request->query_func = UPIU_QUERY_FUNC_STANDARD_WRITE_REQUEST;
3082 case UPIU_QUERY_OPCODE_READ_FLAG:
3083 request->query_func = UPIU_QUERY_FUNC_STANDARD_READ_REQUEST;
3085 /* No dummy reads */
3086 dev_err(hba->dev, "%s: Invalid argument for read request\n",
3094 "%s: Expected query flag opcode but got = %d\n",
3100 err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_QUERY, timeout);
3104 "%s: Sending flag query for idn %d failed, err = %d\n",
3105 __func__, idn, err);
3110 *flag_res = (be32_to_cpu(response->upiu_res.value) &
3111 MASK_QUERY_UPIU_FLAG_LOC) & 0x1;
3114 mutex_unlock(&hba->dev_cmd.lock);
3115 ufshcd_release(hba);
3120 * ufshcd_query_attr - API function for sending attribute requests
3121 * @hba: per-adapter instance
3122 * @opcode: attribute opcode
3123 * @idn: attribute idn to access
3124 * @index: index field
3125 * @selector: selector field
3126 * @attr_val: the attribute value after the query request completes
3128 * Returns 0 for success, non-zero in case of failure
3130 int ufshcd_query_attr(struct ufs_hba *hba, enum query_opcode opcode,
3131 enum attr_idn idn, u8 index, u8 selector, u32 *attr_val)
3133 struct ufs_query_req *request = NULL;
3134 struct ufs_query_res *response = NULL;
3140 dev_err(hba->dev, "%s: attribute value required for opcode 0x%x\n",
3145 ufshcd_hold(hba, false);
3147 mutex_lock(&hba->dev_cmd.lock);
3148 ufshcd_init_query(hba, &request, &response, opcode, idn, index,
3152 case UPIU_QUERY_OPCODE_WRITE_ATTR:
3153 request->query_func = UPIU_QUERY_FUNC_STANDARD_WRITE_REQUEST;
3154 request->upiu_req.value = cpu_to_be32(*attr_val);
3156 case UPIU_QUERY_OPCODE_READ_ATTR:
3157 request->query_func = UPIU_QUERY_FUNC_STANDARD_READ_REQUEST;
3160 dev_err(hba->dev, "%s: Expected query attr opcode but got = 0x%.2x\n",
3166 err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_QUERY, QUERY_REQ_TIMEOUT);
3169 dev_err(hba->dev, "%s: opcode 0x%.2x for idn %d failed, index %d, err = %d\n",
3170 __func__, opcode, idn, index, err);
3174 *attr_val = be32_to_cpu(response->upiu_res.value);
3177 mutex_unlock(&hba->dev_cmd.lock);
3178 ufshcd_release(hba);
3183 * ufshcd_query_attr_retry() - API function for sending query
3184 * attribute with retries
3185 * @hba: per-adapter instance
3186 * @opcode: attribute opcode
3187 * @idn: attribute idn to access
3188 * @index: index field
3189 * @selector: selector field
3190 * @attr_val: the attribute value after the query request
3193 * Returns 0 for success, non-zero in case of failure
3195 static int ufshcd_query_attr_retry(struct ufs_hba *hba,
3196 enum query_opcode opcode, enum attr_idn idn, u8 index, u8 selector,
3202 for (retries = QUERY_REQ_RETRIES; retries > 0; retries--) {
3203 ret = ufshcd_query_attr(hba, opcode, idn, index,
3204 selector, attr_val);
3206 dev_dbg(hba->dev, "%s: failed with error %d, retries %d\n",
3207 __func__, ret, retries);
3214 "%s: query attribute, idn %d, failed with error %d after %d retires\n",
3215 __func__, idn, ret, QUERY_REQ_RETRIES);
3219 static int __ufshcd_query_descriptor(struct ufs_hba *hba,
3220 enum query_opcode opcode, enum desc_idn idn, u8 index,
3221 u8 selector, u8 *desc_buf, int *buf_len)
3223 struct ufs_query_req *request = NULL;
3224 struct ufs_query_res *response = NULL;
3230 dev_err(hba->dev, "%s: descriptor buffer required for opcode 0x%x\n",
3235 if (*buf_len < QUERY_DESC_MIN_SIZE || *buf_len > QUERY_DESC_MAX_SIZE) {
3236 dev_err(hba->dev, "%s: descriptor buffer size (%d) is out of range\n",
3237 __func__, *buf_len);
3241 ufshcd_hold(hba, false);
3243 mutex_lock(&hba->dev_cmd.lock);
3244 ufshcd_init_query(hba, &request, &response, opcode, idn, index,
3246 hba->dev_cmd.query.descriptor = desc_buf;
3247 request->upiu_req.length = cpu_to_be16(*buf_len);
3250 case UPIU_QUERY_OPCODE_WRITE_DESC:
3251 request->query_func = UPIU_QUERY_FUNC_STANDARD_WRITE_REQUEST;
3253 case UPIU_QUERY_OPCODE_READ_DESC:
3254 request->query_func = UPIU_QUERY_FUNC_STANDARD_READ_REQUEST;
3258 "%s: Expected query descriptor opcode but got = 0x%.2x\n",
3264 err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_QUERY, QUERY_REQ_TIMEOUT);
3267 dev_err(hba->dev, "%s: opcode 0x%.2x for idn %d failed, index %d, err = %d\n",
3268 __func__, opcode, idn, index, err);
3272 *buf_len = be16_to_cpu(response->upiu_res.length);
3275 hba->dev_cmd.query.descriptor = NULL;
3276 mutex_unlock(&hba->dev_cmd.lock);
3277 ufshcd_release(hba);
3282 * ufshcd_query_descriptor_retry - API function for sending descriptor requests
3283 * @hba: per-adapter instance
3284 * @opcode: attribute opcode
3285 * @idn: attribute idn to access
3286 * @index: index field
3287 * @selector: selector field
3288 * @desc_buf: the buffer that contains the descriptor
3289 * @buf_len: length parameter passed to the device
3291 * Returns 0 for success, non-zero in case of failure.
3292 * The buf_len parameter will contain, on return, the length parameter
3293 * received on the response.
3295 int ufshcd_query_descriptor_retry(struct ufs_hba *hba,
3296 enum query_opcode opcode,
3297 enum desc_idn idn, u8 index,
3299 u8 *desc_buf, int *buf_len)
3304 for (retries = QUERY_REQ_RETRIES; retries > 0; retries--) {
3305 err = __ufshcd_query_descriptor(hba, opcode, idn, index,
3306 selector, desc_buf, buf_len);
3307 if (!err || err == -EINVAL)
3315 * ufshcd_map_desc_id_to_length - map descriptor IDN to its length
3316 * @hba: Pointer to adapter instance
3317 * @desc_id: descriptor idn value
3318 * @desc_len: mapped desc length (out)
3320 void ufshcd_map_desc_id_to_length(struct ufs_hba *hba, enum desc_idn desc_id,
3323 if (desc_id >= QUERY_DESC_IDN_MAX || desc_id == QUERY_DESC_IDN_RFU_0 ||
3324 desc_id == QUERY_DESC_IDN_RFU_1)
3327 *desc_len = hba->desc_size[desc_id];
3329 EXPORT_SYMBOL(ufshcd_map_desc_id_to_length);
3331 static void ufshcd_update_desc_length(struct ufs_hba *hba,
3332 enum desc_idn desc_id, int desc_index,
3333 unsigned char desc_len)
3335 if (hba->desc_size[desc_id] == QUERY_DESC_MAX_SIZE &&
3336 desc_id != QUERY_DESC_IDN_STRING && desc_index != UFS_RPMB_UNIT)
3337 /* For UFS 3.1, the normal unit descriptor is 10 bytes larger
3338 * than the RPMB unit, however, both descriptors share the same
3339 * desc_idn, to cover both unit descriptors with one length, we
3340 * choose the normal unit descriptor length by desc_index.
3342 hba->desc_size[desc_id] = desc_len;
3346 * ufshcd_read_desc_param - read the specified descriptor parameter
3347 * @hba: Pointer to adapter instance
3348 * @desc_id: descriptor idn value
3349 * @desc_index: descriptor index
3350 * @param_offset: offset of the parameter to read
3351 * @param_read_buf: pointer to buffer where parameter would be read
3352 * @param_size: sizeof(param_read_buf)
3354 * Return 0 in case of success, non-zero otherwise
3356 int ufshcd_read_desc_param(struct ufs_hba *hba,
3357 enum desc_idn desc_id,
3366 bool is_kmalloc = true;
3369 if (desc_id >= QUERY_DESC_IDN_MAX || !param_size)
3372 /* Get the length of descriptor */
3373 ufshcd_map_desc_id_to_length(hba, desc_id, &buff_len);
3375 dev_err(hba->dev, "%s: Failed to get desc length\n", __func__);
3379 if (param_offset >= buff_len) {
3380 dev_err(hba->dev, "%s: Invalid offset 0x%x in descriptor IDN 0x%x, length 0x%x\n",
3381 __func__, param_offset, desc_id, buff_len);
3385 /* Check whether we need temp memory */
3386 if (param_offset != 0 || param_size < buff_len) {
3387 desc_buf = kzalloc(buff_len, GFP_KERNEL);
3391 desc_buf = param_read_buf;
3395 /* Request for full descriptor */
3396 ret = ufshcd_query_descriptor_retry(hba, UPIU_QUERY_OPCODE_READ_DESC,
3397 desc_id, desc_index, 0,
3398 desc_buf, &buff_len);
3401 dev_err(hba->dev, "%s: Failed reading descriptor. desc_id %d, desc_index %d, param_offset %d, ret %d\n",
3402 __func__, desc_id, desc_index, param_offset, ret);
3407 if (desc_buf[QUERY_DESC_DESC_TYPE_OFFSET] != desc_id) {
3408 dev_err(hba->dev, "%s: invalid desc_id %d in descriptor header\n",
3409 __func__, desc_buf[QUERY_DESC_DESC_TYPE_OFFSET]);
3414 /* Update descriptor length */
3415 buff_len = desc_buf[QUERY_DESC_LENGTH_OFFSET];
3416 ufshcd_update_desc_length(hba, desc_id, desc_index, buff_len);
3419 /* Make sure we don't copy more data than available */
3420 if (param_offset + param_size > buff_len)
3421 param_size = buff_len - param_offset;
3422 memcpy(param_read_buf, &desc_buf[param_offset], param_size);
3431 * struct uc_string_id - unicode string
3433 * @len: size of this descriptor inclusive
3434 * @type: descriptor type
3435 * @uc: unicode string character
3437 struct uc_string_id {
3443 /* replace non-printable or non-ASCII characters with spaces */
3444 static inline char ufshcd_remove_non_printable(u8 ch)
3446 return (ch >= 0x20 && ch <= 0x7e) ? ch : ' ';
3450 * ufshcd_read_string_desc - read string descriptor
3451 * @hba: pointer to adapter instance
3452 * @desc_index: descriptor index
3453 * @buf: pointer to buffer where descriptor would be read,
3454 * the caller should free the memory.
3455 * @ascii: if true convert from unicode to ascii characters
3456 * null terminated string.
3459 * * string size on success.
3460 * * -ENOMEM: on allocation failure
3461 * * -EINVAL: on a wrong parameter
3463 int ufshcd_read_string_desc(struct ufs_hba *hba, u8 desc_index,
3464 u8 **buf, bool ascii)
3466 struct uc_string_id *uc_str;
3473 uc_str = kzalloc(QUERY_DESC_MAX_SIZE, GFP_KERNEL);
3477 ret = ufshcd_read_desc_param(hba, QUERY_DESC_IDN_STRING, desc_index, 0,
3478 (u8 *)uc_str, QUERY_DESC_MAX_SIZE);
3480 dev_err(hba->dev, "Reading String Desc failed after %d retries. err = %d\n",
3481 QUERY_REQ_RETRIES, ret);
3486 if (uc_str->len <= QUERY_DESC_HDR_SIZE) {
3487 dev_dbg(hba->dev, "String Desc is of zero length\n");
3496 /* remove header and divide by 2 to move from UTF16 to UTF8 */
3497 ascii_len = (uc_str->len - QUERY_DESC_HDR_SIZE) / 2 + 1;
3498 str = kzalloc(ascii_len, GFP_KERNEL);
3505 * the descriptor contains string in UTF16 format
3506 * we need to convert to utf-8 so it can be displayed
3508 ret = utf16s_to_utf8s(uc_str->uc,
3509 uc_str->len - QUERY_DESC_HDR_SIZE,
3510 UTF16_BIG_ENDIAN, str, ascii_len);
3512 /* replace non-printable or non-ASCII characters with spaces */
3513 for (i = 0; i < ret; i++)
3514 str[i] = ufshcd_remove_non_printable(str[i]);
3519 str = kmemdup(uc_str, uc_str->len, GFP_KERNEL);
3533 * ufshcd_read_unit_desc_param - read the specified unit descriptor parameter
3534 * @hba: Pointer to adapter instance
3536 * @param_offset: offset of the parameter to read
3537 * @param_read_buf: pointer to buffer where parameter would be read
3538 * @param_size: sizeof(param_read_buf)
3540 * Return 0 in case of success, non-zero otherwise
3542 static inline int ufshcd_read_unit_desc_param(struct ufs_hba *hba,
3544 enum unit_desc_param param_offset,
3549 * Unit descriptors are only available for general purpose LUs (LUN id
3550 * from 0 to 7) and RPMB Well known LU.
3552 if (!ufs_is_valid_unit_desc_lun(&hba->dev_info, lun, param_offset))
3555 return ufshcd_read_desc_param(hba, QUERY_DESC_IDN_UNIT, lun,
3556 param_offset, param_read_buf, param_size);
3559 static int ufshcd_get_ref_clk_gating_wait(struct ufs_hba *hba)
3562 u32 gating_wait = UFSHCD_REF_CLK_GATING_WAIT_US;
3564 if (hba->dev_info.wspecversion >= 0x300) {
3565 err = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
3566 QUERY_ATTR_IDN_REF_CLK_GATING_WAIT_TIME, 0, 0,
3569 dev_err(hba->dev, "Failed reading bRefClkGatingWait. err = %d, use default %uus\n",
3572 if (gating_wait == 0) {
3573 gating_wait = UFSHCD_REF_CLK_GATING_WAIT_US;
3574 dev_err(hba->dev, "Undefined ref clk gating wait time, use default %uus\n",
3578 hba->dev_info.clk_gating_wait_us = gating_wait;
3585 * ufshcd_memory_alloc - allocate memory for host memory space data structures
3586 * @hba: per adapter instance
3588 * 1. Allocate DMA memory for Command Descriptor array
3589 * Each command descriptor consist of Command UPIU, Response UPIU and PRDT
3590 * 2. Allocate DMA memory for UTP Transfer Request Descriptor List (UTRDL).
3591 * 3. Allocate DMA memory for UTP Task Management Request Descriptor List
3593 * 4. Allocate memory for local reference block(lrb).
3595 * Returns 0 for success, non-zero in case of failure
3597 static int ufshcd_memory_alloc(struct ufs_hba *hba)
3599 size_t utmrdl_size, utrdl_size, ucdl_size;
3601 /* Allocate memory for UTP command descriptors */
3602 ucdl_size = (sizeof(struct utp_transfer_cmd_desc) * hba->nutrs);
3603 hba->ucdl_base_addr = dmam_alloc_coherent(hba->dev,
3605 &hba->ucdl_dma_addr,
3609 * UFSHCI requires UTP command descriptor to be 128 byte aligned.
3610 * make sure hba->ucdl_dma_addr is aligned to PAGE_SIZE
3611 * if hba->ucdl_dma_addr is aligned to PAGE_SIZE, then it will
3612 * be aligned to 128 bytes as well
3614 if (!hba->ucdl_base_addr ||
3615 WARN_ON(hba->ucdl_dma_addr & (PAGE_SIZE - 1))) {
3617 "Command Descriptor Memory allocation failed\n");
3622 * Allocate memory for UTP Transfer descriptors
3623 * UFSHCI requires 1024 byte alignment of UTRD
3625 utrdl_size = (sizeof(struct utp_transfer_req_desc) * hba->nutrs);
3626 hba->utrdl_base_addr = dmam_alloc_coherent(hba->dev,
3628 &hba->utrdl_dma_addr,
3630 if (!hba->utrdl_base_addr ||
3631 WARN_ON(hba->utrdl_dma_addr & (PAGE_SIZE - 1))) {
3633 "Transfer Descriptor Memory allocation failed\n");
3638 * Allocate memory for UTP Task Management descriptors
3639 * UFSHCI requires 1024 byte alignment of UTMRD
3641 utmrdl_size = sizeof(struct utp_task_req_desc) * hba->nutmrs;
3642 hba->utmrdl_base_addr = dmam_alloc_coherent(hba->dev,
3644 &hba->utmrdl_dma_addr,
3646 if (!hba->utmrdl_base_addr ||
3647 WARN_ON(hba->utmrdl_dma_addr & (PAGE_SIZE - 1))) {
3649 "Task Management Descriptor Memory allocation failed\n");
3653 /* Allocate memory for local reference block */
3654 hba->lrb = devm_kcalloc(hba->dev,
3655 hba->nutrs, sizeof(struct ufshcd_lrb),
3658 dev_err(hba->dev, "LRB Memory allocation failed\n");
3667 * ufshcd_host_memory_configure - configure local reference block with
3669 * @hba: per adapter instance
3671 * Configure Host memory space
3672 * 1. Update Corresponding UTRD.UCDBA and UTRD.UCDBAU with UCD DMA
3674 * 2. Update each UTRD with Response UPIU offset, Response UPIU length
3676 * 3. Save the corresponding addresses of UTRD, UCD.CMD, UCD.RSP and UCD.PRDT
3677 * into local reference block.
3679 static void ufshcd_host_memory_configure(struct ufs_hba *hba)
3681 struct utp_transfer_req_desc *utrdlp;
3682 dma_addr_t cmd_desc_dma_addr;
3683 dma_addr_t cmd_desc_element_addr;
3684 u16 response_offset;
3689 utrdlp = hba->utrdl_base_addr;
3692 offsetof(struct utp_transfer_cmd_desc, response_upiu);
3694 offsetof(struct utp_transfer_cmd_desc, prd_table);
3696 cmd_desc_size = sizeof(struct utp_transfer_cmd_desc);
3697 cmd_desc_dma_addr = hba->ucdl_dma_addr;
3699 for (i = 0; i < hba->nutrs; i++) {
3700 /* Configure UTRD with command descriptor base address */
3701 cmd_desc_element_addr =
3702 (cmd_desc_dma_addr + (cmd_desc_size * i));
3703 utrdlp[i].command_desc_base_addr_lo =
3704 cpu_to_le32(lower_32_bits(cmd_desc_element_addr));
3705 utrdlp[i].command_desc_base_addr_hi =
3706 cpu_to_le32(upper_32_bits(cmd_desc_element_addr));
3708 /* Response upiu and prdt offset should be in double words */
3709 if (hba->quirks & UFSHCD_QUIRK_PRDT_BYTE_GRAN) {
3710 utrdlp[i].response_upiu_offset =
3711 cpu_to_le16(response_offset);
3712 utrdlp[i].prd_table_offset =
3713 cpu_to_le16(prdt_offset);
3714 utrdlp[i].response_upiu_length =
3715 cpu_to_le16(ALIGNED_UPIU_SIZE);
3717 utrdlp[i].response_upiu_offset =
3718 cpu_to_le16(response_offset >> 2);
3719 utrdlp[i].prd_table_offset =
3720 cpu_to_le16(prdt_offset >> 2);
3721 utrdlp[i].response_upiu_length =
3722 cpu_to_le16(ALIGNED_UPIU_SIZE >> 2);
3725 ufshcd_init_lrb(hba, &hba->lrb[i], i);
3730 * ufshcd_dme_link_startup - Notify Unipro to perform link startup
3731 * @hba: per adapter instance
3733 * UIC_CMD_DME_LINK_STARTUP command must be issued to Unipro layer,
3734 * in order to initialize the Unipro link startup procedure.
3735 * Once the Unipro links are up, the device connected to the controller
3738 * Returns 0 on success, non-zero value on failure
3740 static int ufshcd_dme_link_startup(struct ufs_hba *hba)
3742 struct uic_command uic_cmd = {0};
3745 uic_cmd.command = UIC_CMD_DME_LINK_STARTUP;
3747 ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
3750 "dme-link-startup: error code %d\n", ret);
3754 * ufshcd_dme_reset - UIC command for DME_RESET
3755 * @hba: per adapter instance
3757 * DME_RESET command is issued in order to reset UniPro stack.
3758 * This function now deals with cold reset.
3760 * Returns 0 on success, non-zero value on failure
3762 static int ufshcd_dme_reset(struct ufs_hba *hba)
3764 struct uic_command uic_cmd = {0};
3767 uic_cmd.command = UIC_CMD_DME_RESET;
3769 ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
3772 "dme-reset: error code %d\n", ret);
3777 int ufshcd_dme_configure_adapt(struct ufs_hba *hba,
3783 if (agreed_gear != UFS_HS_G4)
3784 adapt_val = PA_NO_ADAPT;
3786 ret = ufshcd_dme_set(hba,
3787 UIC_ARG_MIB(PA_TXHSADAPTTYPE),
3791 EXPORT_SYMBOL_GPL(ufshcd_dme_configure_adapt);
3794 * ufshcd_dme_enable - UIC command for DME_ENABLE
3795 * @hba: per adapter instance
3797 * DME_ENABLE command is issued in order to enable UniPro stack.
3799 * Returns 0 on success, non-zero value on failure
3801 static int ufshcd_dme_enable(struct ufs_hba *hba)
3803 struct uic_command uic_cmd = {0};
3806 uic_cmd.command = UIC_CMD_DME_ENABLE;
3808 ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
3811 "dme-enable: error code %d\n", ret);
3816 static inline void ufshcd_add_delay_before_dme_cmd(struct ufs_hba *hba)
3818 #define MIN_DELAY_BEFORE_DME_CMDS_US 1000
3819 unsigned long min_sleep_time_us;
3821 if (!(hba->quirks & UFSHCD_QUIRK_DELAY_BEFORE_DME_CMDS))
3825 * last_dme_cmd_tstamp will be 0 only for 1st call to
3828 if (unlikely(!ktime_to_us(hba->last_dme_cmd_tstamp))) {
3829 min_sleep_time_us = MIN_DELAY_BEFORE_DME_CMDS_US;
3831 unsigned long delta =
3832 (unsigned long) ktime_to_us(
3833 ktime_sub(ktime_get(),
3834 hba->last_dme_cmd_tstamp));
3836 if (delta < MIN_DELAY_BEFORE_DME_CMDS_US)
3838 MIN_DELAY_BEFORE_DME_CMDS_US - delta;
3840 return; /* no more delay required */
3843 /* allow sleep for extra 50us if needed */
3844 usleep_range(min_sleep_time_us, min_sleep_time_us + 50);
3848 * ufshcd_dme_set_attr - UIC command for DME_SET, DME_PEER_SET
3849 * @hba: per adapter instance
3850 * @attr_sel: uic command argument1
3851 * @attr_set: attribute set type as uic command argument2
3852 * @mib_val: setting value as uic command argument3
3853 * @peer: indicate whether peer or local
3855 * Returns 0 on success, non-zero value on failure
3857 int ufshcd_dme_set_attr(struct ufs_hba *hba, u32 attr_sel,
3858 u8 attr_set, u32 mib_val, u8 peer)
3860 struct uic_command uic_cmd = {0};
3861 static const char *const action[] = {
3865 const char *set = action[!!peer];
3867 int retries = UFS_UIC_COMMAND_RETRIES;
3869 uic_cmd.command = peer ?
3870 UIC_CMD_DME_PEER_SET : UIC_CMD_DME_SET;
3871 uic_cmd.argument1 = attr_sel;
3872 uic_cmd.argument2 = UIC_ARG_ATTR_TYPE(attr_set);
3873 uic_cmd.argument3 = mib_val;
3876 /* for peer attributes we retry upon failure */
3877 ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
3879 dev_dbg(hba->dev, "%s: attr-id 0x%x val 0x%x error code %d\n",
3880 set, UIC_GET_ATTR_ID(attr_sel), mib_val, ret);
3881 } while (ret && peer && --retries);
3884 dev_err(hba->dev, "%s: attr-id 0x%x val 0x%x failed %d retries\n",
3885 set, UIC_GET_ATTR_ID(attr_sel), mib_val,
3886 UFS_UIC_COMMAND_RETRIES - retries);
3890 EXPORT_SYMBOL_GPL(ufshcd_dme_set_attr);
3893 * ufshcd_dme_get_attr - UIC command for DME_GET, DME_PEER_GET
3894 * @hba: per adapter instance
3895 * @attr_sel: uic command argument1
3896 * @mib_val: the value of the attribute as returned by the UIC command
3897 * @peer: indicate whether peer or local
3899 * Returns 0 on success, non-zero value on failure
3901 int ufshcd_dme_get_attr(struct ufs_hba *hba, u32 attr_sel,
3902 u32 *mib_val, u8 peer)
3904 struct uic_command uic_cmd = {0};
3905 static const char *const action[] = {
3909 const char *get = action[!!peer];
3911 int retries = UFS_UIC_COMMAND_RETRIES;
3912 struct ufs_pa_layer_attr orig_pwr_info;
3913 struct ufs_pa_layer_attr temp_pwr_info;
3914 bool pwr_mode_change = false;
3916 if (peer && (hba->quirks & UFSHCD_QUIRK_DME_PEER_ACCESS_AUTO_MODE)) {
3917 orig_pwr_info = hba->pwr_info;
3918 temp_pwr_info = orig_pwr_info;
3920 if (orig_pwr_info.pwr_tx == FAST_MODE ||
3921 orig_pwr_info.pwr_rx == FAST_MODE) {
3922 temp_pwr_info.pwr_tx = FASTAUTO_MODE;
3923 temp_pwr_info.pwr_rx = FASTAUTO_MODE;
3924 pwr_mode_change = true;
3925 } else if (orig_pwr_info.pwr_tx == SLOW_MODE ||
3926 orig_pwr_info.pwr_rx == SLOW_MODE) {
3927 temp_pwr_info.pwr_tx = SLOWAUTO_MODE;
3928 temp_pwr_info.pwr_rx = SLOWAUTO_MODE;
3929 pwr_mode_change = true;
3931 if (pwr_mode_change) {
3932 ret = ufshcd_change_power_mode(hba, &temp_pwr_info);
3938 uic_cmd.command = peer ?
3939 UIC_CMD_DME_PEER_GET : UIC_CMD_DME_GET;
3940 uic_cmd.argument1 = attr_sel;
3943 /* for peer attributes we retry upon failure */
3944 ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
3946 dev_dbg(hba->dev, "%s: attr-id 0x%x error code %d\n",
3947 get, UIC_GET_ATTR_ID(attr_sel), ret);
3948 } while (ret && peer && --retries);
3951 dev_err(hba->dev, "%s: attr-id 0x%x failed %d retries\n",
3952 get, UIC_GET_ATTR_ID(attr_sel),
3953 UFS_UIC_COMMAND_RETRIES - retries);
3955 if (mib_val && !ret)
3956 *mib_val = uic_cmd.argument3;
3958 if (peer && (hba->quirks & UFSHCD_QUIRK_DME_PEER_ACCESS_AUTO_MODE)
3960 ufshcd_change_power_mode(hba, &orig_pwr_info);
3964 EXPORT_SYMBOL_GPL(ufshcd_dme_get_attr);
3967 * ufshcd_uic_pwr_ctrl - executes UIC commands (which affects the link power
3968 * state) and waits for it to take effect.
3970 * @hba: per adapter instance
3971 * @cmd: UIC command to execute
3973 * DME operations like DME_SET(PA_PWRMODE), DME_HIBERNATE_ENTER &
3974 * DME_HIBERNATE_EXIT commands take some time to take its effect on both host
3975 * and device UniPro link and hence it's final completion would be indicated by
3976 * dedicated status bits in Interrupt Status register (UPMS, UHES, UHXS) in
3977 * addition to normal UIC command completion Status (UCCS). This function only
3978 * returns after the relevant status bits indicate the completion.
3980 * Returns 0 on success, non-zero value on failure
3982 static int ufshcd_uic_pwr_ctrl(struct ufs_hba *hba, struct uic_command *cmd)
3984 struct completion uic_async_done;
3985 unsigned long flags;
3988 bool reenable_intr = false;
3990 mutex_lock(&hba->uic_cmd_mutex);
3991 init_completion(&uic_async_done);
3992 ufshcd_add_delay_before_dme_cmd(hba);
3994 spin_lock_irqsave(hba->host->host_lock, flags);
3995 if (ufshcd_is_link_broken(hba)) {
3999 hba->uic_async_done = &uic_async_done;
4000 if (ufshcd_readl(hba, REG_INTERRUPT_ENABLE) & UIC_COMMAND_COMPL) {
4001 ufshcd_disable_intr(hba, UIC_COMMAND_COMPL);
4003 * Make sure UIC command completion interrupt is disabled before
4004 * issuing UIC command.
4007 reenable_intr = true;
4009 ret = __ufshcd_send_uic_cmd(hba, cmd, false);
4010 spin_unlock_irqrestore(hba->host->host_lock, flags);
4013 "pwr ctrl cmd 0x%x with mode 0x%x uic error %d\n",
4014 cmd->command, cmd->argument3, ret);
4018 if (!wait_for_completion_timeout(hba->uic_async_done,
4019 msecs_to_jiffies(UIC_CMD_TIMEOUT))) {
4021 "pwr ctrl cmd 0x%x with mode 0x%x completion timeout\n",
4022 cmd->command, cmd->argument3);
4024 if (!cmd->cmd_active) {
4025 dev_err(hba->dev, "%s: Power Mode Change operation has been completed, go check UPMCRS\n",
4035 status = ufshcd_get_upmcrs(hba);
4036 if (status != PWR_LOCAL) {
4038 "pwr ctrl cmd 0x%x failed, host upmcrs:0x%x\n",
4039 cmd->command, status);
4040 ret = (status != PWR_OK) ? status : -1;
4044 ufshcd_print_host_state(hba);
4045 ufshcd_print_pwr_info(hba);
4046 ufshcd_print_evt_hist(hba);
4049 spin_lock_irqsave(hba->host->host_lock, flags);
4050 hba->active_uic_cmd = NULL;
4051 hba->uic_async_done = NULL;
4053 ufshcd_enable_intr(hba, UIC_COMMAND_COMPL);
4055 ufshcd_set_link_broken(hba);
4056 ufshcd_schedule_eh_work(hba);
4059 spin_unlock_irqrestore(hba->host->host_lock, flags);
4060 mutex_unlock(&hba->uic_cmd_mutex);
4066 * ufshcd_uic_change_pwr_mode - Perform the UIC power mode chage
4067 * using DME_SET primitives.
4068 * @hba: per adapter instance
4069 * @mode: powr mode value
4071 * Returns 0 on success, non-zero value on failure
4073 static int ufshcd_uic_change_pwr_mode(struct ufs_hba *hba, u8 mode)
4075 struct uic_command uic_cmd = {0};
4078 if (hba->quirks & UFSHCD_QUIRK_BROKEN_PA_RXHSUNTERMCAP) {
4079 ret = ufshcd_dme_set(hba,
4080 UIC_ARG_MIB_SEL(PA_RXHSUNTERMCAP, 0), 1);
4082 dev_err(hba->dev, "%s: failed to enable PA_RXHSUNTERMCAP ret %d\n",
4088 uic_cmd.command = UIC_CMD_DME_SET;
4089 uic_cmd.argument1 = UIC_ARG_MIB(PA_PWRMODE);
4090 uic_cmd.argument3 = mode;
4091 ufshcd_hold(hba, false);
4092 ret = ufshcd_uic_pwr_ctrl(hba, &uic_cmd);
4093 ufshcd_release(hba);
4099 int ufshcd_link_recovery(struct ufs_hba *hba)
4102 unsigned long flags;
4104 spin_lock_irqsave(hba->host->host_lock, flags);
4105 hba->ufshcd_state = UFSHCD_STATE_RESET;
4106 ufshcd_set_eh_in_progress(hba);
4107 spin_unlock_irqrestore(hba->host->host_lock, flags);
4109 /* Reset the attached device */
4110 ufshcd_device_reset(hba);
4112 ret = ufshcd_host_reset_and_restore(hba);
4114 spin_lock_irqsave(hba->host->host_lock, flags);
4116 hba->ufshcd_state = UFSHCD_STATE_ERROR;
4117 ufshcd_clear_eh_in_progress(hba);
4118 spin_unlock_irqrestore(hba->host->host_lock, flags);
4121 dev_err(hba->dev, "%s: link recovery failed, err %d",
4124 ufshcd_clear_ua_wluns(hba);
4128 EXPORT_SYMBOL_GPL(ufshcd_link_recovery);
4130 static int ufshcd_uic_hibern8_enter(struct ufs_hba *hba)
4133 struct uic_command uic_cmd = {0};
4134 ktime_t start = ktime_get();
4136 ufshcd_vops_hibern8_notify(hba, UIC_CMD_DME_HIBER_ENTER, PRE_CHANGE);
4138 uic_cmd.command = UIC_CMD_DME_HIBER_ENTER;
4139 ret = ufshcd_uic_pwr_ctrl(hba, &uic_cmd);
4140 trace_ufshcd_profile_hibern8(dev_name(hba->dev), "enter",
4141 ktime_to_us(ktime_sub(ktime_get(), start)), ret);
4144 dev_err(hba->dev, "%s: hibern8 enter failed. ret = %d\n",
4147 ufshcd_vops_hibern8_notify(hba, UIC_CMD_DME_HIBER_ENTER,
4153 int ufshcd_uic_hibern8_exit(struct ufs_hba *hba)
4155 struct uic_command uic_cmd = {0};
4157 ktime_t start = ktime_get();
4159 ufshcd_vops_hibern8_notify(hba, UIC_CMD_DME_HIBER_EXIT, PRE_CHANGE);
4161 uic_cmd.command = UIC_CMD_DME_HIBER_EXIT;
4162 ret = ufshcd_uic_pwr_ctrl(hba, &uic_cmd);
4163 trace_ufshcd_profile_hibern8(dev_name(hba->dev), "exit",
4164 ktime_to_us(ktime_sub(ktime_get(), start)), ret);
4167 dev_err(hba->dev, "%s: hibern8 exit failed. ret = %d\n",
4170 ufshcd_vops_hibern8_notify(hba, UIC_CMD_DME_HIBER_EXIT,
4172 hba->ufs_stats.last_hibern8_exit_tstamp = ktime_get();
4173 hba->ufs_stats.hibern8_exit_cnt++;
4178 EXPORT_SYMBOL_GPL(ufshcd_uic_hibern8_exit);
4180 void ufshcd_auto_hibern8_update(struct ufs_hba *hba, u32 ahit)
4182 unsigned long flags;
4183 bool update = false;
4185 if (!ufshcd_is_auto_hibern8_supported(hba))
4188 spin_lock_irqsave(hba->host->host_lock, flags);
4189 if (hba->ahit != ahit) {
4193 spin_unlock_irqrestore(hba->host->host_lock, flags);
4196 !pm_runtime_suspended(&hba->sdev_ufs_device->sdev_gendev)) {
4197 ufshcd_rpm_get_sync(hba);
4198 ufshcd_hold(hba, false);
4199 ufshcd_auto_hibern8_enable(hba);
4200 ufshcd_release(hba);
4201 ufshcd_rpm_put_sync(hba);
4204 EXPORT_SYMBOL_GPL(ufshcd_auto_hibern8_update);
4206 void ufshcd_auto_hibern8_enable(struct ufs_hba *hba)
4208 unsigned long flags;
4210 if (!ufshcd_is_auto_hibern8_supported(hba))
4213 spin_lock_irqsave(hba->host->host_lock, flags);
4214 ufshcd_writel(hba, hba->ahit, REG_AUTO_HIBERNATE_IDLE_TIMER);
4215 spin_unlock_irqrestore(hba->host->host_lock, flags);
4219 * ufshcd_init_pwr_info - setting the POR (power on reset)
4220 * values in hba power info
4221 * @hba: per-adapter instance
4223 static void ufshcd_init_pwr_info(struct ufs_hba *hba)
4225 hba->pwr_info.gear_rx = UFS_PWM_G1;
4226 hba->pwr_info.gear_tx = UFS_PWM_G1;
4227 hba->pwr_info.lane_rx = 1;
4228 hba->pwr_info.lane_tx = 1;
4229 hba->pwr_info.pwr_rx = SLOWAUTO_MODE;
4230 hba->pwr_info.pwr_tx = SLOWAUTO_MODE;
4231 hba->pwr_info.hs_rate = 0;
4235 * ufshcd_get_max_pwr_mode - reads the max power mode negotiated with device
4236 * @hba: per-adapter instance
4238 static int ufshcd_get_max_pwr_mode(struct ufs_hba *hba)
4240 struct ufs_pa_layer_attr *pwr_info = &hba->max_pwr_info.info;
4242 if (hba->max_pwr_info.is_valid)
4245 pwr_info->pwr_tx = FAST_MODE;
4246 pwr_info->pwr_rx = FAST_MODE;
4247 pwr_info->hs_rate = PA_HS_MODE_B;
4249 /* Get the connected lane count */
4250 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_CONNECTEDRXDATALANES),
4251 &pwr_info->lane_rx);
4252 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_CONNECTEDTXDATALANES),
4253 &pwr_info->lane_tx);
4255 if (!pwr_info->lane_rx || !pwr_info->lane_tx) {
4256 dev_err(hba->dev, "%s: invalid connected lanes value. rx=%d, tx=%d\n",
4264 * First, get the maximum gears of HS speed.
4265 * If a zero value, it means there is no HSGEAR capability.
4266 * Then, get the maximum gears of PWM speed.
4268 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_MAXRXHSGEAR), &pwr_info->gear_rx);
4269 if (!pwr_info->gear_rx) {
4270 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_MAXRXPWMGEAR),
4271 &pwr_info->gear_rx);
4272 if (!pwr_info->gear_rx) {
4273 dev_err(hba->dev, "%s: invalid max pwm rx gear read = %d\n",
4274 __func__, pwr_info->gear_rx);
4277 pwr_info->pwr_rx = SLOW_MODE;
4280 ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_MAXRXHSGEAR),
4281 &pwr_info->gear_tx);
4282 if (!pwr_info->gear_tx) {
4283 ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_MAXRXPWMGEAR),
4284 &pwr_info->gear_tx);
4285 if (!pwr_info->gear_tx) {
4286 dev_err(hba->dev, "%s: invalid max pwm tx gear read = %d\n",
4287 __func__, pwr_info->gear_tx);
4290 pwr_info->pwr_tx = SLOW_MODE;
4293 hba->max_pwr_info.is_valid = true;
4297 static int ufshcd_change_power_mode(struct ufs_hba *hba,
4298 struct ufs_pa_layer_attr *pwr_mode)
4302 /* if already configured to the requested pwr_mode */
4303 if (!hba->force_pmc &&
4304 pwr_mode->gear_rx == hba->pwr_info.gear_rx &&
4305 pwr_mode->gear_tx == hba->pwr_info.gear_tx &&
4306 pwr_mode->lane_rx == hba->pwr_info.lane_rx &&
4307 pwr_mode->lane_tx == hba->pwr_info.lane_tx &&
4308 pwr_mode->pwr_rx == hba->pwr_info.pwr_rx &&
4309 pwr_mode->pwr_tx == hba->pwr_info.pwr_tx &&
4310 pwr_mode->hs_rate == hba->pwr_info.hs_rate) {
4311 dev_dbg(hba->dev, "%s: power already configured\n", __func__);
4316 * Configure attributes for power mode change with below.
4317 * - PA_RXGEAR, PA_ACTIVERXDATALANES, PA_RXTERMINATION,
4318 * - PA_TXGEAR, PA_ACTIVETXDATALANES, PA_TXTERMINATION,
4321 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_RXGEAR), pwr_mode->gear_rx);
4322 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_ACTIVERXDATALANES),
4324 if (pwr_mode->pwr_rx == FASTAUTO_MODE ||
4325 pwr_mode->pwr_rx == FAST_MODE)
4326 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_RXTERMINATION), TRUE);
4328 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_RXTERMINATION), FALSE);
4330 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TXGEAR), pwr_mode->gear_tx);
4331 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_ACTIVETXDATALANES),
4333 if (pwr_mode->pwr_tx == FASTAUTO_MODE ||
4334 pwr_mode->pwr_tx == FAST_MODE)
4335 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TXTERMINATION), TRUE);
4337 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TXTERMINATION), FALSE);
4339 if (pwr_mode->pwr_rx == FASTAUTO_MODE ||
4340 pwr_mode->pwr_tx == FASTAUTO_MODE ||
4341 pwr_mode->pwr_rx == FAST_MODE ||
4342 pwr_mode->pwr_tx == FAST_MODE)
4343 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_HSSERIES),
4346 if (!(hba->quirks & UFSHCD_QUIRK_SKIP_DEF_UNIPRO_TIMEOUT_SETTING)) {
4347 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_PWRMODEUSERDATA0),
4348 DL_FC0ProtectionTimeOutVal_Default);
4349 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_PWRMODEUSERDATA1),
4350 DL_TC0ReplayTimeOutVal_Default);
4351 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_PWRMODEUSERDATA2),
4352 DL_AFC0ReqTimeOutVal_Default);
4353 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_PWRMODEUSERDATA3),
4354 DL_FC1ProtectionTimeOutVal_Default);
4355 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_PWRMODEUSERDATA4),
4356 DL_TC1ReplayTimeOutVal_Default);
4357 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_PWRMODEUSERDATA5),
4358 DL_AFC1ReqTimeOutVal_Default);
4360 ufshcd_dme_set(hba, UIC_ARG_MIB(DME_LocalFC0ProtectionTimeOutVal),
4361 DL_FC0ProtectionTimeOutVal_Default);
4362 ufshcd_dme_set(hba, UIC_ARG_MIB(DME_LocalTC0ReplayTimeOutVal),
4363 DL_TC0ReplayTimeOutVal_Default);
4364 ufshcd_dme_set(hba, UIC_ARG_MIB(DME_LocalAFC0ReqTimeOutVal),
4365 DL_AFC0ReqTimeOutVal_Default);
4368 ret = ufshcd_uic_change_pwr_mode(hba, pwr_mode->pwr_rx << 4
4369 | pwr_mode->pwr_tx);
4373 "%s: power mode change failed %d\n", __func__, ret);
4375 ufshcd_vops_pwr_change_notify(hba, POST_CHANGE, NULL,
4378 memcpy(&hba->pwr_info, pwr_mode,
4379 sizeof(struct ufs_pa_layer_attr));
4386 * ufshcd_config_pwr_mode - configure a new power mode
4387 * @hba: per-adapter instance
4388 * @desired_pwr_mode: desired power configuration
4390 int ufshcd_config_pwr_mode(struct ufs_hba *hba,
4391 struct ufs_pa_layer_attr *desired_pwr_mode)
4393 struct ufs_pa_layer_attr final_params = { 0 };
4396 ret = ufshcd_vops_pwr_change_notify(hba, PRE_CHANGE,
4397 desired_pwr_mode, &final_params);
4400 memcpy(&final_params, desired_pwr_mode, sizeof(final_params));
4402 ret = ufshcd_change_power_mode(hba, &final_params);
4406 EXPORT_SYMBOL_GPL(ufshcd_config_pwr_mode);
4409 * ufshcd_complete_dev_init() - checks device readiness
4410 * @hba: per-adapter instance
4412 * Set fDeviceInit flag and poll until device toggles it.
4414 static int ufshcd_complete_dev_init(struct ufs_hba *hba)
4417 bool flag_res = true;
4420 err = ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_SET_FLAG,
4421 QUERY_FLAG_IDN_FDEVICEINIT, 0, NULL);
4424 "%s setting fDeviceInit flag failed with error %d\n",
4429 /* Poll fDeviceInit flag to be cleared */
4430 timeout = ktime_add_ms(ktime_get(), FDEVICEINIT_COMPL_TIMEOUT);
4432 err = ufshcd_query_flag(hba, UPIU_QUERY_OPCODE_READ_FLAG,
4433 QUERY_FLAG_IDN_FDEVICEINIT, 0, &flag_res);
4436 usleep_range(5000, 10000);
4437 } while (ktime_before(ktime_get(), timeout));
4441 "%s reading fDeviceInit flag failed with error %d\n",
4443 } else if (flag_res) {
4445 "%s fDeviceInit was not cleared by the device\n",
4454 * ufshcd_make_hba_operational - Make UFS controller operational
4455 * @hba: per adapter instance
4457 * To bring UFS host controller to operational state,
4458 * 1. Enable required interrupts
4459 * 2. Configure interrupt aggregation
4460 * 3. Program UTRL and UTMRL base address
4461 * 4. Configure run-stop-registers
4463 * Returns 0 on success, non-zero value on failure
4465 int ufshcd_make_hba_operational(struct ufs_hba *hba)
4470 /* Enable required interrupts */
4471 ufshcd_enable_intr(hba, UFSHCD_ENABLE_INTRS);
4473 /* Configure interrupt aggregation */
4474 if (ufshcd_is_intr_aggr_allowed(hba))
4475 ufshcd_config_intr_aggr(hba, hba->nutrs - 1, INT_AGGR_DEF_TO);
4477 ufshcd_disable_intr_aggr(hba);
4479 /* Configure UTRL and UTMRL base address registers */
4480 ufshcd_writel(hba, lower_32_bits(hba->utrdl_dma_addr),
4481 REG_UTP_TRANSFER_REQ_LIST_BASE_L);
4482 ufshcd_writel(hba, upper_32_bits(hba->utrdl_dma_addr),
4483 REG_UTP_TRANSFER_REQ_LIST_BASE_H);
4484 ufshcd_writel(hba, lower_32_bits(hba->utmrdl_dma_addr),
4485 REG_UTP_TASK_REQ_LIST_BASE_L);
4486 ufshcd_writel(hba, upper_32_bits(hba->utmrdl_dma_addr),
4487 REG_UTP_TASK_REQ_LIST_BASE_H);
4490 * Make sure base address and interrupt setup are updated before
4491 * enabling the run/stop registers below.
4496 * UCRDY, UTMRLDY and UTRLRDY bits must be 1
4498 reg = ufshcd_readl(hba, REG_CONTROLLER_STATUS);
4499 if (!(ufshcd_get_lists_status(reg))) {
4500 ufshcd_enable_run_stop_reg(hba);
4503 "Host controller not ready to process requests");
4509 EXPORT_SYMBOL_GPL(ufshcd_make_hba_operational);
4512 * ufshcd_hba_stop - Send controller to reset state
4513 * @hba: per adapter instance
4515 void ufshcd_hba_stop(struct ufs_hba *hba)
4517 unsigned long flags;
4521 * Obtain the host lock to prevent that the controller is disabled
4522 * while the UFS interrupt handler is active on another CPU.
4524 spin_lock_irqsave(hba->host->host_lock, flags);
4525 ufshcd_writel(hba, CONTROLLER_DISABLE, REG_CONTROLLER_ENABLE);
4526 spin_unlock_irqrestore(hba->host->host_lock, flags);
4528 err = ufshcd_wait_for_register(hba, REG_CONTROLLER_ENABLE,
4529 CONTROLLER_ENABLE, CONTROLLER_DISABLE,
4532 dev_err(hba->dev, "%s: Controller disable failed\n", __func__);
4534 EXPORT_SYMBOL_GPL(ufshcd_hba_stop);
4537 * ufshcd_hba_execute_hce - initialize the controller
4538 * @hba: per adapter instance
4540 * The controller resets itself and controller firmware initialization
4541 * sequence kicks off. When controller is ready it will set
4542 * the Host Controller Enable bit to 1.
4544 * Returns 0 on success, non-zero value on failure
4546 static int ufshcd_hba_execute_hce(struct ufs_hba *hba)
4548 int retry_outer = 3;
4552 if (!ufshcd_is_hba_active(hba))
4553 /* change controller state to "reset state" */
4554 ufshcd_hba_stop(hba);
4556 /* UniPro link is disabled at this point */
4557 ufshcd_set_link_off(hba);
4559 ufshcd_vops_hce_enable_notify(hba, PRE_CHANGE);
4561 /* start controller initialization sequence */
4562 ufshcd_hba_start(hba);
4565 * To initialize a UFS host controller HCE bit must be set to 1.
4566 * During initialization the HCE bit value changes from 1->0->1.
4567 * When the host controller completes initialization sequence
4568 * it sets the value of HCE bit to 1. The same HCE bit is read back
4569 * to check if the controller has completed initialization sequence.
4570 * So without this delay the value HCE = 1, set in the previous
4571 * instruction might be read back.
4572 * This delay can be changed based on the controller.
4574 ufshcd_delay_us(hba->vps->hba_enable_delay_us, 100);
4576 /* wait for the host controller to complete initialization */
4578 while (ufshcd_is_hba_active(hba)) {
4583 "Controller enable failed\n");
4590 usleep_range(1000, 1100);
4593 /* enable UIC related interrupts */
4594 ufshcd_enable_intr(hba, UFSHCD_UIC_MASK);
4596 ufshcd_vops_hce_enable_notify(hba, POST_CHANGE);
4601 int ufshcd_hba_enable(struct ufs_hba *hba)
4605 if (hba->quirks & UFSHCI_QUIRK_BROKEN_HCE) {
4606 ufshcd_set_link_off(hba);
4607 ufshcd_vops_hce_enable_notify(hba, PRE_CHANGE);
4609 /* enable UIC related interrupts */
4610 ufshcd_enable_intr(hba, UFSHCD_UIC_MASK);
4611 ret = ufshcd_dme_reset(hba);
4613 ret = ufshcd_dme_enable(hba);
4615 ufshcd_vops_hce_enable_notify(hba, POST_CHANGE);
4618 "Host controller enable failed with non-hce\n");
4621 ret = ufshcd_hba_execute_hce(hba);
4626 EXPORT_SYMBOL_GPL(ufshcd_hba_enable);
4628 static int ufshcd_disable_tx_lcc(struct ufs_hba *hba, bool peer)
4630 int tx_lanes = 0, i, err = 0;
4633 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_CONNECTEDTXDATALANES),
4636 ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_CONNECTEDTXDATALANES),
4638 for (i = 0; i < tx_lanes; i++) {
4640 err = ufshcd_dme_set(hba,
4641 UIC_ARG_MIB_SEL(TX_LCC_ENABLE,
4642 UIC_ARG_MPHY_TX_GEN_SEL_INDEX(i)),
4645 err = ufshcd_dme_peer_set(hba,
4646 UIC_ARG_MIB_SEL(TX_LCC_ENABLE,
4647 UIC_ARG_MPHY_TX_GEN_SEL_INDEX(i)),
4650 dev_err(hba->dev, "%s: TX LCC Disable failed, peer = %d, lane = %d, err = %d",
4651 __func__, peer, i, err);
4659 static inline int ufshcd_disable_device_tx_lcc(struct ufs_hba *hba)
4661 return ufshcd_disable_tx_lcc(hba, true);
4664 void ufshcd_update_evt_hist(struct ufs_hba *hba, u32 id, u32 val)
4666 struct ufs_event_hist *e;
4668 if (id >= UFS_EVT_CNT)
4671 e = &hba->ufs_stats.event[id];
4672 e->val[e->pos] = val;
4673 e->tstamp[e->pos] = ktime_get();
4675 e->pos = (e->pos + 1) % UFS_EVENT_HIST_LENGTH;
4677 ufshcd_vops_event_notify(hba, id, &val);
4679 EXPORT_SYMBOL_GPL(ufshcd_update_evt_hist);
4682 * ufshcd_link_startup - Initialize unipro link startup
4683 * @hba: per adapter instance
4685 * Returns 0 for success, non-zero in case of failure
4687 static int ufshcd_link_startup(struct ufs_hba *hba)
4690 int retries = DME_LINKSTARTUP_RETRIES;
4691 bool link_startup_again = false;
4694 * If UFS device isn't active then we will have to issue link startup
4695 * 2 times to make sure the device state move to active.
4697 if (!ufshcd_is_ufs_dev_active(hba))
4698 link_startup_again = true;
4702 ufshcd_vops_link_startup_notify(hba, PRE_CHANGE);
4704 ret = ufshcd_dme_link_startup(hba);
4706 /* check if device is detected by inter-connect layer */
4707 if (!ret && !ufshcd_is_device_present(hba)) {
4708 ufshcd_update_evt_hist(hba,
4709 UFS_EVT_LINK_STARTUP_FAIL,
4711 dev_err(hba->dev, "%s: Device not present\n", __func__);
4717 * DME link lost indication is only received when link is up,
4718 * but we can't be sure if the link is up until link startup
4719 * succeeds. So reset the local Uni-Pro and try again.
4721 if (ret && ufshcd_hba_enable(hba)) {
4722 ufshcd_update_evt_hist(hba,
4723 UFS_EVT_LINK_STARTUP_FAIL,
4727 } while (ret && retries--);
4730 /* failed to get the link up... retire */
4731 ufshcd_update_evt_hist(hba,
4732 UFS_EVT_LINK_STARTUP_FAIL,
4737 if (link_startup_again) {
4738 link_startup_again = false;
4739 retries = DME_LINKSTARTUP_RETRIES;
4743 /* Mark that link is up in PWM-G1, 1-lane, SLOW-AUTO mode */
4744 ufshcd_init_pwr_info(hba);
4745 ufshcd_print_pwr_info(hba);
4747 if (hba->quirks & UFSHCD_QUIRK_BROKEN_LCC) {
4748 ret = ufshcd_disable_device_tx_lcc(hba);
4753 /* Include any host controller configuration via UIC commands */
4754 ret = ufshcd_vops_link_startup_notify(hba, POST_CHANGE);
4758 /* Clear UECPA once due to LINERESET has happened during LINK_STARTUP */
4759 ufshcd_readl(hba, REG_UIC_ERROR_CODE_PHY_ADAPTER_LAYER);
4760 ret = ufshcd_make_hba_operational(hba);
4763 dev_err(hba->dev, "link startup failed %d\n", ret);
4764 ufshcd_print_host_state(hba);
4765 ufshcd_print_pwr_info(hba);
4766 ufshcd_print_evt_hist(hba);
4772 * ufshcd_verify_dev_init() - Verify device initialization
4773 * @hba: per-adapter instance
4775 * Send NOP OUT UPIU and wait for NOP IN response to check whether the
4776 * device Transport Protocol (UTP) layer is ready after a reset.
4777 * If the UTP layer at the device side is not initialized, it may
4778 * not respond with NOP IN UPIU within timeout of %NOP_OUT_TIMEOUT
4779 * and we retry sending NOP OUT for %NOP_OUT_RETRIES iterations.
4781 static int ufshcd_verify_dev_init(struct ufs_hba *hba)
4786 ufshcd_hold(hba, false);
4787 mutex_lock(&hba->dev_cmd.lock);
4788 for (retries = NOP_OUT_RETRIES; retries > 0; retries--) {
4789 err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_NOP,
4792 if (!err || err == -ETIMEDOUT)
4795 dev_dbg(hba->dev, "%s: error %d retrying\n", __func__, err);
4797 mutex_unlock(&hba->dev_cmd.lock);
4798 ufshcd_release(hba);
4801 dev_err(hba->dev, "%s: NOP OUT failed %d\n", __func__, err);
4806 * ufshcd_set_queue_depth - set lun queue depth
4807 * @sdev: pointer to SCSI device
4809 * Read bLUQueueDepth value and activate scsi tagged command
4810 * queueing. For WLUN, queue depth is set to 1. For best-effort
4811 * cases (bLUQueueDepth = 0) the queue depth is set to a maximum
4812 * value that host can queue.
4814 static void ufshcd_set_queue_depth(struct scsi_device *sdev)
4818 struct ufs_hba *hba;
4820 hba = shost_priv(sdev->host);
4822 lun_qdepth = hba->nutrs;
4823 ret = ufshcd_read_unit_desc_param(hba,
4824 ufshcd_scsi_to_upiu_lun(sdev->lun),
4825 UNIT_DESC_PARAM_LU_Q_DEPTH,
4827 sizeof(lun_qdepth));
4829 /* Some WLUN doesn't support unit descriptor */
4830 if (ret == -EOPNOTSUPP)
4832 else if (!lun_qdepth)
4833 /* eventually, we can figure out the real queue depth */
4834 lun_qdepth = hba->nutrs;
4836 lun_qdepth = min_t(int, lun_qdepth, hba->nutrs);
4838 dev_dbg(hba->dev, "%s: activate tcq with queue depth %d\n",
4839 __func__, lun_qdepth);
4840 scsi_change_queue_depth(sdev, lun_qdepth);
4844 * ufshcd_get_lu_wp - returns the "b_lu_write_protect" from UNIT DESCRIPTOR
4845 * @hba: per-adapter instance
4846 * @lun: UFS device lun id
4847 * @b_lu_write_protect: pointer to buffer to hold the LU's write protect info
4849 * Returns 0 in case of success and b_lu_write_protect status would be returned
4850 * @b_lu_write_protect parameter.
4851 * Returns -ENOTSUPP if reading b_lu_write_protect is not supported.
4852 * Returns -EINVAL in case of invalid parameters passed to this function.
4854 static int ufshcd_get_lu_wp(struct ufs_hba *hba,
4856 u8 *b_lu_write_protect)
4860 if (!b_lu_write_protect)
4863 * According to UFS device spec, RPMB LU can't be write
4864 * protected so skip reading bLUWriteProtect parameter for
4865 * it. For other W-LUs, UNIT DESCRIPTOR is not available.
4867 else if (lun >= hba->dev_info.max_lu_supported)
4870 ret = ufshcd_read_unit_desc_param(hba,
4872 UNIT_DESC_PARAM_LU_WR_PROTECT,
4874 sizeof(*b_lu_write_protect));
4879 * ufshcd_get_lu_power_on_wp_status - get LU's power on write protect
4881 * @hba: per-adapter instance
4882 * @sdev: pointer to SCSI device
4885 static inline void ufshcd_get_lu_power_on_wp_status(struct ufs_hba *hba,
4886 struct scsi_device *sdev)
4888 if (hba->dev_info.f_power_on_wp_en &&
4889 !hba->dev_info.is_lu_power_on_wp) {
4890 u8 b_lu_write_protect;
4892 if (!ufshcd_get_lu_wp(hba, ufshcd_scsi_to_upiu_lun(sdev->lun),
4893 &b_lu_write_protect) &&
4894 (b_lu_write_protect == UFS_LU_POWER_ON_WP))
4895 hba->dev_info.is_lu_power_on_wp = true;
4900 * ufshcd_setup_links - associate link b/w device wlun and other luns
4901 * @sdev: pointer to SCSI device
4902 * @hba: pointer to ufs hba
4904 static void ufshcd_setup_links(struct ufs_hba *hba, struct scsi_device *sdev)
4906 struct device_link *link;
4909 * Device wlun is the supplier & rest of the luns are consumers.
4910 * This ensures that device wlun suspends after all other luns.
4912 if (hba->sdev_ufs_device) {
4913 link = device_link_add(&sdev->sdev_gendev,
4914 &hba->sdev_ufs_device->sdev_gendev,
4915 DL_FLAG_PM_RUNTIME | DL_FLAG_RPM_ACTIVE);
4917 dev_err(&sdev->sdev_gendev, "Failed establishing link - %s\n",
4918 dev_name(&hba->sdev_ufs_device->sdev_gendev));
4922 /* Ignore REPORT_LUN wlun probing */
4923 if (hba->luns_avail == 1) {
4924 ufshcd_rpm_put(hba);
4929 * Device wlun is probed. The assumption is that WLUNs are
4930 * scanned before other LUNs.
4937 * ufshcd_slave_alloc - handle initial SCSI device configurations
4938 * @sdev: pointer to SCSI device
4942 static int ufshcd_slave_alloc(struct scsi_device *sdev)
4944 struct ufs_hba *hba;
4946 hba = shost_priv(sdev->host);
4948 /* Mode sense(6) is not supported by UFS, so use Mode sense(10) */
4949 sdev->use_10_for_ms = 1;
4951 /* DBD field should be set to 1 in mode sense(10) */
4952 sdev->set_dbd_for_ms = 1;
4954 /* allow SCSI layer to restart the device in case of errors */
4955 sdev->allow_restart = 1;
4957 /* REPORT SUPPORTED OPERATION CODES is not supported */
4958 sdev->no_report_opcodes = 1;
4960 /* WRITE_SAME command is not supported */
4961 sdev->no_write_same = 1;
4963 ufshcd_set_queue_depth(sdev);
4965 ufshcd_get_lu_power_on_wp_status(hba, sdev);
4967 ufshcd_setup_links(hba, sdev);
4973 * ufshcd_change_queue_depth - change queue depth
4974 * @sdev: pointer to SCSI device
4975 * @depth: required depth to set
4977 * Change queue depth and make sure the max. limits are not crossed.
4979 static int ufshcd_change_queue_depth(struct scsi_device *sdev, int depth)
4981 struct ufs_hba *hba = shost_priv(sdev->host);
4983 if (depth > hba->nutrs)
4985 return scsi_change_queue_depth(sdev, depth);
4989 * ufshcd_slave_configure - adjust SCSI device configurations
4990 * @sdev: pointer to SCSI device
4992 static int ufshcd_slave_configure(struct scsi_device *sdev)
4994 struct ufs_hba *hba = shost_priv(sdev->host);
4995 struct request_queue *q = sdev->request_queue;
4997 blk_queue_update_dma_pad(q, PRDT_DATA_BYTE_COUNT_PAD - 1);
4998 if (hba->quirks & UFSHCD_QUIRK_ALIGN_SG_WITH_PAGE_SIZE)
4999 blk_queue_update_dma_alignment(q, PAGE_SIZE - 1);
5001 * Block runtime-pm until all consumers are added.
5002 * Refer ufshcd_setup_links().
5004 if (is_device_wlun(sdev))
5005 pm_runtime_get_noresume(&sdev->sdev_gendev);
5006 else if (ufshcd_is_rpm_autosuspend_allowed(hba))
5007 sdev->rpm_autosuspend = 1;
5009 ufshcd_crypto_setup_rq_keyslot_manager(hba, q);
5015 * ufshcd_slave_destroy - remove SCSI device configurations
5016 * @sdev: pointer to SCSI device
5018 static void ufshcd_slave_destroy(struct scsi_device *sdev)
5020 struct ufs_hba *hba;
5022 hba = shost_priv(sdev->host);
5023 /* Drop the reference as it won't be needed anymore */
5024 if (ufshcd_scsi_to_upiu_lun(sdev->lun) == UFS_UPIU_UFS_DEVICE_WLUN) {
5025 unsigned long flags;
5027 spin_lock_irqsave(hba->host->host_lock, flags);
5028 hba->sdev_ufs_device = NULL;
5029 spin_unlock_irqrestore(hba->host->host_lock, flags);
5034 * ufshcd_scsi_cmd_status - Update SCSI command result based on SCSI status
5035 * @lrbp: pointer to local reference block of completed command
5036 * @scsi_status: SCSI command status
5038 * Returns value base on SCSI command status
5041 ufshcd_scsi_cmd_status(struct ufshcd_lrb *lrbp, int scsi_status)
5045 switch (scsi_status) {
5046 case SAM_STAT_CHECK_CONDITION:
5047 ufshcd_copy_sense_data(lrbp);
5050 result |= DID_OK << 16 | scsi_status;
5052 case SAM_STAT_TASK_SET_FULL:
5054 case SAM_STAT_TASK_ABORTED:
5055 ufshcd_copy_sense_data(lrbp);
5056 result |= scsi_status;
5059 result |= DID_ERROR << 16;
5061 } /* end of switch */
5067 * ufshcd_transfer_rsp_status - Get overall status of the response
5068 * @hba: per adapter instance
5069 * @lrbp: pointer to local reference block of completed command
5071 * Returns result of the command to notify SCSI midlayer
5074 ufshcd_transfer_rsp_status(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
5080 /* overall command status of utrd */
5081 ocs = ufshcd_get_tr_ocs(lrbp);
5083 if (hba->quirks & UFSHCD_QUIRK_BROKEN_OCS_FATAL_ERROR) {
5084 if (be32_to_cpu(lrbp->ucd_rsp_ptr->header.dword_1) &
5085 MASK_RSP_UPIU_RESULT)
5091 result = ufshcd_get_req_rsp(lrbp->ucd_rsp_ptr);
5092 hba->ufs_stats.last_hibern8_exit_tstamp = ktime_set(0, 0);
5094 case UPIU_TRANSACTION_RESPONSE:
5096 * get the response UPIU result to extract
5097 * the SCSI command status
5099 result = ufshcd_get_rsp_upiu_result(lrbp->ucd_rsp_ptr);
5102 * get the result based on SCSI status response
5103 * to notify the SCSI midlayer of the command status
5105 scsi_status = result & MASK_SCSI_STATUS;
5106 result = ufshcd_scsi_cmd_status(lrbp, scsi_status);
5109 * Currently we are only supporting BKOPs exception
5110 * events hence we can ignore BKOPs exception event
5111 * during power management callbacks. BKOPs exception
5112 * event is not expected to be raised in runtime suspend
5113 * callback as it allows the urgent bkops.
5114 * During system suspend, we are anyway forcefully
5115 * disabling the bkops and if urgent bkops is needed
5116 * it will be enabled on system resume. Long term
5117 * solution could be to abort the system suspend if
5118 * UFS device needs urgent BKOPs.
5120 if (!hba->pm_op_in_progress &&
5121 !ufshcd_eh_in_progress(hba) &&
5122 ufshcd_is_exception_event(lrbp->ucd_rsp_ptr))
5123 /* Flushed in suspend */
5124 schedule_work(&hba->eeh_work);
5126 case UPIU_TRANSACTION_REJECT_UPIU:
5127 /* TODO: handle Reject UPIU Response */
5128 result = DID_ERROR << 16;
5130 "Reject UPIU not fully implemented\n");
5134 "Unexpected request response code = %x\n",
5136 result = DID_ERROR << 16;
5141 result |= DID_ABORT << 16;
5143 case OCS_INVALID_COMMAND_STATUS:
5144 result |= DID_REQUEUE << 16;
5146 case OCS_INVALID_CMD_TABLE_ATTR:
5147 case OCS_INVALID_PRDT_ATTR:
5148 case OCS_MISMATCH_DATA_BUF_SIZE:
5149 case OCS_MISMATCH_RESP_UPIU_SIZE:
5150 case OCS_PEER_COMM_FAILURE:
5151 case OCS_FATAL_ERROR:
5152 case OCS_DEVICE_FATAL_ERROR:
5153 case OCS_INVALID_CRYPTO_CONFIG:
5154 case OCS_GENERAL_CRYPTO_ERROR:
5156 result |= DID_ERROR << 16;
5158 "OCS error from controller = %x for tag %d\n",
5159 ocs, lrbp->task_tag);
5160 ufshcd_print_evt_hist(hba);
5161 ufshcd_print_host_state(hba);
5163 } /* end of switch */
5165 if ((host_byte(result) != DID_OK) &&
5166 (host_byte(result) != DID_REQUEUE) && !hba->silence_err_logs)
5167 ufshcd_print_trs(hba, 1 << lrbp->task_tag, true);
5171 static bool ufshcd_is_auto_hibern8_error(struct ufs_hba *hba,
5174 if (!ufshcd_is_auto_hibern8_supported(hba) ||
5175 !ufshcd_is_auto_hibern8_enabled(hba))
5178 if (!(intr_mask & UFSHCD_UIC_HIBERN8_MASK))
5181 if (hba->active_uic_cmd &&
5182 (hba->active_uic_cmd->command == UIC_CMD_DME_HIBER_ENTER ||
5183 hba->active_uic_cmd->command == UIC_CMD_DME_HIBER_EXIT))
5190 * ufshcd_uic_cmd_compl - handle completion of uic command
5191 * @hba: per adapter instance
5192 * @intr_status: interrupt status generated by the controller
5195 * IRQ_HANDLED - If interrupt is valid
5196 * IRQ_NONE - If invalid interrupt
5198 static irqreturn_t ufshcd_uic_cmd_compl(struct ufs_hba *hba, u32 intr_status)
5200 irqreturn_t retval = IRQ_NONE;
5202 spin_lock(hba->host->host_lock);
5203 if (ufshcd_is_auto_hibern8_error(hba, intr_status))
5204 hba->errors |= (UFSHCD_UIC_HIBERN8_MASK & intr_status);
5206 if ((intr_status & UIC_COMMAND_COMPL) && hba->active_uic_cmd) {
5207 hba->active_uic_cmd->argument2 |=
5208 ufshcd_get_uic_cmd_result(hba);
5209 hba->active_uic_cmd->argument3 =
5210 ufshcd_get_dme_attr_val(hba);
5211 if (!hba->uic_async_done)
5212 hba->active_uic_cmd->cmd_active = 0;
5213 complete(&hba->active_uic_cmd->done);
5214 retval = IRQ_HANDLED;
5217 if ((intr_status & UFSHCD_UIC_PWR_MASK) && hba->uic_async_done) {
5218 hba->active_uic_cmd->cmd_active = 0;
5219 complete(hba->uic_async_done);
5220 retval = IRQ_HANDLED;
5223 if (retval == IRQ_HANDLED)
5224 ufshcd_add_uic_command_trace(hba, hba->active_uic_cmd,
5226 spin_unlock(hba->host->host_lock);
5231 * __ufshcd_transfer_req_compl - handle SCSI and query command completion
5232 * @hba: per adapter instance
5233 * @completed_reqs: requests to complete
5235 static void __ufshcd_transfer_req_compl(struct ufs_hba *hba,
5236 unsigned long completed_reqs)
5238 struct ufshcd_lrb *lrbp;
5239 struct scsi_cmnd *cmd;
5242 bool update_scaling = false;
5244 for_each_set_bit(index, &completed_reqs, hba->nutrs) {
5245 if (!test_and_clear_bit(index, &hba->outstanding_reqs))
5247 lrbp = &hba->lrb[index];
5248 lrbp->compl_time_stamp = ktime_get();
5251 if (unlikely(ufshcd_should_inform_monitor(hba, lrbp)))
5252 ufshcd_update_monitor(hba, lrbp);
5253 ufshcd_add_command_trace(hba, index, UFS_CMD_COMP);
5254 result = ufshcd_transfer_rsp_status(hba, lrbp);
5255 scsi_dma_unmap(cmd);
5256 cmd->result = result;
5257 /* Mark completed command as NULL in LRB */
5259 /* Do not touch lrbp after scsi done */
5260 cmd->scsi_done(cmd);
5261 ufshcd_release(hba);
5262 update_scaling = true;
5263 } else if (lrbp->command_type == UTP_CMD_TYPE_DEV_MANAGE ||
5264 lrbp->command_type == UTP_CMD_TYPE_UFS_STORAGE) {
5265 if (hba->dev_cmd.complete) {
5266 ufshcd_add_command_trace(hba, index,
5268 complete(hba->dev_cmd.complete);
5269 update_scaling = true;
5273 ufshcd_clk_scaling_update_busy(hba);
5278 * ufshcd_trc_handler - handle transfer requests completion
5279 * @hba: per adapter instance
5280 * @use_utrlcnr: get completed requests from UTRLCNR
5283 * IRQ_HANDLED - If interrupt is valid
5284 * IRQ_NONE - If invalid interrupt
5286 static irqreturn_t ufshcd_trc_handler(struct ufs_hba *hba, bool use_utrlcnr)
5288 unsigned long completed_reqs = 0;
5290 /* Resetting interrupt aggregation counters first and reading the
5291 * DOOR_BELL afterward allows us to handle all the completed requests.
5292 * In order to prevent other interrupts starvation the DB is read once
5293 * after reset. The down side of this solution is the possibility of
5294 * false interrupt if device completes another request after resetting
5295 * aggregation and before reading the DB.
5297 if (ufshcd_is_intr_aggr_allowed(hba) &&
5298 !(hba->quirks & UFSHCI_QUIRK_SKIP_RESET_INTR_AGGR))
5299 ufshcd_reset_intr_aggr(hba);
5304 utrlcnr = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_LIST_COMPL);
5306 ufshcd_writel(hba, utrlcnr,
5307 REG_UTP_TRANSFER_REQ_LIST_COMPL);
5308 completed_reqs = utrlcnr;
5311 unsigned long flags;
5314 spin_lock_irqsave(hba->host->host_lock, flags);
5315 tr_doorbell = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
5316 completed_reqs = tr_doorbell ^ hba->outstanding_reqs;
5317 spin_unlock_irqrestore(hba->host->host_lock, flags);
5320 if (completed_reqs) {
5321 __ufshcd_transfer_req_compl(hba, completed_reqs);
5328 int __ufshcd_write_ee_control(struct ufs_hba *hba, u32 ee_ctrl_mask)
5330 return ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_WRITE_ATTR,
5331 QUERY_ATTR_IDN_EE_CONTROL, 0, 0,
5335 int ufshcd_write_ee_control(struct ufs_hba *hba)
5339 mutex_lock(&hba->ee_ctrl_mutex);
5340 err = __ufshcd_write_ee_control(hba, hba->ee_ctrl_mask);
5341 mutex_unlock(&hba->ee_ctrl_mutex);
5343 dev_err(hba->dev, "%s: failed to write ee control %d\n",
5348 int ufshcd_update_ee_control(struct ufs_hba *hba, u16 *mask, u16 *other_mask,
5351 u16 new_mask, ee_ctrl_mask;
5354 mutex_lock(&hba->ee_ctrl_mutex);
5355 new_mask = (*mask & ~clr) | set;
5356 ee_ctrl_mask = new_mask | *other_mask;
5357 if (ee_ctrl_mask != hba->ee_ctrl_mask)
5358 err = __ufshcd_write_ee_control(hba, ee_ctrl_mask);
5359 /* Still need to update 'mask' even if 'ee_ctrl_mask' was unchanged */
5361 hba->ee_ctrl_mask = ee_ctrl_mask;
5364 mutex_unlock(&hba->ee_ctrl_mutex);
5369 * ufshcd_disable_ee - disable exception event
5370 * @hba: per-adapter instance
5371 * @mask: exception event to disable
5373 * Disables exception event in the device so that the EVENT_ALERT
5376 * Returns zero on success, non-zero error value on failure.
5378 static inline int ufshcd_disable_ee(struct ufs_hba *hba, u16 mask)
5380 return ufshcd_update_ee_drv_mask(hba, 0, mask);
5384 * ufshcd_enable_ee - enable exception event
5385 * @hba: per-adapter instance
5386 * @mask: exception event to enable
5388 * Enable corresponding exception event in the device to allow
5389 * device to alert host in critical scenarios.
5391 * Returns zero on success, non-zero error value on failure.
5393 static inline int ufshcd_enable_ee(struct ufs_hba *hba, u16 mask)
5395 return ufshcd_update_ee_drv_mask(hba, mask, 0);
5399 * ufshcd_enable_auto_bkops - Allow device managed BKOPS
5400 * @hba: per-adapter instance
5402 * Allow device to manage background operations on its own. Enabling
5403 * this might lead to inconsistent latencies during normal data transfers
5404 * as the device is allowed to manage its own way of handling background
5407 * Returns zero on success, non-zero on failure.
5409 static int ufshcd_enable_auto_bkops(struct ufs_hba *hba)
5413 if (hba->auto_bkops_enabled)
5416 err = ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_SET_FLAG,
5417 QUERY_FLAG_IDN_BKOPS_EN, 0, NULL);
5419 dev_err(hba->dev, "%s: failed to enable bkops %d\n",
5424 hba->auto_bkops_enabled = true;
5425 trace_ufshcd_auto_bkops_state(dev_name(hba->dev), "Enabled");
5427 /* No need of URGENT_BKOPS exception from the device */
5428 err = ufshcd_disable_ee(hba, MASK_EE_URGENT_BKOPS);
5430 dev_err(hba->dev, "%s: failed to disable exception event %d\n",
5437 * ufshcd_disable_auto_bkops - block device in doing background operations
5438 * @hba: per-adapter instance
5440 * Disabling background operations improves command response latency but
5441 * has drawback of device moving into critical state where the device is
5442 * not-operable. Make sure to call ufshcd_enable_auto_bkops() whenever the
5443 * host is idle so that BKOPS are managed effectively without any negative
5446 * Returns zero on success, non-zero on failure.
5448 static int ufshcd_disable_auto_bkops(struct ufs_hba *hba)
5452 if (!hba->auto_bkops_enabled)
5456 * If host assisted BKOPs is to be enabled, make sure
5457 * urgent bkops exception is allowed.
5459 err = ufshcd_enable_ee(hba, MASK_EE_URGENT_BKOPS);
5461 dev_err(hba->dev, "%s: failed to enable exception event %d\n",
5466 err = ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_CLEAR_FLAG,
5467 QUERY_FLAG_IDN_BKOPS_EN, 0, NULL);
5469 dev_err(hba->dev, "%s: failed to disable bkops %d\n",
5471 ufshcd_disable_ee(hba, MASK_EE_URGENT_BKOPS);
5475 hba->auto_bkops_enabled = false;
5476 trace_ufshcd_auto_bkops_state(dev_name(hba->dev), "Disabled");
5477 hba->is_urgent_bkops_lvl_checked = false;
5483 * ufshcd_force_reset_auto_bkops - force reset auto bkops state
5484 * @hba: per adapter instance
5486 * After a device reset the device may toggle the BKOPS_EN flag
5487 * to default value. The s/w tracking variables should be updated
5488 * as well. This function would change the auto-bkops state based on
5489 * UFSHCD_CAP_KEEP_AUTO_BKOPS_ENABLED_EXCEPT_SUSPEND.
5491 static void ufshcd_force_reset_auto_bkops(struct ufs_hba *hba)
5493 if (ufshcd_keep_autobkops_enabled_except_suspend(hba)) {
5494 hba->auto_bkops_enabled = false;
5495 hba->ee_ctrl_mask |= MASK_EE_URGENT_BKOPS;
5496 ufshcd_enable_auto_bkops(hba);
5498 hba->auto_bkops_enabled = true;
5499 hba->ee_ctrl_mask &= ~MASK_EE_URGENT_BKOPS;
5500 ufshcd_disable_auto_bkops(hba);
5502 hba->urgent_bkops_lvl = BKOPS_STATUS_PERF_IMPACT;
5503 hba->is_urgent_bkops_lvl_checked = false;
5506 static inline int ufshcd_get_bkops_status(struct ufs_hba *hba, u32 *status)
5508 return ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
5509 QUERY_ATTR_IDN_BKOPS_STATUS, 0, 0, status);
5513 * ufshcd_bkops_ctrl - control the auto bkops based on current bkops status
5514 * @hba: per-adapter instance
5515 * @status: bkops_status value
5517 * Read the bkops_status from the UFS device and Enable fBackgroundOpsEn
5518 * flag in the device to permit background operations if the device
5519 * bkops_status is greater than or equal to "status" argument passed to
5520 * this function, disable otherwise.
5522 * Returns 0 for success, non-zero in case of failure.
5524 * NOTE: Caller of this function can check the "hba->auto_bkops_enabled" flag
5525 * to know whether auto bkops is enabled or disabled after this function
5526 * returns control to it.
5528 static int ufshcd_bkops_ctrl(struct ufs_hba *hba,
5529 enum bkops_status status)
5532 u32 curr_status = 0;
5534 err = ufshcd_get_bkops_status(hba, &curr_status);
5536 dev_err(hba->dev, "%s: failed to get BKOPS status %d\n",
5539 } else if (curr_status > BKOPS_STATUS_MAX) {
5540 dev_err(hba->dev, "%s: invalid BKOPS status %d\n",
5541 __func__, curr_status);
5546 if (curr_status >= status)
5547 err = ufshcd_enable_auto_bkops(hba);
5549 err = ufshcd_disable_auto_bkops(hba);
5555 * ufshcd_urgent_bkops - handle urgent bkops exception event
5556 * @hba: per-adapter instance
5558 * Enable fBackgroundOpsEn flag in the device to permit background
5561 * If BKOPs is enabled, this function returns 0, 1 if the bkops in not enabled
5562 * and negative error value for any other failure.
5564 static int ufshcd_urgent_bkops(struct ufs_hba *hba)
5566 return ufshcd_bkops_ctrl(hba, hba->urgent_bkops_lvl);
5569 static inline int ufshcd_get_ee_status(struct ufs_hba *hba, u32 *status)
5571 return ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
5572 QUERY_ATTR_IDN_EE_STATUS, 0, 0, status);
5575 static void ufshcd_bkops_exception_event_handler(struct ufs_hba *hba)
5578 u32 curr_status = 0;
5580 if (hba->is_urgent_bkops_lvl_checked)
5581 goto enable_auto_bkops;
5583 err = ufshcd_get_bkops_status(hba, &curr_status);
5585 dev_err(hba->dev, "%s: failed to get BKOPS status %d\n",
5591 * We are seeing that some devices are raising the urgent bkops
5592 * exception events even when BKOPS status doesn't indicate performace
5593 * impacted or critical. Handle these device by determining their urgent
5594 * bkops status at runtime.
5596 if (curr_status < BKOPS_STATUS_PERF_IMPACT) {
5597 dev_err(hba->dev, "%s: device raised urgent BKOPS exception for bkops status %d\n",
5598 __func__, curr_status);
5599 /* update the current status as the urgent bkops level */
5600 hba->urgent_bkops_lvl = curr_status;
5601 hba->is_urgent_bkops_lvl_checked = true;
5605 err = ufshcd_enable_auto_bkops(hba);
5608 dev_err(hba->dev, "%s: failed to handle urgent bkops %d\n",
5612 static int __ufshcd_wb_toggle(struct ufs_hba *hba, bool set, enum flag_idn idn)
5615 enum query_opcode opcode = set ? UPIU_QUERY_OPCODE_SET_FLAG :
5616 UPIU_QUERY_OPCODE_CLEAR_FLAG;
5618 index = ufshcd_wb_get_query_index(hba);
5619 return ufshcd_query_flag_retry(hba, opcode, idn, index, NULL);
5622 int ufshcd_wb_toggle(struct ufs_hba *hba, bool enable)
5626 if (!ufshcd_is_wb_allowed(hba))
5629 if (!(enable ^ hba->dev_info.wb_enabled))
5632 ret = __ufshcd_wb_toggle(hba, enable, QUERY_FLAG_IDN_WB_EN);
5634 dev_err(hba->dev, "%s Write Booster %s failed %d\n",
5635 __func__, enable ? "enable" : "disable", ret);
5639 hba->dev_info.wb_enabled = enable;
5640 dev_info(hba->dev, "%s Write Booster %s\n",
5641 __func__, enable ? "enabled" : "disabled");
5646 static void ufshcd_wb_toggle_flush_during_h8(struct ufs_hba *hba, bool set)
5650 ret = __ufshcd_wb_toggle(hba, set,
5651 QUERY_FLAG_IDN_WB_BUFF_FLUSH_DURING_HIBERN8);
5653 dev_err(hba->dev, "%s: WB-Buf Flush during H8 %s failed: %d\n",
5654 __func__, set ? "enable" : "disable", ret);
5657 dev_dbg(hba->dev, "%s WB-Buf Flush during H8 %s\n",
5658 __func__, set ? "enabled" : "disabled");
5661 static inline void ufshcd_wb_toggle_flush(struct ufs_hba *hba, bool enable)
5665 if (!ufshcd_is_wb_allowed(hba) ||
5666 hba->dev_info.wb_buf_flush_enabled == enable)
5669 ret = __ufshcd_wb_toggle(hba, enable, QUERY_FLAG_IDN_WB_BUFF_FLUSH_EN);
5671 dev_err(hba->dev, "%s WB-Buf Flush %s failed %d\n", __func__,
5672 enable ? "enable" : "disable", ret);
5676 hba->dev_info.wb_buf_flush_enabled = enable;
5678 dev_dbg(hba->dev, "%s WB-Buf Flush %s\n",
5679 __func__, enable ? "enabled" : "disabled");
5682 static bool ufshcd_wb_presrv_usrspc_keep_vcc_on(struct ufs_hba *hba,
5689 index = ufshcd_wb_get_query_index(hba);
5690 ret = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
5691 QUERY_ATTR_IDN_CURR_WB_BUFF_SIZE,
5692 index, 0, &cur_buf);
5694 dev_err(hba->dev, "%s dCurWriteBoosterBufferSize read failed %d\n",
5700 dev_info(hba->dev, "dCurWBBuf: %d WB disabled until free-space is available\n",
5704 /* Let it continue to flush when available buffer exceeds threshold */
5705 if (avail_buf < hba->vps->wb_flush_threshold)
5711 static bool ufshcd_wb_need_flush(struct ufs_hba *hba)
5717 if (!ufshcd_is_wb_allowed(hba))
5720 * The ufs device needs the vcc to be ON to flush.
5721 * With user-space reduction enabled, it's enough to enable flush
5722 * by checking only the available buffer. The threshold
5723 * defined here is > 90% full.
5724 * With user-space preserved enabled, the current-buffer
5725 * should be checked too because the wb buffer size can reduce
5726 * when disk tends to be full. This info is provided by current
5727 * buffer (dCurrentWriteBoosterBufferSize). There's no point in
5728 * keeping vcc on when current buffer is empty.
5730 index = ufshcd_wb_get_query_index(hba);
5731 ret = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
5732 QUERY_ATTR_IDN_AVAIL_WB_BUFF_SIZE,
5733 index, 0, &avail_buf);
5735 dev_warn(hba->dev, "%s dAvailableWriteBoosterBufferSize read failed %d\n",
5740 if (!hba->dev_info.b_presrv_uspc_en) {
5741 if (avail_buf <= UFS_WB_BUF_REMAIN_PERCENT(10))
5746 return ufshcd_wb_presrv_usrspc_keep_vcc_on(hba, avail_buf);
5749 static void ufshcd_rpm_dev_flush_recheck_work(struct work_struct *work)
5751 struct ufs_hba *hba = container_of(to_delayed_work(work),
5753 rpm_dev_flush_recheck_work);
5755 * To prevent unnecessary VCC power drain after device finishes
5756 * WriteBooster buffer flush or Auto BKOPs, force runtime resume
5757 * after a certain delay to recheck the threshold by next runtime
5760 ufshcd_rpm_get_sync(hba);
5761 ufshcd_rpm_put_sync(hba);
5765 * ufshcd_exception_event_handler - handle exceptions raised by device
5766 * @work: pointer to work data
5768 * Read bExceptionEventStatus attribute from the device and handle the
5769 * exception event accordingly.
5771 static void ufshcd_exception_event_handler(struct work_struct *work)
5773 struct ufs_hba *hba;
5776 hba = container_of(work, struct ufs_hba, eeh_work);
5778 ufshcd_scsi_block_requests(hba);
5779 err = ufshcd_get_ee_status(hba, &status);
5781 dev_err(hba->dev, "%s: failed to get exception status %d\n",
5786 trace_ufshcd_exception_event(dev_name(hba->dev), status);
5788 if (status & hba->ee_drv_mask & MASK_EE_URGENT_BKOPS)
5789 ufshcd_bkops_exception_event_handler(hba);
5791 ufs_debugfs_exception_event(hba, status);
5793 ufshcd_scsi_unblock_requests(hba);
5797 /* Complete requests that have door-bell cleared */
5798 static void ufshcd_complete_requests(struct ufs_hba *hba)
5800 ufshcd_trc_handler(hba, false);
5801 ufshcd_tmc_handler(hba);
5805 * ufshcd_quirk_dl_nac_errors - This function checks if error handling is
5806 * to recover from the DL NAC errors or not.
5807 * @hba: per-adapter instance
5809 * Returns true if error handling is required, false otherwise
5811 static bool ufshcd_quirk_dl_nac_errors(struct ufs_hba *hba)
5813 unsigned long flags;
5814 bool err_handling = true;
5816 spin_lock_irqsave(hba->host->host_lock, flags);
5818 * UFS_DEVICE_QUIRK_RECOVERY_FROM_DL_NAC_ERRORS only workaround the
5819 * device fatal error and/or DL NAC & REPLAY timeout errors.
5821 if (hba->saved_err & (CONTROLLER_FATAL_ERROR | SYSTEM_BUS_FATAL_ERROR))
5824 if ((hba->saved_err & DEVICE_FATAL_ERROR) ||
5825 ((hba->saved_err & UIC_ERROR) &&
5826 (hba->saved_uic_err & UFSHCD_UIC_DL_TCx_REPLAY_ERROR)))
5829 if ((hba->saved_err & UIC_ERROR) &&
5830 (hba->saved_uic_err & UFSHCD_UIC_DL_NAC_RECEIVED_ERROR)) {
5833 * wait for 50ms to see if we can get any other errors or not.
5835 spin_unlock_irqrestore(hba->host->host_lock, flags);
5837 spin_lock_irqsave(hba->host->host_lock, flags);
5840 * now check if we have got any other severe errors other than
5843 if ((hba->saved_err & INT_FATAL_ERRORS) ||
5844 ((hba->saved_err & UIC_ERROR) &&
5845 (hba->saved_uic_err & ~UFSHCD_UIC_DL_NAC_RECEIVED_ERROR)))
5849 * As DL NAC is the only error received so far, send out NOP
5850 * command to confirm if link is still active or not.
5851 * - If we don't get any response then do error recovery.
5852 * - If we get response then clear the DL NAC error bit.
5855 spin_unlock_irqrestore(hba->host->host_lock, flags);
5856 err = ufshcd_verify_dev_init(hba);
5857 spin_lock_irqsave(hba->host->host_lock, flags);
5862 /* Link seems to be alive hence ignore the DL NAC errors */
5863 if (hba->saved_uic_err == UFSHCD_UIC_DL_NAC_RECEIVED_ERROR)
5864 hba->saved_err &= ~UIC_ERROR;
5865 /* clear NAC error */
5866 hba->saved_uic_err &= ~UFSHCD_UIC_DL_NAC_RECEIVED_ERROR;
5867 if (!hba->saved_uic_err)
5868 err_handling = false;
5871 spin_unlock_irqrestore(hba->host->host_lock, flags);
5872 return err_handling;
5875 /* host lock must be held before calling this func */
5876 static inline bool ufshcd_is_saved_err_fatal(struct ufs_hba *hba)
5878 return (hba->saved_uic_err & UFSHCD_UIC_DL_PA_INIT_ERROR) ||
5879 (hba->saved_err & (INT_FATAL_ERRORS | UFSHCD_UIC_HIBERN8_MASK));
5882 /* host lock must be held before calling this func */
5883 static inline void ufshcd_schedule_eh_work(struct ufs_hba *hba)
5885 /* handle fatal errors only when link is not in error state */
5886 if (hba->ufshcd_state != UFSHCD_STATE_ERROR) {
5887 if (hba->force_reset || ufshcd_is_link_broken(hba) ||
5888 ufshcd_is_saved_err_fatal(hba))
5889 hba->ufshcd_state = UFSHCD_STATE_EH_SCHEDULED_FATAL;
5891 hba->ufshcd_state = UFSHCD_STATE_EH_SCHEDULED_NON_FATAL;
5892 queue_work(hba->eh_wq, &hba->eh_work);
5896 static void ufshcd_clk_scaling_allow(struct ufs_hba *hba, bool allow)
5898 down_write(&hba->clk_scaling_lock);
5899 hba->clk_scaling.is_allowed = allow;
5900 up_write(&hba->clk_scaling_lock);
5903 static void ufshcd_clk_scaling_suspend(struct ufs_hba *hba, bool suspend)
5906 if (hba->clk_scaling.is_enabled)
5907 ufshcd_suspend_clkscaling(hba);
5908 ufshcd_clk_scaling_allow(hba, false);
5910 ufshcd_clk_scaling_allow(hba, true);
5911 if (hba->clk_scaling.is_enabled)
5912 ufshcd_resume_clkscaling(hba);
5916 static void ufshcd_err_handling_prepare(struct ufs_hba *hba)
5918 ufshcd_rpm_get_sync(hba);
5919 if (pm_runtime_status_suspended(&hba->sdev_ufs_device->sdev_gendev) ||
5920 hba->is_sys_suspended) {
5921 enum ufs_pm_op pm_op;
5924 * Don't assume anything of resume, if
5925 * resume fails, irq and clocks can be OFF, and powers
5926 * can be OFF or in LPM.
5928 ufshcd_setup_hba_vreg(hba, true);
5929 ufshcd_enable_irq(hba);
5930 ufshcd_setup_vreg(hba, true);
5931 ufshcd_config_vreg_hpm(hba, hba->vreg_info.vccq);
5932 ufshcd_config_vreg_hpm(hba, hba->vreg_info.vccq2);
5933 ufshcd_hold(hba, false);
5934 if (!ufshcd_is_clkgating_allowed(hba))
5935 ufshcd_setup_clocks(hba, true);
5936 ufshcd_release(hba);
5937 pm_op = hba->is_sys_suspended ? UFS_SYSTEM_PM : UFS_RUNTIME_PM;
5938 ufshcd_vops_resume(hba, pm_op);
5940 ufshcd_hold(hba, false);
5941 if (ufshcd_is_clkscaling_supported(hba) &&
5942 hba->clk_scaling.is_enabled)
5943 ufshcd_suspend_clkscaling(hba);
5944 ufshcd_clk_scaling_allow(hba, false);
5946 ufshcd_scsi_block_requests(hba);
5947 /* Drain ufshcd_queuecommand() */
5948 down_write(&hba->clk_scaling_lock);
5949 up_write(&hba->clk_scaling_lock);
5950 cancel_work_sync(&hba->eeh_work);
5953 static void ufshcd_err_handling_unprepare(struct ufs_hba *hba)
5955 ufshcd_scsi_unblock_requests(hba);
5956 ufshcd_release(hba);
5957 if (ufshcd_is_clkscaling_supported(hba))
5958 ufshcd_clk_scaling_suspend(hba, false);
5959 ufshcd_clear_ua_wluns(hba);
5960 ufshcd_rpm_put(hba);
5963 static inline bool ufshcd_err_handling_should_stop(struct ufs_hba *hba)
5965 return (!hba->is_powered || hba->shutting_down ||
5966 !hba->sdev_ufs_device ||
5967 hba->ufshcd_state == UFSHCD_STATE_ERROR ||
5968 (!(hba->saved_err || hba->saved_uic_err || hba->force_reset ||
5969 ufshcd_is_link_broken(hba))));
5973 static void ufshcd_recover_pm_error(struct ufs_hba *hba)
5975 struct Scsi_Host *shost = hba->host;
5976 struct scsi_device *sdev;
5977 struct request_queue *q;
5980 hba->is_sys_suspended = false;
5982 * Set RPM status of wlun device to RPM_ACTIVE,
5983 * this also clears its runtime error.
5985 ret = pm_runtime_set_active(&hba->sdev_ufs_device->sdev_gendev);
5987 /* hba device might have a runtime error otherwise */
5989 ret = pm_runtime_set_active(hba->dev);
5991 * If wlun device had runtime error, we also need to resume those
5992 * consumer scsi devices in case any of them has failed to be
5993 * resumed due to supplier runtime resume failure. This is to unblock
5994 * blk_queue_enter in case there are bios waiting inside it.
5997 shost_for_each_device(sdev, shost) {
5998 q = sdev->request_queue;
5999 if (q->dev && (q->rpm_status == RPM_SUSPENDED ||
6000 q->rpm_status == RPM_SUSPENDING))
6001 pm_request_resume(q->dev);
6006 static inline void ufshcd_recover_pm_error(struct ufs_hba *hba)
6011 static bool ufshcd_is_pwr_mode_restore_needed(struct ufs_hba *hba)
6013 struct ufs_pa_layer_attr *pwr_info = &hba->pwr_info;
6016 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_PWRMODE), &mode);
6018 if (pwr_info->pwr_rx != ((mode >> PWRMODE_RX_OFFSET) & PWRMODE_MASK))
6021 if (pwr_info->pwr_tx != (mode & PWRMODE_MASK))
6028 * ufshcd_err_handler - handle UFS errors that require s/w attention
6029 * @work: pointer to work structure
6031 static void ufshcd_err_handler(struct work_struct *work)
6033 struct ufs_hba *hba;
6034 unsigned long flags;
6035 bool err_xfer = false;
6036 bool err_tm = false;
6037 int err = 0, pmc_err;
6039 bool needs_reset = false, needs_restore = false;
6041 hba = container_of(work, struct ufs_hba, eh_work);
6043 down(&hba->host_sem);
6044 spin_lock_irqsave(hba->host->host_lock, flags);
6045 if (ufshcd_err_handling_should_stop(hba)) {
6046 if (hba->ufshcd_state != UFSHCD_STATE_ERROR)
6047 hba->ufshcd_state = UFSHCD_STATE_OPERATIONAL;
6048 spin_unlock_irqrestore(hba->host->host_lock, flags);
6052 ufshcd_set_eh_in_progress(hba);
6053 spin_unlock_irqrestore(hba->host->host_lock, flags);
6054 ufshcd_err_handling_prepare(hba);
6055 /* Complete requests that have door-bell cleared by h/w */
6056 ufshcd_complete_requests(hba);
6057 spin_lock_irqsave(hba->host->host_lock, flags);
6058 if (hba->ufshcd_state != UFSHCD_STATE_ERROR)
6059 hba->ufshcd_state = UFSHCD_STATE_RESET;
6061 * A full reset and restore might have happened after preparation
6062 * is finished, double check whether we should stop.
6064 if (ufshcd_err_handling_should_stop(hba))
6065 goto skip_err_handling;
6067 if (hba->dev_quirks & UFS_DEVICE_QUIRK_RECOVERY_FROM_DL_NAC_ERRORS) {
6070 spin_unlock_irqrestore(hba->host->host_lock, flags);
6071 /* release the lock as ufshcd_quirk_dl_nac_errors() may sleep */
6072 ret = ufshcd_quirk_dl_nac_errors(hba);
6073 spin_lock_irqsave(hba->host->host_lock, flags);
6074 if (!ret && ufshcd_err_handling_should_stop(hba))
6075 goto skip_err_handling;
6078 if ((hba->saved_err & (INT_FATAL_ERRORS | UFSHCD_UIC_HIBERN8_MASK)) ||
6079 (hba->saved_uic_err &&
6080 (hba->saved_uic_err != UFSHCD_UIC_PA_GENERIC_ERROR))) {
6081 bool pr_prdt = !!(hba->saved_err & SYSTEM_BUS_FATAL_ERROR);
6083 spin_unlock_irqrestore(hba->host->host_lock, flags);
6084 ufshcd_print_host_state(hba);
6085 ufshcd_print_pwr_info(hba);
6086 ufshcd_print_evt_hist(hba);
6087 ufshcd_print_tmrs(hba, hba->outstanding_tasks);
6088 ufshcd_print_trs(hba, hba->outstanding_reqs, pr_prdt);
6089 spin_lock_irqsave(hba->host->host_lock, flags);
6093 * if host reset is required then skip clearing the pending
6094 * transfers forcefully because they will get cleared during
6095 * host reset and restore
6097 if (hba->force_reset || ufshcd_is_link_broken(hba) ||
6098 ufshcd_is_saved_err_fatal(hba) ||
6099 ((hba->saved_err & UIC_ERROR) &&
6100 (hba->saved_uic_err & (UFSHCD_UIC_DL_NAC_RECEIVED_ERROR |
6101 UFSHCD_UIC_DL_TCx_REPLAY_ERROR)))) {
6107 * If LINERESET was caught, UFS might have been put to PWM mode,
6108 * check if power mode restore is needed.
6110 if (hba->saved_uic_err & UFSHCD_UIC_PA_GENERIC_ERROR) {
6111 hba->saved_uic_err &= ~UFSHCD_UIC_PA_GENERIC_ERROR;
6112 if (!hba->saved_uic_err)
6113 hba->saved_err &= ~UIC_ERROR;
6114 spin_unlock_irqrestore(hba->host->host_lock, flags);
6115 if (ufshcd_is_pwr_mode_restore_needed(hba))
6116 needs_restore = true;
6117 spin_lock_irqsave(hba->host->host_lock, flags);
6118 if (!hba->saved_err && !needs_restore)
6119 goto skip_err_handling;
6122 hba->silence_err_logs = true;
6123 /* release lock as clear command might sleep */
6124 spin_unlock_irqrestore(hba->host->host_lock, flags);
6125 /* Clear pending transfer requests */
6126 for_each_set_bit(tag, &hba->outstanding_reqs, hba->nutrs) {
6127 if (ufshcd_try_to_abort_task(hba, tag)) {
6129 goto lock_skip_pending_xfer_clear;
6133 /* Clear pending task management requests */
6134 for_each_set_bit(tag, &hba->outstanding_tasks, hba->nutmrs) {
6135 if (ufshcd_clear_tm_cmd(hba, tag)) {
6137 goto lock_skip_pending_xfer_clear;
6141 lock_skip_pending_xfer_clear:
6142 /* Complete the requests that are cleared by s/w */
6143 ufshcd_complete_requests(hba);
6145 spin_lock_irqsave(hba->host->host_lock, flags);
6146 hba->silence_err_logs = false;
6147 if (err_xfer || err_tm) {
6153 * After all reqs and tasks are cleared from doorbell,
6154 * now it is safe to retore power mode.
6156 if (needs_restore) {
6157 spin_unlock_irqrestore(hba->host->host_lock, flags);
6159 * Hold the scaling lock just in case dev cmds
6160 * are sent via bsg and/or sysfs.
6162 down_write(&hba->clk_scaling_lock);
6163 hba->force_pmc = true;
6164 pmc_err = ufshcd_config_pwr_mode(hba, &(hba->pwr_info));
6167 dev_err(hba->dev, "%s: Failed to restore power mode, err = %d\n",
6170 hba->force_pmc = false;
6171 ufshcd_print_pwr_info(hba);
6172 up_write(&hba->clk_scaling_lock);
6173 spin_lock_irqsave(hba->host->host_lock, flags);
6177 /* Fatal errors need reset */
6179 hba->force_reset = false;
6180 spin_unlock_irqrestore(hba->host->host_lock, flags);
6181 err = ufshcd_reset_and_restore(hba);
6183 dev_err(hba->dev, "%s: reset and restore failed with err %d\n",
6186 ufshcd_recover_pm_error(hba);
6187 spin_lock_irqsave(hba->host->host_lock, flags);
6192 if (hba->ufshcd_state == UFSHCD_STATE_RESET)
6193 hba->ufshcd_state = UFSHCD_STATE_OPERATIONAL;
6194 if (hba->saved_err || hba->saved_uic_err)
6195 dev_err_ratelimited(hba->dev, "%s: exit: saved_err 0x%x saved_uic_err 0x%x",
6196 __func__, hba->saved_err, hba->saved_uic_err);
6198 ufshcd_clear_eh_in_progress(hba);
6199 spin_unlock_irqrestore(hba->host->host_lock, flags);
6200 ufshcd_err_handling_unprepare(hba);
6205 * ufshcd_update_uic_error - check and set fatal UIC error flags.
6206 * @hba: per-adapter instance
6209 * IRQ_HANDLED - If interrupt is valid
6210 * IRQ_NONE - If invalid interrupt
6212 static irqreturn_t ufshcd_update_uic_error(struct ufs_hba *hba)
6215 irqreturn_t retval = IRQ_NONE;
6217 /* PHY layer error */
6218 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_PHY_ADAPTER_LAYER);
6219 if ((reg & UIC_PHY_ADAPTER_LAYER_ERROR) &&
6220 (reg & UIC_PHY_ADAPTER_LAYER_ERROR_CODE_MASK)) {
6221 ufshcd_update_evt_hist(hba, UFS_EVT_PA_ERR, reg);
6223 * To know whether this error is fatal or not, DB timeout
6224 * must be checked but this error is handled separately.
6226 if (reg & UIC_PHY_ADAPTER_LAYER_LANE_ERR_MASK)
6227 dev_dbg(hba->dev, "%s: UIC Lane error reported\n",
6230 /* Got a LINERESET indication. */
6231 if (reg & UIC_PHY_ADAPTER_LAYER_GENERIC_ERROR) {
6232 struct uic_command *cmd = NULL;
6234 hba->uic_error |= UFSHCD_UIC_PA_GENERIC_ERROR;
6235 if (hba->uic_async_done && hba->active_uic_cmd)
6236 cmd = hba->active_uic_cmd;
6238 * Ignore the LINERESET during power mode change
6239 * operation via DME_SET command.
6241 if (cmd && (cmd->command == UIC_CMD_DME_SET))
6242 hba->uic_error &= ~UFSHCD_UIC_PA_GENERIC_ERROR;
6244 retval |= IRQ_HANDLED;
6247 /* PA_INIT_ERROR is fatal and needs UIC reset */
6248 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_DATA_LINK_LAYER);
6249 if ((reg & UIC_DATA_LINK_LAYER_ERROR) &&
6250 (reg & UIC_DATA_LINK_LAYER_ERROR_CODE_MASK)) {
6251 ufshcd_update_evt_hist(hba, UFS_EVT_DL_ERR, reg);
6253 if (reg & UIC_DATA_LINK_LAYER_ERROR_PA_INIT)
6254 hba->uic_error |= UFSHCD_UIC_DL_PA_INIT_ERROR;
6255 else if (hba->dev_quirks &
6256 UFS_DEVICE_QUIRK_RECOVERY_FROM_DL_NAC_ERRORS) {
6257 if (reg & UIC_DATA_LINK_LAYER_ERROR_NAC_RECEIVED)
6259 UFSHCD_UIC_DL_NAC_RECEIVED_ERROR;
6260 else if (reg & UIC_DATA_LINK_LAYER_ERROR_TCx_REPLAY_TIMEOUT)
6261 hba->uic_error |= UFSHCD_UIC_DL_TCx_REPLAY_ERROR;
6263 retval |= IRQ_HANDLED;
6266 /* UIC NL/TL/DME errors needs software retry */
6267 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_NETWORK_LAYER);
6268 if ((reg & UIC_NETWORK_LAYER_ERROR) &&
6269 (reg & UIC_NETWORK_LAYER_ERROR_CODE_MASK)) {
6270 ufshcd_update_evt_hist(hba, UFS_EVT_NL_ERR, reg);
6271 hba->uic_error |= UFSHCD_UIC_NL_ERROR;
6272 retval |= IRQ_HANDLED;
6275 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_TRANSPORT_LAYER);
6276 if ((reg & UIC_TRANSPORT_LAYER_ERROR) &&
6277 (reg & UIC_TRANSPORT_LAYER_ERROR_CODE_MASK)) {
6278 ufshcd_update_evt_hist(hba, UFS_EVT_TL_ERR, reg);
6279 hba->uic_error |= UFSHCD_UIC_TL_ERROR;
6280 retval |= IRQ_HANDLED;
6283 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_DME);
6284 if ((reg & UIC_DME_ERROR) &&
6285 (reg & UIC_DME_ERROR_CODE_MASK)) {
6286 ufshcd_update_evt_hist(hba, UFS_EVT_DME_ERR, reg);
6287 hba->uic_error |= UFSHCD_UIC_DME_ERROR;
6288 retval |= IRQ_HANDLED;
6291 dev_dbg(hba->dev, "%s: UIC error flags = 0x%08x\n",
6292 __func__, hba->uic_error);
6297 * ufshcd_check_errors - Check for errors that need s/w attention
6298 * @hba: per-adapter instance
6299 * @intr_status: interrupt status generated by the controller
6302 * IRQ_HANDLED - If interrupt is valid
6303 * IRQ_NONE - If invalid interrupt
6305 static irqreturn_t ufshcd_check_errors(struct ufs_hba *hba, u32 intr_status)
6307 bool queue_eh_work = false;
6308 irqreturn_t retval = IRQ_NONE;
6310 spin_lock(hba->host->host_lock);
6311 hba->errors |= UFSHCD_ERROR_MASK & intr_status;
6313 if (hba->errors & INT_FATAL_ERRORS) {
6314 ufshcd_update_evt_hist(hba, UFS_EVT_FATAL_ERR,
6316 queue_eh_work = true;
6319 if (hba->errors & UIC_ERROR) {
6321 retval = ufshcd_update_uic_error(hba);
6323 queue_eh_work = true;
6326 if (hba->errors & UFSHCD_UIC_HIBERN8_MASK) {
6328 "%s: Auto Hibern8 %s failed - status: 0x%08x, upmcrs: 0x%08x\n",
6329 __func__, (hba->errors & UIC_HIBERNATE_ENTER) ?
6331 hba->errors, ufshcd_get_upmcrs(hba));
6332 ufshcd_update_evt_hist(hba, UFS_EVT_AUTO_HIBERN8_ERR,
6334 ufshcd_set_link_broken(hba);
6335 queue_eh_work = true;
6338 if (queue_eh_work) {
6340 * update the transfer error masks to sticky bits, let's do this
6341 * irrespective of current ufshcd_state.
6343 hba->saved_err |= hba->errors;
6344 hba->saved_uic_err |= hba->uic_error;
6346 /* dump controller state before resetting */
6347 if ((hba->saved_err &
6348 (INT_FATAL_ERRORS | UFSHCD_UIC_HIBERN8_MASK)) ||
6349 (hba->saved_uic_err &&
6350 (hba->saved_uic_err != UFSHCD_UIC_PA_GENERIC_ERROR))) {
6351 dev_err(hba->dev, "%s: saved_err 0x%x saved_uic_err 0x%x\n",
6352 __func__, hba->saved_err,
6353 hba->saved_uic_err);
6354 ufshcd_dump_regs(hba, 0, UFSHCI_REG_SPACE_SIZE,
6356 ufshcd_print_pwr_info(hba);
6358 ufshcd_schedule_eh_work(hba);
6359 retval |= IRQ_HANDLED;
6362 * if (!queue_eh_work) -
6363 * Other errors are either non-fatal where host recovers
6364 * itself without s/w intervention or errors that will be
6365 * handled by the SCSI core layer.
6369 spin_unlock(hba->host->host_lock);
6374 struct ufs_hba *hba;
6375 unsigned long pending;
6379 static bool ufshcd_compl_tm(struct request *req, void *priv, bool reserved)
6381 struct ctm_info *const ci = priv;
6382 struct completion *c;
6384 WARN_ON_ONCE(reserved);
6385 if (test_bit(req->tag, &ci->pending))
6388 c = req->end_io_data;
6395 * ufshcd_tmc_handler - handle task management function completion
6396 * @hba: per adapter instance
6399 * IRQ_HANDLED - If interrupt is valid
6400 * IRQ_NONE - If invalid interrupt
6402 static irqreturn_t ufshcd_tmc_handler(struct ufs_hba *hba)
6404 unsigned long flags;
6405 struct request_queue *q = hba->tmf_queue;
6406 struct ctm_info ci = {
6410 spin_lock_irqsave(hba->host->host_lock, flags);
6411 ci.pending = ufshcd_readl(hba, REG_UTP_TASK_REQ_DOOR_BELL);
6412 blk_mq_tagset_busy_iter(q->tag_set, ufshcd_compl_tm, &ci);
6413 spin_unlock_irqrestore(hba->host->host_lock, flags);
6415 return ci.ncpl ? IRQ_HANDLED : IRQ_NONE;
6419 * ufshcd_sl_intr - Interrupt service routine
6420 * @hba: per adapter instance
6421 * @intr_status: contains interrupts generated by the controller
6424 * IRQ_HANDLED - If interrupt is valid
6425 * IRQ_NONE - If invalid interrupt
6427 static irqreturn_t ufshcd_sl_intr(struct ufs_hba *hba, u32 intr_status)
6429 irqreturn_t retval = IRQ_NONE;
6431 if (intr_status & UFSHCD_UIC_MASK)
6432 retval |= ufshcd_uic_cmd_compl(hba, intr_status);
6434 if (intr_status & UFSHCD_ERROR_MASK || hba->errors)
6435 retval |= ufshcd_check_errors(hba, intr_status);
6437 if (intr_status & UTP_TASK_REQ_COMPL)
6438 retval |= ufshcd_tmc_handler(hba);
6440 if (intr_status & UTP_TRANSFER_REQ_COMPL)
6441 retval |= ufshcd_trc_handler(hba, ufshcd_has_utrlcnr(hba));
6447 * ufshcd_intr - Main interrupt service routine
6449 * @__hba: pointer to adapter instance
6452 * IRQ_HANDLED - If interrupt is valid
6453 * IRQ_NONE - If invalid interrupt
6455 static irqreturn_t ufshcd_intr(int irq, void *__hba)
6457 u32 intr_status, enabled_intr_status = 0;
6458 irqreturn_t retval = IRQ_NONE;
6459 struct ufs_hba *hba = __hba;
6460 int retries = hba->nutrs;
6462 intr_status = ufshcd_readl(hba, REG_INTERRUPT_STATUS);
6463 hba->ufs_stats.last_intr_status = intr_status;
6464 hba->ufs_stats.last_intr_ts = ktime_get();
6467 * There could be max of hba->nutrs reqs in flight and in worst case
6468 * if the reqs get finished 1 by 1 after the interrupt status is
6469 * read, make sure we handle them by checking the interrupt status
6470 * again in a loop until we process all of the reqs before returning.
6472 while (intr_status && retries--) {
6473 enabled_intr_status =
6474 intr_status & ufshcd_readl(hba, REG_INTERRUPT_ENABLE);
6475 ufshcd_writel(hba, intr_status, REG_INTERRUPT_STATUS);
6476 if (enabled_intr_status)
6477 retval |= ufshcd_sl_intr(hba, enabled_intr_status);
6479 intr_status = ufshcd_readl(hba, REG_INTERRUPT_STATUS);
6482 if (enabled_intr_status && retval == IRQ_NONE &&
6483 (!(enabled_intr_status & UTP_TRANSFER_REQ_COMPL) ||
6484 hba->outstanding_reqs) && !ufshcd_eh_in_progress(hba)) {
6485 dev_err(hba->dev, "%s: Unhandled interrupt 0x%08x (0x%08x, 0x%08x)\n",
6488 hba->ufs_stats.last_intr_status,
6489 enabled_intr_status);
6490 ufshcd_dump_regs(hba, 0, UFSHCI_REG_SPACE_SIZE, "host_regs: ");
6496 static int ufshcd_clear_tm_cmd(struct ufs_hba *hba, int tag)
6499 u32 mask = 1 << tag;
6500 unsigned long flags;
6502 if (!test_bit(tag, &hba->outstanding_tasks))
6505 spin_lock_irqsave(hba->host->host_lock, flags);
6506 ufshcd_utmrl_clear(hba, tag);
6507 spin_unlock_irqrestore(hba->host->host_lock, flags);
6509 /* poll for max. 1 sec to clear door bell register by h/w */
6510 err = ufshcd_wait_for_register(hba,
6511 REG_UTP_TASK_REQ_DOOR_BELL,
6512 mask, 0, 1000, 1000);
6517 static int __ufshcd_issue_tm_cmd(struct ufs_hba *hba,
6518 struct utp_task_req_desc *treq, u8 tm_function)
6520 struct request_queue *q = hba->tmf_queue;
6521 struct Scsi_Host *host = hba->host;
6522 DECLARE_COMPLETION_ONSTACK(wait);
6523 struct request *req;
6524 unsigned long flags;
6528 * blk_get_request() is used here only to get a free tag.
6530 req = blk_get_request(q, REQ_OP_DRV_OUT, 0);
6532 return PTR_ERR(req);
6534 req->end_io_data = &wait;
6535 ufshcd_hold(hba, false);
6537 spin_lock_irqsave(host->host_lock, flags);
6538 blk_mq_start_request(req);
6540 task_tag = req->tag;
6541 treq->upiu_req.req_header.dword_0 |= cpu_to_be32(task_tag);
6543 memcpy(hba->utmrdl_base_addr + task_tag, treq, sizeof(*treq));
6544 ufshcd_vops_setup_task_mgmt(hba, task_tag, tm_function);
6546 /* send command to the controller */
6547 __set_bit(task_tag, &hba->outstanding_tasks);
6549 /* Make sure descriptors are ready before ringing the task doorbell */
6552 ufshcd_writel(hba, 1 << task_tag, REG_UTP_TASK_REQ_DOOR_BELL);
6553 /* Make sure that doorbell is committed immediately */
6556 spin_unlock_irqrestore(host->host_lock, flags);
6558 ufshcd_add_tm_upiu_trace(hba, task_tag, UFS_TM_SEND);
6560 /* wait until the task management command is completed */
6561 err = wait_for_completion_io_timeout(&wait,
6562 msecs_to_jiffies(TM_CMD_TIMEOUT));
6565 * Make sure that ufshcd_compl_tm() does not trigger a
6568 req->end_io_data = NULL;
6569 ufshcd_add_tm_upiu_trace(hba, task_tag, UFS_TM_ERR);
6570 dev_err(hba->dev, "%s: task management cmd 0x%.2x timed-out\n",
6571 __func__, tm_function);
6572 if (ufshcd_clear_tm_cmd(hba, task_tag))
6573 dev_WARN(hba->dev, "%s: unable to clear tm cmd (slot %d) after timeout\n",
6574 __func__, task_tag);
6578 memcpy(treq, hba->utmrdl_base_addr + task_tag, sizeof(*treq));
6580 ufshcd_add_tm_upiu_trace(hba, task_tag, UFS_TM_COMP);
6583 spin_lock_irqsave(hba->host->host_lock, flags);
6584 __clear_bit(task_tag, &hba->outstanding_tasks);
6585 spin_unlock_irqrestore(hba->host->host_lock, flags);
6587 ufshcd_release(hba);
6588 blk_put_request(req);
6594 * ufshcd_issue_tm_cmd - issues task management commands to controller
6595 * @hba: per adapter instance
6596 * @lun_id: LUN ID to which TM command is sent
6597 * @task_id: task ID to which the TM command is applicable
6598 * @tm_function: task management function opcode
6599 * @tm_response: task management service response return value
6601 * Returns non-zero value on error, zero on success.
6603 static int ufshcd_issue_tm_cmd(struct ufs_hba *hba, int lun_id, int task_id,
6604 u8 tm_function, u8 *tm_response)
6606 struct utp_task_req_desc treq = { { 0 }, };
6609 /* Configure task request descriptor */
6610 treq.header.dword_0 = cpu_to_le32(UTP_REQ_DESC_INT_CMD);
6611 treq.header.dword_2 = cpu_to_le32(OCS_INVALID_COMMAND_STATUS);
6613 /* Configure task request UPIU */
6614 treq.upiu_req.req_header.dword_0 = cpu_to_be32(lun_id << 8) |
6615 cpu_to_be32(UPIU_TRANSACTION_TASK_REQ << 24);
6616 treq.upiu_req.req_header.dword_1 = cpu_to_be32(tm_function << 16);
6619 * The host shall provide the same value for LUN field in the basic
6620 * header and for Input Parameter.
6622 treq.upiu_req.input_param1 = cpu_to_be32(lun_id);
6623 treq.upiu_req.input_param2 = cpu_to_be32(task_id);
6625 err = __ufshcd_issue_tm_cmd(hba, &treq, tm_function);
6626 if (err == -ETIMEDOUT)
6629 ocs_value = le32_to_cpu(treq.header.dword_2) & MASK_OCS;
6630 if (ocs_value != OCS_SUCCESS)
6631 dev_err(hba->dev, "%s: failed, ocs = 0x%x\n",
6632 __func__, ocs_value);
6633 else if (tm_response)
6634 *tm_response = be32_to_cpu(treq.upiu_rsp.output_param1) &
6635 MASK_TM_SERVICE_RESP;
6640 * ufshcd_issue_devman_upiu_cmd - API for sending "utrd" type requests
6641 * @hba: per-adapter instance
6642 * @req_upiu: upiu request
6643 * @rsp_upiu: upiu reply
6644 * @desc_buff: pointer to descriptor buffer, NULL if NA
6645 * @buff_len: descriptor size, 0 if NA
6646 * @cmd_type: specifies the type (NOP, Query...)
6647 * @desc_op: descriptor operation
6649 * Those type of requests uses UTP Transfer Request Descriptor - utrd.
6650 * Therefore, it "rides" the device management infrastructure: uses its tag and
6651 * tasks work queues.
6653 * Since there is only one available tag for device management commands,
6654 * the caller is expected to hold the hba->dev_cmd.lock mutex.
6656 static int ufshcd_issue_devman_upiu_cmd(struct ufs_hba *hba,
6657 struct utp_upiu_req *req_upiu,
6658 struct utp_upiu_req *rsp_upiu,
6659 u8 *desc_buff, int *buff_len,
6660 enum dev_cmd_type cmd_type,
6661 enum query_opcode desc_op)
6663 struct request_queue *q = hba->cmd_queue;
6664 struct request *req;
6665 struct ufshcd_lrb *lrbp;
6668 struct completion wait;
6671 down_read(&hba->clk_scaling_lock);
6673 req = blk_get_request(q, REQ_OP_DRV_OUT, 0);
6679 WARN_ON_ONCE(!ufshcd_valid_tag(hba, tag));
6681 if (unlikely(test_bit(tag, &hba->outstanding_reqs))) {
6686 init_completion(&wait);
6687 lrbp = &hba->lrb[tag];
6690 lrbp->sense_bufflen = 0;
6691 lrbp->sense_buffer = NULL;
6692 lrbp->task_tag = tag;
6694 lrbp->intr_cmd = true;
6695 ufshcd_prepare_lrbp_crypto(NULL, lrbp);
6696 hba->dev_cmd.type = cmd_type;
6698 if (hba->ufs_version <= ufshci_version(1, 1))
6699 lrbp->command_type = UTP_CMD_TYPE_DEV_MANAGE;
6701 lrbp->command_type = UTP_CMD_TYPE_UFS_STORAGE;
6703 /* update the task tag in the request upiu */
6704 req_upiu->header.dword_0 |= cpu_to_be32(tag);
6706 ufshcd_prepare_req_desc_hdr(lrbp, &upiu_flags, DMA_NONE);
6708 /* just copy the upiu request as it is */
6709 memcpy(lrbp->ucd_req_ptr, req_upiu, sizeof(*lrbp->ucd_req_ptr));
6710 if (desc_buff && desc_op == UPIU_QUERY_OPCODE_WRITE_DESC) {
6711 /* The Data Segment Area is optional depending upon the query
6712 * function value. for WRITE DESCRIPTOR, the data segment
6713 * follows right after the tsf.
6715 memcpy(lrbp->ucd_req_ptr + 1, desc_buff, *buff_len);
6719 memset(lrbp->ucd_rsp_ptr, 0, sizeof(struct utp_upiu_rsp));
6721 hba->dev_cmd.complete = &wait;
6723 ufshcd_add_query_upiu_trace(hba, UFS_QUERY_SEND, lrbp->ucd_req_ptr);
6724 /* Make sure descriptors are ready before ringing the doorbell */
6727 ufshcd_send_command(hba, tag);
6729 * ignore the returning value here - ufshcd_check_query_response is
6730 * bound to fail since dev_cmd.query and dev_cmd.type were left empty.
6731 * read the response directly ignoring all errors.
6733 ufshcd_wait_for_dev_cmd(hba, lrbp, QUERY_REQ_TIMEOUT);
6735 /* just copy the upiu response as it is */
6736 memcpy(rsp_upiu, lrbp->ucd_rsp_ptr, sizeof(*rsp_upiu));
6737 if (desc_buff && desc_op == UPIU_QUERY_OPCODE_READ_DESC) {
6738 u8 *descp = (u8 *)lrbp->ucd_rsp_ptr + sizeof(*rsp_upiu);
6739 u16 resp_len = be32_to_cpu(lrbp->ucd_rsp_ptr->header.dword_2) &
6740 MASK_QUERY_DATA_SEG_LEN;
6742 if (*buff_len >= resp_len) {
6743 memcpy(desc_buff, descp, resp_len);
6744 *buff_len = resp_len;
6747 "%s: rsp size %d is bigger than buffer size %d",
6748 __func__, resp_len, *buff_len);
6753 ufshcd_add_query_upiu_trace(hba, err ? UFS_QUERY_ERR : UFS_QUERY_COMP,
6754 (struct utp_upiu_req *)lrbp->ucd_rsp_ptr);
6757 blk_put_request(req);
6759 up_read(&hba->clk_scaling_lock);
6764 * ufshcd_exec_raw_upiu_cmd - API function for sending raw upiu commands
6765 * @hba: per-adapter instance
6766 * @req_upiu: upiu request
6767 * @rsp_upiu: upiu reply - only 8 DW as we do not support scsi commands
6768 * @msgcode: message code, one of UPIU Transaction Codes Initiator to Target
6769 * @desc_buff: pointer to descriptor buffer, NULL if NA
6770 * @buff_len: descriptor size, 0 if NA
6771 * @desc_op: descriptor operation
6773 * Supports UTP Transfer requests (nop and query), and UTP Task
6774 * Management requests.
6775 * It is up to the caller to fill the upiu conent properly, as it will
6776 * be copied without any further input validations.
6778 int ufshcd_exec_raw_upiu_cmd(struct ufs_hba *hba,
6779 struct utp_upiu_req *req_upiu,
6780 struct utp_upiu_req *rsp_upiu,
6782 u8 *desc_buff, int *buff_len,
6783 enum query_opcode desc_op)
6786 enum dev_cmd_type cmd_type = DEV_CMD_TYPE_QUERY;
6787 struct utp_task_req_desc treq = { { 0 }, };
6789 u8 tm_f = be32_to_cpu(req_upiu->header.dword_1) >> 16 & MASK_TM_FUNC;
6792 case UPIU_TRANSACTION_NOP_OUT:
6793 cmd_type = DEV_CMD_TYPE_NOP;
6795 case UPIU_TRANSACTION_QUERY_REQ:
6796 ufshcd_hold(hba, false);
6797 mutex_lock(&hba->dev_cmd.lock);
6798 err = ufshcd_issue_devman_upiu_cmd(hba, req_upiu, rsp_upiu,
6799 desc_buff, buff_len,
6801 mutex_unlock(&hba->dev_cmd.lock);
6802 ufshcd_release(hba);
6805 case UPIU_TRANSACTION_TASK_REQ:
6806 treq.header.dword_0 = cpu_to_le32(UTP_REQ_DESC_INT_CMD);
6807 treq.header.dword_2 = cpu_to_le32(OCS_INVALID_COMMAND_STATUS);
6809 memcpy(&treq.upiu_req, req_upiu, sizeof(*req_upiu));
6811 err = __ufshcd_issue_tm_cmd(hba, &treq, tm_f);
6812 if (err == -ETIMEDOUT)
6815 ocs_value = le32_to_cpu(treq.header.dword_2) & MASK_OCS;
6816 if (ocs_value != OCS_SUCCESS) {
6817 dev_err(hba->dev, "%s: failed, ocs = 0x%x\n", __func__,
6822 memcpy(rsp_upiu, &treq.upiu_rsp, sizeof(*rsp_upiu));
6835 * ufshcd_eh_device_reset_handler - device reset handler registered to
6837 * @cmd: SCSI command pointer
6839 * Returns SUCCESS/FAILED
6841 static int ufshcd_eh_device_reset_handler(struct scsi_cmnd *cmd)
6843 struct Scsi_Host *host;
6844 struct ufs_hba *hba;
6849 host = cmd->device->host;
6850 hba = shost_priv(host);
6852 lun = ufshcd_scsi_to_upiu_lun(cmd->device->lun);
6853 err = ufshcd_issue_tm_cmd(hba, lun, 0, UFS_LOGICAL_RESET, &resp);
6854 if (err || resp != UPIU_TASK_MANAGEMENT_FUNC_COMPL) {
6860 /* clear the commands that were pending for corresponding LUN */
6861 for_each_set_bit(pos, &hba->outstanding_reqs, hba->nutrs) {
6862 if (hba->lrb[pos].lun == lun) {
6863 err = ufshcd_clear_cmd(hba, pos);
6866 __ufshcd_transfer_req_compl(hba, pos);
6871 hba->req_abort_count = 0;
6872 ufshcd_update_evt_hist(hba, UFS_EVT_DEV_RESET, (u32)err);
6876 dev_err(hba->dev, "%s: failed with err %d\n", __func__, err);
6882 static void ufshcd_set_req_abort_skip(struct ufs_hba *hba, unsigned long bitmap)
6884 struct ufshcd_lrb *lrbp;
6887 for_each_set_bit(tag, &bitmap, hba->nutrs) {
6888 lrbp = &hba->lrb[tag];
6889 lrbp->req_abort_skip = true;
6894 * ufshcd_try_to_abort_task - abort a specific task
6895 * @hba: Pointer to adapter instance
6896 * @tag: Task tag/index to be aborted
6898 * Abort the pending command in device by sending UFS_ABORT_TASK task management
6899 * command, and in host controller by clearing the door-bell register. There can
6900 * be race between controller sending the command to the device while abort is
6901 * issued. To avoid that, first issue UFS_QUERY_TASK to check if the command is
6902 * really issued and then try to abort it.
6904 * Returns zero on success, non-zero on failure
6906 static int ufshcd_try_to_abort_task(struct ufs_hba *hba, int tag)
6908 struct ufshcd_lrb *lrbp = &hba->lrb[tag];
6914 for (poll_cnt = 100; poll_cnt; poll_cnt--) {
6915 err = ufshcd_issue_tm_cmd(hba, lrbp->lun, lrbp->task_tag,
6916 UFS_QUERY_TASK, &resp);
6917 if (!err && resp == UPIU_TASK_MANAGEMENT_FUNC_SUCCEEDED) {
6918 /* cmd pending in the device */
6919 dev_err(hba->dev, "%s: cmd pending in the device. tag = %d\n",
6922 } else if (!err && resp == UPIU_TASK_MANAGEMENT_FUNC_COMPL) {
6924 * cmd not pending in the device, check if it is
6927 dev_err(hba->dev, "%s: cmd at tag %d not pending in the device.\n",
6929 reg = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
6930 if (reg & (1 << tag)) {
6931 /* sleep for max. 200us to stabilize */
6932 usleep_range(100, 200);
6935 /* command completed already */
6936 dev_err(hba->dev, "%s: cmd at tag %d successfully cleared from DB.\n",
6941 "%s: no response from device. tag = %d, err %d\n",
6942 __func__, tag, err);
6944 err = resp; /* service response error */
6954 err = ufshcd_issue_tm_cmd(hba, lrbp->lun, lrbp->task_tag,
6955 UFS_ABORT_TASK, &resp);
6956 if (err || resp != UPIU_TASK_MANAGEMENT_FUNC_COMPL) {
6958 err = resp; /* service response error */
6959 dev_err(hba->dev, "%s: issued. tag = %d, err %d\n",
6960 __func__, tag, err);
6965 err = ufshcd_clear_cmd(hba, tag);
6967 dev_err(hba->dev, "%s: Failed clearing cmd at tag %d, err %d\n",
6968 __func__, tag, err);
6975 * ufshcd_abort - scsi host template eh_abort_handler callback
6976 * @cmd: SCSI command pointer
6978 * Returns SUCCESS/FAILED
6980 static int ufshcd_abort(struct scsi_cmnd *cmd)
6982 struct Scsi_Host *host;
6983 struct ufs_hba *hba;
6984 unsigned long flags;
6987 struct ufshcd_lrb *lrbp;
6990 host = cmd->device->host;
6991 hba = shost_priv(host);
6992 tag = cmd->request->tag;
6993 lrbp = &hba->lrb[tag];
6994 if (!ufshcd_valid_tag(hba, tag)) {
6996 "%s: invalid command tag %d: cmd=0x%p, cmd->request=0x%p",
6997 __func__, tag, cmd, cmd->request);
7001 ufshcd_hold(hba, false);
7002 reg = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
7003 /* If command is already aborted/completed, return SUCCESS */
7004 if (!(test_bit(tag, &hba->outstanding_reqs))) {
7006 "%s: cmd at tag %d already completed, outstanding=0x%lx, doorbell=0x%x\n",
7007 __func__, tag, hba->outstanding_reqs, reg);
7011 /* Print Transfer Request of aborted task */
7012 dev_info(hba->dev, "%s: Device abort task at tag %d\n", __func__, tag);
7015 * Print detailed info about aborted request.
7016 * As more than one request might get aborted at the same time,
7017 * print full information only for the first aborted request in order
7018 * to reduce repeated printouts. For other aborted requests only print
7021 scsi_print_command(cmd);
7022 if (!hba->req_abort_count) {
7023 ufshcd_update_evt_hist(hba, UFS_EVT_ABORT, tag);
7024 ufshcd_print_evt_hist(hba);
7025 ufshcd_print_host_state(hba);
7026 ufshcd_print_pwr_info(hba);
7027 ufshcd_print_trs(hba, 1 << tag, true);
7029 ufshcd_print_trs(hba, 1 << tag, false);
7031 hba->req_abort_count++;
7033 if (!(reg & (1 << tag))) {
7035 "%s: cmd was completed, but without a notifying intr, tag = %d",
7041 * Task abort to the device W-LUN is illegal. When this command
7042 * will fail, due to spec violation, scsi err handling next step
7043 * will be to send LU reset which, again, is a spec violation.
7044 * To avoid these unnecessary/illegal steps, first we clean up
7045 * the lrb taken by this cmd and re-set it in outstanding_reqs,
7046 * then queue the eh_work and bail.
7048 if (lrbp->lun == UFS_UPIU_UFS_DEVICE_WLUN) {
7049 ufshcd_update_evt_hist(hba, UFS_EVT_ABORT, lrbp->lun);
7050 __ufshcd_transfer_req_compl(hba, (1UL << tag));
7051 set_bit(tag, &hba->outstanding_reqs);
7052 spin_lock_irqsave(host->host_lock, flags);
7053 hba->force_reset = true;
7054 ufshcd_schedule_eh_work(hba);
7055 spin_unlock_irqrestore(host->host_lock, flags);
7059 /* Skip task abort in case previous aborts failed and report failure */
7060 if (lrbp->req_abort_skip)
7063 err = ufshcd_try_to_abort_task(hba, tag);
7067 __ufshcd_transfer_req_compl(hba, (1UL << tag));
7071 dev_err(hba->dev, "%s: failed with err %d\n", __func__, err);
7072 ufshcd_set_req_abort_skip(hba, hba->outstanding_reqs);
7077 * This ufshcd_release() corresponds to the original scsi cmd that got
7078 * aborted here (as we won't get any IRQ for it).
7080 ufshcd_release(hba);
7085 * ufshcd_host_reset_and_restore - reset and restore host controller
7086 * @hba: per-adapter instance
7088 * Note that host controller reset may issue DME_RESET to
7089 * local and remote (device) Uni-Pro stack and the attributes
7090 * are reset to default state.
7092 * Returns zero on success, non-zero on failure
7094 static int ufshcd_host_reset_and_restore(struct ufs_hba *hba)
7099 * Stop the host controller and complete the requests
7102 ufshcd_hba_stop(hba);
7103 hba->silence_err_logs = true;
7104 ufshcd_complete_requests(hba);
7105 hba->silence_err_logs = false;
7107 /* scale up clocks to max frequency before full reinitialization */
7108 ufshcd_set_clk_freq(hba, true);
7110 err = ufshcd_hba_enable(hba);
7112 /* Establish the link again and restore the device */
7114 err = ufshcd_probe_hba(hba, false);
7117 dev_err(hba->dev, "%s: Host init failed %d\n", __func__, err);
7118 ufshcd_update_evt_hist(hba, UFS_EVT_HOST_RESET, (u32)err);
7123 * ufshcd_reset_and_restore - reset and re-initialize host/device
7124 * @hba: per-adapter instance
7126 * Reset and recover device, host and re-establish link. This
7127 * is helpful to recover the communication in fatal error conditions.
7129 * Returns zero on success, non-zero on failure
7131 static int ufshcd_reset_and_restore(struct ufs_hba *hba)
7136 unsigned long flags;
7137 int retries = MAX_HOST_RESET_RETRIES;
7140 * This is a fresh start, cache and clear saved error first,
7141 * in case new error generated during reset and restore.
7143 spin_lock_irqsave(hba->host->host_lock, flags);
7144 saved_err = hba->saved_err;
7145 saved_uic_err = hba->saved_uic_err;
7147 hba->saved_uic_err = 0;
7148 spin_unlock_irqrestore(hba->host->host_lock, flags);
7151 /* Reset the attached device */
7152 ufshcd_device_reset(hba);
7154 err = ufshcd_host_reset_and_restore(hba);
7155 } while (err && --retries);
7157 spin_lock_irqsave(hba->host->host_lock, flags);
7159 * Inform scsi mid-layer that we did reset and allow to handle
7160 * Unit Attention properly.
7162 scsi_report_bus_reset(hba->host, 0);
7164 hba->ufshcd_state = UFSHCD_STATE_ERROR;
7165 hba->saved_err |= saved_err;
7166 hba->saved_uic_err |= saved_uic_err;
7168 spin_unlock_irqrestore(hba->host->host_lock, flags);
7174 * ufshcd_eh_host_reset_handler - host reset handler registered to scsi layer
7175 * @cmd: SCSI command pointer
7177 * Returns SUCCESS/FAILED
7179 static int ufshcd_eh_host_reset_handler(struct scsi_cmnd *cmd)
7182 unsigned long flags;
7183 struct ufs_hba *hba;
7185 hba = shost_priv(cmd->device->host);
7187 spin_lock_irqsave(hba->host->host_lock, flags);
7188 hba->force_reset = true;
7189 ufshcd_schedule_eh_work(hba);
7190 dev_err(hba->dev, "%s: reset in progress - 1\n", __func__);
7191 spin_unlock_irqrestore(hba->host->host_lock, flags);
7193 flush_work(&hba->eh_work);
7195 spin_lock_irqsave(hba->host->host_lock, flags);
7196 if (hba->ufshcd_state == UFSHCD_STATE_ERROR)
7198 spin_unlock_irqrestore(hba->host->host_lock, flags);
7204 * ufshcd_get_max_icc_level - calculate the ICC level
7205 * @sup_curr_uA: max. current supported by the regulator
7206 * @start_scan: row at the desc table to start scan from
7207 * @buff: power descriptor buffer
7209 * Returns calculated max ICC level for specific regulator
7211 static u32 ufshcd_get_max_icc_level(int sup_curr_uA, u32 start_scan, char *buff)
7218 for (i = start_scan; i >= 0; i--) {
7219 data = be16_to_cpup((__be16 *)&buff[2 * i]);
7220 unit = (data & ATTR_ICC_LVL_UNIT_MASK) >>
7221 ATTR_ICC_LVL_UNIT_OFFSET;
7222 curr_uA = data & ATTR_ICC_LVL_VALUE_MASK;
7224 case UFSHCD_NANO_AMP:
7225 curr_uA = curr_uA / 1000;
7227 case UFSHCD_MILI_AMP:
7228 curr_uA = curr_uA * 1000;
7231 curr_uA = curr_uA * 1000 * 1000;
7233 case UFSHCD_MICRO_AMP:
7237 if (sup_curr_uA >= curr_uA)
7242 pr_err("%s: Couldn't find valid icc_level = %d", __func__, i);
7249 * ufshcd_find_max_sup_active_icc_level - calculate the max ICC level
7250 * In case regulators are not initialized we'll return 0
7251 * @hba: per-adapter instance
7252 * @desc_buf: power descriptor buffer to extract ICC levels from.
7253 * @len: length of desc_buff
7255 * Returns calculated ICC level
7257 static u32 ufshcd_find_max_sup_active_icc_level(struct ufs_hba *hba,
7258 u8 *desc_buf, int len)
7262 if (!hba->vreg_info.vcc || !hba->vreg_info.vccq ||
7263 !hba->vreg_info.vccq2) {
7265 "%s: Regulator capability was not set, actvIccLevel=%d",
7266 __func__, icc_level);
7270 if (hba->vreg_info.vcc->max_uA)
7271 icc_level = ufshcd_get_max_icc_level(
7272 hba->vreg_info.vcc->max_uA,
7273 POWER_DESC_MAX_ACTV_ICC_LVLS - 1,
7274 &desc_buf[PWR_DESC_ACTIVE_LVLS_VCC_0]);
7276 if (hba->vreg_info.vccq->max_uA)
7277 icc_level = ufshcd_get_max_icc_level(
7278 hba->vreg_info.vccq->max_uA,
7280 &desc_buf[PWR_DESC_ACTIVE_LVLS_VCCQ_0]);
7282 if (hba->vreg_info.vccq2->max_uA)
7283 icc_level = ufshcd_get_max_icc_level(
7284 hba->vreg_info.vccq2->max_uA,
7286 &desc_buf[PWR_DESC_ACTIVE_LVLS_VCCQ2_0]);
7291 static void ufshcd_set_active_icc_lvl(struct ufs_hba *hba)
7294 int buff_len = hba->desc_size[QUERY_DESC_IDN_POWER];
7298 desc_buf = kmalloc(buff_len, GFP_KERNEL);
7302 ret = ufshcd_read_desc_param(hba, QUERY_DESC_IDN_POWER, 0, 0,
7303 desc_buf, buff_len);
7306 "%s: Failed reading power descriptor.len = %d ret = %d",
7307 __func__, buff_len, ret);
7311 icc_level = ufshcd_find_max_sup_active_icc_level(hba, desc_buf,
7313 dev_dbg(hba->dev, "%s: setting icc_level 0x%x", __func__, icc_level);
7315 ret = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_WRITE_ATTR,
7316 QUERY_ATTR_IDN_ACTIVE_ICC_LVL, 0, 0, &icc_level);
7320 "%s: Failed configuring bActiveICCLevel = %d ret = %d",
7321 __func__, icc_level, ret);
7327 static inline void ufshcd_blk_pm_runtime_init(struct scsi_device *sdev)
7329 scsi_autopm_get_device(sdev);
7330 blk_pm_runtime_init(sdev->request_queue, &sdev->sdev_gendev);
7331 if (sdev->rpm_autosuspend)
7332 pm_runtime_set_autosuspend_delay(&sdev->sdev_gendev,
7333 RPM_AUTOSUSPEND_DELAY_MS);
7334 scsi_autopm_put_device(sdev);
7338 * ufshcd_scsi_add_wlus - Adds required W-LUs
7339 * @hba: per-adapter instance
7341 * UFS device specification requires the UFS devices to support 4 well known
7343 * "REPORT_LUNS" (address: 01h)
7344 * "UFS Device" (address: 50h)
7345 * "RPMB" (address: 44h)
7346 * "BOOT" (address: 30h)
7347 * UFS device's power management needs to be controlled by "POWER CONDITION"
7348 * field of SSU (START STOP UNIT) command. But this "power condition" field
7349 * will take effect only when its sent to "UFS device" well known logical unit
7350 * hence we require the scsi_device instance to represent this logical unit in
7351 * order for the UFS host driver to send the SSU command for power management.
7353 * We also require the scsi_device instance for "RPMB" (Replay Protected Memory
7354 * Block) LU so user space process can control this LU. User space may also
7355 * want to have access to BOOT LU.
7357 * This function adds scsi device instances for each of all well known LUs
7358 * (except "REPORT LUNS" LU).
7360 * Returns zero on success (all required W-LUs are added successfully),
7361 * non-zero error value on failure (if failed to add any of the required W-LU).
7363 static int ufshcd_scsi_add_wlus(struct ufs_hba *hba)
7366 struct scsi_device *sdev_boot;
7368 hba->sdev_ufs_device = __scsi_add_device(hba->host, 0, 0,
7369 ufshcd_upiu_wlun_to_scsi_wlun(UFS_UPIU_UFS_DEVICE_WLUN), NULL);
7370 if (IS_ERR(hba->sdev_ufs_device)) {
7371 ret = PTR_ERR(hba->sdev_ufs_device);
7372 hba->sdev_ufs_device = NULL;
7375 scsi_device_put(hba->sdev_ufs_device);
7377 hba->sdev_rpmb = __scsi_add_device(hba->host, 0, 0,
7378 ufshcd_upiu_wlun_to_scsi_wlun(UFS_UPIU_RPMB_WLUN), NULL);
7379 if (IS_ERR(hba->sdev_rpmb)) {
7380 ret = PTR_ERR(hba->sdev_rpmb);
7381 goto remove_sdev_ufs_device;
7383 ufshcd_blk_pm_runtime_init(hba->sdev_rpmb);
7384 scsi_device_put(hba->sdev_rpmb);
7386 sdev_boot = __scsi_add_device(hba->host, 0, 0,
7387 ufshcd_upiu_wlun_to_scsi_wlun(UFS_UPIU_BOOT_WLUN), NULL);
7388 if (IS_ERR(sdev_boot)) {
7389 dev_err(hba->dev, "%s: BOOT WLUN not found\n", __func__);
7391 ufshcd_blk_pm_runtime_init(sdev_boot);
7392 scsi_device_put(sdev_boot);
7396 remove_sdev_ufs_device:
7397 scsi_remove_device(hba->sdev_ufs_device);
7402 static void ufshcd_wb_probe(struct ufs_hba *hba, u8 *desc_buf)
7404 struct ufs_dev_info *dev_info = &hba->dev_info;
7406 u32 d_lu_wb_buf_alloc;
7407 u32 ext_ufs_feature;
7409 if (!ufshcd_is_wb_allowed(hba))
7412 * Probe WB only for UFS-2.2 and UFS-3.1 (and later) devices or
7413 * UFS devices with quirk UFS_DEVICE_QUIRK_SUPPORT_EXTENDED_FEATURES
7416 if (!(dev_info->wspecversion >= 0x310 ||
7417 dev_info->wspecversion == 0x220 ||
7418 (hba->dev_quirks & UFS_DEVICE_QUIRK_SUPPORT_EXTENDED_FEATURES)))
7421 if (hba->desc_size[QUERY_DESC_IDN_DEVICE] <
7422 DEVICE_DESC_PARAM_EXT_UFS_FEATURE_SUP + 4)
7425 ext_ufs_feature = get_unaligned_be32(desc_buf +
7426 DEVICE_DESC_PARAM_EXT_UFS_FEATURE_SUP);
7428 if (!(ext_ufs_feature & UFS_DEV_WRITE_BOOSTER_SUP))
7432 * WB may be supported but not configured while provisioning. The spec
7433 * says, in dedicated wb buffer mode, a max of 1 lun would have wb
7434 * buffer configured.
7436 dev_info->wb_buffer_type = desc_buf[DEVICE_DESC_PARAM_WB_TYPE];
7438 dev_info->b_presrv_uspc_en =
7439 desc_buf[DEVICE_DESC_PARAM_WB_PRESRV_USRSPC_EN];
7441 if (dev_info->wb_buffer_type == WB_BUF_MODE_SHARED) {
7442 if (!get_unaligned_be32(desc_buf +
7443 DEVICE_DESC_PARAM_WB_SHARED_ALLOC_UNITS))
7446 for (lun = 0; lun < UFS_UPIU_MAX_WB_LUN_ID; lun++) {
7447 d_lu_wb_buf_alloc = 0;
7448 ufshcd_read_unit_desc_param(hba,
7450 UNIT_DESC_PARAM_WB_BUF_ALLOC_UNITS,
7451 (u8 *)&d_lu_wb_buf_alloc,
7452 sizeof(d_lu_wb_buf_alloc));
7453 if (d_lu_wb_buf_alloc) {
7454 dev_info->wb_dedicated_lu = lun;
7459 if (!d_lu_wb_buf_alloc)
7465 hba->caps &= ~UFSHCD_CAP_WB_EN;
7468 void ufshcd_fixup_dev_quirks(struct ufs_hba *hba, struct ufs_dev_fix *fixups)
7470 struct ufs_dev_fix *f;
7471 struct ufs_dev_info *dev_info = &hba->dev_info;
7476 for (f = fixups; f->quirk; f++) {
7477 if ((f->wmanufacturerid == dev_info->wmanufacturerid ||
7478 f->wmanufacturerid == UFS_ANY_VENDOR) &&
7479 ((dev_info->model &&
7480 STR_PRFX_EQUAL(f->model, dev_info->model)) ||
7481 !strcmp(f->model, UFS_ANY_MODEL)))
7482 hba->dev_quirks |= f->quirk;
7485 EXPORT_SYMBOL_GPL(ufshcd_fixup_dev_quirks);
7487 static void ufs_fixup_device_setup(struct ufs_hba *hba)
7489 /* fix by general quirk table */
7490 ufshcd_fixup_dev_quirks(hba, ufs_fixups);
7492 /* allow vendors to fix quirks */
7493 ufshcd_vops_fixup_dev_quirks(hba);
7496 static int ufs_get_device_desc(struct ufs_hba *hba)
7501 struct ufs_dev_info *dev_info = &hba->dev_info;
7503 desc_buf = kmalloc(QUERY_DESC_MAX_SIZE, GFP_KERNEL);
7509 err = ufshcd_read_desc_param(hba, QUERY_DESC_IDN_DEVICE, 0, 0, desc_buf,
7510 hba->desc_size[QUERY_DESC_IDN_DEVICE]);
7512 dev_err(hba->dev, "%s: Failed reading Device Desc. err = %d\n",
7518 * getting vendor (manufacturerID) and Bank Index in big endian
7521 dev_info->wmanufacturerid = desc_buf[DEVICE_DESC_PARAM_MANF_ID] << 8 |
7522 desc_buf[DEVICE_DESC_PARAM_MANF_ID + 1];
7524 /* getting Specification Version in big endian format */
7525 dev_info->wspecversion = desc_buf[DEVICE_DESC_PARAM_SPEC_VER] << 8 |
7526 desc_buf[DEVICE_DESC_PARAM_SPEC_VER + 1];
7528 model_index = desc_buf[DEVICE_DESC_PARAM_PRDCT_NAME];
7530 err = ufshcd_read_string_desc(hba, model_index,
7531 &dev_info->model, SD_ASCII_STD);
7533 dev_err(hba->dev, "%s: Failed reading Product Name. err = %d\n",
7538 hba->luns_avail = desc_buf[DEVICE_DESC_PARAM_NUM_LU] +
7539 desc_buf[DEVICE_DESC_PARAM_NUM_WLU];
7541 ufs_fixup_device_setup(hba);
7543 ufshcd_wb_probe(hba, desc_buf);
7546 * ufshcd_read_string_desc returns size of the string
7547 * reset the error value
7556 static void ufs_put_device_desc(struct ufs_hba *hba)
7558 struct ufs_dev_info *dev_info = &hba->dev_info;
7560 kfree(dev_info->model);
7561 dev_info->model = NULL;
7565 * ufshcd_tune_pa_tactivate - Tunes PA_TActivate of local UniPro
7566 * @hba: per-adapter instance
7568 * PA_TActivate parameter can be tuned manually if UniPro version is less than
7569 * 1.61. PA_TActivate needs to be greater than or equal to peerM-PHY's
7570 * RX_MIN_ACTIVATETIME_CAPABILITY attribute. This optimal value can help reduce
7571 * the hibern8 exit latency.
7573 * Returns zero on success, non-zero error value on failure.
7575 static int ufshcd_tune_pa_tactivate(struct ufs_hba *hba)
7578 u32 peer_rx_min_activatetime = 0, tuned_pa_tactivate;
7580 ret = ufshcd_dme_peer_get(hba,
7582 RX_MIN_ACTIVATETIME_CAPABILITY,
7583 UIC_ARG_MPHY_RX_GEN_SEL_INDEX(0)),
7584 &peer_rx_min_activatetime);
7588 /* make sure proper unit conversion is applied */
7589 tuned_pa_tactivate =
7590 ((peer_rx_min_activatetime * RX_MIN_ACTIVATETIME_UNIT_US)
7591 / PA_TACTIVATE_TIME_UNIT_US);
7592 ret = ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TACTIVATE),
7593 tuned_pa_tactivate);
7600 * ufshcd_tune_pa_hibern8time - Tunes PA_Hibern8Time of local UniPro
7601 * @hba: per-adapter instance
7603 * PA_Hibern8Time parameter can be tuned manually if UniPro version is less than
7604 * 1.61. PA_Hibern8Time needs to be maximum of local M-PHY's
7605 * TX_HIBERN8TIME_CAPABILITY & peer M-PHY's RX_HIBERN8TIME_CAPABILITY.
7606 * This optimal value can help reduce the hibern8 exit latency.
7608 * Returns zero on success, non-zero error value on failure.
7610 static int ufshcd_tune_pa_hibern8time(struct ufs_hba *hba)
7613 u32 local_tx_hibern8_time_cap = 0, peer_rx_hibern8_time_cap = 0;
7614 u32 max_hibern8_time, tuned_pa_hibern8time;
7616 ret = ufshcd_dme_get(hba,
7617 UIC_ARG_MIB_SEL(TX_HIBERN8TIME_CAPABILITY,
7618 UIC_ARG_MPHY_TX_GEN_SEL_INDEX(0)),
7619 &local_tx_hibern8_time_cap);
7623 ret = ufshcd_dme_peer_get(hba,
7624 UIC_ARG_MIB_SEL(RX_HIBERN8TIME_CAPABILITY,
7625 UIC_ARG_MPHY_RX_GEN_SEL_INDEX(0)),
7626 &peer_rx_hibern8_time_cap);
7630 max_hibern8_time = max(local_tx_hibern8_time_cap,
7631 peer_rx_hibern8_time_cap);
7632 /* make sure proper unit conversion is applied */
7633 tuned_pa_hibern8time = ((max_hibern8_time * HIBERN8TIME_UNIT_US)
7634 / PA_HIBERN8_TIME_UNIT_US);
7635 ret = ufshcd_dme_set(hba, UIC_ARG_MIB(PA_HIBERN8TIME),
7636 tuned_pa_hibern8time);
7642 * ufshcd_quirk_tune_host_pa_tactivate - Ensures that host PA_TACTIVATE is
7643 * less than device PA_TACTIVATE time.
7644 * @hba: per-adapter instance
7646 * Some UFS devices require host PA_TACTIVATE to be lower than device
7647 * PA_TACTIVATE, we need to enable UFS_DEVICE_QUIRK_HOST_PA_TACTIVATE quirk
7650 * Returns zero on success, non-zero error value on failure.
7652 static int ufshcd_quirk_tune_host_pa_tactivate(struct ufs_hba *hba)
7655 u32 granularity, peer_granularity;
7656 u32 pa_tactivate, peer_pa_tactivate;
7657 u32 pa_tactivate_us, peer_pa_tactivate_us;
7658 u8 gran_to_us_table[] = {1, 4, 8, 16, 32, 100};
7660 ret = ufshcd_dme_get(hba, UIC_ARG_MIB(PA_GRANULARITY),
7665 ret = ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_GRANULARITY),
7670 if ((granularity < PA_GRANULARITY_MIN_VAL) ||
7671 (granularity > PA_GRANULARITY_MAX_VAL)) {
7672 dev_err(hba->dev, "%s: invalid host PA_GRANULARITY %d",
7673 __func__, granularity);
7677 if ((peer_granularity < PA_GRANULARITY_MIN_VAL) ||
7678 (peer_granularity > PA_GRANULARITY_MAX_VAL)) {
7679 dev_err(hba->dev, "%s: invalid device PA_GRANULARITY %d",
7680 __func__, peer_granularity);
7684 ret = ufshcd_dme_get(hba, UIC_ARG_MIB(PA_TACTIVATE), &pa_tactivate);
7688 ret = ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_TACTIVATE),
7689 &peer_pa_tactivate);
7693 pa_tactivate_us = pa_tactivate * gran_to_us_table[granularity - 1];
7694 peer_pa_tactivate_us = peer_pa_tactivate *
7695 gran_to_us_table[peer_granularity - 1];
7697 if (pa_tactivate_us > peer_pa_tactivate_us) {
7698 u32 new_peer_pa_tactivate;
7700 new_peer_pa_tactivate = pa_tactivate_us /
7701 gran_to_us_table[peer_granularity - 1];
7702 new_peer_pa_tactivate++;
7703 ret = ufshcd_dme_peer_set(hba, UIC_ARG_MIB(PA_TACTIVATE),
7704 new_peer_pa_tactivate);
7711 static void ufshcd_tune_unipro_params(struct ufs_hba *hba)
7713 if (ufshcd_is_unipro_pa_params_tuning_req(hba)) {
7714 ufshcd_tune_pa_tactivate(hba);
7715 ufshcd_tune_pa_hibern8time(hba);
7718 ufshcd_vops_apply_dev_quirks(hba);
7720 if (hba->dev_quirks & UFS_DEVICE_QUIRK_PA_TACTIVATE)
7721 /* set 1ms timeout for PA_TACTIVATE */
7722 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TACTIVATE), 10);
7724 if (hba->dev_quirks & UFS_DEVICE_QUIRK_HOST_PA_TACTIVATE)
7725 ufshcd_quirk_tune_host_pa_tactivate(hba);
7728 static void ufshcd_clear_dbg_ufs_stats(struct ufs_hba *hba)
7730 hba->ufs_stats.hibern8_exit_cnt = 0;
7731 hba->ufs_stats.last_hibern8_exit_tstamp = ktime_set(0, 0);
7732 hba->req_abort_count = 0;
7735 static int ufshcd_device_geo_params_init(struct ufs_hba *hba)
7741 buff_len = hba->desc_size[QUERY_DESC_IDN_GEOMETRY];
7742 desc_buf = kmalloc(buff_len, GFP_KERNEL);
7748 err = ufshcd_read_desc_param(hba, QUERY_DESC_IDN_GEOMETRY, 0, 0,
7749 desc_buf, buff_len);
7751 dev_err(hba->dev, "%s: Failed reading Geometry Desc. err = %d\n",
7756 if (desc_buf[GEOMETRY_DESC_PARAM_MAX_NUM_LUN] == 1)
7757 hba->dev_info.max_lu_supported = 32;
7758 else if (desc_buf[GEOMETRY_DESC_PARAM_MAX_NUM_LUN] == 0)
7759 hba->dev_info.max_lu_supported = 8;
7766 static struct ufs_ref_clk ufs_ref_clk_freqs[] = {
7767 {19200000, REF_CLK_FREQ_19_2_MHZ},
7768 {26000000, REF_CLK_FREQ_26_MHZ},
7769 {38400000, REF_CLK_FREQ_38_4_MHZ},
7770 {52000000, REF_CLK_FREQ_52_MHZ},
7771 {0, REF_CLK_FREQ_INVAL},
7774 static enum ufs_ref_clk_freq
7775 ufs_get_bref_clk_from_hz(unsigned long freq)
7779 for (i = 0; ufs_ref_clk_freqs[i].freq_hz; i++)
7780 if (ufs_ref_clk_freqs[i].freq_hz == freq)
7781 return ufs_ref_clk_freqs[i].val;
7783 return REF_CLK_FREQ_INVAL;
7786 void ufshcd_parse_dev_ref_clk_freq(struct ufs_hba *hba, struct clk *refclk)
7790 freq = clk_get_rate(refclk);
7792 hba->dev_ref_clk_freq =
7793 ufs_get_bref_clk_from_hz(freq);
7795 if (hba->dev_ref_clk_freq == REF_CLK_FREQ_INVAL)
7797 "invalid ref_clk setting = %ld\n", freq);
7800 static int ufshcd_set_dev_ref_clk(struct ufs_hba *hba)
7804 u32 freq = hba->dev_ref_clk_freq;
7806 err = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
7807 QUERY_ATTR_IDN_REF_CLK_FREQ, 0, 0, &ref_clk);
7810 dev_err(hba->dev, "failed reading bRefClkFreq. err = %d\n",
7815 if (ref_clk == freq)
7816 goto out; /* nothing to update */
7818 err = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_WRITE_ATTR,
7819 QUERY_ATTR_IDN_REF_CLK_FREQ, 0, 0, &freq);
7822 dev_err(hba->dev, "bRefClkFreq setting to %lu Hz failed\n",
7823 ufs_ref_clk_freqs[freq].freq_hz);
7827 dev_dbg(hba->dev, "bRefClkFreq setting to %lu Hz succeeded\n",
7828 ufs_ref_clk_freqs[freq].freq_hz);
7834 static int ufshcd_device_params_init(struct ufs_hba *hba)
7839 /* Init device descriptor sizes */
7840 for (i = 0; i < QUERY_DESC_IDN_MAX; i++)
7841 hba->desc_size[i] = QUERY_DESC_MAX_SIZE;
7843 /* Init UFS geometry descriptor related parameters */
7844 ret = ufshcd_device_geo_params_init(hba);
7848 /* Check and apply UFS device quirks */
7849 ret = ufs_get_device_desc(hba);
7851 dev_err(hba->dev, "%s: Failed getting device info. err = %d\n",
7856 ufshcd_get_ref_clk_gating_wait(hba);
7858 if (!ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_READ_FLAG,
7859 QUERY_FLAG_IDN_PWR_ON_WPE, 0, &flag))
7860 hba->dev_info.f_power_on_wp_en = flag;
7862 /* Probe maximum power mode co-supported by both UFS host and device */
7863 if (ufshcd_get_max_pwr_mode(hba))
7865 "%s: Failed getting max supported power mode\n",
7872 * ufshcd_add_lus - probe and add UFS logical units
7873 * @hba: per-adapter instance
7875 static int ufshcd_add_lus(struct ufs_hba *hba)
7879 /* Add required well known logical units to scsi mid layer */
7880 ret = ufshcd_scsi_add_wlus(hba);
7884 ufshcd_clear_ua_wluns(hba);
7886 /* Initialize devfreq after UFS device is detected */
7887 if (ufshcd_is_clkscaling_supported(hba)) {
7888 memcpy(&hba->clk_scaling.saved_pwr_info.info,
7890 sizeof(struct ufs_pa_layer_attr));
7891 hba->clk_scaling.saved_pwr_info.is_valid = true;
7892 hba->clk_scaling.is_allowed = true;
7894 ret = ufshcd_devfreq_init(hba);
7898 hba->clk_scaling.is_enabled = true;
7899 ufshcd_init_clk_scaling_sysfs(hba);
7903 scsi_scan_host(hba->host);
7904 pm_runtime_put_sync(hba->dev);
7911 ufshcd_send_request_sense(struct ufs_hba *hba, struct scsi_device *sdp);
7913 static int ufshcd_clear_ua_wlun(struct ufs_hba *hba, u8 wlun)
7915 struct scsi_device *sdp;
7916 unsigned long flags;
7919 spin_lock_irqsave(hba->host->host_lock, flags);
7920 if (wlun == UFS_UPIU_UFS_DEVICE_WLUN)
7921 sdp = hba->sdev_ufs_device;
7922 else if (wlun == UFS_UPIU_RPMB_WLUN)
7923 sdp = hba->sdev_rpmb;
7927 ret = scsi_device_get(sdp);
7928 if (!ret && !scsi_device_online(sdp)) {
7930 scsi_device_put(sdp);
7935 spin_unlock_irqrestore(hba->host->host_lock, flags);
7939 ret = ufshcd_send_request_sense(hba, sdp);
7940 scsi_device_put(sdp);
7943 dev_err(hba->dev, "%s: UAC clear LU=%x ret = %d\n",
7944 __func__, wlun, ret);
7948 static int ufshcd_clear_ua_wluns(struct ufs_hba *hba)
7952 if (!hba->wlun_dev_clr_ua)
7955 ret = ufshcd_clear_ua_wlun(hba, UFS_UPIU_UFS_DEVICE_WLUN);
7957 ret = ufshcd_clear_ua_wlun(hba, UFS_UPIU_RPMB_WLUN);
7959 hba->wlun_dev_clr_ua = false;
7962 dev_err(hba->dev, "%s: Failed to clear UAC WLUNS ret = %d\n",
7968 * ufshcd_probe_hba - probe hba to detect device and initialize
7969 * @hba: per-adapter instance
7970 * @async: asynchronous execution or not
7972 * Execute link-startup and verify device initialization
7974 static int ufshcd_probe_hba(struct ufs_hba *hba, bool async)
7977 unsigned long flags;
7978 ktime_t start = ktime_get();
7980 hba->ufshcd_state = UFSHCD_STATE_RESET;
7982 ret = ufshcd_link_startup(hba);
7986 /* Debug counters initialization */
7987 ufshcd_clear_dbg_ufs_stats(hba);
7989 /* UniPro link is active now */
7990 ufshcd_set_link_active(hba);
7992 /* Verify device initialization by sending NOP OUT UPIU */
7993 ret = ufshcd_verify_dev_init(hba);
7997 /* Initiate UFS initialization, and waiting until completion */
7998 ret = ufshcd_complete_dev_init(hba);
8003 * Initialize UFS device parameters used by driver, these
8004 * parameters are associated with UFS descriptors.
8007 ret = ufshcd_device_params_init(hba);
8012 ufshcd_tune_unipro_params(hba);
8014 /* UFS device is also active now */
8015 ufshcd_set_ufs_dev_active(hba);
8016 ufshcd_force_reset_auto_bkops(hba);
8017 hba->wlun_dev_clr_ua = true;
8018 hba->wlun_rpmb_clr_ua = true;
8020 /* Gear up to HS gear if supported */
8021 if (hba->max_pwr_info.is_valid) {
8023 * Set the right value to bRefClkFreq before attempting to
8024 * switch to HS gears.
8026 if (hba->dev_ref_clk_freq != REF_CLK_FREQ_INVAL)
8027 ufshcd_set_dev_ref_clk(hba);
8028 ret = ufshcd_config_pwr_mode(hba, &hba->max_pwr_info.info);
8030 dev_err(hba->dev, "%s: Failed setting power mode, err = %d\n",
8034 ufshcd_print_pwr_info(hba);
8038 * bActiveICCLevel is volatile for UFS device (as per latest v2.1 spec)
8039 * and for removable UFS card as well, hence always set the parameter.
8040 * Note: Error handler may issue the device reset hence resetting
8041 * bActiveICCLevel as well so it is always safe to set this here.
8043 ufshcd_set_active_icc_lvl(hba);
8045 ufshcd_wb_config(hba);
8046 if (hba->ee_usr_mask)
8047 ufshcd_write_ee_control(hba);
8048 /* Enable Auto-Hibernate if configured */
8049 ufshcd_auto_hibern8_enable(hba);
8052 spin_lock_irqsave(hba->host->host_lock, flags);
8054 hba->ufshcd_state = UFSHCD_STATE_ERROR;
8055 else if (hba->ufshcd_state == UFSHCD_STATE_RESET)
8056 hba->ufshcd_state = UFSHCD_STATE_OPERATIONAL;
8057 spin_unlock_irqrestore(hba->host->host_lock, flags);
8059 trace_ufshcd_init(dev_name(hba->dev), ret,
8060 ktime_to_us(ktime_sub(ktime_get(), start)),
8061 hba->curr_dev_pwr_mode, hba->uic_link_state);
8066 * ufshcd_async_scan - asynchronous execution for probing hba
8067 * @data: data pointer to pass to this function
8068 * @cookie: cookie data
8070 static void ufshcd_async_scan(void *data, async_cookie_t cookie)
8072 struct ufs_hba *hba = (struct ufs_hba *)data;
8075 down(&hba->host_sem);
8076 /* Initialize hba, detect and initialize UFS device */
8077 ret = ufshcd_probe_hba(hba, true);
8082 /* Probe and add UFS logical units */
8083 ret = ufshcd_add_lus(hba);
8086 * If we failed to initialize the device or the device is not
8087 * present, turn off the power/clocks etc.
8090 pm_runtime_put_sync(hba->dev);
8091 ufshcd_hba_exit(hba);
8095 static const struct attribute_group *ufshcd_driver_groups[] = {
8096 &ufs_sysfs_unit_descriptor_group,
8097 &ufs_sysfs_lun_attributes_group,
8101 static struct ufs_hba_variant_params ufs_hba_vps = {
8102 .hba_enable_delay_us = 1000,
8103 .wb_flush_threshold = UFS_WB_BUF_REMAIN_PERCENT(40),
8104 .devfreq_profile.polling_ms = 100,
8105 .devfreq_profile.target = ufshcd_devfreq_target,
8106 .devfreq_profile.get_dev_status = ufshcd_devfreq_get_dev_status,
8107 .ondemand_data.upthreshold = 70,
8108 .ondemand_data.downdifferential = 5,
8111 static struct scsi_host_template ufshcd_driver_template = {
8112 .module = THIS_MODULE,
8114 .proc_name = UFSHCD,
8115 .queuecommand = ufshcd_queuecommand,
8116 .slave_alloc = ufshcd_slave_alloc,
8117 .slave_configure = ufshcd_slave_configure,
8118 .slave_destroy = ufshcd_slave_destroy,
8119 .change_queue_depth = ufshcd_change_queue_depth,
8120 .eh_abort_handler = ufshcd_abort,
8121 .eh_device_reset_handler = ufshcd_eh_device_reset_handler,
8122 .eh_host_reset_handler = ufshcd_eh_host_reset_handler,
8124 .sg_tablesize = SG_ALL,
8125 .cmd_per_lun = UFSHCD_CMD_PER_LUN,
8126 .can_queue = UFSHCD_CAN_QUEUE,
8127 .max_segment_size = PRDT_DATA_BYTE_COUNT_MAX,
8128 .max_host_blocked = 1,
8129 .track_queue_depth = 1,
8130 .sdev_groups = ufshcd_driver_groups,
8131 .dma_boundary = PAGE_SIZE - 1,
8132 .rpm_autosuspend_delay = RPM_AUTOSUSPEND_DELAY_MS,
8135 static int ufshcd_config_vreg_load(struct device *dev, struct ufs_vreg *vreg,
8144 * "set_load" operation shall be required on those regulators
8145 * which specifically configured current limitation. Otherwise
8146 * zero max_uA may cause unexpected behavior when regulator is
8147 * enabled or set as high power mode.
8152 ret = regulator_set_load(vreg->reg, ua);
8154 dev_err(dev, "%s: %s set load (ua=%d) failed, err=%d\n",
8155 __func__, vreg->name, ua, ret);
8161 static inline int ufshcd_config_vreg_lpm(struct ufs_hba *hba,
8162 struct ufs_vreg *vreg)
8164 return ufshcd_config_vreg_load(hba->dev, vreg, UFS_VREG_LPM_LOAD_UA);
8167 static inline int ufshcd_config_vreg_hpm(struct ufs_hba *hba,
8168 struct ufs_vreg *vreg)
8173 return ufshcd_config_vreg_load(hba->dev, vreg, vreg->max_uA);
8176 static int ufshcd_config_vreg(struct device *dev,
8177 struct ufs_vreg *vreg, bool on)
8180 struct regulator *reg;
8182 int min_uV, uA_load;
8189 if (regulator_count_voltages(reg) > 0) {
8190 uA_load = on ? vreg->max_uA : 0;
8191 ret = ufshcd_config_vreg_load(dev, vreg, uA_load);
8195 if (vreg->min_uV && vreg->max_uV) {
8196 min_uV = on ? vreg->min_uV : 0;
8197 ret = regulator_set_voltage(reg, min_uV, vreg->max_uV);
8200 "%s: %s set voltage failed, err=%d\n",
8201 __func__, name, ret);
8208 static int ufshcd_enable_vreg(struct device *dev, struct ufs_vreg *vreg)
8212 if (!vreg || vreg->enabled)
8215 ret = ufshcd_config_vreg(dev, vreg, true);
8217 ret = regulator_enable(vreg->reg);
8220 vreg->enabled = true;
8222 dev_err(dev, "%s: %s enable failed, err=%d\n",
8223 __func__, vreg->name, ret);
8228 static int ufshcd_disable_vreg(struct device *dev, struct ufs_vreg *vreg)
8232 if (!vreg || !vreg->enabled || vreg->always_on)
8235 ret = regulator_disable(vreg->reg);
8238 /* ignore errors on applying disable config */
8239 ufshcd_config_vreg(dev, vreg, false);
8240 vreg->enabled = false;
8242 dev_err(dev, "%s: %s disable failed, err=%d\n",
8243 __func__, vreg->name, ret);
8249 static int ufshcd_setup_vreg(struct ufs_hba *hba, bool on)
8252 struct device *dev = hba->dev;
8253 struct ufs_vreg_info *info = &hba->vreg_info;
8255 ret = ufshcd_toggle_vreg(dev, info->vcc, on);
8259 ret = ufshcd_toggle_vreg(dev, info->vccq, on);
8263 ret = ufshcd_toggle_vreg(dev, info->vccq2, on);
8267 ufshcd_toggle_vreg(dev, info->vccq2, false);
8268 ufshcd_toggle_vreg(dev, info->vccq, false);
8269 ufshcd_toggle_vreg(dev, info->vcc, false);
8274 static int ufshcd_setup_hba_vreg(struct ufs_hba *hba, bool on)
8276 struct ufs_vreg_info *info = &hba->vreg_info;
8278 return ufshcd_toggle_vreg(hba->dev, info->vdd_hba, on);
8281 static int ufshcd_get_vreg(struct device *dev, struct ufs_vreg *vreg)
8288 vreg->reg = devm_regulator_get(dev, vreg->name);
8289 if (IS_ERR(vreg->reg)) {
8290 ret = PTR_ERR(vreg->reg);
8291 dev_err(dev, "%s: %s get failed, err=%d\n",
8292 __func__, vreg->name, ret);
8298 static int ufshcd_init_vreg(struct ufs_hba *hba)
8301 struct device *dev = hba->dev;
8302 struct ufs_vreg_info *info = &hba->vreg_info;
8304 ret = ufshcd_get_vreg(dev, info->vcc);
8308 ret = ufshcd_get_vreg(dev, info->vccq);
8310 ret = ufshcd_get_vreg(dev, info->vccq2);
8315 static int ufshcd_init_hba_vreg(struct ufs_hba *hba)
8317 struct ufs_vreg_info *info = &hba->vreg_info;
8320 return ufshcd_get_vreg(hba->dev, info->vdd_hba);
8325 static int ufshcd_setup_clocks(struct ufs_hba *hba, bool on)
8328 struct ufs_clk_info *clki;
8329 struct list_head *head = &hba->clk_list_head;
8330 unsigned long flags;
8331 ktime_t start = ktime_get();
8332 bool clk_state_changed = false;
8334 if (list_empty(head))
8337 ret = ufshcd_vops_setup_clocks(hba, on, PRE_CHANGE);
8341 list_for_each_entry(clki, head, list) {
8342 if (!IS_ERR_OR_NULL(clki->clk)) {
8344 * Don't disable clocks which are needed
8345 * to keep the link active.
8347 if (ufshcd_is_link_active(hba) &&
8348 clki->keep_link_active)
8351 clk_state_changed = on ^ clki->enabled;
8352 if (on && !clki->enabled) {
8353 ret = clk_prepare_enable(clki->clk);
8355 dev_err(hba->dev, "%s: %s prepare enable failed, %d\n",
8356 __func__, clki->name, ret);
8359 } else if (!on && clki->enabled) {
8360 clk_disable_unprepare(clki->clk);
8363 dev_dbg(hba->dev, "%s: clk: %s %sabled\n", __func__,
8364 clki->name, on ? "en" : "dis");
8368 ret = ufshcd_vops_setup_clocks(hba, on, POST_CHANGE);
8374 list_for_each_entry(clki, head, list) {
8375 if (!IS_ERR_OR_NULL(clki->clk) && clki->enabled)
8376 clk_disable_unprepare(clki->clk);
8378 } else if (!ret && on) {
8379 spin_lock_irqsave(hba->host->host_lock, flags);
8380 hba->clk_gating.state = CLKS_ON;
8381 trace_ufshcd_clk_gating(dev_name(hba->dev),
8382 hba->clk_gating.state);
8383 spin_unlock_irqrestore(hba->host->host_lock, flags);
8386 if (clk_state_changed)
8387 trace_ufshcd_profile_clk_gating(dev_name(hba->dev),
8388 (on ? "on" : "off"),
8389 ktime_to_us(ktime_sub(ktime_get(), start)), ret);
8393 static int ufshcd_init_clocks(struct ufs_hba *hba)
8396 struct ufs_clk_info *clki;
8397 struct device *dev = hba->dev;
8398 struct list_head *head = &hba->clk_list_head;
8400 if (list_empty(head))
8403 list_for_each_entry(clki, head, list) {
8407 clki->clk = devm_clk_get(dev, clki->name);
8408 if (IS_ERR(clki->clk)) {
8409 ret = PTR_ERR(clki->clk);
8410 dev_err(dev, "%s: %s clk get failed, %d\n",
8411 __func__, clki->name, ret);
8416 * Parse device ref clk freq as per device tree "ref_clk".
8417 * Default dev_ref_clk_freq is set to REF_CLK_FREQ_INVAL
8418 * in ufshcd_alloc_host().
8420 if (!strcmp(clki->name, "ref_clk"))
8421 ufshcd_parse_dev_ref_clk_freq(hba, clki->clk);
8423 if (clki->max_freq) {
8424 ret = clk_set_rate(clki->clk, clki->max_freq);
8426 dev_err(hba->dev, "%s: %s clk set rate(%dHz) failed, %d\n",
8427 __func__, clki->name,
8428 clki->max_freq, ret);
8431 clki->curr_freq = clki->max_freq;
8433 dev_dbg(dev, "%s: clk: %s, rate: %lu\n", __func__,
8434 clki->name, clk_get_rate(clki->clk));
8440 static int ufshcd_variant_hba_init(struct ufs_hba *hba)
8447 err = ufshcd_vops_init(hba);
8449 dev_err(hba->dev, "%s: variant %s init failed err %d\n",
8450 __func__, ufshcd_get_var_name(hba), err);
8455 static void ufshcd_variant_hba_exit(struct ufs_hba *hba)
8460 ufshcd_vops_exit(hba);
8463 static int ufshcd_hba_init(struct ufs_hba *hba)
8468 * Handle host controller power separately from the UFS device power
8469 * rails as it will help controlling the UFS host controller power
8470 * collapse easily which is different than UFS device power collapse.
8471 * Also, enable the host controller power before we go ahead with rest
8472 * of the initialization here.
8474 err = ufshcd_init_hba_vreg(hba);
8478 err = ufshcd_setup_hba_vreg(hba, true);
8482 err = ufshcd_init_clocks(hba);
8484 goto out_disable_hba_vreg;
8486 err = ufshcd_setup_clocks(hba, true);
8488 goto out_disable_hba_vreg;
8490 err = ufshcd_init_vreg(hba);
8492 goto out_disable_clks;
8494 err = ufshcd_setup_vreg(hba, true);
8496 goto out_disable_clks;
8498 err = ufshcd_variant_hba_init(hba);
8500 goto out_disable_vreg;
8502 ufs_debugfs_hba_init(hba);
8504 hba->is_powered = true;
8508 ufshcd_setup_vreg(hba, false);
8510 ufshcd_setup_clocks(hba, false);
8511 out_disable_hba_vreg:
8512 ufshcd_setup_hba_vreg(hba, false);
8517 static void ufshcd_hba_exit(struct ufs_hba *hba)
8519 if (hba->is_powered) {
8520 ufshcd_exit_clk_scaling(hba);
8521 ufshcd_exit_clk_gating(hba);
8523 destroy_workqueue(hba->eh_wq);
8524 ufs_debugfs_hba_exit(hba);
8525 ufshcd_variant_hba_exit(hba);
8526 ufshcd_setup_vreg(hba, false);
8527 ufshcd_setup_clocks(hba, false);
8528 ufshcd_setup_hba_vreg(hba, false);
8529 hba->is_powered = false;
8530 ufs_put_device_desc(hba);
8535 ufshcd_send_request_sense(struct ufs_hba *hba, struct scsi_device *sdp)
8537 unsigned char cmd[6] = {REQUEST_SENSE,
8546 buffer = kzalloc(UFS_SENSE_SIZE, GFP_KERNEL);
8552 ret = scsi_execute(sdp, cmd, DMA_FROM_DEVICE, buffer,
8553 UFS_SENSE_SIZE, NULL, NULL,
8554 msecs_to_jiffies(1000), 3, 0, RQF_PM, NULL);
8556 pr_err("%s: failed with err %d\n", __func__, ret);
8564 * ufshcd_set_dev_pwr_mode - sends START STOP UNIT command to set device
8566 * @hba: per adapter instance
8567 * @pwr_mode: device power mode to set
8569 * Returns 0 if requested power mode is set successfully
8570 * Returns non-zero if failed to set the requested power mode
8572 static int ufshcd_set_dev_pwr_mode(struct ufs_hba *hba,
8573 enum ufs_dev_pwr_mode pwr_mode)
8575 unsigned char cmd[6] = { START_STOP };
8576 struct scsi_sense_hdr sshdr;
8577 struct scsi_device *sdp;
8578 unsigned long flags;
8581 spin_lock_irqsave(hba->host->host_lock, flags);
8582 sdp = hba->sdev_ufs_device;
8584 ret = scsi_device_get(sdp);
8585 if (!ret && !scsi_device_online(sdp)) {
8587 scsi_device_put(sdp);
8592 spin_unlock_irqrestore(hba->host->host_lock, flags);
8598 * If scsi commands fail, the scsi mid-layer schedules scsi error-
8599 * handling, which would wait for host to be resumed. Since we know
8600 * we are functional while we are here, skip host resume in error
8603 hba->host->eh_noresume = 1;
8604 if (hba->wlun_dev_clr_ua)
8605 ufshcd_clear_ua_wlun(hba, UFS_UPIU_UFS_DEVICE_WLUN);
8607 cmd[4] = pwr_mode << 4;
8610 * Current function would be generally called from the power management
8611 * callbacks hence set the RQF_PM flag so that it doesn't resume the
8612 * already suspended childs.
8614 ret = scsi_execute(sdp, cmd, DMA_NONE, NULL, 0, NULL, &sshdr,
8615 START_STOP_TIMEOUT, 0, 0, RQF_PM, NULL);
8617 sdev_printk(KERN_WARNING, sdp,
8618 "START_STOP failed for power mode: %d, result %x\n",
8620 if (ret > 0 && scsi_sense_valid(&sshdr))
8621 scsi_print_sense_hdr(sdp, NULL, &sshdr);
8625 hba->curr_dev_pwr_mode = pwr_mode;
8627 scsi_device_put(sdp);
8628 hba->host->eh_noresume = 0;
8632 static int ufshcd_link_state_transition(struct ufs_hba *hba,
8633 enum uic_link_state req_link_state,
8634 int check_for_bkops)
8638 if (req_link_state == hba->uic_link_state)
8641 if (req_link_state == UIC_LINK_HIBERN8_STATE) {
8642 ret = ufshcd_uic_hibern8_enter(hba);
8644 ufshcd_set_link_hibern8(hba);
8646 dev_err(hba->dev, "%s: hibern8 enter failed %d\n",
8652 * If autobkops is enabled, link can't be turned off because
8653 * turning off the link would also turn off the device, except in the
8654 * case of DeepSleep where the device is expected to remain powered.
8656 else if ((req_link_state == UIC_LINK_OFF_STATE) &&
8657 (!check_for_bkops || !hba->auto_bkops_enabled)) {
8659 * Let's make sure that link is in low power mode, we are doing
8660 * this currently by putting the link in Hibern8. Otherway to
8661 * put the link in low power mode is to send the DME end point
8662 * to device and then send the DME reset command to local
8663 * unipro. But putting the link in hibern8 is much faster.
8665 * Note also that putting the link in Hibern8 is a requirement
8666 * for entering DeepSleep.
8668 ret = ufshcd_uic_hibern8_enter(hba);
8670 dev_err(hba->dev, "%s: hibern8 enter failed %d\n",
8675 * Change controller state to "reset state" which
8676 * should also put the link in off/reset state
8678 ufshcd_hba_stop(hba);
8680 * TODO: Check if we need any delay to make sure that
8681 * controller is reset
8683 ufshcd_set_link_off(hba);
8690 static void ufshcd_vreg_set_lpm(struct ufs_hba *hba)
8692 bool vcc_off = false;
8695 * It seems some UFS devices may keep drawing more than sleep current
8696 * (atleast for 500us) from UFS rails (especially from VCCQ rail).
8697 * To avoid this situation, add 2ms delay before putting these UFS
8698 * rails in LPM mode.
8700 if (!ufshcd_is_link_active(hba) &&
8701 hba->dev_quirks & UFS_DEVICE_QUIRK_DELAY_BEFORE_LPM)
8702 usleep_range(2000, 2100);
8705 * If UFS device is either in UFS_Sleep turn off VCC rail to save some
8708 * If UFS device and link is in OFF state, all power supplies (VCC,
8709 * VCCQ, VCCQ2) can be turned off if power on write protect is not
8710 * required. If UFS link is inactive (Hibern8 or OFF state) and device
8711 * is in sleep state, put VCCQ & VCCQ2 rails in LPM mode.
8713 * Ignore the error returned by ufshcd_toggle_vreg() as device is anyway
8714 * in low power state which would save some power.
8716 * If Write Booster is enabled and the device needs to flush the WB
8717 * buffer OR if bkops status is urgent for WB, keep Vcc on.
8719 if (ufshcd_is_ufs_dev_poweroff(hba) && ufshcd_is_link_off(hba) &&
8720 !hba->dev_info.is_lu_power_on_wp) {
8721 ufshcd_setup_vreg(hba, false);
8723 } else if (!ufshcd_is_ufs_dev_active(hba)) {
8724 ufshcd_toggle_vreg(hba->dev, hba->vreg_info.vcc, false);
8726 if (ufshcd_is_link_hibern8(hba) || ufshcd_is_link_off(hba)) {
8727 ufshcd_config_vreg_lpm(hba, hba->vreg_info.vccq);
8728 ufshcd_config_vreg_lpm(hba, hba->vreg_info.vccq2);
8733 * Some UFS devices require delay after VCC power rail is turned-off.
8735 if (vcc_off && hba->vreg_info.vcc &&
8736 hba->dev_quirks & UFS_DEVICE_QUIRK_DELAY_AFTER_LPM)
8737 usleep_range(5000, 5100);
8740 static int ufshcd_vreg_set_hpm(struct ufs_hba *hba)
8744 if (ufshcd_is_ufs_dev_poweroff(hba) && ufshcd_is_link_off(hba) &&
8745 !hba->dev_info.is_lu_power_on_wp) {
8746 ret = ufshcd_setup_vreg(hba, true);
8747 } else if (!ufshcd_is_ufs_dev_active(hba)) {
8748 if (!ufshcd_is_link_active(hba)) {
8749 ret = ufshcd_config_vreg_hpm(hba, hba->vreg_info.vccq);
8752 ret = ufshcd_config_vreg_hpm(hba, hba->vreg_info.vccq2);
8756 ret = ufshcd_toggle_vreg(hba->dev, hba->vreg_info.vcc, true);
8761 ufshcd_config_vreg_lpm(hba, hba->vreg_info.vccq);
8763 ufshcd_toggle_vreg(hba->dev, hba->vreg_info.vcc, false);
8768 static void ufshcd_hba_vreg_set_lpm(struct ufs_hba *hba)
8770 if (ufshcd_is_link_off(hba) || ufshcd_can_aggressive_pc(hba))
8771 ufshcd_setup_hba_vreg(hba, false);
8774 static void ufshcd_hba_vreg_set_hpm(struct ufs_hba *hba)
8776 if (ufshcd_is_link_off(hba) || ufshcd_can_aggressive_pc(hba))
8777 ufshcd_setup_hba_vreg(hba, true);
8780 static int __ufshcd_wl_suspend(struct ufs_hba *hba, enum ufs_pm_op pm_op)
8783 int check_for_bkops;
8784 enum ufs_pm_level pm_lvl;
8785 enum ufs_dev_pwr_mode req_dev_pwr_mode;
8786 enum uic_link_state req_link_state;
8788 hba->pm_op_in_progress = true;
8789 if (pm_op != UFS_SHUTDOWN_PM) {
8790 pm_lvl = pm_op == UFS_RUNTIME_PM ?
8791 hba->rpm_lvl : hba->spm_lvl;
8792 req_dev_pwr_mode = ufs_get_pm_lvl_to_dev_pwr_mode(pm_lvl);
8793 req_link_state = ufs_get_pm_lvl_to_link_pwr_state(pm_lvl);
8795 req_dev_pwr_mode = UFS_POWERDOWN_PWR_MODE;
8796 req_link_state = UIC_LINK_OFF_STATE;
8800 * If we can't transition into any of the low power modes
8801 * just gate the clocks.
8803 ufshcd_hold(hba, false);
8804 hba->clk_gating.is_suspended = true;
8806 if (ufshcd_is_clkscaling_supported(hba))
8807 ufshcd_clk_scaling_suspend(hba, true);
8809 if (req_dev_pwr_mode == UFS_ACTIVE_PWR_MODE &&
8810 req_link_state == UIC_LINK_ACTIVE_STATE) {
8814 if ((req_dev_pwr_mode == hba->curr_dev_pwr_mode) &&
8815 (req_link_state == hba->uic_link_state))
8816 goto enable_scaling;
8818 /* UFS device & link must be active before we enter in this function */
8819 if (!ufshcd_is_ufs_dev_active(hba) || !ufshcd_is_link_active(hba)) {
8821 goto enable_scaling;
8824 if (pm_op == UFS_RUNTIME_PM) {
8825 if (ufshcd_can_autobkops_during_suspend(hba)) {
8827 * The device is idle with no requests in the queue,
8828 * allow background operations if bkops status shows
8829 * that performance might be impacted.
8831 ret = ufshcd_urgent_bkops(hba);
8833 goto enable_scaling;
8835 /* make sure that auto bkops is disabled */
8836 ufshcd_disable_auto_bkops(hba);
8839 * If device needs to do BKOP or WB buffer flush during
8840 * Hibern8, keep device power mode as "active power mode"
8843 hba->dev_info.b_rpm_dev_flush_capable =
8844 hba->auto_bkops_enabled ||
8845 (((req_link_state == UIC_LINK_HIBERN8_STATE) ||
8846 ((req_link_state == UIC_LINK_ACTIVE_STATE) &&
8847 ufshcd_is_auto_hibern8_enabled(hba))) &&
8848 ufshcd_wb_need_flush(hba));
8851 flush_work(&hba->eeh_work);
8853 if (req_dev_pwr_mode != hba->curr_dev_pwr_mode) {
8854 if (pm_op != UFS_RUNTIME_PM)
8855 /* ensure that bkops is disabled */
8856 ufshcd_disable_auto_bkops(hba);
8858 if (!hba->dev_info.b_rpm_dev_flush_capable) {
8859 ret = ufshcd_set_dev_pwr_mode(hba, req_dev_pwr_mode);
8861 goto enable_scaling;
8866 * In the case of DeepSleep, the device is expected to remain powered
8867 * with the link off, so do not check for bkops.
8869 check_for_bkops = !ufshcd_is_ufs_dev_deepsleep(hba);
8870 ret = ufshcd_link_state_transition(hba, req_link_state, check_for_bkops);
8872 goto set_dev_active;
8876 * Call vendor specific suspend callback. As these callbacks may access
8877 * vendor specific host controller register space call them before the
8878 * host clocks are ON.
8880 ret = ufshcd_vops_suspend(hba, pm_op);
8882 goto set_link_active;
8887 * Device hardware reset is required to exit DeepSleep. Also, for
8888 * DeepSleep, the link is off so host reset and restore will be done
8891 if (ufshcd_is_ufs_dev_deepsleep(hba)) {
8892 ufshcd_device_reset(hba);
8893 WARN_ON(!ufshcd_is_link_off(hba));
8895 if (ufshcd_is_link_hibern8(hba) && !ufshcd_uic_hibern8_exit(hba))
8896 ufshcd_set_link_active(hba);
8897 else if (ufshcd_is_link_off(hba))
8898 ufshcd_host_reset_and_restore(hba);
8900 /* Can also get here needing to exit DeepSleep */
8901 if (ufshcd_is_ufs_dev_deepsleep(hba)) {
8902 ufshcd_device_reset(hba);
8903 ufshcd_host_reset_and_restore(hba);
8905 if (!ufshcd_set_dev_pwr_mode(hba, UFS_ACTIVE_PWR_MODE))
8906 ufshcd_disable_auto_bkops(hba);
8908 if (ufshcd_is_clkscaling_supported(hba))
8909 ufshcd_clk_scaling_suspend(hba, false);
8911 hba->dev_info.b_rpm_dev_flush_capable = false;
8913 if (hba->dev_info.b_rpm_dev_flush_capable) {
8914 schedule_delayed_work(&hba->rpm_dev_flush_recheck_work,
8915 msecs_to_jiffies(RPM_DEV_FLUSH_RECHECK_WORK_DELAY_MS));
8919 ufshcd_update_evt_hist(hba, UFS_EVT_WL_SUSP_ERR, (u32)ret);
8920 hba->clk_gating.is_suspended = false;
8921 ufshcd_release(hba);
8923 hba->pm_op_in_progress = false;
8927 static int __ufshcd_wl_resume(struct ufs_hba *hba, enum ufs_pm_op pm_op)
8930 enum uic_link_state old_link_state = hba->uic_link_state;
8932 hba->pm_op_in_progress = true;
8935 * Call vendor specific resume callback. As these callbacks may access
8936 * vendor specific host controller register space call them when the
8937 * host clocks are ON.
8939 ret = ufshcd_vops_resume(hba, pm_op);
8943 /* For DeepSleep, the only supported option is to have the link off */
8944 WARN_ON(ufshcd_is_ufs_dev_deepsleep(hba) && !ufshcd_is_link_off(hba));
8946 if (ufshcd_is_link_hibern8(hba)) {
8947 ret = ufshcd_uic_hibern8_exit(hba);
8949 ufshcd_set_link_active(hba);
8951 dev_err(hba->dev, "%s: hibern8 exit failed %d\n",
8953 goto vendor_suspend;
8955 } else if (ufshcd_is_link_off(hba)) {
8957 * A full initialization of the host and the device is
8958 * required since the link was put to off during suspend.
8959 * Note, in the case of DeepSleep, the device will exit
8960 * DeepSleep due to device reset.
8962 ret = ufshcd_reset_and_restore(hba);
8964 * ufshcd_reset_and_restore() should have already
8965 * set the link state as active
8967 if (ret || !ufshcd_is_link_active(hba))
8968 goto vendor_suspend;
8971 if (!ufshcd_is_ufs_dev_active(hba)) {
8972 ret = ufshcd_set_dev_pwr_mode(hba, UFS_ACTIVE_PWR_MODE);
8974 goto set_old_link_state;
8977 if (ufshcd_keep_autobkops_enabled_except_suspend(hba))
8978 ufshcd_enable_auto_bkops(hba);
8981 * If BKOPs operations are urgently needed at this moment then
8982 * keep auto-bkops enabled or else disable it.
8984 ufshcd_urgent_bkops(hba);
8986 if (hba->ee_usr_mask)
8987 ufshcd_write_ee_control(hba);
8989 if (ufshcd_is_clkscaling_supported(hba))
8990 ufshcd_clk_scaling_suspend(hba, false);
8992 if (hba->dev_info.b_rpm_dev_flush_capable) {
8993 hba->dev_info.b_rpm_dev_flush_capable = false;
8994 cancel_delayed_work(&hba->rpm_dev_flush_recheck_work);
8997 /* Enable Auto-Hibernate if configured */
8998 ufshcd_auto_hibern8_enable(hba);
9002 ufshcd_link_state_transition(hba, old_link_state, 0);
9004 ufshcd_vops_suspend(hba, pm_op);
9007 ufshcd_update_evt_hist(hba, UFS_EVT_WL_RES_ERR, (u32)ret);
9008 hba->clk_gating.is_suspended = false;
9009 ufshcd_release(hba);
9010 hba->pm_op_in_progress = false;
9014 static int ufshcd_wl_runtime_suspend(struct device *dev)
9016 struct scsi_device *sdev = to_scsi_device(dev);
9017 struct ufs_hba *hba;
9019 ktime_t start = ktime_get();
9021 hba = shost_priv(sdev->host);
9023 ret = __ufshcd_wl_suspend(hba, UFS_RUNTIME_PM);
9025 dev_err(&sdev->sdev_gendev, "%s failed: %d\n", __func__, ret);
9027 trace_ufshcd_wl_runtime_suspend(dev_name(dev), ret,
9028 ktime_to_us(ktime_sub(ktime_get(), start)),
9029 hba->curr_dev_pwr_mode, hba->uic_link_state);
9034 static int ufshcd_wl_runtime_resume(struct device *dev)
9036 struct scsi_device *sdev = to_scsi_device(dev);
9037 struct ufs_hba *hba;
9039 ktime_t start = ktime_get();
9041 hba = shost_priv(sdev->host);
9043 ret = __ufshcd_wl_resume(hba, UFS_RUNTIME_PM);
9045 dev_err(&sdev->sdev_gendev, "%s failed: %d\n", __func__, ret);
9047 trace_ufshcd_wl_runtime_resume(dev_name(dev), ret,
9048 ktime_to_us(ktime_sub(ktime_get(), start)),
9049 hba->curr_dev_pwr_mode, hba->uic_link_state);
9054 #ifdef CONFIG_PM_SLEEP
9055 static int ufshcd_wl_suspend(struct device *dev)
9057 struct scsi_device *sdev = to_scsi_device(dev);
9058 struct ufs_hba *hba;
9060 ktime_t start = ktime_get();
9062 hba = shost_priv(sdev->host);
9063 down(&hba->host_sem);
9065 if (pm_runtime_suspended(dev))
9068 ret = __ufshcd_wl_suspend(hba, UFS_SYSTEM_PM);
9070 dev_err(&sdev->sdev_gendev, "%s failed: %d\n", __func__, ret);
9076 hba->is_sys_suspended = true;
9077 trace_ufshcd_wl_suspend(dev_name(dev), ret,
9078 ktime_to_us(ktime_sub(ktime_get(), start)),
9079 hba->curr_dev_pwr_mode, hba->uic_link_state);
9084 static int ufshcd_wl_resume(struct device *dev)
9086 struct scsi_device *sdev = to_scsi_device(dev);
9087 struct ufs_hba *hba;
9089 ktime_t start = ktime_get();
9091 hba = shost_priv(sdev->host);
9093 if (pm_runtime_suspended(dev))
9096 ret = __ufshcd_wl_resume(hba, UFS_SYSTEM_PM);
9098 dev_err(&sdev->sdev_gendev, "%s failed: %d\n", __func__, ret);
9100 trace_ufshcd_wl_resume(dev_name(dev), ret,
9101 ktime_to_us(ktime_sub(ktime_get(), start)),
9102 hba->curr_dev_pwr_mode, hba->uic_link_state);
9104 hba->is_sys_suspended = false;
9110 static void ufshcd_wl_shutdown(struct device *dev)
9112 struct scsi_device *sdev = to_scsi_device(dev);
9113 struct ufs_hba *hba;
9115 hba = shost_priv(sdev->host);
9117 down(&hba->host_sem);
9118 hba->shutting_down = true;
9121 /* Turn on everything while shutting down */
9122 ufshcd_rpm_get_sync(hba);
9123 scsi_device_quiesce(sdev);
9124 shost_for_each_device(sdev, hba->host) {
9125 if (sdev == hba->sdev_ufs_device)
9127 scsi_device_quiesce(sdev);
9129 __ufshcd_wl_suspend(hba, UFS_SHUTDOWN_PM);
9133 * ufshcd_suspend - helper function for suspend operations
9134 * @hba: per adapter instance
9136 * This function will put disable irqs, turn off clocks
9137 * and set vreg and hba-vreg in lpm mode.
9139 static int ufshcd_suspend(struct ufs_hba *hba)
9143 if (!hba->is_powered)
9146 * Disable the host irq as host controller as there won't be any
9147 * host controller transaction expected till resume.
9149 ufshcd_disable_irq(hba);
9150 ret = ufshcd_setup_clocks(hba, false);
9152 ufshcd_enable_irq(hba);
9155 if (ufshcd_is_clkgating_allowed(hba)) {
9156 hba->clk_gating.state = CLKS_OFF;
9157 trace_ufshcd_clk_gating(dev_name(hba->dev),
9158 hba->clk_gating.state);
9161 ufshcd_vreg_set_lpm(hba);
9162 /* Put the host controller in low power mode if possible */
9163 ufshcd_hba_vreg_set_lpm(hba);
9168 * ufshcd_resume - helper function for resume operations
9169 * @hba: per adapter instance
9171 * This function basically turns on the regulators, clocks and
9174 * Returns 0 for success and non-zero for failure
9176 static int ufshcd_resume(struct ufs_hba *hba)
9180 if (!hba->is_powered)
9183 ufshcd_hba_vreg_set_hpm(hba);
9184 ret = ufshcd_vreg_set_hpm(hba);
9188 /* Make sure clocks are enabled before accessing controller */
9189 ret = ufshcd_setup_clocks(hba, true);
9193 /* enable the host irq as host controller would be active soon */
9194 ufshcd_enable_irq(hba);
9198 ufshcd_vreg_set_lpm(hba);
9201 ufshcd_update_evt_hist(hba, UFS_EVT_RESUME_ERR, (u32)ret);
9206 * ufshcd_system_suspend - system suspend routine
9207 * @hba: per adapter instance
9209 * Check the description of ufshcd_suspend() function for more details.
9211 * Returns 0 for success and non-zero for failure
9213 int ufshcd_system_suspend(struct ufs_hba *hba)
9216 ktime_t start = ktime_get();
9218 if (pm_runtime_suspended(hba->dev))
9221 ret = ufshcd_suspend(hba);
9223 trace_ufshcd_system_suspend(dev_name(hba->dev), ret,
9224 ktime_to_us(ktime_sub(ktime_get(), start)),
9225 hba->curr_dev_pwr_mode, hba->uic_link_state);
9228 EXPORT_SYMBOL(ufshcd_system_suspend);
9231 * ufshcd_system_resume - system resume routine
9232 * @hba: per adapter instance
9234 * Returns 0 for success and non-zero for failure
9237 int ufshcd_system_resume(struct ufs_hba *hba)
9240 ktime_t start = ktime_get();
9242 if (pm_runtime_suspended(hba->dev))
9245 ret = ufshcd_resume(hba);
9248 trace_ufshcd_system_resume(dev_name(hba->dev), ret,
9249 ktime_to_us(ktime_sub(ktime_get(), start)),
9250 hba->curr_dev_pwr_mode, hba->uic_link_state);
9254 EXPORT_SYMBOL(ufshcd_system_resume);
9257 * ufshcd_runtime_suspend - runtime suspend routine
9258 * @hba: per adapter instance
9260 * Check the description of ufshcd_suspend() function for more details.
9262 * Returns 0 for success and non-zero for failure
9264 int ufshcd_runtime_suspend(struct ufs_hba *hba)
9267 ktime_t start = ktime_get();
9269 ret = ufshcd_suspend(hba);
9271 trace_ufshcd_runtime_suspend(dev_name(hba->dev), ret,
9272 ktime_to_us(ktime_sub(ktime_get(), start)),
9273 hba->curr_dev_pwr_mode, hba->uic_link_state);
9276 EXPORT_SYMBOL(ufshcd_runtime_suspend);
9279 * ufshcd_runtime_resume - runtime resume routine
9280 * @hba: per adapter instance
9282 * This function basically brings controller
9283 * to active state. Following operations are done in this function:
9285 * 1. Turn on all the controller related clocks
9286 * 2. Turn ON VCC rail
9288 int ufshcd_runtime_resume(struct ufs_hba *hba)
9291 ktime_t start = ktime_get();
9293 ret = ufshcd_resume(hba);
9295 trace_ufshcd_runtime_resume(dev_name(hba->dev), ret,
9296 ktime_to_us(ktime_sub(ktime_get(), start)),
9297 hba->curr_dev_pwr_mode, hba->uic_link_state);
9300 EXPORT_SYMBOL(ufshcd_runtime_resume);
9302 int ufshcd_runtime_idle(struct ufs_hba *hba)
9306 EXPORT_SYMBOL(ufshcd_runtime_idle);
9309 * ufshcd_shutdown - shutdown routine
9310 * @hba: per adapter instance
9312 * This function would turn off both UFS device and UFS hba
9313 * regulators. It would also disable clocks.
9315 * Returns 0 always to allow force shutdown even in case of errors.
9317 int ufshcd_shutdown(struct ufs_hba *hba)
9319 if (ufshcd_is_ufs_dev_poweroff(hba) && ufshcd_is_link_off(hba))
9322 pm_runtime_get_sync(hba->dev);
9324 ufshcd_suspend(hba);
9326 hba->is_powered = false;
9327 /* allow force shutdown even in case of errors */
9330 EXPORT_SYMBOL(ufshcd_shutdown);
9333 * ufshcd_remove - de-allocate SCSI host and host memory space
9334 * data structure memory
9335 * @hba: per adapter instance
9337 void ufshcd_remove(struct ufs_hba *hba)
9339 if (hba->sdev_ufs_device)
9340 ufshcd_rpm_get_sync(hba);
9341 ufs_bsg_remove(hba);
9342 ufs_sysfs_remove_nodes(hba->dev);
9343 blk_cleanup_queue(hba->tmf_queue);
9344 blk_mq_free_tag_set(&hba->tmf_tag_set);
9345 blk_cleanup_queue(hba->cmd_queue);
9346 scsi_remove_host(hba->host);
9347 /* disable interrupts */
9348 ufshcd_disable_intr(hba, hba->intr_mask);
9349 ufshcd_hba_stop(hba);
9350 ufshcd_hba_exit(hba);
9352 EXPORT_SYMBOL_GPL(ufshcd_remove);
9355 * ufshcd_dealloc_host - deallocate Host Bus Adapter (HBA)
9356 * @hba: pointer to Host Bus Adapter (HBA)
9358 void ufshcd_dealloc_host(struct ufs_hba *hba)
9360 scsi_host_put(hba->host);
9362 EXPORT_SYMBOL_GPL(ufshcd_dealloc_host);
9365 * ufshcd_set_dma_mask - Set dma mask based on the controller
9366 * addressing capability
9367 * @hba: per adapter instance
9369 * Returns 0 for success, non-zero for failure
9371 static int ufshcd_set_dma_mask(struct ufs_hba *hba)
9373 if (hba->capabilities & MASK_64_ADDRESSING_SUPPORT) {
9374 if (!dma_set_mask_and_coherent(hba->dev, DMA_BIT_MASK(64)))
9377 return dma_set_mask_and_coherent(hba->dev, DMA_BIT_MASK(32));
9381 * ufshcd_alloc_host - allocate Host Bus Adapter (HBA)
9382 * @dev: pointer to device handle
9383 * @hba_handle: driver private handle
9384 * Returns 0 on success, non-zero value on failure
9386 int ufshcd_alloc_host(struct device *dev, struct ufs_hba **hba_handle)
9388 struct Scsi_Host *host;
9389 struct ufs_hba *hba;
9394 "Invalid memory reference for dev is NULL\n");
9399 host = scsi_host_alloc(&ufshcd_driver_template,
9400 sizeof(struct ufs_hba));
9402 dev_err(dev, "scsi_host_alloc failed\n");
9406 hba = shost_priv(host);
9410 hba->dev_ref_clk_freq = REF_CLK_FREQ_INVAL;
9412 INIT_LIST_HEAD(&hba->clk_list_head);
9417 EXPORT_SYMBOL(ufshcd_alloc_host);
9419 /* This function exists because blk_mq_alloc_tag_set() requires this. */
9420 static blk_status_t ufshcd_queue_tmf(struct blk_mq_hw_ctx *hctx,
9421 const struct blk_mq_queue_data *qd)
9424 return BLK_STS_NOTSUPP;
9427 static const struct blk_mq_ops ufshcd_tmf_ops = {
9428 .queue_rq = ufshcd_queue_tmf,
9432 * ufshcd_init - Driver initialization routine
9433 * @hba: per-adapter instance
9434 * @mmio_base: base register address
9435 * @irq: Interrupt line of device
9436 * Returns 0 on success, non-zero value on failure
9438 int ufshcd_init(struct ufs_hba *hba, void __iomem *mmio_base, unsigned int irq)
9441 struct Scsi_Host *host = hba->host;
9442 struct device *dev = hba->dev;
9443 char eh_wq_name[sizeof("ufs_eh_wq_00")];
9447 "Invalid memory reference for mmio_base is NULL\n");
9452 hba->mmio_base = mmio_base;
9454 hba->vps = &ufs_hba_vps;
9456 err = ufshcd_hba_init(hba);
9460 /* Read capabilities registers */
9461 err = ufshcd_hba_capabilities(hba);
9465 /* Get UFS version supported by the controller */
9466 hba->ufs_version = ufshcd_get_ufs_version(hba);
9468 /* Get Interrupt bit mask per version */
9469 hba->intr_mask = ufshcd_get_intr_mask(hba);
9471 err = ufshcd_set_dma_mask(hba);
9473 dev_err(hba->dev, "set dma mask failed\n");
9477 /* Allocate memory for host memory space */
9478 err = ufshcd_memory_alloc(hba);
9480 dev_err(hba->dev, "Memory allocation failed\n");
9485 ufshcd_host_memory_configure(hba);
9487 host->can_queue = hba->nutrs;
9488 host->cmd_per_lun = hba->nutrs;
9489 host->max_id = UFSHCD_MAX_ID;
9490 host->max_lun = UFS_MAX_LUNS;
9491 host->max_channel = UFSHCD_MAX_CHANNEL;
9492 host->unique_id = host->host_no;
9493 host->max_cmd_len = UFS_CDB_SIZE;
9495 hba->max_pwr_info.is_valid = false;
9497 /* Initialize work queues */
9498 snprintf(eh_wq_name, sizeof(eh_wq_name), "ufs_eh_wq_%d",
9499 hba->host->host_no);
9500 hba->eh_wq = create_singlethread_workqueue(eh_wq_name);
9502 dev_err(hba->dev, "%s: failed to create eh workqueue\n",
9507 INIT_WORK(&hba->eh_work, ufshcd_err_handler);
9508 INIT_WORK(&hba->eeh_work, ufshcd_exception_event_handler);
9510 sema_init(&hba->host_sem, 1);
9512 /* Initialize UIC command mutex */
9513 mutex_init(&hba->uic_cmd_mutex);
9515 /* Initialize mutex for device management commands */
9516 mutex_init(&hba->dev_cmd.lock);
9518 /* Initialize mutex for exception event control */
9519 mutex_init(&hba->ee_ctrl_mutex);
9521 init_rwsem(&hba->clk_scaling_lock);
9523 ufshcd_init_clk_gating(hba);
9525 ufshcd_init_clk_scaling(hba);
9528 * In order to avoid any spurious interrupt immediately after
9529 * registering UFS controller interrupt handler, clear any pending UFS
9530 * interrupt status and disable all the UFS interrupts.
9532 ufshcd_writel(hba, ufshcd_readl(hba, REG_INTERRUPT_STATUS),
9533 REG_INTERRUPT_STATUS);
9534 ufshcd_writel(hba, 0, REG_INTERRUPT_ENABLE);
9536 * Make sure that UFS interrupts are disabled and any pending interrupt
9537 * status is cleared before registering UFS interrupt handler.
9541 /* IRQ registration */
9542 err = devm_request_irq(dev, irq, ufshcd_intr, IRQF_SHARED, UFSHCD, hba);
9544 dev_err(hba->dev, "request irq failed\n");
9547 hba->is_irq_enabled = true;
9550 err = scsi_add_host(host, hba->dev);
9552 dev_err(hba->dev, "scsi_add_host failed\n");
9556 hba->cmd_queue = blk_mq_init_queue(&hba->host->tag_set);
9557 if (IS_ERR(hba->cmd_queue)) {
9558 err = PTR_ERR(hba->cmd_queue);
9559 goto out_remove_scsi_host;
9562 hba->tmf_tag_set = (struct blk_mq_tag_set) {
9564 .queue_depth = hba->nutmrs,
9565 .ops = &ufshcd_tmf_ops,
9566 .flags = BLK_MQ_F_NO_SCHED,
9568 err = blk_mq_alloc_tag_set(&hba->tmf_tag_set);
9570 goto free_cmd_queue;
9571 hba->tmf_queue = blk_mq_init_queue(&hba->tmf_tag_set);
9572 if (IS_ERR(hba->tmf_queue)) {
9573 err = PTR_ERR(hba->tmf_queue);
9574 goto free_tmf_tag_set;
9577 /* Reset the attached device */
9578 ufshcd_device_reset(hba);
9580 ufshcd_init_crypto(hba);
9582 /* Host controller enable */
9583 err = ufshcd_hba_enable(hba);
9585 dev_err(hba->dev, "Host controller enable failed\n");
9586 ufshcd_print_evt_hist(hba);
9587 ufshcd_print_host_state(hba);
9588 goto free_tmf_queue;
9592 * Set the default power management level for runtime and system PM.
9593 * Default power saving mode is to keep UFS link in Hibern8 state
9594 * and UFS device in sleep state.
9596 hba->rpm_lvl = ufs_get_desired_pm_lvl_for_dev_link_state(
9598 UIC_LINK_HIBERN8_STATE);
9599 hba->spm_lvl = ufs_get_desired_pm_lvl_for_dev_link_state(
9601 UIC_LINK_HIBERN8_STATE);
9603 INIT_DELAYED_WORK(&hba->rpm_dev_flush_recheck_work,
9604 ufshcd_rpm_dev_flush_recheck_work);
9606 /* Set the default auto-hiberate idle timer value to 150 ms */
9607 if (ufshcd_is_auto_hibern8_supported(hba) && !hba->ahit) {
9608 hba->ahit = FIELD_PREP(UFSHCI_AHIBERN8_TIMER_MASK, 150) |
9609 FIELD_PREP(UFSHCI_AHIBERN8_SCALE_MASK, 3);
9612 /* Hold auto suspend until async scan completes */
9613 pm_runtime_get_sync(dev);
9614 atomic_set(&hba->scsi_block_reqs_cnt, 0);
9616 * We are assuming that device wasn't put in sleep/power-down
9617 * state exclusively during the boot stage before kernel.
9618 * This assumption helps avoid doing link startup twice during
9619 * ufshcd_probe_hba().
9621 ufshcd_set_ufs_dev_active(hba);
9623 async_schedule(ufshcd_async_scan, hba);
9624 ufs_sysfs_add_nodes(hba->dev);
9629 blk_cleanup_queue(hba->tmf_queue);
9631 blk_mq_free_tag_set(&hba->tmf_tag_set);
9633 blk_cleanup_queue(hba->cmd_queue);
9634 out_remove_scsi_host:
9635 scsi_remove_host(hba->host);
9637 hba->is_irq_enabled = false;
9638 ufshcd_hba_exit(hba);
9642 EXPORT_SYMBOL_GPL(ufshcd_init);
9644 void ufshcd_resume_complete(struct device *dev)
9646 struct ufs_hba *hba = dev_get_drvdata(dev);
9648 if (hba->complete_put) {
9649 ufshcd_rpm_put(hba);
9650 hba->complete_put = false;
9652 if (hba->rpmb_complete_put) {
9653 ufshcd_rpmb_rpm_put(hba);
9654 hba->rpmb_complete_put = false;
9657 EXPORT_SYMBOL_GPL(ufshcd_resume_complete);
9659 int ufshcd_suspend_prepare(struct device *dev)
9661 struct ufs_hba *hba = dev_get_drvdata(dev);
9665 * SCSI assumes that runtime-pm and system-pm for scsi drivers
9666 * are same. And it doesn't wake up the device for system-suspend
9667 * if it's runtime suspended. But ufs doesn't follow that.
9668 * Refer ufshcd_resume_complete()
9670 if (hba->sdev_ufs_device) {
9671 ret = ufshcd_rpm_get_sync(hba);
9672 if (ret < 0 && ret != -EACCES) {
9673 ufshcd_rpm_put(hba);
9676 hba->complete_put = true;
9678 if (hba->sdev_rpmb) {
9679 ufshcd_rpmb_rpm_get_sync(hba);
9680 hba->rpmb_complete_put = true;
9684 EXPORT_SYMBOL_GPL(ufshcd_suspend_prepare);
9686 #ifdef CONFIG_PM_SLEEP
9687 static int ufshcd_wl_poweroff(struct device *dev)
9689 struct scsi_device *sdev = to_scsi_device(dev);
9690 struct ufs_hba *hba = shost_priv(sdev->host);
9692 __ufshcd_wl_suspend(hba, UFS_SHUTDOWN_PM);
9697 static int ufshcd_wl_probe(struct device *dev)
9699 struct scsi_device *sdev = to_scsi_device(dev);
9701 if (!is_device_wlun(sdev))
9704 blk_pm_runtime_init(sdev->request_queue, dev);
9705 pm_runtime_set_autosuspend_delay(dev, 0);
9706 pm_runtime_allow(dev);
9711 static int ufshcd_wl_remove(struct device *dev)
9713 pm_runtime_forbid(dev);
9717 static const struct dev_pm_ops ufshcd_wl_pm_ops = {
9718 #ifdef CONFIG_PM_SLEEP
9719 .suspend = ufshcd_wl_suspend,
9720 .resume = ufshcd_wl_resume,
9721 .freeze = ufshcd_wl_suspend,
9722 .thaw = ufshcd_wl_resume,
9723 .poweroff = ufshcd_wl_poweroff,
9724 .restore = ufshcd_wl_resume,
9726 SET_RUNTIME_PM_OPS(ufshcd_wl_runtime_suspend, ufshcd_wl_runtime_resume, NULL)
9730 * ufs_dev_wlun_template - describes ufs device wlun
9731 * ufs-device wlun - used to send pm commands
9732 * All luns are consumers of ufs-device wlun.
9734 * Currently, no sd driver is present for wluns.
9735 * Hence the no specific pm operations are performed.
9736 * With ufs design, SSU should be sent to ufs-device wlun.
9737 * Hence register a scsi driver for ufs wluns only.
9739 static struct scsi_driver ufs_dev_wlun_template = {
9741 .name = "ufs_device_wlun",
9742 .owner = THIS_MODULE,
9743 .probe = ufshcd_wl_probe,
9744 .remove = ufshcd_wl_remove,
9745 .pm = &ufshcd_wl_pm_ops,
9746 .shutdown = ufshcd_wl_shutdown,
9750 static int ufshcd_rpmb_probe(struct device *dev)
9752 return is_rpmb_wlun(to_scsi_device(dev)) ? 0 : -ENODEV;
9755 static inline int ufshcd_clear_rpmb_uac(struct ufs_hba *hba)
9759 if (!hba->wlun_rpmb_clr_ua)
9761 ret = ufshcd_clear_ua_wlun(hba, UFS_UPIU_RPMB_WLUN);
9763 hba->wlun_rpmb_clr_ua = 0;
9767 static int ufshcd_rpmb_resume(struct device *dev)
9769 struct ufs_hba *hba = wlun_dev_to_hba(dev);
9772 ufshcd_clear_rpmb_uac(hba);
9776 static const struct dev_pm_ops ufs_rpmb_pm_ops = {
9777 SET_RUNTIME_PM_OPS(NULL, ufshcd_rpmb_resume, NULL)
9778 SET_SYSTEM_SLEEP_PM_OPS(NULL, ufshcd_rpmb_resume)
9781 /* ufs_rpmb_wlun_template - Describes UFS RPMB WLUN. Used only to send UAC. */
9782 static struct scsi_driver ufs_rpmb_wlun_template = {
9784 .name = "ufs_rpmb_wlun",
9785 .owner = THIS_MODULE,
9786 .probe = ufshcd_rpmb_probe,
9787 .pm = &ufs_rpmb_pm_ops,
9791 static int __init ufshcd_core_init(void)
9797 ret = scsi_register_driver(&ufs_dev_wlun_template.gendrv);
9801 ret = scsi_register_driver(&ufs_rpmb_wlun_template.gendrv);
9807 scsi_unregister_driver(&ufs_dev_wlun_template.gendrv);
9813 static void __exit ufshcd_core_exit(void)
9816 scsi_unregister_driver(&ufs_rpmb_wlun_template.gendrv);
9817 scsi_unregister_driver(&ufs_dev_wlun_template.gendrv);
9820 module_init(ufshcd_core_init);
9821 module_exit(ufshcd_core_exit);
9823 MODULE_AUTHOR("Santosh Yaragnavi <santosh.sy@samsung.com>");
9824 MODULE_AUTHOR("Vinayak Holikatti <h.vinayak@samsung.com>");
9825 MODULE_DESCRIPTION("Generic UFS host controller driver Core");
9826 MODULE_LICENSE("GPL");
9827 MODULE_VERSION(UFSHCD_DRIVER_VERSION);