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>
19 #include "ufs_quirks.h"
21 #include "ufs-sysfs.h"
23 #include "ufshcd-crypto.h"
24 #include <asm/unaligned.h>
25 #include <linux/blkdev.h>
27 #define CREATE_TRACE_POINTS
28 #include <trace/events/ufs.h>
30 #define UFSHCD_ENABLE_INTRS (UTP_TRANSFER_REQ_COMPL |\
33 /* UIC command timeout, unit: ms */
34 #define UIC_CMD_TIMEOUT 500
36 /* NOP OUT retries waiting for NOP IN response */
37 #define NOP_OUT_RETRIES 10
38 /* Timeout after 30 msecs if NOP OUT hangs without response */
39 #define NOP_OUT_TIMEOUT 30 /* msecs */
41 /* Query request retries */
42 #define QUERY_REQ_RETRIES 3
43 /* Query request timeout */
44 #define QUERY_REQ_TIMEOUT 1500 /* 1.5 seconds */
46 /* Task management command timeout */
47 #define TM_CMD_TIMEOUT 100 /* msecs */
49 /* maximum number of retries for a general UIC command */
50 #define UFS_UIC_COMMAND_RETRIES 3
52 /* maximum number of link-startup retries */
53 #define DME_LINKSTARTUP_RETRIES 3
55 /* Maximum retries for Hibern8 enter */
56 #define UIC_HIBERN8_ENTER_RETRIES 3
58 /* maximum number of reset retries before giving up */
59 #define MAX_HOST_RESET_RETRIES 5
61 /* Expose the flag value from utp_upiu_query.value */
62 #define MASK_QUERY_UPIU_FLAG_LOC 0xFF
64 /* Interrupt aggregation default timeout, unit: 40us */
65 #define INT_AGGR_DEF_TO 0x02
67 /* default delay of autosuspend: 2000 ms */
68 #define RPM_AUTOSUSPEND_DELAY_MS 2000
70 /* Default delay of RPM device flush delayed work */
71 #define RPM_DEV_FLUSH_RECHECK_WORK_DELAY_MS 5000
73 /* Default value of wait time before gating device ref clock */
74 #define UFSHCD_REF_CLK_GATING_WAIT_US 0xFF /* microsecs */
76 #define ufshcd_toggle_vreg(_dev, _vreg, _on) \
80 _ret = ufshcd_enable_vreg(_dev, _vreg); \
82 _ret = ufshcd_disable_vreg(_dev, _vreg); \
86 #define ufshcd_hex_dump(prefix_str, buf, len) do { \
87 size_t __len = (len); \
88 print_hex_dump(KERN_ERR, prefix_str, \
89 __len > 4 ? DUMP_PREFIX_OFFSET : DUMP_PREFIX_NONE,\
90 16, 4, buf, __len, false); \
93 int ufshcd_dump_regs(struct ufs_hba *hba, size_t offset, size_t len,
99 if (offset % 4 != 0 || len % 4 != 0) /* keep readl happy */
102 regs = kzalloc(len, GFP_ATOMIC);
106 for (pos = 0; pos < len; pos += 4)
107 regs[pos / 4] = ufshcd_readl(hba, offset + pos);
109 ufshcd_hex_dump(prefix, regs, len);
114 EXPORT_SYMBOL_GPL(ufshcd_dump_regs);
117 UFSHCD_MAX_CHANNEL = 0,
119 UFSHCD_CMD_PER_LUN = 32,
120 UFSHCD_CAN_QUEUE = 32,
127 UFSHCD_STATE_OPERATIONAL,
128 UFSHCD_STATE_EH_SCHEDULED,
131 /* UFSHCD error handling flags */
133 UFSHCD_EH_IN_PROGRESS = (1 << 0),
136 /* UFSHCD UIC layer error flags */
138 UFSHCD_UIC_DL_PA_INIT_ERROR = (1 << 0), /* Data link layer error */
139 UFSHCD_UIC_DL_NAC_RECEIVED_ERROR = (1 << 1), /* Data link layer error */
140 UFSHCD_UIC_DL_TCx_REPLAY_ERROR = (1 << 2), /* Data link layer error */
141 UFSHCD_UIC_NL_ERROR = (1 << 3), /* Network layer error */
142 UFSHCD_UIC_TL_ERROR = (1 << 4), /* Transport Layer error */
143 UFSHCD_UIC_DME_ERROR = (1 << 5), /* DME error */
146 #define ufshcd_set_eh_in_progress(h) \
147 ((h)->eh_flags |= UFSHCD_EH_IN_PROGRESS)
148 #define ufshcd_eh_in_progress(h) \
149 ((h)->eh_flags & UFSHCD_EH_IN_PROGRESS)
150 #define ufshcd_clear_eh_in_progress(h) \
151 ((h)->eh_flags &= ~UFSHCD_EH_IN_PROGRESS)
153 struct ufs_pm_lvl_states ufs_pm_lvl_states[] = {
154 {UFS_ACTIVE_PWR_MODE, UIC_LINK_ACTIVE_STATE},
155 {UFS_ACTIVE_PWR_MODE, UIC_LINK_HIBERN8_STATE},
156 {UFS_SLEEP_PWR_MODE, UIC_LINK_ACTIVE_STATE},
157 {UFS_SLEEP_PWR_MODE, UIC_LINK_HIBERN8_STATE},
158 {UFS_POWERDOWN_PWR_MODE, UIC_LINK_HIBERN8_STATE},
159 {UFS_POWERDOWN_PWR_MODE, UIC_LINK_OFF_STATE},
162 static inline enum ufs_dev_pwr_mode
163 ufs_get_pm_lvl_to_dev_pwr_mode(enum ufs_pm_level lvl)
165 return ufs_pm_lvl_states[lvl].dev_state;
168 static inline enum uic_link_state
169 ufs_get_pm_lvl_to_link_pwr_state(enum ufs_pm_level lvl)
171 return ufs_pm_lvl_states[lvl].link_state;
174 static inline enum ufs_pm_level
175 ufs_get_desired_pm_lvl_for_dev_link_state(enum ufs_dev_pwr_mode dev_state,
176 enum uic_link_state link_state)
178 enum ufs_pm_level lvl;
180 for (lvl = UFS_PM_LVL_0; lvl < UFS_PM_LVL_MAX; lvl++) {
181 if ((ufs_pm_lvl_states[lvl].dev_state == dev_state) &&
182 (ufs_pm_lvl_states[lvl].link_state == link_state))
186 /* if no match found, return the level 0 */
190 static struct ufs_dev_fix ufs_fixups[] = {
191 /* UFS cards deviations table */
192 UFS_FIX(UFS_VENDOR_MICRON, UFS_ANY_MODEL,
193 UFS_DEVICE_QUIRK_DELAY_BEFORE_LPM),
194 UFS_FIX(UFS_VENDOR_SAMSUNG, UFS_ANY_MODEL,
195 UFS_DEVICE_QUIRK_DELAY_BEFORE_LPM |
196 UFS_DEVICE_QUIRK_HOST_PA_TACTIVATE |
197 UFS_DEVICE_QUIRK_RECOVERY_FROM_DL_NAC_ERRORS),
198 UFS_FIX(UFS_VENDOR_SKHYNIX, UFS_ANY_MODEL,
199 UFS_DEVICE_QUIRK_HOST_PA_SAVECONFIGTIME),
200 UFS_FIX(UFS_VENDOR_SKHYNIX, "hB8aL1" /*H28U62301AMR*/,
201 UFS_DEVICE_QUIRK_HOST_VS_DEBUGSAVECONFIGTIME),
202 UFS_FIX(UFS_VENDOR_TOSHIBA, UFS_ANY_MODEL,
203 UFS_DEVICE_QUIRK_DELAY_BEFORE_LPM),
204 UFS_FIX(UFS_VENDOR_TOSHIBA, "THGLF2G9C8KBADG",
205 UFS_DEVICE_QUIRK_PA_TACTIVATE),
206 UFS_FIX(UFS_VENDOR_TOSHIBA, "THGLF2G9D8KBADG",
207 UFS_DEVICE_QUIRK_PA_TACTIVATE),
211 static irqreturn_t ufshcd_tmc_handler(struct ufs_hba *hba);
212 static void ufshcd_async_scan(void *data, async_cookie_t cookie);
213 static int ufshcd_reset_and_restore(struct ufs_hba *hba);
214 static int ufshcd_eh_host_reset_handler(struct scsi_cmnd *cmd);
215 static int ufshcd_clear_tm_cmd(struct ufs_hba *hba, int tag);
216 static void ufshcd_hba_exit(struct ufs_hba *hba);
217 static int ufshcd_probe_hba(struct ufs_hba *hba, bool async);
218 static int __ufshcd_setup_clocks(struct ufs_hba *hba, bool on,
220 static int ufshcd_setup_clocks(struct ufs_hba *hba, bool on);
221 static int ufshcd_uic_hibern8_enter(struct ufs_hba *hba);
222 static inline void ufshcd_add_delay_before_dme_cmd(struct ufs_hba *hba);
223 static int ufshcd_host_reset_and_restore(struct ufs_hba *hba);
224 static void ufshcd_resume_clkscaling(struct ufs_hba *hba);
225 static void ufshcd_suspend_clkscaling(struct ufs_hba *hba);
226 static void __ufshcd_suspend_clkscaling(struct ufs_hba *hba);
227 static int ufshcd_scale_clks(struct ufs_hba *hba, bool scale_up);
228 static irqreturn_t ufshcd_intr(int irq, void *__hba);
229 static int ufshcd_change_power_mode(struct ufs_hba *hba,
230 struct ufs_pa_layer_attr *pwr_mode);
231 static int ufshcd_wb_buf_flush_enable(struct ufs_hba *hba);
232 static int ufshcd_wb_buf_flush_disable(struct ufs_hba *hba);
233 static int ufshcd_wb_ctrl(struct ufs_hba *hba, bool enable);
234 static int ufshcd_wb_toggle_flush_during_h8(struct ufs_hba *hba, bool set);
235 static inline void ufshcd_wb_toggle_flush(struct ufs_hba *hba, bool enable);
237 static inline bool ufshcd_valid_tag(struct ufs_hba *hba, int tag)
239 return tag >= 0 && tag < hba->nutrs;
242 static inline void ufshcd_enable_irq(struct ufs_hba *hba)
244 if (!hba->is_irq_enabled) {
245 enable_irq(hba->irq);
246 hba->is_irq_enabled = true;
250 static inline void ufshcd_disable_irq(struct ufs_hba *hba)
252 if (hba->is_irq_enabled) {
253 disable_irq(hba->irq);
254 hba->is_irq_enabled = false;
258 static inline void ufshcd_wb_config(struct ufs_hba *hba)
262 if (!ufshcd_is_wb_allowed(hba))
265 ret = ufshcd_wb_ctrl(hba, true);
267 dev_err(hba->dev, "%s: Enable WB failed: %d\n", __func__, ret);
269 dev_info(hba->dev, "%s: Write Booster Configured\n", __func__);
270 ret = ufshcd_wb_toggle_flush_during_h8(hba, true);
272 dev_err(hba->dev, "%s: En WB flush during H8: failed: %d\n",
274 ufshcd_wb_toggle_flush(hba, true);
277 static void ufshcd_scsi_unblock_requests(struct ufs_hba *hba)
279 if (atomic_dec_and_test(&hba->scsi_block_reqs_cnt))
280 scsi_unblock_requests(hba->host);
283 static void ufshcd_scsi_block_requests(struct ufs_hba *hba)
285 if (atomic_inc_return(&hba->scsi_block_reqs_cnt) == 1)
286 scsi_block_requests(hba->host);
289 static void ufshcd_add_cmd_upiu_trace(struct ufs_hba *hba, unsigned int tag,
292 struct utp_upiu_req *rq = hba->lrb[tag].ucd_req_ptr;
294 trace_ufshcd_upiu(dev_name(hba->dev), str, &rq->header, &rq->sc.cdb);
297 static void ufshcd_add_query_upiu_trace(struct ufs_hba *hba, unsigned int tag,
300 struct utp_upiu_req *rq = hba->lrb[tag].ucd_req_ptr;
302 trace_ufshcd_upiu(dev_name(hba->dev), str, &rq->header, &rq->qr);
305 static void ufshcd_add_tm_upiu_trace(struct ufs_hba *hba, unsigned int tag,
308 int off = (int)tag - hba->nutrs;
309 struct utp_task_req_desc *descp = &hba->utmrdl_base_addr[off];
311 trace_ufshcd_upiu(dev_name(hba->dev), str, &descp->req_header,
312 &descp->input_param1);
315 static void ufshcd_add_uic_command_trace(struct ufs_hba *hba,
316 struct uic_command *ucmd,
321 if (!trace_ufshcd_uic_command_enabled())
324 if (!strcmp(str, "send"))
327 cmd = ufshcd_readl(hba, REG_UIC_COMMAND);
329 trace_ufshcd_uic_command(dev_name(hba->dev), str, cmd,
330 ufshcd_readl(hba, REG_UIC_COMMAND_ARG_1),
331 ufshcd_readl(hba, REG_UIC_COMMAND_ARG_2),
332 ufshcd_readl(hba, REG_UIC_COMMAND_ARG_3));
335 static void ufshcd_add_command_trace(struct ufs_hba *hba,
336 unsigned int tag, const char *str)
341 struct ufshcd_lrb *lrbp = &hba->lrb[tag];
342 struct scsi_cmnd *cmd = lrbp->cmd;
343 int transfer_len = -1;
345 if (!trace_ufshcd_command_enabled()) {
346 /* trace UPIU W/O tracing command */
348 ufshcd_add_cmd_upiu_trace(hba, tag, str);
352 if (cmd) { /* data phase exists */
353 /* trace UPIU also */
354 ufshcd_add_cmd_upiu_trace(hba, tag, str);
355 opcode = cmd->cmnd[0];
356 if ((opcode == READ_10) || (opcode == WRITE_10)) {
358 * Currently we only fully trace read(10) and write(10)
361 if (cmd->request && cmd->request->bio)
362 lba = cmd->request->bio->bi_iter.bi_sector;
363 transfer_len = be32_to_cpu(
364 lrbp->ucd_req_ptr->sc.exp_data_transfer_len);
368 intr = ufshcd_readl(hba, REG_INTERRUPT_STATUS);
369 doorbell = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
370 trace_ufshcd_command(dev_name(hba->dev), str, tag,
371 doorbell, transfer_len, intr, lba, opcode);
374 static void ufshcd_print_clk_freqs(struct ufs_hba *hba)
376 struct ufs_clk_info *clki;
377 struct list_head *head = &hba->clk_list_head;
379 if (list_empty(head))
382 list_for_each_entry(clki, head, list) {
383 if (!IS_ERR_OR_NULL(clki->clk) && clki->min_freq &&
385 dev_err(hba->dev, "clk: %s, rate: %u\n",
386 clki->name, clki->curr_freq);
390 static void ufshcd_print_err_hist(struct ufs_hba *hba,
391 struct ufs_err_reg_hist *err_hist,
397 for (i = 0; i < UFS_ERR_REG_HIST_LENGTH; i++) {
398 int p = (i + err_hist->pos) % UFS_ERR_REG_HIST_LENGTH;
400 if (err_hist->tstamp[p] == 0)
402 dev_err(hba->dev, "%s[%d] = 0x%x at %lld us\n", err_name, p,
403 err_hist->reg[p], ktime_to_us(err_hist->tstamp[p]));
408 dev_err(hba->dev, "No record of %s\n", err_name);
411 static void ufshcd_print_host_regs(struct ufs_hba *hba)
413 ufshcd_dump_regs(hba, 0, UFSHCI_REG_SPACE_SIZE, "host_regs: ");
414 dev_err(hba->dev, "hba->ufs_version = 0x%x, hba->capabilities = 0x%x\n",
415 hba->ufs_version, hba->capabilities);
417 "hba->outstanding_reqs = 0x%x, hba->outstanding_tasks = 0x%x\n",
418 (u32)hba->outstanding_reqs, (u32)hba->outstanding_tasks);
420 "last_hibern8_exit_tstamp at %lld us, hibern8_exit_cnt = %d\n",
421 ktime_to_us(hba->ufs_stats.last_hibern8_exit_tstamp),
422 hba->ufs_stats.hibern8_exit_cnt);
424 ufshcd_print_err_hist(hba, &hba->ufs_stats.pa_err, "pa_err");
425 ufshcd_print_err_hist(hba, &hba->ufs_stats.dl_err, "dl_err");
426 ufshcd_print_err_hist(hba, &hba->ufs_stats.nl_err, "nl_err");
427 ufshcd_print_err_hist(hba, &hba->ufs_stats.tl_err, "tl_err");
428 ufshcd_print_err_hist(hba, &hba->ufs_stats.dme_err, "dme_err");
429 ufshcd_print_err_hist(hba, &hba->ufs_stats.auto_hibern8_err,
431 ufshcd_print_err_hist(hba, &hba->ufs_stats.fatal_err, "fatal_err");
432 ufshcd_print_err_hist(hba, &hba->ufs_stats.link_startup_err,
433 "link_startup_fail");
434 ufshcd_print_err_hist(hba, &hba->ufs_stats.resume_err, "resume_fail");
435 ufshcd_print_err_hist(hba, &hba->ufs_stats.suspend_err,
437 ufshcd_print_err_hist(hba, &hba->ufs_stats.dev_reset, "dev_reset");
438 ufshcd_print_err_hist(hba, &hba->ufs_stats.host_reset, "host_reset");
439 ufshcd_print_err_hist(hba, &hba->ufs_stats.task_abort, "task_abort");
441 ufshcd_print_clk_freqs(hba);
443 ufshcd_vops_dbg_register_dump(hba);
447 void ufshcd_print_trs(struct ufs_hba *hba, unsigned long bitmap, bool pr_prdt)
449 struct ufshcd_lrb *lrbp;
453 for_each_set_bit(tag, &bitmap, hba->nutrs) {
454 lrbp = &hba->lrb[tag];
456 dev_err(hba->dev, "UPIU[%d] - issue time %lld us\n",
457 tag, ktime_to_us(lrbp->issue_time_stamp));
458 dev_err(hba->dev, "UPIU[%d] - complete time %lld us\n",
459 tag, ktime_to_us(lrbp->compl_time_stamp));
461 "UPIU[%d] - Transfer Request Descriptor phys@0x%llx\n",
462 tag, (u64)lrbp->utrd_dma_addr);
464 ufshcd_hex_dump("UPIU TRD: ", lrbp->utr_descriptor_ptr,
465 sizeof(struct utp_transfer_req_desc));
466 dev_err(hba->dev, "UPIU[%d] - Request UPIU phys@0x%llx\n", tag,
467 (u64)lrbp->ucd_req_dma_addr);
468 ufshcd_hex_dump("UPIU REQ: ", lrbp->ucd_req_ptr,
469 sizeof(struct utp_upiu_req));
470 dev_err(hba->dev, "UPIU[%d] - Response UPIU phys@0x%llx\n", tag,
471 (u64)lrbp->ucd_rsp_dma_addr);
472 ufshcd_hex_dump("UPIU RSP: ", lrbp->ucd_rsp_ptr,
473 sizeof(struct utp_upiu_rsp));
475 prdt_length = le16_to_cpu(
476 lrbp->utr_descriptor_ptr->prd_table_length);
478 "UPIU[%d] - PRDT - %d entries phys@0x%llx\n",
480 (u64)lrbp->ucd_prdt_dma_addr);
483 ufshcd_hex_dump("UPIU PRDT: ", lrbp->ucd_prdt_ptr,
484 sizeof(struct ufshcd_sg_entry) * prdt_length);
488 static void ufshcd_print_tmrs(struct ufs_hba *hba, unsigned long bitmap)
492 for_each_set_bit(tag, &bitmap, hba->nutmrs) {
493 struct utp_task_req_desc *tmrdp = &hba->utmrdl_base_addr[tag];
495 dev_err(hba->dev, "TM[%d] - Task Management Header\n", tag);
496 ufshcd_hex_dump("", tmrdp, sizeof(*tmrdp));
500 static void ufshcd_print_host_state(struct ufs_hba *hba)
502 dev_err(hba->dev, "UFS Host state=%d\n", hba->ufshcd_state);
503 dev_err(hba->dev, "outstanding reqs=0x%lx tasks=0x%lx\n",
504 hba->outstanding_reqs, hba->outstanding_tasks);
505 dev_err(hba->dev, "saved_err=0x%x, saved_uic_err=0x%x\n",
506 hba->saved_err, hba->saved_uic_err);
507 dev_err(hba->dev, "Device power mode=%d, UIC link state=%d\n",
508 hba->curr_dev_pwr_mode, hba->uic_link_state);
509 dev_err(hba->dev, "PM in progress=%d, sys. suspended=%d\n",
510 hba->pm_op_in_progress, hba->is_sys_suspended);
511 dev_err(hba->dev, "Auto BKOPS=%d, Host self-block=%d\n",
512 hba->auto_bkops_enabled, hba->host->host_self_blocked);
513 dev_err(hba->dev, "Clk gate=%d\n", hba->clk_gating.state);
514 dev_err(hba->dev, "error handling flags=0x%x, req. abort count=%d\n",
515 hba->eh_flags, hba->req_abort_count);
516 dev_err(hba->dev, "Host capabilities=0x%x, caps=0x%x\n",
517 hba->capabilities, hba->caps);
518 dev_err(hba->dev, "quirks=0x%x, dev. quirks=0x%x\n", hba->quirks,
523 * ufshcd_print_pwr_info - print power params as saved in hba
525 * @hba: per-adapter instance
527 static void ufshcd_print_pwr_info(struct ufs_hba *hba)
529 static const char * const names[] = {
539 dev_err(hba->dev, "%s:[RX, TX]: gear=[%d, %d], lane[%d, %d], pwr[%s, %s], rate = %d\n",
541 hba->pwr_info.gear_rx, hba->pwr_info.gear_tx,
542 hba->pwr_info.lane_rx, hba->pwr_info.lane_tx,
543 names[hba->pwr_info.pwr_rx],
544 names[hba->pwr_info.pwr_tx],
545 hba->pwr_info.hs_rate);
548 void ufshcd_delay_us(unsigned long us, unsigned long tolerance)
556 usleep_range(us, us + tolerance);
558 EXPORT_SYMBOL_GPL(ufshcd_delay_us);
561 * ufshcd_wait_for_register - wait for register value to change
562 * @hba: per-adapter interface
563 * @reg: mmio register offset
564 * @mask: mask to apply to the read register value
565 * @val: value to wait for
566 * @interval_us: polling interval in microseconds
567 * @timeout_ms: timeout in milliseconds
570 * -ETIMEDOUT on error, zero on success.
572 int ufshcd_wait_for_register(struct ufs_hba *hba, u32 reg, u32 mask,
573 u32 val, unsigned long interval_us,
574 unsigned long timeout_ms)
577 unsigned long timeout = jiffies + msecs_to_jiffies(timeout_ms);
579 /* ignore bits that we don't intend to wait on */
582 while ((ufshcd_readl(hba, reg) & mask) != val) {
583 usleep_range(interval_us, interval_us + 50);
584 if (time_after(jiffies, timeout)) {
585 if ((ufshcd_readl(hba, reg) & mask) != val)
595 * ufshcd_get_intr_mask - Get the interrupt bit mask
596 * @hba: Pointer to adapter instance
598 * Returns interrupt bit mask per version
600 static inline u32 ufshcd_get_intr_mask(struct ufs_hba *hba)
604 switch (hba->ufs_version) {
605 case UFSHCI_VERSION_10:
606 intr_mask = INTERRUPT_MASK_ALL_VER_10;
608 case UFSHCI_VERSION_11:
609 case UFSHCI_VERSION_20:
610 intr_mask = INTERRUPT_MASK_ALL_VER_11;
612 case UFSHCI_VERSION_21:
614 intr_mask = INTERRUPT_MASK_ALL_VER_21;
622 * ufshcd_get_ufs_version - Get the UFS version supported by the HBA
623 * @hba: Pointer to adapter instance
625 * Returns UFSHCI version supported by the controller
627 static inline u32 ufshcd_get_ufs_version(struct ufs_hba *hba)
629 if (hba->quirks & UFSHCD_QUIRK_BROKEN_UFS_HCI_VERSION)
630 return ufshcd_vops_get_ufs_hci_version(hba);
632 return ufshcd_readl(hba, REG_UFS_VERSION);
636 * ufshcd_is_device_present - Check if any device connected to
637 * the host controller
638 * @hba: pointer to adapter instance
640 * Returns true if device present, false if no device detected
642 static inline bool ufshcd_is_device_present(struct ufs_hba *hba)
644 return (ufshcd_readl(hba, REG_CONTROLLER_STATUS) &
645 DEVICE_PRESENT) ? true : false;
649 * ufshcd_get_tr_ocs - Get the UTRD Overall Command Status
650 * @lrbp: pointer to local command reference block
652 * This function is used to get the OCS field from UTRD
653 * Returns the OCS field in the UTRD
655 static inline int ufshcd_get_tr_ocs(struct ufshcd_lrb *lrbp)
657 return le32_to_cpu(lrbp->utr_descriptor_ptr->header.dword_2) & MASK_OCS;
661 * ufshcd_utrl_clear - Clear a bit in UTRLCLR register
662 * @hba: per adapter instance
663 * @pos: position of the bit to be cleared
665 static inline void ufshcd_utrl_clear(struct ufs_hba *hba, u32 pos)
667 if (hba->quirks & UFSHCI_QUIRK_BROKEN_REQ_LIST_CLR)
668 ufshcd_writel(hba, (1 << pos), REG_UTP_TRANSFER_REQ_LIST_CLEAR);
670 ufshcd_writel(hba, ~(1 << pos),
671 REG_UTP_TRANSFER_REQ_LIST_CLEAR);
675 * ufshcd_utmrl_clear - Clear a bit in UTRMLCLR register
676 * @hba: per adapter instance
677 * @pos: position of the bit to be cleared
679 static inline void ufshcd_utmrl_clear(struct ufs_hba *hba, u32 pos)
681 if (hba->quirks & UFSHCI_QUIRK_BROKEN_REQ_LIST_CLR)
682 ufshcd_writel(hba, (1 << pos), REG_UTP_TASK_REQ_LIST_CLEAR);
684 ufshcd_writel(hba, ~(1 << pos), REG_UTP_TASK_REQ_LIST_CLEAR);
688 * ufshcd_outstanding_req_clear - Clear a bit in outstanding request field
689 * @hba: per adapter instance
690 * @tag: position of the bit to be cleared
692 static inline void ufshcd_outstanding_req_clear(struct ufs_hba *hba, int tag)
694 __clear_bit(tag, &hba->outstanding_reqs);
698 * ufshcd_get_lists_status - Check UCRDY, UTRLRDY and UTMRLRDY
699 * @reg: Register value of host controller status
701 * Returns integer, 0 on Success and positive value if failed
703 static inline int ufshcd_get_lists_status(u32 reg)
705 return !((reg & UFSHCD_STATUS_READY) == UFSHCD_STATUS_READY);
709 * ufshcd_get_uic_cmd_result - Get the UIC command result
710 * @hba: Pointer to adapter instance
712 * This function gets the result of UIC command completion
713 * Returns 0 on success, non zero value on error
715 static inline int ufshcd_get_uic_cmd_result(struct ufs_hba *hba)
717 return ufshcd_readl(hba, REG_UIC_COMMAND_ARG_2) &
718 MASK_UIC_COMMAND_RESULT;
722 * ufshcd_get_dme_attr_val - Get the value of attribute returned by UIC command
723 * @hba: Pointer to adapter instance
725 * This function gets UIC command argument3
726 * Returns 0 on success, non zero value on error
728 static inline u32 ufshcd_get_dme_attr_val(struct ufs_hba *hba)
730 return ufshcd_readl(hba, REG_UIC_COMMAND_ARG_3);
734 * ufshcd_get_req_rsp - returns the TR response transaction type
735 * @ucd_rsp_ptr: pointer to response UPIU
738 ufshcd_get_req_rsp(struct utp_upiu_rsp *ucd_rsp_ptr)
740 return be32_to_cpu(ucd_rsp_ptr->header.dword_0) >> 24;
744 * ufshcd_get_rsp_upiu_result - Get the result from response UPIU
745 * @ucd_rsp_ptr: pointer to response UPIU
747 * This function gets the response status and scsi_status from response UPIU
748 * Returns the response result code.
751 ufshcd_get_rsp_upiu_result(struct utp_upiu_rsp *ucd_rsp_ptr)
753 return be32_to_cpu(ucd_rsp_ptr->header.dword_1) & MASK_RSP_UPIU_RESULT;
757 * ufshcd_get_rsp_upiu_data_seg_len - Get the data segment length
759 * @ucd_rsp_ptr: pointer to response UPIU
761 * Return the data segment length.
763 static inline unsigned int
764 ufshcd_get_rsp_upiu_data_seg_len(struct utp_upiu_rsp *ucd_rsp_ptr)
766 return be32_to_cpu(ucd_rsp_ptr->header.dword_2) &
767 MASK_RSP_UPIU_DATA_SEG_LEN;
771 * ufshcd_is_exception_event - Check if the device raised an exception event
772 * @ucd_rsp_ptr: pointer to response UPIU
774 * The function checks if the device raised an exception event indicated in
775 * the Device Information field of response UPIU.
777 * Returns true if exception is raised, false otherwise.
779 static inline bool ufshcd_is_exception_event(struct utp_upiu_rsp *ucd_rsp_ptr)
781 return be32_to_cpu(ucd_rsp_ptr->header.dword_2) &
782 MASK_RSP_EXCEPTION_EVENT ? true : false;
786 * ufshcd_reset_intr_aggr - Reset interrupt aggregation values.
787 * @hba: per adapter instance
790 ufshcd_reset_intr_aggr(struct ufs_hba *hba)
792 ufshcd_writel(hba, INT_AGGR_ENABLE |
793 INT_AGGR_COUNTER_AND_TIMER_RESET,
794 REG_UTP_TRANSFER_REQ_INT_AGG_CONTROL);
798 * ufshcd_config_intr_aggr - Configure interrupt aggregation values.
799 * @hba: per adapter instance
800 * @cnt: Interrupt aggregation counter threshold
801 * @tmout: Interrupt aggregation timeout value
804 ufshcd_config_intr_aggr(struct ufs_hba *hba, u8 cnt, u8 tmout)
806 ufshcd_writel(hba, INT_AGGR_ENABLE | INT_AGGR_PARAM_WRITE |
807 INT_AGGR_COUNTER_THLD_VAL(cnt) |
808 INT_AGGR_TIMEOUT_VAL(tmout),
809 REG_UTP_TRANSFER_REQ_INT_AGG_CONTROL);
813 * ufshcd_disable_intr_aggr - Disables interrupt aggregation.
814 * @hba: per adapter instance
816 static inline void ufshcd_disable_intr_aggr(struct ufs_hba *hba)
818 ufshcd_writel(hba, 0, REG_UTP_TRANSFER_REQ_INT_AGG_CONTROL);
822 * ufshcd_enable_run_stop_reg - Enable run-stop registers,
823 * When run-stop registers are set to 1, it indicates the
824 * host controller that it can process the requests
825 * @hba: per adapter instance
827 static void ufshcd_enable_run_stop_reg(struct ufs_hba *hba)
829 ufshcd_writel(hba, UTP_TASK_REQ_LIST_RUN_STOP_BIT,
830 REG_UTP_TASK_REQ_LIST_RUN_STOP);
831 ufshcd_writel(hba, UTP_TRANSFER_REQ_LIST_RUN_STOP_BIT,
832 REG_UTP_TRANSFER_REQ_LIST_RUN_STOP);
836 * ufshcd_hba_start - Start controller initialization sequence
837 * @hba: per adapter instance
839 static inline void ufshcd_hba_start(struct ufs_hba *hba)
841 u32 val = CONTROLLER_ENABLE;
843 if (ufshcd_crypto_enable(hba))
844 val |= CRYPTO_GENERAL_ENABLE;
846 ufshcd_writel(hba, val, REG_CONTROLLER_ENABLE);
850 * ufshcd_is_hba_active - Get controller state
851 * @hba: per adapter instance
853 * Returns false if controller is active, true otherwise
855 static inline bool ufshcd_is_hba_active(struct ufs_hba *hba)
857 return (ufshcd_readl(hba, REG_CONTROLLER_ENABLE) & CONTROLLER_ENABLE)
861 u32 ufshcd_get_local_unipro_ver(struct ufs_hba *hba)
863 /* HCI version 1.0 and 1.1 supports UniPro 1.41 */
864 if ((hba->ufs_version == UFSHCI_VERSION_10) ||
865 (hba->ufs_version == UFSHCI_VERSION_11))
866 return UFS_UNIPRO_VER_1_41;
868 return UFS_UNIPRO_VER_1_6;
870 EXPORT_SYMBOL(ufshcd_get_local_unipro_ver);
872 static bool ufshcd_is_unipro_pa_params_tuning_req(struct ufs_hba *hba)
875 * If both host and device support UniPro ver1.6 or later, PA layer
876 * parameters tuning happens during link startup itself.
878 * We can manually tune PA layer parameters if either host or device
879 * doesn't support UniPro ver 1.6 or later. But to keep manual tuning
880 * logic simple, we will only do manual tuning if local unipro version
881 * doesn't support ver1.6 or later.
883 if (ufshcd_get_local_unipro_ver(hba) < UFS_UNIPRO_VER_1_6)
890 * ufshcd_set_clk_freq - set UFS controller clock frequencies
891 * @hba: per adapter instance
892 * @scale_up: If True, set max possible frequency othewise set low frequency
894 * Returns 0 if successful
895 * Returns < 0 for any other errors
897 static int ufshcd_set_clk_freq(struct ufs_hba *hba, bool scale_up)
900 struct ufs_clk_info *clki;
901 struct list_head *head = &hba->clk_list_head;
903 if (list_empty(head))
906 list_for_each_entry(clki, head, list) {
907 if (!IS_ERR_OR_NULL(clki->clk)) {
908 if (scale_up && clki->max_freq) {
909 if (clki->curr_freq == clki->max_freq)
912 ret = clk_set_rate(clki->clk, clki->max_freq);
914 dev_err(hba->dev, "%s: %s clk set rate(%dHz) failed, %d\n",
915 __func__, clki->name,
916 clki->max_freq, ret);
919 trace_ufshcd_clk_scaling(dev_name(hba->dev),
920 "scaled up", clki->name,
924 clki->curr_freq = clki->max_freq;
926 } else if (!scale_up && clki->min_freq) {
927 if (clki->curr_freq == clki->min_freq)
930 ret = clk_set_rate(clki->clk, clki->min_freq);
932 dev_err(hba->dev, "%s: %s clk set rate(%dHz) failed, %d\n",
933 __func__, clki->name,
934 clki->min_freq, ret);
937 trace_ufshcd_clk_scaling(dev_name(hba->dev),
938 "scaled down", clki->name,
941 clki->curr_freq = clki->min_freq;
944 dev_dbg(hba->dev, "%s: clk: %s, rate: %lu\n", __func__,
945 clki->name, clk_get_rate(clki->clk));
953 * ufshcd_scale_clks - scale up or scale down UFS controller clocks
954 * @hba: per adapter instance
955 * @scale_up: True if scaling up and false if scaling down
957 * Returns 0 if successful
958 * Returns < 0 for any other errors
960 static int ufshcd_scale_clks(struct ufs_hba *hba, bool scale_up)
963 ktime_t start = ktime_get();
965 ret = ufshcd_vops_clk_scale_notify(hba, scale_up, PRE_CHANGE);
969 ret = ufshcd_set_clk_freq(hba, scale_up);
973 ret = ufshcd_vops_clk_scale_notify(hba, scale_up, POST_CHANGE);
975 ufshcd_set_clk_freq(hba, !scale_up);
978 trace_ufshcd_profile_clk_scaling(dev_name(hba->dev),
979 (scale_up ? "up" : "down"),
980 ktime_to_us(ktime_sub(ktime_get(), start)), ret);
985 * ufshcd_is_devfreq_scaling_required - check if scaling is required or not
986 * @hba: per adapter instance
987 * @scale_up: True if scaling up and false if scaling down
989 * Returns true if scaling is required, false otherwise.
991 static bool ufshcd_is_devfreq_scaling_required(struct ufs_hba *hba,
994 struct ufs_clk_info *clki;
995 struct list_head *head = &hba->clk_list_head;
997 if (list_empty(head))
1000 list_for_each_entry(clki, head, list) {
1001 if (!IS_ERR_OR_NULL(clki->clk)) {
1002 if (scale_up && clki->max_freq) {
1003 if (clki->curr_freq == clki->max_freq)
1006 } else if (!scale_up && clki->min_freq) {
1007 if (clki->curr_freq == clki->min_freq)
1017 static int ufshcd_wait_for_doorbell_clr(struct ufs_hba *hba,
1018 u64 wait_timeout_us)
1020 unsigned long flags;
1024 bool timeout = false, do_last_check = false;
1027 ufshcd_hold(hba, false);
1028 spin_lock_irqsave(hba->host->host_lock, flags);
1030 * Wait for all the outstanding tasks/transfer requests.
1031 * Verify by checking the doorbell registers are clear.
1033 start = ktime_get();
1035 if (hba->ufshcd_state != UFSHCD_STATE_OPERATIONAL) {
1040 tm_doorbell = ufshcd_readl(hba, REG_UTP_TASK_REQ_DOOR_BELL);
1041 tr_doorbell = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
1042 if (!tm_doorbell && !tr_doorbell) {
1045 } else if (do_last_check) {
1049 spin_unlock_irqrestore(hba->host->host_lock, flags);
1051 if (ktime_to_us(ktime_sub(ktime_get(), start)) >
1055 * We might have scheduled out for long time so make
1056 * sure to check if doorbells are cleared by this time
1059 do_last_check = true;
1061 spin_lock_irqsave(hba->host->host_lock, flags);
1062 } while (tm_doorbell || tr_doorbell);
1066 "%s: timedout waiting for doorbell to clear (tm=0x%x, tr=0x%x)\n",
1067 __func__, tm_doorbell, tr_doorbell);
1071 spin_unlock_irqrestore(hba->host->host_lock, flags);
1072 ufshcd_release(hba);
1077 * ufshcd_scale_gear - scale up/down UFS gear
1078 * @hba: per adapter instance
1079 * @scale_up: True for scaling up gear and false for scaling down
1081 * Returns 0 for success,
1082 * Returns -EBUSY if scaling can't happen at this time
1083 * Returns non-zero for any other errors
1085 static int ufshcd_scale_gear(struct ufs_hba *hba, bool scale_up)
1087 #define UFS_MIN_GEAR_TO_SCALE_DOWN UFS_HS_G1
1089 struct ufs_pa_layer_attr new_pwr_info;
1092 memcpy(&new_pwr_info, &hba->clk_scaling.saved_pwr_info.info,
1093 sizeof(struct ufs_pa_layer_attr));
1095 memcpy(&new_pwr_info, &hba->pwr_info,
1096 sizeof(struct ufs_pa_layer_attr));
1098 if (hba->pwr_info.gear_tx > UFS_MIN_GEAR_TO_SCALE_DOWN
1099 || hba->pwr_info.gear_rx > UFS_MIN_GEAR_TO_SCALE_DOWN) {
1100 /* save the current power mode */
1101 memcpy(&hba->clk_scaling.saved_pwr_info.info,
1103 sizeof(struct ufs_pa_layer_attr));
1105 /* scale down gear */
1106 new_pwr_info.gear_tx = UFS_MIN_GEAR_TO_SCALE_DOWN;
1107 new_pwr_info.gear_rx = UFS_MIN_GEAR_TO_SCALE_DOWN;
1111 /* check if the power mode needs to be changed or not? */
1112 ret = ufshcd_config_pwr_mode(hba, &new_pwr_info);
1114 dev_err(hba->dev, "%s: failed err %d, old gear: (tx %d rx %d), new gear: (tx %d rx %d)",
1116 hba->pwr_info.gear_tx, hba->pwr_info.gear_rx,
1117 new_pwr_info.gear_tx, new_pwr_info.gear_rx);
1122 static int ufshcd_clock_scaling_prepare(struct ufs_hba *hba)
1124 #define DOORBELL_CLR_TOUT_US (1000 * 1000) /* 1 sec */
1127 * make sure that there are no outstanding requests when
1128 * clock scaling is in progress
1130 ufshcd_scsi_block_requests(hba);
1131 down_write(&hba->clk_scaling_lock);
1132 if (ufshcd_wait_for_doorbell_clr(hba, DOORBELL_CLR_TOUT_US)) {
1134 up_write(&hba->clk_scaling_lock);
1135 ufshcd_scsi_unblock_requests(hba);
1141 static void ufshcd_clock_scaling_unprepare(struct ufs_hba *hba)
1143 up_write(&hba->clk_scaling_lock);
1144 ufshcd_scsi_unblock_requests(hba);
1148 * ufshcd_devfreq_scale - scale up/down UFS clocks and gear
1149 * @hba: per adapter instance
1150 * @scale_up: True for scaling up and false for scalin down
1152 * Returns 0 for success,
1153 * Returns -EBUSY if scaling can't happen at this time
1154 * Returns non-zero for any other errors
1156 static int ufshcd_devfreq_scale(struct ufs_hba *hba, bool scale_up)
1160 /* let's not get into low power until clock scaling is completed */
1161 ufshcd_hold(hba, false);
1163 ret = ufshcd_clock_scaling_prepare(hba);
1167 /* scale down the gear before scaling down clocks */
1169 ret = ufshcd_scale_gear(hba, false);
1174 ret = ufshcd_scale_clks(hba, scale_up);
1177 ufshcd_scale_gear(hba, true);
1181 /* scale up the gear after scaling up clocks */
1183 ret = ufshcd_scale_gear(hba, true);
1185 ufshcd_scale_clks(hba, false);
1190 /* Enable Write Booster if we have scaled up else disable it */
1191 up_write(&hba->clk_scaling_lock);
1192 ufshcd_wb_ctrl(hba, scale_up);
1193 down_write(&hba->clk_scaling_lock);
1196 ufshcd_clock_scaling_unprepare(hba);
1198 ufshcd_release(hba);
1202 static void ufshcd_clk_scaling_suspend_work(struct work_struct *work)
1204 struct ufs_hba *hba = container_of(work, struct ufs_hba,
1205 clk_scaling.suspend_work);
1206 unsigned long irq_flags;
1208 spin_lock_irqsave(hba->host->host_lock, irq_flags);
1209 if (hba->clk_scaling.active_reqs || hba->clk_scaling.is_suspended) {
1210 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1213 hba->clk_scaling.is_suspended = true;
1214 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1216 __ufshcd_suspend_clkscaling(hba);
1219 static void ufshcd_clk_scaling_resume_work(struct work_struct *work)
1221 struct ufs_hba *hba = container_of(work, struct ufs_hba,
1222 clk_scaling.resume_work);
1223 unsigned long irq_flags;
1225 spin_lock_irqsave(hba->host->host_lock, irq_flags);
1226 if (!hba->clk_scaling.is_suspended) {
1227 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1230 hba->clk_scaling.is_suspended = false;
1231 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1233 devfreq_resume_device(hba->devfreq);
1236 static int ufshcd_devfreq_target(struct device *dev,
1237 unsigned long *freq, u32 flags)
1240 struct ufs_hba *hba = dev_get_drvdata(dev);
1242 bool scale_up, sched_clk_scaling_suspend_work = false;
1243 struct list_head *clk_list = &hba->clk_list_head;
1244 struct ufs_clk_info *clki;
1245 unsigned long irq_flags;
1247 if (!ufshcd_is_clkscaling_supported(hba))
1250 clki = list_first_entry(&hba->clk_list_head, struct ufs_clk_info, list);
1251 /* Override with the closest supported frequency */
1252 *freq = (unsigned long) clk_round_rate(clki->clk, *freq);
1253 spin_lock_irqsave(hba->host->host_lock, irq_flags);
1254 if (ufshcd_eh_in_progress(hba)) {
1255 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1259 if (!hba->clk_scaling.active_reqs)
1260 sched_clk_scaling_suspend_work = true;
1262 if (list_empty(clk_list)) {
1263 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1267 /* Decide based on the rounded-off frequency and update */
1268 scale_up = (*freq == clki->max_freq) ? true : false;
1270 *freq = clki->min_freq;
1271 /* Update the frequency */
1272 if (!ufshcd_is_devfreq_scaling_required(hba, scale_up)) {
1273 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1275 goto out; /* no state change required */
1277 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1279 start = ktime_get();
1280 ret = ufshcd_devfreq_scale(hba, scale_up);
1282 trace_ufshcd_profile_clk_scaling(dev_name(hba->dev),
1283 (scale_up ? "up" : "down"),
1284 ktime_to_us(ktime_sub(ktime_get(), start)), ret);
1287 if (sched_clk_scaling_suspend_work)
1288 queue_work(hba->clk_scaling.workq,
1289 &hba->clk_scaling.suspend_work);
1294 static bool ufshcd_is_busy(struct request *req, void *priv, bool reserved)
1298 WARN_ON_ONCE(reserved);
1303 /* Whether or not any tag is in use by a request that is in progress. */
1304 static bool ufshcd_any_tag_in_use(struct ufs_hba *hba)
1306 struct request_queue *q = hba->cmd_queue;
1309 blk_mq_tagset_busy_iter(q->tag_set, ufshcd_is_busy, &busy);
1313 static int ufshcd_devfreq_get_dev_status(struct device *dev,
1314 struct devfreq_dev_status *stat)
1316 struct ufs_hba *hba = dev_get_drvdata(dev);
1317 struct ufs_clk_scaling *scaling = &hba->clk_scaling;
1318 unsigned long flags;
1319 struct list_head *clk_list = &hba->clk_list_head;
1320 struct ufs_clk_info *clki;
1323 if (!ufshcd_is_clkscaling_supported(hba))
1326 memset(stat, 0, sizeof(*stat));
1328 spin_lock_irqsave(hba->host->host_lock, flags);
1329 curr_t = ktime_get();
1330 if (!scaling->window_start_t)
1333 clki = list_first_entry(clk_list, struct ufs_clk_info, list);
1335 * If current frequency is 0, then the ondemand governor considers
1336 * there's no initial frequency set. And it always requests to set
1337 * to max. frequency.
1339 stat->current_frequency = clki->curr_freq;
1340 if (scaling->is_busy_started)
1341 scaling->tot_busy_t += ktime_us_delta(curr_t,
1342 scaling->busy_start_t);
1344 stat->total_time = ktime_us_delta(curr_t, scaling->window_start_t);
1345 stat->busy_time = scaling->tot_busy_t;
1347 scaling->window_start_t = curr_t;
1348 scaling->tot_busy_t = 0;
1350 if (hba->outstanding_reqs) {
1351 scaling->busy_start_t = curr_t;
1352 scaling->is_busy_started = true;
1354 scaling->busy_start_t = 0;
1355 scaling->is_busy_started = false;
1357 spin_unlock_irqrestore(hba->host->host_lock, flags);
1361 static int ufshcd_devfreq_init(struct ufs_hba *hba)
1363 struct list_head *clk_list = &hba->clk_list_head;
1364 struct ufs_clk_info *clki;
1365 struct devfreq *devfreq;
1368 /* Skip devfreq if we don't have any clocks in the list */
1369 if (list_empty(clk_list))
1372 clki = list_first_entry(clk_list, struct ufs_clk_info, list);
1373 dev_pm_opp_add(hba->dev, clki->min_freq, 0);
1374 dev_pm_opp_add(hba->dev, clki->max_freq, 0);
1376 ufshcd_vops_config_scaling_param(hba, &hba->vps->devfreq_profile,
1377 &hba->vps->ondemand_data);
1378 devfreq = devfreq_add_device(hba->dev,
1379 &hba->vps->devfreq_profile,
1380 DEVFREQ_GOV_SIMPLE_ONDEMAND,
1381 &hba->vps->ondemand_data);
1382 if (IS_ERR(devfreq)) {
1383 ret = PTR_ERR(devfreq);
1384 dev_err(hba->dev, "Unable to register with devfreq %d\n", ret);
1386 dev_pm_opp_remove(hba->dev, clki->min_freq);
1387 dev_pm_opp_remove(hba->dev, clki->max_freq);
1391 hba->devfreq = devfreq;
1396 static void ufshcd_devfreq_remove(struct ufs_hba *hba)
1398 struct list_head *clk_list = &hba->clk_list_head;
1399 struct ufs_clk_info *clki;
1404 devfreq_remove_device(hba->devfreq);
1405 hba->devfreq = NULL;
1407 clki = list_first_entry(clk_list, struct ufs_clk_info, list);
1408 dev_pm_opp_remove(hba->dev, clki->min_freq);
1409 dev_pm_opp_remove(hba->dev, clki->max_freq);
1412 static void __ufshcd_suspend_clkscaling(struct ufs_hba *hba)
1414 unsigned long flags;
1416 devfreq_suspend_device(hba->devfreq);
1417 spin_lock_irqsave(hba->host->host_lock, flags);
1418 hba->clk_scaling.window_start_t = 0;
1419 spin_unlock_irqrestore(hba->host->host_lock, flags);
1422 static void ufshcd_suspend_clkscaling(struct ufs_hba *hba)
1424 unsigned long flags;
1425 bool suspend = false;
1427 if (!ufshcd_is_clkscaling_supported(hba))
1430 spin_lock_irqsave(hba->host->host_lock, flags);
1431 if (!hba->clk_scaling.is_suspended) {
1433 hba->clk_scaling.is_suspended = true;
1435 spin_unlock_irqrestore(hba->host->host_lock, flags);
1438 __ufshcd_suspend_clkscaling(hba);
1441 static void ufshcd_resume_clkscaling(struct ufs_hba *hba)
1443 unsigned long flags;
1444 bool resume = false;
1446 if (!ufshcd_is_clkscaling_supported(hba))
1449 spin_lock_irqsave(hba->host->host_lock, flags);
1450 if (hba->clk_scaling.is_suspended) {
1452 hba->clk_scaling.is_suspended = false;
1454 spin_unlock_irqrestore(hba->host->host_lock, flags);
1457 devfreq_resume_device(hba->devfreq);
1460 static ssize_t ufshcd_clkscale_enable_show(struct device *dev,
1461 struct device_attribute *attr, char *buf)
1463 struct ufs_hba *hba = dev_get_drvdata(dev);
1465 return snprintf(buf, PAGE_SIZE, "%d\n", hba->clk_scaling.is_allowed);
1468 static ssize_t ufshcd_clkscale_enable_store(struct device *dev,
1469 struct device_attribute *attr, const char *buf, size_t count)
1471 struct ufs_hba *hba = dev_get_drvdata(dev);
1475 if (kstrtou32(buf, 0, &value))
1479 if (value == hba->clk_scaling.is_allowed)
1482 pm_runtime_get_sync(hba->dev);
1483 ufshcd_hold(hba, false);
1485 cancel_work_sync(&hba->clk_scaling.suspend_work);
1486 cancel_work_sync(&hba->clk_scaling.resume_work);
1488 hba->clk_scaling.is_allowed = value;
1491 ufshcd_resume_clkscaling(hba);
1493 ufshcd_suspend_clkscaling(hba);
1494 err = ufshcd_devfreq_scale(hba, true);
1496 dev_err(hba->dev, "%s: failed to scale clocks up %d\n",
1500 ufshcd_release(hba);
1501 pm_runtime_put_sync(hba->dev);
1506 static void ufshcd_clkscaling_init_sysfs(struct ufs_hba *hba)
1508 hba->clk_scaling.enable_attr.show = ufshcd_clkscale_enable_show;
1509 hba->clk_scaling.enable_attr.store = ufshcd_clkscale_enable_store;
1510 sysfs_attr_init(&hba->clk_scaling.enable_attr.attr);
1511 hba->clk_scaling.enable_attr.attr.name = "clkscale_enable";
1512 hba->clk_scaling.enable_attr.attr.mode = 0644;
1513 if (device_create_file(hba->dev, &hba->clk_scaling.enable_attr))
1514 dev_err(hba->dev, "Failed to create sysfs for clkscale_enable\n");
1517 static void ufshcd_ungate_work(struct work_struct *work)
1520 unsigned long flags;
1521 struct ufs_hba *hba = container_of(work, struct ufs_hba,
1522 clk_gating.ungate_work);
1524 cancel_delayed_work_sync(&hba->clk_gating.gate_work);
1526 spin_lock_irqsave(hba->host->host_lock, flags);
1527 if (hba->clk_gating.state == CLKS_ON) {
1528 spin_unlock_irqrestore(hba->host->host_lock, flags);
1532 spin_unlock_irqrestore(hba->host->host_lock, flags);
1533 ufshcd_setup_clocks(hba, true);
1535 ufshcd_enable_irq(hba);
1537 /* Exit from hibern8 */
1538 if (ufshcd_can_hibern8_during_gating(hba)) {
1539 /* Prevent gating in this path */
1540 hba->clk_gating.is_suspended = true;
1541 if (ufshcd_is_link_hibern8(hba)) {
1542 ret = ufshcd_uic_hibern8_exit(hba);
1544 dev_err(hba->dev, "%s: hibern8 exit failed %d\n",
1547 ufshcd_set_link_active(hba);
1549 hba->clk_gating.is_suspended = false;
1552 ufshcd_scsi_unblock_requests(hba);
1556 * ufshcd_hold - Enable clocks that were gated earlier due to ufshcd_release.
1557 * Also, exit from hibern8 mode and set the link as active.
1558 * @hba: per adapter instance
1559 * @async: This indicates whether caller should ungate clocks asynchronously.
1561 int ufshcd_hold(struct ufs_hba *hba, bool async)
1564 unsigned long flags;
1566 if (!ufshcd_is_clkgating_allowed(hba))
1568 spin_lock_irqsave(hba->host->host_lock, flags);
1569 hba->clk_gating.active_reqs++;
1571 if (ufshcd_eh_in_progress(hba)) {
1572 spin_unlock_irqrestore(hba->host->host_lock, flags);
1577 switch (hba->clk_gating.state) {
1580 * Wait for the ungate work to complete if in progress.
1581 * Though the clocks may be in ON state, the link could
1582 * still be in hibner8 state if hibern8 is allowed
1583 * during clock gating.
1584 * Make sure we exit hibern8 state also in addition to
1587 if (ufshcd_can_hibern8_during_gating(hba) &&
1588 ufshcd_is_link_hibern8(hba)) {
1591 hba->clk_gating.active_reqs--;
1594 spin_unlock_irqrestore(hba->host->host_lock, flags);
1595 flush_work(&hba->clk_gating.ungate_work);
1596 spin_lock_irqsave(hba->host->host_lock, flags);
1601 if (cancel_delayed_work(&hba->clk_gating.gate_work)) {
1602 hba->clk_gating.state = CLKS_ON;
1603 trace_ufshcd_clk_gating(dev_name(hba->dev),
1604 hba->clk_gating.state);
1608 * If we are here, it means gating work is either done or
1609 * currently running. Hence, fall through to cancel gating
1610 * work and to enable clocks.
1614 ufshcd_scsi_block_requests(hba);
1615 hba->clk_gating.state = REQ_CLKS_ON;
1616 trace_ufshcd_clk_gating(dev_name(hba->dev),
1617 hba->clk_gating.state);
1618 queue_work(hba->clk_gating.clk_gating_workq,
1619 &hba->clk_gating.ungate_work);
1621 * fall through to check if we should wait for this
1622 * work to be done or not.
1628 hba->clk_gating.active_reqs--;
1632 spin_unlock_irqrestore(hba->host->host_lock, flags);
1633 flush_work(&hba->clk_gating.ungate_work);
1634 /* Make sure state is CLKS_ON before returning */
1635 spin_lock_irqsave(hba->host->host_lock, flags);
1638 dev_err(hba->dev, "%s: clk gating is in invalid state %d\n",
1639 __func__, hba->clk_gating.state);
1642 spin_unlock_irqrestore(hba->host->host_lock, flags);
1646 EXPORT_SYMBOL_GPL(ufshcd_hold);
1648 static void ufshcd_gate_work(struct work_struct *work)
1650 struct ufs_hba *hba = container_of(work, struct ufs_hba,
1651 clk_gating.gate_work.work);
1652 unsigned long flags;
1654 spin_lock_irqsave(hba->host->host_lock, flags);
1656 * In case you are here to cancel this work the gating state
1657 * would be marked as REQ_CLKS_ON. In this case save time by
1658 * skipping the gating work and exit after changing the clock
1661 if (hba->clk_gating.is_suspended ||
1662 (hba->clk_gating.state != REQ_CLKS_OFF)) {
1663 hba->clk_gating.state = CLKS_ON;
1664 trace_ufshcd_clk_gating(dev_name(hba->dev),
1665 hba->clk_gating.state);
1669 if (hba->clk_gating.active_reqs
1670 || hba->ufshcd_state != UFSHCD_STATE_OPERATIONAL
1671 || ufshcd_any_tag_in_use(hba) || hba->outstanding_tasks
1672 || hba->active_uic_cmd || hba->uic_async_done)
1675 spin_unlock_irqrestore(hba->host->host_lock, flags);
1677 /* put the link into hibern8 mode before turning off clocks */
1678 if (ufshcd_can_hibern8_during_gating(hba)) {
1679 if (ufshcd_uic_hibern8_enter(hba)) {
1680 hba->clk_gating.state = CLKS_ON;
1681 trace_ufshcd_clk_gating(dev_name(hba->dev),
1682 hba->clk_gating.state);
1685 ufshcd_set_link_hibern8(hba);
1688 ufshcd_disable_irq(hba);
1690 if (!ufshcd_is_link_active(hba))
1691 ufshcd_setup_clocks(hba, false);
1693 /* If link is active, device ref_clk can't be switched off */
1694 __ufshcd_setup_clocks(hba, false, true);
1697 * In case you are here to cancel this work the gating state
1698 * would be marked as REQ_CLKS_ON. In this case keep the state
1699 * as REQ_CLKS_ON which would anyway imply that clocks are off
1700 * and a request to turn them on is pending. By doing this way,
1701 * we keep the state machine in tact and this would ultimately
1702 * prevent from doing cancel work multiple times when there are
1703 * new requests arriving before the current cancel work is done.
1705 spin_lock_irqsave(hba->host->host_lock, flags);
1706 if (hba->clk_gating.state == REQ_CLKS_OFF) {
1707 hba->clk_gating.state = CLKS_OFF;
1708 trace_ufshcd_clk_gating(dev_name(hba->dev),
1709 hba->clk_gating.state);
1712 spin_unlock_irqrestore(hba->host->host_lock, flags);
1717 /* host lock must be held before calling this variant */
1718 static void __ufshcd_release(struct ufs_hba *hba)
1720 if (!ufshcd_is_clkgating_allowed(hba))
1723 hba->clk_gating.active_reqs--;
1725 if (hba->clk_gating.active_reqs || hba->clk_gating.is_suspended
1726 || hba->ufshcd_state != UFSHCD_STATE_OPERATIONAL
1727 || ufshcd_any_tag_in_use(hba) || hba->outstanding_tasks
1728 || hba->active_uic_cmd || hba->uic_async_done
1729 || ufshcd_eh_in_progress(hba))
1732 hba->clk_gating.state = REQ_CLKS_OFF;
1733 trace_ufshcd_clk_gating(dev_name(hba->dev), hba->clk_gating.state);
1734 queue_delayed_work(hba->clk_gating.clk_gating_workq,
1735 &hba->clk_gating.gate_work,
1736 msecs_to_jiffies(hba->clk_gating.delay_ms));
1739 void ufshcd_release(struct ufs_hba *hba)
1741 unsigned long flags;
1743 spin_lock_irqsave(hba->host->host_lock, flags);
1744 __ufshcd_release(hba);
1745 spin_unlock_irqrestore(hba->host->host_lock, flags);
1747 EXPORT_SYMBOL_GPL(ufshcd_release);
1749 static ssize_t ufshcd_clkgate_delay_show(struct device *dev,
1750 struct device_attribute *attr, char *buf)
1752 struct ufs_hba *hba = dev_get_drvdata(dev);
1754 return snprintf(buf, PAGE_SIZE, "%lu\n", hba->clk_gating.delay_ms);
1757 static ssize_t ufshcd_clkgate_delay_store(struct device *dev,
1758 struct device_attribute *attr, const char *buf, size_t count)
1760 struct ufs_hba *hba = dev_get_drvdata(dev);
1761 unsigned long flags, value;
1763 if (kstrtoul(buf, 0, &value))
1766 spin_lock_irqsave(hba->host->host_lock, flags);
1767 hba->clk_gating.delay_ms = value;
1768 spin_unlock_irqrestore(hba->host->host_lock, flags);
1772 static ssize_t ufshcd_clkgate_enable_show(struct device *dev,
1773 struct device_attribute *attr, char *buf)
1775 struct ufs_hba *hba = dev_get_drvdata(dev);
1777 return snprintf(buf, PAGE_SIZE, "%d\n", hba->clk_gating.is_enabled);
1780 static ssize_t ufshcd_clkgate_enable_store(struct device *dev,
1781 struct device_attribute *attr, const char *buf, size_t count)
1783 struct ufs_hba *hba = dev_get_drvdata(dev);
1784 unsigned long flags;
1787 if (kstrtou32(buf, 0, &value))
1791 if (value == hba->clk_gating.is_enabled)
1795 ufshcd_release(hba);
1797 spin_lock_irqsave(hba->host->host_lock, flags);
1798 hba->clk_gating.active_reqs++;
1799 spin_unlock_irqrestore(hba->host->host_lock, flags);
1802 hba->clk_gating.is_enabled = value;
1807 static void ufshcd_init_clk_scaling(struct ufs_hba *hba)
1809 char wq_name[sizeof("ufs_clkscaling_00")];
1811 if (!ufshcd_is_clkscaling_supported(hba))
1814 INIT_WORK(&hba->clk_scaling.suspend_work,
1815 ufshcd_clk_scaling_suspend_work);
1816 INIT_WORK(&hba->clk_scaling.resume_work,
1817 ufshcd_clk_scaling_resume_work);
1819 snprintf(wq_name, sizeof(wq_name), "ufs_clkscaling_%d",
1820 hba->host->host_no);
1821 hba->clk_scaling.workq = create_singlethread_workqueue(wq_name);
1823 ufshcd_clkscaling_init_sysfs(hba);
1826 static void ufshcd_exit_clk_scaling(struct ufs_hba *hba)
1828 if (!ufshcd_is_clkscaling_supported(hba))
1831 destroy_workqueue(hba->clk_scaling.workq);
1832 ufshcd_devfreq_remove(hba);
1835 static void ufshcd_init_clk_gating(struct ufs_hba *hba)
1837 char wq_name[sizeof("ufs_clk_gating_00")];
1839 if (!ufshcd_is_clkgating_allowed(hba))
1842 hba->clk_gating.delay_ms = 150;
1843 INIT_DELAYED_WORK(&hba->clk_gating.gate_work, ufshcd_gate_work);
1844 INIT_WORK(&hba->clk_gating.ungate_work, ufshcd_ungate_work);
1846 snprintf(wq_name, ARRAY_SIZE(wq_name), "ufs_clk_gating_%d",
1847 hba->host->host_no);
1848 hba->clk_gating.clk_gating_workq = alloc_ordered_workqueue(wq_name,
1851 hba->clk_gating.is_enabled = true;
1853 hba->clk_gating.delay_attr.show = ufshcd_clkgate_delay_show;
1854 hba->clk_gating.delay_attr.store = ufshcd_clkgate_delay_store;
1855 sysfs_attr_init(&hba->clk_gating.delay_attr.attr);
1856 hba->clk_gating.delay_attr.attr.name = "clkgate_delay_ms";
1857 hba->clk_gating.delay_attr.attr.mode = 0644;
1858 if (device_create_file(hba->dev, &hba->clk_gating.delay_attr))
1859 dev_err(hba->dev, "Failed to create sysfs for clkgate_delay\n");
1861 hba->clk_gating.enable_attr.show = ufshcd_clkgate_enable_show;
1862 hba->clk_gating.enable_attr.store = ufshcd_clkgate_enable_store;
1863 sysfs_attr_init(&hba->clk_gating.enable_attr.attr);
1864 hba->clk_gating.enable_attr.attr.name = "clkgate_enable";
1865 hba->clk_gating.enable_attr.attr.mode = 0644;
1866 if (device_create_file(hba->dev, &hba->clk_gating.enable_attr))
1867 dev_err(hba->dev, "Failed to create sysfs for clkgate_enable\n");
1870 static void ufshcd_exit_clk_gating(struct ufs_hba *hba)
1872 if (!ufshcd_is_clkgating_allowed(hba))
1874 device_remove_file(hba->dev, &hba->clk_gating.delay_attr);
1875 device_remove_file(hba->dev, &hba->clk_gating.enable_attr);
1876 cancel_work_sync(&hba->clk_gating.ungate_work);
1877 cancel_delayed_work_sync(&hba->clk_gating.gate_work);
1878 destroy_workqueue(hba->clk_gating.clk_gating_workq);
1881 /* Must be called with host lock acquired */
1882 static void ufshcd_clk_scaling_start_busy(struct ufs_hba *hba)
1884 bool queue_resume_work = false;
1885 ktime_t curr_t = ktime_get();
1887 if (!ufshcd_is_clkscaling_supported(hba))
1890 if (!hba->clk_scaling.active_reqs++)
1891 queue_resume_work = true;
1893 if (!hba->clk_scaling.is_allowed || hba->pm_op_in_progress)
1896 if (queue_resume_work)
1897 queue_work(hba->clk_scaling.workq,
1898 &hba->clk_scaling.resume_work);
1900 if (!hba->clk_scaling.window_start_t) {
1901 hba->clk_scaling.window_start_t = curr_t;
1902 hba->clk_scaling.tot_busy_t = 0;
1903 hba->clk_scaling.is_busy_started = false;
1906 if (!hba->clk_scaling.is_busy_started) {
1907 hba->clk_scaling.busy_start_t = curr_t;
1908 hba->clk_scaling.is_busy_started = true;
1912 static void ufshcd_clk_scaling_update_busy(struct ufs_hba *hba)
1914 struct ufs_clk_scaling *scaling = &hba->clk_scaling;
1916 if (!ufshcd_is_clkscaling_supported(hba))
1919 if (!hba->outstanding_reqs && scaling->is_busy_started) {
1920 scaling->tot_busy_t += ktime_to_us(ktime_sub(ktime_get(),
1921 scaling->busy_start_t));
1922 scaling->busy_start_t = 0;
1923 scaling->is_busy_started = false;
1927 * ufshcd_send_command - Send SCSI or device management commands
1928 * @hba: per adapter instance
1929 * @task_tag: Task tag of the command
1932 void ufshcd_send_command(struct ufs_hba *hba, unsigned int task_tag)
1934 struct ufshcd_lrb *lrbp = &hba->lrb[task_tag];
1936 lrbp->issue_time_stamp = ktime_get();
1937 lrbp->compl_time_stamp = ktime_set(0, 0);
1938 ufshcd_vops_setup_xfer_req(hba, task_tag, (lrbp->cmd ? true : false));
1939 ufshcd_add_command_trace(hba, task_tag, "send");
1940 ufshcd_clk_scaling_start_busy(hba);
1941 __set_bit(task_tag, &hba->outstanding_reqs);
1942 ufshcd_writel(hba, 1 << task_tag, REG_UTP_TRANSFER_REQ_DOOR_BELL);
1943 /* Make sure that doorbell is committed immediately */
1948 * ufshcd_copy_sense_data - Copy sense data in case of check condition
1949 * @lrbp: pointer to local reference block
1951 static inline void ufshcd_copy_sense_data(struct ufshcd_lrb *lrbp)
1954 if (lrbp->sense_buffer &&
1955 ufshcd_get_rsp_upiu_data_seg_len(lrbp->ucd_rsp_ptr)) {
1958 len = be16_to_cpu(lrbp->ucd_rsp_ptr->sr.sense_data_len);
1959 len_to_copy = min_t(int, UFS_SENSE_SIZE, len);
1961 memcpy(lrbp->sense_buffer, lrbp->ucd_rsp_ptr->sr.sense_data,
1967 * ufshcd_copy_query_response() - Copy the Query Response and the data
1969 * @hba: per adapter instance
1970 * @lrbp: pointer to local reference block
1973 int ufshcd_copy_query_response(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
1975 struct ufs_query_res *query_res = &hba->dev_cmd.query.response;
1977 memcpy(&query_res->upiu_res, &lrbp->ucd_rsp_ptr->qr, QUERY_OSF_SIZE);
1979 /* Get the descriptor */
1980 if (hba->dev_cmd.query.descriptor &&
1981 lrbp->ucd_rsp_ptr->qr.opcode == UPIU_QUERY_OPCODE_READ_DESC) {
1982 u8 *descp = (u8 *)lrbp->ucd_rsp_ptr +
1983 GENERAL_UPIU_REQUEST_SIZE;
1987 /* data segment length */
1988 resp_len = be32_to_cpu(lrbp->ucd_rsp_ptr->header.dword_2) &
1989 MASK_QUERY_DATA_SEG_LEN;
1990 buf_len = be16_to_cpu(
1991 hba->dev_cmd.query.request.upiu_req.length);
1992 if (likely(buf_len >= resp_len)) {
1993 memcpy(hba->dev_cmd.query.descriptor, descp, resp_len);
1996 "%s: rsp size %d is bigger than buffer size %d",
1997 __func__, resp_len, buf_len);
2006 * ufshcd_hba_capabilities - Read controller capabilities
2007 * @hba: per adapter instance
2009 * Return: 0 on success, negative on error.
2011 static inline int ufshcd_hba_capabilities(struct ufs_hba *hba)
2015 hba->capabilities = ufshcd_readl(hba, REG_CONTROLLER_CAPABILITIES);
2017 /* nutrs and nutmrs are 0 based values */
2018 hba->nutrs = (hba->capabilities & MASK_TRANSFER_REQUESTS_SLOTS) + 1;
2020 ((hba->capabilities & MASK_TASK_MANAGEMENT_REQUEST_SLOTS) >> 16) + 1;
2022 /* Read crypto capabilities */
2023 err = ufshcd_hba_init_crypto_capabilities(hba);
2025 dev_err(hba->dev, "crypto setup failed\n");
2031 * ufshcd_ready_for_uic_cmd - Check if controller is ready
2032 * to accept UIC commands
2033 * @hba: per adapter instance
2034 * Return true on success, else false
2036 static inline bool ufshcd_ready_for_uic_cmd(struct ufs_hba *hba)
2038 if (ufshcd_readl(hba, REG_CONTROLLER_STATUS) & UIC_COMMAND_READY)
2045 * ufshcd_get_upmcrs - Get the power mode change request status
2046 * @hba: Pointer to adapter instance
2048 * This function gets the UPMCRS field of HCS register
2049 * Returns value of UPMCRS field
2051 static inline u8 ufshcd_get_upmcrs(struct ufs_hba *hba)
2053 return (ufshcd_readl(hba, REG_CONTROLLER_STATUS) >> 8) & 0x7;
2057 * ufshcd_dispatch_uic_cmd - Dispatch UIC commands to unipro layers
2058 * @hba: per adapter instance
2059 * @uic_cmd: UIC command
2061 * Mutex must be held.
2064 ufshcd_dispatch_uic_cmd(struct ufs_hba *hba, struct uic_command *uic_cmd)
2066 WARN_ON(hba->active_uic_cmd);
2068 hba->active_uic_cmd = uic_cmd;
2071 ufshcd_writel(hba, uic_cmd->argument1, REG_UIC_COMMAND_ARG_1);
2072 ufshcd_writel(hba, uic_cmd->argument2, REG_UIC_COMMAND_ARG_2);
2073 ufshcd_writel(hba, uic_cmd->argument3, REG_UIC_COMMAND_ARG_3);
2075 ufshcd_add_uic_command_trace(hba, uic_cmd, "send");
2078 ufshcd_writel(hba, uic_cmd->command & COMMAND_OPCODE_MASK,
2083 * ufshcd_wait_for_uic_cmd - Wait complectioin of UIC command
2084 * @hba: per adapter instance
2085 * @uic_cmd: UIC command
2087 * Must be called with mutex held.
2088 * Returns 0 only if success.
2091 ufshcd_wait_for_uic_cmd(struct ufs_hba *hba, struct uic_command *uic_cmd)
2094 unsigned long flags;
2096 if (wait_for_completion_timeout(&uic_cmd->done,
2097 msecs_to_jiffies(UIC_CMD_TIMEOUT)))
2098 ret = uic_cmd->argument2 & MASK_UIC_COMMAND_RESULT;
2102 spin_lock_irqsave(hba->host->host_lock, flags);
2103 hba->active_uic_cmd = NULL;
2104 spin_unlock_irqrestore(hba->host->host_lock, flags);
2110 * __ufshcd_send_uic_cmd - Send UIC commands and retrieve the result
2111 * @hba: per adapter instance
2112 * @uic_cmd: UIC command
2113 * @completion: initialize the completion only if this is set to true
2115 * Identical to ufshcd_send_uic_cmd() expect mutex. Must be called
2116 * with mutex held and host_lock locked.
2117 * Returns 0 only if success.
2120 __ufshcd_send_uic_cmd(struct ufs_hba *hba, struct uic_command *uic_cmd,
2123 if (!ufshcd_ready_for_uic_cmd(hba)) {
2125 "Controller not ready to accept UIC commands\n");
2130 init_completion(&uic_cmd->done);
2132 ufshcd_dispatch_uic_cmd(hba, uic_cmd);
2138 * ufshcd_send_uic_cmd - Send UIC commands and retrieve the result
2139 * @hba: per adapter instance
2140 * @uic_cmd: UIC command
2142 * Returns 0 only if success.
2144 int ufshcd_send_uic_cmd(struct ufs_hba *hba, struct uic_command *uic_cmd)
2147 unsigned long flags;
2149 ufshcd_hold(hba, false);
2150 mutex_lock(&hba->uic_cmd_mutex);
2151 ufshcd_add_delay_before_dme_cmd(hba);
2153 spin_lock_irqsave(hba->host->host_lock, flags);
2154 ret = __ufshcd_send_uic_cmd(hba, uic_cmd, true);
2155 spin_unlock_irqrestore(hba->host->host_lock, flags);
2157 ret = ufshcd_wait_for_uic_cmd(hba, uic_cmd);
2159 mutex_unlock(&hba->uic_cmd_mutex);
2161 ufshcd_release(hba);
2166 * ufshcd_map_sg - Map scatter-gather list to prdt
2167 * @hba: per adapter instance
2168 * @lrbp: pointer to local reference block
2170 * Returns 0 in case of success, non-zero value in case of failure
2172 static int ufshcd_map_sg(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
2174 struct ufshcd_sg_entry *prd_table;
2175 struct scatterlist *sg;
2176 struct scsi_cmnd *cmd;
2181 sg_segments = scsi_dma_map(cmd);
2182 if (sg_segments < 0)
2187 if (hba->quirks & UFSHCD_QUIRK_PRDT_BYTE_GRAN)
2188 lrbp->utr_descriptor_ptr->prd_table_length =
2189 cpu_to_le16((sg_segments *
2190 sizeof(struct ufshcd_sg_entry)));
2192 lrbp->utr_descriptor_ptr->prd_table_length =
2193 cpu_to_le16((u16) (sg_segments));
2195 prd_table = (struct ufshcd_sg_entry *)lrbp->ucd_prdt_ptr;
2197 scsi_for_each_sg(cmd, sg, sg_segments, i) {
2199 cpu_to_le32(((u32) sg_dma_len(sg))-1);
2200 prd_table[i].base_addr =
2201 cpu_to_le32(lower_32_bits(sg->dma_address));
2202 prd_table[i].upper_addr =
2203 cpu_to_le32(upper_32_bits(sg->dma_address));
2204 prd_table[i].reserved = 0;
2207 lrbp->utr_descriptor_ptr->prd_table_length = 0;
2214 * ufshcd_enable_intr - enable interrupts
2215 * @hba: per adapter instance
2216 * @intrs: interrupt bits
2218 static void ufshcd_enable_intr(struct ufs_hba *hba, u32 intrs)
2220 u32 set = ufshcd_readl(hba, REG_INTERRUPT_ENABLE);
2222 if (hba->ufs_version == UFSHCI_VERSION_10) {
2224 rw = set & INTERRUPT_MASK_RW_VER_10;
2225 set = rw | ((set ^ intrs) & intrs);
2230 ufshcd_writel(hba, set, REG_INTERRUPT_ENABLE);
2234 * ufshcd_disable_intr - disable interrupts
2235 * @hba: per adapter instance
2236 * @intrs: interrupt bits
2238 static void ufshcd_disable_intr(struct ufs_hba *hba, u32 intrs)
2240 u32 set = ufshcd_readl(hba, REG_INTERRUPT_ENABLE);
2242 if (hba->ufs_version == UFSHCI_VERSION_10) {
2244 rw = (set & INTERRUPT_MASK_RW_VER_10) &
2245 ~(intrs & INTERRUPT_MASK_RW_VER_10);
2246 set = rw | ((set & intrs) & ~INTERRUPT_MASK_RW_VER_10);
2252 ufshcd_writel(hba, set, REG_INTERRUPT_ENABLE);
2256 * ufshcd_prepare_req_desc_hdr() - Fills the requests header
2257 * descriptor according to request
2258 * @lrbp: pointer to local reference block
2259 * @upiu_flags: flags required in the header
2260 * @cmd_dir: requests data direction
2262 static void ufshcd_prepare_req_desc_hdr(struct ufshcd_lrb *lrbp,
2263 u8 *upiu_flags, enum dma_data_direction cmd_dir)
2265 struct utp_transfer_req_desc *req_desc = lrbp->utr_descriptor_ptr;
2271 if (cmd_dir == DMA_FROM_DEVICE) {
2272 data_direction = UTP_DEVICE_TO_HOST;
2273 *upiu_flags = UPIU_CMD_FLAGS_READ;
2274 } else if (cmd_dir == DMA_TO_DEVICE) {
2275 data_direction = UTP_HOST_TO_DEVICE;
2276 *upiu_flags = UPIU_CMD_FLAGS_WRITE;
2278 data_direction = UTP_NO_DATA_TRANSFER;
2279 *upiu_flags = UPIU_CMD_FLAGS_NONE;
2282 dword_0 = data_direction | (lrbp->command_type
2283 << UPIU_COMMAND_TYPE_OFFSET);
2285 dword_0 |= UTP_REQ_DESC_INT_CMD;
2287 /* Prepare crypto related dwords */
2288 ufshcd_prepare_req_desc_hdr_crypto(lrbp, &dword_0, &dword_1, &dword_3);
2290 /* Transfer request descriptor header fields */
2291 req_desc->header.dword_0 = cpu_to_le32(dword_0);
2292 req_desc->header.dword_1 = cpu_to_le32(dword_1);
2294 * assigning invalid value for command status. Controller
2295 * updates OCS on command completion, with the command
2298 req_desc->header.dword_2 =
2299 cpu_to_le32(OCS_INVALID_COMMAND_STATUS);
2300 req_desc->header.dword_3 = cpu_to_le32(dword_3);
2302 req_desc->prd_table_length = 0;
2306 * ufshcd_prepare_utp_scsi_cmd_upiu() - fills the utp_transfer_req_desc,
2308 * @lrbp: local reference block pointer
2309 * @upiu_flags: flags
2312 void ufshcd_prepare_utp_scsi_cmd_upiu(struct ufshcd_lrb *lrbp, u8 upiu_flags)
2314 struct scsi_cmnd *cmd = lrbp->cmd;
2315 struct utp_upiu_req *ucd_req_ptr = lrbp->ucd_req_ptr;
2316 unsigned short cdb_len;
2318 /* command descriptor fields */
2319 ucd_req_ptr->header.dword_0 = UPIU_HEADER_DWORD(
2320 UPIU_TRANSACTION_COMMAND, upiu_flags,
2321 lrbp->lun, lrbp->task_tag);
2322 ucd_req_ptr->header.dword_1 = UPIU_HEADER_DWORD(
2323 UPIU_COMMAND_SET_TYPE_SCSI, 0, 0, 0);
2325 /* Total EHS length and Data segment length will be zero */
2326 ucd_req_ptr->header.dword_2 = 0;
2328 ucd_req_ptr->sc.exp_data_transfer_len = cpu_to_be32(cmd->sdb.length);
2330 cdb_len = min_t(unsigned short, cmd->cmd_len, UFS_CDB_SIZE);
2331 memset(ucd_req_ptr->sc.cdb, 0, UFS_CDB_SIZE);
2332 memcpy(ucd_req_ptr->sc.cdb, cmd->cmnd, cdb_len);
2334 memset(lrbp->ucd_rsp_ptr, 0, sizeof(struct utp_upiu_rsp));
2338 * ufshcd_prepare_utp_query_req_upiu() - fills the utp_transfer_req_desc,
2341 * @lrbp: local reference block pointer
2342 * @upiu_flags: flags
2344 static void ufshcd_prepare_utp_query_req_upiu(struct ufs_hba *hba,
2345 struct ufshcd_lrb *lrbp, u8 upiu_flags)
2347 struct utp_upiu_req *ucd_req_ptr = lrbp->ucd_req_ptr;
2348 struct ufs_query *query = &hba->dev_cmd.query;
2349 u16 len = be16_to_cpu(query->request.upiu_req.length);
2351 /* Query request header */
2352 ucd_req_ptr->header.dword_0 = UPIU_HEADER_DWORD(
2353 UPIU_TRANSACTION_QUERY_REQ, upiu_flags,
2354 lrbp->lun, lrbp->task_tag);
2355 ucd_req_ptr->header.dword_1 = UPIU_HEADER_DWORD(
2356 0, query->request.query_func, 0, 0);
2358 /* Data segment length only need for WRITE_DESC */
2359 if (query->request.upiu_req.opcode == UPIU_QUERY_OPCODE_WRITE_DESC)
2360 ucd_req_ptr->header.dword_2 =
2361 UPIU_HEADER_DWORD(0, 0, (len >> 8), (u8)len);
2363 ucd_req_ptr->header.dword_2 = 0;
2365 /* Copy the Query Request buffer as is */
2366 memcpy(&ucd_req_ptr->qr, &query->request.upiu_req,
2369 /* Copy the Descriptor */
2370 if (query->request.upiu_req.opcode == UPIU_QUERY_OPCODE_WRITE_DESC)
2371 memcpy(ucd_req_ptr + 1, query->descriptor, len);
2373 memset(lrbp->ucd_rsp_ptr, 0, sizeof(struct utp_upiu_rsp));
2376 static inline void ufshcd_prepare_utp_nop_upiu(struct ufshcd_lrb *lrbp)
2378 struct utp_upiu_req *ucd_req_ptr = lrbp->ucd_req_ptr;
2380 memset(ucd_req_ptr, 0, sizeof(struct utp_upiu_req));
2382 /* command descriptor fields */
2383 ucd_req_ptr->header.dword_0 =
2385 UPIU_TRANSACTION_NOP_OUT, 0, 0, lrbp->task_tag);
2386 /* clear rest of the fields of basic header */
2387 ucd_req_ptr->header.dword_1 = 0;
2388 ucd_req_ptr->header.dword_2 = 0;
2390 memset(lrbp->ucd_rsp_ptr, 0, sizeof(struct utp_upiu_rsp));
2394 * ufshcd_comp_devman_upiu - UFS Protocol Information Unit(UPIU)
2395 * for Device Management Purposes
2396 * @hba: per adapter instance
2397 * @lrbp: pointer to local reference block
2399 static int ufshcd_comp_devman_upiu(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
2404 if ((hba->ufs_version == UFSHCI_VERSION_10) ||
2405 (hba->ufs_version == UFSHCI_VERSION_11))
2406 lrbp->command_type = UTP_CMD_TYPE_DEV_MANAGE;
2408 lrbp->command_type = UTP_CMD_TYPE_UFS_STORAGE;
2410 ufshcd_prepare_req_desc_hdr(lrbp, &upiu_flags, DMA_NONE);
2411 if (hba->dev_cmd.type == DEV_CMD_TYPE_QUERY)
2412 ufshcd_prepare_utp_query_req_upiu(hba, lrbp, upiu_flags);
2413 else if (hba->dev_cmd.type == DEV_CMD_TYPE_NOP)
2414 ufshcd_prepare_utp_nop_upiu(lrbp);
2422 * ufshcd_comp_scsi_upiu - UFS Protocol Information Unit(UPIU)
2424 * @hba: per adapter instance
2425 * @lrbp: pointer to local reference block
2427 static int ufshcd_comp_scsi_upiu(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
2432 if ((hba->ufs_version == UFSHCI_VERSION_10) ||
2433 (hba->ufs_version == UFSHCI_VERSION_11))
2434 lrbp->command_type = UTP_CMD_TYPE_SCSI;
2436 lrbp->command_type = UTP_CMD_TYPE_UFS_STORAGE;
2438 if (likely(lrbp->cmd)) {
2439 ufshcd_prepare_req_desc_hdr(lrbp, &upiu_flags,
2440 lrbp->cmd->sc_data_direction);
2441 ufshcd_prepare_utp_scsi_cmd_upiu(lrbp, upiu_flags);
2450 * ufshcd_upiu_wlun_to_scsi_wlun - maps UPIU W-LUN id to SCSI W-LUN ID
2451 * @upiu_wlun_id: UPIU W-LUN id
2453 * Returns SCSI W-LUN id
2455 static inline u16 ufshcd_upiu_wlun_to_scsi_wlun(u8 upiu_wlun_id)
2457 return (upiu_wlun_id & ~UFS_UPIU_WLUN_ID) | SCSI_W_LUN_BASE;
2460 static void ufshcd_init_lrb(struct ufs_hba *hba, struct ufshcd_lrb *lrb, int i)
2462 struct utp_transfer_cmd_desc *cmd_descp = hba->ucdl_base_addr;
2463 struct utp_transfer_req_desc *utrdlp = hba->utrdl_base_addr;
2464 dma_addr_t cmd_desc_element_addr = hba->ucdl_dma_addr +
2465 i * sizeof(struct utp_transfer_cmd_desc);
2466 u16 response_offset = offsetof(struct utp_transfer_cmd_desc,
2468 u16 prdt_offset = offsetof(struct utp_transfer_cmd_desc, prd_table);
2470 lrb->utr_descriptor_ptr = utrdlp + i;
2471 lrb->utrd_dma_addr = hba->utrdl_dma_addr +
2472 i * sizeof(struct utp_transfer_req_desc);
2473 lrb->ucd_req_ptr = (struct utp_upiu_req *)(cmd_descp + i);
2474 lrb->ucd_req_dma_addr = cmd_desc_element_addr;
2475 lrb->ucd_rsp_ptr = (struct utp_upiu_rsp *)cmd_descp[i].response_upiu;
2476 lrb->ucd_rsp_dma_addr = cmd_desc_element_addr + response_offset;
2477 lrb->ucd_prdt_ptr = (struct ufshcd_sg_entry *)cmd_descp[i].prd_table;
2478 lrb->ucd_prdt_dma_addr = cmd_desc_element_addr + prdt_offset;
2482 * ufshcd_queuecommand - main entry point for SCSI requests
2483 * @host: SCSI host pointer
2484 * @cmd: command from SCSI Midlayer
2486 * Returns 0 for success, non-zero in case of failure
2488 static int ufshcd_queuecommand(struct Scsi_Host *host, struct scsi_cmnd *cmd)
2490 struct ufshcd_lrb *lrbp;
2491 struct ufs_hba *hba;
2492 unsigned long flags;
2496 hba = shost_priv(host);
2498 tag = cmd->request->tag;
2499 if (!ufshcd_valid_tag(hba, tag)) {
2501 "%s: invalid command tag %d: cmd=0x%p, cmd->request=0x%p",
2502 __func__, tag, cmd, cmd->request);
2506 if (!down_read_trylock(&hba->clk_scaling_lock))
2507 return SCSI_MLQUEUE_HOST_BUSY;
2509 spin_lock_irqsave(hba->host->host_lock, flags);
2510 switch (hba->ufshcd_state) {
2511 case UFSHCD_STATE_OPERATIONAL:
2513 case UFSHCD_STATE_EH_SCHEDULED:
2514 case UFSHCD_STATE_RESET:
2515 err = SCSI_MLQUEUE_HOST_BUSY;
2517 case UFSHCD_STATE_ERROR:
2518 set_host_byte(cmd, DID_ERROR);
2519 cmd->scsi_done(cmd);
2522 dev_WARN_ONCE(hba->dev, 1, "%s: invalid state %d\n",
2523 __func__, hba->ufshcd_state);
2524 set_host_byte(cmd, DID_BAD_TARGET);
2525 cmd->scsi_done(cmd);
2529 /* if error handling is in progress, don't issue commands */
2530 if (ufshcd_eh_in_progress(hba)) {
2531 set_host_byte(cmd, DID_ERROR);
2532 cmd->scsi_done(cmd);
2535 spin_unlock_irqrestore(hba->host->host_lock, flags);
2537 hba->req_abort_count = 0;
2539 err = ufshcd_hold(hba, true);
2541 err = SCSI_MLQUEUE_HOST_BUSY;
2544 WARN_ON(hba->clk_gating.state != CLKS_ON);
2546 lrbp = &hba->lrb[tag];
2550 lrbp->sense_bufflen = UFS_SENSE_SIZE;
2551 lrbp->sense_buffer = cmd->sense_buffer;
2552 lrbp->task_tag = tag;
2553 lrbp->lun = ufshcd_scsi_to_upiu_lun(cmd->device->lun);
2554 lrbp->intr_cmd = !ufshcd_is_intr_aggr_allowed(hba) ? true : false;
2556 ufshcd_prepare_lrbp_crypto(cmd->request, lrbp);
2558 lrbp->req_abort_skip = false;
2560 ufshcd_comp_scsi_upiu(hba, lrbp);
2562 err = ufshcd_map_sg(hba, lrbp);
2565 ufshcd_release(hba);
2568 /* Make sure descriptors are ready before ringing the doorbell */
2571 /* issue command to the controller */
2572 spin_lock_irqsave(hba->host->host_lock, flags);
2573 ufshcd_send_command(hba, tag);
2575 spin_unlock_irqrestore(hba->host->host_lock, flags);
2577 up_read(&hba->clk_scaling_lock);
2581 static int ufshcd_compose_dev_cmd(struct ufs_hba *hba,
2582 struct ufshcd_lrb *lrbp, enum dev_cmd_type cmd_type, int tag)
2585 lrbp->sense_bufflen = 0;
2586 lrbp->sense_buffer = NULL;
2587 lrbp->task_tag = tag;
2588 lrbp->lun = 0; /* device management cmd is not specific to any LUN */
2589 lrbp->intr_cmd = true; /* No interrupt aggregation */
2590 ufshcd_prepare_lrbp_crypto(NULL, lrbp);
2591 hba->dev_cmd.type = cmd_type;
2593 return ufshcd_comp_devman_upiu(hba, lrbp);
2597 ufshcd_clear_cmd(struct ufs_hba *hba, int tag)
2600 unsigned long flags;
2601 u32 mask = 1 << tag;
2603 /* clear outstanding transaction before retry */
2604 spin_lock_irqsave(hba->host->host_lock, flags);
2605 ufshcd_utrl_clear(hba, tag);
2606 spin_unlock_irqrestore(hba->host->host_lock, flags);
2609 * wait for for h/w to clear corresponding bit in door-bell.
2610 * max. wait is 1 sec.
2612 err = ufshcd_wait_for_register(hba,
2613 REG_UTP_TRANSFER_REQ_DOOR_BELL,
2614 mask, ~mask, 1000, 1000);
2620 ufshcd_check_query_response(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
2622 struct ufs_query_res *query_res = &hba->dev_cmd.query.response;
2624 /* Get the UPIU response */
2625 query_res->response = ufshcd_get_rsp_upiu_result(lrbp->ucd_rsp_ptr) >>
2626 UPIU_RSP_CODE_OFFSET;
2627 return query_res->response;
2631 * ufshcd_dev_cmd_completion() - handles device management command responses
2632 * @hba: per adapter instance
2633 * @lrbp: pointer to local reference block
2636 ufshcd_dev_cmd_completion(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
2641 hba->ufs_stats.last_hibern8_exit_tstamp = ktime_set(0, 0);
2642 resp = ufshcd_get_req_rsp(lrbp->ucd_rsp_ptr);
2645 case UPIU_TRANSACTION_NOP_IN:
2646 if (hba->dev_cmd.type != DEV_CMD_TYPE_NOP) {
2648 dev_err(hba->dev, "%s: unexpected response %x\n",
2652 case UPIU_TRANSACTION_QUERY_RSP:
2653 err = ufshcd_check_query_response(hba, lrbp);
2655 err = ufshcd_copy_query_response(hba, lrbp);
2657 case UPIU_TRANSACTION_REJECT_UPIU:
2658 /* TODO: handle Reject UPIU Response */
2660 dev_err(hba->dev, "%s: Reject UPIU not fully implemented\n",
2665 dev_err(hba->dev, "%s: Invalid device management cmd response: %x\n",
2673 static int ufshcd_wait_for_dev_cmd(struct ufs_hba *hba,
2674 struct ufshcd_lrb *lrbp, int max_timeout)
2677 unsigned long time_left;
2678 unsigned long flags;
2680 time_left = wait_for_completion_timeout(hba->dev_cmd.complete,
2681 msecs_to_jiffies(max_timeout));
2683 /* Make sure descriptors are ready before ringing the doorbell */
2685 spin_lock_irqsave(hba->host->host_lock, flags);
2686 hba->dev_cmd.complete = NULL;
2687 if (likely(time_left)) {
2688 err = ufshcd_get_tr_ocs(lrbp);
2690 err = ufshcd_dev_cmd_completion(hba, lrbp);
2692 spin_unlock_irqrestore(hba->host->host_lock, flags);
2696 dev_dbg(hba->dev, "%s: dev_cmd request timedout, tag %d\n",
2697 __func__, lrbp->task_tag);
2698 if (!ufshcd_clear_cmd(hba, lrbp->task_tag))
2699 /* successfully cleared the command, retry if needed */
2702 * in case of an error, after clearing the doorbell,
2703 * we also need to clear the outstanding_request
2706 ufshcd_outstanding_req_clear(hba, lrbp->task_tag);
2713 * ufshcd_exec_dev_cmd - API for sending device management requests
2715 * @cmd_type: specifies the type (NOP, Query...)
2716 * @timeout: time in seconds
2718 * NOTE: Since there is only one available tag for device management commands,
2719 * it is expected you hold the hba->dev_cmd.lock mutex.
2721 static int ufshcd_exec_dev_cmd(struct ufs_hba *hba,
2722 enum dev_cmd_type cmd_type, int timeout)
2724 struct request_queue *q = hba->cmd_queue;
2725 struct request *req;
2726 struct ufshcd_lrb *lrbp;
2729 struct completion wait;
2730 unsigned long flags;
2732 down_read(&hba->clk_scaling_lock);
2735 * Get free slot, sleep if slots are unavailable.
2736 * Even though we use wait_event() which sleeps indefinitely,
2737 * the maximum wait time is bounded by SCSI request timeout.
2739 req = blk_get_request(q, REQ_OP_DRV_OUT, 0);
2745 WARN_ON_ONCE(!ufshcd_valid_tag(hba, tag));
2747 init_completion(&wait);
2748 lrbp = &hba->lrb[tag];
2750 err = ufshcd_compose_dev_cmd(hba, lrbp, cmd_type, tag);
2754 hba->dev_cmd.complete = &wait;
2756 ufshcd_add_query_upiu_trace(hba, tag, "query_send");
2757 /* Make sure descriptors are ready before ringing the doorbell */
2759 spin_lock_irqsave(hba->host->host_lock, flags);
2760 ufshcd_send_command(hba, tag);
2761 spin_unlock_irqrestore(hba->host->host_lock, flags);
2763 err = ufshcd_wait_for_dev_cmd(hba, lrbp, timeout);
2765 ufshcd_add_query_upiu_trace(hba, tag,
2766 err ? "query_complete_err" : "query_complete");
2769 blk_put_request(req);
2771 up_read(&hba->clk_scaling_lock);
2776 * ufshcd_init_query() - init the query response and request parameters
2777 * @hba: per-adapter instance
2778 * @request: address of the request pointer to be initialized
2779 * @response: address of the response pointer to be initialized
2780 * @opcode: operation to perform
2781 * @idn: flag idn to access
2782 * @index: LU number to access
2783 * @selector: query/flag/descriptor further identification
2785 static inline void ufshcd_init_query(struct ufs_hba *hba,
2786 struct ufs_query_req **request, struct ufs_query_res **response,
2787 enum query_opcode opcode, u8 idn, u8 index, u8 selector)
2789 *request = &hba->dev_cmd.query.request;
2790 *response = &hba->dev_cmd.query.response;
2791 memset(*request, 0, sizeof(struct ufs_query_req));
2792 memset(*response, 0, sizeof(struct ufs_query_res));
2793 (*request)->upiu_req.opcode = opcode;
2794 (*request)->upiu_req.idn = idn;
2795 (*request)->upiu_req.index = index;
2796 (*request)->upiu_req.selector = selector;
2799 static int ufshcd_query_flag_retry(struct ufs_hba *hba,
2800 enum query_opcode opcode, enum flag_idn idn, u8 index, bool *flag_res)
2805 for (retries = 0; retries < QUERY_REQ_RETRIES; retries++) {
2806 ret = ufshcd_query_flag(hba, opcode, idn, index, flag_res);
2809 "%s: failed with error %d, retries %d\n",
2810 __func__, ret, retries);
2817 "%s: query attribute, opcode %d, idn %d, failed with error %d after %d retires\n",
2818 __func__, opcode, idn, ret, retries);
2823 * ufshcd_query_flag() - API function for sending flag query requests
2824 * @hba: per-adapter instance
2825 * @opcode: flag query to perform
2826 * @idn: flag idn to access
2827 * @index: flag index to access
2828 * @flag_res: the flag value after the query request completes
2830 * Returns 0 for success, non-zero in case of failure
2832 int ufshcd_query_flag(struct ufs_hba *hba, enum query_opcode opcode,
2833 enum flag_idn idn, u8 index, bool *flag_res)
2835 struct ufs_query_req *request = NULL;
2836 struct ufs_query_res *response = NULL;
2837 int err, selector = 0;
2838 int timeout = QUERY_REQ_TIMEOUT;
2842 ufshcd_hold(hba, false);
2843 mutex_lock(&hba->dev_cmd.lock);
2844 ufshcd_init_query(hba, &request, &response, opcode, idn, index,
2848 case UPIU_QUERY_OPCODE_SET_FLAG:
2849 case UPIU_QUERY_OPCODE_CLEAR_FLAG:
2850 case UPIU_QUERY_OPCODE_TOGGLE_FLAG:
2851 request->query_func = UPIU_QUERY_FUNC_STANDARD_WRITE_REQUEST;
2853 case UPIU_QUERY_OPCODE_READ_FLAG:
2854 request->query_func = UPIU_QUERY_FUNC_STANDARD_READ_REQUEST;
2856 /* No dummy reads */
2857 dev_err(hba->dev, "%s: Invalid argument for read request\n",
2865 "%s: Expected query flag opcode but got = %d\n",
2871 err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_QUERY, timeout);
2875 "%s: Sending flag query for idn %d failed, err = %d\n",
2876 __func__, idn, err);
2881 *flag_res = (be32_to_cpu(response->upiu_res.value) &
2882 MASK_QUERY_UPIU_FLAG_LOC) & 0x1;
2885 mutex_unlock(&hba->dev_cmd.lock);
2886 ufshcd_release(hba);
2891 * ufshcd_query_attr - API function for sending attribute requests
2892 * @hba: per-adapter instance
2893 * @opcode: attribute opcode
2894 * @idn: attribute idn to access
2895 * @index: index field
2896 * @selector: selector field
2897 * @attr_val: the attribute value after the query request completes
2899 * Returns 0 for success, non-zero in case of failure
2901 int ufshcd_query_attr(struct ufs_hba *hba, enum query_opcode opcode,
2902 enum attr_idn idn, u8 index, u8 selector, u32 *attr_val)
2904 struct ufs_query_req *request = NULL;
2905 struct ufs_query_res *response = NULL;
2910 ufshcd_hold(hba, false);
2912 dev_err(hba->dev, "%s: attribute value required for opcode 0x%x\n",
2918 mutex_lock(&hba->dev_cmd.lock);
2919 ufshcd_init_query(hba, &request, &response, opcode, idn, index,
2923 case UPIU_QUERY_OPCODE_WRITE_ATTR:
2924 request->query_func = UPIU_QUERY_FUNC_STANDARD_WRITE_REQUEST;
2925 request->upiu_req.value = cpu_to_be32(*attr_val);
2927 case UPIU_QUERY_OPCODE_READ_ATTR:
2928 request->query_func = UPIU_QUERY_FUNC_STANDARD_READ_REQUEST;
2931 dev_err(hba->dev, "%s: Expected query attr opcode but got = 0x%.2x\n",
2937 err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_QUERY, QUERY_REQ_TIMEOUT);
2940 dev_err(hba->dev, "%s: opcode 0x%.2x for idn %d failed, index %d, err = %d\n",
2941 __func__, opcode, idn, index, err);
2945 *attr_val = be32_to_cpu(response->upiu_res.value);
2948 mutex_unlock(&hba->dev_cmd.lock);
2950 ufshcd_release(hba);
2955 * ufshcd_query_attr_retry() - API function for sending query
2956 * attribute with retries
2957 * @hba: per-adapter instance
2958 * @opcode: attribute opcode
2959 * @idn: attribute idn to access
2960 * @index: index field
2961 * @selector: selector field
2962 * @attr_val: the attribute value after the query request
2965 * Returns 0 for success, non-zero in case of failure
2967 static int ufshcd_query_attr_retry(struct ufs_hba *hba,
2968 enum query_opcode opcode, enum attr_idn idn, u8 index, u8 selector,
2974 for (retries = QUERY_REQ_RETRIES; retries > 0; retries--) {
2975 ret = ufshcd_query_attr(hba, opcode, idn, index,
2976 selector, attr_val);
2978 dev_dbg(hba->dev, "%s: failed with error %d, retries %d\n",
2979 __func__, ret, retries);
2986 "%s: query attribute, idn %d, failed with error %d after %d retires\n",
2987 __func__, idn, ret, QUERY_REQ_RETRIES);
2991 static int __ufshcd_query_descriptor(struct ufs_hba *hba,
2992 enum query_opcode opcode, enum desc_idn idn, u8 index,
2993 u8 selector, u8 *desc_buf, int *buf_len)
2995 struct ufs_query_req *request = NULL;
2996 struct ufs_query_res *response = NULL;
3001 ufshcd_hold(hba, false);
3003 dev_err(hba->dev, "%s: descriptor buffer required for opcode 0x%x\n",
3009 if (*buf_len < QUERY_DESC_MIN_SIZE || *buf_len > QUERY_DESC_MAX_SIZE) {
3010 dev_err(hba->dev, "%s: descriptor buffer size (%d) is out of range\n",
3011 __func__, *buf_len);
3016 mutex_lock(&hba->dev_cmd.lock);
3017 ufshcd_init_query(hba, &request, &response, opcode, idn, index,
3019 hba->dev_cmd.query.descriptor = desc_buf;
3020 request->upiu_req.length = cpu_to_be16(*buf_len);
3023 case UPIU_QUERY_OPCODE_WRITE_DESC:
3024 request->query_func = UPIU_QUERY_FUNC_STANDARD_WRITE_REQUEST;
3026 case UPIU_QUERY_OPCODE_READ_DESC:
3027 request->query_func = UPIU_QUERY_FUNC_STANDARD_READ_REQUEST;
3031 "%s: Expected query descriptor opcode but got = 0x%.2x\n",
3037 err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_QUERY, QUERY_REQ_TIMEOUT);
3040 dev_err(hba->dev, "%s: opcode 0x%.2x for idn %d failed, index %d, err = %d\n",
3041 __func__, opcode, idn, index, err);
3045 *buf_len = be16_to_cpu(response->upiu_res.length);
3048 hba->dev_cmd.query.descriptor = NULL;
3049 mutex_unlock(&hba->dev_cmd.lock);
3051 ufshcd_release(hba);
3056 * ufshcd_query_descriptor_retry - API function for sending descriptor requests
3057 * @hba: per-adapter instance
3058 * @opcode: attribute opcode
3059 * @idn: attribute idn to access
3060 * @index: index field
3061 * @selector: selector field
3062 * @desc_buf: the buffer that contains the descriptor
3063 * @buf_len: length parameter passed to the device
3065 * Returns 0 for success, non-zero in case of failure.
3066 * The buf_len parameter will contain, on return, the length parameter
3067 * received on the response.
3069 int ufshcd_query_descriptor_retry(struct ufs_hba *hba,
3070 enum query_opcode opcode,
3071 enum desc_idn idn, u8 index,
3073 u8 *desc_buf, int *buf_len)
3078 for (retries = QUERY_REQ_RETRIES; retries > 0; retries--) {
3079 err = __ufshcd_query_descriptor(hba, opcode, idn, index,
3080 selector, desc_buf, buf_len);
3081 if (!err || err == -EINVAL)
3089 * ufshcd_map_desc_id_to_length - map descriptor IDN to its length
3090 * @hba: Pointer to adapter instance
3091 * @desc_id: descriptor idn value
3092 * @desc_len: mapped desc length (out)
3094 void ufshcd_map_desc_id_to_length(struct ufs_hba *hba, enum desc_idn desc_id,
3097 if (desc_id >= QUERY_DESC_IDN_MAX || desc_id == QUERY_DESC_IDN_RFU_0 ||
3098 desc_id == QUERY_DESC_IDN_RFU_1)
3101 *desc_len = hba->desc_size[desc_id];
3103 EXPORT_SYMBOL(ufshcd_map_desc_id_to_length);
3105 static void ufshcd_update_desc_length(struct ufs_hba *hba,
3106 enum desc_idn desc_id, int desc_index,
3107 unsigned char desc_len)
3109 if (hba->desc_size[desc_id] == QUERY_DESC_MAX_SIZE &&
3110 desc_id != QUERY_DESC_IDN_STRING && desc_index != UFS_RPMB_UNIT)
3111 /* For UFS 3.1, the normal unit descriptor is 10 bytes larger
3112 * than the RPMB unit, however, both descriptors share the same
3113 * desc_idn, to cover both unit descriptors with one length, we
3114 * choose the normal unit descriptor length by desc_index.
3116 hba->desc_size[desc_id] = desc_len;
3120 * ufshcd_read_desc_param - read the specified descriptor parameter
3121 * @hba: Pointer to adapter instance
3122 * @desc_id: descriptor idn value
3123 * @desc_index: descriptor index
3124 * @param_offset: offset of the parameter to read
3125 * @param_read_buf: pointer to buffer where parameter would be read
3126 * @param_size: sizeof(param_read_buf)
3128 * Return 0 in case of success, non-zero otherwise
3130 int ufshcd_read_desc_param(struct ufs_hba *hba,
3131 enum desc_idn desc_id,
3140 bool is_kmalloc = true;
3143 if (desc_id >= QUERY_DESC_IDN_MAX || !param_size)
3146 /* Get the length of descriptor */
3147 ufshcd_map_desc_id_to_length(hba, desc_id, &buff_len);
3149 dev_err(hba->dev, "%s: Failed to get desc length", __func__);
3153 /* Check whether we need temp memory */
3154 if (param_offset != 0 || param_size < buff_len) {
3155 desc_buf = kmalloc(buff_len, GFP_KERNEL);
3159 desc_buf = param_read_buf;
3163 /* Request for full descriptor */
3164 ret = ufshcd_query_descriptor_retry(hba, UPIU_QUERY_OPCODE_READ_DESC,
3165 desc_id, desc_index, 0,
3166 desc_buf, &buff_len);
3169 dev_err(hba->dev, "%s: Failed reading descriptor. desc_id %d, desc_index %d, param_offset %d, ret %d",
3170 __func__, desc_id, desc_index, param_offset, ret);
3175 if (desc_buf[QUERY_DESC_DESC_TYPE_OFFSET] != desc_id) {
3176 dev_err(hba->dev, "%s: invalid desc_id %d in descriptor header",
3177 __func__, desc_buf[QUERY_DESC_DESC_TYPE_OFFSET]);
3182 /* Update descriptor length */
3183 buff_len = desc_buf[QUERY_DESC_LENGTH_OFFSET];
3184 ufshcd_update_desc_length(hba, desc_id, desc_index, buff_len);
3186 /* Check wherher we will not copy more data, than available */
3187 if (is_kmalloc && (param_offset + param_size) > buff_len)
3188 param_size = buff_len - param_offset;
3191 memcpy(param_read_buf, &desc_buf[param_offset], param_size);
3199 * struct uc_string_id - unicode string
3201 * @len: size of this descriptor inclusive
3202 * @type: descriptor type
3203 * @uc: unicode string character
3205 struct uc_string_id {
3211 /* replace non-printable or non-ASCII characters with spaces */
3212 static inline char ufshcd_remove_non_printable(u8 ch)
3214 return (ch >= 0x20 && ch <= 0x7e) ? ch : ' ';
3218 * ufshcd_read_string_desc - read string descriptor
3219 * @hba: pointer to adapter instance
3220 * @desc_index: descriptor index
3221 * @buf: pointer to buffer where descriptor would be read,
3222 * the caller should free the memory.
3223 * @ascii: if true convert from unicode to ascii characters
3224 * null terminated string.
3227 * * string size on success.
3228 * * -ENOMEM: on allocation failure
3229 * * -EINVAL: on a wrong parameter
3231 int ufshcd_read_string_desc(struct ufs_hba *hba, u8 desc_index,
3232 u8 **buf, bool ascii)
3234 struct uc_string_id *uc_str;
3241 uc_str = kzalloc(QUERY_DESC_MAX_SIZE, GFP_KERNEL);
3245 ret = ufshcd_read_desc_param(hba, QUERY_DESC_IDN_STRING, desc_index, 0,
3246 (u8 *)uc_str, QUERY_DESC_MAX_SIZE);
3248 dev_err(hba->dev, "Reading String Desc failed after %d retries. err = %d\n",
3249 QUERY_REQ_RETRIES, ret);
3254 if (uc_str->len <= QUERY_DESC_HDR_SIZE) {
3255 dev_dbg(hba->dev, "String Desc is of zero length\n");
3264 /* remove header and divide by 2 to move from UTF16 to UTF8 */
3265 ascii_len = (uc_str->len - QUERY_DESC_HDR_SIZE) / 2 + 1;
3266 str = kzalloc(ascii_len, GFP_KERNEL);
3273 * the descriptor contains string in UTF16 format
3274 * we need to convert to utf-8 so it can be displayed
3276 ret = utf16s_to_utf8s(uc_str->uc,
3277 uc_str->len - QUERY_DESC_HDR_SIZE,
3278 UTF16_BIG_ENDIAN, str, ascii_len);
3280 /* replace non-printable or non-ASCII characters with spaces */
3281 for (i = 0; i < ret; i++)
3282 str[i] = ufshcd_remove_non_printable(str[i]);
3287 str = kmemdup(uc_str, uc_str->len, GFP_KERNEL);
3301 * ufshcd_read_unit_desc_param - read the specified unit descriptor parameter
3302 * @hba: Pointer to adapter instance
3304 * @param_offset: offset of the parameter to read
3305 * @param_read_buf: pointer to buffer where parameter would be read
3306 * @param_size: sizeof(param_read_buf)
3308 * Return 0 in case of success, non-zero otherwise
3310 static inline int ufshcd_read_unit_desc_param(struct ufs_hba *hba,
3312 enum unit_desc_param param_offset,
3317 * Unit descriptors are only available for general purpose LUs (LUN id
3318 * from 0 to 7) and RPMB Well known LU.
3320 if (!ufs_is_valid_unit_desc_lun(&hba->dev_info, lun))
3323 return ufshcd_read_desc_param(hba, QUERY_DESC_IDN_UNIT, lun,
3324 param_offset, param_read_buf, param_size);
3327 static int ufshcd_get_ref_clk_gating_wait(struct ufs_hba *hba)
3330 u32 gating_wait = UFSHCD_REF_CLK_GATING_WAIT_US;
3332 if (hba->dev_info.wspecversion >= 0x300) {
3333 err = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
3334 QUERY_ATTR_IDN_REF_CLK_GATING_WAIT_TIME, 0, 0,
3337 dev_err(hba->dev, "Failed reading bRefClkGatingWait. err = %d, use default %uus\n",
3340 if (gating_wait == 0) {
3341 gating_wait = UFSHCD_REF_CLK_GATING_WAIT_US;
3342 dev_err(hba->dev, "Undefined ref clk gating wait time, use default %uus\n",
3346 hba->dev_info.clk_gating_wait_us = gating_wait;
3353 * ufshcd_memory_alloc - allocate memory for host memory space data structures
3354 * @hba: per adapter instance
3356 * 1. Allocate DMA memory for Command Descriptor array
3357 * Each command descriptor consist of Command UPIU, Response UPIU and PRDT
3358 * 2. Allocate DMA memory for UTP Transfer Request Descriptor List (UTRDL).
3359 * 3. Allocate DMA memory for UTP Task Management Request Descriptor List
3361 * 4. Allocate memory for local reference block(lrb).
3363 * Returns 0 for success, non-zero in case of failure
3365 static int ufshcd_memory_alloc(struct ufs_hba *hba)
3367 size_t utmrdl_size, utrdl_size, ucdl_size;
3369 /* Allocate memory for UTP command descriptors */
3370 ucdl_size = (sizeof(struct utp_transfer_cmd_desc) * hba->nutrs);
3371 hba->ucdl_base_addr = dmam_alloc_coherent(hba->dev,
3373 &hba->ucdl_dma_addr,
3377 * UFSHCI requires UTP command descriptor to be 128 byte aligned.
3378 * make sure hba->ucdl_dma_addr is aligned to PAGE_SIZE
3379 * if hba->ucdl_dma_addr is aligned to PAGE_SIZE, then it will
3380 * be aligned to 128 bytes as well
3382 if (!hba->ucdl_base_addr ||
3383 WARN_ON(hba->ucdl_dma_addr & (PAGE_SIZE - 1))) {
3385 "Command Descriptor Memory allocation failed\n");
3390 * Allocate memory for UTP Transfer descriptors
3391 * UFSHCI requires 1024 byte alignment of UTRD
3393 utrdl_size = (sizeof(struct utp_transfer_req_desc) * hba->nutrs);
3394 hba->utrdl_base_addr = dmam_alloc_coherent(hba->dev,
3396 &hba->utrdl_dma_addr,
3398 if (!hba->utrdl_base_addr ||
3399 WARN_ON(hba->utrdl_dma_addr & (PAGE_SIZE - 1))) {
3401 "Transfer Descriptor Memory allocation failed\n");
3406 * Allocate memory for UTP Task Management descriptors
3407 * UFSHCI requires 1024 byte alignment of UTMRD
3409 utmrdl_size = sizeof(struct utp_task_req_desc) * hba->nutmrs;
3410 hba->utmrdl_base_addr = dmam_alloc_coherent(hba->dev,
3412 &hba->utmrdl_dma_addr,
3414 if (!hba->utmrdl_base_addr ||
3415 WARN_ON(hba->utmrdl_dma_addr & (PAGE_SIZE - 1))) {
3417 "Task Management Descriptor Memory allocation failed\n");
3421 /* Allocate memory for local reference block */
3422 hba->lrb = devm_kcalloc(hba->dev,
3423 hba->nutrs, sizeof(struct ufshcd_lrb),
3426 dev_err(hba->dev, "LRB Memory allocation failed\n");
3435 * ufshcd_host_memory_configure - configure local reference block with
3437 * @hba: per adapter instance
3439 * Configure Host memory space
3440 * 1. Update Corresponding UTRD.UCDBA and UTRD.UCDBAU with UCD DMA
3442 * 2. Update each UTRD with Response UPIU offset, Response UPIU length
3444 * 3. Save the corresponding addresses of UTRD, UCD.CMD, UCD.RSP and UCD.PRDT
3445 * into local reference block.
3447 static void ufshcd_host_memory_configure(struct ufs_hba *hba)
3449 struct utp_transfer_req_desc *utrdlp;
3450 dma_addr_t cmd_desc_dma_addr;
3451 dma_addr_t cmd_desc_element_addr;
3452 u16 response_offset;
3457 utrdlp = hba->utrdl_base_addr;
3460 offsetof(struct utp_transfer_cmd_desc, response_upiu);
3462 offsetof(struct utp_transfer_cmd_desc, prd_table);
3464 cmd_desc_size = sizeof(struct utp_transfer_cmd_desc);
3465 cmd_desc_dma_addr = hba->ucdl_dma_addr;
3467 for (i = 0; i < hba->nutrs; i++) {
3468 /* Configure UTRD with command descriptor base address */
3469 cmd_desc_element_addr =
3470 (cmd_desc_dma_addr + (cmd_desc_size * i));
3471 utrdlp[i].command_desc_base_addr_lo =
3472 cpu_to_le32(lower_32_bits(cmd_desc_element_addr));
3473 utrdlp[i].command_desc_base_addr_hi =
3474 cpu_to_le32(upper_32_bits(cmd_desc_element_addr));
3476 /* Response upiu and prdt offset should be in double words */
3477 if (hba->quirks & UFSHCD_QUIRK_PRDT_BYTE_GRAN) {
3478 utrdlp[i].response_upiu_offset =
3479 cpu_to_le16(response_offset);
3480 utrdlp[i].prd_table_offset =
3481 cpu_to_le16(prdt_offset);
3482 utrdlp[i].response_upiu_length =
3483 cpu_to_le16(ALIGNED_UPIU_SIZE);
3485 utrdlp[i].response_upiu_offset =
3486 cpu_to_le16(response_offset >> 2);
3487 utrdlp[i].prd_table_offset =
3488 cpu_to_le16(prdt_offset >> 2);
3489 utrdlp[i].response_upiu_length =
3490 cpu_to_le16(ALIGNED_UPIU_SIZE >> 2);
3493 ufshcd_init_lrb(hba, &hba->lrb[i], i);
3498 * ufshcd_dme_link_startup - Notify Unipro to perform link startup
3499 * @hba: per adapter instance
3501 * UIC_CMD_DME_LINK_STARTUP command must be issued to Unipro layer,
3502 * in order to initialize the Unipro link startup procedure.
3503 * Once the Unipro links are up, the device connected to the controller
3506 * Returns 0 on success, non-zero value on failure
3508 static int ufshcd_dme_link_startup(struct ufs_hba *hba)
3510 struct uic_command uic_cmd = {0};
3513 uic_cmd.command = UIC_CMD_DME_LINK_STARTUP;
3515 ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
3518 "dme-link-startup: error code %d\n", ret);
3522 * ufshcd_dme_reset - UIC command for DME_RESET
3523 * @hba: per adapter instance
3525 * DME_RESET command is issued in order to reset UniPro stack.
3526 * This function now deals with cold reset.
3528 * Returns 0 on success, non-zero value on failure
3530 static int ufshcd_dme_reset(struct ufs_hba *hba)
3532 struct uic_command uic_cmd = {0};
3535 uic_cmd.command = UIC_CMD_DME_RESET;
3537 ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
3540 "dme-reset: error code %d\n", ret);
3546 * ufshcd_dme_enable - UIC command for DME_ENABLE
3547 * @hba: per adapter instance
3549 * DME_ENABLE command is issued in order to enable UniPro stack.
3551 * Returns 0 on success, non-zero value on failure
3553 static int ufshcd_dme_enable(struct ufs_hba *hba)
3555 struct uic_command uic_cmd = {0};
3558 uic_cmd.command = UIC_CMD_DME_ENABLE;
3560 ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
3563 "dme-reset: error code %d\n", ret);
3568 static inline void ufshcd_add_delay_before_dme_cmd(struct ufs_hba *hba)
3570 #define MIN_DELAY_BEFORE_DME_CMDS_US 1000
3571 unsigned long min_sleep_time_us;
3573 if (!(hba->quirks & UFSHCD_QUIRK_DELAY_BEFORE_DME_CMDS))
3577 * last_dme_cmd_tstamp will be 0 only for 1st call to
3580 if (unlikely(!ktime_to_us(hba->last_dme_cmd_tstamp))) {
3581 min_sleep_time_us = MIN_DELAY_BEFORE_DME_CMDS_US;
3583 unsigned long delta =
3584 (unsigned long) ktime_to_us(
3585 ktime_sub(ktime_get(),
3586 hba->last_dme_cmd_tstamp));
3588 if (delta < MIN_DELAY_BEFORE_DME_CMDS_US)
3590 MIN_DELAY_BEFORE_DME_CMDS_US - delta;
3592 return; /* no more delay required */
3595 /* allow sleep for extra 50us if needed */
3596 usleep_range(min_sleep_time_us, min_sleep_time_us + 50);
3600 * ufshcd_dme_set_attr - UIC command for DME_SET, DME_PEER_SET
3601 * @hba: per adapter instance
3602 * @attr_sel: uic command argument1
3603 * @attr_set: attribute set type as uic command argument2
3604 * @mib_val: setting value as uic command argument3
3605 * @peer: indicate whether peer or local
3607 * Returns 0 on success, non-zero value on failure
3609 int ufshcd_dme_set_attr(struct ufs_hba *hba, u32 attr_sel,
3610 u8 attr_set, u32 mib_val, u8 peer)
3612 struct uic_command uic_cmd = {0};
3613 static const char *const action[] = {
3617 const char *set = action[!!peer];
3619 int retries = UFS_UIC_COMMAND_RETRIES;
3621 uic_cmd.command = peer ?
3622 UIC_CMD_DME_PEER_SET : UIC_CMD_DME_SET;
3623 uic_cmd.argument1 = attr_sel;
3624 uic_cmd.argument2 = UIC_ARG_ATTR_TYPE(attr_set);
3625 uic_cmd.argument3 = mib_val;
3628 /* for peer attributes we retry upon failure */
3629 ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
3631 dev_dbg(hba->dev, "%s: attr-id 0x%x val 0x%x error code %d\n",
3632 set, UIC_GET_ATTR_ID(attr_sel), mib_val, ret);
3633 } while (ret && peer && --retries);
3636 dev_err(hba->dev, "%s: attr-id 0x%x val 0x%x failed %d retries\n",
3637 set, UIC_GET_ATTR_ID(attr_sel), mib_val,
3638 UFS_UIC_COMMAND_RETRIES - retries);
3642 EXPORT_SYMBOL_GPL(ufshcd_dme_set_attr);
3645 * ufshcd_dme_get_attr - UIC command for DME_GET, DME_PEER_GET
3646 * @hba: per adapter instance
3647 * @attr_sel: uic command argument1
3648 * @mib_val: the value of the attribute as returned by the UIC command
3649 * @peer: indicate whether peer or local
3651 * Returns 0 on success, non-zero value on failure
3653 int ufshcd_dme_get_attr(struct ufs_hba *hba, u32 attr_sel,
3654 u32 *mib_val, u8 peer)
3656 struct uic_command uic_cmd = {0};
3657 static const char *const action[] = {
3661 const char *get = action[!!peer];
3663 int retries = UFS_UIC_COMMAND_RETRIES;
3664 struct ufs_pa_layer_attr orig_pwr_info;
3665 struct ufs_pa_layer_attr temp_pwr_info;
3666 bool pwr_mode_change = false;
3668 if (peer && (hba->quirks & UFSHCD_QUIRK_DME_PEER_ACCESS_AUTO_MODE)) {
3669 orig_pwr_info = hba->pwr_info;
3670 temp_pwr_info = orig_pwr_info;
3672 if (orig_pwr_info.pwr_tx == FAST_MODE ||
3673 orig_pwr_info.pwr_rx == FAST_MODE) {
3674 temp_pwr_info.pwr_tx = FASTAUTO_MODE;
3675 temp_pwr_info.pwr_rx = FASTAUTO_MODE;
3676 pwr_mode_change = true;
3677 } else if (orig_pwr_info.pwr_tx == SLOW_MODE ||
3678 orig_pwr_info.pwr_rx == SLOW_MODE) {
3679 temp_pwr_info.pwr_tx = SLOWAUTO_MODE;
3680 temp_pwr_info.pwr_rx = SLOWAUTO_MODE;
3681 pwr_mode_change = true;
3683 if (pwr_mode_change) {
3684 ret = ufshcd_change_power_mode(hba, &temp_pwr_info);
3690 uic_cmd.command = peer ?
3691 UIC_CMD_DME_PEER_GET : UIC_CMD_DME_GET;
3692 uic_cmd.argument1 = attr_sel;
3695 /* for peer attributes we retry upon failure */
3696 ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
3698 dev_dbg(hba->dev, "%s: attr-id 0x%x error code %d\n",
3699 get, UIC_GET_ATTR_ID(attr_sel), ret);
3700 } while (ret && peer && --retries);
3703 dev_err(hba->dev, "%s: attr-id 0x%x failed %d retries\n",
3704 get, UIC_GET_ATTR_ID(attr_sel),
3705 UFS_UIC_COMMAND_RETRIES - retries);
3707 if (mib_val && !ret)
3708 *mib_val = uic_cmd.argument3;
3710 if (peer && (hba->quirks & UFSHCD_QUIRK_DME_PEER_ACCESS_AUTO_MODE)
3712 ufshcd_change_power_mode(hba, &orig_pwr_info);
3716 EXPORT_SYMBOL_GPL(ufshcd_dme_get_attr);
3719 * ufshcd_uic_pwr_ctrl - executes UIC commands (which affects the link power
3720 * state) and waits for it to take effect.
3722 * @hba: per adapter instance
3723 * @cmd: UIC command to execute
3725 * DME operations like DME_SET(PA_PWRMODE), DME_HIBERNATE_ENTER &
3726 * DME_HIBERNATE_EXIT commands take some time to take its effect on both host
3727 * and device UniPro link and hence it's final completion would be indicated by
3728 * dedicated status bits in Interrupt Status register (UPMS, UHES, UHXS) in
3729 * addition to normal UIC command completion Status (UCCS). This function only
3730 * returns after the relevant status bits indicate the completion.
3732 * Returns 0 on success, non-zero value on failure
3734 static int ufshcd_uic_pwr_ctrl(struct ufs_hba *hba, struct uic_command *cmd)
3736 struct completion uic_async_done;
3737 unsigned long flags;
3740 bool reenable_intr = false;
3742 mutex_lock(&hba->uic_cmd_mutex);
3743 init_completion(&uic_async_done);
3744 ufshcd_add_delay_before_dme_cmd(hba);
3746 spin_lock_irqsave(hba->host->host_lock, flags);
3747 hba->uic_async_done = &uic_async_done;
3748 if (ufshcd_readl(hba, REG_INTERRUPT_ENABLE) & UIC_COMMAND_COMPL) {
3749 ufshcd_disable_intr(hba, UIC_COMMAND_COMPL);
3751 * Make sure UIC command completion interrupt is disabled before
3752 * issuing UIC command.
3755 reenable_intr = true;
3757 ret = __ufshcd_send_uic_cmd(hba, cmd, false);
3758 spin_unlock_irqrestore(hba->host->host_lock, flags);
3761 "pwr ctrl cmd 0x%x with mode 0x%x uic error %d\n",
3762 cmd->command, cmd->argument3, ret);
3766 if (!wait_for_completion_timeout(hba->uic_async_done,
3767 msecs_to_jiffies(UIC_CMD_TIMEOUT))) {
3769 "pwr ctrl cmd 0x%x with mode 0x%x completion timeout\n",
3770 cmd->command, cmd->argument3);
3775 status = ufshcd_get_upmcrs(hba);
3776 if (status != PWR_LOCAL) {
3778 "pwr ctrl cmd 0x%x failed, host upmcrs:0x%x\n",
3779 cmd->command, status);
3780 ret = (status != PWR_OK) ? status : -1;
3784 ufshcd_print_host_state(hba);
3785 ufshcd_print_pwr_info(hba);
3786 ufshcd_print_host_regs(hba);
3789 spin_lock_irqsave(hba->host->host_lock, flags);
3790 hba->active_uic_cmd = NULL;
3791 hba->uic_async_done = NULL;
3793 ufshcd_enable_intr(hba, UIC_COMMAND_COMPL);
3794 spin_unlock_irqrestore(hba->host->host_lock, flags);
3795 mutex_unlock(&hba->uic_cmd_mutex);
3801 * ufshcd_uic_change_pwr_mode - Perform the UIC power mode chage
3802 * using DME_SET primitives.
3803 * @hba: per adapter instance
3804 * @mode: powr mode value
3806 * Returns 0 on success, non-zero value on failure
3808 static int ufshcd_uic_change_pwr_mode(struct ufs_hba *hba, u8 mode)
3810 struct uic_command uic_cmd = {0};
3813 if (hba->quirks & UFSHCD_QUIRK_BROKEN_PA_RXHSUNTERMCAP) {
3814 ret = ufshcd_dme_set(hba,
3815 UIC_ARG_MIB_SEL(PA_RXHSUNTERMCAP, 0), 1);
3817 dev_err(hba->dev, "%s: failed to enable PA_RXHSUNTERMCAP ret %d\n",
3823 uic_cmd.command = UIC_CMD_DME_SET;
3824 uic_cmd.argument1 = UIC_ARG_MIB(PA_PWRMODE);
3825 uic_cmd.argument3 = mode;
3826 ufshcd_hold(hba, false);
3827 ret = ufshcd_uic_pwr_ctrl(hba, &uic_cmd);
3828 ufshcd_release(hba);
3834 int ufshcd_link_recovery(struct ufs_hba *hba)
3837 unsigned long flags;
3839 spin_lock_irqsave(hba->host->host_lock, flags);
3840 hba->ufshcd_state = UFSHCD_STATE_RESET;
3841 ufshcd_set_eh_in_progress(hba);
3842 spin_unlock_irqrestore(hba->host->host_lock, flags);
3844 /* Reset the attached device */
3845 ufshcd_vops_device_reset(hba);
3847 ret = ufshcd_host_reset_and_restore(hba);
3849 spin_lock_irqsave(hba->host->host_lock, flags);
3851 hba->ufshcd_state = UFSHCD_STATE_ERROR;
3852 ufshcd_clear_eh_in_progress(hba);
3853 spin_unlock_irqrestore(hba->host->host_lock, flags);
3856 dev_err(hba->dev, "%s: link recovery failed, err %d",
3861 EXPORT_SYMBOL_GPL(ufshcd_link_recovery);
3863 static int __ufshcd_uic_hibern8_enter(struct ufs_hba *hba)
3866 struct uic_command uic_cmd = {0};
3867 ktime_t start = ktime_get();
3869 ufshcd_vops_hibern8_notify(hba, UIC_CMD_DME_HIBER_ENTER, PRE_CHANGE);
3871 uic_cmd.command = UIC_CMD_DME_HIBER_ENTER;
3872 ret = ufshcd_uic_pwr_ctrl(hba, &uic_cmd);
3873 trace_ufshcd_profile_hibern8(dev_name(hba->dev), "enter",
3874 ktime_to_us(ktime_sub(ktime_get(), start)), ret);
3879 dev_err(hba->dev, "%s: hibern8 enter failed. ret = %d\n",
3883 * If link recovery fails then return error code returned from
3884 * ufshcd_link_recovery().
3885 * If link recovery succeeds then return -EAGAIN to attempt
3886 * hibern8 enter retry again.
3888 err = ufshcd_link_recovery(hba);
3890 dev_err(hba->dev, "%s: link recovery failed", __func__);
3896 ufshcd_vops_hibern8_notify(hba, UIC_CMD_DME_HIBER_ENTER,
3902 static int ufshcd_uic_hibern8_enter(struct ufs_hba *hba)
3904 int ret = 0, retries;
3906 for (retries = UIC_HIBERN8_ENTER_RETRIES; retries > 0; retries--) {
3907 ret = __ufshcd_uic_hibern8_enter(hba);
3915 int ufshcd_uic_hibern8_exit(struct ufs_hba *hba)
3917 struct uic_command uic_cmd = {0};
3919 ktime_t start = ktime_get();
3921 ufshcd_vops_hibern8_notify(hba, UIC_CMD_DME_HIBER_EXIT, PRE_CHANGE);
3923 uic_cmd.command = UIC_CMD_DME_HIBER_EXIT;
3924 ret = ufshcd_uic_pwr_ctrl(hba, &uic_cmd);
3925 trace_ufshcd_profile_hibern8(dev_name(hba->dev), "exit",
3926 ktime_to_us(ktime_sub(ktime_get(), start)), ret);
3929 dev_err(hba->dev, "%s: hibern8 exit failed. ret = %d\n",
3931 ret = ufshcd_link_recovery(hba);
3933 ufshcd_vops_hibern8_notify(hba, UIC_CMD_DME_HIBER_EXIT,
3935 hba->ufs_stats.last_hibern8_exit_tstamp = ktime_get();
3936 hba->ufs_stats.hibern8_exit_cnt++;
3941 EXPORT_SYMBOL_GPL(ufshcd_uic_hibern8_exit);
3943 void ufshcd_auto_hibern8_update(struct ufs_hba *hba, u32 ahit)
3945 unsigned long flags;
3946 bool update = false;
3948 if (!ufshcd_is_auto_hibern8_supported(hba))
3951 spin_lock_irqsave(hba->host->host_lock, flags);
3952 if (hba->ahit != ahit) {
3956 spin_unlock_irqrestore(hba->host->host_lock, flags);
3958 if (update && !pm_runtime_suspended(hba->dev)) {
3959 pm_runtime_get_sync(hba->dev);
3960 ufshcd_hold(hba, false);
3961 ufshcd_auto_hibern8_enable(hba);
3962 ufshcd_release(hba);
3963 pm_runtime_put(hba->dev);
3966 EXPORT_SYMBOL_GPL(ufshcd_auto_hibern8_update);
3968 void ufshcd_auto_hibern8_enable(struct ufs_hba *hba)
3970 unsigned long flags;
3972 if (!ufshcd_is_auto_hibern8_supported(hba) || !hba->ahit)
3975 spin_lock_irqsave(hba->host->host_lock, flags);
3976 ufshcd_writel(hba, hba->ahit, REG_AUTO_HIBERNATE_IDLE_TIMER);
3977 spin_unlock_irqrestore(hba->host->host_lock, flags);
3981 * ufshcd_init_pwr_info - setting the POR (power on reset)
3982 * values in hba power info
3983 * @hba: per-adapter instance
3985 static void ufshcd_init_pwr_info(struct ufs_hba *hba)
3987 hba->pwr_info.gear_rx = UFS_PWM_G1;
3988 hba->pwr_info.gear_tx = UFS_PWM_G1;
3989 hba->pwr_info.lane_rx = 1;
3990 hba->pwr_info.lane_tx = 1;
3991 hba->pwr_info.pwr_rx = SLOWAUTO_MODE;
3992 hba->pwr_info.pwr_tx = SLOWAUTO_MODE;
3993 hba->pwr_info.hs_rate = 0;
3997 * ufshcd_get_max_pwr_mode - reads the max power mode negotiated with device
3998 * @hba: per-adapter instance
4000 static int ufshcd_get_max_pwr_mode(struct ufs_hba *hba)
4002 struct ufs_pa_layer_attr *pwr_info = &hba->max_pwr_info.info;
4004 if (hba->max_pwr_info.is_valid)
4007 pwr_info->pwr_tx = FAST_MODE;
4008 pwr_info->pwr_rx = FAST_MODE;
4009 pwr_info->hs_rate = PA_HS_MODE_B;
4011 /* Get the connected lane count */
4012 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_CONNECTEDRXDATALANES),
4013 &pwr_info->lane_rx);
4014 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_CONNECTEDTXDATALANES),
4015 &pwr_info->lane_tx);
4017 if (!pwr_info->lane_rx || !pwr_info->lane_tx) {
4018 dev_err(hba->dev, "%s: invalid connected lanes value. rx=%d, tx=%d\n",
4026 * First, get the maximum gears of HS speed.
4027 * If a zero value, it means there is no HSGEAR capability.
4028 * Then, get the maximum gears of PWM speed.
4030 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_MAXRXHSGEAR), &pwr_info->gear_rx);
4031 if (!pwr_info->gear_rx) {
4032 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_MAXRXPWMGEAR),
4033 &pwr_info->gear_rx);
4034 if (!pwr_info->gear_rx) {
4035 dev_err(hba->dev, "%s: invalid max pwm rx gear read = %d\n",
4036 __func__, pwr_info->gear_rx);
4039 pwr_info->pwr_rx = SLOW_MODE;
4042 ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_MAXRXHSGEAR),
4043 &pwr_info->gear_tx);
4044 if (!pwr_info->gear_tx) {
4045 ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_MAXRXPWMGEAR),
4046 &pwr_info->gear_tx);
4047 if (!pwr_info->gear_tx) {
4048 dev_err(hba->dev, "%s: invalid max pwm tx gear read = %d\n",
4049 __func__, pwr_info->gear_tx);
4052 pwr_info->pwr_tx = SLOW_MODE;
4055 hba->max_pwr_info.is_valid = true;
4059 static int ufshcd_change_power_mode(struct ufs_hba *hba,
4060 struct ufs_pa_layer_attr *pwr_mode)
4064 /* if already configured to the requested pwr_mode */
4065 if (pwr_mode->gear_rx == hba->pwr_info.gear_rx &&
4066 pwr_mode->gear_tx == hba->pwr_info.gear_tx &&
4067 pwr_mode->lane_rx == hba->pwr_info.lane_rx &&
4068 pwr_mode->lane_tx == hba->pwr_info.lane_tx &&
4069 pwr_mode->pwr_rx == hba->pwr_info.pwr_rx &&
4070 pwr_mode->pwr_tx == hba->pwr_info.pwr_tx &&
4071 pwr_mode->hs_rate == hba->pwr_info.hs_rate) {
4072 dev_dbg(hba->dev, "%s: power already configured\n", __func__);
4077 * Configure attributes for power mode change with below.
4078 * - PA_RXGEAR, PA_ACTIVERXDATALANES, PA_RXTERMINATION,
4079 * - PA_TXGEAR, PA_ACTIVETXDATALANES, PA_TXTERMINATION,
4082 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_RXGEAR), pwr_mode->gear_rx);
4083 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_ACTIVERXDATALANES),
4085 if (pwr_mode->pwr_rx == FASTAUTO_MODE ||
4086 pwr_mode->pwr_rx == FAST_MODE)
4087 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_RXTERMINATION), TRUE);
4089 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_RXTERMINATION), FALSE);
4091 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TXGEAR), pwr_mode->gear_tx);
4092 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_ACTIVETXDATALANES),
4094 if (pwr_mode->pwr_tx == FASTAUTO_MODE ||
4095 pwr_mode->pwr_tx == FAST_MODE)
4096 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TXTERMINATION), TRUE);
4098 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TXTERMINATION), FALSE);
4100 if (pwr_mode->pwr_rx == FASTAUTO_MODE ||
4101 pwr_mode->pwr_tx == FASTAUTO_MODE ||
4102 pwr_mode->pwr_rx == FAST_MODE ||
4103 pwr_mode->pwr_tx == FAST_MODE)
4104 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_HSSERIES),
4107 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_PWRMODEUSERDATA0),
4108 DL_FC0ProtectionTimeOutVal_Default);
4109 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_PWRMODEUSERDATA1),
4110 DL_TC0ReplayTimeOutVal_Default);
4111 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_PWRMODEUSERDATA2),
4112 DL_AFC0ReqTimeOutVal_Default);
4113 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_PWRMODEUSERDATA3),
4114 DL_FC1ProtectionTimeOutVal_Default);
4115 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_PWRMODEUSERDATA4),
4116 DL_TC1ReplayTimeOutVal_Default);
4117 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_PWRMODEUSERDATA5),
4118 DL_AFC1ReqTimeOutVal_Default);
4120 ufshcd_dme_set(hba, UIC_ARG_MIB(DME_LocalFC0ProtectionTimeOutVal),
4121 DL_FC0ProtectionTimeOutVal_Default);
4122 ufshcd_dme_set(hba, UIC_ARG_MIB(DME_LocalTC0ReplayTimeOutVal),
4123 DL_TC0ReplayTimeOutVal_Default);
4124 ufshcd_dme_set(hba, UIC_ARG_MIB(DME_LocalAFC0ReqTimeOutVal),
4125 DL_AFC0ReqTimeOutVal_Default);
4127 ret = ufshcd_uic_change_pwr_mode(hba, pwr_mode->pwr_rx << 4
4128 | pwr_mode->pwr_tx);
4132 "%s: power mode change failed %d\n", __func__, ret);
4134 ufshcd_vops_pwr_change_notify(hba, POST_CHANGE, NULL,
4137 memcpy(&hba->pwr_info, pwr_mode,
4138 sizeof(struct ufs_pa_layer_attr));
4145 * ufshcd_config_pwr_mode - configure a new power mode
4146 * @hba: per-adapter instance
4147 * @desired_pwr_mode: desired power configuration
4149 int ufshcd_config_pwr_mode(struct ufs_hba *hba,
4150 struct ufs_pa_layer_attr *desired_pwr_mode)
4152 struct ufs_pa_layer_attr final_params = { 0 };
4155 ret = ufshcd_vops_pwr_change_notify(hba, PRE_CHANGE,
4156 desired_pwr_mode, &final_params);
4159 memcpy(&final_params, desired_pwr_mode, sizeof(final_params));
4161 ret = ufshcd_change_power_mode(hba, &final_params);
4165 EXPORT_SYMBOL_GPL(ufshcd_config_pwr_mode);
4168 * ufshcd_complete_dev_init() - checks device readiness
4169 * @hba: per-adapter instance
4171 * Set fDeviceInit flag and poll until device toggles it.
4173 static int ufshcd_complete_dev_init(struct ufs_hba *hba)
4177 bool flag_res = true;
4179 err = ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_SET_FLAG,
4180 QUERY_FLAG_IDN_FDEVICEINIT, 0, NULL);
4183 "%s setting fDeviceInit flag failed with error %d\n",
4188 /* poll for max. 1000 iterations for fDeviceInit flag to clear */
4189 for (i = 0; i < 1000 && !err && flag_res; i++)
4190 err = ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_READ_FLAG,
4191 QUERY_FLAG_IDN_FDEVICEINIT, 0, &flag_res);
4195 "%s reading fDeviceInit flag failed with error %d\n",
4199 "%s fDeviceInit was not cleared by the device\n",
4207 * ufshcd_make_hba_operational - Make UFS controller operational
4208 * @hba: per adapter instance
4210 * To bring UFS host controller to operational state,
4211 * 1. Enable required interrupts
4212 * 2. Configure interrupt aggregation
4213 * 3. Program UTRL and UTMRL base address
4214 * 4. Configure run-stop-registers
4216 * Returns 0 on success, non-zero value on failure
4218 int ufshcd_make_hba_operational(struct ufs_hba *hba)
4223 /* Enable required interrupts */
4224 ufshcd_enable_intr(hba, UFSHCD_ENABLE_INTRS);
4226 /* Configure interrupt aggregation */
4227 if (ufshcd_is_intr_aggr_allowed(hba))
4228 ufshcd_config_intr_aggr(hba, hba->nutrs - 1, INT_AGGR_DEF_TO);
4230 ufshcd_disable_intr_aggr(hba);
4232 /* Configure UTRL and UTMRL base address registers */
4233 ufshcd_writel(hba, lower_32_bits(hba->utrdl_dma_addr),
4234 REG_UTP_TRANSFER_REQ_LIST_BASE_L);
4235 ufshcd_writel(hba, upper_32_bits(hba->utrdl_dma_addr),
4236 REG_UTP_TRANSFER_REQ_LIST_BASE_H);
4237 ufshcd_writel(hba, lower_32_bits(hba->utmrdl_dma_addr),
4238 REG_UTP_TASK_REQ_LIST_BASE_L);
4239 ufshcd_writel(hba, upper_32_bits(hba->utmrdl_dma_addr),
4240 REG_UTP_TASK_REQ_LIST_BASE_H);
4243 * Make sure base address and interrupt setup are updated before
4244 * enabling the run/stop registers below.
4249 * UCRDY, UTMRLDY and UTRLRDY bits must be 1
4251 reg = ufshcd_readl(hba, REG_CONTROLLER_STATUS);
4252 if (!(ufshcd_get_lists_status(reg))) {
4253 ufshcd_enable_run_stop_reg(hba);
4256 "Host controller not ready to process requests");
4264 EXPORT_SYMBOL_GPL(ufshcd_make_hba_operational);
4267 * ufshcd_hba_stop - Send controller to reset state
4268 * @hba: per adapter instance
4270 static inline void ufshcd_hba_stop(struct ufs_hba *hba)
4272 unsigned long flags;
4276 * Obtain the host lock to prevent that the controller is disabled
4277 * while the UFS interrupt handler is active on another CPU.
4279 spin_lock_irqsave(hba->host->host_lock, flags);
4280 ufshcd_writel(hba, CONTROLLER_DISABLE, REG_CONTROLLER_ENABLE);
4281 spin_unlock_irqrestore(hba->host->host_lock, flags);
4283 err = ufshcd_wait_for_register(hba, REG_CONTROLLER_ENABLE,
4284 CONTROLLER_ENABLE, CONTROLLER_DISABLE,
4287 dev_err(hba->dev, "%s: Controller disable failed\n", __func__);
4291 * ufshcd_hba_execute_hce - initialize the controller
4292 * @hba: per adapter instance
4294 * The controller resets itself and controller firmware initialization
4295 * sequence kicks off. When controller is ready it will set
4296 * the Host Controller Enable bit to 1.
4298 * Returns 0 on success, non-zero value on failure
4300 static int ufshcd_hba_execute_hce(struct ufs_hba *hba)
4304 if (!ufshcd_is_hba_active(hba))
4305 /* change controller state to "reset state" */
4306 ufshcd_hba_stop(hba);
4308 /* UniPro link is disabled at this point */
4309 ufshcd_set_link_off(hba);
4311 ufshcd_vops_hce_enable_notify(hba, PRE_CHANGE);
4313 /* start controller initialization sequence */
4314 ufshcd_hba_start(hba);
4317 * To initialize a UFS host controller HCE bit must be set to 1.
4318 * During initialization the HCE bit value changes from 1->0->1.
4319 * When the host controller completes initialization sequence
4320 * it sets the value of HCE bit to 1. The same HCE bit is read back
4321 * to check if the controller has completed initialization sequence.
4322 * So without this delay the value HCE = 1, set in the previous
4323 * instruction might be read back.
4324 * This delay can be changed based on the controller.
4326 ufshcd_delay_us(hba->vps->hba_enable_delay_us, 100);
4328 /* wait for the host controller to complete initialization */
4330 while (ufshcd_is_hba_active(hba)) {
4335 "Controller enable failed\n");
4338 usleep_range(1000, 1100);
4341 /* enable UIC related interrupts */
4342 ufshcd_enable_intr(hba, UFSHCD_UIC_MASK);
4344 ufshcd_vops_hce_enable_notify(hba, POST_CHANGE);
4349 int ufshcd_hba_enable(struct ufs_hba *hba)
4353 if (hba->quirks & UFSHCI_QUIRK_BROKEN_HCE) {
4354 ufshcd_set_link_off(hba);
4355 ufshcd_vops_hce_enable_notify(hba, PRE_CHANGE);
4357 /* enable UIC related interrupts */
4358 ufshcd_enable_intr(hba, UFSHCD_UIC_MASK);
4359 ret = ufshcd_dme_reset(hba);
4361 ret = ufshcd_dme_enable(hba);
4363 ufshcd_vops_hce_enable_notify(hba, POST_CHANGE);
4366 "Host controller enable failed with non-hce\n");
4369 ret = ufshcd_hba_execute_hce(hba);
4374 EXPORT_SYMBOL_GPL(ufshcd_hba_enable);
4376 static int ufshcd_disable_tx_lcc(struct ufs_hba *hba, bool peer)
4378 int tx_lanes = 0, i, err = 0;
4381 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_CONNECTEDTXDATALANES),
4384 ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_CONNECTEDTXDATALANES),
4386 for (i = 0; i < tx_lanes; i++) {
4388 err = ufshcd_dme_set(hba,
4389 UIC_ARG_MIB_SEL(TX_LCC_ENABLE,
4390 UIC_ARG_MPHY_TX_GEN_SEL_INDEX(i)),
4393 err = ufshcd_dme_peer_set(hba,
4394 UIC_ARG_MIB_SEL(TX_LCC_ENABLE,
4395 UIC_ARG_MPHY_TX_GEN_SEL_INDEX(i)),
4398 dev_err(hba->dev, "%s: TX LCC Disable failed, peer = %d, lane = %d, err = %d",
4399 __func__, peer, i, err);
4407 static inline int ufshcd_disable_device_tx_lcc(struct ufs_hba *hba)
4409 return ufshcd_disable_tx_lcc(hba, true);
4412 void ufshcd_update_reg_hist(struct ufs_err_reg_hist *reg_hist,
4415 reg_hist->reg[reg_hist->pos] = reg;
4416 reg_hist->tstamp[reg_hist->pos] = ktime_get();
4417 reg_hist->pos = (reg_hist->pos + 1) % UFS_ERR_REG_HIST_LENGTH;
4419 EXPORT_SYMBOL_GPL(ufshcd_update_reg_hist);
4422 * ufshcd_link_startup - Initialize unipro link startup
4423 * @hba: per adapter instance
4425 * Returns 0 for success, non-zero in case of failure
4427 static int ufshcd_link_startup(struct ufs_hba *hba)
4430 int retries = DME_LINKSTARTUP_RETRIES;
4431 bool link_startup_again = false;
4434 * If UFS device isn't active then we will have to issue link startup
4435 * 2 times to make sure the device state move to active.
4437 if (!ufshcd_is_ufs_dev_active(hba))
4438 link_startup_again = true;
4442 ufshcd_vops_link_startup_notify(hba, PRE_CHANGE);
4444 ret = ufshcd_dme_link_startup(hba);
4446 /* check if device is detected by inter-connect layer */
4447 if (!ret && !ufshcd_is_device_present(hba)) {
4448 ufshcd_update_reg_hist(&hba->ufs_stats.link_startup_err,
4450 dev_err(hba->dev, "%s: Device not present\n", __func__);
4456 * DME link lost indication is only received when link is up,
4457 * but we can't be sure if the link is up until link startup
4458 * succeeds. So reset the local Uni-Pro and try again.
4460 if (ret && ufshcd_hba_enable(hba)) {
4461 ufshcd_update_reg_hist(&hba->ufs_stats.link_startup_err,
4465 } while (ret && retries--);
4468 /* failed to get the link up... retire */
4469 ufshcd_update_reg_hist(&hba->ufs_stats.link_startup_err,
4474 if (link_startup_again) {
4475 link_startup_again = false;
4476 retries = DME_LINKSTARTUP_RETRIES;
4480 /* Mark that link is up in PWM-G1, 1-lane, SLOW-AUTO mode */
4481 ufshcd_init_pwr_info(hba);
4482 ufshcd_print_pwr_info(hba);
4484 if (hba->quirks & UFSHCD_QUIRK_BROKEN_LCC) {
4485 ret = ufshcd_disable_device_tx_lcc(hba);
4490 /* Include any host controller configuration via UIC commands */
4491 ret = ufshcd_vops_link_startup_notify(hba, POST_CHANGE);
4495 ret = ufshcd_make_hba_operational(hba);
4498 dev_err(hba->dev, "link startup failed %d\n", ret);
4499 ufshcd_print_host_state(hba);
4500 ufshcd_print_pwr_info(hba);
4501 ufshcd_print_host_regs(hba);
4507 * ufshcd_verify_dev_init() - Verify device initialization
4508 * @hba: per-adapter instance
4510 * Send NOP OUT UPIU and wait for NOP IN response to check whether the
4511 * device Transport Protocol (UTP) layer is ready after a reset.
4512 * If the UTP layer at the device side is not initialized, it may
4513 * not respond with NOP IN UPIU within timeout of %NOP_OUT_TIMEOUT
4514 * and we retry sending NOP OUT for %NOP_OUT_RETRIES iterations.
4516 static int ufshcd_verify_dev_init(struct ufs_hba *hba)
4521 ufshcd_hold(hba, false);
4522 mutex_lock(&hba->dev_cmd.lock);
4523 for (retries = NOP_OUT_RETRIES; retries > 0; retries--) {
4524 err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_NOP,
4527 if (!err || err == -ETIMEDOUT)
4530 dev_dbg(hba->dev, "%s: error %d retrying\n", __func__, err);
4532 mutex_unlock(&hba->dev_cmd.lock);
4533 ufshcd_release(hba);
4536 dev_err(hba->dev, "%s: NOP OUT failed %d\n", __func__, err);
4541 * ufshcd_set_queue_depth - set lun queue depth
4542 * @sdev: pointer to SCSI device
4544 * Read bLUQueueDepth value and activate scsi tagged command
4545 * queueing. For WLUN, queue depth is set to 1. For best-effort
4546 * cases (bLUQueueDepth = 0) the queue depth is set to a maximum
4547 * value that host can queue.
4549 static void ufshcd_set_queue_depth(struct scsi_device *sdev)
4553 struct ufs_hba *hba;
4555 hba = shost_priv(sdev->host);
4557 lun_qdepth = hba->nutrs;
4558 ret = ufshcd_read_unit_desc_param(hba,
4559 ufshcd_scsi_to_upiu_lun(sdev->lun),
4560 UNIT_DESC_PARAM_LU_Q_DEPTH,
4562 sizeof(lun_qdepth));
4564 /* Some WLUN doesn't support unit descriptor */
4565 if (ret == -EOPNOTSUPP)
4567 else if (!lun_qdepth)
4568 /* eventually, we can figure out the real queue depth */
4569 lun_qdepth = hba->nutrs;
4571 lun_qdepth = min_t(int, lun_qdepth, hba->nutrs);
4573 dev_dbg(hba->dev, "%s: activate tcq with queue depth %d\n",
4574 __func__, lun_qdepth);
4575 scsi_change_queue_depth(sdev, lun_qdepth);
4579 * ufshcd_get_lu_wp - returns the "b_lu_write_protect" from UNIT DESCRIPTOR
4580 * @hba: per-adapter instance
4581 * @lun: UFS device lun id
4582 * @b_lu_write_protect: pointer to buffer to hold the LU's write protect info
4584 * Returns 0 in case of success and b_lu_write_protect status would be returned
4585 * @b_lu_write_protect parameter.
4586 * Returns -ENOTSUPP if reading b_lu_write_protect is not supported.
4587 * Returns -EINVAL in case of invalid parameters passed to this function.
4589 static int ufshcd_get_lu_wp(struct ufs_hba *hba,
4591 u8 *b_lu_write_protect)
4595 if (!b_lu_write_protect)
4598 * According to UFS device spec, RPMB LU can't be write
4599 * protected so skip reading bLUWriteProtect parameter for
4600 * it. For other W-LUs, UNIT DESCRIPTOR is not available.
4602 else if (lun >= hba->dev_info.max_lu_supported)
4605 ret = ufshcd_read_unit_desc_param(hba,
4607 UNIT_DESC_PARAM_LU_WR_PROTECT,
4609 sizeof(*b_lu_write_protect));
4614 * ufshcd_get_lu_power_on_wp_status - get LU's power on write protect
4616 * @hba: per-adapter instance
4617 * @sdev: pointer to SCSI device
4620 static inline void ufshcd_get_lu_power_on_wp_status(struct ufs_hba *hba,
4621 struct scsi_device *sdev)
4623 if (hba->dev_info.f_power_on_wp_en &&
4624 !hba->dev_info.is_lu_power_on_wp) {
4625 u8 b_lu_write_protect;
4627 if (!ufshcd_get_lu_wp(hba, ufshcd_scsi_to_upiu_lun(sdev->lun),
4628 &b_lu_write_protect) &&
4629 (b_lu_write_protect == UFS_LU_POWER_ON_WP))
4630 hba->dev_info.is_lu_power_on_wp = true;
4635 * ufshcd_slave_alloc - handle initial SCSI device configurations
4636 * @sdev: pointer to SCSI device
4640 static int ufshcd_slave_alloc(struct scsi_device *sdev)
4642 struct ufs_hba *hba;
4644 hba = shost_priv(sdev->host);
4646 /* Mode sense(6) is not supported by UFS, so use Mode sense(10) */
4647 sdev->use_10_for_ms = 1;
4649 /* DBD field should be set to 1 in mode sense(10) */
4650 sdev->set_dbd_for_ms = 1;
4652 /* allow SCSI layer to restart the device in case of errors */
4653 sdev->allow_restart = 1;
4655 /* REPORT SUPPORTED OPERATION CODES is not supported */
4656 sdev->no_report_opcodes = 1;
4658 /* WRITE_SAME command is not supported */
4659 sdev->no_write_same = 1;
4661 ufshcd_set_queue_depth(sdev);
4663 ufshcd_get_lu_power_on_wp_status(hba, sdev);
4669 * ufshcd_change_queue_depth - change queue depth
4670 * @sdev: pointer to SCSI device
4671 * @depth: required depth to set
4673 * Change queue depth and make sure the max. limits are not crossed.
4675 static int ufshcd_change_queue_depth(struct scsi_device *sdev, int depth)
4677 struct ufs_hba *hba = shost_priv(sdev->host);
4679 if (depth > hba->nutrs)
4681 return scsi_change_queue_depth(sdev, depth);
4685 * ufshcd_slave_configure - adjust SCSI device configurations
4686 * @sdev: pointer to SCSI device
4688 static int ufshcd_slave_configure(struct scsi_device *sdev)
4690 struct ufs_hba *hba = shost_priv(sdev->host);
4691 struct request_queue *q = sdev->request_queue;
4693 blk_queue_update_dma_pad(q, PRDT_DATA_BYTE_COUNT_PAD - 1);
4695 if (ufshcd_is_rpm_autosuspend_allowed(hba))
4696 sdev->rpm_autosuspend = 1;
4698 ufshcd_crypto_setup_rq_keyslot_manager(hba, q);
4704 * ufshcd_slave_destroy - remove SCSI device configurations
4705 * @sdev: pointer to SCSI device
4707 static void ufshcd_slave_destroy(struct scsi_device *sdev)
4709 struct ufs_hba *hba;
4711 hba = shost_priv(sdev->host);
4712 /* Drop the reference as it won't be needed anymore */
4713 if (ufshcd_scsi_to_upiu_lun(sdev->lun) == UFS_UPIU_UFS_DEVICE_WLUN) {
4714 unsigned long flags;
4716 spin_lock_irqsave(hba->host->host_lock, flags);
4717 hba->sdev_ufs_device = NULL;
4718 spin_unlock_irqrestore(hba->host->host_lock, flags);
4723 * ufshcd_scsi_cmd_status - Update SCSI command result based on SCSI status
4724 * @lrbp: pointer to local reference block of completed command
4725 * @scsi_status: SCSI command status
4727 * Returns value base on SCSI command status
4730 ufshcd_scsi_cmd_status(struct ufshcd_lrb *lrbp, int scsi_status)
4734 switch (scsi_status) {
4735 case SAM_STAT_CHECK_CONDITION:
4736 ufshcd_copy_sense_data(lrbp);
4739 result |= DID_OK << 16 |
4740 COMMAND_COMPLETE << 8 |
4743 case SAM_STAT_TASK_SET_FULL:
4745 case SAM_STAT_TASK_ABORTED:
4746 ufshcd_copy_sense_data(lrbp);
4747 result |= scsi_status;
4750 result |= DID_ERROR << 16;
4752 } /* end of switch */
4758 * ufshcd_transfer_rsp_status - Get overall status of the response
4759 * @hba: per adapter instance
4760 * @lrbp: pointer to local reference block of completed command
4762 * Returns result of the command to notify SCSI midlayer
4765 ufshcd_transfer_rsp_status(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
4771 /* overall command status of utrd */
4772 ocs = ufshcd_get_tr_ocs(lrbp);
4774 if (hba->quirks & UFSHCD_QUIRK_BROKEN_OCS_FATAL_ERROR) {
4775 if (be32_to_cpu(lrbp->ucd_rsp_ptr->header.dword_1) &
4776 MASK_RSP_UPIU_RESULT)
4782 result = ufshcd_get_req_rsp(lrbp->ucd_rsp_ptr);
4783 hba->ufs_stats.last_hibern8_exit_tstamp = ktime_set(0, 0);
4785 case UPIU_TRANSACTION_RESPONSE:
4787 * get the response UPIU result to extract
4788 * the SCSI command status
4790 result = ufshcd_get_rsp_upiu_result(lrbp->ucd_rsp_ptr);
4793 * get the result based on SCSI status response
4794 * to notify the SCSI midlayer of the command status
4796 scsi_status = result & MASK_SCSI_STATUS;
4797 result = ufshcd_scsi_cmd_status(lrbp, scsi_status);
4800 * Currently we are only supporting BKOPs exception
4801 * events hence we can ignore BKOPs exception event
4802 * during power management callbacks. BKOPs exception
4803 * event is not expected to be raised in runtime suspend
4804 * callback as it allows the urgent bkops.
4805 * During system suspend, we are anyway forcefully
4806 * disabling the bkops and if urgent bkops is needed
4807 * it will be enabled on system resume. Long term
4808 * solution could be to abort the system suspend if
4809 * UFS device needs urgent BKOPs.
4811 if (!hba->pm_op_in_progress &&
4812 ufshcd_is_exception_event(lrbp->ucd_rsp_ptr) &&
4813 schedule_work(&hba->eeh_work)) {
4815 * Prevent suspend once eeh_work is scheduled
4816 * to avoid deadlock between ufshcd_suspend
4817 * and exception event handler.
4819 pm_runtime_get_noresume(hba->dev);
4822 case UPIU_TRANSACTION_REJECT_UPIU:
4823 /* TODO: handle Reject UPIU Response */
4824 result = DID_ERROR << 16;
4826 "Reject UPIU not fully implemented\n");
4830 "Unexpected request response code = %x\n",
4832 result = DID_ERROR << 16;
4837 result |= DID_ABORT << 16;
4839 case OCS_INVALID_COMMAND_STATUS:
4840 result |= DID_REQUEUE << 16;
4842 case OCS_INVALID_CMD_TABLE_ATTR:
4843 case OCS_INVALID_PRDT_ATTR:
4844 case OCS_MISMATCH_DATA_BUF_SIZE:
4845 case OCS_MISMATCH_RESP_UPIU_SIZE:
4846 case OCS_PEER_COMM_FAILURE:
4847 case OCS_FATAL_ERROR:
4848 case OCS_DEVICE_FATAL_ERROR:
4849 case OCS_INVALID_CRYPTO_CONFIG:
4850 case OCS_GENERAL_CRYPTO_ERROR:
4852 result |= DID_ERROR << 16;
4854 "OCS error from controller = %x for tag %d\n",
4855 ocs, lrbp->task_tag);
4856 ufshcd_print_host_regs(hba);
4857 ufshcd_print_host_state(hba);
4859 } /* end of switch */
4861 if ((host_byte(result) != DID_OK) && !hba->silence_err_logs)
4862 ufshcd_print_trs(hba, 1 << lrbp->task_tag, true);
4867 * ufshcd_uic_cmd_compl - handle completion of uic command
4868 * @hba: per adapter instance
4869 * @intr_status: interrupt status generated by the controller
4872 * IRQ_HANDLED - If interrupt is valid
4873 * IRQ_NONE - If invalid interrupt
4875 static irqreturn_t ufshcd_uic_cmd_compl(struct ufs_hba *hba, u32 intr_status)
4877 irqreturn_t retval = IRQ_NONE;
4879 if ((intr_status & UIC_COMMAND_COMPL) && hba->active_uic_cmd) {
4880 hba->active_uic_cmd->argument2 |=
4881 ufshcd_get_uic_cmd_result(hba);
4882 hba->active_uic_cmd->argument3 =
4883 ufshcd_get_dme_attr_val(hba);
4884 complete(&hba->active_uic_cmd->done);
4885 retval = IRQ_HANDLED;
4888 if ((intr_status & UFSHCD_UIC_PWR_MASK) && hba->uic_async_done) {
4889 complete(hba->uic_async_done);
4890 retval = IRQ_HANDLED;
4893 if (retval == IRQ_HANDLED)
4894 ufshcd_add_uic_command_trace(hba, hba->active_uic_cmd,
4900 * __ufshcd_transfer_req_compl - handle SCSI and query command completion
4901 * @hba: per adapter instance
4902 * @completed_reqs: requests to complete
4904 static void __ufshcd_transfer_req_compl(struct ufs_hba *hba,
4905 unsigned long completed_reqs)
4907 struct ufshcd_lrb *lrbp;
4908 struct scsi_cmnd *cmd;
4912 for_each_set_bit(index, &completed_reqs, hba->nutrs) {
4913 lrbp = &hba->lrb[index];
4914 lrbp->compl_time_stamp = ktime_get();
4917 ufshcd_add_command_trace(hba, index, "complete");
4918 result = ufshcd_transfer_rsp_status(hba, lrbp);
4919 scsi_dma_unmap(cmd);
4920 cmd->result = result;
4921 /* Mark completed command as NULL in LRB */
4923 /* Do not touch lrbp after scsi done */
4924 cmd->scsi_done(cmd);
4925 __ufshcd_release(hba);
4926 } else if (lrbp->command_type == UTP_CMD_TYPE_DEV_MANAGE ||
4927 lrbp->command_type == UTP_CMD_TYPE_UFS_STORAGE) {
4928 if (hba->dev_cmd.complete) {
4929 ufshcd_add_command_trace(hba, index,
4931 complete(hba->dev_cmd.complete);
4934 if (ufshcd_is_clkscaling_supported(hba))
4935 hba->clk_scaling.active_reqs--;
4938 /* clear corresponding bits of completed commands */
4939 hba->outstanding_reqs ^= completed_reqs;
4941 ufshcd_clk_scaling_update_busy(hba);
4945 * ufshcd_transfer_req_compl - handle SCSI and query command completion
4946 * @hba: per adapter instance
4949 * IRQ_HANDLED - If interrupt is valid
4950 * IRQ_NONE - If invalid interrupt
4952 static irqreturn_t ufshcd_transfer_req_compl(struct ufs_hba *hba)
4954 unsigned long completed_reqs;
4957 /* Resetting interrupt aggregation counters first and reading the
4958 * DOOR_BELL afterward allows us to handle all the completed requests.
4959 * In order to prevent other interrupts starvation the DB is read once
4960 * after reset. The down side of this solution is the possibility of
4961 * false interrupt if device completes another request after resetting
4962 * aggregation and before reading the DB.
4964 if (ufshcd_is_intr_aggr_allowed(hba) &&
4965 !(hba->quirks & UFSHCI_QUIRK_SKIP_RESET_INTR_AGGR))
4966 ufshcd_reset_intr_aggr(hba);
4968 tr_doorbell = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
4969 completed_reqs = tr_doorbell ^ hba->outstanding_reqs;
4971 if (completed_reqs) {
4972 __ufshcd_transfer_req_compl(hba, completed_reqs);
4980 * ufshcd_disable_ee - disable exception event
4981 * @hba: per-adapter instance
4982 * @mask: exception event to disable
4984 * Disables exception event in the device so that the EVENT_ALERT
4987 * Returns zero on success, non-zero error value on failure.
4989 static int ufshcd_disable_ee(struct ufs_hba *hba, u16 mask)
4994 if (!(hba->ee_ctrl_mask & mask))
4997 val = hba->ee_ctrl_mask & ~mask;
4998 val &= MASK_EE_STATUS;
4999 err = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_WRITE_ATTR,
5000 QUERY_ATTR_IDN_EE_CONTROL, 0, 0, &val);
5002 hba->ee_ctrl_mask &= ~mask;
5008 * ufshcd_enable_ee - enable exception event
5009 * @hba: per-adapter instance
5010 * @mask: exception event to enable
5012 * Enable corresponding exception event in the device to allow
5013 * device to alert host in critical scenarios.
5015 * Returns zero on success, non-zero error value on failure.
5017 static int ufshcd_enable_ee(struct ufs_hba *hba, u16 mask)
5022 if (hba->ee_ctrl_mask & mask)
5025 val = hba->ee_ctrl_mask | mask;
5026 val &= MASK_EE_STATUS;
5027 err = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_WRITE_ATTR,
5028 QUERY_ATTR_IDN_EE_CONTROL, 0, 0, &val);
5030 hba->ee_ctrl_mask |= mask;
5036 * ufshcd_enable_auto_bkops - Allow device managed BKOPS
5037 * @hba: per-adapter instance
5039 * Allow device to manage background operations on its own. Enabling
5040 * this might lead to inconsistent latencies during normal data transfers
5041 * as the device is allowed to manage its own way of handling background
5044 * Returns zero on success, non-zero on failure.
5046 static int ufshcd_enable_auto_bkops(struct ufs_hba *hba)
5050 if (hba->auto_bkops_enabled)
5053 err = ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_SET_FLAG,
5054 QUERY_FLAG_IDN_BKOPS_EN, 0, NULL);
5056 dev_err(hba->dev, "%s: failed to enable bkops %d\n",
5061 hba->auto_bkops_enabled = true;
5062 trace_ufshcd_auto_bkops_state(dev_name(hba->dev), "Enabled");
5064 /* No need of URGENT_BKOPS exception from the device */
5065 err = ufshcd_disable_ee(hba, MASK_EE_URGENT_BKOPS);
5067 dev_err(hba->dev, "%s: failed to disable exception event %d\n",
5074 * ufshcd_disable_auto_bkops - block device in doing background operations
5075 * @hba: per-adapter instance
5077 * Disabling background operations improves command response latency but
5078 * has drawback of device moving into critical state where the device is
5079 * not-operable. Make sure to call ufshcd_enable_auto_bkops() whenever the
5080 * host is idle so that BKOPS are managed effectively without any negative
5083 * Returns zero on success, non-zero on failure.
5085 static int ufshcd_disable_auto_bkops(struct ufs_hba *hba)
5089 if (!hba->auto_bkops_enabled)
5093 * If host assisted BKOPs is to be enabled, make sure
5094 * urgent bkops exception is allowed.
5096 err = ufshcd_enable_ee(hba, MASK_EE_URGENT_BKOPS);
5098 dev_err(hba->dev, "%s: failed to enable exception event %d\n",
5103 err = ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_CLEAR_FLAG,
5104 QUERY_FLAG_IDN_BKOPS_EN, 0, NULL);
5106 dev_err(hba->dev, "%s: failed to disable bkops %d\n",
5108 ufshcd_disable_ee(hba, MASK_EE_URGENT_BKOPS);
5112 hba->auto_bkops_enabled = false;
5113 trace_ufshcd_auto_bkops_state(dev_name(hba->dev), "Disabled");
5114 hba->is_urgent_bkops_lvl_checked = false;
5120 * ufshcd_force_reset_auto_bkops - force reset auto bkops state
5121 * @hba: per adapter instance
5123 * After a device reset the device may toggle the BKOPS_EN flag
5124 * to default value. The s/w tracking variables should be updated
5125 * as well. This function would change the auto-bkops state based on
5126 * UFSHCD_CAP_KEEP_AUTO_BKOPS_ENABLED_EXCEPT_SUSPEND.
5128 static void ufshcd_force_reset_auto_bkops(struct ufs_hba *hba)
5130 if (ufshcd_keep_autobkops_enabled_except_suspend(hba)) {
5131 hba->auto_bkops_enabled = false;
5132 hba->ee_ctrl_mask |= MASK_EE_URGENT_BKOPS;
5133 ufshcd_enable_auto_bkops(hba);
5135 hba->auto_bkops_enabled = true;
5136 hba->ee_ctrl_mask &= ~MASK_EE_URGENT_BKOPS;
5137 ufshcd_disable_auto_bkops(hba);
5139 hba->urgent_bkops_lvl = BKOPS_STATUS_PERF_IMPACT;
5140 hba->is_urgent_bkops_lvl_checked = false;
5143 static inline int ufshcd_get_bkops_status(struct ufs_hba *hba, u32 *status)
5145 return ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
5146 QUERY_ATTR_IDN_BKOPS_STATUS, 0, 0, status);
5150 * ufshcd_bkops_ctrl - control the auto bkops based on current bkops status
5151 * @hba: per-adapter instance
5152 * @status: bkops_status value
5154 * Read the bkops_status from the UFS device and Enable fBackgroundOpsEn
5155 * flag in the device to permit background operations if the device
5156 * bkops_status is greater than or equal to "status" argument passed to
5157 * this function, disable otherwise.
5159 * Returns 0 for success, non-zero in case of failure.
5161 * NOTE: Caller of this function can check the "hba->auto_bkops_enabled" flag
5162 * to know whether auto bkops is enabled or disabled after this function
5163 * returns control to it.
5165 static int ufshcd_bkops_ctrl(struct ufs_hba *hba,
5166 enum bkops_status status)
5169 u32 curr_status = 0;
5171 err = ufshcd_get_bkops_status(hba, &curr_status);
5173 dev_err(hba->dev, "%s: failed to get BKOPS status %d\n",
5176 } else if (curr_status > BKOPS_STATUS_MAX) {
5177 dev_err(hba->dev, "%s: invalid BKOPS status %d\n",
5178 __func__, curr_status);
5183 if (curr_status >= status)
5184 err = ufshcd_enable_auto_bkops(hba);
5186 err = ufshcd_disable_auto_bkops(hba);
5192 * ufshcd_urgent_bkops - handle urgent bkops exception event
5193 * @hba: per-adapter instance
5195 * Enable fBackgroundOpsEn flag in the device to permit background
5198 * If BKOPs is enabled, this function returns 0, 1 if the bkops in not enabled
5199 * and negative error value for any other failure.
5201 static int ufshcd_urgent_bkops(struct ufs_hba *hba)
5203 return ufshcd_bkops_ctrl(hba, hba->urgent_bkops_lvl);
5206 static inline int ufshcd_get_ee_status(struct ufs_hba *hba, u32 *status)
5208 return ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
5209 QUERY_ATTR_IDN_EE_STATUS, 0, 0, status);
5212 static void ufshcd_bkops_exception_event_handler(struct ufs_hba *hba)
5215 u32 curr_status = 0;
5217 if (hba->is_urgent_bkops_lvl_checked)
5218 goto enable_auto_bkops;
5220 err = ufshcd_get_bkops_status(hba, &curr_status);
5222 dev_err(hba->dev, "%s: failed to get BKOPS status %d\n",
5228 * We are seeing that some devices are raising the urgent bkops
5229 * exception events even when BKOPS status doesn't indicate performace
5230 * impacted or critical. Handle these device by determining their urgent
5231 * bkops status at runtime.
5233 if (curr_status < BKOPS_STATUS_PERF_IMPACT) {
5234 dev_err(hba->dev, "%s: device raised urgent BKOPS exception for bkops status %d\n",
5235 __func__, curr_status);
5236 /* update the current status as the urgent bkops level */
5237 hba->urgent_bkops_lvl = curr_status;
5238 hba->is_urgent_bkops_lvl_checked = true;
5242 err = ufshcd_enable_auto_bkops(hba);
5245 dev_err(hba->dev, "%s: failed to handle urgent bkops %d\n",
5249 static int ufshcd_wb_ctrl(struct ufs_hba *hba, bool enable)
5253 enum query_opcode opcode;
5255 if (!ufshcd_is_wb_allowed(hba))
5258 if (!(enable ^ hba->wb_enabled))
5261 opcode = UPIU_QUERY_OPCODE_SET_FLAG;
5263 opcode = UPIU_QUERY_OPCODE_CLEAR_FLAG;
5265 index = ufshcd_wb_get_query_index(hba);
5266 ret = ufshcd_query_flag_retry(hba, opcode,
5267 QUERY_FLAG_IDN_WB_EN, index, NULL);
5269 dev_err(hba->dev, "%s write booster %s failed %d\n",
5270 __func__, enable ? "enable" : "disable", ret);
5274 hba->wb_enabled = enable;
5275 dev_dbg(hba->dev, "%s write booster %s %d\n",
5276 __func__, enable ? "enable" : "disable", ret);
5281 static int ufshcd_wb_toggle_flush_during_h8(struct ufs_hba *hba, bool set)
5287 val = UPIU_QUERY_OPCODE_SET_FLAG;
5289 val = UPIU_QUERY_OPCODE_CLEAR_FLAG;
5291 index = ufshcd_wb_get_query_index(hba);
5292 return ufshcd_query_flag_retry(hba, val,
5293 QUERY_FLAG_IDN_WB_BUFF_FLUSH_DURING_HIBERN8,
5297 static inline void ufshcd_wb_toggle_flush(struct ufs_hba *hba, bool enable)
5300 ufshcd_wb_buf_flush_enable(hba);
5302 ufshcd_wb_buf_flush_disable(hba);
5306 static int ufshcd_wb_buf_flush_enable(struct ufs_hba *hba)
5311 if (!ufshcd_is_wb_allowed(hba) || hba->wb_buf_flush_enabled)
5314 index = ufshcd_wb_get_query_index(hba);
5315 ret = ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_SET_FLAG,
5316 QUERY_FLAG_IDN_WB_BUFF_FLUSH_EN,
5319 dev_err(hba->dev, "%s WB - buf flush enable failed %d\n",
5322 hba->wb_buf_flush_enabled = true;
5324 dev_dbg(hba->dev, "WB - Flush enabled: %d\n", ret);
5328 static int ufshcd_wb_buf_flush_disable(struct ufs_hba *hba)
5333 if (!ufshcd_is_wb_allowed(hba) || !hba->wb_buf_flush_enabled)
5336 index = ufshcd_wb_get_query_index(hba);
5337 ret = ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_CLEAR_FLAG,
5338 QUERY_FLAG_IDN_WB_BUFF_FLUSH_EN,
5341 dev_warn(hba->dev, "%s: WB - buf flush disable failed %d\n",
5344 hba->wb_buf_flush_enabled = false;
5345 dev_dbg(hba->dev, "WB - Flush disabled: %d\n", ret);
5351 static bool ufshcd_wb_presrv_usrspc_keep_vcc_on(struct ufs_hba *hba,
5358 index = ufshcd_wb_get_query_index(hba);
5359 ret = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
5360 QUERY_ATTR_IDN_CURR_WB_BUFF_SIZE,
5361 index, 0, &cur_buf);
5363 dev_err(hba->dev, "%s dCurWriteBoosterBufferSize read failed %d\n",
5369 dev_info(hba->dev, "dCurWBBuf: %d WB disabled until free-space is available\n",
5373 /* Let it continue to flush when available buffer exceeds threshold */
5374 if (avail_buf < hba->vps->wb_flush_threshold)
5380 static bool ufshcd_wb_need_flush(struct ufs_hba *hba)
5386 if (!ufshcd_is_wb_allowed(hba))
5389 * The ufs device needs the vcc to be ON to flush.
5390 * With user-space reduction enabled, it's enough to enable flush
5391 * by checking only the available buffer. The threshold
5392 * defined here is > 90% full.
5393 * With user-space preserved enabled, the current-buffer
5394 * should be checked too because the wb buffer size can reduce
5395 * when disk tends to be full. This info is provided by current
5396 * buffer (dCurrentWriteBoosterBufferSize). There's no point in
5397 * keeping vcc on when current buffer is empty.
5399 index = ufshcd_wb_get_query_index(hba);
5400 ret = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
5401 QUERY_ATTR_IDN_AVAIL_WB_BUFF_SIZE,
5402 index, 0, &avail_buf);
5404 dev_warn(hba->dev, "%s dAvailableWriteBoosterBufferSize read failed %d\n",
5409 if (!hba->dev_info.b_presrv_uspc_en) {
5410 if (avail_buf <= UFS_WB_BUF_REMAIN_PERCENT(10))
5415 return ufshcd_wb_presrv_usrspc_keep_vcc_on(hba, avail_buf);
5418 static void ufshcd_rpm_dev_flush_recheck_work(struct work_struct *work)
5420 struct ufs_hba *hba = container_of(to_delayed_work(work),
5422 rpm_dev_flush_recheck_work);
5424 * To prevent unnecessary VCC power drain after device finishes
5425 * WriteBooster buffer flush or Auto BKOPs, force runtime resume
5426 * after a certain delay to recheck the threshold by next runtime
5429 pm_runtime_get_sync(hba->dev);
5430 pm_runtime_put_sync(hba->dev);
5434 * ufshcd_exception_event_handler - handle exceptions raised by device
5435 * @work: pointer to work data
5437 * Read bExceptionEventStatus attribute from the device and handle the
5438 * exception event accordingly.
5440 static void ufshcd_exception_event_handler(struct work_struct *work)
5442 struct ufs_hba *hba;
5445 hba = container_of(work, struct ufs_hba, eeh_work);
5447 pm_runtime_get_sync(hba->dev);
5448 ufshcd_scsi_block_requests(hba);
5449 err = ufshcd_get_ee_status(hba, &status);
5451 dev_err(hba->dev, "%s: failed to get exception status %d\n",
5456 status &= hba->ee_ctrl_mask;
5458 if (status & MASK_EE_URGENT_BKOPS)
5459 ufshcd_bkops_exception_event_handler(hba);
5462 ufshcd_scsi_unblock_requests(hba);
5464 * pm_runtime_get_noresume is called while scheduling
5465 * eeh_work to avoid suspend racing with exception work.
5466 * Hence decrement usage counter using pm_runtime_put_noidle
5467 * to allow suspend on completion of exception event handler.
5469 pm_runtime_put_noidle(hba->dev);
5470 pm_runtime_put(hba->dev);
5474 /* Complete requests that have door-bell cleared */
5475 static void ufshcd_complete_requests(struct ufs_hba *hba)
5477 ufshcd_transfer_req_compl(hba);
5478 ufshcd_tmc_handler(hba);
5482 * ufshcd_quirk_dl_nac_errors - This function checks if error handling is
5483 * to recover from the DL NAC errors or not.
5484 * @hba: per-adapter instance
5486 * Returns true if error handling is required, false otherwise
5488 static bool ufshcd_quirk_dl_nac_errors(struct ufs_hba *hba)
5490 unsigned long flags;
5491 bool err_handling = true;
5493 spin_lock_irqsave(hba->host->host_lock, flags);
5495 * UFS_DEVICE_QUIRK_RECOVERY_FROM_DL_NAC_ERRORS only workaround the
5496 * device fatal error and/or DL NAC & REPLAY timeout errors.
5498 if (hba->saved_err & (CONTROLLER_FATAL_ERROR | SYSTEM_BUS_FATAL_ERROR))
5501 if ((hba->saved_err & DEVICE_FATAL_ERROR) ||
5502 ((hba->saved_err & UIC_ERROR) &&
5503 (hba->saved_uic_err & UFSHCD_UIC_DL_TCx_REPLAY_ERROR)))
5506 if ((hba->saved_err & UIC_ERROR) &&
5507 (hba->saved_uic_err & UFSHCD_UIC_DL_NAC_RECEIVED_ERROR)) {
5510 * wait for 50ms to see if we can get any other errors or not.
5512 spin_unlock_irqrestore(hba->host->host_lock, flags);
5514 spin_lock_irqsave(hba->host->host_lock, flags);
5517 * now check if we have got any other severe errors other than
5520 if ((hba->saved_err & INT_FATAL_ERRORS) ||
5521 ((hba->saved_err & UIC_ERROR) &&
5522 (hba->saved_uic_err & ~UFSHCD_UIC_DL_NAC_RECEIVED_ERROR)))
5526 * As DL NAC is the only error received so far, send out NOP
5527 * command to confirm if link is still active or not.
5528 * - If we don't get any response then do error recovery.
5529 * - If we get response then clear the DL NAC error bit.
5532 spin_unlock_irqrestore(hba->host->host_lock, flags);
5533 err = ufshcd_verify_dev_init(hba);
5534 spin_lock_irqsave(hba->host->host_lock, flags);
5539 /* Link seems to be alive hence ignore the DL NAC errors */
5540 if (hba->saved_uic_err == UFSHCD_UIC_DL_NAC_RECEIVED_ERROR)
5541 hba->saved_err &= ~UIC_ERROR;
5542 /* clear NAC error */
5543 hba->saved_uic_err &= ~UFSHCD_UIC_DL_NAC_RECEIVED_ERROR;
5544 if (!hba->saved_uic_err) {
5545 err_handling = false;
5550 spin_unlock_irqrestore(hba->host->host_lock, flags);
5551 return err_handling;
5555 * ufshcd_err_handler - handle UFS errors that require s/w attention
5556 * @work: pointer to work structure
5558 static void ufshcd_err_handler(struct work_struct *work)
5560 struct ufs_hba *hba;
5561 unsigned long flags;
5566 bool needs_reset = false;
5568 hba = container_of(work, struct ufs_hba, eh_work);
5570 pm_runtime_get_sync(hba->dev);
5571 ufshcd_hold(hba, false);
5573 spin_lock_irqsave(hba->host->host_lock, flags);
5574 if (hba->ufshcd_state == UFSHCD_STATE_RESET)
5577 hba->ufshcd_state = UFSHCD_STATE_RESET;
5578 ufshcd_set_eh_in_progress(hba);
5580 /* Complete requests that have door-bell cleared by h/w */
5581 ufshcd_complete_requests(hba);
5583 if (hba->dev_quirks & UFS_DEVICE_QUIRK_RECOVERY_FROM_DL_NAC_ERRORS) {
5586 spin_unlock_irqrestore(hba->host->host_lock, flags);
5587 /* release the lock as ufshcd_quirk_dl_nac_errors() may sleep */
5588 ret = ufshcd_quirk_dl_nac_errors(hba);
5589 spin_lock_irqsave(hba->host->host_lock, flags);
5591 goto skip_err_handling;
5593 if ((hba->saved_err & INT_FATAL_ERRORS) ||
5594 (hba->saved_err & UFSHCD_UIC_HIBERN8_MASK) ||
5595 ((hba->saved_err & UIC_ERROR) &&
5596 (hba->saved_uic_err & (UFSHCD_UIC_DL_PA_INIT_ERROR |
5597 UFSHCD_UIC_DL_NAC_RECEIVED_ERROR |
5598 UFSHCD_UIC_DL_TCx_REPLAY_ERROR))))
5602 * if host reset is required then skip clearing the pending
5603 * transfers forcefully because they will get cleared during
5604 * host reset and restore
5607 goto skip_pending_xfer_clear;
5609 /* release lock as clear command might sleep */
5610 spin_unlock_irqrestore(hba->host->host_lock, flags);
5611 /* Clear pending transfer requests */
5612 for_each_set_bit(tag, &hba->outstanding_reqs, hba->nutrs) {
5613 if (ufshcd_clear_cmd(hba, tag)) {
5615 goto lock_skip_pending_xfer_clear;
5619 /* Clear pending task management requests */
5620 for_each_set_bit(tag, &hba->outstanding_tasks, hba->nutmrs) {
5621 if (ufshcd_clear_tm_cmd(hba, tag)) {
5623 goto lock_skip_pending_xfer_clear;
5627 lock_skip_pending_xfer_clear:
5628 spin_lock_irqsave(hba->host->host_lock, flags);
5630 /* Complete the requests that are cleared by s/w */
5631 ufshcd_complete_requests(hba);
5633 if (err_xfer || err_tm)
5636 skip_pending_xfer_clear:
5637 /* Fatal errors need reset */
5639 unsigned long max_doorbells = (1UL << hba->nutrs) - 1;
5642 * ufshcd_reset_and_restore() does the link reinitialization
5643 * which will need atleast one empty doorbell slot to send the
5644 * device management commands (NOP and query commands).
5645 * If there is no slot empty at this moment then free up last
5648 if (hba->outstanding_reqs == max_doorbells)
5649 __ufshcd_transfer_req_compl(hba,
5650 (1UL << (hba->nutrs - 1)));
5652 spin_unlock_irqrestore(hba->host->host_lock, flags);
5653 err = ufshcd_reset_and_restore(hba);
5654 spin_lock_irqsave(hba->host->host_lock, flags);
5656 dev_err(hba->dev, "%s: reset and restore failed\n",
5658 hba->ufshcd_state = UFSHCD_STATE_ERROR;
5661 * Inform scsi mid-layer that we did reset and allow to handle
5662 * Unit Attention properly.
5664 scsi_report_bus_reset(hba->host, 0);
5666 hba->saved_uic_err = 0;
5671 hba->ufshcd_state = UFSHCD_STATE_OPERATIONAL;
5672 if (hba->saved_err || hba->saved_uic_err)
5673 dev_err_ratelimited(hba->dev, "%s: exit: saved_err 0x%x saved_uic_err 0x%x",
5674 __func__, hba->saved_err, hba->saved_uic_err);
5677 ufshcd_clear_eh_in_progress(hba);
5680 spin_unlock_irqrestore(hba->host->host_lock, flags);
5681 ufshcd_scsi_unblock_requests(hba);
5682 ufshcd_release(hba);
5683 pm_runtime_put_sync(hba->dev);
5687 * ufshcd_update_uic_error - check and set fatal UIC error flags.
5688 * @hba: per-adapter instance
5691 * IRQ_HANDLED - If interrupt is valid
5692 * IRQ_NONE - If invalid interrupt
5694 static irqreturn_t ufshcd_update_uic_error(struct ufs_hba *hba)
5697 irqreturn_t retval = IRQ_NONE;
5699 /* PHY layer lane error */
5700 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_PHY_ADAPTER_LAYER);
5701 /* Ignore LINERESET indication, as this is not an error */
5702 if ((reg & UIC_PHY_ADAPTER_LAYER_ERROR) &&
5703 (reg & UIC_PHY_ADAPTER_LAYER_LANE_ERR_MASK)) {
5705 * To know whether this error is fatal or not, DB timeout
5706 * must be checked but this error is handled separately.
5708 dev_dbg(hba->dev, "%s: UIC Lane error reported\n", __func__);
5709 ufshcd_update_reg_hist(&hba->ufs_stats.pa_err, reg);
5710 retval |= IRQ_HANDLED;
5713 /* PA_INIT_ERROR is fatal and needs UIC reset */
5714 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_DATA_LINK_LAYER);
5715 if ((reg & UIC_DATA_LINK_LAYER_ERROR) &&
5716 (reg & UIC_DATA_LINK_LAYER_ERROR_CODE_MASK)) {
5717 ufshcd_update_reg_hist(&hba->ufs_stats.dl_err, reg);
5719 if (reg & UIC_DATA_LINK_LAYER_ERROR_PA_INIT)
5720 hba->uic_error |= UFSHCD_UIC_DL_PA_INIT_ERROR;
5721 else if (hba->dev_quirks &
5722 UFS_DEVICE_QUIRK_RECOVERY_FROM_DL_NAC_ERRORS) {
5723 if (reg & UIC_DATA_LINK_LAYER_ERROR_NAC_RECEIVED)
5725 UFSHCD_UIC_DL_NAC_RECEIVED_ERROR;
5726 else if (reg & UIC_DATA_LINK_LAYER_ERROR_TCx_REPLAY_TIMEOUT)
5727 hba->uic_error |= UFSHCD_UIC_DL_TCx_REPLAY_ERROR;
5729 retval |= IRQ_HANDLED;
5732 /* UIC NL/TL/DME errors needs software retry */
5733 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_NETWORK_LAYER);
5734 if ((reg & UIC_NETWORK_LAYER_ERROR) &&
5735 (reg & UIC_NETWORK_LAYER_ERROR_CODE_MASK)) {
5736 ufshcd_update_reg_hist(&hba->ufs_stats.nl_err, reg);
5737 hba->uic_error |= UFSHCD_UIC_NL_ERROR;
5738 retval |= IRQ_HANDLED;
5741 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_TRANSPORT_LAYER);
5742 if ((reg & UIC_TRANSPORT_LAYER_ERROR) &&
5743 (reg & UIC_TRANSPORT_LAYER_ERROR_CODE_MASK)) {
5744 ufshcd_update_reg_hist(&hba->ufs_stats.tl_err, reg);
5745 hba->uic_error |= UFSHCD_UIC_TL_ERROR;
5746 retval |= IRQ_HANDLED;
5749 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_DME);
5750 if ((reg & UIC_DME_ERROR) &&
5751 (reg & UIC_DME_ERROR_CODE_MASK)) {
5752 ufshcd_update_reg_hist(&hba->ufs_stats.dme_err, reg);
5753 hba->uic_error |= UFSHCD_UIC_DME_ERROR;
5754 retval |= IRQ_HANDLED;
5757 dev_dbg(hba->dev, "%s: UIC error flags = 0x%08x\n",
5758 __func__, hba->uic_error);
5762 static bool ufshcd_is_auto_hibern8_error(struct ufs_hba *hba,
5765 if (!ufshcd_is_auto_hibern8_supported(hba) ||
5766 !ufshcd_is_auto_hibern8_enabled(hba))
5769 if (!(intr_mask & UFSHCD_UIC_HIBERN8_MASK))
5772 if (hba->active_uic_cmd &&
5773 (hba->active_uic_cmd->command == UIC_CMD_DME_HIBER_ENTER ||
5774 hba->active_uic_cmd->command == UIC_CMD_DME_HIBER_EXIT))
5781 * ufshcd_check_errors - Check for errors that need s/w attention
5782 * @hba: per-adapter instance
5785 * IRQ_HANDLED - If interrupt is valid
5786 * IRQ_NONE - If invalid interrupt
5788 static irqreturn_t ufshcd_check_errors(struct ufs_hba *hba)
5790 bool queue_eh_work = false;
5791 irqreturn_t retval = IRQ_NONE;
5793 if (hba->errors & INT_FATAL_ERRORS) {
5794 ufshcd_update_reg_hist(&hba->ufs_stats.fatal_err, hba->errors);
5795 queue_eh_work = true;
5798 if (hba->errors & UIC_ERROR) {
5800 retval = ufshcd_update_uic_error(hba);
5802 queue_eh_work = true;
5805 if (hba->errors & UFSHCD_UIC_HIBERN8_MASK) {
5807 "%s: Auto Hibern8 %s failed - status: 0x%08x, upmcrs: 0x%08x\n",
5808 __func__, (hba->errors & UIC_HIBERNATE_ENTER) ?
5810 hba->errors, ufshcd_get_upmcrs(hba));
5811 ufshcd_update_reg_hist(&hba->ufs_stats.auto_hibern8_err,
5813 queue_eh_work = true;
5816 if (queue_eh_work) {
5818 * update the transfer error masks to sticky bits, let's do this
5819 * irrespective of current ufshcd_state.
5821 hba->saved_err |= hba->errors;
5822 hba->saved_uic_err |= hba->uic_error;
5824 /* handle fatal errors only when link is functional */
5825 if (hba->ufshcd_state == UFSHCD_STATE_OPERATIONAL) {
5826 /* block commands from scsi mid-layer */
5827 ufshcd_scsi_block_requests(hba);
5829 hba->ufshcd_state = UFSHCD_STATE_EH_SCHEDULED;
5831 /* dump controller state before resetting */
5832 if (hba->saved_err & (INT_FATAL_ERRORS | UIC_ERROR)) {
5833 bool pr_prdt = !!(hba->saved_err &
5834 SYSTEM_BUS_FATAL_ERROR);
5836 dev_err(hba->dev, "%s: saved_err 0x%x saved_uic_err 0x%x\n",
5837 __func__, hba->saved_err,
5838 hba->saved_uic_err);
5840 ufshcd_print_host_regs(hba);
5841 ufshcd_print_pwr_info(hba);
5842 ufshcd_print_tmrs(hba, hba->outstanding_tasks);
5843 ufshcd_print_trs(hba, hba->outstanding_reqs,
5846 schedule_work(&hba->eh_work);
5848 retval |= IRQ_HANDLED;
5851 * if (!queue_eh_work) -
5852 * Other errors are either non-fatal where host recovers
5853 * itself without s/w intervention or errors that will be
5854 * handled by the SCSI core layer.
5860 struct ufs_hba *hba;
5861 unsigned long pending;
5865 static bool ufshcd_compl_tm(struct request *req, void *priv, bool reserved)
5867 struct ctm_info *const ci = priv;
5868 struct completion *c;
5870 WARN_ON_ONCE(reserved);
5871 if (test_bit(req->tag, &ci->pending))
5874 c = req->end_io_data;
5881 * ufshcd_tmc_handler - handle task management function completion
5882 * @hba: per adapter instance
5885 * IRQ_HANDLED - If interrupt is valid
5886 * IRQ_NONE - If invalid interrupt
5888 static irqreturn_t ufshcd_tmc_handler(struct ufs_hba *hba)
5890 struct request_queue *q = hba->tmf_queue;
5891 struct ctm_info ci = {
5893 .pending = ufshcd_readl(hba, REG_UTP_TASK_REQ_DOOR_BELL),
5896 blk_mq_tagset_busy_iter(q->tag_set, ufshcd_compl_tm, &ci);
5897 return ci.ncpl ? IRQ_HANDLED : IRQ_NONE;
5901 * ufshcd_sl_intr - Interrupt service routine
5902 * @hba: per adapter instance
5903 * @intr_status: contains interrupts generated by the controller
5906 * IRQ_HANDLED - If interrupt is valid
5907 * IRQ_NONE - If invalid interrupt
5909 static irqreturn_t ufshcd_sl_intr(struct ufs_hba *hba, u32 intr_status)
5911 irqreturn_t retval = IRQ_NONE;
5913 hba->errors = UFSHCD_ERROR_MASK & intr_status;
5915 if (ufshcd_is_auto_hibern8_error(hba, intr_status))
5916 hba->errors |= (UFSHCD_UIC_HIBERN8_MASK & intr_status);
5919 retval |= ufshcd_check_errors(hba);
5921 if (intr_status & UFSHCD_UIC_MASK)
5922 retval |= ufshcd_uic_cmd_compl(hba, intr_status);
5924 if (intr_status & UTP_TASK_REQ_COMPL)
5925 retval |= ufshcd_tmc_handler(hba);
5927 if (intr_status & UTP_TRANSFER_REQ_COMPL)
5928 retval |= ufshcd_transfer_req_compl(hba);
5934 * ufshcd_intr - Main interrupt service routine
5936 * @__hba: pointer to adapter instance
5939 * IRQ_HANDLED - If interrupt is valid
5940 * IRQ_NONE - If invalid interrupt
5942 static irqreturn_t ufshcd_intr(int irq, void *__hba)
5944 u32 intr_status, enabled_intr_status;
5945 irqreturn_t retval = IRQ_NONE;
5946 struct ufs_hba *hba = __hba;
5947 int retries = hba->nutrs;
5949 spin_lock(hba->host->host_lock);
5950 intr_status = ufshcd_readl(hba, REG_INTERRUPT_STATUS);
5953 * There could be max of hba->nutrs reqs in flight and in worst case
5954 * if the reqs get finished 1 by 1 after the interrupt status is
5955 * read, make sure we handle them by checking the interrupt status
5956 * again in a loop until we process all of the reqs before returning.
5959 enabled_intr_status =
5960 intr_status & ufshcd_readl(hba, REG_INTERRUPT_ENABLE);
5962 ufshcd_writel(hba, intr_status, REG_INTERRUPT_STATUS);
5963 if (enabled_intr_status)
5964 retval |= ufshcd_sl_intr(hba, enabled_intr_status);
5966 intr_status = ufshcd_readl(hba, REG_INTERRUPT_STATUS);
5967 } while (intr_status && --retries);
5969 if (retval == IRQ_NONE) {
5970 dev_err(hba->dev, "%s: Unhandled interrupt 0x%08x\n",
5971 __func__, intr_status);
5972 ufshcd_dump_regs(hba, 0, UFSHCI_REG_SPACE_SIZE, "host_regs: ");
5975 spin_unlock(hba->host->host_lock);
5979 static int ufshcd_clear_tm_cmd(struct ufs_hba *hba, int tag)
5982 u32 mask = 1 << tag;
5983 unsigned long flags;
5985 if (!test_bit(tag, &hba->outstanding_tasks))
5988 spin_lock_irqsave(hba->host->host_lock, flags);
5989 ufshcd_utmrl_clear(hba, tag);
5990 spin_unlock_irqrestore(hba->host->host_lock, flags);
5992 /* poll for max. 1 sec to clear door bell register by h/w */
5993 err = ufshcd_wait_for_register(hba,
5994 REG_UTP_TASK_REQ_DOOR_BELL,
5995 mask, 0, 1000, 1000);
6000 static int __ufshcd_issue_tm_cmd(struct ufs_hba *hba,
6001 struct utp_task_req_desc *treq, u8 tm_function)
6003 struct request_queue *q = hba->tmf_queue;
6004 struct Scsi_Host *host = hba->host;
6005 DECLARE_COMPLETION_ONSTACK(wait);
6006 struct request *req;
6007 unsigned long flags;
6008 int free_slot, task_tag, err;
6011 * Get free slot, sleep if slots are unavailable.
6012 * Even though we use wait_event() which sleeps indefinitely,
6013 * the maximum wait time is bounded by %TM_CMD_TIMEOUT.
6015 req = blk_get_request(q, REQ_OP_DRV_OUT, BLK_MQ_REQ_RESERVED);
6016 req->end_io_data = &wait;
6017 free_slot = req->tag;
6018 WARN_ON_ONCE(free_slot < 0 || free_slot >= hba->nutmrs);
6019 ufshcd_hold(hba, false);
6021 spin_lock_irqsave(host->host_lock, flags);
6022 task_tag = hba->nutrs + free_slot;
6024 treq->req_header.dword_0 |= cpu_to_be32(task_tag);
6026 memcpy(hba->utmrdl_base_addr + free_slot, treq, sizeof(*treq));
6027 ufshcd_vops_setup_task_mgmt(hba, free_slot, tm_function);
6029 /* send command to the controller */
6030 __set_bit(free_slot, &hba->outstanding_tasks);
6032 /* Make sure descriptors are ready before ringing the task doorbell */
6035 ufshcd_writel(hba, 1 << free_slot, REG_UTP_TASK_REQ_DOOR_BELL);
6036 /* Make sure that doorbell is committed immediately */
6039 spin_unlock_irqrestore(host->host_lock, flags);
6041 ufshcd_add_tm_upiu_trace(hba, task_tag, "tm_send");
6043 /* wait until the task management command is completed */
6044 err = wait_for_completion_io_timeout(&wait,
6045 msecs_to_jiffies(TM_CMD_TIMEOUT));
6048 * Make sure that ufshcd_compl_tm() does not trigger a
6051 req->end_io_data = NULL;
6052 ufshcd_add_tm_upiu_trace(hba, task_tag, "tm_complete_err");
6053 dev_err(hba->dev, "%s: task management cmd 0x%.2x timed-out\n",
6054 __func__, tm_function);
6055 if (ufshcd_clear_tm_cmd(hba, free_slot))
6056 dev_WARN(hba->dev, "%s: unable clear tm cmd (slot %d) after timeout\n",
6057 __func__, free_slot);
6061 memcpy(treq, hba->utmrdl_base_addr + free_slot, sizeof(*treq));
6063 ufshcd_add_tm_upiu_trace(hba, task_tag, "tm_complete");
6066 spin_lock_irqsave(hba->host->host_lock, flags);
6067 __clear_bit(free_slot, &hba->outstanding_tasks);
6068 spin_unlock_irqrestore(hba->host->host_lock, flags);
6070 blk_put_request(req);
6072 ufshcd_release(hba);
6077 * ufshcd_issue_tm_cmd - issues task management commands to controller
6078 * @hba: per adapter instance
6079 * @lun_id: LUN ID to which TM command is sent
6080 * @task_id: task ID to which the TM command is applicable
6081 * @tm_function: task management function opcode
6082 * @tm_response: task management service response return value
6084 * Returns non-zero value on error, zero on success.
6086 static int ufshcd_issue_tm_cmd(struct ufs_hba *hba, int lun_id, int task_id,
6087 u8 tm_function, u8 *tm_response)
6089 struct utp_task_req_desc treq = { { 0 }, };
6092 /* Configure task request descriptor */
6093 treq.header.dword_0 = cpu_to_le32(UTP_REQ_DESC_INT_CMD);
6094 treq.header.dword_2 = cpu_to_le32(OCS_INVALID_COMMAND_STATUS);
6096 /* Configure task request UPIU */
6097 treq.req_header.dword_0 = cpu_to_be32(lun_id << 8) |
6098 cpu_to_be32(UPIU_TRANSACTION_TASK_REQ << 24);
6099 treq.req_header.dword_1 = cpu_to_be32(tm_function << 16);
6102 * The host shall provide the same value for LUN field in the basic
6103 * header and for Input Parameter.
6105 treq.input_param1 = cpu_to_be32(lun_id);
6106 treq.input_param2 = cpu_to_be32(task_id);
6108 err = __ufshcd_issue_tm_cmd(hba, &treq, tm_function);
6109 if (err == -ETIMEDOUT)
6112 ocs_value = le32_to_cpu(treq.header.dword_2) & MASK_OCS;
6113 if (ocs_value != OCS_SUCCESS)
6114 dev_err(hba->dev, "%s: failed, ocs = 0x%x\n",
6115 __func__, ocs_value);
6116 else if (tm_response)
6117 *tm_response = be32_to_cpu(treq.output_param1) &
6118 MASK_TM_SERVICE_RESP;
6123 * ufshcd_issue_devman_upiu_cmd - API for sending "utrd" type requests
6124 * @hba: per-adapter instance
6125 * @req_upiu: upiu request
6126 * @rsp_upiu: upiu reply
6127 * @desc_buff: pointer to descriptor buffer, NULL if NA
6128 * @buff_len: descriptor size, 0 if NA
6129 * @cmd_type: specifies the type (NOP, Query...)
6130 * @desc_op: descriptor operation
6132 * Those type of requests uses UTP Transfer Request Descriptor - utrd.
6133 * Therefore, it "rides" the device management infrastructure: uses its tag and
6134 * tasks work queues.
6136 * Since there is only one available tag for device management commands,
6137 * the caller is expected to hold the hba->dev_cmd.lock mutex.
6139 static int ufshcd_issue_devman_upiu_cmd(struct ufs_hba *hba,
6140 struct utp_upiu_req *req_upiu,
6141 struct utp_upiu_req *rsp_upiu,
6142 u8 *desc_buff, int *buff_len,
6143 enum dev_cmd_type cmd_type,
6144 enum query_opcode desc_op)
6146 struct request_queue *q = hba->cmd_queue;
6147 struct request *req;
6148 struct ufshcd_lrb *lrbp;
6151 struct completion wait;
6152 unsigned long flags;
6155 down_read(&hba->clk_scaling_lock);
6157 req = blk_get_request(q, REQ_OP_DRV_OUT, 0);
6163 WARN_ON_ONCE(!ufshcd_valid_tag(hba, tag));
6165 init_completion(&wait);
6166 lrbp = &hba->lrb[tag];
6170 lrbp->sense_bufflen = 0;
6171 lrbp->sense_buffer = NULL;
6172 lrbp->task_tag = tag;
6174 lrbp->intr_cmd = true;
6175 ufshcd_prepare_lrbp_crypto(NULL, lrbp);
6176 hba->dev_cmd.type = cmd_type;
6178 switch (hba->ufs_version) {
6179 case UFSHCI_VERSION_10:
6180 case UFSHCI_VERSION_11:
6181 lrbp->command_type = UTP_CMD_TYPE_DEV_MANAGE;
6184 lrbp->command_type = UTP_CMD_TYPE_UFS_STORAGE;
6188 /* update the task tag in the request upiu */
6189 req_upiu->header.dword_0 |= cpu_to_be32(tag);
6191 ufshcd_prepare_req_desc_hdr(lrbp, &upiu_flags, DMA_NONE);
6193 /* just copy the upiu request as it is */
6194 memcpy(lrbp->ucd_req_ptr, req_upiu, sizeof(*lrbp->ucd_req_ptr));
6195 if (desc_buff && desc_op == UPIU_QUERY_OPCODE_WRITE_DESC) {
6196 /* The Data Segment Area is optional depending upon the query
6197 * function value. for WRITE DESCRIPTOR, the data segment
6198 * follows right after the tsf.
6200 memcpy(lrbp->ucd_req_ptr + 1, desc_buff, *buff_len);
6204 memset(lrbp->ucd_rsp_ptr, 0, sizeof(struct utp_upiu_rsp));
6206 hba->dev_cmd.complete = &wait;
6208 /* Make sure descriptors are ready before ringing the doorbell */
6210 spin_lock_irqsave(hba->host->host_lock, flags);
6211 ufshcd_send_command(hba, tag);
6212 spin_unlock_irqrestore(hba->host->host_lock, flags);
6215 * ignore the returning value here - ufshcd_check_query_response is
6216 * bound to fail since dev_cmd.query and dev_cmd.type were left empty.
6217 * read the response directly ignoring all errors.
6219 ufshcd_wait_for_dev_cmd(hba, lrbp, QUERY_REQ_TIMEOUT);
6221 /* just copy the upiu response as it is */
6222 memcpy(rsp_upiu, lrbp->ucd_rsp_ptr, sizeof(*rsp_upiu));
6223 if (desc_buff && desc_op == UPIU_QUERY_OPCODE_READ_DESC) {
6224 u8 *descp = (u8 *)lrbp->ucd_rsp_ptr + sizeof(*rsp_upiu);
6225 u16 resp_len = be32_to_cpu(lrbp->ucd_rsp_ptr->header.dword_2) &
6226 MASK_QUERY_DATA_SEG_LEN;
6228 if (*buff_len >= resp_len) {
6229 memcpy(desc_buff, descp, resp_len);
6230 *buff_len = resp_len;
6233 "%s: rsp size %d is bigger than buffer size %d",
6234 __func__, resp_len, *buff_len);
6240 blk_put_request(req);
6242 up_read(&hba->clk_scaling_lock);
6247 * ufshcd_exec_raw_upiu_cmd - API function for sending raw upiu commands
6248 * @hba: per-adapter instance
6249 * @req_upiu: upiu request
6250 * @rsp_upiu: upiu reply - only 8 DW as we do not support scsi commands
6251 * @msgcode: message code, one of UPIU Transaction Codes Initiator to Target
6252 * @desc_buff: pointer to descriptor buffer, NULL if NA
6253 * @buff_len: descriptor size, 0 if NA
6254 * @desc_op: descriptor operation
6256 * Supports UTP Transfer requests (nop and query), and UTP Task
6257 * Management requests.
6258 * It is up to the caller to fill the upiu conent properly, as it will
6259 * be copied without any further input validations.
6261 int ufshcd_exec_raw_upiu_cmd(struct ufs_hba *hba,
6262 struct utp_upiu_req *req_upiu,
6263 struct utp_upiu_req *rsp_upiu,
6265 u8 *desc_buff, int *buff_len,
6266 enum query_opcode desc_op)
6269 enum dev_cmd_type cmd_type = DEV_CMD_TYPE_QUERY;
6270 struct utp_task_req_desc treq = { { 0 }, };
6272 u8 tm_f = be32_to_cpu(req_upiu->header.dword_1) >> 16 & MASK_TM_FUNC;
6275 case UPIU_TRANSACTION_NOP_OUT:
6276 cmd_type = DEV_CMD_TYPE_NOP;
6278 case UPIU_TRANSACTION_QUERY_REQ:
6279 ufshcd_hold(hba, false);
6280 mutex_lock(&hba->dev_cmd.lock);
6281 err = ufshcd_issue_devman_upiu_cmd(hba, req_upiu, rsp_upiu,
6282 desc_buff, buff_len,
6284 mutex_unlock(&hba->dev_cmd.lock);
6285 ufshcd_release(hba);
6288 case UPIU_TRANSACTION_TASK_REQ:
6289 treq.header.dword_0 = cpu_to_le32(UTP_REQ_DESC_INT_CMD);
6290 treq.header.dword_2 = cpu_to_le32(OCS_INVALID_COMMAND_STATUS);
6292 memcpy(&treq.req_header, req_upiu, sizeof(*req_upiu));
6294 err = __ufshcd_issue_tm_cmd(hba, &treq, tm_f);
6295 if (err == -ETIMEDOUT)
6298 ocs_value = le32_to_cpu(treq.header.dword_2) & MASK_OCS;
6299 if (ocs_value != OCS_SUCCESS) {
6300 dev_err(hba->dev, "%s: failed, ocs = 0x%x\n", __func__,
6305 memcpy(rsp_upiu, &treq.rsp_header, sizeof(*rsp_upiu));
6318 * ufshcd_eh_device_reset_handler - device reset handler registered to
6320 * @cmd: SCSI command pointer
6322 * Returns SUCCESS/FAILED
6324 static int ufshcd_eh_device_reset_handler(struct scsi_cmnd *cmd)
6326 struct Scsi_Host *host;
6327 struct ufs_hba *hba;
6332 struct ufshcd_lrb *lrbp;
6333 unsigned long flags;
6335 host = cmd->device->host;
6336 hba = shost_priv(host);
6337 tag = cmd->request->tag;
6339 lrbp = &hba->lrb[tag];
6340 err = ufshcd_issue_tm_cmd(hba, lrbp->lun, 0, UFS_LOGICAL_RESET, &resp);
6341 if (err || resp != UPIU_TASK_MANAGEMENT_FUNC_COMPL) {
6347 /* clear the commands that were pending for corresponding LUN */
6348 for_each_set_bit(pos, &hba->outstanding_reqs, hba->nutrs) {
6349 if (hba->lrb[pos].lun == lrbp->lun) {
6350 err = ufshcd_clear_cmd(hba, pos);
6355 spin_lock_irqsave(host->host_lock, flags);
6356 ufshcd_transfer_req_compl(hba);
6357 spin_unlock_irqrestore(host->host_lock, flags);
6360 hba->req_abort_count = 0;
6361 ufshcd_update_reg_hist(&hba->ufs_stats.dev_reset, (u32)err);
6365 dev_err(hba->dev, "%s: failed with err %d\n", __func__, err);
6371 static void ufshcd_set_req_abort_skip(struct ufs_hba *hba, unsigned long bitmap)
6373 struct ufshcd_lrb *lrbp;
6376 for_each_set_bit(tag, &bitmap, hba->nutrs) {
6377 lrbp = &hba->lrb[tag];
6378 lrbp->req_abort_skip = true;
6383 * ufshcd_abort - abort a specific command
6384 * @cmd: SCSI command pointer
6386 * Abort the pending command in device by sending UFS_ABORT_TASK task management
6387 * command, and in host controller by clearing the door-bell register. There can
6388 * be race between controller sending the command to the device while abort is
6389 * issued. To avoid that, first issue UFS_QUERY_TASK to check if the command is
6390 * really issued and then try to abort it.
6392 * Returns SUCCESS/FAILED
6394 static int ufshcd_abort(struct scsi_cmnd *cmd)
6396 struct Scsi_Host *host;
6397 struct ufs_hba *hba;
6398 unsigned long flags;
6403 struct ufshcd_lrb *lrbp;
6406 host = cmd->device->host;
6407 hba = shost_priv(host);
6408 tag = cmd->request->tag;
6409 lrbp = &hba->lrb[tag];
6410 if (!ufshcd_valid_tag(hba, tag)) {
6412 "%s: invalid command tag %d: cmd=0x%p, cmd->request=0x%p",
6413 __func__, tag, cmd, cmd->request);
6418 * Task abort to the device W-LUN is illegal. When this command
6419 * will fail, due to spec violation, scsi err handling next step
6420 * will be to send LU reset which, again, is a spec violation.
6421 * To avoid these unnecessary/illegal step we skip to the last error
6422 * handling stage: reset and restore.
6424 if (lrbp->lun == UFS_UPIU_UFS_DEVICE_WLUN)
6425 return ufshcd_eh_host_reset_handler(cmd);
6427 ufshcd_hold(hba, false);
6428 reg = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
6429 /* If command is already aborted/completed, return SUCCESS */
6430 if (!(test_bit(tag, &hba->outstanding_reqs))) {
6432 "%s: cmd at tag %d already completed, outstanding=0x%lx, doorbell=0x%x\n",
6433 __func__, tag, hba->outstanding_reqs, reg);
6437 if (!(reg & (1 << tag))) {
6439 "%s: cmd was completed, but without a notifying intr, tag = %d",
6443 /* Print Transfer Request of aborted task */
6444 dev_err(hba->dev, "%s: Device abort task at tag %d\n", __func__, tag);
6447 * Print detailed info about aborted request.
6448 * As more than one request might get aborted at the same time,
6449 * print full information only for the first aborted request in order
6450 * to reduce repeated printouts. For other aborted requests only print
6453 scsi_print_command(hba->lrb[tag].cmd);
6454 if (!hba->req_abort_count) {
6455 ufshcd_update_reg_hist(&hba->ufs_stats.task_abort, 0);
6456 ufshcd_print_host_regs(hba);
6457 ufshcd_print_host_state(hba);
6458 ufshcd_print_pwr_info(hba);
6459 ufshcd_print_trs(hba, 1 << tag, true);
6461 ufshcd_print_trs(hba, 1 << tag, false);
6463 hba->req_abort_count++;
6465 /* Skip task abort in case previous aborts failed and report failure */
6466 if (lrbp->req_abort_skip) {
6471 for (poll_cnt = 100; poll_cnt; poll_cnt--) {
6472 err = ufshcd_issue_tm_cmd(hba, lrbp->lun, lrbp->task_tag,
6473 UFS_QUERY_TASK, &resp);
6474 if (!err && resp == UPIU_TASK_MANAGEMENT_FUNC_SUCCEEDED) {
6475 /* cmd pending in the device */
6476 dev_err(hba->dev, "%s: cmd pending in the device. tag = %d\n",
6479 } else if (!err && resp == UPIU_TASK_MANAGEMENT_FUNC_COMPL) {
6481 * cmd not pending in the device, check if it is
6484 dev_err(hba->dev, "%s: cmd at tag %d not pending in the device.\n",
6486 reg = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
6487 if (reg & (1 << tag)) {
6488 /* sleep for max. 200us to stabilize */
6489 usleep_range(100, 200);
6492 /* command completed already */
6493 dev_err(hba->dev, "%s: cmd at tag %d successfully cleared from DB.\n",
6498 "%s: no response from device. tag = %d, err %d\n",
6499 __func__, tag, err);
6501 err = resp; /* service response error */
6511 err = ufshcd_issue_tm_cmd(hba, lrbp->lun, lrbp->task_tag,
6512 UFS_ABORT_TASK, &resp);
6513 if (err || resp != UPIU_TASK_MANAGEMENT_FUNC_COMPL) {
6515 err = resp; /* service response error */
6516 dev_err(hba->dev, "%s: issued. tag = %d, err %d\n",
6517 __func__, tag, err);
6522 err = ufshcd_clear_cmd(hba, tag);
6524 dev_err(hba->dev, "%s: Failed clearing cmd at tag %d, err %d\n",
6525 __func__, tag, err);
6529 scsi_dma_unmap(cmd);
6531 spin_lock_irqsave(host->host_lock, flags);
6532 ufshcd_outstanding_req_clear(hba, tag);
6533 hba->lrb[tag].cmd = NULL;
6534 spin_unlock_irqrestore(host->host_lock, flags);
6540 dev_err(hba->dev, "%s: failed with err %d\n", __func__, err);
6541 ufshcd_set_req_abort_skip(hba, hba->outstanding_reqs);
6546 * This ufshcd_release() corresponds to the original scsi cmd that got
6547 * aborted here (as we won't get any IRQ for it).
6549 ufshcd_release(hba);
6554 * ufshcd_host_reset_and_restore - reset and restore host controller
6555 * @hba: per-adapter instance
6557 * Note that host controller reset may issue DME_RESET to
6558 * local and remote (device) Uni-Pro stack and the attributes
6559 * are reset to default state.
6561 * Returns zero on success, non-zero on failure
6563 static int ufshcd_host_reset_and_restore(struct ufs_hba *hba)
6566 unsigned long flags;
6569 * Stop the host controller and complete the requests
6572 ufshcd_hba_stop(hba);
6574 spin_lock_irqsave(hba->host->host_lock, flags);
6575 hba->silence_err_logs = true;
6576 ufshcd_complete_requests(hba);
6577 hba->silence_err_logs = false;
6578 spin_unlock_irqrestore(hba->host->host_lock, flags);
6580 /* scale up clocks to max frequency before full reinitialization */
6581 ufshcd_set_clk_freq(hba, true);
6583 err = ufshcd_hba_enable(hba);
6587 /* Establish the link again and restore the device */
6588 err = ufshcd_probe_hba(hba, false);
6590 if (!err && (hba->ufshcd_state != UFSHCD_STATE_OPERATIONAL))
6594 dev_err(hba->dev, "%s: Host init failed %d\n", __func__, err);
6595 ufshcd_update_reg_hist(&hba->ufs_stats.host_reset, (u32)err);
6600 * ufshcd_reset_and_restore - reset and re-initialize host/device
6601 * @hba: per-adapter instance
6603 * Reset and recover device, host and re-establish link. This
6604 * is helpful to recover the communication in fatal error conditions.
6606 * Returns zero on success, non-zero on failure
6608 static int ufshcd_reset_and_restore(struct ufs_hba *hba)
6611 int retries = MAX_HOST_RESET_RETRIES;
6614 /* Reset the attached device */
6615 ufshcd_vops_device_reset(hba);
6617 err = ufshcd_host_reset_and_restore(hba);
6618 } while (err && --retries);
6624 * ufshcd_eh_host_reset_handler - host reset handler registered to scsi layer
6625 * @cmd: SCSI command pointer
6627 * Returns SUCCESS/FAILED
6629 static int ufshcd_eh_host_reset_handler(struct scsi_cmnd *cmd)
6632 unsigned long flags;
6633 struct ufs_hba *hba;
6635 hba = shost_priv(cmd->device->host);
6637 ufshcd_hold(hba, false);
6639 * Check if there is any race with fatal error handling.
6640 * If so, wait for it to complete. Even though fatal error
6641 * handling does reset and restore in some cases, don't assume
6642 * anything out of it. We are just avoiding race here.
6645 spin_lock_irqsave(hba->host->host_lock, flags);
6646 if (!(work_pending(&hba->eh_work) ||
6647 hba->ufshcd_state == UFSHCD_STATE_RESET ||
6648 hba->ufshcd_state == UFSHCD_STATE_EH_SCHEDULED))
6650 spin_unlock_irqrestore(hba->host->host_lock, flags);
6651 dev_dbg(hba->dev, "%s: reset in progress\n", __func__);
6652 flush_work(&hba->eh_work);
6655 hba->ufshcd_state = UFSHCD_STATE_RESET;
6656 ufshcd_set_eh_in_progress(hba);
6657 spin_unlock_irqrestore(hba->host->host_lock, flags);
6659 err = ufshcd_reset_and_restore(hba);
6661 spin_lock_irqsave(hba->host->host_lock, flags);
6664 hba->ufshcd_state = UFSHCD_STATE_OPERATIONAL;
6667 hba->ufshcd_state = UFSHCD_STATE_ERROR;
6669 ufshcd_clear_eh_in_progress(hba);
6670 spin_unlock_irqrestore(hba->host->host_lock, flags);
6672 ufshcd_release(hba);
6677 * ufshcd_get_max_icc_level - calculate the ICC level
6678 * @sup_curr_uA: max. current supported by the regulator
6679 * @start_scan: row at the desc table to start scan from
6680 * @buff: power descriptor buffer
6682 * Returns calculated max ICC level for specific regulator
6684 static u32 ufshcd_get_max_icc_level(int sup_curr_uA, u32 start_scan, char *buff)
6691 for (i = start_scan; i >= 0; i--) {
6692 data = be16_to_cpup((__be16 *)&buff[2 * i]);
6693 unit = (data & ATTR_ICC_LVL_UNIT_MASK) >>
6694 ATTR_ICC_LVL_UNIT_OFFSET;
6695 curr_uA = data & ATTR_ICC_LVL_VALUE_MASK;
6697 case UFSHCD_NANO_AMP:
6698 curr_uA = curr_uA / 1000;
6700 case UFSHCD_MILI_AMP:
6701 curr_uA = curr_uA * 1000;
6704 curr_uA = curr_uA * 1000 * 1000;
6706 case UFSHCD_MICRO_AMP:
6710 if (sup_curr_uA >= curr_uA)
6715 pr_err("%s: Couldn't find valid icc_level = %d", __func__, i);
6722 * ufshcd_calc_icc_level - calculate the max ICC level
6723 * In case regulators are not initialized we'll return 0
6724 * @hba: per-adapter instance
6725 * @desc_buf: power descriptor buffer to extract ICC levels from.
6726 * @len: length of desc_buff
6728 * Returns calculated ICC level
6730 static u32 ufshcd_find_max_sup_active_icc_level(struct ufs_hba *hba,
6731 u8 *desc_buf, int len)
6735 if (!hba->vreg_info.vcc || !hba->vreg_info.vccq ||
6736 !hba->vreg_info.vccq2) {
6738 "%s: Regulator capability was not set, actvIccLevel=%d",
6739 __func__, icc_level);
6743 if (hba->vreg_info.vcc && hba->vreg_info.vcc->max_uA)
6744 icc_level = ufshcd_get_max_icc_level(
6745 hba->vreg_info.vcc->max_uA,
6746 POWER_DESC_MAX_ACTV_ICC_LVLS - 1,
6747 &desc_buf[PWR_DESC_ACTIVE_LVLS_VCC_0]);
6749 if (hba->vreg_info.vccq && hba->vreg_info.vccq->max_uA)
6750 icc_level = ufshcd_get_max_icc_level(
6751 hba->vreg_info.vccq->max_uA,
6753 &desc_buf[PWR_DESC_ACTIVE_LVLS_VCCQ_0]);
6755 if (hba->vreg_info.vccq2 && hba->vreg_info.vccq2->max_uA)
6756 icc_level = ufshcd_get_max_icc_level(
6757 hba->vreg_info.vccq2->max_uA,
6759 &desc_buf[PWR_DESC_ACTIVE_LVLS_VCCQ2_0]);
6764 static void ufshcd_set_active_icc_lvl(struct ufs_hba *hba)
6767 int buff_len = hba->desc_size[QUERY_DESC_IDN_POWER];
6771 desc_buf = kmalloc(buff_len, GFP_KERNEL);
6775 ret = ufshcd_read_desc_param(hba, QUERY_DESC_IDN_POWER, 0, 0,
6776 desc_buf, buff_len);
6779 "%s: Failed reading power descriptor.len = %d ret = %d",
6780 __func__, buff_len, ret);
6784 icc_level = ufshcd_find_max_sup_active_icc_level(hba, desc_buf,
6786 dev_dbg(hba->dev, "%s: setting icc_level 0x%x", __func__, icc_level);
6788 ret = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_WRITE_ATTR,
6789 QUERY_ATTR_IDN_ACTIVE_ICC_LVL, 0, 0, &icc_level);
6793 "%s: Failed configuring bActiveICCLevel = %d ret = %d",
6794 __func__, icc_level, ret);
6800 static inline void ufshcd_blk_pm_runtime_init(struct scsi_device *sdev)
6802 scsi_autopm_get_device(sdev);
6803 blk_pm_runtime_init(sdev->request_queue, &sdev->sdev_gendev);
6804 if (sdev->rpm_autosuspend)
6805 pm_runtime_set_autosuspend_delay(&sdev->sdev_gendev,
6806 RPM_AUTOSUSPEND_DELAY_MS);
6807 scsi_autopm_put_device(sdev);
6811 * ufshcd_scsi_add_wlus - Adds required W-LUs
6812 * @hba: per-adapter instance
6814 * UFS device specification requires the UFS devices to support 4 well known
6816 * "REPORT_LUNS" (address: 01h)
6817 * "UFS Device" (address: 50h)
6818 * "RPMB" (address: 44h)
6819 * "BOOT" (address: 30h)
6820 * UFS device's power management needs to be controlled by "POWER CONDITION"
6821 * field of SSU (START STOP UNIT) command. But this "power condition" field
6822 * will take effect only when its sent to "UFS device" well known logical unit
6823 * hence we require the scsi_device instance to represent this logical unit in
6824 * order for the UFS host driver to send the SSU command for power management.
6826 * We also require the scsi_device instance for "RPMB" (Replay Protected Memory
6827 * Block) LU so user space process can control this LU. User space may also
6828 * want to have access to BOOT LU.
6830 * This function adds scsi device instances for each of all well known LUs
6831 * (except "REPORT LUNS" LU).
6833 * Returns zero on success (all required W-LUs are added successfully),
6834 * non-zero error value on failure (if failed to add any of the required W-LU).
6836 static int ufshcd_scsi_add_wlus(struct ufs_hba *hba)
6839 struct scsi_device *sdev_rpmb;
6840 struct scsi_device *sdev_boot;
6842 hba->sdev_ufs_device = __scsi_add_device(hba->host, 0, 0,
6843 ufshcd_upiu_wlun_to_scsi_wlun(UFS_UPIU_UFS_DEVICE_WLUN), NULL);
6844 if (IS_ERR(hba->sdev_ufs_device)) {
6845 ret = PTR_ERR(hba->sdev_ufs_device);
6846 hba->sdev_ufs_device = NULL;
6849 ufshcd_blk_pm_runtime_init(hba->sdev_ufs_device);
6850 scsi_device_put(hba->sdev_ufs_device);
6852 sdev_rpmb = __scsi_add_device(hba->host, 0, 0,
6853 ufshcd_upiu_wlun_to_scsi_wlun(UFS_UPIU_RPMB_WLUN), NULL);
6854 if (IS_ERR(sdev_rpmb)) {
6855 ret = PTR_ERR(sdev_rpmb);
6856 goto remove_sdev_ufs_device;
6858 ufshcd_blk_pm_runtime_init(sdev_rpmb);
6859 scsi_device_put(sdev_rpmb);
6861 sdev_boot = __scsi_add_device(hba->host, 0, 0,
6862 ufshcd_upiu_wlun_to_scsi_wlun(UFS_UPIU_BOOT_WLUN), NULL);
6863 if (IS_ERR(sdev_boot)) {
6864 dev_err(hba->dev, "%s: BOOT WLUN not found\n", __func__);
6866 ufshcd_blk_pm_runtime_init(sdev_boot);
6867 scsi_device_put(sdev_boot);
6871 remove_sdev_ufs_device:
6872 scsi_remove_device(hba->sdev_ufs_device);
6877 static void ufshcd_wb_probe(struct ufs_hba *hba, u8 *desc_buf)
6879 struct ufs_dev_info *dev_info = &hba->dev_info;
6881 u32 d_lu_wb_buf_alloc;
6883 if (!ufshcd_is_wb_allowed(hba))
6886 * Probe WB only for UFS-2.2 and UFS-3.1 (and later) devices or
6887 * UFS devices with quirk UFS_DEVICE_QUIRK_SUPPORT_EXTENDED_FEATURES
6890 if (!(dev_info->wspecversion >= 0x310 ||
6891 dev_info->wspecversion == 0x220 ||
6892 (hba->dev_quirks & UFS_DEVICE_QUIRK_SUPPORT_EXTENDED_FEATURES)))
6895 if (hba->desc_size[QUERY_DESC_IDN_DEVICE] <
6896 DEVICE_DESC_PARAM_EXT_UFS_FEATURE_SUP + 4)
6899 dev_info->d_ext_ufs_feature_sup =
6900 get_unaligned_be32(desc_buf +
6901 DEVICE_DESC_PARAM_EXT_UFS_FEATURE_SUP);
6903 if (!(dev_info->d_ext_ufs_feature_sup & UFS_DEV_WRITE_BOOSTER_SUP))
6907 * WB may be supported but not configured while provisioning.
6908 * The spec says, in dedicated wb buffer mode,
6909 * a max of 1 lun would have wb buffer configured.
6910 * Now only shared buffer mode is supported.
6912 dev_info->b_wb_buffer_type =
6913 desc_buf[DEVICE_DESC_PARAM_WB_TYPE];
6915 dev_info->b_presrv_uspc_en =
6916 desc_buf[DEVICE_DESC_PARAM_WB_PRESRV_USRSPC_EN];
6918 if (dev_info->b_wb_buffer_type == WB_BUF_MODE_SHARED) {
6919 dev_info->d_wb_alloc_units =
6920 get_unaligned_be32(desc_buf +
6921 DEVICE_DESC_PARAM_WB_SHARED_ALLOC_UNITS);
6922 if (!dev_info->d_wb_alloc_units)
6925 for (lun = 0; lun < UFS_UPIU_MAX_WB_LUN_ID; lun++) {
6926 d_lu_wb_buf_alloc = 0;
6927 ufshcd_read_unit_desc_param(hba,
6929 UNIT_DESC_PARAM_WB_BUF_ALLOC_UNITS,
6930 (u8 *)&d_lu_wb_buf_alloc,
6931 sizeof(d_lu_wb_buf_alloc));
6932 if (d_lu_wb_buf_alloc) {
6933 dev_info->wb_dedicated_lu = lun;
6938 if (!d_lu_wb_buf_alloc)
6944 hba->caps &= ~UFSHCD_CAP_WB_EN;
6947 void ufshcd_fixup_dev_quirks(struct ufs_hba *hba, struct ufs_dev_fix *fixups)
6949 struct ufs_dev_fix *f;
6950 struct ufs_dev_info *dev_info = &hba->dev_info;
6955 for (f = fixups; f->quirk; f++) {
6956 if ((f->wmanufacturerid == dev_info->wmanufacturerid ||
6957 f->wmanufacturerid == UFS_ANY_VENDOR) &&
6958 ((dev_info->model &&
6959 STR_PRFX_EQUAL(f->model, dev_info->model)) ||
6960 !strcmp(f->model, UFS_ANY_MODEL)))
6961 hba->dev_quirks |= f->quirk;
6964 EXPORT_SYMBOL_GPL(ufshcd_fixup_dev_quirks);
6966 static void ufs_fixup_device_setup(struct ufs_hba *hba)
6968 /* fix by general quirk table */
6969 ufshcd_fixup_dev_quirks(hba, ufs_fixups);
6971 /* allow vendors to fix quirks */
6972 ufshcd_vops_fixup_dev_quirks(hba);
6975 static int ufs_get_device_desc(struct ufs_hba *hba)
6980 struct ufs_dev_info *dev_info = &hba->dev_info;
6982 desc_buf = kmalloc(QUERY_DESC_MAX_SIZE, GFP_KERNEL);
6988 err = ufshcd_read_desc_param(hba, QUERY_DESC_IDN_DEVICE, 0, 0, desc_buf,
6989 hba->desc_size[QUERY_DESC_IDN_DEVICE]);
6991 dev_err(hba->dev, "%s: Failed reading Device Desc. err = %d\n",
6997 * getting vendor (manufacturerID) and Bank Index in big endian
7000 dev_info->wmanufacturerid = desc_buf[DEVICE_DESC_PARAM_MANF_ID] << 8 |
7001 desc_buf[DEVICE_DESC_PARAM_MANF_ID + 1];
7003 /* getting Specification Version in big endian format */
7004 dev_info->wspecversion = desc_buf[DEVICE_DESC_PARAM_SPEC_VER] << 8 |
7005 desc_buf[DEVICE_DESC_PARAM_SPEC_VER + 1];
7007 model_index = desc_buf[DEVICE_DESC_PARAM_PRDCT_NAME];
7009 err = ufshcd_read_string_desc(hba, model_index,
7010 &dev_info->model, SD_ASCII_STD);
7012 dev_err(hba->dev, "%s: Failed reading Product Name. err = %d\n",
7017 ufs_fixup_device_setup(hba);
7019 ufshcd_wb_probe(hba, desc_buf);
7022 * ufshcd_read_string_desc returns size of the string
7023 * reset the error value
7032 static void ufs_put_device_desc(struct ufs_hba *hba)
7034 struct ufs_dev_info *dev_info = &hba->dev_info;
7036 kfree(dev_info->model);
7037 dev_info->model = NULL;
7041 * ufshcd_tune_pa_tactivate - Tunes PA_TActivate of local UniPro
7042 * @hba: per-adapter instance
7044 * PA_TActivate parameter can be tuned manually if UniPro version is less than
7045 * 1.61. PA_TActivate needs to be greater than or equal to peerM-PHY's
7046 * RX_MIN_ACTIVATETIME_CAPABILITY attribute. This optimal value can help reduce
7047 * the hibern8 exit latency.
7049 * Returns zero on success, non-zero error value on failure.
7051 static int ufshcd_tune_pa_tactivate(struct ufs_hba *hba)
7054 u32 peer_rx_min_activatetime = 0, tuned_pa_tactivate;
7056 ret = ufshcd_dme_peer_get(hba,
7058 RX_MIN_ACTIVATETIME_CAPABILITY,
7059 UIC_ARG_MPHY_RX_GEN_SEL_INDEX(0)),
7060 &peer_rx_min_activatetime);
7064 /* make sure proper unit conversion is applied */
7065 tuned_pa_tactivate =
7066 ((peer_rx_min_activatetime * RX_MIN_ACTIVATETIME_UNIT_US)
7067 / PA_TACTIVATE_TIME_UNIT_US);
7068 ret = ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TACTIVATE),
7069 tuned_pa_tactivate);
7076 * ufshcd_tune_pa_hibern8time - Tunes PA_Hibern8Time of local UniPro
7077 * @hba: per-adapter instance
7079 * PA_Hibern8Time parameter can be tuned manually if UniPro version is less than
7080 * 1.61. PA_Hibern8Time needs to be maximum of local M-PHY's
7081 * TX_HIBERN8TIME_CAPABILITY & peer M-PHY's RX_HIBERN8TIME_CAPABILITY.
7082 * This optimal value can help reduce the hibern8 exit latency.
7084 * Returns zero on success, non-zero error value on failure.
7086 static int ufshcd_tune_pa_hibern8time(struct ufs_hba *hba)
7089 u32 local_tx_hibern8_time_cap = 0, peer_rx_hibern8_time_cap = 0;
7090 u32 max_hibern8_time, tuned_pa_hibern8time;
7092 ret = ufshcd_dme_get(hba,
7093 UIC_ARG_MIB_SEL(TX_HIBERN8TIME_CAPABILITY,
7094 UIC_ARG_MPHY_TX_GEN_SEL_INDEX(0)),
7095 &local_tx_hibern8_time_cap);
7099 ret = ufshcd_dme_peer_get(hba,
7100 UIC_ARG_MIB_SEL(RX_HIBERN8TIME_CAPABILITY,
7101 UIC_ARG_MPHY_RX_GEN_SEL_INDEX(0)),
7102 &peer_rx_hibern8_time_cap);
7106 max_hibern8_time = max(local_tx_hibern8_time_cap,
7107 peer_rx_hibern8_time_cap);
7108 /* make sure proper unit conversion is applied */
7109 tuned_pa_hibern8time = ((max_hibern8_time * HIBERN8TIME_UNIT_US)
7110 / PA_HIBERN8_TIME_UNIT_US);
7111 ret = ufshcd_dme_set(hba, UIC_ARG_MIB(PA_HIBERN8TIME),
7112 tuned_pa_hibern8time);
7118 * ufshcd_quirk_tune_host_pa_tactivate - Ensures that host PA_TACTIVATE is
7119 * less than device PA_TACTIVATE time.
7120 * @hba: per-adapter instance
7122 * Some UFS devices require host PA_TACTIVATE to be lower than device
7123 * PA_TACTIVATE, we need to enable UFS_DEVICE_QUIRK_HOST_PA_TACTIVATE quirk
7126 * Returns zero on success, non-zero error value on failure.
7128 static int ufshcd_quirk_tune_host_pa_tactivate(struct ufs_hba *hba)
7131 u32 granularity, peer_granularity;
7132 u32 pa_tactivate, peer_pa_tactivate;
7133 u32 pa_tactivate_us, peer_pa_tactivate_us;
7134 u8 gran_to_us_table[] = {1, 4, 8, 16, 32, 100};
7136 ret = ufshcd_dme_get(hba, UIC_ARG_MIB(PA_GRANULARITY),
7141 ret = ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_GRANULARITY),
7146 if ((granularity < PA_GRANULARITY_MIN_VAL) ||
7147 (granularity > PA_GRANULARITY_MAX_VAL)) {
7148 dev_err(hba->dev, "%s: invalid host PA_GRANULARITY %d",
7149 __func__, granularity);
7153 if ((peer_granularity < PA_GRANULARITY_MIN_VAL) ||
7154 (peer_granularity > PA_GRANULARITY_MAX_VAL)) {
7155 dev_err(hba->dev, "%s: invalid device PA_GRANULARITY %d",
7156 __func__, peer_granularity);
7160 ret = ufshcd_dme_get(hba, UIC_ARG_MIB(PA_TACTIVATE), &pa_tactivate);
7164 ret = ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_TACTIVATE),
7165 &peer_pa_tactivate);
7169 pa_tactivate_us = pa_tactivate * gran_to_us_table[granularity - 1];
7170 peer_pa_tactivate_us = peer_pa_tactivate *
7171 gran_to_us_table[peer_granularity - 1];
7173 if (pa_tactivate_us > peer_pa_tactivate_us) {
7174 u32 new_peer_pa_tactivate;
7176 new_peer_pa_tactivate = pa_tactivate_us /
7177 gran_to_us_table[peer_granularity - 1];
7178 new_peer_pa_tactivate++;
7179 ret = ufshcd_dme_peer_set(hba, UIC_ARG_MIB(PA_TACTIVATE),
7180 new_peer_pa_tactivate);
7187 static void ufshcd_tune_unipro_params(struct ufs_hba *hba)
7189 if (ufshcd_is_unipro_pa_params_tuning_req(hba)) {
7190 ufshcd_tune_pa_tactivate(hba);
7191 ufshcd_tune_pa_hibern8time(hba);
7194 ufshcd_vops_apply_dev_quirks(hba);
7196 if (hba->dev_quirks & UFS_DEVICE_QUIRK_PA_TACTIVATE)
7197 /* set 1ms timeout for PA_TACTIVATE */
7198 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TACTIVATE), 10);
7200 if (hba->dev_quirks & UFS_DEVICE_QUIRK_HOST_PA_TACTIVATE)
7201 ufshcd_quirk_tune_host_pa_tactivate(hba);
7204 static void ufshcd_clear_dbg_ufs_stats(struct ufs_hba *hba)
7206 hba->ufs_stats.hibern8_exit_cnt = 0;
7207 hba->ufs_stats.last_hibern8_exit_tstamp = ktime_set(0, 0);
7208 hba->req_abort_count = 0;
7211 static int ufshcd_device_geo_params_init(struct ufs_hba *hba)
7217 buff_len = hba->desc_size[QUERY_DESC_IDN_GEOMETRY];
7218 desc_buf = kmalloc(buff_len, GFP_KERNEL);
7224 err = ufshcd_read_desc_param(hba, QUERY_DESC_IDN_GEOMETRY, 0, 0,
7225 desc_buf, buff_len);
7227 dev_err(hba->dev, "%s: Failed reading Geometry Desc. err = %d\n",
7232 if (desc_buf[GEOMETRY_DESC_PARAM_MAX_NUM_LUN] == 1)
7233 hba->dev_info.max_lu_supported = 32;
7234 else if (desc_buf[GEOMETRY_DESC_PARAM_MAX_NUM_LUN] == 0)
7235 hba->dev_info.max_lu_supported = 8;
7242 static struct ufs_ref_clk ufs_ref_clk_freqs[] = {
7243 {19200000, REF_CLK_FREQ_19_2_MHZ},
7244 {26000000, REF_CLK_FREQ_26_MHZ},
7245 {38400000, REF_CLK_FREQ_38_4_MHZ},
7246 {52000000, REF_CLK_FREQ_52_MHZ},
7247 {0, REF_CLK_FREQ_INVAL},
7250 static enum ufs_ref_clk_freq
7251 ufs_get_bref_clk_from_hz(unsigned long freq)
7255 for (i = 0; ufs_ref_clk_freqs[i].freq_hz; i++)
7256 if (ufs_ref_clk_freqs[i].freq_hz == freq)
7257 return ufs_ref_clk_freqs[i].val;
7259 return REF_CLK_FREQ_INVAL;
7262 void ufshcd_parse_dev_ref_clk_freq(struct ufs_hba *hba, struct clk *refclk)
7266 freq = clk_get_rate(refclk);
7268 hba->dev_ref_clk_freq =
7269 ufs_get_bref_clk_from_hz(freq);
7271 if (hba->dev_ref_clk_freq == REF_CLK_FREQ_INVAL)
7273 "invalid ref_clk setting = %ld\n", freq);
7276 static int ufshcd_set_dev_ref_clk(struct ufs_hba *hba)
7280 u32 freq = hba->dev_ref_clk_freq;
7282 err = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
7283 QUERY_ATTR_IDN_REF_CLK_FREQ, 0, 0, &ref_clk);
7286 dev_err(hba->dev, "failed reading bRefClkFreq. err = %d\n",
7291 if (ref_clk == freq)
7292 goto out; /* nothing to update */
7294 err = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_WRITE_ATTR,
7295 QUERY_ATTR_IDN_REF_CLK_FREQ, 0, 0, &freq);
7298 dev_err(hba->dev, "bRefClkFreq setting to %lu Hz failed\n",
7299 ufs_ref_clk_freqs[freq].freq_hz);
7303 dev_dbg(hba->dev, "bRefClkFreq setting to %lu Hz succeeded\n",
7304 ufs_ref_clk_freqs[freq].freq_hz);
7310 static int ufshcd_device_params_init(struct ufs_hba *hba)
7315 /* Init device descriptor sizes */
7316 for (i = 0; i < QUERY_DESC_IDN_MAX; i++)
7317 hba->desc_size[i] = QUERY_DESC_MAX_SIZE;
7319 /* Init UFS geometry descriptor related parameters */
7320 ret = ufshcd_device_geo_params_init(hba);
7324 /* Check and apply UFS device quirks */
7325 ret = ufs_get_device_desc(hba);
7327 dev_err(hba->dev, "%s: Failed getting device info. err = %d\n",
7332 ufshcd_get_ref_clk_gating_wait(hba);
7334 if (!ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_READ_FLAG,
7335 QUERY_FLAG_IDN_PWR_ON_WPE, 0, &flag))
7336 hba->dev_info.f_power_on_wp_en = flag;
7338 /* Probe maximum power mode co-supported by both UFS host and device */
7339 if (ufshcd_get_max_pwr_mode(hba))
7341 "%s: Failed getting max supported power mode\n",
7348 * ufshcd_add_lus - probe and add UFS logical units
7349 * @hba: per-adapter instance
7351 static int ufshcd_add_lus(struct ufs_hba *hba)
7355 /* Add required well known logical units to scsi mid layer */
7356 ret = ufshcd_scsi_add_wlus(hba);
7360 /* Initialize devfreq after UFS device is detected */
7361 if (ufshcd_is_clkscaling_supported(hba)) {
7362 memcpy(&hba->clk_scaling.saved_pwr_info.info,
7364 sizeof(struct ufs_pa_layer_attr));
7365 hba->clk_scaling.saved_pwr_info.is_valid = true;
7366 if (!hba->devfreq) {
7367 ret = ufshcd_devfreq_init(hba);
7372 hba->clk_scaling.is_allowed = true;
7376 scsi_scan_host(hba->host);
7377 pm_runtime_put_sync(hba->dev);
7384 * ufshcd_probe_hba - probe hba to detect device and initialize
7385 * @hba: per-adapter instance
7386 * @async: asynchronous execution or not
7388 * Execute link-startup and verify device initialization
7390 static int ufshcd_probe_hba(struct ufs_hba *hba, bool async)
7393 ktime_t start = ktime_get();
7395 ret = ufshcd_link_startup(hba);
7399 /* Debug counters initialization */
7400 ufshcd_clear_dbg_ufs_stats(hba);
7402 /* UniPro link is active now */
7403 ufshcd_set_link_active(hba);
7405 /* Verify device initialization by sending NOP OUT UPIU */
7406 ret = ufshcd_verify_dev_init(hba);
7410 /* Initiate UFS initialization, and waiting until completion */
7411 ret = ufshcd_complete_dev_init(hba);
7416 * Initialize UFS device parameters used by driver, these
7417 * parameters are associated with UFS descriptors.
7420 ret = ufshcd_device_params_init(hba);
7425 ufshcd_tune_unipro_params(hba);
7427 /* UFS device is also active now */
7428 ufshcd_set_ufs_dev_active(hba);
7429 ufshcd_force_reset_auto_bkops(hba);
7430 hba->wlun_dev_clr_ua = true;
7432 /* Gear up to HS gear if supported */
7433 if (hba->max_pwr_info.is_valid) {
7435 * Set the right value to bRefClkFreq before attempting to
7436 * switch to HS gears.
7438 if (hba->dev_ref_clk_freq != REF_CLK_FREQ_INVAL)
7439 ufshcd_set_dev_ref_clk(hba);
7440 ret = ufshcd_config_pwr_mode(hba, &hba->max_pwr_info.info);
7442 dev_err(hba->dev, "%s: Failed setting power mode, err = %d\n",
7446 ufshcd_print_pwr_info(hba);
7450 * bActiveICCLevel is volatile for UFS device (as per latest v2.1 spec)
7451 * and for removable UFS card as well, hence always set the parameter.
7452 * Note: Error handler may issue the device reset hence resetting
7453 * bActiveICCLevel as well so it is always safe to set this here.
7455 ufshcd_set_active_icc_lvl(hba);
7457 /* set the state as operational after switching to desired gear */
7458 hba->ufshcd_state = UFSHCD_STATE_OPERATIONAL;
7460 ufshcd_wb_config(hba);
7461 /* Enable Auto-Hibernate if configured */
7462 ufshcd_auto_hibern8_enable(hba);
7466 trace_ufshcd_init(dev_name(hba->dev), ret,
7467 ktime_to_us(ktime_sub(ktime_get(), start)),
7468 hba->curr_dev_pwr_mode, hba->uic_link_state);
7473 * ufshcd_async_scan - asynchronous execution for probing hba
7474 * @data: data pointer to pass to this function
7475 * @cookie: cookie data
7477 static void ufshcd_async_scan(void *data, async_cookie_t cookie)
7479 struct ufs_hba *hba = (struct ufs_hba *)data;
7482 /* Initialize hba, detect and initialize UFS device */
7483 ret = ufshcd_probe_hba(hba, true);
7487 /* Probe and add UFS logical units */
7488 ret = ufshcd_add_lus(hba);
7491 * If we failed to initialize the device or the device is not
7492 * present, turn off the power/clocks etc.
7495 pm_runtime_put_sync(hba->dev);
7496 ufshcd_exit_clk_scaling(hba);
7497 ufshcd_hba_exit(hba);
7501 static const struct attribute_group *ufshcd_driver_groups[] = {
7502 &ufs_sysfs_unit_descriptor_group,
7503 &ufs_sysfs_lun_attributes_group,
7507 static struct ufs_hba_variant_params ufs_hba_vps = {
7508 .hba_enable_delay_us = 1000,
7509 .wb_flush_threshold = UFS_WB_BUF_REMAIN_PERCENT(40),
7510 .devfreq_profile.polling_ms = 100,
7511 .devfreq_profile.target = ufshcd_devfreq_target,
7512 .devfreq_profile.get_dev_status = ufshcd_devfreq_get_dev_status,
7513 .ondemand_data.upthreshold = 70,
7514 .ondemand_data.downdifferential = 5,
7517 static struct scsi_host_template ufshcd_driver_template = {
7518 .module = THIS_MODULE,
7520 .proc_name = UFSHCD,
7521 .queuecommand = ufshcd_queuecommand,
7522 .slave_alloc = ufshcd_slave_alloc,
7523 .slave_configure = ufshcd_slave_configure,
7524 .slave_destroy = ufshcd_slave_destroy,
7525 .change_queue_depth = ufshcd_change_queue_depth,
7526 .eh_abort_handler = ufshcd_abort,
7527 .eh_device_reset_handler = ufshcd_eh_device_reset_handler,
7528 .eh_host_reset_handler = ufshcd_eh_host_reset_handler,
7530 .sg_tablesize = SG_ALL,
7531 .cmd_per_lun = UFSHCD_CMD_PER_LUN,
7532 .can_queue = UFSHCD_CAN_QUEUE,
7533 .max_segment_size = PRDT_DATA_BYTE_COUNT_MAX,
7534 .max_host_blocked = 1,
7535 .track_queue_depth = 1,
7536 .sdev_groups = ufshcd_driver_groups,
7537 .dma_boundary = PAGE_SIZE - 1,
7538 .rpm_autosuspend_delay = RPM_AUTOSUSPEND_DELAY_MS,
7541 static int ufshcd_config_vreg_load(struct device *dev, struct ufs_vreg *vreg,
7550 * "set_load" operation shall be required on those regulators
7551 * which specifically configured current limitation. Otherwise
7552 * zero max_uA may cause unexpected behavior when regulator is
7553 * enabled or set as high power mode.
7558 ret = regulator_set_load(vreg->reg, ua);
7560 dev_err(dev, "%s: %s set load (ua=%d) failed, err=%d\n",
7561 __func__, vreg->name, ua, ret);
7567 static inline int ufshcd_config_vreg_lpm(struct ufs_hba *hba,
7568 struct ufs_vreg *vreg)
7570 return ufshcd_config_vreg_load(hba->dev, vreg, UFS_VREG_LPM_LOAD_UA);
7573 static inline int ufshcd_config_vreg_hpm(struct ufs_hba *hba,
7574 struct ufs_vreg *vreg)
7579 return ufshcd_config_vreg_load(hba->dev, vreg, vreg->max_uA);
7582 static int ufshcd_config_vreg(struct device *dev,
7583 struct ufs_vreg *vreg, bool on)
7586 struct regulator *reg;
7588 int min_uV, uA_load;
7595 if (regulator_count_voltages(reg) > 0) {
7596 uA_load = on ? vreg->max_uA : 0;
7597 ret = ufshcd_config_vreg_load(dev, vreg, uA_load);
7601 if (vreg->min_uV && vreg->max_uV) {
7602 min_uV = on ? vreg->min_uV : 0;
7603 ret = regulator_set_voltage(reg, min_uV, vreg->max_uV);
7606 "%s: %s set voltage failed, err=%d\n",
7607 __func__, name, ret);
7616 static int ufshcd_enable_vreg(struct device *dev, struct ufs_vreg *vreg)
7620 if (!vreg || vreg->enabled)
7623 ret = ufshcd_config_vreg(dev, vreg, true);
7625 ret = regulator_enable(vreg->reg);
7628 vreg->enabled = true;
7630 dev_err(dev, "%s: %s enable failed, err=%d\n",
7631 __func__, vreg->name, ret);
7636 static int ufshcd_disable_vreg(struct device *dev, struct ufs_vreg *vreg)
7640 if (!vreg || !vreg->enabled)
7643 ret = regulator_disable(vreg->reg);
7646 /* ignore errors on applying disable config */
7647 ufshcd_config_vreg(dev, vreg, false);
7648 vreg->enabled = false;
7650 dev_err(dev, "%s: %s disable failed, err=%d\n",
7651 __func__, vreg->name, ret);
7657 static int ufshcd_setup_vreg(struct ufs_hba *hba, bool on)
7660 struct device *dev = hba->dev;
7661 struct ufs_vreg_info *info = &hba->vreg_info;
7663 ret = ufshcd_toggle_vreg(dev, info->vcc, on);
7667 ret = ufshcd_toggle_vreg(dev, info->vccq, on);
7671 ret = ufshcd_toggle_vreg(dev, info->vccq2, on);
7677 ufshcd_toggle_vreg(dev, info->vccq2, false);
7678 ufshcd_toggle_vreg(dev, info->vccq, false);
7679 ufshcd_toggle_vreg(dev, info->vcc, false);
7684 static int ufshcd_setup_hba_vreg(struct ufs_hba *hba, bool on)
7686 struct ufs_vreg_info *info = &hba->vreg_info;
7688 return ufshcd_toggle_vreg(hba->dev, info->vdd_hba, on);
7691 static int ufshcd_get_vreg(struct device *dev, struct ufs_vreg *vreg)
7698 vreg->reg = devm_regulator_get(dev, vreg->name);
7699 if (IS_ERR(vreg->reg)) {
7700 ret = PTR_ERR(vreg->reg);
7701 dev_err(dev, "%s: %s get failed, err=%d\n",
7702 __func__, vreg->name, ret);
7708 static int ufshcd_init_vreg(struct ufs_hba *hba)
7711 struct device *dev = hba->dev;
7712 struct ufs_vreg_info *info = &hba->vreg_info;
7714 ret = ufshcd_get_vreg(dev, info->vcc);
7718 ret = ufshcd_get_vreg(dev, info->vccq);
7722 ret = ufshcd_get_vreg(dev, info->vccq2);
7727 static int ufshcd_init_hba_vreg(struct ufs_hba *hba)
7729 struct ufs_vreg_info *info = &hba->vreg_info;
7732 return ufshcd_get_vreg(hba->dev, info->vdd_hba);
7737 static int __ufshcd_setup_clocks(struct ufs_hba *hba, bool on,
7741 struct ufs_clk_info *clki;
7742 struct list_head *head = &hba->clk_list_head;
7743 unsigned long flags;
7744 ktime_t start = ktime_get();
7745 bool clk_state_changed = false;
7747 if (list_empty(head))
7750 ret = ufshcd_vops_setup_clocks(hba, on, PRE_CHANGE);
7754 list_for_each_entry(clki, head, list) {
7755 if (!IS_ERR_OR_NULL(clki->clk)) {
7756 if (skip_ref_clk && !strcmp(clki->name, "ref_clk"))
7759 clk_state_changed = on ^ clki->enabled;
7760 if (on && !clki->enabled) {
7761 ret = clk_prepare_enable(clki->clk);
7763 dev_err(hba->dev, "%s: %s prepare enable failed, %d\n",
7764 __func__, clki->name, ret);
7767 } else if (!on && clki->enabled) {
7768 clk_disable_unprepare(clki->clk);
7771 dev_dbg(hba->dev, "%s: clk: %s %sabled\n", __func__,
7772 clki->name, on ? "en" : "dis");
7776 ret = ufshcd_vops_setup_clocks(hba, on, POST_CHANGE);
7782 list_for_each_entry(clki, head, list) {
7783 if (!IS_ERR_OR_NULL(clki->clk) && clki->enabled)
7784 clk_disable_unprepare(clki->clk);
7786 } else if (!ret && on) {
7787 spin_lock_irqsave(hba->host->host_lock, flags);
7788 hba->clk_gating.state = CLKS_ON;
7789 trace_ufshcd_clk_gating(dev_name(hba->dev),
7790 hba->clk_gating.state);
7791 spin_unlock_irqrestore(hba->host->host_lock, flags);
7794 if (clk_state_changed)
7795 trace_ufshcd_profile_clk_gating(dev_name(hba->dev),
7796 (on ? "on" : "off"),
7797 ktime_to_us(ktime_sub(ktime_get(), start)), ret);
7801 static int ufshcd_setup_clocks(struct ufs_hba *hba, bool on)
7803 return __ufshcd_setup_clocks(hba, on, false);
7806 static int ufshcd_init_clocks(struct ufs_hba *hba)
7809 struct ufs_clk_info *clki;
7810 struct device *dev = hba->dev;
7811 struct list_head *head = &hba->clk_list_head;
7813 if (list_empty(head))
7816 list_for_each_entry(clki, head, list) {
7820 clki->clk = devm_clk_get(dev, clki->name);
7821 if (IS_ERR(clki->clk)) {
7822 ret = PTR_ERR(clki->clk);
7823 dev_err(dev, "%s: %s clk get failed, %d\n",
7824 __func__, clki->name, ret);
7829 * Parse device ref clk freq as per device tree "ref_clk".
7830 * Default dev_ref_clk_freq is set to REF_CLK_FREQ_INVAL
7831 * in ufshcd_alloc_host().
7833 if (!strcmp(clki->name, "ref_clk"))
7834 ufshcd_parse_dev_ref_clk_freq(hba, clki->clk);
7836 if (clki->max_freq) {
7837 ret = clk_set_rate(clki->clk, clki->max_freq);
7839 dev_err(hba->dev, "%s: %s clk set rate(%dHz) failed, %d\n",
7840 __func__, clki->name,
7841 clki->max_freq, ret);
7844 clki->curr_freq = clki->max_freq;
7846 dev_dbg(dev, "%s: clk: %s, rate: %lu\n", __func__,
7847 clki->name, clk_get_rate(clki->clk));
7853 static int ufshcd_variant_hba_init(struct ufs_hba *hba)
7860 err = ufshcd_vops_init(hba);
7864 err = ufshcd_vops_setup_regulators(hba, true);
7871 ufshcd_vops_exit(hba);
7874 dev_err(hba->dev, "%s: variant %s init failed err %d\n",
7875 __func__, ufshcd_get_var_name(hba), err);
7879 static void ufshcd_variant_hba_exit(struct ufs_hba *hba)
7884 ufshcd_vops_setup_regulators(hba, false);
7886 ufshcd_vops_exit(hba);
7889 static int ufshcd_hba_init(struct ufs_hba *hba)
7894 * Handle host controller power separately from the UFS device power
7895 * rails as it will help controlling the UFS host controller power
7896 * collapse easily which is different than UFS device power collapse.
7897 * Also, enable the host controller power before we go ahead with rest
7898 * of the initialization here.
7900 err = ufshcd_init_hba_vreg(hba);
7904 err = ufshcd_setup_hba_vreg(hba, true);
7908 err = ufshcd_init_clocks(hba);
7910 goto out_disable_hba_vreg;
7912 err = ufshcd_setup_clocks(hba, true);
7914 goto out_disable_hba_vreg;
7916 err = ufshcd_init_vreg(hba);
7918 goto out_disable_clks;
7920 err = ufshcd_setup_vreg(hba, true);
7922 goto out_disable_clks;
7924 err = ufshcd_variant_hba_init(hba);
7926 goto out_disable_vreg;
7928 hba->is_powered = true;
7932 ufshcd_setup_vreg(hba, false);
7934 ufshcd_setup_clocks(hba, false);
7935 out_disable_hba_vreg:
7936 ufshcd_setup_hba_vreg(hba, false);
7941 static void ufshcd_hba_exit(struct ufs_hba *hba)
7943 if (hba->is_powered) {
7944 ufshcd_variant_hba_exit(hba);
7945 ufshcd_setup_vreg(hba, false);
7946 ufshcd_suspend_clkscaling(hba);
7947 if (ufshcd_is_clkscaling_supported(hba))
7949 ufshcd_suspend_clkscaling(hba);
7950 ufshcd_setup_clocks(hba, false);
7951 ufshcd_setup_hba_vreg(hba, false);
7952 hba->is_powered = false;
7953 ufs_put_device_desc(hba);
7958 ufshcd_send_request_sense(struct ufs_hba *hba, struct scsi_device *sdp)
7960 unsigned char cmd[6] = {REQUEST_SENSE,
7969 buffer = kzalloc(UFS_SENSE_SIZE, GFP_KERNEL);
7975 ret = scsi_execute(sdp, cmd, DMA_FROM_DEVICE, buffer,
7976 UFS_SENSE_SIZE, NULL, NULL,
7977 msecs_to_jiffies(1000), 3, 0, RQF_PM, NULL);
7979 pr_err("%s: failed with err %d\n", __func__, ret);
7987 * ufshcd_set_dev_pwr_mode - sends START STOP UNIT command to set device
7989 * @hba: per adapter instance
7990 * @pwr_mode: device power mode to set
7992 * Returns 0 if requested power mode is set successfully
7993 * Returns non-zero if failed to set the requested power mode
7995 static int ufshcd_set_dev_pwr_mode(struct ufs_hba *hba,
7996 enum ufs_dev_pwr_mode pwr_mode)
7998 unsigned char cmd[6] = { START_STOP };
7999 struct scsi_sense_hdr sshdr;
8000 struct scsi_device *sdp;
8001 unsigned long flags;
8004 spin_lock_irqsave(hba->host->host_lock, flags);
8005 sdp = hba->sdev_ufs_device;
8007 ret = scsi_device_get(sdp);
8008 if (!ret && !scsi_device_online(sdp)) {
8010 scsi_device_put(sdp);
8015 spin_unlock_irqrestore(hba->host->host_lock, flags);
8021 * If scsi commands fail, the scsi mid-layer schedules scsi error-
8022 * handling, which would wait for host to be resumed. Since we know
8023 * we are functional while we are here, skip host resume in error
8026 hba->host->eh_noresume = 1;
8027 if (hba->wlun_dev_clr_ua) {
8028 ret = ufshcd_send_request_sense(hba, sdp);
8031 /* Unit attention condition is cleared now */
8032 hba->wlun_dev_clr_ua = false;
8035 cmd[4] = pwr_mode << 4;
8038 * Current function would be generally called from the power management
8039 * callbacks hence set the RQF_PM flag so that it doesn't resume the
8040 * already suspended childs.
8042 ret = scsi_execute(sdp, cmd, DMA_NONE, NULL, 0, NULL, &sshdr,
8043 START_STOP_TIMEOUT, 0, 0, RQF_PM, NULL);
8045 sdev_printk(KERN_WARNING, sdp,
8046 "START_STOP failed for power mode: %d, result %x\n",
8048 if (driver_byte(ret) == DRIVER_SENSE)
8049 scsi_print_sense_hdr(sdp, NULL, &sshdr);
8053 hba->curr_dev_pwr_mode = pwr_mode;
8055 scsi_device_put(sdp);
8056 hba->host->eh_noresume = 0;
8060 static int ufshcd_link_state_transition(struct ufs_hba *hba,
8061 enum uic_link_state req_link_state,
8062 int check_for_bkops)
8066 if (req_link_state == hba->uic_link_state)
8069 if (req_link_state == UIC_LINK_HIBERN8_STATE) {
8070 ret = ufshcd_uic_hibern8_enter(hba);
8072 ufshcd_set_link_hibern8(hba);
8077 * If autobkops is enabled, link can't be turned off because
8078 * turning off the link would also turn off the device.
8080 else if ((req_link_state == UIC_LINK_OFF_STATE) &&
8081 (!check_for_bkops || !hba->auto_bkops_enabled)) {
8083 * Let's make sure that link is in low power mode, we are doing
8084 * this currently by putting the link in Hibern8. Otherway to
8085 * put the link in low power mode is to send the DME end point
8086 * to device and then send the DME reset command to local
8087 * unipro. But putting the link in hibern8 is much faster.
8089 ret = ufshcd_uic_hibern8_enter(hba);
8093 * Change controller state to "reset state" which
8094 * should also put the link in off/reset state
8096 ufshcd_hba_stop(hba);
8098 * TODO: Check if we need any delay to make sure that
8099 * controller is reset
8101 ufshcd_set_link_off(hba);
8108 static void ufshcd_vreg_set_lpm(struct ufs_hba *hba)
8110 bool vcc_off = false;
8113 * It seems some UFS devices may keep drawing more than sleep current
8114 * (atleast for 500us) from UFS rails (especially from VCCQ rail).
8115 * To avoid this situation, add 2ms delay before putting these UFS
8116 * rails in LPM mode.
8118 if (!ufshcd_is_link_active(hba) &&
8119 hba->dev_quirks & UFS_DEVICE_QUIRK_DELAY_BEFORE_LPM)
8120 usleep_range(2000, 2100);
8123 * If UFS device is either in UFS_Sleep turn off VCC rail to save some
8126 * If UFS device and link is in OFF state, all power supplies (VCC,
8127 * VCCQ, VCCQ2) can be turned off if power on write protect is not
8128 * required. If UFS link is inactive (Hibern8 or OFF state) and device
8129 * is in sleep state, put VCCQ & VCCQ2 rails in LPM mode.
8131 * Ignore the error returned by ufshcd_toggle_vreg() as device is anyway
8132 * in low power state which would save some power.
8134 * If Write Booster is enabled and the device needs to flush the WB
8135 * buffer OR if bkops status is urgent for WB, keep Vcc on.
8137 if (ufshcd_is_ufs_dev_poweroff(hba) && ufshcd_is_link_off(hba) &&
8138 !hba->dev_info.is_lu_power_on_wp) {
8139 ufshcd_setup_vreg(hba, false);
8141 } else if (!ufshcd_is_ufs_dev_active(hba)) {
8142 ufshcd_toggle_vreg(hba->dev, hba->vreg_info.vcc, false);
8144 if (!ufshcd_is_link_active(hba)) {
8145 ufshcd_config_vreg_lpm(hba, hba->vreg_info.vccq);
8146 ufshcd_config_vreg_lpm(hba, hba->vreg_info.vccq2);
8151 * Some UFS devices require delay after VCC power rail is turned-off.
8153 if (vcc_off && hba->vreg_info.vcc &&
8154 hba->dev_quirks & UFS_DEVICE_QUIRK_DELAY_AFTER_LPM)
8155 usleep_range(5000, 5100);
8158 static int ufshcd_vreg_set_hpm(struct ufs_hba *hba)
8162 if (ufshcd_is_ufs_dev_poweroff(hba) && ufshcd_is_link_off(hba) &&
8163 !hba->dev_info.is_lu_power_on_wp) {
8164 ret = ufshcd_setup_vreg(hba, true);
8165 } else if (!ufshcd_is_ufs_dev_active(hba)) {
8166 if (!ret && !ufshcd_is_link_active(hba)) {
8167 ret = ufshcd_config_vreg_hpm(hba, hba->vreg_info.vccq);
8170 ret = ufshcd_config_vreg_hpm(hba, hba->vreg_info.vccq2);
8174 ret = ufshcd_toggle_vreg(hba->dev, hba->vreg_info.vcc, true);
8179 ufshcd_config_vreg_lpm(hba, hba->vreg_info.vccq);
8181 ufshcd_toggle_vreg(hba->dev, hba->vreg_info.vcc, false);
8186 static void ufshcd_hba_vreg_set_lpm(struct ufs_hba *hba)
8188 if (ufshcd_is_link_off(hba))
8189 ufshcd_setup_hba_vreg(hba, false);
8192 static void ufshcd_hba_vreg_set_hpm(struct ufs_hba *hba)
8194 if (ufshcd_is_link_off(hba))
8195 ufshcd_setup_hba_vreg(hba, true);
8199 * ufshcd_suspend - helper function for suspend operations
8200 * @hba: per adapter instance
8201 * @pm_op: desired low power operation type
8203 * This function will try to put the UFS device and link into low power
8204 * mode based on the "rpm_lvl" (Runtime PM level) or "spm_lvl"
8205 * (System PM level).
8207 * If this function is called during shutdown, it will make sure that
8208 * both UFS device and UFS link is powered off.
8210 * NOTE: UFS device & link must be active before we enter in this function.
8212 * Returns 0 for success and non-zero for failure
8214 static int ufshcd_suspend(struct ufs_hba *hba, enum ufs_pm_op pm_op)
8217 enum ufs_pm_level pm_lvl;
8218 enum ufs_dev_pwr_mode req_dev_pwr_mode;
8219 enum uic_link_state req_link_state;
8221 hba->pm_op_in_progress = 1;
8222 if (!ufshcd_is_shutdown_pm(pm_op)) {
8223 pm_lvl = ufshcd_is_runtime_pm(pm_op) ?
8224 hba->rpm_lvl : hba->spm_lvl;
8225 req_dev_pwr_mode = ufs_get_pm_lvl_to_dev_pwr_mode(pm_lvl);
8226 req_link_state = ufs_get_pm_lvl_to_link_pwr_state(pm_lvl);
8228 req_dev_pwr_mode = UFS_POWERDOWN_PWR_MODE;
8229 req_link_state = UIC_LINK_OFF_STATE;
8233 * If we can't transition into any of the low power modes
8234 * just gate the clocks.
8236 ufshcd_hold(hba, false);
8237 hba->clk_gating.is_suspended = true;
8239 if (hba->clk_scaling.is_allowed) {
8240 cancel_work_sync(&hba->clk_scaling.suspend_work);
8241 cancel_work_sync(&hba->clk_scaling.resume_work);
8242 ufshcd_suspend_clkscaling(hba);
8245 if (req_dev_pwr_mode == UFS_ACTIVE_PWR_MODE &&
8246 req_link_state == UIC_LINK_ACTIVE_STATE) {
8250 if ((req_dev_pwr_mode == hba->curr_dev_pwr_mode) &&
8251 (req_link_state == hba->uic_link_state))
8254 /* UFS device & link must be active before we enter in this function */
8255 if (!ufshcd_is_ufs_dev_active(hba) || !ufshcd_is_link_active(hba)) {
8260 if (ufshcd_is_runtime_pm(pm_op)) {
8261 if (ufshcd_can_autobkops_during_suspend(hba)) {
8263 * The device is idle with no requests in the queue,
8264 * allow background operations if bkops status shows
8265 * that performance might be impacted.
8267 ret = ufshcd_urgent_bkops(hba);
8271 /* make sure that auto bkops is disabled */
8272 ufshcd_disable_auto_bkops(hba);
8275 * If device needs to do BKOP or WB buffer flush during
8276 * Hibern8, keep device power mode as "active power mode"
8279 hba->dev_info.b_rpm_dev_flush_capable =
8280 hba->auto_bkops_enabled ||
8281 (((req_link_state == UIC_LINK_HIBERN8_STATE) ||
8282 ((req_link_state == UIC_LINK_ACTIVE_STATE) &&
8283 ufshcd_is_auto_hibern8_enabled(hba))) &&
8284 ufshcd_wb_need_flush(hba));
8287 if (req_dev_pwr_mode != hba->curr_dev_pwr_mode) {
8288 if ((ufshcd_is_runtime_pm(pm_op) && !hba->auto_bkops_enabled) ||
8289 !ufshcd_is_runtime_pm(pm_op)) {
8290 /* ensure that bkops is disabled */
8291 ufshcd_disable_auto_bkops(hba);
8294 if (!hba->dev_info.b_rpm_dev_flush_capable) {
8295 ret = ufshcd_set_dev_pwr_mode(hba, req_dev_pwr_mode);
8301 flush_work(&hba->eeh_work);
8302 ret = ufshcd_link_state_transition(hba, req_link_state, 1);
8304 goto set_dev_active;
8306 ufshcd_vreg_set_lpm(hba);
8310 * Call vendor specific suspend callback. As these callbacks may access
8311 * vendor specific host controller register space call them before the
8312 * host clocks are ON.
8314 ret = ufshcd_vops_suspend(hba, pm_op);
8316 goto set_link_active;
8318 * Disable the host irq as host controller as there won't be any
8319 * host controller transaction expected till resume.
8321 ufshcd_disable_irq(hba);
8323 if (!ufshcd_is_link_active(hba))
8324 ufshcd_setup_clocks(hba, false);
8326 /* If link is active, device ref_clk can't be switched off */
8327 __ufshcd_setup_clocks(hba, false, true);
8329 hba->clk_gating.state = CLKS_OFF;
8330 trace_ufshcd_clk_gating(dev_name(hba->dev), hba->clk_gating.state);
8332 /* Put the host controller in low power mode if possible */
8333 ufshcd_hba_vreg_set_lpm(hba);
8337 if (hba->clk_scaling.is_allowed)
8338 ufshcd_resume_clkscaling(hba);
8339 ufshcd_vreg_set_hpm(hba);
8340 if (ufshcd_is_link_hibern8(hba) && !ufshcd_uic_hibern8_exit(hba))
8341 ufshcd_set_link_active(hba);
8342 else if (ufshcd_is_link_off(hba))
8343 ufshcd_host_reset_and_restore(hba);
8345 if (!ufshcd_set_dev_pwr_mode(hba, UFS_ACTIVE_PWR_MODE))
8346 ufshcd_disable_auto_bkops(hba);
8348 if (hba->clk_scaling.is_allowed)
8349 ufshcd_resume_clkscaling(hba);
8350 hba->clk_gating.is_suspended = false;
8351 hba->dev_info.b_rpm_dev_flush_capable = false;
8352 ufshcd_release(hba);
8354 if (hba->dev_info.b_rpm_dev_flush_capable) {
8355 schedule_delayed_work(&hba->rpm_dev_flush_recheck_work,
8356 msecs_to_jiffies(RPM_DEV_FLUSH_RECHECK_WORK_DELAY_MS));
8359 hba->pm_op_in_progress = 0;
8362 ufshcd_update_reg_hist(&hba->ufs_stats.suspend_err, (u32)ret);
8367 * ufshcd_resume - helper function for resume operations
8368 * @hba: per adapter instance
8369 * @pm_op: runtime PM or system PM
8371 * This function basically brings the UFS device, UniPro link and controller
8374 * Returns 0 for success and non-zero for failure
8376 static int ufshcd_resume(struct ufs_hba *hba, enum ufs_pm_op pm_op)
8379 enum uic_link_state old_link_state;
8381 hba->pm_op_in_progress = 1;
8382 old_link_state = hba->uic_link_state;
8384 ufshcd_hba_vreg_set_hpm(hba);
8385 /* Make sure clocks are enabled before accessing controller */
8386 ret = ufshcd_setup_clocks(hba, true);
8390 /* enable the host irq as host controller would be active soon */
8391 ufshcd_enable_irq(hba);
8393 ret = ufshcd_vreg_set_hpm(hba);
8395 goto disable_irq_and_vops_clks;
8398 * Call vendor specific resume callback. As these callbacks may access
8399 * vendor specific host controller register space call them when the
8400 * host clocks are ON.
8402 ret = ufshcd_vops_resume(hba, pm_op);
8406 if (ufshcd_is_link_hibern8(hba)) {
8407 ret = ufshcd_uic_hibern8_exit(hba);
8409 ufshcd_set_link_active(hba);
8411 goto vendor_suspend;
8412 } else if (ufshcd_is_link_off(hba)) {
8414 * A full initialization of the host and the device is
8415 * required since the link was put to off during suspend.
8417 ret = ufshcd_reset_and_restore(hba);
8419 * ufshcd_reset_and_restore() should have already
8420 * set the link state as active
8422 if (ret || !ufshcd_is_link_active(hba))
8423 goto vendor_suspend;
8426 if (!ufshcd_is_ufs_dev_active(hba)) {
8427 ret = ufshcd_set_dev_pwr_mode(hba, UFS_ACTIVE_PWR_MODE);
8429 goto set_old_link_state;
8432 if (ufshcd_keep_autobkops_enabled_except_suspend(hba))
8433 ufshcd_enable_auto_bkops(hba);
8436 * If BKOPs operations are urgently needed at this moment then
8437 * keep auto-bkops enabled or else disable it.
8439 ufshcd_urgent_bkops(hba);
8441 hba->clk_gating.is_suspended = false;
8443 if (hba->clk_scaling.is_allowed)
8444 ufshcd_resume_clkscaling(hba);
8446 /* Enable Auto-Hibernate if configured */
8447 ufshcd_auto_hibern8_enable(hba);
8449 if (hba->dev_info.b_rpm_dev_flush_capable) {
8450 hba->dev_info.b_rpm_dev_flush_capable = false;
8451 cancel_delayed_work(&hba->rpm_dev_flush_recheck_work);
8454 /* Schedule clock gating in case of no access to UFS device yet */
8455 ufshcd_release(hba);
8460 ufshcd_link_state_transition(hba, old_link_state, 0);
8462 ufshcd_vops_suspend(hba, pm_op);
8464 ufshcd_vreg_set_lpm(hba);
8465 disable_irq_and_vops_clks:
8466 ufshcd_disable_irq(hba);
8467 if (hba->clk_scaling.is_allowed)
8468 ufshcd_suspend_clkscaling(hba);
8469 ufshcd_setup_clocks(hba, false);
8471 hba->pm_op_in_progress = 0;
8473 ufshcd_update_reg_hist(&hba->ufs_stats.resume_err, (u32)ret);
8478 * ufshcd_system_suspend - system suspend routine
8479 * @hba: per adapter instance
8481 * Check the description of ufshcd_suspend() function for more details.
8483 * Returns 0 for success and non-zero for failure
8485 int ufshcd_system_suspend(struct ufs_hba *hba)
8488 ktime_t start = ktime_get();
8490 if (!hba || !hba->is_powered)
8493 if ((ufs_get_pm_lvl_to_dev_pwr_mode(hba->spm_lvl) ==
8494 hba->curr_dev_pwr_mode) &&
8495 (ufs_get_pm_lvl_to_link_pwr_state(hba->spm_lvl) ==
8496 hba->uic_link_state))
8499 if (pm_runtime_suspended(hba->dev)) {
8501 * UFS device and/or UFS link low power states during runtime
8502 * suspend seems to be different than what is expected during
8503 * system suspend. Hence runtime resume the devic & link and
8504 * let the system suspend low power states to take effect.
8505 * TODO: If resume takes longer time, we might have optimize
8506 * it in future by not resuming everything if possible.
8508 ret = ufshcd_runtime_resume(hba);
8513 ret = ufshcd_suspend(hba, UFS_SYSTEM_PM);
8515 trace_ufshcd_system_suspend(dev_name(hba->dev), ret,
8516 ktime_to_us(ktime_sub(ktime_get(), start)),
8517 hba->curr_dev_pwr_mode, hba->uic_link_state);
8519 hba->is_sys_suspended = true;
8522 EXPORT_SYMBOL(ufshcd_system_suspend);
8525 * ufshcd_system_resume - system resume routine
8526 * @hba: per adapter instance
8528 * Returns 0 for success and non-zero for failure
8531 int ufshcd_system_resume(struct ufs_hba *hba)
8534 ktime_t start = ktime_get();
8539 if (!hba->is_powered || pm_runtime_suspended(hba->dev))
8541 * Let the runtime resume take care of resuming
8542 * if runtime suspended.
8546 ret = ufshcd_resume(hba, UFS_SYSTEM_PM);
8548 trace_ufshcd_system_resume(dev_name(hba->dev), ret,
8549 ktime_to_us(ktime_sub(ktime_get(), start)),
8550 hba->curr_dev_pwr_mode, hba->uic_link_state);
8552 hba->is_sys_suspended = false;
8555 EXPORT_SYMBOL(ufshcd_system_resume);
8558 * ufshcd_runtime_suspend - runtime suspend routine
8559 * @hba: per adapter instance
8561 * Check the description of ufshcd_suspend() function for more details.
8563 * Returns 0 for success and non-zero for failure
8565 int ufshcd_runtime_suspend(struct ufs_hba *hba)
8568 ktime_t start = ktime_get();
8573 if (!hba->is_powered)
8576 ret = ufshcd_suspend(hba, UFS_RUNTIME_PM);
8578 trace_ufshcd_runtime_suspend(dev_name(hba->dev), ret,
8579 ktime_to_us(ktime_sub(ktime_get(), start)),
8580 hba->curr_dev_pwr_mode, hba->uic_link_state);
8583 EXPORT_SYMBOL(ufshcd_runtime_suspend);
8586 * ufshcd_runtime_resume - runtime resume routine
8587 * @hba: per adapter instance
8589 * This function basically brings the UFS device, UniPro link and controller
8590 * to active state. Following operations are done in this function:
8592 * 1. Turn on all the controller related clocks
8593 * 2. Bring the UniPro link out of Hibernate state
8594 * 3. If UFS device is in sleep state, turn ON VCC rail and bring the UFS device
8596 * 4. If auto-bkops is enabled on the device, disable it.
8598 * So following would be the possible power state after this function return
8600 * S1: UFS device in Active state with VCC rail ON
8601 * UniPro link in Active state
8602 * All the UFS/UniPro controller clocks are ON
8604 * Returns 0 for success and non-zero for failure
8606 int ufshcd_runtime_resume(struct ufs_hba *hba)
8609 ktime_t start = ktime_get();
8614 if (!hba->is_powered)
8617 ret = ufshcd_resume(hba, UFS_RUNTIME_PM);
8619 trace_ufshcd_runtime_resume(dev_name(hba->dev), ret,
8620 ktime_to_us(ktime_sub(ktime_get(), start)),
8621 hba->curr_dev_pwr_mode, hba->uic_link_state);
8624 EXPORT_SYMBOL(ufshcd_runtime_resume);
8626 int ufshcd_runtime_idle(struct ufs_hba *hba)
8630 EXPORT_SYMBOL(ufshcd_runtime_idle);
8633 * ufshcd_shutdown - shutdown routine
8634 * @hba: per adapter instance
8636 * This function would power off both UFS device and UFS link.
8638 * Returns 0 always to allow force shutdown even in case of errors.
8640 int ufshcd_shutdown(struct ufs_hba *hba)
8644 if (!hba->is_powered)
8647 if (ufshcd_is_ufs_dev_poweroff(hba) && ufshcd_is_link_off(hba))
8650 if (pm_runtime_suspended(hba->dev)) {
8651 ret = ufshcd_runtime_resume(hba);
8656 ret = ufshcd_suspend(hba, UFS_SHUTDOWN_PM);
8659 dev_err(hba->dev, "%s failed, err %d\n", __func__, ret);
8660 /* allow force shutdown even in case of errors */
8663 EXPORT_SYMBOL(ufshcd_shutdown);
8666 * ufshcd_remove - de-allocate SCSI host and host memory space
8667 * data structure memory
8668 * @hba: per adapter instance
8670 void ufshcd_remove(struct ufs_hba *hba)
8672 ufs_bsg_remove(hba);
8673 ufs_sysfs_remove_nodes(hba->dev);
8674 blk_cleanup_queue(hba->tmf_queue);
8675 blk_mq_free_tag_set(&hba->tmf_tag_set);
8676 blk_cleanup_queue(hba->cmd_queue);
8677 scsi_remove_host(hba->host);
8678 /* disable interrupts */
8679 ufshcd_disable_intr(hba, hba->intr_mask);
8680 ufshcd_hba_stop(hba);
8682 ufshcd_exit_clk_scaling(hba);
8683 ufshcd_exit_clk_gating(hba);
8684 if (ufshcd_is_clkscaling_supported(hba))
8685 device_remove_file(hba->dev, &hba->clk_scaling.enable_attr);
8686 ufshcd_hba_exit(hba);
8688 EXPORT_SYMBOL_GPL(ufshcd_remove);
8691 * ufshcd_dealloc_host - deallocate Host Bus Adapter (HBA)
8692 * @hba: pointer to Host Bus Adapter (HBA)
8694 void ufshcd_dealloc_host(struct ufs_hba *hba)
8696 ufshcd_crypto_destroy_keyslot_manager(hba);
8697 scsi_host_put(hba->host);
8699 EXPORT_SYMBOL_GPL(ufshcd_dealloc_host);
8702 * ufshcd_set_dma_mask - Set dma mask based on the controller
8703 * addressing capability
8704 * @hba: per adapter instance
8706 * Returns 0 for success, non-zero for failure
8708 static int ufshcd_set_dma_mask(struct ufs_hba *hba)
8710 if (hba->capabilities & MASK_64_ADDRESSING_SUPPORT) {
8711 if (!dma_set_mask_and_coherent(hba->dev, DMA_BIT_MASK(64)))
8714 return dma_set_mask_and_coherent(hba->dev, DMA_BIT_MASK(32));
8718 * ufshcd_alloc_host - allocate Host Bus Adapter (HBA)
8719 * @dev: pointer to device handle
8720 * @hba_handle: driver private handle
8721 * Returns 0 on success, non-zero value on failure
8723 int ufshcd_alloc_host(struct device *dev, struct ufs_hba **hba_handle)
8725 struct Scsi_Host *host;
8726 struct ufs_hba *hba;
8731 "Invalid memory reference for dev is NULL\n");
8736 host = scsi_host_alloc(&ufshcd_driver_template,
8737 sizeof(struct ufs_hba));
8739 dev_err(dev, "scsi_host_alloc failed\n");
8743 hba = shost_priv(host);
8747 hba->dev_ref_clk_freq = REF_CLK_FREQ_INVAL;
8749 INIT_LIST_HEAD(&hba->clk_list_head);
8754 EXPORT_SYMBOL(ufshcd_alloc_host);
8756 /* This function exists because blk_mq_alloc_tag_set() requires this. */
8757 static blk_status_t ufshcd_queue_tmf(struct blk_mq_hw_ctx *hctx,
8758 const struct blk_mq_queue_data *qd)
8761 return BLK_STS_NOTSUPP;
8764 static const struct blk_mq_ops ufshcd_tmf_ops = {
8765 .queue_rq = ufshcd_queue_tmf,
8769 * ufshcd_init - Driver initialization routine
8770 * @hba: per-adapter instance
8771 * @mmio_base: base register address
8772 * @irq: Interrupt line of device
8773 * Returns 0 on success, non-zero value on failure
8775 int ufshcd_init(struct ufs_hba *hba, void __iomem *mmio_base, unsigned int irq)
8778 struct Scsi_Host *host = hba->host;
8779 struct device *dev = hba->dev;
8783 "Invalid memory reference for mmio_base is NULL\n");
8788 hba->mmio_base = mmio_base;
8790 hba->vps = &ufs_hba_vps;
8792 err = ufshcd_hba_init(hba);
8796 /* Read capabilities registers */
8797 err = ufshcd_hba_capabilities(hba);
8801 /* Get UFS version supported by the controller */
8802 hba->ufs_version = ufshcd_get_ufs_version(hba);
8804 if ((hba->ufs_version != UFSHCI_VERSION_10) &&
8805 (hba->ufs_version != UFSHCI_VERSION_11) &&
8806 (hba->ufs_version != UFSHCI_VERSION_20) &&
8807 (hba->ufs_version != UFSHCI_VERSION_21))
8808 dev_err(hba->dev, "invalid UFS version 0x%x\n",
8811 /* Get Interrupt bit mask per version */
8812 hba->intr_mask = ufshcd_get_intr_mask(hba);
8814 err = ufshcd_set_dma_mask(hba);
8816 dev_err(hba->dev, "set dma mask failed\n");
8820 /* Allocate memory for host memory space */
8821 err = ufshcd_memory_alloc(hba);
8823 dev_err(hba->dev, "Memory allocation failed\n");
8828 ufshcd_host_memory_configure(hba);
8830 host->can_queue = hba->nutrs;
8831 host->cmd_per_lun = hba->nutrs;
8832 host->max_id = UFSHCD_MAX_ID;
8833 host->max_lun = UFS_MAX_LUNS;
8834 host->max_channel = UFSHCD_MAX_CHANNEL;
8835 host->unique_id = host->host_no;
8836 host->max_cmd_len = UFS_CDB_SIZE;
8838 hba->max_pwr_info.is_valid = false;
8840 /* Initialize work queues */
8841 INIT_WORK(&hba->eh_work, ufshcd_err_handler);
8842 INIT_WORK(&hba->eeh_work, ufshcd_exception_event_handler);
8844 /* Initialize UIC command mutex */
8845 mutex_init(&hba->uic_cmd_mutex);
8847 /* Initialize mutex for device management commands */
8848 mutex_init(&hba->dev_cmd.lock);
8850 init_rwsem(&hba->clk_scaling_lock);
8852 ufshcd_init_clk_gating(hba);
8854 ufshcd_init_clk_scaling(hba);
8857 * In order to avoid any spurious interrupt immediately after
8858 * registering UFS controller interrupt handler, clear any pending UFS
8859 * interrupt status and disable all the UFS interrupts.
8861 ufshcd_writel(hba, ufshcd_readl(hba, REG_INTERRUPT_STATUS),
8862 REG_INTERRUPT_STATUS);
8863 ufshcd_writel(hba, 0, REG_INTERRUPT_ENABLE);
8865 * Make sure that UFS interrupts are disabled and any pending interrupt
8866 * status is cleared before registering UFS interrupt handler.
8870 /* IRQ registration */
8871 err = devm_request_irq(dev, irq, ufshcd_intr, IRQF_SHARED, UFSHCD, hba);
8873 dev_err(hba->dev, "request irq failed\n");
8876 hba->is_irq_enabled = true;
8879 err = scsi_add_host(host, hba->dev);
8881 dev_err(hba->dev, "scsi_add_host failed\n");
8885 hba->cmd_queue = blk_mq_init_queue(&hba->host->tag_set);
8886 if (IS_ERR(hba->cmd_queue)) {
8887 err = PTR_ERR(hba->cmd_queue);
8888 goto out_remove_scsi_host;
8891 hba->tmf_tag_set = (struct blk_mq_tag_set) {
8893 .queue_depth = hba->nutmrs,
8894 .ops = &ufshcd_tmf_ops,
8895 .flags = BLK_MQ_F_NO_SCHED,
8897 err = blk_mq_alloc_tag_set(&hba->tmf_tag_set);
8899 goto free_cmd_queue;
8900 hba->tmf_queue = blk_mq_init_queue(&hba->tmf_tag_set);
8901 if (IS_ERR(hba->tmf_queue)) {
8902 err = PTR_ERR(hba->tmf_queue);
8903 goto free_tmf_tag_set;
8906 /* Reset the attached device */
8907 ufshcd_vops_device_reset(hba);
8909 ufshcd_init_crypto(hba);
8911 /* Host controller enable */
8912 err = ufshcd_hba_enable(hba);
8914 dev_err(hba->dev, "Host controller enable failed\n");
8915 ufshcd_print_host_regs(hba);
8916 ufshcd_print_host_state(hba);
8917 goto free_tmf_queue;
8921 * Set the default power management level for runtime and system PM.
8922 * Default power saving mode is to keep UFS link in Hibern8 state
8923 * and UFS device in sleep state.
8925 hba->rpm_lvl = ufs_get_desired_pm_lvl_for_dev_link_state(
8927 UIC_LINK_HIBERN8_STATE);
8928 hba->spm_lvl = ufs_get_desired_pm_lvl_for_dev_link_state(
8930 UIC_LINK_HIBERN8_STATE);
8932 INIT_DELAYED_WORK(&hba->rpm_dev_flush_recheck_work,
8933 ufshcd_rpm_dev_flush_recheck_work);
8935 /* Set the default auto-hiberate idle timer value to 150 ms */
8936 if (ufshcd_is_auto_hibern8_supported(hba) && !hba->ahit) {
8937 hba->ahit = FIELD_PREP(UFSHCI_AHIBERN8_TIMER_MASK, 150) |
8938 FIELD_PREP(UFSHCI_AHIBERN8_SCALE_MASK, 3);
8941 /* Hold auto suspend until async scan completes */
8942 pm_runtime_get_sync(dev);
8943 atomic_set(&hba->scsi_block_reqs_cnt, 0);
8945 * We are assuming that device wasn't put in sleep/power-down
8946 * state exclusively during the boot stage before kernel.
8947 * This assumption helps avoid doing link startup twice during
8948 * ufshcd_probe_hba().
8950 ufshcd_set_ufs_dev_active(hba);
8952 async_schedule(ufshcd_async_scan, hba);
8953 ufs_sysfs_add_nodes(hba->dev);
8958 blk_cleanup_queue(hba->tmf_queue);
8960 blk_mq_free_tag_set(&hba->tmf_tag_set);
8962 blk_cleanup_queue(hba->cmd_queue);
8963 out_remove_scsi_host:
8964 scsi_remove_host(hba->host);
8966 ufshcd_exit_clk_scaling(hba);
8967 ufshcd_exit_clk_gating(hba);
8969 hba->is_irq_enabled = false;
8970 ufshcd_hba_exit(hba);
8974 EXPORT_SYMBOL_GPL(ufshcd_init);
8976 MODULE_AUTHOR("Santosh Yaragnavi <santosh.sy@samsung.com>");
8977 MODULE_AUTHOR("Vinayak Holikatti <h.vinayak@samsung.com>");
8978 MODULE_DESCRIPTION("Generic UFS host controller driver Core");
8979 MODULE_LICENSE("GPL");
8980 MODULE_VERSION(UFSHCD_DRIVER_VERSION);