1 // SPDX-License-Identifier: GPL-2.0-or-later
3 * Universal Flash Storage Host controller driver Core
4 * Copyright (C) 2011-2013 Samsung India Software Operations
5 * Copyright (c) 2013-2016, The Linux Foundation. All rights reserved.
8 * Santosh Yaraganavi <santosh.sy@samsung.com>
9 * Vinayak Holikatti <h.vinayak@samsung.com>
12 #include <linux/async.h>
13 #include <linux/devfreq.h>
14 #include <linux/nls.h>
16 #include <linux/bitfield.h>
17 #include <linux/blk-pm.h>
18 #include <linux/blkdev.h>
19 #include <linux/clk.h>
20 #include <linux/delay.h>
21 #include <linux/interrupt.h>
22 #include <linux/module.h>
23 #include <linux/regulator/consumer.h>
24 #include <scsi/scsi_cmnd.h>
25 #include <scsi/scsi_dbg.h>
26 #include <scsi/scsi_driver.h>
27 #include <scsi/scsi_eh.h>
28 #include "ufshcd-priv.h"
29 #include <ufs/ufs_quirks.h>
30 #include <ufs/unipro.h>
31 #include "ufs-sysfs.h"
32 #include "ufs-debugfs.h"
33 #include "ufs-fault-injection.h"
35 #include "ufshcd-crypto.h"
37 #include <asm/unaligned.h>
39 #define CREATE_TRACE_POINTS
40 #include <trace/events/ufs.h>
42 #define UFSHCD_ENABLE_INTRS (UTP_TRANSFER_REQ_COMPL |\
45 /* UIC command timeout, unit: ms */
46 #define UIC_CMD_TIMEOUT 500
48 /* NOP OUT retries waiting for NOP IN response */
49 #define NOP_OUT_RETRIES 10
50 /* Timeout after 50 msecs if NOP OUT hangs without response */
51 #define NOP_OUT_TIMEOUT 50 /* msecs */
53 /* Query request retries */
54 #define QUERY_REQ_RETRIES 3
55 /* Query request timeout */
56 #define QUERY_REQ_TIMEOUT 1500 /* 1.5 seconds */
58 /* Task management command timeout */
59 #define TM_CMD_TIMEOUT 100 /* msecs */
61 /* maximum number of retries for a general UIC command */
62 #define UFS_UIC_COMMAND_RETRIES 3
64 /* maximum number of link-startup retries */
65 #define DME_LINKSTARTUP_RETRIES 3
67 /* maximum number of reset retries before giving up */
68 #define MAX_HOST_RESET_RETRIES 5
70 /* Maximum number of error handler retries before giving up */
71 #define MAX_ERR_HANDLER_RETRIES 5
73 /* Expose the flag value from utp_upiu_query.value */
74 #define MASK_QUERY_UPIU_FLAG_LOC 0xFF
76 /* Interrupt aggregation default timeout, unit: 40us */
77 #define INT_AGGR_DEF_TO 0x02
79 /* default delay of autosuspend: 2000 ms */
80 #define RPM_AUTOSUSPEND_DELAY_MS 2000
82 /* Default delay of RPM device flush delayed work */
83 #define RPM_DEV_FLUSH_RECHECK_WORK_DELAY_MS 5000
85 /* Default value of wait time before gating device ref clock */
86 #define UFSHCD_REF_CLK_GATING_WAIT_US 0xFF /* microsecs */
88 /* Polling time to wait for fDeviceInit */
89 #define FDEVICEINIT_COMPL_TIMEOUT 1500 /* millisecs */
91 #define ufshcd_toggle_vreg(_dev, _vreg, _on) \
95 _ret = ufshcd_enable_vreg(_dev, _vreg); \
97 _ret = ufshcd_disable_vreg(_dev, _vreg); \
101 #define ufshcd_hex_dump(prefix_str, buf, len) do { \
102 size_t __len = (len); \
103 print_hex_dump(KERN_ERR, prefix_str, \
104 __len > 4 ? DUMP_PREFIX_OFFSET : DUMP_PREFIX_NONE,\
105 16, 4, buf, __len, false); \
108 int ufshcd_dump_regs(struct ufs_hba *hba, size_t offset, size_t len,
114 if (offset % 4 != 0 || len % 4 != 0) /* keep readl happy */
117 regs = kzalloc(len, GFP_ATOMIC);
121 for (pos = 0; pos < len; pos += 4) {
123 pos >= REG_UIC_ERROR_CODE_PHY_ADAPTER_LAYER &&
124 pos <= REG_UIC_ERROR_CODE_DME)
126 regs[pos / 4] = ufshcd_readl(hba, offset + pos);
129 ufshcd_hex_dump(prefix, regs, len);
134 EXPORT_SYMBOL_GPL(ufshcd_dump_regs);
137 UFSHCD_MAX_CHANNEL = 0,
139 UFSHCD_NUM_RESERVED = 1,
140 UFSHCD_CMD_PER_LUN = 32 - UFSHCD_NUM_RESERVED,
141 UFSHCD_CAN_QUEUE = 32 - UFSHCD_NUM_RESERVED,
144 static const char *const ufshcd_state_name[] = {
145 [UFSHCD_STATE_RESET] = "reset",
146 [UFSHCD_STATE_OPERATIONAL] = "operational",
147 [UFSHCD_STATE_ERROR] = "error",
148 [UFSHCD_STATE_EH_SCHEDULED_FATAL] = "eh_fatal",
149 [UFSHCD_STATE_EH_SCHEDULED_NON_FATAL] = "eh_non_fatal",
152 /* UFSHCD error handling flags */
154 UFSHCD_EH_IN_PROGRESS = (1 << 0),
157 /* UFSHCD UIC layer error flags */
159 UFSHCD_UIC_DL_PA_INIT_ERROR = (1 << 0), /* Data link layer error */
160 UFSHCD_UIC_DL_NAC_RECEIVED_ERROR = (1 << 1), /* Data link layer error */
161 UFSHCD_UIC_DL_TCx_REPLAY_ERROR = (1 << 2), /* Data link layer error */
162 UFSHCD_UIC_NL_ERROR = (1 << 3), /* Network layer error */
163 UFSHCD_UIC_TL_ERROR = (1 << 4), /* Transport Layer error */
164 UFSHCD_UIC_DME_ERROR = (1 << 5), /* DME error */
165 UFSHCD_UIC_PA_GENERIC_ERROR = (1 << 6), /* Generic PA error */
168 #define ufshcd_set_eh_in_progress(h) \
169 ((h)->eh_flags |= UFSHCD_EH_IN_PROGRESS)
170 #define ufshcd_eh_in_progress(h) \
171 ((h)->eh_flags & UFSHCD_EH_IN_PROGRESS)
172 #define ufshcd_clear_eh_in_progress(h) \
173 ((h)->eh_flags &= ~UFSHCD_EH_IN_PROGRESS)
175 const struct ufs_pm_lvl_states ufs_pm_lvl_states[] = {
176 [UFS_PM_LVL_0] = {UFS_ACTIVE_PWR_MODE, UIC_LINK_ACTIVE_STATE},
177 [UFS_PM_LVL_1] = {UFS_ACTIVE_PWR_MODE, UIC_LINK_HIBERN8_STATE},
178 [UFS_PM_LVL_2] = {UFS_SLEEP_PWR_MODE, UIC_LINK_ACTIVE_STATE},
179 [UFS_PM_LVL_3] = {UFS_SLEEP_PWR_MODE, UIC_LINK_HIBERN8_STATE},
180 [UFS_PM_LVL_4] = {UFS_POWERDOWN_PWR_MODE, UIC_LINK_HIBERN8_STATE},
181 [UFS_PM_LVL_5] = {UFS_POWERDOWN_PWR_MODE, UIC_LINK_OFF_STATE},
183 * For DeepSleep, the link is first put in hibern8 and then off.
184 * Leaving the link in hibern8 is not supported.
186 [UFS_PM_LVL_6] = {UFS_DEEPSLEEP_PWR_MODE, UIC_LINK_OFF_STATE},
189 static inline enum ufs_dev_pwr_mode
190 ufs_get_pm_lvl_to_dev_pwr_mode(enum ufs_pm_level lvl)
192 return ufs_pm_lvl_states[lvl].dev_state;
195 static inline enum uic_link_state
196 ufs_get_pm_lvl_to_link_pwr_state(enum ufs_pm_level lvl)
198 return ufs_pm_lvl_states[lvl].link_state;
201 static inline enum ufs_pm_level
202 ufs_get_desired_pm_lvl_for_dev_link_state(enum ufs_dev_pwr_mode dev_state,
203 enum uic_link_state link_state)
205 enum ufs_pm_level lvl;
207 for (lvl = UFS_PM_LVL_0; lvl < UFS_PM_LVL_MAX; lvl++) {
208 if ((ufs_pm_lvl_states[lvl].dev_state == dev_state) &&
209 (ufs_pm_lvl_states[lvl].link_state == link_state))
213 /* if no match found, return the level 0 */
217 static const struct ufs_dev_quirk ufs_fixups[] = {
218 /* UFS cards deviations table */
219 { .wmanufacturerid = UFS_VENDOR_MICRON,
220 .model = UFS_ANY_MODEL,
221 .quirk = UFS_DEVICE_QUIRK_DELAY_BEFORE_LPM |
222 UFS_DEVICE_QUIRK_SWAP_L2P_ENTRY_FOR_HPB_READ },
223 { .wmanufacturerid = UFS_VENDOR_SAMSUNG,
224 .model = UFS_ANY_MODEL,
225 .quirk = UFS_DEVICE_QUIRK_DELAY_BEFORE_LPM |
226 UFS_DEVICE_QUIRK_HOST_PA_TACTIVATE |
227 UFS_DEVICE_QUIRK_RECOVERY_FROM_DL_NAC_ERRORS },
228 { .wmanufacturerid = UFS_VENDOR_SKHYNIX,
229 .model = UFS_ANY_MODEL,
230 .quirk = UFS_DEVICE_QUIRK_HOST_PA_SAVECONFIGTIME },
231 { .wmanufacturerid = UFS_VENDOR_SKHYNIX,
232 .model = "hB8aL1" /*H28U62301AMR*/,
233 .quirk = UFS_DEVICE_QUIRK_HOST_VS_DEBUGSAVECONFIGTIME },
234 { .wmanufacturerid = UFS_VENDOR_TOSHIBA,
235 .model = UFS_ANY_MODEL,
236 .quirk = UFS_DEVICE_QUIRK_DELAY_BEFORE_LPM },
237 { .wmanufacturerid = UFS_VENDOR_TOSHIBA,
238 .model = "THGLF2G9C8KBADG",
239 .quirk = UFS_DEVICE_QUIRK_PA_TACTIVATE },
240 { .wmanufacturerid = UFS_VENDOR_TOSHIBA,
241 .model = "THGLF2G9D8KBADG",
242 .quirk = UFS_DEVICE_QUIRK_PA_TACTIVATE },
246 static irqreturn_t ufshcd_tmc_handler(struct ufs_hba *hba);
247 static void ufshcd_async_scan(void *data, async_cookie_t cookie);
248 static int ufshcd_reset_and_restore(struct ufs_hba *hba);
249 static int ufshcd_eh_host_reset_handler(struct scsi_cmnd *cmd);
250 static int ufshcd_clear_tm_cmd(struct ufs_hba *hba, int tag);
251 static void ufshcd_hba_exit(struct ufs_hba *hba);
252 static int ufshcd_probe_hba(struct ufs_hba *hba, bool init_dev_params);
253 static int ufshcd_setup_clocks(struct ufs_hba *hba, bool on);
254 static inline void ufshcd_add_delay_before_dme_cmd(struct ufs_hba *hba);
255 static int ufshcd_host_reset_and_restore(struct ufs_hba *hba);
256 static void ufshcd_resume_clkscaling(struct ufs_hba *hba);
257 static void ufshcd_suspend_clkscaling(struct ufs_hba *hba);
258 static void __ufshcd_suspend_clkscaling(struct ufs_hba *hba);
259 static int ufshcd_scale_clks(struct ufs_hba *hba, bool scale_up);
260 static irqreturn_t ufshcd_intr(int irq, void *__hba);
261 static int ufshcd_change_power_mode(struct ufs_hba *hba,
262 struct ufs_pa_layer_attr *pwr_mode);
263 static int ufshcd_setup_hba_vreg(struct ufs_hba *hba, bool on);
264 static int ufshcd_setup_vreg(struct ufs_hba *hba, bool on);
265 static inline int ufshcd_config_vreg_hpm(struct ufs_hba *hba,
266 struct ufs_vreg *vreg);
267 static int ufshcd_try_to_abort_task(struct ufs_hba *hba, int tag);
268 static void ufshcd_wb_toggle_flush_during_h8(struct ufs_hba *hba, bool set);
269 static inline void ufshcd_wb_toggle_flush(struct ufs_hba *hba, bool enable);
270 static void ufshcd_hba_vreg_set_lpm(struct ufs_hba *hba);
271 static void ufshcd_hba_vreg_set_hpm(struct ufs_hba *hba);
273 static inline void ufshcd_enable_irq(struct ufs_hba *hba)
275 if (!hba->is_irq_enabled) {
276 enable_irq(hba->irq);
277 hba->is_irq_enabled = true;
281 static inline void ufshcd_disable_irq(struct ufs_hba *hba)
283 if (hba->is_irq_enabled) {
284 disable_irq(hba->irq);
285 hba->is_irq_enabled = false;
289 static inline void ufshcd_wb_config(struct ufs_hba *hba)
291 if (!ufshcd_is_wb_allowed(hba))
294 ufshcd_wb_toggle(hba, true);
296 ufshcd_wb_toggle_flush_during_h8(hba, true);
297 if (!(hba->quirks & UFSHCI_QUIRK_SKIP_MANUAL_WB_FLUSH_CTRL))
298 ufshcd_wb_toggle_flush(hba, true);
301 static void ufshcd_scsi_unblock_requests(struct ufs_hba *hba)
303 if (atomic_dec_and_test(&hba->scsi_block_reqs_cnt))
304 scsi_unblock_requests(hba->host);
307 static void ufshcd_scsi_block_requests(struct ufs_hba *hba)
309 if (atomic_inc_return(&hba->scsi_block_reqs_cnt) == 1)
310 scsi_block_requests(hba->host);
313 static void ufshcd_add_cmd_upiu_trace(struct ufs_hba *hba, unsigned int tag,
314 enum ufs_trace_str_t str_t)
316 struct utp_upiu_req *rq = hba->lrb[tag].ucd_req_ptr;
317 struct utp_upiu_header *header;
319 if (!trace_ufshcd_upiu_enabled())
322 if (str_t == UFS_CMD_SEND)
323 header = &rq->header;
325 header = &hba->lrb[tag].ucd_rsp_ptr->header;
327 trace_ufshcd_upiu(dev_name(hba->dev), str_t, header, &rq->sc.cdb,
331 static void ufshcd_add_query_upiu_trace(struct ufs_hba *hba,
332 enum ufs_trace_str_t str_t,
333 struct utp_upiu_req *rq_rsp)
335 if (!trace_ufshcd_upiu_enabled())
338 trace_ufshcd_upiu(dev_name(hba->dev), str_t, &rq_rsp->header,
339 &rq_rsp->qr, UFS_TSF_OSF);
342 static void ufshcd_add_tm_upiu_trace(struct ufs_hba *hba, unsigned int tag,
343 enum ufs_trace_str_t str_t)
345 struct utp_task_req_desc *descp = &hba->utmrdl_base_addr[tag];
347 if (!trace_ufshcd_upiu_enabled())
350 if (str_t == UFS_TM_SEND)
351 trace_ufshcd_upiu(dev_name(hba->dev), str_t,
352 &descp->upiu_req.req_header,
353 &descp->upiu_req.input_param1,
356 trace_ufshcd_upiu(dev_name(hba->dev), str_t,
357 &descp->upiu_rsp.rsp_header,
358 &descp->upiu_rsp.output_param1,
362 static void ufshcd_add_uic_command_trace(struct ufs_hba *hba,
363 const struct uic_command *ucmd,
364 enum ufs_trace_str_t str_t)
368 if (!trace_ufshcd_uic_command_enabled())
371 if (str_t == UFS_CMD_SEND)
374 cmd = ufshcd_readl(hba, REG_UIC_COMMAND);
376 trace_ufshcd_uic_command(dev_name(hba->dev), str_t, cmd,
377 ufshcd_readl(hba, REG_UIC_COMMAND_ARG_1),
378 ufshcd_readl(hba, REG_UIC_COMMAND_ARG_2),
379 ufshcd_readl(hba, REG_UIC_COMMAND_ARG_3));
382 static void ufshcd_add_command_trace(struct ufs_hba *hba, unsigned int tag,
383 enum ufs_trace_str_t str_t)
386 u8 opcode = 0, group_id = 0;
388 struct ufshcd_lrb *lrbp = &hba->lrb[tag];
389 struct scsi_cmnd *cmd = lrbp->cmd;
390 struct request *rq = scsi_cmd_to_rq(cmd);
391 int transfer_len = -1;
396 /* trace UPIU also */
397 ufshcd_add_cmd_upiu_trace(hba, tag, str_t);
398 if (!trace_ufshcd_command_enabled())
401 opcode = cmd->cmnd[0];
403 if (opcode == READ_10 || opcode == WRITE_10) {
405 * Currently we only fully trace read(10) and write(10) commands
408 be32_to_cpu(lrbp->ucd_req_ptr->sc.exp_data_transfer_len);
409 lba = scsi_get_lba(cmd);
410 if (opcode == WRITE_10)
411 group_id = lrbp->cmd->cmnd[6];
412 } else if (opcode == UNMAP) {
414 * The number of Bytes to be unmapped beginning with the lba.
416 transfer_len = blk_rq_bytes(rq);
417 lba = scsi_get_lba(cmd);
420 intr = ufshcd_readl(hba, REG_INTERRUPT_STATUS);
421 doorbell = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
422 trace_ufshcd_command(dev_name(hba->dev), str_t, tag,
423 doorbell, transfer_len, intr, lba, opcode, group_id);
426 static void ufshcd_print_clk_freqs(struct ufs_hba *hba)
428 struct ufs_clk_info *clki;
429 struct list_head *head = &hba->clk_list_head;
431 if (list_empty(head))
434 list_for_each_entry(clki, head, list) {
435 if (!IS_ERR_OR_NULL(clki->clk) && clki->min_freq &&
437 dev_err(hba->dev, "clk: %s, rate: %u\n",
438 clki->name, clki->curr_freq);
442 static void ufshcd_print_evt(struct ufs_hba *hba, u32 id,
443 const char *err_name)
447 const struct ufs_event_hist *e;
449 if (id >= UFS_EVT_CNT)
452 e = &hba->ufs_stats.event[id];
454 for (i = 0; i < UFS_EVENT_HIST_LENGTH; i++) {
455 int p = (i + e->pos) % UFS_EVENT_HIST_LENGTH;
457 if (e->tstamp[p] == 0)
459 dev_err(hba->dev, "%s[%d] = 0x%x at %lld us\n", err_name, p,
460 e->val[p], ktime_to_us(e->tstamp[p]));
465 dev_err(hba->dev, "No record of %s\n", err_name);
467 dev_err(hba->dev, "%s: total cnt=%llu\n", err_name, e->cnt);
470 static void ufshcd_print_evt_hist(struct ufs_hba *hba)
472 ufshcd_dump_regs(hba, 0, UFSHCI_REG_SPACE_SIZE, "host_regs: ");
474 ufshcd_print_evt(hba, UFS_EVT_PA_ERR, "pa_err");
475 ufshcd_print_evt(hba, UFS_EVT_DL_ERR, "dl_err");
476 ufshcd_print_evt(hba, UFS_EVT_NL_ERR, "nl_err");
477 ufshcd_print_evt(hba, UFS_EVT_TL_ERR, "tl_err");
478 ufshcd_print_evt(hba, UFS_EVT_DME_ERR, "dme_err");
479 ufshcd_print_evt(hba, UFS_EVT_AUTO_HIBERN8_ERR,
481 ufshcd_print_evt(hba, UFS_EVT_FATAL_ERR, "fatal_err");
482 ufshcd_print_evt(hba, UFS_EVT_LINK_STARTUP_FAIL,
483 "link_startup_fail");
484 ufshcd_print_evt(hba, UFS_EVT_RESUME_ERR, "resume_fail");
485 ufshcd_print_evt(hba, UFS_EVT_SUSPEND_ERR,
487 ufshcd_print_evt(hba, UFS_EVT_DEV_RESET, "dev_reset");
488 ufshcd_print_evt(hba, UFS_EVT_HOST_RESET, "host_reset");
489 ufshcd_print_evt(hba, UFS_EVT_ABORT, "task_abort");
491 ufshcd_vops_dbg_register_dump(hba);
495 void ufshcd_print_trs(struct ufs_hba *hba, unsigned long bitmap, bool pr_prdt)
497 const struct ufshcd_lrb *lrbp;
501 for_each_set_bit(tag, &bitmap, hba->nutrs) {
502 lrbp = &hba->lrb[tag];
504 dev_err(hba->dev, "UPIU[%d] - issue time %lld us\n",
505 tag, ktime_to_us(lrbp->issue_time_stamp));
506 dev_err(hba->dev, "UPIU[%d] - complete time %lld us\n",
507 tag, ktime_to_us(lrbp->compl_time_stamp));
509 "UPIU[%d] - Transfer Request Descriptor phys@0x%llx\n",
510 tag, (u64)lrbp->utrd_dma_addr);
512 ufshcd_hex_dump("UPIU TRD: ", lrbp->utr_descriptor_ptr,
513 sizeof(struct utp_transfer_req_desc));
514 dev_err(hba->dev, "UPIU[%d] - Request UPIU phys@0x%llx\n", tag,
515 (u64)lrbp->ucd_req_dma_addr);
516 ufshcd_hex_dump("UPIU REQ: ", lrbp->ucd_req_ptr,
517 sizeof(struct utp_upiu_req));
518 dev_err(hba->dev, "UPIU[%d] - Response UPIU phys@0x%llx\n", tag,
519 (u64)lrbp->ucd_rsp_dma_addr);
520 ufshcd_hex_dump("UPIU RSP: ", lrbp->ucd_rsp_ptr,
521 sizeof(struct utp_upiu_rsp));
523 prdt_length = le16_to_cpu(
524 lrbp->utr_descriptor_ptr->prd_table_length);
525 if (hba->quirks & UFSHCD_QUIRK_PRDT_BYTE_GRAN)
526 prdt_length /= sizeof(struct ufshcd_sg_entry);
529 "UPIU[%d] - PRDT - %d entries phys@0x%llx\n",
531 (u64)lrbp->ucd_prdt_dma_addr);
534 ufshcd_hex_dump("UPIU PRDT: ", lrbp->ucd_prdt_ptr,
535 sizeof(struct ufshcd_sg_entry) * prdt_length);
539 static void ufshcd_print_tmrs(struct ufs_hba *hba, unsigned long bitmap)
543 for_each_set_bit(tag, &bitmap, hba->nutmrs) {
544 struct utp_task_req_desc *tmrdp = &hba->utmrdl_base_addr[tag];
546 dev_err(hba->dev, "TM[%d] - Task Management Header\n", tag);
547 ufshcd_hex_dump("", tmrdp, sizeof(*tmrdp));
551 static void ufshcd_print_host_state(struct ufs_hba *hba)
553 const struct scsi_device *sdev_ufs = hba->ufs_device_wlun;
555 dev_err(hba->dev, "UFS Host state=%d\n", hba->ufshcd_state);
556 dev_err(hba->dev, "outstanding reqs=0x%lx tasks=0x%lx\n",
557 hba->outstanding_reqs, hba->outstanding_tasks);
558 dev_err(hba->dev, "saved_err=0x%x, saved_uic_err=0x%x\n",
559 hba->saved_err, hba->saved_uic_err);
560 dev_err(hba->dev, "Device power mode=%d, UIC link state=%d\n",
561 hba->curr_dev_pwr_mode, hba->uic_link_state);
562 dev_err(hba->dev, "PM in progress=%d, sys. suspended=%d\n",
563 hba->pm_op_in_progress, hba->is_sys_suspended);
564 dev_err(hba->dev, "Auto BKOPS=%d, Host self-block=%d\n",
565 hba->auto_bkops_enabled, hba->host->host_self_blocked);
566 dev_err(hba->dev, "Clk gate=%d\n", hba->clk_gating.state);
568 "last_hibern8_exit_tstamp at %lld us, hibern8_exit_cnt=%d\n",
569 ktime_to_us(hba->ufs_stats.last_hibern8_exit_tstamp),
570 hba->ufs_stats.hibern8_exit_cnt);
571 dev_err(hba->dev, "last intr at %lld us, last intr status=0x%x\n",
572 ktime_to_us(hba->ufs_stats.last_intr_ts),
573 hba->ufs_stats.last_intr_status);
574 dev_err(hba->dev, "error handling flags=0x%x, req. abort count=%d\n",
575 hba->eh_flags, hba->req_abort_count);
576 dev_err(hba->dev, "hba->ufs_version=0x%x, Host capabilities=0x%x, caps=0x%x\n",
577 hba->ufs_version, hba->capabilities, hba->caps);
578 dev_err(hba->dev, "quirks=0x%x, dev. quirks=0x%x\n", hba->quirks,
581 dev_err(hba->dev, "UFS dev info: %.8s %.16s rev %.4s\n",
582 sdev_ufs->vendor, sdev_ufs->model, sdev_ufs->rev);
584 ufshcd_print_clk_freqs(hba);
588 * ufshcd_print_pwr_info - print power params as saved in hba
590 * @hba: per-adapter instance
592 static void ufshcd_print_pwr_info(struct ufs_hba *hba)
594 static const char * const names[] = {
605 * Using dev_dbg to avoid messages during runtime PM to avoid
606 * never-ending cycles of messages written back to storage by user space
607 * causing runtime resume, causing more messages and so on.
609 dev_dbg(hba->dev, "%s:[RX, TX]: gear=[%d, %d], lane[%d, %d], pwr[%s, %s], rate = %d\n",
611 hba->pwr_info.gear_rx, hba->pwr_info.gear_tx,
612 hba->pwr_info.lane_rx, hba->pwr_info.lane_tx,
613 names[hba->pwr_info.pwr_rx],
614 names[hba->pwr_info.pwr_tx],
615 hba->pwr_info.hs_rate);
618 static void ufshcd_device_reset(struct ufs_hba *hba)
622 err = ufshcd_vops_device_reset(hba);
625 ufshcd_set_ufs_dev_active(hba);
626 if (ufshcd_is_wb_allowed(hba)) {
627 hba->dev_info.wb_enabled = false;
628 hba->dev_info.wb_buf_flush_enabled = false;
631 if (err != -EOPNOTSUPP)
632 ufshcd_update_evt_hist(hba, UFS_EVT_DEV_RESET, err);
635 void ufshcd_delay_us(unsigned long us, unsigned long tolerance)
643 usleep_range(us, us + tolerance);
645 EXPORT_SYMBOL_GPL(ufshcd_delay_us);
648 * ufshcd_wait_for_register - wait for register value to change
649 * @hba: per-adapter interface
650 * @reg: mmio register offset
651 * @mask: mask to apply to the read register value
652 * @val: value to wait for
653 * @interval_us: polling interval in microseconds
654 * @timeout_ms: timeout in milliseconds
657 * -ETIMEDOUT on error, zero on success.
659 static int ufshcd_wait_for_register(struct ufs_hba *hba, u32 reg, u32 mask,
660 u32 val, unsigned long interval_us,
661 unsigned long timeout_ms)
664 unsigned long timeout = jiffies + msecs_to_jiffies(timeout_ms);
666 /* ignore bits that we don't intend to wait on */
669 while ((ufshcd_readl(hba, reg) & mask) != val) {
670 usleep_range(interval_us, interval_us + 50);
671 if (time_after(jiffies, timeout)) {
672 if ((ufshcd_readl(hba, reg) & mask) != val)
682 * ufshcd_get_intr_mask - Get the interrupt bit mask
683 * @hba: Pointer to adapter instance
685 * Returns interrupt bit mask per version
687 static inline u32 ufshcd_get_intr_mask(struct ufs_hba *hba)
689 if (hba->ufs_version == ufshci_version(1, 0))
690 return INTERRUPT_MASK_ALL_VER_10;
691 if (hba->ufs_version <= ufshci_version(2, 0))
692 return INTERRUPT_MASK_ALL_VER_11;
694 return INTERRUPT_MASK_ALL_VER_21;
698 * ufshcd_get_ufs_version - Get the UFS version supported by the HBA
699 * @hba: Pointer to adapter instance
701 * Returns UFSHCI version supported by the controller
703 static inline u32 ufshcd_get_ufs_version(struct ufs_hba *hba)
707 if (hba->quirks & UFSHCD_QUIRK_BROKEN_UFS_HCI_VERSION)
708 ufshci_ver = ufshcd_vops_get_ufs_hci_version(hba);
710 ufshci_ver = ufshcd_readl(hba, REG_UFS_VERSION);
713 * UFSHCI v1.x uses a different version scheme, in order
714 * to allow the use of comparisons with the ufshci_version
715 * function, we convert it to the same scheme as ufs 2.0+.
717 if (ufshci_ver & 0x00010000)
718 return ufshci_version(1, ufshci_ver & 0x00000100);
724 * ufshcd_is_device_present - Check if any device connected to
725 * the host controller
726 * @hba: pointer to adapter instance
728 * Returns true if device present, false if no device detected
730 static inline bool ufshcd_is_device_present(struct ufs_hba *hba)
732 return ufshcd_readl(hba, REG_CONTROLLER_STATUS) & DEVICE_PRESENT;
736 * ufshcd_get_tr_ocs - Get the UTRD Overall Command Status
737 * @lrbp: pointer to local command reference block
739 * This function is used to get the OCS field from UTRD
740 * Returns the OCS field in the UTRD
742 static enum utp_ocs ufshcd_get_tr_ocs(struct ufshcd_lrb *lrbp)
744 return le32_to_cpu(lrbp->utr_descriptor_ptr->header.dword_2) & MASK_OCS;
748 * ufshcd_utrl_clear() - Clear requests from the controller request list.
749 * @hba: per adapter instance
750 * @mask: mask with one bit set for each request to be cleared
752 static inline void ufshcd_utrl_clear(struct ufs_hba *hba, u32 mask)
754 if (hba->quirks & UFSHCI_QUIRK_BROKEN_REQ_LIST_CLR)
757 * From the UFSHCI specification: "UTP Transfer Request List CLear
758 * Register (UTRLCLR): This field is bit significant. Each bit
759 * corresponds to a slot in the UTP Transfer Request List, where bit 0
760 * corresponds to request slot 0. A bit in this field is set to ‘0’
761 * by host software to indicate to the host controller that a transfer
762 * request slot is cleared. The host controller
763 * shall free up any resources associated to the request slot
764 * immediately, and shall set the associated bit in UTRLDBR to ‘0’. The
765 * host software indicates no change to request slots by setting the
766 * associated bits in this field to ‘1’. Bits in this field shall only
767 * be set ‘1’ or ‘0’ by host software when UTRLRSR is set to ‘1’."
769 ufshcd_writel(hba, ~mask, REG_UTP_TRANSFER_REQ_LIST_CLEAR);
773 * ufshcd_utmrl_clear - Clear a bit in UTRMLCLR register
774 * @hba: per adapter instance
775 * @pos: position of the bit to be cleared
777 static inline void ufshcd_utmrl_clear(struct ufs_hba *hba, u32 pos)
779 if (hba->quirks & UFSHCI_QUIRK_BROKEN_REQ_LIST_CLR)
780 ufshcd_writel(hba, (1 << pos), REG_UTP_TASK_REQ_LIST_CLEAR);
782 ufshcd_writel(hba, ~(1 << pos), REG_UTP_TASK_REQ_LIST_CLEAR);
786 * ufshcd_get_lists_status - Check UCRDY, UTRLRDY and UTMRLRDY
787 * @reg: Register value of host controller status
789 * Returns integer, 0 on Success and positive value if failed
791 static inline int ufshcd_get_lists_status(u32 reg)
793 return !((reg & UFSHCD_STATUS_READY) == UFSHCD_STATUS_READY);
797 * ufshcd_get_uic_cmd_result - Get the UIC command result
798 * @hba: Pointer to adapter instance
800 * This function gets the result of UIC command completion
801 * Returns 0 on success, non zero value on error
803 static inline int ufshcd_get_uic_cmd_result(struct ufs_hba *hba)
805 return ufshcd_readl(hba, REG_UIC_COMMAND_ARG_2) &
806 MASK_UIC_COMMAND_RESULT;
810 * ufshcd_get_dme_attr_val - Get the value of attribute returned by UIC command
811 * @hba: Pointer to adapter instance
813 * This function gets UIC command argument3
814 * Returns 0 on success, non zero value on error
816 static inline u32 ufshcd_get_dme_attr_val(struct ufs_hba *hba)
818 return ufshcd_readl(hba, REG_UIC_COMMAND_ARG_3);
822 * ufshcd_get_req_rsp - returns the TR response transaction type
823 * @ucd_rsp_ptr: pointer to response UPIU
826 ufshcd_get_req_rsp(struct utp_upiu_rsp *ucd_rsp_ptr)
828 return be32_to_cpu(ucd_rsp_ptr->header.dword_0) >> 24;
832 * ufshcd_get_rsp_upiu_result - Get the result from response UPIU
833 * @ucd_rsp_ptr: pointer to response UPIU
835 * This function gets the response status and scsi_status from response UPIU
836 * Returns the response result code.
839 ufshcd_get_rsp_upiu_result(struct utp_upiu_rsp *ucd_rsp_ptr)
841 return be32_to_cpu(ucd_rsp_ptr->header.dword_1) & MASK_RSP_UPIU_RESULT;
845 * ufshcd_get_rsp_upiu_data_seg_len - Get the data segment length
847 * @ucd_rsp_ptr: pointer to response UPIU
849 * Return the data segment length.
851 static inline unsigned int
852 ufshcd_get_rsp_upiu_data_seg_len(struct utp_upiu_rsp *ucd_rsp_ptr)
854 return be32_to_cpu(ucd_rsp_ptr->header.dword_2) &
855 MASK_RSP_UPIU_DATA_SEG_LEN;
859 * ufshcd_is_exception_event - Check if the device raised an exception event
860 * @ucd_rsp_ptr: pointer to response UPIU
862 * The function checks if the device raised an exception event indicated in
863 * the Device Information field of response UPIU.
865 * Returns true if exception is raised, false otherwise.
867 static inline bool ufshcd_is_exception_event(struct utp_upiu_rsp *ucd_rsp_ptr)
869 return be32_to_cpu(ucd_rsp_ptr->header.dword_2) &
870 MASK_RSP_EXCEPTION_EVENT;
874 * ufshcd_reset_intr_aggr - Reset interrupt aggregation values.
875 * @hba: per adapter instance
878 ufshcd_reset_intr_aggr(struct ufs_hba *hba)
880 ufshcd_writel(hba, INT_AGGR_ENABLE |
881 INT_AGGR_COUNTER_AND_TIMER_RESET,
882 REG_UTP_TRANSFER_REQ_INT_AGG_CONTROL);
886 * ufshcd_config_intr_aggr - Configure interrupt aggregation values.
887 * @hba: per adapter instance
888 * @cnt: Interrupt aggregation counter threshold
889 * @tmout: Interrupt aggregation timeout value
892 ufshcd_config_intr_aggr(struct ufs_hba *hba, u8 cnt, u8 tmout)
894 ufshcd_writel(hba, INT_AGGR_ENABLE | INT_AGGR_PARAM_WRITE |
895 INT_AGGR_COUNTER_THLD_VAL(cnt) |
896 INT_AGGR_TIMEOUT_VAL(tmout),
897 REG_UTP_TRANSFER_REQ_INT_AGG_CONTROL);
901 * ufshcd_disable_intr_aggr - Disables interrupt aggregation.
902 * @hba: per adapter instance
904 static inline void ufshcd_disable_intr_aggr(struct ufs_hba *hba)
906 ufshcd_writel(hba, 0, REG_UTP_TRANSFER_REQ_INT_AGG_CONTROL);
910 * ufshcd_enable_run_stop_reg - Enable run-stop registers,
911 * When run-stop registers are set to 1, it indicates the
912 * host controller that it can process the requests
913 * @hba: per adapter instance
915 static void ufshcd_enable_run_stop_reg(struct ufs_hba *hba)
917 ufshcd_writel(hba, UTP_TASK_REQ_LIST_RUN_STOP_BIT,
918 REG_UTP_TASK_REQ_LIST_RUN_STOP);
919 ufshcd_writel(hba, UTP_TRANSFER_REQ_LIST_RUN_STOP_BIT,
920 REG_UTP_TRANSFER_REQ_LIST_RUN_STOP);
924 * ufshcd_hba_start - Start controller initialization sequence
925 * @hba: per adapter instance
927 static inline void ufshcd_hba_start(struct ufs_hba *hba)
929 u32 val = CONTROLLER_ENABLE;
931 if (ufshcd_crypto_enable(hba))
932 val |= CRYPTO_GENERAL_ENABLE;
934 ufshcd_writel(hba, val, REG_CONTROLLER_ENABLE);
938 * ufshcd_is_hba_active - Get controller state
939 * @hba: per adapter instance
941 * Returns true if and only if the controller is active.
943 static inline bool ufshcd_is_hba_active(struct ufs_hba *hba)
945 return ufshcd_readl(hba, REG_CONTROLLER_ENABLE) & CONTROLLER_ENABLE;
948 u32 ufshcd_get_local_unipro_ver(struct ufs_hba *hba)
950 /* HCI version 1.0 and 1.1 supports UniPro 1.41 */
951 if (hba->ufs_version <= ufshci_version(1, 1))
952 return UFS_UNIPRO_VER_1_41;
954 return UFS_UNIPRO_VER_1_6;
956 EXPORT_SYMBOL(ufshcd_get_local_unipro_ver);
958 static bool ufshcd_is_unipro_pa_params_tuning_req(struct ufs_hba *hba)
961 * If both host and device support UniPro ver1.6 or later, PA layer
962 * parameters tuning happens during link startup itself.
964 * We can manually tune PA layer parameters if either host or device
965 * doesn't support UniPro ver 1.6 or later. But to keep manual tuning
966 * logic simple, we will only do manual tuning if local unipro version
967 * doesn't support ver1.6 or later.
969 return ufshcd_get_local_unipro_ver(hba) < UFS_UNIPRO_VER_1_6;
973 * ufshcd_set_clk_freq - set UFS controller clock frequencies
974 * @hba: per adapter instance
975 * @scale_up: If True, set max possible frequency othewise set low frequency
977 * Returns 0 if successful
978 * Returns < 0 for any other errors
980 static int ufshcd_set_clk_freq(struct ufs_hba *hba, bool scale_up)
983 struct ufs_clk_info *clki;
984 struct list_head *head = &hba->clk_list_head;
986 if (list_empty(head))
989 list_for_each_entry(clki, head, list) {
990 if (!IS_ERR_OR_NULL(clki->clk)) {
991 if (scale_up && clki->max_freq) {
992 if (clki->curr_freq == clki->max_freq)
995 ret = clk_set_rate(clki->clk, clki->max_freq);
997 dev_err(hba->dev, "%s: %s clk set rate(%dHz) failed, %d\n",
998 __func__, clki->name,
999 clki->max_freq, ret);
1002 trace_ufshcd_clk_scaling(dev_name(hba->dev),
1003 "scaled up", clki->name,
1007 clki->curr_freq = clki->max_freq;
1009 } else if (!scale_up && clki->min_freq) {
1010 if (clki->curr_freq == clki->min_freq)
1013 ret = clk_set_rate(clki->clk, clki->min_freq);
1015 dev_err(hba->dev, "%s: %s clk set rate(%dHz) failed, %d\n",
1016 __func__, clki->name,
1017 clki->min_freq, ret);
1020 trace_ufshcd_clk_scaling(dev_name(hba->dev),
1021 "scaled down", clki->name,
1024 clki->curr_freq = clki->min_freq;
1027 dev_dbg(hba->dev, "%s: clk: %s, rate: %lu\n", __func__,
1028 clki->name, clk_get_rate(clki->clk));
1036 * ufshcd_scale_clks - scale up or scale down UFS controller clocks
1037 * @hba: per adapter instance
1038 * @scale_up: True if scaling up and false if scaling down
1040 * Returns 0 if successful
1041 * Returns < 0 for any other errors
1043 static int ufshcd_scale_clks(struct ufs_hba *hba, bool scale_up)
1046 ktime_t start = ktime_get();
1048 ret = ufshcd_vops_clk_scale_notify(hba, scale_up, PRE_CHANGE);
1052 ret = ufshcd_set_clk_freq(hba, scale_up);
1056 ret = ufshcd_vops_clk_scale_notify(hba, scale_up, POST_CHANGE);
1058 ufshcd_set_clk_freq(hba, !scale_up);
1061 trace_ufshcd_profile_clk_scaling(dev_name(hba->dev),
1062 (scale_up ? "up" : "down"),
1063 ktime_to_us(ktime_sub(ktime_get(), start)), ret);
1068 * ufshcd_is_devfreq_scaling_required - check if scaling is required or not
1069 * @hba: per adapter instance
1070 * @scale_up: True if scaling up and false if scaling down
1072 * Returns true if scaling is required, false otherwise.
1074 static bool ufshcd_is_devfreq_scaling_required(struct ufs_hba *hba,
1077 struct ufs_clk_info *clki;
1078 struct list_head *head = &hba->clk_list_head;
1080 if (list_empty(head))
1083 list_for_each_entry(clki, head, list) {
1084 if (!IS_ERR_OR_NULL(clki->clk)) {
1085 if (scale_up && clki->max_freq) {
1086 if (clki->curr_freq == clki->max_freq)
1089 } else if (!scale_up && clki->min_freq) {
1090 if (clki->curr_freq == clki->min_freq)
1101 * Determine the number of pending commands by counting the bits in the SCSI
1102 * device budget maps. This approach has been selected because a bit is set in
1103 * the budget map before scsi_host_queue_ready() checks the host_self_blocked
1104 * flag. The host_self_blocked flag can be modified by calling
1105 * scsi_block_requests() or scsi_unblock_requests().
1107 static u32 ufshcd_pending_cmds(struct ufs_hba *hba)
1109 const struct scsi_device *sdev;
1112 lockdep_assert_held(hba->host->host_lock);
1113 __shost_for_each_device(sdev, hba->host)
1114 pending += sbitmap_weight(&sdev->budget_map);
1119 static int ufshcd_wait_for_doorbell_clr(struct ufs_hba *hba,
1120 u64 wait_timeout_us)
1122 unsigned long flags;
1126 bool timeout = false, do_last_check = false;
1129 ufshcd_hold(hba, false);
1130 spin_lock_irqsave(hba->host->host_lock, flags);
1132 * Wait for all the outstanding tasks/transfer requests.
1133 * Verify by checking the doorbell registers are clear.
1135 start = ktime_get();
1137 if (hba->ufshcd_state != UFSHCD_STATE_OPERATIONAL) {
1142 tm_doorbell = ufshcd_readl(hba, REG_UTP_TASK_REQ_DOOR_BELL);
1143 tr_pending = ufshcd_pending_cmds(hba);
1144 if (!tm_doorbell && !tr_pending) {
1147 } else if (do_last_check) {
1151 spin_unlock_irqrestore(hba->host->host_lock, flags);
1153 if (ktime_to_us(ktime_sub(ktime_get(), start)) >
1157 * We might have scheduled out for long time so make
1158 * sure to check if doorbells are cleared by this time
1161 do_last_check = true;
1163 spin_lock_irqsave(hba->host->host_lock, flags);
1164 } while (tm_doorbell || tr_pending);
1168 "%s: timedout waiting for doorbell to clear (tm=0x%x, tr=0x%x)\n",
1169 __func__, tm_doorbell, tr_pending);
1173 spin_unlock_irqrestore(hba->host->host_lock, flags);
1174 ufshcd_release(hba);
1179 * ufshcd_scale_gear - scale up/down UFS gear
1180 * @hba: per adapter instance
1181 * @scale_up: True for scaling up gear and false for scaling down
1183 * Returns 0 for success,
1184 * Returns -EBUSY if scaling can't happen at this time
1185 * Returns non-zero for any other errors
1187 static int ufshcd_scale_gear(struct ufs_hba *hba, bool scale_up)
1190 struct ufs_pa_layer_attr new_pwr_info;
1193 memcpy(&new_pwr_info, &hba->clk_scaling.saved_pwr_info.info,
1194 sizeof(struct ufs_pa_layer_attr));
1196 memcpy(&new_pwr_info, &hba->pwr_info,
1197 sizeof(struct ufs_pa_layer_attr));
1199 if (hba->pwr_info.gear_tx > hba->clk_scaling.min_gear ||
1200 hba->pwr_info.gear_rx > hba->clk_scaling.min_gear) {
1201 /* save the current power mode */
1202 memcpy(&hba->clk_scaling.saved_pwr_info.info,
1204 sizeof(struct ufs_pa_layer_attr));
1206 /* scale down gear */
1207 new_pwr_info.gear_tx = hba->clk_scaling.min_gear;
1208 new_pwr_info.gear_rx = hba->clk_scaling.min_gear;
1212 /* check if the power mode needs to be changed or not? */
1213 ret = ufshcd_config_pwr_mode(hba, &new_pwr_info);
1215 dev_err(hba->dev, "%s: failed err %d, old gear: (tx %d rx %d), new gear: (tx %d rx %d)",
1217 hba->pwr_info.gear_tx, hba->pwr_info.gear_rx,
1218 new_pwr_info.gear_tx, new_pwr_info.gear_rx);
1223 static int ufshcd_clock_scaling_prepare(struct ufs_hba *hba)
1225 #define DOORBELL_CLR_TOUT_US (1000 * 1000) /* 1 sec */
1228 * make sure that there are no outstanding requests when
1229 * clock scaling is in progress
1231 ufshcd_scsi_block_requests(hba);
1232 down_write(&hba->clk_scaling_lock);
1234 if (!hba->clk_scaling.is_allowed ||
1235 ufshcd_wait_for_doorbell_clr(hba, DOORBELL_CLR_TOUT_US)) {
1237 up_write(&hba->clk_scaling_lock);
1238 ufshcd_scsi_unblock_requests(hba);
1242 /* let's not get into low power until clock scaling is completed */
1243 ufshcd_hold(hba, false);
1249 static void ufshcd_clock_scaling_unprepare(struct ufs_hba *hba, bool writelock)
1252 up_write(&hba->clk_scaling_lock);
1254 up_read(&hba->clk_scaling_lock);
1255 ufshcd_scsi_unblock_requests(hba);
1256 ufshcd_release(hba);
1260 * ufshcd_devfreq_scale - scale up/down UFS clocks and gear
1261 * @hba: per adapter instance
1262 * @scale_up: True for scaling up and false for scalin down
1264 * Returns 0 for success,
1265 * Returns -EBUSY if scaling can't happen at this time
1266 * Returns non-zero for any other errors
1268 static int ufshcd_devfreq_scale(struct ufs_hba *hba, bool scale_up)
1271 bool is_writelock = true;
1273 ret = ufshcd_clock_scaling_prepare(hba);
1277 /* scale down the gear before scaling down clocks */
1279 ret = ufshcd_scale_gear(hba, false);
1284 ret = ufshcd_scale_clks(hba, scale_up);
1287 ufshcd_scale_gear(hba, true);
1291 /* scale up the gear after scaling up clocks */
1293 ret = ufshcd_scale_gear(hba, true);
1295 ufshcd_scale_clks(hba, false);
1300 /* Enable Write Booster if we have scaled up else disable it */
1301 downgrade_write(&hba->clk_scaling_lock);
1302 is_writelock = false;
1303 ufshcd_wb_toggle(hba, scale_up);
1306 ufshcd_clock_scaling_unprepare(hba, is_writelock);
1310 static void ufshcd_clk_scaling_suspend_work(struct work_struct *work)
1312 struct ufs_hba *hba = container_of(work, struct ufs_hba,
1313 clk_scaling.suspend_work);
1314 unsigned long irq_flags;
1316 spin_lock_irqsave(hba->host->host_lock, irq_flags);
1317 if (hba->clk_scaling.active_reqs || hba->clk_scaling.is_suspended) {
1318 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1321 hba->clk_scaling.is_suspended = true;
1322 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1324 __ufshcd_suspend_clkscaling(hba);
1327 static void ufshcd_clk_scaling_resume_work(struct work_struct *work)
1329 struct ufs_hba *hba = container_of(work, struct ufs_hba,
1330 clk_scaling.resume_work);
1331 unsigned long irq_flags;
1333 spin_lock_irqsave(hba->host->host_lock, irq_flags);
1334 if (!hba->clk_scaling.is_suspended) {
1335 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1338 hba->clk_scaling.is_suspended = false;
1339 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1341 devfreq_resume_device(hba->devfreq);
1344 static int ufshcd_devfreq_target(struct device *dev,
1345 unsigned long *freq, u32 flags)
1348 struct ufs_hba *hba = dev_get_drvdata(dev);
1350 bool scale_up, sched_clk_scaling_suspend_work = false;
1351 struct list_head *clk_list = &hba->clk_list_head;
1352 struct ufs_clk_info *clki;
1353 unsigned long irq_flags;
1355 if (!ufshcd_is_clkscaling_supported(hba))
1358 clki = list_first_entry(&hba->clk_list_head, struct ufs_clk_info, list);
1359 /* Override with the closest supported frequency */
1360 *freq = (unsigned long) clk_round_rate(clki->clk, *freq);
1361 spin_lock_irqsave(hba->host->host_lock, irq_flags);
1362 if (ufshcd_eh_in_progress(hba)) {
1363 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1367 if (!hba->clk_scaling.active_reqs)
1368 sched_clk_scaling_suspend_work = true;
1370 if (list_empty(clk_list)) {
1371 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1375 /* Decide based on the rounded-off frequency and update */
1376 scale_up = *freq == clki->max_freq;
1378 *freq = clki->min_freq;
1379 /* Update the frequency */
1380 if (!ufshcd_is_devfreq_scaling_required(hba, scale_up)) {
1381 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1383 goto out; /* no state change required */
1385 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1387 start = ktime_get();
1388 ret = ufshcd_devfreq_scale(hba, scale_up);
1390 trace_ufshcd_profile_clk_scaling(dev_name(hba->dev),
1391 (scale_up ? "up" : "down"),
1392 ktime_to_us(ktime_sub(ktime_get(), start)), ret);
1395 if (sched_clk_scaling_suspend_work)
1396 queue_work(hba->clk_scaling.workq,
1397 &hba->clk_scaling.suspend_work);
1402 static int ufshcd_devfreq_get_dev_status(struct device *dev,
1403 struct devfreq_dev_status *stat)
1405 struct ufs_hba *hba = dev_get_drvdata(dev);
1406 struct ufs_clk_scaling *scaling = &hba->clk_scaling;
1407 unsigned long flags;
1408 struct list_head *clk_list = &hba->clk_list_head;
1409 struct ufs_clk_info *clki;
1412 if (!ufshcd_is_clkscaling_supported(hba))
1415 memset(stat, 0, sizeof(*stat));
1417 spin_lock_irqsave(hba->host->host_lock, flags);
1418 curr_t = ktime_get();
1419 if (!scaling->window_start_t)
1422 clki = list_first_entry(clk_list, struct ufs_clk_info, list);
1424 * If current frequency is 0, then the ondemand governor considers
1425 * there's no initial frequency set. And it always requests to set
1426 * to max. frequency.
1428 stat->current_frequency = clki->curr_freq;
1429 if (scaling->is_busy_started)
1430 scaling->tot_busy_t += ktime_us_delta(curr_t,
1431 scaling->busy_start_t);
1433 stat->total_time = ktime_us_delta(curr_t, scaling->window_start_t);
1434 stat->busy_time = scaling->tot_busy_t;
1436 scaling->window_start_t = curr_t;
1437 scaling->tot_busy_t = 0;
1439 if (hba->outstanding_reqs) {
1440 scaling->busy_start_t = curr_t;
1441 scaling->is_busy_started = true;
1443 scaling->busy_start_t = 0;
1444 scaling->is_busy_started = false;
1446 spin_unlock_irqrestore(hba->host->host_lock, flags);
1450 static int ufshcd_devfreq_init(struct ufs_hba *hba)
1452 struct list_head *clk_list = &hba->clk_list_head;
1453 struct ufs_clk_info *clki;
1454 struct devfreq *devfreq;
1457 /* Skip devfreq if we don't have any clocks in the list */
1458 if (list_empty(clk_list))
1461 clki = list_first_entry(clk_list, struct ufs_clk_info, list);
1462 dev_pm_opp_add(hba->dev, clki->min_freq, 0);
1463 dev_pm_opp_add(hba->dev, clki->max_freq, 0);
1465 ufshcd_vops_config_scaling_param(hba, &hba->vps->devfreq_profile,
1466 &hba->vps->ondemand_data);
1467 devfreq = devfreq_add_device(hba->dev,
1468 &hba->vps->devfreq_profile,
1469 DEVFREQ_GOV_SIMPLE_ONDEMAND,
1470 &hba->vps->ondemand_data);
1471 if (IS_ERR(devfreq)) {
1472 ret = PTR_ERR(devfreq);
1473 dev_err(hba->dev, "Unable to register with devfreq %d\n", ret);
1475 dev_pm_opp_remove(hba->dev, clki->min_freq);
1476 dev_pm_opp_remove(hba->dev, clki->max_freq);
1480 hba->devfreq = devfreq;
1485 static void ufshcd_devfreq_remove(struct ufs_hba *hba)
1487 struct list_head *clk_list = &hba->clk_list_head;
1488 struct ufs_clk_info *clki;
1493 devfreq_remove_device(hba->devfreq);
1494 hba->devfreq = NULL;
1496 clki = list_first_entry(clk_list, struct ufs_clk_info, list);
1497 dev_pm_opp_remove(hba->dev, clki->min_freq);
1498 dev_pm_opp_remove(hba->dev, clki->max_freq);
1501 static void __ufshcd_suspend_clkscaling(struct ufs_hba *hba)
1503 unsigned long flags;
1505 devfreq_suspend_device(hba->devfreq);
1506 spin_lock_irqsave(hba->host->host_lock, flags);
1507 hba->clk_scaling.window_start_t = 0;
1508 spin_unlock_irqrestore(hba->host->host_lock, flags);
1511 static void ufshcd_suspend_clkscaling(struct ufs_hba *hba)
1513 unsigned long flags;
1514 bool suspend = false;
1516 cancel_work_sync(&hba->clk_scaling.suspend_work);
1517 cancel_work_sync(&hba->clk_scaling.resume_work);
1519 spin_lock_irqsave(hba->host->host_lock, flags);
1520 if (!hba->clk_scaling.is_suspended) {
1522 hba->clk_scaling.is_suspended = true;
1524 spin_unlock_irqrestore(hba->host->host_lock, flags);
1527 __ufshcd_suspend_clkscaling(hba);
1530 static void ufshcd_resume_clkscaling(struct ufs_hba *hba)
1532 unsigned long flags;
1533 bool resume = false;
1535 spin_lock_irqsave(hba->host->host_lock, flags);
1536 if (hba->clk_scaling.is_suspended) {
1538 hba->clk_scaling.is_suspended = false;
1540 spin_unlock_irqrestore(hba->host->host_lock, flags);
1543 devfreq_resume_device(hba->devfreq);
1546 static ssize_t ufshcd_clkscale_enable_show(struct device *dev,
1547 struct device_attribute *attr, char *buf)
1549 struct ufs_hba *hba = dev_get_drvdata(dev);
1551 return sysfs_emit(buf, "%d\n", hba->clk_scaling.is_enabled);
1554 static ssize_t ufshcd_clkscale_enable_store(struct device *dev,
1555 struct device_attribute *attr, const char *buf, size_t count)
1557 struct ufs_hba *hba = dev_get_drvdata(dev);
1561 if (kstrtou32(buf, 0, &value))
1564 down(&hba->host_sem);
1565 if (!ufshcd_is_user_access_allowed(hba)) {
1571 if (value == hba->clk_scaling.is_enabled)
1574 ufshcd_rpm_get_sync(hba);
1575 ufshcd_hold(hba, false);
1577 hba->clk_scaling.is_enabled = value;
1580 ufshcd_resume_clkscaling(hba);
1582 ufshcd_suspend_clkscaling(hba);
1583 err = ufshcd_devfreq_scale(hba, true);
1585 dev_err(hba->dev, "%s: failed to scale clocks up %d\n",
1589 ufshcd_release(hba);
1590 ufshcd_rpm_put_sync(hba);
1593 return err ? err : count;
1596 static void ufshcd_init_clk_scaling_sysfs(struct ufs_hba *hba)
1598 hba->clk_scaling.enable_attr.show = ufshcd_clkscale_enable_show;
1599 hba->clk_scaling.enable_attr.store = ufshcd_clkscale_enable_store;
1600 sysfs_attr_init(&hba->clk_scaling.enable_attr.attr);
1601 hba->clk_scaling.enable_attr.attr.name = "clkscale_enable";
1602 hba->clk_scaling.enable_attr.attr.mode = 0644;
1603 if (device_create_file(hba->dev, &hba->clk_scaling.enable_attr))
1604 dev_err(hba->dev, "Failed to create sysfs for clkscale_enable\n");
1607 static void ufshcd_remove_clk_scaling_sysfs(struct ufs_hba *hba)
1609 if (hba->clk_scaling.enable_attr.attr.name)
1610 device_remove_file(hba->dev, &hba->clk_scaling.enable_attr);
1613 static void ufshcd_init_clk_scaling(struct ufs_hba *hba)
1615 char wq_name[sizeof("ufs_clkscaling_00")];
1617 if (!ufshcd_is_clkscaling_supported(hba))
1620 if (!hba->clk_scaling.min_gear)
1621 hba->clk_scaling.min_gear = UFS_HS_G1;
1623 INIT_WORK(&hba->clk_scaling.suspend_work,
1624 ufshcd_clk_scaling_suspend_work);
1625 INIT_WORK(&hba->clk_scaling.resume_work,
1626 ufshcd_clk_scaling_resume_work);
1628 snprintf(wq_name, sizeof(wq_name), "ufs_clkscaling_%d",
1629 hba->host->host_no);
1630 hba->clk_scaling.workq = create_singlethread_workqueue(wq_name);
1632 hba->clk_scaling.is_initialized = true;
1635 static void ufshcd_exit_clk_scaling(struct ufs_hba *hba)
1637 if (!hba->clk_scaling.is_initialized)
1640 ufshcd_remove_clk_scaling_sysfs(hba);
1641 destroy_workqueue(hba->clk_scaling.workq);
1642 ufshcd_devfreq_remove(hba);
1643 hba->clk_scaling.is_initialized = false;
1646 static void ufshcd_ungate_work(struct work_struct *work)
1649 unsigned long flags;
1650 struct ufs_hba *hba = container_of(work, struct ufs_hba,
1651 clk_gating.ungate_work);
1653 cancel_delayed_work_sync(&hba->clk_gating.gate_work);
1655 spin_lock_irqsave(hba->host->host_lock, flags);
1656 if (hba->clk_gating.state == CLKS_ON) {
1657 spin_unlock_irqrestore(hba->host->host_lock, flags);
1661 spin_unlock_irqrestore(hba->host->host_lock, flags);
1662 ufshcd_hba_vreg_set_hpm(hba);
1663 ufshcd_setup_clocks(hba, true);
1665 ufshcd_enable_irq(hba);
1667 /* Exit from hibern8 */
1668 if (ufshcd_can_hibern8_during_gating(hba)) {
1669 /* Prevent gating in this path */
1670 hba->clk_gating.is_suspended = true;
1671 if (ufshcd_is_link_hibern8(hba)) {
1672 ret = ufshcd_uic_hibern8_exit(hba);
1674 dev_err(hba->dev, "%s: hibern8 exit failed %d\n",
1677 ufshcd_set_link_active(hba);
1679 hba->clk_gating.is_suspended = false;
1682 ufshcd_scsi_unblock_requests(hba);
1686 * ufshcd_hold - Enable clocks that were gated earlier due to ufshcd_release.
1687 * Also, exit from hibern8 mode and set the link as active.
1688 * @hba: per adapter instance
1689 * @async: This indicates whether caller should ungate clocks asynchronously.
1691 int ufshcd_hold(struct ufs_hba *hba, bool async)
1695 unsigned long flags;
1697 if (!ufshcd_is_clkgating_allowed(hba) ||
1698 !hba->clk_gating.is_initialized)
1700 spin_lock_irqsave(hba->host->host_lock, flags);
1701 hba->clk_gating.active_reqs++;
1704 switch (hba->clk_gating.state) {
1707 * Wait for the ungate work to complete if in progress.
1708 * Though the clocks may be in ON state, the link could
1709 * still be in hibner8 state if hibern8 is allowed
1710 * during clock gating.
1711 * Make sure we exit hibern8 state also in addition to
1714 if (ufshcd_can_hibern8_during_gating(hba) &&
1715 ufshcd_is_link_hibern8(hba)) {
1718 hba->clk_gating.active_reqs--;
1721 spin_unlock_irqrestore(hba->host->host_lock, flags);
1722 flush_result = flush_work(&hba->clk_gating.ungate_work);
1723 if (hba->clk_gating.is_suspended && !flush_result)
1725 spin_lock_irqsave(hba->host->host_lock, flags);
1730 if (cancel_delayed_work(&hba->clk_gating.gate_work)) {
1731 hba->clk_gating.state = CLKS_ON;
1732 trace_ufshcd_clk_gating(dev_name(hba->dev),
1733 hba->clk_gating.state);
1737 * If we are here, it means gating work is either done or
1738 * currently running. Hence, fall through to cancel gating
1739 * work and to enable clocks.
1743 hba->clk_gating.state = REQ_CLKS_ON;
1744 trace_ufshcd_clk_gating(dev_name(hba->dev),
1745 hba->clk_gating.state);
1746 if (queue_work(hba->clk_gating.clk_gating_workq,
1747 &hba->clk_gating.ungate_work))
1748 ufshcd_scsi_block_requests(hba);
1750 * fall through to check if we should wait for this
1751 * work to be done or not.
1757 hba->clk_gating.active_reqs--;
1761 spin_unlock_irqrestore(hba->host->host_lock, flags);
1762 flush_work(&hba->clk_gating.ungate_work);
1763 /* Make sure state is CLKS_ON before returning */
1764 spin_lock_irqsave(hba->host->host_lock, flags);
1767 dev_err(hba->dev, "%s: clk gating is in invalid state %d\n",
1768 __func__, hba->clk_gating.state);
1771 spin_unlock_irqrestore(hba->host->host_lock, flags);
1775 EXPORT_SYMBOL_GPL(ufshcd_hold);
1777 static void ufshcd_gate_work(struct work_struct *work)
1779 struct ufs_hba *hba = container_of(work, struct ufs_hba,
1780 clk_gating.gate_work.work);
1781 unsigned long flags;
1784 spin_lock_irqsave(hba->host->host_lock, flags);
1786 * In case you are here to cancel this work the gating state
1787 * would be marked as REQ_CLKS_ON. In this case save time by
1788 * skipping the gating work and exit after changing the clock
1791 if (hba->clk_gating.is_suspended ||
1792 (hba->clk_gating.state != REQ_CLKS_OFF)) {
1793 hba->clk_gating.state = CLKS_ON;
1794 trace_ufshcd_clk_gating(dev_name(hba->dev),
1795 hba->clk_gating.state);
1799 if (hba->clk_gating.active_reqs
1800 || hba->ufshcd_state != UFSHCD_STATE_OPERATIONAL
1801 || hba->outstanding_reqs || hba->outstanding_tasks
1802 || hba->active_uic_cmd || hba->uic_async_done)
1805 spin_unlock_irqrestore(hba->host->host_lock, flags);
1807 /* put the link into hibern8 mode before turning off clocks */
1808 if (ufshcd_can_hibern8_during_gating(hba)) {
1809 ret = ufshcd_uic_hibern8_enter(hba);
1811 hba->clk_gating.state = CLKS_ON;
1812 dev_err(hba->dev, "%s: hibern8 enter failed %d\n",
1814 trace_ufshcd_clk_gating(dev_name(hba->dev),
1815 hba->clk_gating.state);
1818 ufshcd_set_link_hibern8(hba);
1821 ufshcd_disable_irq(hba);
1823 ufshcd_setup_clocks(hba, false);
1825 /* Put the host controller in low power mode if possible */
1826 ufshcd_hba_vreg_set_lpm(hba);
1828 * In case you are here to cancel this work the gating state
1829 * would be marked as REQ_CLKS_ON. In this case keep the state
1830 * as REQ_CLKS_ON which would anyway imply that clocks are off
1831 * and a request to turn them on is pending. By doing this way,
1832 * we keep the state machine in tact and this would ultimately
1833 * prevent from doing cancel work multiple times when there are
1834 * new requests arriving before the current cancel work is done.
1836 spin_lock_irqsave(hba->host->host_lock, flags);
1837 if (hba->clk_gating.state == REQ_CLKS_OFF) {
1838 hba->clk_gating.state = CLKS_OFF;
1839 trace_ufshcd_clk_gating(dev_name(hba->dev),
1840 hba->clk_gating.state);
1843 spin_unlock_irqrestore(hba->host->host_lock, flags);
1848 /* host lock must be held before calling this variant */
1849 static void __ufshcd_release(struct ufs_hba *hba)
1851 if (!ufshcd_is_clkgating_allowed(hba))
1854 hba->clk_gating.active_reqs--;
1856 if (hba->clk_gating.active_reqs || hba->clk_gating.is_suspended ||
1857 hba->ufshcd_state != UFSHCD_STATE_OPERATIONAL ||
1858 hba->outstanding_tasks || !hba->clk_gating.is_initialized ||
1859 hba->active_uic_cmd || hba->uic_async_done ||
1860 hba->clk_gating.state == CLKS_OFF)
1863 hba->clk_gating.state = REQ_CLKS_OFF;
1864 trace_ufshcd_clk_gating(dev_name(hba->dev), hba->clk_gating.state);
1865 queue_delayed_work(hba->clk_gating.clk_gating_workq,
1866 &hba->clk_gating.gate_work,
1867 msecs_to_jiffies(hba->clk_gating.delay_ms));
1870 void ufshcd_release(struct ufs_hba *hba)
1872 unsigned long flags;
1874 spin_lock_irqsave(hba->host->host_lock, flags);
1875 __ufshcd_release(hba);
1876 spin_unlock_irqrestore(hba->host->host_lock, flags);
1878 EXPORT_SYMBOL_GPL(ufshcd_release);
1880 static ssize_t ufshcd_clkgate_delay_show(struct device *dev,
1881 struct device_attribute *attr, char *buf)
1883 struct ufs_hba *hba = dev_get_drvdata(dev);
1885 return sysfs_emit(buf, "%lu\n", hba->clk_gating.delay_ms);
1888 void ufshcd_clkgate_delay_set(struct device *dev, unsigned long value)
1890 struct ufs_hba *hba = dev_get_drvdata(dev);
1891 unsigned long flags;
1893 spin_lock_irqsave(hba->host->host_lock, flags);
1894 hba->clk_gating.delay_ms = value;
1895 spin_unlock_irqrestore(hba->host->host_lock, flags);
1897 EXPORT_SYMBOL_GPL(ufshcd_clkgate_delay_set);
1899 static ssize_t ufshcd_clkgate_delay_store(struct device *dev,
1900 struct device_attribute *attr, const char *buf, size_t count)
1902 unsigned long value;
1904 if (kstrtoul(buf, 0, &value))
1907 ufshcd_clkgate_delay_set(dev, value);
1911 static ssize_t ufshcd_clkgate_enable_show(struct device *dev,
1912 struct device_attribute *attr, char *buf)
1914 struct ufs_hba *hba = dev_get_drvdata(dev);
1916 return sysfs_emit(buf, "%d\n", hba->clk_gating.is_enabled);
1919 static ssize_t ufshcd_clkgate_enable_store(struct device *dev,
1920 struct device_attribute *attr, const char *buf, size_t count)
1922 struct ufs_hba *hba = dev_get_drvdata(dev);
1923 unsigned long flags;
1926 if (kstrtou32(buf, 0, &value))
1931 spin_lock_irqsave(hba->host->host_lock, flags);
1932 if (value == hba->clk_gating.is_enabled)
1936 __ufshcd_release(hba);
1938 hba->clk_gating.active_reqs++;
1940 hba->clk_gating.is_enabled = value;
1942 spin_unlock_irqrestore(hba->host->host_lock, flags);
1946 static void ufshcd_init_clk_gating_sysfs(struct ufs_hba *hba)
1948 hba->clk_gating.delay_attr.show = ufshcd_clkgate_delay_show;
1949 hba->clk_gating.delay_attr.store = ufshcd_clkgate_delay_store;
1950 sysfs_attr_init(&hba->clk_gating.delay_attr.attr);
1951 hba->clk_gating.delay_attr.attr.name = "clkgate_delay_ms";
1952 hba->clk_gating.delay_attr.attr.mode = 0644;
1953 if (device_create_file(hba->dev, &hba->clk_gating.delay_attr))
1954 dev_err(hba->dev, "Failed to create sysfs for clkgate_delay\n");
1956 hba->clk_gating.enable_attr.show = ufshcd_clkgate_enable_show;
1957 hba->clk_gating.enable_attr.store = ufshcd_clkgate_enable_store;
1958 sysfs_attr_init(&hba->clk_gating.enable_attr.attr);
1959 hba->clk_gating.enable_attr.attr.name = "clkgate_enable";
1960 hba->clk_gating.enable_attr.attr.mode = 0644;
1961 if (device_create_file(hba->dev, &hba->clk_gating.enable_attr))
1962 dev_err(hba->dev, "Failed to create sysfs for clkgate_enable\n");
1965 static void ufshcd_remove_clk_gating_sysfs(struct ufs_hba *hba)
1967 if (hba->clk_gating.delay_attr.attr.name)
1968 device_remove_file(hba->dev, &hba->clk_gating.delay_attr);
1969 if (hba->clk_gating.enable_attr.attr.name)
1970 device_remove_file(hba->dev, &hba->clk_gating.enable_attr);
1973 static void ufshcd_init_clk_gating(struct ufs_hba *hba)
1975 char wq_name[sizeof("ufs_clk_gating_00")];
1977 if (!ufshcd_is_clkgating_allowed(hba))
1980 hba->clk_gating.state = CLKS_ON;
1982 hba->clk_gating.delay_ms = 150;
1983 INIT_DELAYED_WORK(&hba->clk_gating.gate_work, ufshcd_gate_work);
1984 INIT_WORK(&hba->clk_gating.ungate_work, ufshcd_ungate_work);
1986 snprintf(wq_name, ARRAY_SIZE(wq_name), "ufs_clk_gating_%d",
1987 hba->host->host_no);
1988 hba->clk_gating.clk_gating_workq = alloc_ordered_workqueue(wq_name,
1989 WQ_MEM_RECLAIM | WQ_HIGHPRI);
1991 ufshcd_init_clk_gating_sysfs(hba);
1993 hba->clk_gating.is_enabled = true;
1994 hba->clk_gating.is_initialized = true;
1997 static void ufshcd_exit_clk_gating(struct ufs_hba *hba)
1999 if (!hba->clk_gating.is_initialized)
2002 ufshcd_remove_clk_gating_sysfs(hba);
2004 /* Ungate the clock if necessary. */
2005 ufshcd_hold(hba, false);
2006 hba->clk_gating.is_initialized = false;
2007 ufshcd_release(hba);
2009 destroy_workqueue(hba->clk_gating.clk_gating_workq);
2012 /* Must be called with host lock acquired */
2013 static void ufshcd_clk_scaling_start_busy(struct ufs_hba *hba)
2015 bool queue_resume_work = false;
2016 ktime_t curr_t = ktime_get();
2017 unsigned long flags;
2019 if (!ufshcd_is_clkscaling_supported(hba))
2022 spin_lock_irqsave(hba->host->host_lock, flags);
2023 if (!hba->clk_scaling.active_reqs++)
2024 queue_resume_work = true;
2026 if (!hba->clk_scaling.is_enabled || hba->pm_op_in_progress) {
2027 spin_unlock_irqrestore(hba->host->host_lock, flags);
2031 if (queue_resume_work)
2032 queue_work(hba->clk_scaling.workq,
2033 &hba->clk_scaling.resume_work);
2035 if (!hba->clk_scaling.window_start_t) {
2036 hba->clk_scaling.window_start_t = curr_t;
2037 hba->clk_scaling.tot_busy_t = 0;
2038 hba->clk_scaling.is_busy_started = false;
2041 if (!hba->clk_scaling.is_busy_started) {
2042 hba->clk_scaling.busy_start_t = curr_t;
2043 hba->clk_scaling.is_busy_started = true;
2045 spin_unlock_irqrestore(hba->host->host_lock, flags);
2048 static void ufshcd_clk_scaling_update_busy(struct ufs_hba *hba)
2050 struct ufs_clk_scaling *scaling = &hba->clk_scaling;
2051 unsigned long flags;
2053 if (!ufshcd_is_clkscaling_supported(hba))
2056 spin_lock_irqsave(hba->host->host_lock, flags);
2057 hba->clk_scaling.active_reqs--;
2058 if (!hba->outstanding_reqs && scaling->is_busy_started) {
2059 scaling->tot_busy_t += ktime_to_us(ktime_sub(ktime_get(),
2060 scaling->busy_start_t));
2061 scaling->busy_start_t = 0;
2062 scaling->is_busy_started = false;
2064 spin_unlock_irqrestore(hba->host->host_lock, flags);
2067 static inline int ufshcd_monitor_opcode2dir(u8 opcode)
2069 if (opcode == READ_6 || opcode == READ_10 || opcode == READ_16)
2071 else if (opcode == WRITE_6 || opcode == WRITE_10 || opcode == WRITE_16)
2077 static inline bool ufshcd_should_inform_monitor(struct ufs_hba *hba,
2078 struct ufshcd_lrb *lrbp)
2080 const struct ufs_hba_monitor *m = &hba->monitor;
2082 return (m->enabled && lrbp && lrbp->cmd &&
2083 (!m->chunk_size || m->chunk_size == lrbp->cmd->sdb.length) &&
2084 ktime_before(hba->monitor.enabled_ts, lrbp->issue_time_stamp));
2087 static void ufshcd_start_monitor(struct ufs_hba *hba,
2088 const struct ufshcd_lrb *lrbp)
2090 int dir = ufshcd_monitor_opcode2dir(*lrbp->cmd->cmnd);
2091 unsigned long flags;
2093 spin_lock_irqsave(hba->host->host_lock, flags);
2094 if (dir >= 0 && hba->monitor.nr_queued[dir]++ == 0)
2095 hba->monitor.busy_start_ts[dir] = ktime_get();
2096 spin_unlock_irqrestore(hba->host->host_lock, flags);
2099 static void ufshcd_update_monitor(struct ufs_hba *hba, const struct ufshcd_lrb *lrbp)
2101 int dir = ufshcd_monitor_opcode2dir(*lrbp->cmd->cmnd);
2102 unsigned long flags;
2104 spin_lock_irqsave(hba->host->host_lock, flags);
2105 if (dir >= 0 && hba->monitor.nr_queued[dir] > 0) {
2106 const struct request *req = scsi_cmd_to_rq(lrbp->cmd);
2107 struct ufs_hba_monitor *m = &hba->monitor;
2108 ktime_t now, inc, lat;
2110 now = lrbp->compl_time_stamp;
2111 inc = ktime_sub(now, m->busy_start_ts[dir]);
2112 m->total_busy[dir] = ktime_add(m->total_busy[dir], inc);
2113 m->nr_sec_rw[dir] += blk_rq_sectors(req);
2115 /* Update latencies */
2117 lat = ktime_sub(now, lrbp->issue_time_stamp);
2118 m->lat_sum[dir] += lat;
2119 if (m->lat_max[dir] < lat || !m->lat_max[dir])
2120 m->lat_max[dir] = lat;
2121 if (m->lat_min[dir] > lat || !m->lat_min[dir])
2122 m->lat_min[dir] = lat;
2124 m->nr_queued[dir]--;
2125 /* Push forward the busy start of monitor */
2126 m->busy_start_ts[dir] = now;
2128 spin_unlock_irqrestore(hba->host->host_lock, flags);
2132 * ufshcd_send_command - Send SCSI or device management commands
2133 * @hba: per adapter instance
2134 * @task_tag: Task tag of the command
2137 void ufshcd_send_command(struct ufs_hba *hba, unsigned int task_tag)
2139 struct ufshcd_lrb *lrbp = &hba->lrb[task_tag];
2140 unsigned long flags;
2142 lrbp->issue_time_stamp = ktime_get();
2143 lrbp->compl_time_stamp = ktime_set(0, 0);
2144 ufshcd_add_command_trace(hba, task_tag, UFS_CMD_SEND);
2145 ufshcd_clk_scaling_start_busy(hba);
2146 if (unlikely(ufshcd_should_inform_monitor(hba, lrbp)))
2147 ufshcd_start_monitor(hba, lrbp);
2149 spin_lock_irqsave(&hba->outstanding_lock, flags);
2150 if (hba->vops && hba->vops->setup_xfer_req)
2151 hba->vops->setup_xfer_req(hba, task_tag, !!lrbp->cmd);
2152 __set_bit(task_tag, &hba->outstanding_reqs);
2153 ufshcd_writel(hba, 1 << task_tag, REG_UTP_TRANSFER_REQ_DOOR_BELL);
2154 spin_unlock_irqrestore(&hba->outstanding_lock, flags);
2158 * ufshcd_copy_sense_data - Copy sense data in case of check condition
2159 * @lrbp: pointer to local reference block
2161 static inline void ufshcd_copy_sense_data(struct ufshcd_lrb *lrbp)
2163 u8 *const sense_buffer = lrbp->cmd->sense_buffer;
2167 ufshcd_get_rsp_upiu_data_seg_len(lrbp->ucd_rsp_ptr)) {
2170 len = be16_to_cpu(lrbp->ucd_rsp_ptr->sr.sense_data_len);
2171 len_to_copy = min_t(int, UFS_SENSE_SIZE, len);
2173 memcpy(sense_buffer, lrbp->ucd_rsp_ptr->sr.sense_data,
2179 * ufshcd_copy_query_response() - Copy the Query Response and the data
2181 * @hba: per adapter instance
2182 * @lrbp: pointer to local reference block
2185 int ufshcd_copy_query_response(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
2187 struct ufs_query_res *query_res = &hba->dev_cmd.query.response;
2189 memcpy(&query_res->upiu_res, &lrbp->ucd_rsp_ptr->qr, QUERY_OSF_SIZE);
2191 /* Get the descriptor */
2192 if (hba->dev_cmd.query.descriptor &&
2193 lrbp->ucd_rsp_ptr->qr.opcode == UPIU_QUERY_OPCODE_READ_DESC) {
2194 u8 *descp = (u8 *)lrbp->ucd_rsp_ptr +
2195 GENERAL_UPIU_REQUEST_SIZE;
2199 /* data segment length */
2200 resp_len = be32_to_cpu(lrbp->ucd_rsp_ptr->header.dword_2) &
2201 MASK_QUERY_DATA_SEG_LEN;
2202 buf_len = be16_to_cpu(
2203 hba->dev_cmd.query.request.upiu_req.length);
2204 if (likely(buf_len >= resp_len)) {
2205 memcpy(hba->dev_cmd.query.descriptor, descp, resp_len);
2208 "%s: rsp size %d is bigger than buffer size %d",
2209 __func__, resp_len, buf_len);
2218 * ufshcd_hba_capabilities - Read controller capabilities
2219 * @hba: per adapter instance
2221 * Return: 0 on success, negative on error.
2223 static inline int ufshcd_hba_capabilities(struct ufs_hba *hba)
2227 hba->capabilities = ufshcd_readl(hba, REG_CONTROLLER_CAPABILITIES);
2228 if (hba->quirks & UFSHCD_QUIRK_BROKEN_64BIT_ADDRESS)
2229 hba->capabilities &= ~MASK_64_ADDRESSING_SUPPORT;
2231 /* nutrs and nutmrs are 0 based values */
2232 hba->nutrs = (hba->capabilities & MASK_TRANSFER_REQUESTS_SLOTS) + 1;
2234 ((hba->capabilities & MASK_TASK_MANAGEMENT_REQUEST_SLOTS) >> 16) + 1;
2235 hba->reserved_slot = hba->nutrs - 1;
2237 /* Read crypto capabilities */
2238 err = ufshcd_hba_init_crypto_capabilities(hba);
2240 dev_err(hba->dev, "crypto setup failed\n");
2246 * ufshcd_ready_for_uic_cmd - Check if controller is ready
2247 * to accept UIC commands
2248 * @hba: per adapter instance
2249 * Return true on success, else false
2251 static inline bool ufshcd_ready_for_uic_cmd(struct ufs_hba *hba)
2253 return ufshcd_readl(hba, REG_CONTROLLER_STATUS) & UIC_COMMAND_READY;
2257 * ufshcd_get_upmcrs - Get the power mode change request status
2258 * @hba: Pointer to adapter instance
2260 * This function gets the UPMCRS field of HCS register
2261 * Returns value of UPMCRS field
2263 static inline u8 ufshcd_get_upmcrs(struct ufs_hba *hba)
2265 return (ufshcd_readl(hba, REG_CONTROLLER_STATUS) >> 8) & 0x7;
2269 * ufshcd_dispatch_uic_cmd - Dispatch an UIC command to the Unipro layer
2270 * @hba: per adapter instance
2271 * @uic_cmd: UIC command
2274 ufshcd_dispatch_uic_cmd(struct ufs_hba *hba, struct uic_command *uic_cmd)
2276 lockdep_assert_held(&hba->uic_cmd_mutex);
2278 WARN_ON(hba->active_uic_cmd);
2280 hba->active_uic_cmd = uic_cmd;
2283 ufshcd_writel(hba, uic_cmd->argument1, REG_UIC_COMMAND_ARG_1);
2284 ufshcd_writel(hba, uic_cmd->argument2, REG_UIC_COMMAND_ARG_2);
2285 ufshcd_writel(hba, uic_cmd->argument3, REG_UIC_COMMAND_ARG_3);
2287 ufshcd_add_uic_command_trace(hba, uic_cmd, UFS_CMD_SEND);
2290 ufshcd_writel(hba, uic_cmd->command & COMMAND_OPCODE_MASK,
2295 * ufshcd_wait_for_uic_cmd - Wait for completion of an UIC command
2296 * @hba: per adapter instance
2297 * @uic_cmd: UIC command
2299 * Returns 0 only if success.
2302 ufshcd_wait_for_uic_cmd(struct ufs_hba *hba, struct uic_command *uic_cmd)
2305 unsigned long flags;
2307 lockdep_assert_held(&hba->uic_cmd_mutex);
2309 if (wait_for_completion_timeout(&uic_cmd->done,
2310 msecs_to_jiffies(UIC_CMD_TIMEOUT))) {
2311 ret = uic_cmd->argument2 & MASK_UIC_COMMAND_RESULT;
2315 "uic cmd 0x%x with arg3 0x%x completion timeout\n",
2316 uic_cmd->command, uic_cmd->argument3);
2318 if (!uic_cmd->cmd_active) {
2319 dev_err(hba->dev, "%s: UIC cmd has been completed, return the result\n",
2321 ret = uic_cmd->argument2 & MASK_UIC_COMMAND_RESULT;
2325 spin_lock_irqsave(hba->host->host_lock, flags);
2326 hba->active_uic_cmd = NULL;
2327 spin_unlock_irqrestore(hba->host->host_lock, flags);
2333 * __ufshcd_send_uic_cmd - Send UIC commands and retrieve the result
2334 * @hba: per adapter instance
2335 * @uic_cmd: UIC command
2336 * @completion: initialize the completion only if this is set to true
2338 * Returns 0 only if success.
2341 __ufshcd_send_uic_cmd(struct ufs_hba *hba, struct uic_command *uic_cmd,
2344 lockdep_assert_held(&hba->uic_cmd_mutex);
2345 lockdep_assert_held(hba->host->host_lock);
2347 if (!ufshcd_ready_for_uic_cmd(hba)) {
2349 "Controller not ready to accept UIC commands\n");
2354 init_completion(&uic_cmd->done);
2356 uic_cmd->cmd_active = 1;
2357 ufshcd_dispatch_uic_cmd(hba, uic_cmd);
2363 * ufshcd_send_uic_cmd - Send UIC commands and retrieve the result
2364 * @hba: per adapter instance
2365 * @uic_cmd: UIC command
2367 * Returns 0 only if success.
2369 int ufshcd_send_uic_cmd(struct ufs_hba *hba, struct uic_command *uic_cmd)
2372 unsigned long flags;
2374 if (hba->quirks & UFSHCD_QUIRK_BROKEN_UIC_CMD)
2377 ufshcd_hold(hba, false);
2378 mutex_lock(&hba->uic_cmd_mutex);
2379 ufshcd_add_delay_before_dme_cmd(hba);
2381 spin_lock_irqsave(hba->host->host_lock, flags);
2382 ret = __ufshcd_send_uic_cmd(hba, uic_cmd, true);
2383 spin_unlock_irqrestore(hba->host->host_lock, flags);
2385 ret = ufshcd_wait_for_uic_cmd(hba, uic_cmd);
2387 mutex_unlock(&hba->uic_cmd_mutex);
2389 ufshcd_release(hba);
2394 * ufshcd_map_sg - Map scatter-gather list to prdt
2395 * @hba: per adapter instance
2396 * @lrbp: pointer to local reference block
2398 * Returns 0 in case of success, non-zero value in case of failure
2400 static int ufshcd_map_sg(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
2402 struct ufshcd_sg_entry *prd_table;
2403 struct scatterlist *sg;
2404 struct scsi_cmnd *cmd;
2409 sg_segments = scsi_dma_map(cmd);
2410 if (sg_segments < 0)
2415 if (hba->quirks & UFSHCD_QUIRK_PRDT_BYTE_GRAN)
2416 lrbp->utr_descriptor_ptr->prd_table_length =
2417 cpu_to_le16((sg_segments *
2418 sizeof(struct ufshcd_sg_entry)));
2420 lrbp->utr_descriptor_ptr->prd_table_length =
2421 cpu_to_le16(sg_segments);
2423 prd_table = lrbp->ucd_prdt_ptr;
2425 scsi_for_each_sg(cmd, sg, sg_segments, i) {
2426 const unsigned int len = sg_dma_len(sg);
2429 * From the UFSHCI spec: "Data Byte Count (DBC): A '0'
2430 * based value that indicates the length, in bytes, of
2431 * the data block. A maximum of length of 256KB may
2432 * exist for any entry. Bits 1:0 of this field shall be
2433 * 11b to indicate Dword granularity. A value of '3'
2434 * indicates 4 bytes, '7' indicates 8 bytes, etc."
2436 WARN_ONCE(len > 256 * 1024, "len = %#x\n", len);
2437 prd_table[i].size = cpu_to_le32(len - 1);
2438 prd_table[i].addr = cpu_to_le64(sg->dma_address);
2439 prd_table[i].reserved = 0;
2442 lrbp->utr_descriptor_ptr->prd_table_length = 0;
2449 * ufshcd_enable_intr - enable interrupts
2450 * @hba: per adapter instance
2451 * @intrs: interrupt bits
2453 static void ufshcd_enable_intr(struct ufs_hba *hba, u32 intrs)
2455 u32 set = ufshcd_readl(hba, REG_INTERRUPT_ENABLE);
2457 if (hba->ufs_version == ufshci_version(1, 0)) {
2459 rw = set & INTERRUPT_MASK_RW_VER_10;
2460 set = rw | ((set ^ intrs) & intrs);
2465 ufshcd_writel(hba, set, REG_INTERRUPT_ENABLE);
2469 * ufshcd_disable_intr - disable interrupts
2470 * @hba: per adapter instance
2471 * @intrs: interrupt bits
2473 static void ufshcd_disable_intr(struct ufs_hba *hba, u32 intrs)
2475 u32 set = ufshcd_readl(hba, REG_INTERRUPT_ENABLE);
2477 if (hba->ufs_version == ufshci_version(1, 0)) {
2479 rw = (set & INTERRUPT_MASK_RW_VER_10) &
2480 ~(intrs & INTERRUPT_MASK_RW_VER_10);
2481 set = rw | ((set & intrs) & ~INTERRUPT_MASK_RW_VER_10);
2487 ufshcd_writel(hba, set, REG_INTERRUPT_ENABLE);
2491 * ufshcd_prepare_req_desc_hdr() - Fills the requests header
2492 * descriptor according to request
2493 * @lrbp: pointer to local reference block
2494 * @upiu_flags: flags required in the header
2495 * @cmd_dir: requests data direction
2497 static void ufshcd_prepare_req_desc_hdr(struct ufshcd_lrb *lrbp,
2498 u8 *upiu_flags, enum dma_data_direction cmd_dir)
2500 struct utp_transfer_req_desc *req_desc = lrbp->utr_descriptor_ptr;
2506 if (cmd_dir == DMA_FROM_DEVICE) {
2507 data_direction = UTP_DEVICE_TO_HOST;
2508 *upiu_flags = UPIU_CMD_FLAGS_READ;
2509 } else if (cmd_dir == DMA_TO_DEVICE) {
2510 data_direction = UTP_HOST_TO_DEVICE;
2511 *upiu_flags = UPIU_CMD_FLAGS_WRITE;
2513 data_direction = UTP_NO_DATA_TRANSFER;
2514 *upiu_flags = UPIU_CMD_FLAGS_NONE;
2517 dword_0 = data_direction | (lrbp->command_type
2518 << UPIU_COMMAND_TYPE_OFFSET);
2520 dword_0 |= UTP_REQ_DESC_INT_CMD;
2522 /* Prepare crypto related dwords */
2523 ufshcd_prepare_req_desc_hdr_crypto(lrbp, &dword_0, &dword_1, &dword_3);
2525 /* Transfer request descriptor header fields */
2526 req_desc->header.dword_0 = cpu_to_le32(dword_0);
2527 req_desc->header.dword_1 = cpu_to_le32(dword_1);
2529 * assigning invalid value for command status. Controller
2530 * updates OCS on command completion, with the command
2533 req_desc->header.dword_2 =
2534 cpu_to_le32(OCS_INVALID_COMMAND_STATUS);
2535 req_desc->header.dword_3 = cpu_to_le32(dword_3);
2537 req_desc->prd_table_length = 0;
2541 * ufshcd_prepare_utp_scsi_cmd_upiu() - fills the utp_transfer_req_desc,
2543 * @lrbp: local reference block pointer
2544 * @upiu_flags: flags
2547 void ufshcd_prepare_utp_scsi_cmd_upiu(struct ufshcd_lrb *lrbp, u8 upiu_flags)
2549 struct scsi_cmnd *cmd = lrbp->cmd;
2550 struct utp_upiu_req *ucd_req_ptr = lrbp->ucd_req_ptr;
2551 unsigned short cdb_len;
2553 /* command descriptor fields */
2554 ucd_req_ptr->header.dword_0 = UPIU_HEADER_DWORD(
2555 UPIU_TRANSACTION_COMMAND, upiu_flags,
2556 lrbp->lun, lrbp->task_tag);
2557 ucd_req_ptr->header.dword_1 = UPIU_HEADER_DWORD(
2558 UPIU_COMMAND_SET_TYPE_SCSI, 0, 0, 0);
2560 /* Total EHS length and Data segment length will be zero */
2561 ucd_req_ptr->header.dword_2 = 0;
2563 ucd_req_ptr->sc.exp_data_transfer_len = cpu_to_be32(cmd->sdb.length);
2565 cdb_len = min_t(unsigned short, cmd->cmd_len, UFS_CDB_SIZE);
2566 memset(ucd_req_ptr->sc.cdb, 0, UFS_CDB_SIZE);
2567 memcpy(ucd_req_ptr->sc.cdb, cmd->cmnd, cdb_len);
2569 memset(lrbp->ucd_rsp_ptr, 0, sizeof(struct utp_upiu_rsp));
2573 * ufshcd_prepare_utp_query_req_upiu() - fills the utp_transfer_req_desc,
2576 * @lrbp: local reference block pointer
2577 * @upiu_flags: flags
2579 static void ufshcd_prepare_utp_query_req_upiu(struct ufs_hba *hba,
2580 struct ufshcd_lrb *lrbp, u8 upiu_flags)
2582 struct utp_upiu_req *ucd_req_ptr = lrbp->ucd_req_ptr;
2583 struct ufs_query *query = &hba->dev_cmd.query;
2584 u16 len = be16_to_cpu(query->request.upiu_req.length);
2586 /* Query request header */
2587 ucd_req_ptr->header.dword_0 = UPIU_HEADER_DWORD(
2588 UPIU_TRANSACTION_QUERY_REQ, upiu_flags,
2589 lrbp->lun, lrbp->task_tag);
2590 ucd_req_ptr->header.dword_1 = UPIU_HEADER_DWORD(
2591 0, query->request.query_func, 0, 0);
2593 /* Data segment length only need for WRITE_DESC */
2594 if (query->request.upiu_req.opcode == UPIU_QUERY_OPCODE_WRITE_DESC)
2595 ucd_req_ptr->header.dword_2 =
2596 UPIU_HEADER_DWORD(0, 0, (len >> 8), (u8)len);
2598 ucd_req_ptr->header.dword_2 = 0;
2600 /* Copy the Query Request buffer as is */
2601 memcpy(&ucd_req_ptr->qr, &query->request.upiu_req,
2604 /* Copy the Descriptor */
2605 if (query->request.upiu_req.opcode == UPIU_QUERY_OPCODE_WRITE_DESC)
2606 memcpy(ucd_req_ptr + 1, query->descriptor, len);
2608 memset(lrbp->ucd_rsp_ptr, 0, sizeof(struct utp_upiu_rsp));
2611 static inline void ufshcd_prepare_utp_nop_upiu(struct ufshcd_lrb *lrbp)
2613 struct utp_upiu_req *ucd_req_ptr = lrbp->ucd_req_ptr;
2615 memset(ucd_req_ptr, 0, sizeof(struct utp_upiu_req));
2617 /* command descriptor fields */
2618 ucd_req_ptr->header.dword_0 =
2620 UPIU_TRANSACTION_NOP_OUT, 0, 0, lrbp->task_tag);
2621 /* clear rest of the fields of basic header */
2622 ucd_req_ptr->header.dword_1 = 0;
2623 ucd_req_ptr->header.dword_2 = 0;
2625 memset(lrbp->ucd_rsp_ptr, 0, sizeof(struct utp_upiu_rsp));
2629 * ufshcd_compose_devman_upiu - UFS Protocol Information Unit(UPIU)
2630 * for Device Management Purposes
2631 * @hba: per adapter instance
2632 * @lrbp: pointer to local reference block
2634 static int ufshcd_compose_devman_upiu(struct ufs_hba *hba,
2635 struct ufshcd_lrb *lrbp)
2640 if (hba->ufs_version <= ufshci_version(1, 1))
2641 lrbp->command_type = UTP_CMD_TYPE_DEV_MANAGE;
2643 lrbp->command_type = UTP_CMD_TYPE_UFS_STORAGE;
2645 ufshcd_prepare_req_desc_hdr(lrbp, &upiu_flags, DMA_NONE);
2646 if (hba->dev_cmd.type == DEV_CMD_TYPE_QUERY)
2647 ufshcd_prepare_utp_query_req_upiu(hba, lrbp, upiu_flags);
2648 else if (hba->dev_cmd.type == DEV_CMD_TYPE_NOP)
2649 ufshcd_prepare_utp_nop_upiu(lrbp);
2657 * ufshcd_comp_scsi_upiu - UFS Protocol Information Unit(UPIU)
2659 * @hba: per adapter instance
2660 * @lrbp: pointer to local reference block
2662 static int ufshcd_comp_scsi_upiu(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
2667 if (hba->ufs_version <= ufshci_version(1, 1))
2668 lrbp->command_type = UTP_CMD_TYPE_SCSI;
2670 lrbp->command_type = UTP_CMD_TYPE_UFS_STORAGE;
2672 if (likely(lrbp->cmd)) {
2673 ufshcd_prepare_req_desc_hdr(lrbp, &upiu_flags,
2674 lrbp->cmd->sc_data_direction);
2675 ufshcd_prepare_utp_scsi_cmd_upiu(lrbp, upiu_flags);
2684 * ufshcd_upiu_wlun_to_scsi_wlun - maps UPIU W-LUN id to SCSI W-LUN ID
2685 * @upiu_wlun_id: UPIU W-LUN id
2687 * Returns SCSI W-LUN id
2689 static inline u16 ufshcd_upiu_wlun_to_scsi_wlun(u8 upiu_wlun_id)
2691 return (upiu_wlun_id & ~UFS_UPIU_WLUN_ID) | SCSI_W_LUN_BASE;
2694 static inline bool is_device_wlun(struct scsi_device *sdev)
2697 ufshcd_upiu_wlun_to_scsi_wlun(UFS_UPIU_UFS_DEVICE_WLUN);
2701 * Associate the UFS controller queue with the default and poll HCTX types.
2702 * Initialize the mq_map[] arrays.
2704 static int ufshcd_map_queues(struct Scsi_Host *shost)
2708 for (i = 0; i < shost->nr_maps; i++) {
2709 struct blk_mq_queue_map *map = &shost->tag_set.map[i];
2712 case HCTX_TYPE_DEFAULT:
2713 case HCTX_TYPE_POLL:
2716 case HCTX_TYPE_READ:
2722 map->queue_offset = 0;
2723 ret = blk_mq_map_queues(map);
2730 static void ufshcd_init_lrb(struct ufs_hba *hba, struct ufshcd_lrb *lrb, int i)
2732 struct utp_transfer_cmd_desc *cmd_descp = hba->ucdl_base_addr;
2733 struct utp_transfer_req_desc *utrdlp = hba->utrdl_base_addr;
2734 dma_addr_t cmd_desc_element_addr = hba->ucdl_dma_addr +
2735 i * sizeof(struct utp_transfer_cmd_desc);
2736 u16 response_offset = offsetof(struct utp_transfer_cmd_desc,
2738 u16 prdt_offset = offsetof(struct utp_transfer_cmd_desc, prd_table);
2740 lrb->utr_descriptor_ptr = utrdlp + i;
2741 lrb->utrd_dma_addr = hba->utrdl_dma_addr +
2742 i * sizeof(struct utp_transfer_req_desc);
2743 lrb->ucd_req_ptr = (struct utp_upiu_req *)(cmd_descp + i);
2744 lrb->ucd_req_dma_addr = cmd_desc_element_addr;
2745 lrb->ucd_rsp_ptr = (struct utp_upiu_rsp *)cmd_descp[i].response_upiu;
2746 lrb->ucd_rsp_dma_addr = cmd_desc_element_addr + response_offset;
2747 lrb->ucd_prdt_ptr = cmd_descp[i].prd_table;
2748 lrb->ucd_prdt_dma_addr = cmd_desc_element_addr + prdt_offset;
2752 * ufshcd_queuecommand - main entry point for SCSI requests
2753 * @host: SCSI host pointer
2754 * @cmd: command from SCSI Midlayer
2756 * Returns 0 for success, non-zero in case of failure
2758 static int ufshcd_queuecommand(struct Scsi_Host *host, struct scsi_cmnd *cmd)
2760 struct ufs_hba *hba = shost_priv(host);
2761 int tag = scsi_cmd_to_rq(cmd)->tag;
2762 struct ufshcd_lrb *lrbp;
2765 WARN_ONCE(tag < 0 || tag >= hba->nutrs, "Invalid tag %d\n", tag);
2768 * Allows the UFS error handler to wait for prior ufshcd_queuecommand()
2773 switch (hba->ufshcd_state) {
2774 case UFSHCD_STATE_OPERATIONAL:
2776 case UFSHCD_STATE_EH_SCHEDULED_NON_FATAL:
2778 * SCSI error handler can call ->queuecommand() while UFS error
2779 * handler is in progress. Error interrupts could change the
2780 * state from UFSHCD_STATE_RESET to
2781 * UFSHCD_STATE_EH_SCHEDULED_NON_FATAL. Prevent requests
2782 * being issued in that case.
2784 if (ufshcd_eh_in_progress(hba)) {
2785 err = SCSI_MLQUEUE_HOST_BUSY;
2789 case UFSHCD_STATE_EH_SCHEDULED_FATAL:
2791 * pm_runtime_get_sync() is used at error handling preparation
2792 * stage. If a scsi cmd, e.g. the SSU cmd, is sent from hba's
2793 * PM ops, it can never be finished if we let SCSI layer keep
2794 * retrying it, which gets err handler stuck forever. Neither
2795 * can we let the scsi cmd pass through, because UFS is in bad
2796 * state, the scsi cmd may eventually time out, which will get
2797 * err handler blocked for too long. So, just fail the scsi cmd
2798 * sent from PM ops, err handler can recover PM error anyways.
2800 if (hba->pm_op_in_progress) {
2801 hba->force_reset = true;
2802 set_host_byte(cmd, DID_BAD_TARGET);
2807 case UFSHCD_STATE_RESET:
2808 err = SCSI_MLQUEUE_HOST_BUSY;
2810 case UFSHCD_STATE_ERROR:
2811 set_host_byte(cmd, DID_ERROR);
2816 hba->req_abort_count = 0;
2818 err = ufshcd_hold(hba, true);
2820 err = SCSI_MLQUEUE_HOST_BUSY;
2823 WARN_ON(ufshcd_is_clkgating_allowed(hba) &&
2824 (hba->clk_gating.state != CLKS_ON));
2826 lrbp = &hba->lrb[tag];
2829 lrbp->task_tag = tag;
2830 lrbp->lun = ufshcd_scsi_to_upiu_lun(cmd->device->lun);
2831 lrbp->intr_cmd = !ufshcd_is_intr_aggr_allowed(hba);
2833 ufshcd_prepare_lrbp_crypto(scsi_cmd_to_rq(cmd), lrbp);
2835 lrbp->req_abort_skip = false;
2837 ufshpb_prep(hba, lrbp);
2839 ufshcd_comp_scsi_upiu(hba, lrbp);
2841 err = ufshcd_map_sg(hba, lrbp);
2844 ufshcd_release(hba);
2848 ufshcd_send_command(hba, tag);
2853 if (ufs_trigger_eh()) {
2854 unsigned long flags;
2856 spin_lock_irqsave(hba->host->host_lock, flags);
2857 ufshcd_schedule_eh_work(hba);
2858 spin_unlock_irqrestore(hba->host->host_lock, flags);
2864 static int ufshcd_compose_dev_cmd(struct ufs_hba *hba,
2865 struct ufshcd_lrb *lrbp, enum dev_cmd_type cmd_type, int tag)
2868 lrbp->task_tag = tag;
2869 lrbp->lun = 0; /* device management cmd is not specific to any LUN */
2870 lrbp->intr_cmd = true; /* No interrupt aggregation */
2871 ufshcd_prepare_lrbp_crypto(NULL, lrbp);
2872 hba->dev_cmd.type = cmd_type;
2874 return ufshcd_compose_devman_upiu(hba, lrbp);
2878 * Clear all the requests from the controller for which a bit has been set in
2879 * @mask and wait until the controller confirms that these requests have been
2882 static int ufshcd_clear_cmds(struct ufs_hba *hba, u32 mask)
2884 unsigned long flags;
2886 /* clear outstanding transaction before retry */
2887 spin_lock_irqsave(hba->host->host_lock, flags);
2888 ufshcd_utrl_clear(hba, mask);
2889 spin_unlock_irqrestore(hba->host->host_lock, flags);
2892 * wait for h/w to clear corresponding bit in door-bell.
2893 * max. wait is 1 sec.
2895 return ufshcd_wait_for_register(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL,
2896 mask, ~mask, 1000, 1000);
2900 ufshcd_check_query_response(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
2902 struct ufs_query_res *query_res = &hba->dev_cmd.query.response;
2904 /* Get the UPIU response */
2905 query_res->response = ufshcd_get_rsp_upiu_result(lrbp->ucd_rsp_ptr) >>
2906 UPIU_RSP_CODE_OFFSET;
2907 return query_res->response;
2911 * ufshcd_dev_cmd_completion() - handles device management command responses
2912 * @hba: per adapter instance
2913 * @lrbp: pointer to local reference block
2916 ufshcd_dev_cmd_completion(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
2921 hba->ufs_stats.last_hibern8_exit_tstamp = ktime_set(0, 0);
2922 resp = ufshcd_get_req_rsp(lrbp->ucd_rsp_ptr);
2925 case UPIU_TRANSACTION_NOP_IN:
2926 if (hba->dev_cmd.type != DEV_CMD_TYPE_NOP) {
2928 dev_err(hba->dev, "%s: unexpected response %x\n",
2932 case UPIU_TRANSACTION_QUERY_RSP:
2933 err = ufshcd_check_query_response(hba, lrbp);
2935 err = ufshcd_copy_query_response(hba, lrbp);
2937 case UPIU_TRANSACTION_REJECT_UPIU:
2938 /* TODO: handle Reject UPIU Response */
2940 dev_err(hba->dev, "%s: Reject UPIU not fully implemented\n",
2945 dev_err(hba->dev, "%s: Invalid device management cmd response: %x\n",
2953 static int ufshcd_wait_for_dev_cmd(struct ufs_hba *hba,
2954 struct ufshcd_lrb *lrbp, int max_timeout)
2957 unsigned long time_left;
2958 unsigned long flags;
2960 time_left = wait_for_completion_timeout(hba->dev_cmd.complete,
2961 msecs_to_jiffies(max_timeout));
2963 spin_lock_irqsave(hba->host->host_lock, flags);
2964 hba->dev_cmd.complete = NULL;
2965 if (likely(time_left)) {
2966 err = ufshcd_get_tr_ocs(lrbp);
2968 err = ufshcd_dev_cmd_completion(hba, lrbp);
2970 spin_unlock_irqrestore(hba->host->host_lock, flags);
2974 dev_dbg(hba->dev, "%s: dev_cmd request timedout, tag %d\n",
2975 __func__, lrbp->task_tag);
2976 if (!ufshcd_clear_cmds(hba, 1U << lrbp->task_tag))
2977 /* successfully cleared the command, retry if needed */
2980 * in case of an error, after clearing the doorbell,
2981 * we also need to clear the outstanding_request
2984 spin_lock_irqsave(&hba->outstanding_lock, flags);
2985 __clear_bit(lrbp->task_tag, &hba->outstanding_reqs);
2986 spin_unlock_irqrestore(&hba->outstanding_lock, flags);
2993 * ufshcd_exec_dev_cmd - API for sending device management requests
2995 * @cmd_type: specifies the type (NOP, Query...)
2996 * @timeout: timeout in milliseconds
2998 * NOTE: Since there is only one available tag for device management commands,
2999 * it is expected you hold the hba->dev_cmd.lock mutex.
3001 static int ufshcd_exec_dev_cmd(struct ufs_hba *hba,
3002 enum dev_cmd_type cmd_type, int timeout)
3004 DECLARE_COMPLETION_ONSTACK(wait);
3005 const u32 tag = hba->reserved_slot;
3006 struct ufshcd_lrb *lrbp;
3009 /* Protects use of hba->reserved_slot. */
3010 lockdep_assert_held(&hba->dev_cmd.lock);
3012 down_read(&hba->clk_scaling_lock);
3014 lrbp = &hba->lrb[tag];
3016 err = ufshcd_compose_dev_cmd(hba, lrbp, cmd_type, tag);
3020 hba->dev_cmd.complete = &wait;
3022 ufshcd_add_query_upiu_trace(hba, UFS_QUERY_SEND, lrbp->ucd_req_ptr);
3024 ufshcd_send_command(hba, tag);
3025 err = ufshcd_wait_for_dev_cmd(hba, lrbp, timeout);
3026 ufshcd_add_query_upiu_trace(hba, err ? UFS_QUERY_ERR : UFS_QUERY_COMP,
3027 (struct utp_upiu_req *)lrbp->ucd_rsp_ptr);
3030 up_read(&hba->clk_scaling_lock);
3035 * ufshcd_init_query() - init the query response and request parameters
3036 * @hba: per-adapter instance
3037 * @request: address of the request pointer to be initialized
3038 * @response: address of the response pointer to be initialized
3039 * @opcode: operation to perform
3040 * @idn: flag idn to access
3041 * @index: LU number to access
3042 * @selector: query/flag/descriptor further identification
3044 static inline void ufshcd_init_query(struct ufs_hba *hba,
3045 struct ufs_query_req **request, struct ufs_query_res **response,
3046 enum query_opcode opcode, u8 idn, u8 index, u8 selector)
3048 *request = &hba->dev_cmd.query.request;
3049 *response = &hba->dev_cmd.query.response;
3050 memset(*request, 0, sizeof(struct ufs_query_req));
3051 memset(*response, 0, sizeof(struct ufs_query_res));
3052 (*request)->upiu_req.opcode = opcode;
3053 (*request)->upiu_req.idn = idn;
3054 (*request)->upiu_req.index = index;
3055 (*request)->upiu_req.selector = selector;
3058 static int ufshcd_query_flag_retry(struct ufs_hba *hba,
3059 enum query_opcode opcode, enum flag_idn idn, u8 index, bool *flag_res)
3064 for (retries = 0; retries < QUERY_REQ_RETRIES; retries++) {
3065 ret = ufshcd_query_flag(hba, opcode, idn, index, flag_res);
3068 "%s: failed with error %d, retries %d\n",
3069 __func__, ret, retries);
3076 "%s: query attribute, opcode %d, idn %d, failed with error %d after %d retries\n",
3077 __func__, opcode, idn, ret, retries);
3082 * ufshcd_query_flag() - API function for sending flag query requests
3083 * @hba: per-adapter instance
3084 * @opcode: flag query to perform
3085 * @idn: flag idn to access
3086 * @index: flag index to access
3087 * @flag_res: the flag value after the query request completes
3089 * Returns 0 for success, non-zero in case of failure
3091 int ufshcd_query_flag(struct ufs_hba *hba, enum query_opcode opcode,
3092 enum flag_idn idn, u8 index, bool *flag_res)
3094 struct ufs_query_req *request = NULL;
3095 struct ufs_query_res *response = NULL;
3096 int err, selector = 0;
3097 int timeout = QUERY_REQ_TIMEOUT;
3101 ufshcd_hold(hba, false);
3102 mutex_lock(&hba->dev_cmd.lock);
3103 ufshcd_init_query(hba, &request, &response, opcode, idn, index,
3107 case UPIU_QUERY_OPCODE_SET_FLAG:
3108 case UPIU_QUERY_OPCODE_CLEAR_FLAG:
3109 case UPIU_QUERY_OPCODE_TOGGLE_FLAG:
3110 request->query_func = UPIU_QUERY_FUNC_STANDARD_WRITE_REQUEST;
3112 case UPIU_QUERY_OPCODE_READ_FLAG:
3113 request->query_func = UPIU_QUERY_FUNC_STANDARD_READ_REQUEST;
3115 /* No dummy reads */
3116 dev_err(hba->dev, "%s: Invalid argument for read request\n",
3124 "%s: Expected query flag opcode but got = %d\n",
3130 err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_QUERY, timeout);
3134 "%s: Sending flag query for idn %d failed, err = %d\n",
3135 __func__, idn, err);
3140 *flag_res = (be32_to_cpu(response->upiu_res.value) &
3141 MASK_QUERY_UPIU_FLAG_LOC) & 0x1;
3144 mutex_unlock(&hba->dev_cmd.lock);
3145 ufshcd_release(hba);
3150 * ufshcd_query_attr - API function for sending attribute requests
3151 * @hba: per-adapter instance
3152 * @opcode: attribute opcode
3153 * @idn: attribute idn to access
3154 * @index: index field
3155 * @selector: selector field
3156 * @attr_val: the attribute value after the query request completes
3158 * Returns 0 for success, non-zero in case of failure
3160 int ufshcd_query_attr(struct ufs_hba *hba, enum query_opcode opcode,
3161 enum attr_idn idn, u8 index, u8 selector, u32 *attr_val)
3163 struct ufs_query_req *request = NULL;
3164 struct ufs_query_res *response = NULL;
3170 dev_err(hba->dev, "%s: attribute value required for opcode 0x%x\n",
3175 ufshcd_hold(hba, false);
3177 mutex_lock(&hba->dev_cmd.lock);
3178 ufshcd_init_query(hba, &request, &response, opcode, idn, index,
3182 case UPIU_QUERY_OPCODE_WRITE_ATTR:
3183 request->query_func = UPIU_QUERY_FUNC_STANDARD_WRITE_REQUEST;
3184 request->upiu_req.value = cpu_to_be32(*attr_val);
3186 case UPIU_QUERY_OPCODE_READ_ATTR:
3187 request->query_func = UPIU_QUERY_FUNC_STANDARD_READ_REQUEST;
3190 dev_err(hba->dev, "%s: Expected query attr opcode but got = 0x%.2x\n",
3196 err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_QUERY, QUERY_REQ_TIMEOUT);
3199 dev_err(hba->dev, "%s: opcode 0x%.2x for idn %d failed, index %d, err = %d\n",
3200 __func__, opcode, idn, index, err);
3204 *attr_val = be32_to_cpu(response->upiu_res.value);
3207 mutex_unlock(&hba->dev_cmd.lock);
3208 ufshcd_release(hba);
3213 * ufshcd_query_attr_retry() - API function for sending query
3214 * attribute with retries
3215 * @hba: per-adapter instance
3216 * @opcode: attribute opcode
3217 * @idn: attribute idn to access
3218 * @index: index field
3219 * @selector: selector field
3220 * @attr_val: the attribute value after the query request
3223 * Returns 0 for success, non-zero in case of failure
3225 int ufshcd_query_attr_retry(struct ufs_hba *hba,
3226 enum query_opcode opcode, enum attr_idn idn, u8 index, u8 selector,
3232 for (retries = QUERY_REQ_RETRIES; retries > 0; retries--) {
3233 ret = ufshcd_query_attr(hba, opcode, idn, index,
3234 selector, attr_val);
3236 dev_dbg(hba->dev, "%s: failed with error %d, retries %d\n",
3237 __func__, ret, retries);
3244 "%s: query attribute, idn %d, failed with error %d after %d retries\n",
3245 __func__, idn, ret, QUERY_REQ_RETRIES);
3249 static int __ufshcd_query_descriptor(struct ufs_hba *hba,
3250 enum query_opcode opcode, enum desc_idn idn, u8 index,
3251 u8 selector, u8 *desc_buf, int *buf_len)
3253 struct ufs_query_req *request = NULL;
3254 struct ufs_query_res *response = NULL;
3260 dev_err(hba->dev, "%s: descriptor buffer required for opcode 0x%x\n",
3265 if (*buf_len < QUERY_DESC_MIN_SIZE || *buf_len > QUERY_DESC_MAX_SIZE) {
3266 dev_err(hba->dev, "%s: descriptor buffer size (%d) is out of range\n",
3267 __func__, *buf_len);
3271 ufshcd_hold(hba, false);
3273 mutex_lock(&hba->dev_cmd.lock);
3274 ufshcd_init_query(hba, &request, &response, opcode, idn, index,
3276 hba->dev_cmd.query.descriptor = desc_buf;
3277 request->upiu_req.length = cpu_to_be16(*buf_len);
3280 case UPIU_QUERY_OPCODE_WRITE_DESC:
3281 request->query_func = UPIU_QUERY_FUNC_STANDARD_WRITE_REQUEST;
3283 case UPIU_QUERY_OPCODE_READ_DESC:
3284 request->query_func = UPIU_QUERY_FUNC_STANDARD_READ_REQUEST;
3288 "%s: Expected query descriptor opcode but got = 0x%.2x\n",
3294 err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_QUERY, QUERY_REQ_TIMEOUT);
3297 dev_err(hba->dev, "%s: opcode 0x%.2x for idn %d failed, index %d, err = %d\n",
3298 __func__, opcode, idn, index, err);
3302 *buf_len = be16_to_cpu(response->upiu_res.length);
3305 hba->dev_cmd.query.descriptor = NULL;
3306 mutex_unlock(&hba->dev_cmd.lock);
3307 ufshcd_release(hba);
3312 * ufshcd_query_descriptor_retry - API function for sending descriptor requests
3313 * @hba: per-adapter instance
3314 * @opcode: attribute opcode
3315 * @idn: attribute idn to access
3316 * @index: index field
3317 * @selector: selector field
3318 * @desc_buf: the buffer that contains the descriptor
3319 * @buf_len: length parameter passed to the device
3321 * Returns 0 for success, non-zero in case of failure.
3322 * The buf_len parameter will contain, on return, the length parameter
3323 * received on the response.
3325 int ufshcd_query_descriptor_retry(struct ufs_hba *hba,
3326 enum query_opcode opcode,
3327 enum desc_idn idn, u8 index,
3329 u8 *desc_buf, int *buf_len)
3334 for (retries = QUERY_REQ_RETRIES; retries > 0; retries--) {
3335 err = __ufshcd_query_descriptor(hba, opcode, idn, index,
3336 selector, desc_buf, buf_len);
3337 if (!err || err == -EINVAL)
3345 * ufshcd_map_desc_id_to_length - map descriptor IDN to its length
3346 * @hba: Pointer to adapter instance
3347 * @desc_id: descriptor idn value
3348 * @desc_len: mapped desc length (out)
3350 void ufshcd_map_desc_id_to_length(struct ufs_hba *hba, enum desc_idn desc_id,
3353 if (desc_id >= QUERY_DESC_IDN_MAX || desc_id == QUERY_DESC_IDN_RFU_0 ||
3354 desc_id == QUERY_DESC_IDN_RFU_1)
3357 *desc_len = hba->desc_size[desc_id];
3359 EXPORT_SYMBOL(ufshcd_map_desc_id_to_length);
3361 static void ufshcd_update_desc_length(struct ufs_hba *hba,
3362 enum desc_idn desc_id, int desc_index,
3363 unsigned char desc_len)
3365 if (hba->desc_size[desc_id] == QUERY_DESC_MAX_SIZE &&
3366 desc_id != QUERY_DESC_IDN_STRING && desc_index != UFS_RPMB_UNIT)
3367 /* For UFS 3.1, the normal unit descriptor is 10 bytes larger
3368 * than the RPMB unit, however, both descriptors share the same
3369 * desc_idn, to cover both unit descriptors with one length, we
3370 * choose the normal unit descriptor length by desc_index.
3372 hba->desc_size[desc_id] = desc_len;
3376 * ufshcd_read_desc_param - read the specified descriptor parameter
3377 * @hba: Pointer to adapter instance
3378 * @desc_id: descriptor idn value
3379 * @desc_index: descriptor index
3380 * @param_offset: offset of the parameter to read
3381 * @param_read_buf: pointer to buffer where parameter would be read
3382 * @param_size: sizeof(param_read_buf)
3384 * Return 0 in case of success, non-zero otherwise
3386 int ufshcd_read_desc_param(struct ufs_hba *hba,
3387 enum desc_idn desc_id,
3396 bool is_kmalloc = true;
3399 if (desc_id >= QUERY_DESC_IDN_MAX || !param_size)
3402 /* Get the length of descriptor */
3403 ufshcd_map_desc_id_to_length(hba, desc_id, &buff_len);
3405 dev_err(hba->dev, "%s: Failed to get desc length\n", __func__);
3409 if (param_offset >= buff_len) {
3410 dev_err(hba->dev, "%s: Invalid offset 0x%x in descriptor IDN 0x%x, length 0x%x\n",
3411 __func__, param_offset, desc_id, buff_len);
3415 /* Check whether we need temp memory */
3416 if (param_offset != 0 || param_size < buff_len) {
3417 desc_buf = kzalloc(buff_len, GFP_KERNEL);
3421 desc_buf = param_read_buf;
3425 /* Request for full descriptor */
3426 ret = ufshcd_query_descriptor_retry(hba, UPIU_QUERY_OPCODE_READ_DESC,
3427 desc_id, desc_index, 0,
3428 desc_buf, &buff_len);
3431 dev_err(hba->dev, "%s: Failed reading descriptor. desc_id %d, desc_index %d, param_offset %d, ret %d\n",
3432 __func__, desc_id, desc_index, param_offset, ret);
3437 if (desc_buf[QUERY_DESC_DESC_TYPE_OFFSET] != desc_id) {
3438 dev_err(hba->dev, "%s: invalid desc_id %d in descriptor header\n",
3439 __func__, desc_buf[QUERY_DESC_DESC_TYPE_OFFSET]);
3444 /* Update descriptor length */
3445 buff_len = desc_buf[QUERY_DESC_LENGTH_OFFSET];
3446 ufshcd_update_desc_length(hba, desc_id, desc_index, buff_len);
3449 /* Make sure we don't copy more data than available */
3450 if (param_offset >= buff_len)
3453 memcpy(param_read_buf, &desc_buf[param_offset],
3454 min_t(u32, param_size, buff_len - param_offset));
3463 * struct uc_string_id - unicode string
3465 * @len: size of this descriptor inclusive
3466 * @type: descriptor type
3467 * @uc: unicode string character
3469 struct uc_string_id {
3475 /* replace non-printable or non-ASCII characters with spaces */
3476 static inline char ufshcd_remove_non_printable(u8 ch)
3478 return (ch >= 0x20 && ch <= 0x7e) ? ch : ' ';
3482 * ufshcd_read_string_desc - read string descriptor
3483 * @hba: pointer to adapter instance
3484 * @desc_index: descriptor index
3485 * @buf: pointer to buffer where descriptor would be read,
3486 * the caller should free the memory.
3487 * @ascii: if true convert from unicode to ascii characters
3488 * null terminated string.
3491 * * string size on success.
3492 * * -ENOMEM: on allocation failure
3493 * * -EINVAL: on a wrong parameter
3495 int ufshcd_read_string_desc(struct ufs_hba *hba, u8 desc_index,
3496 u8 **buf, bool ascii)
3498 struct uc_string_id *uc_str;
3505 uc_str = kzalloc(QUERY_DESC_MAX_SIZE, GFP_KERNEL);
3509 ret = ufshcd_read_desc_param(hba, QUERY_DESC_IDN_STRING, desc_index, 0,
3510 (u8 *)uc_str, QUERY_DESC_MAX_SIZE);
3512 dev_err(hba->dev, "Reading String Desc failed after %d retries. err = %d\n",
3513 QUERY_REQ_RETRIES, ret);
3518 if (uc_str->len <= QUERY_DESC_HDR_SIZE) {
3519 dev_dbg(hba->dev, "String Desc is of zero length\n");
3528 /* remove header and divide by 2 to move from UTF16 to UTF8 */
3529 ascii_len = (uc_str->len - QUERY_DESC_HDR_SIZE) / 2 + 1;
3530 str = kzalloc(ascii_len, GFP_KERNEL);
3537 * the descriptor contains string in UTF16 format
3538 * we need to convert to utf-8 so it can be displayed
3540 ret = utf16s_to_utf8s(uc_str->uc,
3541 uc_str->len - QUERY_DESC_HDR_SIZE,
3542 UTF16_BIG_ENDIAN, str, ascii_len);
3544 /* replace non-printable or non-ASCII characters with spaces */
3545 for (i = 0; i < ret; i++)
3546 str[i] = ufshcd_remove_non_printable(str[i]);
3551 str = kmemdup(uc_str, uc_str->len, GFP_KERNEL);
3565 * ufshcd_read_unit_desc_param - read the specified unit descriptor parameter
3566 * @hba: Pointer to adapter instance
3568 * @param_offset: offset of the parameter to read
3569 * @param_read_buf: pointer to buffer where parameter would be read
3570 * @param_size: sizeof(param_read_buf)
3572 * Return 0 in case of success, non-zero otherwise
3574 static inline int ufshcd_read_unit_desc_param(struct ufs_hba *hba,
3576 enum unit_desc_param param_offset,
3581 * Unit descriptors are only available for general purpose LUs (LUN id
3582 * from 0 to 7) and RPMB Well known LU.
3584 if (!ufs_is_valid_unit_desc_lun(&hba->dev_info, lun, param_offset))
3587 return ufshcd_read_desc_param(hba, QUERY_DESC_IDN_UNIT, lun,
3588 param_offset, param_read_buf, param_size);
3591 static int ufshcd_get_ref_clk_gating_wait(struct ufs_hba *hba)
3594 u32 gating_wait = UFSHCD_REF_CLK_GATING_WAIT_US;
3596 if (hba->dev_info.wspecversion >= 0x300) {
3597 err = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
3598 QUERY_ATTR_IDN_REF_CLK_GATING_WAIT_TIME, 0, 0,
3601 dev_err(hba->dev, "Failed reading bRefClkGatingWait. err = %d, use default %uus\n",
3604 if (gating_wait == 0) {
3605 gating_wait = UFSHCD_REF_CLK_GATING_WAIT_US;
3606 dev_err(hba->dev, "Undefined ref clk gating wait time, use default %uus\n",
3610 hba->dev_info.clk_gating_wait_us = gating_wait;
3617 * ufshcd_memory_alloc - allocate memory for host memory space data structures
3618 * @hba: per adapter instance
3620 * 1. Allocate DMA memory for Command Descriptor array
3621 * Each command descriptor consist of Command UPIU, Response UPIU and PRDT
3622 * 2. Allocate DMA memory for UTP Transfer Request Descriptor List (UTRDL).
3623 * 3. Allocate DMA memory for UTP Task Management Request Descriptor List
3625 * 4. Allocate memory for local reference block(lrb).
3627 * Returns 0 for success, non-zero in case of failure
3629 static int ufshcd_memory_alloc(struct ufs_hba *hba)
3631 size_t utmrdl_size, utrdl_size, ucdl_size;
3633 /* Allocate memory for UTP command descriptors */
3634 ucdl_size = (sizeof(struct utp_transfer_cmd_desc) * hba->nutrs);
3635 hba->ucdl_base_addr = dmam_alloc_coherent(hba->dev,
3637 &hba->ucdl_dma_addr,
3641 * UFSHCI requires UTP command descriptor to be 128 byte aligned.
3642 * make sure hba->ucdl_dma_addr is aligned to PAGE_SIZE
3643 * if hba->ucdl_dma_addr is aligned to PAGE_SIZE, then it will
3644 * be aligned to 128 bytes as well
3646 if (!hba->ucdl_base_addr ||
3647 WARN_ON(hba->ucdl_dma_addr & (PAGE_SIZE - 1))) {
3649 "Command Descriptor Memory allocation failed\n");
3654 * Allocate memory for UTP Transfer descriptors
3655 * UFSHCI requires 1024 byte alignment of UTRD
3657 utrdl_size = (sizeof(struct utp_transfer_req_desc) * hba->nutrs);
3658 hba->utrdl_base_addr = dmam_alloc_coherent(hba->dev,
3660 &hba->utrdl_dma_addr,
3662 if (!hba->utrdl_base_addr ||
3663 WARN_ON(hba->utrdl_dma_addr & (PAGE_SIZE - 1))) {
3665 "Transfer Descriptor Memory allocation failed\n");
3670 * Allocate memory for UTP Task Management descriptors
3671 * UFSHCI requires 1024 byte alignment of UTMRD
3673 utmrdl_size = sizeof(struct utp_task_req_desc) * hba->nutmrs;
3674 hba->utmrdl_base_addr = dmam_alloc_coherent(hba->dev,
3676 &hba->utmrdl_dma_addr,
3678 if (!hba->utmrdl_base_addr ||
3679 WARN_ON(hba->utmrdl_dma_addr & (PAGE_SIZE - 1))) {
3681 "Task Management Descriptor Memory allocation failed\n");
3685 /* Allocate memory for local reference block */
3686 hba->lrb = devm_kcalloc(hba->dev,
3687 hba->nutrs, sizeof(struct ufshcd_lrb),
3690 dev_err(hba->dev, "LRB Memory allocation failed\n");
3699 * ufshcd_host_memory_configure - configure local reference block with
3701 * @hba: per adapter instance
3703 * Configure Host memory space
3704 * 1. Update Corresponding UTRD.UCDBA and UTRD.UCDBAU with UCD DMA
3706 * 2. Update each UTRD with Response UPIU offset, Response UPIU length
3708 * 3. Save the corresponding addresses of UTRD, UCD.CMD, UCD.RSP and UCD.PRDT
3709 * into local reference block.
3711 static void ufshcd_host_memory_configure(struct ufs_hba *hba)
3713 struct utp_transfer_req_desc *utrdlp;
3714 dma_addr_t cmd_desc_dma_addr;
3715 dma_addr_t cmd_desc_element_addr;
3716 u16 response_offset;
3721 utrdlp = hba->utrdl_base_addr;
3724 offsetof(struct utp_transfer_cmd_desc, response_upiu);
3726 offsetof(struct utp_transfer_cmd_desc, prd_table);
3728 cmd_desc_size = sizeof(struct utp_transfer_cmd_desc);
3729 cmd_desc_dma_addr = hba->ucdl_dma_addr;
3731 for (i = 0; i < hba->nutrs; i++) {
3732 /* Configure UTRD with command descriptor base address */
3733 cmd_desc_element_addr =
3734 (cmd_desc_dma_addr + (cmd_desc_size * i));
3735 utrdlp[i].command_desc_base_addr_lo =
3736 cpu_to_le32(lower_32_bits(cmd_desc_element_addr));
3737 utrdlp[i].command_desc_base_addr_hi =
3738 cpu_to_le32(upper_32_bits(cmd_desc_element_addr));
3740 /* Response upiu and prdt offset should be in double words */
3741 if (hba->quirks & UFSHCD_QUIRK_PRDT_BYTE_GRAN) {
3742 utrdlp[i].response_upiu_offset =
3743 cpu_to_le16(response_offset);
3744 utrdlp[i].prd_table_offset =
3745 cpu_to_le16(prdt_offset);
3746 utrdlp[i].response_upiu_length =
3747 cpu_to_le16(ALIGNED_UPIU_SIZE);
3749 utrdlp[i].response_upiu_offset =
3750 cpu_to_le16(response_offset >> 2);
3751 utrdlp[i].prd_table_offset =
3752 cpu_to_le16(prdt_offset >> 2);
3753 utrdlp[i].response_upiu_length =
3754 cpu_to_le16(ALIGNED_UPIU_SIZE >> 2);
3757 ufshcd_init_lrb(hba, &hba->lrb[i], i);
3762 * ufshcd_dme_link_startup - Notify Unipro to perform link startup
3763 * @hba: per adapter instance
3765 * UIC_CMD_DME_LINK_STARTUP command must be issued to Unipro layer,
3766 * in order to initialize the Unipro link startup procedure.
3767 * Once the Unipro links are up, the device connected to the controller
3770 * Returns 0 on success, non-zero value on failure
3772 static int ufshcd_dme_link_startup(struct ufs_hba *hba)
3774 struct uic_command uic_cmd = {0};
3777 uic_cmd.command = UIC_CMD_DME_LINK_STARTUP;
3779 ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
3782 "dme-link-startup: error code %d\n", ret);
3786 * ufshcd_dme_reset - UIC command for DME_RESET
3787 * @hba: per adapter instance
3789 * DME_RESET command is issued in order to reset UniPro stack.
3790 * This function now deals with cold reset.
3792 * Returns 0 on success, non-zero value on failure
3794 static int ufshcd_dme_reset(struct ufs_hba *hba)
3796 struct uic_command uic_cmd = {0};
3799 uic_cmd.command = UIC_CMD_DME_RESET;
3801 ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
3804 "dme-reset: error code %d\n", ret);
3809 int ufshcd_dme_configure_adapt(struct ufs_hba *hba,
3815 if (agreed_gear < UFS_HS_G4)
3816 adapt_val = PA_NO_ADAPT;
3818 ret = ufshcd_dme_set(hba,
3819 UIC_ARG_MIB(PA_TXHSADAPTTYPE),
3823 EXPORT_SYMBOL_GPL(ufshcd_dme_configure_adapt);
3826 * ufshcd_dme_enable - UIC command for DME_ENABLE
3827 * @hba: per adapter instance
3829 * DME_ENABLE command is issued in order to enable UniPro stack.
3831 * Returns 0 on success, non-zero value on failure
3833 static int ufshcd_dme_enable(struct ufs_hba *hba)
3835 struct uic_command uic_cmd = {0};
3838 uic_cmd.command = UIC_CMD_DME_ENABLE;
3840 ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
3843 "dme-enable: error code %d\n", ret);
3848 static inline void ufshcd_add_delay_before_dme_cmd(struct ufs_hba *hba)
3850 #define MIN_DELAY_BEFORE_DME_CMDS_US 1000
3851 unsigned long min_sleep_time_us;
3853 if (!(hba->quirks & UFSHCD_QUIRK_DELAY_BEFORE_DME_CMDS))
3857 * last_dme_cmd_tstamp will be 0 only for 1st call to
3860 if (unlikely(!ktime_to_us(hba->last_dme_cmd_tstamp))) {
3861 min_sleep_time_us = MIN_DELAY_BEFORE_DME_CMDS_US;
3863 unsigned long delta =
3864 (unsigned long) ktime_to_us(
3865 ktime_sub(ktime_get(),
3866 hba->last_dme_cmd_tstamp));
3868 if (delta < MIN_DELAY_BEFORE_DME_CMDS_US)
3870 MIN_DELAY_BEFORE_DME_CMDS_US - delta;
3872 return; /* no more delay required */
3875 /* allow sleep for extra 50us if needed */
3876 usleep_range(min_sleep_time_us, min_sleep_time_us + 50);
3880 * ufshcd_dme_set_attr - UIC command for DME_SET, DME_PEER_SET
3881 * @hba: per adapter instance
3882 * @attr_sel: uic command argument1
3883 * @attr_set: attribute set type as uic command argument2
3884 * @mib_val: setting value as uic command argument3
3885 * @peer: indicate whether peer or local
3887 * Returns 0 on success, non-zero value on failure
3889 int ufshcd_dme_set_attr(struct ufs_hba *hba, u32 attr_sel,
3890 u8 attr_set, u32 mib_val, u8 peer)
3892 struct uic_command uic_cmd = {0};
3893 static const char *const action[] = {
3897 const char *set = action[!!peer];
3899 int retries = UFS_UIC_COMMAND_RETRIES;
3901 uic_cmd.command = peer ?
3902 UIC_CMD_DME_PEER_SET : UIC_CMD_DME_SET;
3903 uic_cmd.argument1 = attr_sel;
3904 uic_cmd.argument2 = UIC_ARG_ATTR_TYPE(attr_set);
3905 uic_cmd.argument3 = mib_val;
3908 /* for peer attributes we retry upon failure */
3909 ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
3911 dev_dbg(hba->dev, "%s: attr-id 0x%x val 0x%x error code %d\n",
3912 set, UIC_GET_ATTR_ID(attr_sel), mib_val, ret);
3913 } while (ret && peer && --retries);
3916 dev_err(hba->dev, "%s: attr-id 0x%x val 0x%x failed %d retries\n",
3917 set, UIC_GET_ATTR_ID(attr_sel), mib_val,
3918 UFS_UIC_COMMAND_RETRIES - retries);
3922 EXPORT_SYMBOL_GPL(ufshcd_dme_set_attr);
3925 * ufshcd_dme_get_attr - UIC command for DME_GET, DME_PEER_GET
3926 * @hba: per adapter instance
3927 * @attr_sel: uic command argument1
3928 * @mib_val: the value of the attribute as returned by the UIC command
3929 * @peer: indicate whether peer or local
3931 * Returns 0 on success, non-zero value on failure
3933 int ufshcd_dme_get_attr(struct ufs_hba *hba, u32 attr_sel,
3934 u32 *mib_val, u8 peer)
3936 struct uic_command uic_cmd = {0};
3937 static const char *const action[] = {
3941 const char *get = action[!!peer];
3943 int retries = UFS_UIC_COMMAND_RETRIES;
3944 struct ufs_pa_layer_attr orig_pwr_info;
3945 struct ufs_pa_layer_attr temp_pwr_info;
3946 bool pwr_mode_change = false;
3948 if (peer && (hba->quirks & UFSHCD_QUIRK_DME_PEER_ACCESS_AUTO_MODE)) {
3949 orig_pwr_info = hba->pwr_info;
3950 temp_pwr_info = orig_pwr_info;
3952 if (orig_pwr_info.pwr_tx == FAST_MODE ||
3953 orig_pwr_info.pwr_rx == FAST_MODE) {
3954 temp_pwr_info.pwr_tx = FASTAUTO_MODE;
3955 temp_pwr_info.pwr_rx = FASTAUTO_MODE;
3956 pwr_mode_change = true;
3957 } else if (orig_pwr_info.pwr_tx == SLOW_MODE ||
3958 orig_pwr_info.pwr_rx == SLOW_MODE) {
3959 temp_pwr_info.pwr_tx = SLOWAUTO_MODE;
3960 temp_pwr_info.pwr_rx = SLOWAUTO_MODE;
3961 pwr_mode_change = true;
3963 if (pwr_mode_change) {
3964 ret = ufshcd_change_power_mode(hba, &temp_pwr_info);
3970 uic_cmd.command = peer ?
3971 UIC_CMD_DME_PEER_GET : UIC_CMD_DME_GET;
3972 uic_cmd.argument1 = attr_sel;
3975 /* for peer attributes we retry upon failure */
3976 ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
3978 dev_dbg(hba->dev, "%s: attr-id 0x%x error code %d\n",
3979 get, UIC_GET_ATTR_ID(attr_sel), ret);
3980 } while (ret && peer && --retries);
3983 dev_err(hba->dev, "%s: attr-id 0x%x failed %d retries\n",
3984 get, UIC_GET_ATTR_ID(attr_sel),
3985 UFS_UIC_COMMAND_RETRIES - retries);
3987 if (mib_val && !ret)
3988 *mib_val = uic_cmd.argument3;
3990 if (peer && (hba->quirks & UFSHCD_QUIRK_DME_PEER_ACCESS_AUTO_MODE)
3992 ufshcd_change_power_mode(hba, &orig_pwr_info);
3996 EXPORT_SYMBOL_GPL(ufshcd_dme_get_attr);
3999 * ufshcd_uic_pwr_ctrl - executes UIC commands (which affects the link power
4000 * state) and waits for it to take effect.
4002 * @hba: per adapter instance
4003 * @cmd: UIC command to execute
4005 * DME operations like DME_SET(PA_PWRMODE), DME_HIBERNATE_ENTER &
4006 * DME_HIBERNATE_EXIT commands take some time to take its effect on both host
4007 * and device UniPro link and hence it's final completion would be indicated by
4008 * dedicated status bits in Interrupt Status register (UPMS, UHES, UHXS) in
4009 * addition to normal UIC command completion Status (UCCS). This function only
4010 * returns after the relevant status bits indicate the completion.
4012 * Returns 0 on success, non-zero value on failure
4014 static int ufshcd_uic_pwr_ctrl(struct ufs_hba *hba, struct uic_command *cmd)
4016 DECLARE_COMPLETION_ONSTACK(uic_async_done);
4017 unsigned long flags;
4020 bool reenable_intr = false;
4022 mutex_lock(&hba->uic_cmd_mutex);
4023 ufshcd_add_delay_before_dme_cmd(hba);
4025 spin_lock_irqsave(hba->host->host_lock, flags);
4026 if (ufshcd_is_link_broken(hba)) {
4030 hba->uic_async_done = &uic_async_done;
4031 if (ufshcd_readl(hba, REG_INTERRUPT_ENABLE) & UIC_COMMAND_COMPL) {
4032 ufshcd_disable_intr(hba, UIC_COMMAND_COMPL);
4034 * Make sure UIC command completion interrupt is disabled before
4035 * issuing UIC command.
4038 reenable_intr = true;
4040 ret = __ufshcd_send_uic_cmd(hba, cmd, false);
4041 spin_unlock_irqrestore(hba->host->host_lock, flags);
4044 "pwr ctrl cmd 0x%x with mode 0x%x uic error %d\n",
4045 cmd->command, cmd->argument3, ret);
4049 if (!wait_for_completion_timeout(hba->uic_async_done,
4050 msecs_to_jiffies(UIC_CMD_TIMEOUT))) {
4052 "pwr ctrl cmd 0x%x with mode 0x%x completion timeout\n",
4053 cmd->command, cmd->argument3);
4055 if (!cmd->cmd_active) {
4056 dev_err(hba->dev, "%s: Power Mode Change operation has been completed, go check UPMCRS\n",
4066 status = ufshcd_get_upmcrs(hba);
4067 if (status != PWR_LOCAL) {
4069 "pwr ctrl cmd 0x%x failed, host upmcrs:0x%x\n",
4070 cmd->command, status);
4071 ret = (status != PWR_OK) ? status : -1;
4075 ufshcd_print_host_state(hba);
4076 ufshcd_print_pwr_info(hba);
4077 ufshcd_print_evt_hist(hba);
4080 spin_lock_irqsave(hba->host->host_lock, flags);
4081 hba->active_uic_cmd = NULL;
4082 hba->uic_async_done = NULL;
4084 ufshcd_enable_intr(hba, UIC_COMMAND_COMPL);
4086 ufshcd_set_link_broken(hba);
4087 ufshcd_schedule_eh_work(hba);
4090 spin_unlock_irqrestore(hba->host->host_lock, flags);
4091 mutex_unlock(&hba->uic_cmd_mutex);
4097 * ufshcd_uic_change_pwr_mode - Perform the UIC power mode chage
4098 * using DME_SET primitives.
4099 * @hba: per adapter instance
4100 * @mode: powr mode value
4102 * Returns 0 on success, non-zero value on failure
4104 int ufshcd_uic_change_pwr_mode(struct ufs_hba *hba, u8 mode)
4106 struct uic_command uic_cmd = {0};
4109 if (hba->quirks & UFSHCD_QUIRK_BROKEN_PA_RXHSUNTERMCAP) {
4110 ret = ufshcd_dme_set(hba,
4111 UIC_ARG_MIB_SEL(PA_RXHSUNTERMCAP, 0), 1);
4113 dev_err(hba->dev, "%s: failed to enable PA_RXHSUNTERMCAP ret %d\n",
4119 uic_cmd.command = UIC_CMD_DME_SET;
4120 uic_cmd.argument1 = UIC_ARG_MIB(PA_PWRMODE);
4121 uic_cmd.argument3 = mode;
4122 ufshcd_hold(hba, false);
4123 ret = ufshcd_uic_pwr_ctrl(hba, &uic_cmd);
4124 ufshcd_release(hba);
4129 EXPORT_SYMBOL_GPL(ufshcd_uic_change_pwr_mode);
4131 int ufshcd_link_recovery(struct ufs_hba *hba)
4134 unsigned long flags;
4136 spin_lock_irqsave(hba->host->host_lock, flags);
4137 hba->ufshcd_state = UFSHCD_STATE_RESET;
4138 ufshcd_set_eh_in_progress(hba);
4139 spin_unlock_irqrestore(hba->host->host_lock, flags);
4141 /* Reset the attached device */
4142 ufshcd_device_reset(hba);
4144 ret = ufshcd_host_reset_and_restore(hba);
4146 spin_lock_irqsave(hba->host->host_lock, flags);
4148 hba->ufshcd_state = UFSHCD_STATE_ERROR;
4149 ufshcd_clear_eh_in_progress(hba);
4150 spin_unlock_irqrestore(hba->host->host_lock, flags);
4153 dev_err(hba->dev, "%s: link recovery failed, err %d",
4158 EXPORT_SYMBOL_GPL(ufshcd_link_recovery);
4160 int ufshcd_uic_hibern8_enter(struct ufs_hba *hba)
4163 struct uic_command uic_cmd = {0};
4164 ktime_t start = ktime_get();
4166 ufshcd_vops_hibern8_notify(hba, UIC_CMD_DME_HIBER_ENTER, PRE_CHANGE);
4168 uic_cmd.command = UIC_CMD_DME_HIBER_ENTER;
4169 ret = ufshcd_uic_pwr_ctrl(hba, &uic_cmd);
4170 trace_ufshcd_profile_hibern8(dev_name(hba->dev), "enter",
4171 ktime_to_us(ktime_sub(ktime_get(), start)), ret);
4174 dev_err(hba->dev, "%s: hibern8 enter failed. ret = %d\n",
4177 ufshcd_vops_hibern8_notify(hba, UIC_CMD_DME_HIBER_ENTER,
4182 EXPORT_SYMBOL_GPL(ufshcd_uic_hibern8_enter);
4184 int ufshcd_uic_hibern8_exit(struct ufs_hba *hba)
4186 struct uic_command uic_cmd = {0};
4188 ktime_t start = ktime_get();
4190 ufshcd_vops_hibern8_notify(hba, UIC_CMD_DME_HIBER_EXIT, PRE_CHANGE);
4192 uic_cmd.command = UIC_CMD_DME_HIBER_EXIT;
4193 ret = ufshcd_uic_pwr_ctrl(hba, &uic_cmd);
4194 trace_ufshcd_profile_hibern8(dev_name(hba->dev), "exit",
4195 ktime_to_us(ktime_sub(ktime_get(), start)), ret);
4198 dev_err(hba->dev, "%s: hibern8 exit failed. ret = %d\n",
4201 ufshcd_vops_hibern8_notify(hba, UIC_CMD_DME_HIBER_EXIT,
4203 hba->ufs_stats.last_hibern8_exit_tstamp = ktime_get();
4204 hba->ufs_stats.hibern8_exit_cnt++;
4209 EXPORT_SYMBOL_GPL(ufshcd_uic_hibern8_exit);
4211 void ufshcd_auto_hibern8_update(struct ufs_hba *hba, u32 ahit)
4213 unsigned long flags;
4214 bool update = false;
4216 if (!ufshcd_is_auto_hibern8_supported(hba))
4219 spin_lock_irqsave(hba->host->host_lock, flags);
4220 if (hba->ahit != ahit) {
4224 spin_unlock_irqrestore(hba->host->host_lock, flags);
4227 !pm_runtime_suspended(&hba->ufs_device_wlun->sdev_gendev)) {
4228 ufshcd_rpm_get_sync(hba);
4229 ufshcd_hold(hba, false);
4230 ufshcd_auto_hibern8_enable(hba);
4231 ufshcd_release(hba);
4232 ufshcd_rpm_put_sync(hba);
4235 EXPORT_SYMBOL_GPL(ufshcd_auto_hibern8_update);
4237 void ufshcd_auto_hibern8_enable(struct ufs_hba *hba)
4239 if (!ufshcd_is_auto_hibern8_supported(hba))
4242 ufshcd_writel(hba, hba->ahit, REG_AUTO_HIBERNATE_IDLE_TIMER);
4246 * ufshcd_init_pwr_info - setting the POR (power on reset)
4247 * values in hba power info
4248 * @hba: per-adapter instance
4250 static void ufshcd_init_pwr_info(struct ufs_hba *hba)
4252 hba->pwr_info.gear_rx = UFS_PWM_G1;
4253 hba->pwr_info.gear_tx = UFS_PWM_G1;
4254 hba->pwr_info.lane_rx = 1;
4255 hba->pwr_info.lane_tx = 1;
4256 hba->pwr_info.pwr_rx = SLOWAUTO_MODE;
4257 hba->pwr_info.pwr_tx = SLOWAUTO_MODE;
4258 hba->pwr_info.hs_rate = 0;
4262 * ufshcd_get_max_pwr_mode - reads the max power mode negotiated with device
4263 * @hba: per-adapter instance
4265 static int ufshcd_get_max_pwr_mode(struct ufs_hba *hba)
4267 struct ufs_pa_layer_attr *pwr_info = &hba->max_pwr_info.info;
4269 if (hba->max_pwr_info.is_valid)
4272 if (hba->quirks & UFSHCD_QUIRK_HIBERN_FASTAUTO) {
4273 pwr_info->pwr_tx = FASTAUTO_MODE;
4274 pwr_info->pwr_rx = FASTAUTO_MODE;
4276 pwr_info->pwr_tx = FAST_MODE;
4277 pwr_info->pwr_rx = FAST_MODE;
4279 pwr_info->hs_rate = PA_HS_MODE_B;
4281 /* Get the connected lane count */
4282 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_CONNECTEDRXDATALANES),
4283 &pwr_info->lane_rx);
4284 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_CONNECTEDTXDATALANES),
4285 &pwr_info->lane_tx);
4287 if (!pwr_info->lane_rx || !pwr_info->lane_tx) {
4288 dev_err(hba->dev, "%s: invalid connected lanes value. rx=%d, tx=%d\n",
4296 * First, get the maximum gears of HS speed.
4297 * If a zero value, it means there is no HSGEAR capability.
4298 * Then, get the maximum gears of PWM speed.
4300 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_MAXRXHSGEAR), &pwr_info->gear_rx);
4301 if (!pwr_info->gear_rx) {
4302 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_MAXRXPWMGEAR),
4303 &pwr_info->gear_rx);
4304 if (!pwr_info->gear_rx) {
4305 dev_err(hba->dev, "%s: invalid max pwm rx gear read = %d\n",
4306 __func__, pwr_info->gear_rx);
4309 pwr_info->pwr_rx = SLOW_MODE;
4312 ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_MAXRXHSGEAR),
4313 &pwr_info->gear_tx);
4314 if (!pwr_info->gear_tx) {
4315 ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_MAXRXPWMGEAR),
4316 &pwr_info->gear_tx);
4317 if (!pwr_info->gear_tx) {
4318 dev_err(hba->dev, "%s: invalid max pwm tx gear read = %d\n",
4319 __func__, pwr_info->gear_tx);
4322 pwr_info->pwr_tx = SLOW_MODE;
4325 hba->max_pwr_info.is_valid = true;
4329 static int ufshcd_change_power_mode(struct ufs_hba *hba,
4330 struct ufs_pa_layer_attr *pwr_mode)
4334 /* if already configured to the requested pwr_mode */
4335 if (!hba->force_pmc &&
4336 pwr_mode->gear_rx == hba->pwr_info.gear_rx &&
4337 pwr_mode->gear_tx == hba->pwr_info.gear_tx &&
4338 pwr_mode->lane_rx == hba->pwr_info.lane_rx &&
4339 pwr_mode->lane_tx == hba->pwr_info.lane_tx &&
4340 pwr_mode->pwr_rx == hba->pwr_info.pwr_rx &&
4341 pwr_mode->pwr_tx == hba->pwr_info.pwr_tx &&
4342 pwr_mode->hs_rate == hba->pwr_info.hs_rate) {
4343 dev_dbg(hba->dev, "%s: power already configured\n", __func__);
4348 * Configure attributes for power mode change with below.
4349 * - PA_RXGEAR, PA_ACTIVERXDATALANES, PA_RXTERMINATION,
4350 * - PA_TXGEAR, PA_ACTIVETXDATALANES, PA_TXTERMINATION,
4353 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_RXGEAR), pwr_mode->gear_rx);
4354 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_ACTIVERXDATALANES),
4356 if (pwr_mode->pwr_rx == FASTAUTO_MODE ||
4357 pwr_mode->pwr_rx == FAST_MODE)
4358 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_RXTERMINATION), true);
4360 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_RXTERMINATION), false);
4362 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TXGEAR), pwr_mode->gear_tx);
4363 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_ACTIVETXDATALANES),
4365 if (pwr_mode->pwr_tx == FASTAUTO_MODE ||
4366 pwr_mode->pwr_tx == FAST_MODE)
4367 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TXTERMINATION), true);
4369 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TXTERMINATION), false);
4371 if (pwr_mode->pwr_rx == FASTAUTO_MODE ||
4372 pwr_mode->pwr_tx == FASTAUTO_MODE ||
4373 pwr_mode->pwr_rx == FAST_MODE ||
4374 pwr_mode->pwr_tx == FAST_MODE)
4375 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_HSSERIES),
4378 if (!(hba->quirks & UFSHCD_QUIRK_SKIP_DEF_UNIPRO_TIMEOUT_SETTING)) {
4379 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_PWRMODEUSERDATA0),
4380 DL_FC0ProtectionTimeOutVal_Default);
4381 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_PWRMODEUSERDATA1),
4382 DL_TC0ReplayTimeOutVal_Default);
4383 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_PWRMODEUSERDATA2),
4384 DL_AFC0ReqTimeOutVal_Default);
4385 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_PWRMODEUSERDATA3),
4386 DL_FC1ProtectionTimeOutVal_Default);
4387 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_PWRMODEUSERDATA4),
4388 DL_TC1ReplayTimeOutVal_Default);
4389 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_PWRMODEUSERDATA5),
4390 DL_AFC1ReqTimeOutVal_Default);
4392 ufshcd_dme_set(hba, UIC_ARG_MIB(DME_LocalFC0ProtectionTimeOutVal),
4393 DL_FC0ProtectionTimeOutVal_Default);
4394 ufshcd_dme_set(hba, UIC_ARG_MIB(DME_LocalTC0ReplayTimeOutVal),
4395 DL_TC0ReplayTimeOutVal_Default);
4396 ufshcd_dme_set(hba, UIC_ARG_MIB(DME_LocalAFC0ReqTimeOutVal),
4397 DL_AFC0ReqTimeOutVal_Default);
4400 ret = ufshcd_uic_change_pwr_mode(hba, pwr_mode->pwr_rx << 4
4401 | pwr_mode->pwr_tx);
4405 "%s: power mode change failed %d\n", __func__, ret);
4407 ufshcd_vops_pwr_change_notify(hba, POST_CHANGE, NULL,
4410 memcpy(&hba->pwr_info, pwr_mode,
4411 sizeof(struct ufs_pa_layer_attr));
4418 * ufshcd_config_pwr_mode - configure a new power mode
4419 * @hba: per-adapter instance
4420 * @desired_pwr_mode: desired power configuration
4422 int ufshcd_config_pwr_mode(struct ufs_hba *hba,
4423 struct ufs_pa_layer_attr *desired_pwr_mode)
4425 struct ufs_pa_layer_attr final_params = { 0 };
4428 ret = ufshcd_vops_pwr_change_notify(hba, PRE_CHANGE,
4429 desired_pwr_mode, &final_params);
4432 memcpy(&final_params, desired_pwr_mode, sizeof(final_params));
4434 ret = ufshcd_change_power_mode(hba, &final_params);
4438 EXPORT_SYMBOL_GPL(ufshcd_config_pwr_mode);
4441 * ufshcd_complete_dev_init() - checks device readiness
4442 * @hba: per-adapter instance
4444 * Set fDeviceInit flag and poll until device toggles it.
4446 static int ufshcd_complete_dev_init(struct ufs_hba *hba)
4449 bool flag_res = true;
4452 err = ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_SET_FLAG,
4453 QUERY_FLAG_IDN_FDEVICEINIT, 0, NULL);
4456 "%s setting fDeviceInit flag failed with error %d\n",
4461 /* Poll fDeviceInit flag to be cleared */
4462 timeout = ktime_add_ms(ktime_get(), FDEVICEINIT_COMPL_TIMEOUT);
4464 err = ufshcd_query_flag(hba, UPIU_QUERY_OPCODE_READ_FLAG,
4465 QUERY_FLAG_IDN_FDEVICEINIT, 0, &flag_res);
4468 usleep_range(500, 1000);
4469 } while (ktime_before(ktime_get(), timeout));
4473 "%s reading fDeviceInit flag failed with error %d\n",
4475 } else if (flag_res) {
4477 "%s fDeviceInit was not cleared by the device\n",
4486 * ufshcd_make_hba_operational - Make UFS controller operational
4487 * @hba: per adapter instance
4489 * To bring UFS host controller to operational state,
4490 * 1. Enable required interrupts
4491 * 2. Configure interrupt aggregation
4492 * 3. Program UTRL and UTMRL base address
4493 * 4. Configure run-stop-registers
4495 * Returns 0 on success, non-zero value on failure
4497 int ufshcd_make_hba_operational(struct ufs_hba *hba)
4502 /* Enable required interrupts */
4503 ufshcd_enable_intr(hba, UFSHCD_ENABLE_INTRS);
4505 /* Configure interrupt aggregation */
4506 if (ufshcd_is_intr_aggr_allowed(hba))
4507 ufshcd_config_intr_aggr(hba, hba->nutrs - 1, INT_AGGR_DEF_TO);
4509 ufshcd_disable_intr_aggr(hba);
4511 /* Configure UTRL and UTMRL base address registers */
4512 ufshcd_writel(hba, lower_32_bits(hba->utrdl_dma_addr),
4513 REG_UTP_TRANSFER_REQ_LIST_BASE_L);
4514 ufshcd_writel(hba, upper_32_bits(hba->utrdl_dma_addr),
4515 REG_UTP_TRANSFER_REQ_LIST_BASE_H);
4516 ufshcd_writel(hba, lower_32_bits(hba->utmrdl_dma_addr),
4517 REG_UTP_TASK_REQ_LIST_BASE_L);
4518 ufshcd_writel(hba, upper_32_bits(hba->utmrdl_dma_addr),
4519 REG_UTP_TASK_REQ_LIST_BASE_H);
4522 * Make sure base address and interrupt setup are updated before
4523 * enabling the run/stop registers below.
4528 * UCRDY, UTMRLDY and UTRLRDY bits must be 1
4530 reg = ufshcd_readl(hba, REG_CONTROLLER_STATUS);
4531 if (!(ufshcd_get_lists_status(reg))) {
4532 ufshcd_enable_run_stop_reg(hba);
4535 "Host controller not ready to process requests");
4541 EXPORT_SYMBOL_GPL(ufshcd_make_hba_operational);
4544 * ufshcd_hba_stop - Send controller to reset state
4545 * @hba: per adapter instance
4547 void ufshcd_hba_stop(struct ufs_hba *hba)
4549 unsigned long flags;
4553 * Obtain the host lock to prevent that the controller is disabled
4554 * while the UFS interrupt handler is active on another CPU.
4556 spin_lock_irqsave(hba->host->host_lock, flags);
4557 ufshcd_writel(hba, CONTROLLER_DISABLE, REG_CONTROLLER_ENABLE);
4558 spin_unlock_irqrestore(hba->host->host_lock, flags);
4560 err = ufshcd_wait_for_register(hba, REG_CONTROLLER_ENABLE,
4561 CONTROLLER_ENABLE, CONTROLLER_DISABLE,
4564 dev_err(hba->dev, "%s: Controller disable failed\n", __func__);
4566 EXPORT_SYMBOL_GPL(ufshcd_hba_stop);
4569 * ufshcd_hba_execute_hce - initialize the controller
4570 * @hba: per adapter instance
4572 * The controller resets itself and controller firmware initialization
4573 * sequence kicks off. When controller is ready it will set
4574 * the Host Controller Enable bit to 1.
4576 * Returns 0 on success, non-zero value on failure
4578 static int ufshcd_hba_execute_hce(struct ufs_hba *hba)
4580 int retry_outer = 3;
4584 if (ufshcd_is_hba_active(hba))
4585 /* change controller state to "reset state" */
4586 ufshcd_hba_stop(hba);
4588 /* UniPro link is disabled at this point */
4589 ufshcd_set_link_off(hba);
4591 ufshcd_vops_hce_enable_notify(hba, PRE_CHANGE);
4593 /* start controller initialization sequence */
4594 ufshcd_hba_start(hba);
4597 * To initialize a UFS host controller HCE bit must be set to 1.
4598 * During initialization the HCE bit value changes from 1->0->1.
4599 * When the host controller completes initialization sequence
4600 * it sets the value of HCE bit to 1. The same HCE bit is read back
4601 * to check if the controller has completed initialization sequence.
4602 * So without this delay the value HCE = 1, set in the previous
4603 * instruction might be read back.
4604 * This delay can be changed based on the controller.
4606 ufshcd_delay_us(hba->vps->hba_enable_delay_us, 100);
4608 /* wait for the host controller to complete initialization */
4610 while (!ufshcd_is_hba_active(hba)) {
4615 "Controller enable failed\n");
4622 usleep_range(1000, 1100);
4625 /* enable UIC related interrupts */
4626 ufshcd_enable_intr(hba, UFSHCD_UIC_MASK);
4628 ufshcd_vops_hce_enable_notify(hba, POST_CHANGE);
4633 int ufshcd_hba_enable(struct ufs_hba *hba)
4637 if (hba->quirks & UFSHCI_QUIRK_BROKEN_HCE) {
4638 ufshcd_set_link_off(hba);
4639 ufshcd_vops_hce_enable_notify(hba, PRE_CHANGE);
4641 /* enable UIC related interrupts */
4642 ufshcd_enable_intr(hba, UFSHCD_UIC_MASK);
4643 ret = ufshcd_dme_reset(hba);
4645 ret = ufshcd_dme_enable(hba);
4647 ufshcd_vops_hce_enable_notify(hba, POST_CHANGE);
4650 "Host controller enable failed with non-hce\n");
4653 ret = ufshcd_hba_execute_hce(hba);
4658 EXPORT_SYMBOL_GPL(ufshcd_hba_enable);
4660 static int ufshcd_disable_tx_lcc(struct ufs_hba *hba, bool peer)
4662 int tx_lanes = 0, i, err = 0;
4665 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_CONNECTEDTXDATALANES),
4668 ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_CONNECTEDTXDATALANES),
4670 for (i = 0; i < tx_lanes; i++) {
4672 err = ufshcd_dme_set(hba,
4673 UIC_ARG_MIB_SEL(TX_LCC_ENABLE,
4674 UIC_ARG_MPHY_TX_GEN_SEL_INDEX(i)),
4677 err = ufshcd_dme_peer_set(hba,
4678 UIC_ARG_MIB_SEL(TX_LCC_ENABLE,
4679 UIC_ARG_MPHY_TX_GEN_SEL_INDEX(i)),
4682 dev_err(hba->dev, "%s: TX LCC Disable failed, peer = %d, lane = %d, err = %d",
4683 __func__, peer, i, err);
4691 static inline int ufshcd_disable_device_tx_lcc(struct ufs_hba *hba)
4693 return ufshcd_disable_tx_lcc(hba, true);
4696 void ufshcd_update_evt_hist(struct ufs_hba *hba, u32 id, u32 val)
4698 struct ufs_event_hist *e;
4700 if (id >= UFS_EVT_CNT)
4703 e = &hba->ufs_stats.event[id];
4704 e->val[e->pos] = val;
4705 e->tstamp[e->pos] = ktime_get();
4707 e->pos = (e->pos + 1) % UFS_EVENT_HIST_LENGTH;
4709 ufshcd_vops_event_notify(hba, id, &val);
4711 EXPORT_SYMBOL_GPL(ufshcd_update_evt_hist);
4714 * ufshcd_link_startup - Initialize unipro link startup
4715 * @hba: per adapter instance
4717 * Returns 0 for success, non-zero in case of failure
4719 static int ufshcd_link_startup(struct ufs_hba *hba)
4722 int retries = DME_LINKSTARTUP_RETRIES;
4723 bool link_startup_again = false;
4726 * If UFS device isn't active then we will have to issue link startup
4727 * 2 times to make sure the device state move to active.
4729 if (!ufshcd_is_ufs_dev_active(hba))
4730 link_startup_again = true;
4734 ufshcd_vops_link_startup_notify(hba, PRE_CHANGE);
4736 ret = ufshcd_dme_link_startup(hba);
4738 /* check if device is detected by inter-connect layer */
4739 if (!ret && !ufshcd_is_device_present(hba)) {
4740 ufshcd_update_evt_hist(hba,
4741 UFS_EVT_LINK_STARTUP_FAIL,
4743 dev_err(hba->dev, "%s: Device not present\n", __func__);
4749 * DME link lost indication is only received when link is up,
4750 * but we can't be sure if the link is up until link startup
4751 * succeeds. So reset the local Uni-Pro and try again.
4753 if (ret && retries && ufshcd_hba_enable(hba)) {
4754 ufshcd_update_evt_hist(hba,
4755 UFS_EVT_LINK_STARTUP_FAIL,
4759 } while (ret && retries--);
4762 /* failed to get the link up... retire */
4763 ufshcd_update_evt_hist(hba,
4764 UFS_EVT_LINK_STARTUP_FAIL,
4769 if (link_startup_again) {
4770 link_startup_again = false;
4771 retries = DME_LINKSTARTUP_RETRIES;
4775 /* Mark that link is up in PWM-G1, 1-lane, SLOW-AUTO mode */
4776 ufshcd_init_pwr_info(hba);
4777 ufshcd_print_pwr_info(hba);
4779 if (hba->quirks & UFSHCD_QUIRK_BROKEN_LCC) {
4780 ret = ufshcd_disable_device_tx_lcc(hba);
4785 /* Include any host controller configuration via UIC commands */
4786 ret = ufshcd_vops_link_startup_notify(hba, POST_CHANGE);
4790 /* Clear UECPA once due to LINERESET has happened during LINK_STARTUP */
4791 ufshcd_readl(hba, REG_UIC_ERROR_CODE_PHY_ADAPTER_LAYER);
4792 ret = ufshcd_make_hba_operational(hba);
4795 dev_err(hba->dev, "link startup failed %d\n", ret);
4796 ufshcd_print_host_state(hba);
4797 ufshcd_print_pwr_info(hba);
4798 ufshcd_print_evt_hist(hba);
4804 * ufshcd_verify_dev_init() - Verify device initialization
4805 * @hba: per-adapter instance
4807 * Send NOP OUT UPIU and wait for NOP IN response to check whether the
4808 * device Transport Protocol (UTP) layer is ready after a reset.
4809 * If the UTP layer at the device side is not initialized, it may
4810 * not respond with NOP IN UPIU within timeout of %NOP_OUT_TIMEOUT
4811 * and we retry sending NOP OUT for %NOP_OUT_RETRIES iterations.
4813 static int ufshcd_verify_dev_init(struct ufs_hba *hba)
4818 ufshcd_hold(hba, false);
4819 mutex_lock(&hba->dev_cmd.lock);
4820 for (retries = NOP_OUT_RETRIES; retries > 0; retries--) {
4821 err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_NOP,
4822 hba->nop_out_timeout);
4824 if (!err || err == -ETIMEDOUT)
4827 dev_dbg(hba->dev, "%s: error %d retrying\n", __func__, err);
4829 mutex_unlock(&hba->dev_cmd.lock);
4830 ufshcd_release(hba);
4833 dev_err(hba->dev, "%s: NOP OUT failed %d\n", __func__, err);
4838 * ufshcd_set_queue_depth - set lun queue depth
4839 * @sdev: pointer to SCSI device
4841 * Read bLUQueueDepth value and activate scsi tagged command
4842 * queueing. For WLUN, queue depth is set to 1. For best-effort
4843 * cases (bLUQueueDepth = 0) the queue depth is set to a maximum
4844 * value that host can queue.
4846 static void ufshcd_set_queue_depth(struct scsi_device *sdev)
4850 struct ufs_hba *hba;
4852 hba = shost_priv(sdev->host);
4854 lun_qdepth = hba->nutrs;
4855 ret = ufshcd_read_unit_desc_param(hba,
4856 ufshcd_scsi_to_upiu_lun(sdev->lun),
4857 UNIT_DESC_PARAM_LU_Q_DEPTH,
4859 sizeof(lun_qdepth));
4861 /* Some WLUN doesn't support unit descriptor */
4862 if (ret == -EOPNOTSUPP)
4864 else if (!lun_qdepth)
4865 /* eventually, we can figure out the real queue depth */
4866 lun_qdepth = hba->nutrs;
4868 lun_qdepth = min_t(int, lun_qdepth, hba->nutrs);
4870 dev_dbg(hba->dev, "%s: activate tcq with queue depth %d\n",
4871 __func__, lun_qdepth);
4872 scsi_change_queue_depth(sdev, lun_qdepth);
4876 * ufshcd_get_lu_wp - returns the "b_lu_write_protect" from UNIT DESCRIPTOR
4877 * @hba: per-adapter instance
4878 * @lun: UFS device lun id
4879 * @b_lu_write_protect: pointer to buffer to hold the LU's write protect info
4881 * Returns 0 in case of success and b_lu_write_protect status would be returned
4882 * @b_lu_write_protect parameter.
4883 * Returns -ENOTSUPP if reading b_lu_write_protect is not supported.
4884 * Returns -EINVAL in case of invalid parameters passed to this function.
4886 static int ufshcd_get_lu_wp(struct ufs_hba *hba,
4888 u8 *b_lu_write_protect)
4892 if (!b_lu_write_protect)
4895 * According to UFS device spec, RPMB LU can't be write
4896 * protected so skip reading bLUWriteProtect parameter for
4897 * it. For other W-LUs, UNIT DESCRIPTOR is not available.
4899 else if (lun >= hba->dev_info.max_lu_supported)
4902 ret = ufshcd_read_unit_desc_param(hba,
4904 UNIT_DESC_PARAM_LU_WR_PROTECT,
4906 sizeof(*b_lu_write_protect));
4911 * ufshcd_get_lu_power_on_wp_status - get LU's power on write protect
4913 * @hba: per-adapter instance
4914 * @sdev: pointer to SCSI device
4917 static inline void ufshcd_get_lu_power_on_wp_status(struct ufs_hba *hba,
4918 const struct scsi_device *sdev)
4920 if (hba->dev_info.f_power_on_wp_en &&
4921 !hba->dev_info.is_lu_power_on_wp) {
4922 u8 b_lu_write_protect;
4924 if (!ufshcd_get_lu_wp(hba, ufshcd_scsi_to_upiu_lun(sdev->lun),
4925 &b_lu_write_protect) &&
4926 (b_lu_write_protect == UFS_LU_POWER_ON_WP))
4927 hba->dev_info.is_lu_power_on_wp = true;
4932 * ufshcd_setup_links - associate link b/w device wlun and other luns
4933 * @sdev: pointer to SCSI device
4934 * @hba: pointer to ufs hba
4936 static void ufshcd_setup_links(struct ufs_hba *hba, struct scsi_device *sdev)
4938 struct device_link *link;
4941 * Device wlun is the supplier & rest of the luns are consumers.
4942 * This ensures that device wlun suspends after all other luns.
4944 if (hba->ufs_device_wlun) {
4945 link = device_link_add(&sdev->sdev_gendev,
4946 &hba->ufs_device_wlun->sdev_gendev,
4947 DL_FLAG_PM_RUNTIME | DL_FLAG_RPM_ACTIVE);
4949 dev_err(&sdev->sdev_gendev, "Failed establishing link - %s\n",
4950 dev_name(&hba->ufs_device_wlun->sdev_gendev));
4954 /* Ignore REPORT_LUN wlun probing */
4955 if (hba->luns_avail == 1) {
4956 ufshcd_rpm_put(hba);
4961 * Device wlun is probed. The assumption is that WLUNs are
4962 * scanned before other LUNs.
4969 * ufshcd_slave_alloc - handle initial SCSI device configurations
4970 * @sdev: pointer to SCSI device
4974 static int ufshcd_slave_alloc(struct scsi_device *sdev)
4976 struct ufs_hba *hba;
4978 hba = shost_priv(sdev->host);
4980 /* Mode sense(6) is not supported by UFS, so use Mode sense(10) */
4981 sdev->use_10_for_ms = 1;
4983 /* DBD field should be set to 1 in mode sense(10) */
4984 sdev->set_dbd_for_ms = 1;
4986 /* allow SCSI layer to restart the device in case of errors */
4987 sdev->allow_restart = 1;
4989 /* REPORT SUPPORTED OPERATION CODES is not supported */
4990 sdev->no_report_opcodes = 1;
4992 /* WRITE_SAME command is not supported */
4993 sdev->no_write_same = 1;
4995 ufshcd_set_queue_depth(sdev);
4997 ufshcd_get_lu_power_on_wp_status(hba, sdev);
4999 ufshcd_setup_links(hba, sdev);
5005 * ufshcd_change_queue_depth - change queue depth
5006 * @sdev: pointer to SCSI device
5007 * @depth: required depth to set
5009 * Change queue depth and make sure the max. limits are not crossed.
5011 static int ufshcd_change_queue_depth(struct scsi_device *sdev, int depth)
5013 return scsi_change_queue_depth(sdev, min(depth, sdev->host->can_queue));
5016 static void ufshcd_hpb_destroy(struct ufs_hba *hba, struct scsi_device *sdev)
5018 /* skip well-known LU */
5019 if ((sdev->lun >= UFS_UPIU_MAX_UNIT_NUM_ID) ||
5020 !(hba->dev_info.hpb_enabled) || !ufshpb_is_allowed(hba))
5023 ufshpb_destroy_lu(hba, sdev);
5026 static void ufshcd_hpb_configure(struct ufs_hba *hba, struct scsi_device *sdev)
5028 /* skip well-known LU */
5029 if ((sdev->lun >= UFS_UPIU_MAX_UNIT_NUM_ID) ||
5030 !(hba->dev_info.hpb_enabled) || !ufshpb_is_allowed(hba))
5033 ufshpb_init_hpb_lu(hba, sdev);
5037 * ufshcd_slave_configure - adjust SCSI device configurations
5038 * @sdev: pointer to SCSI device
5040 static int ufshcd_slave_configure(struct scsi_device *sdev)
5042 struct ufs_hba *hba = shost_priv(sdev->host);
5043 struct request_queue *q = sdev->request_queue;
5045 ufshcd_hpb_configure(hba, sdev);
5047 blk_queue_update_dma_pad(q, PRDT_DATA_BYTE_COUNT_PAD - 1);
5048 if (hba->quirks & UFSHCD_QUIRK_ALIGN_SG_WITH_PAGE_SIZE)
5049 blk_queue_update_dma_alignment(q, PAGE_SIZE - 1);
5051 * Block runtime-pm until all consumers are added.
5052 * Refer ufshcd_setup_links().
5054 if (is_device_wlun(sdev))
5055 pm_runtime_get_noresume(&sdev->sdev_gendev);
5056 else if (ufshcd_is_rpm_autosuspend_allowed(hba))
5057 sdev->rpm_autosuspend = 1;
5059 * Do not print messages during runtime PM to avoid never-ending cycles
5060 * of messages written back to storage by user space causing runtime
5061 * resume, causing more messages and so on.
5063 sdev->silence_suspend = 1;
5065 ufshcd_crypto_register(hba, q);
5071 * ufshcd_slave_destroy - remove SCSI device configurations
5072 * @sdev: pointer to SCSI device
5074 static void ufshcd_slave_destroy(struct scsi_device *sdev)
5076 struct ufs_hba *hba;
5077 unsigned long flags;
5079 hba = shost_priv(sdev->host);
5081 ufshcd_hpb_destroy(hba, sdev);
5083 /* Drop the reference as it won't be needed anymore */
5084 if (ufshcd_scsi_to_upiu_lun(sdev->lun) == UFS_UPIU_UFS_DEVICE_WLUN) {
5085 spin_lock_irqsave(hba->host->host_lock, flags);
5086 hba->ufs_device_wlun = NULL;
5087 spin_unlock_irqrestore(hba->host->host_lock, flags);
5088 } else if (hba->ufs_device_wlun) {
5089 struct device *supplier = NULL;
5091 /* Ensure UFS Device WLUN exists and does not disappear */
5092 spin_lock_irqsave(hba->host->host_lock, flags);
5093 if (hba->ufs_device_wlun) {
5094 supplier = &hba->ufs_device_wlun->sdev_gendev;
5095 get_device(supplier);
5097 spin_unlock_irqrestore(hba->host->host_lock, flags);
5101 * If a LUN fails to probe (e.g. absent BOOT WLUN), the
5102 * device will not have been registered but can still
5103 * have a device link holding a reference to the device.
5105 device_link_remove(&sdev->sdev_gendev, supplier);
5106 put_device(supplier);
5112 * ufshcd_scsi_cmd_status - Update SCSI command result based on SCSI status
5113 * @lrbp: pointer to local reference block of completed command
5114 * @scsi_status: SCSI command status
5116 * Returns value base on SCSI command status
5119 ufshcd_scsi_cmd_status(struct ufshcd_lrb *lrbp, int scsi_status)
5123 switch (scsi_status) {
5124 case SAM_STAT_CHECK_CONDITION:
5125 ufshcd_copy_sense_data(lrbp);
5128 result |= DID_OK << 16 | scsi_status;
5130 case SAM_STAT_TASK_SET_FULL:
5132 case SAM_STAT_TASK_ABORTED:
5133 ufshcd_copy_sense_data(lrbp);
5134 result |= scsi_status;
5137 result |= DID_ERROR << 16;
5139 } /* end of switch */
5145 * ufshcd_transfer_rsp_status - Get overall status of the response
5146 * @hba: per adapter instance
5147 * @lrbp: pointer to local reference block of completed command
5149 * Returns result of the command to notify SCSI midlayer
5152 ufshcd_transfer_rsp_status(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
5158 /* overall command status of utrd */
5159 ocs = ufshcd_get_tr_ocs(lrbp);
5161 if (hba->quirks & UFSHCD_QUIRK_BROKEN_OCS_FATAL_ERROR) {
5162 if (be32_to_cpu(lrbp->ucd_rsp_ptr->header.dword_1) &
5163 MASK_RSP_UPIU_RESULT)
5169 result = ufshcd_get_req_rsp(lrbp->ucd_rsp_ptr);
5170 hba->ufs_stats.last_hibern8_exit_tstamp = ktime_set(0, 0);
5172 case UPIU_TRANSACTION_RESPONSE:
5174 * get the response UPIU result to extract
5175 * the SCSI command status
5177 result = ufshcd_get_rsp_upiu_result(lrbp->ucd_rsp_ptr);
5180 * get the result based on SCSI status response
5181 * to notify the SCSI midlayer of the command status
5183 scsi_status = result & MASK_SCSI_STATUS;
5184 result = ufshcd_scsi_cmd_status(lrbp, scsi_status);
5187 * Currently we are only supporting BKOPs exception
5188 * events hence we can ignore BKOPs exception event
5189 * during power management callbacks. BKOPs exception
5190 * event is not expected to be raised in runtime suspend
5191 * callback as it allows the urgent bkops.
5192 * During system suspend, we are anyway forcefully
5193 * disabling the bkops and if urgent bkops is needed
5194 * it will be enabled on system resume. Long term
5195 * solution could be to abort the system suspend if
5196 * UFS device needs urgent BKOPs.
5198 if (!hba->pm_op_in_progress &&
5199 !ufshcd_eh_in_progress(hba) &&
5200 ufshcd_is_exception_event(lrbp->ucd_rsp_ptr))
5201 /* Flushed in suspend */
5202 schedule_work(&hba->eeh_work);
5204 if (scsi_status == SAM_STAT_GOOD)
5205 ufshpb_rsp_upiu(hba, lrbp);
5207 case UPIU_TRANSACTION_REJECT_UPIU:
5208 /* TODO: handle Reject UPIU Response */
5209 result = DID_ERROR << 16;
5211 "Reject UPIU not fully implemented\n");
5215 "Unexpected request response code = %x\n",
5217 result = DID_ERROR << 16;
5222 result |= DID_ABORT << 16;
5224 case OCS_INVALID_COMMAND_STATUS:
5225 result |= DID_REQUEUE << 16;
5227 case OCS_INVALID_CMD_TABLE_ATTR:
5228 case OCS_INVALID_PRDT_ATTR:
5229 case OCS_MISMATCH_DATA_BUF_SIZE:
5230 case OCS_MISMATCH_RESP_UPIU_SIZE:
5231 case OCS_PEER_COMM_FAILURE:
5232 case OCS_FATAL_ERROR:
5233 case OCS_DEVICE_FATAL_ERROR:
5234 case OCS_INVALID_CRYPTO_CONFIG:
5235 case OCS_GENERAL_CRYPTO_ERROR:
5237 result |= DID_ERROR << 16;
5239 "OCS error from controller = %x for tag %d\n",
5240 ocs, lrbp->task_tag);
5241 ufshcd_print_evt_hist(hba);
5242 ufshcd_print_host_state(hba);
5244 } /* end of switch */
5246 if ((host_byte(result) != DID_OK) &&
5247 (host_byte(result) != DID_REQUEUE) && !hba->silence_err_logs)
5248 ufshcd_print_trs(hba, 1 << lrbp->task_tag, true);
5252 static bool ufshcd_is_auto_hibern8_error(struct ufs_hba *hba,
5255 if (!ufshcd_is_auto_hibern8_supported(hba) ||
5256 !ufshcd_is_auto_hibern8_enabled(hba))
5259 if (!(intr_mask & UFSHCD_UIC_HIBERN8_MASK))
5262 if (hba->active_uic_cmd &&
5263 (hba->active_uic_cmd->command == UIC_CMD_DME_HIBER_ENTER ||
5264 hba->active_uic_cmd->command == UIC_CMD_DME_HIBER_EXIT))
5271 * ufshcd_uic_cmd_compl - handle completion of uic command
5272 * @hba: per adapter instance
5273 * @intr_status: interrupt status generated by the controller
5276 * IRQ_HANDLED - If interrupt is valid
5277 * IRQ_NONE - If invalid interrupt
5279 static irqreturn_t ufshcd_uic_cmd_compl(struct ufs_hba *hba, u32 intr_status)
5281 irqreturn_t retval = IRQ_NONE;
5283 spin_lock(hba->host->host_lock);
5284 if (ufshcd_is_auto_hibern8_error(hba, intr_status))
5285 hba->errors |= (UFSHCD_UIC_HIBERN8_MASK & intr_status);
5287 if ((intr_status & UIC_COMMAND_COMPL) && hba->active_uic_cmd) {
5288 hba->active_uic_cmd->argument2 |=
5289 ufshcd_get_uic_cmd_result(hba);
5290 hba->active_uic_cmd->argument3 =
5291 ufshcd_get_dme_attr_val(hba);
5292 if (!hba->uic_async_done)
5293 hba->active_uic_cmd->cmd_active = 0;
5294 complete(&hba->active_uic_cmd->done);
5295 retval = IRQ_HANDLED;
5298 if ((intr_status & UFSHCD_UIC_PWR_MASK) && hba->uic_async_done) {
5299 hba->active_uic_cmd->cmd_active = 0;
5300 complete(hba->uic_async_done);
5301 retval = IRQ_HANDLED;
5304 if (retval == IRQ_HANDLED)
5305 ufshcd_add_uic_command_trace(hba, hba->active_uic_cmd,
5307 spin_unlock(hba->host->host_lock);
5311 /* Release the resources allocated for processing a SCSI command. */
5312 static void ufshcd_release_scsi_cmd(struct ufs_hba *hba,
5313 struct ufshcd_lrb *lrbp)
5315 struct scsi_cmnd *cmd = lrbp->cmd;
5317 scsi_dma_unmap(cmd);
5318 lrbp->cmd = NULL; /* Mark the command as completed. */
5319 ufshcd_release(hba);
5320 ufshcd_clk_scaling_update_busy(hba);
5324 * __ufshcd_transfer_req_compl - handle SCSI and query command completion
5325 * @hba: per adapter instance
5326 * @completed_reqs: bitmask that indicates which requests to complete
5328 static void __ufshcd_transfer_req_compl(struct ufs_hba *hba,
5329 unsigned long completed_reqs)
5331 struct ufshcd_lrb *lrbp;
5332 struct scsi_cmnd *cmd;
5335 for_each_set_bit(index, &completed_reqs, hba->nutrs) {
5336 lrbp = &hba->lrb[index];
5337 lrbp->compl_time_stamp = ktime_get();
5340 if (unlikely(ufshcd_should_inform_monitor(hba, lrbp)))
5341 ufshcd_update_monitor(hba, lrbp);
5342 ufshcd_add_command_trace(hba, index, UFS_CMD_COMP);
5343 cmd->result = ufshcd_transfer_rsp_status(hba, lrbp);
5344 ufshcd_release_scsi_cmd(hba, lrbp);
5345 /* Do not touch lrbp after scsi done */
5347 } else if (lrbp->command_type == UTP_CMD_TYPE_DEV_MANAGE ||
5348 lrbp->command_type == UTP_CMD_TYPE_UFS_STORAGE) {
5349 if (hba->dev_cmd.complete) {
5350 ufshcd_add_command_trace(hba, index,
5352 complete(hba->dev_cmd.complete);
5353 ufshcd_clk_scaling_update_busy(hba);
5360 * Returns > 0 if one or more commands have been completed or 0 if no
5361 * requests have been completed.
5363 static int ufshcd_poll(struct Scsi_Host *shost, unsigned int queue_num)
5365 struct ufs_hba *hba = shost_priv(shost);
5366 unsigned long completed_reqs, flags;
5369 spin_lock_irqsave(&hba->outstanding_lock, flags);
5370 tr_doorbell = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
5371 completed_reqs = ~tr_doorbell & hba->outstanding_reqs;
5372 WARN_ONCE(completed_reqs & ~hba->outstanding_reqs,
5373 "completed: %#lx; outstanding: %#lx\n", completed_reqs,
5374 hba->outstanding_reqs);
5375 hba->outstanding_reqs &= ~completed_reqs;
5376 spin_unlock_irqrestore(&hba->outstanding_lock, flags);
5379 __ufshcd_transfer_req_compl(hba, completed_reqs);
5381 return completed_reqs;
5385 * ufshcd_transfer_req_compl - handle SCSI and query command completion
5386 * @hba: per adapter instance
5389 * IRQ_HANDLED - If interrupt is valid
5390 * IRQ_NONE - If invalid interrupt
5392 static irqreturn_t ufshcd_transfer_req_compl(struct ufs_hba *hba)
5394 /* Resetting interrupt aggregation counters first and reading the
5395 * DOOR_BELL afterward allows us to handle all the completed requests.
5396 * In order to prevent other interrupts starvation the DB is read once
5397 * after reset. The down side of this solution is the possibility of
5398 * false interrupt if device completes another request after resetting
5399 * aggregation and before reading the DB.
5401 if (ufshcd_is_intr_aggr_allowed(hba) &&
5402 !(hba->quirks & UFSHCI_QUIRK_SKIP_RESET_INTR_AGGR))
5403 ufshcd_reset_intr_aggr(hba);
5405 if (ufs_fail_completion())
5409 * Ignore the ufshcd_poll() return value and return IRQ_HANDLED since we
5410 * do not want polling to trigger spurious interrupt complaints.
5412 ufshcd_poll(hba->host, 0);
5417 int __ufshcd_write_ee_control(struct ufs_hba *hba, u32 ee_ctrl_mask)
5419 return ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_WRITE_ATTR,
5420 QUERY_ATTR_IDN_EE_CONTROL, 0, 0,
5424 int ufshcd_write_ee_control(struct ufs_hba *hba)
5428 mutex_lock(&hba->ee_ctrl_mutex);
5429 err = __ufshcd_write_ee_control(hba, hba->ee_ctrl_mask);
5430 mutex_unlock(&hba->ee_ctrl_mutex);
5432 dev_err(hba->dev, "%s: failed to write ee control %d\n",
5437 int ufshcd_update_ee_control(struct ufs_hba *hba, u16 *mask,
5438 const u16 *other_mask, u16 set, u16 clr)
5440 u16 new_mask, ee_ctrl_mask;
5443 mutex_lock(&hba->ee_ctrl_mutex);
5444 new_mask = (*mask & ~clr) | set;
5445 ee_ctrl_mask = new_mask | *other_mask;
5446 if (ee_ctrl_mask != hba->ee_ctrl_mask)
5447 err = __ufshcd_write_ee_control(hba, ee_ctrl_mask);
5448 /* Still need to update 'mask' even if 'ee_ctrl_mask' was unchanged */
5450 hba->ee_ctrl_mask = ee_ctrl_mask;
5453 mutex_unlock(&hba->ee_ctrl_mutex);
5458 * ufshcd_disable_ee - disable exception event
5459 * @hba: per-adapter instance
5460 * @mask: exception event to disable
5462 * Disables exception event in the device so that the EVENT_ALERT
5465 * Returns zero on success, non-zero error value on failure.
5467 static inline int ufshcd_disable_ee(struct ufs_hba *hba, u16 mask)
5469 return ufshcd_update_ee_drv_mask(hba, 0, mask);
5473 * ufshcd_enable_ee - enable exception event
5474 * @hba: per-adapter instance
5475 * @mask: exception event to enable
5477 * Enable corresponding exception event in the device to allow
5478 * device to alert host in critical scenarios.
5480 * Returns zero on success, non-zero error value on failure.
5482 static inline int ufshcd_enable_ee(struct ufs_hba *hba, u16 mask)
5484 return ufshcd_update_ee_drv_mask(hba, mask, 0);
5488 * ufshcd_enable_auto_bkops - Allow device managed BKOPS
5489 * @hba: per-adapter instance
5491 * Allow device to manage background operations on its own. Enabling
5492 * this might lead to inconsistent latencies during normal data transfers
5493 * as the device is allowed to manage its own way of handling background
5496 * Returns zero on success, non-zero on failure.
5498 static int ufshcd_enable_auto_bkops(struct ufs_hba *hba)
5502 if (hba->auto_bkops_enabled)
5505 err = ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_SET_FLAG,
5506 QUERY_FLAG_IDN_BKOPS_EN, 0, NULL);
5508 dev_err(hba->dev, "%s: failed to enable bkops %d\n",
5513 hba->auto_bkops_enabled = true;
5514 trace_ufshcd_auto_bkops_state(dev_name(hba->dev), "Enabled");
5516 /* No need of URGENT_BKOPS exception from the device */
5517 err = ufshcd_disable_ee(hba, MASK_EE_URGENT_BKOPS);
5519 dev_err(hba->dev, "%s: failed to disable exception event %d\n",
5526 * ufshcd_disable_auto_bkops - block device in doing background operations
5527 * @hba: per-adapter instance
5529 * Disabling background operations improves command response latency but
5530 * has drawback of device moving into critical state where the device is
5531 * not-operable. Make sure to call ufshcd_enable_auto_bkops() whenever the
5532 * host is idle so that BKOPS are managed effectively without any negative
5535 * Returns zero on success, non-zero on failure.
5537 static int ufshcd_disable_auto_bkops(struct ufs_hba *hba)
5541 if (!hba->auto_bkops_enabled)
5545 * If host assisted BKOPs is to be enabled, make sure
5546 * urgent bkops exception is allowed.
5548 err = ufshcd_enable_ee(hba, MASK_EE_URGENT_BKOPS);
5550 dev_err(hba->dev, "%s: failed to enable exception event %d\n",
5555 err = ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_CLEAR_FLAG,
5556 QUERY_FLAG_IDN_BKOPS_EN, 0, NULL);
5558 dev_err(hba->dev, "%s: failed to disable bkops %d\n",
5560 ufshcd_disable_ee(hba, MASK_EE_URGENT_BKOPS);
5564 hba->auto_bkops_enabled = false;
5565 trace_ufshcd_auto_bkops_state(dev_name(hba->dev), "Disabled");
5566 hba->is_urgent_bkops_lvl_checked = false;
5572 * ufshcd_force_reset_auto_bkops - force reset auto bkops state
5573 * @hba: per adapter instance
5575 * After a device reset the device may toggle the BKOPS_EN flag
5576 * to default value. The s/w tracking variables should be updated
5577 * as well. This function would change the auto-bkops state based on
5578 * UFSHCD_CAP_KEEP_AUTO_BKOPS_ENABLED_EXCEPT_SUSPEND.
5580 static void ufshcd_force_reset_auto_bkops(struct ufs_hba *hba)
5582 if (ufshcd_keep_autobkops_enabled_except_suspend(hba)) {
5583 hba->auto_bkops_enabled = false;
5584 hba->ee_ctrl_mask |= MASK_EE_URGENT_BKOPS;
5585 ufshcd_enable_auto_bkops(hba);
5587 hba->auto_bkops_enabled = true;
5588 hba->ee_ctrl_mask &= ~MASK_EE_URGENT_BKOPS;
5589 ufshcd_disable_auto_bkops(hba);
5591 hba->urgent_bkops_lvl = BKOPS_STATUS_PERF_IMPACT;
5592 hba->is_urgent_bkops_lvl_checked = false;
5595 static inline int ufshcd_get_bkops_status(struct ufs_hba *hba, u32 *status)
5597 return ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
5598 QUERY_ATTR_IDN_BKOPS_STATUS, 0, 0, status);
5602 * ufshcd_bkops_ctrl - control the auto bkops based on current bkops status
5603 * @hba: per-adapter instance
5604 * @status: bkops_status value
5606 * Read the bkops_status from the UFS device and Enable fBackgroundOpsEn
5607 * flag in the device to permit background operations if the device
5608 * bkops_status is greater than or equal to "status" argument passed to
5609 * this function, disable otherwise.
5611 * Returns 0 for success, non-zero in case of failure.
5613 * NOTE: Caller of this function can check the "hba->auto_bkops_enabled" flag
5614 * to know whether auto bkops is enabled or disabled after this function
5615 * returns control to it.
5617 static int ufshcd_bkops_ctrl(struct ufs_hba *hba,
5618 enum bkops_status status)
5621 u32 curr_status = 0;
5623 err = ufshcd_get_bkops_status(hba, &curr_status);
5625 dev_err(hba->dev, "%s: failed to get BKOPS status %d\n",
5628 } else if (curr_status > BKOPS_STATUS_MAX) {
5629 dev_err(hba->dev, "%s: invalid BKOPS status %d\n",
5630 __func__, curr_status);
5635 if (curr_status >= status)
5636 err = ufshcd_enable_auto_bkops(hba);
5638 err = ufshcd_disable_auto_bkops(hba);
5644 * ufshcd_urgent_bkops - handle urgent bkops exception event
5645 * @hba: per-adapter instance
5647 * Enable fBackgroundOpsEn flag in the device to permit background
5650 * If BKOPs is enabled, this function returns 0, 1 if the bkops in not enabled
5651 * and negative error value for any other failure.
5653 static int ufshcd_urgent_bkops(struct ufs_hba *hba)
5655 return ufshcd_bkops_ctrl(hba, hba->urgent_bkops_lvl);
5658 static inline int ufshcd_get_ee_status(struct ufs_hba *hba, u32 *status)
5660 return ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
5661 QUERY_ATTR_IDN_EE_STATUS, 0, 0, status);
5664 static void ufshcd_bkops_exception_event_handler(struct ufs_hba *hba)
5667 u32 curr_status = 0;
5669 if (hba->is_urgent_bkops_lvl_checked)
5670 goto enable_auto_bkops;
5672 err = ufshcd_get_bkops_status(hba, &curr_status);
5674 dev_err(hba->dev, "%s: failed to get BKOPS status %d\n",
5680 * We are seeing that some devices are raising the urgent bkops
5681 * exception events even when BKOPS status doesn't indicate performace
5682 * impacted or critical. Handle these device by determining their urgent
5683 * bkops status at runtime.
5685 if (curr_status < BKOPS_STATUS_PERF_IMPACT) {
5686 dev_err(hba->dev, "%s: device raised urgent BKOPS exception for bkops status %d\n",
5687 __func__, curr_status);
5688 /* update the current status as the urgent bkops level */
5689 hba->urgent_bkops_lvl = curr_status;
5690 hba->is_urgent_bkops_lvl_checked = true;
5694 err = ufshcd_enable_auto_bkops(hba);
5697 dev_err(hba->dev, "%s: failed to handle urgent bkops %d\n",
5701 static void ufshcd_temp_exception_event_handler(struct ufs_hba *hba, u16 status)
5705 if (ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
5706 QUERY_ATTR_IDN_CASE_ROUGH_TEMP, 0, 0, &value))
5709 dev_info(hba->dev, "exception Tcase %d\n", value - 80);
5711 ufs_hwmon_notify_event(hba, status & MASK_EE_URGENT_TEMP);
5714 * A placeholder for the platform vendors to add whatever additional
5719 static int __ufshcd_wb_toggle(struct ufs_hba *hba, bool set, enum flag_idn idn)
5722 enum query_opcode opcode = set ? UPIU_QUERY_OPCODE_SET_FLAG :
5723 UPIU_QUERY_OPCODE_CLEAR_FLAG;
5725 index = ufshcd_wb_get_query_index(hba);
5726 return ufshcd_query_flag_retry(hba, opcode, idn, index, NULL);
5729 int ufshcd_wb_toggle(struct ufs_hba *hba, bool enable)
5733 if (!ufshcd_is_wb_allowed(hba))
5736 if (!(enable ^ hba->dev_info.wb_enabled))
5739 ret = __ufshcd_wb_toggle(hba, enable, QUERY_FLAG_IDN_WB_EN);
5741 dev_err(hba->dev, "%s Write Booster %s failed %d\n",
5742 __func__, enable ? "enable" : "disable", ret);
5746 hba->dev_info.wb_enabled = enable;
5747 dev_info(hba->dev, "%s Write Booster %s\n",
5748 __func__, enable ? "enabled" : "disabled");
5753 static void ufshcd_wb_toggle_flush_during_h8(struct ufs_hba *hba, bool set)
5757 ret = __ufshcd_wb_toggle(hba, set,
5758 QUERY_FLAG_IDN_WB_BUFF_FLUSH_DURING_HIBERN8);
5760 dev_err(hba->dev, "%s: WB-Buf Flush during H8 %s failed: %d\n",
5761 __func__, set ? "enable" : "disable", ret);
5764 dev_dbg(hba->dev, "%s WB-Buf Flush during H8 %s\n",
5765 __func__, set ? "enabled" : "disabled");
5768 static inline void ufshcd_wb_toggle_flush(struct ufs_hba *hba, bool enable)
5772 if (!ufshcd_is_wb_allowed(hba) ||
5773 hba->dev_info.wb_buf_flush_enabled == enable)
5776 ret = __ufshcd_wb_toggle(hba, enable, QUERY_FLAG_IDN_WB_BUFF_FLUSH_EN);
5778 dev_err(hba->dev, "%s WB-Buf Flush %s failed %d\n", __func__,
5779 enable ? "enable" : "disable", ret);
5783 hba->dev_info.wb_buf_flush_enabled = enable;
5785 dev_dbg(hba->dev, "%s WB-Buf Flush %s\n",
5786 __func__, enable ? "enabled" : "disabled");
5789 static bool ufshcd_wb_presrv_usrspc_keep_vcc_on(struct ufs_hba *hba,
5796 index = ufshcd_wb_get_query_index(hba);
5797 ret = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
5798 QUERY_ATTR_IDN_CURR_WB_BUFF_SIZE,
5799 index, 0, &cur_buf);
5801 dev_err(hba->dev, "%s dCurWriteBoosterBufferSize read failed %d\n",
5807 dev_info(hba->dev, "dCurWBBuf: %d WB disabled until free-space is available\n",
5811 /* Let it continue to flush when available buffer exceeds threshold */
5812 return avail_buf < hba->vps->wb_flush_threshold;
5815 static void ufshcd_wb_force_disable(struct ufs_hba *hba)
5817 if (!(hba->quirks & UFSHCI_QUIRK_SKIP_MANUAL_WB_FLUSH_CTRL))
5818 ufshcd_wb_toggle_flush(hba, false);
5820 ufshcd_wb_toggle_flush_during_h8(hba, false);
5821 ufshcd_wb_toggle(hba, false);
5822 hba->caps &= ~UFSHCD_CAP_WB_EN;
5824 dev_info(hba->dev, "%s: WB force disabled\n", __func__);
5827 static bool ufshcd_is_wb_buf_lifetime_available(struct ufs_hba *hba)
5833 index = ufshcd_wb_get_query_index(hba);
5834 ret = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
5835 QUERY_ATTR_IDN_WB_BUFF_LIFE_TIME_EST,
5836 index, 0, &lifetime);
5839 "%s: bWriteBoosterBufferLifeTimeEst read failed %d\n",
5844 if (lifetime == UFS_WB_EXCEED_LIFETIME) {
5845 dev_err(hba->dev, "%s: WB buf lifetime is exhausted 0x%02X\n",
5846 __func__, lifetime);
5850 dev_dbg(hba->dev, "%s: WB buf lifetime is 0x%02X\n",
5851 __func__, lifetime);
5856 static bool ufshcd_wb_need_flush(struct ufs_hba *hba)
5862 if (!ufshcd_is_wb_allowed(hba))
5865 if (!ufshcd_is_wb_buf_lifetime_available(hba)) {
5866 ufshcd_wb_force_disable(hba);
5871 * The ufs device needs the vcc to be ON to flush.
5872 * With user-space reduction enabled, it's enough to enable flush
5873 * by checking only the available buffer. The threshold
5874 * defined here is > 90% full.
5875 * With user-space preserved enabled, the current-buffer
5876 * should be checked too because the wb buffer size can reduce
5877 * when disk tends to be full. This info is provided by current
5878 * buffer (dCurrentWriteBoosterBufferSize). There's no point in
5879 * keeping vcc on when current buffer is empty.
5881 index = ufshcd_wb_get_query_index(hba);
5882 ret = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
5883 QUERY_ATTR_IDN_AVAIL_WB_BUFF_SIZE,
5884 index, 0, &avail_buf);
5886 dev_warn(hba->dev, "%s dAvailableWriteBoosterBufferSize read failed %d\n",
5891 if (!hba->dev_info.b_presrv_uspc_en)
5892 return avail_buf <= UFS_WB_BUF_REMAIN_PERCENT(10);
5894 return ufshcd_wb_presrv_usrspc_keep_vcc_on(hba, avail_buf);
5897 static void ufshcd_rpm_dev_flush_recheck_work(struct work_struct *work)
5899 struct ufs_hba *hba = container_of(to_delayed_work(work),
5901 rpm_dev_flush_recheck_work);
5903 * To prevent unnecessary VCC power drain after device finishes
5904 * WriteBooster buffer flush or Auto BKOPs, force runtime resume
5905 * after a certain delay to recheck the threshold by next runtime
5908 ufshcd_rpm_get_sync(hba);
5909 ufshcd_rpm_put_sync(hba);
5913 * ufshcd_exception_event_handler - handle exceptions raised by device
5914 * @work: pointer to work data
5916 * Read bExceptionEventStatus attribute from the device and handle the
5917 * exception event accordingly.
5919 static void ufshcd_exception_event_handler(struct work_struct *work)
5921 struct ufs_hba *hba;
5924 hba = container_of(work, struct ufs_hba, eeh_work);
5926 ufshcd_scsi_block_requests(hba);
5927 err = ufshcd_get_ee_status(hba, &status);
5929 dev_err(hba->dev, "%s: failed to get exception status %d\n",
5934 trace_ufshcd_exception_event(dev_name(hba->dev), status);
5936 if (status & hba->ee_drv_mask & MASK_EE_URGENT_BKOPS)
5937 ufshcd_bkops_exception_event_handler(hba);
5939 if (status & hba->ee_drv_mask & MASK_EE_URGENT_TEMP)
5940 ufshcd_temp_exception_event_handler(hba, status);
5942 ufs_debugfs_exception_event(hba, status);
5944 ufshcd_scsi_unblock_requests(hba);
5947 /* Complete requests that have door-bell cleared */
5948 static void ufshcd_complete_requests(struct ufs_hba *hba)
5950 ufshcd_transfer_req_compl(hba);
5951 ufshcd_tmc_handler(hba);
5955 * ufshcd_quirk_dl_nac_errors - This function checks if error handling is
5956 * to recover from the DL NAC errors or not.
5957 * @hba: per-adapter instance
5959 * Returns true if error handling is required, false otherwise
5961 static bool ufshcd_quirk_dl_nac_errors(struct ufs_hba *hba)
5963 unsigned long flags;
5964 bool err_handling = true;
5966 spin_lock_irqsave(hba->host->host_lock, flags);
5968 * UFS_DEVICE_QUIRK_RECOVERY_FROM_DL_NAC_ERRORS only workaround the
5969 * device fatal error and/or DL NAC & REPLAY timeout errors.
5971 if (hba->saved_err & (CONTROLLER_FATAL_ERROR | SYSTEM_BUS_FATAL_ERROR))
5974 if ((hba->saved_err & DEVICE_FATAL_ERROR) ||
5975 ((hba->saved_err & UIC_ERROR) &&
5976 (hba->saved_uic_err & UFSHCD_UIC_DL_TCx_REPLAY_ERROR)))
5979 if ((hba->saved_err & UIC_ERROR) &&
5980 (hba->saved_uic_err & UFSHCD_UIC_DL_NAC_RECEIVED_ERROR)) {
5983 * wait for 50ms to see if we can get any other errors or not.
5985 spin_unlock_irqrestore(hba->host->host_lock, flags);
5987 spin_lock_irqsave(hba->host->host_lock, flags);
5990 * now check if we have got any other severe errors other than
5993 if ((hba->saved_err & INT_FATAL_ERRORS) ||
5994 ((hba->saved_err & UIC_ERROR) &&
5995 (hba->saved_uic_err & ~UFSHCD_UIC_DL_NAC_RECEIVED_ERROR)))
5999 * As DL NAC is the only error received so far, send out NOP
6000 * command to confirm if link is still active or not.
6001 * - If we don't get any response then do error recovery.
6002 * - If we get response then clear the DL NAC error bit.
6005 spin_unlock_irqrestore(hba->host->host_lock, flags);
6006 err = ufshcd_verify_dev_init(hba);
6007 spin_lock_irqsave(hba->host->host_lock, flags);
6012 /* Link seems to be alive hence ignore the DL NAC errors */
6013 if (hba->saved_uic_err == UFSHCD_UIC_DL_NAC_RECEIVED_ERROR)
6014 hba->saved_err &= ~UIC_ERROR;
6015 /* clear NAC error */
6016 hba->saved_uic_err &= ~UFSHCD_UIC_DL_NAC_RECEIVED_ERROR;
6017 if (!hba->saved_uic_err)
6018 err_handling = false;
6021 spin_unlock_irqrestore(hba->host->host_lock, flags);
6022 return err_handling;
6025 /* host lock must be held before calling this func */
6026 static inline bool ufshcd_is_saved_err_fatal(struct ufs_hba *hba)
6028 return (hba->saved_uic_err & UFSHCD_UIC_DL_PA_INIT_ERROR) ||
6029 (hba->saved_err & (INT_FATAL_ERRORS | UFSHCD_UIC_HIBERN8_MASK));
6032 void ufshcd_schedule_eh_work(struct ufs_hba *hba)
6034 lockdep_assert_held(hba->host->host_lock);
6036 /* handle fatal errors only when link is not in error state */
6037 if (hba->ufshcd_state != UFSHCD_STATE_ERROR) {
6038 if (hba->force_reset || ufshcd_is_link_broken(hba) ||
6039 ufshcd_is_saved_err_fatal(hba))
6040 hba->ufshcd_state = UFSHCD_STATE_EH_SCHEDULED_FATAL;
6042 hba->ufshcd_state = UFSHCD_STATE_EH_SCHEDULED_NON_FATAL;
6043 queue_work(hba->eh_wq, &hba->eh_work);
6047 static void ufshcd_clk_scaling_allow(struct ufs_hba *hba, bool allow)
6049 down_write(&hba->clk_scaling_lock);
6050 hba->clk_scaling.is_allowed = allow;
6051 up_write(&hba->clk_scaling_lock);
6054 static void ufshcd_clk_scaling_suspend(struct ufs_hba *hba, bool suspend)
6057 if (hba->clk_scaling.is_enabled)
6058 ufshcd_suspend_clkscaling(hba);
6059 ufshcd_clk_scaling_allow(hba, false);
6061 ufshcd_clk_scaling_allow(hba, true);
6062 if (hba->clk_scaling.is_enabled)
6063 ufshcd_resume_clkscaling(hba);
6067 static void ufshcd_err_handling_prepare(struct ufs_hba *hba)
6069 ufshcd_rpm_get_sync(hba);
6070 if (pm_runtime_status_suspended(&hba->ufs_device_wlun->sdev_gendev) ||
6071 hba->is_sys_suspended) {
6072 enum ufs_pm_op pm_op;
6075 * Don't assume anything of resume, if
6076 * resume fails, irq and clocks can be OFF, and powers
6077 * can be OFF or in LPM.
6079 ufshcd_setup_hba_vreg(hba, true);
6080 ufshcd_enable_irq(hba);
6081 ufshcd_setup_vreg(hba, true);
6082 ufshcd_config_vreg_hpm(hba, hba->vreg_info.vccq);
6083 ufshcd_config_vreg_hpm(hba, hba->vreg_info.vccq2);
6084 ufshcd_hold(hba, false);
6085 if (!ufshcd_is_clkgating_allowed(hba))
6086 ufshcd_setup_clocks(hba, true);
6087 ufshcd_release(hba);
6088 pm_op = hba->is_sys_suspended ? UFS_SYSTEM_PM : UFS_RUNTIME_PM;
6089 ufshcd_vops_resume(hba, pm_op);
6091 ufshcd_hold(hba, false);
6092 if (ufshcd_is_clkscaling_supported(hba) &&
6093 hba->clk_scaling.is_enabled)
6094 ufshcd_suspend_clkscaling(hba);
6095 ufshcd_clk_scaling_allow(hba, false);
6097 ufshcd_scsi_block_requests(hba);
6098 /* Drain ufshcd_queuecommand() */
6100 cancel_work_sync(&hba->eeh_work);
6103 static void ufshcd_err_handling_unprepare(struct ufs_hba *hba)
6105 ufshcd_scsi_unblock_requests(hba);
6106 ufshcd_release(hba);
6107 if (ufshcd_is_clkscaling_supported(hba))
6108 ufshcd_clk_scaling_suspend(hba, false);
6109 ufshcd_rpm_put(hba);
6112 static inline bool ufshcd_err_handling_should_stop(struct ufs_hba *hba)
6114 return (!hba->is_powered || hba->shutting_down ||
6115 !hba->ufs_device_wlun ||
6116 hba->ufshcd_state == UFSHCD_STATE_ERROR ||
6117 (!(hba->saved_err || hba->saved_uic_err || hba->force_reset ||
6118 ufshcd_is_link_broken(hba))));
6122 static void ufshcd_recover_pm_error(struct ufs_hba *hba)
6124 struct Scsi_Host *shost = hba->host;
6125 struct scsi_device *sdev;
6126 struct request_queue *q;
6129 hba->is_sys_suspended = false;
6131 * Set RPM status of wlun device to RPM_ACTIVE,
6132 * this also clears its runtime error.
6134 ret = pm_runtime_set_active(&hba->ufs_device_wlun->sdev_gendev);
6136 /* hba device might have a runtime error otherwise */
6138 ret = pm_runtime_set_active(hba->dev);
6140 * If wlun device had runtime error, we also need to resume those
6141 * consumer scsi devices in case any of them has failed to be
6142 * resumed due to supplier runtime resume failure. This is to unblock
6143 * blk_queue_enter in case there are bios waiting inside it.
6146 shost_for_each_device(sdev, shost) {
6147 q = sdev->request_queue;
6148 if (q->dev && (q->rpm_status == RPM_SUSPENDED ||
6149 q->rpm_status == RPM_SUSPENDING))
6150 pm_request_resume(q->dev);
6155 static inline void ufshcd_recover_pm_error(struct ufs_hba *hba)
6160 static bool ufshcd_is_pwr_mode_restore_needed(struct ufs_hba *hba)
6162 struct ufs_pa_layer_attr *pwr_info = &hba->pwr_info;
6165 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_PWRMODE), &mode);
6167 if (pwr_info->pwr_rx != ((mode >> PWRMODE_RX_OFFSET) & PWRMODE_MASK))
6170 if (pwr_info->pwr_tx != (mode & PWRMODE_MASK))
6177 * ufshcd_err_handler - handle UFS errors that require s/w attention
6178 * @work: pointer to work structure
6180 static void ufshcd_err_handler(struct work_struct *work)
6182 int retries = MAX_ERR_HANDLER_RETRIES;
6183 struct ufs_hba *hba;
6184 unsigned long flags;
6192 hba = container_of(work, struct ufs_hba, eh_work);
6195 "%s started; HBA state %s; powered %d; shutting down %d; saved_err = %d; saved_uic_err = %d; force_reset = %d%s\n",
6196 __func__, ufshcd_state_name[hba->ufshcd_state],
6197 hba->is_powered, hba->shutting_down, hba->saved_err,
6198 hba->saved_uic_err, hba->force_reset,
6199 ufshcd_is_link_broken(hba) ? "; link is broken" : "");
6201 down(&hba->host_sem);
6202 spin_lock_irqsave(hba->host->host_lock, flags);
6203 if (ufshcd_err_handling_should_stop(hba)) {
6204 if (hba->ufshcd_state != UFSHCD_STATE_ERROR)
6205 hba->ufshcd_state = UFSHCD_STATE_OPERATIONAL;
6206 spin_unlock_irqrestore(hba->host->host_lock, flags);
6210 ufshcd_set_eh_in_progress(hba);
6211 spin_unlock_irqrestore(hba->host->host_lock, flags);
6212 ufshcd_err_handling_prepare(hba);
6213 /* Complete requests that have door-bell cleared by h/w */
6214 ufshcd_complete_requests(hba);
6215 spin_lock_irqsave(hba->host->host_lock, flags);
6217 needs_restore = false;
6218 needs_reset = false;
6222 if (hba->ufshcd_state != UFSHCD_STATE_ERROR)
6223 hba->ufshcd_state = UFSHCD_STATE_RESET;
6225 * A full reset and restore might have happened after preparation
6226 * is finished, double check whether we should stop.
6228 if (ufshcd_err_handling_should_stop(hba))
6229 goto skip_err_handling;
6231 if (hba->dev_quirks & UFS_DEVICE_QUIRK_RECOVERY_FROM_DL_NAC_ERRORS) {
6234 spin_unlock_irqrestore(hba->host->host_lock, flags);
6235 /* release the lock as ufshcd_quirk_dl_nac_errors() may sleep */
6236 ret = ufshcd_quirk_dl_nac_errors(hba);
6237 spin_lock_irqsave(hba->host->host_lock, flags);
6238 if (!ret && ufshcd_err_handling_should_stop(hba))
6239 goto skip_err_handling;
6242 if ((hba->saved_err & (INT_FATAL_ERRORS | UFSHCD_UIC_HIBERN8_MASK)) ||
6243 (hba->saved_uic_err &&
6244 (hba->saved_uic_err != UFSHCD_UIC_PA_GENERIC_ERROR))) {
6245 bool pr_prdt = !!(hba->saved_err & SYSTEM_BUS_FATAL_ERROR);
6247 spin_unlock_irqrestore(hba->host->host_lock, flags);
6248 ufshcd_print_host_state(hba);
6249 ufshcd_print_pwr_info(hba);
6250 ufshcd_print_evt_hist(hba);
6251 ufshcd_print_tmrs(hba, hba->outstanding_tasks);
6252 ufshcd_print_trs(hba, hba->outstanding_reqs, pr_prdt);
6253 spin_lock_irqsave(hba->host->host_lock, flags);
6257 * if host reset is required then skip clearing the pending
6258 * transfers forcefully because they will get cleared during
6259 * host reset and restore
6261 if (hba->force_reset || ufshcd_is_link_broken(hba) ||
6262 ufshcd_is_saved_err_fatal(hba) ||
6263 ((hba->saved_err & UIC_ERROR) &&
6264 (hba->saved_uic_err & (UFSHCD_UIC_DL_NAC_RECEIVED_ERROR |
6265 UFSHCD_UIC_DL_TCx_REPLAY_ERROR)))) {
6271 * If LINERESET was caught, UFS might have been put to PWM mode,
6272 * check if power mode restore is needed.
6274 if (hba->saved_uic_err & UFSHCD_UIC_PA_GENERIC_ERROR) {
6275 hba->saved_uic_err &= ~UFSHCD_UIC_PA_GENERIC_ERROR;
6276 if (!hba->saved_uic_err)
6277 hba->saved_err &= ~UIC_ERROR;
6278 spin_unlock_irqrestore(hba->host->host_lock, flags);
6279 if (ufshcd_is_pwr_mode_restore_needed(hba))
6280 needs_restore = true;
6281 spin_lock_irqsave(hba->host->host_lock, flags);
6282 if (!hba->saved_err && !needs_restore)
6283 goto skip_err_handling;
6286 hba->silence_err_logs = true;
6287 /* release lock as clear command might sleep */
6288 spin_unlock_irqrestore(hba->host->host_lock, flags);
6289 /* Clear pending transfer requests */
6290 for_each_set_bit(tag, &hba->outstanding_reqs, hba->nutrs) {
6291 if (ufshcd_try_to_abort_task(hba, tag)) {
6293 goto lock_skip_pending_xfer_clear;
6295 dev_err(hba->dev, "Aborted tag %d / CDB %#02x\n", tag,
6296 hba->lrb[tag].cmd ? hba->lrb[tag].cmd->cmnd[0] : -1);
6299 /* Clear pending task management requests */
6300 for_each_set_bit(tag, &hba->outstanding_tasks, hba->nutmrs) {
6301 if (ufshcd_clear_tm_cmd(hba, tag)) {
6303 goto lock_skip_pending_xfer_clear;
6307 lock_skip_pending_xfer_clear:
6308 /* Complete the requests that are cleared by s/w */
6309 ufshcd_complete_requests(hba);
6311 spin_lock_irqsave(hba->host->host_lock, flags);
6312 hba->silence_err_logs = false;
6313 if (err_xfer || err_tm) {
6319 * After all reqs and tasks are cleared from doorbell,
6320 * now it is safe to retore power mode.
6322 if (needs_restore) {
6323 spin_unlock_irqrestore(hba->host->host_lock, flags);
6325 * Hold the scaling lock just in case dev cmds
6326 * are sent via bsg and/or sysfs.
6328 down_write(&hba->clk_scaling_lock);
6329 hba->force_pmc = true;
6330 pmc_err = ufshcd_config_pwr_mode(hba, &(hba->pwr_info));
6333 dev_err(hba->dev, "%s: Failed to restore power mode, err = %d\n",
6336 hba->force_pmc = false;
6337 ufshcd_print_pwr_info(hba);
6338 up_write(&hba->clk_scaling_lock);
6339 spin_lock_irqsave(hba->host->host_lock, flags);
6343 /* Fatal errors need reset */
6347 hba->force_reset = false;
6348 spin_unlock_irqrestore(hba->host->host_lock, flags);
6349 err = ufshcd_reset_and_restore(hba);
6351 dev_err(hba->dev, "%s: reset and restore failed with err %d\n",
6354 ufshcd_recover_pm_error(hba);
6355 spin_lock_irqsave(hba->host->host_lock, flags);
6360 if (hba->ufshcd_state == UFSHCD_STATE_RESET)
6361 hba->ufshcd_state = UFSHCD_STATE_OPERATIONAL;
6362 if (hba->saved_err || hba->saved_uic_err)
6363 dev_err_ratelimited(hba->dev, "%s: exit: saved_err 0x%x saved_uic_err 0x%x",
6364 __func__, hba->saved_err, hba->saved_uic_err);
6366 /* Exit in an operational state or dead */
6367 if (hba->ufshcd_state != UFSHCD_STATE_OPERATIONAL &&
6368 hba->ufshcd_state != UFSHCD_STATE_ERROR) {
6371 hba->ufshcd_state = UFSHCD_STATE_ERROR;
6373 ufshcd_clear_eh_in_progress(hba);
6374 spin_unlock_irqrestore(hba->host->host_lock, flags);
6375 ufshcd_err_handling_unprepare(hba);
6378 dev_info(hba->dev, "%s finished; HBA state %s\n", __func__,
6379 ufshcd_state_name[hba->ufshcd_state]);
6383 * ufshcd_update_uic_error - check and set fatal UIC error flags.
6384 * @hba: per-adapter instance
6387 * IRQ_HANDLED - If interrupt is valid
6388 * IRQ_NONE - If invalid interrupt
6390 static irqreturn_t ufshcd_update_uic_error(struct ufs_hba *hba)
6393 irqreturn_t retval = IRQ_NONE;
6395 /* PHY layer error */
6396 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_PHY_ADAPTER_LAYER);
6397 if ((reg & UIC_PHY_ADAPTER_LAYER_ERROR) &&
6398 (reg & UIC_PHY_ADAPTER_LAYER_ERROR_CODE_MASK)) {
6399 ufshcd_update_evt_hist(hba, UFS_EVT_PA_ERR, reg);
6401 * To know whether this error is fatal or not, DB timeout
6402 * must be checked but this error is handled separately.
6404 if (reg & UIC_PHY_ADAPTER_LAYER_LANE_ERR_MASK)
6405 dev_dbg(hba->dev, "%s: UIC Lane error reported\n",
6408 /* Got a LINERESET indication. */
6409 if (reg & UIC_PHY_ADAPTER_LAYER_GENERIC_ERROR) {
6410 struct uic_command *cmd = NULL;
6412 hba->uic_error |= UFSHCD_UIC_PA_GENERIC_ERROR;
6413 if (hba->uic_async_done && hba->active_uic_cmd)
6414 cmd = hba->active_uic_cmd;
6416 * Ignore the LINERESET during power mode change
6417 * operation via DME_SET command.
6419 if (cmd && (cmd->command == UIC_CMD_DME_SET))
6420 hba->uic_error &= ~UFSHCD_UIC_PA_GENERIC_ERROR;
6422 retval |= IRQ_HANDLED;
6425 /* PA_INIT_ERROR is fatal and needs UIC reset */
6426 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_DATA_LINK_LAYER);
6427 if ((reg & UIC_DATA_LINK_LAYER_ERROR) &&
6428 (reg & UIC_DATA_LINK_LAYER_ERROR_CODE_MASK)) {
6429 ufshcd_update_evt_hist(hba, UFS_EVT_DL_ERR, reg);
6431 if (reg & UIC_DATA_LINK_LAYER_ERROR_PA_INIT)
6432 hba->uic_error |= UFSHCD_UIC_DL_PA_INIT_ERROR;
6433 else if (hba->dev_quirks &
6434 UFS_DEVICE_QUIRK_RECOVERY_FROM_DL_NAC_ERRORS) {
6435 if (reg & UIC_DATA_LINK_LAYER_ERROR_NAC_RECEIVED)
6437 UFSHCD_UIC_DL_NAC_RECEIVED_ERROR;
6438 else if (reg & UIC_DATA_LINK_LAYER_ERROR_TCx_REPLAY_TIMEOUT)
6439 hba->uic_error |= UFSHCD_UIC_DL_TCx_REPLAY_ERROR;
6441 retval |= IRQ_HANDLED;
6444 /* UIC NL/TL/DME errors needs software retry */
6445 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_NETWORK_LAYER);
6446 if ((reg & UIC_NETWORK_LAYER_ERROR) &&
6447 (reg & UIC_NETWORK_LAYER_ERROR_CODE_MASK)) {
6448 ufshcd_update_evt_hist(hba, UFS_EVT_NL_ERR, reg);
6449 hba->uic_error |= UFSHCD_UIC_NL_ERROR;
6450 retval |= IRQ_HANDLED;
6453 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_TRANSPORT_LAYER);
6454 if ((reg & UIC_TRANSPORT_LAYER_ERROR) &&
6455 (reg & UIC_TRANSPORT_LAYER_ERROR_CODE_MASK)) {
6456 ufshcd_update_evt_hist(hba, UFS_EVT_TL_ERR, reg);
6457 hba->uic_error |= UFSHCD_UIC_TL_ERROR;
6458 retval |= IRQ_HANDLED;
6461 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_DME);
6462 if ((reg & UIC_DME_ERROR) &&
6463 (reg & UIC_DME_ERROR_CODE_MASK)) {
6464 ufshcd_update_evt_hist(hba, UFS_EVT_DME_ERR, reg);
6465 hba->uic_error |= UFSHCD_UIC_DME_ERROR;
6466 retval |= IRQ_HANDLED;
6469 dev_dbg(hba->dev, "%s: UIC error flags = 0x%08x\n",
6470 __func__, hba->uic_error);
6475 * ufshcd_check_errors - Check for errors that need s/w attention
6476 * @hba: per-adapter instance
6477 * @intr_status: interrupt status generated by the controller
6480 * IRQ_HANDLED - If interrupt is valid
6481 * IRQ_NONE - If invalid interrupt
6483 static irqreturn_t ufshcd_check_errors(struct ufs_hba *hba, u32 intr_status)
6485 bool queue_eh_work = false;
6486 irqreturn_t retval = IRQ_NONE;
6488 spin_lock(hba->host->host_lock);
6489 hba->errors |= UFSHCD_ERROR_MASK & intr_status;
6491 if (hba->errors & INT_FATAL_ERRORS) {
6492 ufshcd_update_evt_hist(hba, UFS_EVT_FATAL_ERR,
6494 queue_eh_work = true;
6497 if (hba->errors & UIC_ERROR) {
6499 retval = ufshcd_update_uic_error(hba);
6501 queue_eh_work = true;
6504 if (hba->errors & UFSHCD_UIC_HIBERN8_MASK) {
6506 "%s: Auto Hibern8 %s failed - status: 0x%08x, upmcrs: 0x%08x\n",
6507 __func__, (hba->errors & UIC_HIBERNATE_ENTER) ?
6509 hba->errors, ufshcd_get_upmcrs(hba));
6510 ufshcd_update_evt_hist(hba, UFS_EVT_AUTO_HIBERN8_ERR,
6512 ufshcd_set_link_broken(hba);
6513 queue_eh_work = true;
6516 if (queue_eh_work) {
6518 * update the transfer error masks to sticky bits, let's do this
6519 * irrespective of current ufshcd_state.
6521 hba->saved_err |= hba->errors;
6522 hba->saved_uic_err |= hba->uic_error;
6524 /* dump controller state before resetting */
6525 if ((hba->saved_err &
6526 (INT_FATAL_ERRORS | UFSHCD_UIC_HIBERN8_MASK)) ||
6527 (hba->saved_uic_err &&
6528 (hba->saved_uic_err != UFSHCD_UIC_PA_GENERIC_ERROR))) {
6529 dev_err(hba->dev, "%s: saved_err 0x%x saved_uic_err 0x%x\n",
6530 __func__, hba->saved_err,
6531 hba->saved_uic_err);
6532 ufshcd_dump_regs(hba, 0, UFSHCI_REG_SPACE_SIZE,
6534 ufshcd_print_pwr_info(hba);
6536 ufshcd_schedule_eh_work(hba);
6537 retval |= IRQ_HANDLED;
6540 * if (!queue_eh_work) -
6541 * Other errors are either non-fatal where host recovers
6542 * itself without s/w intervention or errors that will be
6543 * handled by the SCSI core layer.
6547 spin_unlock(hba->host->host_lock);
6552 * ufshcd_tmc_handler - handle task management function completion
6553 * @hba: per adapter instance
6556 * IRQ_HANDLED - If interrupt is valid
6557 * IRQ_NONE - If invalid interrupt
6559 static irqreturn_t ufshcd_tmc_handler(struct ufs_hba *hba)
6561 unsigned long flags, pending, issued;
6562 irqreturn_t ret = IRQ_NONE;
6565 spin_lock_irqsave(hba->host->host_lock, flags);
6566 pending = ufshcd_readl(hba, REG_UTP_TASK_REQ_DOOR_BELL);
6567 issued = hba->outstanding_tasks & ~pending;
6568 for_each_set_bit(tag, &issued, hba->nutmrs) {
6569 struct request *req = hba->tmf_rqs[tag];
6570 struct completion *c = req->end_io_data;
6575 spin_unlock_irqrestore(hba->host->host_lock, flags);
6581 * ufshcd_sl_intr - Interrupt service routine
6582 * @hba: per adapter instance
6583 * @intr_status: contains interrupts generated by the controller
6586 * IRQ_HANDLED - If interrupt is valid
6587 * IRQ_NONE - If invalid interrupt
6589 static irqreturn_t ufshcd_sl_intr(struct ufs_hba *hba, u32 intr_status)
6591 irqreturn_t retval = IRQ_NONE;
6593 if (intr_status & UFSHCD_UIC_MASK)
6594 retval |= ufshcd_uic_cmd_compl(hba, intr_status);
6596 if (intr_status & UFSHCD_ERROR_MASK || hba->errors)
6597 retval |= ufshcd_check_errors(hba, intr_status);
6599 if (intr_status & UTP_TASK_REQ_COMPL)
6600 retval |= ufshcd_tmc_handler(hba);
6602 if (intr_status & UTP_TRANSFER_REQ_COMPL)
6603 retval |= ufshcd_transfer_req_compl(hba);
6609 * ufshcd_intr - Main interrupt service routine
6611 * @__hba: pointer to adapter instance
6614 * IRQ_HANDLED - If interrupt is valid
6615 * IRQ_NONE - If invalid interrupt
6617 static irqreturn_t ufshcd_intr(int irq, void *__hba)
6619 u32 intr_status, enabled_intr_status = 0;
6620 irqreturn_t retval = IRQ_NONE;
6621 struct ufs_hba *hba = __hba;
6622 int retries = hba->nutrs;
6624 intr_status = ufshcd_readl(hba, REG_INTERRUPT_STATUS);
6625 hba->ufs_stats.last_intr_status = intr_status;
6626 hba->ufs_stats.last_intr_ts = ktime_get();
6629 * There could be max of hba->nutrs reqs in flight and in worst case
6630 * if the reqs get finished 1 by 1 after the interrupt status is
6631 * read, make sure we handle them by checking the interrupt status
6632 * again in a loop until we process all of the reqs before returning.
6634 while (intr_status && retries--) {
6635 enabled_intr_status =
6636 intr_status & ufshcd_readl(hba, REG_INTERRUPT_ENABLE);
6637 ufshcd_writel(hba, intr_status, REG_INTERRUPT_STATUS);
6638 if (enabled_intr_status)
6639 retval |= ufshcd_sl_intr(hba, enabled_intr_status);
6641 intr_status = ufshcd_readl(hba, REG_INTERRUPT_STATUS);
6644 if (enabled_intr_status && retval == IRQ_NONE &&
6645 (!(enabled_intr_status & UTP_TRANSFER_REQ_COMPL) ||
6646 hba->outstanding_reqs) && !ufshcd_eh_in_progress(hba)) {
6647 dev_err(hba->dev, "%s: Unhandled interrupt 0x%08x (0x%08x, 0x%08x)\n",
6650 hba->ufs_stats.last_intr_status,
6651 enabled_intr_status);
6652 ufshcd_dump_regs(hba, 0, UFSHCI_REG_SPACE_SIZE, "host_regs: ");
6658 static int ufshcd_clear_tm_cmd(struct ufs_hba *hba, int tag)
6661 u32 mask = 1 << tag;
6662 unsigned long flags;
6664 if (!test_bit(tag, &hba->outstanding_tasks))
6667 spin_lock_irqsave(hba->host->host_lock, flags);
6668 ufshcd_utmrl_clear(hba, tag);
6669 spin_unlock_irqrestore(hba->host->host_lock, flags);
6671 /* poll for max. 1 sec to clear door bell register by h/w */
6672 err = ufshcd_wait_for_register(hba,
6673 REG_UTP_TASK_REQ_DOOR_BELL,
6674 mask, 0, 1000, 1000);
6676 dev_err(hba->dev, "Clearing task management function with tag %d %s\n",
6677 tag, err ? "succeeded" : "failed");
6683 static int __ufshcd_issue_tm_cmd(struct ufs_hba *hba,
6684 struct utp_task_req_desc *treq, u8 tm_function)
6686 struct request_queue *q = hba->tmf_queue;
6687 struct Scsi_Host *host = hba->host;
6688 DECLARE_COMPLETION_ONSTACK(wait);
6689 struct request *req;
6690 unsigned long flags;
6694 * blk_mq_alloc_request() is used here only to get a free tag.
6696 req = blk_mq_alloc_request(q, REQ_OP_DRV_OUT, 0);
6698 return PTR_ERR(req);
6700 req->end_io_data = &wait;
6701 ufshcd_hold(hba, false);
6703 spin_lock_irqsave(host->host_lock, flags);
6705 task_tag = req->tag;
6706 WARN_ONCE(task_tag < 0 || task_tag >= hba->nutmrs, "Invalid tag %d\n",
6708 hba->tmf_rqs[req->tag] = req;
6709 treq->upiu_req.req_header.dword_0 |= cpu_to_be32(task_tag);
6711 memcpy(hba->utmrdl_base_addr + task_tag, treq, sizeof(*treq));
6712 ufshcd_vops_setup_task_mgmt(hba, task_tag, tm_function);
6714 /* send command to the controller */
6715 __set_bit(task_tag, &hba->outstanding_tasks);
6717 ufshcd_writel(hba, 1 << task_tag, REG_UTP_TASK_REQ_DOOR_BELL);
6718 /* Make sure that doorbell is committed immediately */
6721 spin_unlock_irqrestore(host->host_lock, flags);
6723 ufshcd_add_tm_upiu_trace(hba, task_tag, UFS_TM_SEND);
6725 /* wait until the task management command is completed */
6726 err = wait_for_completion_io_timeout(&wait,
6727 msecs_to_jiffies(TM_CMD_TIMEOUT));
6729 ufshcd_add_tm_upiu_trace(hba, task_tag, UFS_TM_ERR);
6730 dev_err(hba->dev, "%s: task management cmd 0x%.2x timed-out\n",
6731 __func__, tm_function);
6732 if (ufshcd_clear_tm_cmd(hba, task_tag))
6733 dev_WARN(hba->dev, "%s: unable to clear tm cmd (slot %d) after timeout\n",
6734 __func__, task_tag);
6738 memcpy(treq, hba->utmrdl_base_addr + task_tag, sizeof(*treq));
6740 ufshcd_add_tm_upiu_trace(hba, task_tag, UFS_TM_COMP);
6743 spin_lock_irqsave(hba->host->host_lock, flags);
6744 hba->tmf_rqs[req->tag] = NULL;
6745 __clear_bit(task_tag, &hba->outstanding_tasks);
6746 spin_unlock_irqrestore(hba->host->host_lock, flags);
6748 ufshcd_release(hba);
6749 blk_mq_free_request(req);
6755 * ufshcd_issue_tm_cmd - issues task management commands to controller
6756 * @hba: per adapter instance
6757 * @lun_id: LUN ID to which TM command is sent
6758 * @task_id: task ID to which the TM command is applicable
6759 * @tm_function: task management function opcode
6760 * @tm_response: task management service response return value
6762 * Returns non-zero value on error, zero on success.
6764 static int ufshcd_issue_tm_cmd(struct ufs_hba *hba, int lun_id, int task_id,
6765 u8 tm_function, u8 *tm_response)
6767 struct utp_task_req_desc treq = { { 0 }, };
6768 enum utp_ocs ocs_value;
6771 /* Configure task request descriptor */
6772 treq.header.dword_0 = cpu_to_le32(UTP_REQ_DESC_INT_CMD);
6773 treq.header.dword_2 = cpu_to_le32(OCS_INVALID_COMMAND_STATUS);
6775 /* Configure task request UPIU */
6776 treq.upiu_req.req_header.dword_0 = cpu_to_be32(lun_id << 8) |
6777 cpu_to_be32(UPIU_TRANSACTION_TASK_REQ << 24);
6778 treq.upiu_req.req_header.dword_1 = cpu_to_be32(tm_function << 16);
6781 * The host shall provide the same value for LUN field in the basic
6782 * header and for Input Parameter.
6784 treq.upiu_req.input_param1 = cpu_to_be32(lun_id);
6785 treq.upiu_req.input_param2 = cpu_to_be32(task_id);
6787 err = __ufshcd_issue_tm_cmd(hba, &treq, tm_function);
6788 if (err == -ETIMEDOUT)
6791 ocs_value = le32_to_cpu(treq.header.dword_2) & MASK_OCS;
6792 if (ocs_value != OCS_SUCCESS)
6793 dev_err(hba->dev, "%s: failed, ocs = 0x%x\n",
6794 __func__, ocs_value);
6795 else if (tm_response)
6796 *tm_response = be32_to_cpu(treq.upiu_rsp.output_param1) &
6797 MASK_TM_SERVICE_RESP;
6802 * ufshcd_issue_devman_upiu_cmd - API for sending "utrd" type requests
6803 * @hba: per-adapter instance
6804 * @req_upiu: upiu request
6805 * @rsp_upiu: upiu reply
6806 * @desc_buff: pointer to descriptor buffer, NULL if NA
6807 * @buff_len: descriptor size, 0 if NA
6808 * @cmd_type: specifies the type (NOP, Query...)
6809 * @desc_op: descriptor operation
6811 * Those type of requests uses UTP Transfer Request Descriptor - utrd.
6812 * Therefore, it "rides" the device management infrastructure: uses its tag and
6813 * tasks work queues.
6815 * Since there is only one available tag for device management commands,
6816 * the caller is expected to hold the hba->dev_cmd.lock mutex.
6818 static int ufshcd_issue_devman_upiu_cmd(struct ufs_hba *hba,
6819 struct utp_upiu_req *req_upiu,
6820 struct utp_upiu_req *rsp_upiu,
6821 u8 *desc_buff, int *buff_len,
6822 enum dev_cmd_type cmd_type,
6823 enum query_opcode desc_op)
6825 DECLARE_COMPLETION_ONSTACK(wait);
6826 const u32 tag = hba->reserved_slot;
6827 struct ufshcd_lrb *lrbp;
6831 /* Protects use of hba->reserved_slot. */
6832 lockdep_assert_held(&hba->dev_cmd.lock);
6834 down_read(&hba->clk_scaling_lock);
6836 lrbp = &hba->lrb[tag];
6839 lrbp->task_tag = tag;
6841 lrbp->intr_cmd = true;
6842 ufshcd_prepare_lrbp_crypto(NULL, lrbp);
6843 hba->dev_cmd.type = cmd_type;
6845 if (hba->ufs_version <= ufshci_version(1, 1))
6846 lrbp->command_type = UTP_CMD_TYPE_DEV_MANAGE;
6848 lrbp->command_type = UTP_CMD_TYPE_UFS_STORAGE;
6850 /* update the task tag in the request upiu */
6851 req_upiu->header.dword_0 |= cpu_to_be32(tag);
6853 ufshcd_prepare_req_desc_hdr(lrbp, &upiu_flags, DMA_NONE);
6855 /* just copy the upiu request as it is */
6856 memcpy(lrbp->ucd_req_ptr, req_upiu, sizeof(*lrbp->ucd_req_ptr));
6857 if (desc_buff && desc_op == UPIU_QUERY_OPCODE_WRITE_DESC) {
6858 /* The Data Segment Area is optional depending upon the query
6859 * function value. for WRITE DESCRIPTOR, the data segment
6860 * follows right after the tsf.
6862 memcpy(lrbp->ucd_req_ptr + 1, desc_buff, *buff_len);
6866 memset(lrbp->ucd_rsp_ptr, 0, sizeof(struct utp_upiu_rsp));
6868 hba->dev_cmd.complete = &wait;
6870 ufshcd_add_query_upiu_trace(hba, UFS_QUERY_SEND, lrbp->ucd_req_ptr);
6872 ufshcd_send_command(hba, tag);
6874 * ignore the returning value here - ufshcd_check_query_response is
6875 * bound to fail since dev_cmd.query and dev_cmd.type were left empty.
6876 * read the response directly ignoring all errors.
6878 ufshcd_wait_for_dev_cmd(hba, lrbp, QUERY_REQ_TIMEOUT);
6880 /* just copy the upiu response as it is */
6881 memcpy(rsp_upiu, lrbp->ucd_rsp_ptr, sizeof(*rsp_upiu));
6882 if (desc_buff && desc_op == UPIU_QUERY_OPCODE_READ_DESC) {
6883 u8 *descp = (u8 *)lrbp->ucd_rsp_ptr + sizeof(*rsp_upiu);
6884 u16 resp_len = be32_to_cpu(lrbp->ucd_rsp_ptr->header.dword_2) &
6885 MASK_QUERY_DATA_SEG_LEN;
6887 if (*buff_len >= resp_len) {
6888 memcpy(desc_buff, descp, resp_len);
6889 *buff_len = resp_len;
6892 "%s: rsp size %d is bigger than buffer size %d",
6893 __func__, resp_len, *buff_len);
6898 ufshcd_add_query_upiu_trace(hba, err ? UFS_QUERY_ERR : UFS_QUERY_COMP,
6899 (struct utp_upiu_req *)lrbp->ucd_rsp_ptr);
6901 up_read(&hba->clk_scaling_lock);
6906 * ufshcd_exec_raw_upiu_cmd - API function for sending raw upiu commands
6907 * @hba: per-adapter instance
6908 * @req_upiu: upiu request
6909 * @rsp_upiu: upiu reply - only 8 DW as we do not support scsi commands
6910 * @msgcode: message code, one of UPIU Transaction Codes Initiator to Target
6911 * @desc_buff: pointer to descriptor buffer, NULL if NA
6912 * @buff_len: descriptor size, 0 if NA
6913 * @desc_op: descriptor operation
6915 * Supports UTP Transfer requests (nop and query), and UTP Task
6916 * Management requests.
6917 * It is up to the caller to fill the upiu conent properly, as it will
6918 * be copied without any further input validations.
6920 int ufshcd_exec_raw_upiu_cmd(struct ufs_hba *hba,
6921 struct utp_upiu_req *req_upiu,
6922 struct utp_upiu_req *rsp_upiu,
6924 u8 *desc_buff, int *buff_len,
6925 enum query_opcode desc_op)
6928 enum dev_cmd_type cmd_type = DEV_CMD_TYPE_QUERY;
6929 struct utp_task_req_desc treq = { { 0 }, };
6930 enum utp_ocs ocs_value;
6931 u8 tm_f = be32_to_cpu(req_upiu->header.dword_1) >> 16 & MASK_TM_FUNC;
6934 case UPIU_TRANSACTION_NOP_OUT:
6935 cmd_type = DEV_CMD_TYPE_NOP;
6937 case UPIU_TRANSACTION_QUERY_REQ:
6938 ufshcd_hold(hba, false);
6939 mutex_lock(&hba->dev_cmd.lock);
6940 err = ufshcd_issue_devman_upiu_cmd(hba, req_upiu, rsp_upiu,
6941 desc_buff, buff_len,
6943 mutex_unlock(&hba->dev_cmd.lock);
6944 ufshcd_release(hba);
6947 case UPIU_TRANSACTION_TASK_REQ:
6948 treq.header.dword_0 = cpu_to_le32(UTP_REQ_DESC_INT_CMD);
6949 treq.header.dword_2 = cpu_to_le32(OCS_INVALID_COMMAND_STATUS);
6951 memcpy(&treq.upiu_req, req_upiu, sizeof(*req_upiu));
6953 err = __ufshcd_issue_tm_cmd(hba, &treq, tm_f);
6954 if (err == -ETIMEDOUT)
6957 ocs_value = le32_to_cpu(treq.header.dword_2) & MASK_OCS;
6958 if (ocs_value != OCS_SUCCESS) {
6959 dev_err(hba->dev, "%s: failed, ocs = 0x%x\n", __func__,
6964 memcpy(rsp_upiu, &treq.upiu_rsp, sizeof(*rsp_upiu));
6977 * ufshcd_eh_device_reset_handler() - Reset a single logical unit.
6978 * @cmd: SCSI command pointer
6980 * Returns SUCCESS/FAILED
6982 static int ufshcd_eh_device_reset_handler(struct scsi_cmnd *cmd)
6984 unsigned long flags, pending_reqs = 0, not_cleared = 0;
6985 struct Scsi_Host *host;
6986 struct ufs_hba *hba;
6991 host = cmd->device->host;
6992 hba = shost_priv(host);
6994 lun = ufshcd_scsi_to_upiu_lun(cmd->device->lun);
6995 err = ufshcd_issue_tm_cmd(hba, lun, 0, UFS_LOGICAL_RESET, &resp);
6996 if (err || resp != UPIU_TASK_MANAGEMENT_FUNC_COMPL) {
7002 /* clear the commands that were pending for corresponding LUN */
7003 spin_lock_irqsave(&hba->outstanding_lock, flags);
7004 for_each_set_bit(pos, &hba->outstanding_reqs, hba->nutrs)
7005 if (hba->lrb[pos].lun == lun)
7006 __set_bit(pos, &pending_reqs);
7007 hba->outstanding_reqs &= ~pending_reqs;
7008 spin_unlock_irqrestore(&hba->outstanding_lock, flags);
7010 if (ufshcd_clear_cmds(hba, pending_reqs) < 0) {
7011 spin_lock_irqsave(&hba->outstanding_lock, flags);
7012 not_cleared = pending_reqs &
7013 ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
7014 hba->outstanding_reqs |= not_cleared;
7015 spin_unlock_irqrestore(&hba->outstanding_lock, flags);
7017 dev_err(hba->dev, "%s: failed to clear requests %#lx\n",
7018 __func__, not_cleared);
7020 __ufshcd_transfer_req_compl(hba, pending_reqs & ~not_cleared);
7023 hba->req_abort_count = 0;
7024 ufshcd_update_evt_hist(hba, UFS_EVT_DEV_RESET, (u32)err);
7028 dev_err(hba->dev, "%s: failed with err %d\n", __func__, err);
7034 static void ufshcd_set_req_abort_skip(struct ufs_hba *hba, unsigned long bitmap)
7036 struct ufshcd_lrb *lrbp;
7039 for_each_set_bit(tag, &bitmap, hba->nutrs) {
7040 lrbp = &hba->lrb[tag];
7041 lrbp->req_abort_skip = true;
7046 * ufshcd_try_to_abort_task - abort a specific task
7047 * @hba: Pointer to adapter instance
7048 * @tag: Task tag/index to be aborted
7050 * Abort the pending command in device by sending UFS_ABORT_TASK task management
7051 * command, and in host controller by clearing the door-bell register. There can
7052 * be race between controller sending the command to the device while abort is
7053 * issued. To avoid that, first issue UFS_QUERY_TASK to check if the command is
7054 * really issued and then try to abort it.
7056 * Returns zero on success, non-zero on failure
7058 static int ufshcd_try_to_abort_task(struct ufs_hba *hba, int tag)
7060 struct ufshcd_lrb *lrbp = &hba->lrb[tag];
7066 for (poll_cnt = 100; poll_cnt; poll_cnt--) {
7067 err = ufshcd_issue_tm_cmd(hba, lrbp->lun, lrbp->task_tag,
7068 UFS_QUERY_TASK, &resp);
7069 if (!err && resp == UPIU_TASK_MANAGEMENT_FUNC_SUCCEEDED) {
7070 /* cmd pending in the device */
7071 dev_err(hba->dev, "%s: cmd pending in the device. tag = %d\n",
7074 } else if (!err && resp == UPIU_TASK_MANAGEMENT_FUNC_COMPL) {
7076 * cmd not pending in the device, check if it is
7079 dev_err(hba->dev, "%s: cmd at tag %d not pending in the device.\n",
7081 reg = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
7082 if (reg & (1 << tag)) {
7083 /* sleep for max. 200us to stabilize */
7084 usleep_range(100, 200);
7087 /* command completed already */
7088 dev_err(hba->dev, "%s: cmd at tag %d successfully cleared from DB.\n",
7093 "%s: no response from device. tag = %d, err %d\n",
7094 __func__, tag, err);
7096 err = resp; /* service response error */
7106 err = ufshcd_issue_tm_cmd(hba, lrbp->lun, lrbp->task_tag,
7107 UFS_ABORT_TASK, &resp);
7108 if (err || resp != UPIU_TASK_MANAGEMENT_FUNC_COMPL) {
7110 err = resp; /* service response error */
7111 dev_err(hba->dev, "%s: issued. tag = %d, err %d\n",
7112 __func__, tag, err);
7117 err = ufshcd_clear_cmds(hba, 1U << tag);
7119 dev_err(hba->dev, "%s: Failed clearing cmd at tag %d, err %d\n",
7120 __func__, tag, err);
7127 * ufshcd_abort - scsi host template eh_abort_handler callback
7128 * @cmd: SCSI command pointer
7130 * Returns SUCCESS/FAILED
7132 static int ufshcd_abort(struct scsi_cmnd *cmd)
7134 struct Scsi_Host *host = cmd->device->host;
7135 struct ufs_hba *hba = shost_priv(host);
7136 int tag = scsi_cmd_to_rq(cmd)->tag;
7137 struct ufshcd_lrb *lrbp = &hba->lrb[tag];
7138 unsigned long flags;
7143 WARN_ONCE(tag < 0, "Invalid tag %d\n", tag);
7145 ufshcd_hold(hba, false);
7146 reg = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
7147 /* If command is already aborted/completed, return FAILED. */
7148 if (!(test_bit(tag, &hba->outstanding_reqs))) {
7150 "%s: cmd at tag %d already completed, outstanding=0x%lx, doorbell=0x%x\n",
7151 __func__, tag, hba->outstanding_reqs, reg);
7155 /* Print Transfer Request of aborted task */
7156 dev_info(hba->dev, "%s: Device abort task at tag %d\n", __func__, tag);
7159 * Print detailed info about aborted request.
7160 * As more than one request might get aborted at the same time,
7161 * print full information only for the first aborted request in order
7162 * to reduce repeated printouts. For other aborted requests only print
7165 scsi_print_command(cmd);
7166 if (!hba->req_abort_count) {
7167 ufshcd_update_evt_hist(hba, UFS_EVT_ABORT, tag);
7168 ufshcd_print_evt_hist(hba);
7169 ufshcd_print_host_state(hba);
7170 ufshcd_print_pwr_info(hba);
7171 ufshcd_print_trs(hba, 1 << tag, true);
7173 ufshcd_print_trs(hba, 1 << tag, false);
7175 hba->req_abort_count++;
7177 if (!(reg & (1 << tag))) {
7179 "%s: cmd was completed, but without a notifying intr, tag = %d",
7181 __ufshcd_transfer_req_compl(hba, 1UL << tag);
7186 * Task abort to the device W-LUN is illegal. When this command
7187 * will fail, due to spec violation, scsi err handling next step
7188 * will be to send LU reset which, again, is a spec violation.
7189 * To avoid these unnecessary/illegal steps, first we clean up
7190 * the lrb taken by this cmd and re-set it in outstanding_reqs,
7191 * then queue the eh_work and bail.
7193 if (lrbp->lun == UFS_UPIU_UFS_DEVICE_WLUN) {
7194 ufshcd_update_evt_hist(hba, UFS_EVT_ABORT, lrbp->lun);
7196 spin_lock_irqsave(host->host_lock, flags);
7197 hba->force_reset = true;
7198 ufshcd_schedule_eh_work(hba);
7199 spin_unlock_irqrestore(host->host_lock, flags);
7203 /* Skip task abort in case previous aborts failed and report failure */
7204 if (lrbp->req_abort_skip) {
7205 dev_err(hba->dev, "%s: skipping abort\n", __func__);
7206 ufshcd_set_req_abort_skip(hba, hba->outstanding_reqs);
7210 err = ufshcd_try_to_abort_task(hba, tag);
7212 dev_err(hba->dev, "%s: failed with err %d\n", __func__, err);
7213 ufshcd_set_req_abort_skip(hba, hba->outstanding_reqs);
7219 * Clear the corresponding bit from outstanding_reqs since the command
7220 * has been aborted successfully.
7222 spin_lock_irqsave(&hba->outstanding_lock, flags);
7223 outstanding = __test_and_clear_bit(tag, &hba->outstanding_reqs);
7224 spin_unlock_irqrestore(&hba->outstanding_lock, flags);
7227 ufshcd_release_scsi_cmd(hba, lrbp);
7232 /* Matches the ufshcd_hold() call at the start of this function. */
7233 ufshcd_release(hba);
7238 * ufshcd_host_reset_and_restore - reset and restore host controller
7239 * @hba: per-adapter instance
7241 * Note that host controller reset may issue DME_RESET to
7242 * local and remote (device) Uni-Pro stack and the attributes
7243 * are reset to default state.
7245 * Returns zero on success, non-zero on failure
7247 static int ufshcd_host_reset_and_restore(struct ufs_hba *hba)
7252 * Stop the host controller and complete the requests
7255 ufshpb_toggle_state(hba, HPB_PRESENT, HPB_RESET);
7256 ufshcd_hba_stop(hba);
7257 hba->silence_err_logs = true;
7258 ufshcd_complete_requests(hba);
7259 hba->silence_err_logs = false;
7261 /* scale up clocks to max frequency before full reinitialization */
7262 ufshcd_set_clk_freq(hba, true);
7264 err = ufshcd_hba_enable(hba);
7266 /* Establish the link again and restore the device */
7268 err = ufshcd_probe_hba(hba, false);
7271 dev_err(hba->dev, "%s: Host init failed %d\n", __func__, err);
7272 ufshcd_update_evt_hist(hba, UFS_EVT_HOST_RESET, (u32)err);
7277 * ufshcd_reset_and_restore - reset and re-initialize host/device
7278 * @hba: per-adapter instance
7280 * Reset and recover device, host and re-establish link. This
7281 * is helpful to recover the communication in fatal error conditions.
7283 * Returns zero on success, non-zero on failure
7285 static int ufshcd_reset_and_restore(struct ufs_hba *hba)
7288 u32 saved_uic_err = 0;
7290 unsigned long flags;
7291 int retries = MAX_HOST_RESET_RETRIES;
7293 spin_lock_irqsave(hba->host->host_lock, flags);
7296 * This is a fresh start, cache and clear saved error first,
7297 * in case new error generated during reset and restore.
7299 saved_err |= hba->saved_err;
7300 saved_uic_err |= hba->saved_uic_err;
7302 hba->saved_uic_err = 0;
7303 hba->force_reset = false;
7304 hba->ufshcd_state = UFSHCD_STATE_RESET;
7305 spin_unlock_irqrestore(hba->host->host_lock, flags);
7307 /* Reset the attached device */
7308 ufshcd_device_reset(hba);
7310 err = ufshcd_host_reset_and_restore(hba);
7312 spin_lock_irqsave(hba->host->host_lock, flags);
7315 /* Do not exit unless operational or dead */
7316 if (hba->ufshcd_state != UFSHCD_STATE_OPERATIONAL &&
7317 hba->ufshcd_state != UFSHCD_STATE_ERROR &&
7318 hba->ufshcd_state != UFSHCD_STATE_EH_SCHEDULED_NON_FATAL)
7320 } while (err && --retries);
7323 * Inform scsi mid-layer that we did reset and allow to handle
7324 * Unit Attention properly.
7326 scsi_report_bus_reset(hba->host, 0);
7328 hba->ufshcd_state = UFSHCD_STATE_ERROR;
7329 hba->saved_err |= saved_err;
7330 hba->saved_uic_err |= saved_uic_err;
7332 spin_unlock_irqrestore(hba->host->host_lock, flags);
7338 * ufshcd_eh_host_reset_handler - host reset handler registered to scsi layer
7339 * @cmd: SCSI command pointer
7341 * Returns SUCCESS/FAILED
7343 static int ufshcd_eh_host_reset_handler(struct scsi_cmnd *cmd)
7346 unsigned long flags;
7347 struct ufs_hba *hba;
7349 hba = shost_priv(cmd->device->host);
7351 spin_lock_irqsave(hba->host->host_lock, flags);
7352 hba->force_reset = true;
7353 ufshcd_schedule_eh_work(hba);
7354 dev_err(hba->dev, "%s: reset in progress - 1\n", __func__);
7355 spin_unlock_irqrestore(hba->host->host_lock, flags);
7357 flush_work(&hba->eh_work);
7359 spin_lock_irqsave(hba->host->host_lock, flags);
7360 if (hba->ufshcd_state == UFSHCD_STATE_ERROR)
7362 spin_unlock_irqrestore(hba->host->host_lock, flags);
7368 * ufshcd_get_max_icc_level - calculate the ICC level
7369 * @sup_curr_uA: max. current supported by the regulator
7370 * @start_scan: row at the desc table to start scan from
7371 * @buff: power descriptor buffer
7373 * Returns calculated max ICC level for specific regulator
7375 static u32 ufshcd_get_max_icc_level(int sup_curr_uA, u32 start_scan,
7383 for (i = start_scan; i >= 0; i--) {
7384 data = get_unaligned_be16(&buff[2 * i]);
7385 unit = (data & ATTR_ICC_LVL_UNIT_MASK) >>
7386 ATTR_ICC_LVL_UNIT_OFFSET;
7387 curr_uA = data & ATTR_ICC_LVL_VALUE_MASK;
7389 case UFSHCD_NANO_AMP:
7390 curr_uA = curr_uA / 1000;
7392 case UFSHCD_MILI_AMP:
7393 curr_uA = curr_uA * 1000;
7396 curr_uA = curr_uA * 1000 * 1000;
7398 case UFSHCD_MICRO_AMP:
7402 if (sup_curr_uA >= curr_uA)
7407 pr_err("%s: Couldn't find valid icc_level = %d", __func__, i);
7414 * ufshcd_find_max_sup_active_icc_level - calculate the max ICC level
7415 * In case regulators are not initialized we'll return 0
7416 * @hba: per-adapter instance
7417 * @desc_buf: power descriptor buffer to extract ICC levels from.
7418 * @len: length of desc_buff
7420 * Returns calculated ICC level
7422 static u32 ufshcd_find_max_sup_active_icc_level(struct ufs_hba *hba,
7423 const u8 *desc_buf, int len)
7427 if (!hba->vreg_info.vcc || !hba->vreg_info.vccq ||
7428 !hba->vreg_info.vccq2) {
7430 * Using dev_dbg to avoid messages during runtime PM to avoid
7431 * never-ending cycles of messages written back to storage by
7432 * user space causing runtime resume, causing more messages and
7436 "%s: Regulator capability was not set, actvIccLevel=%d",
7437 __func__, icc_level);
7441 if (hba->vreg_info.vcc->max_uA)
7442 icc_level = ufshcd_get_max_icc_level(
7443 hba->vreg_info.vcc->max_uA,
7444 POWER_DESC_MAX_ACTV_ICC_LVLS - 1,
7445 &desc_buf[PWR_DESC_ACTIVE_LVLS_VCC_0]);
7447 if (hba->vreg_info.vccq->max_uA)
7448 icc_level = ufshcd_get_max_icc_level(
7449 hba->vreg_info.vccq->max_uA,
7451 &desc_buf[PWR_DESC_ACTIVE_LVLS_VCCQ_0]);
7453 if (hba->vreg_info.vccq2->max_uA)
7454 icc_level = ufshcd_get_max_icc_level(
7455 hba->vreg_info.vccq2->max_uA,
7457 &desc_buf[PWR_DESC_ACTIVE_LVLS_VCCQ2_0]);
7462 static void ufshcd_set_active_icc_lvl(struct ufs_hba *hba)
7465 int buff_len = hba->desc_size[QUERY_DESC_IDN_POWER];
7469 desc_buf = kmalloc(buff_len, GFP_KERNEL);
7473 ret = ufshcd_read_desc_param(hba, QUERY_DESC_IDN_POWER, 0, 0,
7474 desc_buf, buff_len);
7477 "%s: Failed reading power descriptor.len = %d ret = %d",
7478 __func__, buff_len, ret);
7482 icc_level = ufshcd_find_max_sup_active_icc_level(hba, desc_buf,
7484 dev_dbg(hba->dev, "%s: setting icc_level 0x%x", __func__, icc_level);
7486 ret = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_WRITE_ATTR,
7487 QUERY_ATTR_IDN_ACTIVE_ICC_LVL, 0, 0, &icc_level);
7491 "%s: Failed configuring bActiveICCLevel = %d ret = %d",
7492 __func__, icc_level, ret);
7498 static inline void ufshcd_blk_pm_runtime_init(struct scsi_device *sdev)
7500 scsi_autopm_get_device(sdev);
7501 blk_pm_runtime_init(sdev->request_queue, &sdev->sdev_gendev);
7502 if (sdev->rpm_autosuspend)
7503 pm_runtime_set_autosuspend_delay(&sdev->sdev_gendev,
7504 RPM_AUTOSUSPEND_DELAY_MS);
7505 scsi_autopm_put_device(sdev);
7509 * ufshcd_scsi_add_wlus - Adds required W-LUs
7510 * @hba: per-adapter instance
7512 * UFS device specification requires the UFS devices to support 4 well known
7514 * "REPORT_LUNS" (address: 01h)
7515 * "UFS Device" (address: 50h)
7516 * "RPMB" (address: 44h)
7517 * "BOOT" (address: 30h)
7518 * UFS device's power management needs to be controlled by "POWER CONDITION"
7519 * field of SSU (START STOP UNIT) command. But this "power condition" field
7520 * will take effect only when its sent to "UFS device" well known logical unit
7521 * hence we require the scsi_device instance to represent this logical unit in
7522 * order for the UFS host driver to send the SSU command for power management.
7524 * We also require the scsi_device instance for "RPMB" (Replay Protected Memory
7525 * Block) LU so user space process can control this LU. User space may also
7526 * want to have access to BOOT LU.
7528 * This function adds scsi device instances for each of all well known LUs
7529 * (except "REPORT LUNS" LU).
7531 * Returns zero on success (all required W-LUs are added successfully),
7532 * non-zero error value on failure (if failed to add any of the required W-LU).
7534 static int ufshcd_scsi_add_wlus(struct ufs_hba *hba)
7537 struct scsi_device *sdev_boot, *sdev_rpmb;
7539 hba->ufs_device_wlun = __scsi_add_device(hba->host, 0, 0,
7540 ufshcd_upiu_wlun_to_scsi_wlun(UFS_UPIU_UFS_DEVICE_WLUN), NULL);
7541 if (IS_ERR(hba->ufs_device_wlun)) {
7542 ret = PTR_ERR(hba->ufs_device_wlun);
7543 hba->ufs_device_wlun = NULL;
7546 scsi_device_put(hba->ufs_device_wlun);
7548 sdev_rpmb = __scsi_add_device(hba->host, 0, 0,
7549 ufshcd_upiu_wlun_to_scsi_wlun(UFS_UPIU_RPMB_WLUN), NULL);
7550 if (IS_ERR(sdev_rpmb)) {
7551 ret = PTR_ERR(sdev_rpmb);
7552 goto remove_ufs_device_wlun;
7554 ufshcd_blk_pm_runtime_init(sdev_rpmb);
7555 scsi_device_put(sdev_rpmb);
7557 sdev_boot = __scsi_add_device(hba->host, 0, 0,
7558 ufshcd_upiu_wlun_to_scsi_wlun(UFS_UPIU_BOOT_WLUN), NULL);
7559 if (IS_ERR(sdev_boot)) {
7560 dev_err(hba->dev, "%s: BOOT WLUN not found\n", __func__);
7562 ufshcd_blk_pm_runtime_init(sdev_boot);
7563 scsi_device_put(sdev_boot);
7567 remove_ufs_device_wlun:
7568 scsi_remove_device(hba->ufs_device_wlun);
7573 static void ufshcd_wb_probe(struct ufs_hba *hba, const u8 *desc_buf)
7575 struct ufs_dev_info *dev_info = &hba->dev_info;
7577 u32 d_lu_wb_buf_alloc;
7578 u32 ext_ufs_feature;
7580 if (!ufshcd_is_wb_allowed(hba))
7584 * Probe WB only for UFS-2.2 and UFS-3.1 (and later) devices or
7585 * UFS devices with quirk UFS_DEVICE_QUIRK_SUPPORT_EXTENDED_FEATURES
7588 if (!(dev_info->wspecversion >= 0x310 ||
7589 dev_info->wspecversion == 0x220 ||
7590 (hba->dev_quirks & UFS_DEVICE_QUIRK_SUPPORT_EXTENDED_FEATURES)))
7593 if (hba->desc_size[QUERY_DESC_IDN_DEVICE] <
7594 DEVICE_DESC_PARAM_EXT_UFS_FEATURE_SUP + 4)
7597 ext_ufs_feature = get_unaligned_be32(desc_buf +
7598 DEVICE_DESC_PARAM_EXT_UFS_FEATURE_SUP);
7600 if (!(ext_ufs_feature & UFS_DEV_WRITE_BOOSTER_SUP))
7604 * WB may be supported but not configured while provisioning. The spec
7605 * says, in dedicated wb buffer mode, a max of 1 lun would have wb
7606 * buffer configured.
7608 dev_info->wb_buffer_type = desc_buf[DEVICE_DESC_PARAM_WB_TYPE];
7610 dev_info->b_presrv_uspc_en =
7611 desc_buf[DEVICE_DESC_PARAM_WB_PRESRV_USRSPC_EN];
7613 if (dev_info->wb_buffer_type == WB_BUF_MODE_SHARED) {
7614 if (!get_unaligned_be32(desc_buf +
7615 DEVICE_DESC_PARAM_WB_SHARED_ALLOC_UNITS))
7618 for (lun = 0; lun < UFS_UPIU_MAX_WB_LUN_ID; lun++) {
7619 d_lu_wb_buf_alloc = 0;
7620 ufshcd_read_unit_desc_param(hba,
7622 UNIT_DESC_PARAM_WB_BUF_ALLOC_UNITS,
7623 (u8 *)&d_lu_wb_buf_alloc,
7624 sizeof(d_lu_wb_buf_alloc));
7625 if (d_lu_wb_buf_alloc) {
7626 dev_info->wb_dedicated_lu = lun;
7631 if (!d_lu_wb_buf_alloc)
7635 if (!ufshcd_is_wb_buf_lifetime_available(hba))
7641 hba->caps &= ~UFSHCD_CAP_WB_EN;
7644 static void ufshcd_temp_notif_probe(struct ufs_hba *hba, const u8 *desc_buf)
7646 struct ufs_dev_info *dev_info = &hba->dev_info;
7647 u32 ext_ufs_feature;
7650 if (!(hba->caps & UFSHCD_CAP_TEMP_NOTIF) || dev_info->wspecversion < 0x300)
7653 ext_ufs_feature = get_unaligned_be32(desc_buf + DEVICE_DESC_PARAM_EXT_UFS_FEATURE_SUP);
7655 if (ext_ufs_feature & UFS_DEV_LOW_TEMP_NOTIF)
7656 mask |= MASK_EE_TOO_LOW_TEMP;
7658 if (ext_ufs_feature & UFS_DEV_HIGH_TEMP_NOTIF)
7659 mask |= MASK_EE_TOO_HIGH_TEMP;
7662 ufshcd_enable_ee(hba, mask);
7663 ufs_hwmon_probe(hba, mask);
7667 void ufshcd_fixup_dev_quirks(struct ufs_hba *hba,
7668 const struct ufs_dev_quirk *fixups)
7670 const struct ufs_dev_quirk *f;
7671 struct ufs_dev_info *dev_info = &hba->dev_info;
7676 for (f = fixups; f->quirk; f++) {
7677 if ((f->wmanufacturerid == dev_info->wmanufacturerid ||
7678 f->wmanufacturerid == UFS_ANY_VENDOR) &&
7679 ((dev_info->model &&
7680 STR_PRFX_EQUAL(f->model, dev_info->model)) ||
7681 !strcmp(f->model, UFS_ANY_MODEL)))
7682 hba->dev_quirks |= f->quirk;
7685 EXPORT_SYMBOL_GPL(ufshcd_fixup_dev_quirks);
7687 static void ufs_fixup_device_setup(struct ufs_hba *hba)
7689 /* fix by general quirk table */
7690 ufshcd_fixup_dev_quirks(hba, ufs_fixups);
7692 /* allow vendors to fix quirks */
7693 ufshcd_vops_fixup_dev_quirks(hba);
7696 static int ufs_get_device_desc(struct ufs_hba *hba)
7700 u8 b_ufs_feature_sup;
7702 struct ufs_dev_info *dev_info = &hba->dev_info;
7704 desc_buf = kmalloc(QUERY_DESC_MAX_SIZE, GFP_KERNEL);
7710 err = ufshcd_read_desc_param(hba, QUERY_DESC_IDN_DEVICE, 0, 0, desc_buf,
7711 hba->desc_size[QUERY_DESC_IDN_DEVICE]);
7713 dev_err(hba->dev, "%s: Failed reading Device Desc. err = %d\n",
7719 * getting vendor (manufacturerID) and Bank Index in big endian
7722 dev_info->wmanufacturerid = desc_buf[DEVICE_DESC_PARAM_MANF_ID] << 8 |
7723 desc_buf[DEVICE_DESC_PARAM_MANF_ID + 1];
7725 /* getting Specification Version in big endian format */
7726 dev_info->wspecversion = desc_buf[DEVICE_DESC_PARAM_SPEC_VER] << 8 |
7727 desc_buf[DEVICE_DESC_PARAM_SPEC_VER + 1];
7728 b_ufs_feature_sup = desc_buf[DEVICE_DESC_PARAM_UFS_FEAT];
7730 model_index = desc_buf[DEVICE_DESC_PARAM_PRDCT_NAME];
7732 if (dev_info->wspecversion >= UFS_DEV_HPB_SUPPORT_VERSION &&
7733 (b_ufs_feature_sup & UFS_DEV_HPB_SUPPORT)) {
7734 bool hpb_en = false;
7736 ufshpb_get_dev_info(hba, desc_buf);
7738 if (!ufshpb_is_legacy(hba))
7739 err = ufshcd_query_flag_retry(hba,
7740 UPIU_QUERY_OPCODE_READ_FLAG,
7741 QUERY_FLAG_IDN_HPB_EN, 0,
7744 if (ufshpb_is_legacy(hba) || (!err && hpb_en))
7745 dev_info->hpb_enabled = true;
7748 err = ufshcd_read_string_desc(hba, model_index,
7749 &dev_info->model, SD_ASCII_STD);
7751 dev_err(hba->dev, "%s: Failed reading Product Name. err = %d\n",
7756 hba->luns_avail = desc_buf[DEVICE_DESC_PARAM_NUM_LU] +
7757 desc_buf[DEVICE_DESC_PARAM_NUM_WLU];
7759 ufs_fixup_device_setup(hba);
7761 ufshcd_wb_probe(hba, desc_buf);
7763 ufshcd_temp_notif_probe(hba, desc_buf);
7766 * ufshcd_read_string_desc returns size of the string
7767 * reset the error value
7776 static void ufs_put_device_desc(struct ufs_hba *hba)
7778 struct ufs_dev_info *dev_info = &hba->dev_info;
7780 kfree(dev_info->model);
7781 dev_info->model = NULL;
7785 * ufshcd_tune_pa_tactivate - Tunes PA_TActivate of local UniPro
7786 * @hba: per-adapter instance
7788 * PA_TActivate parameter can be tuned manually if UniPro version is less than
7789 * 1.61. PA_TActivate needs to be greater than or equal to peerM-PHY's
7790 * RX_MIN_ACTIVATETIME_CAPABILITY attribute. This optimal value can help reduce
7791 * the hibern8 exit latency.
7793 * Returns zero on success, non-zero error value on failure.
7795 static int ufshcd_tune_pa_tactivate(struct ufs_hba *hba)
7798 u32 peer_rx_min_activatetime = 0, tuned_pa_tactivate;
7800 ret = ufshcd_dme_peer_get(hba,
7802 RX_MIN_ACTIVATETIME_CAPABILITY,
7803 UIC_ARG_MPHY_RX_GEN_SEL_INDEX(0)),
7804 &peer_rx_min_activatetime);
7808 /* make sure proper unit conversion is applied */
7809 tuned_pa_tactivate =
7810 ((peer_rx_min_activatetime * RX_MIN_ACTIVATETIME_UNIT_US)
7811 / PA_TACTIVATE_TIME_UNIT_US);
7812 ret = ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TACTIVATE),
7813 tuned_pa_tactivate);
7820 * ufshcd_tune_pa_hibern8time - Tunes PA_Hibern8Time of local UniPro
7821 * @hba: per-adapter instance
7823 * PA_Hibern8Time parameter can be tuned manually if UniPro version is less than
7824 * 1.61. PA_Hibern8Time needs to be maximum of local M-PHY's
7825 * TX_HIBERN8TIME_CAPABILITY & peer M-PHY's RX_HIBERN8TIME_CAPABILITY.
7826 * This optimal value can help reduce the hibern8 exit latency.
7828 * Returns zero on success, non-zero error value on failure.
7830 static int ufshcd_tune_pa_hibern8time(struct ufs_hba *hba)
7833 u32 local_tx_hibern8_time_cap = 0, peer_rx_hibern8_time_cap = 0;
7834 u32 max_hibern8_time, tuned_pa_hibern8time;
7836 ret = ufshcd_dme_get(hba,
7837 UIC_ARG_MIB_SEL(TX_HIBERN8TIME_CAPABILITY,
7838 UIC_ARG_MPHY_TX_GEN_SEL_INDEX(0)),
7839 &local_tx_hibern8_time_cap);
7843 ret = ufshcd_dme_peer_get(hba,
7844 UIC_ARG_MIB_SEL(RX_HIBERN8TIME_CAPABILITY,
7845 UIC_ARG_MPHY_RX_GEN_SEL_INDEX(0)),
7846 &peer_rx_hibern8_time_cap);
7850 max_hibern8_time = max(local_tx_hibern8_time_cap,
7851 peer_rx_hibern8_time_cap);
7852 /* make sure proper unit conversion is applied */
7853 tuned_pa_hibern8time = ((max_hibern8_time * HIBERN8TIME_UNIT_US)
7854 / PA_HIBERN8_TIME_UNIT_US);
7855 ret = ufshcd_dme_set(hba, UIC_ARG_MIB(PA_HIBERN8TIME),
7856 tuned_pa_hibern8time);
7862 * ufshcd_quirk_tune_host_pa_tactivate - Ensures that host PA_TACTIVATE is
7863 * less than device PA_TACTIVATE time.
7864 * @hba: per-adapter instance
7866 * Some UFS devices require host PA_TACTIVATE to be lower than device
7867 * PA_TACTIVATE, we need to enable UFS_DEVICE_QUIRK_HOST_PA_TACTIVATE quirk
7870 * Returns zero on success, non-zero error value on failure.
7872 static int ufshcd_quirk_tune_host_pa_tactivate(struct ufs_hba *hba)
7875 u32 granularity, peer_granularity;
7876 u32 pa_tactivate, peer_pa_tactivate;
7877 u32 pa_tactivate_us, peer_pa_tactivate_us;
7878 static const u8 gran_to_us_table[] = {1, 4, 8, 16, 32, 100};
7880 ret = ufshcd_dme_get(hba, UIC_ARG_MIB(PA_GRANULARITY),
7885 ret = ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_GRANULARITY),
7890 if ((granularity < PA_GRANULARITY_MIN_VAL) ||
7891 (granularity > PA_GRANULARITY_MAX_VAL)) {
7892 dev_err(hba->dev, "%s: invalid host PA_GRANULARITY %d",
7893 __func__, granularity);
7897 if ((peer_granularity < PA_GRANULARITY_MIN_VAL) ||
7898 (peer_granularity > PA_GRANULARITY_MAX_VAL)) {
7899 dev_err(hba->dev, "%s: invalid device PA_GRANULARITY %d",
7900 __func__, peer_granularity);
7904 ret = ufshcd_dme_get(hba, UIC_ARG_MIB(PA_TACTIVATE), &pa_tactivate);
7908 ret = ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_TACTIVATE),
7909 &peer_pa_tactivate);
7913 pa_tactivate_us = pa_tactivate * gran_to_us_table[granularity - 1];
7914 peer_pa_tactivate_us = peer_pa_tactivate *
7915 gran_to_us_table[peer_granularity - 1];
7917 if (pa_tactivate_us >= peer_pa_tactivate_us) {
7918 u32 new_peer_pa_tactivate;
7920 new_peer_pa_tactivate = pa_tactivate_us /
7921 gran_to_us_table[peer_granularity - 1];
7922 new_peer_pa_tactivate++;
7923 ret = ufshcd_dme_peer_set(hba, UIC_ARG_MIB(PA_TACTIVATE),
7924 new_peer_pa_tactivate);
7931 static void ufshcd_tune_unipro_params(struct ufs_hba *hba)
7933 if (ufshcd_is_unipro_pa_params_tuning_req(hba)) {
7934 ufshcd_tune_pa_tactivate(hba);
7935 ufshcd_tune_pa_hibern8time(hba);
7938 ufshcd_vops_apply_dev_quirks(hba);
7940 if (hba->dev_quirks & UFS_DEVICE_QUIRK_PA_TACTIVATE)
7941 /* set 1ms timeout for PA_TACTIVATE */
7942 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TACTIVATE), 10);
7944 if (hba->dev_quirks & UFS_DEVICE_QUIRK_HOST_PA_TACTIVATE)
7945 ufshcd_quirk_tune_host_pa_tactivate(hba);
7948 static void ufshcd_clear_dbg_ufs_stats(struct ufs_hba *hba)
7950 hba->ufs_stats.hibern8_exit_cnt = 0;
7951 hba->ufs_stats.last_hibern8_exit_tstamp = ktime_set(0, 0);
7952 hba->req_abort_count = 0;
7955 static int ufshcd_device_geo_params_init(struct ufs_hba *hba)
7961 buff_len = hba->desc_size[QUERY_DESC_IDN_GEOMETRY];
7962 desc_buf = kmalloc(buff_len, GFP_KERNEL);
7968 err = ufshcd_read_desc_param(hba, QUERY_DESC_IDN_GEOMETRY, 0, 0,
7969 desc_buf, buff_len);
7971 dev_err(hba->dev, "%s: Failed reading Geometry Desc. err = %d\n",
7976 if (desc_buf[GEOMETRY_DESC_PARAM_MAX_NUM_LUN] == 1)
7977 hba->dev_info.max_lu_supported = 32;
7978 else if (desc_buf[GEOMETRY_DESC_PARAM_MAX_NUM_LUN] == 0)
7979 hba->dev_info.max_lu_supported = 8;
7981 if (hba->desc_size[QUERY_DESC_IDN_GEOMETRY] >=
7982 GEOMETRY_DESC_PARAM_HPB_MAX_ACTIVE_REGS)
7983 ufshpb_get_geo_info(hba, desc_buf);
7990 struct ufs_ref_clk {
7991 unsigned long freq_hz;
7992 enum ufs_ref_clk_freq val;
7995 static const struct ufs_ref_clk ufs_ref_clk_freqs[] = {
7996 {19200000, REF_CLK_FREQ_19_2_MHZ},
7997 {26000000, REF_CLK_FREQ_26_MHZ},
7998 {38400000, REF_CLK_FREQ_38_4_MHZ},
7999 {52000000, REF_CLK_FREQ_52_MHZ},
8000 {0, REF_CLK_FREQ_INVAL},
8003 static enum ufs_ref_clk_freq
8004 ufs_get_bref_clk_from_hz(unsigned long freq)
8008 for (i = 0; ufs_ref_clk_freqs[i].freq_hz; i++)
8009 if (ufs_ref_clk_freqs[i].freq_hz == freq)
8010 return ufs_ref_clk_freqs[i].val;
8012 return REF_CLK_FREQ_INVAL;
8015 void ufshcd_parse_dev_ref_clk_freq(struct ufs_hba *hba, struct clk *refclk)
8019 freq = clk_get_rate(refclk);
8021 hba->dev_ref_clk_freq =
8022 ufs_get_bref_clk_from_hz(freq);
8024 if (hba->dev_ref_clk_freq == REF_CLK_FREQ_INVAL)
8026 "invalid ref_clk setting = %ld\n", freq);
8029 static int ufshcd_set_dev_ref_clk(struct ufs_hba *hba)
8033 u32 freq = hba->dev_ref_clk_freq;
8035 err = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
8036 QUERY_ATTR_IDN_REF_CLK_FREQ, 0, 0, &ref_clk);
8039 dev_err(hba->dev, "failed reading bRefClkFreq. err = %d\n",
8044 if (ref_clk == freq)
8045 goto out; /* nothing to update */
8047 err = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_WRITE_ATTR,
8048 QUERY_ATTR_IDN_REF_CLK_FREQ, 0, 0, &freq);
8051 dev_err(hba->dev, "bRefClkFreq setting to %lu Hz failed\n",
8052 ufs_ref_clk_freqs[freq].freq_hz);
8056 dev_dbg(hba->dev, "bRefClkFreq setting to %lu Hz succeeded\n",
8057 ufs_ref_clk_freqs[freq].freq_hz);
8063 static int ufshcd_device_params_init(struct ufs_hba *hba)
8068 /* Init device descriptor sizes */
8069 for (i = 0; i < QUERY_DESC_IDN_MAX; i++)
8070 hba->desc_size[i] = QUERY_DESC_MAX_SIZE;
8072 /* Init UFS geometry descriptor related parameters */
8073 ret = ufshcd_device_geo_params_init(hba);
8077 /* Check and apply UFS device quirks */
8078 ret = ufs_get_device_desc(hba);
8080 dev_err(hba->dev, "%s: Failed getting device info. err = %d\n",
8085 ufshcd_get_ref_clk_gating_wait(hba);
8087 if (!ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_READ_FLAG,
8088 QUERY_FLAG_IDN_PWR_ON_WPE, 0, &flag))
8089 hba->dev_info.f_power_on_wp_en = flag;
8091 /* Probe maximum power mode co-supported by both UFS host and device */
8092 if (ufshcd_get_max_pwr_mode(hba))
8094 "%s: Failed getting max supported power mode\n",
8101 * ufshcd_add_lus - probe and add UFS logical units
8102 * @hba: per-adapter instance
8104 static int ufshcd_add_lus(struct ufs_hba *hba)
8108 /* Add required well known logical units to scsi mid layer */
8109 ret = ufshcd_scsi_add_wlus(hba);
8113 /* Initialize devfreq after UFS device is detected */
8114 if (ufshcd_is_clkscaling_supported(hba)) {
8115 memcpy(&hba->clk_scaling.saved_pwr_info.info,
8117 sizeof(struct ufs_pa_layer_attr));
8118 hba->clk_scaling.saved_pwr_info.is_valid = true;
8119 hba->clk_scaling.is_allowed = true;
8121 ret = ufshcd_devfreq_init(hba);
8125 hba->clk_scaling.is_enabled = true;
8126 ufshcd_init_clk_scaling_sysfs(hba);
8131 scsi_scan_host(hba->host);
8132 pm_runtime_put_sync(hba->dev);
8139 * ufshcd_probe_hba - probe hba to detect device and initialize it
8140 * @hba: per-adapter instance
8141 * @init_dev_params: whether or not to call ufshcd_device_params_init().
8143 * Execute link-startup and verify device initialization
8145 static int ufshcd_probe_hba(struct ufs_hba *hba, bool init_dev_params)
8148 unsigned long flags;
8149 ktime_t start = ktime_get();
8151 hba->ufshcd_state = UFSHCD_STATE_RESET;
8153 ret = ufshcd_link_startup(hba);
8157 if (hba->quirks & UFSHCD_QUIRK_SKIP_PH_CONFIGURATION)
8160 /* Debug counters initialization */
8161 ufshcd_clear_dbg_ufs_stats(hba);
8163 /* UniPro link is active now */
8164 ufshcd_set_link_active(hba);
8166 /* Verify device initialization by sending NOP OUT UPIU */
8167 ret = ufshcd_verify_dev_init(hba);
8171 /* Initiate UFS initialization, and waiting until completion */
8172 ret = ufshcd_complete_dev_init(hba);
8177 * Initialize UFS device parameters used by driver, these
8178 * parameters are associated with UFS descriptors.
8180 if (init_dev_params) {
8181 ret = ufshcd_device_params_init(hba);
8186 ufshcd_tune_unipro_params(hba);
8188 /* UFS device is also active now */
8189 ufshcd_set_ufs_dev_active(hba);
8190 ufshcd_force_reset_auto_bkops(hba);
8192 /* Gear up to HS gear if supported */
8193 if (hba->max_pwr_info.is_valid) {
8195 * Set the right value to bRefClkFreq before attempting to
8196 * switch to HS gears.
8198 if (hba->dev_ref_clk_freq != REF_CLK_FREQ_INVAL)
8199 ufshcd_set_dev_ref_clk(hba);
8200 ret = ufshcd_config_pwr_mode(hba, &hba->max_pwr_info.info);
8202 dev_err(hba->dev, "%s: Failed setting power mode, err = %d\n",
8206 ufshcd_print_pwr_info(hba);
8210 * bActiveICCLevel is volatile for UFS device (as per latest v2.1 spec)
8211 * and for removable UFS card as well, hence always set the parameter.
8212 * Note: Error handler may issue the device reset hence resetting
8213 * bActiveICCLevel as well so it is always safe to set this here.
8215 ufshcd_set_active_icc_lvl(hba);
8217 ufshcd_wb_config(hba);
8218 if (hba->ee_usr_mask)
8219 ufshcd_write_ee_control(hba);
8220 /* Enable Auto-Hibernate if configured */
8221 ufshcd_auto_hibern8_enable(hba);
8223 ufshpb_toggle_state(hba, HPB_RESET, HPB_PRESENT);
8225 spin_lock_irqsave(hba->host->host_lock, flags);
8227 hba->ufshcd_state = UFSHCD_STATE_ERROR;
8228 else if (hba->ufshcd_state == UFSHCD_STATE_RESET)
8229 hba->ufshcd_state = UFSHCD_STATE_OPERATIONAL;
8230 spin_unlock_irqrestore(hba->host->host_lock, flags);
8232 trace_ufshcd_init(dev_name(hba->dev), ret,
8233 ktime_to_us(ktime_sub(ktime_get(), start)),
8234 hba->curr_dev_pwr_mode, hba->uic_link_state);
8239 * ufshcd_async_scan - asynchronous execution for probing hba
8240 * @data: data pointer to pass to this function
8241 * @cookie: cookie data
8243 static void ufshcd_async_scan(void *data, async_cookie_t cookie)
8245 struct ufs_hba *hba = (struct ufs_hba *)data;
8248 down(&hba->host_sem);
8249 /* Initialize hba, detect and initialize UFS device */
8250 ret = ufshcd_probe_hba(hba, true);
8255 /* Probe and add UFS logical units */
8256 ret = ufshcd_add_lus(hba);
8259 * If we failed to initialize the device or the device is not
8260 * present, turn off the power/clocks etc.
8263 pm_runtime_put_sync(hba->dev);
8264 ufshcd_hba_exit(hba);
8268 static const struct attribute_group *ufshcd_driver_groups[] = {
8269 &ufs_sysfs_unit_descriptor_group,
8270 &ufs_sysfs_lun_attributes_group,
8271 #ifdef CONFIG_SCSI_UFS_HPB
8272 &ufs_sysfs_hpb_stat_group,
8273 &ufs_sysfs_hpb_param_group,
8278 static struct ufs_hba_variant_params ufs_hba_vps = {
8279 .hba_enable_delay_us = 1000,
8280 .wb_flush_threshold = UFS_WB_BUF_REMAIN_PERCENT(40),
8281 .devfreq_profile.polling_ms = 100,
8282 .devfreq_profile.target = ufshcd_devfreq_target,
8283 .devfreq_profile.get_dev_status = ufshcd_devfreq_get_dev_status,
8284 .ondemand_data.upthreshold = 70,
8285 .ondemand_data.downdifferential = 5,
8288 static struct scsi_host_template ufshcd_driver_template = {
8289 .module = THIS_MODULE,
8291 .proc_name = UFSHCD,
8292 .map_queues = ufshcd_map_queues,
8293 .queuecommand = ufshcd_queuecommand,
8294 .mq_poll = ufshcd_poll,
8295 .slave_alloc = ufshcd_slave_alloc,
8296 .slave_configure = ufshcd_slave_configure,
8297 .slave_destroy = ufshcd_slave_destroy,
8298 .change_queue_depth = ufshcd_change_queue_depth,
8299 .eh_abort_handler = ufshcd_abort,
8300 .eh_device_reset_handler = ufshcd_eh_device_reset_handler,
8301 .eh_host_reset_handler = ufshcd_eh_host_reset_handler,
8303 .sg_tablesize = SG_ALL,
8304 .cmd_per_lun = UFSHCD_CMD_PER_LUN,
8305 .can_queue = UFSHCD_CAN_QUEUE,
8306 .max_segment_size = PRDT_DATA_BYTE_COUNT_MAX,
8307 .max_host_blocked = 1,
8308 .track_queue_depth = 1,
8309 .sdev_groups = ufshcd_driver_groups,
8310 .dma_boundary = PAGE_SIZE - 1,
8311 .rpm_autosuspend_delay = RPM_AUTOSUSPEND_DELAY_MS,
8314 static int ufshcd_config_vreg_load(struct device *dev, struct ufs_vreg *vreg,
8323 * "set_load" operation shall be required on those regulators
8324 * which specifically configured current limitation. Otherwise
8325 * zero max_uA may cause unexpected behavior when regulator is
8326 * enabled or set as high power mode.
8331 ret = regulator_set_load(vreg->reg, ua);
8333 dev_err(dev, "%s: %s set load (ua=%d) failed, err=%d\n",
8334 __func__, vreg->name, ua, ret);
8340 static inline int ufshcd_config_vreg_lpm(struct ufs_hba *hba,
8341 struct ufs_vreg *vreg)
8343 return ufshcd_config_vreg_load(hba->dev, vreg, UFS_VREG_LPM_LOAD_UA);
8346 static inline int ufshcd_config_vreg_hpm(struct ufs_hba *hba,
8347 struct ufs_vreg *vreg)
8352 return ufshcd_config_vreg_load(hba->dev, vreg, vreg->max_uA);
8355 static int ufshcd_config_vreg(struct device *dev,
8356 struct ufs_vreg *vreg, bool on)
8358 if (regulator_count_voltages(vreg->reg) <= 0)
8361 return ufshcd_config_vreg_load(dev, vreg, on ? vreg->max_uA : 0);
8364 static int ufshcd_enable_vreg(struct device *dev, struct ufs_vreg *vreg)
8368 if (!vreg || vreg->enabled)
8371 ret = ufshcd_config_vreg(dev, vreg, true);
8373 ret = regulator_enable(vreg->reg);
8376 vreg->enabled = true;
8378 dev_err(dev, "%s: %s enable failed, err=%d\n",
8379 __func__, vreg->name, ret);
8384 static int ufshcd_disable_vreg(struct device *dev, struct ufs_vreg *vreg)
8388 if (!vreg || !vreg->enabled || vreg->always_on)
8391 ret = regulator_disable(vreg->reg);
8394 /* ignore errors on applying disable config */
8395 ufshcd_config_vreg(dev, vreg, false);
8396 vreg->enabled = false;
8398 dev_err(dev, "%s: %s disable failed, err=%d\n",
8399 __func__, vreg->name, ret);
8405 static int ufshcd_setup_vreg(struct ufs_hba *hba, bool on)
8408 struct device *dev = hba->dev;
8409 struct ufs_vreg_info *info = &hba->vreg_info;
8411 ret = ufshcd_toggle_vreg(dev, info->vcc, on);
8415 ret = ufshcd_toggle_vreg(dev, info->vccq, on);
8419 ret = ufshcd_toggle_vreg(dev, info->vccq2, on);
8423 ufshcd_toggle_vreg(dev, info->vccq2, false);
8424 ufshcd_toggle_vreg(dev, info->vccq, false);
8425 ufshcd_toggle_vreg(dev, info->vcc, false);
8430 static int ufshcd_setup_hba_vreg(struct ufs_hba *hba, bool on)
8432 struct ufs_vreg_info *info = &hba->vreg_info;
8434 return ufshcd_toggle_vreg(hba->dev, info->vdd_hba, on);
8437 int ufshcd_get_vreg(struct device *dev, struct ufs_vreg *vreg)
8444 vreg->reg = devm_regulator_get(dev, vreg->name);
8445 if (IS_ERR(vreg->reg)) {
8446 ret = PTR_ERR(vreg->reg);
8447 dev_err(dev, "%s: %s get failed, err=%d\n",
8448 __func__, vreg->name, ret);
8453 EXPORT_SYMBOL_GPL(ufshcd_get_vreg);
8455 static int ufshcd_init_vreg(struct ufs_hba *hba)
8458 struct device *dev = hba->dev;
8459 struct ufs_vreg_info *info = &hba->vreg_info;
8461 ret = ufshcd_get_vreg(dev, info->vcc);
8465 ret = ufshcd_get_vreg(dev, info->vccq);
8467 ret = ufshcd_get_vreg(dev, info->vccq2);
8472 static int ufshcd_init_hba_vreg(struct ufs_hba *hba)
8474 struct ufs_vreg_info *info = &hba->vreg_info;
8476 return ufshcd_get_vreg(hba->dev, info->vdd_hba);
8479 static int ufshcd_setup_clocks(struct ufs_hba *hba, bool on)
8482 struct ufs_clk_info *clki;
8483 struct list_head *head = &hba->clk_list_head;
8484 unsigned long flags;
8485 ktime_t start = ktime_get();
8486 bool clk_state_changed = false;
8488 if (list_empty(head))
8491 ret = ufshcd_vops_setup_clocks(hba, on, PRE_CHANGE);
8495 list_for_each_entry(clki, head, list) {
8496 if (!IS_ERR_OR_NULL(clki->clk)) {
8498 * Don't disable clocks which are needed
8499 * to keep the link active.
8501 if (ufshcd_is_link_active(hba) &&
8502 clki->keep_link_active)
8505 clk_state_changed = on ^ clki->enabled;
8506 if (on && !clki->enabled) {
8507 ret = clk_prepare_enable(clki->clk);
8509 dev_err(hba->dev, "%s: %s prepare enable failed, %d\n",
8510 __func__, clki->name, ret);
8513 } else if (!on && clki->enabled) {
8514 clk_disable_unprepare(clki->clk);
8517 dev_dbg(hba->dev, "%s: clk: %s %sabled\n", __func__,
8518 clki->name, on ? "en" : "dis");
8522 ret = ufshcd_vops_setup_clocks(hba, on, POST_CHANGE);
8528 list_for_each_entry(clki, head, list) {
8529 if (!IS_ERR_OR_NULL(clki->clk) && clki->enabled)
8530 clk_disable_unprepare(clki->clk);
8532 } else if (!ret && on) {
8533 spin_lock_irqsave(hba->host->host_lock, flags);
8534 hba->clk_gating.state = CLKS_ON;
8535 trace_ufshcd_clk_gating(dev_name(hba->dev),
8536 hba->clk_gating.state);
8537 spin_unlock_irqrestore(hba->host->host_lock, flags);
8540 if (clk_state_changed)
8541 trace_ufshcd_profile_clk_gating(dev_name(hba->dev),
8542 (on ? "on" : "off"),
8543 ktime_to_us(ktime_sub(ktime_get(), start)), ret);
8547 static enum ufs_ref_clk_freq ufshcd_parse_ref_clk_property(struct ufs_hba *hba)
8550 int ret = device_property_read_u32(hba->dev, "ref-clk-freq", &freq);
8553 dev_dbg(hba->dev, "Cannnot query 'ref-clk-freq' property = %d", ret);
8554 return REF_CLK_FREQ_INVAL;
8557 return ufs_get_bref_clk_from_hz(freq);
8560 static int ufshcd_init_clocks(struct ufs_hba *hba)
8563 struct ufs_clk_info *clki;
8564 struct device *dev = hba->dev;
8565 struct list_head *head = &hba->clk_list_head;
8567 if (list_empty(head))
8570 list_for_each_entry(clki, head, list) {
8574 clki->clk = devm_clk_get(dev, clki->name);
8575 if (IS_ERR(clki->clk)) {
8576 ret = PTR_ERR(clki->clk);
8577 dev_err(dev, "%s: %s clk get failed, %d\n",
8578 __func__, clki->name, ret);
8583 * Parse device ref clk freq as per device tree "ref_clk".
8584 * Default dev_ref_clk_freq is set to REF_CLK_FREQ_INVAL
8585 * in ufshcd_alloc_host().
8587 if (!strcmp(clki->name, "ref_clk"))
8588 ufshcd_parse_dev_ref_clk_freq(hba, clki->clk);
8590 if (clki->max_freq) {
8591 ret = clk_set_rate(clki->clk, clki->max_freq);
8593 dev_err(hba->dev, "%s: %s clk set rate(%dHz) failed, %d\n",
8594 __func__, clki->name,
8595 clki->max_freq, ret);
8598 clki->curr_freq = clki->max_freq;
8600 dev_dbg(dev, "%s: clk: %s, rate: %lu\n", __func__,
8601 clki->name, clk_get_rate(clki->clk));
8607 static int ufshcd_variant_hba_init(struct ufs_hba *hba)
8614 err = ufshcd_vops_init(hba);
8616 dev_err(hba->dev, "%s: variant %s init failed err %d\n",
8617 __func__, ufshcd_get_var_name(hba), err);
8622 static void ufshcd_variant_hba_exit(struct ufs_hba *hba)
8627 ufshcd_vops_exit(hba);
8630 static int ufshcd_hba_init(struct ufs_hba *hba)
8635 * Handle host controller power separately from the UFS device power
8636 * rails as it will help controlling the UFS host controller power
8637 * collapse easily which is different than UFS device power collapse.
8638 * Also, enable the host controller power before we go ahead with rest
8639 * of the initialization here.
8641 err = ufshcd_init_hba_vreg(hba);
8645 err = ufshcd_setup_hba_vreg(hba, true);
8649 err = ufshcd_init_clocks(hba);
8651 goto out_disable_hba_vreg;
8653 if (hba->dev_ref_clk_freq == REF_CLK_FREQ_INVAL)
8654 hba->dev_ref_clk_freq = ufshcd_parse_ref_clk_property(hba);
8656 err = ufshcd_setup_clocks(hba, true);
8658 goto out_disable_hba_vreg;
8660 err = ufshcd_init_vreg(hba);
8662 goto out_disable_clks;
8664 err = ufshcd_setup_vreg(hba, true);
8666 goto out_disable_clks;
8668 err = ufshcd_variant_hba_init(hba);
8670 goto out_disable_vreg;
8672 ufs_debugfs_hba_init(hba);
8674 hba->is_powered = true;
8678 ufshcd_setup_vreg(hba, false);
8680 ufshcd_setup_clocks(hba, false);
8681 out_disable_hba_vreg:
8682 ufshcd_setup_hba_vreg(hba, false);
8687 static void ufshcd_hba_exit(struct ufs_hba *hba)
8689 if (hba->is_powered) {
8690 ufshcd_exit_clk_scaling(hba);
8691 ufshcd_exit_clk_gating(hba);
8693 destroy_workqueue(hba->eh_wq);
8694 ufs_debugfs_hba_exit(hba);
8695 ufshcd_variant_hba_exit(hba);
8696 ufshcd_setup_vreg(hba, false);
8697 ufshcd_setup_clocks(hba, false);
8698 ufshcd_setup_hba_vreg(hba, false);
8699 hba->is_powered = false;
8700 ufs_put_device_desc(hba);
8705 * ufshcd_set_dev_pwr_mode - sends START STOP UNIT command to set device
8707 * @hba: per adapter instance
8708 * @pwr_mode: device power mode to set
8710 * Returns 0 if requested power mode is set successfully
8711 * Returns < 0 if failed to set the requested power mode
8713 static int ufshcd_set_dev_pwr_mode(struct ufs_hba *hba,
8714 enum ufs_dev_pwr_mode pwr_mode)
8716 unsigned char cmd[6] = { START_STOP };
8717 struct scsi_sense_hdr sshdr;
8718 struct scsi_device *sdp;
8719 unsigned long flags;
8722 spin_lock_irqsave(hba->host->host_lock, flags);
8723 sdp = hba->ufs_device_wlun;
8725 ret = scsi_device_get(sdp);
8726 if (!ret && !scsi_device_online(sdp)) {
8728 scsi_device_put(sdp);
8733 spin_unlock_irqrestore(hba->host->host_lock, flags);
8739 * If scsi commands fail, the scsi mid-layer schedules scsi error-
8740 * handling, which would wait for host to be resumed. Since we know
8741 * we are functional while we are here, skip host resume in error
8744 hba->host->eh_noresume = 1;
8746 cmd[4] = pwr_mode << 4;
8749 * Current function would be generally called from the power management
8750 * callbacks hence set the RQF_PM flag so that it doesn't resume the
8751 * already suspended childs.
8753 for (retries = 3; retries > 0; --retries) {
8754 ret = scsi_execute(sdp, cmd, DMA_NONE, NULL, 0, NULL, &sshdr,
8755 START_STOP_TIMEOUT, 0, 0, RQF_PM, NULL);
8756 if (!scsi_status_is_check_condition(ret) ||
8757 !scsi_sense_valid(&sshdr) ||
8758 sshdr.sense_key != UNIT_ATTENTION)
8762 sdev_printk(KERN_WARNING, sdp,
8763 "START_STOP failed for power mode: %d, result %x\n",
8766 if (scsi_sense_valid(&sshdr))
8767 scsi_print_sense_hdr(sdp, NULL, &sshdr);
8773 hba->curr_dev_pwr_mode = pwr_mode;
8775 scsi_device_put(sdp);
8776 hba->host->eh_noresume = 0;
8780 static int ufshcd_link_state_transition(struct ufs_hba *hba,
8781 enum uic_link_state req_link_state,
8782 int check_for_bkops)
8786 if (req_link_state == hba->uic_link_state)
8789 if (req_link_state == UIC_LINK_HIBERN8_STATE) {
8790 ret = ufshcd_uic_hibern8_enter(hba);
8792 ufshcd_set_link_hibern8(hba);
8794 dev_err(hba->dev, "%s: hibern8 enter failed %d\n",
8800 * If autobkops is enabled, link can't be turned off because
8801 * turning off the link would also turn off the device, except in the
8802 * case of DeepSleep where the device is expected to remain powered.
8804 else if ((req_link_state == UIC_LINK_OFF_STATE) &&
8805 (!check_for_bkops || !hba->auto_bkops_enabled)) {
8807 * Let's make sure that link is in low power mode, we are doing
8808 * this currently by putting the link in Hibern8. Otherway to
8809 * put the link in low power mode is to send the DME end point
8810 * to device and then send the DME reset command to local
8811 * unipro. But putting the link in hibern8 is much faster.
8813 * Note also that putting the link in Hibern8 is a requirement
8814 * for entering DeepSleep.
8816 ret = ufshcd_uic_hibern8_enter(hba);
8818 dev_err(hba->dev, "%s: hibern8 enter failed %d\n",
8823 * Change controller state to "reset state" which
8824 * should also put the link in off/reset state
8826 ufshcd_hba_stop(hba);
8828 * TODO: Check if we need any delay to make sure that
8829 * controller is reset
8831 ufshcd_set_link_off(hba);
8838 static void ufshcd_vreg_set_lpm(struct ufs_hba *hba)
8840 bool vcc_off = false;
8843 * It seems some UFS devices may keep drawing more than sleep current
8844 * (atleast for 500us) from UFS rails (especially from VCCQ rail).
8845 * To avoid this situation, add 2ms delay before putting these UFS
8846 * rails in LPM mode.
8848 if (!ufshcd_is_link_active(hba) &&
8849 hba->dev_quirks & UFS_DEVICE_QUIRK_DELAY_BEFORE_LPM)
8850 usleep_range(2000, 2100);
8853 * If UFS device is either in UFS_Sleep turn off VCC rail to save some
8856 * If UFS device and link is in OFF state, all power supplies (VCC,
8857 * VCCQ, VCCQ2) can be turned off if power on write protect is not
8858 * required. If UFS link is inactive (Hibern8 or OFF state) and device
8859 * is in sleep state, put VCCQ & VCCQ2 rails in LPM mode.
8861 * Ignore the error returned by ufshcd_toggle_vreg() as device is anyway
8862 * in low power state which would save some power.
8864 * If Write Booster is enabled and the device needs to flush the WB
8865 * buffer OR if bkops status is urgent for WB, keep Vcc on.
8867 if (ufshcd_is_ufs_dev_poweroff(hba) && ufshcd_is_link_off(hba) &&
8868 !hba->dev_info.is_lu_power_on_wp) {
8869 ufshcd_setup_vreg(hba, false);
8871 } else if (!ufshcd_is_ufs_dev_active(hba)) {
8872 ufshcd_toggle_vreg(hba->dev, hba->vreg_info.vcc, false);
8874 if (ufshcd_is_link_hibern8(hba) || ufshcd_is_link_off(hba)) {
8875 ufshcd_config_vreg_lpm(hba, hba->vreg_info.vccq);
8876 ufshcd_config_vreg_lpm(hba, hba->vreg_info.vccq2);
8881 * Some UFS devices require delay after VCC power rail is turned-off.
8883 if (vcc_off && hba->vreg_info.vcc &&
8884 hba->dev_quirks & UFS_DEVICE_QUIRK_DELAY_AFTER_LPM)
8885 usleep_range(5000, 5100);
8889 static int ufshcd_vreg_set_hpm(struct ufs_hba *hba)
8893 if (ufshcd_is_ufs_dev_poweroff(hba) && ufshcd_is_link_off(hba) &&
8894 !hba->dev_info.is_lu_power_on_wp) {
8895 ret = ufshcd_setup_vreg(hba, true);
8896 } else if (!ufshcd_is_ufs_dev_active(hba)) {
8897 if (!ufshcd_is_link_active(hba)) {
8898 ret = ufshcd_config_vreg_hpm(hba, hba->vreg_info.vccq);
8901 ret = ufshcd_config_vreg_hpm(hba, hba->vreg_info.vccq2);
8905 ret = ufshcd_toggle_vreg(hba->dev, hba->vreg_info.vcc, true);
8910 ufshcd_config_vreg_lpm(hba, hba->vreg_info.vccq);
8912 ufshcd_toggle_vreg(hba->dev, hba->vreg_info.vcc, false);
8916 #endif /* CONFIG_PM */
8918 static void ufshcd_hba_vreg_set_lpm(struct ufs_hba *hba)
8920 if (ufshcd_is_link_off(hba) || ufshcd_can_aggressive_pc(hba))
8921 ufshcd_setup_hba_vreg(hba, false);
8924 static void ufshcd_hba_vreg_set_hpm(struct ufs_hba *hba)
8926 if (ufshcd_is_link_off(hba) || ufshcd_can_aggressive_pc(hba))
8927 ufshcd_setup_hba_vreg(hba, true);
8930 static int __ufshcd_wl_suspend(struct ufs_hba *hba, enum ufs_pm_op pm_op)
8933 int check_for_bkops;
8934 enum ufs_pm_level pm_lvl;
8935 enum ufs_dev_pwr_mode req_dev_pwr_mode;
8936 enum uic_link_state req_link_state;
8938 hba->pm_op_in_progress = true;
8939 if (pm_op != UFS_SHUTDOWN_PM) {
8940 pm_lvl = pm_op == UFS_RUNTIME_PM ?
8941 hba->rpm_lvl : hba->spm_lvl;
8942 req_dev_pwr_mode = ufs_get_pm_lvl_to_dev_pwr_mode(pm_lvl);
8943 req_link_state = ufs_get_pm_lvl_to_link_pwr_state(pm_lvl);
8945 req_dev_pwr_mode = UFS_POWERDOWN_PWR_MODE;
8946 req_link_state = UIC_LINK_OFF_STATE;
8949 ufshpb_suspend(hba);
8952 * If we can't transition into any of the low power modes
8953 * just gate the clocks.
8955 ufshcd_hold(hba, false);
8956 hba->clk_gating.is_suspended = true;
8958 if (ufshcd_is_clkscaling_supported(hba))
8959 ufshcd_clk_scaling_suspend(hba, true);
8961 if (req_dev_pwr_mode == UFS_ACTIVE_PWR_MODE &&
8962 req_link_state == UIC_LINK_ACTIVE_STATE) {
8966 if ((req_dev_pwr_mode == hba->curr_dev_pwr_mode) &&
8967 (req_link_state == hba->uic_link_state))
8968 goto enable_scaling;
8970 /* UFS device & link must be active before we enter in this function */
8971 if (!ufshcd_is_ufs_dev_active(hba) || !ufshcd_is_link_active(hba)) {
8973 goto enable_scaling;
8976 if (pm_op == UFS_RUNTIME_PM) {
8977 if (ufshcd_can_autobkops_during_suspend(hba)) {
8979 * The device is idle with no requests in the queue,
8980 * allow background operations if bkops status shows
8981 * that performance might be impacted.
8983 ret = ufshcd_urgent_bkops(hba);
8985 goto enable_scaling;
8987 /* make sure that auto bkops is disabled */
8988 ufshcd_disable_auto_bkops(hba);
8991 * If device needs to do BKOP or WB buffer flush during
8992 * Hibern8, keep device power mode as "active power mode"
8995 hba->dev_info.b_rpm_dev_flush_capable =
8996 hba->auto_bkops_enabled ||
8997 (((req_link_state == UIC_LINK_HIBERN8_STATE) ||
8998 ((req_link_state == UIC_LINK_ACTIVE_STATE) &&
8999 ufshcd_is_auto_hibern8_enabled(hba))) &&
9000 ufshcd_wb_need_flush(hba));
9003 flush_work(&hba->eeh_work);
9005 ret = ufshcd_vops_suspend(hba, pm_op, PRE_CHANGE);
9007 goto enable_scaling;
9009 if (req_dev_pwr_mode != hba->curr_dev_pwr_mode) {
9010 if (pm_op != UFS_RUNTIME_PM)
9011 /* ensure that bkops is disabled */
9012 ufshcd_disable_auto_bkops(hba);
9014 if (!hba->dev_info.b_rpm_dev_flush_capable) {
9015 ret = ufshcd_set_dev_pwr_mode(hba, req_dev_pwr_mode);
9017 goto enable_scaling;
9022 * In the case of DeepSleep, the device is expected to remain powered
9023 * with the link off, so do not check for bkops.
9025 check_for_bkops = !ufshcd_is_ufs_dev_deepsleep(hba);
9026 ret = ufshcd_link_state_transition(hba, req_link_state, check_for_bkops);
9028 goto set_dev_active;
9032 * Call vendor specific suspend callback. As these callbacks may access
9033 * vendor specific host controller register space call them before the
9034 * host clocks are ON.
9036 ret = ufshcd_vops_suspend(hba, pm_op, POST_CHANGE);
9038 goto set_link_active;
9043 * Device hardware reset is required to exit DeepSleep. Also, for
9044 * DeepSleep, the link is off so host reset and restore will be done
9047 if (ufshcd_is_ufs_dev_deepsleep(hba)) {
9048 ufshcd_device_reset(hba);
9049 WARN_ON(!ufshcd_is_link_off(hba));
9051 if (ufshcd_is_link_hibern8(hba) && !ufshcd_uic_hibern8_exit(hba))
9052 ufshcd_set_link_active(hba);
9053 else if (ufshcd_is_link_off(hba))
9054 ufshcd_host_reset_and_restore(hba);
9056 /* Can also get here needing to exit DeepSleep */
9057 if (ufshcd_is_ufs_dev_deepsleep(hba)) {
9058 ufshcd_device_reset(hba);
9059 ufshcd_host_reset_and_restore(hba);
9061 if (!ufshcd_set_dev_pwr_mode(hba, UFS_ACTIVE_PWR_MODE))
9062 ufshcd_disable_auto_bkops(hba);
9064 if (ufshcd_is_clkscaling_supported(hba))
9065 ufshcd_clk_scaling_suspend(hba, false);
9067 hba->dev_info.b_rpm_dev_flush_capable = false;
9069 if (hba->dev_info.b_rpm_dev_flush_capable) {
9070 schedule_delayed_work(&hba->rpm_dev_flush_recheck_work,
9071 msecs_to_jiffies(RPM_DEV_FLUSH_RECHECK_WORK_DELAY_MS));
9075 ufshcd_update_evt_hist(hba, UFS_EVT_WL_SUSP_ERR, (u32)ret);
9076 hba->clk_gating.is_suspended = false;
9077 ufshcd_release(hba);
9080 hba->pm_op_in_progress = false;
9085 static int __ufshcd_wl_resume(struct ufs_hba *hba, enum ufs_pm_op pm_op)
9088 enum uic_link_state old_link_state = hba->uic_link_state;
9090 hba->pm_op_in_progress = true;
9093 * Call vendor specific resume callback. As these callbacks may access
9094 * vendor specific host controller register space call them when the
9095 * host clocks are ON.
9097 ret = ufshcd_vops_resume(hba, pm_op);
9101 /* For DeepSleep, the only supported option is to have the link off */
9102 WARN_ON(ufshcd_is_ufs_dev_deepsleep(hba) && !ufshcd_is_link_off(hba));
9104 if (ufshcd_is_link_hibern8(hba)) {
9105 ret = ufshcd_uic_hibern8_exit(hba);
9107 ufshcd_set_link_active(hba);
9109 dev_err(hba->dev, "%s: hibern8 exit failed %d\n",
9111 goto vendor_suspend;
9113 } else if (ufshcd_is_link_off(hba)) {
9115 * A full initialization of the host and the device is
9116 * required since the link was put to off during suspend.
9117 * Note, in the case of DeepSleep, the device will exit
9118 * DeepSleep due to device reset.
9120 ret = ufshcd_reset_and_restore(hba);
9122 * ufshcd_reset_and_restore() should have already
9123 * set the link state as active
9125 if (ret || !ufshcd_is_link_active(hba))
9126 goto vendor_suspend;
9129 if (!ufshcd_is_ufs_dev_active(hba)) {
9130 ret = ufshcd_set_dev_pwr_mode(hba, UFS_ACTIVE_PWR_MODE);
9132 goto set_old_link_state;
9135 if (ufshcd_keep_autobkops_enabled_except_suspend(hba))
9136 ufshcd_enable_auto_bkops(hba);
9139 * If BKOPs operations are urgently needed at this moment then
9140 * keep auto-bkops enabled or else disable it.
9142 ufshcd_urgent_bkops(hba);
9144 if (hba->ee_usr_mask)
9145 ufshcd_write_ee_control(hba);
9147 if (ufshcd_is_clkscaling_supported(hba))
9148 ufshcd_clk_scaling_suspend(hba, false);
9150 if (hba->dev_info.b_rpm_dev_flush_capable) {
9151 hba->dev_info.b_rpm_dev_flush_capable = false;
9152 cancel_delayed_work(&hba->rpm_dev_flush_recheck_work);
9155 /* Enable Auto-Hibernate if configured */
9156 ufshcd_auto_hibern8_enable(hba);
9162 ufshcd_link_state_transition(hba, old_link_state, 0);
9164 ufshcd_vops_suspend(hba, pm_op, PRE_CHANGE);
9165 ufshcd_vops_suspend(hba, pm_op, POST_CHANGE);
9168 ufshcd_update_evt_hist(hba, UFS_EVT_WL_RES_ERR, (u32)ret);
9169 hba->clk_gating.is_suspended = false;
9170 ufshcd_release(hba);
9171 hba->pm_op_in_progress = false;
9175 static int ufshcd_wl_runtime_suspend(struct device *dev)
9177 struct scsi_device *sdev = to_scsi_device(dev);
9178 struct ufs_hba *hba;
9180 ktime_t start = ktime_get();
9182 hba = shost_priv(sdev->host);
9184 ret = __ufshcd_wl_suspend(hba, UFS_RUNTIME_PM);
9186 dev_err(&sdev->sdev_gendev, "%s failed: %d\n", __func__, ret);
9188 trace_ufshcd_wl_runtime_suspend(dev_name(dev), ret,
9189 ktime_to_us(ktime_sub(ktime_get(), start)),
9190 hba->curr_dev_pwr_mode, hba->uic_link_state);
9195 static int ufshcd_wl_runtime_resume(struct device *dev)
9197 struct scsi_device *sdev = to_scsi_device(dev);
9198 struct ufs_hba *hba;
9200 ktime_t start = ktime_get();
9202 hba = shost_priv(sdev->host);
9204 ret = __ufshcd_wl_resume(hba, UFS_RUNTIME_PM);
9206 dev_err(&sdev->sdev_gendev, "%s failed: %d\n", __func__, ret);
9208 trace_ufshcd_wl_runtime_resume(dev_name(dev), ret,
9209 ktime_to_us(ktime_sub(ktime_get(), start)),
9210 hba->curr_dev_pwr_mode, hba->uic_link_state);
9216 #ifdef CONFIG_PM_SLEEP
9217 static int ufshcd_wl_suspend(struct device *dev)
9219 struct scsi_device *sdev = to_scsi_device(dev);
9220 struct ufs_hba *hba;
9222 ktime_t start = ktime_get();
9224 hba = shost_priv(sdev->host);
9225 down(&hba->host_sem);
9227 if (pm_runtime_suspended(dev))
9230 ret = __ufshcd_wl_suspend(hba, UFS_SYSTEM_PM);
9232 dev_err(&sdev->sdev_gendev, "%s failed: %d\n", __func__, ret);
9238 hba->is_sys_suspended = true;
9239 trace_ufshcd_wl_suspend(dev_name(dev), ret,
9240 ktime_to_us(ktime_sub(ktime_get(), start)),
9241 hba->curr_dev_pwr_mode, hba->uic_link_state);
9246 static int ufshcd_wl_resume(struct device *dev)
9248 struct scsi_device *sdev = to_scsi_device(dev);
9249 struct ufs_hba *hba;
9251 ktime_t start = ktime_get();
9253 hba = shost_priv(sdev->host);
9255 if (pm_runtime_suspended(dev))
9258 ret = __ufshcd_wl_resume(hba, UFS_SYSTEM_PM);
9260 dev_err(&sdev->sdev_gendev, "%s failed: %d\n", __func__, ret);
9262 trace_ufshcd_wl_resume(dev_name(dev), ret,
9263 ktime_to_us(ktime_sub(ktime_get(), start)),
9264 hba->curr_dev_pwr_mode, hba->uic_link_state);
9266 hba->is_sys_suspended = false;
9272 static void ufshcd_wl_shutdown(struct device *dev)
9274 struct scsi_device *sdev = to_scsi_device(dev);
9275 struct ufs_hba *hba;
9277 hba = shost_priv(sdev->host);
9279 down(&hba->host_sem);
9280 hba->shutting_down = true;
9283 /* Turn on everything while shutting down */
9284 ufshcd_rpm_get_sync(hba);
9285 scsi_device_quiesce(sdev);
9286 shost_for_each_device(sdev, hba->host) {
9287 if (sdev == hba->ufs_device_wlun)
9289 scsi_device_quiesce(sdev);
9291 __ufshcd_wl_suspend(hba, UFS_SHUTDOWN_PM);
9295 * ufshcd_suspend - helper function for suspend operations
9296 * @hba: per adapter instance
9298 * This function will put disable irqs, turn off clocks
9299 * and set vreg and hba-vreg in lpm mode.
9301 static int ufshcd_suspend(struct ufs_hba *hba)
9305 if (!hba->is_powered)
9308 * Disable the host irq as host controller as there won't be any
9309 * host controller transaction expected till resume.
9311 ufshcd_disable_irq(hba);
9312 ret = ufshcd_setup_clocks(hba, false);
9314 ufshcd_enable_irq(hba);
9317 if (ufshcd_is_clkgating_allowed(hba)) {
9318 hba->clk_gating.state = CLKS_OFF;
9319 trace_ufshcd_clk_gating(dev_name(hba->dev),
9320 hba->clk_gating.state);
9323 ufshcd_vreg_set_lpm(hba);
9324 /* Put the host controller in low power mode if possible */
9325 ufshcd_hba_vreg_set_lpm(hba);
9331 * ufshcd_resume - helper function for resume operations
9332 * @hba: per adapter instance
9334 * This function basically turns on the regulators, clocks and
9337 * Returns 0 for success and non-zero for failure
9339 static int ufshcd_resume(struct ufs_hba *hba)
9343 if (!hba->is_powered)
9346 ufshcd_hba_vreg_set_hpm(hba);
9347 ret = ufshcd_vreg_set_hpm(hba);
9351 /* Make sure clocks are enabled before accessing controller */
9352 ret = ufshcd_setup_clocks(hba, true);
9356 /* enable the host irq as host controller would be active soon */
9357 ufshcd_enable_irq(hba);
9361 ufshcd_vreg_set_lpm(hba);
9364 ufshcd_update_evt_hist(hba, UFS_EVT_RESUME_ERR, (u32)ret);
9367 #endif /* CONFIG_PM */
9369 #ifdef CONFIG_PM_SLEEP
9371 * ufshcd_system_suspend - system suspend callback
9372 * @dev: Device associated with the UFS controller.
9374 * Executed before putting the system into a sleep state in which the contents
9375 * of main memory are preserved.
9377 * Returns 0 for success and non-zero for failure
9379 int ufshcd_system_suspend(struct device *dev)
9381 struct ufs_hba *hba = dev_get_drvdata(dev);
9383 ktime_t start = ktime_get();
9385 if (pm_runtime_suspended(hba->dev))
9388 ret = ufshcd_suspend(hba);
9390 trace_ufshcd_system_suspend(dev_name(hba->dev), ret,
9391 ktime_to_us(ktime_sub(ktime_get(), start)),
9392 hba->curr_dev_pwr_mode, hba->uic_link_state);
9395 EXPORT_SYMBOL(ufshcd_system_suspend);
9398 * ufshcd_system_resume - system resume callback
9399 * @dev: Device associated with the UFS controller.
9401 * Executed after waking the system up from a sleep state in which the contents
9402 * of main memory were preserved.
9404 * Returns 0 for success and non-zero for failure
9406 int ufshcd_system_resume(struct device *dev)
9408 struct ufs_hba *hba = dev_get_drvdata(dev);
9409 ktime_t start = ktime_get();
9412 if (pm_runtime_suspended(hba->dev))
9415 ret = ufshcd_resume(hba);
9418 trace_ufshcd_system_resume(dev_name(hba->dev), ret,
9419 ktime_to_us(ktime_sub(ktime_get(), start)),
9420 hba->curr_dev_pwr_mode, hba->uic_link_state);
9424 EXPORT_SYMBOL(ufshcd_system_resume);
9425 #endif /* CONFIG_PM_SLEEP */
9429 * ufshcd_runtime_suspend - runtime suspend callback
9430 * @dev: Device associated with the UFS controller.
9432 * Check the description of ufshcd_suspend() function for more details.
9434 * Returns 0 for success and non-zero for failure
9436 int ufshcd_runtime_suspend(struct device *dev)
9438 struct ufs_hba *hba = dev_get_drvdata(dev);
9440 ktime_t start = ktime_get();
9442 ret = ufshcd_suspend(hba);
9444 trace_ufshcd_runtime_suspend(dev_name(hba->dev), ret,
9445 ktime_to_us(ktime_sub(ktime_get(), start)),
9446 hba->curr_dev_pwr_mode, hba->uic_link_state);
9449 EXPORT_SYMBOL(ufshcd_runtime_suspend);
9452 * ufshcd_runtime_resume - runtime resume routine
9453 * @dev: Device associated with the UFS controller.
9455 * This function basically brings controller
9456 * to active state. Following operations are done in this function:
9458 * 1. Turn on all the controller related clocks
9459 * 2. Turn ON VCC rail
9461 int ufshcd_runtime_resume(struct device *dev)
9463 struct ufs_hba *hba = dev_get_drvdata(dev);
9465 ktime_t start = ktime_get();
9467 ret = ufshcd_resume(hba);
9469 trace_ufshcd_runtime_resume(dev_name(hba->dev), ret,
9470 ktime_to_us(ktime_sub(ktime_get(), start)),
9471 hba->curr_dev_pwr_mode, hba->uic_link_state);
9474 EXPORT_SYMBOL(ufshcd_runtime_resume);
9475 #endif /* CONFIG_PM */
9478 * ufshcd_shutdown - shutdown routine
9479 * @hba: per adapter instance
9481 * This function would turn off both UFS device and UFS hba
9482 * regulators. It would also disable clocks.
9484 * Returns 0 always to allow force shutdown even in case of errors.
9486 int ufshcd_shutdown(struct ufs_hba *hba)
9488 if (ufshcd_is_ufs_dev_poweroff(hba) && ufshcd_is_link_off(hba))
9491 pm_runtime_get_sync(hba->dev);
9493 ufshcd_suspend(hba);
9495 hba->is_powered = false;
9496 /* allow force shutdown even in case of errors */
9499 EXPORT_SYMBOL(ufshcd_shutdown);
9502 * ufshcd_remove - de-allocate SCSI host and host memory space
9503 * data structure memory
9504 * @hba: per adapter instance
9506 void ufshcd_remove(struct ufs_hba *hba)
9508 if (hba->ufs_device_wlun)
9509 ufshcd_rpm_get_sync(hba);
9510 ufs_hwmon_remove(hba);
9511 ufs_bsg_remove(hba);
9513 ufs_sysfs_remove_nodes(hba->dev);
9514 blk_cleanup_queue(hba->tmf_queue);
9515 blk_mq_free_tag_set(&hba->tmf_tag_set);
9516 scsi_remove_host(hba->host);
9517 /* disable interrupts */
9518 ufshcd_disable_intr(hba, hba->intr_mask);
9519 ufshcd_hba_stop(hba);
9520 ufshcd_hba_exit(hba);
9522 EXPORT_SYMBOL_GPL(ufshcd_remove);
9525 * ufshcd_dealloc_host - deallocate Host Bus Adapter (HBA)
9526 * @hba: pointer to Host Bus Adapter (HBA)
9528 void ufshcd_dealloc_host(struct ufs_hba *hba)
9530 scsi_host_put(hba->host);
9532 EXPORT_SYMBOL_GPL(ufshcd_dealloc_host);
9535 * ufshcd_set_dma_mask - Set dma mask based on the controller
9536 * addressing capability
9537 * @hba: per adapter instance
9539 * Returns 0 for success, non-zero for failure
9541 static int ufshcd_set_dma_mask(struct ufs_hba *hba)
9543 if (hba->capabilities & MASK_64_ADDRESSING_SUPPORT) {
9544 if (!dma_set_mask_and_coherent(hba->dev, DMA_BIT_MASK(64)))
9547 return dma_set_mask_and_coherent(hba->dev, DMA_BIT_MASK(32));
9551 * ufshcd_alloc_host - allocate Host Bus Adapter (HBA)
9552 * @dev: pointer to device handle
9553 * @hba_handle: driver private handle
9554 * Returns 0 on success, non-zero value on failure
9556 int ufshcd_alloc_host(struct device *dev, struct ufs_hba **hba_handle)
9558 struct Scsi_Host *host;
9559 struct ufs_hba *hba;
9564 "Invalid memory reference for dev is NULL\n");
9569 host = scsi_host_alloc(&ufshcd_driver_template,
9570 sizeof(struct ufs_hba));
9572 dev_err(dev, "scsi_host_alloc failed\n");
9576 host->nr_maps = HCTX_TYPE_POLL + 1;
9577 hba = shost_priv(host);
9580 hba->dev_ref_clk_freq = REF_CLK_FREQ_INVAL;
9581 hba->nop_out_timeout = NOP_OUT_TIMEOUT;
9582 INIT_LIST_HEAD(&hba->clk_list_head);
9583 spin_lock_init(&hba->outstanding_lock);
9590 EXPORT_SYMBOL(ufshcd_alloc_host);
9592 /* This function exists because blk_mq_alloc_tag_set() requires this. */
9593 static blk_status_t ufshcd_queue_tmf(struct blk_mq_hw_ctx *hctx,
9594 const struct blk_mq_queue_data *qd)
9597 return BLK_STS_NOTSUPP;
9600 static const struct blk_mq_ops ufshcd_tmf_ops = {
9601 .queue_rq = ufshcd_queue_tmf,
9605 * ufshcd_init - Driver initialization routine
9606 * @hba: per-adapter instance
9607 * @mmio_base: base register address
9608 * @irq: Interrupt line of device
9609 * Returns 0 on success, non-zero value on failure
9611 int ufshcd_init(struct ufs_hba *hba, void __iomem *mmio_base, unsigned int irq)
9614 struct Scsi_Host *host = hba->host;
9615 struct device *dev = hba->dev;
9616 char eh_wq_name[sizeof("ufs_eh_wq_00")];
9619 * dev_set_drvdata() must be called before any callbacks are registered
9620 * that use dev_get_drvdata() (frequency scaling, clock scaling, hwmon,
9623 dev_set_drvdata(dev, hba);
9627 "Invalid memory reference for mmio_base is NULL\n");
9632 hba->mmio_base = mmio_base;
9634 hba->vps = &ufs_hba_vps;
9636 err = ufshcd_hba_init(hba);
9640 /* Read capabilities registers */
9641 err = ufshcd_hba_capabilities(hba);
9645 /* Get UFS version supported by the controller */
9646 hba->ufs_version = ufshcd_get_ufs_version(hba);
9648 /* Get Interrupt bit mask per version */
9649 hba->intr_mask = ufshcd_get_intr_mask(hba);
9651 err = ufshcd_set_dma_mask(hba);
9653 dev_err(hba->dev, "set dma mask failed\n");
9657 /* Allocate memory for host memory space */
9658 err = ufshcd_memory_alloc(hba);
9660 dev_err(hba->dev, "Memory allocation failed\n");
9665 ufshcd_host_memory_configure(hba);
9667 host->can_queue = hba->nutrs - UFSHCD_NUM_RESERVED;
9668 host->cmd_per_lun = hba->nutrs - UFSHCD_NUM_RESERVED;
9669 host->max_id = UFSHCD_MAX_ID;
9670 host->max_lun = UFS_MAX_LUNS;
9671 host->max_channel = UFSHCD_MAX_CHANNEL;
9672 host->unique_id = host->host_no;
9673 host->max_cmd_len = UFS_CDB_SIZE;
9675 hba->max_pwr_info.is_valid = false;
9677 /* Initialize work queues */
9678 snprintf(eh_wq_name, sizeof(eh_wq_name), "ufs_eh_wq_%d",
9679 hba->host->host_no);
9680 hba->eh_wq = create_singlethread_workqueue(eh_wq_name);
9682 dev_err(hba->dev, "%s: failed to create eh workqueue\n",
9687 INIT_WORK(&hba->eh_work, ufshcd_err_handler);
9688 INIT_WORK(&hba->eeh_work, ufshcd_exception_event_handler);
9690 sema_init(&hba->host_sem, 1);
9692 /* Initialize UIC command mutex */
9693 mutex_init(&hba->uic_cmd_mutex);
9695 /* Initialize mutex for device management commands */
9696 mutex_init(&hba->dev_cmd.lock);
9698 /* Initialize mutex for exception event control */
9699 mutex_init(&hba->ee_ctrl_mutex);
9701 init_rwsem(&hba->clk_scaling_lock);
9703 ufshcd_init_clk_gating(hba);
9705 ufshcd_init_clk_scaling(hba);
9708 * In order to avoid any spurious interrupt immediately after
9709 * registering UFS controller interrupt handler, clear any pending UFS
9710 * interrupt status and disable all the UFS interrupts.
9712 ufshcd_writel(hba, ufshcd_readl(hba, REG_INTERRUPT_STATUS),
9713 REG_INTERRUPT_STATUS);
9714 ufshcd_writel(hba, 0, REG_INTERRUPT_ENABLE);
9716 * Make sure that UFS interrupts are disabled and any pending interrupt
9717 * status is cleared before registering UFS interrupt handler.
9721 /* IRQ registration */
9722 err = devm_request_irq(dev, irq, ufshcd_intr, IRQF_SHARED, UFSHCD, hba);
9724 dev_err(hba->dev, "request irq failed\n");
9727 hba->is_irq_enabled = true;
9730 err = scsi_add_host(host, hba->dev);
9732 dev_err(hba->dev, "scsi_add_host failed\n");
9736 hba->tmf_tag_set = (struct blk_mq_tag_set) {
9738 .queue_depth = hba->nutmrs,
9739 .ops = &ufshcd_tmf_ops,
9740 .flags = BLK_MQ_F_NO_SCHED,
9742 err = blk_mq_alloc_tag_set(&hba->tmf_tag_set);
9744 goto out_remove_scsi_host;
9745 hba->tmf_queue = blk_mq_init_queue(&hba->tmf_tag_set);
9746 if (IS_ERR(hba->tmf_queue)) {
9747 err = PTR_ERR(hba->tmf_queue);
9748 goto free_tmf_tag_set;
9750 hba->tmf_rqs = devm_kcalloc(hba->dev, hba->nutmrs,
9751 sizeof(*hba->tmf_rqs), GFP_KERNEL);
9752 if (!hba->tmf_rqs) {
9754 goto free_tmf_queue;
9757 /* Reset the attached device */
9758 ufshcd_device_reset(hba);
9760 ufshcd_init_crypto(hba);
9762 /* Host controller enable */
9763 err = ufshcd_hba_enable(hba);
9765 dev_err(hba->dev, "Host controller enable failed\n");
9766 ufshcd_print_evt_hist(hba);
9767 ufshcd_print_host_state(hba);
9768 goto free_tmf_queue;
9772 * Set the default power management level for runtime and system PM.
9773 * Default power saving mode is to keep UFS link in Hibern8 state
9774 * and UFS device in sleep state.
9776 hba->rpm_lvl = ufs_get_desired_pm_lvl_for_dev_link_state(
9778 UIC_LINK_HIBERN8_STATE);
9779 hba->spm_lvl = ufs_get_desired_pm_lvl_for_dev_link_state(
9781 UIC_LINK_HIBERN8_STATE);
9783 INIT_DELAYED_WORK(&hba->rpm_dev_flush_recheck_work,
9784 ufshcd_rpm_dev_flush_recheck_work);
9786 /* Set the default auto-hiberate idle timer value to 150 ms */
9787 if (ufshcd_is_auto_hibern8_supported(hba) && !hba->ahit) {
9788 hba->ahit = FIELD_PREP(UFSHCI_AHIBERN8_TIMER_MASK, 150) |
9789 FIELD_PREP(UFSHCI_AHIBERN8_SCALE_MASK, 3);
9792 /* Hold auto suspend until async scan completes */
9793 pm_runtime_get_sync(dev);
9794 atomic_set(&hba->scsi_block_reqs_cnt, 0);
9796 * We are assuming that device wasn't put in sleep/power-down
9797 * state exclusively during the boot stage before kernel.
9798 * This assumption helps avoid doing link startup twice during
9799 * ufshcd_probe_hba().
9801 ufshcd_set_ufs_dev_active(hba);
9803 async_schedule(ufshcd_async_scan, hba);
9804 ufs_sysfs_add_nodes(hba->dev);
9806 device_enable_async_suspend(dev);
9810 blk_cleanup_queue(hba->tmf_queue);
9812 blk_mq_free_tag_set(&hba->tmf_tag_set);
9813 out_remove_scsi_host:
9814 scsi_remove_host(hba->host);
9816 hba->is_irq_enabled = false;
9817 ufshcd_hba_exit(hba);
9821 EXPORT_SYMBOL_GPL(ufshcd_init);
9823 void ufshcd_resume_complete(struct device *dev)
9825 struct ufs_hba *hba = dev_get_drvdata(dev);
9827 if (hba->complete_put) {
9828 ufshcd_rpm_put(hba);
9829 hba->complete_put = false;
9832 EXPORT_SYMBOL_GPL(ufshcd_resume_complete);
9834 static bool ufshcd_rpm_ok_for_spm(struct ufs_hba *hba)
9836 struct device *dev = &hba->ufs_device_wlun->sdev_gendev;
9837 enum ufs_dev_pwr_mode dev_pwr_mode;
9838 enum uic_link_state link_state;
9839 unsigned long flags;
9842 spin_lock_irqsave(&dev->power.lock, flags);
9843 dev_pwr_mode = ufs_get_pm_lvl_to_dev_pwr_mode(hba->spm_lvl);
9844 link_state = ufs_get_pm_lvl_to_link_pwr_state(hba->spm_lvl);
9845 res = pm_runtime_suspended(dev) &&
9846 hba->curr_dev_pwr_mode == dev_pwr_mode &&
9847 hba->uic_link_state == link_state &&
9848 !hba->dev_info.b_rpm_dev_flush_capable;
9849 spin_unlock_irqrestore(&dev->power.lock, flags);
9854 int __ufshcd_suspend_prepare(struct device *dev, bool rpm_ok_for_spm)
9856 struct ufs_hba *hba = dev_get_drvdata(dev);
9860 * SCSI assumes that runtime-pm and system-pm for scsi drivers
9861 * are same. And it doesn't wake up the device for system-suspend
9862 * if it's runtime suspended. But ufs doesn't follow that.
9863 * Refer ufshcd_resume_complete()
9865 if (hba->ufs_device_wlun) {
9866 /* Prevent runtime suspend */
9867 ufshcd_rpm_get_noresume(hba);
9869 * Check if already runtime suspended in same state as system
9872 if (!rpm_ok_for_spm || !ufshcd_rpm_ok_for_spm(hba)) {
9873 /* RPM state is not ok for SPM, so runtime resume */
9874 ret = ufshcd_rpm_resume(hba);
9875 if (ret < 0 && ret != -EACCES) {
9876 ufshcd_rpm_put(hba);
9880 hba->complete_put = true;
9884 EXPORT_SYMBOL_GPL(__ufshcd_suspend_prepare);
9886 int ufshcd_suspend_prepare(struct device *dev)
9888 return __ufshcd_suspend_prepare(dev, true);
9890 EXPORT_SYMBOL_GPL(ufshcd_suspend_prepare);
9892 #ifdef CONFIG_PM_SLEEP
9893 static int ufshcd_wl_poweroff(struct device *dev)
9895 struct scsi_device *sdev = to_scsi_device(dev);
9896 struct ufs_hba *hba = shost_priv(sdev->host);
9898 __ufshcd_wl_suspend(hba, UFS_SHUTDOWN_PM);
9903 static int ufshcd_wl_probe(struct device *dev)
9905 struct scsi_device *sdev = to_scsi_device(dev);
9907 if (!is_device_wlun(sdev))
9910 blk_pm_runtime_init(sdev->request_queue, dev);
9911 pm_runtime_set_autosuspend_delay(dev, 0);
9912 pm_runtime_allow(dev);
9917 static int ufshcd_wl_remove(struct device *dev)
9919 pm_runtime_forbid(dev);
9923 static const struct dev_pm_ops ufshcd_wl_pm_ops = {
9924 #ifdef CONFIG_PM_SLEEP
9925 .suspend = ufshcd_wl_suspend,
9926 .resume = ufshcd_wl_resume,
9927 .freeze = ufshcd_wl_suspend,
9928 .thaw = ufshcd_wl_resume,
9929 .poweroff = ufshcd_wl_poweroff,
9930 .restore = ufshcd_wl_resume,
9932 SET_RUNTIME_PM_OPS(ufshcd_wl_runtime_suspend, ufshcd_wl_runtime_resume, NULL)
9936 * ufs_dev_wlun_template - describes ufs device wlun
9937 * ufs-device wlun - used to send pm commands
9938 * All luns are consumers of ufs-device wlun.
9940 * Currently, no sd driver is present for wluns.
9941 * Hence the no specific pm operations are performed.
9942 * With ufs design, SSU should be sent to ufs-device wlun.
9943 * Hence register a scsi driver for ufs wluns only.
9945 static struct scsi_driver ufs_dev_wlun_template = {
9947 .name = "ufs_device_wlun",
9948 .owner = THIS_MODULE,
9949 .probe = ufshcd_wl_probe,
9950 .remove = ufshcd_wl_remove,
9951 .pm = &ufshcd_wl_pm_ops,
9952 .shutdown = ufshcd_wl_shutdown,
9956 static int __init ufshcd_core_init(void)
9960 /* Verify that there are no gaps in struct utp_transfer_cmd_desc. */
9961 static_assert(sizeof(struct utp_transfer_cmd_desc) ==
9962 2 * ALIGNED_UPIU_SIZE +
9963 SG_ALL * sizeof(struct ufshcd_sg_entry));
9967 ret = scsi_register_driver(&ufs_dev_wlun_template.gendrv);
9973 static void __exit ufshcd_core_exit(void)
9976 scsi_unregister_driver(&ufs_dev_wlun_template.gendrv);
9979 module_init(ufshcd_core_init);
9980 module_exit(ufshcd_core_exit);
9982 MODULE_AUTHOR("Santosh Yaragnavi <santosh.sy@samsung.com>");
9983 MODULE_AUTHOR("Vinayak Holikatti <h.vinayak@samsung.com>");
9984 MODULE_DESCRIPTION("Generic UFS host controller driver Core");
9985 MODULE_LICENSE("GPL");