1 // SPDX-License-Identifier: GPL-2.0-or-later
3 * Universal Flash Storage Host controller driver Core
4 * Copyright (C) 2011-2013 Samsung India Software Operations
5 * Copyright (c) 2013-2016, The Linux Foundation. All rights reserved.
8 * Santosh Yaraganavi <santosh.sy@samsung.com>
9 * Vinayak Holikatti <h.vinayak@samsung.com>
12 #include <linux/async.h>
13 #include <linux/devfreq.h>
14 #include <linux/nls.h>
16 #include <linux/bitfield.h>
17 #include <linux/blk-pm.h>
18 #include <linux/blkdev.h>
20 #include "ufs_quirks.h"
22 #include "ufs-sysfs.h"
24 #include "ufshcd-crypto.h"
25 #include <asm/unaligned.h>
26 #include <linux/blkdev.h>
28 #define CREATE_TRACE_POINTS
29 #include <trace/events/ufs.h>
31 #define UFSHCD_ENABLE_INTRS (UTP_TRANSFER_REQ_COMPL |\
34 /* UIC command timeout, unit: ms */
35 #define UIC_CMD_TIMEOUT 500
37 /* NOP OUT retries waiting for NOP IN response */
38 #define NOP_OUT_RETRIES 10
39 /* Timeout after 50 msecs if NOP OUT hangs without response */
40 #define NOP_OUT_TIMEOUT 50 /* msecs */
42 /* Query request retries */
43 #define QUERY_REQ_RETRIES 3
44 /* Query request timeout */
45 #define QUERY_REQ_TIMEOUT 1500 /* 1.5 seconds */
47 /* Task management command timeout */
48 #define TM_CMD_TIMEOUT 100 /* msecs */
50 /* maximum number of retries for a general UIC command */
51 #define UFS_UIC_COMMAND_RETRIES 3
53 /* maximum number of link-startup retries */
54 #define DME_LINKSTARTUP_RETRIES 3
56 /* Maximum retries for Hibern8 enter */
57 #define UIC_HIBERN8_ENTER_RETRIES 3
59 /* maximum number of reset retries before giving up */
60 #define MAX_HOST_RESET_RETRIES 5
62 /* Expose the flag value from utp_upiu_query.value */
63 #define MASK_QUERY_UPIU_FLAG_LOC 0xFF
65 /* Interrupt aggregation default timeout, unit: 40us */
66 #define INT_AGGR_DEF_TO 0x02
68 /* default delay of autosuspend: 2000 ms */
69 #define RPM_AUTOSUSPEND_DELAY_MS 2000
71 /* Default delay of RPM device flush delayed work */
72 #define RPM_DEV_FLUSH_RECHECK_WORK_DELAY_MS 5000
74 /* Default value of wait time before gating device ref clock */
75 #define UFSHCD_REF_CLK_GATING_WAIT_US 0xFF /* microsecs */
77 /* Polling time to wait for fDeviceInit */
78 #define FDEVICEINIT_COMPL_TIMEOUT 1500 /* millisecs */
80 #define ufshcd_toggle_vreg(_dev, _vreg, _on) \
84 _ret = ufshcd_enable_vreg(_dev, _vreg); \
86 _ret = ufshcd_disable_vreg(_dev, _vreg); \
90 #define ufshcd_hex_dump(prefix_str, buf, len) do { \
91 size_t __len = (len); \
92 print_hex_dump(KERN_ERR, prefix_str, \
93 __len > 4 ? DUMP_PREFIX_OFFSET : DUMP_PREFIX_NONE,\
94 16, 4, buf, __len, false); \
97 int ufshcd_dump_regs(struct ufs_hba *hba, size_t offset, size_t len,
103 if (offset % 4 != 0 || len % 4 != 0) /* keep readl happy */
106 regs = kzalloc(len, GFP_ATOMIC);
110 for (pos = 0; pos < len; pos += 4)
111 regs[pos / 4] = ufshcd_readl(hba, offset + pos);
113 ufshcd_hex_dump(prefix, regs, len);
118 EXPORT_SYMBOL_GPL(ufshcd_dump_regs);
121 UFSHCD_MAX_CHANNEL = 0,
123 UFSHCD_CMD_PER_LUN = 32,
124 UFSHCD_CAN_QUEUE = 32,
131 UFSHCD_STATE_OPERATIONAL,
132 UFSHCD_STATE_EH_SCHEDULED_FATAL,
133 UFSHCD_STATE_EH_SCHEDULED_NON_FATAL,
136 /* UFSHCD error handling flags */
138 UFSHCD_EH_IN_PROGRESS = (1 << 0),
141 /* UFSHCD UIC layer error flags */
143 UFSHCD_UIC_DL_PA_INIT_ERROR = (1 << 0), /* Data link layer error */
144 UFSHCD_UIC_DL_NAC_RECEIVED_ERROR = (1 << 1), /* Data link layer error */
145 UFSHCD_UIC_DL_TCx_REPLAY_ERROR = (1 << 2), /* Data link layer error */
146 UFSHCD_UIC_NL_ERROR = (1 << 3), /* Network layer error */
147 UFSHCD_UIC_TL_ERROR = (1 << 4), /* Transport Layer error */
148 UFSHCD_UIC_DME_ERROR = (1 << 5), /* DME error */
149 UFSHCD_UIC_PA_GENERIC_ERROR = (1 << 6), /* Generic PA error */
152 #define ufshcd_set_eh_in_progress(h) \
153 ((h)->eh_flags |= UFSHCD_EH_IN_PROGRESS)
154 #define ufshcd_eh_in_progress(h) \
155 ((h)->eh_flags & UFSHCD_EH_IN_PROGRESS)
156 #define ufshcd_clear_eh_in_progress(h) \
157 ((h)->eh_flags &= ~UFSHCD_EH_IN_PROGRESS)
159 struct ufs_pm_lvl_states ufs_pm_lvl_states[] = {
160 {UFS_ACTIVE_PWR_MODE, UIC_LINK_ACTIVE_STATE},
161 {UFS_ACTIVE_PWR_MODE, UIC_LINK_HIBERN8_STATE},
162 {UFS_SLEEP_PWR_MODE, UIC_LINK_ACTIVE_STATE},
163 {UFS_SLEEP_PWR_MODE, UIC_LINK_HIBERN8_STATE},
164 {UFS_POWERDOWN_PWR_MODE, UIC_LINK_HIBERN8_STATE},
165 {UFS_POWERDOWN_PWR_MODE, UIC_LINK_OFF_STATE},
168 static inline enum ufs_dev_pwr_mode
169 ufs_get_pm_lvl_to_dev_pwr_mode(enum ufs_pm_level lvl)
171 return ufs_pm_lvl_states[lvl].dev_state;
174 static inline enum uic_link_state
175 ufs_get_pm_lvl_to_link_pwr_state(enum ufs_pm_level lvl)
177 return ufs_pm_lvl_states[lvl].link_state;
180 static inline enum ufs_pm_level
181 ufs_get_desired_pm_lvl_for_dev_link_state(enum ufs_dev_pwr_mode dev_state,
182 enum uic_link_state link_state)
184 enum ufs_pm_level lvl;
186 for (lvl = UFS_PM_LVL_0; lvl < UFS_PM_LVL_MAX; lvl++) {
187 if ((ufs_pm_lvl_states[lvl].dev_state == dev_state) &&
188 (ufs_pm_lvl_states[lvl].link_state == link_state))
192 /* if no match found, return the level 0 */
196 static struct ufs_dev_fix ufs_fixups[] = {
197 /* UFS cards deviations table */
198 UFS_FIX(UFS_VENDOR_MICRON, UFS_ANY_MODEL,
199 UFS_DEVICE_QUIRK_DELAY_BEFORE_LPM),
200 UFS_FIX(UFS_VENDOR_SAMSUNG, UFS_ANY_MODEL,
201 UFS_DEVICE_QUIRK_DELAY_BEFORE_LPM |
202 UFS_DEVICE_QUIRK_HOST_PA_TACTIVATE |
203 UFS_DEVICE_QUIRK_RECOVERY_FROM_DL_NAC_ERRORS),
204 UFS_FIX(UFS_VENDOR_SKHYNIX, UFS_ANY_MODEL,
205 UFS_DEVICE_QUIRK_HOST_PA_SAVECONFIGTIME),
206 UFS_FIX(UFS_VENDOR_SKHYNIX, "hB8aL1" /*H28U62301AMR*/,
207 UFS_DEVICE_QUIRK_HOST_VS_DEBUGSAVECONFIGTIME),
208 UFS_FIX(UFS_VENDOR_TOSHIBA, UFS_ANY_MODEL,
209 UFS_DEVICE_QUIRK_DELAY_BEFORE_LPM),
210 UFS_FIX(UFS_VENDOR_TOSHIBA, "THGLF2G9C8KBADG",
211 UFS_DEVICE_QUIRK_PA_TACTIVATE),
212 UFS_FIX(UFS_VENDOR_TOSHIBA, "THGLF2G9D8KBADG",
213 UFS_DEVICE_QUIRK_PA_TACTIVATE),
217 static irqreturn_t ufshcd_tmc_handler(struct ufs_hba *hba);
218 static void ufshcd_async_scan(void *data, async_cookie_t cookie);
219 static int ufshcd_reset_and_restore(struct ufs_hba *hba);
220 static int ufshcd_eh_host_reset_handler(struct scsi_cmnd *cmd);
221 static int ufshcd_clear_tm_cmd(struct ufs_hba *hba, int tag);
222 static void ufshcd_hba_exit(struct ufs_hba *hba);
223 static int ufshcd_probe_hba(struct ufs_hba *hba, bool async);
224 static int __ufshcd_setup_clocks(struct ufs_hba *hba, bool on,
226 static int ufshcd_setup_clocks(struct ufs_hba *hba, bool on);
227 static int ufshcd_uic_hibern8_enter(struct ufs_hba *hba);
228 static inline void ufshcd_add_delay_before_dme_cmd(struct ufs_hba *hba);
229 static int ufshcd_host_reset_and_restore(struct ufs_hba *hba);
230 static void ufshcd_resume_clkscaling(struct ufs_hba *hba);
231 static void ufshcd_suspend_clkscaling(struct ufs_hba *hba);
232 static void __ufshcd_suspend_clkscaling(struct ufs_hba *hba);
233 static int ufshcd_scale_clks(struct ufs_hba *hba, bool scale_up);
234 static irqreturn_t ufshcd_intr(int irq, void *__hba);
235 static int ufshcd_change_power_mode(struct ufs_hba *hba,
236 struct ufs_pa_layer_attr *pwr_mode);
237 static void ufshcd_schedule_eh_work(struct ufs_hba *hba);
238 static int ufshcd_setup_hba_vreg(struct ufs_hba *hba, bool on);
239 static int ufshcd_setup_vreg(struct ufs_hba *hba, bool on);
240 static inline int ufshcd_config_vreg_hpm(struct ufs_hba *hba,
241 struct ufs_vreg *vreg);
242 static int ufshcd_try_to_abort_task(struct ufs_hba *hba, int tag);
243 static int ufshcd_wb_buf_flush_enable(struct ufs_hba *hba);
244 static int ufshcd_wb_buf_flush_disable(struct ufs_hba *hba);
245 static int ufshcd_wb_ctrl(struct ufs_hba *hba, bool enable);
246 static int ufshcd_wb_toggle_flush_during_h8(struct ufs_hba *hba, bool set);
247 static inline void ufshcd_wb_toggle_flush(struct ufs_hba *hba, bool enable);
249 static inline bool ufshcd_valid_tag(struct ufs_hba *hba, int tag)
251 return tag >= 0 && tag < hba->nutrs;
254 static inline void ufshcd_enable_irq(struct ufs_hba *hba)
256 if (!hba->is_irq_enabled) {
257 enable_irq(hba->irq);
258 hba->is_irq_enabled = true;
262 static inline void ufshcd_disable_irq(struct ufs_hba *hba)
264 if (hba->is_irq_enabled) {
265 disable_irq(hba->irq);
266 hba->is_irq_enabled = false;
270 static inline void ufshcd_wb_config(struct ufs_hba *hba)
274 if (!ufshcd_is_wb_allowed(hba))
277 ret = ufshcd_wb_ctrl(hba, true);
279 dev_err(hba->dev, "%s: Enable WB failed: %d\n", __func__, ret);
281 dev_info(hba->dev, "%s: Write Booster Configured\n", __func__);
282 ret = ufshcd_wb_toggle_flush_during_h8(hba, true);
284 dev_err(hba->dev, "%s: En WB flush during H8: failed: %d\n",
286 ufshcd_wb_toggle_flush(hba, true);
289 static void ufshcd_scsi_unblock_requests(struct ufs_hba *hba)
291 if (atomic_dec_and_test(&hba->scsi_block_reqs_cnt))
292 scsi_unblock_requests(hba->host);
295 static void ufshcd_scsi_block_requests(struct ufs_hba *hba)
297 if (atomic_inc_return(&hba->scsi_block_reqs_cnt) == 1)
298 scsi_block_requests(hba->host);
301 static void ufshcd_add_cmd_upiu_trace(struct ufs_hba *hba, unsigned int tag,
304 struct utp_upiu_req *rq = hba->lrb[tag].ucd_req_ptr;
306 trace_ufshcd_upiu(dev_name(hba->dev), str, &rq->header, &rq->sc.cdb);
309 static void ufshcd_add_query_upiu_trace(struct ufs_hba *hba, unsigned int tag,
312 struct utp_upiu_req *rq = hba->lrb[tag].ucd_req_ptr;
314 trace_ufshcd_upiu(dev_name(hba->dev), str, &rq->header, &rq->qr);
317 static void ufshcd_add_tm_upiu_trace(struct ufs_hba *hba, unsigned int tag,
320 int off = (int)tag - hba->nutrs;
321 struct utp_task_req_desc *descp = &hba->utmrdl_base_addr[off];
323 trace_ufshcd_upiu(dev_name(hba->dev), str, &descp->req_header,
324 &descp->input_param1);
327 static void ufshcd_add_uic_command_trace(struct ufs_hba *hba,
328 struct uic_command *ucmd,
333 if (!trace_ufshcd_uic_command_enabled())
336 if (!strcmp(str, "send"))
339 cmd = ufshcd_readl(hba, REG_UIC_COMMAND);
341 trace_ufshcd_uic_command(dev_name(hba->dev), str, cmd,
342 ufshcd_readl(hba, REG_UIC_COMMAND_ARG_1),
343 ufshcd_readl(hba, REG_UIC_COMMAND_ARG_2),
344 ufshcd_readl(hba, REG_UIC_COMMAND_ARG_3));
347 static void ufshcd_add_command_trace(struct ufs_hba *hba,
348 unsigned int tag, const char *str)
353 struct ufshcd_lrb *lrbp = &hba->lrb[tag];
354 struct scsi_cmnd *cmd = lrbp->cmd;
355 int transfer_len = -1;
357 if (!trace_ufshcd_command_enabled()) {
358 /* trace UPIU W/O tracing command */
360 ufshcd_add_cmd_upiu_trace(hba, tag, str);
364 if (cmd) { /* data phase exists */
365 /* trace UPIU also */
366 ufshcd_add_cmd_upiu_trace(hba, tag, str);
367 opcode = cmd->cmnd[0];
368 if ((opcode == READ_10) || (opcode == WRITE_10)) {
370 * Currently we only fully trace read(10) and write(10)
373 if (cmd->request && cmd->request->bio)
374 lba = cmd->request->bio->bi_iter.bi_sector;
375 transfer_len = be32_to_cpu(
376 lrbp->ucd_req_ptr->sc.exp_data_transfer_len);
380 intr = ufshcd_readl(hba, REG_INTERRUPT_STATUS);
381 doorbell = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
382 trace_ufshcd_command(dev_name(hba->dev), str, tag,
383 doorbell, transfer_len, intr, lba, opcode);
386 static void ufshcd_print_clk_freqs(struct ufs_hba *hba)
388 struct ufs_clk_info *clki;
389 struct list_head *head = &hba->clk_list_head;
391 if (list_empty(head))
394 list_for_each_entry(clki, head, list) {
395 if (!IS_ERR_OR_NULL(clki->clk) && clki->min_freq &&
397 dev_err(hba->dev, "clk: %s, rate: %u\n",
398 clki->name, clki->curr_freq);
402 static void ufshcd_print_err_hist(struct ufs_hba *hba,
403 struct ufs_err_reg_hist *err_hist,
409 for (i = 0; i < UFS_ERR_REG_HIST_LENGTH; i++) {
410 int p = (i + err_hist->pos) % UFS_ERR_REG_HIST_LENGTH;
412 if (err_hist->tstamp[p] == 0)
414 dev_err(hba->dev, "%s[%d] = 0x%x at %lld us\n", err_name, p,
415 err_hist->reg[p], ktime_to_us(err_hist->tstamp[p]));
420 dev_err(hba->dev, "No record of %s\n", err_name);
423 static void ufshcd_print_host_regs(struct ufs_hba *hba)
425 ufshcd_dump_regs(hba, 0, UFSHCI_REG_SPACE_SIZE, "host_regs: ");
427 ufshcd_print_err_hist(hba, &hba->ufs_stats.pa_err, "pa_err");
428 ufshcd_print_err_hist(hba, &hba->ufs_stats.dl_err, "dl_err");
429 ufshcd_print_err_hist(hba, &hba->ufs_stats.nl_err, "nl_err");
430 ufshcd_print_err_hist(hba, &hba->ufs_stats.tl_err, "tl_err");
431 ufshcd_print_err_hist(hba, &hba->ufs_stats.dme_err, "dme_err");
432 ufshcd_print_err_hist(hba, &hba->ufs_stats.auto_hibern8_err,
434 ufshcd_print_err_hist(hba, &hba->ufs_stats.fatal_err, "fatal_err");
435 ufshcd_print_err_hist(hba, &hba->ufs_stats.link_startup_err,
436 "link_startup_fail");
437 ufshcd_print_err_hist(hba, &hba->ufs_stats.resume_err, "resume_fail");
438 ufshcd_print_err_hist(hba, &hba->ufs_stats.suspend_err,
440 ufshcd_print_err_hist(hba, &hba->ufs_stats.dev_reset, "dev_reset");
441 ufshcd_print_err_hist(hba, &hba->ufs_stats.host_reset, "host_reset");
442 ufshcd_print_err_hist(hba, &hba->ufs_stats.task_abort, "task_abort");
444 ufshcd_vops_dbg_register_dump(hba);
448 void ufshcd_print_trs(struct ufs_hba *hba, unsigned long bitmap, bool pr_prdt)
450 struct ufshcd_lrb *lrbp;
454 for_each_set_bit(tag, &bitmap, hba->nutrs) {
455 lrbp = &hba->lrb[tag];
457 dev_err(hba->dev, "UPIU[%d] - issue time %lld us\n",
458 tag, ktime_to_us(lrbp->issue_time_stamp));
459 dev_err(hba->dev, "UPIU[%d] - complete time %lld us\n",
460 tag, ktime_to_us(lrbp->compl_time_stamp));
462 "UPIU[%d] - Transfer Request Descriptor phys@0x%llx\n",
463 tag, (u64)lrbp->utrd_dma_addr);
465 ufshcd_hex_dump("UPIU TRD: ", lrbp->utr_descriptor_ptr,
466 sizeof(struct utp_transfer_req_desc));
467 dev_err(hba->dev, "UPIU[%d] - Request UPIU phys@0x%llx\n", tag,
468 (u64)lrbp->ucd_req_dma_addr);
469 ufshcd_hex_dump("UPIU REQ: ", lrbp->ucd_req_ptr,
470 sizeof(struct utp_upiu_req));
471 dev_err(hba->dev, "UPIU[%d] - Response UPIU phys@0x%llx\n", tag,
472 (u64)lrbp->ucd_rsp_dma_addr);
473 ufshcd_hex_dump("UPIU RSP: ", lrbp->ucd_rsp_ptr,
474 sizeof(struct utp_upiu_rsp));
476 prdt_length = le16_to_cpu(
477 lrbp->utr_descriptor_ptr->prd_table_length);
478 if (hba->quirks & UFSHCD_QUIRK_PRDT_BYTE_GRAN)
479 prdt_length /= sizeof(struct ufshcd_sg_entry);
482 "UPIU[%d] - PRDT - %d entries phys@0x%llx\n",
484 (u64)lrbp->ucd_prdt_dma_addr);
487 ufshcd_hex_dump("UPIU PRDT: ", lrbp->ucd_prdt_ptr,
488 sizeof(struct ufshcd_sg_entry) * prdt_length);
492 static void ufshcd_print_tmrs(struct ufs_hba *hba, unsigned long bitmap)
496 for_each_set_bit(tag, &bitmap, hba->nutmrs) {
497 struct utp_task_req_desc *tmrdp = &hba->utmrdl_base_addr[tag];
499 dev_err(hba->dev, "TM[%d] - Task Management Header\n", tag);
500 ufshcd_hex_dump("", tmrdp, sizeof(*tmrdp));
504 static void ufshcd_print_host_state(struct ufs_hba *hba)
506 struct scsi_device *sdev_ufs = hba->sdev_ufs_device;
508 dev_err(hba->dev, "UFS Host state=%d\n", hba->ufshcd_state);
509 dev_err(hba->dev, "outstanding reqs=0x%lx tasks=0x%lx\n",
510 hba->outstanding_reqs, hba->outstanding_tasks);
511 dev_err(hba->dev, "saved_err=0x%x, saved_uic_err=0x%x\n",
512 hba->saved_err, hba->saved_uic_err);
513 dev_err(hba->dev, "Device power mode=%d, UIC link state=%d\n",
514 hba->curr_dev_pwr_mode, hba->uic_link_state);
515 dev_err(hba->dev, "PM in progress=%d, sys. suspended=%d\n",
516 hba->pm_op_in_progress, hba->is_sys_suspended);
517 dev_err(hba->dev, "Auto BKOPS=%d, Host self-block=%d\n",
518 hba->auto_bkops_enabled, hba->host->host_self_blocked);
519 dev_err(hba->dev, "Clk gate=%d\n", hba->clk_gating.state);
521 "last_hibern8_exit_tstamp at %lld us, hibern8_exit_cnt=%d\n",
522 ktime_to_us(hba->ufs_stats.last_hibern8_exit_tstamp),
523 hba->ufs_stats.hibern8_exit_cnt);
524 dev_err(hba->dev, "last intr at %lld us, last intr status=0x%x\n",
525 ktime_to_us(hba->ufs_stats.last_intr_ts),
526 hba->ufs_stats.last_intr_status);
527 dev_err(hba->dev, "error handling flags=0x%x, req. abort count=%d\n",
528 hba->eh_flags, hba->req_abort_count);
529 dev_err(hba->dev, "hba->ufs_version=0x%x, Host capabilities=0x%x, caps=0x%x\n",
530 hba->ufs_version, hba->capabilities, hba->caps);
531 dev_err(hba->dev, "quirks=0x%x, dev. quirks=0x%x\n", hba->quirks,
534 dev_err(hba->dev, "UFS dev info: %.8s %.16s rev %.4s\n",
535 sdev_ufs->vendor, sdev_ufs->model, sdev_ufs->rev);
537 ufshcd_print_clk_freqs(hba);
541 * ufshcd_print_pwr_info - print power params as saved in hba
543 * @hba: per-adapter instance
545 static void ufshcd_print_pwr_info(struct ufs_hba *hba)
547 static const char * const names[] = {
557 dev_err(hba->dev, "%s:[RX, TX]: gear=[%d, %d], lane[%d, %d], pwr[%s, %s], rate = %d\n",
559 hba->pwr_info.gear_rx, hba->pwr_info.gear_tx,
560 hba->pwr_info.lane_rx, hba->pwr_info.lane_tx,
561 names[hba->pwr_info.pwr_rx],
562 names[hba->pwr_info.pwr_tx],
563 hba->pwr_info.hs_rate);
566 void ufshcd_delay_us(unsigned long us, unsigned long tolerance)
574 usleep_range(us, us + tolerance);
576 EXPORT_SYMBOL_GPL(ufshcd_delay_us);
579 * ufshcd_wait_for_register - wait for register value to change
580 * @hba: per-adapter interface
581 * @reg: mmio register offset
582 * @mask: mask to apply to the read register value
583 * @val: value to wait for
584 * @interval_us: polling interval in microseconds
585 * @timeout_ms: timeout in milliseconds
588 * -ETIMEDOUT on error, zero on success.
590 int ufshcd_wait_for_register(struct ufs_hba *hba, u32 reg, u32 mask,
591 u32 val, unsigned long interval_us,
592 unsigned long timeout_ms)
595 unsigned long timeout = jiffies + msecs_to_jiffies(timeout_ms);
597 /* ignore bits that we don't intend to wait on */
600 while ((ufshcd_readl(hba, reg) & mask) != val) {
601 usleep_range(interval_us, interval_us + 50);
602 if (time_after(jiffies, timeout)) {
603 if ((ufshcd_readl(hba, reg) & mask) != val)
613 * ufshcd_get_intr_mask - Get the interrupt bit mask
614 * @hba: Pointer to adapter instance
616 * Returns interrupt bit mask per version
618 static inline u32 ufshcd_get_intr_mask(struct ufs_hba *hba)
622 switch (hba->ufs_version) {
623 case UFSHCI_VERSION_10:
624 intr_mask = INTERRUPT_MASK_ALL_VER_10;
626 case UFSHCI_VERSION_11:
627 case UFSHCI_VERSION_20:
628 intr_mask = INTERRUPT_MASK_ALL_VER_11;
630 case UFSHCI_VERSION_21:
632 intr_mask = INTERRUPT_MASK_ALL_VER_21;
640 * ufshcd_get_ufs_version - Get the UFS version supported by the HBA
641 * @hba: Pointer to adapter instance
643 * Returns UFSHCI version supported by the controller
645 static inline u32 ufshcd_get_ufs_version(struct ufs_hba *hba)
647 if (hba->quirks & UFSHCD_QUIRK_BROKEN_UFS_HCI_VERSION)
648 return ufshcd_vops_get_ufs_hci_version(hba);
650 return ufshcd_readl(hba, REG_UFS_VERSION);
654 * ufshcd_is_device_present - Check if any device connected to
655 * the host controller
656 * @hba: pointer to adapter instance
658 * Returns true if device present, false if no device detected
660 static inline bool ufshcd_is_device_present(struct ufs_hba *hba)
662 return (ufshcd_readl(hba, REG_CONTROLLER_STATUS) &
663 DEVICE_PRESENT) ? true : false;
667 * ufshcd_get_tr_ocs - Get the UTRD Overall Command Status
668 * @lrbp: pointer to local command reference block
670 * This function is used to get the OCS field from UTRD
671 * Returns the OCS field in the UTRD
673 static inline int ufshcd_get_tr_ocs(struct ufshcd_lrb *lrbp)
675 return le32_to_cpu(lrbp->utr_descriptor_ptr->header.dword_2) & MASK_OCS;
679 * ufshcd_utrl_clear - Clear a bit in UTRLCLR register
680 * @hba: per adapter instance
681 * @pos: position of the bit to be cleared
683 static inline void ufshcd_utrl_clear(struct ufs_hba *hba, u32 pos)
685 if (hba->quirks & UFSHCI_QUIRK_BROKEN_REQ_LIST_CLR)
686 ufshcd_writel(hba, (1 << pos), REG_UTP_TRANSFER_REQ_LIST_CLEAR);
688 ufshcd_writel(hba, ~(1 << pos),
689 REG_UTP_TRANSFER_REQ_LIST_CLEAR);
693 * ufshcd_utmrl_clear - Clear a bit in UTRMLCLR register
694 * @hba: per adapter instance
695 * @pos: position of the bit to be cleared
697 static inline void ufshcd_utmrl_clear(struct ufs_hba *hba, u32 pos)
699 if (hba->quirks & UFSHCI_QUIRK_BROKEN_REQ_LIST_CLR)
700 ufshcd_writel(hba, (1 << pos), REG_UTP_TASK_REQ_LIST_CLEAR);
702 ufshcd_writel(hba, ~(1 << pos), REG_UTP_TASK_REQ_LIST_CLEAR);
706 * ufshcd_outstanding_req_clear - Clear a bit in outstanding request field
707 * @hba: per adapter instance
708 * @tag: position of the bit to be cleared
710 static inline void ufshcd_outstanding_req_clear(struct ufs_hba *hba, int tag)
712 __clear_bit(tag, &hba->outstanding_reqs);
716 * ufshcd_get_lists_status - Check UCRDY, UTRLRDY and UTMRLRDY
717 * @reg: Register value of host controller status
719 * Returns integer, 0 on Success and positive value if failed
721 static inline int ufshcd_get_lists_status(u32 reg)
723 return !((reg & UFSHCD_STATUS_READY) == UFSHCD_STATUS_READY);
727 * ufshcd_get_uic_cmd_result - Get the UIC command result
728 * @hba: Pointer to adapter instance
730 * This function gets the result of UIC command completion
731 * Returns 0 on success, non zero value on error
733 static inline int ufshcd_get_uic_cmd_result(struct ufs_hba *hba)
735 return ufshcd_readl(hba, REG_UIC_COMMAND_ARG_2) &
736 MASK_UIC_COMMAND_RESULT;
740 * ufshcd_get_dme_attr_val - Get the value of attribute returned by UIC command
741 * @hba: Pointer to adapter instance
743 * This function gets UIC command argument3
744 * Returns 0 on success, non zero value on error
746 static inline u32 ufshcd_get_dme_attr_val(struct ufs_hba *hba)
748 return ufshcd_readl(hba, REG_UIC_COMMAND_ARG_3);
752 * ufshcd_get_req_rsp - returns the TR response transaction type
753 * @ucd_rsp_ptr: pointer to response UPIU
756 ufshcd_get_req_rsp(struct utp_upiu_rsp *ucd_rsp_ptr)
758 return be32_to_cpu(ucd_rsp_ptr->header.dword_0) >> 24;
762 * ufshcd_get_rsp_upiu_result - Get the result from response UPIU
763 * @ucd_rsp_ptr: pointer to response UPIU
765 * This function gets the response status and scsi_status from response UPIU
766 * Returns the response result code.
769 ufshcd_get_rsp_upiu_result(struct utp_upiu_rsp *ucd_rsp_ptr)
771 return be32_to_cpu(ucd_rsp_ptr->header.dword_1) & MASK_RSP_UPIU_RESULT;
775 * ufshcd_get_rsp_upiu_data_seg_len - Get the data segment length
777 * @ucd_rsp_ptr: pointer to response UPIU
779 * Return the data segment length.
781 static inline unsigned int
782 ufshcd_get_rsp_upiu_data_seg_len(struct utp_upiu_rsp *ucd_rsp_ptr)
784 return be32_to_cpu(ucd_rsp_ptr->header.dword_2) &
785 MASK_RSP_UPIU_DATA_SEG_LEN;
789 * ufshcd_is_exception_event - Check if the device raised an exception event
790 * @ucd_rsp_ptr: pointer to response UPIU
792 * The function checks if the device raised an exception event indicated in
793 * the Device Information field of response UPIU.
795 * Returns true if exception is raised, false otherwise.
797 static inline bool ufshcd_is_exception_event(struct utp_upiu_rsp *ucd_rsp_ptr)
799 return be32_to_cpu(ucd_rsp_ptr->header.dword_2) &
800 MASK_RSP_EXCEPTION_EVENT ? true : false;
804 * ufshcd_reset_intr_aggr - Reset interrupt aggregation values.
805 * @hba: per adapter instance
808 ufshcd_reset_intr_aggr(struct ufs_hba *hba)
810 ufshcd_writel(hba, INT_AGGR_ENABLE |
811 INT_AGGR_COUNTER_AND_TIMER_RESET,
812 REG_UTP_TRANSFER_REQ_INT_AGG_CONTROL);
816 * ufshcd_config_intr_aggr - Configure interrupt aggregation values.
817 * @hba: per adapter instance
818 * @cnt: Interrupt aggregation counter threshold
819 * @tmout: Interrupt aggregation timeout value
822 ufshcd_config_intr_aggr(struct ufs_hba *hba, u8 cnt, u8 tmout)
824 ufshcd_writel(hba, INT_AGGR_ENABLE | INT_AGGR_PARAM_WRITE |
825 INT_AGGR_COUNTER_THLD_VAL(cnt) |
826 INT_AGGR_TIMEOUT_VAL(tmout),
827 REG_UTP_TRANSFER_REQ_INT_AGG_CONTROL);
831 * ufshcd_disable_intr_aggr - Disables interrupt aggregation.
832 * @hba: per adapter instance
834 static inline void ufshcd_disable_intr_aggr(struct ufs_hba *hba)
836 ufshcd_writel(hba, 0, REG_UTP_TRANSFER_REQ_INT_AGG_CONTROL);
840 * ufshcd_enable_run_stop_reg - Enable run-stop registers,
841 * When run-stop registers are set to 1, it indicates the
842 * host controller that it can process the requests
843 * @hba: per adapter instance
845 static void ufshcd_enable_run_stop_reg(struct ufs_hba *hba)
847 ufshcd_writel(hba, UTP_TASK_REQ_LIST_RUN_STOP_BIT,
848 REG_UTP_TASK_REQ_LIST_RUN_STOP);
849 ufshcd_writel(hba, UTP_TRANSFER_REQ_LIST_RUN_STOP_BIT,
850 REG_UTP_TRANSFER_REQ_LIST_RUN_STOP);
854 * ufshcd_hba_start - Start controller initialization sequence
855 * @hba: per adapter instance
857 static inline void ufshcd_hba_start(struct ufs_hba *hba)
859 u32 val = CONTROLLER_ENABLE;
861 if (ufshcd_crypto_enable(hba))
862 val |= CRYPTO_GENERAL_ENABLE;
864 ufshcd_writel(hba, val, REG_CONTROLLER_ENABLE);
868 * ufshcd_is_hba_active - Get controller state
869 * @hba: per adapter instance
871 * Returns false if controller is active, true otherwise
873 static inline bool ufshcd_is_hba_active(struct ufs_hba *hba)
875 return (ufshcd_readl(hba, REG_CONTROLLER_ENABLE) & CONTROLLER_ENABLE)
879 u32 ufshcd_get_local_unipro_ver(struct ufs_hba *hba)
881 /* HCI version 1.0 and 1.1 supports UniPro 1.41 */
882 if ((hba->ufs_version == UFSHCI_VERSION_10) ||
883 (hba->ufs_version == UFSHCI_VERSION_11))
884 return UFS_UNIPRO_VER_1_41;
886 return UFS_UNIPRO_VER_1_6;
888 EXPORT_SYMBOL(ufshcd_get_local_unipro_ver);
890 static bool ufshcd_is_unipro_pa_params_tuning_req(struct ufs_hba *hba)
893 * If both host and device support UniPro ver1.6 or later, PA layer
894 * parameters tuning happens during link startup itself.
896 * We can manually tune PA layer parameters if either host or device
897 * doesn't support UniPro ver 1.6 or later. But to keep manual tuning
898 * logic simple, we will only do manual tuning if local unipro version
899 * doesn't support ver1.6 or later.
901 if (ufshcd_get_local_unipro_ver(hba) < UFS_UNIPRO_VER_1_6)
908 * ufshcd_set_clk_freq - set UFS controller clock frequencies
909 * @hba: per adapter instance
910 * @scale_up: If True, set max possible frequency othewise set low frequency
912 * Returns 0 if successful
913 * Returns < 0 for any other errors
915 static int ufshcd_set_clk_freq(struct ufs_hba *hba, bool scale_up)
918 struct ufs_clk_info *clki;
919 struct list_head *head = &hba->clk_list_head;
921 if (list_empty(head))
924 list_for_each_entry(clki, head, list) {
925 if (!IS_ERR_OR_NULL(clki->clk)) {
926 if (scale_up && clki->max_freq) {
927 if (clki->curr_freq == clki->max_freq)
930 ret = clk_set_rate(clki->clk, clki->max_freq);
932 dev_err(hba->dev, "%s: %s clk set rate(%dHz) failed, %d\n",
933 __func__, clki->name,
934 clki->max_freq, ret);
937 trace_ufshcd_clk_scaling(dev_name(hba->dev),
938 "scaled up", clki->name,
942 clki->curr_freq = clki->max_freq;
944 } else if (!scale_up && clki->min_freq) {
945 if (clki->curr_freq == clki->min_freq)
948 ret = clk_set_rate(clki->clk, clki->min_freq);
950 dev_err(hba->dev, "%s: %s clk set rate(%dHz) failed, %d\n",
951 __func__, clki->name,
952 clki->min_freq, ret);
955 trace_ufshcd_clk_scaling(dev_name(hba->dev),
956 "scaled down", clki->name,
959 clki->curr_freq = clki->min_freq;
962 dev_dbg(hba->dev, "%s: clk: %s, rate: %lu\n", __func__,
963 clki->name, clk_get_rate(clki->clk));
971 * ufshcd_scale_clks - scale up or scale down UFS controller clocks
972 * @hba: per adapter instance
973 * @scale_up: True if scaling up and false if scaling down
975 * Returns 0 if successful
976 * Returns < 0 for any other errors
978 static int ufshcd_scale_clks(struct ufs_hba *hba, bool scale_up)
981 ktime_t start = ktime_get();
983 ret = ufshcd_vops_clk_scale_notify(hba, scale_up, PRE_CHANGE);
987 ret = ufshcd_set_clk_freq(hba, scale_up);
991 ret = ufshcd_vops_clk_scale_notify(hba, scale_up, POST_CHANGE);
993 ufshcd_set_clk_freq(hba, !scale_up);
996 trace_ufshcd_profile_clk_scaling(dev_name(hba->dev),
997 (scale_up ? "up" : "down"),
998 ktime_to_us(ktime_sub(ktime_get(), start)), ret);
1003 * ufshcd_is_devfreq_scaling_required - check if scaling is required or not
1004 * @hba: per adapter instance
1005 * @scale_up: True if scaling up and false if scaling down
1007 * Returns true if scaling is required, false otherwise.
1009 static bool ufshcd_is_devfreq_scaling_required(struct ufs_hba *hba,
1012 struct ufs_clk_info *clki;
1013 struct list_head *head = &hba->clk_list_head;
1015 if (list_empty(head))
1018 list_for_each_entry(clki, head, list) {
1019 if (!IS_ERR_OR_NULL(clki->clk)) {
1020 if (scale_up && clki->max_freq) {
1021 if (clki->curr_freq == clki->max_freq)
1024 } else if (!scale_up && clki->min_freq) {
1025 if (clki->curr_freq == clki->min_freq)
1035 static int ufshcd_wait_for_doorbell_clr(struct ufs_hba *hba,
1036 u64 wait_timeout_us)
1038 unsigned long flags;
1042 bool timeout = false, do_last_check = false;
1045 ufshcd_hold(hba, false);
1046 spin_lock_irqsave(hba->host->host_lock, flags);
1048 * Wait for all the outstanding tasks/transfer requests.
1049 * Verify by checking the doorbell registers are clear.
1051 start = ktime_get();
1053 if (hba->ufshcd_state != UFSHCD_STATE_OPERATIONAL) {
1058 tm_doorbell = ufshcd_readl(hba, REG_UTP_TASK_REQ_DOOR_BELL);
1059 tr_doorbell = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
1060 if (!tm_doorbell && !tr_doorbell) {
1063 } else if (do_last_check) {
1067 spin_unlock_irqrestore(hba->host->host_lock, flags);
1069 if (ktime_to_us(ktime_sub(ktime_get(), start)) >
1073 * We might have scheduled out for long time so make
1074 * sure to check if doorbells are cleared by this time
1077 do_last_check = true;
1079 spin_lock_irqsave(hba->host->host_lock, flags);
1080 } while (tm_doorbell || tr_doorbell);
1084 "%s: timedout waiting for doorbell to clear (tm=0x%x, tr=0x%x)\n",
1085 __func__, tm_doorbell, tr_doorbell);
1089 spin_unlock_irqrestore(hba->host->host_lock, flags);
1090 ufshcd_release(hba);
1095 * ufshcd_scale_gear - scale up/down UFS gear
1096 * @hba: per adapter instance
1097 * @scale_up: True for scaling up gear and false for scaling down
1099 * Returns 0 for success,
1100 * Returns -EBUSY if scaling can't happen at this time
1101 * Returns non-zero for any other errors
1103 static int ufshcd_scale_gear(struct ufs_hba *hba, bool scale_up)
1105 #define UFS_MIN_GEAR_TO_SCALE_DOWN UFS_HS_G1
1107 struct ufs_pa_layer_attr new_pwr_info;
1110 memcpy(&new_pwr_info, &hba->clk_scaling.saved_pwr_info.info,
1111 sizeof(struct ufs_pa_layer_attr));
1113 memcpy(&new_pwr_info, &hba->pwr_info,
1114 sizeof(struct ufs_pa_layer_attr));
1116 if (hba->pwr_info.gear_tx > UFS_MIN_GEAR_TO_SCALE_DOWN
1117 || hba->pwr_info.gear_rx > UFS_MIN_GEAR_TO_SCALE_DOWN) {
1118 /* save the current power mode */
1119 memcpy(&hba->clk_scaling.saved_pwr_info.info,
1121 sizeof(struct ufs_pa_layer_attr));
1123 /* scale down gear */
1124 new_pwr_info.gear_tx = UFS_MIN_GEAR_TO_SCALE_DOWN;
1125 new_pwr_info.gear_rx = UFS_MIN_GEAR_TO_SCALE_DOWN;
1129 /* check if the power mode needs to be changed or not? */
1130 ret = ufshcd_config_pwr_mode(hba, &new_pwr_info);
1132 dev_err(hba->dev, "%s: failed err %d, old gear: (tx %d rx %d), new gear: (tx %d rx %d)",
1134 hba->pwr_info.gear_tx, hba->pwr_info.gear_rx,
1135 new_pwr_info.gear_tx, new_pwr_info.gear_rx);
1140 static int ufshcd_clock_scaling_prepare(struct ufs_hba *hba)
1142 #define DOORBELL_CLR_TOUT_US (1000 * 1000) /* 1 sec */
1145 * make sure that there are no outstanding requests when
1146 * clock scaling is in progress
1148 ufshcd_scsi_block_requests(hba);
1149 down_write(&hba->clk_scaling_lock);
1150 if (ufshcd_wait_for_doorbell_clr(hba, DOORBELL_CLR_TOUT_US)) {
1152 up_write(&hba->clk_scaling_lock);
1153 ufshcd_scsi_unblock_requests(hba);
1159 static void ufshcd_clock_scaling_unprepare(struct ufs_hba *hba)
1161 up_write(&hba->clk_scaling_lock);
1162 ufshcd_scsi_unblock_requests(hba);
1166 * ufshcd_devfreq_scale - scale up/down UFS clocks and gear
1167 * @hba: per adapter instance
1168 * @scale_up: True for scaling up and false for scalin down
1170 * Returns 0 for success,
1171 * Returns -EBUSY if scaling can't happen at this time
1172 * Returns non-zero for any other errors
1174 static int ufshcd_devfreq_scale(struct ufs_hba *hba, bool scale_up)
1178 /* let's not get into low power until clock scaling is completed */
1179 ufshcd_hold(hba, false);
1181 ret = ufshcd_clock_scaling_prepare(hba);
1185 /* scale down the gear before scaling down clocks */
1187 ret = ufshcd_scale_gear(hba, false);
1192 ret = ufshcd_scale_clks(hba, scale_up);
1195 ufshcd_scale_gear(hba, true);
1199 /* scale up the gear after scaling up clocks */
1201 ret = ufshcd_scale_gear(hba, true);
1203 ufshcd_scale_clks(hba, false);
1208 /* Enable Write Booster if we have scaled up else disable it */
1209 up_write(&hba->clk_scaling_lock);
1210 ufshcd_wb_ctrl(hba, scale_up);
1211 down_write(&hba->clk_scaling_lock);
1214 ufshcd_clock_scaling_unprepare(hba);
1216 ufshcd_release(hba);
1220 static void ufshcd_clk_scaling_suspend_work(struct work_struct *work)
1222 struct ufs_hba *hba = container_of(work, struct ufs_hba,
1223 clk_scaling.suspend_work);
1224 unsigned long irq_flags;
1226 spin_lock_irqsave(hba->host->host_lock, irq_flags);
1227 if (hba->clk_scaling.active_reqs || hba->clk_scaling.is_suspended) {
1228 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1231 hba->clk_scaling.is_suspended = true;
1232 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1234 __ufshcd_suspend_clkscaling(hba);
1237 static void ufshcd_clk_scaling_resume_work(struct work_struct *work)
1239 struct ufs_hba *hba = container_of(work, struct ufs_hba,
1240 clk_scaling.resume_work);
1241 unsigned long irq_flags;
1243 spin_lock_irqsave(hba->host->host_lock, irq_flags);
1244 if (!hba->clk_scaling.is_suspended) {
1245 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1248 hba->clk_scaling.is_suspended = false;
1249 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1251 devfreq_resume_device(hba->devfreq);
1254 static int ufshcd_devfreq_target(struct device *dev,
1255 unsigned long *freq, u32 flags)
1258 struct ufs_hba *hba = dev_get_drvdata(dev);
1260 bool scale_up, sched_clk_scaling_suspend_work = false;
1261 struct list_head *clk_list = &hba->clk_list_head;
1262 struct ufs_clk_info *clki;
1263 unsigned long irq_flags;
1265 if (!ufshcd_is_clkscaling_supported(hba))
1268 clki = list_first_entry(&hba->clk_list_head, struct ufs_clk_info, list);
1269 /* Override with the closest supported frequency */
1270 *freq = (unsigned long) clk_round_rate(clki->clk, *freq);
1271 spin_lock_irqsave(hba->host->host_lock, irq_flags);
1272 if (ufshcd_eh_in_progress(hba)) {
1273 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1277 if (!hba->clk_scaling.active_reqs)
1278 sched_clk_scaling_suspend_work = true;
1280 if (list_empty(clk_list)) {
1281 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1285 /* Decide based on the rounded-off frequency and update */
1286 scale_up = (*freq == clki->max_freq) ? true : false;
1288 *freq = clki->min_freq;
1289 /* Update the frequency */
1290 if (!ufshcd_is_devfreq_scaling_required(hba, scale_up)) {
1291 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1293 goto out; /* no state change required */
1295 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1297 start = ktime_get();
1298 ret = ufshcd_devfreq_scale(hba, scale_up);
1300 trace_ufshcd_profile_clk_scaling(dev_name(hba->dev),
1301 (scale_up ? "up" : "down"),
1302 ktime_to_us(ktime_sub(ktime_get(), start)), ret);
1305 if (sched_clk_scaling_suspend_work)
1306 queue_work(hba->clk_scaling.workq,
1307 &hba->clk_scaling.suspend_work);
1312 static bool ufshcd_is_busy(struct request *req, void *priv, bool reserved)
1316 WARN_ON_ONCE(reserved);
1321 /* Whether or not any tag is in use by a request that is in progress. */
1322 static bool ufshcd_any_tag_in_use(struct ufs_hba *hba)
1324 struct request_queue *q = hba->cmd_queue;
1327 blk_mq_tagset_busy_iter(q->tag_set, ufshcd_is_busy, &busy);
1331 static int ufshcd_devfreq_get_dev_status(struct device *dev,
1332 struct devfreq_dev_status *stat)
1334 struct ufs_hba *hba = dev_get_drvdata(dev);
1335 struct ufs_clk_scaling *scaling = &hba->clk_scaling;
1336 unsigned long flags;
1337 struct list_head *clk_list = &hba->clk_list_head;
1338 struct ufs_clk_info *clki;
1341 if (!ufshcd_is_clkscaling_supported(hba))
1344 memset(stat, 0, sizeof(*stat));
1346 spin_lock_irqsave(hba->host->host_lock, flags);
1347 curr_t = ktime_get();
1348 if (!scaling->window_start_t)
1351 clki = list_first_entry(clk_list, struct ufs_clk_info, list);
1353 * If current frequency is 0, then the ondemand governor considers
1354 * there's no initial frequency set. And it always requests to set
1355 * to max. frequency.
1357 stat->current_frequency = clki->curr_freq;
1358 if (scaling->is_busy_started)
1359 scaling->tot_busy_t += ktime_us_delta(curr_t,
1360 scaling->busy_start_t);
1362 stat->total_time = ktime_us_delta(curr_t, scaling->window_start_t);
1363 stat->busy_time = scaling->tot_busy_t;
1365 scaling->window_start_t = curr_t;
1366 scaling->tot_busy_t = 0;
1368 if (hba->outstanding_reqs) {
1369 scaling->busy_start_t = curr_t;
1370 scaling->is_busy_started = true;
1372 scaling->busy_start_t = 0;
1373 scaling->is_busy_started = false;
1375 spin_unlock_irqrestore(hba->host->host_lock, flags);
1379 static int ufshcd_devfreq_init(struct ufs_hba *hba)
1381 struct list_head *clk_list = &hba->clk_list_head;
1382 struct ufs_clk_info *clki;
1383 struct devfreq *devfreq;
1386 /* Skip devfreq if we don't have any clocks in the list */
1387 if (list_empty(clk_list))
1390 clki = list_first_entry(clk_list, struct ufs_clk_info, list);
1391 dev_pm_opp_add(hba->dev, clki->min_freq, 0);
1392 dev_pm_opp_add(hba->dev, clki->max_freq, 0);
1394 ufshcd_vops_config_scaling_param(hba, &hba->vps->devfreq_profile,
1395 &hba->vps->ondemand_data);
1396 devfreq = devfreq_add_device(hba->dev,
1397 &hba->vps->devfreq_profile,
1398 DEVFREQ_GOV_SIMPLE_ONDEMAND,
1399 &hba->vps->ondemand_data);
1400 if (IS_ERR(devfreq)) {
1401 ret = PTR_ERR(devfreq);
1402 dev_err(hba->dev, "Unable to register with devfreq %d\n", ret);
1404 dev_pm_opp_remove(hba->dev, clki->min_freq);
1405 dev_pm_opp_remove(hba->dev, clki->max_freq);
1409 hba->devfreq = devfreq;
1414 static void ufshcd_devfreq_remove(struct ufs_hba *hba)
1416 struct list_head *clk_list = &hba->clk_list_head;
1417 struct ufs_clk_info *clki;
1422 devfreq_remove_device(hba->devfreq);
1423 hba->devfreq = NULL;
1425 clki = list_first_entry(clk_list, struct ufs_clk_info, list);
1426 dev_pm_opp_remove(hba->dev, clki->min_freq);
1427 dev_pm_opp_remove(hba->dev, clki->max_freq);
1430 static void __ufshcd_suspend_clkscaling(struct ufs_hba *hba)
1432 unsigned long flags;
1434 devfreq_suspend_device(hba->devfreq);
1435 spin_lock_irqsave(hba->host->host_lock, flags);
1436 hba->clk_scaling.window_start_t = 0;
1437 spin_unlock_irqrestore(hba->host->host_lock, flags);
1440 static void ufshcd_suspend_clkscaling(struct ufs_hba *hba)
1442 unsigned long flags;
1443 bool suspend = false;
1445 if (!ufshcd_is_clkscaling_supported(hba))
1448 spin_lock_irqsave(hba->host->host_lock, flags);
1449 if (!hba->clk_scaling.is_suspended) {
1451 hba->clk_scaling.is_suspended = true;
1453 spin_unlock_irqrestore(hba->host->host_lock, flags);
1456 __ufshcd_suspend_clkscaling(hba);
1459 static void ufshcd_resume_clkscaling(struct ufs_hba *hba)
1461 unsigned long flags;
1462 bool resume = false;
1464 if (!ufshcd_is_clkscaling_supported(hba))
1467 spin_lock_irqsave(hba->host->host_lock, flags);
1468 if (hba->clk_scaling.is_suspended) {
1470 hba->clk_scaling.is_suspended = false;
1472 spin_unlock_irqrestore(hba->host->host_lock, flags);
1475 devfreq_resume_device(hba->devfreq);
1478 static ssize_t ufshcd_clkscale_enable_show(struct device *dev,
1479 struct device_attribute *attr, char *buf)
1481 struct ufs_hba *hba = dev_get_drvdata(dev);
1483 return snprintf(buf, PAGE_SIZE, "%d\n", hba->clk_scaling.is_allowed);
1486 static ssize_t ufshcd_clkscale_enable_store(struct device *dev,
1487 struct device_attribute *attr, const char *buf, size_t count)
1489 struct ufs_hba *hba = dev_get_drvdata(dev);
1493 if (kstrtou32(buf, 0, &value))
1497 if (value == hba->clk_scaling.is_allowed)
1500 pm_runtime_get_sync(hba->dev);
1501 ufshcd_hold(hba, false);
1503 cancel_work_sync(&hba->clk_scaling.suspend_work);
1504 cancel_work_sync(&hba->clk_scaling.resume_work);
1506 hba->clk_scaling.is_allowed = value;
1509 ufshcd_resume_clkscaling(hba);
1511 ufshcd_suspend_clkscaling(hba);
1512 err = ufshcd_devfreq_scale(hba, true);
1514 dev_err(hba->dev, "%s: failed to scale clocks up %d\n",
1518 ufshcd_release(hba);
1519 pm_runtime_put_sync(hba->dev);
1524 static void ufshcd_clkscaling_init_sysfs(struct ufs_hba *hba)
1526 hba->clk_scaling.enable_attr.show = ufshcd_clkscale_enable_show;
1527 hba->clk_scaling.enable_attr.store = ufshcd_clkscale_enable_store;
1528 sysfs_attr_init(&hba->clk_scaling.enable_attr.attr);
1529 hba->clk_scaling.enable_attr.attr.name = "clkscale_enable";
1530 hba->clk_scaling.enable_attr.attr.mode = 0644;
1531 if (device_create_file(hba->dev, &hba->clk_scaling.enable_attr))
1532 dev_err(hba->dev, "Failed to create sysfs for clkscale_enable\n");
1535 static void ufshcd_ungate_work(struct work_struct *work)
1538 unsigned long flags;
1539 struct ufs_hba *hba = container_of(work, struct ufs_hba,
1540 clk_gating.ungate_work);
1542 cancel_delayed_work_sync(&hba->clk_gating.gate_work);
1544 spin_lock_irqsave(hba->host->host_lock, flags);
1545 if (hba->clk_gating.state == CLKS_ON) {
1546 spin_unlock_irqrestore(hba->host->host_lock, flags);
1550 spin_unlock_irqrestore(hba->host->host_lock, flags);
1551 ufshcd_setup_clocks(hba, true);
1553 ufshcd_enable_irq(hba);
1555 /* Exit from hibern8 */
1556 if (ufshcd_can_hibern8_during_gating(hba)) {
1557 /* Prevent gating in this path */
1558 hba->clk_gating.is_suspended = true;
1559 if (ufshcd_is_link_hibern8(hba)) {
1560 ret = ufshcd_uic_hibern8_exit(hba);
1562 dev_err(hba->dev, "%s: hibern8 exit failed %d\n",
1565 ufshcd_set_link_active(hba);
1567 hba->clk_gating.is_suspended = false;
1570 ufshcd_scsi_unblock_requests(hba);
1574 * ufshcd_hold - Enable clocks that were gated earlier due to ufshcd_release.
1575 * Also, exit from hibern8 mode and set the link as active.
1576 * @hba: per adapter instance
1577 * @async: This indicates whether caller should ungate clocks asynchronously.
1579 int ufshcd_hold(struct ufs_hba *hba, bool async)
1583 unsigned long flags;
1585 if (!ufshcd_is_clkgating_allowed(hba))
1587 spin_lock_irqsave(hba->host->host_lock, flags);
1588 hba->clk_gating.active_reqs++;
1591 switch (hba->clk_gating.state) {
1594 * Wait for the ungate work to complete if in progress.
1595 * Though the clocks may be in ON state, the link could
1596 * still be in hibner8 state if hibern8 is allowed
1597 * during clock gating.
1598 * Make sure we exit hibern8 state also in addition to
1601 if (ufshcd_can_hibern8_during_gating(hba) &&
1602 ufshcd_is_link_hibern8(hba)) {
1605 hba->clk_gating.active_reqs--;
1608 spin_unlock_irqrestore(hba->host->host_lock, flags);
1609 flush_result = flush_work(&hba->clk_gating.ungate_work);
1610 if (hba->clk_gating.is_suspended && !flush_result)
1612 spin_lock_irqsave(hba->host->host_lock, flags);
1617 if (cancel_delayed_work(&hba->clk_gating.gate_work)) {
1618 hba->clk_gating.state = CLKS_ON;
1619 trace_ufshcd_clk_gating(dev_name(hba->dev),
1620 hba->clk_gating.state);
1624 * If we are here, it means gating work is either done or
1625 * currently running. Hence, fall through to cancel gating
1626 * work and to enable clocks.
1630 hba->clk_gating.state = REQ_CLKS_ON;
1631 trace_ufshcd_clk_gating(dev_name(hba->dev),
1632 hba->clk_gating.state);
1633 if (queue_work(hba->clk_gating.clk_gating_workq,
1634 &hba->clk_gating.ungate_work))
1635 ufshcd_scsi_block_requests(hba);
1637 * fall through to check if we should wait for this
1638 * work to be done or not.
1644 hba->clk_gating.active_reqs--;
1648 spin_unlock_irqrestore(hba->host->host_lock, flags);
1649 flush_work(&hba->clk_gating.ungate_work);
1650 /* Make sure state is CLKS_ON before returning */
1651 spin_lock_irqsave(hba->host->host_lock, flags);
1654 dev_err(hba->dev, "%s: clk gating is in invalid state %d\n",
1655 __func__, hba->clk_gating.state);
1658 spin_unlock_irqrestore(hba->host->host_lock, flags);
1662 EXPORT_SYMBOL_GPL(ufshcd_hold);
1664 static void ufshcd_gate_work(struct work_struct *work)
1666 struct ufs_hba *hba = container_of(work, struct ufs_hba,
1667 clk_gating.gate_work.work);
1668 unsigned long flags;
1671 spin_lock_irqsave(hba->host->host_lock, flags);
1673 * In case you are here to cancel this work the gating state
1674 * would be marked as REQ_CLKS_ON. In this case save time by
1675 * skipping the gating work and exit after changing the clock
1678 if (hba->clk_gating.is_suspended ||
1679 (hba->clk_gating.state != REQ_CLKS_OFF)) {
1680 hba->clk_gating.state = CLKS_ON;
1681 trace_ufshcd_clk_gating(dev_name(hba->dev),
1682 hba->clk_gating.state);
1686 if (hba->clk_gating.active_reqs
1687 || hba->ufshcd_state != UFSHCD_STATE_OPERATIONAL
1688 || ufshcd_any_tag_in_use(hba) || hba->outstanding_tasks
1689 || hba->active_uic_cmd || hba->uic_async_done)
1692 spin_unlock_irqrestore(hba->host->host_lock, flags);
1694 /* put the link into hibern8 mode before turning off clocks */
1695 if (ufshcd_can_hibern8_during_gating(hba)) {
1696 ret = ufshcd_uic_hibern8_enter(hba);
1698 hba->clk_gating.state = CLKS_ON;
1699 dev_err(hba->dev, "%s: hibern8 enter failed %d\n",
1701 trace_ufshcd_clk_gating(dev_name(hba->dev),
1702 hba->clk_gating.state);
1705 ufshcd_set_link_hibern8(hba);
1708 ufshcd_disable_irq(hba);
1710 if (!ufshcd_is_link_active(hba))
1711 ufshcd_setup_clocks(hba, false);
1713 /* If link is active, device ref_clk can't be switched off */
1714 __ufshcd_setup_clocks(hba, false, true);
1717 * In case you are here to cancel this work the gating state
1718 * would be marked as REQ_CLKS_ON. In this case keep the state
1719 * as REQ_CLKS_ON which would anyway imply that clocks are off
1720 * and a request to turn them on is pending. By doing this way,
1721 * we keep the state machine in tact and this would ultimately
1722 * prevent from doing cancel work multiple times when there are
1723 * new requests arriving before the current cancel work is done.
1725 spin_lock_irqsave(hba->host->host_lock, flags);
1726 if (hba->clk_gating.state == REQ_CLKS_OFF) {
1727 hba->clk_gating.state = CLKS_OFF;
1728 trace_ufshcd_clk_gating(dev_name(hba->dev),
1729 hba->clk_gating.state);
1732 spin_unlock_irqrestore(hba->host->host_lock, flags);
1737 /* host lock must be held before calling this variant */
1738 static void __ufshcd_release(struct ufs_hba *hba)
1740 if (!ufshcd_is_clkgating_allowed(hba))
1743 hba->clk_gating.active_reqs--;
1745 if (hba->clk_gating.active_reqs || hba->clk_gating.is_suspended ||
1746 hba->ufshcd_state != UFSHCD_STATE_OPERATIONAL ||
1747 ufshcd_any_tag_in_use(hba) || hba->outstanding_tasks ||
1748 hba->active_uic_cmd || hba->uic_async_done)
1751 hba->clk_gating.state = REQ_CLKS_OFF;
1752 trace_ufshcd_clk_gating(dev_name(hba->dev), hba->clk_gating.state);
1753 queue_delayed_work(hba->clk_gating.clk_gating_workq,
1754 &hba->clk_gating.gate_work,
1755 msecs_to_jiffies(hba->clk_gating.delay_ms));
1758 void ufshcd_release(struct ufs_hba *hba)
1760 unsigned long flags;
1762 spin_lock_irqsave(hba->host->host_lock, flags);
1763 __ufshcd_release(hba);
1764 spin_unlock_irqrestore(hba->host->host_lock, flags);
1766 EXPORT_SYMBOL_GPL(ufshcd_release);
1768 static ssize_t ufshcd_clkgate_delay_show(struct device *dev,
1769 struct device_attribute *attr, char *buf)
1771 struct ufs_hba *hba = dev_get_drvdata(dev);
1773 return snprintf(buf, PAGE_SIZE, "%lu\n", hba->clk_gating.delay_ms);
1776 static ssize_t ufshcd_clkgate_delay_store(struct device *dev,
1777 struct device_attribute *attr, const char *buf, size_t count)
1779 struct ufs_hba *hba = dev_get_drvdata(dev);
1780 unsigned long flags, value;
1782 if (kstrtoul(buf, 0, &value))
1785 spin_lock_irqsave(hba->host->host_lock, flags);
1786 hba->clk_gating.delay_ms = value;
1787 spin_unlock_irqrestore(hba->host->host_lock, flags);
1791 static ssize_t ufshcd_clkgate_enable_show(struct device *dev,
1792 struct device_attribute *attr, char *buf)
1794 struct ufs_hba *hba = dev_get_drvdata(dev);
1796 return snprintf(buf, PAGE_SIZE, "%d\n", hba->clk_gating.is_enabled);
1799 static ssize_t ufshcd_clkgate_enable_store(struct device *dev,
1800 struct device_attribute *attr, const char *buf, size_t count)
1802 struct ufs_hba *hba = dev_get_drvdata(dev);
1803 unsigned long flags;
1806 if (kstrtou32(buf, 0, &value))
1810 if (value == hba->clk_gating.is_enabled)
1814 ufshcd_release(hba);
1816 spin_lock_irqsave(hba->host->host_lock, flags);
1817 hba->clk_gating.active_reqs++;
1818 spin_unlock_irqrestore(hba->host->host_lock, flags);
1821 hba->clk_gating.is_enabled = value;
1826 static void ufshcd_init_clk_scaling(struct ufs_hba *hba)
1828 char wq_name[sizeof("ufs_clkscaling_00")];
1830 if (!ufshcd_is_clkscaling_supported(hba))
1833 INIT_WORK(&hba->clk_scaling.suspend_work,
1834 ufshcd_clk_scaling_suspend_work);
1835 INIT_WORK(&hba->clk_scaling.resume_work,
1836 ufshcd_clk_scaling_resume_work);
1838 snprintf(wq_name, sizeof(wq_name), "ufs_clkscaling_%d",
1839 hba->host->host_no);
1840 hba->clk_scaling.workq = create_singlethread_workqueue(wq_name);
1842 ufshcd_clkscaling_init_sysfs(hba);
1845 static void ufshcd_exit_clk_scaling(struct ufs_hba *hba)
1847 if (!ufshcd_is_clkscaling_supported(hba))
1850 destroy_workqueue(hba->clk_scaling.workq);
1851 ufshcd_devfreq_remove(hba);
1854 static void ufshcd_init_clk_gating(struct ufs_hba *hba)
1856 char wq_name[sizeof("ufs_clk_gating_00")];
1858 if (!ufshcd_is_clkgating_allowed(hba))
1861 hba->clk_gating.state = CLKS_ON;
1863 hba->clk_gating.delay_ms = 150;
1864 INIT_DELAYED_WORK(&hba->clk_gating.gate_work, ufshcd_gate_work);
1865 INIT_WORK(&hba->clk_gating.ungate_work, ufshcd_ungate_work);
1867 snprintf(wq_name, ARRAY_SIZE(wq_name), "ufs_clk_gating_%d",
1868 hba->host->host_no);
1869 hba->clk_gating.clk_gating_workq = alloc_ordered_workqueue(wq_name,
1872 hba->clk_gating.is_enabled = true;
1874 hba->clk_gating.delay_attr.show = ufshcd_clkgate_delay_show;
1875 hba->clk_gating.delay_attr.store = ufshcd_clkgate_delay_store;
1876 sysfs_attr_init(&hba->clk_gating.delay_attr.attr);
1877 hba->clk_gating.delay_attr.attr.name = "clkgate_delay_ms";
1878 hba->clk_gating.delay_attr.attr.mode = 0644;
1879 if (device_create_file(hba->dev, &hba->clk_gating.delay_attr))
1880 dev_err(hba->dev, "Failed to create sysfs for clkgate_delay\n");
1882 hba->clk_gating.enable_attr.show = ufshcd_clkgate_enable_show;
1883 hba->clk_gating.enable_attr.store = ufshcd_clkgate_enable_store;
1884 sysfs_attr_init(&hba->clk_gating.enable_attr.attr);
1885 hba->clk_gating.enable_attr.attr.name = "clkgate_enable";
1886 hba->clk_gating.enable_attr.attr.mode = 0644;
1887 if (device_create_file(hba->dev, &hba->clk_gating.enable_attr))
1888 dev_err(hba->dev, "Failed to create sysfs for clkgate_enable\n");
1891 static void ufshcd_exit_clk_gating(struct ufs_hba *hba)
1893 if (!ufshcd_is_clkgating_allowed(hba))
1895 device_remove_file(hba->dev, &hba->clk_gating.delay_attr);
1896 device_remove_file(hba->dev, &hba->clk_gating.enable_attr);
1897 cancel_work_sync(&hba->clk_gating.ungate_work);
1898 cancel_delayed_work_sync(&hba->clk_gating.gate_work);
1899 destroy_workqueue(hba->clk_gating.clk_gating_workq);
1902 /* Must be called with host lock acquired */
1903 static void ufshcd_clk_scaling_start_busy(struct ufs_hba *hba)
1905 bool queue_resume_work = false;
1906 ktime_t curr_t = ktime_get();
1908 if (!ufshcd_is_clkscaling_supported(hba))
1911 if (!hba->clk_scaling.active_reqs++)
1912 queue_resume_work = true;
1914 if (!hba->clk_scaling.is_allowed || hba->pm_op_in_progress)
1917 if (queue_resume_work)
1918 queue_work(hba->clk_scaling.workq,
1919 &hba->clk_scaling.resume_work);
1921 if (!hba->clk_scaling.window_start_t) {
1922 hba->clk_scaling.window_start_t = curr_t;
1923 hba->clk_scaling.tot_busy_t = 0;
1924 hba->clk_scaling.is_busy_started = false;
1927 if (!hba->clk_scaling.is_busy_started) {
1928 hba->clk_scaling.busy_start_t = curr_t;
1929 hba->clk_scaling.is_busy_started = true;
1933 static void ufshcd_clk_scaling_update_busy(struct ufs_hba *hba)
1935 struct ufs_clk_scaling *scaling = &hba->clk_scaling;
1937 if (!ufshcd_is_clkscaling_supported(hba))
1940 if (!hba->outstanding_reqs && scaling->is_busy_started) {
1941 scaling->tot_busy_t += ktime_to_us(ktime_sub(ktime_get(),
1942 scaling->busy_start_t));
1943 scaling->busy_start_t = 0;
1944 scaling->is_busy_started = false;
1948 * ufshcd_send_command - Send SCSI or device management commands
1949 * @hba: per adapter instance
1950 * @task_tag: Task tag of the command
1953 void ufshcd_send_command(struct ufs_hba *hba, unsigned int task_tag)
1955 struct ufshcd_lrb *lrbp = &hba->lrb[task_tag];
1957 lrbp->issue_time_stamp = ktime_get();
1958 lrbp->compl_time_stamp = ktime_set(0, 0);
1959 ufshcd_vops_setup_xfer_req(hba, task_tag, (lrbp->cmd ? true : false));
1960 ufshcd_add_command_trace(hba, task_tag, "send");
1961 ufshcd_clk_scaling_start_busy(hba);
1962 __set_bit(task_tag, &hba->outstanding_reqs);
1963 ufshcd_writel(hba, 1 << task_tag, REG_UTP_TRANSFER_REQ_DOOR_BELL);
1964 /* Make sure that doorbell is committed immediately */
1969 * ufshcd_copy_sense_data - Copy sense data in case of check condition
1970 * @lrbp: pointer to local reference block
1972 static inline void ufshcd_copy_sense_data(struct ufshcd_lrb *lrbp)
1975 if (lrbp->sense_buffer &&
1976 ufshcd_get_rsp_upiu_data_seg_len(lrbp->ucd_rsp_ptr)) {
1979 len = be16_to_cpu(lrbp->ucd_rsp_ptr->sr.sense_data_len);
1980 len_to_copy = min_t(int, UFS_SENSE_SIZE, len);
1982 memcpy(lrbp->sense_buffer, lrbp->ucd_rsp_ptr->sr.sense_data,
1988 * ufshcd_copy_query_response() - Copy the Query Response and the data
1990 * @hba: per adapter instance
1991 * @lrbp: pointer to local reference block
1994 int ufshcd_copy_query_response(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
1996 struct ufs_query_res *query_res = &hba->dev_cmd.query.response;
1998 memcpy(&query_res->upiu_res, &lrbp->ucd_rsp_ptr->qr, QUERY_OSF_SIZE);
2000 /* Get the descriptor */
2001 if (hba->dev_cmd.query.descriptor &&
2002 lrbp->ucd_rsp_ptr->qr.opcode == UPIU_QUERY_OPCODE_READ_DESC) {
2003 u8 *descp = (u8 *)lrbp->ucd_rsp_ptr +
2004 GENERAL_UPIU_REQUEST_SIZE;
2008 /* data segment length */
2009 resp_len = be32_to_cpu(lrbp->ucd_rsp_ptr->header.dword_2) &
2010 MASK_QUERY_DATA_SEG_LEN;
2011 buf_len = be16_to_cpu(
2012 hba->dev_cmd.query.request.upiu_req.length);
2013 if (likely(buf_len >= resp_len)) {
2014 memcpy(hba->dev_cmd.query.descriptor, descp, resp_len);
2017 "%s: rsp size %d is bigger than buffer size %d",
2018 __func__, resp_len, buf_len);
2027 * ufshcd_hba_capabilities - Read controller capabilities
2028 * @hba: per adapter instance
2030 * Return: 0 on success, negative on error.
2032 static inline int ufshcd_hba_capabilities(struct ufs_hba *hba)
2036 hba->capabilities = ufshcd_readl(hba, REG_CONTROLLER_CAPABILITIES);
2038 /* nutrs and nutmrs are 0 based values */
2039 hba->nutrs = (hba->capabilities & MASK_TRANSFER_REQUESTS_SLOTS) + 1;
2041 ((hba->capabilities & MASK_TASK_MANAGEMENT_REQUEST_SLOTS) >> 16) + 1;
2043 /* Read crypto capabilities */
2044 err = ufshcd_hba_init_crypto_capabilities(hba);
2046 dev_err(hba->dev, "crypto setup failed\n");
2052 * ufshcd_ready_for_uic_cmd - Check if controller is ready
2053 * to accept UIC commands
2054 * @hba: per adapter instance
2055 * Return true on success, else false
2057 static inline bool ufshcd_ready_for_uic_cmd(struct ufs_hba *hba)
2059 if (ufshcd_readl(hba, REG_CONTROLLER_STATUS) & UIC_COMMAND_READY)
2066 * ufshcd_get_upmcrs - Get the power mode change request status
2067 * @hba: Pointer to adapter instance
2069 * This function gets the UPMCRS field of HCS register
2070 * Returns value of UPMCRS field
2072 static inline u8 ufshcd_get_upmcrs(struct ufs_hba *hba)
2074 return (ufshcd_readl(hba, REG_CONTROLLER_STATUS) >> 8) & 0x7;
2078 * ufshcd_dispatch_uic_cmd - Dispatch UIC commands to unipro layers
2079 * @hba: per adapter instance
2080 * @uic_cmd: UIC command
2082 * Mutex must be held.
2085 ufshcd_dispatch_uic_cmd(struct ufs_hba *hba, struct uic_command *uic_cmd)
2087 WARN_ON(hba->active_uic_cmd);
2089 hba->active_uic_cmd = uic_cmd;
2092 ufshcd_writel(hba, uic_cmd->argument1, REG_UIC_COMMAND_ARG_1);
2093 ufshcd_writel(hba, uic_cmd->argument2, REG_UIC_COMMAND_ARG_2);
2094 ufshcd_writel(hba, uic_cmd->argument3, REG_UIC_COMMAND_ARG_3);
2096 ufshcd_add_uic_command_trace(hba, uic_cmd, "send");
2099 ufshcd_writel(hba, uic_cmd->command & COMMAND_OPCODE_MASK,
2104 * ufshcd_wait_for_uic_cmd - Wait complectioin of UIC command
2105 * @hba: per adapter instance
2106 * @uic_cmd: UIC command
2108 * Must be called with mutex held.
2109 * Returns 0 only if success.
2112 ufshcd_wait_for_uic_cmd(struct ufs_hba *hba, struct uic_command *uic_cmd)
2115 unsigned long flags;
2117 if (wait_for_completion_timeout(&uic_cmd->done,
2118 msecs_to_jiffies(UIC_CMD_TIMEOUT))) {
2119 ret = uic_cmd->argument2 & MASK_UIC_COMMAND_RESULT;
2123 "uic cmd 0x%x with arg3 0x%x completion timeout\n",
2124 uic_cmd->command, uic_cmd->argument3);
2126 if (!uic_cmd->cmd_active) {
2127 dev_err(hba->dev, "%s: UIC cmd has been completed, return the result\n",
2129 ret = uic_cmd->argument2 & MASK_UIC_COMMAND_RESULT;
2133 spin_lock_irqsave(hba->host->host_lock, flags);
2134 hba->active_uic_cmd = NULL;
2135 spin_unlock_irqrestore(hba->host->host_lock, flags);
2141 * __ufshcd_send_uic_cmd - Send UIC commands and retrieve the result
2142 * @hba: per adapter instance
2143 * @uic_cmd: UIC command
2144 * @completion: initialize the completion only if this is set to true
2146 * Identical to ufshcd_send_uic_cmd() expect mutex. Must be called
2147 * with mutex held and host_lock locked.
2148 * Returns 0 only if success.
2151 __ufshcd_send_uic_cmd(struct ufs_hba *hba, struct uic_command *uic_cmd,
2154 if (!ufshcd_ready_for_uic_cmd(hba)) {
2156 "Controller not ready to accept UIC commands\n");
2161 init_completion(&uic_cmd->done);
2163 uic_cmd->cmd_active = 1;
2164 ufshcd_dispatch_uic_cmd(hba, uic_cmd);
2170 * ufshcd_send_uic_cmd - Send UIC commands and retrieve the result
2171 * @hba: per adapter instance
2172 * @uic_cmd: UIC command
2174 * Returns 0 only if success.
2176 int ufshcd_send_uic_cmd(struct ufs_hba *hba, struct uic_command *uic_cmd)
2179 unsigned long flags;
2181 ufshcd_hold(hba, false);
2182 mutex_lock(&hba->uic_cmd_mutex);
2183 ufshcd_add_delay_before_dme_cmd(hba);
2185 spin_lock_irqsave(hba->host->host_lock, flags);
2186 ret = __ufshcd_send_uic_cmd(hba, uic_cmd, true);
2187 spin_unlock_irqrestore(hba->host->host_lock, flags);
2189 ret = ufshcd_wait_for_uic_cmd(hba, uic_cmd);
2191 mutex_unlock(&hba->uic_cmd_mutex);
2193 ufshcd_release(hba);
2198 * ufshcd_map_sg - Map scatter-gather list to prdt
2199 * @hba: per adapter instance
2200 * @lrbp: pointer to local reference block
2202 * Returns 0 in case of success, non-zero value in case of failure
2204 static int ufshcd_map_sg(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
2206 struct ufshcd_sg_entry *prd_table;
2207 struct scatterlist *sg;
2208 struct scsi_cmnd *cmd;
2213 sg_segments = scsi_dma_map(cmd);
2214 if (sg_segments < 0)
2219 if (hba->quirks & UFSHCD_QUIRK_PRDT_BYTE_GRAN)
2220 lrbp->utr_descriptor_ptr->prd_table_length =
2221 cpu_to_le16((sg_segments *
2222 sizeof(struct ufshcd_sg_entry)));
2224 lrbp->utr_descriptor_ptr->prd_table_length =
2225 cpu_to_le16((u16) (sg_segments));
2227 prd_table = (struct ufshcd_sg_entry *)lrbp->ucd_prdt_ptr;
2229 scsi_for_each_sg(cmd, sg, sg_segments, i) {
2231 cpu_to_le32(((u32) sg_dma_len(sg))-1);
2232 prd_table[i].base_addr =
2233 cpu_to_le32(lower_32_bits(sg->dma_address));
2234 prd_table[i].upper_addr =
2235 cpu_to_le32(upper_32_bits(sg->dma_address));
2236 prd_table[i].reserved = 0;
2239 lrbp->utr_descriptor_ptr->prd_table_length = 0;
2246 * ufshcd_enable_intr - enable interrupts
2247 * @hba: per adapter instance
2248 * @intrs: interrupt bits
2250 static void ufshcd_enable_intr(struct ufs_hba *hba, u32 intrs)
2252 u32 set = ufshcd_readl(hba, REG_INTERRUPT_ENABLE);
2254 if (hba->ufs_version == UFSHCI_VERSION_10) {
2256 rw = set & INTERRUPT_MASK_RW_VER_10;
2257 set = rw | ((set ^ intrs) & intrs);
2262 ufshcd_writel(hba, set, REG_INTERRUPT_ENABLE);
2266 * ufshcd_disable_intr - disable interrupts
2267 * @hba: per adapter instance
2268 * @intrs: interrupt bits
2270 static void ufshcd_disable_intr(struct ufs_hba *hba, u32 intrs)
2272 u32 set = ufshcd_readl(hba, REG_INTERRUPT_ENABLE);
2274 if (hba->ufs_version == UFSHCI_VERSION_10) {
2276 rw = (set & INTERRUPT_MASK_RW_VER_10) &
2277 ~(intrs & INTERRUPT_MASK_RW_VER_10);
2278 set = rw | ((set & intrs) & ~INTERRUPT_MASK_RW_VER_10);
2284 ufshcd_writel(hba, set, REG_INTERRUPT_ENABLE);
2288 * ufshcd_prepare_req_desc_hdr() - Fills the requests header
2289 * descriptor according to request
2290 * @lrbp: pointer to local reference block
2291 * @upiu_flags: flags required in the header
2292 * @cmd_dir: requests data direction
2294 static void ufshcd_prepare_req_desc_hdr(struct ufshcd_lrb *lrbp,
2295 u8 *upiu_flags, enum dma_data_direction cmd_dir)
2297 struct utp_transfer_req_desc *req_desc = lrbp->utr_descriptor_ptr;
2303 if (cmd_dir == DMA_FROM_DEVICE) {
2304 data_direction = UTP_DEVICE_TO_HOST;
2305 *upiu_flags = UPIU_CMD_FLAGS_READ;
2306 } else if (cmd_dir == DMA_TO_DEVICE) {
2307 data_direction = UTP_HOST_TO_DEVICE;
2308 *upiu_flags = UPIU_CMD_FLAGS_WRITE;
2310 data_direction = UTP_NO_DATA_TRANSFER;
2311 *upiu_flags = UPIU_CMD_FLAGS_NONE;
2314 dword_0 = data_direction | (lrbp->command_type
2315 << UPIU_COMMAND_TYPE_OFFSET);
2317 dword_0 |= UTP_REQ_DESC_INT_CMD;
2319 /* Prepare crypto related dwords */
2320 ufshcd_prepare_req_desc_hdr_crypto(lrbp, &dword_0, &dword_1, &dword_3);
2322 /* Transfer request descriptor header fields */
2323 req_desc->header.dword_0 = cpu_to_le32(dword_0);
2324 req_desc->header.dword_1 = cpu_to_le32(dword_1);
2326 * assigning invalid value for command status. Controller
2327 * updates OCS on command completion, with the command
2330 req_desc->header.dword_2 =
2331 cpu_to_le32(OCS_INVALID_COMMAND_STATUS);
2332 req_desc->header.dword_3 = cpu_to_le32(dword_3);
2334 req_desc->prd_table_length = 0;
2338 * ufshcd_prepare_utp_scsi_cmd_upiu() - fills the utp_transfer_req_desc,
2340 * @lrbp: local reference block pointer
2341 * @upiu_flags: flags
2344 void ufshcd_prepare_utp_scsi_cmd_upiu(struct ufshcd_lrb *lrbp, u8 upiu_flags)
2346 struct scsi_cmnd *cmd = lrbp->cmd;
2347 struct utp_upiu_req *ucd_req_ptr = lrbp->ucd_req_ptr;
2348 unsigned short cdb_len;
2350 /* command descriptor fields */
2351 ucd_req_ptr->header.dword_0 = UPIU_HEADER_DWORD(
2352 UPIU_TRANSACTION_COMMAND, upiu_flags,
2353 lrbp->lun, lrbp->task_tag);
2354 ucd_req_ptr->header.dword_1 = UPIU_HEADER_DWORD(
2355 UPIU_COMMAND_SET_TYPE_SCSI, 0, 0, 0);
2357 /* Total EHS length and Data segment length will be zero */
2358 ucd_req_ptr->header.dword_2 = 0;
2360 ucd_req_ptr->sc.exp_data_transfer_len = cpu_to_be32(cmd->sdb.length);
2362 cdb_len = min_t(unsigned short, cmd->cmd_len, UFS_CDB_SIZE);
2363 memset(ucd_req_ptr->sc.cdb, 0, UFS_CDB_SIZE);
2364 memcpy(ucd_req_ptr->sc.cdb, cmd->cmnd, cdb_len);
2366 memset(lrbp->ucd_rsp_ptr, 0, sizeof(struct utp_upiu_rsp));
2370 * ufshcd_prepare_utp_query_req_upiu() - fills the utp_transfer_req_desc,
2373 * @lrbp: local reference block pointer
2374 * @upiu_flags: flags
2376 static void ufshcd_prepare_utp_query_req_upiu(struct ufs_hba *hba,
2377 struct ufshcd_lrb *lrbp, u8 upiu_flags)
2379 struct utp_upiu_req *ucd_req_ptr = lrbp->ucd_req_ptr;
2380 struct ufs_query *query = &hba->dev_cmd.query;
2381 u16 len = be16_to_cpu(query->request.upiu_req.length);
2383 /* Query request header */
2384 ucd_req_ptr->header.dword_0 = UPIU_HEADER_DWORD(
2385 UPIU_TRANSACTION_QUERY_REQ, upiu_flags,
2386 lrbp->lun, lrbp->task_tag);
2387 ucd_req_ptr->header.dword_1 = UPIU_HEADER_DWORD(
2388 0, query->request.query_func, 0, 0);
2390 /* Data segment length only need for WRITE_DESC */
2391 if (query->request.upiu_req.opcode == UPIU_QUERY_OPCODE_WRITE_DESC)
2392 ucd_req_ptr->header.dword_2 =
2393 UPIU_HEADER_DWORD(0, 0, (len >> 8), (u8)len);
2395 ucd_req_ptr->header.dword_2 = 0;
2397 /* Copy the Query Request buffer as is */
2398 memcpy(&ucd_req_ptr->qr, &query->request.upiu_req,
2401 /* Copy the Descriptor */
2402 if (query->request.upiu_req.opcode == UPIU_QUERY_OPCODE_WRITE_DESC)
2403 memcpy(ucd_req_ptr + 1, query->descriptor, len);
2405 memset(lrbp->ucd_rsp_ptr, 0, sizeof(struct utp_upiu_rsp));
2408 static inline void ufshcd_prepare_utp_nop_upiu(struct ufshcd_lrb *lrbp)
2410 struct utp_upiu_req *ucd_req_ptr = lrbp->ucd_req_ptr;
2412 memset(ucd_req_ptr, 0, sizeof(struct utp_upiu_req));
2414 /* command descriptor fields */
2415 ucd_req_ptr->header.dword_0 =
2417 UPIU_TRANSACTION_NOP_OUT, 0, 0, lrbp->task_tag);
2418 /* clear rest of the fields of basic header */
2419 ucd_req_ptr->header.dword_1 = 0;
2420 ucd_req_ptr->header.dword_2 = 0;
2422 memset(lrbp->ucd_rsp_ptr, 0, sizeof(struct utp_upiu_rsp));
2426 * ufshcd_compose_devman_upiu - UFS Protocol Information Unit(UPIU)
2427 * for Device Management Purposes
2428 * @hba: per adapter instance
2429 * @lrbp: pointer to local reference block
2431 static int ufshcd_compose_devman_upiu(struct ufs_hba *hba,
2432 struct ufshcd_lrb *lrbp)
2437 if ((hba->ufs_version == UFSHCI_VERSION_10) ||
2438 (hba->ufs_version == UFSHCI_VERSION_11))
2439 lrbp->command_type = UTP_CMD_TYPE_DEV_MANAGE;
2441 lrbp->command_type = UTP_CMD_TYPE_UFS_STORAGE;
2443 ufshcd_prepare_req_desc_hdr(lrbp, &upiu_flags, DMA_NONE);
2444 if (hba->dev_cmd.type == DEV_CMD_TYPE_QUERY)
2445 ufshcd_prepare_utp_query_req_upiu(hba, lrbp, upiu_flags);
2446 else if (hba->dev_cmd.type == DEV_CMD_TYPE_NOP)
2447 ufshcd_prepare_utp_nop_upiu(lrbp);
2455 * ufshcd_comp_scsi_upiu - UFS Protocol Information Unit(UPIU)
2457 * @hba: per adapter instance
2458 * @lrbp: pointer to local reference block
2460 static int ufshcd_comp_scsi_upiu(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
2465 if ((hba->ufs_version == UFSHCI_VERSION_10) ||
2466 (hba->ufs_version == UFSHCI_VERSION_11))
2467 lrbp->command_type = UTP_CMD_TYPE_SCSI;
2469 lrbp->command_type = UTP_CMD_TYPE_UFS_STORAGE;
2471 if (likely(lrbp->cmd)) {
2472 ufshcd_prepare_req_desc_hdr(lrbp, &upiu_flags,
2473 lrbp->cmd->sc_data_direction);
2474 ufshcd_prepare_utp_scsi_cmd_upiu(lrbp, upiu_flags);
2483 * ufshcd_upiu_wlun_to_scsi_wlun - maps UPIU W-LUN id to SCSI W-LUN ID
2484 * @upiu_wlun_id: UPIU W-LUN id
2486 * Returns SCSI W-LUN id
2488 static inline u16 ufshcd_upiu_wlun_to_scsi_wlun(u8 upiu_wlun_id)
2490 return (upiu_wlun_id & ~UFS_UPIU_WLUN_ID) | SCSI_W_LUN_BASE;
2493 static void ufshcd_init_lrb(struct ufs_hba *hba, struct ufshcd_lrb *lrb, int i)
2495 struct utp_transfer_cmd_desc *cmd_descp = hba->ucdl_base_addr;
2496 struct utp_transfer_req_desc *utrdlp = hba->utrdl_base_addr;
2497 dma_addr_t cmd_desc_element_addr = hba->ucdl_dma_addr +
2498 i * sizeof(struct utp_transfer_cmd_desc);
2499 u16 response_offset = offsetof(struct utp_transfer_cmd_desc,
2501 u16 prdt_offset = offsetof(struct utp_transfer_cmd_desc, prd_table);
2503 lrb->utr_descriptor_ptr = utrdlp + i;
2504 lrb->utrd_dma_addr = hba->utrdl_dma_addr +
2505 i * sizeof(struct utp_transfer_req_desc);
2506 lrb->ucd_req_ptr = (struct utp_upiu_req *)(cmd_descp + i);
2507 lrb->ucd_req_dma_addr = cmd_desc_element_addr;
2508 lrb->ucd_rsp_ptr = (struct utp_upiu_rsp *)cmd_descp[i].response_upiu;
2509 lrb->ucd_rsp_dma_addr = cmd_desc_element_addr + response_offset;
2510 lrb->ucd_prdt_ptr = (struct ufshcd_sg_entry *)cmd_descp[i].prd_table;
2511 lrb->ucd_prdt_dma_addr = cmd_desc_element_addr + prdt_offset;
2515 * ufshcd_queuecommand - main entry point for SCSI requests
2516 * @host: SCSI host pointer
2517 * @cmd: command from SCSI Midlayer
2519 * Returns 0 for success, non-zero in case of failure
2521 static int ufshcd_queuecommand(struct Scsi_Host *host, struct scsi_cmnd *cmd)
2523 struct ufshcd_lrb *lrbp;
2524 struct ufs_hba *hba;
2525 unsigned long flags;
2529 hba = shost_priv(host);
2531 tag = cmd->request->tag;
2532 if (!ufshcd_valid_tag(hba, tag)) {
2534 "%s: invalid command tag %d: cmd=0x%p, cmd->request=0x%p",
2535 __func__, tag, cmd, cmd->request);
2539 if (!down_read_trylock(&hba->clk_scaling_lock))
2540 return SCSI_MLQUEUE_HOST_BUSY;
2542 hba->req_abort_count = 0;
2544 err = ufshcd_hold(hba, true);
2546 err = SCSI_MLQUEUE_HOST_BUSY;
2549 WARN_ON(ufshcd_is_clkgating_allowed(hba) &&
2550 (hba->clk_gating.state != CLKS_ON));
2552 lrbp = &hba->lrb[tag];
2556 lrbp->sense_bufflen = UFS_SENSE_SIZE;
2557 lrbp->sense_buffer = cmd->sense_buffer;
2558 lrbp->task_tag = tag;
2559 lrbp->lun = ufshcd_scsi_to_upiu_lun(cmd->device->lun);
2560 lrbp->intr_cmd = !ufshcd_is_intr_aggr_allowed(hba) ? true : false;
2562 ufshcd_prepare_lrbp_crypto(cmd->request, lrbp);
2564 lrbp->req_abort_skip = false;
2566 ufshcd_comp_scsi_upiu(hba, lrbp);
2568 err = ufshcd_map_sg(hba, lrbp);
2571 ufshcd_release(hba);
2574 /* Make sure descriptors are ready before ringing the doorbell */
2577 spin_lock_irqsave(hba->host->host_lock, flags);
2578 switch (hba->ufshcd_state) {
2579 case UFSHCD_STATE_OPERATIONAL:
2580 case UFSHCD_STATE_EH_SCHEDULED_NON_FATAL:
2582 case UFSHCD_STATE_EH_SCHEDULED_FATAL:
2584 * pm_runtime_get_sync() is used at error handling preparation
2585 * stage. If a scsi cmd, e.g. the SSU cmd, is sent from hba's
2586 * PM ops, it can never be finished if we let SCSI layer keep
2587 * retrying it, which gets err handler stuck forever. Neither
2588 * can we let the scsi cmd pass through, because UFS is in bad
2589 * state, the scsi cmd may eventually time out, which will get
2590 * err handler blocked for too long. So, just fail the scsi cmd
2591 * sent from PM ops, err handler can recover PM error anyways.
2593 if (hba->pm_op_in_progress) {
2594 hba->force_reset = true;
2595 set_host_byte(cmd, DID_BAD_TARGET);
2599 case UFSHCD_STATE_RESET:
2600 err = SCSI_MLQUEUE_HOST_BUSY;
2602 case UFSHCD_STATE_ERROR:
2603 set_host_byte(cmd, DID_ERROR);
2606 dev_WARN_ONCE(hba->dev, 1, "%s: invalid state %d\n",
2607 __func__, hba->ufshcd_state);
2608 set_host_byte(cmd, DID_BAD_TARGET);
2611 ufshcd_send_command(hba, tag);
2612 spin_unlock_irqrestore(hba->host->host_lock, flags);
2616 scsi_dma_unmap(lrbp->cmd);
2618 spin_unlock_irqrestore(hba->host->host_lock, flags);
2619 ufshcd_release(hba);
2621 cmd->scsi_done(cmd);
2623 up_read(&hba->clk_scaling_lock);
2627 static int ufshcd_compose_dev_cmd(struct ufs_hba *hba,
2628 struct ufshcd_lrb *lrbp, enum dev_cmd_type cmd_type, int tag)
2631 lrbp->sense_bufflen = 0;
2632 lrbp->sense_buffer = NULL;
2633 lrbp->task_tag = tag;
2634 lrbp->lun = 0; /* device management cmd is not specific to any LUN */
2635 lrbp->intr_cmd = true; /* No interrupt aggregation */
2636 ufshcd_prepare_lrbp_crypto(NULL, lrbp);
2637 hba->dev_cmd.type = cmd_type;
2639 return ufshcd_compose_devman_upiu(hba, lrbp);
2643 ufshcd_clear_cmd(struct ufs_hba *hba, int tag)
2646 unsigned long flags;
2647 u32 mask = 1 << tag;
2649 /* clear outstanding transaction before retry */
2650 spin_lock_irqsave(hba->host->host_lock, flags);
2651 ufshcd_utrl_clear(hba, tag);
2652 spin_unlock_irqrestore(hba->host->host_lock, flags);
2655 * wait for for h/w to clear corresponding bit in door-bell.
2656 * max. wait is 1 sec.
2658 err = ufshcd_wait_for_register(hba,
2659 REG_UTP_TRANSFER_REQ_DOOR_BELL,
2660 mask, ~mask, 1000, 1000);
2666 ufshcd_check_query_response(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
2668 struct ufs_query_res *query_res = &hba->dev_cmd.query.response;
2670 /* Get the UPIU response */
2671 query_res->response = ufshcd_get_rsp_upiu_result(lrbp->ucd_rsp_ptr) >>
2672 UPIU_RSP_CODE_OFFSET;
2673 return query_res->response;
2677 * ufshcd_dev_cmd_completion() - handles device management command responses
2678 * @hba: per adapter instance
2679 * @lrbp: pointer to local reference block
2682 ufshcd_dev_cmd_completion(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
2687 hba->ufs_stats.last_hibern8_exit_tstamp = ktime_set(0, 0);
2688 resp = ufshcd_get_req_rsp(lrbp->ucd_rsp_ptr);
2691 case UPIU_TRANSACTION_NOP_IN:
2692 if (hba->dev_cmd.type != DEV_CMD_TYPE_NOP) {
2694 dev_err(hba->dev, "%s: unexpected response %x\n",
2698 case UPIU_TRANSACTION_QUERY_RSP:
2699 err = ufshcd_check_query_response(hba, lrbp);
2701 err = ufshcd_copy_query_response(hba, lrbp);
2703 case UPIU_TRANSACTION_REJECT_UPIU:
2704 /* TODO: handle Reject UPIU Response */
2706 dev_err(hba->dev, "%s: Reject UPIU not fully implemented\n",
2711 dev_err(hba->dev, "%s: Invalid device management cmd response: %x\n",
2719 static int ufshcd_wait_for_dev_cmd(struct ufs_hba *hba,
2720 struct ufshcd_lrb *lrbp, int max_timeout)
2723 unsigned long time_left;
2724 unsigned long flags;
2726 time_left = wait_for_completion_timeout(hba->dev_cmd.complete,
2727 msecs_to_jiffies(max_timeout));
2729 /* Make sure descriptors are ready before ringing the doorbell */
2731 spin_lock_irqsave(hba->host->host_lock, flags);
2732 hba->dev_cmd.complete = NULL;
2733 if (likely(time_left)) {
2734 err = ufshcd_get_tr_ocs(lrbp);
2736 err = ufshcd_dev_cmd_completion(hba, lrbp);
2738 spin_unlock_irqrestore(hba->host->host_lock, flags);
2742 dev_dbg(hba->dev, "%s: dev_cmd request timedout, tag %d\n",
2743 __func__, lrbp->task_tag);
2744 if (!ufshcd_clear_cmd(hba, lrbp->task_tag))
2745 /* successfully cleared the command, retry if needed */
2748 * in case of an error, after clearing the doorbell,
2749 * we also need to clear the outstanding_request
2752 ufshcd_outstanding_req_clear(hba, lrbp->task_tag);
2759 * ufshcd_exec_dev_cmd - API for sending device management requests
2761 * @cmd_type: specifies the type (NOP, Query...)
2762 * @timeout: time in seconds
2764 * NOTE: Since there is only one available tag for device management commands,
2765 * it is expected you hold the hba->dev_cmd.lock mutex.
2767 static int ufshcd_exec_dev_cmd(struct ufs_hba *hba,
2768 enum dev_cmd_type cmd_type, int timeout)
2770 struct request_queue *q = hba->cmd_queue;
2771 struct request *req;
2772 struct ufshcd_lrb *lrbp;
2775 struct completion wait;
2776 unsigned long flags;
2778 down_read(&hba->clk_scaling_lock);
2781 * Get free slot, sleep if slots are unavailable.
2782 * Even though we use wait_event() which sleeps indefinitely,
2783 * the maximum wait time is bounded by SCSI request timeout.
2785 req = blk_get_request(q, REQ_OP_DRV_OUT, 0);
2791 WARN_ON_ONCE(!ufshcd_valid_tag(hba, tag));
2793 init_completion(&wait);
2794 lrbp = &hba->lrb[tag];
2796 err = ufshcd_compose_dev_cmd(hba, lrbp, cmd_type, tag);
2800 hba->dev_cmd.complete = &wait;
2802 ufshcd_add_query_upiu_trace(hba, tag, "query_send");
2803 /* Make sure descriptors are ready before ringing the doorbell */
2805 spin_lock_irqsave(hba->host->host_lock, flags);
2806 ufshcd_send_command(hba, tag);
2807 spin_unlock_irqrestore(hba->host->host_lock, flags);
2809 err = ufshcd_wait_for_dev_cmd(hba, lrbp, timeout);
2811 ufshcd_add_query_upiu_trace(hba, tag,
2812 err ? "query_complete_err" : "query_complete");
2815 blk_put_request(req);
2817 up_read(&hba->clk_scaling_lock);
2822 * ufshcd_init_query() - init the query response and request parameters
2823 * @hba: per-adapter instance
2824 * @request: address of the request pointer to be initialized
2825 * @response: address of the response pointer to be initialized
2826 * @opcode: operation to perform
2827 * @idn: flag idn to access
2828 * @index: LU number to access
2829 * @selector: query/flag/descriptor further identification
2831 static inline void ufshcd_init_query(struct ufs_hba *hba,
2832 struct ufs_query_req **request, struct ufs_query_res **response,
2833 enum query_opcode opcode, u8 idn, u8 index, u8 selector)
2835 *request = &hba->dev_cmd.query.request;
2836 *response = &hba->dev_cmd.query.response;
2837 memset(*request, 0, sizeof(struct ufs_query_req));
2838 memset(*response, 0, sizeof(struct ufs_query_res));
2839 (*request)->upiu_req.opcode = opcode;
2840 (*request)->upiu_req.idn = idn;
2841 (*request)->upiu_req.index = index;
2842 (*request)->upiu_req.selector = selector;
2845 static int ufshcd_query_flag_retry(struct ufs_hba *hba,
2846 enum query_opcode opcode, enum flag_idn idn, u8 index, bool *flag_res)
2851 for (retries = 0; retries < QUERY_REQ_RETRIES; retries++) {
2852 ret = ufshcd_query_flag(hba, opcode, idn, index, flag_res);
2855 "%s: failed with error %d, retries %d\n",
2856 __func__, ret, retries);
2863 "%s: query attribute, opcode %d, idn %d, failed with error %d after %d retires\n",
2864 __func__, opcode, idn, ret, retries);
2869 * ufshcd_query_flag() - API function for sending flag query requests
2870 * @hba: per-adapter instance
2871 * @opcode: flag query to perform
2872 * @idn: flag idn to access
2873 * @index: flag index to access
2874 * @flag_res: the flag value after the query request completes
2876 * Returns 0 for success, non-zero in case of failure
2878 int ufshcd_query_flag(struct ufs_hba *hba, enum query_opcode opcode,
2879 enum flag_idn idn, u8 index, bool *flag_res)
2881 struct ufs_query_req *request = NULL;
2882 struct ufs_query_res *response = NULL;
2883 int err, selector = 0;
2884 int timeout = QUERY_REQ_TIMEOUT;
2888 ufshcd_hold(hba, false);
2889 mutex_lock(&hba->dev_cmd.lock);
2890 ufshcd_init_query(hba, &request, &response, opcode, idn, index,
2894 case UPIU_QUERY_OPCODE_SET_FLAG:
2895 case UPIU_QUERY_OPCODE_CLEAR_FLAG:
2896 case UPIU_QUERY_OPCODE_TOGGLE_FLAG:
2897 request->query_func = UPIU_QUERY_FUNC_STANDARD_WRITE_REQUEST;
2899 case UPIU_QUERY_OPCODE_READ_FLAG:
2900 request->query_func = UPIU_QUERY_FUNC_STANDARD_READ_REQUEST;
2902 /* No dummy reads */
2903 dev_err(hba->dev, "%s: Invalid argument for read request\n",
2911 "%s: Expected query flag opcode but got = %d\n",
2917 err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_QUERY, timeout);
2921 "%s: Sending flag query for idn %d failed, err = %d\n",
2922 __func__, idn, err);
2927 *flag_res = (be32_to_cpu(response->upiu_res.value) &
2928 MASK_QUERY_UPIU_FLAG_LOC) & 0x1;
2931 mutex_unlock(&hba->dev_cmd.lock);
2932 ufshcd_release(hba);
2937 * ufshcd_query_attr - API function for sending attribute requests
2938 * @hba: per-adapter instance
2939 * @opcode: attribute opcode
2940 * @idn: attribute idn to access
2941 * @index: index field
2942 * @selector: selector field
2943 * @attr_val: the attribute value after the query request completes
2945 * Returns 0 for success, non-zero in case of failure
2947 int ufshcd_query_attr(struct ufs_hba *hba, enum query_opcode opcode,
2948 enum attr_idn idn, u8 index, u8 selector, u32 *attr_val)
2950 struct ufs_query_req *request = NULL;
2951 struct ufs_query_res *response = NULL;
2956 ufshcd_hold(hba, false);
2958 dev_err(hba->dev, "%s: attribute value required for opcode 0x%x\n",
2964 mutex_lock(&hba->dev_cmd.lock);
2965 ufshcd_init_query(hba, &request, &response, opcode, idn, index,
2969 case UPIU_QUERY_OPCODE_WRITE_ATTR:
2970 request->query_func = UPIU_QUERY_FUNC_STANDARD_WRITE_REQUEST;
2971 request->upiu_req.value = cpu_to_be32(*attr_val);
2973 case UPIU_QUERY_OPCODE_READ_ATTR:
2974 request->query_func = UPIU_QUERY_FUNC_STANDARD_READ_REQUEST;
2977 dev_err(hba->dev, "%s: Expected query attr opcode but got = 0x%.2x\n",
2983 err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_QUERY, QUERY_REQ_TIMEOUT);
2986 dev_err(hba->dev, "%s: opcode 0x%.2x for idn %d failed, index %d, err = %d\n",
2987 __func__, opcode, idn, index, err);
2991 *attr_val = be32_to_cpu(response->upiu_res.value);
2994 mutex_unlock(&hba->dev_cmd.lock);
2996 ufshcd_release(hba);
3001 * ufshcd_query_attr_retry() - API function for sending query
3002 * attribute with retries
3003 * @hba: per-adapter instance
3004 * @opcode: attribute opcode
3005 * @idn: attribute idn to access
3006 * @index: index field
3007 * @selector: selector field
3008 * @attr_val: the attribute value after the query request
3011 * Returns 0 for success, non-zero in case of failure
3013 static int ufshcd_query_attr_retry(struct ufs_hba *hba,
3014 enum query_opcode opcode, enum attr_idn idn, u8 index, u8 selector,
3020 for (retries = QUERY_REQ_RETRIES; retries > 0; retries--) {
3021 ret = ufshcd_query_attr(hba, opcode, idn, index,
3022 selector, attr_val);
3024 dev_dbg(hba->dev, "%s: failed with error %d, retries %d\n",
3025 __func__, ret, retries);
3032 "%s: query attribute, idn %d, failed with error %d after %d retires\n",
3033 __func__, idn, ret, QUERY_REQ_RETRIES);
3037 static int __ufshcd_query_descriptor(struct ufs_hba *hba,
3038 enum query_opcode opcode, enum desc_idn idn, u8 index,
3039 u8 selector, u8 *desc_buf, int *buf_len)
3041 struct ufs_query_req *request = NULL;
3042 struct ufs_query_res *response = NULL;
3047 ufshcd_hold(hba, false);
3049 dev_err(hba->dev, "%s: descriptor buffer required for opcode 0x%x\n",
3055 if (*buf_len < QUERY_DESC_MIN_SIZE || *buf_len > QUERY_DESC_MAX_SIZE) {
3056 dev_err(hba->dev, "%s: descriptor buffer size (%d) is out of range\n",
3057 __func__, *buf_len);
3062 mutex_lock(&hba->dev_cmd.lock);
3063 ufshcd_init_query(hba, &request, &response, opcode, idn, index,
3065 hba->dev_cmd.query.descriptor = desc_buf;
3066 request->upiu_req.length = cpu_to_be16(*buf_len);
3069 case UPIU_QUERY_OPCODE_WRITE_DESC:
3070 request->query_func = UPIU_QUERY_FUNC_STANDARD_WRITE_REQUEST;
3072 case UPIU_QUERY_OPCODE_READ_DESC:
3073 request->query_func = UPIU_QUERY_FUNC_STANDARD_READ_REQUEST;
3077 "%s: Expected query descriptor opcode but got = 0x%.2x\n",
3083 err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_QUERY, QUERY_REQ_TIMEOUT);
3086 dev_err(hba->dev, "%s: opcode 0x%.2x for idn %d failed, index %d, err = %d\n",
3087 __func__, opcode, idn, index, err);
3091 *buf_len = be16_to_cpu(response->upiu_res.length);
3094 hba->dev_cmd.query.descriptor = NULL;
3095 mutex_unlock(&hba->dev_cmd.lock);
3097 ufshcd_release(hba);
3102 * ufshcd_query_descriptor_retry - API function for sending descriptor requests
3103 * @hba: per-adapter instance
3104 * @opcode: attribute opcode
3105 * @idn: attribute idn to access
3106 * @index: index field
3107 * @selector: selector field
3108 * @desc_buf: the buffer that contains the descriptor
3109 * @buf_len: length parameter passed to the device
3111 * Returns 0 for success, non-zero in case of failure.
3112 * The buf_len parameter will contain, on return, the length parameter
3113 * received on the response.
3115 int ufshcd_query_descriptor_retry(struct ufs_hba *hba,
3116 enum query_opcode opcode,
3117 enum desc_idn idn, u8 index,
3119 u8 *desc_buf, int *buf_len)
3124 for (retries = QUERY_REQ_RETRIES; retries > 0; retries--) {
3125 err = __ufshcd_query_descriptor(hba, opcode, idn, index,
3126 selector, desc_buf, buf_len);
3127 if (!err || err == -EINVAL)
3135 * ufshcd_map_desc_id_to_length - map descriptor IDN to its length
3136 * @hba: Pointer to adapter instance
3137 * @desc_id: descriptor idn value
3138 * @desc_len: mapped desc length (out)
3140 void ufshcd_map_desc_id_to_length(struct ufs_hba *hba, enum desc_idn desc_id,
3143 if (desc_id >= QUERY_DESC_IDN_MAX || desc_id == QUERY_DESC_IDN_RFU_0 ||
3144 desc_id == QUERY_DESC_IDN_RFU_1)
3147 *desc_len = hba->desc_size[desc_id];
3149 EXPORT_SYMBOL(ufshcd_map_desc_id_to_length);
3151 static void ufshcd_update_desc_length(struct ufs_hba *hba,
3152 enum desc_idn desc_id, int desc_index,
3153 unsigned char desc_len)
3155 if (hba->desc_size[desc_id] == QUERY_DESC_MAX_SIZE &&
3156 desc_id != QUERY_DESC_IDN_STRING && desc_index != UFS_RPMB_UNIT)
3157 /* For UFS 3.1, the normal unit descriptor is 10 bytes larger
3158 * than the RPMB unit, however, both descriptors share the same
3159 * desc_idn, to cover both unit descriptors with one length, we
3160 * choose the normal unit descriptor length by desc_index.
3162 hba->desc_size[desc_id] = desc_len;
3166 * ufshcd_read_desc_param - read the specified descriptor parameter
3167 * @hba: Pointer to adapter instance
3168 * @desc_id: descriptor idn value
3169 * @desc_index: descriptor index
3170 * @param_offset: offset of the parameter to read
3171 * @param_read_buf: pointer to buffer where parameter would be read
3172 * @param_size: sizeof(param_read_buf)
3174 * Return 0 in case of success, non-zero otherwise
3176 int ufshcd_read_desc_param(struct ufs_hba *hba,
3177 enum desc_idn desc_id,
3186 bool is_kmalloc = true;
3189 if (desc_id >= QUERY_DESC_IDN_MAX || !param_size)
3192 /* Get the length of descriptor */
3193 ufshcd_map_desc_id_to_length(hba, desc_id, &buff_len);
3195 dev_err(hba->dev, "%s: Failed to get desc length", __func__);
3199 /* Check whether we need temp memory */
3200 if (param_offset != 0 || param_size < buff_len) {
3201 desc_buf = kmalloc(buff_len, GFP_KERNEL);
3205 desc_buf = param_read_buf;
3209 /* Request for full descriptor */
3210 ret = ufshcd_query_descriptor_retry(hba, UPIU_QUERY_OPCODE_READ_DESC,
3211 desc_id, desc_index, 0,
3212 desc_buf, &buff_len);
3215 dev_err(hba->dev, "%s: Failed reading descriptor. desc_id %d, desc_index %d, param_offset %d, ret %d",
3216 __func__, desc_id, desc_index, param_offset, ret);
3221 if (desc_buf[QUERY_DESC_DESC_TYPE_OFFSET] != desc_id) {
3222 dev_err(hba->dev, "%s: invalid desc_id %d in descriptor header",
3223 __func__, desc_buf[QUERY_DESC_DESC_TYPE_OFFSET]);
3228 /* Update descriptor length */
3229 buff_len = desc_buf[QUERY_DESC_LENGTH_OFFSET];
3230 ufshcd_update_desc_length(hba, desc_id, desc_index, buff_len);
3232 /* Check wherher we will not copy more data, than available */
3233 if (is_kmalloc && (param_offset + param_size) > buff_len)
3234 param_size = buff_len - param_offset;
3237 memcpy(param_read_buf, &desc_buf[param_offset], param_size);
3245 * struct uc_string_id - unicode string
3247 * @len: size of this descriptor inclusive
3248 * @type: descriptor type
3249 * @uc: unicode string character
3251 struct uc_string_id {
3257 /* replace non-printable or non-ASCII characters with spaces */
3258 static inline char ufshcd_remove_non_printable(u8 ch)
3260 return (ch >= 0x20 && ch <= 0x7e) ? ch : ' ';
3264 * ufshcd_read_string_desc - read string descriptor
3265 * @hba: pointer to adapter instance
3266 * @desc_index: descriptor index
3267 * @buf: pointer to buffer where descriptor would be read,
3268 * the caller should free the memory.
3269 * @ascii: if true convert from unicode to ascii characters
3270 * null terminated string.
3273 * * string size on success.
3274 * * -ENOMEM: on allocation failure
3275 * * -EINVAL: on a wrong parameter
3277 int ufshcd_read_string_desc(struct ufs_hba *hba, u8 desc_index,
3278 u8 **buf, bool ascii)
3280 struct uc_string_id *uc_str;
3287 uc_str = kzalloc(QUERY_DESC_MAX_SIZE, GFP_KERNEL);
3291 ret = ufshcd_read_desc_param(hba, QUERY_DESC_IDN_STRING, desc_index, 0,
3292 (u8 *)uc_str, QUERY_DESC_MAX_SIZE);
3294 dev_err(hba->dev, "Reading String Desc failed after %d retries. err = %d\n",
3295 QUERY_REQ_RETRIES, ret);
3300 if (uc_str->len <= QUERY_DESC_HDR_SIZE) {
3301 dev_dbg(hba->dev, "String Desc is of zero length\n");
3310 /* remove header and divide by 2 to move from UTF16 to UTF8 */
3311 ascii_len = (uc_str->len - QUERY_DESC_HDR_SIZE) / 2 + 1;
3312 str = kzalloc(ascii_len, GFP_KERNEL);
3319 * the descriptor contains string in UTF16 format
3320 * we need to convert to utf-8 so it can be displayed
3322 ret = utf16s_to_utf8s(uc_str->uc,
3323 uc_str->len - QUERY_DESC_HDR_SIZE,
3324 UTF16_BIG_ENDIAN, str, ascii_len);
3326 /* replace non-printable or non-ASCII characters with spaces */
3327 for (i = 0; i < ret; i++)
3328 str[i] = ufshcd_remove_non_printable(str[i]);
3333 str = kmemdup(uc_str, uc_str->len, GFP_KERNEL);
3347 * ufshcd_read_unit_desc_param - read the specified unit descriptor parameter
3348 * @hba: Pointer to adapter instance
3350 * @param_offset: offset of the parameter to read
3351 * @param_read_buf: pointer to buffer where parameter would be read
3352 * @param_size: sizeof(param_read_buf)
3354 * Return 0 in case of success, non-zero otherwise
3356 static inline int ufshcd_read_unit_desc_param(struct ufs_hba *hba,
3358 enum unit_desc_param param_offset,
3363 * Unit descriptors are only available for general purpose LUs (LUN id
3364 * from 0 to 7) and RPMB Well known LU.
3366 if (!ufs_is_valid_unit_desc_lun(&hba->dev_info, lun))
3369 return ufshcd_read_desc_param(hba, QUERY_DESC_IDN_UNIT, lun,
3370 param_offset, param_read_buf, param_size);
3373 static int ufshcd_get_ref_clk_gating_wait(struct ufs_hba *hba)
3376 u32 gating_wait = UFSHCD_REF_CLK_GATING_WAIT_US;
3378 if (hba->dev_info.wspecversion >= 0x300) {
3379 err = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
3380 QUERY_ATTR_IDN_REF_CLK_GATING_WAIT_TIME, 0, 0,
3383 dev_err(hba->dev, "Failed reading bRefClkGatingWait. err = %d, use default %uus\n",
3386 if (gating_wait == 0) {
3387 gating_wait = UFSHCD_REF_CLK_GATING_WAIT_US;
3388 dev_err(hba->dev, "Undefined ref clk gating wait time, use default %uus\n",
3392 hba->dev_info.clk_gating_wait_us = gating_wait;
3399 * ufshcd_memory_alloc - allocate memory for host memory space data structures
3400 * @hba: per adapter instance
3402 * 1. Allocate DMA memory for Command Descriptor array
3403 * Each command descriptor consist of Command UPIU, Response UPIU and PRDT
3404 * 2. Allocate DMA memory for UTP Transfer Request Descriptor List (UTRDL).
3405 * 3. Allocate DMA memory for UTP Task Management Request Descriptor List
3407 * 4. Allocate memory for local reference block(lrb).
3409 * Returns 0 for success, non-zero in case of failure
3411 static int ufshcd_memory_alloc(struct ufs_hba *hba)
3413 size_t utmrdl_size, utrdl_size, ucdl_size;
3415 /* Allocate memory for UTP command descriptors */
3416 ucdl_size = (sizeof(struct utp_transfer_cmd_desc) * hba->nutrs);
3417 hba->ucdl_base_addr = dmam_alloc_coherent(hba->dev,
3419 &hba->ucdl_dma_addr,
3423 * UFSHCI requires UTP command descriptor to be 128 byte aligned.
3424 * make sure hba->ucdl_dma_addr is aligned to PAGE_SIZE
3425 * if hba->ucdl_dma_addr is aligned to PAGE_SIZE, then it will
3426 * be aligned to 128 bytes as well
3428 if (!hba->ucdl_base_addr ||
3429 WARN_ON(hba->ucdl_dma_addr & (PAGE_SIZE - 1))) {
3431 "Command Descriptor Memory allocation failed\n");
3436 * Allocate memory for UTP Transfer descriptors
3437 * UFSHCI requires 1024 byte alignment of UTRD
3439 utrdl_size = (sizeof(struct utp_transfer_req_desc) * hba->nutrs);
3440 hba->utrdl_base_addr = dmam_alloc_coherent(hba->dev,
3442 &hba->utrdl_dma_addr,
3444 if (!hba->utrdl_base_addr ||
3445 WARN_ON(hba->utrdl_dma_addr & (PAGE_SIZE - 1))) {
3447 "Transfer Descriptor Memory allocation failed\n");
3452 * Allocate memory for UTP Task Management descriptors
3453 * UFSHCI requires 1024 byte alignment of UTMRD
3455 utmrdl_size = sizeof(struct utp_task_req_desc) * hba->nutmrs;
3456 hba->utmrdl_base_addr = dmam_alloc_coherent(hba->dev,
3458 &hba->utmrdl_dma_addr,
3460 if (!hba->utmrdl_base_addr ||
3461 WARN_ON(hba->utmrdl_dma_addr & (PAGE_SIZE - 1))) {
3463 "Task Management Descriptor Memory allocation failed\n");
3467 /* Allocate memory for local reference block */
3468 hba->lrb = devm_kcalloc(hba->dev,
3469 hba->nutrs, sizeof(struct ufshcd_lrb),
3472 dev_err(hba->dev, "LRB Memory allocation failed\n");
3481 * ufshcd_host_memory_configure - configure local reference block with
3483 * @hba: per adapter instance
3485 * Configure Host memory space
3486 * 1. Update Corresponding UTRD.UCDBA and UTRD.UCDBAU with UCD DMA
3488 * 2. Update each UTRD with Response UPIU offset, Response UPIU length
3490 * 3. Save the corresponding addresses of UTRD, UCD.CMD, UCD.RSP and UCD.PRDT
3491 * into local reference block.
3493 static void ufshcd_host_memory_configure(struct ufs_hba *hba)
3495 struct utp_transfer_req_desc *utrdlp;
3496 dma_addr_t cmd_desc_dma_addr;
3497 dma_addr_t cmd_desc_element_addr;
3498 u16 response_offset;
3503 utrdlp = hba->utrdl_base_addr;
3506 offsetof(struct utp_transfer_cmd_desc, response_upiu);
3508 offsetof(struct utp_transfer_cmd_desc, prd_table);
3510 cmd_desc_size = sizeof(struct utp_transfer_cmd_desc);
3511 cmd_desc_dma_addr = hba->ucdl_dma_addr;
3513 for (i = 0; i < hba->nutrs; i++) {
3514 /* Configure UTRD with command descriptor base address */
3515 cmd_desc_element_addr =
3516 (cmd_desc_dma_addr + (cmd_desc_size * i));
3517 utrdlp[i].command_desc_base_addr_lo =
3518 cpu_to_le32(lower_32_bits(cmd_desc_element_addr));
3519 utrdlp[i].command_desc_base_addr_hi =
3520 cpu_to_le32(upper_32_bits(cmd_desc_element_addr));
3522 /* Response upiu and prdt offset should be in double words */
3523 if (hba->quirks & UFSHCD_QUIRK_PRDT_BYTE_GRAN) {
3524 utrdlp[i].response_upiu_offset =
3525 cpu_to_le16(response_offset);
3526 utrdlp[i].prd_table_offset =
3527 cpu_to_le16(prdt_offset);
3528 utrdlp[i].response_upiu_length =
3529 cpu_to_le16(ALIGNED_UPIU_SIZE);
3531 utrdlp[i].response_upiu_offset =
3532 cpu_to_le16(response_offset >> 2);
3533 utrdlp[i].prd_table_offset =
3534 cpu_to_le16(prdt_offset >> 2);
3535 utrdlp[i].response_upiu_length =
3536 cpu_to_le16(ALIGNED_UPIU_SIZE >> 2);
3539 ufshcd_init_lrb(hba, &hba->lrb[i], i);
3544 * ufshcd_dme_link_startup - Notify Unipro to perform link startup
3545 * @hba: per adapter instance
3547 * UIC_CMD_DME_LINK_STARTUP command must be issued to Unipro layer,
3548 * in order to initialize the Unipro link startup procedure.
3549 * Once the Unipro links are up, the device connected to the controller
3552 * Returns 0 on success, non-zero value on failure
3554 static int ufshcd_dme_link_startup(struct ufs_hba *hba)
3556 struct uic_command uic_cmd = {0};
3559 uic_cmd.command = UIC_CMD_DME_LINK_STARTUP;
3561 ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
3564 "dme-link-startup: error code %d\n", ret);
3568 * ufshcd_dme_reset - UIC command for DME_RESET
3569 * @hba: per adapter instance
3571 * DME_RESET command is issued in order to reset UniPro stack.
3572 * This function now deals with cold reset.
3574 * Returns 0 on success, non-zero value on failure
3576 static int ufshcd_dme_reset(struct ufs_hba *hba)
3578 struct uic_command uic_cmd = {0};
3581 uic_cmd.command = UIC_CMD_DME_RESET;
3583 ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
3586 "dme-reset: error code %d\n", ret);
3592 * ufshcd_dme_enable - UIC command for DME_ENABLE
3593 * @hba: per adapter instance
3595 * DME_ENABLE command is issued in order to enable UniPro stack.
3597 * Returns 0 on success, non-zero value on failure
3599 static int ufshcd_dme_enable(struct ufs_hba *hba)
3601 struct uic_command uic_cmd = {0};
3604 uic_cmd.command = UIC_CMD_DME_ENABLE;
3606 ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
3609 "dme-reset: error code %d\n", ret);
3614 static inline void ufshcd_add_delay_before_dme_cmd(struct ufs_hba *hba)
3616 #define MIN_DELAY_BEFORE_DME_CMDS_US 1000
3617 unsigned long min_sleep_time_us;
3619 if (!(hba->quirks & UFSHCD_QUIRK_DELAY_BEFORE_DME_CMDS))
3623 * last_dme_cmd_tstamp will be 0 only for 1st call to
3626 if (unlikely(!ktime_to_us(hba->last_dme_cmd_tstamp))) {
3627 min_sleep_time_us = MIN_DELAY_BEFORE_DME_CMDS_US;
3629 unsigned long delta =
3630 (unsigned long) ktime_to_us(
3631 ktime_sub(ktime_get(),
3632 hba->last_dme_cmd_tstamp));
3634 if (delta < MIN_DELAY_BEFORE_DME_CMDS_US)
3636 MIN_DELAY_BEFORE_DME_CMDS_US - delta;
3638 return; /* no more delay required */
3641 /* allow sleep for extra 50us if needed */
3642 usleep_range(min_sleep_time_us, min_sleep_time_us + 50);
3646 * ufshcd_dme_set_attr - UIC command for DME_SET, DME_PEER_SET
3647 * @hba: per adapter instance
3648 * @attr_sel: uic command argument1
3649 * @attr_set: attribute set type as uic command argument2
3650 * @mib_val: setting value as uic command argument3
3651 * @peer: indicate whether peer or local
3653 * Returns 0 on success, non-zero value on failure
3655 int ufshcd_dme_set_attr(struct ufs_hba *hba, u32 attr_sel,
3656 u8 attr_set, u32 mib_val, u8 peer)
3658 struct uic_command uic_cmd = {0};
3659 static const char *const action[] = {
3663 const char *set = action[!!peer];
3665 int retries = UFS_UIC_COMMAND_RETRIES;
3667 uic_cmd.command = peer ?
3668 UIC_CMD_DME_PEER_SET : UIC_CMD_DME_SET;
3669 uic_cmd.argument1 = attr_sel;
3670 uic_cmd.argument2 = UIC_ARG_ATTR_TYPE(attr_set);
3671 uic_cmd.argument3 = mib_val;
3674 /* for peer attributes we retry upon failure */
3675 ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
3677 dev_dbg(hba->dev, "%s: attr-id 0x%x val 0x%x error code %d\n",
3678 set, UIC_GET_ATTR_ID(attr_sel), mib_val, ret);
3679 } while (ret && peer && --retries);
3682 dev_err(hba->dev, "%s: attr-id 0x%x val 0x%x failed %d retries\n",
3683 set, UIC_GET_ATTR_ID(attr_sel), mib_val,
3684 UFS_UIC_COMMAND_RETRIES - retries);
3688 EXPORT_SYMBOL_GPL(ufshcd_dme_set_attr);
3691 * ufshcd_dme_get_attr - UIC command for DME_GET, DME_PEER_GET
3692 * @hba: per adapter instance
3693 * @attr_sel: uic command argument1
3694 * @mib_val: the value of the attribute as returned by the UIC command
3695 * @peer: indicate whether peer or local
3697 * Returns 0 on success, non-zero value on failure
3699 int ufshcd_dme_get_attr(struct ufs_hba *hba, u32 attr_sel,
3700 u32 *mib_val, u8 peer)
3702 struct uic_command uic_cmd = {0};
3703 static const char *const action[] = {
3707 const char *get = action[!!peer];
3709 int retries = UFS_UIC_COMMAND_RETRIES;
3710 struct ufs_pa_layer_attr orig_pwr_info;
3711 struct ufs_pa_layer_attr temp_pwr_info;
3712 bool pwr_mode_change = false;
3714 if (peer && (hba->quirks & UFSHCD_QUIRK_DME_PEER_ACCESS_AUTO_MODE)) {
3715 orig_pwr_info = hba->pwr_info;
3716 temp_pwr_info = orig_pwr_info;
3718 if (orig_pwr_info.pwr_tx == FAST_MODE ||
3719 orig_pwr_info.pwr_rx == FAST_MODE) {
3720 temp_pwr_info.pwr_tx = FASTAUTO_MODE;
3721 temp_pwr_info.pwr_rx = FASTAUTO_MODE;
3722 pwr_mode_change = true;
3723 } else if (orig_pwr_info.pwr_tx == SLOW_MODE ||
3724 orig_pwr_info.pwr_rx == SLOW_MODE) {
3725 temp_pwr_info.pwr_tx = SLOWAUTO_MODE;
3726 temp_pwr_info.pwr_rx = SLOWAUTO_MODE;
3727 pwr_mode_change = true;
3729 if (pwr_mode_change) {
3730 ret = ufshcd_change_power_mode(hba, &temp_pwr_info);
3736 uic_cmd.command = peer ?
3737 UIC_CMD_DME_PEER_GET : UIC_CMD_DME_GET;
3738 uic_cmd.argument1 = attr_sel;
3741 /* for peer attributes we retry upon failure */
3742 ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
3744 dev_dbg(hba->dev, "%s: attr-id 0x%x error code %d\n",
3745 get, UIC_GET_ATTR_ID(attr_sel), ret);
3746 } while (ret && peer && --retries);
3749 dev_err(hba->dev, "%s: attr-id 0x%x failed %d retries\n",
3750 get, UIC_GET_ATTR_ID(attr_sel),
3751 UFS_UIC_COMMAND_RETRIES - retries);
3753 if (mib_val && !ret)
3754 *mib_val = uic_cmd.argument3;
3756 if (peer && (hba->quirks & UFSHCD_QUIRK_DME_PEER_ACCESS_AUTO_MODE)
3758 ufshcd_change_power_mode(hba, &orig_pwr_info);
3762 EXPORT_SYMBOL_GPL(ufshcd_dme_get_attr);
3765 * ufshcd_uic_pwr_ctrl - executes UIC commands (which affects the link power
3766 * state) and waits for it to take effect.
3768 * @hba: per adapter instance
3769 * @cmd: UIC command to execute
3771 * DME operations like DME_SET(PA_PWRMODE), DME_HIBERNATE_ENTER &
3772 * DME_HIBERNATE_EXIT commands take some time to take its effect on both host
3773 * and device UniPro link and hence it's final completion would be indicated by
3774 * dedicated status bits in Interrupt Status register (UPMS, UHES, UHXS) in
3775 * addition to normal UIC command completion Status (UCCS). This function only
3776 * returns after the relevant status bits indicate the completion.
3778 * Returns 0 on success, non-zero value on failure
3780 static int ufshcd_uic_pwr_ctrl(struct ufs_hba *hba, struct uic_command *cmd)
3782 struct completion uic_async_done;
3783 unsigned long flags;
3786 bool reenable_intr = false;
3788 mutex_lock(&hba->uic_cmd_mutex);
3789 init_completion(&uic_async_done);
3790 ufshcd_add_delay_before_dme_cmd(hba);
3792 spin_lock_irqsave(hba->host->host_lock, flags);
3793 if (ufshcd_is_link_broken(hba)) {
3797 hba->uic_async_done = &uic_async_done;
3798 if (ufshcd_readl(hba, REG_INTERRUPT_ENABLE) & UIC_COMMAND_COMPL) {
3799 ufshcd_disable_intr(hba, UIC_COMMAND_COMPL);
3801 * Make sure UIC command completion interrupt is disabled before
3802 * issuing UIC command.
3805 reenable_intr = true;
3807 ret = __ufshcd_send_uic_cmd(hba, cmd, false);
3808 spin_unlock_irqrestore(hba->host->host_lock, flags);
3811 "pwr ctrl cmd 0x%x with mode 0x%x uic error %d\n",
3812 cmd->command, cmd->argument3, ret);
3816 if (!wait_for_completion_timeout(hba->uic_async_done,
3817 msecs_to_jiffies(UIC_CMD_TIMEOUT))) {
3819 "pwr ctrl cmd 0x%x with mode 0x%x completion timeout\n",
3820 cmd->command, cmd->argument3);
3822 if (!cmd->cmd_active) {
3823 dev_err(hba->dev, "%s: Power Mode Change operation has been completed, go check UPMCRS\n",
3833 status = ufshcd_get_upmcrs(hba);
3834 if (status != PWR_LOCAL) {
3836 "pwr ctrl cmd 0x%x failed, host upmcrs:0x%x\n",
3837 cmd->command, status);
3838 ret = (status != PWR_OK) ? status : -1;
3842 ufshcd_print_host_state(hba);
3843 ufshcd_print_pwr_info(hba);
3844 ufshcd_print_host_regs(hba);
3847 spin_lock_irqsave(hba->host->host_lock, flags);
3848 hba->active_uic_cmd = NULL;
3849 hba->uic_async_done = NULL;
3851 ufshcd_enable_intr(hba, UIC_COMMAND_COMPL);
3853 ufshcd_set_link_broken(hba);
3854 ufshcd_schedule_eh_work(hba);
3857 spin_unlock_irqrestore(hba->host->host_lock, flags);
3858 mutex_unlock(&hba->uic_cmd_mutex);
3864 * ufshcd_uic_change_pwr_mode - Perform the UIC power mode chage
3865 * using DME_SET primitives.
3866 * @hba: per adapter instance
3867 * @mode: powr mode value
3869 * Returns 0 on success, non-zero value on failure
3871 static int ufshcd_uic_change_pwr_mode(struct ufs_hba *hba, u8 mode)
3873 struct uic_command uic_cmd = {0};
3876 if (hba->quirks & UFSHCD_QUIRK_BROKEN_PA_RXHSUNTERMCAP) {
3877 ret = ufshcd_dme_set(hba,
3878 UIC_ARG_MIB_SEL(PA_RXHSUNTERMCAP, 0), 1);
3880 dev_err(hba->dev, "%s: failed to enable PA_RXHSUNTERMCAP ret %d\n",
3886 uic_cmd.command = UIC_CMD_DME_SET;
3887 uic_cmd.argument1 = UIC_ARG_MIB(PA_PWRMODE);
3888 uic_cmd.argument3 = mode;
3889 ufshcd_hold(hba, false);
3890 ret = ufshcd_uic_pwr_ctrl(hba, &uic_cmd);
3891 ufshcd_release(hba);
3897 int ufshcd_link_recovery(struct ufs_hba *hba)
3900 unsigned long flags;
3902 spin_lock_irqsave(hba->host->host_lock, flags);
3903 hba->ufshcd_state = UFSHCD_STATE_RESET;
3904 ufshcd_set_eh_in_progress(hba);
3905 spin_unlock_irqrestore(hba->host->host_lock, flags);
3907 /* Reset the attached device */
3908 ufshcd_vops_device_reset(hba);
3910 ret = ufshcd_host_reset_and_restore(hba);
3912 spin_lock_irqsave(hba->host->host_lock, flags);
3914 hba->ufshcd_state = UFSHCD_STATE_ERROR;
3915 ufshcd_clear_eh_in_progress(hba);
3916 spin_unlock_irqrestore(hba->host->host_lock, flags);
3919 dev_err(hba->dev, "%s: link recovery failed, err %d",
3924 EXPORT_SYMBOL_GPL(ufshcd_link_recovery);
3926 static int ufshcd_uic_hibern8_enter(struct ufs_hba *hba)
3929 struct uic_command uic_cmd = {0};
3930 ktime_t start = ktime_get();
3932 ufshcd_vops_hibern8_notify(hba, UIC_CMD_DME_HIBER_ENTER, PRE_CHANGE);
3934 uic_cmd.command = UIC_CMD_DME_HIBER_ENTER;
3935 ret = ufshcd_uic_pwr_ctrl(hba, &uic_cmd);
3936 trace_ufshcd_profile_hibern8(dev_name(hba->dev), "enter",
3937 ktime_to_us(ktime_sub(ktime_get(), start)), ret);
3940 dev_err(hba->dev, "%s: hibern8 enter failed. ret = %d\n",
3943 ufshcd_vops_hibern8_notify(hba, UIC_CMD_DME_HIBER_ENTER,
3949 int ufshcd_uic_hibern8_exit(struct ufs_hba *hba)
3951 struct uic_command uic_cmd = {0};
3953 ktime_t start = ktime_get();
3955 ufshcd_vops_hibern8_notify(hba, UIC_CMD_DME_HIBER_EXIT, PRE_CHANGE);
3957 uic_cmd.command = UIC_CMD_DME_HIBER_EXIT;
3958 ret = ufshcd_uic_pwr_ctrl(hba, &uic_cmd);
3959 trace_ufshcd_profile_hibern8(dev_name(hba->dev), "exit",
3960 ktime_to_us(ktime_sub(ktime_get(), start)), ret);
3963 dev_err(hba->dev, "%s: hibern8 exit failed. ret = %d\n",
3966 ufshcd_vops_hibern8_notify(hba, UIC_CMD_DME_HIBER_EXIT,
3968 hba->ufs_stats.last_hibern8_exit_tstamp = ktime_get();
3969 hba->ufs_stats.hibern8_exit_cnt++;
3974 EXPORT_SYMBOL_GPL(ufshcd_uic_hibern8_exit);
3976 void ufshcd_auto_hibern8_update(struct ufs_hba *hba, u32 ahit)
3978 unsigned long flags;
3979 bool update = false;
3981 if (!ufshcd_is_auto_hibern8_supported(hba))
3984 spin_lock_irqsave(hba->host->host_lock, flags);
3985 if (hba->ahit != ahit) {
3989 spin_unlock_irqrestore(hba->host->host_lock, flags);
3991 if (update && !pm_runtime_suspended(hba->dev)) {
3992 pm_runtime_get_sync(hba->dev);
3993 ufshcd_hold(hba, false);
3994 ufshcd_auto_hibern8_enable(hba);
3995 ufshcd_release(hba);
3996 pm_runtime_put(hba->dev);
3999 EXPORT_SYMBOL_GPL(ufshcd_auto_hibern8_update);
4001 void ufshcd_auto_hibern8_enable(struct ufs_hba *hba)
4003 unsigned long flags;
4005 if (!ufshcd_is_auto_hibern8_supported(hba))
4008 spin_lock_irqsave(hba->host->host_lock, flags);
4009 ufshcd_writel(hba, hba->ahit, REG_AUTO_HIBERNATE_IDLE_TIMER);
4010 spin_unlock_irqrestore(hba->host->host_lock, flags);
4014 * ufshcd_init_pwr_info - setting the POR (power on reset)
4015 * values in hba power info
4016 * @hba: per-adapter instance
4018 static void ufshcd_init_pwr_info(struct ufs_hba *hba)
4020 hba->pwr_info.gear_rx = UFS_PWM_G1;
4021 hba->pwr_info.gear_tx = UFS_PWM_G1;
4022 hba->pwr_info.lane_rx = 1;
4023 hba->pwr_info.lane_tx = 1;
4024 hba->pwr_info.pwr_rx = SLOWAUTO_MODE;
4025 hba->pwr_info.pwr_tx = SLOWAUTO_MODE;
4026 hba->pwr_info.hs_rate = 0;
4030 * ufshcd_get_max_pwr_mode - reads the max power mode negotiated with device
4031 * @hba: per-adapter instance
4033 static int ufshcd_get_max_pwr_mode(struct ufs_hba *hba)
4035 struct ufs_pa_layer_attr *pwr_info = &hba->max_pwr_info.info;
4037 if (hba->max_pwr_info.is_valid)
4040 pwr_info->pwr_tx = FAST_MODE;
4041 pwr_info->pwr_rx = FAST_MODE;
4042 pwr_info->hs_rate = PA_HS_MODE_B;
4044 /* Get the connected lane count */
4045 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_CONNECTEDRXDATALANES),
4046 &pwr_info->lane_rx);
4047 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_CONNECTEDTXDATALANES),
4048 &pwr_info->lane_tx);
4050 if (!pwr_info->lane_rx || !pwr_info->lane_tx) {
4051 dev_err(hba->dev, "%s: invalid connected lanes value. rx=%d, tx=%d\n",
4059 * First, get the maximum gears of HS speed.
4060 * If a zero value, it means there is no HSGEAR capability.
4061 * Then, get the maximum gears of PWM speed.
4063 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_MAXRXHSGEAR), &pwr_info->gear_rx);
4064 if (!pwr_info->gear_rx) {
4065 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_MAXRXPWMGEAR),
4066 &pwr_info->gear_rx);
4067 if (!pwr_info->gear_rx) {
4068 dev_err(hba->dev, "%s: invalid max pwm rx gear read = %d\n",
4069 __func__, pwr_info->gear_rx);
4072 pwr_info->pwr_rx = SLOW_MODE;
4075 ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_MAXRXHSGEAR),
4076 &pwr_info->gear_tx);
4077 if (!pwr_info->gear_tx) {
4078 ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_MAXRXPWMGEAR),
4079 &pwr_info->gear_tx);
4080 if (!pwr_info->gear_tx) {
4081 dev_err(hba->dev, "%s: invalid max pwm tx gear read = %d\n",
4082 __func__, pwr_info->gear_tx);
4085 pwr_info->pwr_tx = SLOW_MODE;
4088 hba->max_pwr_info.is_valid = true;
4092 static int ufshcd_change_power_mode(struct ufs_hba *hba,
4093 struct ufs_pa_layer_attr *pwr_mode)
4097 /* if already configured to the requested pwr_mode */
4098 if (!hba->force_pmc &&
4099 pwr_mode->gear_rx == hba->pwr_info.gear_rx &&
4100 pwr_mode->gear_tx == hba->pwr_info.gear_tx &&
4101 pwr_mode->lane_rx == hba->pwr_info.lane_rx &&
4102 pwr_mode->lane_tx == hba->pwr_info.lane_tx &&
4103 pwr_mode->pwr_rx == hba->pwr_info.pwr_rx &&
4104 pwr_mode->pwr_tx == hba->pwr_info.pwr_tx &&
4105 pwr_mode->hs_rate == hba->pwr_info.hs_rate) {
4106 dev_dbg(hba->dev, "%s: power already configured\n", __func__);
4111 * Configure attributes for power mode change with below.
4112 * - PA_RXGEAR, PA_ACTIVERXDATALANES, PA_RXTERMINATION,
4113 * - PA_TXGEAR, PA_ACTIVETXDATALANES, PA_TXTERMINATION,
4116 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_RXGEAR), pwr_mode->gear_rx);
4117 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_ACTIVERXDATALANES),
4119 if (pwr_mode->pwr_rx == FASTAUTO_MODE ||
4120 pwr_mode->pwr_rx == FAST_MODE)
4121 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_RXTERMINATION), TRUE);
4123 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_RXTERMINATION), FALSE);
4125 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TXGEAR), pwr_mode->gear_tx);
4126 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_ACTIVETXDATALANES),
4128 if (pwr_mode->pwr_tx == FASTAUTO_MODE ||
4129 pwr_mode->pwr_tx == FAST_MODE)
4130 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TXTERMINATION), TRUE);
4132 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TXTERMINATION), FALSE);
4134 if (pwr_mode->pwr_rx == FASTAUTO_MODE ||
4135 pwr_mode->pwr_tx == FASTAUTO_MODE ||
4136 pwr_mode->pwr_rx == FAST_MODE ||
4137 pwr_mode->pwr_tx == FAST_MODE)
4138 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_HSSERIES),
4141 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_PWRMODEUSERDATA0),
4142 DL_FC0ProtectionTimeOutVal_Default);
4143 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_PWRMODEUSERDATA1),
4144 DL_TC0ReplayTimeOutVal_Default);
4145 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_PWRMODEUSERDATA2),
4146 DL_AFC0ReqTimeOutVal_Default);
4147 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_PWRMODEUSERDATA3),
4148 DL_FC1ProtectionTimeOutVal_Default);
4149 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_PWRMODEUSERDATA4),
4150 DL_TC1ReplayTimeOutVal_Default);
4151 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_PWRMODEUSERDATA5),
4152 DL_AFC1ReqTimeOutVal_Default);
4154 ufshcd_dme_set(hba, UIC_ARG_MIB(DME_LocalFC0ProtectionTimeOutVal),
4155 DL_FC0ProtectionTimeOutVal_Default);
4156 ufshcd_dme_set(hba, UIC_ARG_MIB(DME_LocalTC0ReplayTimeOutVal),
4157 DL_TC0ReplayTimeOutVal_Default);
4158 ufshcd_dme_set(hba, UIC_ARG_MIB(DME_LocalAFC0ReqTimeOutVal),
4159 DL_AFC0ReqTimeOutVal_Default);
4161 ret = ufshcd_uic_change_pwr_mode(hba, pwr_mode->pwr_rx << 4
4162 | pwr_mode->pwr_tx);
4166 "%s: power mode change failed %d\n", __func__, ret);
4168 ufshcd_vops_pwr_change_notify(hba, POST_CHANGE, NULL,
4171 memcpy(&hba->pwr_info, pwr_mode,
4172 sizeof(struct ufs_pa_layer_attr));
4179 * ufshcd_config_pwr_mode - configure a new power mode
4180 * @hba: per-adapter instance
4181 * @desired_pwr_mode: desired power configuration
4183 int ufshcd_config_pwr_mode(struct ufs_hba *hba,
4184 struct ufs_pa_layer_attr *desired_pwr_mode)
4186 struct ufs_pa_layer_attr final_params = { 0 };
4189 ret = ufshcd_vops_pwr_change_notify(hba, PRE_CHANGE,
4190 desired_pwr_mode, &final_params);
4193 memcpy(&final_params, desired_pwr_mode, sizeof(final_params));
4195 ret = ufshcd_change_power_mode(hba, &final_params);
4199 EXPORT_SYMBOL_GPL(ufshcd_config_pwr_mode);
4202 * ufshcd_complete_dev_init() - checks device readiness
4203 * @hba: per-adapter instance
4205 * Set fDeviceInit flag and poll until device toggles it.
4207 static int ufshcd_complete_dev_init(struct ufs_hba *hba)
4210 bool flag_res = true;
4213 err = ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_SET_FLAG,
4214 QUERY_FLAG_IDN_FDEVICEINIT, 0, NULL);
4217 "%s setting fDeviceInit flag failed with error %d\n",
4222 /* Poll fDeviceInit flag to be cleared */
4223 timeout = ktime_add_ms(ktime_get(), FDEVICEINIT_COMPL_TIMEOUT);
4225 err = ufshcd_query_flag(hba, UPIU_QUERY_OPCODE_READ_FLAG,
4226 QUERY_FLAG_IDN_FDEVICEINIT, 0, &flag_res);
4229 usleep_range(5000, 10000);
4230 } while (ktime_before(ktime_get(), timeout));
4234 "%s reading fDeviceInit flag failed with error %d\n",
4236 } else if (flag_res) {
4238 "%s fDeviceInit was not cleared by the device\n",
4247 * ufshcd_make_hba_operational - Make UFS controller operational
4248 * @hba: per adapter instance
4250 * To bring UFS host controller to operational state,
4251 * 1. Enable required interrupts
4252 * 2. Configure interrupt aggregation
4253 * 3. Program UTRL and UTMRL base address
4254 * 4. Configure run-stop-registers
4256 * Returns 0 on success, non-zero value on failure
4258 int ufshcd_make_hba_operational(struct ufs_hba *hba)
4263 /* Enable required interrupts */
4264 ufshcd_enable_intr(hba, UFSHCD_ENABLE_INTRS);
4266 /* Configure interrupt aggregation */
4267 if (ufshcd_is_intr_aggr_allowed(hba))
4268 ufshcd_config_intr_aggr(hba, hba->nutrs - 1, INT_AGGR_DEF_TO);
4270 ufshcd_disable_intr_aggr(hba);
4272 /* Configure UTRL and UTMRL base address registers */
4273 ufshcd_writel(hba, lower_32_bits(hba->utrdl_dma_addr),
4274 REG_UTP_TRANSFER_REQ_LIST_BASE_L);
4275 ufshcd_writel(hba, upper_32_bits(hba->utrdl_dma_addr),
4276 REG_UTP_TRANSFER_REQ_LIST_BASE_H);
4277 ufshcd_writel(hba, lower_32_bits(hba->utmrdl_dma_addr),
4278 REG_UTP_TASK_REQ_LIST_BASE_L);
4279 ufshcd_writel(hba, upper_32_bits(hba->utmrdl_dma_addr),
4280 REG_UTP_TASK_REQ_LIST_BASE_H);
4283 * Make sure base address and interrupt setup are updated before
4284 * enabling the run/stop registers below.
4289 * UCRDY, UTMRLDY and UTRLRDY bits must be 1
4291 reg = ufshcd_readl(hba, REG_CONTROLLER_STATUS);
4292 if (!(ufshcd_get_lists_status(reg))) {
4293 ufshcd_enable_run_stop_reg(hba);
4296 "Host controller not ready to process requests");
4302 EXPORT_SYMBOL_GPL(ufshcd_make_hba_operational);
4305 * ufshcd_hba_stop - Send controller to reset state
4306 * @hba: per adapter instance
4308 static inline void ufshcd_hba_stop(struct ufs_hba *hba)
4310 unsigned long flags;
4314 * Obtain the host lock to prevent that the controller is disabled
4315 * while the UFS interrupt handler is active on another CPU.
4317 spin_lock_irqsave(hba->host->host_lock, flags);
4318 ufshcd_writel(hba, CONTROLLER_DISABLE, REG_CONTROLLER_ENABLE);
4319 spin_unlock_irqrestore(hba->host->host_lock, flags);
4321 err = ufshcd_wait_for_register(hba, REG_CONTROLLER_ENABLE,
4322 CONTROLLER_ENABLE, CONTROLLER_DISABLE,
4325 dev_err(hba->dev, "%s: Controller disable failed\n", __func__);
4329 * ufshcd_hba_execute_hce - initialize the controller
4330 * @hba: per adapter instance
4332 * The controller resets itself and controller firmware initialization
4333 * sequence kicks off. When controller is ready it will set
4334 * the Host Controller Enable bit to 1.
4336 * Returns 0 on success, non-zero value on failure
4338 static int ufshcd_hba_execute_hce(struct ufs_hba *hba)
4342 if (!ufshcd_is_hba_active(hba))
4343 /* change controller state to "reset state" */
4344 ufshcd_hba_stop(hba);
4346 /* UniPro link is disabled at this point */
4347 ufshcd_set_link_off(hba);
4349 ufshcd_vops_hce_enable_notify(hba, PRE_CHANGE);
4351 /* start controller initialization sequence */
4352 ufshcd_hba_start(hba);
4355 * To initialize a UFS host controller HCE bit must be set to 1.
4356 * During initialization the HCE bit value changes from 1->0->1.
4357 * When the host controller completes initialization sequence
4358 * it sets the value of HCE bit to 1. The same HCE bit is read back
4359 * to check if the controller has completed initialization sequence.
4360 * So without this delay the value HCE = 1, set in the previous
4361 * instruction might be read back.
4362 * This delay can be changed based on the controller.
4364 ufshcd_delay_us(hba->vps->hba_enable_delay_us, 100);
4366 /* wait for the host controller to complete initialization */
4368 while (ufshcd_is_hba_active(hba)) {
4373 "Controller enable failed\n");
4376 usleep_range(1000, 1100);
4379 /* enable UIC related interrupts */
4380 ufshcd_enable_intr(hba, UFSHCD_UIC_MASK);
4382 ufshcd_vops_hce_enable_notify(hba, POST_CHANGE);
4387 int ufshcd_hba_enable(struct ufs_hba *hba)
4391 if (hba->quirks & UFSHCI_QUIRK_BROKEN_HCE) {
4392 ufshcd_set_link_off(hba);
4393 ufshcd_vops_hce_enable_notify(hba, PRE_CHANGE);
4395 /* enable UIC related interrupts */
4396 ufshcd_enable_intr(hba, UFSHCD_UIC_MASK);
4397 ret = ufshcd_dme_reset(hba);
4399 ret = ufshcd_dme_enable(hba);
4401 ufshcd_vops_hce_enable_notify(hba, POST_CHANGE);
4404 "Host controller enable failed with non-hce\n");
4407 ret = ufshcd_hba_execute_hce(hba);
4412 EXPORT_SYMBOL_GPL(ufshcd_hba_enable);
4414 static int ufshcd_disable_tx_lcc(struct ufs_hba *hba, bool peer)
4416 int tx_lanes = 0, i, err = 0;
4419 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_CONNECTEDTXDATALANES),
4422 ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_CONNECTEDTXDATALANES),
4424 for (i = 0; i < tx_lanes; i++) {
4426 err = ufshcd_dme_set(hba,
4427 UIC_ARG_MIB_SEL(TX_LCC_ENABLE,
4428 UIC_ARG_MPHY_TX_GEN_SEL_INDEX(i)),
4431 err = ufshcd_dme_peer_set(hba,
4432 UIC_ARG_MIB_SEL(TX_LCC_ENABLE,
4433 UIC_ARG_MPHY_TX_GEN_SEL_INDEX(i)),
4436 dev_err(hba->dev, "%s: TX LCC Disable failed, peer = %d, lane = %d, err = %d",
4437 __func__, peer, i, err);
4445 static inline int ufshcd_disable_device_tx_lcc(struct ufs_hba *hba)
4447 return ufshcd_disable_tx_lcc(hba, true);
4450 void ufshcd_update_reg_hist(struct ufs_err_reg_hist *reg_hist,
4453 reg_hist->reg[reg_hist->pos] = reg;
4454 reg_hist->tstamp[reg_hist->pos] = ktime_get();
4455 reg_hist->pos = (reg_hist->pos + 1) % UFS_ERR_REG_HIST_LENGTH;
4457 EXPORT_SYMBOL_GPL(ufshcd_update_reg_hist);
4460 * ufshcd_link_startup - Initialize unipro link startup
4461 * @hba: per adapter instance
4463 * Returns 0 for success, non-zero in case of failure
4465 static int ufshcd_link_startup(struct ufs_hba *hba)
4468 int retries = DME_LINKSTARTUP_RETRIES;
4469 bool link_startup_again = false;
4472 * If UFS device isn't active then we will have to issue link startup
4473 * 2 times to make sure the device state move to active.
4475 if (!ufshcd_is_ufs_dev_active(hba))
4476 link_startup_again = true;
4480 ufshcd_vops_link_startup_notify(hba, PRE_CHANGE);
4482 ret = ufshcd_dme_link_startup(hba);
4484 /* check if device is detected by inter-connect layer */
4485 if (!ret && !ufshcd_is_device_present(hba)) {
4486 ufshcd_update_reg_hist(&hba->ufs_stats.link_startup_err,
4488 dev_err(hba->dev, "%s: Device not present\n", __func__);
4494 * DME link lost indication is only received when link is up,
4495 * but we can't be sure if the link is up until link startup
4496 * succeeds. So reset the local Uni-Pro and try again.
4498 if (ret && ufshcd_hba_enable(hba)) {
4499 ufshcd_update_reg_hist(&hba->ufs_stats.link_startup_err,
4503 } while (ret && retries--);
4506 /* failed to get the link up... retire */
4507 ufshcd_update_reg_hist(&hba->ufs_stats.link_startup_err,
4512 if (link_startup_again) {
4513 link_startup_again = false;
4514 retries = DME_LINKSTARTUP_RETRIES;
4518 /* Mark that link is up in PWM-G1, 1-lane, SLOW-AUTO mode */
4519 ufshcd_init_pwr_info(hba);
4520 ufshcd_print_pwr_info(hba);
4522 if (hba->quirks & UFSHCD_QUIRK_BROKEN_LCC) {
4523 ret = ufshcd_disable_device_tx_lcc(hba);
4528 /* Include any host controller configuration via UIC commands */
4529 ret = ufshcd_vops_link_startup_notify(hba, POST_CHANGE);
4533 /* Clear UECPA once due to LINERESET has happened during LINK_STARTUP */
4534 ufshcd_readl(hba, REG_UIC_ERROR_CODE_PHY_ADAPTER_LAYER);
4535 ret = ufshcd_make_hba_operational(hba);
4538 dev_err(hba->dev, "link startup failed %d\n", ret);
4539 ufshcd_print_host_state(hba);
4540 ufshcd_print_pwr_info(hba);
4541 ufshcd_print_host_regs(hba);
4547 * ufshcd_verify_dev_init() - Verify device initialization
4548 * @hba: per-adapter instance
4550 * Send NOP OUT UPIU and wait for NOP IN response to check whether the
4551 * device Transport Protocol (UTP) layer is ready after a reset.
4552 * If the UTP layer at the device side is not initialized, it may
4553 * not respond with NOP IN UPIU within timeout of %NOP_OUT_TIMEOUT
4554 * and we retry sending NOP OUT for %NOP_OUT_RETRIES iterations.
4556 static int ufshcd_verify_dev_init(struct ufs_hba *hba)
4561 ufshcd_hold(hba, false);
4562 mutex_lock(&hba->dev_cmd.lock);
4563 for (retries = NOP_OUT_RETRIES; retries > 0; retries--) {
4564 err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_NOP,
4567 if (!err || err == -ETIMEDOUT)
4570 dev_dbg(hba->dev, "%s: error %d retrying\n", __func__, err);
4572 mutex_unlock(&hba->dev_cmd.lock);
4573 ufshcd_release(hba);
4576 dev_err(hba->dev, "%s: NOP OUT failed %d\n", __func__, err);
4581 * ufshcd_set_queue_depth - set lun queue depth
4582 * @sdev: pointer to SCSI device
4584 * Read bLUQueueDepth value and activate scsi tagged command
4585 * queueing. For WLUN, queue depth is set to 1. For best-effort
4586 * cases (bLUQueueDepth = 0) the queue depth is set to a maximum
4587 * value that host can queue.
4589 static void ufshcd_set_queue_depth(struct scsi_device *sdev)
4593 struct ufs_hba *hba;
4595 hba = shost_priv(sdev->host);
4597 lun_qdepth = hba->nutrs;
4598 ret = ufshcd_read_unit_desc_param(hba,
4599 ufshcd_scsi_to_upiu_lun(sdev->lun),
4600 UNIT_DESC_PARAM_LU_Q_DEPTH,
4602 sizeof(lun_qdepth));
4604 /* Some WLUN doesn't support unit descriptor */
4605 if (ret == -EOPNOTSUPP)
4607 else if (!lun_qdepth)
4608 /* eventually, we can figure out the real queue depth */
4609 lun_qdepth = hba->nutrs;
4611 lun_qdepth = min_t(int, lun_qdepth, hba->nutrs);
4613 dev_dbg(hba->dev, "%s: activate tcq with queue depth %d\n",
4614 __func__, lun_qdepth);
4615 scsi_change_queue_depth(sdev, lun_qdepth);
4619 * ufshcd_get_lu_wp - returns the "b_lu_write_protect" from UNIT DESCRIPTOR
4620 * @hba: per-adapter instance
4621 * @lun: UFS device lun id
4622 * @b_lu_write_protect: pointer to buffer to hold the LU's write protect info
4624 * Returns 0 in case of success and b_lu_write_protect status would be returned
4625 * @b_lu_write_protect parameter.
4626 * Returns -ENOTSUPP if reading b_lu_write_protect is not supported.
4627 * Returns -EINVAL in case of invalid parameters passed to this function.
4629 static int ufshcd_get_lu_wp(struct ufs_hba *hba,
4631 u8 *b_lu_write_protect)
4635 if (!b_lu_write_protect)
4638 * According to UFS device spec, RPMB LU can't be write
4639 * protected so skip reading bLUWriteProtect parameter for
4640 * it. For other W-LUs, UNIT DESCRIPTOR is not available.
4642 else if (lun >= hba->dev_info.max_lu_supported)
4645 ret = ufshcd_read_unit_desc_param(hba,
4647 UNIT_DESC_PARAM_LU_WR_PROTECT,
4649 sizeof(*b_lu_write_protect));
4654 * ufshcd_get_lu_power_on_wp_status - get LU's power on write protect
4656 * @hba: per-adapter instance
4657 * @sdev: pointer to SCSI device
4660 static inline void ufshcd_get_lu_power_on_wp_status(struct ufs_hba *hba,
4661 struct scsi_device *sdev)
4663 if (hba->dev_info.f_power_on_wp_en &&
4664 !hba->dev_info.is_lu_power_on_wp) {
4665 u8 b_lu_write_protect;
4667 if (!ufshcd_get_lu_wp(hba, ufshcd_scsi_to_upiu_lun(sdev->lun),
4668 &b_lu_write_protect) &&
4669 (b_lu_write_protect == UFS_LU_POWER_ON_WP))
4670 hba->dev_info.is_lu_power_on_wp = true;
4675 * ufshcd_slave_alloc - handle initial SCSI device configurations
4676 * @sdev: pointer to SCSI device
4680 static int ufshcd_slave_alloc(struct scsi_device *sdev)
4682 struct ufs_hba *hba;
4684 hba = shost_priv(sdev->host);
4686 /* Mode sense(6) is not supported by UFS, so use Mode sense(10) */
4687 sdev->use_10_for_ms = 1;
4689 /* DBD field should be set to 1 in mode sense(10) */
4690 sdev->set_dbd_for_ms = 1;
4692 /* allow SCSI layer to restart the device in case of errors */
4693 sdev->allow_restart = 1;
4695 /* REPORT SUPPORTED OPERATION CODES is not supported */
4696 sdev->no_report_opcodes = 1;
4698 /* WRITE_SAME command is not supported */
4699 sdev->no_write_same = 1;
4701 ufshcd_set_queue_depth(sdev);
4703 ufshcd_get_lu_power_on_wp_status(hba, sdev);
4709 * ufshcd_change_queue_depth - change queue depth
4710 * @sdev: pointer to SCSI device
4711 * @depth: required depth to set
4713 * Change queue depth and make sure the max. limits are not crossed.
4715 static int ufshcd_change_queue_depth(struct scsi_device *sdev, int depth)
4717 struct ufs_hba *hba = shost_priv(sdev->host);
4719 if (depth > hba->nutrs)
4721 return scsi_change_queue_depth(sdev, depth);
4725 * ufshcd_slave_configure - adjust SCSI device configurations
4726 * @sdev: pointer to SCSI device
4728 static int ufshcd_slave_configure(struct scsi_device *sdev)
4730 struct ufs_hba *hba = shost_priv(sdev->host);
4731 struct request_queue *q = sdev->request_queue;
4733 blk_queue_update_dma_pad(q, PRDT_DATA_BYTE_COUNT_PAD - 1);
4735 if (ufshcd_is_rpm_autosuspend_allowed(hba))
4736 sdev->rpm_autosuspend = 1;
4738 ufshcd_crypto_setup_rq_keyslot_manager(hba, q);
4744 * ufshcd_slave_destroy - remove SCSI device configurations
4745 * @sdev: pointer to SCSI device
4747 static void ufshcd_slave_destroy(struct scsi_device *sdev)
4749 struct ufs_hba *hba;
4751 hba = shost_priv(sdev->host);
4752 /* Drop the reference as it won't be needed anymore */
4753 if (ufshcd_scsi_to_upiu_lun(sdev->lun) == UFS_UPIU_UFS_DEVICE_WLUN) {
4754 unsigned long flags;
4756 spin_lock_irqsave(hba->host->host_lock, flags);
4757 hba->sdev_ufs_device = NULL;
4758 spin_unlock_irqrestore(hba->host->host_lock, flags);
4763 * ufshcd_scsi_cmd_status - Update SCSI command result based on SCSI status
4764 * @lrbp: pointer to local reference block of completed command
4765 * @scsi_status: SCSI command status
4767 * Returns value base on SCSI command status
4770 ufshcd_scsi_cmd_status(struct ufshcd_lrb *lrbp, int scsi_status)
4774 switch (scsi_status) {
4775 case SAM_STAT_CHECK_CONDITION:
4776 ufshcd_copy_sense_data(lrbp);
4779 result |= DID_OK << 16 |
4780 COMMAND_COMPLETE << 8 |
4783 case SAM_STAT_TASK_SET_FULL:
4785 case SAM_STAT_TASK_ABORTED:
4786 ufshcd_copy_sense_data(lrbp);
4787 result |= scsi_status;
4790 result |= DID_ERROR << 16;
4792 } /* end of switch */
4798 * ufshcd_transfer_rsp_status - Get overall status of the response
4799 * @hba: per adapter instance
4800 * @lrbp: pointer to local reference block of completed command
4802 * Returns result of the command to notify SCSI midlayer
4805 ufshcd_transfer_rsp_status(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
4811 /* overall command status of utrd */
4812 ocs = ufshcd_get_tr_ocs(lrbp);
4814 if (hba->quirks & UFSHCD_QUIRK_BROKEN_OCS_FATAL_ERROR) {
4815 if (be32_to_cpu(lrbp->ucd_rsp_ptr->header.dword_1) &
4816 MASK_RSP_UPIU_RESULT)
4822 result = ufshcd_get_req_rsp(lrbp->ucd_rsp_ptr);
4823 hba->ufs_stats.last_hibern8_exit_tstamp = ktime_set(0, 0);
4825 case UPIU_TRANSACTION_RESPONSE:
4827 * get the response UPIU result to extract
4828 * the SCSI command status
4830 result = ufshcd_get_rsp_upiu_result(lrbp->ucd_rsp_ptr);
4833 * get the result based on SCSI status response
4834 * to notify the SCSI midlayer of the command status
4836 scsi_status = result & MASK_SCSI_STATUS;
4837 result = ufshcd_scsi_cmd_status(lrbp, scsi_status);
4840 * Currently we are only supporting BKOPs exception
4841 * events hence we can ignore BKOPs exception event
4842 * during power management callbacks. BKOPs exception
4843 * event is not expected to be raised in runtime suspend
4844 * callback as it allows the urgent bkops.
4845 * During system suspend, we are anyway forcefully
4846 * disabling the bkops and if urgent bkops is needed
4847 * it will be enabled on system resume. Long term
4848 * solution could be to abort the system suspend if
4849 * UFS device needs urgent BKOPs.
4851 if (!hba->pm_op_in_progress &&
4852 ufshcd_is_exception_event(lrbp->ucd_rsp_ptr) &&
4853 schedule_work(&hba->eeh_work)) {
4855 * Prevent suspend once eeh_work is scheduled
4856 * to avoid deadlock between ufshcd_suspend
4857 * and exception event handler.
4859 pm_runtime_get_noresume(hba->dev);
4862 case UPIU_TRANSACTION_REJECT_UPIU:
4863 /* TODO: handle Reject UPIU Response */
4864 result = DID_ERROR << 16;
4866 "Reject UPIU not fully implemented\n");
4870 "Unexpected request response code = %x\n",
4872 result = DID_ERROR << 16;
4877 result |= DID_ABORT << 16;
4879 case OCS_INVALID_COMMAND_STATUS:
4880 result |= DID_REQUEUE << 16;
4882 case OCS_INVALID_CMD_TABLE_ATTR:
4883 case OCS_INVALID_PRDT_ATTR:
4884 case OCS_MISMATCH_DATA_BUF_SIZE:
4885 case OCS_MISMATCH_RESP_UPIU_SIZE:
4886 case OCS_PEER_COMM_FAILURE:
4887 case OCS_FATAL_ERROR:
4888 case OCS_DEVICE_FATAL_ERROR:
4889 case OCS_INVALID_CRYPTO_CONFIG:
4890 case OCS_GENERAL_CRYPTO_ERROR:
4892 result |= DID_ERROR << 16;
4894 "OCS error from controller = %x for tag %d\n",
4895 ocs, lrbp->task_tag);
4896 ufshcd_print_host_regs(hba);
4897 ufshcd_print_host_state(hba);
4899 } /* end of switch */
4901 if ((host_byte(result) != DID_OK) && !hba->silence_err_logs)
4902 ufshcd_print_trs(hba, 1 << lrbp->task_tag, true);
4907 * ufshcd_uic_cmd_compl - handle completion of uic command
4908 * @hba: per adapter instance
4909 * @intr_status: interrupt status generated by the controller
4912 * IRQ_HANDLED - If interrupt is valid
4913 * IRQ_NONE - If invalid interrupt
4915 static irqreturn_t ufshcd_uic_cmd_compl(struct ufs_hba *hba, u32 intr_status)
4917 irqreturn_t retval = IRQ_NONE;
4919 if ((intr_status & UIC_COMMAND_COMPL) && hba->active_uic_cmd) {
4920 hba->active_uic_cmd->argument2 |=
4921 ufshcd_get_uic_cmd_result(hba);
4922 hba->active_uic_cmd->argument3 =
4923 ufshcd_get_dme_attr_val(hba);
4924 if (!hba->uic_async_done)
4925 hba->active_uic_cmd->cmd_active = 0;
4926 complete(&hba->active_uic_cmd->done);
4927 retval = IRQ_HANDLED;
4930 if ((intr_status & UFSHCD_UIC_PWR_MASK) && hba->uic_async_done) {
4931 hba->active_uic_cmd->cmd_active = 0;
4932 complete(hba->uic_async_done);
4933 retval = IRQ_HANDLED;
4936 if (retval == IRQ_HANDLED)
4937 ufshcd_add_uic_command_trace(hba, hba->active_uic_cmd,
4943 * __ufshcd_transfer_req_compl - handle SCSI and query command completion
4944 * @hba: per adapter instance
4945 * @completed_reqs: requests to complete
4947 static void __ufshcd_transfer_req_compl(struct ufs_hba *hba,
4948 unsigned long completed_reqs)
4950 struct ufshcd_lrb *lrbp;
4951 struct scsi_cmnd *cmd;
4955 for_each_set_bit(index, &completed_reqs, hba->nutrs) {
4956 lrbp = &hba->lrb[index];
4957 lrbp->compl_time_stamp = ktime_get();
4960 ufshcd_add_command_trace(hba, index, "complete");
4961 result = ufshcd_transfer_rsp_status(hba, lrbp);
4962 scsi_dma_unmap(cmd);
4963 cmd->result = result;
4964 /* Mark completed command as NULL in LRB */
4966 /* Do not touch lrbp after scsi done */
4967 cmd->scsi_done(cmd);
4968 __ufshcd_release(hba);
4969 } else if (lrbp->command_type == UTP_CMD_TYPE_DEV_MANAGE ||
4970 lrbp->command_type == UTP_CMD_TYPE_UFS_STORAGE) {
4971 if (hba->dev_cmd.complete) {
4972 ufshcd_add_command_trace(hba, index,
4974 complete(hba->dev_cmd.complete);
4977 if (ufshcd_is_clkscaling_supported(hba))
4978 hba->clk_scaling.active_reqs--;
4981 /* clear corresponding bits of completed commands */
4982 hba->outstanding_reqs ^= completed_reqs;
4984 ufshcd_clk_scaling_update_busy(hba);
4988 * ufshcd_transfer_req_compl - handle SCSI and query command completion
4989 * @hba: per adapter instance
4992 * IRQ_HANDLED - If interrupt is valid
4993 * IRQ_NONE - If invalid interrupt
4995 static irqreturn_t ufshcd_transfer_req_compl(struct ufs_hba *hba)
4997 unsigned long completed_reqs;
5000 /* Resetting interrupt aggregation counters first and reading the
5001 * DOOR_BELL afterward allows us to handle all the completed requests.
5002 * In order to prevent other interrupts starvation the DB is read once
5003 * after reset. The down side of this solution is the possibility of
5004 * false interrupt if device completes another request after resetting
5005 * aggregation and before reading the DB.
5007 if (ufshcd_is_intr_aggr_allowed(hba) &&
5008 !(hba->quirks & UFSHCI_QUIRK_SKIP_RESET_INTR_AGGR))
5009 ufshcd_reset_intr_aggr(hba);
5011 tr_doorbell = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
5012 completed_reqs = tr_doorbell ^ hba->outstanding_reqs;
5014 if (completed_reqs) {
5015 __ufshcd_transfer_req_compl(hba, completed_reqs);
5023 * ufshcd_disable_ee - disable exception event
5024 * @hba: per-adapter instance
5025 * @mask: exception event to disable
5027 * Disables exception event in the device so that the EVENT_ALERT
5030 * Returns zero on success, non-zero error value on failure.
5032 static int ufshcd_disable_ee(struct ufs_hba *hba, u16 mask)
5037 if (!(hba->ee_ctrl_mask & mask))
5040 val = hba->ee_ctrl_mask & ~mask;
5041 val &= MASK_EE_STATUS;
5042 err = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_WRITE_ATTR,
5043 QUERY_ATTR_IDN_EE_CONTROL, 0, 0, &val);
5045 hba->ee_ctrl_mask &= ~mask;
5051 * ufshcd_enable_ee - enable exception event
5052 * @hba: per-adapter instance
5053 * @mask: exception event to enable
5055 * Enable corresponding exception event in the device to allow
5056 * device to alert host in critical scenarios.
5058 * Returns zero on success, non-zero error value on failure.
5060 static int ufshcd_enable_ee(struct ufs_hba *hba, u16 mask)
5065 if (hba->ee_ctrl_mask & mask)
5068 val = hba->ee_ctrl_mask | mask;
5069 val &= MASK_EE_STATUS;
5070 err = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_WRITE_ATTR,
5071 QUERY_ATTR_IDN_EE_CONTROL, 0, 0, &val);
5073 hba->ee_ctrl_mask |= mask;
5079 * ufshcd_enable_auto_bkops - Allow device managed BKOPS
5080 * @hba: per-adapter instance
5082 * Allow device to manage background operations on its own. Enabling
5083 * this might lead to inconsistent latencies during normal data transfers
5084 * as the device is allowed to manage its own way of handling background
5087 * Returns zero on success, non-zero on failure.
5089 static int ufshcd_enable_auto_bkops(struct ufs_hba *hba)
5093 if (hba->auto_bkops_enabled)
5096 err = ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_SET_FLAG,
5097 QUERY_FLAG_IDN_BKOPS_EN, 0, NULL);
5099 dev_err(hba->dev, "%s: failed to enable bkops %d\n",
5104 hba->auto_bkops_enabled = true;
5105 trace_ufshcd_auto_bkops_state(dev_name(hba->dev), "Enabled");
5107 /* No need of URGENT_BKOPS exception from the device */
5108 err = ufshcd_disable_ee(hba, MASK_EE_URGENT_BKOPS);
5110 dev_err(hba->dev, "%s: failed to disable exception event %d\n",
5117 * ufshcd_disable_auto_bkops - block device in doing background operations
5118 * @hba: per-adapter instance
5120 * Disabling background operations improves command response latency but
5121 * has drawback of device moving into critical state where the device is
5122 * not-operable. Make sure to call ufshcd_enable_auto_bkops() whenever the
5123 * host is idle so that BKOPS are managed effectively without any negative
5126 * Returns zero on success, non-zero on failure.
5128 static int ufshcd_disable_auto_bkops(struct ufs_hba *hba)
5132 if (!hba->auto_bkops_enabled)
5136 * If host assisted BKOPs is to be enabled, make sure
5137 * urgent bkops exception is allowed.
5139 err = ufshcd_enable_ee(hba, MASK_EE_URGENT_BKOPS);
5141 dev_err(hba->dev, "%s: failed to enable exception event %d\n",
5146 err = ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_CLEAR_FLAG,
5147 QUERY_FLAG_IDN_BKOPS_EN, 0, NULL);
5149 dev_err(hba->dev, "%s: failed to disable bkops %d\n",
5151 ufshcd_disable_ee(hba, MASK_EE_URGENT_BKOPS);
5155 hba->auto_bkops_enabled = false;
5156 trace_ufshcd_auto_bkops_state(dev_name(hba->dev), "Disabled");
5157 hba->is_urgent_bkops_lvl_checked = false;
5163 * ufshcd_force_reset_auto_bkops - force reset auto bkops state
5164 * @hba: per adapter instance
5166 * After a device reset the device may toggle the BKOPS_EN flag
5167 * to default value. The s/w tracking variables should be updated
5168 * as well. This function would change the auto-bkops state based on
5169 * UFSHCD_CAP_KEEP_AUTO_BKOPS_ENABLED_EXCEPT_SUSPEND.
5171 static void ufshcd_force_reset_auto_bkops(struct ufs_hba *hba)
5173 if (ufshcd_keep_autobkops_enabled_except_suspend(hba)) {
5174 hba->auto_bkops_enabled = false;
5175 hba->ee_ctrl_mask |= MASK_EE_URGENT_BKOPS;
5176 ufshcd_enable_auto_bkops(hba);
5178 hba->auto_bkops_enabled = true;
5179 hba->ee_ctrl_mask &= ~MASK_EE_URGENT_BKOPS;
5180 ufshcd_disable_auto_bkops(hba);
5182 hba->urgent_bkops_lvl = BKOPS_STATUS_PERF_IMPACT;
5183 hba->is_urgent_bkops_lvl_checked = false;
5186 static inline int ufshcd_get_bkops_status(struct ufs_hba *hba, u32 *status)
5188 return ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
5189 QUERY_ATTR_IDN_BKOPS_STATUS, 0, 0, status);
5193 * ufshcd_bkops_ctrl - control the auto bkops based on current bkops status
5194 * @hba: per-adapter instance
5195 * @status: bkops_status value
5197 * Read the bkops_status from the UFS device and Enable fBackgroundOpsEn
5198 * flag in the device to permit background operations if the device
5199 * bkops_status is greater than or equal to "status" argument passed to
5200 * this function, disable otherwise.
5202 * Returns 0 for success, non-zero in case of failure.
5204 * NOTE: Caller of this function can check the "hba->auto_bkops_enabled" flag
5205 * to know whether auto bkops is enabled or disabled after this function
5206 * returns control to it.
5208 static int ufshcd_bkops_ctrl(struct ufs_hba *hba,
5209 enum bkops_status status)
5212 u32 curr_status = 0;
5214 err = ufshcd_get_bkops_status(hba, &curr_status);
5216 dev_err(hba->dev, "%s: failed to get BKOPS status %d\n",
5219 } else if (curr_status > BKOPS_STATUS_MAX) {
5220 dev_err(hba->dev, "%s: invalid BKOPS status %d\n",
5221 __func__, curr_status);
5226 if (curr_status >= status)
5227 err = ufshcd_enable_auto_bkops(hba);
5229 err = ufshcd_disable_auto_bkops(hba);
5235 * ufshcd_urgent_bkops - handle urgent bkops exception event
5236 * @hba: per-adapter instance
5238 * Enable fBackgroundOpsEn flag in the device to permit background
5241 * If BKOPs is enabled, this function returns 0, 1 if the bkops in not enabled
5242 * and negative error value for any other failure.
5244 static int ufshcd_urgent_bkops(struct ufs_hba *hba)
5246 return ufshcd_bkops_ctrl(hba, hba->urgent_bkops_lvl);
5249 static inline int ufshcd_get_ee_status(struct ufs_hba *hba, u32 *status)
5251 return ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
5252 QUERY_ATTR_IDN_EE_STATUS, 0, 0, status);
5255 static void ufshcd_bkops_exception_event_handler(struct ufs_hba *hba)
5258 u32 curr_status = 0;
5260 if (hba->is_urgent_bkops_lvl_checked)
5261 goto enable_auto_bkops;
5263 err = ufshcd_get_bkops_status(hba, &curr_status);
5265 dev_err(hba->dev, "%s: failed to get BKOPS status %d\n",
5271 * We are seeing that some devices are raising the urgent bkops
5272 * exception events even when BKOPS status doesn't indicate performace
5273 * impacted or critical. Handle these device by determining their urgent
5274 * bkops status at runtime.
5276 if (curr_status < BKOPS_STATUS_PERF_IMPACT) {
5277 dev_err(hba->dev, "%s: device raised urgent BKOPS exception for bkops status %d\n",
5278 __func__, curr_status);
5279 /* update the current status as the urgent bkops level */
5280 hba->urgent_bkops_lvl = curr_status;
5281 hba->is_urgent_bkops_lvl_checked = true;
5285 err = ufshcd_enable_auto_bkops(hba);
5288 dev_err(hba->dev, "%s: failed to handle urgent bkops %d\n",
5292 static int ufshcd_wb_ctrl(struct ufs_hba *hba, bool enable)
5296 enum query_opcode opcode;
5298 if (!ufshcd_is_wb_allowed(hba))
5301 if (!(enable ^ hba->wb_enabled))
5304 opcode = UPIU_QUERY_OPCODE_SET_FLAG;
5306 opcode = UPIU_QUERY_OPCODE_CLEAR_FLAG;
5308 index = ufshcd_wb_get_query_index(hba);
5309 ret = ufshcd_query_flag_retry(hba, opcode,
5310 QUERY_FLAG_IDN_WB_EN, index, NULL);
5312 dev_err(hba->dev, "%s write booster %s failed %d\n",
5313 __func__, enable ? "enable" : "disable", ret);
5317 hba->wb_enabled = enable;
5318 dev_dbg(hba->dev, "%s write booster %s %d\n",
5319 __func__, enable ? "enable" : "disable", ret);
5324 static int ufshcd_wb_toggle_flush_during_h8(struct ufs_hba *hba, bool set)
5330 val = UPIU_QUERY_OPCODE_SET_FLAG;
5332 val = UPIU_QUERY_OPCODE_CLEAR_FLAG;
5334 index = ufshcd_wb_get_query_index(hba);
5335 return ufshcd_query_flag_retry(hba, val,
5336 QUERY_FLAG_IDN_WB_BUFF_FLUSH_DURING_HIBERN8,
5340 static inline void ufshcd_wb_toggle_flush(struct ufs_hba *hba, bool enable)
5342 if (hba->quirks & UFSHCI_QUIRK_SKIP_MANUAL_WB_FLUSH_CTRL)
5346 ufshcd_wb_buf_flush_enable(hba);
5348 ufshcd_wb_buf_flush_disable(hba);
5352 static int ufshcd_wb_buf_flush_enable(struct ufs_hba *hba)
5357 if (!ufshcd_is_wb_allowed(hba) || hba->wb_buf_flush_enabled)
5360 index = ufshcd_wb_get_query_index(hba);
5361 ret = ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_SET_FLAG,
5362 QUERY_FLAG_IDN_WB_BUFF_FLUSH_EN,
5365 dev_err(hba->dev, "%s WB - buf flush enable failed %d\n",
5368 hba->wb_buf_flush_enabled = true;
5370 dev_dbg(hba->dev, "WB - Flush enabled: %d\n", ret);
5374 static int ufshcd_wb_buf_flush_disable(struct ufs_hba *hba)
5379 if (!ufshcd_is_wb_allowed(hba) || !hba->wb_buf_flush_enabled)
5382 index = ufshcd_wb_get_query_index(hba);
5383 ret = ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_CLEAR_FLAG,
5384 QUERY_FLAG_IDN_WB_BUFF_FLUSH_EN,
5387 dev_warn(hba->dev, "%s: WB - buf flush disable failed %d\n",
5390 hba->wb_buf_flush_enabled = false;
5391 dev_dbg(hba->dev, "WB - Flush disabled: %d\n", ret);
5397 static bool ufshcd_wb_presrv_usrspc_keep_vcc_on(struct ufs_hba *hba,
5404 index = ufshcd_wb_get_query_index(hba);
5405 ret = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
5406 QUERY_ATTR_IDN_CURR_WB_BUFF_SIZE,
5407 index, 0, &cur_buf);
5409 dev_err(hba->dev, "%s dCurWriteBoosterBufferSize read failed %d\n",
5415 dev_info(hba->dev, "dCurWBBuf: %d WB disabled until free-space is available\n",
5419 /* Let it continue to flush when available buffer exceeds threshold */
5420 if (avail_buf < hba->vps->wb_flush_threshold)
5426 static bool ufshcd_wb_need_flush(struct ufs_hba *hba)
5432 if (!ufshcd_is_wb_allowed(hba))
5435 * The ufs device needs the vcc to be ON to flush.
5436 * With user-space reduction enabled, it's enough to enable flush
5437 * by checking only the available buffer. The threshold
5438 * defined here is > 90% full.
5439 * With user-space preserved enabled, the current-buffer
5440 * should be checked too because the wb buffer size can reduce
5441 * when disk tends to be full. This info is provided by current
5442 * buffer (dCurrentWriteBoosterBufferSize). There's no point in
5443 * keeping vcc on when current buffer is empty.
5445 index = ufshcd_wb_get_query_index(hba);
5446 ret = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
5447 QUERY_ATTR_IDN_AVAIL_WB_BUFF_SIZE,
5448 index, 0, &avail_buf);
5450 dev_warn(hba->dev, "%s dAvailableWriteBoosterBufferSize read failed %d\n",
5455 if (!hba->dev_info.b_presrv_uspc_en) {
5456 if (avail_buf <= UFS_WB_BUF_REMAIN_PERCENT(10))
5461 return ufshcd_wb_presrv_usrspc_keep_vcc_on(hba, avail_buf);
5464 static void ufshcd_rpm_dev_flush_recheck_work(struct work_struct *work)
5466 struct ufs_hba *hba = container_of(to_delayed_work(work),
5468 rpm_dev_flush_recheck_work);
5470 * To prevent unnecessary VCC power drain after device finishes
5471 * WriteBooster buffer flush or Auto BKOPs, force runtime resume
5472 * after a certain delay to recheck the threshold by next runtime
5475 pm_runtime_get_sync(hba->dev);
5476 pm_runtime_put_sync(hba->dev);
5480 * ufshcd_exception_event_handler - handle exceptions raised by device
5481 * @work: pointer to work data
5483 * Read bExceptionEventStatus attribute from the device and handle the
5484 * exception event accordingly.
5486 static void ufshcd_exception_event_handler(struct work_struct *work)
5488 struct ufs_hba *hba;
5491 hba = container_of(work, struct ufs_hba, eeh_work);
5493 pm_runtime_get_sync(hba->dev);
5494 ufshcd_scsi_block_requests(hba);
5495 err = ufshcd_get_ee_status(hba, &status);
5497 dev_err(hba->dev, "%s: failed to get exception status %d\n",
5502 status &= hba->ee_ctrl_mask;
5504 if (status & MASK_EE_URGENT_BKOPS)
5505 ufshcd_bkops_exception_event_handler(hba);
5508 ufshcd_scsi_unblock_requests(hba);
5510 * pm_runtime_get_noresume is called while scheduling
5511 * eeh_work to avoid suspend racing with exception work.
5512 * Hence decrement usage counter using pm_runtime_put_noidle
5513 * to allow suspend on completion of exception event handler.
5515 pm_runtime_put_noidle(hba->dev);
5516 pm_runtime_put(hba->dev);
5520 /* Complete requests that have door-bell cleared */
5521 static void ufshcd_complete_requests(struct ufs_hba *hba)
5523 ufshcd_transfer_req_compl(hba);
5524 ufshcd_tmc_handler(hba);
5528 * ufshcd_quirk_dl_nac_errors - This function checks if error handling is
5529 * to recover from the DL NAC errors or not.
5530 * @hba: per-adapter instance
5532 * Returns true if error handling is required, false otherwise
5534 static bool ufshcd_quirk_dl_nac_errors(struct ufs_hba *hba)
5536 unsigned long flags;
5537 bool err_handling = true;
5539 spin_lock_irqsave(hba->host->host_lock, flags);
5541 * UFS_DEVICE_QUIRK_RECOVERY_FROM_DL_NAC_ERRORS only workaround the
5542 * device fatal error and/or DL NAC & REPLAY timeout errors.
5544 if (hba->saved_err & (CONTROLLER_FATAL_ERROR | SYSTEM_BUS_FATAL_ERROR))
5547 if ((hba->saved_err & DEVICE_FATAL_ERROR) ||
5548 ((hba->saved_err & UIC_ERROR) &&
5549 (hba->saved_uic_err & UFSHCD_UIC_DL_TCx_REPLAY_ERROR)))
5552 if ((hba->saved_err & UIC_ERROR) &&
5553 (hba->saved_uic_err & UFSHCD_UIC_DL_NAC_RECEIVED_ERROR)) {
5556 * wait for 50ms to see if we can get any other errors or not.
5558 spin_unlock_irqrestore(hba->host->host_lock, flags);
5560 spin_lock_irqsave(hba->host->host_lock, flags);
5563 * now check if we have got any other severe errors other than
5566 if ((hba->saved_err & INT_FATAL_ERRORS) ||
5567 ((hba->saved_err & UIC_ERROR) &&
5568 (hba->saved_uic_err & ~UFSHCD_UIC_DL_NAC_RECEIVED_ERROR)))
5572 * As DL NAC is the only error received so far, send out NOP
5573 * command to confirm if link is still active or not.
5574 * - If we don't get any response then do error recovery.
5575 * - If we get response then clear the DL NAC error bit.
5578 spin_unlock_irqrestore(hba->host->host_lock, flags);
5579 err = ufshcd_verify_dev_init(hba);
5580 spin_lock_irqsave(hba->host->host_lock, flags);
5585 /* Link seems to be alive hence ignore the DL NAC errors */
5586 if (hba->saved_uic_err == UFSHCD_UIC_DL_NAC_RECEIVED_ERROR)
5587 hba->saved_err &= ~UIC_ERROR;
5588 /* clear NAC error */
5589 hba->saved_uic_err &= ~UFSHCD_UIC_DL_NAC_RECEIVED_ERROR;
5590 if (!hba->saved_uic_err)
5591 err_handling = false;
5594 spin_unlock_irqrestore(hba->host->host_lock, flags);
5595 return err_handling;
5598 /* host lock must be held before calling this func */
5599 static inline bool ufshcd_is_saved_err_fatal(struct ufs_hba *hba)
5601 return (hba->saved_uic_err & UFSHCD_UIC_DL_PA_INIT_ERROR) ||
5602 (hba->saved_err & (INT_FATAL_ERRORS | UFSHCD_UIC_HIBERN8_MASK));
5605 /* host lock must be held before calling this func */
5606 static inline void ufshcd_schedule_eh_work(struct ufs_hba *hba)
5608 /* handle fatal errors only when link is not in error state */
5609 if (hba->ufshcd_state != UFSHCD_STATE_ERROR) {
5610 if (hba->force_reset || ufshcd_is_link_broken(hba) ||
5611 ufshcd_is_saved_err_fatal(hba))
5612 hba->ufshcd_state = UFSHCD_STATE_EH_SCHEDULED_FATAL;
5614 hba->ufshcd_state = UFSHCD_STATE_EH_SCHEDULED_NON_FATAL;
5615 queue_work(hba->eh_wq, &hba->eh_work);
5619 static void ufshcd_err_handling_prepare(struct ufs_hba *hba)
5621 pm_runtime_get_sync(hba->dev);
5622 if (pm_runtime_suspended(hba->dev)) {
5624 * Don't assume anything of pm_runtime_get_sync(), if
5625 * resume fails, irq and clocks can be OFF, and powers
5626 * can be OFF or in LPM.
5628 ufshcd_setup_hba_vreg(hba, true);
5629 ufshcd_enable_irq(hba);
5630 ufshcd_setup_vreg(hba, true);
5631 ufshcd_config_vreg_hpm(hba, hba->vreg_info.vccq);
5632 ufshcd_config_vreg_hpm(hba, hba->vreg_info.vccq2);
5633 ufshcd_hold(hba, false);
5634 if (!ufshcd_is_clkgating_allowed(hba))
5635 ufshcd_setup_clocks(hba, true);
5636 ufshcd_release(hba);
5637 ufshcd_vops_resume(hba, UFS_RUNTIME_PM);
5639 ufshcd_hold(hba, false);
5640 if (hba->clk_scaling.is_allowed) {
5641 cancel_work_sync(&hba->clk_scaling.suspend_work);
5642 cancel_work_sync(&hba->clk_scaling.resume_work);
5643 ufshcd_suspend_clkscaling(hba);
5648 static void ufshcd_err_handling_unprepare(struct ufs_hba *hba)
5650 ufshcd_release(hba);
5651 if (hba->clk_scaling.is_allowed)
5652 ufshcd_resume_clkscaling(hba);
5653 pm_runtime_put(hba->dev);
5656 static inline bool ufshcd_err_handling_should_stop(struct ufs_hba *hba)
5658 return (hba->ufshcd_state == UFSHCD_STATE_ERROR ||
5659 (!(hba->saved_err || hba->saved_uic_err || hba->force_reset ||
5660 ufshcd_is_link_broken(hba))));
5664 static void ufshcd_recover_pm_error(struct ufs_hba *hba)
5666 struct Scsi_Host *shost = hba->host;
5667 struct scsi_device *sdev;
5668 struct request_queue *q;
5672 * Set RPM status of hba device to RPM_ACTIVE,
5673 * this also clears its runtime error.
5675 ret = pm_runtime_set_active(hba->dev);
5677 * If hba device had runtime error, we also need to resume those
5678 * scsi devices under hba in case any of them has failed to be
5679 * resumed due to hba runtime resume failure. This is to unblock
5680 * blk_queue_enter in case there are bios waiting inside it.
5683 shost_for_each_device(sdev, shost) {
5684 q = sdev->request_queue;
5685 if (q->dev && (q->rpm_status == RPM_SUSPENDED ||
5686 q->rpm_status == RPM_SUSPENDING))
5687 pm_request_resume(q->dev);
5692 static inline void ufshcd_recover_pm_error(struct ufs_hba *hba)
5697 static bool ufshcd_is_pwr_mode_restore_needed(struct ufs_hba *hba)
5699 struct ufs_pa_layer_attr *pwr_info = &hba->pwr_info;
5702 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_PWRMODE), &mode);
5704 if (pwr_info->pwr_rx != ((mode >> PWRMODE_RX_OFFSET) & PWRMODE_MASK))
5707 if (pwr_info->pwr_tx != (mode & PWRMODE_MASK))
5714 * ufshcd_err_handler - handle UFS errors that require s/w attention
5715 * @work: pointer to work structure
5717 static void ufshcd_err_handler(struct work_struct *work)
5719 struct ufs_hba *hba;
5720 unsigned long flags;
5721 bool err_xfer = false;
5722 bool err_tm = false;
5723 int err = 0, pmc_err;
5725 bool needs_reset = false, needs_restore = false;
5727 hba = container_of(work, struct ufs_hba, eh_work);
5729 spin_lock_irqsave(hba->host->host_lock, flags);
5730 if (ufshcd_err_handling_should_stop(hba)) {
5731 if (hba->ufshcd_state != UFSHCD_STATE_ERROR)
5732 hba->ufshcd_state = UFSHCD_STATE_OPERATIONAL;
5733 spin_unlock_irqrestore(hba->host->host_lock, flags);
5736 ufshcd_set_eh_in_progress(hba);
5737 spin_unlock_irqrestore(hba->host->host_lock, flags);
5738 ufshcd_err_handling_prepare(hba);
5739 spin_lock_irqsave(hba->host->host_lock, flags);
5740 ufshcd_scsi_block_requests(hba);
5742 * A full reset and restore might have happened after preparation
5743 * is finished, double check whether we should stop.
5745 if (ufshcd_err_handling_should_stop(hba)) {
5746 if (hba->ufshcd_state != UFSHCD_STATE_ERROR)
5747 hba->ufshcd_state = UFSHCD_STATE_OPERATIONAL;
5750 hba->ufshcd_state = UFSHCD_STATE_RESET;
5752 /* Complete requests that have door-bell cleared by h/w */
5753 ufshcd_complete_requests(hba);
5755 if (hba->dev_quirks & UFS_DEVICE_QUIRK_RECOVERY_FROM_DL_NAC_ERRORS) {
5758 spin_unlock_irqrestore(hba->host->host_lock, flags);
5759 /* release the lock as ufshcd_quirk_dl_nac_errors() may sleep */
5760 ret = ufshcd_quirk_dl_nac_errors(hba);
5761 spin_lock_irqsave(hba->host->host_lock, flags);
5762 if (!ret && !hba->force_reset && ufshcd_is_link_active(hba))
5763 goto skip_err_handling;
5766 if (hba->force_reset || ufshcd_is_link_broken(hba) ||
5767 ufshcd_is_saved_err_fatal(hba) ||
5768 ((hba->saved_err & UIC_ERROR) &&
5769 (hba->saved_uic_err & (UFSHCD_UIC_DL_NAC_RECEIVED_ERROR |
5770 UFSHCD_UIC_DL_TCx_REPLAY_ERROR))))
5773 if ((hba->saved_err & (INT_FATAL_ERRORS | UFSHCD_UIC_HIBERN8_MASK)) ||
5774 (hba->saved_uic_err &&
5775 (hba->saved_uic_err != UFSHCD_UIC_PA_GENERIC_ERROR))) {
5776 bool pr_prdt = !!(hba->saved_err & SYSTEM_BUS_FATAL_ERROR);
5778 spin_unlock_irqrestore(hba->host->host_lock, flags);
5779 ufshcd_print_host_state(hba);
5780 ufshcd_print_pwr_info(hba);
5781 ufshcd_print_host_regs(hba);
5782 ufshcd_print_tmrs(hba, hba->outstanding_tasks);
5783 ufshcd_print_trs(hba, hba->outstanding_reqs, pr_prdt);
5784 spin_lock_irqsave(hba->host->host_lock, flags);
5788 * if host reset is required then skip clearing the pending
5789 * transfers forcefully because they will get cleared during
5790 * host reset and restore
5796 * If LINERESET was caught, UFS might have been put to PWM mode,
5797 * check if power mode restore is needed.
5799 if (hba->saved_uic_err & UFSHCD_UIC_PA_GENERIC_ERROR) {
5800 hba->saved_uic_err &= ~UFSHCD_UIC_PA_GENERIC_ERROR;
5801 if (!hba->saved_uic_err)
5802 hba->saved_err &= ~UIC_ERROR;
5803 spin_unlock_irqrestore(hba->host->host_lock, flags);
5804 if (ufshcd_is_pwr_mode_restore_needed(hba))
5805 needs_restore = true;
5806 spin_lock_irqsave(hba->host->host_lock, flags);
5807 if (!hba->saved_err && !needs_restore)
5808 goto skip_err_handling;
5811 hba->silence_err_logs = true;
5812 /* release lock as clear command might sleep */
5813 spin_unlock_irqrestore(hba->host->host_lock, flags);
5814 /* Clear pending transfer requests */
5815 for_each_set_bit(tag, &hba->outstanding_reqs, hba->nutrs) {
5816 if (ufshcd_try_to_abort_task(hba, tag)) {
5818 goto lock_skip_pending_xfer_clear;
5822 /* Clear pending task management requests */
5823 for_each_set_bit(tag, &hba->outstanding_tasks, hba->nutmrs) {
5824 if (ufshcd_clear_tm_cmd(hba, tag)) {
5826 goto lock_skip_pending_xfer_clear;
5830 lock_skip_pending_xfer_clear:
5831 spin_lock_irqsave(hba->host->host_lock, flags);
5833 /* Complete the requests that are cleared by s/w */
5834 ufshcd_complete_requests(hba);
5835 hba->silence_err_logs = false;
5837 if (err_xfer || err_tm) {
5843 * After all reqs and tasks are cleared from doorbell,
5844 * now it is safe to retore power mode.
5846 if (needs_restore) {
5847 spin_unlock_irqrestore(hba->host->host_lock, flags);
5849 * Hold the scaling lock just in case dev cmds
5850 * are sent via bsg and/or sysfs.
5852 down_write(&hba->clk_scaling_lock);
5853 hba->force_pmc = true;
5854 pmc_err = ufshcd_config_pwr_mode(hba, &(hba->pwr_info));
5857 dev_err(hba->dev, "%s: Failed to restore power mode, err = %d\n",
5860 hba->force_pmc = false;
5861 ufshcd_print_pwr_info(hba);
5862 up_write(&hba->clk_scaling_lock);
5863 spin_lock_irqsave(hba->host->host_lock, flags);
5867 /* Fatal errors need reset */
5869 unsigned long max_doorbells = (1UL << hba->nutrs) - 1;
5872 * ufshcd_reset_and_restore() does the link reinitialization
5873 * which will need atleast one empty doorbell slot to send the
5874 * device management commands (NOP and query commands).
5875 * If there is no slot empty at this moment then free up last
5878 if (hba->outstanding_reqs == max_doorbells)
5879 __ufshcd_transfer_req_compl(hba,
5880 (1UL << (hba->nutrs - 1)));
5882 hba->force_reset = false;
5883 spin_unlock_irqrestore(hba->host->host_lock, flags);
5884 err = ufshcd_reset_and_restore(hba);
5886 dev_err(hba->dev, "%s: reset and restore failed with err %d\n",
5889 ufshcd_recover_pm_error(hba);
5890 spin_lock_irqsave(hba->host->host_lock, flags);
5895 if (hba->ufshcd_state == UFSHCD_STATE_RESET)
5896 hba->ufshcd_state = UFSHCD_STATE_OPERATIONAL;
5897 if (hba->saved_err || hba->saved_uic_err)
5898 dev_err_ratelimited(hba->dev, "%s: exit: saved_err 0x%x saved_uic_err 0x%x",
5899 __func__, hba->saved_err, hba->saved_uic_err);
5903 ufshcd_clear_eh_in_progress(hba);
5904 spin_unlock_irqrestore(hba->host->host_lock, flags);
5905 ufshcd_scsi_unblock_requests(hba);
5906 ufshcd_err_handling_unprepare(hba);
5910 * ufshcd_update_uic_error - check and set fatal UIC error flags.
5911 * @hba: per-adapter instance
5914 * IRQ_HANDLED - If interrupt is valid
5915 * IRQ_NONE - If invalid interrupt
5917 static irqreturn_t ufshcd_update_uic_error(struct ufs_hba *hba)
5920 irqreturn_t retval = IRQ_NONE;
5922 /* PHY layer error */
5923 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_PHY_ADAPTER_LAYER);
5924 if ((reg & UIC_PHY_ADAPTER_LAYER_ERROR) &&
5925 (reg & UIC_PHY_ADAPTER_LAYER_ERROR_CODE_MASK)) {
5926 ufshcd_update_reg_hist(&hba->ufs_stats.pa_err, reg);
5928 * To know whether this error is fatal or not, DB timeout
5929 * must be checked but this error is handled separately.
5931 if (reg & UIC_PHY_ADAPTER_LAYER_LANE_ERR_MASK)
5932 dev_dbg(hba->dev, "%s: UIC Lane error reported\n",
5935 /* Got a LINERESET indication. */
5936 if (reg & UIC_PHY_ADAPTER_LAYER_GENERIC_ERROR) {
5937 struct uic_command *cmd = NULL;
5939 hba->uic_error |= UFSHCD_UIC_PA_GENERIC_ERROR;
5940 if (hba->uic_async_done && hba->active_uic_cmd)
5941 cmd = hba->active_uic_cmd;
5943 * Ignore the LINERESET during power mode change
5944 * operation via DME_SET command.
5946 if (cmd && (cmd->command == UIC_CMD_DME_SET))
5947 hba->uic_error &= ~UFSHCD_UIC_PA_GENERIC_ERROR;
5949 retval |= IRQ_HANDLED;
5952 /* PA_INIT_ERROR is fatal and needs UIC reset */
5953 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_DATA_LINK_LAYER);
5954 if ((reg & UIC_DATA_LINK_LAYER_ERROR) &&
5955 (reg & UIC_DATA_LINK_LAYER_ERROR_CODE_MASK)) {
5956 ufshcd_update_reg_hist(&hba->ufs_stats.dl_err, reg);
5958 if (reg & UIC_DATA_LINK_LAYER_ERROR_PA_INIT)
5959 hba->uic_error |= UFSHCD_UIC_DL_PA_INIT_ERROR;
5960 else if (hba->dev_quirks &
5961 UFS_DEVICE_QUIRK_RECOVERY_FROM_DL_NAC_ERRORS) {
5962 if (reg & UIC_DATA_LINK_LAYER_ERROR_NAC_RECEIVED)
5964 UFSHCD_UIC_DL_NAC_RECEIVED_ERROR;
5965 else if (reg & UIC_DATA_LINK_LAYER_ERROR_TCx_REPLAY_TIMEOUT)
5966 hba->uic_error |= UFSHCD_UIC_DL_TCx_REPLAY_ERROR;
5968 retval |= IRQ_HANDLED;
5971 /* UIC NL/TL/DME errors needs software retry */
5972 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_NETWORK_LAYER);
5973 if ((reg & UIC_NETWORK_LAYER_ERROR) &&
5974 (reg & UIC_NETWORK_LAYER_ERROR_CODE_MASK)) {
5975 ufshcd_update_reg_hist(&hba->ufs_stats.nl_err, reg);
5976 hba->uic_error |= UFSHCD_UIC_NL_ERROR;
5977 retval |= IRQ_HANDLED;
5980 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_TRANSPORT_LAYER);
5981 if ((reg & UIC_TRANSPORT_LAYER_ERROR) &&
5982 (reg & UIC_TRANSPORT_LAYER_ERROR_CODE_MASK)) {
5983 ufshcd_update_reg_hist(&hba->ufs_stats.tl_err, reg);
5984 hba->uic_error |= UFSHCD_UIC_TL_ERROR;
5985 retval |= IRQ_HANDLED;
5988 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_DME);
5989 if ((reg & UIC_DME_ERROR) &&
5990 (reg & UIC_DME_ERROR_CODE_MASK)) {
5991 ufshcd_update_reg_hist(&hba->ufs_stats.dme_err, reg);
5992 hba->uic_error |= UFSHCD_UIC_DME_ERROR;
5993 retval |= IRQ_HANDLED;
5996 dev_dbg(hba->dev, "%s: UIC error flags = 0x%08x\n",
5997 __func__, hba->uic_error);
6001 static bool ufshcd_is_auto_hibern8_error(struct ufs_hba *hba,
6004 if (!ufshcd_is_auto_hibern8_supported(hba) ||
6005 !ufshcd_is_auto_hibern8_enabled(hba))
6008 if (!(intr_mask & UFSHCD_UIC_HIBERN8_MASK))
6011 if (hba->active_uic_cmd &&
6012 (hba->active_uic_cmd->command == UIC_CMD_DME_HIBER_ENTER ||
6013 hba->active_uic_cmd->command == UIC_CMD_DME_HIBER_EXIT))
6020 * ufshcd_check_errors - Check for errors that need s/w attention
6021 * @hba: per-adapter instance
6024 * IRQ_HANDLED - If interrupt is valid
6025 * IRQ_NONE - If invalid interrupt
6027 static irqreturn_t ufshcd_check_errors(struct ufs_hba *hba)
6029 bool queue_eh_work = false;
6030 irqreturn_t retval = IRQ_NONE;
6032 if (hba->errors & INT_FATAL_ERRORS) {
6033 ufshcd_update_reg_hist(&hba->ufs_stats.fatal_err, hba->errors);
6034 queue_eh_work = true;
6037 if (hba->errors & UIC_ERROR) {
6039 retval = ufshcd_update_uic_error(hba);
6041 queue_eh_work = true;
6044 if (hba->errors & UFSHCD_UIC_HIBERN8_MASK) {
6046 "%s: Auto Hibern8 %s failed - status: 0x%08x, upmcrs: 0x%08x\n",
6047 __func__, (hba->errors & UIC_HIBERNATE_ENTER) ?
6049 hba->errors, ufshcd_get_upmcrs(hba));
6050 ufshcd_update_reg_hist(&hba->ufs_stats.auto_hibern8_err,
6052 ufshcd_set_link_broken(hba);
6053 queue_eh_work = true;
6056 if (queue_eh_work) {
6058 * update the transfer error masks to sticky bits, let's do this
6059 * irrespective of current ufshcd_state.
6061 hba->saved_err |= hba->errors;
6062 hba->saved_uic_err |= hba->uic_error;
6064 /* dump controller state before resetting */
6065 if ((hba->saved_err & (INT_FATAL_ERRORS)) ||
6066 (hba->saved_uic_err &&
6067 (hba->saved_uic_err != UFSHCD_UIC_PA_GENERIC_ERROR))) {
6068 dev_err(hba->dev, "%s: saved_err 0x%x saved_uic_err 0x%x\n",
6069 __func__, hba->saved_err,
6070 hba->saved_uic_err);
6071 ufshcd_dump_regs(hba, 0, UFSHCI_REG_SPACE_SIZE,
6073 ufshcd_print_pwr_info(hba);
6075 ufshcd_schedule_eh_work(hba);
6076 retval |= IRQ_HANDLED;
6079 * if (!queue_eh_work) -
6080 * Other errors are either non-fatal where host recovers
6081 * itself without s/w intervention or errors that will be
6082 * handled by the SCSI core layer.
6088 struct ufs_hba *hba;
6089 unsigned long pending;
6093 static bool ufshcd_compl_tm(struct request *req, void *priv, bool reserved)
6095 struct ctm_info *const ci = priv;
6096 struct completion *c;
6098 WARN_ON_ONCE(reserved);
6099 if (test_bit(req->tag, &ci->pending))
6102 c = req->end_io_data;
6109 * ufshcd_tmc_handler - handle task management function completion
6110 * @hba: per adapter instance
6113 * IRQ_HANDLED - If interrupt is valid
6114 * IRQ_NONE - If invalid interrupt
6116 static irqreturn_t ufshcd_tmc_handler(struct ufs_hba *hba)
6118 struct request_queue *q = hba->tmf_queue;
6119 struct ctm_info ci = {
6121 .pending = ufshcd_readl(hba, REG_UTP_TASK_REQ_DOOR_BELL),
6124 blk_mq_tagset_busy_iter(q->tag_set, ufshcd_compl_tm, &ci);
6125 return ci.ncpl ? IRQ_HANDLED : IRQ_NONE;
6129 * ufshcd_sl_intr - Interrupt service routine
6130 * @hba: per adapter instance
6131 * @intr_status: contains interrupts generated by the controller
6134 * IRQ_HANDLED - If interrupt is valid
6135 * IRQ_NONE - If invalid interrupt
6137 static irqreturn_t ufshcd_sl_intr(struct ufs_hba *hba, u32 intr_status)
6139 irqreturn_t retval = IRQ_NONE;
6141 hba->errors = UFSHCD_ERROR_MASK & intr_status;
6143 if (ufshcd_is_auto_hibern8_error(hba, intr_status))
6144 hba->errors |= (UFSHCD_UIC_HIBERN8_MASK & intr_status);
6147 retval |= ufshcd_check_errors(hba);
6149 if (intr_status & UFSHCD_UIC_MASK)
6150 retval |= ufshcd_uic_cmd_compl(hba, intr_status);
6152 if (intr_status & UTP_TASK_REQ_COMPL)
6153 retval |= ufshcd_tmc_handler(hba);
6155 if (intr_status & UTP_TRANSFER_REQ_COMPL)
6156 retval |= ufshcd_transfer_req_compl(hba);
6162 * ufshcd_intr - Main interrupt service routine
6164 * @__hba: pointer to adapter instance
6167 * IRQ_HANDLED - If interrupt is valid
6168 * IRQ_NONE - If invalid interrupt
6170 static irqreturn_t ufshcd_intr(int irq, void *__hba)
6172 u32 intr_status, enabled_intr_status = 0;
6173 irqreturn_t retval = IRQ_NONE;
6174 struct ufs_hba *hba = __hba;
6175 int retries = hba->nutrs;
6177 spin_lock(hba->host->host_lock);
6178 intr_status = ufshcd_readl(hba, REG_INTERRUPT_STATUS);
6179 hba->ufs_stats.last_intr_status = intr_status;
6180 hba->ufs_stats.last_intr_ts = ktime_get();
6183 * There could be max of hba->nutrs reqs in flight and in worst case
6184 * if the reqs get finished 1 by 1 after the interrupt status is
6185 * read, make sure we handle them by checking the interrupt status
6186 * again in a loop until we process all of the reqs before returning.
6188 while (intr_status && retries--) {
6189 enabled_intr_status =
6190 intr_status & ufshcd_readl(hba, REG_INTERRUPT_ENABLE);
6192 ufshcd_writel(hba, intr_status, REG_INTERRUPT_STATUS);
6193 if (enabled_intr_status)
6194 retval |= ufshcd_sl_intr(hba, enabled_intr_status);
6196 intr_status = ufshcd_readl(hba, REG_INTERRUPT_STATUS);
6199 if (enabled_intr_status && retval == IRQ_NONE) {
6200 dev_err(hba->dev, "%s: Unhandled interrupt 0x%08x\n",
6201 __func__, intr_status);
6202 ufshcd_dump_regs(hba, 0, UFSHCI_REG_SPACE_SIZE, "host_regs: ");
6205 spin_unlock(hba->host->host_lock);
6209 static int ufshcd_clear_tm_cmd(struct ufs_hba *hba, int tag)
6212 u32 mask = 1 << tag;
6213 unsigned long flags;
6215 if (!test_bit(tag, &hba->outstanding_tasks))
6218 spin_lock_irqsave(hba->host->host_lock, flags);
6219 ufshcd_utmrl_clear(hba, tag);
6220 spin_unlock_irqrestore(hba->host->host_lock, flags);
6222 /* poll for max. 1 sec to clear door bell register by h/w */
6223 err = ufshcd_wait_for_register(hba,
6224 REG_UTP_TASK_REQ_DOOR_BELL,
6225 mask, 0, 1000, 1000);
6230 static int __ufshcd_issue_tm_cmd(struct ufs_hba *hba,
6231 struct utp_task_req_desc *treq, u8 tm_function)
6233 struct request_queue *q = hba->tmf_queue;
6234 struct Scsi_Host *host = hba->host;
6235 DECLARE_COMPLETION_ONSTACK(wait);
6236 struct request *req;
6237 unsigned long flags;
6238 int free_slot, task_tag, err;
6241 * Get free slot, sleep if slots are unavailable.
6242 * Even though we use wait_event() which sleeps indefinitely,
6243 * the maximum wait time is bounded by %TM_CMD_TIMEOUT.
6245 req = blk_get_request(q, REQ_OP_DRV_OUT, BLK_MQ_REQ_RESERVED);
6246 req->end_io_data = &wait;
6247 free_slot = req->tag;
6248 WARN_ON_ONCE(free_slot < 0 || free_slot >= hba->nutmrs);
6249 ufshcd_hold(hba, false);
6251 spin_lock_irqsave(host->host_lock, flags);
6252 task_tag = hba->nutrs + free_slot;
6254 treq->req_header.dword_0 |= cpu_to_be32(task_tag);
6256 memcpy(hba->utmrdl_base_addr + free_slot, treq, sizeof(*treq));
6257 ufshcd_vops_setup_task_mgmt(hba, free_slot, tm_function);
6259 /* send command to the controller */
6260 __set_bit(free_slot, &hba->outstanding_tasks);
6262 /* Make sure descriptors are ready before ringing the task doorbell */
6265 ufshcd_writel(hba, 1 << free_slot, REG_UTP_TASK_REQ_DOOR_BELL);
6266 /* Make sure that doorbell is committed immediately */
6269 spin_unlock_irqrestore(host->host_lock, flags);
6271 ufshcd_add_tm_upiu_trace(hba, task_tag, "tm_send");
6273 /* wait until the task management command is completed */
6274 err = wait_for_completion_io_timeout(&wait,
6275 msecs_to_jiffies(TM_CMD_TIMEOUT));
6278 * Make sure that ufshcd_compl_tm() does not trigger a
6281 req->end_io_data = NULL;
6282 ufshcd_add_tm_upiu_trace(hba, task_tag, "tm_complete_err");
6283 dev_err(hba->dev, "%s: task management cmd 0x%.2x timed-out\n",
6284 __func__, tm_function);
6285 if (ufshcd_clear_tm_cmd(hba, free_slot))
6286 dev_WARN(hba->dev, "%s: unable clear tm cmd (slot %d) after timeout\n",
6287 __func__, free_slot);
6291 memcpy(treq, hba->utmrdl_base_addr + free_slot, sizeof(*treq));
6293 ufshcd_add_tm_upiu_trace(hba, task_tag, "tm_complete");
6296 spin_lock_irqsave(hba->host->host_lock, flags);
6297 __clear_bit(free_slot, &hba->outstanding_tasks);
6298 spin_unlock_irqrestore(hba->host->host_lock, flags);
6300 blk_put_request(req);
6302 ufshcd_release(hba);
6307 * ufshcd_issue_tm_cmd - issues task management commands to controller
6308 * @hba: per adapter instance
6309 * @lun_id: LUN ID to which TM command is sent
6310 * @task_id: task ID to which the TM command is applicable
6311 * @tm_function: task management function opcode
6312 * @tm_response: task management service response return value
6314 * Returns non-zero value on error, zero on success.
6316 static int ufshcd_issue_tm_cmd(struct ufs_hba *hba, int lun_id, int task_id,
6317 u8 tm_function, u8 *tm_response)
6319 struct utp_task_req_desc treq = { { 0 }, };
6322 /* Configure task request descriptor */
6323 treq.header.dword_0 = cpu_to_le32(UTP_REQ_DESC_INT_CMD);
6324 treq.header.dword_2 = cpu_to_le32(OCS_INVALID_COMMAND_STATUS);
6326 /* Configure task request UPIU */
6327 treq.req_header.dword_0 = cpu_to_be32(lun_id << 8) |
6328 cpu_to_be32(UPIU_TRANSACTION_TASK_REQ << 24);
6329 treq.req_header.dword_1 = cpu_to_be32(tm_function << 16);
6332 * The host shall provide the same value for LUN field in the basic
6333 * header and for Input Parameter.
6335 treq.input_param1 = cpu_to_be32(lun_id);
6336 treq.input_param2 = cpu_to_be32(task_id);
6338 err = __ufshcd_issue_tm_cmd(hba, &treq, tm_function);
6339 if (err == -ETIMEDOUT)
6342 ocs_value = le32_to_cpu(treq.header.dword_2) & MASK_OCS;
6343 if (ocs_value != OCS_SUCCESS)
6344 dev_err(hba->dev, "%s: failed, ocs = 0x%x\n",
6345 __func__, ocs_value);
6346 else if (tm_response)
6347 *tm_response = be32_to_cpu(treq.output_param1) &
6348 MASK_TM_SERVICE_RESP;
6353 * ufshcd_issue_devman_upiu_cmd - API for sending "utrd" type requests
6354 * @hba: per-adapter instance
6355 * @req_upiu: upiu request
6356 * @rsp_upiu: upiu reply
6357 * @desc_buff: pointer to descriptor buffer, NULL if NA
6358 * @buff_len: descriptor size, 0 if NA
6359 * @cmd_type: specifies the type (NOP, Query...)
6360 * @desc_op: descriptor operation
6362 * Those type of requests uses UTP Transfer Request Descriptor - utrd.
6363 * Therefore, it "rides" the device management infrastructure: uses its tag and
6364 * tasks work queues.
6366 * Since there is only one available tag for device management commands,
6367 * the caller is expected to hold the hba->dev_cmd.lock mutex.
6369 static int ufshcd_issue_devman_upiu_cmd(struct ufs_hba *hba,
6370 struct utp_upiu_req *req_upiu,
6371 struct utp_upiu_req *rsp_upiu,
6372 u8 *desc_buff, int *buff_len,
6373 enum dev_cmd_type cmd_type,
6374 enum query_opcode desc_op)
6376 struct request_queue *q = hba->cmd_queue;
6377 struct request *req;
6378 struct ufshcd_lrb *lrbp;
6381 struct completion wait;
6382 unsigned long flags;
6385 down_read(&hba->clk_scaling_lock);
6387 req = blk_get_request(q, REQ_OP_DRV_OUT, 0);
6393 WARN_ON_ONCE(!ufshcd_valid_tag(hba, tag));
6395 init_completion(&wait);
6396 lrbp = &hba->lrb[tag];
6400 lrbp->sense_bufflen = 0;
6401 lrbp->sense_buffer = NULL;
6402 lrbp->task_tag = tag;
6404 lrbp->intr_cmd = true;
6405 ufshcd_prepare_lrbp_crypto(NULL, lrbp);
6406 hba->dev_cmd.type = cmd_type;
6408 switch (hba->ufs_version) {
6409 case UFSHCI_VERSION_10:
6410 case UFSHCI_VERSION_11:
6411 lrbp->command_type = UTP_CMD_TYPE_DEV_MANAGE;
6414 lrbp->command_type = UTP_CMD_TYPE_UFS_STORAGE;
6418 /* update the task tag in the request upiu */
6419 req_upiu->header.dword_0 |= cpu_to_be32(tag);
6421 ufshcd_prepare_req_desc_hdr(lrbp, &upiu_flags, DMA_NONE);
6423 /* just copy the upiu request as it is */
6424 memcpy(lrbp->ucd_req_ptr, req_upiu, sizeof(*lrbp->ucd_req_ptr));
6425 if (desc_buff && desc_op == UPIU_QUERY_OPCODE_WRITE_DESC) {
6426 /* The Data Segment Area is optional depending upon the query
6427 * function value. for WRITE DESCRIPTOR, the data segment
6428 * follows right after the tsf.
6430 memcpy(lrbp->ucd_req_ptr + 1, desc_buff, *buff_len);
6434 memset(lrbp->ucd_rsp_ptr, 0, sizeof(struct utp_upiu_rsp));
6436 hba->dev_cmd.complete = &wait;
6438 /* Make sure descriptors are ready before ringing the doorbell */
6440 spin_lock_irqsave(hba->host->host_lock, flags);
6441 ufshcd_send_command(hba, tag);
6442 spin_unlock_irqrestore(hba->host->host_lock, flags);
6445 * ignore the returning value here - ufshcd_check_query_response is
6446 * bound to fail since dev_cmd.query and dev_cmd.type were left empty.
6447 * read the response directly ignoring all errors.
6449 ufshcd_wait_for_dev_cmd(hba, lrbp, QUERY_REQ_TIMEOUT);
6451 /* just copy the upiu response as it is */
6452 memcpy(rsp_upiu, lrbp->ucd_rsp_ptr, sizeof(*rsp_upiu));
6453 if (desc_buff && desc_op == UPIU_QUERY_OPCODE_READ_DESC) {
6454 u8 *descp = (u8 *)lrbp->ucd_rsp_ptr + sizeof(*rsp_upiu);
6455 u16 resp_len = be32_to_cpu(lrbp->ucd_rsp_ptr->header.dword_2) &
6456 MASK_QUERY_DATA_SEG_LEN;
6458 if (*buff_len >= resp_len) {
6459 memcpy(desc_buff, descp, resp_len);
6460 *buff_len = resp_len;
6463 "%s: rsp size %d is bigger than buffer size %d",
6464 __func__, resp_len, *buff_len);
6470 blk_put_request(req);
6472 up_read(&hba->clk_scaling_lock);
6477 * ufshcd_exec_raw_upiu_cmd - API function for sending raw upiu commands
6478 * @hba: per-adapter instance
6479 * @req_upiu: upiu request
6480 * @rsp_upiu: upiu reply - only 8 DW as we do not support scsi commands
6481 * @msgcode: message code, one of UPIU Transaction Codes Initiator to Target
6482 * @desc_buff: pointer to descriptor buffer, NULL if NA
6483 * @buff_len: descriptor size, 0 if NA
6484 * @desc_op: descriptor operation
6486 * Supports UTP Transfer requests (nop and query), and UTP Task
6487 * Management requests.
6488 * It is up to the caller to fill the upiu conent properly, as it will
6489 * be copied without any further input validations.
6491 int ufshcd_exec_raw_upiu_cmd(struct ufs_hba *hba,
6492 struct utp_upiu_req *req_upiu,
6493 struct utp_upiu_req *rsp_upiu,
6495 u8 *desc_buff, int *buff_len,
6496 enum query_opcode desc_op)
6499 enum dev_cmd_type cmd_type = DEV_CMD_TYPE_QUERY;
6500 struct utp_task_req_desc treq = { { 0 }, };
6502 u8 tm_f = be32_to_cpu(req_upiu->header.dword_1) >> 16 & MASK_TM_FUNC;
6505 case UPIU_TRANSACTION_NOP_OUT:
6506 cmd_type = DEV_CMD_TYPE_NOP;
6508 case UPIU_TRANSACTION_QUERY_REQ:
6509 ufshcd_hold(hba, false);
6510 mutex_lock(&hba->dev_cmd.lock);
6511 err = ufshcd_issue_devman_upiu_cmd(hba, req_upiu, rsp_upiu,
6512 desc_buff, buff_len,
6514 mutex_unlock(&hba->dev_cmd.lock);
6515 ufshcd_release(hba);
6518 case UPIU_TRANSACTION_TASK_REQ:
6519 treq.header.dword_0 = cpu_to_le32(UTP_REQ_DESC_INT_CMD);
6520 treq.header.dword_2 = cpu_to_le32(OCS_INVALID_COMMAND_STATUS);
6522 memcpy(&treq.req_header, req_upiu, sizeof(*req_upiu));
6524 err = __ufshcd_issue_tm_cmd(hba, &treq, tm_f);
6525 if (err == -ETIMEDOUT)
6528 ocs_value = le32_to_cpu(treq.header.dword_2) & MASK_OCS;
6529 if (ocs_value != OCS_SUCCESS) {
6530 dev_err(hba->dev, "%s: failed, ocs = 0x%x\n", __func__,
6535 memcpy(rsp_upiu, &treq.rsp_header, sizeof(*rsp_upiu));
6548 * ufshcd_eh_device_reset_handler - device reset handler registered to
6550 * @cmd: SCSI command pointer
6552 * Returns SUCCESS/FAILED
6554 static int ufshcd_eh_device_reset_handler(struct scsi_cmnd *cmd)
6556 struct Scsi_Host *host;
6557 struct ufs_hba *hba;
6562 struct ufshcd_lrb *lrbp;
6563 unsigned long flags;
6565 host = cmd->device->host;
6566 hba = shost_priv(host);
6567 tag = cmd->request->tag;
6569 lrbp = &hba->lrb[tag];
6570 err = ufshcd_issue_tm_cmd(hba, lrbp->lun, 0, UFS_LOGICAL_RESET, &resp);
6571 if (err || resp != UPIU_TASK_MANAGEMENT_FUNC_COMPL) {
6577 /* clear the commands that were pending for corresponding LUN */
6578 for_each_set_bit(pos, &hba->outstanding_reqs, hba->nutrs) {
6579 if (hba->lrb[pos].lun == lrbp->lun) {
6580 err = ufshcd_clear_cmd(hba, pos);
6585 spin_lock_irqsave(host->host_lock, flags);
6586 ufshcd_transfer_req_compl(hba);
6587 spin_unlock_irqrestore(host->host_lock, flags);
6590 hba->req_abort_count = 0;
6591 ufshcd_update_reg_hist(&hba->ufs_stats.dev_reset, (u32)err);
6595 dev_err(hba->dev, "%s: failed with err %d\n", __func__, err);
6601 static void ufshcd_set_req_abort_skip(struct ufs_hba *hba, unsigned long bitmap)
6603 struct ufshcd_lrb *lrbp;
6606 for_each_set_bit(tag, &bitmap, hba->nutrs) {
6607 lrbp = &hba->lrb[tag];
6608 lrbp->req_abort_skip = true;
6613 * ufshcd_try_to_abort_task - abort a specific task
6614 * @cmd: SCSI command pointer
6616 * Abort the pending command in device by sending UFS_ABORT_TASK task management
6617 * command, and in host controller by clearing the door-bell register. There can
6618 * be race between controller sending the command to the device while abort is
6619 * issued. To avoid that, first issue UFS_QUERY_TASK to check if the command is
6620 * really issued and then try to abort it.
6622 * Returns zero on success, non-zero on failure
6624 static int ufshcd_try_to_abort_task(struct ufs_hba *hba, int tag)
6626 struct ufshcd_lrb *lrbp = &hba->lrb[tag];
6632 for (poll_cnt = 100; poll_cnt; poll_cnt--) {
6633 err = ufshcd_issue_tm_cmd(hba, lrbp->lun, lrbp->task_tag,
6634 UFS_QUERY_TASK, &resp);
6635 if (!err && resp == UPIU_TASK_MANAGEMENT_FUNC_SUCCEEDED) {
6636 /* cmd pending in the device */
6637 dev_err(hba->dev, "%s: cmd pending in the device. tag = %d\n",
6640 } else if (!err && resp == UPIU_TASK_MANAGEMENT_FUNC_COMPL) {
6642 * cmd not pending in the device, check if it is
6645 dev_err(hba->dev, "%s: cmd at tag %d not pending in the device.\n",
6647 reg = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
6648 if (reg & (1 << tag)) {
6649 /* sleep for max. 200us to stabilize */
6650 usleep_range(100, 200);
6653 /* command completed already */
6654 dev_err(hba->dev, "%s: cmd at tag %d successfully cleared from DB.\n",
6659 "%s: no response from device. tag = %d, err %d\n",
6660 __func__, tag, err);
6662 err = resp; /* service response error */
6672 err = ufshcd_issue_tm_cmd(hba, lrbp->lun, lrbp->task_tag,
6673 UFS_ABORT_TASK, &resp);
6674 if (err || resp != UPIU_TASK_MANAGEMENT_FUNC_COMPL) {
6676 err = resp; /* service response error */
6677 dev_err(hba->dev, "%s: issued. tag = %d, err %d\n",
6678 __func__, tag, err);
6683 err = ufshcd_clear_cmd(hba, tag);
6685 dev_err(hba->dev, "%s: Failed clearing cmd at tag %d, err %d\n",
6686 __func__, tag, err);
6693 * ufshcd_abort - scsi host template eh_abort_handler callback
6694 * @cmd: SCSI command pointer
6696 * Returns SUCCESS/FAILED
6698 static int ufshcd_abort(struct scsi_cmnd *cmd)
6700 struct Scsi_Host *host;
6701 struct ufs_hba *hba;
6702 unsigned long flags;
6705 struct ufshcd_lrb *lrbp;
6708 host = cmd->device->host;
6709 hba = shost_priv(host);
6710 tag = cmd->request->tag;
6711 lrbp = &hba->lrb[tag];
6712 if (!ufshcd_valid_tag(hba, tag)) {
6714 "%s: invalid command tag %d: cmd=0x%p, cmd->request=0x%p",
6715 __func__, tag, cmd, cmd->request);
6720 * Task abort to the device W-LUN is illegal. When this command
6721 * will fail, due to spec violation, scsi err handling next step
6722 * will be to send LU reset which, again, is a spec violation.
6723 * To avoid these unnecessary/illegal step we skip to the last error
6724 * handling stage: reset and restore.
6726 if (lrbp->lun == UFS_UPIU_UFS_DEVICE_WLUN)
6727 return ufshcd_eh_host_reset_handler(cmd);
6729 ufshcd_hold(hba, false);
6730 reg = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
6731 /* If command is already aborted/completed, return SUCCESS */
6732 if (!(test_bit(tag, &hba->outstanding_reqs))) {
6734 "%s: cmd at tag %d already completed, outstanding=0x%lx, doorbell=0x%x\n",
6735 __func__, tag, hba->outstanding_reqs, reg);
6739 /* Print Transfer Request of aborted task */
6740 dev_info(hba->dev, "%s: Device abort task at tag %d\n", __func__, tag);
6743 * Print detailed info about aborted request.
6744 * As more than one request might get aborted at the same time,
6745 * print full information only for the first aborted request in order
6746 * to reduce repeated printouts. For other aborted requests only print
6749 scsi_print_command(hba->lrb[tag].cmd);
6750 if (!hba->req_abort_count) {
6751 ufshcd_update_reg_hist(&hba->ufs_stats.task_abort, 0);
6752 ufshcd_print_host_regs(hba);
6753 ufshcd_print_host_state(hba);
6754 ufshcd_print_pwr_info(hba);
6755 ufshcd_print_trs(hba, 1 << tag, true);
6757 ufshcd_print_trs(hba, 1 << tag, false);
6759 hba->req_abort_count++;
6761 if (!(reg & (1 << tag))) {
6763 "%s: cmd was completed, but without a notifying intr, tag = %d",
6768 /* Skip task abort in case previous aborts failed and report failure */
6769 if (lrbp->req_abort_skip)
6772 err = ufshcd_try_to_abort_task(hba, tag);
6776 spin_lock_irqsave(host->host_lock, flags);
6777 __ufshcd_transfer_req_compl(hba, (1UL << tag));
6778 spin_unlock_irqrestore(host->host_lock, flags);
6782 dev_err(hba->dev, "%s: failed with err %d\n", __func__, err);
6783 ufshcd_set_req_abort_skip(hba, hba->outstanding_reqs);
6788 * This ufshcd_release() corresponds to the original scsi cmd that got
6789 * aborted here (as we won't get any IRQ for it).
6791 ufshcd_release(hba);
6796 * ufshcd_host_reset_and_restore - reset and restore host controller
6797 * @hba: per-adapter instance
6799 * Note that host controller reset may issue DME_RESET to
6800 * local and remote (device) Uni-Pro stack and the attributes
6801 * are reset to default state.
6803 * Returns zero on success, non-zero on failure
6805 static int ufshcd_host_reset_and_restore(struct ufs_hba *hba)
6808 unsigned long flags;
6811 * Stop the host controller and complete the requests
6814 ufshcd_hba_stop(hba);
6816 spin_lock_irqsave(hba->host->host_lock, flags);
6817 hba->silence_err_logs = true;
6818 ufshcd_complete_requests(hba);
6819 hba->silence_err_logs = false;
6820 spin_unlock_irqrestore(hba->host->host_lock, flags);
6822 /* scale up clocks to max frequency before full reinitialization */
6823 ufshcd_set_clk_freq(hba, true);
6825 err = ufshcd_hba_enable(hba);
6829 /* Establish the link again and restore the device */
6830 err = ufshcd_probe_hba(hba, false);
6834 dev_err(hba->dev, "%s: Host init failed %d\n", __func__, err);
6835 ufshcd_update_reg_hist(&hba->ufs_stats.host_reset, (u32)err);
6840 * ufshcd_reset_and_restore - reset and re-initialize host/device
6841 * @hba: per-adapter instance
6843 * Reset and recover device, host and re-establish link. This
6844 * is helpful to recover the communication in fatal error conditions.
6846 * Returns zero on success, non-zero on failure
6848 static int ufshcd_reset_and_restore(struct ufs_hba *hba)
6853 unsigned long flags;
6854 int retries = MAX_HOST_RESET_RETRIES;
6857 * This is a fresh start, cache and clear saved error first,
6858 * in case new error generated during reset and restore.
6860 spin_lock_irqsave(hba->host->host_lock, flags);
6861 saved_err = hba->saved_err;
6862 saved_uic_err = hba->saved_uic_err;
6864 hba->saved_uic_err = 0;
6865 spin_unlock_irqrestore(hba->host->host_lock, flags);
6868 /* Reset the attached device */
6869 ufshcd_vops_device_reset(hba);
6871 err = ufshcd_host_reset_and_restore(hba);
6872 } while (err && --retries);
6874 spin_lock_irqsave(hba->host->host_lock, flags);
6876 * Inform scsi mid-layer that we did reset and allow to handle
6877 * Unit Attention properly.
6879 scsi_report_bus_reset(hba->host, 0);
6881 hba->saved_err |= saved_err;
6882 hba->saved_uic_err |= saved_uic_err;
6884 spin_unlock_irqrestore(hba->host->host_lock, flags);
6890 * ufshcd_eh_host_reset_handler - host reset handler registered to scsi layer
6891 * @cmd: SCSI command pointer
6893 * Returns SUCCESS/FAILED
6895 static int ufshcd_eh_host_reset_handler(struct scsi_cmnd *cmd)
6898 unsigned long flags;
6899 struct ufs_hba *hba;
6901 hba = shost_priv(cmd->device->host);
6903 spin_lock_irqsave(hba->host->host_lock, flags);
6904 hba->force_reset = true;
6905 ufshcd_schedule_eh_work(hba);
6906 dev_err(hba->dev, "%s: reset in progress - 1\n", __func__);
6907 spin_unlock_irqrestore(hba->host->host_lock, flags);
6909 flush_work(&hba->eh_work);
6911 spin_lock_irqsave(hba->host->host_lock, flags);
6912 if (hba->ufshcd_state == UFSHCD_STATE_ERROR)
6914 spin_unlock_irqrestore(hba->host->host_lock, flags);
6920 * ufshcd_get_max_icc_level - calculate the ICC level
6921 * @sup_curr_uA: max. current supported by the regulator
6922 * @start_scan: row at the desc table to start scan from
6923 * @buff: power descriptor buffer
6925 * Returns calculated max ICC level for specific regulator
6927 static u32 ufshcd_get_max_icc_level(int sup_curr_uA, u32 start_scan, char *buff)
6934 for (i = start_scan; i >= 0; i--) {
6935 data = be16_to_cpup((__be16 *)&buff[2 * i]);
6936 unit = (data & ATTR_ICC_LVL_UNIT_MASK) >>
6937 ATTR_ICC_LVL_UNIT_OFFSET;
6938 curr_uA = data & ATTR_ICC_LVL_VALUE_MASK;
6940 case UFSHCD_NANO_AMP:
6941 curr_uA = curr_uA / 1000;
6943 case UFSHCD_MILI_AMP:
6944 curr_uA = curr_uA * 1000;
6947 curr_uA = curr_uA * 1000 * 1000;
6949 case UFSHCD_MICRO_AMP:
6953 if (sup_curr_uA >= curr_uA)
6958 pr_err("%s: Couldn't find valid icc_level = %d", __func__, i);
6965 * ufshcd_calc_icc_level - calculate the max ICC level
6966 * In case regulators are not initialized we'll return 0
6967 * @hba: per-adapter instance
6968 * @desc_buf: power descriptor buffer to extract ICC levels from.
6969 * @len: length of desc_buff
6971 * Returns calculated ICC level
6973 static u32 ufshcd_find_max_sup_active_icc_level(struct ufs_hba *hba,
6974 u8 *desc_buf, int len)
6978 if (!hba->vreg_info.vcc || !hba->vreg_info.vccq ||
6979 !hba->vreg_info.vccq2) {
6981 "%s: Regulator capability was not set, actvIccLevel=%d",
6982 __func__, icc_level);
6986 if (hba->vreg_info.vcc && hba->vreg_info.vcc->max_uA)
6987 icc_level = ufshcd_get_max_icc_level(
6988 hba->vreg_info.vcc->max_uA,
6989 POWER_DESC_MAX_ACTV_ICC_LVLS - 1,
6990 &desc_buf[PWR_DESC_ACTIVE_LVLS_VCC_0]);
6992 if (hba->vreg_info.vccq && hba->vreg_info.vccq->max_uA)
6993 icc_level = ufshcd_get_max_icc_level(
6994 hba->vreg_info.vccq->max_uA,
6996 &desc_buf[PWR_DESC_ACTIVE_LVLS_VCCQ_0]);
6998 if (hba->vreg_info.vccq2 && hba->vreg_info.vccq2->max_uA)
6999 icc_level = ufshcd_get_max_icc_level(
7000 hba->vreg_info.vccq2->max_uA,
7002 &desc_buf[PWR_DESC_ACTIVE_LVLS_VCCQ2_0]);
7007 static void ufshcd_set_active_icc_lvl(struct ufs_hba *hba)
7010 int buff_len = hba->desc_size[QUERY_DESC_IDN_POWER];
7014 desc_buf = kmalloc(buff_len, GFP_KERNEL);
7018 ret = ufshcd_read_desc_param(hba, QUERY_DESC_IDN_POWER, 0, 0,
7019 desc_buf, buff_len);
7022 "%s: Failed reading power descriptor.len = %d ret = %d",
7023 __func__, buff_len, ret);
7027 icc_level = ufshcd_find_max_sup_active_icc_level(hba, desc_buf,
7029 dev_dbg(hba->dev, "%s: setting icc_level 0x%x", __func__, icc_level);
7031 ret = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_WRITE_ATTR,
7032 QUERY_ATTR_IDN_ACTIVE_ICC_LVL, 0, 0, &icc_level);
7036 "%s: Failed configuring bActiveICCLevel = %d ret = %d",
7037 __func__, icc_level, ret);
7043 static inline void ufshcd_blk_pm_runtime_init(struct scsi_device *sdev)
7045 scsi_autopm_get_device(sdev);
7046 blk_pm_runtime_init(sdev->request_queue, &sdev->sdev_gendev);
7047 if (sdev->rpm_autosuspend)
7048 pm_runtime_set_autosuspend_delay(&sdev->sdev_gendev,
7049 RPM_AUTOSUSPEND_DELAY_MS);
7050 scsi_autopm_put_device(sdev);
7054 * ufshcd_scsi_add_wlus - Adds required W-LUs
7055 * @hba: per-adapter instance
7057 * UFS device specification requires the UFS devices to support 4 well known
7059 * "REPORT_LUNS" (address: 01h)
7060 * "UFS Device" (address: 50h)
7061 * "RPMB" (address: 44h)
7062 * "BOOT" (address: 30h)
7063 * UFS device's power management needs to be controlled by "POWER CONDITION"
7064 * field of SSU (START STOP UNIT) command. But this "power condition" field
7065 * will take effect only when its sent to "UFS device" well known logical unit
7066 * hence we require the scsi_device instance to represent this logical unit in
7067 * order for the UFS host driver to send the SSU command for power management.
7069 * We also require the scsi_device instance for "RPMB" (Replay Protected Memory
7070 * Block) LU so user space process can control this LU. User space may also
7071 * want to have access to BOOT LU.
7073 * This function adds scsi device instances for each of all well known LUs
7074 * (except "REPORT LUNS" LU).
7076 * Returns zero on success (all required W-LUs are added successfully),
7077 * non-zero error value on failure (if failed to add any of the required W-LU).
7079 static int ufshcd_scsi_add_wlus(struct ufs_hba *hba)
7082 struct scsi_device *sdev_rpmb;
7083 struct scsi_device *sdev_boot;
7085 hba->sdev_ufs_device = __scsi_add_device(hba->host, 0, 0,
7086 ufshcd_upiu_wlun_to_scsi_wlun(UFS_UPIU_UFS_DEVICE_WLUN), NULL);
7087 if (IS_ERR(hba->sdev_ufs_device)) {
7088 ret = PTR_ERR(hba->sdev_ufs_device);
7089 hba->sdev_ufs_device = NULL;
7092 ufshcd_blk_pm_runtime_init(hba->sdev_ufs_device);
7093 scsi_device_put(hba->sdev_ufs_device);
7095 sdev_rpmb = __scsi_add_device(hba->host, 0, 0,
7096 ufshcd_upiu_wlun_to_scsi_wlun(UFS_UPIU_RPMB_WLUN), NULL);
7097 if (IS_ERR(sdev_rpmb)) {
7098 ret = PTR_ERR(sdev_rpmb);
7099 goto remove_sdev_ufs_device;
7101 ufshcd_blk_pm_runtime_init(sdev_rpmb);
7102 scsi_device_put(sdev_rpmb);
7104 sdev_boot = __scsi_add_device(hba->host, 0, 0,
7105 ufshcd_upiu_wlun_to_scsi_wlun(UFS_UPIU_BOOT_WLUN), NULL);
7106 if (IS_ERR(sdev_boot)) {
7107 dev_err(hba->dev, "%s: BOOT WLUN not found\n", __func__);
7109 ufshcd_blk_pm_runtime_init(sdev_boot);
7110 scsi_device_put(sdev_boot);
7114 remove_sdev_ufs_device:
7115 scsi_remove_device(hba->sdev_ufs_device);
7120 static void ufshcd_wb_probe(struct ufs_hba *hba, u8 *desc_buf)
7122 struct ufs_dev_info *dev_info = &hba->dev_info;
7124 u32 d_lu_wb_buf_alloc;
7126 if (!ufshcd_is_wb_allowed(hba))
7129 * Probe WB only for UFS-2.2 and UFS-3.1 (and later) devices or
7130 * UFS devices with quirk UFS_DEVICE_QUIRK_SUPPORT_EXTENDED_FEATURES
7133 if (!(dev_info->wspecversion >= 0x310 ||
7134 dev_info->wspecversion == 0x220 ||
7135 (hba->dev_quirks & UFS_DEVICE_QUIRK_SUPPORT_EXTENDED_FEATURES)))
7138 if (hba->desc_size[QUERY_DESC_IDN_DEVICE] <
7139 DEVICE_DESC_PARAM_EXT_UFS_FEATURE_SUP + 4)
7142 dev_info->d_ext_ufs_feature_sup =
7143 get_unaligned_be32(desc_buf +
7144 DEVICE_DESC_PARAM_EXT_UFS_FEATURE_SUP);
7146 if (!(dev_info->d_ext_ufs_feature_sup & UFS_DEV_WRITE_BOOSTER_SUP))
7150 * WB may be supported but not configured while provisioning.
7151 * The spec says, in dedicated wb buffer mode,
7152 * a max of 1 lun would have wb buffer configured.
7153 * Now only shared buffer mode is supported.
7155 dev_info->b_wb_buffer_type =
7156 desc_buf[DEVICE_DESC_PARAM_WB_TYPE];
7158 dev_info->b_presrv_uspc_en =
7159 desc_buf[DEVICE_DESC_PARAM_WB_PRESRV_USRSPC_EN];
7161 if (dev_info->b_wb_buffer_type == WB_BUF_MODE_SHARED) {
7162 dev_info->d_wb_alloc_units =
7163 get_unaligned_be32(desc_buf +
7164 DEVICE_DESC_PARAM_WB_SHARED_ALLOC_UNITS);
7165 if (!dev_info->d_wb_alloc_units)
7168 for (lun = 0; lun < UFS_UPIU_MAX_WB_LUN_ID; lun++) {
7169 d_lu_wb_buf_alloc = 0;
7170 ufshcd_read_unit_desc_param(hba,
7172 UNIT_DESC_PARAM_WB_BUF_ALLOC_UNITS,
7173 (u8 *)&d_lu_wb_buf_alloc,
7174 sizeof(d_lu_wb_buf_alloc));
7175 if (d_lu_wb_buf_alloc) {
7176 dev_info->wb_dedicated_lu = lun;
7181 if (!d_lu_wb_buf_alloc)
7187 hba->caps &= ~UFSHCD_CAP_WB_EN;
7190 void ufshcd_fixup_dev_quirks(struct ufs_hba *hba, struct ufs_dev_fix *fixups)
7192 struct ufs_dev_fix *f;
7193 struct ufs_dev_info *dev_info = &hba->dev_info;
7198 for (f = fixups; f->quirk; f++) {
7199 if ((f->wmanufacturerid == dev_info->wmanufacturerid ||
7200 f->wmanufacturerid == UFS_ANY_VENDOR) &&
7201 ((dev_info->model &&
7202 STR_PRFX_EQUAL(f->model, dev_info->model)) ||
7203 !strcmp(f->model, UFS_ANY_MODEL)))
7204 hba->dev_quirks |= f->quirk;
7207 EXPORT_SYMBOL_GPL(ufshcd_fixup_dev_quirks);
7209 static void ufs_fixup_device_setup(struct ufs_hba *hba)
7211 /* fix by general quirk table */
7212 ufshcd_fixup_dev_quirks(hba, ufs_fixups);
7214 /* allow vendors to fix quirks */
7215 ufshcd_vops_fixup_dev_quirks(hba);
7218 static int ufs_get_device_desc(struct ufs_hba *hba)
7223 struct ufs_dev_info *dev_info = &hba->dev_info;
7225 desc_buf = kmalloc(QUERY_DESC_MAX_SIZE, GFP_KERNEL);
7231 err = ufshcd_read_desc_param(hba, QUERY_DESC_IDN_DEVICE, 0, 0, desc_buf,
7232 hba->desc_size[QUERY_DESC_IDN_DEVICE]);
7234 dev_err(hba->dev, "%s: Failed reading Device Desc. err = %d\n",
7240 * getting vendor (manufacturerID) and Bank Index in big endian
7243 dev_info->wmanufacturerid = desc_buf[DEVICE_DESC_PARAM_MANF_ID] << 8 |
7244 desc_buf[DEVICE_DESC_PARAM_MANF_ID + 1];
7246 /* getting Specification Version in big endian format */
7247 dev_info->wspecversion = desc_buf[DEVICE_DESC_PARAM_SPEC_VER] << 8 |
7248 desc_buf[DEVICE_DESC_PARAM_SPEC_VER + 1];
7250 model_index = desc_buf[DEVICE_DESC_PARAM_PRDCT_NAME];
7252 err = ufshcd_read_string_desc(hba, model_index,
7253 &dev_info->model, SD_ASCII_STD);
7255 dev_err(hba->dev, "%s: Failed reading Product Name. err = %d\n",
7260 ufs_fixup_device_setup(hba);
7262 ufshcd_wb_probe(hba, desc_buf);
7265 * ufshcd_read_string_desc returns size of the string
7266 * reset the error value
7275 static void ufs_put_device_desc(struct ufs_hba *hba)
7277 struct ufs_dev_info *dev_info = &hba->dev_info;
7279 kfree(dev_info->model);
7280 dev_info->model = NULL;
7284 * ufshcd_tune_pa_tactivate - Tunes PA_TActivate of local UniPro
7285 * @hba: per-adapter instance
7287 * PA_TActivate parameter can be tuned manually if UniPro version is less than
7288 * 1.61. PA_TActivate needs to be greater than or equal to peerM-PHY's
7289 * RX_MIN_ACTIVATETIME_CAPABILITY attribute. This optimal value can help reduce
7290 * the hibern8 exit latency.
7292 * Returns zero on success, non-zero error value on failure.
7294 static int ufshcd_tune_pa_tactivate(struct ufs_hba *hba)
7297 u32 peer_rx_min_activatetime = 0, tuned_pa_tactivate;
7299 ret = ufshcd_dme_peer_get(hba,
7301 RX_MIN_ACTIVATETIME_CAPABILITY,
7302 UIC_ARG_MPHY_RX_GEN_SEL_INDEX(0)),
7303 &peer_rx_min_activatetime);
7307 /* make sure proper unit conversion is applied */
7308 tuned_pa_tactivate =
7309 ((peer_rx_min_activatetime * RX_MIN_ACTIVATETIME_UNIT_US)
7310 / PA_TACTIVATE_TIME_UNIT_US);
7311 ret = ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TACTIVATE),
7312 tuned_pa_tactivate);
7319 * ufshcd_tune_pa_hibern8time - Tunes PA_Hibern8Time of local UniPro
7320 * @hba: per-adapter instance
7322 * PA_Hibern8Time parameter can be tuned manually if UniPro version is less than
7323 * 1.61. PA_Hibern8Time needs to be maximum of local M-PHY's
7324 * TX_HIBERN8TIME_CAPABILITY & peer M-PHY's RX_HIBERN8TIME_CAPABILITY.
7325 * This optimal value can help reduce the hibern8 exit latency.
7327 * Returns zero on success, non-zero error value on failure.
7329 static int ufshcd_tune_pa_hibern8time(struct ufs_hba *hba)
7332 u32 local_tx_hibern8_time_cap = 0, peer_rx_hibern8_time_cap = 0;
7333 u32 max_hibern8_time, tuned_pa_hibern8time;
7335 ret = ufshcd_dme_get(hba,
7336 UIC_ARG_MIB_SEL(TX_HIBERN8TIME_CAPABILITY,
7337 UIC_ARG_MPHY_TX_GEN_SEL_INDEX(0)),
7338 &local_tx_hibern8_time_cap);
7342 ret = ufshcd_dme_peer_get(hba,
7343 UIC_ARG_MIB_SEL(RX_HIBERN8TIME_CAPABILITY,
7344 UIC_ARG_MPHY_RX_GEN_SEL_INDEX(0)),
7345 &peer_rx_hibern8_time_cap);
7349 max_hibern8_time = max(local_tx_hibern8_time_cap,
7350 peer_rx_hibern8_time_cap);
7351 /* make sure proper unit conversion is applied */
7352 tuned_pa_hibern8time = ((max_hibern8_time * HIBERN8TIME_UNIT_US)
7353 / PA_HIBERN8_TIME_UNIT_US);
7354 ret = ufshcd_dme_set(hba, UIC_ARG_MIB(PA_HIBERN8TIME),
7355 tuned_pa_hibern8time);
7361 * ufshcd_quirk_tune_host_pa_tactivate - Ensures that host PA_TACTIVATE is
7362 * less than device PA_TACTIVATE time.
7363 * @hba: per-adapter instance
7365 * Some UFS devices require host PA_TACTIVATE to be lower than device
7366 * PA_TACTIVATE, we need to enable UFS_DEVICE_QUIRK_HOST_PA_TACTIVATE quirk
7369 * Returns zero on success, non-zero error value on failure.
7371 static int ufshcd_quirk_tune_host_pa_tactivate(struct ufs_hba *hba)
7374 u32 granularity, peer_granularity;
7375 u32 pa_tactivate, peer_pa_tactivate;
7376 u32 pa_tactivate_us, peer_pa_tactivate_us;
7377 u8 gran_to_us_table[] = {1, 4, 8, 16, 32, 100};
7379 ret = ufshcd_dme_get(hba, UIC_ARG_MIB(PA_GRANULARITY),
7384 ret = ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_GRANULARITY),
7389 if ((granularity < PA_GRANULARITY_MIN_VAL) ||
7390 (granularity > PA_GRANULARITY_MAX_VAL)) {
7391 dev_err(hba->dev, "%s: invalid host PA_GRANULARITY %d",
7392 __func__, granularity);
7396 if ((peer_granularity < PA_GRANULARITY_MIN_VAL) ||
7397 (peer_granularity > PA_GRANULARITY_MAX_VAL)) {
7398 dev_err(hba->dev, "%s: invalid device PA_GRANULARITY %d",
7399 __func__, peer_granularity);
7403 ret = ufshcd_dme_get(hba, UIC_ARG_MIB(PA_TACTIVATE), &pa_tactivate);
7407 ret = ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_TACTIVATE),
7408 &peer_pa_tactivate);
7412 pa_tactivate_us = pa_tactivate * gran_to_us_table[granularity - 1];
7413 peer_pa_tactivate_us = peer_pa_tactivate *
7414 gran_to_us_table[peer_granularity - 1];
7416 if (pa_tactivate_us > peer_pa_tactivate_us) {
7417 u32 new_peer_pa_tactivate;
7419 new_peer_pa_tactivate = pa_tactivate_us /
7420 gran_to_us_table[peer_granularity - 1];
7421 new_peer_pa_tactivate++;
7422 ret = ufshcd_dme_peer_set(hba, UIC_ARG_MIB(PA_TACTIVATE),
7423 new_peer_pa_tactivate);
7430 static void ufshcd_tune_unipro_params(struct ufs_hba *hba)
7432 if (ufshcd_is_unipro_pa_params_tuning_req(hba)) {
7433 ufshcd_tune_pa_tactivate(hba);
7434 ufshcd_tune_pa_hibern8time(hba);
7437 ufshcd_vops_apply_dev_quirks(hba);
7439 if (hba->dev_quirks & UFS_DEVICE_QUIRK_PA_TACTIVATE)
7440 /* set 1ms timeout for PA_TACTIVATE */
7441 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TACTIVATE), 10);
7443 if (hba->dev_quirks & UFS_DEVICE_QUIRK_HOST_PA_TACTIVATE)
7444 ufshcd_quirk_tune_host_pa_tactivate(hba);
7447 static void ufshcd_clear_dbg_ufs_stats(struct ufs_hba *hba)
7449 hba->ufs_stats.hibern8_exit_cnt = 0;
7450 hba->ufs_stats.last_hibern8_exit_tstamp = ktime_set(0, 0);
7451 hba->req_abort_count = 0;
7454 static int ufshcd_device_geo_params_init(struct ufs_hba *hba)
7460 buff_len = hba->desc_size[QUERY_DESC_IDN_GEOMETRY];
7461 desc_buf = kmalloc(buff_len, GFP_KERNEL);
7467 err = ufshcd_read_desc_param(hba, QUERY_DESC_IDN_GEOMETRY, 0, 0,
7468 desc_buf, buff_len);
7470 dev_err(hba->dev, "%s: Failed reading Geometry Desc. err = %d\n",
7475 if (desc_buf[GEOMETRY_DESC_PARAM_MAX_NUM_LUN] == 1)
7476 hba->dev_info.max_lu_supported = 32;
7477 else if (desc_buf[GEOMETRY_DESC_PARAM_MAX_NUM_LUN] == 0)
7478 hba->dev_info.max_lu_supported = 8;
7485 static struct ufs_ref_clk ufs_ref_clk_freqs[] = {
7486 {19200000, REF_CLK_FREQ_19_2_MHZ},
7487 {26000000, REF_CLK_FREQ_26_MHZ},
7488 {38400000, REF_CLK_FREQ_38_4_MHZ},
7489 {52000000, REF_CLK_FREQ_52_MHZ},
7490 {0, REF_CLK_FREQ_INVAL},
7493 static enum ufs_ref_clk_freq
7494 ufs_get_bref_clk_from_hz(unsigned long freq)
7498 for (i = 0; ufs_ref_clk_freqs[i].freq_hz; i++)
7499 if (ufs_ref_clk_freqs[i].freq_hz == freq)
7500 return ufs_ref_clk_freqs[i].val;
7502 return REF_CLK_FREQ_INVAL;
7505 void ufshcd_parse_dev_ref_clk_freq(struct ufs_hba *hba, struct clk *refclk)
7509 freq = clk_get_rate(refclk);
7511 hba->dev_ref_clk_freq =
7512 ufs_get_bref_clk_from_hz(freq);
7514 if (hba->dev_ref_clk_freq == REF_CLK_FREQ_INVAL)
7516 "invalid ref_clk setting = %ld\n", freq);
7519 static int ufshcd_set_dev_ref_clk(struct ufs_hba *hba)
7523 u32 freq = hba->dev_ref_clk_freq;
7525 err = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
7526 QUERY_ATTR_IDN_REF_CLK_FREQ, 0, 0, &ref_clk);
7529 dev_err(hba->dev, "failed reading bRefClkFreq. err = %d\n",
7534 if (ref_clk == freq)
7535 goto out; /* nothing to update */
7537 err = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_WRITE_ATTR,
7538 QUERY_ATTR_IDN_REF_CLK_FREQ, 0, 0, &freq);
7541 dev_err(hba->dev, "bRefClkFreq setting to %lu Hz failed\n",
7542 ufs_ref_clk_freqs[freq].freq_hz);
7546 dev_dbg(hba->dev, "bRefClkFreq setting to %lu Hz succeeded\n",
7547 ufs_ref_clk_freqs[freq].freq_hz);
7553 static int ufshcd_device_params_init(struct ufs_hba *hba)
7558 /* Init device descriptor sizes */
7559 for (i = 0; i < QUERY_DESC_IDN_MAX; i++)
7560 hba->desc_size[i] = QUERY_DESC_MAX_SIZE;
7562 /* Init UFS geometry descriptor related parameters */
7563 ret = ufshcd_device_geo_params_init(hba);
7567 /* Check and apply UFS device quirks */
7568 ret = ufs_get_device_desc(hba);
7570 dev_err(hba->dev, "%s: Failed getting device info. err = %d\n",
7575 ufshcd_get_ref_clk_gating_wait(hba);
7577 if (!ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_READ_FLAG,
7578 QUERY_FLAG_IDN_PWR_ON_WPE, 0, &flag))
7579 hba->dev_info.f_power_on_wp_en = flag;
7581 /* Probe maximum power mode co-supported by both UFS host and device */
7582 if (ufshcd_get_max_pwr_mode(hba))
7584 "%s: Failed getting max supported power mode\n",
7591 * ufshcd_add_lus - probe and add UFS logical units
7592 * @hba: per-adapter instance
7594 static int ufshcd_add_lus(struct ufs_hba *hba)
7598 /* Add required well known logical units to scsi mid layer */
7599 ret = ufshcd_scsi_add_wlus(hba);
7603 /* Initialize devfreq after UFS device is detected */
7604 if (ufshcd_is_clkscaling_supported(hba)) {
7605 memcpy(&hba->clk_scaling.saved_pwr_info.info,
7607 sizeof(struct ufs_pa_layer_attr));
7608 hba->clk_scaling.saved_pwr_info.is_valid = true;
7609 if (!hba->devfreq) {
7610 ret = ufshcd_devfreq_init(hba);
7615 hba->clk_scaling.is_allowed = true;
7619 scsi_scan_host(hba->host);
7620 pm_runtime_put_sync(hba->dev);
7627 * ufshcd_probe_hba - probe hba to detect device and initialize
7628 * @hba: per-adapter instance
7629 * @async: asynchronous execution or not
7631 * Execute link-startup and verify device initialization
7633 static int ufshcd_probe_hba(struct ufs_hba *hba, bool async)
7636 unsigned long flags;
7637 ktime_t start = ktime_get();
7639 ret = ufshcd_link_startup(hba);
7643 /* Debug counters initialization */
7644 ufshcd_clear_dbg_ufs_stats(hba);
7646 /* UniPro link is active now */
7647 ufshcd_set_link_active(hba);
7649 /* Verify device initialization by sending NOP OUT UPIU */
7650 ret = ufshcd_verify_dev_init(hba);
7654 /* Initiate UFS initialization, and waiting until completion */
7655 ret = ufshcd_complete_dev_init(hba);
7660 * Initialize UFS device parameters used by driver, these
7661 * parameters are associated with UFS descriptors.
7664 ret = ufshcd_device_params_init(hba);
7669 ufshcd_tune_unipro_params(hba);
7671 /* UFS device is also active now */
7672 ufshcd_set_ufs_dev_active(hba);
7673 ufshcd_force_reset_auto_bkops(hba);
7674 hba->wlun_dev_clr_ua = true;
7676 /* Gear up to HS gear if supported */
7677 if (hba->max_pwr_info.is_valid) {
7679 * Set the right value to bRefClkFreq before attempting to
7680 * switch to HS gears.
7682 if (hba->dev_ref_clk_freq != REF_CLK_FREQ_INVAL)
7683 ufshcd_set_dev_ref_clk(hba);
7684 ret = ufshcd_config_pwr_mode(hba, &hba->max_pwr_info.info);
7686 dev_err(hba->dev, "%s: Failed setting power mode, err = %d\n",
7690 ufshcd_print_pwr_info(hba);
7694 * bActiveICCLevel is volatile for UFS device (as per latest v2.1 spec)
7695 * and for removable UFS card as well, hence always set the parameter.
7696 * Note: Error handler may issue the device reset hence resetting
7697 * bActiveICCLevel as well so it is always safe to set this here.
7699 ufshcd_set_active_icc_lvl(hba);
7701 ufshcd_wb_config(hba);
7702 /* Enable Auto-Hibernate if configured */
7703 ufshcd_auto_hibern8_enable(hba);
7706 spin_lock_irqsave(hba->host->host_lock, flags);
7708 hba->ufshcd_state = UFSHCD_STATE_ERROR;
7709 else if (hba->ufshcd_state == UFSHCD_STATE_RESET)
7710 hba->ufshcd_state = UFSHCD_STATE_OPERATIONAL;
7711 spin_unlock_irqrestore(hba->host->host_lock, flags);
7713 trace_ufshcd_init(dev_name(hba->dev), ret,
7714 ktime_to_us(ktime_sub(ktime_get(), start)),
7715 hba->curr_dev_pwr_mode, hba->uic_link_state);
7720 * ufshcd_async_scan - asynchronous execution for probing hba
7721 * @data: data pointer to pass to this function
7722 * @cookie: cookie data
7724 static void ufshcd_async_scan(void *data, async_cookie_t cookie)
7726 struct ufs_hba *hba = (struct ufs_hba *)data;
7729 /* Initialize hba, detect and initialize UFS device */
7730 ret = ufshcd_probe_hba(hba, true);
7734 /* Probe and add UFS logical units */
7735 ret = ufshcd_add_lus(hba);
7738 * If we failed to initialize the device or the device is not
7739 * present, turn off the power/clocks etc.
7742 pm_runtime_put_sync(hba->dev);
7743 ufshcd_exit_clk_scaling(hba);
7744 ufshcd_hba_exit(hba);
7748 static const struct attribute_group *ufshcd_driver_groups[] = {
7749 &ufs_sysfs_unit_descriptor_group,
7750 &ufs_sysfs_lun_attributes_group,
7754 static struct ufs_hba_variant_params ufs_hba_vps = {
7755 .hba_enable_delay_us = 1000,
7756 .wb_flush_threshold = UFS_WB_BUF_REMAIN_PERCENT(40),
7757 .devfreq_profile.polling_ms = 100,
7758 .devfreq_profile.target = ufshcd_devfreq_target,
7759 .devfreq_profile.get_dev_status = ufshcd_devfreq_get_dev_status,
7760 .ondemand_data.upthreshold = 70,
7761 .ondemand_data.downdifferential = 5,
7764 static struct scsi_host_template ufshcd_driver_template = {
7765 .module = THIS_MODULE,
7767 .proc_name = UFSHCD,
7768 .queuecommand = ufshcd_queuecommand,
7769 .slave_alloc = ufshcd_slave_alloc,
7770 .slave_configure = ufshcd_slave_configure,
7771 .slave_destroy = ufshcd_slave_destroy,
7772 .change_queue_depth = ufshcd_change_queue_depth,
7773 .eh_abort_handler = ufshcd_abort,
7774 .eh_device_reset_handler = ufshcd_eh_device_reset_handler,
7775 .eh_host_reset_handler = ufshcd_eh_host_reset_handler,
7777 .sg_tablesize = SG_ALL,
7778 .cmd_per_lun = UFSHCD_CMD_PER_LUN,
7779 .can_queue = UFSHCD_CAN_QUEUE,
7780 .max_segment_size = PRDT_DATA_BYTE_COUNT_MAX,
7781 .max_host_blocked = 1,
7782 .track_queue_depth = 1,
7783 .sdev_groups = ufshcd_driver_groups,
7784 .dma_boundary = PAGE_SIZE - 1,
7785 .rpm_autosuspend_delay = RPM_AUTOSUSPEND_DELAY_MS,
7788 static int ufshcd_config_vreg_load(struct device *dev, struct ufs_vreg *vreg,
7797 * "set_load" operation shall be required on those regulators
7798 * which specifically configured current limitation. Otherwise
7799 * zero max_uA may cause unexpected behavior when regulator is
7800 * enabled or set as high power mode.
7805 ret = regulator_set_load(vreg->reg, ua);
7807 dev_err(dev, "%s: %s set load (ua=%d) failed, err=%d\n",
7808 __func__, vreg->name, ua, ret);
7814 static inline int ufshcd_config_vreg_lpm(struct ufs_hba *hba,
7815 struct ufs_vreg *vreg)
7817 return ufshcd_config_vreg_load(hba->dev, vreg, UFS_VREG_LPM_LOAD_UA);
7820 static inline int ufshcd_config_vreg_hpm(struct ufs_hba *hba,
7821 struct ufs_vreg *vreg)
7826 return ufshcd_config_vreg_load(hba->dev, vreg, vreg->max_uA);
7829 static int ufshcd_config_vreg(struct device *dev,
7830 struct ufs_vreg *vreg, bool on)
7833 struct regulator *reg;
7835 int min_uV, uA_load;
7842 if (regulator_count_voltages(reg) > 0) {
7843 uA_load = on ? vreg->max_uA : 0;
7844 ret = ufshcd_config_vreg_load(dev, vreg, uA_load);
7848 if (vreg->min_uV && vreg->max_uV) {
7849 min_uV = on ? vreg->min_uV : 0;
7850 ret = regulator_set_voltage(reg, min_uV, vreg->max_uV);
7853 "%s: %s set voltage failed, err=%d\n",
7854 __func__, name, ret);
7861 static int ufshcd_enable_vreg(struct device *dev, struct ufs_vreg *vreg)
7865 if (!vreg || vreg->enabled)
7868 ret = ufshcd_config_vreg(dev, vreg, true);
7870 ret = regulator_enable(vreg->reg);
7873 vreg->enabled = true;
7875 dev_err(dev, "%s: %s enable failed, err=%d\n",
7876 __func__, vreg->name, ret);
7881 static int ufshcd_disable_vreg(struct device *dev, struct ufs_vreg *vreg)
7885 if (!vreg || !vreg->enabled)
7888 ret = regulator_disable(vreg->reg);
7891 /* ignore errors on applying disable config */
7892 ufshcd_config_vreg(dev, vreg, false);
7893 vreg->enabled = false;
7895 dev_err(dev, "%s: %s disable failed, err=%d\n",
7896 __func__, vreg->name, ret);
7902 static int ufshcd_setup_vreg(struct ufs_hba *hba, bool on)
7905 struct device *dev = hba->dev;
7906 struct ufs_vreg_info *info = &hba->vreg_info;
7908 ret = ufshcd_toggle_vreg(dev, info->vcc, on);
7912 ret = ufshcd_toggle_vreg(dev, info->vccq, on);
7916 ret = ufshcd_toggle_vreg(dev, info->vccq2, on);
7920 ufshcd_toggle_vreg(dev, info->vccq2, false);
7921 ufshcd_toggle_vreg(dev, info->vccq, false);
7922 ufshcd_toggle_vreg(dev, info->vcc, false);
7927 static int ufshcd_setup_hba_vreg(struct ufs_hba *hba, bool on)
7929 struct ufs_vreg_info *info = &hba->vreg_info;
7931 return ufshcd_toggle_vreg(hba->dev, info->vdd_hba, on);
7934 static int ufshcd_get_vreg(struct device *dev, struct ufs_vreg *vreg)
7941 vreg->reg = devm_regulator_get(dev, vreg->name);
7942 if (IS_ERR(vreg->reg)) {
7943 ret = PTR_ERR(vreg->reg);
7944 dev_err(dev, "%s: %s get failed, err=%d\n",
7945 __func__, vreg->name, ret);
7951 static int ufshcd_init_vreg(struct ufs_hba *hba)
7954 struct device *dev = hba->dev;
7955 struct ufs_vreg_info *info = &hba->vreg_info;
7957 ret = ufshcd_get_vreg(dev, info->vcc);
7961 ret = ufshcd_get_vreg(dev, info->vccq);
7963 ret = ufshcd_get_vreg(dev, info->vccq2);
7968 static int ufshcd_init_hba_vreg(struct ufs_hba *hba)
7970 struct ufs_vreg_info *info = &hba->vreg_info;
7973 return ufshcd_get_vreg(hba->dev, info->vdd_hba);
7978 static int __ufshcd_setup_clocks(struct ufs_hba *hba, bool on,
7982 struct ufs_clk_info *clki;
7983 struct list_head *head = &hba->clk_list_head;
7984 unsigned long flags;
7985 ktime_t start = ktime_get();
7986 bool clk_state_changed = false;
7988 if (list_empty(head))
7991 ret = ufshcd_vops_setup_clocks(hba, on, PRE_CHANGE);
7995 list_for_each_entry(clki, head, list) {
7996 if (!IS_ERR_OR_NULL(clki->clk)) {
7997 if (skip_ref_clk && !strcmp(clki->name, "ref_clk"))
8000 clk_state_changed = on ^ clki->enabled;
8001 if (on && !clki->enabled) {
8002 ret = clk_prepare_enable(clki->clk);
8004 dev_err(hba->dev, "%s: %s prepare enable failed, %d\n",
8005 __func__, clki->name, ret);
8008 } else if (!on && clki->enabled) {
8009 clk_disable_unprepare(clki->clk);
8012 dev_dbg(hba->dev, "%s: clk: %s %sabled\n", __func__,
8013 clki->name, on ? "en" : "dis");
8017 ret = ufshcd_vops_setup_clocks(hba, on, POST_CHANGE);
8023 list_for_each_entry(clki, head, list) {
8024 if (!IS_ERR_OR_NULL(clki->clk) && clki->enabled)
8025 clk_disable_unprepare(clki->clk);
8027 } else if (!ret && on) {
8028 spin_lock_irqsave(hba->host->host_lock, flags);
8029 hba->clk_gating.state = CLKS_ON;
8030 trace_ufshcd_clk_gating(dev_name(hba->dev),
8031 hba->clk_gating.state);
8032 spin_unlock_irqrestore(hba->host->host_lock, flags);
8035 if (clk_state_changed)
8036 trace_ufshcd_profile_clk_gating(dev_name(hba->dev),
8037 (on ? "on" : "off"),
8038 ktime_to_us(ktime_sub(ktime_get(), start)), ret);
8042 static int ufshcd_setup_clocks(struct ufs_hba *hba, bool on)
8044 return __ufshcd_setup_clocks(hba, on, false);
8047 static int ufshcd_init_clocks(struct ufs_hba *hba)
8050 struct ufs_clk_info *clki;
8051 struct device *dev = hba->dev;
8052 struct list_head *head = &hba->clk_list_head;
8054 if (list_empty(head))
8057 list_for_each_entry(clki, head, list) {
8061 clki->clk = devm_clk_get(dev, clki->name);
8062 if (IS_ERR(clki->clk)) {
8063 ret = PTR_ERR(clki->clk);
8064 dev_err(dev, "%s: %s clk get failed, %d\n",
8065 __func__, clki->name, ret);
8070 * Parse device ref clk freq as per device tree "ref_clk".
8071 * Default dev_ref_clk_freq is set to REF_CLK_FREQ_INVAL
8072 * in ufshcd_alloc_host().
8074 if (!strcmp(clki->name, "ref_clk"))
8075 ufshcd_parse_dev_ref_clk_freq(hba, clki->clk);
8077 if (clki->max_freq) {
8078 ret = clk_set_rate(clki->clk, clki->max_freq);
8080 dev_err(hba->dev, "%s: %s clk set rate(%dHz) failed, %d\n",
8081 __func__, clki->name,
8082 clki->max_freq, ret);
8085 clki->curr_freq = clki->max_freq;
8087 dev_dbg(dev, "%s: clk: %s, rate: %lu\n", __func__,
8088 clki->name, clk_get_rate(clki->clk));
8094 static int ufshcd_variant_hba_init(struct ufs_hba *hba)
8101 err = ufshcd_vops_init(hba);
8105 err = ufshcd_vops_setup_regulators(hba, true);
8107 ufshcd_vops_exit(hba);
8110 dev_err(hba->dev, "%s: variant %s init failed err %d\n",
8111 __func__, ufshcd_get_var_name(hba), err);
8115 static void ufshcd_variant_hba_exit(struct ufs_hba *hba)
8120 ufshcd_vops_setup_regulators(hba, false);
8122 ufshcd_vops_exit(hba);
8125 static int ufshcd_hba_init(struct ufs_hba *hba)
8130 * Handle host controller power separately from the UFS device power
8131 * rails as it will help controlling the UFS host controller power
8132 * collapse easily which is different than UFS device power collapse.
8133 * Also, enable the host controller power before we go ahead with rest
8134 * of the initialization here.
8136 err = ufshcd_init_hba_vreg(hba);
8140 err = ufshcd_setup_hba_vreg(hba, true);
8144 err = ufshcd_init_clocks(hba);
8146 goto out_disable_hba_vreg;
8148 err = ufshcd_setup_clocks(hba, true);
8150 goto out_disable_hba_vreg;
8152 err = ufshcd_init_vreg(hba);
8154 goto out_disable_clks;
8156 err = ufshcd_setup_vreg(hba, true);
8158 goto out_disable_clks;
8160 err = ufshcd_variant_hba_init(hba);
8162 goto out_disable_vreg;
8164 hba->is_powered = true;
8168 ufshcd_setup_vreg(hba, false);
8170 ufshcd_setup_clocks(hba, false);
8171 out_disable_hba_vreg:
8172 ufshcd_setup_hba_vreg(hba, false);
8177 static void ufshcd_hba_exit(struct ufs_hba *hba)
8179 if (hba->is_powered) {
8180 ufshcd_variant_hba_exit(hba);
8181 ufshcd_setup_vreg(hba, false);
8182 ufshcd_suspend_clkscaling(hba);
8183 if (ufshcd_is_clkscaling_supported(hba))
8185 ufshcd_suspend_clkscaling(hba);
8186 ufshcd_setup_clocks(hba, false);
8187 ufshcd_setup_hba_vreg(hba, false);
8188 hba->is_powered = false;
8189 ufs_put_device_desc(hba);
8194 ufshcd_send_request_sense(struct ufs_hba *hba, struct scsi_device *sdp)
8196 unsigned char cmd[6] = {REQUEST_SENSE,
8205 buffer = kzalloc(UFS_SENSE_SIZE, GFP_KERNEL);
8211 ret = scsi_execute(sdp, cmd, DMA_FROM_DEVICE, buffer,
8212 UFS_SENSE_SIZE, NULL, NULL,
8213 msecs_to_jiffies(1000), 3, 0, RQF_PM, NULL);
8215 pr_err("%s: failed with err %d\n", __func__, ret);
8223 * ufshcd_set_dev_pwr_mode - sends START STOP UNIT command to set device
8225 * @hba: per adapter instance
8226 * @pwr_mode: device power mode to set
8228 * Returns 0 if requested power mode is set successfully
8229 * Returns non-zero if failed to set the requested power mode
8231 static int ufshcd_set_dev_pwr_mode(struct ufs_hba *hba,
8232 enum ufs_dev_pwr_mode pwr_mode)
8234 unsigned char cmd[6] = { START_STOP };
8235 struct scsi_sense_hdr sshdr;
8236 struct scsi_device *sdp;
8237 unsigned long flags;
8240 spin_lock_irqsave(hba->host->host_lock, flags);
8241 sdp = hba->sdev_ufs_device;
8243 ret = scsi_device_get(sdp);
8244 if (!ret && !scsi_device_online(sdp)) {
8246 scsi_device_put(sdp);
8251 spin_unlock_irqrestore(hba->host->host_lock, flags);
8257 * If scsi commands fail, the scsi mid-layer schedules scsi error-
8258 * handling, which would wait for host to be resumed. Since we know
8259 * we are functional while we are here, skip host resume in error
8262 hba->host->eh_noresume = 1;
8263 if (hba->wlun_dev_clr_ua) {
8264 ret = ufshcd_send_request_sense(hba, sdp);
8267 /* Unit attention condition is cleared now */
8268 hba->wlun_dev_clr_ua = false;
8271 cmd[4] = pwr_mode << 4;
8274 * Current function would be generally called from the power management
8275 * callbacks hence set the RQF_PM flag so that it doesn't resume the
8276 * already suspended childs.
8278 ret = scsi_execute(sdp, cmd, DMA_NONE, NULL, 0, NULL, &sshdr,
8279 START_STOP_TIMEOUT, 0, 0, RQF_PM, NULL);
8281 sdev_printk(KERN_WARNING, sdp,
8282 "START_STOP failed for power mode: %d, result %x\n",
8284 if (driver_byte(ret) == DRIVER_SENSE)
8285 scsi_print_sense_hdr(sdp, NULL, &sshdr);
8289 hba->curr_dev_pwr_mode = pwr_mode;
8291 scsi_device_put(sdp);
8292 hba->host->eh_noresume = 0;
8296 static int ufshcd_link_state_transition(struct ufs_hba *hba,
8297 enum uic_link_state req_link_state,
8298 int check_for_bkops)
8302 if (req_link_state == hba->uic_link_state)
8305 if (req_link_state == UIC_LINK_HIBERN8_STATE) {
8306 ret = ufshcd_uic_hibern8_enter(hba);
8308 ufshcd_set_link_hibern8(hba);
8310 dev_err(hba->dev, "%s: hibern8 enter failed %d\n",
8316 * If autobkops is enabled, link can't be turned off because
8317 * turning off the link would also turn off the device.
8319 else if ((req_link_state == UIC_LINK_OFF_STATE) &&
8320 (!check_for_bkops || !hba->auto_bkops_enabled)) {
8322 * Let's make sure that link is in low power mode, we are doing
8323 * this currently by putting the link in Hibern8. Otherway to
8324 * put the link in low power mode is to send the DME end point
8325 * to device and then send the DME reset command to local
8326 * unipro. But putting the link in hibern8 is much faster.
8328 ret = ufshcd_uic_hibern8_enter(hba);
8330 dev_err(hba->dev, "%s: hibern8 enter failed %d\n",
8335 * Change controller state to "reset state" which
8336 * should also put the link in off/reset state
8338 ufshcd_hba_stop(hba);
8340 * TODO: Check if we need any delay to make sure that
8341 * controller is reset
8343 ufshcd_set_link_off(hba);
8350 static void ufshcd_vreg_set_lpm(struct ufs_hba *hba)
8352 bool vcc_off = false;
8355 * It seems some UFS devices may keep drawing more than sleep current
8356 * (atleast for 500us) from UFS rails (especially from VCCQ rail).
8357 * To avoid this situation, add 2ms delay before putting these UFS
8358 * rails in LPM mode.
8360 if (!ufshcd_is_link_active(hba) &&
8361 hba->dev_quirks & UFS_DEVICE_QUIRK_DELAY_BEFORE_LPM)
8362 usleep_range(2000, 2100);
8365 * If UFS device is either in UFS_Sleep turn off VCC rail to save some
8368 * If UFS device and link is in OFF state, all power supplies (VCC,
8369 * VCCQ, VCCQ2) can be turned off if power on write protect is not
8370 * required. If UFS link is inactive (Hibern8 or OFF state) and device
8371 * is in sleep state, put VCCQ & VCCQ2 rails in LPM mode.
8373 * Ignore the error returned by ufshcd_toggle_vreg() as device is anyway
8374 * in low power state which would save some power.
8376 * If Write Booster is enabled and the device needs to flush the WB
8377 * buffer OR if bkops status is urgent for WB, keep Vcc on.
8379 if (ufshcd_is_ufs_dev_poweroff(hba) && ufshcd_is_link_off(hba) &&
8380 !hba->dev_info.is_lu_power_on_wp) {
8381 ufshcd_setup_vreg(hba, false);
8383 } else if (!ufshcd_is_ufs_dev_active(hba)) {
8384 ufshcd_toggle_vreg(hba->dev, hba->vreg_info.vcc, false);
8386 if (!ufshcd_is_link_active(hba)) {
8387 ufshcd_config_vreg_lpm(hba, hba->vreg_info.vccq);
8388 ufshcd_config_vreg_lpm(hba, hba->vreg_info.vccq2);
8393 * Some UFS devices require delay after VCC power rail is turned-off.
8395 if (vcc_off && hba->vreg_info.vcc &&
8396 hba->dev_quirks & UFS_DEVICE_QUIRK_DELAY_AFTER_LPM)
8397 usleep_range(5000, 5100);
8400 static int ufshcd_vreg_set_hpm(struct ufs_hba *hba)
8404 if (ufshcd_is_ufs_dev_poweroff(hba) && ufshcd_is_link_off(hba) &&
8405 !hba->dev_info.is_lu_power_on_wp) {
8406 ret = ufshcd_setup_vreg(hba, true);
8407 } else if (!ufshcd_is_ufs_dev_active(hba)) {
8408 if (!ret && !ufshcd_is_link_active(hba)) {
8409 ret = ufshcd_config_vreg_hpm(hba, hba->vreg_info.vccq);
8412 ret = ufshcd_config_vreg_hpm(hba, hba->vreg_info.vccq2);
8416 ret = ufshcd_toggle_vreg(hba->dev, hba->vreg_info.vcc, true);
8421 ufshcd_config_vreg_lpm(hba, hba->vreg_info.vccq);
8423 ufshcd_toggle_vreg(hba->dev, hba->vreg_info.vcc, false);
8428 static void ufshcd_hba_vreg_set_lpm(struct ufs_hba *hba)
8430 if (ufshcd_is_link_off(hba))
8431 ufshcd_setup_hba_vreg(hba, false);
8434 static void ufshcd_hba_vreg_set_hpm(struct ufs_hba *hba)
8436 if (ufshcd_is_link_off(hba))
8437 ufshcd_setup_hba_vreg(hba, true);
8441 * ufshcd_suspend - helper function for suspend operations
8442 * @hba: per adapter instance
8443 * @pm_op: desired low power operation type
8445 * This function will try to put the UFS device and link into low power
8446 * mode based on the "rpm_lvl" (Runtime PM level) or "spm_lvl"
8447 * (System PM level).
8449 * If this function is called during shutdown, it will make sure that
8450 * both UFS device and UFS link is powered off.
8452 * NOTE: UFS device & link must be active before we enter in this function.
8454 * Returns 0 for success and non-zero for failure
8456 static int ufshcd_suspend(struct ufs_hba *hba, enum ufs_pm_op pm_op)
8459 enum ufs_pm_level pm_lvl;
8460 enum ufs_dev_pwr_mode req_dev_pwr_mode;
8461 enum uic_link_state req_link_state;
8463 hba->pm_op_in_progress = 1;
8464 if (!ufshcd_is_shutdown_pm(pm_op)) {
8465 pm_lvl = ufshcd_is_runtime_pm(pm_op) ?
8466 hba->rpm_lvl : hba->spm_lvl;
8467 req_dev_pwr_mode = ufs_get_pm_lvl_to_dev_pwr_mode(pm_lvl);
8468 req_link_state = ufs_get_pm_lvl_to_link_pwr_state(pm_lvl);
8470 req_dev_pwr_mode = UFS_POWERDOWN_PWR_MODE;
8471 req_link_state = UIC_LINK_OFF_STATE;
8475 * If we can't transition into any of the low power modes
8476 * just gate the clocks.
8478 ufshcd_hold(hba, false);
8479 hba->clk_gating.is_suspended = true;
8481 if (hba->clk_scaling.is_allowed) {
8482 cancel_work_sync(&hba->clk_scaling.suspend_work);
8483 cancel_work_sync(&hba->clk_scaling.resume_work);
8484 ufshcd_suspend_clkscaling(hba);
8487 if (req_dev_pwr_mode == UFS_ACTIVE_PWR_MODE &&
8488 req_link_state == UIC_LINK_ACTIVE_STATE) {
8492 if ((req_dev_pwr_mode == hba->curr_dev_pwr_mode) &&
8493 (req_link_state == hba->uic_link_state))
8496 /* UFS device & link must be active before we enter in this function */
8497 if (!ufshcd_is_ufs_dev_active(hba) || !ufshcd_is_link_active(hba)) {
8502 if (ufshcd_is_runtime_pm(pm_op)) {
8503 if (ufshcd_can_autobkops_during_suspend(hba)) {
8505 * The device is idle with no requests in the queue,
8506 * allow background operations if bkops status shows
8507 * that performance might be impacted.
8509 ret = ufshcd_urgent_bkops(hba);
8513 /* make sure that auto bkops is disabled */
8514 ufshcd_disable_auto_bkops(hba);
8517 * If device needs to do BKOP or WB buffer flush during
8518 * Hibern8, keep device power mode as "active power mode"
8521 hba->dev_info.b_rpm_dev_flush_capable =
8522 hba->auto_bkops_enabled ||
8523 (((req_link_state == UIC_LINK_HIBERN8_STATE) ||
8524 ((req_link_state == UIC_LINK_ACTIVE_STATE) &&
8525 ufshcd_is_auto_hibern8_enabled(hba))) &&
8526 ufshcd_wb_need_flush(hba));
8529 if (req_dev_pwr_mode != hba->curr_dev_pwr_mode) {
8530 if ((ufshcd_is_runtime_pm(pm_op) && !hba->auto_bkops_enabled) ||
8531 !ufshcd_is_runtime_pm(pm_op)) {
8532 /* ensure that bkops is disabled */
8533 ufshcd_disable_auto_bkops(hba);
8536 if (!hba->dev_info.b_rpm_dev_flush_capable) {
8537 ret = ufshcd_set_dev_pwr_mode(hba, req_dev_pwr_mode);
8543 flush_work(&hba->eeh_work);
8544 ret = ufshcd_link_state_transition(hba, req_link_state, 1);
8546 goto set_dev_active;
8548 ufshcd_vreg_set_lpm(hba);
8552 * Call vendor specific suspend callback. As these callbacks may access
8553 * vendor specific host controller register space call them before the
8554 * host clocks are ON.
8556 ret = ufshcd_vops_suspend(hba, pm_op);
8558 goto set_link_active;
8560 * Disable the host irq as host controller as there won't be any
8561 * host controller transaction expected till resume.
8563 ufshcd_disable_irq(hba);
8565 if (!ufshcd_is_link_active(hba))
8566 ufshcd_setup_clocks(hba, false);
8568 /* If link is active, device ref_clk can't be switched off */
8569 __ufshcd_setup_clocks(hba, false, true);
8571 if (ufshcd_is_clkgating_allowed(hba)) {
8572 hba->clk_gating.state = CLKS_OFF;
8573 trace_ufshcd_clk_gating(dev_name(hba->dev),
8574 hba->clk_gating.state);
8577 /* Put the host controller in low power mode if possible */
8578 ufshcd_hba_vreg_set_lpm(hba);
8582 if (hba->clk_scaling.is_allowed)
8583 ufshcd_resume_clkscaling(hba);
8584 ufshcd_vreg_set_hpm(hba);
8585 if (ufshcd_is_link_hibern8(hba) && !ufshcd_uic_hibern8_exit(hba))
8586 ufshcd_set_link_active(hba);
8587 else if (ufshcd_is_link_off(hba))
8588 ufshcd_host_reset_and_restore(hba);
8590 if (!ufshcd_set_dev_pwr_mode(hba, UFS_ACTIVE_PWR_MODE))
8591 ufshcd_disable_auto_bkops(hba);
8593 if (hba->clk_scaling.is_allowed)
8594 ufshcd_resume_clkscaling(hba);
8595 hba->clk_gating.is_suspended = false;
8596 hba->dev_info.b_rpm_dev_flush_capable = false;
8597 ufshcd_release(hba);
8599 if (hba->dev_info.b_rpm_dev_flush_capable) {
8600 schedule_delayed_work(&hba->rpm_dev_flush_recheck_work,
8601 msecs_to_jiffies(RPM_DEV_FLUSH_RECHECK_WORK_DELAY_MS));
8604 hba->pm_op_in_progress = 0;
8607 ufshcd_update_reg_hist(&hba->ufs_stats.suspend_err, (u32)ret);
8612 * ufshcd_resume - helper function for resume operations
8613 * @hba: per adapter instance
8614 * @pm_op: runtime PM or system PM
8616 * This function basically brings the UFS device, UniPro link and controller
8619 * Returns 0 for success and non-zero for failure
8621 static int ufshcd_resume(struct ufs_hba *hba, enum ufs_pm_op pm_op)
8624 enum uic_link_state old_link_state;
8626 hba->pm_op_in_progress = 1;
8627 old_link_state = hba->uic_link_state;
8629 ufshcd_hba_vreg_set_hpm(hba);
8630 /* Make sure clocks are enabled before accessing controller */
8631 ret = ufshcd_setup_clocks(hba, true);
8635 /* enable the host irq as host controller would be active soon */
8636 ufshcd_enable_irq(hba);
8638 ret = ufshcd_vreg_set_hpm(hba);
8640 goto disable_irq_and_vops_clks;
8643 * Call vendor specific resume callback. As these callbacks may access
8644 * vendor specific host controller register space call them when the
8645 * host clocks are ON.
8647 ret = ufshcd_vops_resume(hba, pm_op);
8651 if (ufshcd_is_link_hibern8(hba)) {
8652 ret = ufshcd_uic_hibern8_exit(hba);
8654 ufshcd_set_link_active(hba);
8656 dev_err(hba->dev, "%s: hibern8 exit failed %d\n",
8658 goto vendor_suspend;
8660 } else if (ufshcd_is_link_off(hba)) {
8662 * A full initialization of the host and the device is
8663 * required since the link was put to off during suspend.
8665 ret = ufshcd_reset_and_restore(hba);
8667 * ufshcd_reset_and_restore() should have already
8668 * set the link state as active
8670 if (ret || !ufshcd_is_link_active(hba))
8671 goto vendor_suspend;
8674 if (!ufshcd_is_ufs_dev_active(hba)) {
8675 ret = ufshcd_set_dev_pwr_mode(hba, UFS_ACTIVE_PWR_MODE);
8677 goto set_old_link_state;
8680 if (ufshcd_keep_autobkops_enabled_except_suspend(hba))
8681 ufshcd_enable_auto_bkops(hba);
8684 * If BKOPs operations are urgently needed at this moment then
8685 * keep auto-bkops enabled or else disable it.
8687 ufshcd_urgent_bkops(hba);
8689 hba->clk_gating.is_suspended = false;
8691 if (hba->clk_scaling.is_allowed)
8692 ufshcd_resume_clkscaling(hba);
8694 /* Enable Auto-Hibernate if configured */
8695 ufshcd_auto_hibern8_enable(hba);
8697 if (hba->dev_info.b_rpm_dev_flush_capable) {
8698 hba->dev_info.b_rpm_dev_flush_capable = false;
8699 cancel_delayed_work(&hba->rpm_dev_flush_recheck_work);
8702 /* Schedule clock gating in case of no access to UFS device yet */
8703 ufshcd_release(hba);
8708 ufshcd_link_state_transition(hba, old_link_state, 0);
8710 ufshcd_vops_suspend(hba, pm_op);
8712 ufshcd_vreg_set_lpm(hba);
8713 disable_irq_and_vops_clks:
8714 ufshcd_disable_irq(hba);
8715 if (hba->clk_scaling.is_allowed)
8716 ufshcd_suspend_clkscaling(hba);
8717 ufshcd_setup_clocks(hba, false);
8718 if (ufshcd_is_clkgating_allowed(hba)) {
8719 hba->clk_gating.state = CLKS_OFF;
8720 trace_ufshcd_clk_gating(dev_name(hba->dev),
8721 hba->clk_gating.state);
8724 hba->pm_op_in_progress = 0;
8726 ufshcd_update_reg_hist(&hba->ufs_stats.resume_err, (u32)ret);
8731 * ufshcd_system_suspend - system suspend routine
8732 * @hba: per adapter instance
8734 * Check the description of ufshcd_suspend() function for more details.
8736 * Returns 0 for success and non-zero for failure
8738 int ufshcd_system_suspend(struct ufs_hba *hba)
8741 ktime_t start = ktime_get();
8743 if (!hba || !hba->is_powered)
8746 if ((ufs_get_pm_lvl_to_dev_pwr_mode(hba->spm_lvl) ==
8747 hba->curr_dev_pwr_mode) &&
8748 (ufs_get_pm_lvl_to_link_pwr_state(hba->spm_lvl) ==
8749 hba->uic_link_state))
8752 if (pm_runtime_suspended(hba->dev)) {
8754 * UFS device and/or UFS link low power states during runtime
8755 * suspend seems to be different than what is expected during
8756 * system suspend. Hence runtime resume the devic & link and
8757 * let the system suspend low power states to take effect.
8758 * TODO: If resume takes longer time, we might have optimize
8759 * it in future by not resuming everything if possible.
8761 ret = ufshcd_runtime_resume(hba);
8766 ret = ufshcd_suspend(hba, UFS_SYSTEM_PM);
8768 trace_ufshcd_system_suspend(dev_name(hba->dev), ret,
8769 ktime_to_us(ktime_sub(ktime_get(), start)),
8770 hba->curr_dev_pwr_mode, hba->uic_link_state);
8772 hba->is_sys_suspended = true;
8775 EXPORT_SYMBOL(ufshcd_system_suspend);
8778 * ufshcd_system_resume - system resume routine
8779 * @hba: per adapter instance
8781 * Returns 0 for success and non-zero for failure
8784 int ufshcd_system_resume(struct ufs_hba *hba)
8787 ktime_t start = ktime_get();
8792 if (!hba->is_powered || pm_runtime_suspended(hba->dev))
8794 * Let the runtime resume take care of resuming
8795 * if runtime suspended.
8799 ret = ufshcd_resume(hba, UFS_SYSTEM_PM);
8801 trace_ufshcd_system_resume(dev_name(hba->dev), ret,
8802 ktime_to_us(ktime_sub(ktime_get(), start)),
8803 hba->curr_dev_pwr_mode, hba->uic_link_state);
8805 hba->is_sys_suspended = false;
8808 EXPORT_SYMBOL(ufshcd_system_resume);
8811 * ufshcd_runtime_suspend - runtime suspend routine
8812 * @hba: per adapter instance
8814 * Check the description of ufshcd_suspend() function for more details.
8816 * Returns 0 for success and non-zero for failure
8818 int ufshcd_runtime_suspend(struct ufs_hba *hba)
8821 ktime_t start = ktime_get();
8826 if (!hba->is_powered)
8829 ret = ufshcd_suspend(hba, UFS_RUNTIME_PM);
8831 trace_ufshcd_runtime_suspend(dev_name(hba->dev), ret,
8832 ktime_to_us(ktime_sub(ktime_get(), start)),
8833 hba->curr_dev_pwr_mode, hba->uic_link_state);
8836 EXPORT_SYMBOL(ufshcd_runtime_suspend);
8839 * ufshcd_runtime_resume - runtime resume routine
8840 * @hba: per adapter instance
8842 * This function basically brings the UFS device, UniPro link and controller
8843 * to active state. Following operations are done in this function:
8845 * 1. Turn on all the controller related clocks
8846 * 2. Bring the UniPro link out of Hibernate state
8847 * 3. If UFS device is in sleep state, turn ON VCC rail and bring the UFS device
8849 * 4. If auto-bkops is enabled on the device, disable it.
8851 * So following would be the possible power state after this function return
8853 * S1: UFS device in Active state with VCC rail ON
8854 * UniPro link in Active state
8855 * All the UFS/UniPro controller clocks are ON
8857 * Returns 0 for success and non-zero for failure
8859 int ufshcd_runtime_resume(struct ufs_hba *hba)
8862 ktime_t start = ktime_get();
8867 if (!hba->is_powered)
8870 ret = ufshcd_resume(hba, UFS_RUNTIME_PM);
8872 trace_ufshcd_runtime_resume(dev_name(hba->dev), ret,
8873 ktime_to_us(ktime_sub(ktime_get(), start)),
8874 hba->curr_dev_pwr_mode, hba->uic_link_state);
8877 EXPORT_SYMBOL(ufshcd_runtime_resume);
8879 int ufshcd_runtime_idle(struct ufs_hba *hba)
8883 EXPORT_SYMBOL(ufshcd_runtime_idle);
8886 * ufshcd_shutdown - shutdown routine
8887 * @hba: per adapter instance
8889 * This function would power off both UFS device and UFS link.
8891 * Returns 0 always to allow force shutdown even in case of errors.
8893 int ufshcd_shutdown(struct ufs_hba *hba)
8897 if (!hba->is_powered)
8900 if (ufshcd_is_ufs_dev_poweroff(hba) && ufshcd_is_link_off(hba))
8903 if (pm_runtime_suspended(hba->dev)) {
8904 ret = ufshcd_runtime_resume(hba);
8909 ret = ufshcd_suspend(hba, UFS_SHUTDOWN_PM);
8912 dev_err(hba->dev, "%s failed, err %d\n", __func__, ret);
8913 /* allow force shutdown even in case of errors */
8916 EXPORT_SYMBOL(ufshcd_shutdown);
8919 * ufshcd_remove - de-allocate SCSI host and host memory space
8920 * data structure memory
8921 * @hba: per adapter instance
8923 void ufshcd_remove(struct ufs_hba *hba)
8925 ufs_bsg_remove(hba);
8926 ufs_sysfs_remove_nodes(hba->dev);
8927 blk_cleanup_queue(hba->tmf_queue);
8928 blk_mq_free_tag_set(&hba->tmf_tag_set);
8929 blk_cleanup_queue(hba->cmd_queue);
8930 scsi_remove_host(hba->host);
8931 destroy_workqueue(hba->eh_wq);
8932 /* disable interrupts */
8933 ufshcd_disable_intr(hba, hba->intr_mask);
8934 ufshcd_hba_stop(hba);
8936 ufshcd_exit_clk_scaling(hba);
8937 ufshcd_exit_clk_gating(hba);
8938 if (ufshcd_is_clkscaling_supported(hba))
8939 device_remove_file(hba->dev, &hba->clk_scaling.enable_attr);
8940 ufshcd_hba_exit(hba);
8942 EXPORT_SYMBOL_GPL(ufshcd_remove);
8945 * ufshcd_dealloc_host - deallocate Host Bus Adapter (HBA)
8946 * @hba: pointer to Host Bus Adapter (HBA)
8948 void ufshcd_dealloc_host(struct ufs_hba *hba)
8950 ufshcd_crypto_destroy_keyslot_manager(hba);
8951 scsi_host_put(hba->host);
8953 EXPORT_SYMBOL_GPL(ufshcd_dealloc_host);
8956 * ufshcd_set_dma_mask - Set dma mask based on the controller
8957 * addressing capability
8958 * @hba: per adapter instance
8960 * Returns 0 for success, non-zero for failure
8962 static int ufshcd_set_dma_mask(struct ufs_hba *hba)
8964 if (hba->capabilities & MASK_64_ADDRESSING_SUPPORT) {
8965 if (!dma_set_mask_and_coherent(hba->dev, DMA_BIT_MASK(64)))
8968 return dma_set_mask_and_coherent(hba->dev, DMA_BIT_MASK(32));
8972 * ufshcd_alloc_host - allocate Host Bus Adapter (HBA)
8973 * @dev: pointer to device handle
8974 * @hba_handle: driver private handle
8975 * Returns 0 on success, non-zero value on failure
8977 int ufshcd_alloc_host(struct device *dev, struct ufs_hba **hba_handle)
8979 struct Scsi_Host *host;
8980 struct ufs_hba *hba;
8985 "Invalid memory reference for dev is NULL\n");
8990 host = scsi_host_alloc(&ufshcd_driver_template,
8991 sizeof(struct ufs_hba));
8993 dev_err(dev, "scsi_host_alloc failed\n");
8997 hba = shost_priv(host);
9001 hba->dev_ref_clk_freq = REF_CLK_FREQ_INVAL;
9003 INIT_LIST_HEAD(&hba->clk_list_head);
9008 EXPORT_SYMBOL(ufshcd_alloc_host);
9010 /* This function exists because blk_mq_alloc_tag_set() requires this. */
9011 static blk_status_t ufshcd_queue_tmf(struct blk_mq_hw_ctx *hctx,
9012 const struct blk_mq_queue_data *qd)
9015 return BLK_STS_NOTSUPP;
9018 static const struct blk_mq_ops ufshcd_tmf_ops = {
9019 .queue_rq = ufshcd_queue_tmf,
9023 * ufshcd_init - Driver initialization routine
9024 * @hba: per-adapter instance
9025 * @mmio_base: base register address
9026 * @irq: Interrupt line of device
9027 * Returns 0 on success, non-zero value on failure
9029 int ufshcd_init(struct ufs_hba *hba, void __iomem *mmio_base, unsigned int irq)
9032 struct Scsi_Host *host = hba->host;
9033 struct device *dev = hba->dev;
9034 char eh_wq_name[sizeof("ufs_eh_wq_00")];
9038 "Invalid memory reference for mmio_base is NULL\n");
9043 hba->mmio_base = mmio_base;
9045 hba->vps = &ufs_hba_vps;
9047 err = ufshcd_hba_init(hba);
9051 /* Read capabilities registers */
9052 err = ufshcd_hba_capabilities(hba);
9056 /* Get UFS version supported by the controller */
9057 hba->ufs_version = ufshcd_get_ufs_version(hba);
9059 if ((hba->ufs_version != UFSHCI_VERSION_10) &&
9060 (hba->ufs_version != UFSHCI_VERSION_11) &&
9061 (hba->ufs_version != UFSHCI_VERSION_20) &&
9062 (hba->ufs_version != UFSHCI_VERSION_21))
9063 dev_err(hba->dev, "invalid UFS version 0x%x\n",
9066 /* Get Interrupt bit mask per version */
9067 hba->intr_mask = ufshcd_get_intr_mask(hba);
9069 err = ufshcd_set_dma_mask(hba);
9071 dev_err(hba->dev, "set dma mask failed\n");
9075 /* Allocate memory for host memory space */
9076 err = ufshcd_memory_alloc(hba);
9078 dev_err(hba->dev, "Memory allocation failed\n");
9083 ufshcd_host_memory_configure(hba);
9085 host->can_queue = hba->nutrs;
9086 host->cmd_per_lun = hba->nutrs;
9087 host->max_id = UFSHCD_MAX_ID;
9088 host->max_lun = UFS_MAX_LUNS;
9089 host->max_channel = UFSHCD_MAX_CHANNEL;
9090 host->unique_id = host->host_no;
9091 host->max_cmd_len = UFS_CDB_SIZE;
9093 hba->max_pwr_info.is_valid = false;
9095 /* Initialize work queues */
9096 snprintf(eh_wq_name, sizeof(eh_wq_name), "ufs_eh_wq_%d",
9097 hba->host->host_no);
9098 hba->eh_wq = create_singlethread_workqueue(eh_wq_name);
9100 dev_err(hba->dev, "%s: failed to create eh workqueue\n",
9105 INIT_WORK(&hba->eh_work, ufshcd_err_handler);
9106 INIT_WORK(&hba->eeh_work, ufshcd_exception_event_handler);
9108 /* Initialize UIC command mutex */
9109 mutex_init(&hba->uic_cmd_mutex);
9111 /* Initialize mutex for device management commands */
9112 mutex_init(&hba->dev_cmd.lock);
9114 init_rwsem(&hba->clk_scaling_lock);
9116 ufshcd_init_clk_gating(hba);
9118 ufshcd_init_clk_scaling(hba);
9121 * In order to avoid any spurious interrupt immediately after
9122 * registering UFS controller interrupt handler, clear any pending UFS
9123 * interrupt status and disable all the UFS interrupts.
9125 ufshcd_writel(hba, ufshcd_readl(hba, REG_INTERRUPT_STATUS),
9126 REG_INTERRUPT_STATUS);
9127 ufshcd_writel(hba, 0, REG_INTERRUPT_ENABLE);
9129 * Make sure that UFS interrupts are disabled and any pending interrupt
9130 * status is cleared before registering UFS interrupt handler.
9134 /* IRQ registration */
9135 err = devm_request_irq(dev, irq, ufshcd_intr, IRQF_SHARED, UFSHCD, hba);
9137 dev_err(hba->dev, "request irq failed\n");
9140 hba->is_irq_enabled = true;
9143 err = scsi_add_host(host, hba->dev);
9145 dev_err(hba->dev, "scsi_add_host failed\n");
9149 hba->cmd_queue = blk_mq_init_queue(&hba->host->tag_set);
9150 if (IS_ERR(hba->cmd_queue)) {
9151 err = PTR_ERR(hba->cmd_queue);
9152 goto out_remove_scsi_host;
9155 hba->tmf_tag_set = (struct blk_mq_tag_set) {
9157 .queue_depth = hba->nutmrs,
9158 .ops = &ufshcd_tmf_ops,
9159 .flags = BLK_MQ_F_NO_SCHED,
9161 err = blk_mq_alloc_tag_set(&hba->tmf_tag_set);
9163 goto free_cmd_queue;
9164 hba->tmf_queue = blk_mq_init_queue(&hba->tmf_tag_set);
9165 if (IS_ERR(hba->tmf_queue)) {
9166 err = PTR_ERR(hba->tmf_queue);
9167 goto free_tmf_tag_set;
9170 /* Reset the attached device */
9171 ufshcd_vops_device_reset(hba);
9173 ufshcd_init_crypto(hba);
9175 /* Host controller enable */
9176 err = ufshcd_hba_enable(hba);
9178 dev_err(hba->dev, "Host controller enable failed\n");
9179 ufshcd_print_host_regs(hba);
9180 ufshcd_print_host_state(hba);
9181 goto free_tmf_queue;
9185 * Set the default power management level for runtime and system PM.
9186 * Default power saving mode is to keep UFS link in Hibern8 state
9187 * and UFS device in sleep state.
9189 hba->rpm_lvl = ufs_get_desired_pm_lvl_for_dev_link_state(
9191 UIC_LINK_HIBERN8_STATE);
9192 hba->spm_lvl = ufs_get_desired_pm_lvl_for_dev_link_state(
9194 UIC_LINK_HIBERN8_STATE);
9196 INIT_DELAYED_WORK(&hba->rpm_dev_flush_recheck_work,
9197 ufshcd_rpm_dev_flush_recheck_work);
9199 /* Set the default auto-hiberate idle timer value to 150 ms */
9200 if (ufshcd_is_auto_hibern8_supported(hba) && !hba->ahit) {
9201 hba->ahit = FIELD_PREP(UFSHCI_AHIBERN8_TIMER_MASK, 150) |
9202 FIELD_PREP(UFSHCI_AHIBERN8_SCALE_MASK, 3);
9205 /* Hold auto suspend until async scan completes */
9206 pm_runtime_get_sync(dev);
9207 atomic_set(&hba->scsi_block_reqs_cnt, 0);
9209 * We are assuming that device wasn't put in sleep/power-down
9210 * state exclusively during the boot stage before kernel.
9211 * This assumption helps avoid doing link startup twice during
9212 * ufshcd_probe_hba().
9214 ufshcd_set_ufs_dev_active(hba);
9216 async_schedule(ufshcd_async_scan, hba);
9217 ufs_sysfs_add_nodes(hba->dev);
9222 blk_cleanup_queue(hba->tmf_queue);
9224 blk_mq_free_tag_set(&hba->tmf_tag_set);
9226 blk_cleanup_queue(hba->cmd_queue);
9227 out_remove_scsi_host:
9228 scsi_remove_host(hba->host);
9230 ufshcd_exit_clk_scaling(hba);
9231 ufshcd_exit_clk_gating(hba);
9232 destroy_workqueue(hba->eh_wq);
9234 hba->is_irq_enabled = false;
9235 ufshcd_hba_exit(hba);
9239 EXPORT_SYMBOL_GPL(ufshcd_init);
9241 MODULE_AUTHOR("Santosh Yaragnavi <santosh.sy@samsung.com>");
9242 MODULE_AUTHOR("Vinayak Holikatti <h.vinayak@samsung.com>");
9243 MODULE_DESCRIPTION("Generic UFS host controller driver Core");
9244 MODULE_LICENSE("GPL");
9245 MODULE_VERSION(UFSHCD_DRIVER_VERSION);