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)
1565 unsigned long flags;
1567 if (!ufshcd_is_clkgating_allowed(hba))
1569 spin_lock_irqsave(hba->host->host_lock, flags);
1570 hba->clk_gating.active_reqs++;
1572 if (ufshcd_eh_in_progress(hba)) {
1573 spin_unlock_irqrestore(hba->host->host_lock, flags);
1578 switch (hba->clk_gating.state) {
1581 * Wait for the ungate work to complete if in progress.
1582 * Though the clocks may be in ON state, the link could
1583 * still be in hibner8 state if hibern8 is allowed
1584 * during clock gating.
1585 * Make sure we exit hibern8 state also in addition to
1588 if (ufshcd_can_hibern8_during_gating(hba) &&
1589 ufshcd_is_link_hibern8(hba)) {
1592 hba->clk_gating.active_reqs--;
1595 spin_unlock_irqrestore(hba->host->host_lock, flags);
1596 flush_result = flush_work(&hba->clk_gating.ungate_work);
1597 if (hba->clk_gating.is_suspended && !flush_result)
1599 spin_lock_irqsave(hba->host->host_lock, flags);
1604 if (cancel_delayed_work(&hba->clk_gating.gate_work)) {
1605 hba->clk_gating.state = CLKS_ON;
1606 trace_ufshcd_clk_gating(dev_name(hba->dev),
1607 hba->clk_gating.state);
1611 * If we are here, it means gating work is either done or
1612 * currently running. Hence, fall through to cancel gating
1613 * work and to enable clocks.
1617 ufshcd_scsi_block_requests(hba);
1618 hba->clk_gating.state = REQ_CLKS_ON;
1619 trace_ufshcd_clk_gating(dev_name(hba->dev),
1620 hba->clk_gating.state);
1621 queue_work(hba->clk_gating.clk_gating_workq,
1622 &hba->clk_gating.ungate_work);
1624 * fall through to check if we should wait for this
1625 * work to be done or not.
1631 hba->clk_gating.active_reqs--;
1635 spin_unlock_irqrestore(hba->host->host_lock, flags);
1636 flush_work(&hba->clk_gating.ungate_work);
1637 /* Make sure state is CLKS_ON before returning */
1638 spin_lock_irqsave(hba->host->host_lock, flags);
1641 dev_err(hba->dev, "%s: clk gating is in invalid state %d\n",
1642 __func__, hba->clk_gating.state);
1645 spin_unlock_irqrestore(hba->host->host_lock, flags);
1649 EXPORT_SYMBOL_GPL(ufshcd_hold);
1651 static void ufshcd_gate_work(struct work_struct *work)
1653 struct ufs_hba *hba = container_of(work, struct ufs_hba,
1654 clk_gating.gate_work.work);
1655 unsigned long flags;
1657 spin_lock_irqsave(hba->host->host_lock, flags);
1659 * In case you are here to cancel this work the gating state
1660 * would be marked as REQ_CLKS_ON. In this case save time by
1661 * skipping the gating work and exit after changing the clock
1664 if (hba->clk_gating.is_suspended ||
1665 (hba->clk_gating.state != REQ_CLKS_OFF)) {
1666 hba->clk_gating.state = CLKS_ON;
1667 trace_ufshcd_clk_gating(dev_name(hba->dev),
1668 hba->clk_gating.state);
1672 if (hba->clk_gating.active_reqs
1673 || hba->ufshcd_state != UFSHCD_STATE_OPERATIONAL
1674 || ufshcd_any_tag_in_use(hba) || hba->outstanding_tasks
1675 || hba->active_uic_cmd || hba->uic_async_done)
1678 spin_unlock_irqrestore(hba->host->host_lock, flags);
1680 /* put the link into hibern8 mode before turning off clocks */
1681 if (ufshcd_can_hibern8_during_gating(hba)) {
1682 if (ufshcd_uic_hibern8_enter(hba)) {
1683 hba->clk_gating.state = CLKS_ON;
1684 trace_ufshcd_clk_gating(dev_name(hba->dev),
1685 hba->clk_gating.state);
1688 ufshcd_set_link_hibern8(hba);
1691 ufshcd_disable_irq(hba);
1693 if (!ufshcd_is_link_active(hba))
1694 ufshcd_setup_clocks(hba, false);
1696 /* If link is active, device ref_clk can't be switched off */
1697 __ufshcd_setup_clocks(hba, false, true);
1700 * In case you are here to cancel this work the gating state
1701 * would be marked as REQ_CLKS_ON. In this case keep the state
1702 * as REQ_CLKS_ON which would anyway imply that clocks are off
1703 * and a request to turn them on is pending. By doing this way,
1704 * we keep the state machine in tact and this would ultimately
1705 * prevent from doing cancel work multiple times when there are
1706 * new requests arriving before the current cancel work is done.
1708 spin_lock_irqsave(hba->host->host_lock, flags);
1709 if (hba->clk_gating.state == REQ_CLKS_OFF) {
1710 hba->clk_gating.state = CLKS_OFF;
1711 trace_ufshcd_clk_gating(dev_name(hba->dev),
1712 hba->clk_gating.state);
1715 spin_unlock_irqrestore(hba->host->host_lock, flags);
1720 /* host lock must be held before calling this variant */
1721 static void __ufshcd_release(struct ufs_hba *hba)
1723 if (!ufshcd_is_clkgating_allowed(hba))
1726 hba->clk_gating.active_reqs--;
1728 if (hba->clk_gating.active_reqs || hba->clk_gating.is_suspended
1729 || hba->ufshcd_state != UFSHCD_STATE_OPERATIONAL
1730 || ufshcd_any_tag_in_use(hba) || hba->outstanding_tasks
1731 || hba->active_uic_cmd || hba->uic_async_done
1732 || ufshcd_eh_in_progress(hba))
1735 hba->clk_gating.state = REQ_CLKS_OFF;
1736 trace_ufshcd_clk_gating(dev_name(hba->dev), hba->clk_gating.state);
1737 queue_delayed_work(hba->clk_gating.clk_gating_workq,
1738 &hba->clk_gating.gate_work,
1739 msecs_to_jiffies(hba->clk_gating.delay_ms));
1742 void ufshcd_release(struct ufs_hba *hba)
1744 unsigned long flags;
1746 spin_lock_irqsave(hba->host->host_lock, flags);
1747 __ufshcd_release(hba);
1748 spin_unlock_irqrestore(hba->host->host_lock, flags);
1750 EXPORT_SYMBOL_GPL(ufshcd_release);
1752 static ssize_t ufshcd_clkgate_delay_show(struct device *dev,
1753 struct device_attribute *attr, char *buf)
1755 struct ufs_hba *hba = dev_get_drvdata(dev);
1757 return snprintf(buf, PAGE_SIZE, "%lu\n", hba->clk_gating.delay_ms);
1760 static ssize_t ufshcd_clkgate_delay_store(struct device *dev,
1761 struct device_attribute *attr, const char *buf, size_t count)
1763 struct ufs_hba *hba = dev_get_drvdata(dev);
1764 unsigned long flags, value;
1766 if (kstrtoul(buf, 0, &value))
1769 spin_lock_irqsave(hba->host->host_lock, flags);
1770 hba->clk_gating.delay_ms = value;
1771 spin_unlock_irqrestore(hba->host->host_lock, flags);
1775 static ssize_t ufshcd_clkgate_enable_show(struct device *dev,
1776 struct device_attribute *attr, char *buf)
1778 struct ufs_hba *hba = dev_get_drvdata(dev);
1780 return snprintf(buf, PAGE_SIZE, "%d\n", hba->clk_gating.is_enabled);
1783 static ssize_t ufshcd_clkgate_enable_store(struct device *dev,
1784 struct device_attribute *attr, const char *buf, size_t count)
1786 struct ufs_hba *hba = dev_get_drvdata(dev);
1787 unsigned long flags;
1790 if (kstrtou32(buf, 0, &value))
1794 if (value == hba->clk_gating.is_enabled)
1798 ufshcd_release(hba);
1800 spin_lock_irqsave(hba->host->host_lock, flags);
1801 hba->clk_gating.active_reqs++;
1802 spin_unlock_irqrestore(hba->host->host_lock, flags);
1805 hba->clk_gating.is_enabled = value;
1810 static void ufshcd_init_clk_scaling(struct ufs_hba *hba)
1812 char wq_name[sizeof("ufs_clkscaling_00")];
1814 if (!ufshcd_is_clkscaling_supported(hba))
1817 INIT_WORK(&hba->clk_scaling.suspend_work,
1818 ufshcd_clk_scaling_suspend_work);
1819 INIT_WORK(&hba->clk_scaling.resume_work,
1820 ufshcd_clk_scaling_resume_work);
1822 snprintf(wq_name, sizeof(wq_name), "ufs_clkscaling_%d",
1823 hba->host->host_no);
1824 hba->clk_scaling.workq = create_singlethread_workqueue(wq_name);
1826 ufshcd_clkscaling_init_sysfs(hba);
1829 static void ufshcd_exit_clk_scaling(struct ufs_hba *hba)
1831 if (!ufshcd_is_clkscaling_supported(hba))
1834 destroy_workqueue(hba->clk_scaling.workq);
1835 ufshcd_devfreq_remove(hba);
1838 static void ufshcd_init_clk_gating(struct ufs_hba *hba)
1840 char wq_name[sizeof("ufs_clk_gating_00")];
1842 if (!ufshcd_is_clkgating_allowed(hba))
1845 hba->clk_gating.delay_ms = 150;
1846 INIT_DELAYED_WORK(&hba->clk_gating.gate_work, ufshcd_gate_work);
1847 INIT_WORK(&hba->clk_gating.ungate_work, ufshcd_ungate_work);
1849 snprintf(wq_name, ARRAY_SIZE(wq_name), "ufs_clk_gating_%d",
1850 hba->host->host_no);
1851 hba->clk_gating.clk_gating_workq = alloc_ordered_workqueue(wq_name,
1854 hba->clk_gating.is_enabled = true;
1856 hba->clk_gating.delay_attr.show = ufshcd_clkgate_delay_show;
1857 hba->clk_gating.delay_attr.store = ufshcd_clkgate_delay_store;
1858 sysfs_attr_init(&hba->clk_gating.delay_attr.attr);
1859 hba->clk_gating.delay_attr.attr.name = "clkgate_delay_ms";
1860 hba->clk_gating.delay_attr.attr.mode = 0644;
1861 if (device_create_file(hba->dev, &hba->clk_gating.delay_attr))
1862 dev_err(hba->dev, "Failed to create sysfs for clkgate_delay\n");
1864 hba->clk_gating.enable_attr.show = ufshcd_clkgate_enable_show;
1865 hba->clk_gating.enable_attr.store = ufshcd_clkgate_enable_store;
1866 sysfs_attr_init(&hba->clk_gating.enable_attr.attr);
1867 hba->clk_gating.enable_attr.attr.name = "clkgate_enable";
1868 hba->clk_gating.enable_attr.attr.mode = 0644;
1869 if (device_create_file(hba->dev, &hba->clk_gating.enable_attr))
1870 dev_err(hba->dev, "Failed to create sysfs for clkgate_enable\n");
1873 static void ufshcd_exit_clk_gating(struct ufs_hba *hba)
1875 if (!ufshcd_is_clkgating_allowed(hba))
1877 device_remove_file(hba->dev, &hba->clk_gating.delay_attr);
1878 device_remove_file(hba->dev, &hba->clk_gating.enable_attr);
1879 cancel_work_sync(&hba->clk_gating.ungate_work);
1880 cancel_delayed_work_sync(&hba->clk_gating.gate_work);
1881 destroy_workqueue(hba->clk_gating.clk_gating_workq);
1884 /* Must be called with host lock acquired */
1885 static void ufshcd_clk_scaling_start_busy(struct ufs_hba *hba)
1887 bool queue_resume_work = false;
1888 ktime_t curr_t = ktime_get();
1890 if (!ufshcd_is_clkscaling_supported(hba))
1893 if (!hba->clk_scaling.active_reqs++)
1894 queue_resume_work = true;
1896 if (!hba->clk_scaling.is_allowed || hba->pm_op_in_progress)
1899 if (queue_resume_work)
1900 queue_work(hba->clk_scaling.workq,
1901 &hba->clk_scaling.resume_work);
1903 if (!hba->clk_scaling.window_start_t) {
1904 hba->clk_scaling.window_start_t = curr_t;
1905 hba->clk_scaling.tot_busy_t = 0;
1906 hba->clk_scaling.is_busy_started = false;
1909 if (!hba->clk_scaling.is_busy_started) {
1910 hba->clk_scaling.busy_start_t = curr_t;
1911 hba->clk_scaling.is_busy_started = true;
1915 static void ufshcd_clk_scaling_update_busy(struct ufs_hba *hba)
1917 struct ufs_clk_scaling *scaling = &hba->clk_scaling;
1919 if (!ufshcd_is_clkscaling_supported(hba))
1922 if (!hba->outstanding_reqs && scaling->is_busy_started) {
1923 scaling->tot_busy_t += ktime_to_us(ktime_sub(ktime_get(),
1924 scaling->busy_start_t));
1925 scaling->busy_start_t = 0;
1926 scaling->is_busy_started = false;
1930 * ufshcd_send_command - Send SCSI or device management commands
1931 * @hba: per adapter instance
1932 * @task_tag: Task tag of the command
1935 void ufshcd_send_command(struct ufs_hba *hba, unsigned int task_tag)
1937 struct ufshcd_lrb *lrbp = &hba->lrb[task_tag];
1939 lrbp->issue_time_stamp = ktime_get();
1940 lrbp->compl_time_stamp = ktime_set(0, 0);
1941 ufshcd_vops_setup_xfer_req(hba, task_tag, (lrbp->cmd ? true : false));
1942 ufshcd_add_command_trace(hba, task_tag, "send");
1943 ufshcd_clk_scaling_start_busy(hba);
1944 __set_bit(task_tag, &hba->outstanding_reqs);
1945 ufshcd_writel(hba, 1 << task_tag, REG_UTP_TRANSFER_REQ_DOOR_BELL);
1946 /* Make sure that doorbell is committed immediately */
1951 * ufshcd_copy_sense_data - Copy sense data in case of check condition
1952 * @lrbp: pointer to local reference block
1954 static inline void ufshcd_copy_sense_data(struct ufshcd_lrb *lrbp)
1957 if (lrbp->sense_buffer &&
1958 ufshcd_get_rsp_upiu_data_seg_len(lrbp->ucd_rsp_ptr)) {
1961 len = be16_to_cpu(lrbp->ucd_rsp_ptr->sr.sense_data_len);
1962 len_to_copy = min_t(int, UFS_SENSE_SIZE, len);
1964 memcpy(lrbp->sense_buffer, lrbp->ucd_rsp_ptr->sr.sense_data,
1970 * ufshcd_copy_query_response() - Copy the Query Response and the data
1972 * @hba: per adapter instance
1973 * @lrbp: pointer to local reference block
1976 int ufshcd_copy_query_response(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
1978 struct ufs_query_res *query_res = &hba->dev_cmd.query.response;
1980 memcpy(&query_res->upiu_res, &lrbp->ucd_rsp_ptr->qr, QUERY_OSF_SIZE);
1982 /* Get the descriptor */
1983 if (hba->dev_cmd.query.descriptor &&
1984 lrbp->ucd_rsp_ptr->qr.opcode == UPIU_QUERY_OPCODE_READ_DESC) {
1985 u8 *descp = (u8 *)lrbp->ucd_rsp_ptr +
1986 GENERAL_UPIU_REQUEST_SIZE;
1990 /* data segment length */
1991 resp_len = be32_to_cpu(lrbp->ucd_rsp_ptr->header.dword_2) &
1992 MASK_QUERY_DATA_SEG_LEN;
1993 buf_len = be16_to_cpu(
1994 hba->dev_cmd.query.request.upiu_req.length);
1995 if (likely(buf_len >= resp_len)) {
1996 memcpy(hba->dev_cmd.query.descriptor, descp, resp_len);
1999 "%s: rsp size %d is bigger than buffer size %d",
2000 __func__, resp_len, buf_len);
2009 * ufshcd_hba_capabilities - Read controller capabilities
2010 * @hba: per adapter instance
2012 * Return: 0 on success, negative on error.
2014 static inline int ufshcd_hba_capabilities(struct ufs_hba *hba)
2018 hba->capabilities = ufshcd_readl(hba, REG_CONTROLLER_CAPABILITIES);
2020 /* nutrs and nutmrs are 0 based values */
2021 hba->nutrs = (hba->capabilities & MASK_TRANSFER_REQUESTS_SLOTS) + 1;
2023 ((hba->capabilities & MASK_TASK_MANAGEMENT_REQUEST_SLOTS) >> 16) + 1;
2025 /* Read crypto capabilities */
2026 err = ufshcd_hba_init_crypto_capabilities(hba);
2028 dev_err(hba->dev, "crypto setup failed\n");
2034 * ufshcd_ready_for_uic_cmd - Check if controller is ready
2035 * to accept UIC commands
2036 * @hba: per adapter instance
2037 * Return true on success, else false
2039 static inline bool ufshcd_ready_for_uic_cmd(struct ufs_hba *hba)
2041 if (ufshcd_readl(hba, REG_CONTROLLER_STATUS) & UIC_COMMAND_READY)
2048 * ufshcd_get_upmcrs - Get the power mode change request status
2049 * @hba: Pointer to adapter instance
2051 * This function gets the UPMCRS field of HCS register
2052 * Returns value of UPMCRS field
2054 static inline u8 ufshcd_get_upmcrs(struct ufs_hba *hba)
2056 return (ufshcd_readl(hba, REG_CONTROLLER_STATUS) >> 8) & 0x7;
2060 * ufshcd_dispatch_uic_cmd - Dispatch UIC commands to unipro layers
2061 * @hba: per adapter instance
2062 * @uic_cmd: UIC command
2064 * Mutex must be held.
2067 ufshcd_dispatch_uic_cmd(struct ufs_hba *hba, struct uic_command *uic_cmd)
2069 WARN_ON(hba->active_uic_cmd);
2071 hba->active_uic_cmd = uic_cmd;
2074 ufshcd_writel(hba, uic_cmd->argument1, REG_UIC_COMMAND_ARG_1);
2075 ufshcd_writel(hba, uic_cmd->argument2, REG_UIC_COMMAND_ARG_2);
2076 ufshcd_writel(hba, uic_cmd->argument3, REG_UIC_COMMAND_ARG_3);
2078 ufshcd_add_uic_command_trace(hba, uic_cmd, "send");
2081 ufshcd_writel(hba, uic_cmd->command & COMMAND_OPCODE_MASK,
2086 * ufshcd_wait_for_uic_cmd - Wait complectioin of UIC command
2087 * @hba: per adapter instance
2088 * @uic_cmd: UIC command
2090 * Must be called with mutex held.
2091 * Returns 0 only if success.
2094 ufshcd_wait_for_uic_cmd(struct ufs_hba *hba, struct uic_command *uic_cmd)
2097 unsigned long flags;
2099 if (wait_for_completion_timeout(&uic_cmd->done,
2100 msecs_to_jiffies(UIC_CMD_TIMEOUT)))
2101 ret = uic_cmd->argument2 & MASK_UIC_COMMAND_RESULT;
2105 spin_lock_irqsave(hba->host->host_lock, flags);
2106 hba->active_uic_cmd = NULL;
2107 spin_unlock_irqrestore(hba->host->host_lock, flags);
2113 * __ufshcd_send_uic_cmd - Send UIC commands and retrieve the result
2114 * @hba: per adapter instance
2115 * @uic_cmd: UIC command
2116 * @completion: initialize the completion only if this is set to true
2118 * Identical to ufshcd_send_uic_cmd() expect mutex. Must be called
2119 * with mutex held and host_lock locked.
2120 * Returns 0 only if success.
2123 __ufshcd_send_uic_cmd(struct ufs_hba *hba, struct uic_command *uic_cmd,
2126 if (!ufshcd_ready_for_uic_cmd(hba)) {
2128 "Controller not ready to accept UIC commands\n");
2133 init_completion(&uic_cmd->done);
2135 ufshcd_dispatch_uic_cmd(hba, uic_cmd);
2141 * ufshcd_send_uic_cmd - Send UIC commands and retrieve the result
2142 * @hba: per adapter instance
2143 * @uic_cmd: UIC command
2145 * Returns 0 only if success.
2147 int ufshcd_send_uic_cmd(struct ufs_hba *hba, struct uic_command *uic_cmd)
2150 unsigned long flags;
2152 ufshcd_hold(hba, false);
2153 mutex_lock(&hba->uic_cmd_mutex);
2154 ufshcd_add_delay_before_dme_cmd(hba);
2156 spin_lock_irqsave(hba->host->host_lock, flags);
2157 ret = __ufshcd_send_uic_cmd(hba, uic_cmd, true);
2158 spin_unlock_irqrestore(hba->host->host_lock, flags);
2160 ret = ufshcd_wait_for_uic_cmd(hba, uic_cmd);
2162 mutex_unlock(&hba->uic_cmd_mutex);
2164 ufshcd_release(hba);
2169 * ufshcd_map_sg - Map scatter-gather list to prdt
2170 * @hba: per adapter instance
2171 * @lrbp: pointer to local reference block
2173 * Returns 0 in case of success, non-zero value in case of failure
2175 static int ufshcd_map_sg(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
2177 struct ufshcd_sg_entry *prd_table;
2178 struct scatterlist *sg;
2179 struct scsi_cmnd *cmd;
2184 sg_segments = scsi_dma_map(cmd);
2185 if (sg_segments < 0)
2190 if (hba->quirks & UFSHCD_QUIRK_PRDT_BYTE_GRAN)
2191 lrbp->utr_descriptor_ptr->prd_table_length =
2192 cpu_to_le16((sg_segments *
2193 sizeof(struct ufshcd_sg_entry)));
2195 lrbp->utr_descriptor_ptr->prd_table_length =
2196 cpu_to_le16((u16) (sg_segments));
2198 prd_table = (struct ufshcd_sg_entry *)lrbp->ucd_prdt_ptr;
2200 scsi_for_each_sg(cmd, sg, sg_segments, i) {
2202 cpu_to_le32(((u32) sg_dma_len(sg))-1);
2203 prd_table[i].base_addr =
2204 cpu_to_le32(lower_32_bits(sg->dma_address));
2205 prd_table[i].upper_addr =
2206 cpu_to_le32(upper_32_bits(sg->dma_address));
2207 prd_table[i].reserved = 0;
2210 lrbp->utr_descriptor_ptr->prd_table_length = 0;
2217 * ufshcd_enable_intr - enable interrupts
2218 * @hba: per adapter instance
2219 * @intrs: interrupt bits
2221 static void ufshcd_enable_intr(struct ufs_hba *hba, u32 intrs)
2223 u32 set = ufshcd_readl(hba, REG_INTERRUPT_ENABLE);
2225 if (hba->ufs_version == UFSHCI_VERSION_10) {
2227 rw = set & INTERRUPT_MASK_RW_VER_10;
2228 set = rw | ((set ^ intrs) & intrs);
2233 ufshcd_writel(hba, set, REG_INTERRUPT_ENABLE);
2237 * ufshcd_disable_intr - disable interrupts
2238 * @hba: per adapter instance
2239 * @intrs: interrupt bits
2241 static void ufshcd_disable_intr(struct ufs_hba *hba, u32 intrs)
2243 u32 set = ufshcd_readl(hba, REG_INTERRUPT_ENABLE);
2245 if (hba->ufs_version == UFSHCI_VERSION_10) {
2247 rw = (set & INTERRUPT_MASK_RW_VER_10) &
2248 ~(intrs & INTERRUPT_MASK_RW_VER_10);
2249 set = rw | ((set & intrs) & ~INTERRUPT_MASK_RW_VER_10);
2255 ufshcd_writel(hba, set, REG_INTERRUPT_ENABLE);
2259 * ufshcd_prepare_req_desc_hdr() - Fills the requests header
2260 * descriptor according to request
2261 * @lrbp: pointer to local reference block
2262 * @upiu_flags: flags required in the header
2263 * @cmd_dir: requests data direction
2265 static void ufshcd_prepare_req_desc_hdr(struct ufshcd_lrb *lrbp,
2266 u8 *upiu_flags, enum dma_data_direction cmd_dir)
2268 struct utp_transfer_req_desc *req_desc = lrbp->utr_descriptor_ptr;
2274 if (cmd_dir == DMA_FROM_DEVICE) {
2275 data_direction = UTP_DEVICE_TO_HOST;
2276 *upiu_flags = UPIU_CMD_FLAGS_READ;
2277 } else if (cmd_dir == DMA_TO_DEVICE) {
2278 data_direction = UTP_HOST_TO_DEVICE;
2279 *upiu_flags = UPIU_CMD_FLAGS_WRITE;
2281 data_direction = UTP_NO_DATA_TRANSFER;
2282 *upiu_flags = UPIU_CMD_FLAGS_NONE;
2285 dword_0 = data_direction | (lrbp->command_type
2286 << UPIU_COMMAND_TYPE_OFFSET);
2288 dword_0 |= UTP_REQ_DESC_INT_CMD;
2290 /* Prepare crypto related dwords */
2291 ufshcd_prepare_req_desc_hdr_crypto(lrbp, &dword_0, &dword_1, &dword_3);
2293 /* Transfer request descriptor header fields */
2294 req_desc->header.dword_0 = cpu_to_le32(dword_0);
2295 req_desc->header.dword_1 = cpu_to_le32(dword_1);
2297 * assigning invalid value for command status. Controller
2298 * updates OCS on command completion, with the command
2301 req_desc->header.dword_2 =
2302 cpu_to_le32(OCS_INVALID_COMMAND_STATUS);
2303 req_desc->header.dword_3 = cpu_to_le32(dword_3);
2305 req_desc->prd_table_length = 0;
2309 * ufshcd_prepare_utp_scsi_cmd_upiu() - fills the utp_transfer_req_desc,
2311 * @lrbp: local reference block pointer
2312 * @upiu_flags: flags
2315 void ufshcd_prepare_utp_scsi_cmd_upiu(struct ufshcd_lrb *lrbp, u8 upiu_flags)
2317 struct scsi_cmnd *cmd = lrbp->cmd;
2318 struct utp_upiu_req *ucd_req_ptr = lrbp->ucd_req_ptr;
2319 unsigned short cdb_len;
2321 /* command descriptor fields */
2322 ucd_req_ptr->header.dword_0 = UPIU_HEADER_DWORD(
2323 UPIU_TRANSACTION_COMMAND, upiu_flags,
2324 lrbp->lun, lrbp->task_tag);
2325 ucd_req_ptr->header.dword_1 = UPIU_HEADER_DWORD(
2326 UPIU_COMMAND_SET_TYPE_SCSI, 0, 0, 0);
2328 /* Total EHS length and Data segment length will be zero */
2329 ucd_req_ptr->header.dword_2 = 0;
2331 ucd_req_ptr->sc.exp_data_transfer_len = cpu_to_be32(cmd->sdb.length);
2333 cdb_len = min_t(unsigned short, cmd->cmd_len, UFS_CDB_SIZE);
2334 memset(ucd_req_ptr->sc.cdb, 0, UFS_CDB_SIZE);
2335 memcpy(ucd_req_ptr->sc.cdb, cmd->cmnd, cdb_len);
2337 memset(lrbp->ucd_rsp_ptr, 0, sizeof(struct utp_upiu_rsp));
2341 * ufshcd_prepare_utp_query_req_upiu() - fills the utp_transfer_req_desc,
2344 * @lrbp: local reference block pointer
2345 * @upiu_flags: flags
2347 static void ufshcd_prepare_utp_query_req_upiu(struct ufs_hba *hba,
2348 struct ufshcd_lrb *lrbp, u8 upiu_flags)
2350 struct utp_upiu_req *ucd_req_ptr = lrbp->ucd_req_ptr;
2351 struct ufs_query *query = &hba->dev_cmd.query;
2352 u16 len = be16_to_cpu(query->request.upiu_req.length);
2354 /* Query request header */
2355 ucd_req_ptr->header.dword_0 = UPIU_HEADER_DWORD(
2356 UPIU_TRANSACTION_QUERY_REQ, upiu_flags,
2357 lrbp->lun, lrbp->task_tag);
2358 ucd_req_ptr->header.dword_1 = UPIU_HEADER_DWORD(
2359 0, query->request.query_func, 0, 0);
2361 /* Data segment length only need for WRITE_DESC */
2362 if (query->request.upiu_req.opcode == UPIU_QUERY_OPCODE_WRITE_DESC)
2363 ucd_req_ptr->header.dword_2 =
2364 UPIU_HEADER_DWORD(0, 0, (len >> 8), (u8)len);
2366 ucd_req_ptr->header.dword_2 = 0;
2368 /* Copy the Query Request buffer as is */
2369 memcpy(&ucd_req_ptr->qr, &query->request.upiu_req,
2372 /* Copy the Descriptor */
2373 if (query->request.upiu_req.opcode == UPIU_QUERY_OPCODE_WRITE_DESC)
2374 memcpy(ucd_req_ptr + 1, query->descriptor, len);
2376 memset(lrbp->ucd_rsp_ptr, 0, sizeof(struct utp_upiu_rsp));
2379 static inline void ufshcd_prepare_utp_nop_upiu(struct ufshcd_lrb *lrbp)
2381 struct utp_upiu_req *ucd_req_ptr = lrbp->ucd_req_ptr;
2383 memset(ucd_req_ptr, 0, sizeof(struct utp_upiu_req));
2385 /* command descriptor fields */
2386 ucd_req_ptr->header.dword_0 =
2388 UPIU_TRANSACTION_NOP_OUT, 0, 0, lrbp->task_tag);
2389 /* clear rest of the fields of basic header */
2390 ucd_req_ptr->header.dword_1 = 0;
2391 ucd_req_ptr->header.dword_2 = 0;
2393 memset(lrbp->ucd_rsp_ptr, 0, sizeof(struct utp_upiu_rsp));
2397 * ufshcd_comp_devman_upiu - UFS Protocol Information Unit(UPIU)
2398 * for Device Management Purposes
2399 * @hba: per adapter instance
2400 * @lrbp: pointer to local reference block
2402 static int ufshcd_comp_devman_upiu(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
2407 if ((hba->ufs_version == UFSHCI_VERSION_10) ||
2408 (hba->ufs_version == UFSHCI_VERSION_11))
2409 lrbp->command_type = UTP_CMD_TYPE_DEV_MANAGE;
2411 lrbp->command_type = UTP_CMD_TYPE_UFS_STORAGE;
2413 ufshcd_prepare_req_desc_hdr(lrbp, &upiu_flags, DMA_NONE);
2414 if (hba->dev_cmd.type == DEV_CMD_TYPE_QUERY)
2415 ufshcd_prepare_utp_query_req_upiu(hba, lrbp, upiu_flags);
2416 else if (hba->dev_cmd.type == DEV_CMD_TYPE_NOP)
2417 ufshcd_prepare_utp_nop_upiu(lrbp);
2425 * ufshcd_comp_scsi_upiu - UFS Protocol Information Unit(UPIU)
2427 * @hba: per adapter instance
2428 * @lrbp: pointer to local reference block
2430 static int ufshcd_comp_scsi_upiu(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
2435 if ((hba->ufs_version == UFSHCI_VERSION_10) ||
2436 (hba->ufs_version == UFSHCI_VERSION_11))
2437 lrbp->command_type = UTP_CMD_TYPE_SCSI;
2439 lrbp->command_type = UTP_CMD_TYPE_UFS_STORAGE;
2441 if (likely(lrbp->cmd)) {
2442 ufshcd_prepare_req_desc_hdr(lrbp, &upiu_flags,
2443 lrbp->cmd->sc_data_direction);
2444 ufshcd_prepare_utp_scsi_cmd_upiu(lrbp, upiu_flags);
2453 * ufshcd_upiu_wlun_to_scsi_wlun - maps UPIU W-LUN id to SCSI W-LUN ID
2454 * @upiu_wlun_id: UPIU W-LUN id
2456 * Returns SCSI W-LUN id
2458 static inline u16 ufshcd_upiu_wlun_to_scsi_wlun(u8 upiu_wlun_id)
2460 return (upiu_wlun_id & ~UFS_UPIU_WLUN_ID) | SCSI_W_LUN_BASE;
2463 static void ufshcd_init_lrb(struct ufs_hba *hba, struct ufshcd_lrb *lrb, int i)
2465 struct utp_transfer_cmd_desc *cmd_descp = hba->ucdl_base_addr;
2466 struct utp_transfer_req_desc *utrdlp = hba->utrdl_base_addr;
2467 dma_addr_t cmd_desc_element_addr = hba->ucdl_dma_addr +
2468 i * sizeof(struct utp_transfer_cmd_desc);
2469 u16 response_offset = offsetof(struct utp_transfer_cmd_desc,
2471 u16 prdt_offset = offsetof(struct utp_transfer_cmd_desc, prd_table);
2473 lrb->utr_descriptor_ptr = utrdlp + i;
2474 lrb->utrd_dma_addr = hba->utrdl_dma_addr +
2475 i * sizeof(struct utp_transfer_req_desc);
2476 lrb->ucd_req_ptr = (struct utp_upiu_req *)(cmd_descp + i);
2477 lrb->ucd_req_dma_addr = cmd_desc_element_addr;
2478 lrb->ucd_rsp_ptr = (struct utp_upiu_rsp *)cmd_descp[i].response_upiu;
2479 lrb->ucd_rsp_dma_addr = cmd_desc_element_addr + response_offset;
2480 lrb->ucd_prdt_ptr = (struct ufshcd_sg_entry *)cmd_descp[i].prd_table;
2481 lrb->ucd_prdt_dma_addr = cmd_desc_element_addr + prdt_offset;
2485 * ufshcd_queuecommand - main entry point for SCSI requests
2486 * @host: SCSI host pointer
2487 * @cmd: command from SCSI Midlayer
2489 * Returns 0 for success, non-zero in case of failure
2491 static int ufshcd_queuecommand(struct Scsi_Host *host, struct scsi_cmnd *cmd)
2493 struct ufshcd_lrb *lrbp;
2494 struct ufs_hba *hba;
2495 unsigned long flags;
2499 hba = shost_priv(host);
2501 tag = cmd->request->tag;
2502 if (!ufshcd_valid_tag(hba, tag)) {
2504 "%s: invalid command tag %d: cmd=0x%p, cmd->request=0x%p",
2505 __func__, tag, cmd, cmd->request);
2509 if (!down_read_trylock(&hba->clk_scaling_lock))
2510 return SCSI_MLQUEUE_HOST_BUSY;
2512 spin_lock_irqsave(hba->host->host_lock, flags);
2513 switch (hba->ufshcd_state) {
2514 case UFSHCD_STATE_OPERATIONAL:
2516 case UFSHCD_STATE_EH_SCHEDULED:
2517 case UFSHCD_STATE_RESET:
2518 err = SCSI_MLQUEUE_HOST_BUSY;
2520 case UFSHCD_STATE_ERROR:
2521 set_host_byte(cmd, DID_ERROR);
2522 cmd->scsi_done(cmd);
2525 dev_WARN_ONCE(hba->dev, 1, "%s: invalid state %d\n",
2526 __func__, hba->ufshcd_state);
2527 set_host_byte(cmd, DID_BAD_TARGET);
2528 cmd->scsi_done(cmd);
2532 /* if error handling is in progress, don't issue commands */
2533 if (ufshcd_eh_in_progress(hba)) {
2534 set_host_byte(cmd, DID_ERROR);
2535 cmd->scsi_done(cmd);
2538 spin_unlock_irqrestore(hba->host->host_lock, flags);
2540 hba->req_abort_count = 0;
2542 err = ufshcd_hold(hba, true);
2544 err = SCSI_MLQUEUE_HOST_BUSY;
2547 WARN_ON(hba->clk_gating.state != CLKS_ON);
2549 lrbp = &hba->lrb[tag];
2553 lrbp->sense_bufflen = UFS_SENSE_SIZE;
2554 lrbp->sense_buffer = cmd->sense_buffer;
2555 lrbp->task_tag = tag;
2556 lrbp->lun = ufshcd_scsi_to_upiu_lun(cmd->device->lun);
2557 lrbp->intr_cmd = !ufshcd_is_intr_aggr_allowed(hba) ? true : false;
2559 ufshcd_prepare_lrbp_crypto(cmd->request, lrbp);
2561 lrbp->req_abort_skip = false;
2563 ufshcd_comp_scsi_upiu(hba, lrbp);
2565 err = ufshcd_map_sg(hba, lrbp);
2568 ufshcd_release(hba);
2571 /* Make sure descriptors are ready before ringing the doorbell */
2574 /* issue command to the controller */
2575 spin_lock_irqsave(hba->host->host_lock, flags);
2576 ufshcd_send_command(hba, tag);
2578 spin_unlock_irqrestore(hba->host->host_lock, flags);
2580 up_read(&hba->clk_scaling_lock);
2584 static int ufshcd_compose_dev_cmd(struct ufs_hba *hba,
2585 struct ufshcd_lrb *lrbp, enum dev_cmd_type cmd_type, int tag)
2588 lrbp->sense_bufflen = 0;
2589 lrbp->sense_buffer = NULL;
2590 lrbp->task_tag = tag;
2591 lrbp->lun = 0; /* device management cmd is not specific to any LUN */
2592 lrbp->intr_cmd = true; /* No interrupt aggregation */
2593 ufshcd_prepare_lrbp_crypto(NULL, lrbp);
2594 hba->dev_cmd.type = cmd_type;
2596 return ufshcd_comp_devman_upiu(hba, lrbp);
2600 ufshcd_clear_cmd(struct ufs_hba *hba, int tag)
2603 unsigned long flags;
2604 u32 mask = 1 << tag;
2606 /* clear outstanding transaction before retry */
2607 spin_lock_irqsave(hba->host->host_lock, flags);
2608 ufshcd_utrl_clear(hba, tag);
2609 spin_unlock_irqrestore(hba->host->host_lock, flags);
2612 * wait for for h/w to clear corresponding bit in door-bell.
2613 * max. wait is 1 sec.
2615 err = ufshcd_wait_for_register(hba,
2616 REG_UTP_TRANSFER_REQ_DOOR_BELL,
2617 mask, ~mask, 1000, 1000);
2623 ufshcd_check_query_response(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
2625 struct ufs_query_res *query_res = &hba->dev_cmd.query.response;
2627 /* Get the UPIU response */
2628 query_res->response = ufshcd_get_rsp_upiu_result(lrbp->ucd_rsp_ptr) >>
2629 UPIU_RSP_CODE_OFFSET;
2630 return query_res->response;
2634 * ufshcd_dev_cmd_completion() - handles device management command responses
2635 * @hba: per adapter instance
2636 * @lrbp: pointer to local reference block
2639 ufshcd_dev_cmd_completion(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
2644 hba->ufs_stats.last_hibern8_exit_tstamp = ktime_set(0, 0);
2645 resp = ufshcd_get_req_rsp(lrbp->ucd_rsp_ptr);
2648 case UPIU_TRANSACTION_NOP_IN:
2649 if (hba->dev_cmd.type != DEV_CMD_TYPE_NOP) {
2651 dev_err(hba->dev, "%s: unexpected response %x\n",
2655 case UPIU_TRANSACTION_QUERY_RSP:
2656 err = ufshcd_check_query_response(hba, lrbp);
2658 err = ufshcd_copy_query_response(hba, lrbp);
2660 case UPIU_TRANSACTION_REJECT_UPIU:
2661 /* TODO: handle Reject UPIU Response */
2663 dev_err(hba->dev, "%s: Reject UPIU not fully implemented\n",
2668 dev_err(hba->dev, "%s: Invalid device management cmd response: %x\n",
2676 static int ufshcd_wait_for_dev_cmd(struct ufs_hba *hba,
2677 struct ufshcd_lrb *lrbp, int max_timeout)
2680 unsigned long time_left;
2681 unsigned long flags;
2683 time_left = wait_for_completion_timeout(hba->dev_cmd.complete,
2684 msecs_to_jiffies(max_timeout));
2686 /* Make sure descriptors are ready before ringing the doorbell */
2688 spin_lock_irqsave(hba->host->host_lock, flags);
2689 hba->dev_cmd.complete = NULL;
2690 if (likely(time_left)) {
2691 err = ufshcd_get_tr_ocs(lrbp);
2693 err = ufshcd_dev_cmd_completion(hba, lrbp);
2695 spin_unlock_irqrestore(hba->host->host_lock, flags);
2699 dev_dbg(hba->dev, "%s: dev_cmd request timedout, tag %d\n",
2700 __func__, lrbp->task_tag);
2701 if (!ufshcd_clear_cmd(hba, lrbp->task_tag))
2702 /* successfully cleared the command, retry if needed */
2705 * in case of an error, after clearing the doorbell,
2706 * we also need to clear the outstanding_request
2709 ufshcd_outstanding_req_clear(hba, lrbp->task_tag);
2716 * ufshcd_exec_dev_cmd - API for sending device management requests
2718 * @cmd_type: specifies the type (NOP, Query...)
2719 * @timeout: time in seconds
2721 * NOTE: Since there is only one available tag for device management commands,
2722 * it is expected you hold the hba->dev_cmd.lock mutex.
2724 static int ufshcd_exec_dev_cmd(struct ufs_hba *hba,
2725 enum dev_cmd_type cmd_type, int timeout)
2727 struct request_queue *q = hba->cmd_queue;
2728 struct request *req;
2729 struct ufshcd_lrb *lrbp;
2732 struct completion wait;
2733 unsigned long flags;
2735 down_read(&hba->clk_scaling_lock);
2738 * Get free slot, sleep if slots are unavailable.
2739 * Even though we use wait_event() which sleeps indefinitely,
2740 * the maximum wait time is bounded by SCSI request timeout.
2742 req = blk_get_request(q, REQ_OP_DRV_OUT, 0);
2748 WARN_ON_ONCE(!ufshcd_valid_tag(hba, tag));
2750 init_completion(&wait);
2751 lrbp = &hba->lrb[tag];
2753 err = ufshcd_compose_dev_cmd(hba, lrbp, cmd_type, tag);
2757 hba->dev_cmd.complete = &wait;
2759 ufshcd_add_query_upiu_trace(hba, tag, "query_send");
2760 /* Make sure descriptors are ready before ringing the doorbell */
2762 spin_lock_irqsave(hba->host->host_lock, flags);
2763 ufshcd_send_command(hba, tag);
2764 spin_unlock_irqrestore(hba->host->host_lock, flags);
2766 err = ufshcd_wait_for_dev_cmd(hba, lrbp, timeout);
2768 ufshcd_add_query_upiu_trace(hba, tag,
2769 err ? "query_complete_err" : "query_complete");
2772 blk_put_request(req);
2774 up_read(&hba->clk_scaling_lock);
2779 * ufshcd_init_query() - init the query response and request parameters
2780 * @hba: per-adapter instance
2781 * @request: address of the request pointer to be initialized
2782 * @response: address of the response pointer to be initialized
2783 * @opcode: operation to perform
2784 * @idn: flag idn to access
2785 * @index: LU number to access
2786 * @selector: query/flag/descriptor further identification
2788 static inline void ufshcd_init_query(struct ufs_hba *hba,
2789 struct ufs_query_req **request, struct ufs_query_res **response,
2790 enum query_opcode opcode, u8 idn, u8 index, u8 selector)
2792 *request = &hba->dev_cmd.query.request;
2793 *response = &hba->dev_cmd.query.response;
2794 memset(*request, 0, sizeof(struct ufs_query_req));
2795 memset(*response, 0, sizeof(struct ufs_query_res));
2796 (*request)->upiu_req.opcode = opcode;
2797 (*request)->upiu_req.idn = idn;
2798 (*request)->upiu_req.index = index;
2799 (*request)->upiu_req.selector = selector;
2802 static int ufshcd_query_flag_retry(struct ufs_hba *hba,
2803 enum query_opcode opcode, enum flag_idn idn, u8 index, bool *flag_res)
2808 for (retries = 0; retries < QUERY_REQ_RETRIES; retries++) {
2809 ret = ufshcd_query_flag(hba, opcode, idn, index, flag_res);
2812 "%s: failed with error %d, retries %d\n",
2813 __func__, ret, retries);
2820 "%s: query attribute, opcode %d, idn %d, failed with error %d after %d retires\n",
2821 __func__, opcode, idn, ret, retries);
2826 * ufshcd_query_flag() - API function for sending flag query requests
2827 * @hba: per-adapter instance
2828 * @opcode: flag query to perform
2829 * @idn: flag idn to access
2830 * @index: flag index to access
2831 * @flag_res: the flag value after the query request completes
2833 * Returns 0 for success, non-zero in case of failure
2835 int ufshcd_query_flag(struct ufs_hba *hba, enum query_opcode opcode,
2836 enum flag_idn idn, u8 index, bool *flag_res)
2838 struct ufs_query_req *request = NULL;
2839 struct ufs_query_res *response = NULL;
2840 int err, selector = 0;
2841 int timeout = QUERY_REQ_TIMEOUT;
2845 ufshcd_hold(hba, false);
2846 mutex_lock(&hba->dev_cmd.lock);
2847 ufshcd_init_query(hba, &request, &response, opcode, idn, index,
2851 case UPIU_QUERY_OPCODE_SET_FLAG:
2852 case UPIU_QUERY_OPCODE_CLEAR_FLAG:
2853 case UPIU_QUERY_OPCODE_TOGGLE_FLAG:
2854 request->query_func = UPIU_QUERY_FUNC_STANDARD_WRITE_REQUEST;
2856 case UPIU_QUERY_OPCODE_READ_FLAG:
2857 request->query_func = UPIU_QUERY_FUNC_STANDARD_READ_REQUEST;
2859 /* No dummy reads */
2860 dev_err(hba->dev, "%s: Invalid argument for read request\n",
2868 "%s: Expected query flag opcode but got = %d\n",
2874 err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_QUERY, timeout);
2878 "%s: Sending flag query for idn %d failed, err = %d\n",
2879 __func__, idn, err);
2884 *flag_res = (be32_to_cpu(response->upiu_res.value) &
2885 MASK_QUERY_UPIU_FLAG_LOC) & 0x1;
2888 mutex_unlock(&hba->dev_cmd.lock);
2889 ufshcd_release(hba);
2894 * ufshcd_query_attr - API function for sending attribute requests
2895 * @hba: per-adapter instance
2896 * @opcode: attribute opcode
2897 * @idn: attribute idn to access
2898 * @index: index field
2899 * @selector: selector field
2900 * @attr_val: the attribute value after the query request completes
2902 * Returns 0 for success, non-zero in case of failure
2904 int ufshcd_query_attr(struct ufs_hba *hba, enum query_opcode opcode,
2905 enum attr_idn idn, u8 index, u8 selector, u32 *attr_val)
2907 struct ufs_query_req *request = NULL;
2908 struct ufs_query_res *response = NULL;
2913 ufshcd_hold(hba, false);
2915 dev_err(hba->dev, "%s: attribute value required for opcode 0x%x\n",
2921 mutex_lock(&hba->dev_cmd.lock);
2922 ufshcd_init_query(hba, &request, &response, opcode, idn, index,
2926 case UPIU_QUERY_OPCODE_WRITE_ATTR:
2927 request->query_func = UPIU_QUERY_FUNC_STANDARD_WRITE_REQUEST;
2928 request->upiu_req.value = cpu_to_be32(*attr_val);
2930 case UPIU_QUERY_OPCODE_READ_ATTR:
2931 request->query_func = UPIU_QUERY_FUNC_STANDARD_READ_REQUEST;
2934 dev_err(hba->dev, "%s: Expected query attr opcode but got = 0x%.2x\n",
2940 err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_QUERY, QUERY_REQ_TIMEOUT);
2943 dev_err(hba->dev, "%s: opcode 0x%.2x for idn %d failed, index %d, err = %d\n",
2944 __func__, opcode, idn, index, err);
2948 *attr_val = be32_to_cpu(response->upiu_res.value);
2951 mutex_unlock(&hba->dev_cmd.lock);
2953 ufshcd_release(hba);
2958 * ufshcd_query_attr_retry() - API function for sending query
2959 * attribute with retries
2960 * @hba: per-adapter instance
2961 * @opcode: attribute opcode
2962 * @idn: attribute idn to access
2963 * @index: index field
2964 * @selector: selector field
2965 * @attr_val: the attribute value after the query request
2968 * Returns 0 for success, non-zero in case of failure
2970 static int ufshcd_query_attr_retry(struct ufs_hba *hba,
2971 enum query_opcode opcode, enum attr_idn idn, u8 index, u8 selector,
2977 for (retries = QUERY_REQ_RETRIES; retries > 0; retries--) {
2978 ret = ufshcd_query_attr(hba, opcode, idn, index,
2979 selector, attr_val);
2981 dev_dbg(hba->dev, "%s: failed with error %d, retries %d\n",
2982 __func__, ret, retries);
2989 "%s: query attribute, idn %d, failed with error %d after %d retires\n",
2990 __func__, idn, ret, QUERY_REQ_RETRIES);
2994 static int __ufshcd_query_descriptor(struct ufs_hba *hba,
2995 enum query_opcode opcode, enum desc_idn idn, u8 index,
2996 u8 selector, u8 *desc_buf, int *buf_len)
2998 struct ufs_query_req *request = NULL;
2999 struct ufs_query_res *response = NULL;
3004 ufshcd_hold(hba, false);
3006 dev_err(hba->dev, "%s: descriptor buffer required for opcode 0x%x\n",
3012 if (*buf_len < QUERY_DESC_MIN_SIZE || *buf_len > QUERY_DESC_MAX_SIZE) {
3013 dev_err(hba->dev, "%s: descriptor buffer size (%d) is out of range\n",
3014 __func__, *buf_len);
3019 mutex_lock(&hba->dev_cmd.lock);
3020 ufshcd_init_query(hba, &request, &response, opcode, idn, index,
3022 hba->dev_cmd.query.descriptor = desc_buf;
3023 request->upiu_req.length = cpu_to_be16(*buf_len);
3026 case UPIU_QUERY_OPCODE_WRITE_DESC:
3027 request->query_func = UPIU_QUERY_FUNC_STANDARD_WRITE_REQUEST;
3029 case UPIU_QUERY_OPCODE_READ_DESC:
3030 request->query_func = UPIU_QUERY_FUNC_STANDARD_READ_REQUEST;
3034 "%s: Expected query descriptor opcode but got = 0x%.2x\n",
3040 err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_QUERY, QUERY_REQ_TIMEOUT);
3043 dev_err(hba->dev, "%s: opcode 0x%.2x for idn %d failed, index %d, err = %d\n",
3044 __func__, opcode, idn, index, err);
3048 *buf_len = be16_to_cpu(response->upiu_res.length);
3051 hba->dev_cmd.query.descriptor = NULL;
3052 mutex_unlock(&hba->dev_cmd.lock);
3054 ufshcd_release(hba);
3059 * ufshcd_query_descriptor_retry - API function for sending descriptor requests
3060 * @hba: per-adapter instance
3061 * @opcode: attribute opcode
3062 * @idn: attribute idn to access
3063 * @index: index field
3064 * @selector: selector field
3065 * @desc_buf: the buffer that contains the descriptor
3066 * @buf_len: length parameter passed to the device
3068 * Returns 0 for success, non-zero in case of failure.
3069 * The buf_len parameter will contain, on return, the length parameter
3070 * received on the response.
3072 int ufshcd_query_descriptor_retry(struct ufs_hba *hba,
3073 enum query_opcode opcode,
3074 enum desc_idn idn, u8 index,
3076 u8 *desc_buf, int *buf_len)
3081 for (retries = QUERY_REQ_RETRIES; retries > 0; retries--) {
3082 err = __ufshcd_query_descriptor(hba, opcode, idn, index,
3083 selector, desc_buf, buf_len);
3084 if (!err || err == -EINVAL)
3092 * ufshcd_map_desc_id_to_length - map descriptor IDN to its length
3093 * @hba: Pointer to adapter instance
3094 * @desc_id: descriptor idn value
3095 * @desc_len: mapped desc length (out)
3097 void ufshcd_map_desc_id_to_length(struct ufs_hba *hba, enum desc_idn desc_id,
3100 if (desc_id >= QUERY_DESC_IDN_MAX || desc_id == QUERY_DESC_IDN_RFU_0 ||
3101 desc_id == QUERY_DESC_IDN_RFU_1)
3104 *desc_len = hba->desc_size[desc_id];
3106 EXPORT_SYMBOL(ufshcd_map_desc_id_to_length);
3108 static void ufshcd_update_desc_length(struct ufs_hba *hba,
3109 enum desc_idn desc_id, int desc_index,
3110 unsigned char desc_len)
3112 if (hba->desc_size[desc_id] == QUERY_DESC_MAX_SIZE &&
3113 desc_id != QUERY_DESC_IDN_STRING && desc_index != UFS_RPMB_UNIT)
3114 /* For UFS 3.1, the normal unit descriptor is 10 bytes larger
3115 * than the RPMB unit, however, both descriptors share the same
3116 * desc_idn, to cover both unit descriptors with one length, we
3117 * choose the normal unit descriptor length by desc_index.
3119 hba->desc_size[desc_id] = desc_len;
3123 * ufshcd_read_desc_param - read the specified descriptor parameter
3124 * @hba: Pointer to adapter instance
3125 * @desc_id: descriptor idn value
3126 * @desc_index: descriptor index
3127 * @param_offset: offset of the parameter to read
3128 * @param_read_buf: pointer to buffer where parameter would be read
3129 * @param_size: sizeof(param_read_buf)
3131 * Return 0 in case of success, non-zero otherwise
3133 int ufshcd_read_desc_param(struct ufs_hba *hba,
3134 enum desc_idn desc_id,
3143 bool is_kmalloc = true;
3146 if (desc_id >= QUERY_DESC_IDN_MAX || !param_size)
3149 /* Get the length of descriptor */
3150 ufshcd_map_desc_id_to_length(hba, desc_id, &buff_len);
3152 dev_err(hba->dev, "%s: Failed to get desc length", __func__);
3156 /* Check whether we need temp memory */
3157 if (param_offset != 0 || param_size < buff_len) {
3158 desc_buf = kmalloc(buff_len, GFP_KERNEL);
3162 desc_buf = param_read_buf;
3166 /* Request for full descriptor */
3167 ret = ufshcd_query_descriptor_retry(hba, UPIU_QUERY_OPCODE_READ_DESC,
3168 desc_id, desc_index, 0,
3169 desc_buf, &buff_len);
3172 dev_err(hba->dev, "%s: Failed reading descriptor. desc_id %d, desc_index %d, param_offset %d, ret %d",
3173 __func__, desc_id, desc_index, param_offset, ret);
3178 if (desc_buf[QUERY_DESC_DESC_TYPE_OFFSET] != desc_id) {
3179 dev_err(hba->dev, "%s: invalid desc_id %d in descriptor header",
3180 __func__, desc_buf[QUERY_DESC_DESC_TYPE_OFFSET]);
3185 /* Update descriptor length */
3186 buff_len = desc_buf[QUERY_DESC_LENGTH_OFFSET];
3187 ufshcd_update_desc_length(hba, desc_id, desc_index, buff_len);
3189 /* Check wherher we will not copy more data, than available */
3190 if (is_kmalloc && (param_offset + param_size) > buff_len)
3191 param_size = buff_len - param_offset;
3194 memcpy(param_read_buf, &desc_buf[param_offset], param_size);
3202 * struct uc_string_id - unicode string
3204 * @len: size of this descriptor inclusive
3205 * @type: descriptor type
3206 * @uc: unicode string character
3208 struct uc_string_id {
3214 /* replace non-printable or non-ASCII characters with spaces */
3215 static inline char ufshcd_remove_non_printable(u8 ch)
3217 return (ch >= 0x20 && ch <= 0x7e) ? ch : ' ';
3221 * ufshcd_read_string_desc - read string descriptor
3222 * @hba: pointer to adapter instance
3223 * @desc_index: descriptor index
3224 * @buf: pointer to buffer where descriptor would be read,
3225 * the caller should free the memory.
3226 * @ascii: if true convert from unicode to ascii characters
3227 * null terminated string.
3230 * * string size on success.
3231 * * -ENOMEM: on allocation failure
3232 * * -EINVAL: on a wrong parameter
3234 int ufshcd_read_string_desc(struct ufs_hba *hba, u8 desc_index,
3235 u8 **buf, bool ascii)
3237 struct uc_string_id *uc_str;
3244 uc_str = kzalloc(QUERY_DESC_MAX_SIZE, GFP_KERNEL);
3248 ret = ufshcd_read_desc_param(hba, QUERY_DESC_IDN_STRING, desc_index, 0,
3249 (u8 *)uc_str, QUERY_DESC_MAX_SIZE);
3251 dev_err(hba->dev, "Reading String Desc failed after %d retries. err = %d\n",
3252 QUERY_REQ_RETRIES, ret);
3257 if (uc_str->len <= QUERY_DESC_HDR_SIZE) {
3258 dev_dbg(hba->dev, "String Desc is of zero length\n");
3267 /* remove header and divide by 2 to move from UTF16 to UTF8 */
3268 ascii_len = (uc_str->len - QUERY_DESC_HDR_SIZE) / 2 + 1;
3269 str = kzalloc(ascii_len, GFP_KERNEL);
3276 * the descriptor contains string in UTF16 format
3277 * we need to convert to utf-8 so it can be displayed
3279 ret = utf16s_to_utf8s(uc_str->uc,
3280 uc_str->len - QUERY_DESC_HDR_SIZE,
3281 UTF16_BIG_ENDIAN, str, ascii_len);
3283 /* replace non-printable or non-ASCII characters with spaces */
3284 for (i = 0; i < ret; i++)
3285 str[i] = ufshcd_remove_non_printable(str[i]);
3290 str = kmemdup(uc_str, uc_str->len, GFP_KERNEL);
3304 * ufshcd_read_unit_desc_param - read the specified unit descriptor parameter
3305 * @hba: Pointer to adapter instance
3307 * @param_offset: offset of the parameter to read
3308 * @param_read_buf: pointer to buffer where parameter would be read
3309 * @param_size: sizeof(param_read_buf)
3311 * Return 0 in case of success, non-zero otherwise
3313 static inline int ufshcd_read_unit_desc_param(struct ufs_hba *hba,
3315 enum unit_desc_param param_offset,
3320 * Unit descriptors are only available for general purpose LUs (LUN id
3321 * from 0 to 7) and RPMB Well known LU.
3323 if (!ufs_is_valid_unit_desc_lun(&hba->dev_info, lun))
3326 return ufshcd_read_desc_param(hba, QUERY_DESC_IDN_UNIT, lun,
3327 param_offset, param_read_buf, param_size);
3330 static int ufshcd_get_ref_clk_gating_wait(struct ufs_hba *hba)
3333 u32 gating_wait = UFSHCD_REF_CLK_GATING_WAIT_US;
3335 if (hba->dev_info.wspecversion >= 0x300) {
3336 err = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
3337 QUERY_ATTR_IDN_REF_CLK_GATING_WAIT_TIME, 0, 0,
3340 dev_err(hba->dev, "Failed reading bRefClkGatingWait. err = %d, use default %uus\n",
3343 if (gating_wait == 0) {
3344 gating_wait = UFSHCD_REF_CLK_GATING_WAIT_US;
3345 dev_err(hba->dev, "Undefined ref clk gating wait time, use default %uus\n",
3349 hba->dev_info.clk_gating_wait_us = gating_wait;
3356 * ufshcd_memory_alloc - allocate memory for host memory space data structures
3357 * @hba: per adapter instance
3359 * 1. Allocate DMA memory for Command Descriptor array
3360 * Each command descriptor consist of Command UPIU, Response UPIU and PRDT
3361 * 2. Allocate DMA memory for UTP Transfer Request Descriptor List (UTRDL).
3362 * 3. Allocate DMA memory for UTP Task Management Request Descriptor List
3364 * 4. Allocate memory for local reference block(lrb).
3366 * Returns 0 for success, non-zero in case of failure
3368 static int ufshcd_memory_alloc(struct ufs_hba *hba)
3370 size_t utmrdl_size, utrdl_size, ucdl_size;
3372 /* Allocate memory for UTP command descriptors */
3373 ucdl_size = (sizeof(struct utp_transfer_cmd_desc) * hba->nutrs);
3374 hba->ucdl_base_addr = dmam_alloc_coherent(hba->dev,
3376 &hba->ucdl_dma_addr,
3380 * UFSHCI requires UTP command descriptor to be 128 byte aligned.
3381 * make sure hba->ucdl_dma_addr is aligned to PAGE_SIZE
3382 * if hba->ucdl_dma_addr is aligned to PAGE_SIZE, then it will
3383 * be aligned to 128 bytes as well
3385 if (!hba->ucdl_base_addr ||
3386 WARN_ON(hba->ucdl_dma_addr & (PAGE_SIZE - 1))) {
3388 "Command Descriptor Memory allocation failed\n");
3393 * Allocate memory for UTP Transfer descriptors
3394 * UFSHCI requires 1024 byte alignment of UTRD
3396 utrdl_size = (sizeof(struct utp_transfer_req_desc) * hba->nutrs);
3397 hba->utrdl_base_addr = dmam_alloc_coherent(hba->dev,
3399 &hba->utrdl_dma_addr,
3401 if (!hba->utrdl_base_addr ||
3402 WARN_ON(hba->utrdl_dma_addr & (PAGE_SIZE - 1))) {
3404 "Transfer Descriptor Memory allocation failed\n");
3409 * Allocate memory for UTP Task Management descriptors
3410 * UFSHCI requires 1024 byte alignment of UTMRD
3412 utmrdl_size = sizeof(struct utp_task_req_desc) * hba->nutmrs;
3413 hba->utmrdl_base_addr = dmam_alloc_coherent(hba->dev,
3415 &hba->utmrdl_dma_addr,
3417 if (!hba->utmrdl_base_addr ||
3418 WARN_ON(hba->utmrdl_dma_addr & (PAGE_SIZE - 1))) {
3420 "Task Management Descriptor Memory allocation failed\n");
3424 /* Allocate memory for local reference block */
3425 hba->lrb = devm_kcalloc(hba->dev,
3426 hba->nutrs, sizeof(struct ufshcd_lrb),
3429 dev_err(hba->dev, "LRB Memory allocation failed\n");
3438 * ufshcd_host_memory_configure - configure local reference block with
3440 * @hba: per adapter instance
3442 * Configure Host memory space
3443 * 1. Update Corresponding UTRD.UCDBA and UTRD.UCDBAU with UCD DMA
3445 * 2. Update each UTRD with Response UPIU offset, Response UPIU length
3447 * 3. Save the corresponding addresses of UTRD, UCD.CMD, UCD.RSP and UCD.PRDT
3448 * into local reference block.
3450 static void ufshcd_host_memory_configure(struct ufs_hba *hba)
3452 struct utp_transfer_req_desc *utrdlp;
3453 dma_addr_t cmd_desc_dma_addr;
3454 dma_addr_t cmd_desc_element_addr;
3455 u16 response_offset;
3460 utrdlp = hba->utrdl_base_addr;
3463 offsetof(struct utp_transfer_cmd_desc, response_upiu);
3465 offsetof(struct utp_transfer_cmd_desc, prd_table);
3467 cmd_desc_size = sizeof(struct utp_transfer_cmd_desc);
3468 cmd_desc_dma_addr = hba->ucdl_dma_addr;
3470 for (i = 0; i < hba->nutrs; i++) {
3471 /* Configure UTRD with command descriptor base address */
3472 cmd_desc_element_addr =
3473 (cmd_desc_dma_addr + (cmd_desc_size * i));
3474 utrdlp[i].command_desc_base_addr_lo =
3475 cpu_to_le32(lower_32_bits(cmd_desc_element_addr));
3476 utrdlp[i].command_desc_base_addr_hi =
3477 cpu_to_le32(upper_32_bits(cmd_desc_element_addr));
3479 /* Response upiu and prdt offset should be in double words */
3480 if (hba->quirks & UFSHCD_QUIRK_PRDT_BYTE_GRAN) {
3481 utrdlp[i].response_upiu_offset =
3482 cpu_to_le16(response_offset);
3483 utrdlp[i].prd_table_offset =
3484 cpu_to_le16(prdt_offset);
3485 utrdlp[i].response_upiu_length =
3486 cpu_to_le16(ALIGNED_UPIU_SIZE);
3488 utrdlp[i].response_upiu_offset =
3489 cpu_to_le16(response_offset >> 2);
3490 utrdlp[i].prd_table_offset =
3491 cpu_to_le16(prdt_offset >> 2);
3492 utrdlp[i].response_upiu_length =
3493 cpu_to_le16(ALIGNED_UPIU_SIZE >> 2);
3496 ufshcd_init_lrb(hba, &hba->lrb[i], i);
3501 * ufshcd_dme_link_startup - Notify Unipro to perform link startup
3502 * @hba: per adapter instance
3504 * UIC_CMD_DME_LINK_STARTUP command must be issued to Unipro layer,
3505 * in order to initialize the Unipro link startup procedure.
3506 * Once the Unipro links are up, the device connected to the controller
3509 * Returns 0 on success, non-zero value on failure
3511 static int ufshcd_dme_link_startup(struct ufs_hba *hba)
3513 struct uic_command uic_cmd = {0};
3516 uic_cmd.command = UIC_CMD_DME_LINK_STARTUP;
3518 ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
3521 "dme-link-startup: error code %d\n", ret);
3525 * ufshcd_dme_reset - UIC command for DME_RESET
3526 * @hba: per adapter instance
3528 * DME_RESET command is issued in order to reset UniPro stack.
3529 * This function now deals with cold reset.
3531 * Returns 0 on success, non-zero value on failure
3533 static int ufshcd_dme_reset(struct ufs_hba *hba)
3535 struct uic_command uic_cmd = {0};
3538 uic_cmd.command = UIC_CMD_DME_RESET;
3540 ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
3543 "dme-reset: error code %d\n", ret);
3549 * ufshcd_dme_enable - UIC command for DME_ENABLE
3550 * @hba: per adapter instance
3552 * DME_ENABLE command is issued in order to enable UniPro stack.
3554 * Returns 0 on success, non-zero value on failure
3556 static int ufshcd_dme_enable(struct ufs_hba *hba)
3558 struct uic_command uic_cmd = {0};
3561 uic_cmd.command = UIC_CMD_DME_ENABLE;
3563 ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
3566 "dme-reset: error code %d\n", ret);
3571 static inline void ufshcd_add_delay_before_dme_cmd(struct ufs_hba *hba)
3573 #define MIN_DELAY_BEFORE_DME_CMDS_US 1000
3574 unsigned long min_sleep_time_us;
3576 if (!(hba->quirks & UFSHCD_QUIRK_DELAY_BEFORE_DME_CMDS))
3580 * last_dme_cmd_tstamp will be 0 only for 1st call to
3583 if (unlikely(!ktime_to_us(hba->last_dme_cmd_tstamp))) {
3584 min_sleep_time_us = MIN_DELAY_BEFORE_DME_CMDS_US;
3586 unsigned long delta =
3587 (unsigned long) ktime_to_us(
3588 ktime_sub(ktime_get(),
3589 hba->last_dme_cmd_tstamp));
3591 if (delta < MIN_DELAY_BEFORE_DME_CMDS_US)
3593 MIN_DELAY_BEFORE_DME_CMDS_US - delta;
3595 return; /* no more delay required */
3598 /* allow sleep for extra 50us if needed */
3599 usleep_range(min_sleep_time_us, min_sleep_time_us + 50);
3603 * ufshcd_dme_set_attr - UIC command for DME_SET, DME_PEER_SET
3604 * @hba: per adapter instance
3605 * @attr_sel: uic command argument1
3606 * @attr_set: attribute set type as uic command argument2
3607 * @mib_val: setting value as uic command argument3
3608 * @peer: indicate whether peer or local
3610 * Returns 0 on success, non-zero value on failure
3612 int ufshcd_dme_set_attr(struct ufs_hba *hba, u32 attr_sel,
3613 u8 attr_set, u32 mib_val, u8 peer)
3615 struct uic_command uic_cmd = {0};
3616 static const char *const action[] = {
3620 const char *set = action[!!peer];
3622 int retries = UFS_UIC_COMMAND_RETRIES;
3624 uic_cmd.command = peer ?
3625 UIC_CMD_DME_PEER_SET : UIC_CMD_DME_SET;
3626 uic_cmd.argument1 = attr_sel;
3627 uic_cmd.argument2 = UIC_ARG_ATTR_TYPE(attr_set);
3628 uic_cmd.argument3 = mib_val;
3631 /* for peer attributes we retry upon failure */
3632 ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
3634 dev_dbg(hba->dev, "%s: attr-id 0x%x val 0x%x error code %d\n",
3635 set, UIC_GET_ATTR_ID(attr_sel), mib_val, ret);
3636 } while (ret && peer && --retries);
3639 dev_err(hba->dev, "%s: attr-id 0x%x val 0x%x failed %d retries\n",
3640 set, UIC_GET_ATTR_ID(attr_sel), mib_val,
3641 UFS_UIC_COMMAND_RETRIES - retries);
3645 EXPORT_SYMBOL_GPL(ufshcd_dme_set_attr);
3648 * ufshcd_dme_get_attr - UIC command for DME_GET, DME_PEER_GET
3649 * @hba: per adapter instance
3650 * @attr_sel: uic command argument1
3651 * @mib_val: the value of the attribute as returned by the UIC command
3652 * @peer: indicate whether peer or local
3654 * Returns 0 on success, non-zero value on failure
3656 int ufshcd_dme_get_attr(struct ufs_hba *hba, u32 attr_sel,
3657 u32 *mib_val, u8 peer)
3659 struct uic_command uic_cmd = {0};
3660 static const char *const action[] = {
3664 const char *get = action[!!peer];
3666 int retries = UFS_UIC_COMMAND_RETRIES;
3667 struct ufs_pa_layer_attr orig_pwr_info;
3668 struct ufs_pa_layer_attr temp_pwr_info;
3669 bool pwr_mode_change = false;
3671 if (peer && (hba->quirks & UFSHCD_QUIRK_DME_PEER_ACCESS_AUTO_MODE)) {
3672 orig_pwr_info = hba->pwr_info;
3673 temp_pwr_info = orig_pwr_info;
3675 if (orig_pwr_info.pwr_tx == FAST_MODE ||
3676 orig_pwr_info.pwr_rx == FAST_MODE) {
3677 temp_pwr_info.pwr_tx = FASTAUTO_MODE;
3678 temp_pwr_info.pwr_rx = FASTAUTO_MODE;
3679 pwr_mode_change = true;
3680 } else if (orig_pwr_info.pwr_tx == SLOW_MODE ||
3681 orig_pwr_info.pwr_rx == SLOW_MODE) {
3682 temp_pwr_info.pwr_tx = SLOWAUTO_MODE;
3683 temp_pwr_info.pwr_rx = SLOWAUTO_MODE;
3684 pwr_mode_change = true;
3686 if (pwr_mode_change) {
3687 ret = ufshcd_change_power_mode(hba, &temp_pwr_info);
3693 uic_cmd.command = peer ?
3694 UIC_CMD_DME_PEER_GET : UIC_CMD_DME_GET;
3695 uic_cmd.argument1 = attr_sel;
3698 /* for peer attributes we retry upon failure */
3699 ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
3701 dev_dbg(hba->dev, "%s: attr-id 0x%x error code %d\n",
3702 get, UIC_GET_ATTR_ID(attr_sel), ret);
3703 } while (ret && peer && --retries);
3706 dev_err(hba->dev, "%s: attr-id 0x%x failed %d retries\n",
3707 get, UIC_GET_ATTR_ID(attr_sel),
3708 UFS_UIC_COMMAND_RETRIES - retries);
3710 if (mib_val && !ret)
3711 *mib_val = uic_cmd.argument3;
3713 if (peer && (hba->quirks & UFSHCD_QUIRK_DME_PEER_ACCESS_AUTO_MODE)
3715 ufshcd_change_power_mode(hba, &orig_pwr_info);
3719 EXPORT_SYMBOL_GPL(ufshcd_dme_get_attr);
3722 * ufshcd_uic_pwr_ctrl - executes UIC commands (which affects the link power
3723 * state) and waits for it to take effect.
3725 * @hba: per adapter instance
3726 * @cmd: UIC command to execute
3728 * DME operations like DME_SET(PA_PWRMODE), DME_HIBERNATE_ENTER &
3729 * DME_HIBERNATE_EXIT commands take some time to take its effect on both host
3730 * and device UniPro link and hence it's final completion would be indicated by
3731 * dedicated status bits in Interrupt Status register (UPMS, UHES, UHXS) in
3732 * addition to normal UIC command completion Status (UCCS). This function only
3733 * returns after the relevant status bits indicate the completion.
3735 * Returns 0 on success, non-zero value on failure
3737 static int ufshcd_uic_pwr_ctrl(struct ufs_hba *hba, struct uic_command *cmd)
3739 struct completion uic_async_done;
3740 unsigned long flags;
3743 bool reenable_intr = false;
3745 mutex_lock(&hba->uic_cmd_mutex);
3746 init_completion(&uic_async_done);
3747 ufshcd_add_delay_before_dme_cmd(hba);
3749 spin_lock_irqsave(hba->host->host_lock, flags);
3750 hba->uic_async_done = &uic_async_done;
3751 if (ufshcd_readl(hba, REG_INTERRUPT_ENABLE) & UIC_COMMAND_COMPL) {
3752 ufshcd_disable_intr(hba, UIC_COMMAND_COMPL);
3754 * Make sure UIC command completion interrupt is disabled before
3755 * issuing UIC command.
3758 reenable_intr = true;
3760 ret = __ufshcd_send_uic_cmd(hba, cmd, false);
3761 spin_unlock_irqrestore(hba->host->host_lock, flags);
3764 "pwr ctrl cmd 0x%x with mode 0x%x uic error %d\n",
3765 cmd->command, cmd->argument3, ret);
3769 if (!wait_for_completion_timeout(hba->uic_async_done,
3770 msecs_to_jiffies(UIC_CMD_TIMEOUT))) {
3772 "pwr ctrl cmd 0x%x with mode 0x%x completion timeout\n",
3773 cmd->command, cmd->argument3);
3778 status = ufshcd_get_upmcrs(hba);
3779 if (status != PWR_LOCAL) {
3781 "pwr ctrl cmd 0x%x failed, host upmcrs:0x%x\n",
3782 cmd->command, status);
3783 ret = (status != PWR_OK) ? status : -1;
3787 ufshcd_print_host_state(hba);
3788 ufshcd_print_pwr_info(hba);
3789 ufshcd_print_host_regs(hba);
3792 spin_lock_irqsave(hba->host->host_lock, flags);
3793 hba->active_uic_cmd = NULL;
3794 hba->uic_async_done = NULL;
3796 ufshcd_enable_intr(hba, UIC_COMMAND_COMPL);
3797 spin_unlock_irqrestore(hba->host->host_lock, flags);
3798 mutex_unlock(&hba->uic_cmd_mutex);
3804 * ufshcd_uic_change_pwr_mode - Perform the UIC power mode chage
3805 * using DME_SET primitives.
3806 * @hba: per adapter instance
3807 * @mode: powr mode value
3809 * Returns 0 on success, non-zero value on failure
3811 static int ufshcd_uic_change_pwr_mode(struct ufs_hba *hba, u8 mode)
3813 struct uic_command uic_cmd = {0};
3816 if (hba->quirks & UFSHCD_QUIRK_BROKEN_PA_RXHSUNTERMCAP) {
3817 ret = ufshcd_dme_set(hba,
3818 UIC_ARG_MIB_SEL(PA_RXHSUNTERMCAP, 0), 1);
3820 dev_err(hba->dev, "%s: failed to enable PA_RXHSUNTERMCAP ret %d\n",
3826 uic_cmd.command = UIC_CMD_DME_SET;
3827 uic_cmd.argument1 = UIC_ARG_MIB(PA_PWRMODE);
3828 uic_cmd.argument3 = mode;
3829 ufshcd_hold(hba, false);
3830 ret = ufshcd_uic_pwr_ctrl(hba, &uic_cmd);
3831 ufshcd_release(hba);
3837 int ufshcd_link_recovery(struct ufs_hba *hba)
3840 unsigned long flags;
3842 spin_lock_irqsave(hba->host->host_lock, flags);
3843 hba->ufshcd_state = UFSHCD_STATE_RESET;
3844 ufshcd_set_eh_in_progress(hba);
3845 spin_unlock_irqrestore(hba->host->host_lock, flags);
3847 /* Reset the attached device */
3848 ufshcd_vops_device_reset(hba);
3850 ret = ufshcd_host_reset_and_restore(hba);
3852 spin_lock_irqsave(hba->host->host_lock, flags);
3854 hba->ufshcd_state = UFSHCD_STATE_ERROR;
3855 ufshcd_clear_eh_in_progress(hba);
3856 spin_unlock_irqrestore(hba->host->host_lock, flags);
3859 dev_err(hba->dev, "%s: link recovery failed, err %d",
3864 EXPORT_SYMBOL_GPL(ufshcd_link_recovery);
3866 static int __ufshcd_uic_hibern8_enter(struct ufs_hba *hba)
3869 struct uic_command uic_cmd = {0};
3870 ktime_t start = ktime_get();
3872 ufshcd_vops_hibern8_notify(hba, UIC_CMD_DME_HIBER_ENTER, PRE_CHANGE);
3874 uic_cmd.command = UIC_CMD_DME_HIBER_ENTER;
3875 ret = ufshcd_uic_pwr_ctrl(hba, &uic_cmd);
3876 trace_ufshcd_profile_hibern8(dev_name(hba->dev), "enter",
3877 ktime_to_us(ktime_sub(ktime_get(), start)), ret);
3882 dev_err(hba->dev, "%s: hibern8 enter failed. ret = %d\n",
3886 * If link recovery fails then return error code returned from
3887 * ufshcd_link_recovery().
3888 * If link recovery succeeds then return -EAGAIN to attempt
3889 * hibern8 enter retry again.
3891 err = ufshcd_link_recovery(hba);
3893 dev_err(hba->dev, "%s: link recovery failed", __func__);
3899 ufshcd_vops_hibern8_notify(hba, UIC_CMD_DME_HIBER_ENTER,
3905 static int ufshcd_uic_hibern8_enter(struct ufs_hba *hba)
3907 int ret = 0, retries;
3909 for (retries = UIC_HIBERN8_ENTER_RETRIES; retries > 0; retries--) {
3910 ret = __ufshcd_uic_hibern8_enter(hba);
3918 int ufshcd_uic_hibern8_exit(struct ufs_hba *hba)
3920 struct uic_command uic_cmd = {0};
3922 ktime_t start = ktime_get();
3924 ufshcd_vops_hibern8_notify(hba, UIC_CMD_DME_HIBER_EXIT, PRE_CHANGE);
3926 uic_cmd.command = UIC_CMD_DME_HIBER_EXIT;
3927 ret = ufshcd_uic_pwr_ctrl(hba, &uic_cmd);
3928 trace_ufshcd_profile_hibern8(dev_name(hba->dev), "exit",
3929 ktime_to_us(ktime_sub(ktime_get(), start)), ret);
3932 dev_err(hba->dev, "%s: hibern8 exit failed. ret = %d\n",
3934 ret = ufshcd_link_recovery(hba);
3936 ufshcd_vops_hibern8_notify(hba, UIC_CMD_DME_HIBER_EXIT,
3938 hba->ufs_stats.last_hibern8_exit_tstamp = ktime_get();
3939 hba->ufs_stats.hibern8_exit_cnt++;
3944 EXPORT_SYMBOL_GPL(ufshcd_uic_hibern8_exit);
3946 void ufshcd_auto_hibern8_update(struct ufs_hba *hba, u32 ahit)
3948 unsigned long flags;
3949 bool update = false;
3951 if (!ufshcd_is_auto_hibern8_supported(hba))
3954 spin_lock_irqsave(hba->host->host_lock, flags);
3955 if (hba->ahit != ahit) {
3959 spin_unlock_irqrestore(hba->host->host_lock, flags);
3961 if (update && !pm_runtime_suspended(hba->dev)) {
3962 pm_runtime_get_sync(hba->dev);
3963 ufshcd_hold(hba, false);
3964 ufshcd_auto_hibern8_enable(hba);
3965 ufshcd_release(hba);
3966 pm_runtime_put(hba->dev);
3969 EXPORT_SYMBOL_GPL(ufshcd_auto_hibern8_update);
3971 void ufshcd_auto_hibern8_enable(struct ufs_hba *hba)
3973 unsigned long flags;
3975 if (!ufshcd_is_auto_hibern8_supported(hba) || !hba->ahit)
3978 spin_lock_irqsave(hba->host->host_lock, flags);
3979 ufshcd_writel(hba, hba->ahit, REG_AUTO_HIBERNATE_IDLE_TIMER);
3980 spin_unlock_irqrestore(hba->host->host_lock, flags);
3984 * ufshcd_init_pwr_info - setting the POR (power on reset)
3985 * values in hba power info
3986 * @hba: per-adapter instance
3988 static void ufshcd_init_pwr_info(struct ufs_hba *hba)
3990 hba->pwr_info.gear_rx = UFS_PWM_G1;
3991 hba->pwr_info.gear_tx = UFS_PWM_G1;
3992 hba->pwr_info.lane_rx = 1;
3993 hba->pwr_info.lane_tx = 1;
3994 hba->pwr_info.pwr_rx = SLOWAUTO_MODE;
3995 hba->pwr_info.pwr_tx = SLOWAUTO_MODE;
3996 hba->pwr_info.hs_rate = 0;
4000 * ufshcd_get_max_pwr_mode - reads the max power mode negotiated with device
4001 * @hba: per-adapter instance
4003 static int ufshcd_get_max_pwr_mode(struct ufs_hba *hba)
4005 struct ufs_pa_layer_attr *pwr_info = &hba->max_pwr_info.info;
4007 if (hba->max_pwr_info.is_valid)
4010 pwr_info->pwr_tx = FAST_MODE;
4011 pwr_info->pwr_rx = FAST_MODE;
4012 pwr_info->hs_rate = PA_HS_MODE_B;
4014 /* Get the connected lane count */
4015 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_CONNECTEDRXDATALANES),
4016 &pwr_info->lane_rx);
4017 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_CONNECTEDTXDATALANES),
4018 &pwr_info->lane_tx);
4020 if (!pwr_info->lane_rx || !pwr_info->lane_tx) {
4021 dev_err(hba->dev, "%s: invalid connected lanes value. rx=%d, tx=%d\n",
4029 * First, get the maximum gears of HS speed.
4030 * If a zero value, it means there is no HSGEAR capability.
4031 * Then, get the maximum gears of PWM speed.
4033 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_MAXRXHSGEAR), &pwr_info->gear_rx);
4034 if (!pwr_info->gear_rx) {
4035 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_MAXRXPWMGEAR),
4036 &pwr_info->gear_rx);
4037 if (!pwr_info->gear_rx) {
4038 dev_err(hba->dev, "%s: invalid max pwm rx gear read = %d\n",
4039 __func__, pwr_info->gear_rx);
4042 pwr_info->pwr_rx = SLOW_MODE;
4045 ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_MAXRXHSGEAR),
4046 &pwr_info->gear_tx);
4047 if (!pwr_info->gear_tx) {
4048 ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_MAXRXPWMGEAR),
4049 &pwr_info->gear_tx);
4050 if (!pwr_info->gear_tx) {
4051 dev_err(hba->dev, "%s: invalid max pwm tx gear read = %d\n",
4052 __func__, pwr_info->gear_tx);
4055 pwr_info->pwr_tx = SLOW_MODE;
4058 hba->max_pwr_info.is_valid = true;
4062 static int ufshcd_change_power_mode(struct ufs_hba *hba,
4063 struct ufs_pa_layer_attr *pwr_mode)
4067 /* if already configured to the requested pwr_mode */
4068 if (pwr_mode->gear_rx == hba->pwr_info.gear_rx &&
4069 pwr_mode->gear_tx == hba->pwr_info.gear_tx &&
4070 pwr_mode->lane_rx == hba->pwr_info.lane_rx &&
4071 pwr_mode->lane_tx == hba->pwr_info.lane_tx &&
4072 pwr_mode->pwr_rx == hba->pwr_info.pwr_rx &&
4073 pwr_mode->pwr_tx == hba->pwr_info.pwr_tx &&
4074 pwr_mode->hs_rate == hba->pwr_info.hs_rate) {
4075 dev_dbg(hba->dev, "%s: power already configured\n", __func__);
4080 * Configure attributes for power mode change with below.
4081 * - PA_RXGEAR, PA_ACTIVERXDATALANES, PA_RXTERMINATION,
4082 * - PA_TXGEAR, PA_ACTIVETXDATALANES, PA_TXTERMINATION,
4085 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_RXGEAR), pwr_mode->gear_rx);
4086 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_ACTIVERXDATALANES),
4088 if (pwr_mode->pwr_rx == FASTAUTO_MODE ||
4089 pwr_mode->pwr_rx == FAST_MODE)
4090 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_RXTERMINATION), TRUE);
4092 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_RXTERMINATION), FALSE);
4094 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TXGEAR), pwr_mode->gear_tx);
4095 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_ACTIVETXDATALANES),
4097 if (pwr_mode->pwr_tx == FASTAUTO_MODE ||
4098 pwr_mode->pwr_tx == FAST_MODE)
4099 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TXTERMINATION), TRUE);
4101 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TXTERMINATION), FALSE);
4103 if (pwr_mode->pwr_rx == FASTAUTO_MODE ||
4104 pwr_mode->pwr_tx == FASTAUTO_MODE ||
4105 pwr_mode->pwr_rx == FAST_MODE ||
4106 pwr_mode->pwr_tx == FAST_MODE)
4107 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_HSSERIES),
4110 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_PWRMODEUSERDATA0),
4111 DL_FC0ProtectionTimeOutVal_Default);
4112 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_PWRMODEUSERDATA1),
4113 DL_TC0ReplayTimeOutVal_Default);
4114 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_PWRMODEUSERDATA2),
4115 DL_AFC0ReqTimeOutVal_Default);
4116 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_PWRMODEUSERDATA3),
4117 DL_FC1ProtectionTimeOutVal_Default);
4118 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_PWRMODEUSERDATA4),
4119 DL_TC1ReplayTimeOutVal_Default);
4120 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_PWRMODEUSERDATA5),
4121 DL_AFC1ReqTimeOutVal_Default);
4123 ufshcd_dme_set(hba, UIC_ARG_MIB(DME_LocalFC0ProtectionTimeOutVal),
4124 DL_FC0ProtectionTimeOutVal_Default);
4125 ufshcd_dme_set(hba, UIC_ARG_MIB(DME_LocalTC0ReplayTimeOutVal),
4126 DL_TC0ReplayTimeOutVal_Default);
4127 ufshcd_dme_set(hba, UIC_ARG_MIB(DME_LocalAFC0ReqTimeOutVal),
4128 DL_AFC0ReqTimeOutVal_Default);
4130 ret = ufshcd_uic_change_pwr_mode(hba, pwr_mode->pwr_rx << 4
4131 | pwr_mode->pwr_tx);
4135 "%s: power mode change failed %d\n", __func__, ret);
4137 ufshcd_vops_pwr_change_notify(hba, POST_CHANGE, NULL,
4140 memcpy(&hba->pwr_info, pwr_mode,
4141 sizeof(struct ufs_pa_layer_attr));
4148 * ufshcd_config_pwr_mode - configure a new power mode
4149 * @hba: per-adapter instance
4150 * @desired_pwr_mode: desired power configuration
4152 int ufshcd_config_pwr_mode(struct ufs_hba *hba,
4153 struct ufs_pa_layer_attr *desired_pwr_mode)
4155 struct ufs_pa_layer_attr final_params = { 0 };
4158 ret = ufshcd_vops_pwr_change_notify(hba, PRE_CHANGE,
4159 desired_pwr_mode, &final_params);
4162 memcpy(&final_params, desired_pwr_mode, sizeof(final_params));
4164 ret = ufshcd_change_power_mode(hba, &final_params);
4168 EXPORT_SYMBOL_GPL(ufshcd_config_pwr_mode);
4171 * ufshcd_complete_dev_init() - checks device readiness
4172 * @hba: per-adapter instance
4174 * Set fDeviceInit flag and poll until device toggles it.
4176 static int ufshcd_complete_dev_init(struct ufs_hba *hba)
4180 bool flag_res = true;
4182 err = ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_SET_FLAG,
4183 QUERY_FLAG_IDN_FDEVICEINIT, 0, NULL);
4186 "%s setting fDeviceInit flag failed with error %d\n",
4191 /* poll for max. 1000 iterations for fDeviceInit flag to clear */
4192 for (i = 0; i < 1000 && !err && flag_res; i++)
4193 err = ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_READ_FLAG,
4194 QUERY_FLAG_IDN_FDEVICEINIT, 0, &flag_res);
4198 "%s reading fDeviceInit flag failed with error %d\n",
4202 "%s fDeviceInit was not cleared by the device\n",
4210 * ufshcd_make_hba_operational - Make UFS controller operational
4211 * @hba: per adapter instance
4213 * To bring UFS host controller to operational state,
4214 * 1. Enable required interrupts
4215 * 2. Configure interrupt aggregation
4216 * 3. Program UTRL and UTMRL base address
4217 * 4. Configure run-stop-registers
4219 * Returns 0 on success, non-zero value on failure
4221 int ufshcd_make_hba_operational(struct ufs_hba *hba)
4226 /* Enable required interrupts */
4227 ufshcd_enable_intr(hba, UFSHCD_ENABLE_INTRS);
4229 /* Configure interrupt aggregation */
4230 if (ufshcd_is_intr_aggr_allowed(hba))
4231 ufshcd_config_intr_aggr(hba, hba->nutrs - 1, INT_AGGR_DEF_TO);
4233 ufshcd_disable_intr_aggr(hba);
4235 /* Configure UTRL and UTMRL base address registers */
4236 ufshcd_writel(hba, lower_32_bits(hba->utrdl_dma_addr),
4237 REG_UTP_TRANSFER_REQ_LIST_BASE_L);
4238 ufshcd_writel(hba, upper_32_bits(hba->utrdl_dma_addr),
4239 REG_UTP_TRANSFER_REQ_LIST_BASE_H);
4240 ufshcd_writel(hba, lower_32_bits(hba->utmrdl_dma_addr),
4241 REG_UTP_TASK_REQ_LIST_BASE_L);
4242 ufshcd_writel(hba, upper_32_bits(hba->utmrdl_dma_addr),
4243 REG_UTP_TASK_REQ_LIST_BASE_H);
4246 * Make sure base address and interrupt setup are updated before
4247 * enabling the run/stop registers below.
4252 * UCRDY, UTMRLDY and UTRLRDY bits must be 1
4254 reg = ufshcd_readl(hba, REG_CONTROLLER_STATUS);
4255 if (!(ufshcd_get_lists_status(reg))) {
4256 ufshcd_enable_run_stop_reg(hba);
4259 "Host controller not ready to process requests");
4267 EXPORT_SYMBOL_GPL(ufshcd_make_hba_operational);
4270 * ufshcd_hba_stop - Send controller to reset state
4271 * @hba: per adapter instance
4273 static inline void ufshcd_hba_stop(struct ufs_hba *hba)
4275 unsigned long flags;
4279 * Obtain the host lock to prevent that the controller is disabled
4280 * while the UFS interrupt handler is active on another CPU.
4282 spin_lock_irqsave(hba->host->host_lock, flags);
4283 ufshcd_writel(hba, CONTROLLER_DISABLE, REG_CONTROLLER_ENABLE);
4284 spin_unlock_irqrestore(hba->host->host_lock, flags);
4286 err = ufshcd_wait_for_register(hba, REG_CONTROLLER_ENABLE,
4287 CONTROLLER_ENABLE, CONTROLLER_DISABLE,
4290 dev_err(hba->dev, "%s: Controller disable failed\n", __func__);
4294 * ufshcd_hba_execute_hce - initialize the controller
4295 * @hba: per adapter instance
4297 * The controller resets itself and controller firmware initialization
4298 * sequence kicks off. When controller is ready it will set
4299 * the Host Controller Enable bit to 1.
4301 * Returns 0 on success, non-zero value on failure
4303 static int ufshcd_hba_execute_hce(struct ufs_hba *hba)
4307 if (!ufshcd_is_hba_active(hba))
4308 /* change controller state to "reset state" */
4309 ufshcd_hba_stop(hba);
4311 /* UniPro link is disabled at this point */
4312 ufshcd_set_link_off(hba);
4314 ufshcd_vops_hce_enable_notify(hba, PRE_CHANGE);
4316 /* start controller initialization sequence */
4317 ufshcd_hba_start(hba);
4320 * To initialize a UFS host controller HCE bit must be set to 1.
4321 * During initialization the HCE bit value changes from 1->0->1.
4322 * When the host controller completes initialization sequence
4323 * it sets the value of HCE bit to 1. The same HCE bit is read back
4324 * to check if the controller has completed initialization sequence.
4325 * So without this delay the value HCE = 1, set in the previous
4326 * instruction might be read back.
4327 * This delay can be changed based on the controller.
4329 ufshcd_delay_us(hba->vps->hba_enable_delay_us, 100);
4331 /* wait for the host controller to complete initialization */
4333 while (ufshcd_is_hba_active(hba)) {
4338 "Controller enable failed\n");
4341 usleep_range(1000, 1100);
4344 /* enable UIC related interrupts */
4345 ufshcd_enable_intr(hba, UFSHCD_UIC_MASK);
4347 ufshcd_vops_hce_enable_notify(hba, POST_CHANGE);
4352 int ufshcd_hba_enable(struct ufs_hba *hba)
4356 if (hba->quirks & UFSHCI_QUIRK_BROKEN_HCE) {
4357 ufshcd_set_link_off(hba);
4358 ufshcd_vops_hce_enable_notify(hba, PRE_CHANGE);
4360 /* enable UIC related interrupts */
4361 ufshcd_enable_intr(hba, UFSHCD_UIC_MASK);
4362 ret = ufshcd_dme_reset(hba);
4364 ret = ufshcd_dme_enable(hba);
4366 ufshcd_vops_hce_enable_notify(hba, POST_CHANGE);
4369 "Host controller enable failed with non-hce\n");
4372 ret = ufshcd_hba_execute_hce(hba);
4377 EXPORT_SYMBOL_GPL(ufshcd_hba_enable);
4379 static int ufshcd_disable_tx_lcc(struct ufs_hba *hba, bool peer)
4381 int tx_lanes = 0, i, err = 0;
4384 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_CONNECTEDTXDATALANES),
4387 ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_CONNECTEDTXDATALANES),
4389 for (i = 0; i < tx_lanes; i++) {
4391 err = ufshcd_dme_set(hba,
4392 UIC_ARG_MIB_SEL(TX_LCC_ENABLE,
4393 UIC_ARG_MPHY_TX_GEN_SEL_INDEX(i)),
4396 err = ufshcd_dme_peer_set(hba,
4397 UIC_ARG_MIB_SEL(TX_LCC_ENABLE,
4398 UIC_ARG_MPHY_TX_GEN_SEL_INDEX(i)),
4401 dev_err(hba->dev, "%s: TX LCC Disable failed, peer = %d, lane = %d, err = %d",
4402 __func__, peer, i, err);
4410 static inline int ufshcd_disable_device_tx_lcc(struct ufs_hba *hba)
4412 return ufshcd_disable_tx_lcc(hba, true);
4415 void ufshcd_update_reg_hist(struct ufs_err_reg_hist *reg_hist,
4418 reg_hist->reg[reg_hist->pos] = reg;
4419 reg_hist->tstamp[reg_hist->pos] = ktime_get();
4420 reg_hist->pos = (reg_hist->pos + 1) % UFS_ERR_REG_HIST_LENGTH;
4422 EXPORT_SYMBOL_GPL(ufshcd_update_reg_hist);
4425 * ufshcd_link_startup - Initialize unipro link startup
4426 * @hba: per adapter instance
4428 * Returns 0 for success, non-zero in case of failure
4430 static int ufshcd_link_startup(struct ufs_hba *hba)
4433 int retries = DME_LINKSTARTUP_RETRIES;
4434 bool link_startup_again = false;
4437 * If UFS device isn't active then we will have to issue link startup
4438 * 2 times to make sure the device state move to active.
4440 if (!ufshcd_is_ufs_dev_active(hba))
4441 link_startup_again = true;
4445 ufshcd_vops_link_startup_notify(hba, PRE_CHANGE);
4447 ret = ufshcd_dme_link_startup(hba);
4449 /* check if device is detected by inter-connect layer */
4450 if (!ret && !ufshcd_is_device_present(hba)) {
4451 ufshcd_update_reg_hist(&hba->ufs_stats.link_startup_err,
4453 dev_err(hba->dev, "%s: Device not present\n", __func__);
4459 * DME link lost indication is only received when link is up,
4460 * but we can't be sure if the link is up until link startup
4461 * succeeds. So reset the local Uni-Pro and try again.
4463 if (ret && ufshcd_hba_enable(hba)) {
4464 ufshcd_update_reg_hist(&hba->ufs_stats.link_startup_err,
4468 } while (ret && retries--);
4471 /* failed to get the link up... retire */
4472 ufshcd_update_reg_hist(&hba->ufs_stats.link_startup_err,
4477 if (link_startup_again) {
4478 link_startup_again = false;
4479 retries = DME_LINKSTARTUP_RETRIES;
4483 /* Mark that link is up in PWM-G1, 1-lane, SLOW-AUTO mode */
4484 ufshcd_init_pwr_info(hba);
4485 ufshcd_print_pwr_info(hba);
4487 if (hba->quirks & UFSHCD_QUIRK_BROKEN_LCC) {
4488 ret = ufshcd_disable_device_tx_lcc(hba);
4493 /* Include any host controller configuration via UIC commands */
4494 ret = ufshcd_vops_link_startup_notify(hba, POST_CHANGE);
4498 ret = ufshcd_make_hba_operational(hba);
4501 dev_err(hba->dev, "link startup failed %d\n", ret);
4502 ufshcd_print_host_state(hba);
4503 ufshcd_print_pwr_info(hba);
4504 ufshcd_print_host_regs(hba);
4510 * ufshcd_verify_dev_init() - Verify device initialization
4511 * @hba: per-adapter instance
4513 * Send NOP OUT UPIU and wait for NOP IN response to check whether the
4514 * device Transport Protocol (UTP) layer is ready after a reset.
4515 * If the UTP layer at the device side is not initialized, it may
4516 * not respond with NOP IN UPIU within timeout of %NOP_OUT_TIMEOUT
4517 * and we retry sending NOP OUT for %NOP_OUT_RETRIES iterations.
4519 static int ufshcd_verify_dev_init(struct ufs_hba *hba)
4524 ufshcd_hold(hba, false);
4525 mutex_lock(&hba->dev_cmd.lock);
4526 for (retries = NOP_OUT_RETRIES; retries > 0; retries--) {
4527 err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_NOP,
4530 if (!err || err == -ETIMEDOUT)
4533 dev_dbg(hba->dev, "%s: error %d retrying\n", __func__, err);
4535 mutex_unlock(&hba->dev_cmd.lock);
4536 ufshcd_release(hba);
4539 dev_err(hba->dev, "%s: NOP OUT failed %d\n", __func__, err);
4544 * ufshcd_set_queue_depth - set lun queue depth
4545 * @sdev: pointer to SCSI device
4547 * Read bLUQueueDepth value and activate scsi tagged command
4548 * queueing. For WLUN, queue depth is set to 1. For best-effort
4549 * cases (bLUQueueDepth = 0) the queue depth is set to a maximum
4550 * value that host can queue.
4552 static void ufshcd_set_queue_depth(struct scsi_device *sdev)
4556 struct ufs_hba *hba;
4558 hba = shost_priv(sdev->host);
4560 lun_qdepth = hba->nutrs;
4561 ret = ufshcd_read_unit_desc_param(hba,
4562 ufshcd_scsi_to_upiu_lun(sdev->lun),
4563 UNIT_DESC_PARAM_LU_Q_DEPTH,
4565 sizeof(lun_qdepth));
4567 /* Some WLUN doesn't support unit descriptor */
4568 if (ret == -EOPNOTSUPP)
4570 else if (!lun_qdepth)
4571 /* eventually, we can figure out the real queue depth */
4572 lun_qdepth = hba->nutrs;
4574 lun_qdepth = min_t(int, lun_qdepth, hba->nutrs);
4576 dev_dbg(hba->dev, "%s: activate tcq with queue depth %d\n",
4577 __func__, lun_qdepth);
4578 scsi_change_queue_depth(sdev, lun_qdepth);
4582 * ufshcd_get_lu_wp - returns the "b_lu_write_protect" from UNIT DESCRIPTOR
4583 * @hba: per-adapter instance
4584 * @lun: UFS device lun id
4585 * @b_lu_write_protect: pointer to buffer to hold the LU's write protect info
4587 * Returns 0 in case of success and b_lu_write_protect status would be returned
4588 * @b_lu_write_protect parameter.
4589 * Returns -ENOTSUPP if reading b_lu_write_protect is not supported.
4590 * Returns -EINVAL in case of invalid parameters passed to this function.
4592 static int ufshcd_get_lu_wp(struct ufs_hba *hba,
4594 u8 *b_lu_write_protect)
4598 if (!b_lu_write_protect)
4601 * According to UFS device spec, RPMB LU can't be write
4602 * protected so skip reading bLUWriteProtect parameter for
4603 * it. For other W-LUs, UNIT DESCRIPTOR is not available.
4605 else if (lun >= hba->dev_info.max_lu_supported)
4608 ret = ufshcd_read_unit_desc_param(hba,
4610 UNIT_DESC_PARAM_LU_WR_PROTECT,
4612 sizeof(*b_lu_write_protect));
4617 * ufshcd_get_lu_power_on_wp_status - get LU's power on write protect
4619 * @hba: per-adapter instance
4620 * @sdev: pointer to SCSI device
4623 static inline void ufshcd_get_lu_power_on_wp_status(struct ufs_hba *hba,
4624 struct scsi_device *sdev)
4626 if (hba->dev_info.f_power_on_wp_en &&
4627 !hba->dev_info.is_lu_power_on_wp) {
4628 u8 b_lu_write_protect;
4630 if (!ufshcd_get_lu_wp(hba, ufshcd_scsi_to_upiu_lun(sdev->lun),
4631 &b_lu_write_protect) &&
4632 (b_lu_write_protect == UFS_LU_POWER_ON_WP))
4633 hba->dev_info.is_lu_power_on_wp = true;
4638 * ufshcd_slave_alloc - handle initial SCSI device configurations
4639 * @sdev: pointer to SCSI device
4643 static int ufshcd_slave_alloc(struct scsi_device *sdev)
4645 struct ufs_hba *hba;
4647 hba = shost_priv(sdev->host);
4649 /* Mode sense(6) is not supported by UFS, so use Mode sense(10) */
4650 sdev->use_10_for_ms = 1;
4652 /* DBD field should be set to 1 in mode sense(10) */
4653 sdev->set_dbd_for_ms = 1;
4655 /* allow SCSI layer to restart the device in case of errors */
4656 sdev->allow_restart = 1;
4658 /* REPORT SUPPORTED OPERATION CODES is not supported */
4659 sdev->no_report_opcodes = 1;
4661 /* WRITE_SAME command is not supported */
4662 sdev->no_write_same = 1;
4664 ufshcd_set_queue_depth(sdev);
4666 ufshcd_get_lu_power_on_wp_status(hba, sdev);
4672 * ufshcd_change_queue_depth - change queue depth
4673 * @sdev: pointer to SCSI device
4674 * @depth: required depth to set
4676 * Change queue depth and make sure the max. limits are not crossed.
4678 static int ufshcd_change_queue_depth(struct scsi_device *sdev, int depth)
4680 struct ufs_hba *hba = shost_priv(sdev->host);
4682 if (depth > hba->nutrs)
4684 return scsi_change_queue_depth(sdev, depth);
4688 * ufshcd_slave_configure - adjust SCSI device configurations
4689 * @sdev: pointer to SCSI device
4691 static int ufshcd_slave_configure(struct scsi_device *sdev)
4693 struct ufs_hba *hba = shost_priv(sdev->host);
4694 struct request_queue *q = sdev->request_queue;
4696 blk_queue_update_dma_pad(q, PRDT_DATA_BYTE_COUNT_PAD - 1);
4698 if (ufshcd_is_rpm_autosuspend_allowed(hba))
4699 sdev->rpm_autosuspend = 1;
4701 ufshcd_crypto_setup_rq_keyslot_manager(hba, q);
4707 * ufshcd_slave_destroy - remove SCSI device configurations
4708 * @sdev: pointer to SCSI device
4710 static void ufshcd_slave_destroy(struct scsi_device *sdev)
4712 struct ufs_hba *hba;
4714 hba = shost_priv(sdev->host);
4715 /* Drop the reference as it won't be needed anymore */
4716 if (ufshcd_scsi_to_upiu_lun(sdev->lun) == UFS_UPIU_UFS_DEVICE_WLUN) {
4717 unsigned long flags;
4719 spin_lock_irqsave(hba->host->host_lock, flags);
4720 hba->sdev_ufs_device = NULL;
4721 spin_unlock_irqrestore(hba->host->host_lock, flags);
4726 * ufshcd_scsi_cmd_status - Update SCSI command result based on SCSI status
4727 * @lrbp: pointer to local reference block of completed command
4728 * @scsi_status: SCSI command status
4730 * Returns value base on SCSI command status
4733 ufshcd_scsi_cmd_status(struct ufshcd_lrb *lrbp, int scsi_status)
4737 switch (scsi_status) {
4738 case SAM_STAT_CHECK_CONDITION:
4739 ufshcd_copy_sense_data(lrbp);
4742 result |= DID_OK << 16 |
4743 COMMAND_COMPLETE << 8 |
4746 case SAM_STAT_TASK_SET_FULL:
4748 case SAM_STAT_TASK_ABORTED:
4749 ufshcd_copy_sense_data(lrbp);
4750 result |= scsi_status;
4753 result |= DID_ERROR << 16;
4755 } /* end of switch */
4761 * ufshcd_transfer_rsp_status - Get overall status of the response
4762 * @hba: per adapter instance
4763 * @lrbp: pointer to local reference block of completed command
4765 * Returns result of the command to notify SCSI midlayer
4768 ufshcd_transfer_rsp_status(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
4774 /* overall command status of utrd */
4775 ocs = ufshcd_get_tr_ocs(lrbp);
4777 if (hba->quirks & UFSHCD_QUIRK_BROKEN_OCS_FATAL_ERROR) {
4778 if (be32_to_cpu(lrbp->ucd_rsp_ptr->header.dword_1) &
4779 MASK_RSP_UPIU_RESULT)
4785 result = ufshcd_get_req_rsp(lrbp->ucd_rsp_ptr);
4786 hba->ufs_stats.last_hibern8_exit_tstamp = ktime_set(0, 0);
4788 case UPIU_TRANSACTION_RESPONSE:
4790 * get the response UPIU result to extract
4791 * the SCSI command status
4793 result = ufshcd_get_rsp_upiu_result(lrbp->ucd_rsp_ptr);
4796 * get the result based on SCSI status response
4797 * to notify the SCSI midlayer of the command status
4799 scsi_status = result & MASK_SCSI_STATUS;
4800 result = ufshcd_scsi_cmd_status(lrbp, scsi_status);
4803 * Currently we are only supporting BKOPs exception
4804 * events hence we can ignore BKOPs exception event
4805 * during power management callbacks. BKOPs exception
4806 * event is not expected to be raised in runtime suspend
4807 * callback as it allows the urgent bkops.
4808 * During system suspend, we are anyway forcefully
4809 * disabling the bkops and if urgent bkops is needed
4810 * it will be enabled on system resume. Long term
4811 * solution could be to abort the system suspend if
4812 * UFS device needs urgent BKOPs.
4814 if (!hba->pm_op_in_progress &&
4815 ufshcd_is_exception_event(lrbp->ucd_rsp_ptr) &&
4816 schedule_work(&hba->eeh_work)) {
4818 * Prevent suspend once eeh_work is scheduled
4819 * to avoid deadlock between ufshcd_suspend
4820 * and exception event handler.
4822 pm_runtime_get_noresume(hba->dev);
4825 case UPIU_TRANSACTION_REJECT_UPIU:
4826 /* TODO: handle Reject UPIU Response */
4827 result = DID_ERROR << 16;
4829 "Reject UPIU not fully implemented\n");
4833 "Unexpected request response code = %x\n",
4835 result = DID_ERROR << 16;
4840 result |= DID_ABORT << 16;
4842 case OCS_INVALID_COMMAND_STATUS:
4843 result |= DID_REQUEUE << 16;
4845 case OCS_INVALID_CMD_TABLE_ATTR:
4846 case OCS_INVALID_PRDT_ATTR:
4847 case OCS_MISMATCH_DATA_BUF_SIZE:
4848 case OCS_MISMATCH_RESP_UPIU_SIZE:
4849 case OCS_PEER_COMM_FAILURE:
4850 case OCS_FATAL_ERROR:
4851 case OCS_DEVICE_FATAL_ERROR:
4852 case OCS_INVALID_CRYPTO_CONFIG:
4853 case OCS_GENERAL_CRYPTO_ERROR:
4855 result |= DID_ERROR << 16;
4857 "OCS error from controller = %x for tag %d\n",
4858 ocs, lrbp->task_tag);
4859 ufshcd_print_host_regs(hba);
4860 ufshcd_print_host_state(hba);
4862 } /* end of switch */
4864 if ((host_byte(result) != DID_OK) && !hba->silence_err_logs)
4865 ufshcd_print_trs(hba, 1 << lrbp->task_tag, true);
4870 * ufshcd_uic_cmd_compl - handle completion of uic command
4871 * @hba: per adapter instance
4872 * @intr_status: interrupt status generated by the controller
4875 * IRQ_HANDLED - If interrupt is valid
4876 * IRQ_NONE - If invalid interrupt
4878 static irqreturn_t ufshcd_uic_cmd_compl(struct ufs_hba *hba, u32 intr_status)
4880 irqreturn_t retval = IRQ_NONE;
4882 if ((intr_status & UIC_COMMAND_COMPL) && hba->active_uic_cmd) {
4883 hba->active_uic_cmd->argument2 |=
4884 ufshcd_get_uic_cmd_result(hba);
4885 hba->active_uic_cmd->argument3 =
4886 ufshcd_get_dme_attr_val(hba);
4887 complete(&hba->active_uic_cmd->done);
4888 retval = IRQ_HANDLED;
4891 if ((intr_status & UFSHCD_UIC_PWR_MASK) && hba->uic_async_done) {
4892 complete(hba->uic_async_done);
4893 retval = IRQ_HANDLED;
4896 if (retval == IRQ_HANDLED)
4897 ufshcd_add_uic_command_trace(hba, hba->active_uic_cmd,
4903 * __ufshcd_transfer_req_compl - handle SCSI and query command completion
4904 * @hba: per adapter instance
4905 * @completed_reqs: requests to complete
4907 static void __ufshcd_transfer_req_compl(struct ufs_hba *hba,
4908 unsigned long completed_reqs)
4910 struct ufshcd_lrb *lrbp;
4911 struct scsi_cmnd *cmd;
4915 for_each_set_bit(index, &completed_reqs, hba->nutrs) {
4916 lrbp = &hba->lrb[index];
4917 lrbp->compl_time_stamp = ktime_get();
4920 ufshcd_add_command_trace(hba, index, "complete");
4921 result = ufshcd_transfer_rsp_status(hba, lrbp);
4922 scsi_dma_unmap(cmd);
4923 cmd->result = result;
4924 /* Mark completed command as NULL in LRB */
4926 /* Do not touch lrbp after scsi done */
4927 cmd->scsi_done(cmd);
4928 __ufshcd_release(hba);
4929 } else if (lrbp->command_type == UTP_CMD_TYPE_DEV_MANAGE ||
4930 lrbp->command_type == UTP_CMD_TYPE_UFS_STORAGE) {
4931 if (hba->dev_cmd.complete) {
4932 ufshcd_add_command_trace(hba, index,
4934 complete(hba->dev_cmd.complete);
4937 if (ufshcd_is_clkscaling_supported(hba))
4938 hba->clk_scaling.active_reqs--;
4941 /* clear corresponding bits of completed commands */
4942 hba->outstanding_reqs ^= completed_reqs;
4944 ufshcd_clk_scaling_update_busy(hba);
4948 * ufshcd_transfer_req_compl - handle SCSI and query command completion
4949 * @hba: per adapter instance
4952 * IRQ_HANDLED - If interrupt is valid
4953 * IRQ_NONE - If invalid interrupt
4955 static irqreturn_t ufshcd_transfer_req_compl(struct ufs_hba *hba)
4957 unsigned long completed_reqs;
4960 /* Resetting interrupt aggregation counters first and reading the
4961 * DOOR_BELL afterward allows us to handle all the completed requests.
4962 * In order to prevent other interrupts starvation the DB is read once
4963 * after reset. The down side of this solution is the possibility of
4964 * false interrupt if device completes another request after resetting
4965 * aggregation and before reading the DB.
4967 if (ufshcd_is_intr_aggr_allowed(hba) &&
4968 !(hba->quirks & UFSHCI_QUIRK_SKIP_RESET_INTR_AGGR))
4969 ufshcd_reset_intr_aggr(hba);
4971 tr_doorbell = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
4972 completed_reqs = tr_doorbell ^ hba->outstanding_reqs;
4974 if (completed_reqs) {
4975 __ufshcd_transfer_req_compl(hba, completed_reqs);
4983 * ufshcd_disable_ee - disable exception event
4984 * @hba: per-adapter instance
4985 * @mask: exception event to disable
4987 * Disables exception event in the device so that the EVENT_ALERT
4990 * Returns zero on success, non-zero error value on failure.
4992 static int ufshcd_disable_ee(struct ufs_hba *hba, u16 mask)
4997 if (!(hba->ee_ctrl_mask & mask))
5000 val = hba->ee_ctrl_mask & ~mask;
5001 val &= MASK_EE_STATUS;
5002 err = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_WRITE_ATTR,
5003 QUERY_ATTR_IDN_EE_CONTROL, 0, 0, &val);
5005 hba->ee_ctrl_mask &= ~mask;
5011 * ufshcd_enable_ee - enable exception event
5012 * @hba: per-adapter instance
5013 * @mask: exception event to enable
5015 * Enable corresponding exception event in the device to allow
5016 * device to alert host in critical scenarios.
5018 * Returns zero on success, non-zero error value on failure.
5020 static int ufshcd_enable_ee(struct ufs_hba *hba, u16 mask)
5025 if (hba->ee_ctrl_mask & mask)
5028 val = hba->ee_ctrl_mask | mask;
5029 val &= MASK_EE_STATUS;
5030 err = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_WRITE_ATTR,
5031 QUERY_ATTR_IDN_EE_CONTROL, 0, 0, &val);
5033 hba->ee_ctrl_mask |= mask;
5039 * ufshcd_enable_auto_bkops - Allow device managed BKOPS
5040 * @hba: per-adapter instance
5042 * Allow device to manage background operations on its own. Enabling
5043 * this might lead to inconsistent latencies during normal data transfers
5044 * as the device is allowed to manage its own way of handling background
5047 * Returns zero on success, non-zero on failure.
5049 static int ufshcd_enable_auto_bkops(struct ufs_hba *hba)
5053 if (hba->auto_bkops_enabled)
5056 err = ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_SET_FLAG,
5057 QUERY_FLAG_IDN_BKOPS_EN, 0, NULL);
5059 dev_err(hba->dev, "%s: failed to enable bkops %d\n",
5064 hba->auto_bkops_enabled = true;
5065 trace_ufshcd_auto_bkops_state(dev_name(hba->dev), "Enabled");
5067 /* No need of URGENT_BKOPS exception from the device */
5068 err = ufshcd_disable_ee(hba, MASK_EE_URGENT_BKOPS);
5070 dev_err(hba->dev, "%s: failed to disable exception event %d\n",
5077 * ufshcd_disable_auto_bkops - block device in doing background operations
5078 * @hba: per-adapter instance
5080 * Disabling background operations improves command response latency but
5081 * has drawback of device moving into critical state where the device is
5082 * not-operable. Make sure to call ufshcd_enable_auto_bkops() whenever the
5083 * host is idle so that BKOPS are managed effectively without any negative
5086 * Returns zero on success, non-zero on failure.
5088 static int ufshcd_disable_auto_bkops(struct ufs_hba *hba)
5092 if (!hba->auto_bkops_enabled)
5096 * If host assisted BKOPs is to be enabled, make sure
5097 * urgent bkops exception is allowed.
5099 err = ufshcd_enable_ee(hba, MASK_EE_URGENT_BKOPS);
5101 dev_err(hba->dev, "%s: failed to enable exception event %d\n",
5106 err = ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_CLEAR_FLAG,
5107 QUERY_FLAG_IDN_BKOPS_EN, 0, NULL);
5109 dev_err(hba->dev, "%s: failed to disable bkops %d\n",
5111 ufshcd_disable_ee(hba, MASK_EE_URGENT_BKOPS);
5115 hba->auto_bkops_enabled = false;
5116 trace_ufshcd_auto_bkops_state(dev_name(hba->dev), "Disabled");
5117 hba->is_urgent_bkops_lvl_checked = false;
5123 * ufshcd_force_reset_auto_bkops - force reset auto bkops state
5124 * @hba: per adapter instance
5126 * After a device reset the device may toggle the BKOPS_EN flag
5127 * to default value. The s/w tracking variables should be updated
5128 * as well. This function would change the auto-bkops state based on
5129 * UFSHCD_CAP_KEEP_AUTO_BKOPS_ENABLED_EXCEPT_SUSPEND.
5131 static void ufshcd_force_reset_auto_bkops(struct ufs_hba *hba)
5133 if (ufshcd_keep_autobkops_enabled_except_suspend(hba)) {
5134 hba->auto_bkops_enabled = false;
5135 hba->ee_ctrl_mask |= MASK_EE_URGENT_BKOPS;
5136 ufshcd_enable_auto_bkops(hba);
5138 hba->auto_bkops_enabled = true;
5139 hba->ee_ctrl_mask &= ~MASK_EE_URGENT_BKOPS;
5140 ufshcd_disable_auto_bkops(hba);
5142 hba->urgent_bkops_lvl = BKOPS_STATUS_PERF_IMPACT;
5143 hba->is_urgent_bkops_lvl_checked = false;
5146 static inline int ufshcd_get_bkops_status(struct ufs_hba *hba, u32 *status)
5148 return ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
5149 QUERY_ATTR_IDN_BKOPS_STATUS, 0, 0, status);
5153 * ufshcd_bkops_ctrl - control the auto bkops based on current bkops status
5154 * @hba: per-adapter instance
5155 * @status: bkops_status value
5157 * Read the bkops_status from the UFS device and Enable fBackgroundOpsEn
5158 * flag in the device to permit background operations if the device
5159 * bkops_status is greater than or equal to "status" argument passed to
5160 * this function, disable otherwise.
5162 * Returns 0 for success, non-zero in case of failure.
5164 * NOTE: Caller of this function can check the "hba->auto_bkops_enabled" flag
5165 * to know whether auto bkops is enabled or disabled after this function
5166 * returns control to it.
5168 static int ufshcd_bkops_ctrl(struct ufs_hba *hba,
5169 enum bkops_status status)
5172 u32 curr_status = 0;
5174 err = ufshcd_get_bkops_status(hba, &curr_status);
5176 dev_err(hba->dev, "%s: failed to get BKOPS status %d\n",
5179 } else if (curr_status > BKOPS_STATUS_MAX) {
5180 dev_err(hba->dev, "%s: invalid BKOPS status %d\n",
5181 __func__, curr_status);
5186 if (curr_status >= status)
5187 err = ufshcd_enable_auto_bkops(hba);
5189 err = ufshcd_disable_auto_bkops(hba);
5195 * ufshcd_urgent_bkops - handle urgent bkops exception event
5196 * @hba: per-adapter instance
5198 * Enable fBackgroundOpsEn flag in the device to permit background
5201 * If BKOPs is enabled, this function returns 0, 1 if the bkops in not enabled
5202 * and negative error value for any other failure.
5204 static int ufshcd_urgent_bkops(struct ufs_hba *hba)
5206 return ufshcd_bkops_ctrl(hba, hba->urgent_bkops_lvl);
5209 static inline int ufshcd_get_ee_status(struct ufs_hba *hba, u32 *status)
5211 return ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
5212 QUERY_ATTR_IDN_EE_STATUS, 0, 0, status);
5215 static void ufshcd_bkops_exception_event_handler(struct ufs_hba *hba)
5218 u32 curr_status = 0;
5220 if (hba->is_urgent_bkops_lvl_checked)
5221 goto enable_auto_bkops;
5223 err = ufshcd_get_bkops_status(hba, &curr_status);
5225 dev_err(hba->dev, "%s: failed to get BKOPS status %d\n",
5231 * We are seeing that some devices are raising the urgent bkops
5232 * exception events even when BKOPS status doesn't indicate performace
5233 * impacted or critical. Handle these device by determining their urgent
5234 * bkops status at runtime.
5236 if (curr_status < BKOPS_STATUS_PERF_IMPACT) {
5237 dev_err(hba->dev, "%s: device raised urgent BKOPS exception for bkops status %d\n",
5238 __func__, curr_status);
5239 /* update the current status as the urgent bkops level */
5240 hba->urgent_bkops_lvl = curr_status;
5241 hba->is_urgent_bkops_lvl_checked = true;
5245 err = ufshcd_enable_auto_bkops(hba);
5248 dev_err(hba->dev, "%s: failed to handle urgent bkops %d\n",
5252 static int ufshcd_wb_ctrl(struct ufs_hba *hba, bool enable)
5256 enum query_opcode opcode;
5258 if (!ufshcd_is_wb_allowed(hba))
5261 if (!(enable ^ hba->wb_enabled))
5264 opcode = UPIU_QUERY_OPCODE_SET_FLAG;
5266 opcode = UPIU_QUERY_OPCODE_CLEAR_FLAG;
5268 index = ufshcd_wb_get_query_index(hba);
5269 ret = ufshcd_query_flag_retry(hba, opcode,
5270 QUERY_FLAG_IDN_WB_EN, index, NULL);
5272 dev_err(hba->dev, "%s write booster %s failed %d\n",
5273 __func__, enable ? "enable" : "disable", ret);
5277 hba->wb_enabled = enable;
5278 dev_dbg(hba->dev, "%s write booster %s %d\n",
5279 __func__, enable ? "enable" : "disable", ret);
5284 static int ufshcd_wb_toggle_flush_during_h8(struct ufs_hba *hba, bool set)
5290 val = UPIU_QUERY_OPCODE_SET_FLAG;
5292 val = UPIU_QUERY_OPCODE_CLEAR_FLAG;
5294 index = ufshcd_wb_get_query_index(hba);
5295 return ufshcd_query_flag_retry(hba, val,
5296 QUERY_FLAG_IDN_WB_BUFF_FLUSH_DURING_HIBERN8,
5300 static inline void ufshcd_wb_toggle_flush(struct ufs_hba *hba, bool enable)
5303 ufshcd_wb_buf_flush_enable(hba);
5305 ufshcd_wb_buf_flush_disable(hba);
5309 static int ufshcd_wb_buf_flush_enable(struct ufs_hba *hba)
5314 if (!ufshcd_is_wb_allowed(hba) || hba->wb_buf_flush_enabled)
5317 index = ufshcd_wb_get_query_index(hba);
5318 ret = ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_SET_FLAG,
5319 QUERY_FLAG_IDN_WB_BUFF_FLUSH_EN,
5322 dev_err(hba->dev, "%s WB - buf flush enable failed %d\n",
5325 hba->wb_buf_flush_enabled = true;
5327 dev_dbg(hba->dev, "WB - Flush enabled: %d\n", ret);
5331 static int ufshcd_wb_buf_flush_disable(struct ufs_hba *hba)
5336 if (!ufshcd_is_wb_allowed(hba) || !hba->wb_buf_flush_enabled)
5339 index = ufshcd_wb_get_query_index(hba);
5340 ret = ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_CLEAR_FLAG,
5341 QUERY_FLAG_IDN_WB_BUFF_FLUSH_EN,
5344 dev_warn(hba->dev, "%s: WB - buf flush disable failed %d\n",
5347 hba->wb_buf_flush_enabled = false;
5348 dev_dbg(hba->dev, "WB - Flush disabled: %d\n", ret);
5354 static bool ufshcd_wb_presrv_usrspc_keep_vcc_on(struct ufs_hba *hba,
5361 index = ufshcd_wb_get_query_index(hba);
5362 ret = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
5363 QUERY_ATTR_IDN_CURR_WB_BUFF_SIZE,
5364 index, 0, &cur_buf);
5366 dev_err(hba->dev, "%s dCurWriteBoosterBufferSize read failed %d\n",
5372 dev_info(hba->dev, "dCurWBBuf: %d WB disabled until free-space is available\n",
5376 /* Let it continue to flush when available buffer exceeds threshold */
5377 if (avail_buf < hba->vps->wb_flush_threshold)
5383 static bool ufshcd_wb_need_flush(struct ufs_hba *hba)
5389 if (!ufshcd_is_wb_allowed(hba))
5392 * The ufs device needs the vcc to be ON to flush.
5393 * With user-space reduction enabled, it's enough to enable flush
5394 * by checking only the available buffer. The threshold
5395 * defined here is > 90% full.
5396 * With user-space preserved enabled, the current-buffer
5397 * should be checked too because the wb buffer size can reduce
5398 * when disk tends to be full. This info is provided by current
5399 * buffer (dCurrentWriteBoosterBufferSize). There's no point in
5400 * keeping vcc on when current buffer is empty.
5402 index = ufshcd_wb_get_query_index(hba);
5403 ret = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
5404 QUERY_ATTR_IDN_AVAIL_WB_BUFF_SIZE,
5405 index, 0, &avail_buf);
5407 dev_warn(hba->dev, "%s dAvailableWriteBoosterBufferSize read failed %d\n",
5412 if (!hba->dev_info.b_presrv_uspc_en) {
5413 if (avail_buf <= UFS_WB_BUF_REMAIN_PERCENT(10))
5418 return ufshcd_wb_presrv_usrspc_keep_vcc_on(hba, avail_buf);
5421 static void ufshcd_rpm_dev_flush_recheck_work(struct work_struct *work)
5423 struct ufs_hba *hba = container_of(to_delayed_work(work),
5425 rpm_dev_flush_recheck_work);
5427 * To prevent unnecessary VCC power drain after device finishes
5428 * WriteBooster buffer flush or Auto BKOPs, force runtime resume
5429 * after a certain delay to recheck the threshold by next runtime
5432 pm_runtime_get_sync(hba->dev);
5433 pm_runtime_put_sync(hba->dev);
5437 * ufshcd_exception_event_handler - handle exceptions raised by device
5438 * @work: pointer to work data
5440 * Read bExceptionEventStatus attribute from the device and handle the
5441 * exception event accordingly.
5443 static void ufshcd_exception_event_handler(struct work_struct *work)
5445 struct ufs_hba *hba;
5448 hba = container_of(work, struct ufs_hba, eeh_work);
5450 pm_runtime_get_sync(hba->dev);
5451 ufshcd_scsi_block_requests(hba);
5452 err = ufshcd_get_ee_status(hba, &status);
5454 dev_err(hba->dev, "%s: failed to get exception status %d\n",
5459 status &= hba->ee_ctrl_mask;
5461 if (status & MASK_EE_URGENT_BKOPS)
5462 ufshcd_bkops_exception_event_handler(hba);
5465 ufshcd_scsi_unblock_requests(hba);
5467 * pm_runtime_get_noresume is called while scheduling
5468 * eeh_work to avoid suspend racing with exception work.
5469 * Hence decrement usage counter using pm_runtime_put_noidle
5470 * to allow suspend on completion of exception event handler.
5472 pm_runtime_put_noidle(hba->dev);
5473 pm_runtime_put(hba->dev);
5477 /* Complete requests that have door-bell cleared */
5478 static void ufshcd_complete_requests(struct ufs_hba *hba)
5480 ufshcd_transfer_req_compl(hba);
5481 ufshcd_tmc_handler(hba);
5485 * ufshcd_quirk_dl_nac_errors - This function checks if error handling is
5486 * to recover from the DL NAC errors or not.
5487 * @hba: per-adapter instance
5489 * Returns true if error handling is required, false otherwise
5491 static bool ufshcd_quirk_dl_nac_errors(struct ufs_hba *hba)
5493 unsigned long flags;
5494 bool err_handling = true;
5496 spin_lock_irqsave(hba->host->host_lock, flags);
5498 * UFS_DEVICE_QUIRK_RECOVERY_FROM_DL_NAC_ERRORS only workaround the
5499 * device fatal error and/or DL NAC & REPLAY timeout errors.
5501 if (hba->saved_err & (CONTROLLER_FATAL_ERROR | SYSTEM_BUS_FATAL_ERROR))
5504 if ((hba->saved_err & DEVICE_FATAL_ERROR) ||
5505 ((hba->saved_err & UIC_ERROR) &&
5506 (hba->saved_uic_err & UFSHCD_UIC_DL_TCx_REPLAY_ERROR)))
5509 if ((hba->saved_err & UIC_ERROR) &&
5510 (hba->saved_uic_err & UFSHCD_UIC_DL_NAC_RECEIVED_ERROR)) {
5513 * wait for 50ms to see if we can get any other errors or not.
5515 spin_unlock_irqrestore(hba->host->host_lock, flags);
5517 spin_lock_irqsave(hba->host->host_lock, flags);
5520 * now check if we have got any other severe errors other than
5523 if ((hba->saved_err & INT_FATAL_ERRORS) ||
5524 ((hba->saved_err & UIC_ERROR) &&
5525 (hba->saved_uic_err & ~UFSHCD_UIC_DL_NAC_RECEIVED_ERROR)))
5529 * As DL NAC is the only error received so far, send out NOP
5530 * command to confirm if link is still active or not.
5531 * - If we don't get any response then do error recovery.
5532 * - If we get response then clear the DL NAC error bit.
5535 spin_unlock_irqrestore(hba->host->host_lock, flags);
5536 err = ufshcd_verify_dev_init(hba);
5537 spin_lock_irqsave(hba->host->host_lock, flags);
5542 /* Link seems to be alive hence ignore the DL NAC errors */
5543 if (hba->saved_uic_err == UFSHCD_UIC_DL_NAC_RECEIVED_ERROR)
5544 hba->saved_err &= ~UIC_ERROR;
5545 /* clear NAC error */
5546 hba->saved_uic_err &= ~UFSHCD_UIC_DL_NAC_RECEIVED_ERROR;
5547 if (!hba->saved_uic_err) {
5548 err_handling = false;
5553 spin_unlock_irqrestore(hba->host->host_lock, flags);
5554 return err_handling;
5558 * ufshcd_err_handler - handle UFS errors that require s/w attention
5559 * @work: pointer to work structure
5561 static void ufshcd_err_handler(struct work_struct *work)
5563 struct ufs_hba *hba;
5564 unsigned long flags;
5569 bool needs_reset = false;
5571 hba = container_of(work, struct ufs_hba, eh_work);
5573 pm_runtime_get_sync(hba->dev);
5574 ufshcd_hold(hba, false);
5576 spin_lock_irqsave(hba->host->host_lock, flags);
5577 if (hba->ufshcd_state == UFSHCD_STATE_RESET)
5580 hba->ufshcd_state = UFSHCD_STATE_RESET;
5581 ufshcd_set_eh_in_progress(hba);
5583 /* Complete requests that have door-bell cleared by h/w */
5584 ufshcd_complete_requests(hba);
5586 if (hba->dev_quirks & UFS_DEVICE_QUIRK_RECOVERY_FROM_DL_NAC_ERRORS) {
5589 spin_unlock_irqrestore(hba->host->host_lock, flags);
5590 /* release the lock as ufshcd_quirk_dl_nac_errors() may sleep */
5591 ret = ufshcd_quirk_dl_nac_errors(hba);
5592 spin_lock_irqsave(hba->host->host_lock, flags);
5594 goto skip_err_handling;
5596 if ((hba->saved_err & INT_FATAL_ERRORS) ||
5597 (hba->saved_err & UFSHCD_UIC_HIBERN8_MASK) ||
5598 ((hba->saved_err & UIC_ERROR) &&
5599 (hba->saved_uic_err & (UFSHCD_UIC_DL_PA_INIT_ERROR |
5600 UFSHCD_UIC_DL_NAC_RECEIVED_ERROR |
5601 UFSHCD_UIC_DL_TCx_REPLAY_ERROR))))
5605 * if host reset is required then skip clearing the pending
5606 * transfers forcefully because they will get cleared during
5607 * host reset and restore
5610 goto skip_pending_xfer_clear;
5612 /* release lock as clear command might sleep */
5613 spin_unlock_irqrestore(hba->host->host_lock, flags);
5614 /* Clear pending transfer requests */
5615 for_each_set_bit(tag, &hba->outstanding_reqs, hba->nutrs) {
5616 if (ufshcd_clear_cmd(hba, tag)) {
5618 goto lock_skip_pending_xfer_clear;
5622 /* Clear pending task management requests */
5623 for_each_set_bit(tag, &hba->outstanding_tasks, hba->nutmrs) {
5624 if (ufshcd_clear_tm_cmd(hba, tag)) {
5626 goto lock_skip_pending_xfer_clear;
5630 lock_skip_pending_xfer_clear:
5631 spin_lock_irqsave(hba->host->host_lock, flags);
5633 /* Complete the requests that are cleared by s/w */
5634 ufshcd_complete_requests(hba);
5636 if (err_xfer || err_tm)
5639 skip_pending_xfer_clear:
5640 /* Fatal errors need reset */
5642 unsigned long max_doorbells = (1UL << hba->nutrs) - 1;
5645 * ufshcd_reset_and_restore() does the link reinitialization
5646 * which will need atleast one empty doorbell slot to send the
5647 * device management commands (NOP and query commands).
5648 * If there is no slot empty at this moment then free up last
5651 if (hba->outstanding_reqs == max_doorbells)
5652 __ufshcd_transfer_req_compl(hba,
5653 (1UL << (hba->nutrs - 1)));
5655 spin_unlock_irqrestore(hba->host->host_lock, flags);
5656 err = ufshcd_reset_and_restore(hba);
5657 spin_lock_irqsave(hba->host->host_lock, flags);
5659 dev_err(hba->dev, "%s: reset and restore failed\n",
5661 hba->ufshcd_state = UFSHCD_STATE_ERROR;
5664 * Inform scsi mid-layer that we did reset and allow to handle
5665 * Unit Attention properly.
5667 scsi_report_bus_reset(hba->host, 0);
5669 hba->saved_uic_err = 0;
5674 hba->ufshcd_state = UFSHCD_STATE_OPERATIONAL;
5675 if (hba->saved_err || hba->saved_uic_err)
5676 dev_err_ratelimited(hba->dev, "%s: exit: saved_err 0x%x saved_uic_err 0x%x",
5677 __func__, hba->saved_err, hba->saved_uic_err);
5680 ufshcd_clear_eh_in_progress(hba);
5683 spin_unlock_irqrestore(hba->host->host_lock, flags);
5684 ufshcd_scsi_unblock_requests(hba);
5685 ufshcd_release(hba);
5686 pm_runtime_put_sync(hba->dev);
5690 * ufshcd_update_uic_error - check and set fatal UIC error flags.
5691 * @hba: per-adapter instance
5694 * IRQ_HANDLED - If interrupt is valid
5695 * IRQ_NONE - If invalid interrupt
5697 static irqreturn_t ufshcd_update_uic_error(struct ufs_hba *hba)
5700 irqreturn_t retval = IRQ_NONE;
5702 /* PHY layer lane error */
5703 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_PHY_ADAPTER_LAYER);
5704 /* Ignore LINERESET indication, as this is not an error */
5705 if ((reg & UIC_PHY_ADAPTER_LAYER_ERROR) &&
5706 (reg & UIC_PHY_ADAPTER_LAYER_LANE_ERR_MASK)) {
5708 * To know whether this error is fatal or not, DB timeout
5709 * must be checked but this error is handled separately.
5711 dev_dbg(hba->dev, "%s: UIC Lane error reported\n", __func__);
5712 ufshcd_update_reg_hist(&hba->ufs_stats.pa_err, reg);
5713 retval |= IRQ_HANDLED;
5716 /* PA_INIT_ERROR is fatal and needs UIC reset */
5717 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_DATA_LINK_LAYER);
5718 if ((reg & UIC_DATA_LINK_LAYER_ERROR) &&
5719 (reg & UIC_DATA_LINK_LAYER_ERROR_CODE_MASK)) {
5720 ufshcd_update_reg_hist(&hba->ufs_stats.dl_err, reg);
5722 if (reg & UIC_DATA_LINK_LAYER_ERROR_PA_INIT)
5723 hba->uic_error |= UFSHCD_UIC_DL_PA_INIT_ERROR;
5724 else if (hba->dev_quirks &
5725 UFS_DEVICE_QUIRK_RECOVERY_FROM_DL_NAC_ERRORS) {
5726 if (reg & UIC_DATA_LINK_LAYER_ERROR_NAC_RECEIVED)
5728 UFSHCD_UIC_DL_NAC_RECEIVED_ERROR;
5729 else if (reg & UIC_DATA_LINK_LAYER_ERROR_TCx_REPLAY_TIMEOUT)
5730 hba->uic_error |= UFSHCD_UIC_DL_TCx_REPLAY_ERROR;
5732 retval |= IRQ_HANDLED;
5735 /* UIC NL/TL/DME errors needs software retry */
5736 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_NETWORK_LAYER);
5737 if ((reg & UIC_NETWORK_LAYER_ERROR) &&
5738 (reg & UIC_NETWORK_LAYER_ERROR_CODE_MASK)) {
5739 ufshcd_update_reg_hist(&hba->ufs_stats.nl_err, reg);
5740 hba->uic_error |= UFSHCD_UIC_NL_ERROR;
5741 retval |= IRQ_HANDLED;
5744 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_TRANSPORT_LAYER);
5745 if ((reg & UIC_TRANSPORT_LAYER_ERROR) &&
5746 (reg & UIC_TRANSPORT_LAYER_ERROR_CODE_MASK)) {
5747 ufshcd_update_reg_hist(&hba->ufs_stats.tl_err, reg);
5748 hba->uic_error |= UFSHCD_UIC_TL_ERROR;
5749 retval |= IRQ_HANDLED;
5752 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_DME);
5753 if ((reg & UIC_DME_ERROR) &&
5754 (reg & UIC_DME_ERROR_CODE_MASK)) {
5755 ufshcd_update_reg_hist(&hba->ufs_stats.dme_err, reg);
5756 hba->uic_error |= UFSHCD_UIC_DME_ERROR;
5757 retval |= IRQ_HANDLED;
5760 dev_dbg(hba->dev, "%s: UIC error flags = 0x%08x\n",
5761 __func__, hba->uic_error);
5765 static bool ufshcd_is_auto_hibern8_error(struct ufs_hba *hba,
5768 if (!ufshcd_is_auto_hibern8_supported(hba) ||
5769 !ufshcd_is_auto_hibern8_enabled(hba))
5772 if (!(intr_mask & UFSHCD_UIC_HIBERN8_MASK))
5775 if (hba->active_uic_cmd &&
5776 (hba->active_uic_cmd->command == UIC_CMD_DME_HIBER_ENTER ||
5777 hba->active_uic_cmd->command == UIC_CMD_DME_HIBER_EXIT))
5784 * ufshcd_check_errors - Check for errors that need s/w attention
5785 * @hba: per-adapter instance
5788 * IRQ_HANDLED - If interrupt is valid
5789 * IRQ_NONE - If invalid interrupt
5791 static irqreturn_t ufshcd_check_errors(struct ufs_hba *hba)
5793 bool queue_eh_work = false;
5794 irqreturn_t retval = IRQ_NONE;
5796 if (hba->errors & INT_FATAL_ERRORS) {
5797 ufshcd_update_reg_hist(&hba->ufs_stats.fatal_err, hba->errors);
5798 queue_eh_work = true;
5801 if (hba->errors & UIC_ERROR) {
5803 retval = ufshcd_update_uic_error(hba);
5805 queue_eh_work = true;
5808 if (hba->errors & UFSHCD_UIC_HIBERN8_MASK) {
5810 "%s: Auto Hibern8 %s failed - status: 0x%08x, upmcrs: 0x%08x\n",
5811 __func__, (hba->errors & UIC_HIBERNATE_ENTER) ?
5813 hba->errors, ufshcd_get_upmcrs(hba));
5814 ufshcd_update_reg_hist(&hba->ufs_stats.auto_hibern8_err,
5816 queue_eh_work = true;
5819 if (queue_eh_work) {
5821 * update the transfer error masks to sticky bits, let's do this
5822 * irrespective of current ufshcd_state.
5824 hba->saved_err |= hba->errors;
5825 hba->saved_uic_err |= hba->uic_error;
5827 /* handle fatal errors only when link is functional */
5828 if (hba->ufshcd_state == UFSHCD_STATE_OPERATIONAL) {
5829 /* block commands from scsi mid-layer */
5830 ufshcd_scsi_block_requests(hba);
5832 hba->ufshcd_state = UFSHCD_STATE_EH_SCHEDULED;
5834 /* dump controller state before resetting */
5835 if (hba->saved_err & (INT_FATAL_ERRORS | UIC_ERROR)) {
5836 bool pr_prdt = !!(hba->saved_err &
5837 SYSTEM_BUS_FATAL_ERROR);
5839 dev_err(hba->dev, "%s: saved_err 0x%x saved_uic_err 0x%x\n",
5840 __func__, hba->saved_err,
5841 hba->saved_uic_err);
5843 ufshcd_print_host_regs(hba);
5844 ufshcd_print_pwr_info(hba);
5845 ufshcd_print_tmrs(hba, hba->outstanding_tasks);
5846 ufshcd_print_trs(hba, hba->outstanding_reqs,
5849 schedule_work(&hba->eh_work);
5851 retval |= IRQ_HANDLED;
5854 * if (!queue_eh_work) -
5855 * Other errors are either non-fatal where host recovers
5856 * itself without s/w intervention or errors that will be
5857 * handled by the SCSI core layer.
5863 struct ufs_hba *hba;
5864 unsigned long pending;
5868 static bool ufshcd_compl_tm(struct request *req, void *priv, bool reserved)
5870 struct ctm_info *const ci = priv;
5871 struct completion *c;
5873 WARN_ON_ONCE(reserved);
5874 if (test_bit(req->tag, &ci->pending))
5877 c = req->end_io_data;
5884 * ufshcd_tmc_handler - handle task management function completion
5885 * @hba: per adapter instance
5888 * IRQ_HANDLED - If interrupt is valid
5889 * IRQ_NONE - If invalid interrupt
5891 static irqreturn_t ufshcd_tmc_handler(struct ufs_hba *hba)
5893 struct request_queue *q = hba->tmf_queue;
5894 struct ctm_info ci = {
5896 .pending = ufshcd_readl(hba, REG_UTP_TASK_REQ_DOOR_BELL),
5899 blk_mq_tagset_busy_iter(q->tag_set, ufshcd_compl_tm, &ci);
5900 return ci.ncpl ? IRQ_HANDLED : IRQ_NONE;
5904 * ufshcd_sl_intr - Interrupt service routine
5905 * @hba: per adapter instance
5906 * @intr_status: contains interrupts generated by the controller
5909 * IRQ_HANDLED - If interrupt is valid
5910 * IRQ_NONE - If invalid interrupt
5912 static irqreturn_t ufshcd_sl_intr(struct ufs_hba *hba, u32 intr_status)
5914 irqreturn_t retval = IRQ_NONE;
5916 hba->errors = UFSHCD_ERROR_MASK & intr_status;
5918 if (ufshcd_is_auto_hibern8_error(hba, intr_status))
5919 hba->errors |= (UFSHCD_UIC_HIBERN8_MASK & intr_status);
5922 retval |= ufshcd_check_errors(hba);
5924 if (intr_status & UFSHCD_UIC_MASK)
5925 retval |= ufshcd_uic_cmd_compl(hba, intr_status);
5927 if (intr_status & UTP_TASK_REQ_COMPL)
5928 retval |= ufshcd_tmc_handler(hba);
5930 if (intr_status & UTP_TRANSFER_REQ_COMPL)
5931 retval |= ufshcd_transfer_req_compl(hba);
5937 * ufshcd_intr - Main interrupt service routine
5939 * @__hba: pointer to adapter instance
5942 * IRQ_HANDLED - If interrupt is valid
5943 * IRQ_NONE - If invalid interrupt
5945 static irqreturn_t ufshcd_intr(int irq, void *__hba)
5947 u32 intr_status, enabled_intr_status = 0;
5948 irqreturn_t retval = IRQ_NONE;
5949 struct ufs_hba *hba = __hba;
5950 int retries = hba->nutrs;
5952 spin_lock(hba->host->host_lock);
5953 intr_status = ufshcd_readl(hba, REG_INTERRUPT_STATUS);
5956 * There could be max of hba->nutrs reqs in flight and in worst case
5957 * if the reqs get finished 1 by 1 after the interrupt status is
5958 * read, make sure we handle them by checking the interrupt status
5959 * again in a loop until we process all of the reqs before returning.
5961 while (intr_status && retries--) {
5962 enabled_intr_status =
5963 intr_status & ufshcd_readl(hba, REG_INTERRUPT_ENABLE);
5965 ufshcd_writel(hba, intr_status, REG_INTERRUPT_STATUS);
5966 if (enabled_intr_status)
5967 retval |= ufshcd_sl_intr(hba, enabled_intr_status);
5969 intr_status = ufshcd_readl(hba, REG_INTERRUPT_STATUS);
5972 if (enabled_intr_status && retval == IRQ_NONE) {
5973 dev_err(hba->dev, "%s: Unhandled interrupt 0x%08x\n",
5974 __func__, intr_status);
5975 ufshcd_dump_regs(hba, 0, UFSHCI_REG_SPACE_SIZE, "host_regs: ");
5978 spin_unlock(hba->host->host_lock);
5982 static int ufshcd_clear_tm_cmd(struct ufs_hba *hba, int tag)
5985 u32 mask = 1 << tag;
5986 unsigned long flags;
5988 if (!test_bit(tag, &hba->outstanding_tasks))
5991 spin_lock_irqsave(hba->host->host_lock, flags);
5992 ufshcd_utmrl_clear(hba, tag);
5993 spin_unlock_irqrestore(hba->host->host_lock, flags);
5995 /* poll for max. 1 sec to clear door bell register by h/w */
5996 err = ufshcd_wait_for_register(hba,
5997 REG_UTP_TASK_REQ_DOOR_BELL,
5998 mask, 0, 1000, 1000);
6003 static int __ufshcd_issue_tm_cmd(struct ufs_hba *hba,
6004 struct utp_task_req_desc *treq, u8 tm_function)
6006 struct request_queue *q = hba->tmf_queue;
6007 struct Scsi_Host *host = hba->host;
6008 DECLARE_COMPLETION_ONSTACK(wait);
6009 struct request *req;
6010 unsigned long flags;
6011 int free_slot, task_tag, err;
6014 * Get free slot, sleep if slots are unavailable.
6015 * Even though we use wait_event() which sleeps indefinitely,
6016 * the maximum wait time is bounded by %TM_CMD_TIMEOUT.
6018 req = blk_get_request(q, REQ_OP_DRV_OUT, BLK_MQ_REQ_RESERVED);
6019 req->end_io_data = &wait;
6020 free_slot = req->tag;
6021 WARN_ON_ONCE(free_slot < 0 || free_slot >= hba->nutmrs);
6022 ufshcd_hold(hba, false);
6024 spin_lock_irqsave(host->host_lock, flags);
6025 task_tag = hba->nutrs + free_slot;
6027 treq->req_header.dword_0 |= cpu_to_be32(task_tag);
6029 memcpy(hba->utmrdl_base_addr + free_slot, treq, sizeof(*treq));
6030 ufshcd_vops_setup_task_mgmt(hba, free_slot, tm_function);
6032 /* send command to the controller */
6033 __set_bit(free_slot, &hba->outstanding_tasks);
6035 /* Make sure descriptors are ready before ringing the task doorbell */
6038 ufshcd_writel(hba, 1 << free_slot, REG_UTP_TASK_REQ_DOOR_BELL);
6039 /* Make sure that doorbell is committed immediately */
6042 spin_unlock_irqrestore(host->host_lock, flags);
6044 ufshcd_add_tm_upiu_trace(hba, task_tag, "tm_send");
6046 /* wait until the task management command is completed */
6047 err = wait_for_completion_io_timeout(&wait,
6048 msecs_to_jiffies(TM_CMD_TIMEOUT));
6051 * Make sure that ufshcd_compl_tm() does not trigger a
6054 req->end_io_data = NULL;
6055 ufshcd_add_tm_upiu_trace(hba, task_tag, "tm_complete_err");
6056 dev_err(hba->dev, "%s: task management cmd 0x%.2x timed-out\n",
6057 __func__, tm_function);
6058 if (ufshcd_clear_tm_cmd(hba, free_slot))
6059 dev_WARN(hba->dev, "%s: unable clear tm cmd (slot %d) after timeout\n",
6060 __func__, free_slot);
6064 memcpy(treq, hba->utmrdl_base_addr + free_slot, sizeof(*treq));
6066 ufshcd_add_tm_upiu_trace(hba, task_tag, "tm_complete");
6069 spin_lock_irqsave(hba->host->host_lock, flags);
6070 __clear_bit(free_slot, &hba->outstanding_tasks);
6071 spin_unlock_irqrestore(hba->host->host_lock, flags);
6073 blk_put_request(req);
6075 ufshcd_release(hba);
6080 * ufshcd_issue_tm_cmd - issues task management commands to controller
6081 * @hba: per adapter instance
6082 * @lun_id: LUN ID to which TM command is sent
6083 * @task_id: task ID to which the TM command is applicable
6084 * @tm_function: task management function opcode
6085 * @tm_response: task management service response return value
6087 * Returns non-zero value on error, zero on success.
6089 static int ufshcd_issue_tm_cmd(struct ufs_hba *hba, int lun_id, int task_id,
6090 u8 tm_function, u8 *tm_response)
6092 struct utp_task_req_desc treq = { { 0 }, };
6095 /* Configure task request descriptor */
6096 treq.header.dword_0 = cpu_to_le32(UTP_REQ_DESC_INT_CMD);
6097 treq.header.dword_2 = cpu_to_le32(OCS_INVALID_COMMAND_STATUS);
6099 /* Configure task request UPIU */
6100 treq.req_header.dword_0 = cpu_to_be32(lun_id << 8) |
6101 cpu_to_be32(UPIU_TRANSACTION_TASK_REQ << 24);
6102 treq.req_header.dword_1 = cpu_to_be32(tm_function << 16);
6105 * The host shall provide the same value for LUN field in the basic
6106 * header and for Input Parameter.
6108 treq.input_param1 = cpu_to_be32(lun_id);
6109 treq.input_param2 = cpu_to_be32(task_id);
6111 err = __ufshcd_issue_tm_cmd(hba, &treq, tm_function);
6112 if (err == -ETIMEDOUT)
6115 ocs_value = le32_to_cpu(treq.header.dword_2) & MASK_OCS;
6116 if (ocs_value != OCS_SUCCESS)
6117 dev_err(hba->dev, "%s: failed, ocs = 0x%x\n",
6118 __func__, ocs_value);
6119 else if (tm_response)
6120 *tm_response = be32_to_cpu(treq.output_param1) &
6121 MASK_TM_SERVICE_RESP;
6126 * ufshcd_issue_devman_upiu_cmd - API for sending "utrd" type requests
6127 * @hba: per-adapter instance
6128 * @req_upiu: upiu request
6129 * @rsp_upiu: upiu reply
6130 * @desc_buff: pointer to descriptor buffer, NULL if NA
6131 * @buff_len: descriptor size, 0 if NA
6132 * @cmd_type: specifies the type (NOP, Query...)
6133 * @desc_op: descriptor operation
6135 * Those type of requests uses UTP Transfer Request Descriptor - utrd.
6136 * Therefore, it "rides" the device management infrastructure: uses its tag and
6137 * tasks work queues.
6139 * Since there is only one available tag for device management commands,
6140 * the caller is expected to hold the hba->dev_cmd.lock mutex.
6142 static int ufshcd_issue_devman_upiu_cmd(struct ufs_hba *hba,
6143 struct utp_upiu_req *req_upiu,
6144 struct utp_upiu_req *rsp_upiu,
6145 u8 *desc_buff, int *buff_len,
6146 enum dev_cmd_type cmd_type,
6147 enum query_opcode desc_op)
6149 struct request_queue *q = hba->cmd_queue;
6150 struct request *req;
6151 struct ufshcd_lrb *lrbp;
6154 struct completion wait;
6155 unsigned long flags;
6158 down_read(&hba->clk_scaling_lock);
6160 req = blk_get_request(q, REQ_OP_DRV_OUT, 0);
6166 WARN_ON_ONCE(!ufshcd_valid_tag(hba, tag));
6168 init_completion(&wait);
6169 lrbp = &hba->lrb[tag];
6173 lrbp->sense_bufflen = 0;
6174 lrbp->sense_buffer = NULL;
6175 lrbp->task_tag = tag;
6177 lrbp->intr_cmd = true;
6178 ufshcd_prepare_lrbp_crypto(NULL, lrbp);
6179 hba->dev_cmd.type = cmd_type;
6181 switch (hba->ufs_version) {
6182 case UFSHCI_VERSION_10:
6183 case UFSHCI_VERSION_11:
6184 lrbp->command_type = UTP_CMD_TYPE_DEV_MANAGE;
6187 lrbp->command_type = UTP_CMD_TYPE_UFS_STORAGE;
6191 /* update the task tag in the request upiu */
6192 req_upiu->header.dword_0 |= cpu_to_be32(tag);
6194 ufshcd_prepare_req_desc_hdr(lrbp, &upiu_flags, DMA_NONE);
6196 /* just copy the upiu request as it is */
6197 memcpy(lrbp->ucd_req_ptr, req_upiu, sizeof(*lrbp->ucd_req_ptr));
6198 if (desc_buff && desc_op == UPIU_QUERY_OPCODE_WRITE_DESC) {
6199 /* The Data Segment Area is optional depending upon the query
6200 * function value. for WRITE DESCRIPTOR, the data segment
6201 * follows right after the tsf.
6203 memcpy(lrbp->ucd_req_ptr + 1, desc_buff, *buff_len);
6207 memset(lrbp->ucd_rsp_ptr, 0, sizeof(struct utp_upiu_rsp));
6209 hba->dev_cmd.complete = &wait;
6211 /* Make sure descriptors are ready before ringing the doorbell */
6213 spin_lock_irqsave(hba->host->host_lock, flags);
6214 ufshcd_send_command(hba, tag);
6215 spin_unlock_irqrestore(hba->host->host_lock, flags);
6218 * ignore the returning value here - ufshcd_check_query_response is
6219 * bound to fail since dev_cmd.query and dev_cmd.type were left empty.
6220 * read the response directly ignoring all errors.
6222 ufshcd_wait_for_dev_cmd(hba, lrbp, QUERY_REQ_TIMEOUT);
6224 /* just copy the upiu response as it is */
6225 memcpy(rsp_upiu, lrbp->ucd_rsp_ptr, sizeof(*rsp_upiu));
6226 if (desc_buff && desc_op == UPIU_QUERY_OPCODE_READ_DESC) {
6227 u8 *descp = (u8 *)lrbp->ucd_rsp_ptr + sizeof(*rsp_upiu);
6228 u16 resp_len = be32_to_cpu(lrbp->ucd_rsp_ptr->header.dword_2) &
6229 MASK_QUERY_DATA_SEG_LEN;
6231 if (*buff_len >= resp_len) {
6232 memcpy(desc_buff, descp, resp_len);
6233 *buff_len = resp_len;
6236 "%s: rsp size %d is bigger than buffer size %d",
6237 __func__, resp_len, *buff_len);
6243 blk_put_request(req);
6245 up_read(&hba->clk_scaling_lock);
6250 * ufshcd_exec_raw_upiu_cmd - API function for sending raw upiu commands
6251 * @hba: per-adapter instance
6252 * @req_upiu: upiu request
6253 * @rsp_upiu: upiu reply - only 8 DW as we do not support scsi commands
6254 * @msgcode: message code, one of UPIU Transaction Codes Initiator to Target
6255 * @desc_buff: pointer to descriptor buffer, NULL if NA
6256 * @buff_len: descriptor size, 0 if NA
6257 * @desc_op: descriptor operation
6259 * Supports UTP Transfer requests (nop and query), and UTP Task
6260 * Management requests.
6261 * It is up to the caller to fill the upiu conent properly, as it will
6262 * be copied without any further input validations.
6264 int ufshcd_exec_raw_upiu_cmd(struct ufs_hba *hba,
6265 struct utp_upiu_req *req_upiu,
6266 struct utp_upiu_req *rsp_upiu,
6268 u8 *desc_buff, int *buff_len,
6269 enum query_opcode desc_op)
6272 enum dev_cmd_type cmd_type = DEV_CMD_TYPE_QUERY;
6273 struct utp_task_req_desc treq = { { 0 }, };
6275 u8 tm_f = be32_to_cpu(req_upiu->header.dword_1) >> 16 & MASK_TM_FUNC;
6278 case UPIU_TRANSACTION_NOP_OUT:
6279 cmd_type = DEV_CMD_TYPE_NOP;
6281 case UPIU_TRANSACTION_QUERY_REQ:
6282 ufshcd_hold(hba, false);
6283 mutex_lock(&hba->dev_cmd.lock);
6284 err = ufshcd_issue_devman_upiu_cmd(hba, req_upiu, rsp_upiu,
6285 desc_buff, buff_len,
6287 mutex_unlock(&hba->dev_cmd.lock);
6288 ufshcd_release(hba);
6291 case UPIU_TRANSACTION_TASK_REQ:
6292 treq.header.dword_0 = cpu_to_le32(UTP_REQ_DESC_INT_CMD);
6293 treq.header.dword_2 = cpu_to_le32(OCS_INVALID_COMMAND_STATUS);
6295 memcpy(&treq.req_header, req_upiu, sizeof(*req_upiu));
6297 err = __ufshcd_issue_tm_cmd(hba, &treq, tm_f);
6298 if (err == -ETIMEDOUT)
6301 ocs_value = le32_to_cpu(treq.header.dword_2) & MASK_OCS;
6302 if (ocs_value != OCS_SUCCESS) {
6303 dev_err(hba->dev, "%s: failed, ocs = 0x%x\n", __func__,
6308 memcpy(rsp_upiu, &treq.rsp_header, sizeof(*rsp_upiu));
6321 * ufshcd_eh_device_reset_handler - device reset handler registered to
6323 * @cmd: SCSI command pointer
6325 * Returns SUCCESS/FAILED
6327 static int ufshcd_eh_device_reset_handler(struct scsi_cmnd *cmd)
6329 struct Scsi_Host *host;
6330 struct ufs_hba *hba;
6335 struct ufshcd_lrb *lrbp;
6336 unsigned long flags;
6338 host = cmd->device->host;
6339 hba = shost_priv(host);
6340 tag = cmd->request->tag;
6342 lrbp = &hba->lrb[tag];
6343 err = ufshcd_issue_tm_cmd(hba, lrbp->lun, 0, UFS_LOGICAL_RESET, &resp);
6344 if (err || resp != UPIU_TASK_MANAGEMENT_FUNC_COMPL) {
6350 /* clear the commands that were pending for corresponding LUN */
6351 for_each_set_bit(pos, &hba->outstanding_reqs, hba->nutrs) {
6352 if (hba->lrb[pos].lun == lrbp->lun) {
6353 err = ufshcd_clear_cmd(hba, pos);
6358 spin_lock_irqsave(host->host_lock, flags);
6359 ufshcd_transfer_req_compl(hba);
6360 spin_unlock_irqrestore(host->host_lock, flags);
6363 hba->req_abort_count = 0;
6364 ufshcd_update_reg_hist(&hba->ufs_stats.dev_reset, (u32)err);
6368 dev_err(hba->dev, "%s: failed with err %d\n", __func__, err);
6374 static void ufshcd_set_req_abort_skip(struct ufs_hba *hba, unsigned long bitmap)
6376 struct ufshcd_lrb *lrbp;
6379 for_each_set_bit(tag, &bitmap, hba->nutrs) {
6380 lrbp = &hba->lrb[tag];
6381 lrbp->req_abort_skip = true;
6386 * ufshcd_abort - abort a specific command
6387 * @cmd: SCSI command pointer
6389 * Abort the pending command in device by sending UFS_ABORT_TASK task management
6390 * command, and in host controller by clearing the door-bell register. There can
6391 * be race between controller sending the command to the device while abort is
6392 * issued. To avoid that, first issue UFS_QUERY_TASK to check if the command is
6393 * really issued and then try to abort it.
6395 * Returns SUCCESS/FAILED
6397 static int ufshcd_abort(struct scsi_cmnd *cmd)
6399 struct Scsi_Host *host;
6400 struct ufs_hba *hba;
6401 unsigned long flags;
6406 struct ufshcd_lrb *lrbp;
6409 host = cmd->device->host;
6410 hba = shost_priv(host);
6411 tag = cmd->request->tag;
6412 lrbp = &hba->lrb[tag];
6413 if (!ufshcd_valid_tag(hba, tag)) {
6415 "%s: invalid command tag %d: cmd=0x%p, cmd->request=0x%p",
6416 __func__, tag, cmd, cmd->request);
6421 * Task abort to the device W-LUN is illegal. When this command
6422 * will fail, due to spec violation, scsi err handling next step
6423 * will be to send LU reset which, again, is a spec violation.
6424 * To avoid these unnecessary/illegal step we skip to the last error
6425 * handling stage: reset and restore.
6427 if (lrbp->lun == UFS_UPIU_UFS_DEVICE_WLUN)
6428 return ufshcd_eh_host_reset_handler(cmd);
6430 ufshcd_hold(hba, false);
6431 reg = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
6432 /* If command is already aborted/completed, return SUCCESS */
6433 if (!(test_bit(tag, &hba->outstanding_reqs))) {
6435 "%s: cmd at tag %d already completed, outstanding=0x%lx, doorbell=0x%x\n",
6436 __func__, tag, hba->outstanding_reqs, reg);
6440 /* Print Transfer Request of aborted task */
6441 dev_info(hba->dev, "%s: Device abort task at tag %d\n", __func__, tag);
6444 * Print detailed info about aborted request.
6445 * As more than one request might get aborted at the same time,
6446 * print full information only for the first aborted request in order
6447 * to reduce repeated printouts. For other aborted requests only print
6450 scsi_print_command(hba->lrb[tag].cmd);
6451 if (!hba->req_abort_count) {
6452 ufshcd_update_reg_hist(&hba->ufs_stats.task_abort, 0);
6453 ufshcd_print_host_regs(hba);
6454 ufshcd_print_host_state(hba);
6455 ufshcd_print_pwr_info(hba);
6456 ufshcd_print_trs(hba, 1 << tag, true);
6458 ufshcd_print_trs(hba, 1 << tag, false);
6460 hba->req_abort_count++;
6462 if (!(reg & (1 << tag))) {
6464 "%s: cmd was completed, but without a notifying intr, tag = %d",
6469 /* Skip task abort in case previous aborts failed and report failure */
6470 if (lrbp->req_abort_skip) {
6475 for (poll_cnt = 100; poll_cnt; poll_cnt--) {
6476 err = ufshcd_issue_tm_cmd(hba, lrbp->lun, lrbp->task_tag,
6477 UFS_QUERY_TASK, &resp);
6478 if (!err && resp == UPIU_TASK_MANAGEMENT_FUNC_SUCCEEDED) {
6479 /* cmd pending in the device */
6480 dev_err(hba->dev, "%s: cmd pending in the device. tag = %d\n",
6483 } else if (!err && resp == UPIU_TASK_MANAGEMENT_FUNC_COMPL) {
6485 * cmd not pending in the device, check if it is
6488 dev_err(hba->dev, "%s: cmd at tag %d not pending in the device.\n",
6490 reg = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
6491 if (reg & (1 << tag)) {
6492 /* sleep for max. 200us to stabilize */
6493 usleep_range(100, 200);
6496 /* command completed already */
6497 dev_err(hba->dev, "%s: cmd at tag %d successfully cleared from DB.\n",
6502 "%s: no response from device. tag = %d, err %d\n",
6503 __func__, tag, err);
6505 err = resp; /* service response error */
6515 err = ufshcd_issue_tm_cmd(hba, lrbp->lun, lrbp->task_tag,
6516 UFS_ABORT_TASK, &resp);
6517 if (err || resp != UPIU_TASK_MANAGEMENT_FUNC_COMPL) {
6519 err = resp; /* service response error */
6520 dev_err(hba->dev, "%s: issued. tag = %d, err %d\n",
6521 __func__, tag, err);
6526 err = ufshcd_clear_cmd(hba, tag);
6528 dev_err(hba->dev, "%s: Failed clearing cmd at tag %d, err %d\n",
6529 __func__, tag, err);
6534 scsi_dma_unmap(cmd);
6536 spin_lock_irqsave(host->host_lock, flags);
6537 ufshcd_outstanding_req_clear(hba, tag);
6538 hba->lrb[tag].cmd = NULL;
6539 spin_unlock_irqrestore(host->host_lock, flags);
6545 dev_err(hba->dev, "%s: failed with err %d\n", __func__, err);
6546 ufshcd_set_req_abort_skip(hba, hba->outstanding_reqs);
6551 * This ufshcd_release() corresponds to the original scsi cmd that got
6552 * aborted here (as we won't get any IRQ for it).
6554 ufshcd_release(hba);
6559 * ufshcd_host_reset_and_restore - reset and restore host controller
6560 * @hba: per-adapter instance
6562 * Note that host controller reset may issue DME_RESET to
6563 * local and remote (device) Uni-Pro stack and the attributes
6564 * are reset to default state.
6566 * Returns zero on success, non-zero on failure
6568 static int ufshcd_host_reset_and_restore(struct ufs_hba *hba)
6571 unsigned long flags;
6574 * Stop the host controller and complete the requests
6577 ufshcd_hba_stop(hba);
6579 spin_lock_irqsave(hba->host->host_lock, flags);
6580 hba->silence_err_logs = true;
6581 ufshcd_complete_requests(hba);
6582 hba->silence_err_logs = false;
6583 spin_unlock_irqrestore(hba->host->host_lock, flags);
6585 /* scale up clocks to max frequency before full reinitialization */
6586 ufshcd_set_clk_freq(hba, true);
6588 err = ufshcd_hba_enable(hba);
6592 /* Establish the link again and restore the device */
6593 err = ufshcd_probe_hba(hba, false);
6595 if (!err && (hba->ufshcd_state != UFSHCD_STATE_OPERATIONAL))
6599 dev_err(hba->dev, "%s: Host init failed %d\n", __func__, err);
6600 ufshcd_update_reg_hist(&hba->ufs_stats.host_reset, (u32)err);
6605 * ufshcd_reset_and_restore - reset and re-initialize host/device
6606 * @hba: per-adapter instance
6608 * Reset and recover device, host and re-establish link. This
6609 * is helpful to recover the communication in fatal error conditions.
6611 * Returns zero on success, non-zero on failure
6613 static int ufshcd_reset_and_restore(struct ufs_hba *hba)
6616 int retries = MAX_HOST_RESET_RETRIES;
6619 /* Reset the attached device */
6620 ufshcd_vops_device_reset(hba);
6622 err = ufshcd_host_reset_and_restore(hba);
6623 } while (err && --retries);
6629 * ufshcd_eh_host_reset_handler - host reset handler registered to scsi layer
6630 * @cmd: SCSI command pointer
6632 * Returns SUCCESS/FAILED
6634 static int ufshcd_eh_host_reset_handler(struct scsi_cmnd *cmd)
6637 unsigned long flags;
6638 struct ufs_hba *hba;
6640 hba = shost_priv(cmd->device->host);
6642 ufshcd_hold(hba, false);
6644 * Check if there is any race with fatal error handling.
6645 * If so, wait for it to complete. Even though fatal error
6646 * handling does reset and restore in some cases, don't assume
6647 * anything out of it. We are just avoiding race here.
6650 spin_lock_irqsave(hba->host->host_lock, flags);
6651 if (!(work_pending(&hba->eh_work) ||
6652 hba->ufshcd_state == UFSHCD_STATE_RESET ||
6653 hba->ufshcd_state == UFSHCD_STATE_EH_SCHEDULED))
6655 spin_unlock_irqrestore(hba->host->host_lock, flags);
6656 dev_dbg(hba->dev, "%s: reset in progress\n", __func__);
6657 flush_work(&hba->eh_work);
6660 hba->ufshcd_state = UFSHCD_STATE_RESET;
6661 ufshcd_set_eh_in_progress(hba);
6662 spin_unlock_irqrestore(hba->host->host_lock, flags);
6664 err = ufshcd_reset_and_restore(hba);
6666 spin_lock_irqsave(hba->host->host_lock, flags);
6669 hba->ufshcd_state = UFSHCD_STATE_OPERATIONAL;
6672 hba->ufshcd_state = UFSHCD_STATE_ERROR;
6674 ufshcd_clear_eh_in_progress(hba);
6675 spin_unlock_irqrestore(hba->host->host_lock, flags);
6677 ufshcd_release(hba);
6682 * ufshcd_get_max_icc_level - calculate the ICC level
6683 * @sup_curr_uA: max. current supported by the regulator
6684 * @start_scan: row at the desc table to start scan from
6685 * @buff: power descriptor buffer
6687 * Returns calculated max ICC level for specific regulator
6689 static u32 ufshcd_get_max_icc_level(int sup_curr_uA, u32 start_scan, char *buff)
6696 for (i = start_scan; i >= 0; i--) {
6697 data = be16_to_cpup((__be16 *)&buff[2 * i]);
6698 unit = (data & ATTR_ICC_LVL_UNIT_MASK) >>
6699 ATTR_ICC_LVL_UNIT_OFFSET;
6700 curr_uA = data & ATTR_ICC_LVL_VALUE_MASK;
6702 case UFSHCD_NANO_AMP:
6703 curr_uA = curr_uA / 1000;
6705 case UFSHCD_MILI_AMP:
6706 curr_uA = curr_uA * 1000;
6709 curr_uA = curr_uA * 1000 * 1000;
6711 case UFSHCD_MICRO_AMP:
6715 if (sup_curr_uA >= curr_uA)
6720 pr_err("%s: Couldn't find valid icc_level = %d", __func__, i);
6727 * ufshcd_calc_icc_level - calculate the max ICC level
6728 * In case regulators are not initialized we'll return 0
6729 * @hba: per-adapter instance
6730 * @desc_buf: power descriptor buffer to extract ICC levels from.
6731 * @len: length of desc_buff
6733 * Returns calculated ICC level
6735 static u32 ufshcd_find_max_sup_active_icc_level(struct ufs_hba *hba,
6736 u8 *desc_buf, int len)
6740 if (!hba->vreg_info.vcc || !hba->vreg_info.vccq ||
6741 !hba->vreg_info.vccq2) {
6743 "%s: Regulator capability was not set, actvIccLevel=%d",
6744 __func__, icc_level);
6748 if (hba->vreg_info.vcc && hba->vreg_info.vcc->max_uA)
6749 icc_level = ufshcd_get_max_icc_level(
6750 hba->vreg_info.vcc->max_uA,
6751 POWER_DESC_MAX_ACTV_ICC_LVLS - 1,
6752 &desc_buf[PWR_DESC_ACTIVE_LVLS_VCC_0]);
6754 if (hba->vreg_info.vccq && hba->vreg_info.vccq->max_uA)
6755 icc_level = ufshcd_get_max_icc_level(
6756 hba->vreg_info.vccq->max_uA,
6758 &desc_buf[PWR_DESC_ACTIVE_LVLS_VCCQ_0]);
6760 if (hba->vreg_info.vccq2 && hba->vreg_info.vccq2->max_uA)
6761 icc_level = ufshcd_get_max_icc_level(
6762 hba->vreg_info.vccq2->max_uA,
6764 &desc_buf[PWR_DESC_ACTIVE_LVLS_VCCQ2_0]);
6769 static void ufshcd_set_active_icc_lvl(struct ufs_hba *hba)
6772 int buff_len = hba->desc_size[QUERY_DESC_IDN_POWER];
6776 desc_buf = kmalloc(buff_len, GFP_KERNEL);
6780 ret = ufshcd_read_desc_param(hba, QUERY_DESC_IDN_POWER, 0, 0,
6781 desc_buf, buff_len);
6784 "%s: Failed reading power descriptor.len = %d ret = %d",
6785 __func__, buff_len, ret);
6789 icc_level = ufshcd_find_max_sup_active_icc_level(hba, desc_buf,
6791 dev_dbg(hba->dev, "%s: setting icc_level 0x%x", __func__, icc_level);
6793 ret = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_WRITE_ATTR,
6794 QUERY_ATTR_IDN_ACTIVE_ICC_LVL, 0, 0, &icc_level);
6798 "%s: Failed configuring bActiveICCLevel = %d ret = %d",
6799 __func__, icc_level, ret);
6805 static inline void ufshcd_blk_pm_runtime_init(struct scsi_device *sdev)
6807 scsi_autopm_get_device(sdev);
6808 blk_pm_runtime_init(sdev->request_queue, &sdev->sdev_gendev);
6809 if (sdev->rpm_autosuspend)
6810 pm_runtime_set_autosuspend_delay(&sdev->sdev_gendev,
6811 RPM_AUTOSUSPEND_DELAY_MS);
6812 scsi_autopm_put_device(sdev);
6816 * ufshcd_scsi_add_wlus - Adds required W-LUs
6817 * @hba: per-adapter instance
6819 * UFS device specification requires the UFS devices to support 4 well known
6821 * "REPORT_LUNS" (address: 01h)
6822 * "UFS Device" (address: 50h)
6823 * "RPMB" (address: 44h)
6824 * "BOOT" (address: 30h)
6825 * UFS device's power management needs to be controlled by "POWER CONDITION"
6826 * field of SSU (START STOP UNIT) command. But this "power condition" field
6827 * will take effect only when its sent to "UFS device" well known logical unit
6828 * hence we require the scsi_device instance to represent this logical unit in
6829 * order for the UFS host driver to send the SSU command for power management.
6831 * We also require the scsi_device instance for "RPMB" (Replay Protected Memory
6832 * Block) LU so user space process can control this LU. User space may also
6833 * want to have access to BOOT LU.
6835 * This function adds scsi device instances for each of all well known LUs
6836 * (except "REPORT LUNS" LU).
6838 * Returns zero on success (all required W-LUs are added successfully),
6839 * non-zero error value on failure (if failed to add any of the required W-LU).
6841 static int ufshcd_scsi_add_wlus(struct ufs_hba *hba)
6844 struct scsi_device *sdev_rpmb;
6845 struct scsi_device *sdev_boot;
6847 hba->sdev_ufs_device = __scsi_add_device(hba->host, 0, 0,
6848 ufshcd_upiu_wlun_to_scsi_wlun(UFS_UPIU_UFS_DEVICE_WLUN), NULL);
6849 if (IS_ERR(hba->sdev_ufs_device)) {
6850 ret = PTR_ERR(hba->sdev_ufs_device);
6851 hba->sdev_ufs_device = NULL;
6854 ufshcd_blk_pm_runtime_init(hba->sdev_ufs_device);
6855 scsi_device_put(hba->sdev_ufs_device);
6857 sdev_rpmb = __scsi_add_device(hba->host, 0, 0,
6858 ufshcd_upiu_wlun_to_scsi_wlun(UFS_UPIU_RPMB_WLUN), NULL);
6859 if (IS_ERR(sdev_rpmb)) {
6860 ret = PTR_ERR(sdev_rpmb);
6861 goto remove_sdev_ufs_device;
6863 ufshcd_blk_pm_runtime_init(sdev_rpmb);
6864 scsi_device_put(sdev_rpmb);
6866 sdev_boot = __scsi_add_device(hba->host, 0, 0,
6867 ufshcd_upiu_wlun_to_scsi_wlun(UFS_UPIU_BOOT_WLUN), NULL);
6868 if (IS_ERR(sdev_boot)) {
6869 dev_err(hba->dev, "%s: BOOT WLUN not found\n", __func__);
6871 ufshcd_blk_pm_runtime_init(sdev_boot);
6872 scsi_device_put(sdev_boot);
6876 remove_sdev_ufs_device:
6877 scsi_remove_device(hba->sdev_ufs_device);
6882 static void ufshcd_wb_probe(struct ufs_hba *hba, u8 *desc_buf)
6884 struct ufs_dev_info *dev_info = &hba->dev_info;
6886 u32 d_lu_wb_buf_alloc;
6888 if (!ufshcd_is_wb_allowed(hba))
6891 * Probe WB only for UFS-2.2 and UFS-3.1 (and later) devices or
6892 * UFS devices with quirk UFS_DEVICE_QUIRK_SUPPORT_EXTENDED_FEATURES
6895 if (!(dev_info->wspecversion >= 0x310 ||
6896 dev_info->wspecversion == 0x220 ||
6897 (hba->dev_quirks & UFS_DEVICE_QUIRK_SUPPORT_EXTENDED_FEATURES)))
6900 if (hba->desc_size[QUERY_DESC_IDN_DEVICE] <
6901 DEVICE_DESC_PARAM_EXT_UFS_FEATURE_SUP + 4)
6904 dev_info->d_ext_ufs_feature_sup =
6905 get_unaligned_be32(desc_buf +
6906 DEVICE_DESC_PARAM_EXT_UFS_FEATURE_SUP);
6908 if (!(dev_info->d_ext_ufs_feature_sup & UFS_DEV_WRITE_BOOSTER_SUP))
6912 * WB may be supported but not configured while provisioning.
6913 * The spec says, in dedicated wb buffer mode,
6914 * a max of 1 lun would have wb buffer configured.
6915 * Now only shared buffer mode is supported.
6917 dev_info->b_wb_buffer_type =
6918 desc_buf[DEVICE_DESC_PARAM_WB_TYPE];
6920 dev_info->b_presrv_uspc_en =
6921 desc_buf[DEVICE_DESC_PARAM_WB_PRESRV_USRSPC_EN];
6923 if (dev_info->b_wb_buffer_type == WB_BUF_MODE_SHARED) {
6924 dev_info->d_wb_alloc_units =
6925 get_unaligned_be32(desc_buf +
6926 DEVICE_DESC_PARAM_WB_SHARED_ALLOC_UNITS);
6927 if (!dev_info->d_wb_alloc_units)
6930 for (lun = 0; lun < UFS_UPIU_MAX_WB_LUN_ID; lun++) {
6931 d_lu_wb_buf_alloc = 0;
6932 ufshcd_read_unit_desc_param(hba,
6934 UNIT_DESC_PARAM_WB_BUF_ALLOC_UNITS,
6935 (u8 *)&d_lu_wb_buf_alloc,
6936 sizeof(d_lu_wb_buf_alloc));
6937 if (d_lu_wb_buf_alloc) {
6938 dev_info->wb_dedicated_lu = lun;
6943 if (!d_lu_wb_buf_alloc)
6949 hba->caps &= ~UFSHCD_CAP_WB_EN;
6952 void ufshcd_fixup_dev_quirks(struct ufs_hba *hba, struct ufs_dev_fix *fixups)
6954 struct ufs_dev_fix *f;
6955 struct ufs_dev_info *dev_info = &hba->dev_info;
6960 for (f = fixups; f->quirk; f++) {
6961 if ((f->wmanufacturerid == dev_info->wmanufacturerid ||
6962 f->wmanufacturerid == UFS_ANY_VENDOR) &&
6963 ((dev_info->model &&
6964 STR_PRFX_EQUAL(f->model, dev_info->model)) ||
6965 !strcmp(f->model, UFS_ANY_MODEL)))
6966 hba->dev_quirks |= f->quirk;
6969 EXPORT_SYMBOL_GPL(ufshcd_fixup_dev_quirks);
6971 static void ufs_fixup_device_setup(struct ufs_hba *hba)
6973 /* fix by general quirk table */
6974 ufshcd_fixup_dev_quirks(hba, ufs_fixups);
6976 /* allow vendors to fix quirks */
6977 ufshcd_vops_fixup_dev_quirks(hba);
6980 static int ufs_get_device_desc(struct ufs_hba *hba)
6985 struct ufs_dev_info *dev_info = &hba->dev_info;
6987 desc_buf = kmalloc(QUERY_DESC_MAX_SIZE, GFP_KERNEL);
6993 err = ufshcd_read_desc_param(hba, QUERY_DESC_IDN_DEVICE, 0, 0, desc_buf,
6994 hba->desc_size[QUERY_DESC_IDN_DEVICE]);
6996 dev_err(hba->dev, "%s: Failed reading Device Desc. err = %d\n",
7002 * getting vendor (manufacturerID) and Bank Index in big endian
7005 dev_info->wmanufacturerid = desc_buf[DEVICE_DESC_PARAM_MANF_ID] << 8 |
7006 desc_buf[DEVICE_DESC_PARAM_MANF_ID + 1];
7008 /* getting Specification Version in big endian format */
7009 dev_info->wspecversion = desc_buf[DEVICE_DESC_PARAM_SPEC_VER] << 8 |
7010 desc_buf[DEVICE_DESC_PARAM_SPEC_VER + 1];
7012 model_index = desc_buf[DEVICE_DESC_PARAM_PRDCT_NAME];
7014 err = ufshcd_read_string_desc(hba, model_index,
7015 &dev_info->model, SD_ASCII_STD);
7017 dev_err(hba->dev, "%s: Failed reading Product Name. err = %d\n",
7022 ufs_fixup_device_setup(hba);
7024 ufshcd_wb_probe(hba, desc_buf);
7027 * ufshcd_read_string_desc returns size of the string
7028 * reset the error value
7037 static void ufs_put_device_desc(struct ufs_hba *hba)
7039 struct ufs_dev_info *dev_info = &hba->dev_info;
7041 kfree(dev_info->model);
7042 dev_info->model = NULL;
7046 * ufshcd_tune_pa_tactivate - Tunes PA_TActivate of local UniPro
7047 * @hba: per-adapter instance
7049 * PA_TActivate parameter can be tuned manually if UniPro version is less than
7050 * 1.61. PA_TActivate needs to be greater than or equal to peerM-PHY's
7051 * RX_MIN_ACTIVATETIME_CAPABILITY attribute. This optimal value can help reduce
7052 * the hibern8 exit latency.
7054 * Returns zero on success, non-zero error value on failure.
7056 static int ufshcd_tune_pa_tactivate(struct ufs_hba *hba)
7059 u32 peer_rx_min_activatetime = 0, tuned_pa_tactivate;
7061 ret = ufshcd_dme_peer_get(hba,
7063 RX_MIN_ACTIVATETIME_CAPABILITY,
7064 UIC_ARG_MPHY_RX_GEN_SEL_INDEX(0)),
7065 &peer_rx_min_activatetime);
7069 /* make sure proper unit conversion is applied */
7070 tuned_pa_tactivate =
7071 ((peer_rx_min_activatetime * RX_MIN_ACTIVATETIME_UNIT_US)
7072 / PA_TACTIVATE_TIME_UNIT_US);
7073 ret = ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TACTIVATE),
7074 tuned_pa_tactivate);
7081 * ufshcd_tune_pa_hibern8time - Tunes PA_Hibern8Time of local UniPro
7082 * @hba: per-adapter instance
7084 * PA_Hibern8Time parameter can be tuned manually if UniPro version is less than
7085 * 1.61. PA_Hibern8Time needs to be maximum of local M-PHY's
7086 * TX_HIBERN8TIME_CAPABILITY & peer M-PHY's RX_HIBERN8TIME_CAPABILITY.
7087 * This optimal value can help reduce the hibern8 exit latency.
7089 * Returns zero on success, non-zero error value on failure.
7091 static int ufshcd_tune_pa_hibern8time(struct ufs_hba *hba)
7094 u32 local_tx_hibern8_time_cap = 0, peer_rx_hibern8_time_cap = 0;
7095 u32 max_hibern8_time, tuned_pa_hibern8time;
7097 ret = ufshcd_dme_get(hba,
7098 UIC_ARG_MIB_SEL(TX_HIBERN8TIME_CAPABILITY,
7099 UIC_ARG_MPHY_TX_GEN_SEL_INDEX(0)),
7100 &local_tx_hibern8_time_cap);
7104 ret = ufshcd_dme_peer_get(hba,
7105 UIC_ARG_MIB_SEL(RX_HIBERN8TIME_CAPABILITY,
7106 UIC_ARG_MPHY_RX_GEN_SEL_INDEX(0)),
7107 &peer_rx_hibern8_time_cap);
7111 max_hibern8_time = max(local_tx_hibern8_time_cap,
7112 peer_rx_hibern8_time_cap);
7113 /* make sure proper unit conversion is applied */
7114 tuned_pa_hibern8time = ((max_hibern8_time * HIBERN8TIME_UNIT_US)
7115 / PA_HIBERN8_TIME_UNIT_US);
7116 ret = ufshcd_dme_set(hba, UIC_ARG_MIB(PA_HIBERN8TIME),
7117 tuned_pa_hibern8time);
7123 * ufshcd_quirk_tune_host_pa_tactivate - Ensures that host PA_TACTIVATE is
7124 * less than device PA_TACTIVATE time.
7125 * @hba: per-adapter instance
7127 * Some UFS devices require host PA_TACTIVATE to be lower than device
7128 * PA_TACTIVATE, we need to enable UFS_DEVICE_QUIRK_HOST_PA_TACTIVATE quirk
7131 * Returns zero on success, non-zero error value on failure.
7133 static int ufshcd_quirk_tune_host_pa_tactivate(struct ufs_hba *hba)
7136 u32 granularity, peer_granularity;
7137 u32 pa_tactivate, peer_pa_tactivate;
7138 u32 pa_tactivate_us, peer_pa_tactivate_us;
7139 u8 gran_to_us_table[] = {1, 4, 8, 16, 32, 100};
7141 ret = ufshcd_dme_get(hba, UIC_ARG_MIB(PA_GRANULARITY),
7146 ret = ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_GRANULARITY),
7151 if ((granularity < PA_GRANULARITY_MIN_VAL) ||
7152 (granularity > PA_GRANULARITY_MAX_VAL)) {
7153 dev_err(hba->dev, "%s: invalid host PA_GRANULARITY %d",
7154 __func__, granularity);
7158 if ((peer_granularity < PA_GRANULARITY_MIN_VAL) ||
7159 (peer_granularity > PA_GRANULARITY_MAX_VAL)) {
7160 dev_err(hba->dev, "%s: invalid device PA_GRANULARITY %d",
7161 __func__, peer_granularity);
7165 ret = ufshcd_dme_get(hba, UIC_ARG_MIB(PA_TACTIVATE), &pa_tactivate);
7169 ret = ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_TACTIVATE),
7170 &peer_pa_tactivate);
7174 pa_tactivate_us = pa_tactivate * gran_to_us_table[granularity - 1];
7175 peer_pa_tactivate_us = peer_pa_tactivate *
7176 gran_to_us_table[peer_granularity - 1];
7178 if (pa_tactivate_us > peer_pa_tactivate_us) {
7179 u32 new_peer_pa_tactivate;
7181 new_peer_pa_tactivate = pa_tactivate_us /
7182 gran_to_us_table[peer_granularity - 1];
7183 new_peer_pa_tactivate++;
7184 ret = ufshcd_dme_peer_set(hba, UIC_ARG_MIB(PA_TACTIVATE),
7185 new_peer_pa_tactivate);
7192 static void ufshcd_tune_unipro_params(struct ufs_hba *hba)
7194 if (ufshcd_is_unipro_pa_params_tuning_req(hba)) {
7195 ufshcd_tune_pa_tactivate(hba);
7196 ufshcd_tune_pa_hibern8time(hba);
7199 ufshcd_vops_apply_dev_quirks(hba);
7201 if (hba->dev_quirks & UFS_DEVICE_QUIRK_PA_TACTIVATE)
7202 /* set 1ms timeout for PA_TACTIVATE */
7203 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TACTIVATE), 10);
7205 if (hba->dev_quirks & UFS_DEVICE_QUIRK_HOST_PA_TACTIVATE)
7206 ufshcd_quirk_tune_host_pa_tactivate(hba);
7209 static void ufshcd_clear_dbg_ufs_stats(struct ufs_hba *hba)
7211 hba->ufs_stats.hibern8_exit_cnt = 0;
7212 hba->ufs_stats.last_hibern8_exit_tstamp = ktime_set(0, 0);
7213 hba->req_abort_count = 0;
7216 static int ufshcd_device_geo_params_init(struct ufs_hba *hba)
7222 buff_len = hba->desc_size[QUERY_DESC_IDN_GEOMETRY];
7223 desc_buf = kmalloc(buff_len, GFP_KERNEL);
7229 err = ufshcd_read_desc_param(hba, QUERY_DESC_IDN_GEOMETRY, 0, 0,
7230 desc_buf, buff_len);
7232 dev_err(hba->dev, "%s: Failed reading Geometry Desc. err = %d\n",
7237 if (desc_buf[GEOMETRY_DESC_PARAM_MAX_NUM_LUN] == 1)
7238 hba->dev_info.max_lu_supported = 32;
7239 else if (desc_buf[GEOMETRY_DESC_PARAM_MAX_NUM_LUN] == 0)
7240 hba->dev_info.max_lu_supported = 8;
7247 static struct ufs_ref_clk ufs_ref_clk_freqs[] = {
7248 {19200000, REF_CLK_FREQ_19_2_MHZ},
7249 {26000000, REF_CLK_FREQ_26_MHZ},
7250 {38400000, REF_CLK_FREQ_38_4_MHZ},
7251 {52000000, REF_CLK_FREQ_52_MHZ},
7252 {0, REF_CLK_FREQ_INVAL},
7255 static enum ufs_ref_clk_freq
7256 ufs_get_bref_clk_from_hz(unsigned long freq)
7260 for (i = 0; ufs_ref_clk_freqs[i].freq_hz; i++)
7261 if (ufs_ref_clk_freqs[i].freq_hz == freq)
7262 return ufs_ref_clk_freqs[i].val;
7264 return REF_CLK_FREQ_INVAL;
7267 void ufshcd_parse_dev_ref_clk_freq(struct ufs_hba *hba, struct clk *refclk)
7271 freq = clk_get_rate(refclk);
7273 hba->dev_ref_clk_freq =
7274 ufs_get_bref_clk_from_hz(freq);
7276 if (hba->dev_ref_clk_freq == REF_CLK_FREQ_INVAL)
7278 "invalid ref_clk setting = %ld\n", freq);
7281 static int ufshcd_set_dev_ref_clk(struct ufs_hba *hba)
7285 u32 freq = hba->dev_ref_clk_freq;
7287 err = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
7288 QUERY_ATTR_IDN_REF_CLK_FREQ, 0, 0, &ref_clk);
7291 dev_err(hba->dev, "failed reading bRefClkFreq. err = %d\n",
7296 if (ref_clk == freq)
7297 goto out; /* nothing to update */
7299 err = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_WRITE_ATTR,
7300 QUERY_ATTR_IDN_REF_CLK_FREQ, 0, 0, &freq);
7303 dev_err(hba->dev, "bRefClkFreq setting to %lu Hz failed\n",
7304 ufs_ref_clk_freqs[freq].freq_hz);
7308 dev_dbg(hba->dev, "bRefClkFreq setting to %lu Hz succeeded\n",
7309 ufs_ref_clk_freqs[freq].freq_hz);
7315 static int ufshcd_device_params_init(struct ufs_hba *hba)
7320 /* Init device descriptor sizes */
7321 for (i = 0; i < QUERY_DESC_IDN_MAX; i++)
7322 hba->desc_size[i] = QUERY_DESC_MAX_SIZE;
7324 /* Init UFS geometry descriptor related parameters */
7325 ret = ufshcd_device_geo_params_init(hba);
7329 /* Check and apply UFS device quirks */
7330 ret = ufs_get_device_desc(hba);
7332 dev_err(hba->dev, "%s: Failed getting device info. err = %d\n",
7337 ufshcd_get_ref_clk_gating_wait(hba);
7339 if (!ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_READ_FLAG,
7340 QUERY_FLAG_IDN_PWR_ON_WPE, 0, &flag))
7341 hba->dev_info.f_power_on_wp_en = flag;
7343 /* Probe maximum power mode co-supported by both UFS host and device */
7344 if (ufshcd_get_max_pwr_mode(hba))
7346 "%s: Failed getting max supported power mode\n",
7353 * ufshcd_add_lus - probe and add UFS logical units
7354 * @hba: per-adapter instance
7356 static int ufshcd_add_lus(struct ufs_hba *hba)
7360 /* Add required well known logical units to scsi mid layer */
7361 ret = ufshcd_scsi_add_wlus(hba);
7365 /* Initialize devfreq after UFS device is detected */
7366 if (ufshcd_is_clkscaling_supported(hba)) {
7367 memcpy(&hba->clk_scaling.saved_pwr_info.info,
7369 sizeof(struct ufs_pa_layer_attr));
7370 hba->clk_scaling.saved_pwr_info.is_valid = true;
7371 if (!hba->devfreq) {
7372 ret = ufshcd_devfreq_init(hba);
7377 hba->clk_scaling.is_allowed = true;
7381 scsi_scan_host(hba->host);
7382 pm_runtime_put_sync(hba->dev);
7389 * ufshcd_probe_hba - probe hba to detect device and initialize
7390 * @hba: per-adapter instance
7391 * @async: asynchronous execution or not
7393 * Execute link-startup and verify device initialization
7395 static int ufshcd_probe_hba(struct ufs_hba *hba, bool async)
7398 ktime_t start = ktime_get();
7400 ret = ufshcd_link_startup(hba);
7404 /* Debug counters initialization */
7405 ufshcd_clear_dbg_ufs_stats(hba);
7407 /* UniPro link is active now */
7408 ufshcd_set_link_active(hba);
7410 /* Verify device initialization by sending NOP OUT UPIU */
7411 ret = ufshcd_verify_dev_init(hba);
7415 /* Initiate UFS initialization, and waiting until completion */
7416 ret = ufshcd_complete_dev_init(hba);
7421 * Initialize UFS device parameters used by driver, these
7422 * parameters are associated with UFS descriptors.
7425 ret = ufshcd_device_params_init(hba);
7430 ufshcd_tune_unipro_params(hba);
7432 /* UFS device is also active now */
7433 ufshcd_set_ufs_dev_active(hba);
7434 ufshcd_force_reset_auto_bkops(hba);
7435 hba->wlun_dev_clr_ua = true;
7437 /* Gear up to HS gear if supported */
7438 if (hba->max_pwr_info.is_valid) {
7440 * Set the right value to bRefClkFreq before attempting to
7441 * switch to HS gears.
7443 if (hba->dev_ref_clk_freq != REF_CLK_FREQ_INVAL)
7444 ufshcd_set_dev_ref_clk(hba);
7445 ret = ufshcd_config_pwr_mode(hba, &hba->max_pwr_info.info);
7447 dev_err(hba->dev, "%s: Failed setting power mode, err = %d\n",
7451 ufshcd_print_pwr_info(hba);
7455 * bActiveICCLevel is volatile for UFS device (as per latest v2.1 spec)
7456 * and for removable UFS card as well, hence always set the parameter.
7457 * Note: Error handler may issue the device reset hence resetting
7458 * bActiveICCLevel as well so it is always safe to set this here.
7460 ufshcd_set_active_icc_lvl(hba);
7462 /* set the state as operational after switching to desired gear */
7463 hba->ufshcd_state = UFSHCD_STATE_OPERATIONAL;
7465 ufshcd_wb_config(hba);
7466 /* Enable Auto-Hibernate if configured */
7467 ufshcd_auto_hibern8_enable(hba);
7471 trace_ufshcd_init(dev_name(hba->dev), ret,
7472 ktime_to_us(ktime_sub(ktime_get(), start)),
7473 hba->curr_dev_pwr_mode, hba->uic_link_state);
7478 * ufshcd_async_scan - asynchronous execution for probing hba
7479 * @data: data pointer to pass to this function
7480 * @cookie: cookie data
7482 static void ufshcd_async_scan(void *data, async_cookie_t cookie)
7484 struct ufs_hba *hba = (struct ufs_hba *)data;
7487 /* Initialize hba, detect and initialize UFS device */
7488 ret = ufshcd_probe_hba(hba, true);
7492 /* Probe and add UFS logical units */
7493 ret = ufshcd_add_lus(hba);
7496 * If we failed to initialize the device or the device is not
7497 * present, turn off the power/clocks etc.
7500 pm_runtime_put_sync(hba->dev);
7501 ufshcd_exit_clk_scaling(hba);
7502 ufshcd_hba_exit(hba);
7506 static const struct attribute_group *ufshcd_driver_groups[] = {
7507 &ufs_sysfs_unit_descriptor_group,
7508 &ufs_sysfs_lun_attributes_group,
7512 static struct ufs_hba_variant_params ufs_hba_vps = {
7513 .hba_enable_delay_us = 1000,
7514 .wb_flush_threshold = UFS_WB_BUF_REMAIN_PERCENT(40),
7515 .devfreq_profile.polling_ms = 100,
7516 .devfreq_profile.target = ufshcd_devfreq_target,
7517 .devfreq_profile.get_dev_status = ufshcd_devfreq_get_dev_status,
7518 .ondemand_data.upthreshold = 70,
7519 .ondemand_data.downdifferential = 5,
7522 static struct scsi_host_template ufshcd_driver_template = {
7523 .module = THIS_MODULE,
7525 .proc_name = UFSHCD,
7526 .queuecommand = ufshcd_queuecommand,
7527 .slave_alloc = ufshcd_slave_alloc,
7528 .slave_configure = ufshcd_slave_configure,
7529 .slave_destroy = ufshcd_slave_destroy,
7530 .change_queue_depth = ufshcd_change_queue_depth,
7531 .eh_abort_handler = ufshcd_abort,
7532 .eh_device_reset_handler = ufshcd_eh_device_reset_handler,
7533 .eh_host_reset_handler = ufshcd_eh_host_reset_handler,
7535 .sg_tablesize = SG_ALL,
7536 .cmd_per_lun = UFSHCD_CMD_PER_LUN,
7537 .can_queue = UFSHCD_CAN_QUEUE,
7538 .max_segment_size = PRDT_DATA_BYTE_COUNT_MAX,
7539 .max_host_blocked = 1,
7540 .track_queue_depth = 1,
7541 .sdev_groups = ufshcd_driver_groups,
7542 .dma_boundary = PAGE_SIZE - 1,
7543 .rpm_autosuspend_delay = RPM_AUTOSUSPEND_DELAY_MS,
7546 static int ufshcd_config_vreg_load(struct device *dev, struct ufs_vreg *vreg,
7555 * "set_load" operation shall be required on those regulators
7556 * which specifically configured current limitation. Otherwise
7557 * zero max_uA may cause unexpected behavior when regulator is
7558 * enabled or set as high power mode.
7563 ret = regulator_set_load(vreg->reg, ua);
7565 dev_err(dev, "%s: %s set load (ua=%d) failed, err=%d\n",
7566 __func__, vreg->name, ua, ret);
7572 static inline int ufshcd_config_vreg_lpm(struct ufs_hba *hba,
7573 struct ufs_vreg *vreg)
7575 return ufshcd_config_vreg_load(hba->dev, vreg, UFS_VREG_LPM_LOAD_UA);
7578 static inline int ufshcd_config_vreg_hpm(struct ufs_hba *hba,
7579 struct ufs_vreg *vreg)
7584 return ufshcd_config_vreg_load(hba->dev, vreg, vreg->max_uA);
7587 static int ufshcd_config_vreg(struct device *dev,
7588 struct ufs_vreg *vreg, bool on)
7591 struct regulator *reg;
7593 int min_uV, uA_load;
7600 if (regulator_count_voltages(reg) > 0) {
7601 uA_load = on ? vreg->max_uA : 0;
7602 ret = ufshcd_config_vreg_load(dev, vreg, uA_load);
7606 if (vreg->min_uV && vreg->max_uV) {
7607 min_uV = on ? vreg->min_uV : 0;
7608 ret = regulator_set_voltage(reg, min_uV, vreg->max_uV);
7611 "%s: %s set voltage failed, err=%d\n",
7612 __func__, name, ret);
7621 static int ufshcd_enable_vreg(struct device *dev, struct ufs_vreg *vreg)
7625 if (!vreg || vreg->enabled)
7628 ret = ufshcd_config_vreg(dev, vreg, true);
7630 ret = regulator_enable(vreg->reg);
7633 vreg->enabled = true;
7635 dev_err(dev, "%s: %s enable failed, err=%d\n",
7636 __func__, vreg->name, ret);
7641 static int ufshcd_disable_vreg(struct device *dev, struct ufs_vreg *vreg)
7645 if (!vreg || !vreg->enabled)
7648 ret = regulator_disable(vreg->reg);
7651 /* ignore errors on applying disable config */
7652 ufshcd_config_vreg(dev, vreg, false);
7653 vreg->enabled = false;
7655 dev_err(dev, "%s: %s disable failed, err=%d\n",
7656 __func__, vreg->name, ret);
7662 static int ufshcd_setup_vreg(struct ufs_hba *hba, bool on)
7665 struct device *dev = hba->dev;
7666 struct ufs_vreg_info *info = &hba->vreg_info;
7668 ret = ufshcd_toggle_vreg(dev, info->vcc, on);
7672 ret = ufshcd_toggle_vreg(dev, info->vccq, on);
7676 ret = ufshcd_toggle_vreg(dev, info->vccq2, on);
7682 ufshcd_toggle_vreg(dev, info->vccq2, false);
7683 ufshcd_toggle_vreg(dev, info->vccq, false);
7684 ufshcd_toggle_vreg(dev, info->vcc, false);
7689 static int ufshcd_setup_hba_vreg(struct ufs_hba *hba, bool on)
7691 struct ufs_vreg_info *info = &hba->vreg_info;
7693 return ufshcd_toggle_vreg(hba->dev, info->vdd_hba, on);
7696 static int ufshcd_get_vreg(struct device *dev, struct ufs_vreg *vreg)
7703 vreg->reg = devm_regulator_get(dev, vreg->name);
7704 if (IS_ERR(vreg->reg)) {
7705 ret = PTR_ERR(vreg->reg);
7706 dev_err(dev, "%s: %s get failed, err=%d\n",
7707 __func__, vreg->name, ret);
7713 static int ufshcd_init_vreg(struct ufs_hba *hba)
7716 struct device *dev = hba->dev;
7717 struct ufs_vreg_info *info = &hba->vreg_info;
7719 ret = ufshcd_get_vreg(dev, info->vcc);
7723 ret = ufshcd_get_vreg(dev, info->vccq);
7727 ret = ufshcd_get_vreg(dev, info->vccq2);
7732 static int ufshcd_init_hba_vreg(struct ufs_hba *hba)
7734 struct ufs_vreg_info *info = &hba->vreg_info;
7737 return ufshcd_get_vreg(hba->dev, info->vdd_hba);
7742 static int __ufshcd_setup_clocks(struct ufs_hba *hba, bool on,
7746 struct ufs_clk_info *clki;
7747 struct list_head *head = &hba->clk_list_head;
7748 unsigned long flags;
7749 ktime_t start = ktime_get();
7750 bool clk_state_changed = false;
7752 if (list_empty(head))
7755 ret = ufshcd_vops_setup_clocks(hba, on, PRE_CHANGE);
7759 list_for_each_entry(clki, head, list) {
7760 if (!IS_ERR_OR_NULL(clki->clk)) {
7761 if (skip_ref_clk && !strcmp(clki->name, "ref_clk"))
7764 clk_state_changed = on ^ clki->enabled;
7765 if (on && !clki->enabled) {
7766 ret = clk_prepare_enable(clki->clk);
7768 dev_err(hba->dev, "%s: %s prepare enable failed, %d\n",
7769 __func__, clki->name, ret);
7772 } else if (!on && clki->enabled) {
7773 clk_disable_unprepare(clki->clk);
7776 dev_dbg(hba->dev, "%s: clk: %s %sabled\n", __func__,
7777 clki->name, on ? "en" : "dis");
7781 ret = ufshcd_vops_setup_clocks(hba, on, POST_CHANGE);
7787 list_for_each_entry(clki, head, list) {
7788 if (!IS_ERR_OR_NULL(clki->clk) && clki->enabled)
7789 clk_disable_unprepare(clki->clk);
7791 } else if (!ret && on) {
7792 spin_lock_irqsave(hba->host->host_lock, flags);
7793 hba->clk_gating.state = CLKS_ON;
7794 trace_ufshcd_clk_gating(dev_name(hba->dev),
7795 hba->clk_gating.state);
7796 spin_unlock_irqrestore(hba->host->host_lock, flags);
7799 if (clk_state_changed)
7800 trace_ufshcd_profile_clk_gating(dev_name(hba->dev),
7801 (on ? "on" : "off"),
7802 ktime_to_us(ktime_sub(ktime_get(), start)), ret);
7806 static int ufshcd_setup_clocks(struct ufs_hba *hba, bool on)
7808 return __ufshcd_setup_clocks(hba, on, false);
7811 static int ufshcd_init_clocks(struct ufs_hba *hba)
7814 struct ufs_clk_info *clki;
7815 struct device *dev = hba->dev;
7816 struct list_head *head = &hba->clk_list_head;
7818 if (list_empty(head))
7821 list_for_each_entry(clki, head, list) {
7825 clki->clk = devm_clk_get(dev, clki->name);
7826 if (IS_ERR(clki->clk)) {
7827 ret = PTR_ERR(clki->clk);
7828 dev_err(dev, "%s: %s clk get failed, %d\n",
7829 __func__, clki->name, ret);
7834 * Parse device ref clk freq as per device tree "ref_clk".
7835 * Default dev_ref_clk_freq is set to REF_CLK_FREQ_INVAL
7836 * in ufshcd_alloc_host().
7838 if (!strcmp(clki->name, "ref_clk"))
7839 ufshcd_parse_dev_ref_clk_freq(hba, clki->clk);
7841 if (clki->max_freq) {
7842 ret = clk_set_rate(clki->clk, clki->max_freq);
7844 dev_err(hba->dev, "%s: %s clk set rate(%dHz) failed, %d\n",
7845 __func__, clki->name,
7846 clki->max_freq, ret);
7849 clki->curr_freq = clki->max_freq;
7851 dev_dbg(dev, "%s: clk: %s, rate: %lu\n", __func__,
7852 clki->name, clk_get_rate(clki->clk));
7858 static int ufshcd_variant_hba_init(struct ufs_hba *hba)
7865 err = ufshcd_vops_init(hba);
7869 err = ufshcd_vops_setup_regulators(hba, true);
7876 ufshcd_vops_exit(hba);
7879 dev_err(hba->dev, "%s: variant %s init failed err %d\n",
7880 __func__, ufshcd_get_var_name(hba), err);
7884 static void ufshcd_variant_hba_exit(struct ufs_hba *hba)
7889 ufshcd_vops_setup_regulators(hba, false);
7891 ufshcd_vops_exit(hba);
7894 static int ufshcd_hba_init(struct ufs_hba *hba)
7899 * Handle host controller power separately from the UFS device power
7900 * rails as it will help controlling the UFS host controller power
7901 * collapse easily which is different than UFS device power collapse.
7902 * Also, enable the host controller power before we go ahead with rest
7903 * of the initialization here.
7905 err = ufshcd_init_hba_vreg(hba);
7909 err = ufshcd_setup_hba_vreg(hba, true);
7913 err = ufshcd_init_clocks(hba);
7915 goto out_disable_hba_vreg;
7917 err = ufshcd_setup_clocks(hba, true);
7919 goto out_disable_hba_vreg;
7921 err = ufshcd_init_vreg(hba);
7923 goto out_disable_clks;
7925 err = ufshcd_setup_vreg(hba, true);
7927 goto out_disable_clks;
7929 err = ufshcd_variant_hba_init(hba);
7931 goto out_disable_vreg;
7933 hba->is_powered = true;
7937 ufshcd_setup_vreg(hba, false);
7939 ufshcd_setup_clocks(hba, false);
7940 out_disable_hba_vreg:
7941 ufshcd_setup_hba_vreg(hba, false);
7946 static void ufshcd_hba_exit(struct ufs_hba *hba)
7948 if (hba->is_powered) {
7949 ufshcd_variant_hba_exit(hba);
7950 ufshcd_setup_vreg(hba, false);
7951 ufshcd_suspend_clkscaling(hba);
7952 if (ufshcd_is_clkscaling_supported(hba))
7954 ufshcd_suspend_clkscaling(hba);
7955 ufshcd_setup_clocks(hba, false);
7956 ufshcd_setup_hba_vreg(hba, false);
7957 hba->is_powered = false;
7958 ufs_put_device_desc(hba);
7963 ufshcd_send_request_sense(struct ufs_hba *hba, struct scsi_device *sdp)
7965 unsigned char cmd[6] = {REQUEST_SENSE,
7974 buffer = kzalloc(UFS_SENSE_SIZE, GFP_KERNEL);
7980 ret = scsi_execute(sdp, cmd, DMA_FROM_DEVICE, buffer,
7981 UFS_SENSE_SIZE, NULL, NULL,
7982 msecs_to_jiffies(1000), 3, 0, RQF_PM, NULL);
7984 pr_err("%s: failed with err %d\n", __func__, ret);
7992 * ufshcd_set_dev_pwr_mode - sends START STOP UNIT command to set device
7994 * @hba: per adapter instance
7995 * @pwr_mode: device power mode to set
7997 * Returns 0 if requested power mode is set successfully
7998 * Returns non-zero if failed to set the requested power mode
8000 static int ufshcd_set_dev_pwr_mode(struct ufs_hba *hba,
8001 enum ufs_dev_pwr_mode pwr_mode)
8003 unsigned char cmd[6] = { START_STOP };
8004 struct scsi_sense_hdr sshdr;
8005 struct scsi_device *sdp;
8006 unsigned long flags;
8009 spin_lock_irqsave(hba->host->host_lock, flags);
8010 sdp = hba->sdev_ufs_device;
8012 ret = scsi_device_get(sdp);
8013 if (!ret && !scsi_device_online(sdp)) {
8015 scsi_device_put(sdp);
8020 spin_unlock_irqrestore(hba->host->host_lock, flags);
8026 * If scsi commands fail, the scsi mid-layer schedules scsi error-
8027 * handling, which would wait for host to be resumed. Since we know
8028 * we are functional while we are here, skip host resume in error
8031 hba->host->eh_noresume = 1;
8032 if (hba->wlun_dev_clr_ua) {
8033 ret = ufshcd_send_request_sense(hba, sdp);
8036 /* Unit attention condition is cleared now */
8037 hba->wlun_dev_clr_ua = false;
8040 cmd[4] = pwr_mode << 4;
8043 * Current function would be generally called from the power management
8044 * callbacks hence set the RQF_PM flag so that it doesn't resume the
8045 * already suspended childs.
8047 ret = scsi_execute(sdp, cmd, DMA_NONE, NULL, 0, NULL, &sshdr,
8048 START_STOP_TIMEOUT, 0, 0, RQF_PM, NULL);
8050 sdev_printk(KERN_WARNING, sdp,
8051 "START_STOP failed for power mode: %d, result %x\n",
8053 if (driver_byte(ret) == DRIVER_SENSE)
8054 scsi_print_sense_hdr(sdp, NULL, &sshdr);
8058 hba->curr_dev_pwr_mode = pwr_mode;
8060 scsi_device_put(sdp);
8061 hba->host->eh_noresume = 0;
8065 static int ufshcd_link_state_transition(struct ufs_hba *hba,
8066 enum uic_link_state req_link_state,
8067 int check_for_bkops)
8071 if (req_link_state == hba->uic_link_state)
8074 if (req_link_state == UIC_LINK_HIBERN8_STATE) {
8075 ret = ufshcd_uic_hibern8_enter(hba);
8077 ufshcd_set_link_hibern8(hba);
8082 * If autobkops is enabled, link can't be turned off because
8083 * turning off the link would also turn off the device.
8085 else if ((req_link_state == UIC_LINK_OFF_STATE) &&
8086 (!check_for_bkops || !hba->auto_bkops_enabled)) {
8088 * Let's make sure that link is in low power mode, we are doing
8089 * this currently by putting the link in Hibern8. Otherway to
8090 * put the link in low power mode is to send the DME end point
8091 * to device and then send the DME reset command to local
8092 * unipro. But putting the link in hibern8 is much faster.
8094 ret = ufshcd_uic_hibern8_enter(hba);
8098 * Change controller state to "reset state" which
8099 * should also put the link in off/reset state
8101 ufshcd_hba_stop(hba);
8103 * TODO: Check if we need any delay to make sure that
8104 * controller is reset
8106 ufshcd_set_link_off(hba);
8113 static void ufshcd_vreg_set_lpm(struct ufs_hba *hba)
8115 bool vcc_off = false;
8118 * It seems some UFS devices may keep drawing more than sleep current
8119 * (atleast for 500us) from UFS rails (especially from VCCQ rail).
8120 * To avoid this situation, add 2ms delay before putting these UFS
8121 * rails in LPM mode.
8123 if (!ufshcd_is_link_active(hba) &&
8124 hba->dev_quirks & UFS_DEVICE_QUIRK_DELAY_BEFORE_LPM)
8125 usleep_range(2000, 2100);
8128 * If UFS device is either in UFS_Sleep turn off VCC rail to save some
8131 * If UFS device and link is in OFF state, all power supplies (VCC,
8132 * VCCQ, VCCQ2) can be turned off if power on write protect is not
8133 * required. If UFS link is inactive (Hibern8 or OFF state) and device
8134 * is in sleep state, put VCCQ & VCCQ2 rails in LPM mode.
8136 * Ignore the error returned by ufshcd_toggle_vreg() as device is anyway
8137 * in low power state which would save some power.
8139 * If Write Booster is enabled and the device needs to flush the WB
8140 * buffer OR if bkops status is urgent for WB, keep Vcc on.
8142 if (ufshcd_is_ufs_dev_poweroff(hba) && ufshcd_is_link_off(hba) &&
8143 !hba->dev_info.is_lu_power_on_wp) {
8144 ufshcd_setup_vreg(hba, false);
8146 } else if (!ufshcd_is_ufs_dev_active(hba)) {
8147 ufshcd_toggle_vreg(hba->dev, hba->vreg_info.vcc, false);
8149 if (!ufshcd_is_link_active(hba)) {
8150 ufshcd_config_vreg_lpm(hba, hba->vreg_info.vccq);
8151 ufshcd_config_vreg_lpm(hba, hba->vreg_info.vccq2);
8156 * Some UFS devices require delay after VCC power rail is turned-off.
8158 if (vcc_off && hba->vreg_info.vcc &&
8159 hba->dev_quirks & UFS_DEVICE_QUIRK_DELAY_AFTER_LPM)
8160 usleep_range(5000, 5100);
8163 static int ufshcd_vreg_set_hpm(struct ufs_hba *hba)
8167 if (ufshcd_is_ufs_dev_poweroff(hba) && ufshcd_is_link_off(hba) &&
8168 !hba->dev_info.is_lu_power_on_wp) {
8169 ret = ufshcd_setup_vreg(hba, true);
8170 } else if (!ufshcd_is_ufs_dev_active(hba)) {
8171 if (!ret && !ufshcd_is_link_active(hba)) {
8172 ret = ufshcd_config_vreg_hpm(hba, hba->vreg_info.vccq);
8175 ret = ufshcd_config_vreg_hpm(hba, hba->vreg_info.vccq2);
8179 ret = ufshcd_toggle_vreg(hba->dev, hba->vreg_info.vcc, true);
8184 ufshcd_config_vreg_lpm(hba, hba->vreg_info.vccq);
8186 ufshcd_toggle_vreg(hba->dev, hba->vreg_info.vcc, false);
8191 static void ufshcd_hba_vreg_set_lpm(struct ufs_hba *hba)
8193 if (ufshcd_is_link_off(hba))
8194 ufshcd_setup_hba_vreg(hba, false);
8197 static void ufshcd_hba_vreg_set_hpm(struct ufs_hba *hba)
8199 if (ufshcd_is_link_off(hba))
8200 ufshcd_setup_hba_vreg(hba, true);
8204 * ufshcd_suspend - helper function for suspend operations
8205 * @hba: per adapter instance
8206 * @pm_op: desired low power operation type
8208 * This function will try to put the UFS device and link into low power
8209 * mode based on the "rpm_lvl" (Runtime PM level) or "spm_lvl"
8210 * (System PM level).
8212 * If this function is called during shutdown, it will make sure that
8213 * both UFS device and UFS link is powered off.
8215 * NOTE: UFS device & link must be active before we enter in this function.
8217 * Returns 0 for success and non-zero for failure
8219 static int ufshcd_suspend(struct ufs_hba *hba, enum ufs_pm_op pm_op)
8222 enum ufs_pm_level pm_lvl;
8223 enum ufs_dev_pwr_mode req_dev_pwr_mode;
8224 enum uic_link_state req_link_state;
8226 hba->pm_op_in_progress = 1;
8227 if (!ufshcd_is_shutdown_pm(pm_op)) {
8228 pm_lvl = ufshcd_is_runtime_pm(pm_op) ?
8229 hba->rpm_lvl : hba->spm_lvl;
8230 req_dev_pwr_mode = ufs_get_pm_lvl_to_dev_pwr_mode(pm_lvl);
8231 req_link_state = ufs_get_pm_lvl_to_link_pwr_state(pm_lvl);
8233 req_dev_pwr_mode = UFS_POWERDOWN_PWR_MODE;
8234 req_link_state = UIC_LINK_OFF_STATE;
8238 * If we can't transition into any of the low power modes
8239 * just gate the clocks.
8241 ufshcd_hold(hba, false);
8242 hba->clk_gating.is_suspended = true;
8244 if (hba->clk_scaling.is_allowed) {
8245 cancel_work_sync(&hba->clk_scaling.suspend_work);
8246 cancel_work_sync(&hba->clk_scaling.resume_work);
8247 ufshcd_suspend_clkscaling(hba);
8250 if (req_dev_pwr_mode == UFS_ACTIVE_PWR_MODE &&
8251 req_link_state == UIC_LINK_ACTIVE_STATE) {
8255 if ((req_dev_pwr_mode == hba->curr_dev_pwr_mode) &&
8256 (req_link_state == hba->uic_link_state))
8259 /* UFS device & link must be active before we enter in this function */
8260 if (!ufshcd_is_ufs_dev_active(hba) || !ufshcd_is_link_active(hba)) {
8265 if (ufshcd_is_runtime_pm(pm_op)) {
8266 if (ufshcd_can_autobkops_during_suspend(hba)) {
8268 * The device is idle with no requests in the queue,
8269 * allow background operations if bkops status shows
8270 * that performance might be impacted.
8272 ret = ufshcd_urgent_bkops(hba);
8276 /* make sure that auto bkops is disabled */
8277 ufshcd_disable_auto_bkops(hba);
8280 * If device needs to do BKOP or WB buffer flush during
8281 * Hibern8, keep device power mode as "active power mode"
8284 hba->dev_info.b_rpm_dev_flush_capable =
8285 hba->auto_bkops_enabled ||
8286 (((req_link_state == UIC_LINK_HIBERN8_STATE) ||
8287 ((req_link_state == UIC_LINK_ACTIVE_STATE) &&
8288 ufshcd_is_auto_hibern8_enabled(hba))) &&
8289 ufshcd_wb_need_flush(hba));
8292 if (req_dev_pwr_mode != hba->curr_dev_pwr_mode) {
8293 if ((ufshcd_is_runtime_pm(pm_op) && !hba->auto_bkops_enabled) ||
8294 !ufshcd_is_runtime_pm(pm_op)) {
8295 /* ensure that bkops is disabled */
8296 ufshcd_disable_auto_bkops(hba);
8299 if (!hba->dev_info.b_rpm_dev_flush_capable) {
8300 ret = ufshcd_set_dev_pwr_mode(hba, req_dev_pwr_mode);
8306 flush_work(&hba->eeh_work);
8307 ret = ufshcd_link_state_transition(hba, req_link_state, 1);
8309 goto set_dev_active;
8311 ufshcd_vreg_set_lpm(hba);
8315 * Call vendor specific suspend callback. As these callbacks may access
8316 * vendor specific host controller register space call them before the
8317 * host clocks are ON.
8319 ret = ufshcd_vops_suspend(hba, pm_op);
8321 goto set_link_active;
8323 * Disable the host irq as host controller as there won't be any
8324 * host controller transaction expected till resume.
8326 ufshcd_disable_irq(hba);
8328 if (!ufshcd_is_link_active(hba))
8329 ufshcd_setup_clocks(hba, false);
8331 /* If link is active, device ref_clk can't be switched off */
8332 __ufshcd_setup_clocks(hba, false, true);
8334 hba->clk_gating.state = CLKS_OFF;
8335 trace_ufshcd_clk_gating(dev_name(hba->dev), hba->clk_gating.state);
8337 /* Put the host controller in low power mode if possible */
8338 ufshcd_hba_vreg_set_lpm(hba);
8342 if (hba->clk_scaling.is_allowed)
8343 ufshcd_resume_clkscaling(hba);
8344 ufshcd_vreg_set_hpm(hba);
8345 if (ufshcd_is_link_hibern8(hba) && !ufshcd_uic_hibern8_exit(hba))
8346 ufshcd_set_link_active(hba);
8347 else if (ufshcd_is_link_off(hba))
8348 ufshcd_host_reset_and_restore(hba);
8350 if (!ufshcd_set_dev_pwr_mode(hba, UFS_ACTIVE_PWR_MODE))
8351 ufshcd_disable_auto_bkops(hba);
8353 if (hba->clk_scaling.is_allowed)
8354 ufshcd_resume_clkscaling(hba);
8355 hba->clk_gating.is_suspended = false;
8356 hba->dev_info.b_rpm_dev_flush_capable = false;
8357 ufshcd_release(hba);
8359 if (hba->dev_info.b_rpm_dev_flush_capable) {
8360 schedule_delayed_work(&hba->rpm_dev_flush_recheck_work,
8361 msecs_to_jiffies(RPM_DEV_FLUSH_RECHECK_WORK_DELAY_MS));
8364 hba->pm_op_in_progress = 0;
8367 ufshcd_update_reg_hist(&hba->ufs_stats.suspend_err, (u32)ret);
8372 * ufshcd_resume - helper function for resume operations
8373 * @hba: per adapter instance
8374 * @pm_op: runtime PM or system PM
8376 * This function basically brings the UFS device, UniPro link and controller
8379 * Returns 0 for success and non-zero for failure
8381 static int ufshcd_resume(struct ufs_hba *hba, enum ufs_pm_op pm_op)
8384 enum uic_link_state old_link_state;
8386 hba->pm_op_in_progress = 1;
8387 old_link_state = hba->uic_link_state;
8389 ufshcd_hba_vreg_set_hpm(hba);
8390 /* Make sure clocks are enabled before accessing controller */
8391 ret = ufshcd_setup_clocks(hba, true);
8395 /* enable the host irq as host controller would be active soon */
8396 ufshcd_enable_irq(hba);
8398 ret = ufshcd_vreg_set_hpm(hba);
8400 goto disable_irq_and_vops_clks;
8403 * Call vendor specific resume callback. As these callbacks may access
8404 * vendor specific host controller register space call them when the
8405 * host clocks are ON.
8407 ret = ufshcd_vops_resume(hba, pm_op);
8411 if (ufshcd_is_link_hibern8(hba)) {
8412 ret = ufshcd_uic_hibern8_exit(hba);
8414 ufshcd_set_link_active(hba);
8416 goto vendor_suspend;
8417 } else if (ufshcd_is_link_off(hba)) {
8419 * A full initialization of the host and the device is
8420 * required since the link was put to off during suspend.
8422 ret = ufshcd_reset_and_restore(hba);
8424 * ufshcd_reset_and_restore() should have already
8425 * set the link state as active
8427 if (ret || !ufshcd_is_link_active(hba))
8428 goto vendor_suspend;
8431 if (!ufshcd_is_ufs_dev_active(hba)) {
8432 ret = ufshcd_set_dev_pwr_mode(hba, UFS_ACTIVE_PWR_MODE);
8434 goto set_old_link_state;
8437 if (ufshcd_keep_autobkops_enabled_except_suspend(hba))
8438 ufshcd_enable_auto_bkops(hba);
8441 * If BKOPs operations are urgently needed at this moment then
8442 * keep auto-bkops enabled or else disable it.
8444 ufshcd_urgent_bkops(hba);
8446 hba->clk_gating.is_suspended = false;
8448 if (hba->clk_scaling.is_allowed)
8449 ufshcd_resume_clkscaling(hba);
8451 /* Enable Auto-Hibernate if configured */
8452 ufshcd_auto_hibern8_enable(hba);
8454 if (hba->dev_info.b_rpm_dev_flush_capable) {
8455 hba->dev_info.b_rpm_dev_flush_capable = false;
8456 cancel_delayed_work(&hba->rpm_dev_flush_recheck_work);
8459 /* Schedule clock gating in case of no access to UFS device yet */
8460 ufshcd_release(hba);
8465 ufshcd_link_state_transition(hba, old_link_state, 0);
8467 ufshcd_vops_suspend(hba, pm_op);
8469 ufshcd_vreg_set_lpm(hba);
8470 disable_irq_and_vops_clks:
8471 ufshcd_disable_irq(hba);
8472 if (hba->clk_scaling.is_allowed)
8473 ufshcd_suspend_clkscaling(hba);
8474 ufshcd_setup_clocks(hba, false);
8476 hba->pm_op_in_progress = 0;
8478 ufshcd_update_reg_hist(&hba->ufs_stats.resume_err, (u32)ret);
8483 * ufshcd_system_suspend - system suspend routine
8484 * @hba: per adapter instance
8486 * Check the description of ufshcd_suspend() function for more details.
8488 * Returns 0 for success and non-zero for failure
8490 int ufshcd_system_suspend(struct ufs_hba *hba)
8493 ktime_t start = ktime_get();
8495 if (!hba || !hba->is_powered)
8498 if ((ufs_get_pm_lvl_to_dev_pwr_mode(hba->spm_lvl) ==
8499 hba->curr_dev_pwr_mode) &&
8500 (ufs_get_pm_lvl_to_link_pwr_state(hba->spm_lvl) ==
8501 hba->uic_link_state))
8504 if (pm_runtime_suspended(hba->dev)) {
8506 * UFS device and/or UFS link low power states during runtime
8507 * suspend seems to be different than what is expected during
8508 * system suspend. Hence runtime resume the devic & link and
8509 * let the system suspend low power states to take effect.
8510 * TODO: If resume takes longer time, we might have optimize
8511 * it in future by not resuming everything if possible.
8513 ret = ufshcd_runtime_resume(hba);
8518 ret = ufshcd_suspend(hba, UFS_SYSTEM_PM);
8520 trace_ufshcd_system_suspend(dev_name(hba->dev), ret,
8521 ktime_to_us(ktime_sub(ktime_get(), start)),
8522 hba->curr_dev_pwr_mode, hba->uic_link_state);
8524 hba->is_sys_suspended = true;
8527 EXPORT_SYMBOL(ufshcd_system_suspend);
8530 * ufshcd_system_resume - system resume routine
8531 * @hba: per adapter instance
8533 * Returns 0 for success and non-zero for failure
8536 int ufshcd_system_resume(struct ufs_hba *hba)
8539 ktime_t start = ktime_get();
8544 if (!hba->is_powered || pm_runtime_suspended(hba->dev))
8546 * Let the runtime resume take care of resuming
8547 * if runtime suspended.
8551 ret = ufshcd_resume(hba, UFS_SYSTEM_PM);
8553 trace_ufshcd_system_resume(dev_name(hba->dev), ret,
8554 ktime_to_us(ktime_sub(ktime_get(), start)),
8555 hba->curr_dev_pwr_mode, hba->uic_link_state);
8557 hba->is_sys_suspended = false;
8560 EXPORT_SYMBOL(ufshcd_system_resume);
8563 * ufshcd_runtime_suspend - runtime suspend routine
8564 * @hba: per adapter instance
8566 * Check the description of ufshcd_suspend() function for more details.
8568 * Returns 0 for success and non-zero for failure
8570 int ufshcd_runtime_suspend(struct ufs_hba *hba)
8573 ktime_t start = ktime_get();
8578 if (!hba->is_powered)
8581 ret = ufshcd_suspend(hba, UFS_RUNTIME_PM);
8583 trace_ufshcd_runtime_suspend(dev_name(hba->dev), ret,
8584 ktime_to_us(ktime_sub(ktime_get(), start)),
8585 hba->curr_dev_pwr_mode, hba->uic_link_state);
8588 EXPORT_SYMBOL(ufshcd_runtime_suspend);
8591 * ufshcd_runtime_resume - runtime resume routine
8592 * @hba: per adapter instance
8594 * This function basically brings the UFS device, UniPro link and controller
8595 * to active state. Following operations are done in this function:
8597 * 1. Turn on all the controller related clocks
8598 * 2. Bring the UniPro link out of Hibernate state
8599 * 3. If UFS device is in sleep state, turn ON VCC rail and bring the UFS device
8601 * 4. If auto-bkops is enabled on the device, disable it.
8603 * So following would be the possible power state after this function return
8605 * S1: UFS device in Active state with VCC rail ON
8606 * UniPro link in Active state
8607 * All the UFS/UniPro controller clocks are ON
8609 * Returns 0 for success and non-zero for failure
8611 int ufshcd_runtime_resume(struct ufs_hba *hba)
8614 ktime_t start = ktime_get();
8619 if (!hba->is_powered)
8622 ret = ufshcd_resume(hba, UFS_RUNTIME_PM);
8624 trace_ufshcd_runtime_resume(dev_name(hba->dev), ret,
8625 ktime_to_us(ktime_sub(ktime_get(), start)),
8626 hba->curr_dev_pwr_mode, hba->uic_link_state);
8629 EXPORT_SYMBOL(ufshcd_runtime_resume);
8631 int ufshcd_runtime_idle(struct ufs_hba *hba)
8635 EXPORT_SYMBOL(ufshcd_runtime_idle);
8638 * ufshcd_shutdown - shutdown routine
8639 * @hba: per adapter instance
8641 * This function would power off both UFS device and UFS link.
8643 * Returns 0 always to allow force shutdown even in case of errors.
8645 int ufshcd_shutdown(struct ufs_hba *hba)
8649 if (!hba->is_powered)
8652 if (ufshcd_is_ufs_dev_poweroff(hba) && ufshcd_is_link_off(hba))
8655 if (pm_runtime_suspended(hba->dev)) {
8656 ret = ufshcd_runtime_resume(hba);
8661 ret = ufshcd_suspend(hba, UFS_SHUTDOWN_PM);
8664 dev_err(hba->dev, "%s failed, err %d\n", __func__, ret);
8665 /* allow force shutdown even in case of errors */
8668 EXPORT_SYMBOL(ufshcd_shutdown);
8671 * ufshcd_remove - de-allocate SCSI host and host memory space
8672 * data structure memory
8673 * @hba: per adapter instance
8675 void ufshcd_remove(struct ufs_hba *hba)
8677 ufs_bsg_remove(hba);
8678 ufs_sysfs_remove_nodes(hba->dev);
8679 blk_cleanup_queue(hba->tmf_queue);
8680 blk_mq_free_tag_set(&hba->tmf_tag_set);
8681 blk_cleanup_queue(hba->cmd_queue);
8682 scsi_remove_host(hba->host);
8683 /* disable interrupts */
8684 ufshcd_disable_intr(hba, hba->intr_mask);
8685 ufshcd_hba_stop(hba);
8687 ufshcd_exit_clk_scaling(hba);
8688 ufshcd_exit_clk_gating(hba);
8689 if (ufshcd_is_clkscaling_supported(hba))
8690 device_remove_file(hba->dev, &hba->clk_scaling.enable_attr);
8691 ufshcd_hba_exit(hba);
8693 EXPORT_SYMBOL_GPL(ufshcd_remove);
8696 * ufshcd_dealloc_host - deallocate Host Bus Adapter (HBA)
8697 * @hba: pointer to Host Bus Adapter (HBA)
8699 void ufshcd_dealloc_host(struct ufs_hba *hba)
8701 ufshcd_crypto_destroy_keyslot_manager(hba);
8702 scsi_host_put(hba->host);
8704 EXPORT_SYMBOL_GPL(ufshcd_dealloc_host);
8707 * ufshcd_set_dma_mask - Set dma mask based on the controller
8708 * addressing capability
8709 * @hba: per adapter instance
8711 * Returns 0 for success, non-zero for failure
8713 static int ufshcd_set_dma_mask(struct ufs_hba *hba)
8715 if (hba->capabilities & MASK_64_ADDRESSING_SUPPORT) {
8716 if (!dma_set_mask_and_coherent(hba->dev, DMA_BIT_MASK(64)))
8719 return dma_set_mask_and_coherent(hba->dev, DMA_BIT_MASK(32));
8723 * ufshcd_alloc_host - allocate Host Bus Adapter (HBA)
8724 * @dev: pointer to device handle
8725 * @hba_handle: driver private handle
8726 * Returns 0 on success, non-zero value on failure
8728 int ufshcd_alloc_host(struct device *dev, struct ufs_hba **hba_handle)
8730 struct Scsi_Host *host;
8731 struct ufs_hba *hba;
8736 "Invalid memory reference for dev is NULL\n");
8741 host = scsi_host_alloc(&ufshcd_driver_template,
8742 sizeof(struct ufs_hba));
8744 dev_err(dev, "scsi_host_alloc failed\n");
8748 hba = shost_priv(host);
8752 hba->dev_ref_clk_freq = REF_CLK_FREQ_INVAL;
8754 INIT_LIST_HEAD(&hba->clk_list_head);
8759 EXPORT_SYMBOL(ufshcd_alloc_host);
8761 /* This function exists because blk_mq_alloc_tag_set() requires this. */
8762 static blk_status_t ufshcd_queue_tmf(struct blk_mq_hw_ctx *hctx,
8763 const struct blk_mq_queue_data *qd)
8766 return BLK_STS_NOTSUPP;
8769 static const struct blk_mq_ops ufshcd_tmf_ops = {
8770 .queue_rq = ufshcd_queue_tmf,
8774 * ufshcd_init - Driver initialization routine
8775 * @hba: per-adapter instance
8776 * @mmio_base: base register address
8777 * @irq: Interrupt line of device
8778 * Returns 0 on success, non-zero value on failure
8780 int ufshcd_init(struct ufs_hba *hba, void __iomem *mmio_base, unsigned int irq)
8783 struct Scsi_Host *host = hba->host;
8784 struct device *dev = hba->dev;
8788 "Invalid memory reference for mmio_base is NULL\n");
8793 hba->mmio_base = mmio_base;
8795 hba->vps = &ufs_hba_vps;
8797 err = ufshcd_hba_init(hba);
8801 /* Read capabilities registers */
8802 err = ufshcd_hba_capabilities(hba);
8806 /* Get UFS version supported by the controller */
8807 hba->ufs_version = ufshcd_get_ufs_version(hba);
8809 if ((hba->ufs_version != UFSHCI_VERSION_10) &&
8810 (hba->ufs_version != UFSHCI_VERSION_11) &&
8811 (hba->ufs_version != UFSHCI_VERSION_20) &&
8812 (hba->ufs_version != UFSHCI_VERSION_21))
8813 dev_err(hba->dev, "invalid UFS version 0x%x\n",
8816 /* Get Interrupt bit mask per version */
8817 hba->intr_mask = ufshcd_get_intr_mask(hba);
8819 err = ufshcd_set_dma_mask(hba);
8821 dev_err(hba->dev, "set dma mask failed\n");
8825 /* Allocate memory for host memory space */
8826 err = ufshcd_memory_alloc(hba);
8828 dev_err(hba->dev, "Memory allocation failed\n");
8833 ufshcd_host_memory_configure(hba);
8835 host->can_queue = hba->nutrs;
8836 host->cmd_per_lun = hba->nutrs;
8837 host->max_id = UFSHCD_MAX_ID;
8838 host->max_lun = UFS_MAX_LUNS;
8839 host->max_channel = UFSHCD_MAX_CHANNEL;
8840 host->unique_id = host->host_no;
8841 host->max_cmd_len = UFS_CDB_SIZE;
8843 hba->max_pwr_info.is_valid = false;
8845 /* Initialize work queues */
8846 INIT_WORK(&hba->eh_work, ufshcd_err_handler);
8847 INIT_WORK(&hba->eeh_work, ufshcd_exception_event_handler);
8849 /* Initialize UIC command mutex */
8850 mutex_init(&hba->uic_cmd_mutex);
8852 /* Initialize mutex for device management commands */
8853 mutex_init(&hba->dev_cmd.lock);
8855 init_rwsem(&hba->clk_scaling_lock);
8857 ufshcd_init_clk_gating(hba);
8859 ufshcd_init_clk_scaling(hba);
8862 * In order to avoid any spurious interrupt immediately after
8863 * registering UFS controller interrupt handler, clear any pending UFS
8864 * interrupt status and disable all the UFS interrupts.
8866 ufshcd_writel(hba, ufshcd_readl(hba, REG_INTERRUPT_STATUS),
8867 REG_INTERRUPT_STATUS);
8868 ufshcd_writel(hba, 0, REG_INTERRUPT_ENABLE);
8870 * Make sure that UFS interrupts are disabled and any pending interrupt
8871 * status is cleared before registering UFS interrupt handler.
8875 /* IRQ registration */
8876 err = devm_request_irq(dev, irq, ufshcd_intr, IRQF_SHARED, UFSHCD, hba);
8878 dev_err(hba->dev, "request irq failed\n");
8881 hba->is_irq_enabled = true;
8884 err = scsi_add_host(host, hba->dev);
8886 dev_err(hba->dev, "scsi_add_host failed\n");
8890 hba->cmd_queue = blk_mq_init_queue(&hba->host->tag_set);
8891 if (IS_ERR(hba->cmd_queue)) {
8892 err = PTR_ERR(hba->cmd_queue);
8893 goto out_remove_scsi_host;
8896 hba->tmf_tag_set = (struct blk_mq_tag_set) {
8898 .queue_depth = hba->nutmrs,
8899 .ops = &ufshcd_tmf_ops,
8900 .flags = BLK_MQ_F_NO_SCHED,
8902 err = blk_mq_alloc_tag_set(&hba->tmf_tag_set);
8904 goto free_cmd_queue;
8905 hba->tmf_queue = blk_mq_init_queue(&hba->tmf_tag_set);
8906 if (IS_ERR(hba->tmf_queue)) {
8907 err = PTR_ERR(hba->tmf_queue);
8908 goto free_tmf_tag_set;
8911 /* Reset the attached device */
8912 ufshcd_vops_device_reset(hba);
8914 ufshcd_init_crypto(hba);
8916 /* Host controller enable */
8917 err = ufshcd_hba_enable(hba);
8919 dev_err(hba->dev, "Host controller enable failed\n");
8920 ufshcd_print_host_regs(hba);
8921 ufshcd_print_host_state(hba);
8922 goto free_tmf_queue;
8926 * Set the default power management level for runtime and system PM.
8927 * Default power saving mode is to keep UFS link in Hibern8 state
8928 * and UFS device in sleep state.
8930 hba->rpm_lvl = ufs_get_desired_pm_lvl_for_dev_link_state(
8932 UIC_LINK_HIBERN8_STATE);
8933 hba->spm_lvl = ufs_get_desired_pm_lvl_for_dev_link_state(
8935 UIC_LINK_HIBERN8_STATE);
8937 INIT_DELAYED_WORK(&hba->rpm_dev_flush_recheck_work,
8938 ufshcd_rpm_dev_flush_recheck_work);
8940 /* Set the default auto-hiberate idle timer value to 150 ms */
8941 if (ufshcd_is_auto_hibern8_supported(hba) && !hba->ahit) {
8942 hba->ahit = FIELD_PREP(UFSHCI_AHIBERN8_TIMER_MASK, 150) |
8943 FIELD_PREP(UFSHCI_AHIBERN8_SCALE_MASK, 3);
8946 /* Hold auto suspend until async scan completes */
8947 pm_runtime_get_sync(dev);
8948 atomic_set(&hba->scsi_block_reqs_cnt, 0);
8950 * We are assuming that device wasn't put in sleep/power-down
8951 * state exclusively during the boot stage before kernel.
8952 * This assumption helps avoid doing link startup twice during
8953 * ufshcd_probe_hba().
8955 ufshcd_set_ufs_dev_active(hba);
8957 async_schedule(ufshcd_async_scan, hba);
8958 ufs_sysfs_add_nodes(hba->dev);
8963 blk_cleanup_queue(hba->tmf_queue);
8965 blk_mq_free_tag_set(&hba->tmf_tag_set);
8967 blk_cleanup_queue(hba->cmd_queue);
8968 out_remove_scsi_host:
8969 scsi_remove_host(hba->host);
8971 ufshcd_exit_clk_scaling(hba);
8972 ufshcd_exit_clk_gating(hba);
8974 hba->is_irq_enabled = false;
8975 ufshcd_hba_exit(hba);
8979 EXPORT_SYMBOL_GPL(ufshcd_init);
8981 MODULE_AUTHOR("Santosh Yaragnavi <santosh.sy@samsung.com>");
8982 MODULE_AUTHOR("Vinayak Holikatti <h.vinayak@samsung.com>");
8983 MODULE_DESCRIPTION("Generic UFS host controller driver Core");
8984 MODULE_LICENSE("GPL");
8985 MODULE_VERSION(UFSHCD_DRIVER_VERSION);