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 <linux/sched/clock.h>
25 #include <scsi/scsi_cmnd.h>
26 #include <scsi/scsi_dbg.h>
27 #include <scsi/scsi_driver.h>
28 #include <scsi/scsi_eh.h>
29 #include "ufshcd-priv.h"
30 #include <ufs/ufs_quirks.h>
31 #include <ufs/unipro.h>
32 #include "ufs-sysfs.h"
33 #include "ufs-debugfs.h"
34 #include "ufs-fault-injection.h"
36 #include "ufshcd-crypto.h"
38 #include <asm/unaligned.h>
40 #define CREATE_TRACE_POINTS
41 #include <trace/events/ufs.h>
43 #define UFSHCD_ENABLE_INTRS (UTP_TRANSFER_REQ_COMPL |\
46 /* UIC command timeout, unit: ms */
47 #define UIC_CMD_TIMEOUT 500
49 /* NOP OUT retries waiting for NOP IN response */
50 #define NOP_OUT_RETRIES 10
51 /* Timeout after 50 msecs if NOP OUT hangs without response */
52 #define NOP_OUT_TIMEOUT 50 /* msecs */
54 /* Query request retries */
55 #define QUERY_REQ_RETRIES 3
56 /* Query request timeout */
57 #define QUERY_REQ_TIMEOUT 1500 /* 1.5 seconds */
59 /* Advanced RPMB request timeout */
60 #define ADVANCED_RPMB_REQ_TIMEOUT 3000 /* 3 seconds */
62 /* Task management command timeout */
63 #define TM_CMD_TIMEOUT 100 /* msecs */
65 /* maximum number of retries for a general UIC command */
66 #define UFS_UIC_COMMAND_RETRIES 3
68 /* maximum number of link-startup retries */
69 #define DME_LINKSTARTUP_RETRIES 3
71 /* maximum number of reset retries before giving up */
72 #define MAX_HOST_RESET_RETRIES 5
74 /* Maximum number of error handler retries before giving up */
75 #define MAX_ERR_HANDLER_RETRIES 5
77 /* Expose the flag value from utp_upiu_query.value */
78 #define MASK_QUERY_UPIU_FLAG_LOC 0xFF
80 /* Interrupt aggregation default timeout, unit: 40us */
81 #define INT_AGGR_DEF_TO 0x02
83 /* default delay of autosuspend: 2000 ms */
84 #define RPM_AUTOSUSPEND_DELAY_MS 2000
86 /* Default delay of RPM device flush delayed work */
87 #define RPM_DEV_FLUSH_RECHECK_WORK_DELAY_MS 5000
89 /* Default value of wait time before gating device ref clock */
90 #define UFSHCD_REF_CLK_GATING_WAIT_US 0xFF /* microsecs */
92 /* Polling time to wait for fDeviceInit */
93 #define FDEVICEINIT_COMPL_TIMEOUT 1500 /* millisecs */
95 #define ufshcd_toggle_vreg(_dev, _vreg, _on) \
99 _ret = ufshcd_enable_vreg(_dev, _vreg); \
101 _ret = ufshcd_disable_vreg(_dev, _vreg); \
105 #define ufshcd_hex_dump(prefix_str, buf, len) do { \
106 size_t __len = (len); \
107 print_hex_dump(KERN_ERR, prefix_str, \
108 __len > 4 ? DUMP_PREFIX_OFFSET : DUMP_PREFIX_NONE,\
109 16, 4, buf, __len, false); \
112 int ufshcd_dump_regs(struct ufs_hba *hba, size_t offset, size_t len,
118 if (offset % 4 != 0 || len % 4 != 0) /* keep readl happy */
121 regs = kzalloc(len, GFP_ATOMIC);
125 for (pos = 0; pos < len; pos += 4) {
127 pos >= REG_UIC_ERROR_CODE_PHY_ADAPTER_LAYER &&
128 pos <= REG_UIC_ERROR_CODE_DME)
130 regs[pos / 4] = ufshcd_readl(hba, offset + pos);
133 ufshcd_hex_dump(prefix, regs, len);
138 EXPORT_SYMBOL_GPL(ufshcd_dump_regs);
141 UFSHCD_MAX_CHANNEL = 0,
143 UFSHCD_NUM_RESERVED = 1,
144 UFSHCD_CMD_PER_LUN = 32 - UFSHCD_NUM_RESERVED,
145 UFSHCD_CAN_QUEUE = 32 - UFSHCD_NUM_RESERVED,
148 static const char *const ufshcd_state_name[] = {
149 [UFSHCD_STATE_RESET] = "reset",
150 [UFSHCD_STATE_OPERATIONAL] = "operational",
151 [UFSHCD_STATE_ERROR] = "error",
152 [UFSHCD_STATE_EH_SCHEDULED_FATAL] = "eh_fatal",
153 [UFSHCD_STATE_EH_SCHEDULED_NON_FATAL] = "eh_non_fatal",
156 /* UFSHCD error handling flags */
158 UFSHCD_EH_IN_PROGRESS = (1 << 0),
161 /* UFSHCD UIC layer error flags */
163 UFSHCD_UIC_DL_PA_INIT_ERROR = (1 << 0), /* Data link layer error */
164 UFSHCD_UIC_DL_NAC_RECEIVED_ERROR = (1 << 1), /* Data link layer error */
165 UFSHCD_UIC_DL_TCx_REPLAY_ERROR = (1 << 2), /* Data link layer error */
166 UFSHCD_UIC_NL_ERROR = (1 << 3), /* Network layer error */
167 UFSHCD_UIC_TL_ERROR = (1 << 4), /* Transport Layer error */
168 UFSHCD_UIC_DME_ERROR = (1 << 5), /* DME error */
169 UFSHCD_UIC_PA_GENERIC_ERROR = (1 << 6), /* Generic PA error */
172 #define ufshcd_set_eh_in_progress(h) \
173 ((h)->eh_flags |= UFSHCD_EH_IN_PROGRESS)
174 #define ufshcd_eh_in_progress(h) \
175 ((h)->eh_flags & UFSHCD_EH_IN_PROGRESS)
176 #define ufshcd_clear_eh_in_progress(h) \
177 ((h)->eh_flags &= ~UFSHCD_EH_IN_PROGRESS)
179 const struct ufs_pm_lvl_states ufs_pm_lvl_states[] = {
180 [UFS_PM_LVL_0] = {UFS_ACTIVE_PWR_MODE, UIC_LINK_ACTIVE_STATE},
181 [UFS_PM_LVL_1] = {UFS_ACTIVE_PWR_MODE, UIC_LINK_HIBERN8_STATE},
182 [UFS_PM_LVL_2] = {UFS_SLEEP_PWR_MODE, UIC_LINK_ACTIVE_STATE},
183 [UFS_PM_LVL_3] = {UFS_SLEEP_PWR_MODE, UIC_LINK_HIBERN8_STATE},
184 [UFS_PM_LVL_4] = {UFS_POWERDOWN_PWR_MODE, UIC_LINK_HIBERN8_STATE},
185 [UFS_PM_LVL_5] = {UFS_POWERDOWN_PWR_MODE, UIC_LINK_OFF_STATE},
187 * For DeepSleep, the link is first put in hibern8 and then off.
188 * Leaving the link in hibern8 is not supported.
190 [UFS_PM_LVL_6] = {UFS_DEEPSLEEP_PWR_MODE, UIC_LINK_OFF_STATE},
193 static inline enum ufs_dev_pwr_mode
194 ufs_get_pm_lvl_to_dev_pwr_mode(enum ufs_pm_level lvl)
196 return ufs_pm_lvl_states[lvl].dev_state;
199 static inline enum uic_link_state
200 ufs_get_pm_lvl_to_link_pwr_state(enum ufs_pm_level lvl)
202 return ufs_pm_lvl_states[lvl].link_state;
205 static inline enum ufs_pm_level
206 ufs_get_desired_pm_lvl_for_dev_link_state(enum ufs_dev_pwr_mode dev_state,
207 enum uic_link_state link_state)
209 enum ufs_pm_level lvl;
211 for (lvl = UFS_PM_LVL_0; lvl < UFS_PM_LVL_MAX; lvl++) {
212 if ((ufs_pm_lvl_states[lvl].dev_state == dev_state) &&
213 (ufs_pm_lvl_states[lvl].link_state == link_state))
217 /* if no match found, return the level 0 */
221 static const struct ufs_dev_quirk ufs_fixups[] = {
222 /* UFS cards deviations table */
223 { .wmanufacturerid = UFS_VENDOR_MICRON,
224 .model = UFS_ANY_MODEL,
225 .quirk = UFS_DEVICE_QUIRK_DELAY_BEFORE_LPM |
226 UFS_DEVICE_QUIRK_SWAP_L2P_ENTRY_FOR_HPB_READ },
227 { .wmanufacturerid = UFS_VENDOR_SAMSUNG,
228 .model = UFS_ANY_MODEL,
229 .quirk = UFS_DEVICE_QUIRK_DELAY_BEFORE_LPM |
230 UFS_DEVICE_QUIRK_HOST_PA_TACTIVATE |
231 UFS_DEVICE_QUIRK_RECOVERY_FROM_DL_NAC_ERRORS },
232 { .wmanufacturerid = UFS_VENDOR_SKHYNIX,
233 .model = UFS_ANY_MODEL,
234 .quirk = UFS_DEVICE_QUIRK_HOST_PA_SAVECONFIGTIME },
235 { .wmanufacturerid = UFS_VENDOR_SKHYNIX,
236 .model = "hB8aL1" /*H28U62301AMR*/,
237 .quirk = UFS_DEVICE_QUIRK_HOST_VS_DEBUGSAVECONFIGTIME },
238 { .wmanufacturerid = UFS_VENDOR_TOSHIBA,
239 .model = UFS_ANY_MODEL,
240 .quirk = UFS_DEVICE_QUIRK_DELAY_BEFORE_LPM },
241 { .wmanufacturerid = UFS_VENDOR_TOSHIBA,
242 .model = "THGLF2G9C8KBADG",
243 .quirk = UFS_DEVICE_QUIRK_PA_TACTIVATE },
244 { .wmanufacturerid = UFS_VENDOR_TOSHIBA,
245 .model = "THGLF2G9D8KBADG",
246 .quirk = UFS_DEVICE_QUIRK_PA_TACTIVATE },
250 static irqreturn_t ufshcd_tmc_handler(struct ufs_hba *hba);
251 static void ufshcd_async_scan(void *data, async_cookie_t cookie);
252 static int ufshcd_reset_and_restore(struct ufs_hba *hba);
253 static int ufshcd_eh_host_reset_handler(struct scsi_cmnd *cmd);
254 static int ufshcd_clear_tm_cmd(struct ufs_hba *hba, int tag);
255 static void ufshcd_hba_exit(struct ufs_hba *hba);
256 static int ufshcd_probe_hba(struct ufs_hba *hba, bool init_dev_params);
257 static int ufshcd_setup_clocks(struct ufs_hba *hba, bool on);
258 static inline void ufshcd_add_delay_before_dme_cmd(struct ufs_hba *hba);
259 static int ufshcd_host_reset_and_restore(struct ufs_hba *hba);
260 static void ufshcd_resume_clkscaling(struct ufs_hba *hba);
261 static void ufshcd_suspend_clkscaling(struct ufs_hba *hba);
262 static void __ufshcd_suspend_clkscaling(struct ufs_hba *hba);
263 static int ufshcd_scale_clks(struct ufs_hba *hba, bool scale_up);
264 static irqreturn_t ufshcd_intr(int irq, void *__hba);
265 static int ufshcd_change_power_mode(struct ufs_hba *hba,
266 struct ufs_pa_layer_attr *pwr_mode);
267 static int ufshcd_setup_hba_vreg(struct ufs_hba *hba, bool on);
268 static int ufshcd_setup_vreg(struct ufs_hba *hba, bool on);
269 static inline int ufshcd_config_vreg_hpm(struct ufs_hba *hba,
270 struct ufs_vreg *vreg);
271 static int ufshcd_try_to_abort_task(struct ufs_hba *hba, int tag);
272 static void ufshcd_wb_toggle_buf_flush_during_h8(struct ufs_hba *hba,
274 static void ufshcd_hba_vreg_set_lpm(struct ufs_hba *hba);
275 static void ufshcd_hba_vreg_set_hpm(struct ufs_hba *hba);
277 static inline void ufshcd_enable_irq(struct ufs_hba *hba)
279 if (!hba->is_irq_enabled) {
280 enable_irq(hba->irq);
281 hba->is_irq_enabled = true;
285 static inline void ufshcd_disable_irq(struct ufs_hba *hba)
287 if (hba->is_irq_enabled) {
288 disable_irq(hba->irq);
289 hba->is_irq_enabled = false;
293 static void ufshcd_configure_wb(struct ufs_hba *hba)
295 if (!ufshcd_is_wb_allowed(hba))
298 ufshcd_wb_toggle(hba, true);
300 ufshcd_wb_toggle_buf_flush_during_h8(hba, true);
302 if (ufshcd_is_wb_buf_flush_allowed(hba))
303 ufshcd_wb_toggle_buf_flush(hba, true);
306 static void ufshcd_scsi_unblock_requests(struct ufs_hba *hba)
308 if (atomic_dec_and_test(&hba->scsi_block_reqs_cnt))
309 scsi_unblock_requests(hba->host);
312 static void ufshcd_scsi_block_requests(struct ufs_hba *hba)
314 if (atomic_inc_return(&hba->scsi_block_reqs_cnt) == 1)
315 scsi_block_requests(hba->host);
318 static void ufshcd_add_cmd_upiu_trace(struct ufs_hba *hba, unsigned int tag,
319 enum ufs_trace_str_t str_t)
321 struct utp_upiu_req *rq = hba->lrb[tag].ucd_req_ptr;
322 struct utp_upiu_header *header;
324 if (!trace_ufshcd_upiu_enabled())
327 if (str_t == UFS_CMD_SEND)
328 header = &rq->header;
330 header = &hba->lrb[tag].ucd_rsp_ptr->header;
332 trace_ufshcd_upiu(dev_name(hba->dev), str_t, header, &rq->sc.cdb,
336 static void ufshcd_add_query_upiu_trace(struct ufs_hba *hba,
337 enum ufs_trace_str_t str_t,
338 struct utp_upiu_req *rq_rsp)
340 if (!trace_ufshcd_upiu_enabled())
343 trace_ufshcd_upiu(dev_name(hba->dev), str_t, &rq_rsp->header,
344 &rq_rsp->qr, UFS_TSF_OSF);
347 static void ufshcd_add_tm_upiu_trace(struct ufs_hba *hba, unsigned int tag,
348 enum ufs_trace_str_t str_t)
350 struct utp_task_req_desc *descp = &hba->utmrdl_base_addr[tag];
352 if (!trace_ufshcd_upiu_enabled())
355 if (str_t == UFS_TM_SEND)
356 trace_ufshcd_upiu(dev_name(hba->dev), str_t,
357 &descp->upiu_req.req_header,
358 &descp->upiu_req.input_param1,
361 trace_ufshcd_upiu(dev_name(hba->dev), str_t,
362 &descp->upiu_rsp.rsp_header,
363 &descp->upiu_rsp.output_param1,
367 static void ufshcd_add_uic_command_trace(struct ufs_hba *hba,
368 const struct uic_command *ucmd,
369 enum ufs_trace_str_t str_t)
373 if (!trace_ufshcd_uic_command_enabled())
376 if (str_t == UFS_CMD_SEND)
379 cmd = ufshcd_readl(hba, REG_UIC_COMMAND);
381 trace_ufshcd_uic_command(dev_name(hba->dev), str_t, cmd,
382 ufshcd_readl(hba, REG_UIC_COMMAND_ARG_1),
383 ufshcd_readl(hba, REG_UIC_COMMAND_ARG_2),
384 ufshcd_readl(hba, REG_UIC_COMMAND_ARG_3));
387 static void ufshcd_add_command_trace(struct ufs_hba *hba, unsigned int tag,
388 enum ufs_trace_str_t str_t)
391 u8 opcode = 0, group_id = 0;
393 struct ufshcd_lrb *lrbp = &hba->lrb[tag];
394 struct scsi_cmnd *cmd = lrbp->cmd;
395 struct request *rq = scsi_cmd_to_rq(cmd);
396 int transfer_len = -1;
401 /* trace UPIU also */
402 ufshcd_add_cmd_upiu_trace(hba, tag, str_t);
403 if (!trace_ufshcd_command_enabled())
406 opcode = cmd->cmnd[0];
408 if (opcode == READ_10 || opcode == WRITE_10) {
410 * Currently we only fully trace read(10) and write(10) commands
413 be32_to_cpu(lrbp->ucd_req_ptr->sc.exp_data_transfer_len);
414 lba = scsi_get_lba(cmd);
415 if (opcode == WRITE_10)
416 group_id = lrbp->cmd->cmnd[6];
417 } else if (opcode == UNMAP) {
419 * The number of Bytes to be unmapped beginning with the lba.
421 transfer_len = blk_rq_bytes(rq);
422 lba = scsi_get_lba(cmd);
425 intr = ufshcd_readl(hba, REG_INTERRUPT_STATUS);
426 doorbell = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
427 trace_ufshcd_command(dev_name(hba->dev), str_t, tag,
428 doorbell, transfer_len, intr, lba, opcode, group_id);
431 static void ufshcd_print_clk_freqs(struct ufs_hba *hba)
433 struct ufs_clk_info *clki;
434 struct list_head *head = &hba->clk_list_head;
436 if (list_empty(head))
439 list_for_each_entry(clki, head, list) {
440 if (!IS_ERR_OR_NULL(clki->clk) && clki->min_freq &&
442 dev_err(hba->dev, "clk: %s, rate: %u\n",
443 clki->name, clki->curr_freq);
447 static void ufshcd_print_evt(struct ufs_hba *hba, u32 id,
448 const char *err_name)
452 const struct ufs_event_hist *e;
454 if (id >= UFS_EVT_CNT)
457 e = &hba->ufs_stats.event[id];
459 for (i = 0; i < UFS_EVENT_HIST_LENGTH; i++) {
460 int p = (i + e->pos) % UFS_EVENT_HIST_LENGTH;
462 if (e->tstamp[p] == 0)
464 dev_err(hba->dev, "%s[%d] = 0x%x at %lld us\n", err_name, p,
465 e->val[p], div_u64(e->tstamp[p], 1000));
470 dev_err(hba->dev, "No record of %s\n", err_name);
472 dev_err(hba->dev, "%s: total cnt=%llu\n", err_name, e->cnt);
475 static void ufshcd_print_evt_hist(struct ufs_hba *hba)
477 ufshcd_dump_regs(hba, 0, UFSHCI_REG_SPACE_SIZE, "host_regs: ");
479 ufshcd_print_evt(hba, UFS_EVT_PA_ERR, "pa_err");
480 ufshcd_print_evt(hba, UFS_EVT_DL_ERR, "dl_err");
481 ufshcd_print_evt(hba, UFS_EVT_NL_ERR, "nl_err");
482 ufshcd_print_evt(hba, UFS_EVT_TL_ERR, "tl_err");
483 ufshcd_print_evt(hba, UFS_EVT_DME_ERR, "dme_err");
484 ufshcd_print_evt(hba, UFS_EVT_AUTO_HIBERN8_ERR,
486 ufshcd_print_evt(hba, UFS_EVT_FATAL_ERR, "fatal_err");
487 ufshcd_print_evt(hba, UFS_EVT_LINK_STARTUP_FAIL,
488 "link_startup_fail");
489 ufshcd_print_evt(hba, UFS_EVT_RESUME_ERR, "resume_fail");
490 ufshcd_print_evt(hba, UFS_EVT_SUSPEND_ERR,
492 ufshcd_print_evt(hba, UFS_EVT_WL_RES_ERR, "wlun resume_fail");
493 ufshcd_print_evt(hba, UFS_EVT_WL_SUSP_ERR,
494 "wlun suspend_fail");
495 ufshcd_print_evt(hba, UFS_EVT_DEV_RESET, "dev_reset");
496 ufshcd_print_evt(hba, UFS_EVT_HOST_RESET, "host_reset");
497 ufshcd_print_evt(hba, UFS_EVT_ABORT, "task_abort");
499 ufshcd_vops_dbg_register_dump(hba);
503 void ufshcd_print_trs(struct ufs_hba *hba, unsigned long bitmap, bool pr_prdt)
505 const struct ufshcd_lrb *lrbp;
509 for_each_set_bit(tag, &bitmap, hba->nutrs) {
510 lrbp = &hba->lrb[tag];
512 dev_err(hba->dev, "UPIU[%d] - issue time %lld us\n",
513 tag, div_u64(lrbp->issue_time_stamp_local_clock, 1000));
514 dev_err(hba->dev, "UPIU[%d] - complete time %lld us\n",
515 tag, div_u64(lrbp->compl_time_stamp_local_clock, 1000));
517 "UPIU[%d] - Transfer Request Descriptor phys@0x%llx\n",
518 tag, (u64)lrbp->utrd_dma_addr);
520 ufshcd_hex_dump("UPIU TRD: ", lrbp->utr_descriptor_ptr,
521 sizeof(struct utp_transfer_req_desc));
522 dev_err(hba->dev, "UPIU[%d] - Request UPIU phys@0x%llx\n", tag,
523 (u64)lrbp->ucd_req_dma_addr);
524 ufshcd_hex_dump("UPIU REQ: ", lrbp->ucd_req_ptr,
525 sizeof(struct utp_upiu_req));
526 dev_err(hba->dev, "UPIU[%d] - Response UPIU phys@0x%llx\n", tag,
527 (u64)lrbp->ucd_rsp_dma_addr);
528 ufshcd_hex_dump("UPIU RSP: ", lrbp->ucd_rsp_ptr,
529 sizeof(struct utp_upiu_rsp));
531 prdt_length = le16_to_cpu(
532 lrbp->utr_descriptor_ptr->prd_table_length);
533 if (hba->quirks & UFSHCD_QUIRK_PRDT_BYTE_GRAN)
534 prdt_length /= sizeof(struct ufshcd_sg_entry);
537 "UPIU[%d] - PRDT - %d entries phys@0x%llx\n",
539 (u64)lrbp->ucd_prdt_dma_addr);
542 ufshcd_hex_dump("UPIU PRDT: ", lrbp->ucd_prdt_ptr,
543 sizeof(struct ufshcd_sg_entry) * prdt_length);
547 static void ufshcd_print_tmrs(struct ufs_hba *hba, unsigned long bitmap)
551 for_each_set_bit(tag, &bitmap, hba->nutmrs) {
552 struct utp_task_req_desc *tmrdp = &hba->utmrdl_base_addr[tag];
554 dev_err(hba->dev, "TM[%d] - Task Management Header\n", tag);
555 ufshcd_hex_dump("", tmrdp, sizeof(*tmrdp));
559 static void ufshcd_print_host_state(struct ufs_hba *hba)
561 const struct scsi_device *sdev_ufs = hba->ufs_device_wlun;
563 dev_err(hba->dev, "UFS Host state=%d\n", hba->ufshcd_state);
564 dev_err(hba->dev, "outstanding reqs=0x%lx tasks=0x%lx\n",
565 hba->outstanding_reqs, hba->outstanding_tasks);
566 dev_err(hba->dev, "saved_err=0x%x, saved_uic_err=0x%x\n",
567 hba->saved_err, hba->saved_uic_err);
568 dev_err(hba->dev, "Device power mode=%d, UIC link state=%d\n",
569 hba->curr_dev_pwr_mode, hba->uic_link_state);
570 dev_err(hba->dev, "PM in progress=%d, sys. suspended=%d\n",
571 hba->pm_op_in_progress, hba->is_sys_suspended);
572 dev_err(hba->dev, "Auto BKOPS=%d, Host self-block=%d\n",
573 hba->auto_bkops_enabled, hba->host->host_self_blocked);
574 dev_err(hba->dev, "Clk gate=%d\n", hba->clk_gating.state);
576 "last_hibern8_exit_tstamp at %lld us, hibern8_exit_cnt=%d\n",
577 div_u64(hba->ufs_stats.last_hibern8_exit_tstamp, 1000),
578 hba->ufs_stats.hibern8_exit_cnt);
579 dev_err(hba->dev, "last intr at %lld us, last intr status=0x%x\n",
580 div_u64(hba->ufs_stats.last_intr_ts, 1000),
581 hba->ufs_stats.last_intr_status);
582 dev_err(hba->dev, "error handling flags=0x%x, req. abort count=%d\n",
583 hba->eh_flags, hba->req_abort_count);
584 dev_err(hba->dev, "hba->ufs_version=0x%x, Host capabilities=0x%x, caps=0x%x\n",
585 hba->ufs_version, hba->capabilities, hba->caps);
586 dev_err(hba->dev, "quirks=0x%x, dev. quirks=0x%x\n", hba->quirks,
589 dev_err(hba->dev, "UFS dev info: %.8s %.16s rev %.4s\n",
590 sdev_ufs->vendor, sdev_ufs->model, sdev_ufs->rev);
592 ufshcd_print_clk_freqs(hba);
596 * ufshcd_print_pwr_info - print power params as saved in hba
598 * @hba: per-adapter instance
600 static void ufshcd_print_pwr_info(struct ufs_hba *hba)
602 static const char * const names[] = {
613 * Using dev_dbg to avoid messages during runtime PM to avoid
614 * never-ending cycles of messages written back to storage by user space
615 * causing runtime resume, causing more messages and so on.
617 dev_dbg(hba->dev, "%s:[RX, TX]: gear=[%d, %d], lane[%d, %d], pwr[%s, %s], rate = %d\n",
619 hba->pwr_info.gear_rx, hba->pwr_info.gear_tx,
620 hba->pwr_info.lane_rx, hba->pwr_info.lane_tx,
621 names[hba->pwr_info.pwr_rx],
622 names[hba->pwr_info.pwr_tx],
623 hba->pwr_info.hs_rate);
626 static void ufshcd_device_reset(struct ufs_hba *hba)
630 err = ufshcd_vops_device_reset(hba);
633 ufshcd_set_ufs_dev_active(hba);
634 if (ufshcd_is_wb_allowed(hba)) {
635 hba->dev_info.wb_enabled = false;
636 hba->dev_info.wb_buf_flush_enabled = false;
639 if (err != -EOPNOTSUPP)
640 ufshcd_update_evt_hist(hba, UFS_EVT_DEV_RESET, err);
643 void ufshcd_delay_us(unsigned long us, unsigned long tolerance)
651 usleep_range(us, us + tolerance);
653 EXPORT_SYMBOL_GPL(ufshcd_delay_us);
656 * ufshcd_wait_for_register - wait for register value to change
657 * @hba: per-adapter interface
658 * @reg: mmio register offset
659 * @mask: mask to apply to the read register value
660 * @val: value to wait for
661 * @interval_us: polling interval in microseconds
662 * @timeout_ms: timeout in milliseconds
665 * -ETIMEDOUT on error, zero on success.
667 static int ufshcd_wait_for_register(struct ufs_hba *hba, u32 reg, u32 mask,
668 u32 val, unsigned long interval_us,
669 unsigned long timeout_ms)
672 unsigned long timeout = jiffies + msecs_to_jiffies(timeout_ms);
674 /* ignore bits that we don't intend to wait on */
677 while ((ufshcd_readl(hba, reg) & mask) != val) {
678 usleep_range(interval_us, interval_us + 50);
679 if (time_after(jiffies, timeout)) {
680 if ((ufshcd_readl(hba, reg) & mask) != val)
690 * ufshcd_get_intr_mask - Get the interrupt bit mask
691 * @hba: Pointer to adapter instance
693 * Returns interrupt bit mask per version
695 static inline u32 ufshcd_get_intr_mask(struct ufs_hba *hba)
697 if (hba->ufs_version == ufshci_version(1, 0))
698 return INTERRUPT_MASK_ALL_VER_10;
699 if (hba->ufs_version <= ufshci_version(2, 0))
700 return INTERRUPT_MASK_ALL_VER_11;
702 return INTERRUPT_MASK_ALL_VER_21;
706 * ufshcd_get_ufs_version - Get the UFS version supported by the HBA
707 * @hba: Pointer to adapter instance
709 * Returns UFSHCI version supported by the controller
711 static inline u32 ufshcd_get_ufs_version(struct ufs_hba *hba)
715 if (hba->quirks & UFSHCD_QUIRK_BROKEN_UFS_HCI_VERSION)
716 ufshci_ver = ufshcd_vops_get_ufs_hci_version(hba);
718 ufshci_ver = ufshcd_readl(hba, REG_UFS_VERSION);
721 * UFSHCI v1.x uses a different version scheme, in order
722 * to allow the use of comparisons with the ufshci_version
723 * function, we convert it to the same scheme as ufs 2.0+.
725 if (ufshci_ver & 0x00010000)
726 return ufshci_version(1, ufshci_ver & 0x00000100);
732 * ufshcd_is_device_present - Check if any device connected to
733 * the host controller
734 * @hba: pointer to adapter instance
736 * Returns true if device present, false if no device detected
738 static inline bool ufshcd_is_device_present(struct ufs_hba *hba)
740 return ufshcd_readl(hba, REG_CONTROLLER_STATUS) & DEVICE_PRESENT;
744 * ufshcd_get_tr_ocs - Get the UTRD Overall Command Status
745 * @lrbp: pointer to local command reference block
747 * This function is used to get the OCS field from UTRD
748 * Returns the OCS field in the UTRD
750 static enum utp_ocs ufshcd_get_tr_ocs(struct ufshcd_lrb *lrbp)
752 return le32_to_cpu(lrbp->utr_descriptor_ptr->header.dword_2) & MASK_OCS;
756 * ufshcd_utrl_clear() - Clear requests from the controller request list.
757 * @hba: per adapter instance
758 * @mask: mask with one bit set for each request to be cleared
760 static inline void ufshcd_utrl_clear(struct ufs_hba *hba, u32 mask)
762 if (hba->quirks & UFSHCI_QUIRK_BROKEN_REQ_LIST_CLR)
765 * From the UFSHCI specification: "UTP Transfer Request List CLear
766 * Register (UTRLCLR): This field is bit significant. Each bit
767 * corresponds to a slot in the UTP Transfer Request List, where bit 0
768 * corresponds to request slot 0. A bit in this field is set to ‘0’
769 * by host software to indicate to the host controller that a transfer
770 * request slot is cleared. The host controller
771 * shall free up any resources associated to the request slot
772 * immediately, and shall set the associated bit in UTRLDBR to ‘0’. The
773 * host software indicates no change to request slots by setting the
774 * associated bits in this field to ‘1’. Bits in this field shall only
775 * be set ‘1’ or ‘0’ by host software when UTRLRSR is set to ‘1’."
777 ufshcd_writel(hba, ~mask, REG_UTP_TRANSFER_REQ_LIST_CLEAR);
781 * ufshcd_utmrl_clear - Clear a bit in UTMRLCLR register
782 * @hba: per adapter instance
783 * @pos: position of the bit to be cleared
785 static inline void ufshcd_utmrl_clear(struct ufs_hba *hba, u32 pos)
787 if (hba->quirks & UFSHCI_QUIRK_BROKEN_REQ_LIST_CLR)
788 ufshcd_writel(hba, (1 << pos), REG_UTP_TASK_REQ_LIST_CLEAR);
790 ufshcd_writel(hba, ~(1 << pos), REG_UTP_TASK_REQ_LIST_CLEAR);
794 * ufshcd_get_lists_status - Check UCRDY, UTRLRDY and UTMRLRDY
795 * @reg: Register value of host controller status
797 * Returns integer, 0 on Success and positive value if failed
799 static inline int ufshcd_get_lists_status(u32 reg)
801 return !((reg & UFSHCD_STATUS_READY) == UFSHCD_STATUS_READY);
805 * ufshcd_get_uic_cmd_result - Get the UIC command result
806 * @hba: Pointer to adapter instance
808 * This function gets the result of UIC command completion
809 * Returns 0 on success, non zero value on error
811 static inline int ufshcd_get_uic_cmd_result(struct ufs_hba *hba)
813 return ufshcd_readl(hba, REG_UIC_COMMAND_ARG_2) &
814 MASK_UIC_COMMAND_RESULT;
818 * ufshcd_get_dme_attr_val - Get the value of attribute returned by UIC command
819 * @hba: Pointer to adapter instance
821 * This function gets UIC command argument3
822 * Returns 0 on success, non zero value on error
824 static inline u32 ufshcd_get_dme_attr_val(struct ufs_hba *hba)
826 return ufshcd_readl(hba, REG_UIC_COMMAND_ARG_3);
830 * ufshcd_get_req_rsp - returns the TR response transaction type
831 * @ucd_rsp_ptr: pointer to response UPIU
834 ufshcd_get_req_rsp(struct utp_upiu_rsp *ucd_rsp_ptr)
836 return be32_to_cpu(ucd_rsp_ptr->header.dword_0) >> 24;
840 * ufshcd_get_rsp_upiu_result - Get the result from response UPIU
841 * @ucd_rsp_ptr: pointer to response UPIU
843 * This function gets the response status and scsi_status from response UPIU
844 * Returns the response result code.
847 ufshcd_get_rsp_upiu_result(struct utp_upiu_rsp *ucd_rsp_ptr)
849 return be32_to_cpu(ucd_rsp_ptr->header.dword_1) & MASK_RSP_UPIU_RESULT;
853 * ufshcd_get_rsp_upiu_data_seg_len - Get the data segment length
855 * @ucd_rsp_ptr: pointer to response UPIU
857 * Return the data segment length.
859 static inline unsigned int
860 ufshcd_get_rsp_upiu_data_seg_len(struct utp_upiu_rsp *ucd_rsp_ptr)
862 return be32_to_cpu(ucd_rsp_ptr->header.dword_2) &
863 MASK_RSP_UPIU_DATA_SEG_LEN;
867 * ufshcd_is_exception_event - Check if the device raised an exception event
868 * @ucd_rsp_ptr: pointer to response UPIU
870 * The function checks if the device raised an exception event indicated in
871 * the Device Information field of response UPIU.
873 * Returns true if exception is raised, false otherwise.
875 static inline bool ufshcd_is_exception_event(struct utp_upiu_rsp *ucd_rsp_ptr)
877 return be32_to_cpu(ucd_rsp_ptr->header.dword_2) &
878 MASK_RSP_EXCEPTION_EVENT;
882 * ufshcd_reset_intr_aggr - Reset interrupt aggregation values.
883 * @hba: per adapter instance
886 ufshcd_reset_intr_aggr(struct ufs_hba *hba)
888 ufshcd_writel(hba, INT_AGGR_ENABLE |
889 INT_AGGR_COUNTER_AND_TIMER_RESET,
890 REG_UTP_TRANSFER_REQ_INT_AGG_CONTROL);
894 * ufshcd_config_intr_aggr - Configure interrupt aggregation values.
895 * @hba: per adapter instance
896 * @cnt: Interrupt aggregation counter threshold
897 * @tmout: Interrupt aggregation timeout value
900 ufshcd_config_intr_aggr(struct ufs_hba *hba, u8 cnt, u8 tmout)
902 ufshcd_writel(hba, INT_AGGR_ENABLE | INT_AGGR_PARAM_WRITE |
903 INT_AGGR_COUNTER_THLD_VAL(cnt) |
904 INT_AGGR_TIMEOUT_VAL(tmout),
905 REG_UTP_TRANSFER_REQ_INT_AGG_CONTROL);
909 * ufshcd_disable_intr_aggr - Disables interrupt aggregation.
910 * @hba: per adapter instance
912 static inline void ufshcd_disable_intr_aggr(struct ufs_hba *hba)
914 ufshcd_writel(hba, 0, REG_UTP_TRANSFER_REQ_INT_AGG_CONTROL);
918 * ufshcd_enable_run_stop_reg - Enable run-stop registers,
919 * When run-stop registers are set to 1, it indicates the
920 * host controller that it can process the requests
921 * @hba: per adapter instance
923 static void ufshcd_enable_run_stop_reg(struct ufs_hba *hba)
925 ufshcd_writel(hba, UTP_TASK_REQ_LIST_RUN_STOP_BIT,
926 REG_UTP_TASK_REQ_LIST_RUN_STOP);
927 ufshcd_writel(hba, UTP_TRANSFER_REQ_LIST_RUN_STOP_BIT,
928 REG_UTP_TRANSFER_REQ_LIST_RUN_STOP);
932 * ufshcd_hba_start - Start controller initialization sequence
933 * @hba: per adapter instance
935 static inline void ufshcd_hba_start(struct ufs_hba *hba)
937 u32 val = CONTROLLER_ENABLE;
939 if (ufshcd_crypto_enable(hba))
940 val |= CRYPTO_GENERAL_ENABLE;
942 ufshcd_writel(hba, val, REG_CONTROLLER_ENABLE);
946 * ufshcd_is_hba_active - Get controller state
947 * @hba: per adapter instance
949 * Returns true if and only if the controller is active.
951 static inline bool ufshcd_is_hba_active(struct ufs_hba *hba)
953 return ufshcd_readl(hba, REG_CONTROLLER_ENABLE) & CONTROLLER_ENABLE;
956 u32 ufshcd_get_local_unipro_ver(struct ufs_hba *hba)
958 /* HCI version 1.0 and 1.1 supports UniPro 1.41 */
959 if (hba->ufs_version <= ufshci_version(1, 1))
960 return UFS_UNIPRO_VER_1_41;
962 return UFS_UNIPRO_VER_1_6;
964 EXPORT_SYMBOL(ufshcd_get_local_unipro_ver);
966 static bool ufshcd_is_unipro_pa_params_tuning_req(struct ufs_hba *hba)
969 * If both host and device support UniPro ver1.6 or later, PA layer
970 * parameters tuning happens during link startup itself.
972 * We can manually tune PA layer parameters if either host or device
973 * doesn't support UniPro ver 1.6 or later. But to keep manual tuning
974 * logic simple, we will only do manual tuning if local unipro version
975 * doesn't support ver1.6 or later.
977 return ufshcd_get_local_unipro_ver(hba) < UFS_UNIPRO_VER_1_6;
981 * ufshcd_set_clk_freq - set UFS controller clock frequencies
982 * @hba: per adapter instance
983 * @scale_up: If True, set max possible frequency othewise set low frequency
985 * Returns 0 if successful
986 * Returns < 0 for any other errors
988 static int ufshcd_set_clk_freq(struct ufs_hba *hba, bool scale_up)
991 struct ufs_clk_info *clki;
992 struct list_head *head = &hba->clk_list_head;
994 if (list_empty(head))
997 list_for_each_entry(clki, head, list) {
998 if (!IS_ERR_OR_NULL(clki->clk)) {
999 if (scale_up && clki->max_freq) {
1000 if (clki->curr_freq == clki->max_freq)
1003 ret = clk_set_rate(clki->clk, clki->max_freq);
1005 dev_err(hba->dev, "%s: %s clk set rate(%dHz) failed, %d\n",
1006 __func__, clki->name,
1007 clki->max_freq, ret);
1010 trace_ufshcd_clk_scaling(dev_name(hba->dev),
1011 "scaled up", clki->name,
1015 clki->curr_freq = clki->max_freq;
1017 } else if (!scale_up && clki->min_freq) {
1018 if (clki->curr_freq == clki->min_freq)
1021 ret = clk_set_rate(clki->clk, clki->min_freq);
1023 dev_err(hba->dev, "%s: %s clk set rate(%dHz) failed, %d\n",
1024 __func__, clki->name,
1025 clki->min_freq, ret);
1028 trace_ufshcd_clk_scaling(dev_name(hba->dev),
1029 "scaled down", clki->name,
1032 clki->curr_freq = clki->min_freq;
1035 dev_dbg(hba->dev, "%s: clk: %s, rate: %lu\n", __func__,
1036 clki->name, clk_get_rate(clki->clk));
1044 * ufshcd_scale_clks - scale up or scale down UFS controller clocks
1045 * @hba: per adapter instance
1046 * @scale_up: True if scaling up and false if scaling down
1048 * Returns 0 if successful
1049 * Returns < 0 for any other errors
1051 static int ufshcd_scale_clks(struct ufs_hba *hba, bool scale_up)
1054 ktime_t start = ktime_get();
1056 ret = ufshcd_vops_clk_scale_notify(hba, scale_up, PRE_CHANGE);
1060 ret = ufshcd_set_clk_freq(hba, scale_up);
1064 ret = ufshcd_vops_clk_scale_notify(hba, scale_up, POST_CHANGE);
1066 ufshcd_set_clk_freq(hba, !scale_up);
1069 trace_ufshcd_profile_clk_scaling(dev_name(hba->dev),
1070 (scale_up ? "up" : "down"),
1071 ktime_to_us(ktime_sub(ktime_get(), start)), ret);
1076 * ufshcd_is_devfreq_scaling_required - check if scaling is required or not
1077 * @hba: per adapter instance
1078 * @scale_up: True if scaling up and false if scaling down
1080 * Returns true if scaling is required, false otherwise.
1082 static bool ufshcd_is_devfreq_scaling_required(struct ufs_hba *hba,
1085 struct ufs_clk_info *clki;
1086 struct list_head *head = &hba->clk_list_head;
1088 if (list_empty(head))
1091 list_for_each_entry(clki, head, list) {
1092 if (!IS_ERR_OR_NULL(clki->clk)) {
1093 if (scale_up && clki->max_freq) {
1094 if (clki->curr_freq == clki->max_freq)
1097 } else if (!scale_up && clki->min_freq) {
1098 if (clki->curr_freq == clki->min_freq)
1109 * Determine the number of pending commands by counting the bits in the SCSI
1110 * device budget maps. This approach has been selected because a bit is set in
1111 * the budget map before scsi_host_queue_ready() checks the host_self_blocked
1112 * flag. The host_self_blocked flag can be modified by calling
1113 * scsi_block_requests() or scsi_unblock_requests().
1115 static u32 ufshcd_pending_cmds(struct ufs_hba *hba)
1117 const struct scsi_device *sdev;
1120 lockdep_assert_held(hba->host->host_lock);
1121 __shost_for_each_device(sdev, hba->host)
1122 pending += sbitmap_weight(&sdev->budget_map);
1127 static int ufshcd_wait_for_doorbell_clr(struct ufs_hba *hba,
1128 u64 wait_timeout_us)
1130 unsigned long flags;
1134 bool timeout = false, do_last_check = false;
1137 ufshcd_hold(hba, false);
1138 spin_lock_irqsave(hba->host->host_lock, flags);
1140 * Wait for all the outstanding tasks/transfer requests.
1141 * Verify by checking the doorbell registers are clear.
1143 start = ktime_get();
1145 if (hba->ufshcd_state != UFSHCD_STATE_OPERATIONAL) {
1150 tm_doorbell = ufshcd_readl(hba, REG_UTP_TASK_REQ_DOOR_BELL);
1151 tr_pending = ufshcd_pending_cmds(hba);
1152 if (!tm_doorbell && !tr_pending) {
1155 } else if (do_last_check) {
1159 spin_unlock_irqrestore(hba->host->host_lock, flags);
1161 if (ktime_to_us(ktime_sub(ktime_get(), start)) >
1165 * We might have scheduled out for long time so make
1166 * sure to check if doorbells are cleared by this time
1169 do_last_check = true;
1171 spin_lock_irqsave(hba->host->host_lock, flags);
1172 } while (tm_doorbell || tr_pending);
1176 "%s: timedout waiting for doorbell to clear (tm=0x%x, tr=0x%x)\n",
1177 __func__, tm_doorbell, tr_pending);
1181 spin_unlock_irqrestore(hba->host->host_lock, flags);
1182 ufshcd_release(hba);
1187 * ufshcd_scale_gear - scale up/down UFS gear
1188 * @hba: per adapter instance
1189 * @scale_up: True for scaling up gear and false for scaling down
1191 * Returns 0 for success,
1192 * Returns -EBUSY if scaling can't happen at this time
1193 * Returns non-zero for any other errors
1195 static int ufshcd_scale_gear(struct ufs_hba *hba, bool scale_up)
1198 struct ufs_pa_layer_attr new_pwr_info;
1201 memcpy(&new_pwr_info, &hba->clk_scaling.saved_pwr_info.info,
1202 sizeof(struct ufs_pa_layer_attr));
1204 memcpy(&new_pwr_info, &hba->pwr_info,
1205 sizeof(struct ufs_pa_layer_attr));
1207 if (hba->pwr_info.gear_tx > hba->clk_scaling.min_gear ||
1208 hba->pwr_info.gear_rx > hba->clk_scaling.min_gear) {
1209 /* save the current power mode */
1210 memcpy(&hba->clk_scaling.saved_pwr_info.info,
1212 sizeof(struct ufs_pa_layer_attr));
1214 /* scale down gear */
1215 new_pwr_info.gear_tx = hba->clk_scaling.min_gear;
1216 new_pwr_info.gear_rx = hba->clk_scaling.min_gear;
1220 /* check if the power mode needs to be changed or not? */
1221 ret = ufshcd_config_pwr_mode(hba, &new_pwr_info);
1223 dev_err(hba->dev, "%s: failed err %d, old gear: (tx %d rx %d), new gear: (tx %d rx %d)",
1225 hba->pwr_info.gear_tx, hba->pwr_info.gear_rx,
1226 new_pwr_info.gear_tx, new_pwr_info.gear_rx);
1231 static int ufshcd_clock_scaling_prepare(struct ufs_hba *hba)
1233 #define DOORBELL_CLR_TOUT_US (1000 * 1000) /* 1 sec */
1236 * make sure that there are no outstanding requests when
1237 * clock scaling is in progress
1239 ufshcd_scsi_block_requests(hba);
1240 down_write(&hba->clk_scaling_lock);
1242 if (!hba->clk_scaling.is_allowed ||
1243 ufshcd_wait_for_doorbell_clr(hba, DOORBELL_CLR_TOUT_US)) {
1245 up_write(&hba->clk_scaling_lock);
1246 ufshcd_scsi_unblock_requests(hba);
1250 /* let's not get into low power until clock scaling is completed */
1251 ufshcd_hold(hba, false);
1257 static void ufshcd_clock_scaling_unprepare(struct ufs_hba *hba, bool writelock)
1260 up_write(&hba->clk_scaling_lock);
1262 up_read(&hba->clk_scaling_lock);
1263 ufshcd_scsi_unblock_requests(hba);
1264 ufshcd_release(hba);
1268 * ufshcd_devfreq_scale - scale up/down UFS clocks and gear
1269 * @hba: per adapter instance
1270 * @scale_up: True for scaling up and false for scalin down
1272 * Returns 0 for success,
1273 * Returns -EBUSY if scaling can't happen at this time
1274 * Returns non-zero for any other errors
1276 static int ufshcd_devfreq_scale(struct ufs_hba *hba, bool scale_up)
1279 bool is_writelock = true;
1281 ret = ufshcd_clock_scaling_prepare(hba);
1285 /* scale down the gear before scaling down clocks */
1287 ret = ufshcd_scale_gear(hba, false);
1292 ret = ufshcd_scale_clks(hba, scale_up);
1295 ufshcd_scale_gear(hba, true);
1299 /* scale up the gear after scaling up clocks */
1301 ret = ufshcd_scale_gear(hba, true);
1303 ufshcd_scale_clks(hba, false);
1308 /* Enable Write Booster if we have scaled up else disable it */
1309 if (ufshcd_enable_wb_if_scaling_up(hba)) {
1310 downgrade_write(&hba->clk_scaling_lock);
1311 is_writelock = false;
1312 ufshcd_wb_toggle(hba, scale_up);
1316 ufshcd_clock_scaling_unprepare(hba, is_writelock);
1320 static void ufshcd_clk_scaling_suspend_work(struct work_struct *work)
1322 struct ufs_hba *hba = container_of(work, struct ufs_hba,
1323 clk_scaling.suspend_work);
1324 unsigned long irq_flags;
1326 spin_lock_irqsave(hba->host->host_lock, irq_flags);
1327 if (hba->clk_scaling.active_reqs || hba->clk_scaling.is_suspended) {
1328 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1331 hba->clk_scaling.is_suspended = true;
1332 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1334 __ufshcd_suspend_clkscaling(hba);
1337 static void ufshcd_clk_scaling_resume_work(struct work_struct *work)
1339 struct ufs_hba *hba = container_of(work, struct ufs_hba,
1340 clk_scaling.resume_work);
1341 unsigned long irq_flags;
1343 spin_lock_irqsave(hba->host->host_lock, irq_flags);
1344 if (!hba->clk_scaling.is_suspended) {
1345 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1348 hba->clk_scaling.is_suspended = false;
1349 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1351 devfreq_resume_device(hba->devfreq);
1354 static int ufshcd_devfreq_target(struct device *dev,
1355 unsigned long *freq, u32 flags)
1358 struct ufs_hba *hba = dev_get_drvdata(dev);
1360 bool scale_up, sched_clk_scaling_suspend_work = false;
1361 struct list_head *clk_list = &hba->clk_list_head;
1362 struct ufs_clk_info *clki;
1363 unsigned long irq_flags;
1365 if (!ufshcd_is_clkscaling_supported(hba))
1368 clki = list_first_entry(&hba->clk_list_head, struct ufs_clk_info, list);
1369 /* Override with the closest supported frequency */
1370 *freq = (unsigned long) clk_round_rate(clki->clk, *freq);
1371 spin_lock_irqsave(hba->host->host_lock, irq_flags);
1372 if (ufshcd_eh_in_progress(hba)) {
1373 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1377 if (!hba->clk_scaling.active_reqs)
1378 sched_clk_scaling_suspend_work = true;
1380 if (list_empty(clk_list)) {
1381 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1385 /* Decide based on the rounded-off frequency and update */
1386 scale_up = *freq == clki->max_freq;
1388 *freq = clki->min_freq;
1389 /* Update the frequency */
1390 if (!ufshcd_is_devfreq_scaling_required(hba, scale_up)) {
1391 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1393 goto out; /* no state change required */
1395 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1397 start = ktime_get();
1398 ret = ufshcd_devfreq_scale(hba, scale_up);
1400 trace_ufshcd_profile_clk_scaling(dev_name(hba->dev),
1401 (scale_up ? "up" : "down"),
1402 ktime_to_us(ktime_sub(ktime_get(), start)), ret);
1405 if (sched_clk_scaling_suspend_work)
1406 queue_work(hba->clk_scaling.workq,
1407 &hba->clk_scaling.suspend_work);
1412 static int ufshcd_devfreq_get_dev_status(struct device *dev,
1413 struct devfreq_dev_status *stat)
1415 struct ufs_hba *hba = dev_get_drvdata(dev);
1416 struct ufs_clk_scaling *scaling = &hba->clk_scaling;
1417 unsigned long flags;
1418 struct list_head *clk_list = &hba->clk_list_head;
1419 struct ufs_clk_info *clki;
1422 if (!ufshcd_is_clkscaling_supported(hba))
1425 memset(stat, 0, sizeof(*stat));
1427 spin_lock_irqsave(hba->host->host_lock, flags);
1428 curr_t = ktime_get();
1429 if (!scaling->window_start_t)
1432 clki = list_first_entry(clk_list, struct ufs_clk_info, list);
1434 * If current frequency is 0, then the ondemand governor considers
1435 * there's no initial frequency set. And it always requests to set
1436 * to max. frequency.
1438 stat->current_frequency = clki->curr_freq;
1439 if (scaling->is_busy_started)
1440 scaling->tot_busy_t += ktime_us_delta(curr_t,
1441 scaling->busy_start_t);
1443 stat->total_time = ktime_us_delta(curr_t, scaling->window_start_t);
1444 stat->busy_time = scaling->tot_busy_t;
1446 scaling->window_start_t = curr_t;
1447 scaling->tot_busy_t = 0;
1449 if (hba->outstanding_reqs) {
1450 scaling->busy_start_t = curr_t;
1451 scaling->is_busy_started = true;
1453 scaling->busy_start_t = 0;
1454 scaling->is_busy_started = false;
1456 spin_unlock_irqrestore(hba->host->host_lock, flags);
1460 static int ufshcd_devfreq_init(struct ufs_hba *hba)
1462 struct list_head *clk_list = &hba->clk_list_head;
1463 struct ufs_clk_info *clki;
1464 struct devfreq *devfreq;
1467 /* Skip devfreq if we don't have any clocks in the list */
1468 if (list_empty(clk_list))
1471 clki = list_first_entry(clk_list, struct ufs_clk_info, list);
1472 dev_pm_opp_add(hba->dev, clki->min_freq, 0);
1473 dev_pm_opp_add(hba->dev, clki->max_freq, 0);
1475 ufshcd_vops_config_scaling_param(hba, &hba->vps->devfreq_profile,
1476 &hba->vps->ondemand_data);
1477 devfreq = devfreq_add_device(hba->dev,
1478 &hba->vps->devfreq_profile,
1479 DEVFREQ_GOV_SIMPLE_ONDEMAND,
1480 &hba->vps->ondemand_data);
1481 if (IS_ERR(devfreq)) {
1482 ret = PTR_ERR(devfreq);
1483 dev_err(hba->dev, "Unable to register with devfreq %d\n", ret);
1485 dev_pm_opp_remove(hba->dev, clki->min_freq);
1486 dev_pm_opp_remove(hba->dev, clki->max_freq);
1490 hba->devfreq = devfreq;
1495 static void ufshcd_devfreq_remove(struct ufs_hba *hba)
1497 struct list_head *clk_list = &hba->clk_list_head;
1498 struct ufs_clk_info *clki;
1503 devfreq_remove_device(hba->devfreq);
1504 hba->devfreq = NULL;
1506 clki = list_first_entry(clk_list, struct ufs_clk_info, list);
1507 dev_pm_opp_remove(hba->dev, clki->min_freq);
1508 dev_pm_opp_remove(hba->dev, clki->max_freq);
1511 static void __ufshcd_suspend_clkscaling(struct ufs_hba *hba)
1513 unsigned long flags;
1515 devfreq_suspend_device(hba->devfreq);
1516 spin_lock_irqsave(hba->host->host_lock, flags);
1517 hba->clk_scaling.window_start_t = 0;
1518 spin_unlock_irqrestore(hba->host->host_lock, flags);
1521 static void ufshcd_suspend_clkscaling(struct ufs_hba *hba)
1523 unsigned long flags;
1524 bool suspend = false;
1526 cancel_work_sync(&hba->clk_scaling.suspend_work);
1527 cancel_work_sync(&hba->clk_scaling.resume_work);
1529 spin_lock_irqsave(hba->host->host_lock, flags);
1530 if (!hba->clk_scaling.is_suspended) {
1532 hba->clk_scaling.is_suspended = true;
1534 spin_unlock_irqrestore(hba->host->host_lock, flags);
1537 __ufshcd_suspend_clkscaling(hba);
1540 static void ufshcd_resume_clkscaling(struct ufs_hba *hba)
1542 unsigned long flags;
1543 bool resume = false;
1545 spin_lock_irqsave(hba->host->host_lock, flags);
1546 if (hba->clk_scaling.is_suspended) {
1548 hba->clk_scaling.is_suspended = false;
1550 spin_unlock_irqrestore(hba->host->host_lock, flags);
1553 devfreq_resume_device(hba->devfreq);
1556 static ssize_t ufshcd_clkscale_enable_show(struct device *dev,
1557 struct device_attribute *attr, char *buf)
1559 struct ufs_hba *hba = dev_get_drvdata(dev);
1561 return sysfs_emit(buf, "%d\n", hba->clk_scaling.is_enabled);
1564 static ssize_t ufshcd_clkscale_enable_store(struct device *dev,
1565 struct device_attribute *attr, const char *buf, size_t count)
1567 struct ufs_hba *hba = dev_get_drvdata(dev);
1571 if (kstrtou32(buf, 0, &value))
1574 down(&hba->host_sem);
1575 if (!ufshcd_is_user_access_allowed(hba)) {
1581 if (value == hba->clk_scaling.is_enabled)
1584 ufshcd_rpm_get_sync(hba);
1585 ufshcd_hold(hba, false);
1587 hba->clk_scaling.is_enabled = value;
1590 ufshcd_resume_clkscaling(hba);
1592 ufshcd_suspend_clkscaling(hba);
1593 err = ufshcd_devfreq_scale(hba, true);
1595 dev_err(hba->dev, "%s: failed to scale clocks up %d\n",
1599 ufshcd_release(hba);
1600 ufshcd_rpm_put_sync(hba);
1603 return err ? err : count;
1606 static void ufshcd_init_clk_scaling_sysfs(struct ufs_hba *hba)
1608 hba->clk_scaling.enable_attr.show = ufshcd_clkscale_enable_show;
1609 hba->clk_scaling.enable_attr.store = ufshcd_clkscale_enable_store;
1610 sysfs_attr_init(&hba->clk_scaling.enable_attr.attr);
1611 hba->clk_scaling.enable_attr.attr.name = "clkscale_enable";
1612 hba->clk_scaling.enable_attr.attr.mode = 0644;
1613 if (device_create_file(hba->dev, &hba->clk_scaling.enable_attr))
1614 dev_err(hba->dev, "Failed to create sysfs for clkscale_enable\n");
1617 static void ufshcd_remove_clk_scaling_sysfs(struct ufs_hba *hba)
1619 if (hba->clk_scaling.enable_attr.attr.name)
1620 device_remove_file(hba->dev, &hba->clk_scaling.enable_attr);
1623 static void ufshcd_init_clk_scaling(struct ufs_hba *hba)
1625 char wq_name[sizeof("ufs_clkscaling_00")];
1627 if (!ufshcd_is_clkscaling_supported(hba))
1630 if (!hba->clk_scaling.min_gear)
1631 hba->clk_scaling.min_gear = UFS_HS_G1;
1633 INIT_WORK(&hba->clk_scaling.suspend_work,
1634 ufshcd_clk_scaling_suspend_work);
1635 INIT_WORK(&hba->clk_scaling.resume_work,
1636 ufshcd_clk_scaling_resume_work);
1638 snprintf(wq_name, sizeof(wq_name), "ufs_clkscaling_%d",
1639 hba->host->host_no);
1640 hba->clk_scaling.workq = create_singlethread_workqueue(wq_name);
1642 hba->clk_scaling.is_initialized = true;
1645 static void ufshcd_exit_clk_scaling(struct ufs_hba *hba)
1647 if (!hba->clk_scaling.is_initialized)
1650 ufshcd_remove_clk_scaling_sysfs(hba);
1651 destroy_workqueue(hba->clk_scaling.workq);
1652 ufshcd_devfreq_remove(hba);
1653 hba->clk_scaling.is_initialized = false;
1656 static void ufshcd_ungate_work(struct work_struct *work)
1659 unsigned long flags;
1660 struct ufs_hba *hba = container_of(work, struct ufs_hba,
1661 clk_gating.ungate_work);
1663 cancel_delayed_work_sync(&hba->clk_gating.gate_work);
1665 spin_lock_irqsave(hba->host->host_lock, flags);
1666 if (hba->clk_gating.state == CLKS_ON) {
1667 spin_unlock_irqrestore(hba->host->host_lock, flags);
1671 spin_unlock_irqrestore(hba->host->host_lock, flags);
1672 ufshcd_hba_vreg_set_hpm(hba);
1673 ufshcd_setup_clocks(hba, true);
1675 ufshcd_enable_irq(hba);
1677 /* Exit from hibern8 */
1678 if (ufshcd_can_hibern8_during_gating(hba)) {
1679 /* Prevent gating in this path */
1680 hba->clk_gating.is_suspended = true;
1681 if (ufshcd_is_link_hibern8(hba)) {
1682 ret = ufshcd_uic_hibern8_exit(hba);
1684 dev_err(hba->dev, "%s: hibern8 exit failed %d\n",
1687 ufshcd_set_link_active(hba);
1689 hba->clk_gating.is_suspended = false;
1692 ufshcd_scsi_unblock_requests(hba);
1696 * ufshcd_hold - Enable clocks that were gated earlier due to ufshcd_release.
1697 * Also, exit from hibern8 mode and set the link as active.
1698 * @hba: per adapter instance
1699 * @async: This indicates whether caller should ungate clocks asynchronously.
1701 int ufshcd_hold(struct ufs_hba *hba, bool async)
1705 unsigned long flags;
1707 if (!ufshcd_is_clkgating_allowed(hba) ||
1708 !hba->clk_gating.is_initialized)
1710 spin_lock_irqsave(hba->host->host_lock, flags);
1711 hba->clk_gating.active_reqs++;
1714 switch (hba->clk_gating.state) {
1717 * Wait for the ungate work to complete if in progress.
1718 * Though the clocks may be in ON state, the link could
1719 * still be in hibner8 state if hibern8 is allowed
1720 * during clock gating.
1721 * Make sure we exit hibern8 state also in addition to
1724 if (ufshcd_can_hibern8_during_gating(hba) &&
1725 ufshcd_is_link_hibern8(hba)) {
1728 hba->clk_gating.active_reqs--;
1731 spin_unlock_irqrestore(hba->host->host_lock, flags);
1732 flush_result = flush_work(&hba->clk_gating.ungate_work);
1733 if (hba->clk_gating.is_suspended && !flush_result)
1735 spin_lock_irqsave(hba->host->host_lock, flags);
1740 if (cancel_delayed_work(&hba->clk_gating.gate_work)) {
1741 hba->clk_gating.state = CLKS_ON;
1742 trace_ufshcd_clk_gating(dev_name(hba->dev),
1743 hba->clk_gating.state);
1747 * If we are here, it means gating work is either done or
1748 * currently running. Hence, fall through to cancel gating
1749 * work and to enable clocks.
1753 hba->clk_gating.state = REQ_CLKS_ON;
1754 trace_ufshcd_clk_gating(dev_name(hba->dev),
1755 hba->clk_gating.state);
1756 if (queue_work(hba->clk_gating.clk_gating_workq,
1757 &hba->clk_gating.ungate_work))
1758 ufshcd_scsi_block_requests(hba);
1760 * fall through to check if we should wait for this
1761 * work to be done or not.
1767 hba->clk_gating.active_reqs--;
1771 spin_unlock_irqrestore(hba->host->host_lock, flags);
1772 flush_work(&hba->clk_gating.ungate_work);
1773 /* Make sure state is CLKS_ON before returning */
1774 spin_lock_irqsave(hba->host->host_lock, flags);
1777 dev_err(hba->dev, "%s: clk gating is in invalid state %d\n",
1778 __func__, hba->clk_gating.state);
1781 spin_unlock_irqrestore(hba->host->host_lock, flags);
1785 EXPORT_SYMBOL_GPL(ufshcd_hold);
1787 static void ufshcd_gate_work(struct work_struct *work)
1789 struct ufs_hba *hba = container_of(work, struct ufs_hba,
1790 clk_gating.gate_work.work);
1791 unsigned long flags;
1794 spin_lock_irqsave(hba->host->host_lock, flags);
1796 * In case you are here to cancel this work the gating state
1797 * would be marked as REQ_CLKS_ON. In this case save time by
1798 * skipping the gating work and exit after changing the clock
1801 if (hba->clk_gating.is_suspended ||
1802 (hba->clk_gating.state != REQ_CLKS_OFF)) {
1803 hba->clk_gating.state = CLKS_ON;
1804 trace_ufshcd_clk_gating(dev_name(hba->dev),
1805 hba->clk_gating.state);
1809 if (hba->clk_gating.active_reqs
1810 || hba->ufshcd_state != UFSHCD_STATE_OPERATIONAL
1811 || hba->outstanding_reqs || hba->outstanding_tasks
1812 || hba->active_uic_cmd || hba->uic_async_done)
1815 spin_unlock_irqrestore(hba->host->host_lock, flags);
1817 /* put the link into hibern8 mode before turning off clocks */
1818 if (ufshcd_can_hibern8_during_gating(hba)) {
1819 ret = ufshcd_uic_hibern8_enter(hba);
1821 hba->clk_gating.state = CLKS_ON;
1822 dev_err(hba->dev, "%s: hibern8 enter failed %d\n",
1824 trace_ufshcd_clk_gating(dev_name(hba->dev),
1825 hba->clk_gating.state);
1828 ufshcd_set_link_hibern8(hba);
1831 ufshcd_disable_irq(hba);
1833 ufshcd_setup_clocks(hba, false);
1835 /* Put the host controller in low power mode if possible */
1836 ufshcd_hba_vreg_set_lpm(hba);
1838 * In case you are here to cancel this work the gating state
1839 * would be marked as REQ_CLKS_ON. In this case keep the state
1840 * as REQ_CLKS_ON which would anyway imply that clocks are off
1841 * and a request to turn them on is pending. By doing this way,
1842 * we keep the state machine in tact and this would ultimately
1843 * prevent from doing cancel work multiple times when there are
1844 * new requests arriving before the current cancel work is done.
1846 spin_lock_irqsave(hba->host->host_lock, flags);
1847 if (hba->clk_gating.state == REQ_CLKS_OFF) {
1848 hba->clk_gating.state = CLKS_OFF;
1849 trace_ufshcd_clk_gating(dev_name(hba->dev),
1850 hba->clk_gating.state);
1853 spin_unlock_irqrestore(hba->host->host_lock, flags);
1858 /* host lock must be held before calling this variant */
1859 static void __ufshcd_release(struct ufs_hba *hba)
1861 if (!ufshcd_is_clkgating_allowed(hba))
1864 hba->clk_gating.active_reqs--;
1866 if (hba->clk_gating.active_reqs || hba->clk_gating.is_suspended ||
1867 hba->ufshcd_state != UFSHCD_STATE_OPERATIONAL ||
1868 hba->outstanding_tasks || !hba->clk_gating.is_initialized ||
1869 hba->active_uic_cmd || hba->uic_async_done ||
1870 hba->clk_gating.state == CLKS_OFF)
1873 hba->clk_gating.state = REQ_CLKS_OFF;
1874 trace_ufshcd_clk_gating(dev_name(hba->dev), hba->clk_gating.state);
1875 queue_delayed_work(hba->clk_gating.clk_gating_workq,
1876 &hba->clk_gating.gate_work,
1877 msecs_to_jiffies(hba->clk_gating.delay_ms));
1880 void ufshcd_release(struct ufs_hba *hba)
1882 unsigned long flags;
1884 spin_lock_irqsave(hba->host->host_lock, flags);
1885 __ufshcd_release(hba);
1886 spin_unlock_irqrestore(hba->host->host_lock, flags);
1888 EXPORT_SYMBOL_GPL(ufshcd_release);
1890 static ssize_t ufshcd_clkgate_delay_show(struct device *dev,
1891 struct device_attribute *attr, char *buf)
1893 struct ufs_hba *hba = dev_get_drvdata(dev);
1895 return sysfs_emit(buf, "%lu\n", hba->clk_gating.delay_ms);
1898 void ufshcd_clkgate_delay_set(struct device *dev, unsigned long value)
1900 struct ufs_hba *hba = dev_get_drvdata(dev);
1901 unsigned long flags;
1903 spin_lock_irqsave(hba->host->host_lock, flags);
1904 hba->clk_gating.delay_ms = value;
1905 spin_unlock_irqrestore(hba->host->host_lock, flags);
1907 EXPORT_SYMBOL_GPL(ufshcd_clkgate_delay_set);
1909 static ssize_t ufshcd_clkgate_delay_store(struct device *dev,
1910 struct device_attribute *attr, const char *buf, size_t count)
1912 unsigned long value;
1914 if (kstrtoul(buf, 0, &value))
1917 ufshcd_clkgate_delay_set(dev, value);
1921 static ssize_t ufshcd_clkgate_enable_show(struct device *dev,
1922 struct device_attribute *attr, char *buf)
1924 struct ufs_hba *hba = dev_get_drvdata(dev);
1926 return sysfs_emit(buf, "%d\n", hba->clk_gating.is_enabled);
1929 static ssize_t ufshcd_clkgate_enable_store(struct device *dev,
1930 struct device_attribute *attr, const char *buf, size_t count)
1932 struct ufs_hba *hba = dev_get_drvdata(dev);
1933 unsigned long flags;
1936 if (kstrtou32(buf, 0, &value))
1941 spin_lock_irqsave(hba->host->host_lock, flags);
1942 if (value == hba->clk_gating.is_enabled)
1946 __ufshcd_release(hba);
1948 hba->clk_gating.active_reqs++;
1950 hba->clk_gating.is_enabled = value;
1952 spin_unlock_irqrestore(hba->host->host_lock, flags);
1956 static void ufshcd_init_clk_gating_sysfs(struct ufs_hba *hba)
1958 hba->clk_gating.delay_attr.show = ufshcd_clkgate_delay_show;
1959 hba->clk_gating.delay_attr.store = ufshcd_clkgate_delay_store;
1960 sysfs_attr_init(&hba->clk_gating.delay_attr.attr);
1961 hba->clk_gating.delay_attr.attr.name = "clkgate_delay_ms";
1962 hba->clk_gating.delay_attr.attr.mode = 0644;
1963 if (device_create_file(hba->dev, &hba->clk_gating.delay_attr))
1964 dev_err(hba->dev, "Failed to create sysfs for clkgate_delay\n");
1966 hba->clk_gating.enable_attr.show = ufshcd_clkgate_enable_show;
1967 hba->clk_gating.enable_attr.store = ufshcd_clkgate_enable_store;
1968 sysfs_attr_init(&hba->clk_gating.enable_attr.attr);
1969 hba->clk_gating.enable_attr.attr.name = "clkgate_enable";
1970 hba->clk_gating.enable_attr.attr.mode = 0644;
1971 if (device_create_file(hba->dev, &hba->clk_gating.enable_attr))
1972 dev_err(hba->dev, "Failed to create sysfs for clkgate_enable\n");
1975 static void ufshcd_remove_clk_gating_sysfs(struct ufs_hba *hba)
1977 if (hba->clk_gating.delay_attr.attr.name)
1978 device_remove_file(hba->dev, &hba->clk_gating.delay_attr);
1979 if (hba->clk_gating.enable_attr.attr.name)
1980 device_remove_file(hba->dev, &hba->clk_gating.enable_attr);
1983 static void ufshcd_init_clk_gating(struct ufs_hba *hba)
1985 char wq_name[sizeof("ufs_clk_gating_00")];
1987 if (!ufshcd_is_clkgating_allowed(hba))
1990 hba->clk_gating.state = CLKS_ON;
1992 hba->clk_gating.delay_ms = 150;
1993 INIT_DELAYED_WORK(&hba->clk_gating.gate_work, ufshcd_gate_work);
1994 INIT_WORK(&hba->clk_gating.ungate_work, ufshcd_ungate_work);
1996 snprintf(wq_name, ARRAY_SIZE(wq_name), "ufs_clk_gating_%d",
1997 hba->host->host_no);
1998 hba->clk_gating.clk_gating_workq = alloc_ordered_workqueue(wq_name,
1999 WQ_MEM_RECLAIM | WQ_HIGHPRI);
2001 ufshcd_init_clk_gating_sysfs(hba);
2003 hba->clk_gating.is_enabled = true;
2004 hba->clk_gating.is_initialized = true;
2007 static void ufshcd_exit_clk_gating(struct ufs_hba *hba)
2009 if (!hba->clk_gating.is_initialized)
2012 ufshcd_remove_clk_gating_sysfs(hba);
2014 /* Ungate the clock if necessary. */
2015 ufshcd_hold(hba, false);
2016 hba->clk_gating.is_initialized = false;
2017 ufshcd_release(hba);
2019 destroy_workqueue(hba->clk_gating.clk_gating_workq);
2022 static void ufshcd_clk_scaling_start_busy(struct ufs_hba *hba)
2024 bool queue_resume_work = false;
2025 ktime_t curr_t = ktime_get();
2026 unsigned long flags;
2028 if (!ufshcd_is_clkscaling_supported(hba))
2031 spin_lock_irqsave(hba->host->host_lock, flags);
2032 if (!hba->clk_scaling.active_reqs++)
2033 queue_resume_work = true;
2035 if (!hba->clk_scaling.is_enabled || hba->pm_op_in_progress) {
2036 spin_unlock_irqrestore(hba->host->host_lock, flags);
2040 if (queue_resume_work)
2041 queue_work(hba->clk_scaling.workq,
2042 &hba->clk_scaling.resume_work);
2044 if (!hba->clk_scaling.window_start_t) {
2045 hba->clk_scaling.window_start_t = curr_t;
2046 hba->clk_scaling.tot_busy_t = 0;
2047 hba->clk_scaling.is_busy_started = false;
2050 if (!hba->clk_scaling.is_busy_started) {
2051 hba->clk_scaling.busy_start_t = curr_t;
2052 hba->clk_scaling.is_busy_started = true;
2054 spin_unlock_irqrestore(hba->host->host_lock, flags);
2057 static void ufshcd_clk_scaling_update_busy(struct ufs_hba *hba)
2059 struct ufs_clk_scaling *scaling = &hba->clk_scaling;
2060 unsigned long flags;
2062 if (!ufshcd_is_clkscaling_supported(hba))
2065 spin_lock_irqsave(hba->host->host_lock, flags);
2066 hba->clk_scaling.active_reqs--;
2067 if (!hba->outstanding_reqs && scaling->is_busy_started) {
2068 scaling->tot_busy_t += ktime_to_us(ktime_sub(ktime_get(),
2069 scaling->busy_start_t));
2070 scaling->busy_start_t = 0;
2071 scaling->is_busy_started = false;
2073 spin_unlock_irqrestore(hba->host->host_lock, flags);
2076 static inline int ufshcd_monitor_opcode2dir(u8 opcode)
2078 if (opcode == READ_6 || opcode == READ_10 || opcode == READ_16)
2080 else if (opcode == WRITE_6 || opcode == WRITE_10 || opcode == WRITE_16)
2086 static inline bool ufshcd_should_inform_monitor(struct ufs_hba *hba,
2087 struct ufshcd_lrb *lrbp)
2089 const struct ufs_hba_monitor *m = &hba->monitor;
2091 return (m->enabled && lrbp && lrbp->cmd &&
2092 (!m->chunk_size || m->chunk_size == lrbp->cmd->sdb.length) &&
2093 ktime_before(hba->monitor.enabled_ts, lrbp->issue_time_stamp));
2096 static void ufshcd_start_monitor(struct ufs_hba *hba,
2097 const struct ufshcd_lrb *lrbp)
2099 int dir = ufshcd_monitor_opcode2dir(*lrbp->cmd->cmnd);
2100 unsigned long flags;
2102 spin_lock_irqsave(hba->host->host_lock, flags);
2103 if (dir >= 0 && hba->monitor.nr_queued[dir]++ == 0)
2104 hba->monitor.busy_start_ts[dir] = ktime_get();
2105 spin_unlock_irqrestore(hba->host->host_lock, flags);
2108 static void ufshcd_update_monitor(struct ufs_hba *hba, const struct ufshcd_lrb *lrbp)
2110 int dir = ufshcd_monitor_opcode2dir(*lrbp->cmd->cmnd);
2111 unsigned long flags;
2113 spin_lock_irqsave(hba->host->host_lock, flags);
2114 if (dir >= 0 && hba->monitor.nr_queued[dir] > 0) {
2115 const struct request *req = scsi_cmd_to_rq(lrbp->cmd);
2116 struct ufs_hba_monitor *m = &hba->monitor;
2117 ktime_t now, inc, lat;
2119 now = lrbp->compl_time_stamp;
2120 inc = ktime_sub(now, m->busy_start_ts[dir]);
2121 m->total_busy[dir] = ktime_add(m->total_busy[dir], inc);
2122 m->nr_sec_rw[dir] += blk_rq_sectors(req);
2124 /* Update latencies */
2126 lat = ktime_sub(now, lrbp->issue_time_stamp);
2127 m->lat_sum[dir] += lat;
2128 if (m->lat_max[dir] < lat || !m->lat_max[dir])
2129 m->lat_max[dir] = lat;
2130 if (m->lat_min[dir] > lat || !m->lat_min[dir])
2131 m->lat_min[dir] = lat;
2133 m->nr_queued[dir]--;
2134 /* Push forward the busy start of monitor */
2135 m->busy_start_ts[dir] = now;
2137 spin_unlock_irqrestore(hba->host->host_lock, flags);
2141 * ufshcd_send_command - Send SCSI or device management commands
2142 * @hba: per adapter instance
2143 * @task_tag: Task tag of the command
2146 void ufshcd_send_command(struct ufs_hba *hba, unsigned int task_tag)
2148 struct ufshcd_lrb *lrbp = &hba->lrb[task_tag];
2149 unsigned long flags;
2151 lrbp->issue_time_stamp = ktime_get();
2152 lrbp->issue_time_stamp_local_clock = local_clock();
2153 lrbp->compl_time_stamp = ktime_set(0, 0);
2154 lrbp->compl_time_stamp_local_clock = 0;
2155 ufshcd_add_command_trace(hba, task_tag, UFS_CMD_SEND);
2156 ufshcd_clk_scaling_start_busy(hba);
2157 if (unlikely(ufshcd_should_inform_monitor(hba, lrbp)))
2158 ufshcd_start_monitor(hba, lrbp);
2160 spin_lock_irqsave(&hba->outstanding_lock, flags);
2161 if (hba->vops && hba->vops->setup_xfer_req)
2162 hba->vops->setup_xfer_req(hba, task_tag, !!lrbp->cmd);
2163 __set_bit(task_tag, &hba->outstanding_reqs);
2164 ufshcd_writel(hba, 1 << task_tag, REG_UTP_TRANSFER_REQ_DOOR_BELL);
2165 spin_unlock_irqrestore(&hba->outstanding_lock, flags);
2169 * ufshcd_copy_sense_data - Copy sense data in case of check condition
2170 * @lrbp: pointer to local reference block
2172 static inline void ufshcd_copy_sense_data(struct ufshcd_lrb *lrbp)
2174 u8 *const sense_buffer = lrbp->cmd->sense_buffer;
2178 ufshcd_get_rsp_upiu_data_seg_len(lrbp->ucd_rsp_ptr)) {
2181 len = be16_to_cpu(lrbp->ucd_rsp_ptr->sr.sense_data_len);
2182 len_to_copy = min_t(int, UFS_SENSE_SIZE, len);
2184 memcpy(sense_buffer, lrbp->ucd_rsp_ptr->sr.sense_data,
2190 * ufshcd_copy_query_response() - Copy the Query Response and the data
2192 * @hba: per adapter instance
2193 * @lrbp: pointer to local reference block
2196 int ufshcd_copy_query_response(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
2198 struct ufs_query_res *query_res = &hba->dev_cmd.query.response;
2200 memcpy(&query_res->upiu_res, &lrbp->ucd_rsp_ptr->qr, QUERY_OSF_SIZE);
2202 /* Get the descriptor */
2203 if (hba->dev_cmd.query.descriptor &&
2204 lrbp->ucd_rsp_ptr->qr.opcode == UPIU_QUERY_OPCODE_READ_DESC) {
2205 u8 *descp = (u8 *)lrbp->ucd_rsp_ptr +
2206 GENERAL_UPIU_REQUEST_SIZE;
2210 /* data segment length */
2211 resp_len = be32_to_cpu(lrbp->ucd_rsp_ptr->header.dword_2) &
2212 MASK_QUERY_DATA_SEG_LEN;
2213 buf_len = be16_to_cpu(
2214 hba->dev_cmd.query.request.upiu_req.length);
2215 if (likely(buf_len >= resp_len)) {
2216 memcpy(hba->dev_cmd.query.descriptor, descp, resp_len);
2219 "%s: rsp size %d is bigger than buffer size %d",
2220 __func__, resp_len, buf_len);
2229 * ufshcd_hba_capabilities - Read controller capabilities
2230 * @hba: per adapter instance
2232 * Return: 0 on success, negative on error.
2234 static inline int ufshcd_hba_capabilities(struct ufs_hba *hba)
2238 hba->capabilities = ufshcd_readl(hba, REG_CONTROLLER_CAPABILITIES);
2239 if (hba->quirks & UFSHCD_QUIRK_BROKEN_64BIT_ADDRESS)
2240 hba->capabilities &= ~MASK_64_ADDRESSING_SUPPORT;
2242 /* nutrs and nutmrs are 0 based values */
2243 hba->nutrs = (hba->capabilities & MASK_TRANSFER_REQUESTS_SLOTS) + 1;
2245 ((hba->capabilities & MASK_TASK_MANAGEMENT_REQUEST_SLOTS) >> 16) + 1;
2246 hba->reserved_slot = hba->nutrs - 1;
2248 /* Read crypto capabilities */
2249 err = ufshcd_hba_init_crypto_capabilities(hba);
2251 dev_err(hba->dev, "crypto setup failed\n");
2257 * ufshcd_ready_for_uic_cmd - Check if controller is ready
2258 * to accept UIC commands
2259 * @hba: per adapter instance
2260 * Return true on success, else false
2262 static inline bool ufshcd_ready_for_uic_cmd(struct ufs_hba *hba)
2264 return ufshcd_readl(hba, REG_CONTROLLER_STATUS) & UIC_COMMAND_READY;
2268 * ufshcd_get_upmcrs - Get the power mode change request status
2269 * @hba: Pointer to adapter instance
2271 * This function gets the UPMCRS field of HCS register
2272 * Returns value of UPMCRS field
2274 static inline u8 ufshcd_get_upmcrs(struct ufs_hba *hba)
2276 return (ufshcd_readl(hba, REG_CONTROLLER_STATUS) >> 8) & 0x7;
2280 * ufshcd_dispatch_uic_cmd - Dispatch an UIC command to the Unipro layer
2281 * @hba: per adapter instance
2282 * @uic_cmd: UIC command
2285 ufshcd_dispatch_uic_cmd(struct ufs_hba *hba, struct uic_command *uic_cmd)
2287 lockdep_assert_held(&hba->uic_cmd_mutex);
2289 WARN_ON(hba->active_uic_cmd);
2291 hba->active_uic_cmd = uic_cmd;
2294 ufshcd_writel(hba, uic_cmd->argument1, REG_UIC_COMMAND_ARG_1);
2295 ufshcd_writel(hba, uic_cmd->argument2, REG_UIC_COMMAND_ARG_2);
2296 ufshcd_writel(hba, uic_cmd->argument3, REG_UIC_COMMAND_ARG_3);
2298 ufshcd_add_uic_command_trace(hba, uic_cmd, UFS_CMD_SEND);
2301 ufshcd_writel(hba, uic_cmd->command & COMMAND_OPCODE_MASK,
2306 * ufshcd_wait_for_uic_cmd - Wait for completion of an UIC command
2307 * @hba: per adapter instance
2308 * @uic_cmd: UIC command
2310 * Returns 0 only if success.
2313 ufshcd_wait_for_uic_cmd(struct ufs_hba *hba, struct uic_command *uic_cmd)
2316 unsigned long flags;
2318 lockdep_assert_held(&hba->uic_cmd_mutex);
2320 if (wait_for_completion_timeout(&uic_cmd->done,
2321 msecs_to_jiffies(UIC_CMD_TIMEOUT))) {
2322 ret = uic_cmd->argument2 & MASK_UIC_COMMAND_RESULT;
2326 "uic cmd 0x%x with arg3 0x%x completion timeout\n",
2327 uic_cmd->command, uic_cmd->argument3);
2329 if (!uic_cmd->cmd_active) {
2330 dev_err(hba->dev, "%s: UIC cmd has been completed, return the result\n",
2332 ret = uic_cmd->argument2 & MASK_UIC_COMMAND_RESULT;
2336 spin_lock_irqsave(hba->host->host_lock, flags);
2337 hba->active_uic_cmd = NULL;
2338 spin_unlock_irqrestore(hba->host->host_lock, flags);
2344 * __ufshcd_send_uic_cmd - Send UIC commands and retrieve the result
2345 * @hba: per adapter instance
2346 * @uic_cmd: UIC command
2347 * @completion: initialize the completion only if this is set to true
2349 * Returns 0 only if success.
2352 __ufshcd_send_uic_cmd(struct ufs_hba *hba, struct uic_command *uic_cmd,
2355 lockdep_assert_held(&hba->uic_cmd_mutex);
2356 lockdep_assert_held(hba->host->host_lock);
2358 if (!ufshcd_ready_for_uic_cmd(hba)) {
2360 "Controller not ready to accept UIC commands\n");
2365 init_completion(&uic_cmd->done);
2367 uic_cmd->cmd_active = 1;
2368 ufshcd_dispatch_uic_cmd(hba, uic_cmd);
2374 * ufshcd_send_uic_cmd - Send UIC commands and retrieve the result
2375 * @hba: per adapter instance
2376 * @uic_cmd: UIC command
2378 * Returns 0 only if success.
2380 int ufshcd_send_uic_cmd(struct ufs_hba *hba, struct uic_command *uic_cmd)
2383 unsigned long flags;
2385 if (hba->quirks & UFSHCD_QUIRK_BROKEN_UIC_CMD)
2388 ufshcd_hold(hba, false);
2389 mutex_lock(&hba->uic_cmd_mutex);
2390 ufshcd_add_delay_before_dme_cmd(hba);
2392 spin_lock_irqsave(hba->host->host_lock, flags);
2393 ret = __ufshcd_send_uic_cmd(hba, uic_cmd, true);
2394 spin_unlock_irqrestore(hba->host->host_lock, flags);
2396 ret = ufshcd_wait_for_uic_cmd(hba, uic_cmd);
2398 mutex_unlock(&hba->uic_cmd_mutex);
2400 ufshcd_release(hba);
2405 * ufshcd_sgl_to_prdt - SG list to PRTD (Physical Region Description Table, 4DW format)
2406 * @hba: per-adapter instance
2407 * @lrbp: pointer to local reference block
2408 * @sg_entries: The number of sg lists actually used
2409 * @sg_list: Pointer to SG list
2411 static void ufshcd_sgl_to_prdt(struct ufs_hba *hba, struct ufshcd_lrb *lrbp, int sg_entries,
2412 struct scatterlist *sg_list)
2414 struct ufshcd_sg_entry *prd_table;
2415 struct scatterlist *sg;
2420 if (hba->quirks & UFSHCD_QUIRK_PRDT_BYTE_GRAN)
2421 lrbp->utr_descriptor_ptr->prd_table_length =
2422 cpu_to_le16((sg_entries * sizeof(struct ufshcd_sg_entry)));
2424 lrbp->utr_descriptor_ptr->prd_table_length = cpu_to_le16(sg_entries);
2426 prd_table = lrbp->ucd_prdt_ptr;
2428 for_each_sg(sg_list, sg, sg_entries, i) {
2429 const unsigned int len = sg_dma_len(sg);
2432 * From the UFSHCI spec: "Data Byte Count (DBC): A '0'
2433 * based value that indicates the length, in bytes, of
2434 * the data block. A maximum of length of 256KB may
2435 * exist for any entry. Bits 1:0 of this field shall be
2436 * 11b to indicate Dword granularity. A value of '3'
2437 * indicates 4 bytes, '7' indicates 8 bytes, etc."
2439 WARN_ONCE(len > 256 * 1024, "len = %#x\n", len);
2440 prd_table[i].size = cpu_to_le32(len - 1);
2441 prd_table[i].addr = cpu_to_le64(sg->dma_address);
2442 prd_table[i].reserved = 0;
2445 lrbp->utr_descriptor_ptr->prd_table_length = 0;
2450 * ufshcd_map_sg - Map scatter-gather list to prdt
2451 * @hba: per adapter instance
2452 * @lrbp: pointer to local reference block
2454 * Returns 0 in case of success, non-zero value in case of failure
2456 static int ufshcd_map_sg(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
2458 struct scsi_cmnd *cmd = lrbp->cmd;
2459 int sg_segments = scsi_dma_map(cmd);
2461 if (sg_segments < 0)
2464 ufshcd_sgl_to_prdt(hba, lrbp, sg_segments, scsi_sglist(cmd));
2470 * ufshcd_enable_intr - enable interrupts
2471 * @hba: per adapter instance
2472 * @intrs: interrupt bits
2474 static void ufshcd_enable_intr(struct ufs_hba *hba, u32 intrs)
2476 u32 set = ufshcd_readl(hba, REG_INTERRUPT_ENABLE);
2478 if (hba->ufs_version == ufshci_version(1, 0)) {
2480 rw = set & INTERRUPT_MASK_RW_VER_10;
2481 set = rw | ((set ^ intrs) & intrs);
2486 ufshcd_writel(hba, set, REG_INTERRUPT_ENABLE);
2490 * ufshcd_disable_intr - disable interrupts
2491 * @hba: per adapter instance
2492 * @intrs: interrupt bits
2494 static void ufshcd_disable_intr(struct ufs_hba *hba, u32 intrs)
2496 u32 set = ufshcd_readl(hba, REG_INTERRUPT_ENABLE);
2498 if (hba->ufs_version == ufshci_version(1, 0)) {
2500 rw = (set & INTERRUPT_MASK_RW_VER_10) &
2501 ~(intrs & INTERRUPT_MASK_RW_VER_10);
2502 set = rw | ((set & intrs) & ~INTERRUPT_MASK_RW_VER_10);
2508 ufshcd_writel(hba, set, REG_INTERRUPT_ENABLE);
2512 * ufshcd_prepare_req_desc_hdr - Fill UTP Transfer request descriptor header according to request
2513 * descriptor according to request
2514 * @lrbp: pointer to local reference block
2515 * @upiu_flags: flags required in the header
2516 * @cmd_dir: requests data direction
2517 * @ehs_length: Total EHS Length (in 32‐bytes units of all Extra Header Segments)
2519 static void ufshcd_prepare_req_desc_hdr(struct ufshcd_lrb *lrbp, u8 *upiu_flags,
2520 enum dma_data_direction cmd_dir, int ehs_length)
2522 struct utp_transfer_req_desc *req_desc = lrbp->utr_descriptor_ptr;
2528 if (cmd_dir == DMA_FROM_DEVICE) {
2529 data_direction = UTP_DEVICE_TO_HOST;
2530 *upiu_flags = UPIU_CMD_FLAGS_READ;
2531 } else if (cmd_dir == DMA_TO_DEVICE) {
2532 data_direction = UTP_HOST_TO_DEVICE;
2533 *upiu_flags = UPIU_CMD_FLAGS_WRITE;
2535 data_direction = UTP_NO_DATA_TRANSFER;
2536 *upiu_flags = UPIU_CMD_FLAGS_NONE;
2539 dword_0 = data_direction | (lrbp->command_type << UPIU_COMMAND_TYPE_OFFSET) |
2542 dword_0 |= UTP_REQ_DESC_INT_CMD;
2544 /* Prepare crypto related dwords */
2545 ufshcd_prepare_req_desc_hdr_crypto(lrbp, &dword_0, &dword_1, &dword_3);
2547 /* Transfer request descriptor header fields */
2548 req_desc->header.dword_0 = cpu_to_le32(dword_0);
2549 req_desc->header.dword_1 = cpu_to_le32(dword_1);
2551 * assigning invalid value for command status. Controller
2552 * updates OCS on command completion, with the command
2555 req_desc->header.dword_2 =
2556 cpu_to_le32(OCS_INVALID_COMMAND_STATUS);
2557 req_desc->header.dword_3 = cpu_to_le32(dword_3);
2559 req_desc->prd_table_length = 0;
2563 * ufshcd_prepare_utp_scsi_cmd_upiu() - fills the utp_transfer_req_desc,
2565 * @lrbp: local reference block pointer
2566 * @upiu_flags: flags
2569 void ufshcd_prepare_utp_scsi_cmd_upiu(struct ufshcd_lrb *lrbp, u8 upiu_flags)
2571 struct scsi_cmnd *cmd = lrbp->cmd;
2572 struct utp_upiu_req *ucd_req_ptr = lrbp->ucd_req_ptr;
2573 unsigned short cdb_len;
2575 /* command descriptor fields */
2576 ucd_req_ptr->header.dword_0 = UPIU_HEADER_DWORD(
2577 UPIU_TRANSACTION_COMMAND, upiu_flags,
2578 lrbp->lun, lrbp->task_tag);
2579 ucd_req_ptr->header.dword_1 = UPIU_HEADER_DWORD(
2580 UPIU_COMMAND_SET_TYPE_SCSI, 0, 0, 0);
2582 /* Total EHS length and Data segment length will be zero */
2583 ucd_req_ptr->header.dword_2 = 0;
2585 ucd_req_ptr->sc.exp_data_transfer_len = cpu_to_be32(cmd->sdb.length);
2587 cdb_len = min_t(unsigned short, cmd->cmd_len, UFS_CDB_SIZE);
2588 memset(ucd_req_ptr->sc.cdb, 0, UFS_CDB_SIZE);
2589 memcpy(ucd_req_ptr->sc.cdb, cmd->cmnd, cdb_len);
2591 memset(lrbp->ucd_rsp_ptr, 0, sizeof(struct utp_upiu_rsp));
2595 * ufshcd_prepare_utp_query_req_upiu() - fill the utp_transfer_req_desc for query request
2597 * @lrbp: local reference block pointer
2598 * @upiu_flags: flags
2600 static void ufshcd_prepare_utp_query_req_upiu(struct ufs_hba *hba,
2601 struct ufshcd_lrb *lrbp, u8 upiu_flags)
2603 struct utp_upiu_req *ucd_req_ptr = lrbp->ucd_req_ptr;
2604 struct ufs_query *query = &hba->dev_cmd.query;
2605 u16 len = be16_to_cpu(query->request.upiu_req.length);
2607 /* Query request header */
2608 ucd_req_ptr->header.dword_0 = UPIU_HEADER_DWORD(
2609 UPIU_TRANSACTION_QUERY_REQ, upiu_flags,
2610 lrbp->lun, lrbp->task_tag);
2611 ucd_req_ptr->header.dword_1 = UPIU_HEADER_DWORD(
2612 0, query->request.query_func, 0, 0);
2614 /* Data segment length only need for WRITE_DESC */
2615 if (query->request.upiu_req.opcode == UPIU_QUERY_OPCODE_WRITE_DESC)
2616 ucd_req_ptr->header.dword_2 =
2617 UPIU_HEADER_DWORD(0, 0, (len >> 8), (u8)len);
2619 ucd_req_ptr->header.dword_2 = 0;
2621 /* Copy the Query Request buffer as is */
2622 memcpy(&ucd_req_ptr->qr, &query->request.upiu_req,
2625 /* Copy the Descriptor */
2626 if (query->request.upiu_req.opcode == UPIU_QUERY_OPCODE_WRITE_DESC)
2627 memcpy(ucd_req_ptr + 1, query->descriptor, len);
2629 memset(lrbp->ucd_rsp_ptr, 0, sizeof(struct utp_upiu_rsp));
2632 static inline void ufshcd_prepare_utp_nop_upiu(struct ufshcd_lrb *lrbp)
2634 struct utp_upiu_req *ucd_req_ptr = lrbp->ucd_req_ptr;
2636 memset(ucd_req_ptr, 0, sizeof(struct utp_upiu_req));
2638 /* command descriptor fields */
2639 ucd_req_ptr->header.dword_0 =
2641 UPIU_TRANSACTION_NOP_OUT, 0, 0, lrbp->task_tag);
2642 /* clear rest of the fields of basic header */
2643 ucd_req_ptr->header.dword_1 = 0;
2644 ucd_req_ptr->header.dword_2 = 0;
2646 memset(lrbp->ucd_rsp_ptr, 0, sizeof(struct utp_upiu_rsp));
2650 * ufshcd_compose_devman_upiu - UFS Protocol Information Unit(UPIU)
2651 * for Device Management Purposes
2652 * @hba: per adapter instance
2653 * @lrbp: pointer to local reference block
2655 static int ufshcd_compose_devman_upiu(struct ufs_hba *hba,
2656 struct ufshcd_lrb *lrbp)
2661 if (hba->ufs_version <= ufshci_version(1, 1))
2662 lrbp->command_type = UTP_CMD_TYPE_DEV_MANAGE;
2664 lrbp->command_type = UTP_CMD_TYPE_UFS_STORAGE;
2666 ufshcd_prepare_req_desc_hdr(lrbp, &upiu_flags, DMA_NONE, 0);
2667 if (hba->dev_cmd.type == DEV_CMD_TYPE_QUERY)
2668 ufshcd_prepare_utp_query_req_upiu(hba, lrbp, upiu_flags);
2669 else if (hba->dev_cmd.type == DEV_CMD_TYPE_NOP)
2670 ufshcd_prepare_utp_nop_upiu(lrbp);
2678 * ufshcd_comp_scsi_upiu - UFS Protocol Information Unit(UPIU)
2680 * @hba: per adapter instance
2681 * @lrbp: pointer to local reference block
2683 static int ufshcd_comp_scsi_upiu(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
2688 if (hba->ufs_version <= ufshci_version(1, 1))
2689 lrbp->command_type = UTP_CMD_TYPE_SCSI;
2691 lrbp->command_type = UTP_CMD_TYPE_UFS_STORAGE;
2693 if (likely(lrbp->cmd)) {
2694 ufshcd_prepare_req_desc_hdr(lrbp, &upiu_flags, lrbp->cmd->sc_data_direction, 0);
2695 ufshcd_prepare_utp_scsi_cmd_upiu(lrbp, upiu_flags);
2704 * ufshcd_upiu_wlun_to_scsi_wlun - maps UPIU W-LUN id to SCSI W-LUN ID
2705 * @upiu_wlun_id: UPIU W-LUN id
2707 * Returns SCSI W-LUN id
2709 static inline u16 ufshcd_upiu_wlun_to_scsi_wlun(u8 upiu_wlun_id)
2711 return (upiu_wlun_id & ~UFS_UPIU_WLUN_ID) | SCSI_W_LUN_BASE;
2714 static inline bool is_device_wlun(struct scsi_device *sdev)
2717 ufshcd_upiu_wlun_to_scsi_wlun(UFS_UPIU_UFS_DEVICE_WLUN);
2721 * Associate the UFS controller queue with the default and poll HCTX types.
2722 * Initialize the mq_map[] arrays.
2724 static void ufshcd_map_queues(struct Scsi_Host *shost)
2728 for (i = 0; i < shost->nr_maps; i++) {
2729 struct blk_mq_queue_map *map = &shost->tag_set.map[i];
2732 case HCTX_TYPE_DEFAULT:
2733 case HCTX_TYPE_POLL:
2736 case HCTX_TYPE_READ:
2742 map->queue_offset = 0;
2743 blk_mq_map_queues(map);
2747 static void ufshcd_init_lrb(struct ufs_hba *hba, struct ufshcd_lrb *lrb, int i)
2749 struct utp_transfer_cmd_desc *cmd_descp = hba->ucdl_base_addr;
2750 struct utp_transfer_req_desc *utrdlp = hba->utrdl_base_addr;
2751 dma_addr_t cmd_desc_element_addr = hba->ucdl_dma_addr +
2752 i * sizeof(struct utp_transfer_cmd_desc);
2753 u16 response_offset = offsetof(struct utp_transfer_cmd_desc,
2755 u16 prdt_offset = offsetof(struct utp_transfer_cmd_desc, prd_table);
2757 lrb->utr_descriptor_ptr = utrdlp + i;
2758 lrb->utrd_dma_addr = hba->utrdl_dma_addr +
2759 i * sizeof(struct utp_transfer_req_desc);
2760 lrb->ucd_req_ptr = (struct utp_upiu_req *)(cmd_descp + i);
2761 lrb->ucd_req_dma_addr = cmd_desc_element_addr;
2762 lrb->ucd_rsp_ptr = (struct utp_upiu_rsp *)cmd_descp[i].response_upiu;
2763 lrb->ucd_rsp_dma_addr = cmd_desc_element_addr + response_offset;
2764 lrb->ucd_prdt_ptr = cmd_descp[i].prd_table;
2765 lrb->ucd_prdt_dma_addr = cmd_desc_element_addr + prdt_offset;
2769 * ufshcd_queuecommand - main entry point for SCSI requests
2770 * @host: SCSI host pointer
2771 * @cmd: command from SCSI Midlayer
2773 * Returns 0 for success, non-zero in case of failure
2775 static int ufshcd_queuecommand(struct Scsi_Host *host, struct scsi_cmnd *cmd)
2777 struct ufs_hba *hba = shost_priv(host);
2778 int tag = scsi_cmd_to_rq(cmd)->tag;
2779 struct ufshcd_lrb *lrbp;
2782 WARN_ONCE(tag < 0 || tag >= hba->nutrs, "Invalid tag %d\n", tag);
2785 * Allows the UFS error handler to wait for prior ufshcd_queuecommand()
2790 switch (hba->ufshcd_state) {
2791 case UFSHCD_STATE_OPERATIONAL:
2793 case UFSHCD_STATE_EH_SCHEDULED_NON_FATAL:
2795 * SCSI error handler can call ->queuecommand() while UFS error
2796 * handler is in progress. Error interrupts could change the
2797 * state from UFSHCD_STATE_RESET to
2798 * UFSHCD_STATE_EH_SCHEDULED_NON_FATAL. Prevent requests
2799 * being issued in that case.
2801 if (ufshcd_eh_in_progress(hba)) {
2802 err = SCSI_MLQUEUE_HOST_BUSY;
2806 case UFSHCD_STATE_EH_SCHEDULED_FATAL:
2808 * pm_runtime_get_sync() is used at error handling preparation
2809 * stage. If a scsi cmd, e.g. the SSU cmd, is sent from hba's
2810 * PM ops, it can never be finished if we let SCSI layer keep
2811 * retrying it, which gets err handler stuck forever. Neither
2812 * can we let the scsi cmd pass through, because UFS is in bad
2813 * state, the scsi cmd may eventually time out, which will get
2814 * err handler blocked for too long. So, just fail the scsi cmd
2815 * sent from PM ops, err handler can recover PM error anyways.
2817 if (hba->pm_op_in_progress) {
2818 hba->force_reset = true;
2819 set_host_byte(cmd, DID_BAD_TARGET);
2824 case UFSHCD_STATE_RESET:
2825 err = SCSI_MLQUEUE_HOST_BUSY;
2827 case UFSHCD_STATE_ERROR:
2828 set_host_byte(cmd, DID_ERROR);
2833 hba->req_abort_count = 0;
2835 err = ufshcd_hold(hba, true);
2837 err = SCSI_MLQUEUE_HOST_BUSY;
2840 WARN_ON(ufshcd_is_clkgating_allowed(hba) &&
2841 (hba->clk_gating.state != CLKS_ON));
2843 lrbp = &hba->lrb[tag];
2846 lrbp->task_tag = tag;
2847 lrbp->lun = ufshcd_scsi_to_upiu_lun(cmd->device->lun);
2848 lrbp->intr_cmd = !ufshcd_is_intr_aggr_allowed(hba);
2850 ufshcd_prepare_lrbp_crypto(scsi_cmd_to_rq(cmd), lrbp);
2852 lrbp->req_abort_skip = false;
2854 ufshpb_prep(hba, lrbp);
2856 ufshcd_comp_scsi_upiu(hba, lrbp);
2858 err = ufshcd_map_sg(hba, lrbp);
2861 ufshcd_release(hba);
2865 ufshcd_send_command(hba, tag);
2870 if (ufs_trigger_eh()) {
2871 unsigned long flags;
2873 spin_lock_irqsave(hba->host->host_lock, flags);
2874 ufshcd_schedule_eh_work(hba);
2875 spin_unlock_irqrestore(hba->host->host_lock, flags);
2881 static int ufshcd_compose_dev_cmd(struct ufs_hba *hba,
2882 struct ufshcd_lrb *lrbp, enum dev_cmd_type cmd_type, int tag)
2885 lrbp->task_tag = tag;
2886 lrbp->lun = 0; /* device management cmd is not specific to any LUN */
2887 lrbp->intr_cmd = true; /* No interrupt aggregation */
2888 ufshcd_prepare_lrbp_crypto(NULL, lrbp);
2889 hba->dev_cmd.type = cmd_type;
2891 return ufshcd_compose_devman_upiu(hba, lrbp);
2895 * Clear all the requests from the controller for which a bit has been set in
2896 * @mask and wait until the controller confirms that these requests have been
2899 static int ufshcd_clear_cmds(struct ufs_hba *hba, u32 mask)
2901 unsigned long flags;
2903 /* clear outstanding transaction before retry */
2904 spin_lock_irqsave(hba->host->host_lock, flags);
2905 ufshcd_utrl_clear(hba, mask);
2906 spin_unlock_irqrestore(hba->host->host_lock, flags);
2909 * wait for h/w to clear corresponding bit in door-bell.
2910 * max. wait is 1 sec.
2912 return ufshcd_wait_for_register(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL,
2913 mask, ~mask, 1000, 1000);
2917 ufshcd_check_query_response(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
2919 struct ufs_query_res *query_res = &hba->dev_cmd.query.response;
2921 /* Get the UPIU response */
2922 query_res->response = ufshcd_get_rsp_upiu_result(lrbp->ucd_rsp_ptr) >>
2923 UPIU_RSP_CODE_OFFSET;
2924 return query_res->response;
2928 * ufshcd_dev_cmd_completion() - handles device management command responses
2929 * @hba: per adapter instance
2930 * @lrbp: pointer to local reference block
2933 ufshcd_dev_cmd_completion(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
2938 hba->ufs_stats.last_hibern8_exit_tstamp = ktime_set(0, 0);
2939 resp = ufshcd_get_req_rsp(lrbp->ucd_rsp_ptr);
2942 case UPIU_TRANSACTION_NOP_IN:
2943 if (hba->dev_cmd.type != DEV_CMD_TYPE_NOP) {
2945 dev_err(hba->dev, "%s: unexpected response %x\n",
2949 case UPIU_TRANSACTION_QUERY_RSP:
2950 err = ufshcd_check_query_response(hba, lrbp);
2952 err = ufshcd_copy_query_response(hba, lrbp);
2954 case UPIU_TRANSACTION_REJECT_UPIU:
2955 /* TODO: handle Reject UPIU Response */
2957 dev_err(hba->dev, "%s: Reject UPIU not fully implemented\n",
2960 case UPIU_TRANSACTION_RESPONSE:
2961 if (hba->dev_cmd.type != DEV_CMD_TYPE_RPMB) {
2963 dev_err(hba->dev, "%s: unexpected response %x\n", __func__, resp);
2968 dev_err(hba->dev, "%s: Invalid device management cmd response: %x\n",
2976 static int ufshcd_wait_for_dev_cmd(struct ufs_hba *hba,
2977 struct ufshcd_lrb *lrbp, int max_timeout)
2979 unsigned long time_left = msecs_to_jiffies(max_timeout);
2980 unsigned long flags;
2985 time_left = wait_for_completion_timeout(hba->dev_cmd.complete,
2988 if (likely(time_left)) {
2990 * The completion handler called complete() and the caller of
2991 * this function still owns the @lrbp tag so the code below does
2992 * not trigger any race conditions.
2994 hba->dev_cmd.complete = NULL;
2995 err = ufshcd_get_tr_ocs(lrbp);
2997 err = ufshcd_dev_cmd_completion(hba, lrbp);
3000 dev_dbg(hba->dev, "%s: dev_cmd request timedout, tag %d\n",
3001 __func__, lrbp->task_tag);
3002 if (ufshcd_clear_cmds(hba, 1U << lrbp->task_tag) == 0) {
3003 /* successfully cleared the command, retry if needed */
3006 * Since clearing the command succeeded we also need to
3007 * clear the task tag bit from the outstanding_reqs
3010 spin_lock_irqsave(&hba->outstanding_lock, flags);
3011 pending = test_bit(lrbp->task_tag,
3012 &hba->outstanding_reqs);
3014 hba->dev_cmd.complete = NULL;
3015 __clear_bit(lrbp->task_tag,
3016 &hba->outstanding_reqs);
3018 spin_unlock_irqrestore(&hba->outstanding_lock, flags);
3022 * The completion handler ran while we tried to
3023 * clear the command.
3029 dev_err(hba->dev, "%s: failed to clear tag %d\n",
3030 __func__, lrbp->task_tag);
3038 * ufshcd_exec_dev_cmd - API for sending device management requests
3040 * @cmd_type: specifies the type (NOP, Query...)
3041 * @timeout: timeout in milliseconds
3043 * NOTE: Since there is only one available tag for device management commands,
3044 * it is expected you hold the hba->dev_cmd.lock mutex.
3046 static int ufshcd_exec_dev_cmd(struct ufs_hba *hba,
3047 enum dev_cmd_type cmd_type, int timeout)
3049 DECLARE_COMPLETION_ONSTACK(wait);
3050 const u32 tag = hba->reserved_slot;
3051 struct ufshcd_lrb *lrbp;
3054 /* Protects use of hba->reserved_slot. */
3055 lockdep_assert_held(&hba->dev_cmd.lock);
3057 down_read(&hba->clk_scaling_lock);
3059 lrbp = &hba->lrb[tag];
3061 err = ufshcd_compose_dev_cmd(hba, lrbp, cmd_type, tag);
3065 hba->dev_cmd.complete = &wait;
3067 ufshcd_add_query_upiu_trace(hba, UFS_QUERY_SEND, lrbp->ucd_req_ptr);
3069 ufshcd_send_command(hba, tag);
3070 err = ufshcd_wait_for_dev_cmd(hba, lrbp, timeout);
3071 ufshcd_add_query_upiu_trace(hba, err ? UFS_QUERY_ERR : UFS_QUERY_COMP,
3072 (struct utp_upiu_req *)lrbp->ucd_rsp_ptr);
3075 up_read(&hba->clk_scaling_lock);
3080 * ufshcd_init_query() - init the query response and request parameters
3081 * @hba: per-adapter instance
3082 * @request: address of the request pointer to be initialized
3083 * @response: address of the response pointer to be initialized
3084 * @opcode: operation to perform
3085 * @idn: flag idn to access
3086 * @index: LU number to access
3087 * @selector: query/flag/descriptor further identification
3089 static inline void ufshcd_init_query(struct ufs_hba *hba,
3090 struct ufs_query_req **request, struct ufs_query_res **response,
3091 enum query_opcode opcode, u8 idn, u8 index, u8 selector)
3093 *request = &hba->dev_cmd.query.request;
3094 *response = &hba->dev_cmd.query.response;
3095 memset(*request, 0, sizeof(struct ufs_query_req));
3096 memset(*response, 0, sizeof(struct ufs_query_res));
3097 (*request)->upiu_req.opcode = opcode;
3098 (*request)->upiu_req.idn = idn;
3099 (*request)->upiu_req.index = index;
3100 (*request)->upiu_req.selector = selector;
3103 static int ufshcd_query_flag_retry(struct ufs_hba *hba,
3104 enum query_opcode opcode, enum flag_idn idn, u8 index, bool *flag_res)
3109 for (retries = 0; retries < QUERY_REQ_RETRIES; retries++) {
3110 ret = ufshcd_query_flag(hba, opcode, idn, index, flag_res);
3113 "%s: failed with error %d, retries %d\n",
3114 __func__, ret, retries);
3121 "%s: query flag, opcode %d, idn %d, failed with error %d after %d retries\n",
3122 __func__, opcode, idn, ret, retries);
3127 * ufshcd_query_flag() - API function for sending flag query requests
3128 * @hba: per-adapter instance
3129 * @opcode: flag query to perform
3130 * @idn: flag idn to access
3131 * @index: flag index to access
3132 * @flag_res: the flag value after the query request completes
3134 * Returns 0 for success, non-zero in case of failure
3136 int ufshcd_query_flag(struct ufs_hba *hba, enum query_opcode opcode,
3137 enum flag_idn idn, u8 index, bool *flag_res)
3139 struct ufs_query_req *request = NULL;
3140 struct ufs_query_res *response = NULL;
3141 int err, selector = 0;
3142 int timeout = QUERY_REQ_TIMEOUT;
3146 ufshcd_hold(hba, false);
3147 mutex_lock(&hba->dev_cmd.lock);
3148 ufshcd_init_query(hba, &request, &response, opcode, idn, index,
3152 case UPIU_QUERY_OPCODE_SET_FLAG:
3153 case UPIU_QUERY_OPCODE_CLEAR_FLAG:
3154 case UPIU_QUERY_OPCODE_TOGGLE_FLAG:
3155 request->query_func = UPIU_QUERY_FUNC_STANDARD_WRITE_REQUEST;
3157 case UPIU_QUERY_OPCODE_READ_FLAG:
3158 request->query_func = UPIU_QUERY_FUNC_STANDARD_READ_REQUEST;
3160 /* No dummy reads */
3161 dev_err(hba->dev, "%s: Invalid argument for read request\n",
3169 "%s: Expected query flag opcode but got = %d\n",
3175 err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_QUERY, timeout);
3179 "%s: Sending flag query for idn %d failed, err = %d\n",
3180 __func__, idn, err);
3185 *flag_res = (be32_to_cpu(response->upiu_res.value) &
3186 MASK_QUERY_UPIU_FLAG_LOC) & 0x1;
3189 mutex_unlock(&hba->dev_cmd.lock);
3190 ufshcd_release(hba);
3195 * ufshcd_query_attr - API function for sending attribute requests
3196 * @hba: per-adapter instance
3197 * @opcode: attribute opcode
3198 * @idn: attribute idn to access
3199 * @index: index field
3200 * @selector: selector field
3201 * @attr_val: the attribute value after the query request completes
3203 * Returns 0 for success, non-zero in case of failure
3205 int ufshcd_query_attr(struct ufs_hba *hba, enum query_opcode opcode,
3206 enum attr_idn idn, u8 index, u8 selector, u32 *attr_val)
3208 struct ufs_query_req *request = NULL;
3209 struct ufs_query_res *response = NULL;
3215 dev_err(hba->dev, "%s: attribute value required for opcode 0x%x\n",
3220 ufshcd_hold(hba, false);
3222 mutex_lock(&hba->dev_cmd.lock);
3223 ufshcd_init_query(hba, &request, &response, opcode, idn, index,
3227 case UPIU_QUERY_OPCODE_WRITE_ATTR:
3228 request->query_func = UPIU_QUERY_FUNC_STANDARD_WRITE_REQUEST;
3229 request->upiu_req.value = cpu_to_be32(*attr_val);
3231 case UPIU_QUERY_OPCODE_READ_ATTR:
3232 request->query_func = UPIU_QUERY_FUNC_STANDARD_READ_REQUEST;
3235 dev_err(hba->dev, "%s: Expected query attr opcode but got = 0x%.2x\n",
3241 err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_QUERY, QUERY_REQ_TIMEOUT);
3244 dev_err(hba->dev, "%s: opcode 0x%.2x for idn %d failed, index %d, err = %d\n",
3245 __func__, opcode, idn, index, err);
3249 *attr_val = be32_to_cpu(response->upiu_res.value);
3252 mutex_unlock(&hba->dev_cmd.lock);
3253 ufshcd_release(hba);
3258 * ufshcd_query_attr_retry() - API function for sending query
3259 * attribute with retries
3260 * @hba: per-adapter instance
3261 * @opcode: attribute opcode
3262 * @idn: attribute idn to access
3263 * @index: index field
3264 * @selector: selector field
3265 * @attr_val: the attribute value after the query request
3268 * Returns 0 for success, non-zero in case of failure
3270 int ufshcd_query_attr_retry(struct ufs_hba *hba,
3271 enum query_opcode opcode, enum attr_idn idn, u8 index, u8 selector,
3277 for (retries = QUERY_REQ_RETRIES; retries > 0; retries--) {
3278 ret = ufshcd_query_attr(hba, opcode, idn, index,
3279 selector, attr_val);
3281 dev_dbg(hba->dev, "%s: failed with error %d, retries %d\n",
3282 __func__, ret, retries);
3289 "%s: query attribute, idn %d, failed with error %d after %d retries\n",
3290 __func__, idn, ret, QUERY_REQ_RETRIES);
3294 static int __ufshcd_query_descriptor(struct ufs_hba *hba,
3295 enum query_opcode opcode, enum desc_idn idn, u8 index,
3296 u8 selector, u8 *desc_buf, int *buf_len)
3298 struct ufs_query_req *request = NULL;
3299 struct ufs_query_res *response = NULL;
3305 dev_err(hba->dev, "%s: descriptor buffer required for opcode 0x%x\n",
3310 if (*buf_len < QUERY_DESC_MIN_SIZE || *buf_len > QUERY_DESC_MAX_SIZE) {
3311 dev_err(hba->dev, "%s: descriptor buffer size (%d) is out of range\n",
3312 __func__, *buf_len);
3316 ufshcd_hold(hba, false);
3318 mutex_lock(&hba->dev_cmd.lock);
3319 ufshcd_init_query(hba, &request, &response, opcode, idn, index,
3321 hba->dev_cmd.query.descriptor = desc_buf;
3322 request->upiu_req.length = cpu_to_be16(*buf_len);
3325 case UPIU_QUERY_OPCODE_WRITE_DESC:
3326 request->query_func = UPIU_QUERY_FUNC_STANDARD_WRITE_REQUEST;
3328 case UPIU_QUERY_OPCODE_READ_DESC:
3329 request->query_func = UPIU_QUERY_FUNC_STANDARD_READ_REQUEST;
3333 "%s: Expected query descriptor opcode but got = 0x%.2x\n",
3339 err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_QUERY, QUERY_REQ_TIMEOUT);
3342 dev_err(hba->dev, "%s: opcode 0x%.2x for idn %d failed, index %d, err = %d\n",
3343 __func__, opcode, idn, index, err);
3347 *buf_len = be16_to_cpu(response->upiu_res.length);
3350 hba->dev_cmd.query.descriptor = NULL;
3351 mutex_unlock(&hba->dev_cmd.lock);
3352 ufshcd_release(hba);
3357 * ufshcd_query_descriptor_retry - API function for sending descriptor requests
3358 * @hba: per-adapter instance
3359 * @opcode: attribute opcode
3360 * @idn: attribute idn to access
3361 * @index: index field
3362 * @selector: selector field
3363 * @desc_buf: the buffer that contains the descriptor
3364 * @buf_len: length parameter passed to the device
3366 * Returns 0 for success, non-zero in case of failure.
3367 * The buf_len parameter will contain, on return, the length parameter
3368 * received on the response.
3370 int ufshcd_query_descriptor_retry(struct ufs_hba *hba,
3371 enum query_opcode opcode,
3372 enum desc_idn idn, u8 index,
3374 u8 *desc_buf, int *buf_len)
3379 for (retries = QUERY_REQ_RETRIES; retries > 0; retries--) {
3380 err = __ufshcd_query_descriptor(hba, opcode, idn, index,
3381 selector, desc_buf, buf_len);
3382 if (!err || err == -EINVAL)
3390 * ufshcd_map_desc_id_to_length - map descriptor IDN to its length
3391 * @hba: Pointer to adapter instance
3392 * @desc_id: descriptor idn value
3393 * @desc_len: mapped desc length (out)
3395 void ufshcd_map_desc_id_to_length(struct ufs_hba *hba, enum desc_idn desc_id,
3398 if (desc_id >= QUERY_DESC_IDN_MAX || desc_id == QUERY_DESC_IDN_RFU_0 ||
3399 desc_id == QUERY_DESC_IDN_RFU_1)
3402 *desc_len = hba->desc_size[desc_id];
3404 EXPORT_SYMBOL(ufshcd_map_desc_id_to_length);
3406 static void ufshcd_update_desc_length(struct ufs_hba *hba,
3407 enum desc_idn desc_id, int desc_index,
3408 unsigned char desc_len)
3410 if (hba->desc_size[desc_id] == QUERY_DESC_MAX_SIZE &&
3411 desc_id != QUERY_DESC_IDN_STRING && desc_index != UFS_RPMB_UNIT)
3412 /* For UFS 3.1, the normal unit descriptor is 10 bytes larger
3413 * than the RPMB unit, however, both descriptors share the same
3414 * desc_idn, to cover both unit descriptors with one length, we
3415 * choose the normal unit descriptor length by desc_index.
3417 hba->desc_size[desc_id] = desc_len;
3421 * ufshcd_read_desc_param - read the specified descriptor parameter
3422 * @hba: Pointer to adapter instance
3423 * @desc_id: descriptor idn value
3424 * @desc_index: descriptor index
3425 * @param_offset: offset of the parameter to read
3426 * @param_read_buf: pointer to buffer where parameter would be read
3427 * @param_size: sizeof(param_read_buf)
3429 * Return 0 in case of success, non-zero otherwise
3431 int ufshcd_read_desc_param(struct ufs_hba *hba,
3432 enum desc_idn desc_id,
3441 bool is_kmalloc = true;
3444 if (desc_id >= QUERY_DESC_IDN_MAX || !param_size)
3447 /* Get the length of descriptor */
3448 ufshcd_map_desc_id_to_length(hba, desc_id, &buff_len);
3450 dev_err(hba->dev, "%s: Failed to get desc length\n", __func__);
3454 if (param_offset >= buff_len) {
3455 dev_err(hba->dev, "%s: Invalid offset 0x%x in descriptor IDN 0x%x, length 0x%x\n",
3456 __func__, param_offset, desc_id, buff_len);
3460 /* Check whether we need temp memory */
3461 if (param_offset != 0 || param_size < buff_len) {
3462 desc_buf = kzalloc(buff_len, GFP_KERNEL);
3466 desc_buf = param_read_buf;
3470 /* Request for full descriptor */
3471 ret = ufshcd_query_descriptor_retry(hba, UPIU_QUERY_OPCODE_READ_DESC,
3472 desc_id, desc_index, 0,
3473 desc_buf, &buff_len);
3476 dev_err(hba->dev, "%s: Failed reading descriptor. desc_id %d, desc_index %d, param_offset %d, ret %d\n",
3477 __func__, desc_id, desc_index, param_offset, ret);
3482 if (desc_buf[QUERY_DESC_DESC_TYPE_OFFSET] != desc_id) {
3483 dev_err(hba->dev, "%s: invalid desc_id %d in descriptor header\n",
3484 __func__, desc_buf[QUERY_DESC_DESC_TYPE_OFFSET]);
3489 /* Update descriptor length */
3490 buff_len = desc_buf[QUERY_DESC_LENGTH_OFFSET];
3491 ufshcd_update_desc_length(hba, desc_id, desc_index, buff_len);
3494 /* Make sure we don't copy more data than available */
3495 if (param_offset >= buff_len)
3498 memcpy(param_read_buf, &desc_buf[param_offset],
3499 min_t(u32, param_size, buff_len - param_offset));
3508 * struct uc_string_id - unicode string
3510 * @len: size of this descriptor inclusive
3511 * @type: descriptor type
3512 * @uc: unicode string character
3514 struct uc_string_id {
3520 /* replace non-printable or non-ASCII characters with spaces */
3521 static inline char ufshcd_remove_non_printable(u8 ch)
3523 return (ch >= 0x20 && ch <= 0x7e) ? ch : ' ';
3527 * ufshcd_read_string_desc - read string descriptor
3528 * @hba: pointer to adapter instance
3529 * @desc_index: descriptor index
3530 * @buf: pointer to buffer where descriptor would be read,
3531 * the caller should free the memory.
3532 * @ascii: if true convert from unicode to ascii characters
3533 * null terminated string.
3536 * * string size on success.
3537 * * -ENOMEM: on allocation failure
3538 * * -EINVAL: on a wrong parameter
3540 int ufshcd_read_string_desc(struct ufs_hba *hba, u8 desc_index,
3541 u8 **buf, bool ascii)
3543 struct uc_string_id *uc_str;
3550 uc_str = kzalloc(QUERY_DESC_MAX_SIZE, GFP_KERNEL);
3554 ret = ufshcd_read_desc_param(hba, QUERY_DESC_IDN_STRING, desc_index, 0,
3555 (u8 *)uc_str, QUERY_DESC_MAX_SIZE);
3557 dev_err(hba->dev, "Reading String Desc failed after %d retries. err = %d\n",
3558 QUERY_REQ_RETRIES, ret);
3563 if (uc_str->len <= QUERY_DESC_HDR_SIZE) {
3564 dev_dbg(hba->dev, "String Desc is of zero length\n");
3573 /* remove header and divide by 2 to move from UTF16 to UTF8 */
3574 ascii_len = (uc_str->len - QUERY_DESC_HDR_SIZE) / 2 + 1;
3575 str = kzalloc(ascii_len, GFP_KERNEL);
3582 * the descriptor contains string in UTF16 format
3583 * we need to convert to utf-8 so it can be displayed
3585 ret = utf16s_to_utf8s(uc_str->uc,
3586 uc_str->len - QUERY_DESC_HDR_SIZE,
3587 UTF16_BIG_ENDIAN, str, ascii_len);
3589 /* replace non-printable or non-ASCII characters with spaces */
3590 for (i = 0; i < ret; i++)
3591 str[i] = ufshcd_remove_non_printable(str[i]);
3596 str = kmemdup(uc_str, uc_str->len, GFP_KERNEL);
3610 * ufshcd_read_unit_desc_param - read the specified unit descriptor parameter
3611 * @hba: Pointer to adapter instance
3613 * @param_offset: offset of the parameter to read
3614 * @param_read_buf: pointer to buffer where parameter would be read
3615 * @param_size: sizeof(param_read_buf)
3617 * Return 0 in case of success, non-zero otherwise
3619 static inline int ufshcd_read_unit_desc_param(struct ufs_hba *hba,
3621 enum unit_desc_param param_offset,
3626 * Unit descriptors are only available for general purpose LUs (LUN id
3627 * from 0 to 7) and RPMB Well known LU.
3629 if (!ufs_is_valid_unit_desc_lun(&hba->dev_info, lun))
3632 return ufshcd_read_desc_param(hba, QUERY_DESC_IDN_UNIT, lun,
3633 param_offset, param_read_buf, param_size);
3636 static int ufshcd_get_ref_clk_gating_wait(struct ufs_hba *hba)
3639 u32 gating_wait = UFSHCD_REF_CLK_GATING_WAIT_US;
3641 if (hba->dev_info.wspecversion >= 0x300) {
3642 err = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
3643 QUERY_ATTR_IDN_REF_CLK_GATING_WAIT_TIME, 0, 0,
3646 dev_err(hba->dev, "Failed reading bRefClkGatingWait. err = %d, use default %uus\n",
3649 if (gating_wait == 0) {
3650 gating_wait = UFSHCD_REF_CLK_GATING_WAIT_US;
3651 dev_err(hba->dev, "Undefined ref clk gating wait time, use default %uus\n",
3655 hba->dev_info.clk_gating_wait_us = gating_wait;
3662 * ufshcd_memory_alloc - allocate memory for host memory space data structures
3663 * @hba: per adapter instance
3665 * 1. Allocate DMA memory for Command Descriptor array
3666 * Each command descriptor consist of Command UPIU, Response UPIU and PRDT
3667 * 2. Allocate DMA memory for UTP Transfer Request Descriptor List (UTRDL).
3668 * 3. Allocate DMA memory for UTP Task Management Request Descriptor List
3670 * 4. Allocate memory for local reference block(lrb).
3672 * Returns 0 for success, non-zero in case of failure
3674 static int ufshcd_memory_alloc(struct ufs_hba *hba)
3676 size_t utmrdl_size, utrdl_size, ucdl_size;
3678 /* Allocate memory for UTP command descriptors */
3679 ucdl_size = (sizeof(struct utp_transfer_cmd_desc) * hba->nutrs);
3680 hba->ucdl_base_addr = dmam_alloc_coherent(hba->dev,
3682 &hba->ucdl_dma_addr,
3686 * UFSHCI requires UTP command descriptor to be 128 byte aligned.
3687 * make sure hba->ucdl_dma_addr is aligned to PAGE_SIZE
3688 * if hba->ucdl_dma_addr is aligned to PAGE_SIZE, then it will
3689 * be aligned to 128 bytes as well
3691 if (!hba->ucdl_base_addr ||
3692 WARN_ON(hba->ucdl_dma_addr & (PAGE_SIZE - 1))) {
3694 "Command Descriptor Memory allocation failed\n");
3699 * Allocate memory for UTP Transfer descriptors
3700 * UFSHCI requires 1024 byte alignment of UTRD
3702 utrdl_size = (sizeof(struct utp_transfer_req_desc) * hba->nutrs);
3703 hba->utrdl_base_addr = dmam_alloc_coherent(hba->dev,
3705 &hba->utrdl_dma_addr,
3707 if (!hba->utrdl_base_addr ||
3708 WARN_ON(hba->utrdl_dma_addr & (PAGE_SIZE - 1))) {
3710 "Transfer Descriptor Memory allocation failed\n");
3715 * Allocate memory for UTP Task Management descriptors
3716 * UFSHCI requires 1024 byte alignment of UTMRD
3718 utmrdl_size = sizeof(struct utp_task_req_desc) * hba->nutmrs;
3719 hba->utmrdl_base_addr = dmam_alloc_coherent(hba->dev,
3721 &hba->utmrdl_dma_addr,
3723 if (!hba->utmrdl_base_addr ||
3724 WARN_ON(hba->utmrdl_dma_addr & (PAGE_SIZE - 1))) {
3726 "Task Management Descriptor Memory allocation failed\n");
3730 /* Allocate memory for local reference block */
3731 hba->lrb = devm_kcalloc(hba->dev,
3732 hba->nutrs, sizeof(struct ufshcd_lrb),
3735 dev_err(hba->dev, "LRB Memory allocation failed\n");
3744 * ufshcd_host_memory_configure - configure local reference block with
3746 * @hba: per adapter instance
3748 * Configure Host memory space
3749 * 1. Update Corresponding UTRD.UCDBA and UTRD.UCDBAU with UCD DMA
3751 * 2. Update each UTRD with Response UPIU offset, Response UPIU length
3753 * 3. Save the corresponding addresses of UTRD, UCD.CMD, UCD.RSP and UCD.PRDT
3754 * into local reference block.
3756 static void ufshcd_host_memory_configure(struct ufs_hba *hba)
3758 struct utp_transfer_req_desc *utrdlp;
3759 dma_addr_t cmd_desc_dma_addr;
3760 dma_addr_t cmd_desc_element_addr;
3761 u16 response_offset;
3766 utrdlp = hba->utrdl_base_addr;
3769 offsetof(struct utp_transfer_cmd_desc, response_upiu);
3771 offsetof(struct utp_transfer_cmd_desc, prd_table);
3773 cmd_desc_size = sizeof(struct utp_transfer_cmd_desc);
3774 cmd_desc_dma_addr = hba->ucdl_dma_addr;
3776 for (i = 0; i < hba->nutrs; i++) {
3777 /* Configure UTRD with command descriptor base address */
3778 cmd_desc_element_addr =
3779 (cmd_desc_dma_addr + (cmd_desc_size * i));
3780 utrdlp[i].command_desc_base_addr_lo =
3781 cpu_to_le32(lower_32_bits(cmd_desc_element_addr));
3782 utrdlp[i].command_desc_base_addr_hi =
3783 cpu_to_le32(upper_32_bits(cmd_desc_element_addr));
3785 /* Response upiu and prdt offset should be in double words */
3786 if (hba->quirks & UFSHCD_QUIRK_PRDT_BYTE_GRAN) {
3787 utrdlp[i].response_upiu_offset =
3788 cpu_to_le16(response_offset);
3789 utrdlp[i].prd_table_offset =
3790 cpu_to_le16(prdt_offset);
3791 utrdlp[i].response_upiu_length =
3792 cpu_to_le16(ALIGNED_UPIU_SIZE);
3794 utrdlp[i].response_upiu_offset =
3795 cpu_to_le16(response_offset >> 2);
3796 utrdlp[i].prd_table_offset =
3797 cpu_to_le16(prdt_offset >> 2);
3798 utrdlp[i].response_upiu_length =
3799 cpu_to_le16(ALIGNED_UPIU_SIZE >> 2);
3802 ufshcd_init_lrb(hba, &hba->lrb[i], i);
3807 * ufshcd_dme_link_startup - Notify Unipro to perform link startup
3808 * @hba: per adapter instance
3810 * UIC_CMD_DME_LINK_STARTUP command must be issued to Unipro layer,
3811 * in order to initialize the Unipro link startup procedure.
3812 * Once the Unipro links are up, the device connected to the controller
3815 * Returns 0 on success, non-zero value on failure
3817 static int ufshcd_dme_link_startup(struct ufs_hba *hba)
3819 struct uic_command uic_cmd = {0};
3822 uic_cmd.command = UIC_CMD_DME_LINK_STARTUP;
3824 ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
3827 "dme-link-startup: error code %d\n", ret);
3831 * ufshcd_dme_reset - UIC command for DME_RESET
3832 * @hba: per adapter instance
3834 * DME_RESET command is issued in order to reset UniPro stack.
3835 * This function now deals with cold reset.
3837 * Returns 0 on success, non-zero value on failure
3839 static int ufshcd_dme_reset(struct ufs_hba *hba)
3841 struct uic_command uic_cmd = {0};
3844 uic_cmd.command = UIC_CMD_DME_RESET;
3846 ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
3849 "dme-reset: error code %d\n", ret);
3854 int ufshcd_dme_configure_adapt(struct ufs_hba *hba,
3860 if (agreed_gear < UFS_HS_G4)
3861 adapt_val = PA_NO_ADAPT;
3863 ret = ufshcd_dme_set(hba,
3864 UIC_ARG_MIB(PA_TXHSADAPTTYPE),
3868 EXPORT_SYMBOL_GPL(ufshcd_dme_configure_adapt);
3871 * ufshcd_dme_enable - UIC command for DME_ENABLE
3872 * @hba: per adapter instance
3874 * DME_ENABLE command is issued in order to enable UniPro stack.
3876 * Returns 0 on success, non-zero value on failure
3878 static int ufshcd_dme_enable(struct ufs_hba *hba)
3880 struct uic_command uic_cmd = {0};
3883 uic_cmd.command = UIC_CMD_DME_ENABLE;
3885 ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
3888 "dme-enable: error code %d\n", ret);
3893 static inline void ufshcd_add_delay_before_dme_cmd(struct ufs_hba *hba)
3895 #define MIN_DELAY_BEFORE_DME_CMDS_US 1000
3896 unsigned long min_sleep_time_us;
3898 if (!(hba->quirks & UFSHCD_QUIRK_DELAY_BEFORE_DME_CMDS))
3902 * last_dme_cmd_tstamp will be 0 only for 1st call to
3905 if (unlikely(!ktime_to_us(hba->last_dme_cmd_tstamp))) {
3906 min_sleep_time_us = MIN_DELAY_BEFORE_DME_CMDS_US;
3908 unsigned long delta =
3909 (unsigned long) ktime_to_us(
3910 ktime_sub(ktime_get(),
3911 hba->last_dme_cmd_tstamp));
3913 if (delta < MIN_DELAY_BEFORE_DME_CMDS_US)
3915 MIN_DELAY_BEFORE_DME_CMDS_US - delta;
3917 return; /* no more delay required */
3920 /* allow sleep for extra 50us if needed */
3921 usleep_range(min_sleep_time_us, min_sleep_time_us + 50);
3925 * ufshcd_dme_set_attr - UIC command for DME_SET, DME_PEER_SET
3926 * @hba: per adapter instance
3927 * @attr_sel: uic command argument1
3928 * @attr_set: attribute set type as uic command argument2
3929 * @mib_val: setting value as uic command argument3
3930 * @peer: indicate whether peer or local
3932 * Returns 0 on success, non-zero value on failure
3934 int ufshcd_dme_set_attr(struct ufs_hba *hba, u32 attr_sel,
3935 u8 attr_set, u32 mib_val, u8 peer)
3937 struct uic_command uic_cmd = {0};
3938 static const char *const action[] = {
3942 const char *set = action[!!peer];
3944 int retries = UFS_UIC_COMMAND_RETRIES;
3946 uic_cmd.command = peer ?
3947 UIC_CMD_DME_PEER_SET : UIC_CMD_DME_SET;
3948 uic_cmd.argument1 = attr_sel;
3949 uic_cmd.argument2 = UIC_ARG_ATTR_TYPE(attr_set);
3950 uic_cmd.argument3 = mib_val;
3953 /* for peer attributes we retry upon failure */
3954 ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
3956 dev_dbg(hba->dev, "%s: attr-id 0x%x val 0x%x error code %d\n",
3957 set, UIC_GET_ATTR_ID(attr_sel), mib_val, ret);
3958 } while (ret && peer && --retries);
3961 dev_err(hba->dev, "%s: attr-id 0x%x val 0x%x failed %d retries\n",
3962 set, UIC_GET_ATTR_ID(attr_sel), mib_val,
3963 UFS_UIC_COMMAND_RETRIES - retries);
3967 EXPORT_SYMBOL_GPL(ufshcd_dme_set_attr);
3970 * ufshcd_dme_get_attr - UIC command for DME_GET, DME_PEER_GET
3971 * @hba: per adapter instance
3972 * @attr_sel: uic command argument1
3973 * @mib_val: the value of the attribute as returned by the UIC command
3974 * @peer: indicate whether peer or local
3976 * Returns 0 on success, non-zero value on failure
3978 int ufshcd_dme_get_attr(struct ufs_hba *hba, u32 attr_sel,
3979 u32 *mib_val, u8 peer)
3981 struct uic_command uic_cmd = {0};
3982 static const char *const action[] = {
3986 const char *get = action[!!peer];
3988 int retries = UFS_UIC_COMMAND_RETRIES;
3989 struct ufs_pa_layer_attr orig_pwr_info;
3990 struct ufs_pa_layer_attr temp_pwr_info;
3991 bool pwr_mode_change = false;
3993 if (peer && (hba->quirks & UFSHCD_QUIRK_DME_PEER_ACCESS_AUTO_MODE)) {
3994 orig_pwr_info = hba->pwr_info;
3995 temp_pwr_info = orig_pwr_info;
3997 if (orig_pwr_info.pwr_tx == FAST_MODE ||
3998 orig_pwr_info.pwr_rx == FAST_MODE) {
3999 temp_pwr_info.pwr_tx = FASTAUTO_MODE;
4000 temp_pwr_info.pwr_rx = FASTAUTO_MODE;
4001 pwr_mode_change = true;
4002 } else if (orig_pwr_info.pwr_tx == SLOW_MODE ||
4003 orig_pwr_info.pwr_rx == SLOW_MODE) {
4004 temp_pwr_info.pwr_tx = SLOWAUTO_MODE;
4005 temp_pwr_info.pwr_rx = SLOWAUTO_MODE;
4006 pwr_mode_change = true;
4008 if (pwr_mode_change) {
4009 ret = ufshcd_change_power_mode(hba, &temp_pwr_info);
4015 uic_cmd.command = peer ?
4016 UIC_CMD_DME_PEER_GET : UIC_CMD_DME_GET;
4017 uic_cmd.argument1 = attr_sel;
4020 /* for peer attributes we retry upon failure */
4021 ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
4023 dev_dbg(hba->dev, "%s: attr-id 0x%x error code %d\n",
4024 get, UIC_GET_ATTR_ID(attr_sel), ret);
4025 } while (ret && peer && --retries);
4028 dev_err(hba->dev, "%s: attr-id 0x%x failed %d retries\n",
4029 get, UIC_GET_ATTR_ID(attr_sel),
4030 UFS_UIC_COMMAND_RETRIES - retries);
4032 if (mib_val && !ret)
4033 *mib_val = uic_cmd.argument3;
4035 if (peer && (hba->quirks & UFSHCD_QUIRK_DME_PEER_ACCESS_AUTO_MODE)
4037 ufshcd_change_power_mode(hba, &orig_pwr_info);
4041 EXPORT_SYMBOL_GPL(ufshcd_dme_get_attr);
4044 * ufshcd_uic_pwr_ctrl - executes UIC commands (which affects the link power
4045 * state) and waits for it to take effect.
4047 * @hba: per adapter instance
4048 * @cmd: UIC command to execute
4050 * DME operations like DME_SET(PA_PWRMODE), DME_HIBERNATE_ENTER &
4051 * DME_HIBERNATE_EXIT commands take some time to take its effect on both host
4052 * and device UniPro link and hence it's final completion would be indicated by
4053 * dedicated status bits in Interrupt Status register (UPMS, UHES, UHXS) in
4054 * addition to normal UIC command completion Status (UCCS). This function only
4055 * returns after the relevant status bits indicate the completion.
4057 * Returns 0 on success, non-zero value on failure
4059 static int ufshcd_uic_pwr_ctrl(struct ufs_hba *hba, struct uic_command *cmd)
4061 DECLARE_COMPLETION_ONSTACK(uic_async_done);
4062 unsigned long flags;
4065 bool reenable_intr = false;
4067 mutex_lock(&hba->uic_cmd_mutex);
4068 ufshcd_add_delay_before_dme_cmd(hba);
4070 spin_lock_irqsave(hba->host->host_lock, flags);
4071 if (ufshcd_is_link_broken(hba)) {
4075 hba->uic_async_done = &uic_async_done;
4076 if (ufshcd_readl(hba, REG_INTERRUPT_ENABLE) & UIC_COMMAND_COMPL) {
4077 ufshcd_disable_intr(hba, UIC_COMMAND_COMPL);
4079 * Make sure UIC command completion interrupt is disabled before
4080 * issuing UIC command.
4083 reenable_intr = true;
4085 ret = __ufshcd_send_uic_cmd(hba, cmd, false);
4086 spin_unlock_irqrestore(hba->host->host_lock, flags);
4089 "pwr ctrl cmd 0x%x with mode 0x%x uic error %d\n",
4090 cmd->command, cmd->argument3, ret);
4094 if (!wait_for_completion_timeout(hba->uic_async_done,
4095 msecs_to_jiffies(UIC_CMD_TIMEOUT))) {
4097 "pwr ctrl cmd 0x%x with mode 0x%x completion timeout\n",
4098 cmd->command, cmd->argument3);
4100 if (!cmd->cmd_active) {
4101 dev_err(hba->dev, "%s: Power Mode Change operation has been completed, go check UPMCRS\n",
4111 status = ufshcd_get_upmcrs(hba);
4112 if (status != PWR_LOCAL) {
4114 "pwr ctrl cmd 0x%x failed, host upmcrs:0x%x\n",
4115 cmd->command, status);
4116 ret = (status != PWR_OK) ? status : -1;
4120 ufshcd_print_host_state(hba);
4121 ufshcd_print_pwr_info(hba);
4122 ufshcd_print_evt_hist(hba);
4125 spin_lock_irqsave(hba->host->host_lock, flags);
4126 hba->active_uic_cmd = NULL;
4127 hba->uic_async_done = NULL;
4129 ufshcd_enable_intr(hba, UIC_COMMAND_COMPL);
4131 ufshcd_set_link_broken(hba);
4132 ufshcd_schedule_eh_work(hba);
4135 spin_unlock_irqrestore(hba->host->host_lock, flags);
4136 mutex_unlock(&hba->uic_cmd_mutex);
4142 * ufshcd_uic_change_pwr_mode - Perform the UIC power mode chage
4143 * using DME_SET primitives.
4144 * @hba: per adapter instance
4145 * @mode: powr mode value
4147 * Returns 0 on success, non-zero value on failure
4149 int ufshcd_uic_change_pwr_mode(struct ufs_hba *hba, u8 mode)
4151 struct uic_command uic_cmd = {0};
4154 if (hba->quirks & UFSHCD_QUIRK_BROKEN_PA_RXHSUNTERMCAP) {
4155 ret = ufshcd_dme_set(hba,
4156 UIC_ARG_MIB_SEL(PA_RXHSUNTERMCAP, 0), 1);
4158 dev_err(hba->dev, "%s: failed to enable PA_RXHSUNTERMCAP ret %d\n",
4164 uic_cmd.command = UIC_CMD_DME_SET;
4165 uic_cmd.argument1 = UIC_ARG_MIB(PA_PWRMODE);
4166 uic_cmd.argument3 = mode;
4167 ufshcd_hold(hba, false);
4168 ret = ufshcd_uic_pwr_ctrl(hba, &uic_cmd);
4169 ufshcd_release(hba);
4174 EXPORT_SYMBOL_GPL(ufshcd_uic_change_pwr_mode);
4176 int ufshcd_link_recovery(struct ufs_hba *hba)
4179 unsigned long flags;
4181 spin_lock_irqsave(hba->host->host_lock, flags);
4182 hba->ufshcd_state = UFSHCD_STATE_RESET;
4183 ufshcd_set_eh_in_progress(hba);
4184 spin_unlock_irqrestore(hba->host->host_lock, flags);
4186 /* Reset the attached device */
4187 ufshcd_device_reset(hba);
4189 ret = ufshcd_host_reset_and_restore(hba);
4191 spin_lock_irqsave(hba->host->host_lock, flags);
4193 hba->ufshcd_state = UFSHCD_STATE_ERROR;
4194 ufshcd_clear_eh_in_progress(hba);
4195 spin_unlock_irqrestore(hba->host->host_lock, flags);
4198 dev_err(hba->dev, "%s: link recovery failed, err %d",
4203 EXPORT_SYMBOL_GPL(ufshcd_link_recovery);
4205 int ufshcd_uic_hibern8_enter(struct ufs_hba *hba)
4208 struct uic_command uic_cmd = {0};
4209 ktime_t start = ktime_get();
4211 ufshcd_vops_hibern8_notify(hba, UIC_CMD_DME_HIBER_ENTER, PRE_CHANGE);
4213 uic_cmd.command = UIC_CMD_DME_HIBER_ENTER;
4214 ret = ufshcd_uic_pwr_ctrl(hba, &uic_cmd);
4215 trace_ufshcd_profile_hibern8(dev_name(hba->dev), "enter",
4216 ktime_to_us(ktime_sub(ktime_get(), start)), ret);
4219 dev_err(hba->dev, "%s: hibern8 enter failed. ret = %d\n",
4222 ufshcd_vops_hibern8_notify(hba, UIC_CMD_DME_HIBER_ENTER,
4227 EXPORT_SYMBOL_GPL(ufshcd_uic_hibern8_enter);
4229 int ufshcd_uic_hibern8_exit(struct ufs_hba *hba)
4231 struct uic_command uic_cmd = {0};
4233 ktime_t start = ktime_get();
4235 ufshcd_vops_hibern8_notify(hba, UIC_CMD_DME_HIBER_EXIT, PRE_CHANGE);
4237 uic_cmd.command = UIC_CMD_DME_HIBER_EXIT;
4238 ret = ufshcd_uic_pwr_ctrl(hba, &uic_cmd);
4239 trace_ufshcd_profile_hibern8(dev_name(hba->dev), "exit",
4240 ktime_to_us(ktime_sub(ktime_get(), start)), ret);
4243 dev_err(hba->dev, "%s: hibern8 exit failed. ret = %d\n",
4246 ufshcd_vops_hibern8_notify(hba, UIC_CMD_DME_HIBER_EXIT,
4248 hba->ufs_stats.last_hibern8_exit_tstamp = local_clock();
4249 hba->ufs_stats.hibern8_exit_cnt++;
4254 EXPORT_SYMBOL_GPL(ufshcd_uic_hibern8_exit);
4256 void ufshcd_auto_hibern8_update(struct ufs_hba *hba, u32 ahit)
4258 unsigned long flags;
4259 bool update = false;
4261 if (!ufshcd_is_auto_hibern8_supported(hba))
4264 spin_lock_irqsave(hba->host->host_lock, flags);
4265 if (hba->ahit != ahit) {
4269 spin_unlock_irqrestore(hba->host->host_lock, flags);
4272 !pm_runtime_suspended(&hba->ufs_device_wlun->sdev_gendev)) {
4273 ufshcd_rpm_get_sync(hba);
4274 ufshcd_hold(hba, false);
4275 ufshcd_auto_hibern8_enable(hba);
4276 ufshcd_release(hba);
4277 ufshcd_rpm_put_sync(hba);
4280 EXPORT_SYMBOL_GPL(ufshcd_auto_hibern8_update);
4282 void ufshcd_auto_hibern8_enable(struct ufs_hba *hba)
4284 if (!ufshcd_is_auto_hibern8_supported(hba))
4287 ufshcd_writel(hba, hba->ahit, REG_AUTO_HIBERNATE_IDLE_TIMER);
4291 * ufshcd_init_pwr_info - setting the POR (power on reset)
4292 * values in hba power info
4293 * @hba: per-adapter instance
4295 static void ufshcd_init_pwr_info(struct ufs_hba *hba)
4297 hba->pwr_info.gear_rx = UFS_PWM_G1;
4298 hba->pwr_info.gear_tx = UFS_PWM_G1;
4299 hba->pwr_info.lane_rx = 1;
4300 hba->pwr_info.lane_tx = 1;
4301 hba->pwr_info.pwr_rx = SLOWAUTO_MODE;
4302 hba->pwr_info.pwr_tx = SLOWAUTO_MODE;
4303 hba->pwr_info.hs_rate = 0;
4307 * ufshcd_get_max_pwr_mode - reads the max power mode negotiated with device
4308 * @hba: per-adapter instance
4310 static int ufshcd_get_max_pwr_mode(struct ufs_hba *hba)
4312 struct ufs_pa_layer_attr *pwr_info = &hba->max_pwr_info.info;
4314 if (hba->max_pwr_info.is_valid)
4317 if (hba->quirks & UFSHCD_QUIRK_HIBERN_FASTAUTO) {
4318 pwr_info->pwr_tx = FASTAUTO_MODE;
4319 pwr_info->pwr_rx = FASTAUTO_MODE;
4321 pwr_info->pwr_tx = FAST_MODE;
4322 pwr_info->pwr_rx = FAST_MODE;
4324 pwr_info->hs_rate = PA_HS_MODE_B;
4326 /* Get the connected lane count */
4327 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_CONNECTEDRXDATALANES),
4328 &pwr_info->lane_rx);
4329 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_CONNECTEDTXDATALANES),
4330 &pwr_info->lane_tx);
4332 if (!pwr_info->lane_rx || !pwr_info->lane_tx) {
4333 dev_err(hba->dev, "%s: invalid connected lanes value. rx=%d, tx=%d\n",
4341 * First, get the maximum gears of HS speed.
4342 * If a zero value, it means there is no HSGEAR capability.
4343 * Then, get the maximum gears of PWM speed.
4345 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_MAXRXHSGEAR), &pwr_info->gear_rx);
4346 if (!pwr_info->gear_rx) {
4347 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_MAXRXPWMGEAR),
4348 &pwr_info->gear_rx);
4349 if (!pwr_info->gear_rx) {
4350 dev_err(hba->dev, "%s: invalid max pwm rx gear read = %d\n",
4351 __func__, pwr_info->gear_rx);
4354 pwr_info->pwr_rx = SLOW_MODE;
4357 ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_MAXRXHSGEAR),
4358 &pwr_info->gear_tx);
4359 if (!pwr_info->gear_tx) {
4360 ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_MAXRXPWMGEAR),
4361 &pwr_info->gear_tx);
4362 if (!pwr_info->gear_tx) {
4363 dev_err(hba->dev, "%s: invalid max pwm tx gear read = %d\n",
4364 __func__, pwr_info->gear_tx);
4367 pwr_info->pwr_tx = SLOW_MODE;
4370 hba->max_pwr_info.is_valid = true;
4374 static int ufshcd_change_power_mode(struct ufs_hba *hba,
4375 struct ufs_pa_layer_attr *pwr_mode)
4379 /* if already configured to the requested pwr_mode */
4380 if (!hba->force_pmc &&
4381 pwr_mode->gear_rx == hba->pwr_info.gear_rx &&
4382 pwr_mode->gear_tx == hba->pwr_info.gear_tx &&
4383 pwr_mode->lane_rx == hba->pwr_info.lane_rx &&
4384 pwr_mode->lane_tx == hba->pwr_info.lane_tx &&
4385 pwr_mode->pwr_rx == hba->pwr_info.pwr_rx &&
4386 pwr_mode->pwr_tx == hba->pwr_info.pwr_tx &&
4387 pwr_mode->hs_rate == hba->pwr_info.hs_rate) {
4388 dev_dbg(hba->dev, "%s: power already configured\n", __func__);
4393 * Configure attributes for power mode change with below.
4394 * - PA_RXGEAR, PA_ACTIVERXDATALANES, PA_RXTERMINATION,
4395 * - PA_TXGEAR, PA_ACTIVETXDATALANES, PA_TXTERMINATION,
4398 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_RXGEAR), pwr_mode->gear_rx);
4399 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_ACTIVERXDATALANES),
4401 if (pwr_mode->pwr_rx == FASTAUTO_MODE ||
4402 pwr_mode->pwr_rx == FAST_MODE)
4403 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_RXTERMINATION), true);
4405 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_RXTERMINATION), false);
4407 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TXGEAR), pwr_mode->gear_tx);
4408 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_ACTIVETXDATALANES),
4410 if (pwr_mode->pwr_tx == FASTAUTO_MODE ||
4411 pwr_mode->pwr_tx == FAST_MODE)
4412 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TXTERMINATION), true);
4414 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TXTERMINATION), false);
4416 if (pwr_mode->pwr_rx == FASTAUTO_MODE ||
4417 pwr_mode->pwr_tx == FASTAUTO_MODE ||
4418 pwr_mode->pwr_rx == FAST_MODE ||
4419 pwr_mode->pwr_tx == FAST_MODE)
4420 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_HSSERIES),
4423 if (!(hba->quirks & UFSHCD_QUIRK_SKIP_DEF_UNIPRO_TIMEOUT_SETTING)) {
4424 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_PWRMODEUSERDATA0),
4425 DL_FC0ProtectionTimeOutVal_Default);
4426 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_PWRMODEUSERDATA1),
4427 DL_TC0ReplayTimeOutVal_Default);
4428 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_PWRMODEUSERDATA2),
4429 DL_AFC0ReqTimeOutVal_Default);
4430 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_PWRMODEUSERDATA3),
4431 DL_FC1ProtectionTimeOutVal_Default);
4432 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_PWRMODEUSERDATA4),
4433 DL_TC1ReplayTimeOutVal_Default);
4434 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_PWRMODEUSERDATA5),
4435 DL_AFC1ReqTimeOutVal_Default);
4437 ufshcd_dme_set(hba, UIC_ARG_MIB(DME_LocalFC0ProtectionTimeOutVal),
4438 DL_FC0ProtectionTimeOutVal_Default);
4439 ufshcd_dme_set(hba, UIC_ARG_MIB(DME_LocalTC0ReplayTimeOutVal),
4440 DL_TC0ReplayTimeOutVal_Default);
4441 ufshcd_dme_set(hba, UIC_ARG_MIB(DME_LocalAFC0ReqTimeOutVal),
4442 DL_AFC0ReqTimeOutVal_Default);
4445 ret = ufshcd_uic_change_pwr_mode(hba, pwr_mode->pwr_rx << 4
4446 | pwr_mode->pwr_tx);
4450 "%s: power mode change failed %d\n", __func__, ret);
4452 ufshcd_vops_pwr_change_notify(hba, POST_CHANGE, NULL,
4455 memcpy(&hba->pwr_info, pwr_mode,
4456 sizeof(struct ufs_pa_layer_attr));
4463 * ufshcd_config_pwr_mode - configure a new power mode
4464 * @hba: per-adapter instance
4465 * @desired_pwr_mode: desired power configuration
4467 int ufshcd_config_pwr_mode(struct ufs_hba *hba,
4468 struct ufs_pa_layer_attr *desired_pwr_mode)
4470 struct ufs_pa_layer_attr final_params = { 0 };
4473 ret = ufshcd_vops_pwr_change_notify(hba, PRE_CHANGE,
4474 desired_pwr_mode, &final_params);
4477 memcpy(&final_params, desired_pwr_mode, sizeof(final_params));
4479 ret = ufshcd_change_power_mode(hba, &final_params);
4483 EXPORT_SYMBOL_GPL(ufshcd_config_pwr_mode);
4486 * ufshcd_complete_dev_init() - checks device readiness
4487 * @hba: per-adapter instance
4489 * Set fDeviceInit flag and poll until device toggles it.
4491 static int ufshcd_complete_dev_init(struct ufs_hba *hba)
4494 bool flag_res = true;
4497 err = ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_SET_FLAG,
4498 QUERY_FLAG_IDN_FDEVICEINIT, 0, NULL);
4501 "%s: setting fDeviceInit flag failed with error %d\n",
4506 /* Poll fDeviceInit flag to be cleared */
4507 timeout = ktime_add_ms(ktime_get(), FDEVICEINIT_COMPL_TIMEOUT);
4509 err = ufshcd_query_flag(hba, UPIU_QUERY_OPCODE_READ_FLAG,
4510 QUERY_FLAG_IDN_FDEVICEINIT, 0, &flag_res);
4513 usleep_range(500, 1000);
4514 } while (ktime_before(ktime_get(), timeout));
4518 "%s: reading fDeviceInit flag failed with error %d\n",
4520 } else if (flag_res) {
4522 "%s: fDeviceInit was not cleared by the device\n",
4531 * ufshcd_make_hba_operational - Make UFS controller operational
4532 * @hba: per adapter instance
4534 * To bring UFS host controller to operational state,
4535 * 1. Enable required interrupts
4536 * 2. Configure interrupt aggregation
4537 * 3. Program UTRL and UTMRL base address
4538 * 4. Configure run-stop-registers
4540 * Returns 0 on success, non-zero value on failure
4542 int ufshcd_make_hba_operational(struct ufs_hba *hba)
4547 /* Enable required interrupts */
4548 ufshcd_enable_intr(hba, UFSHCD_ENABLE_INTRS);
4550 /* Configure interrupt aggregation */
4551 if (ufshcd_is_intr_aggr_allowed(hba))
4552 ufshcd_config_intr_aggr(hba, hba->nutrs - 1, INT_AGGR_DEF_TO);
4554 ufshcd_disable_intr_aggr(hba);
4556 /* Configure UTRL and UTMRL base address registers */
4557 ufshcd_writel(hba, lower_32_bits(hba->utrdl_dma_addr),
4558 REG_UTP_TRANSFER_REQ_LIST_BASE_L);
4559 ufshcd_writel(hba, upper_32_bits(hba->utrdl_dma_addr),
4560 REG_UTP_TRANSFER_REQ_LIST_BASE_H);
4561 ufshcd_writel(hba, lower_32_bits(hba->utmrdl_dma_addr),
4562 REG_UTP_TASK_REQ_LIST_BASE_L);
4563 ufshcd_writel(hba, upper_32_bits(hba->utmrdl_dma_addr),
4564 REG_UTP_TASK_REQ_LIST_BASE_H);
4567 * Make sure base address and interrupt setup are updated before
4568 * enabling the run/stop registers below.
4573 * UCRDY, UTMRLDY and UTRLRDY bits must be 1
4575 reg = ufshcd_readl(hba, REG_CONTROLLER_STATUS);
4576 if (!(ufshcd_get_lists_status(reg))) {
4577 ufshcd_enable_run_stop_reg(hba);
4580 "Host controller not ready to process requests");
4586 EXPORT_SYMBOL_GPL(ufshcd_make_hba_operational);
4589 * ufshcd_hba_stop - Send controller to reset state
4590 * @hba: per adapter instance
4592 void ufshcd_hba_stop(struct ufs_hba *hba)
4594 unsigned long flags;
4598 * Obtain the host lock to prevent that the controller is disabled
4599 * while the UFS interrupt handler is active on another CPU.
4601 spin_lock_irqsave(hba->host->host_lock, flags);
4602 ufshcd_writel(hba, CONTROLLER_DISABLE, REG_CONTROLLER_ENABLE);
4603 spin_unlock_irqrestore(hba->host->host_lock, flags);
4605 err = ufshcd_wait_for_register(hba, REG_CONTROLLER_ENABLE,
4606 CONTROLLER_ENABLE, CONTROLLER_DISABLE,
4609 dev_err(hba->dev, "%s: Controller disable failed\n", __func__);
4611 EXPORT_SYMBOL_GPL(ufshcd_hba_stop);
4614 * ufshcd_hba_execute_hce - initialize the controller
4615 * @hba: per adapter instance
4617 * The controller resets itself and controller firmware initialization
4618 * sequence kicks off. When controller is ready it will set
4619 * the Host Controller Enable bit to 1.
4621 * Returns 0 on success, non-zero value on failure
4623 static int ufshcd_hba_execute_hce(struct ufs_hba *hba)
4625 int retry_outer = 3;
4629 if (ufshcd_is_hba_active(hba))
4630 /* change controller state to "reset state" */
4631 ufshcd_hba_stop(hba);
4633 /* UniPro link is disabled at this point */
4634 ufshcd_set_link_off(hba);
4636 ufshcd_vops_hce_enable_notify(hba, PRE_CHANGE);
4638 /* start controller initialization sequence */
4639 ufshcd_hba_start(hba);
4642 * To initialize a UFS host controller HCE bit must be set to 1.
4643 * During initialization the HCE bit value changes from 1->0->1.
4644 * When the host controller completes initialization sequence
4645 * it sets the value of HCE bit to 1. The same HCE bit is read back
4646 * to check if the controller has completed initialization sequence.
4647 * So without this delay the value HCE = 1, set in the previous
4648 * instruction might be read back.
4649 * This delay can be changed based on the controller.
4651 ufshcd_delay_us(hba->vps->hba_enable_delay_us, 100);
4653 /* wait for the host controller to complete initialization */
4655 while (!ufshcd_is_hba_active(hba)) {
4660 "Controller enable failed\n");
4667 usleep_range(1000, 1100);
4670 /* enable UIC related interrupts */
4671 ufshcd_enable_intr(hba, UFSHCD_UIC_MASK);
4673 ufshcd_vops_hce_enable_notify(hba, POST_CHANGE);
4678 int ufshcd_hba_enable(struct ufs_hba *hba)
4682 if (hba->quirks & UFSHCI_QUIRK_BROKEN_HCE) {
4683 ufshcd_set_link_off(hba);
4684 ufshcd_vops_hce_enable_notify(hba, PRE_CHANGE);
4686 /* enable UIC related interrupts */
4687 ufshcd_enable_intr(hba, UFSHCD_UIC_MASK);
4688 ret = ufshcd_dme_reset(hba);
4690 dev_err(hba->dev, "DME_RESET failed\n");
4694 ret = ufshcd_dme_enable(hba);
4696 dev_err(hba->dev, "Enabling DME failed\n");
4700 ufshcd_vops_hce_enable_notify(hba, POST_CHANGE);
4702 ret = ufshcd_hba_execute_hce(hba);
4707 EXPORT_SYMBOL_GPL(ufshcd_hba_enable);
4709 static int ufshcd_disable_tx_lcc(struct ufs_hba *hba, bool peer)
4711 int tx_lanes = 0, i, err = 0;
4714 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_CONNECTEDTXDATALANES),
4717 ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_CONNECTEDTXDATALANES),
4719 for (i = 0; i < tx_lanes; i++) {
4721 err = ufshcd_dme_set(hba,
4722 UIC_ARG_MIB_SEL(TX_LCC_ENABLE,
4723 UIC_ARG_MPHY_TX_GEN_SEL_INDEX(i)),
4726 err = ufshcd_dme_peer_set(hba,
4727 UIC_ARG_MIB_SEL(TX_LCC_ENABLE,
4728 UIC_ARG_MPHY_TX_GEN_SEL_INDEX(i)),
4731 dev_err(hba->dev, "%s: TX LCC Disable failed, peer = %d, lane = %d, err = %d",
4732 __func__, peer, i, err);
4740 static inline int ufshcd_disable_device_tx_lcc(struct ufs_hba *hba)
4742 return ufshcd_disable_tx_lcc(hba, true);
4745 void ufshcd_update_evt_hist(struct ufs_hba *hba, u32 id, u32 val)
4747 struct ufs_event_hist *e;
4749 if (id >= UFS_EVT_CNT)
4752 e = &hba->ufs_stats.event[id];
4753 e->val[e->pos] = val;
4754 e->tstamp[e->pos] = local_clock();
4756 e->pos = (e->pos + 1) % UFS_EVENT_HIST_LENGTH;
4758 ufshcd_vops_event_notify(hba, id, &val);
4760 EXPORT_SYMBOL_GPL(ufshcd_update_evt_hist);
4763 * ufshcd_link_startup - Initialize unipro link startup
4764 * @hba: per adapter instance
4766 * Returns 0 for success, non-zero in case of failure
4768 static int ufshcd_link_startup(struct ufs_hba *hba)
4771 int retries = DME_LINKSTARTUP_RETRIES;
4772 bool link_startup_again = false;
4775 * If UFS device isn't active then we will have to issue link startup
4776 * 2 times to make sure the device state move to active.
4778 if (!ufshcd_is_ufs_dev_active(hba))
4779 link_startup_again = true;
4783 ufshcd_vops_link_startup_notify(hba, PRE_CHANGE);
4785 ret = ufshcd_dme_link_startup(hba);
4787 /* check if device is detected by inter-connect layer */
4788 if (!ret && !ufshcd_is_device_present(hba)) {
4789 ufshcd_update_evt_hist(hba,
4790 UFS_EVT_LINK_STARTUP_FAIL,
4792 dev_err(hba->dev, "%s: Device not present\n", __func__);
4798 * DME link lost indication is only received when link is up,
4799 * but we can't be sure if the link is up until link startup
4800 * succeeds. So reset the local Uni-Pro and try again.
4802 if (ret && retries && ufshcd_hba_enable(hba)) {
4803 ufshcd_update_evt_hist(hba,
4804 UFS_EVT_LINK_STARTUP_FAIL,
4808 } while (ret && retries--);
4811 /* failed to get the link up... retire */
4812 ufshcd_update_evt_hist(hba,
4813 UFS_EVT_LINK_STARTUP_FAIL,
4818 if (link_startup_again) {
4819 link_startup_again = false;
4820 retries = DME_LINKSTARTUP_RETRIES;
4824 /* Mark that link is up in PWM-G1, 1-lane, SLOW-AUTO mode */
4825 ufshcd_init_pwr_info(hba);
4826 ufshcd_print_pwr_info(hba);
4828 if (hba->quirks & UFSHCD_QUIRK_BROKEN_LCC) {
4829 ret = ufshcd_disable_device_tx_lcc(hba);
4834 /* Include any host controller configuration via UIC commands */
4835 ret = ufshcd_vops_link_startup_notify(hba, POST_CHANGE);
4839 /* Clear UECPA once due to LINERESET has happened during LINK_STARTUP */
4840 ufshcd_readl(hba, REG_UIC_ERROR_CODE_PHY_ADAPTER_LAYER);
4841 ret = ufshcd_make_hba_operational(hba);
4844 dev_err(hba->dev, "link startup failed %d\n", ret);
4845 ufshcd_print_host_state(hba);
4846 ufshcd_print_pwr_info(hba);
4847 ufshcd_print_evt_hist(hba);
4853 * ufshcd_verify_dev_init() - Verify device initialization
4854 * @hba: per-adapter instance
4856 * Send NOP OUT UPIU and wait for NOP IN response to check whether the
4857 * device Transport Protocol (UTP) layer is ready after a reset.
4858 * If the UTP layer at the device side is not initialized, it may
4859 * not respond with NOP IN UPIU within timeout of %NOP_OUT_TIMEOUT
4860 * and we retry sending NOP OUT for %NOP_OUT_RETRIES iterations.
4862 static int ufshcd_verify_dev_init(struct ufs_hba *hba)
4867 ufshcd_hold(hba, false);
4868 mutex_lock(&hba->dev_cmd.lock);
4869 for (retries = NOP_OUT_RETRIES; retries > 0; retries--) {
4870 err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_NOP,
4871 hba->nop_out_timeout);
4873 if (!err || err == -ETIMEDOUT)
4876 dev_dbg(hba->dev, "%s: error %d retrying\n", __func__, err);
4878 mutex_unlock(&hba->dev_cmd.lock);
4879 ufshcd_release(hba);
4882 dev_err(hba->dev, "%s: NOP OUT failed %d\n", __func__, err);
4887 * ufshcd_setup_links - associate link b/w device wlun and other luns
4888 * @sdev: pointer to SCSI device
4889 * @hba: pointer to ufs hba
4891 static void ufshcd_setup_links(struct ufs_hba *hba, struct scsi_device *sdev)
4893 struct device_link *link;
4896 * Device wlun is the supplier & rest of the luns are consumers.
4897 * This ensures that device wlun suspends after all other luns.
4899 if (hba->ufs_device_wlun) {
4900 link = device_link_add(&sdev->sdev_gendev,
4901 &hba->ufs_device_wlun->sdev_gendev,
4902 DL_FLAG_PM_RUNTIME | DL_FLAG_RPM_ACTIVE);
4904 dev_err(&sdev->sdev_gendev, "Failed establishing link - %s\n",
4905 dev_name(&hba->ufs_device_wlun->sdev_gendev));
4909 /* Ignore REPORT_LUN wlun probing */
4910 if (hba->luns_avail == 1) {
4911 ufshcd_rpm_put(hba);
4916 * Device wlun is probed. The assumption is that WLUNs are
4917 * scanned before other LUNs.
4924 * ufshcd_lu_init - Initialize the relevant parameters of the LU
4925 * @hba: per-adapter instance
4926 * @sdev: pointer to SCSI device
4928 static void ufshcd_lu_init(struct ufs_hba *hba, struct scsi_device *sdev)
4930 int len = hba->desc_size[QUERY_DESC_IDN_UNIT];
4931 u8 lun = ufshcd_scsi_to_upiu_lun(sdev->lun);
4932 u8 lun_qdepth = hba->nutrs;
4936 desc_buf = kzalloc(len, GFP_KERNEL);
4940 ret = ufshcd_read_unit_desc_param(hba, lun, 0, desc_buf, len);
4942 if (ret == -EOPNOTSUPP)
4943 /* If LU doesn't support unit descriptor, its queue depth is set to 1 */
4949 if (desc_buf[UNIT_DESC_PARAM_LU_Q_DEPTH]) {
4951 * In per-LU queueing architecture, bLUQueueDepth will not be 0, then we will
4952 * use the smaller between UFSHCI CAP.NUTRS and UFS LU bLUQueueDepth
4954 lun_qdepth = min_t(int, desc_buf[UNIT_DESC_PARAM_LU_Q_DEPTH], hba->nutrs);
4957 * According to UFS device specification, the write protection mode is only supported by
4958 * normal LU, not supported by WLUN.
4960 if (hba->dev_info.f_power_on_wp_en && lun < hba->dev_info.max_lu_supported &&
4961 !hba->dev_info.is_lu_power_on_wp &&
4962 desc_buf[UNIT_DESC_PARAM_LU_WR_PROTECT] == UFS_LU_POWER_ON_WP)
4963 hba->dev_info.is_lu_power_on_wp = true;
4965 /* In case of RPMB LU, check if advanced RPMB mode is enabled */
4966 if (desc_buf[UNIT_DESC_PARAM_UNIT_INDEX] == UFS_UPIU_RPMB_WLUN &&
4967 desc_buf[RPMB_UNIT_DESC_PARAM_REGION_EN] & BIT(4))
4968 hba->dev_info.b_advanced_rpmb_en = true;
4974 * For WLUNs that don't support unit descriptor, queue depth is set to 1. For LUs whose
4975 * bLUQueueDepth == 0, the queue depth is set to a maximum value that host can queue.
4977 dev_dbg(hba->dev, "Set LU %x queue depth %d\n", lun, lun_qdepth);
4978 scsi_change_queue_depth(sdev, lun_qdepth);
4982 * ufshcd_slave_alloc - handle initial SCSI device configurations
4983 * @sdev: pointer to SCSI device
4987 static int ufshcd_slave_alloc(struct scsi_device *sdev)
4989 struct ufs_hba *hba;
4991 hba = shost_priv(sdev->host);
4993 /* Mode sense(6) is not supported by UFS, so use Mode sense(10) */
4994 sdev->use_10_for_ms = 1;
4996 /* DBD field should be set to 1 in mode sense(10) */
4997 sdev->set_dbd_for_ms = 1;
4999 /* allow SCSI layer to restart the device in case of errors */
5000 sdev->allow_restart = 1;
5002 /* REPORT SUPPORTED OPERATION CODES is not supported */
5003 sdev->no_report_opcodes = 1;
5005 /* WRITE_SAME command is not supported */
5006 sdev->no_write_same = 1;
5008 ufshcd_lu_init(hba, sdev);
5010 ufshcd_setup_links(hba, sdev);
5016 * ufshcd_change_queue_depth - change queue depth
5017 * @sdev: pointer to SCSI device
5018 * @depth: required depth to set
5020 * Change queue depth and make sure the max. limits are not crossed.
5022 static int ufshcd_change_queue_depth(struct scsi_device *sdev, int depth)
5024 return scsi_change_queue_depth(sdev, min(depth, sdev->host->can_queue));
5027 static void ufshcd_hpb_destroy(struct ufs_hba *hba, struct scsi_device *sdev)
5029 /* skip well-known LU */
5030 if ((sdev->lun >= UFS_UPIU_MAX_UNIT_NUM_ID) ||
5031 !(hba->dev_info.hpb_enabled) || !ufshpb_is_allowed(hba))
5034 ufshpb_destroy_lu(hba, sdev);
5037 static void ufshcd_hpb_configure(struct ufs_hba *hba, struct scsi_device *sdev)
5039 /* skip well-known LU */
5040 if ((sdev->lun >= UFS_UPIU_MAX_UNIT_NUM_ID) ||
5041 !(hba->dev_info.hpb_enabled) || !ufshpb_is_allowed(hba))
5044 ufshpb_init_hpb_lu(hba, sdev);
5048 * ufshcd_slave_configure - adjust SCSI device configurations
5049 * @sdev: pointer to SCSI device
5051 static int ufshcd_slave_configure(struct scsi_device *sdev)
5053 struct ufs_hba *hba = shost_priv(sdev->host);
5054 struct request_queue *q = sdev->request_queue;
5056 ufshcd_hpb_configure(hba, sdev);
5058 blk_queue_update_dma_pad(q, PRDT_DATA_BYTE_COUNT_PAD - 1);
5059 if (hba->quirks & UFSHCD_QUIRK_ALIGN_SG_WITH_PAGE_SIZE)
5060 blk_queue_update_dma_alignment(q, PAGE_SIZE - 1);
5062 * Block runtime-pm until all consumers are added.
5063 * Refer ufshcd_setup_links().
5065 if (is_device_wlun(sdev))
5066 pm_runtime_get_noresume(&sdev->sdev_gendev);
5067 else if (ufshcd_is_rpm_autosuspend_allowed(hba))
5068 sdev->rpm_autosuspend = 1;
5070 * Do not print messages during runtime PM to avoid never-ending cycles
5071 * of messages written back to storage by user space causing runtime
5072 * resume, causing more messages and so on.
5074 sdev->silence_suspend = 1;
5076 ufshcd_crypto_register(hba, q);
5082 * ufshcd_slave_destroy - remove SCSI device configurations
5083 * @sdev: pointer to SCSI device
5085 static void ufshcd_slave_destroy(struct scsi_device *sdev)
5087 struct ufs_hba *hba;
5088 unsigned long flags;
5090 hba = shost_priv(sdev->host);
5092 ufshcd_hpb_destroy(hba, sdev);
5094 /* Drop the reference as it won't be needed anymore */
5095 if (ufshcd_scsi_to_upiu_lun(sdev->lun) == UFS_UPIU_UFS_DEVICE_WLUN) {
5096 spin_lock_irqsave(hba->host->host_lock, flags);
5097 hba->ufs_device_wlun = NULL;
5098 spin_unlock_irqrestore(hba->host->host_lock, flags);
5099 } else if (hba->ufs_device_wlun) {
5100 struct device *supplier = NULL;
5102 /* Ensure UFS Device WLUN exists and does not disappear */
5103 spin_lock_irqsave(hba->host->host_lock, flags);
5104 if (hba->ufs_device_wlun) {
5105 supplier = &hba->ufs_device_wlun->sdev_gendev;
5106 get_device(supplier);
5108 spin_unlock_irqrestore(hba->host->host_lock, flags);
5112 * If a LUN fails to probe (e.g. absent BOOT WLUN), the
5113 * device will not have been registered but can still
5114 * have a device link holding a reference to the device.
5116 device_link_remove(&sdev->sdev_gendev, supplier);
5117 put_device(supplier);
5123 * ufshcd_scsi_cmd_status - Update SCSI command result based on SCSI status
5124 * @lrbp: pointer to local reference block of completed command
5125 * @scsi_status: SCSI command status
5127 * Returns value base on SCSI command status
5130 ufshcd_scsi_cmd_status(struct ufshcd_lrb *lrbp, int scsi_status)
5134 switch (scsi_status) {
5135 case SAM_STAT_CHECK_CONDITION:
5136 ufshcd_copy_sense_data(lrbp);
5139 result |= DID_OK << 16 | scsi_status;
5141 case SAM_STAT_TASK_SET_FULL:
5143 case SAM_STAT_TASK_ABORTED:
5144 ufshcd_copy_sense_data(lrbp);
5145 result |= scsi_status;
5148 result |= DID_ERROR << 16;
5150 } /* end of switch */
5156 * ufshcd_transfer_rsp_status - Get overall status of the response
5157 * @hba: per adapter instance
5158 * @lrbp: pointer to local reference block of completed command
5160 * Returns result of the command to notify SCSI midlayer
5163 ufshcd_transfer_rsp_status(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
5169 /* overall command status of utrd */
5170 ocs = ufshcd_get_tr_ocs(lrbp);
5172 if (hba->quirks & UFSHCD_QUIRK_BROKEN_OCS_FATAL_ERROR) {
5173 if (be32_to_cpu(lrbp->ucd_rsp_ptr->header.dword_1) &
5174 MASK_RSP_UPIU_RESULT)
5180 result = ufshcd_get_req_rsp(lrbp->ucd_rsp_ptr);
5181 hba->ufs_stats.last_hibern8_exit_tstamp = ktime_set(0, 0);
5183 case UPIU_TRANSACTION_RESPONSE:
5185 * get the response UPIU result to extract
5186 * the SCSI command status
5188 result = ufshcd_get_rsp_upiu_result(lrbp->ucd_rsp_ptr);
5191 * get the result based on SCSI status response
5192 * to notify the SCSI midlayer of the command status
5194 scsi_status = result & MASK_SCSI_STATUS;
5195 result = ufshcd_scsi_cmd_status(lrbp, scsi_status);
5198 * Currently we are only supporting BKOPs exception
5199 * events hence we can ignore BKOPs exception event
5200 * during power management callbacks. BKOPs exception
5201 * event is not expected to be raised in runtime suspend
5202 * callback as it allows the urgent bkops.
5203 * During system suspend, we are anyway forcefully
5204 * disabling the bkops and if urgent bkops is needed
5205 * it will be enabled on system resume. Long term
5206 * solution could be to abort the system suspend if
5207 * UFS device needs urgent BKOPs.
5209 if (!hba->pm_op_in_progress &&
5210 !ufshcd_eh_in_progress(hba) &&
5211 ufshcd_is_exception_event(lrbp->ucd_rsp_ptr))
5212 /* Flushed in suspend */
5213 schedule_work(&hba->eeh_work);
5215 if (scsi_status == SAM_STAT_GOOD)
5216 ufshpb_rsp_upiu(hba, lrbp);
5218 case UPIU_TRANSACTION_REJECT_UPIU:
5219 /* TODO: handle Reject UPIU Response */
5220 result = DID_ERROR << 16;
5222 "Reject UPIU not fully implemented\n");
5226 "Unexpected request response code = %x\n",
5228 result = DID_ERROR << 16;
5233 result |= DID_ABORT << 16;
5235 case OCS_INVALID_COMMAND_STATUS:
5236 result |= DID_REQUEUE << 16;
5238 case OCS_INVALID_CMD_TABLE_ATTR:
5239 case OCS_INVALID_PRDT_ATTR:
5240 case OCS_MISMATCH_DATA_BUF_SIZE:
5241 case OCS_MISMATCH_RESP_UPIU_SIZE:
5242 case OCS_PEER_COMM_FAILURE:
5243 case OCS_FATAL_ERROR:
5244 case OCS_DEVICE_FATAL_ERROR:
5245 case OCS_INVALID_CRYPTO_CONFIG:
5246 case OCS_GENERAL_CRYPTO_ERROR:
5248 result |= DID_ERROR << 16;
5250 "OCS error from controller = %x for tag %d\n",
5251 ocs, lrbp->task_tag);
5252 ufshcd_print_evt_hist(hba);
5253 ufshcd_print_host_state(hba);
5255 } /* end of switch */
5257 if ((host_byte(result) != DID_OK) &&
5258 (host_byte(result) != DID_REQUEUE) && !hba->silence_err_logs)
5259 ufshcd_print_trs(hba, 1 << lrbp->task_tag, true);
5263 static bool ufshcd_is_auto_hibern8_error(struct ufs_hba *hba,
5266 if (!ufshcd_is_auto_hibern8_supported(hba) ||
5267 !ufshcd_is_auto_hibern8_enabled(hba))
5270 if (!(intr_mask & UFSHCD_UIC_HIBERN8_MASK))
5273 if (hba->active_uic_cmd &&
5274 (hba->active_uic_cmd->command == UIC_CMD_DME_HIBER_ENTER ||
5275 hba->active_uic_cmd->command == UIC_CMD_DME_HIBER_EXIT))
5282 * ufshcd_uic_cmd_compl - handle completion of uic command
5283 * @hba: per adapter instance
5284 * @intr_status: interrupt status generated by the controller
5287 * IRQ_HANDLED - If interrupt is valid
5288 * IRQ_NONE - If invalid interrupt
5290 static irqreturn_t ufshcd_uic_cmd_compl(struct ufs_hba *hba, u32 intr_status)
5292 irqreturn_t retval = IRQ_NONE;
5294 spin_lock(hba->host->host_lock);
5295 if (ufshcd_is_auto_hibern8_error(hba, intr_status))
5296 hba->errors |= (UFSHCD_UIC_HIBERN8_MASK & intr_status);
5298 if ((intr_status & UIC_COMMAND_COMPL) && hba->active_uic_cmd) {
5299 hba->active_uic_cmd->argument2 |=
5300 ufshcd_get_uic_cmd_result(hba);
5301 hba->active_uic_cmd->argument3 =
5302 ufshcd_get_dme_attr_val(hba);
5303 if (!hba->uic_async_done)
5304 hba->active_uic_cmd->cmd_active = 0;
5305 complete(&hba->active_uic_cmd->done);
5306 retval = IRQ_HANDLED;
5309 if ((intr_status & UFSHCD_UIC_PWR_MASK) && hba->uic_async_done) {
5310 hba->active_uic_cmd->cmd_active = 0;
5311 complete(hba->uic_async_done);
5312 retval = IRQ_HANDLED;
5315 if (retval == IRQ_HANDLED)
5316 ufshcd_add_uic_command_trace(hba, hba->active_uic_cmd,
5318 spin_unlock(hba->host->host_lock);
5322 /* Release the resources allocated for processing a SCSI command. */
5323 static void ufshcd_release_scsi_cmd(struct ufs_hba *hba,
5324 struct ufshcd_lrb *lrbp)
5326 struct scsi_cmnd *cmd = lrbp->cmd;
5328 scsi_dma_unmap(cmd);
5329 lrbp->cmd = NULL; /* Mark the command as completed. */
5330 ufshcd_release(hba);
5331 ufshcd_clk_scaling_update_busy(hba);
5335 * __ufshcd_transfer_req_compl - handle SCSI and query command completion
5336 * @hba: per adapter instance
5337 * @completed_reqs: bitmask that indicates which requests to complete
5339 static void __ufshcd_transfer_req_compl(struct ufs_hba *hba,
5340 unsigned long completed_reqs)
5342 struct ufshcd_lrb *lrbp;
5343 struct scsi_cmnd *cmd;
5346 for_each_set_bit(index, &completed_reqs, hba->nutrs) {
5347 lrbp = &hba->lrb[index];
5348 lrbp->compl_time_stamp = ktime_get();
5349 lrbp->compl_time_stamp_local_clock = local_clock();
5352 if (unlikely(ufshcd_should_inform_monitor(hba, lrbp)))
5353 ufshcd_update_monitor(hba, lrbp);
5354 ufshcd_add_command_trace(hba, index, UFS_CMD_COMP);
5355 cmd->result = ufshcd_transfer_rsp_status(hba, lrbp);
5356 ufshcd_release_scsi_cmd(hba, lrbp);
5357 /* Do not touch lrbp after scsi done */
5359 } else if (lrbp->command_type == UTP_CMD_TYPE_DEV_MANAGE ||
5360 lrbp->command_type == UTP_CMD_TYPE_UFS_STORAGE) {
5361 if (hba->dev_cmd.complete) {
5362 ufshcd_add_command_trace(hba, index,
5364 complete(hba->dev_cmd.complete);
5365 ufshcd_clk_scaling_update_busy(hba);
5371 /* Any value that is not an existing queue number is fine for this constant. */
5373 UFSHCD_POLL_FROM_INTERRUPT_CONTEXT = -1
5376 static void ufshcd_clear_polled(struct ufs_hba *hba,
5377 unsigned long *completed_reqs)
5381 for_each_set_bit(tag, completed_reqs, hba->nutrs) {
5382 struct scsi_cmnd *cmd = hba->lrb[tag].cmd;
5386 if (scsi_cmd_to_rq(cmd)->cmd_flags & REQ_POLLED)
5387 __clear_bit(tag, completed_reqs);
5392 * Returns > 0 if one or more commands have been completed or 0 if no
5393 * requests have been completed.
5395 static int ufshcd_poll(struct Scsi_Host *shost, unsigned int queue_num)
5397 struct ufs_hba *hba = shost_priv(shost);
5398 unsigned long completed_reqs, flags;
5401 spin_lock_irqsave(&hba->outstanding_lock, flags);
5402 tr_doorbell = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
5403 completed_reqs = ~tr_doorbell & hba->outstanding_reqs;
5404 WARN_ONCE(completed_reqs & ~hba->outstanding_reqs,
5405 "completed: %#lx; outstanding: %#lx\n", completed_reqs,
5406 hba->outstanding_reqs);
5407 if (queue_num == UFSHCD_POLL_FROM_INTERRUPT_CONTEXT) {
5408 /* Do not complete polled requests from interrupt context. */
5409 ufshcd_clear_polled(hba, &completed_reqs);
5411 hba->outstanding_reqs &= ~completed_reqs;
5412 spin_unlock_irqrestore(&hba->outstanding_lock, flags);
5415 __ufshcd_transfer_req_compl(hba, completed_reqs);
5417 return completed_reqs != 0;
5421 * ufshcd_transfer_req_compl - handle SCSI and query command completion
5422 * @hba: per adapter instance
5425 * IRQ_HANDLED - If interrupt is valid
5426 * IRQ_NONE - If invalid interrupt
5428 static irqreturn_t ufshcd_transfer_req_compl(struct ufs_hba *hba)
5430 /* Resetting interrupt aggregation counters first and reading the
5431 * DOOR_BELL afterward allows us to handle all the completed requests.
5432 * In order to prevent other interrupts starvation the DB is read once
5433 * after reset. The down side of this solution is the possibility of
5434 * false interrupt if device completes another request after resetting
5435 * aggregation and before reading the DB.
5437 if (ufshcd_is_intr_aggr_allowed(hba) &&
5438 !(hba->quirks & UFSHCI_QUIRK_SKIP_RESET_INTR_AGGR))
5439 ufshcd_reset_intr_aggr(hba);
5441 if (ufs_fail_completion())
5445 * Ignore the ufshcd_poll() return value and return IRQ_HANDLED since we
5446 * do not want polling to trigger spurious interrupt complaints.
5448 ufshcd_poll(hba->host, UFSHCD_POLL_FROM_INTERRUPT_CONTEXT);
5453 int __ufshcd_write_ee_control(struct ufs_hba *hba, u32 ee_ctrl_mask)
5455 return ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_WRITE_ATTR,
5456 QUERY_ATTR_IDN_EE_CONTROL, 0, 0,
5460 int ufshcd_write_ee_control(struct ufs_hba *hba)
5464 mutex_lock(&hba->ee_ctrl_mutex);
5465 err = __ufshcd_write_ee_control(hba, hba->ee_ctrl_mask);
5466 mutex_unlock(&hba->ee_ctrl_mutex);
5468 dev_err(hba->dev, "%s: failed to write ee control %d\n",
5473 int ufshcd_update_ee_control(struct ufs_hba *hba, u16 *mask,
5474 const u16 *other_mask, u16 set, u16 clr)
5476 u16 new_mask, ee_ctrl_mask;
5479 mutex_lock(&hba->ee_ctrl_mutex);
5480 new_mask = (*mask & ~clr) | set;
5481 ee_ctrl_mask = new_mask | *other_mask;
5482 if (ee_ctrl_mask != hba->ee_ctrl_mask)
5483 err = __ufshcd_write_ee_control(hba, ee_ctrl_mask);
5484 /* Still need to update 'mask' even if 'ee_ctrl_mask' was unchanged */
5486 hba->ee_ctrl_mask = ee_ctrl_mask;
5489 mutex_unlock(&hba->ee_ctrl_mutex);
5494 * ufshcd_disable_ee - disable exception event
5495 * @hba: per-adapter instance
5496 * @mask: exception event to disable
5498 * Disables exception event in the device so that the EVENT_ALERT
5501 * Returns zero on success, non-zero error value on failure.
5503 static inline int ufshcd_disable_ee(struct ufs_hba *hba, u16 mask)
5505 return ufshcd_update_ee_drv_mask(hba, 0, mask);
5509 * ufshcd_enable_ee - enable exception event
5510 * @hba: per-adapter instance
5511 * @mask: exception event to enable
5513 * Enable corresponding exception event in the device to allow
5514 * device to alert host in critical scenarios.
5516 * Returns zero on success, non-zero error value on failure.
5518 static inline int ufshcd_enable_ee(struct ufs_hba *hba, u16 mask)
5520 return ufshcd_update_ee_drv_mask(hba, mask, 0);
5524 * ufshcd_enable_auto_bkops - Allow device managed BKOPS
5525 * @hba: per-adapter instance
5527 * Allow device to manage background operations on its own. Enabling
5528 * this might lead to inconsistent latencies during normal data transfers
5529 * as the device is allowed to manage its own way of handling background
5532 * Returns zero on success, non-zero on failure.
5534 static int ufshcd_enable_auto_bkops(struct ufs_hba *hba)
5538 if (hba->auto_bkops_enabled)
5541 err = ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_SET_FLAG,
5542 QUERY_FLAG_IDN_BKOPS_EN, 0, NULL);
5544 dev_err(hba->dev, "%s: failed to enable bkops %d\n",
5549 hba->auto_bkops_enabled = true;
5550 trace_ufshcd_auto_bkops_state(dev_name(hba->dev), "Enabled");
5552 /* No need of URGENT_BKOPS exception from the device */
5553 err = ufshcd_disable_ee(hba, MASK_EE_URGENT_BKOPS);
5555 dev_err(hba->dev, "%s: failed to disable exception event %d\n",
5562 * ufshcd_disable_auto_bkops - block device in doing background operations
5563 * @hba: per-adapter instance
5565 * Disabling background operations improves command response latency but
5566 * has drawback of device moving into critical state where the device is
5567 * not-operable. Make sure to call ufshcd_enable_auto_bkops() whenever the
5568 * host is idle so that BKOPS are managed effectively without any negative
5571 * Returns zero on success, non-zero on failure.
5573 static int ufshcd_disable_auto_bkops(struct ufs_hba *hba)
5577 if (!hba->auto_bkops_enabled)
5581 * If host assisted BKOPs is to be enabled, make sure
5582 * urgent bkops exception is allowed.
5584 err = ufshcd_enable_ee(hba, MASK_EE_URGENT_BKOPS);
5586 dev_err(hba->dev, "%s: failed to enable exception event %d\n",
5591 err = ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_CLEAR_FLAG,
5592 QUERY_FLAG_IDN_BKOPS_EN, 0, NULL);
5594 dev_err(hba->dev, "%s: failed to disable bkops %d\n",
5596 ufshcd_disable_ee(hba, MASK_EE_URGENT_BKOPS);
5600 hba->auto_bkops_enabled = false;
5601 trace_ufshcd_auto_bkops_state(dev_name(hba->dev), "Disabled");
5602 hba->is_urgent_bkops_lvl_checked = false;
5608 * ufshcd_force_reset_auto_bkops - force reset auto bkops state
5609 * @hba: per adapter instance
5611 * After a device reset the device may toggle the BKOPS_EN flag
5612 * to default value. The s/w tracking variables should be updated
5613 * as well. This function would change the auto-bkops state based on
5614 * UFSHCD_CAP_KEEP_AUTO_BKOPS_ENABLED_EXCEPT_SUSPEND.
5616 static void ufshcd_force_reset_auto_bkops(struct ufs_hba *hba)
5618 if (ufshcd_keep_autobkops_enabled_except_suspend(hba)) {
5619 hba->auto_bkops_enabled = false;
5620 hba->ee_ctrl_mask |= MASK_EE_URGENT_BKOPS;
5621 ufshcd_enable_auto_bkops(hba);
5623 hba->auto_bkops_enabled = true;
5624 hba->ee_ctrl_mask &= ~MASK_EE_URGENT_BKOPS;
5625 ufshcd_disable_auto_bkops(hba);
5627 hba->urgent_bkops_lvl = BKOPS_STATUS_PERF_IMPACT;
5628 hba->is_urgent_bkops_lvl_checked = false;
5631 static inline int ufshcd_get_bkops_status(struct ufs_hba *hba, u32 *status)
5633 return ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
5634 QUERY_ATTR_IDN_BKOPS_STATUS, 0, 0, status);
5638 * ufshcd_bkops_ctrl - control the auto bkops based on current bkops status
5639 * @hba: per-adapter instance
5640 * @status: bkops_status value
5642 * Read the bkops_status from the UFS device and Enable fBackgroundOpsEn
5643 * flag in the device to permit background operations if the device
5644 * bkops_status is greater than or equal to "status" argument passed to
5645 * this function, disable otherwise.
5647 * Returns 0 for success, non-zero in case of failure.
5649 * NOTE: Caller of this function can check the "hba->auto_bkops_enabled" flag
5650 * to know whether auto bkops is enabled or disabled after this function
5651 * returns control to it.
5653 static int ufshcd_bkops_ctrl(struct ufs_hba *hba,
5654 enum bkops_status status)
5657 u32 curr_status = 0;
5659 err = ufshcd_get_bkops_status(hba, &curr_status);
5661 dev_err(hba->dev, "%s: failed to get BKOPS status %d\n",
5664 } else if (curr_status > BKOPS_STATUS_MAX) {
5665 dev_err(hba->dev, "%s: invalid BKOPS status %d\n",
5666 __func__, curr_status);
5671 if (curr_status >= status)
5672 err = ufshcd_enable_auto_bkops(hba);
5674 err = ufshcd_disable_auto_bkops(hba);
5680 * ufshcd_urgent_bkops - handle urgent bkops exception event
5681 * @hba: per-adapter instance
5683 * Enable fBackgroundOpsEn flag in the device to permit background
5686 * If BKOPs is enabled, this function returns 0, 1 if the bkops in not enabled
5687 * and negative error value for any other failure.
5689 static int ufshcd_urgent_bkops(struct ufs_hba *hba)
5691 return ufshcd_bkops_ctrl(hba, hba->urgent_bkops_lvl);
5694 static inline int ufshcd_get_ee_status(struct ufs_hba *hba, u32 *status)
5696 return ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
5697 QUERY_ATTR_IDN_EE_STATUS, 0, 0, status);
5700 static void ufshcd_bkops_exception_event_handler(struct ufs_hba *hba)
5703 u32 curr_status = 0;
5705 if (hba->is_urgent_bkops_lvl_checked)
5706 goto enable_auto_bkops;
5708 err = ufshcd_get_bkops_status(hba, &curr_status);
5710 dev_err(hba->dev, "%s: failed to get BKOPS status %d\n",
5716 * We are seeing that some devices are raising the urgent bkops
5717 * exception events even when BKOPS status doesn't indicate performace
5718 * impacted or critical. Handle these device by determining their urgent
5719 * bkops status at runtime.
5721 if (curr_status < BKOPS_STATUS_PERF_IMPACT) {
5722 dev_err(hba->dev, "%s: device raised urgent BKOPS exception for bkops status %d\n",
5723 __func__, curr_status);
5724 /* update the current status as the urgent bkops level */
5725 hba->urgent_bkops_lvl = curr_status;
5726 hba->is_urgent_bkops_lvl_checked = true;
5730 err = ufshcd_enable_auto_bkops(hba);
5733 dev_err(hba->dev, "%s: failed to handle urgent bkops %d\n",
5737 static void ufshcd_temp_exception_event_handler(struct ufs_hba *hba, u16 status)
5741 if (ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
5742 QUERY_ATTR_IDN_CASE_ROUGH_TEMP, 0, 0, &value))
5745 dev_info(hba->dev, "exception Tcase %d\n", value - 80);
5747 ufs_hwmon_notify_event(hba, status & MASK_EE_URGENT_TEMP);
5750 * A placeholder for the platform vendors to add whatever additional
5755 static int __ufshcd_wb_toggle(struct ufs_hba *hba, bool set, enum flag_idn idn)
5758 enum query_opcode opcode = set ? UPIU_QUERY_OPCODE_SET_FLAG :
5759 UPIU_QUERY_OPCODE_CLEAR_FLAG;
5761 index = ufshcd_wb_get_query_index(hba);
5762 return ufshcd_query_flag_retry(hba, opcode, idn, index, NULL);
5765 int ufshcd_wb_toggle(struct ufs_hba *hba, bool enable)
5769 if (!ufshcd_is_wb_allowed(hba) ||
5770 hba->dev_info.wb_enabled == enable)
5773 ret = __ufshcd_wb_toggle(hba, enable, QUERY_FLAG_IDN_WB_EN);
5775 dev_err(hba->dev, "%s: Write Booster %s failed %d\n",
5776 __func__, enable ? "enabling" : "disabling", ret);
5780 hba->dev_info.wb_enabled = enable;
5781 dev_dbg(hba->dev, "%s: Write Booster %s\n",
5782 __func__, enable ? "enabled" : "disabled");
5787 static void ufshcd_wb_toggle_buf_flush_during_h8(struct ufs_hba *hba,
5792 ret = __ufshcd_wb_toggle(hba, enable,
5793 QUERY_FLAG_IDN_WB_BUFF_FLUSH_DURING_HIBERN8);
5795 dev_err(hba->dev, "%s: WB-Buf Flush during H8 %s failed %d\n",
5796 __func__, enable ? "enabling" : "disabling", ret);
5799 dev_dbg(hba->dev, "%s: WB-Buf Flush during H8 %s\n",
5800 __func__, enable ? "enabled" : "disabled");
5803 int ufshcd_wb_toggle_buf_flush(struct ufs_hba *hba, bool enable)
5807 if (!ufshcd_is_wb_allowed(hba) ||
5808 hba->dev_info.wb_buf_flush_enabled == enable)
5811 ret = __ufshcd_wb_toggle(hba, enable, QUERY_FLAG_IDN_WB_BUFF_FLUSH_EN);
5813 dev_err(hba->dev, "%s: WB-Buf Flush %s failed %d\n",
5814 __func__, enable ? "enabling" : "disabling", ret);
5818 hba->dev_info.wb_buf_flush_enabled = enable;
5819 dev_dbg(hba->dev, "%s: WB-Buf Flush %s\n",
5820 __func__, enable ? "enabled" : "disabled");
5825 static bool ufshcd_wb_presrv_usrspc_keep_vcc_on(struct ufs_hba *hba,
5832 index = ufshcd_wb_get_query_index(hba);
5833 ret = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
5834 QUERY_ATTR_IDN_CURR_WB_BUFF_SIZE,
5835 index, 0, &cur_buf);
5837 dev_err(hba->dev, "%s: dCurWriteBoosterBufferSize read failed %d\n",
5843 dev_info(hba->dev, "dCurWBBuf: %d WB disabled until free-space is available\n",
5847 /* Let it continue to flush when available buffer exceeds threshold */
5848 return avail_buf < hba->vps->wb_flush_threshold;
5851 static void ufshcd_wb_force_disable(struct ufs_hba *hba)
5853 if (ufshcd_is_wb_buf_flush_allowed(hba))
5854 ufshcd_wb_toggle_buf_flush(hba, false);
5856 ufshcd_wb_toggle_buf_flush_during_h8(hba, false);
5857 ufshcd_wb_toggle(hba, false);
5858 hba->caps &= ~UFSHCD_CAP_WB_EN;
5860 dev_info(hba->dev, "%s: WB force disabled\n", __func__);
5863 static bool ufshcd_is_wb_buf_lifetime_available(struct ufs_hba *hba)
5869 index = ufshcd_wb_get_query_index(hba);
5870 ret = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
5871 QUERY_ATTR_IDN_WB_BUFF_LIFE_TIME_EST,
5872 index, 0, &lifetime);
5875 "%s: bWriteBoosterBufferLifeTimeEst read failed %d\n",
5880 if (lifetime == UFS_WB_EXCEED_LIFETIME) {
5881 dev_err(hba->dev, "%s: WB buf lifetime is exhausted 0x%02X\n",
5882 __func__, lifetime);
5886 dev_dbg(hba->dev, "%s: WB buf lifetime is 0x%02X\n",
5887 __func__, lifetime);
5892 static bool ufshcd_wb_need_flush(struct ufs_hba *hba)
5898 if (!ufshcd_is_wb_allowed(hba))
5901 if (!ufshcd_is_wb_buf_lifetime_available(hba)) {
5902 ufshcd_wb_force_disable(hba);
5907 * The ufs device needs the vcc to be ON to flush.
5908 * With user-space reduction enabled, it's enough to enable flush
5909 * by checking only the available buffer. The threshold
5910 * defined here is > 90% full.
5911 * With user-space preserved enabled, the current-buffer
5912 * should be checked too because the wb buffer size can reduce
5913 * when disk tends to be full. This info is provided by current
5914 * buffer (dCurrentWriteBoosterBufferSize). There's no point in
5915 * keeping vcc on when current buffer is empty.
5917 index = ufshcd_wb_get_query_index(hba);
5918 ret = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
5919 QUERY_ATTR_IDN_AVAIL_WB_BUFF_SIZE,
5920 index, 0, &avail_buf);
5922 dev_warn(hba->dev, "%s: dAvailableWriteBoosterBufferSize read failed %d\n",
5927 if (!hba->dev_info.b_presrv_uspc_en)
5928 return avail_buf <= UFS_WB_BUF_REMAIN_PERCENT(10);
5930 return ufshcd_wb_presrv_usrspc_keep_vcc_on(hba, avail_buf);
5933 static void ufshcd_rpm_dev_flush_recheck_work(struct work_struct *work)
5935 struct ufs_hba *hba = container_of(to_delayed_work(work),
5937 rpm_dev_flush_recheck_work);
5939 * To prevent unnecessary VCC power drain after device finishes
5940 * WriteBooster buffer flush or Auto BKOPs, force runtime resume
5941 * after a certain delay to recheck the threshold by next runtime
5944 ufshcd_rpm_get_sync(hba);
5945 ufshcd_rpm_put_sync(hba);
5949 * ufshcd_exception_event_handler - handle exceptions raised by device
5950 * @work: pointer to work data
5952 * Read bExceptionEventStatus attribute from the device and handle the
5953 * exception event accordingly.
5955 static void ufshcd_exception_event_handler(struct work_struct *work)
5957 struct ufs_hba *hba;
5960 hba = container_of(work, struct ufs_hba, eeh_work);
5962 ufshcd_scsi_block_requests(hba);
5963 err = ufshcd_get_ee_status(hba, &status);
5965 dev_err(hba->dev, "%s: failed to get exception status %d\n",
5970 trace_ufshcd_exception_event(dev_name(hba->dev), status);
5972 if (status & hba->ee_drv_mask & MASK_EE_URGENT_BKOPS)
5973 ufshcd_bkops_exception_event_handler(hba);
5975 if (status & hba->ee_drv_mask & MASK_EE_URGENT_TEMP)
5976 ufshcd_temp_exception_event_handler(hba, status);
5978 ufs_debugfs_exception_event(hba, status);
5980 ufshcd_scsi_unblock_requests(hba);
5983 /* Complete requests that have door-bell cleared */
5984 static void ufshcd_complete_requests(struct ufs_hba *hba)
5986 ufshcd_transfer_req_compl(hba);
5987 ufshcd_tmc_handler(hba);
5991 * ufshcd_quirk_dl_nac_errors - This function checks if error handling is
5992 * to recover from the DL NAC errors or not.
5993 * @hba: per-adapter instance
5995 * Returns true if error handling is required, false otherwise
5997 static bool ufshcd_quirk_dl_nac_errors(struct ufs_hba *hba)
5999 unsigned long flags;
6000 bool err_handling = true;
6002 spin_lock_irqsave(hba->host->host_lock, flags);
6004 * UFS_DEVICE_QUIRK_RECOVERY_FROM_DL_NAC_ERRORS only workaround the
6005 * device fatal error and/or DL NAC & REPLAY timeout errors.
6007 if (hba->saved_err & (CONTROLLER_FATAL_ERROR | SYSTEM_BUS_FATAL_ERROR))
6010 if ((hba->saved_err & DEVICE_FATAL_ERROR) ||
6011 ((hba->saved_err & UIC_ERROR) &&
6012 (hba->saved_uic_err & UFSHCD_UIC_DL_TCx_REPLAY_ERROR)))
6015 if ((hba->saved_err & UIC_ERROR) &&
6016 (hba->saved_uic_err & UFSHCD_UIC_DL_NAC_RECEIVED_ERROR)) {
6019 * wait for 50ms to see if we can get any other errors or not.
6021 spin_unlock_irqrestore(hba->host->host_lock, flags);
6023 spin_lock_irqsave(hba->host->host_lock, flags);
6026 * now check if we have got any other severe errors other than
6029 if ((hba->saved_err & INT_FATAL_ERRORS) ||
6030 ((hba->saved_err & UIC_ERROR) &&
6031 (hba->saved_uic_err & ~UFSHCD_UIC_DL_NAC_RECEIVED_ERROR)))
6035 * As DL NAC is the only error received so far, send out NOP
6036 * command to confirm if link is still active or not.
6037 * - If we don't get any response then do error recovery.
6038 * - If we get response then clear the DL NAC error bit.
6041 spin_unlock_irqrestore(hba->host->host_lock, flags);
6042 err = ufshcd_verify_dev_init(hba);
6043 spin_lock_irqsave(hba->host->host_lock, flags);
6048 /* Link seems to be alive hence ignore the DL NAC errors */
6049 if (hba->saved_uic_err == UFSHCD_UIC_DL_NAC_RECEIVED_ERROR)
6050 hba->saved_err &= ~UIC_ERROR;
6051 /* clear NAC error */
6052 hba->saved_uic_err &= ~UFSHCD_UIC_DL_NAC_RECEIVED_ERROR;
6053 if (!hba->saved_uic_err)
6054 err_handling = false;
6057 spin_unlock_irqrestore(hba->host->host_lock, flags);
6058 return err_handling;
6061 /* host lock must be held before calling this func */
6062 static inline bool ufshcd_is_saved_err_fatal(struct ufs_hba *hba)
6064 return (hba->saved_uic_err & UFSHCD_UIC_DL_PA_INIT_ERROR) ||
6065 (hba->saved_err & (INT_FATAL_ERRORS | UFSHCD_UIC_HIBERN8_MASK));
6068 void ufshcd_schedule_eh_work(struct ufs_hba *hba)
6070 lockdep_assert_held(hba->host->host_lock);
6072 /* handle fatal errors only when link is not in error state */
6073 if (hba->ufshcd_state != UFSHCD_STATE_ERROR) {
6074 if (hba->force_reset || ufshcd_is_link_broken(hba) ||
6075 ufshcd_is_saved_err_fatal(hba))
6076 hba->ufshcd_state = UFSHCD_STATE_EH_SCHEDULED_FATAL;
6078 hba->ufshcd_state = UFSHCD_STATE_EH_SCHEDULED_NON_FATAL;
6079 queue_work(hba->eh_wq, &hba->eh_work);
6083 static void ufshcd_clk_scaling_allow(struct ufs_hba *hba, bool allow)
6085 down_write(&hba->clk_scaling_lock);
6086 hba->clk_scaling.is_allowed = allow;
6087 up_write(&hba->clk_scaling_lock);
6090 static void ufshcd_clk_scaling_suspend(struct ufs_hba *hba, bool suspend)
6093 if (hba->clk_scaling.is_enabled)
6094 ufshcd_suspend_clkscaling(hba);
6095 ufshcd_clk_scaling_allow(hba, false);
6097 ufshcd_clk_scaling_allow(hba, true);
6098 if (hba->clk_scaling.is_enabled)
6099 ufshcd_resume_clkscaling(hba);
6103 static void ufshcd_err_handling_prepare(struct ufs_hba *hba)
6105 ufshcd_rpm_get_sync(hba);
6106 if (pm_runtime_status_suspended(&hba->ufs_device_wlun->sdev_gendev) ||
6107 hba->is_sys_suspended) {
6108 enum ufs_pm_op pm_op;
6111 * Don't assume anything of resume, if
6112 * resume fails, irq and clocks can be OFF, and powers
6113 * can be OFF or in LPM.
6115 ufshcd_setup_hba_vreg(hba, true);
6116 ufshcd_enable_irq(hba);
6117 ufshcd_setup_vreg(hba, true);
6118 ufshcd_config_vreg_hpm(hba, hba->vreg_info.vccq);
6119 ufshcd_config_vreg_hpm(hba, hba->vreg_info.vccq2);
6120 ufshcd_hold(hba, false);
6121 if (!ufshcd_is_clkgating_allowed(hba))
6122 ufshcd_setup_clocks(hba, true);
6123 ufshcd_release(hba);
6124 pm_op = hba->is_sys_suspended ? UFS_SYSTEM_PM : UFS_RUNTIME_PM;
6125 ufshcd_vops_resume(hba, pm_op);
6127 ufshcd_hold(hba, false);
6128 if (ufshcd_is_clkscaling_supported(hba) &&
6129 hba->clk_scaling.is_enabled)
6130 ufshcd_suspend_clkscaling(hba);
6131 ufshcd_clk_scaling_allow(hba, false);
6133 ufshcd_scsi_block_requests(hba);
6134 /* Drain ufshcd_queuecommand() */
6136 cancel_work_sync(&hba->eeh_work);
6139 static void ufshcd_err_handling_unprepare(struct ufs_hba *hba)
6141 ufshcd_scsi_unblock_requests(hba);
6142 ufshcd_release(hba);
6143 if (ufshcd_is_clkscaling_supported(hba))
6144 ufshcd_clk_scaling_suspend(hba, false);
6145 ufshcd_rpm_put(hba);
6148 static inline bool ufshcd_err_handling_should_stop(struct ufs_hba *hba)
6150 return (!hba->is_powered || hba->shutting_down ||
6151 !hba->ufs_device_wlun ||
6152 hba->ufshcd_state == UFSHCD_STATE_ERROR ||
6153 (!(hba->saved_err || hba->saved_uic_err || hba->force_reset ||
6154 ufshcd_is_link_broken(hba))));
6158 static void ufshcd_recover_pm_error(struct ufs_hba *hba)
6160 struct Scsi_Host *shost = hba->host;
6161 struct scsi_device *sdev;
6162 struct request_queue *q;
6165 hba->is_sys_suspended = false;
6167 * Set RPM status of wlun device to RPM_ACTIVE,
6168 * this also clears its runtime error.
6170 ret = pm_runtime_set_active(&hba->ufs_device_wlun->sdev_gendev);
6172 /* hba device might have a runtime error otherwise */
6174 ret = pm_runtime_set_active(hba->dev);
6176 * If wlun device had runtime error, we also need to resume those
6177 * consumer scsi devices in case any of them has failed to be
6178 * resumed due to supplier runtime resume failure. This is to unblock
6179 * blk_queue_enter in case there are bios waiting inside it.
6182 shost_for_each_device(sdev, shost) {
6183 q = sdev->request_queue;
6184 if (q->dev && (q->rpm_status == RPM_SUSPENDED ||
6185 q->rpm_status == RPM_SUSPENDING))
6186 pm_request_resume(q->dev);
6191 static inline void ufshcd_recover_pm_error(struct ufs_hba *hba)
6196 static bool ufshcd_is_pwr_mode_restore_needed(struct ufs_hba *hba)
6198 struct ufs_pa_layer_attr *pwr_info = &hba->pwr_info;
6201 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_PWRMODE), &mode);
6203 if (pwr_info->pwr_rx != ((mode >> PWRMODE_RX_OFFSET) & PWRMODE_MASK))
6206 if (pwr_info->pwr_tx != (mode & PWRMODE_MASK))
6212 static bool ufshcd_abort_all(struct ufs_hba *hba)
6214 bool needs_reset = false;
6217 /* Clear pending transfer requests */
6218 for_each_set_bit(tag, &hba->outstanding_reqs, hba->nutrs) {
6219 ret = ufshcd_try_to_abort_task(hba, tag);
6220 dev_err(hba->dev, "Aborting tag %d / CDB %#02x %s\n", tag,
6221 hba->lrb[tag].cmd ? hba->lrb[tag].cmd->cmnd[0] : -1,
6222 ret ? "failed" : "succeeded");
6229 /* Clear pending task management requests */
6230 for_each_set_bit(tag, &hba->outstanding_tasks, hba->nutmrs) {
6231 if (ufshcd_clear_tm_cmd(hba, tag)) {
6238 /* Complete the requests that are cleared by s/w */
6239 ufshcd_complete_requests(hba);
6245 * ufshcd_err_handler - handle UFS errors that require s/w attention
6246 * @work: pointer to work structure
6248 static void ufshcd_err_handler(struct work_struct *work)
6250 int retries = MAX_ERR_HANDLER_RETRIES;
6251 struct ufs_hba *hba;
6252 unsigned long flags;
6257 hba = container_of(work, struct ufs_hba, eh_work);
6260 "%s started; HBA state %s; powered %d; shutting down %d; saved_err = %d; saved_uic_err = %d; force_reset = %d%s\n",
6261 __func__, ufshcd_state_name[hba->ufshcd_state],
6262 hba->is_powered, hba->shutting_down, hba->saved_err,
6263 hba->saved_uic_err, hba->force_reset,
6264 ufshcd_is_link_broken(hba) ? "; link is broken" : "");
6266 down(&hba->host_sem);
6267 spin_lock_irqsave(hba->host->host_lock, flags);
6268 if (ufshcd_err_handling_should_stop(hba)) {
6269 if (hba->ufshcd_state != UFSHCD_STATE_ERROR)
6270 hba->ufshcd_state = UFSHCD_STATE_OPERATIONAL;
6271 spin_unlock_irqrestore(hba->host->host_lock, flags);
6275 ufshcd_set_eh_in_progress(hba);
6276 spin_unlock_irqrestore(hba->host->host_lock, flags);
6277 ufshcd_err_handling_prepare(hba);
6278 /* Complete requests that have door-bell cleared by h/w */
6279 ufshcd_complete_requests(hba);
6280 spin_lock_irqsave(hba->host->host_lock, flags);
6282 needs_restore = false;
6283 needs_reset = false;
6285 if (hba->ufshcd_state != UFSHCD_STATE_ERROR)
6286 hba->ufshcd_state = UFSHCD_STATE_RESET;
6288 * A full reset and restore might have happened after preparation
6289 * is finished, double check whether we should stop.
6291 if (ufshcd_err_handling_should_stop(hba))
6292 goto skip_err_handling;
6294 if (hba->dev_quirks & UFS_DEVICE_QUIRK_RECOVERY_FROM_DL_NAC_ERRORS) {
6297 spin_unlock_irqrestore(hba->host->host_lock, flags);
6298 /* release the lock as ufshcd_quirk_dl_nac_errors() may sleep */
6299 ret = ufshcd_quirk_dl_nac_errors(hba);
6300 spin_lock_irqsave(hba->host->host_lock, flags);
6301 if (!ret && ufshcd_err_handling_should_stop(hba))
6302 goto skip_err_handling;
6305 if ((hba->saved_err & (INT_FATAL_ERRORS | UFSHCD_UIC_HIBERN8_MASK)) ||
6306 (hba->saved_uic_err &&
6307 (hba->saved_uic_err != UFSHCD_UIC_PA_GENERIC_ERROR))) {
6308 bool pr_prdt = !!(hba->saved_err & SYSTEM_BUS_FATAL_ERROR);
6310 spin_unlock_irqrestore(hba->host->host_lock, flags);
6311 ufshcd_print_host_state(hba);
6312 ufshcd_print_pwr_info(hba);
6313 ufshcd_print_evt_hist(hba);
6314 ufshcd_print_tmrs(hba, hba->outstanding_tasks);
6315 ufshcd_print_trs(hba, hba->outstanding_reqs, pr_prdt);
6316 spin_lock_irqsave(hba->host->host_lock, flags);
6320 * if host reset is required then skip clearing the pending
6321 * transfers forcefully because they will get cleared during
6322 * host reset and restore
6324 if (hba->force_reset || ufshcd_is_link_broken(hba) ||
6325 ufshcd_is_saved_err_fatal(hba) ||
6326 ((hba->saved_err & UIC_ERROR) &&
6327 (hba->saved_uic_err & (UFSHCD_UIC_DL_NAC_RECEIVED_ERROR |
6328 UFSHCD_UIC_DL_TCx_REPLAY_ERROR)))) {
6334 * If LINERESET was caught, UFS might have been put to PWM mode,
6335 * check if power mode restore is needed.
6337 if (hba->saved_uic_err & UFSHCD_UIC_PA_GENERIC_ERROR) {
6338 hba->saved_uic_err &= ~UFSHCD_UIC_PA_GENERIC_ERROR;
6339 if (!hba->saved_uic_err)
6340 hba->saved_err &= ~UIC_ERROR;
6341 spin_unlock_irqrestore(hba->host->host_lock, flags);
6342 if (ufshcd_is_pwr_mode_restore_needed(hba))
6343 needs_restore = true;
6344 spin_lock_irqsave(hba->host->host_lock, flags);
6345 if (!hba->saved_err && !needs_restore)
6346 goto skip_err_handling;
6349 hba->silence_err_logs = true;
6350 /* release lock as clear command might sleep */
6351 spin_unlock_irqrestore(hba->host->host_lock, flags);
6353 needs_reset = ufshcd_abort_all(hba);
6355 spin_lock_irqsave(hba->host->host_lock, flags);
6356 hba->silence_err_logs = false;
6361 * After all reqs and tasks are cleared from doorbell,
6362 * now it is safe to retore power mode.
6364 if (needs_restore) {
6365 spin_unlock_irqrestore(hba->host->host_lock, flags);
6367 * Hold the scaling lock just in case dev cmds
6368 * are sent via bsg and/or sysfs.
6370 down_write(&hba->clk_scaling_lock);
6371 hba->force_pmc = true;
6372 pmc_err = ufshcd_config_pwr_mode(hba, &(hba->pwr_info));
6375 dev_err(hba->dev, "%s: Failed to restore power mode, err = %d\n",
6378 hba->force_pmc = false;
6379 ufshcd_print_pwr_info(hba);
6380 up_write(&hba->clk_scaling_lock);
6381 spin_lock_irqsave(hba->host->host_lock, flags);
6385 /* Fatal errors need reset */
6389 hba->force_reset = false;
6390 spin_unlock_irqrestore(hba->host->host_lock, flags);
6391 err = ufshcd_reset_and_restore(hba);
6393 dev_err(hba->dev, "%s: reset and restore failed with err %d\n",
6396 ufshcd_recover_pm_error(hba);
6397 spin_lock_irqsave(hba->host->host_lock, flags);
6402 if (hba->ufshcd_state == UFSHCD_STATE_RESET)
6403 hba->ufshcd_state = UFSHCD_STATE_OPERATIONAL;
6404 if (hba->saved_err || hba->saved_uic_err)
6405 dev_err_ratelimited(hba->dev, "%s: exit: saved_err 0x%x saved_uic_err 0x%x",
6406 __func__, hba->saved_err, hba->saved_uic_err);
6408 /* Exit in an operational state or dead */
6409 if (hba->ufshcd_state != UFSHCD_STATE_OPERATIONAL &&
6410 hba->ufshcd_state != UFSHCD_STATE_ERROR) {
6413 hba->ufshcd_state = UFSHCD_STATE_ERROR;
6415 ufshcd_clear_eh_in_progress(hba);
6416 spin_unlock_irqrestore(hba->host->host_lock, flags);
6417 ufshcd_err_handling_unprepare(hba);
6420 dev_info(hba->dev, "%s finished; HBA state %s\n", __func__,
6421 ufshcd_state_name[hba->ufshcd_state]);
6425 * ufshcd_update_uic_error - check and set fatal UIC error flags.
6426 * @hba: per-adapter instance
6429 * IRQ_HANDLED - If interrupt is valid
6430 * IRQ_NONE - If invalid interrupt
6432 static irqreturn_t ufshcd_update_uic_error(struct ufs_hba *hba)
6435 irqreturn_t retval = IRQ_NONE;
6437 /* PHY layer error */
6438 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_PHY_ADAPTER_LAYER);
6439 if ((reg & UIC_PHY_ADAPTER_LAYER_ERROR) &&
6440 (reg & UIC_PHY_ADAPTER_LAYER_ERROR_CODE_MASK)) {
6441 ufshcd_update_evt_hist(hba, UFS_EVT_PA_ERR, reg);
6443 * To know whether this error is fatal or not, DB timeout
6444 * must be checked but this error is handled separately.
6446 if (reg & UIC_PHY_ADAPTER_LAYER_LANE_ERR_MASK)
6447 dev_dbg(hba->dev, "%s: UIC Lane error reported\n",
6450 /* Got a LINERESET indication. */
6451 if (reg & UIC_PHY_ADAPTER_LAYER_GENERIC_ERROR) {
6452 struct uic_command *cmd = NULL;
6454 hba->uic_error |= UFSHCD_UIC_PA_GENERIC_ERROR;
6455 if (hba->uic_async_done && hba->active_uic_cmd)
6456 cmd = hba->active_uic_cmd;
6458 * Ignore the LINERESET during power mode change
6459 * operation via DME_SET command.
6461 if (cmd && (cmd->command == UIC_CMD_DME_SET))
6462 hba->uic_error &= ~UFSHCD_UIC_PA_GENERIC_ERROR;
6464 retval |= IRQ_HANDLED;
6467 /* PA_INIT_ERROR is fatal and needs UIC reset */
6468 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_DATA_LINK_LAYER);
6469 if ((reg & UIC_DATA_LINK_LAYER_ERROR) &&
6470 (reg & UIC_DATA_LINK_LAYER_ERROR_CODE_MASK)) {
6471 ufshcd_update_evt_hist(hba, UFS_EVT_DL_ERR, reg);
6473 if (reg & UIC_DATA_LINK_LAYER_ERROR_PA_INIT)
6474 hba->uic_error |= UFSHCD_UIC_DL_PA_INIT_ERROR;
6475 else if (hba->dev_quirks &
6476 UFS_DEVICE_QUIRK_RECOVERY_FROM_DL_NAC_ERRORS) {
6477 if (reg & UIC_DATA_LINK_LAYER_ERROR_NAC_RECEIVED)
6479 UFSHCD_UIC_DL_NAC_RECEIVED_ERROR;
6480 else if (reg & UIC_DATA_LINK_LAYER_ERROR_TCx_REPLAY_TIMEOUT)
6481 hba->uic_error |= UFSHCD_UIC_DL_TCx_REPLAY_ERROR;
6483 retval |= IRQ_HANDLED;
6486 /* UIC NL/TL/DME errors needs software retry */
6487 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_NETWORK_LAYER);
6488 if ((reg & UIC_NETWORK_LAYER_ERROR) &&
6489 (reg & UIC_NETWORK_LAYER_ERROR_CODE_MASK)) {
6490 ufshcd_update_evt_hist(hba, UFS_EVT_NL_ERR, reg);
6491 hba->uic_error |= UFSHCD_UIC_NL_ERROR;
6492 retval |= IRQ_HANDLED;
6495 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_TRANSPORT_LAYER);
6496 if ((reg & UIC_TRANSPORT_LAYER_ERROR) &&
6497 (reg & UIC_TRANSPORT_LAYER_ERROR_CODE_MASK)) {
6498 ufshcd_update_evt_hist(hba, UFS_EVT_TL_ERR, reg);
6499 hba->uic_error |= UFSHCD_UIC_TL_ERROR;
6500 retval |= IRQ_HANDLED;
6503 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_DME);
6504 if ((reg & UIC_DME_ERROR) &&
6505 (reg & UIC_DME_ERROR_CODE_MASK)) {
6506 ufshcd_update_evt_hist(hba, UFS_EVT_DME_ERR, reg);
6507 hba->uic_error |= UFSHCD_UIC_DME_ERROR;
6508 retval |= IRQ_HANDLED;
6511 dev_dbg(hba->dev, "%s: UIC error flags = 0x%08x\n",
6512 __func__, hba->uic_error);
6517 * ufshcd_check_errors - Check for errors that need s/w attention
6518 * @hba: per-adapter instance
6519 * @intr_status: interrupt status generated by the controller
6522 * IRQ_HANDLED - If interrupt is valid
6523 * IRQ_NONE - If invalid interrupt
6525 static irqreturn_t ufshcd_check_errors(struct ufs_hba *hba, u32 intr_status)
6527 bool queue_eh_work = false;
6528 irqreturn_t retval = IRQ_NONE;
6530 spin_lock(hba->host->host_lock);
6531 hba->errors |= UFSHCD_ERROR_MASK & intr_status;
6533 if (hba->errors & INT_FATAL_ERRORS) {
6534 ufshcd_update_evt_hist(hba, UFS_EVT_FATAL_ERR,
6536 queue_eh_work = true;
6539 if (hba->errors & UIC_ERROR) {
6541 retval = ufshcd_update_uic_error(hba);
6543 queue_eh_work = true;
6546 if (hba->errors & UFSHCD_UIC_HIBERN8_MASK) {
6548 "%s: Auto Hibern8 %s failed - status: 0x%08x, upmcrs: 0x%08x\n",
6549 __func__, (hba->errors & UIC_HIBERNATE_ENTER) ?
6551 hba->errors, ufshcd_get_upmcrs(hba));
6552 ufshcd_update_evt_hist(hba, UFS_EVT_AUTO_HIBERN8_ERR,
6554 ufshcd_set_link_broken(hba);
6555 queue_eh_work = true;
6558 if (queue_eh_work) {
6560 * update the transfer error masks to sticky bits, let's do this
6561 * irrespective of current ufshcd_state.
6563 hba->saved_err |= hba->errors;
6564 hba->saved_uic_err |= hba->uic_error;
6566 /* dump controller state before resetting */
6567 if ((hba->saved_err &
6568 (INT_FATAL_ERRORS | UFSHCD_UIC_HIBERN8_MASK)) ||
6569 (hba->saved_uic_err &&
6570 (hba->saved_uic_err != UFSHCD_UIC_PA_GENERIC_ERROR))) {
6571 dev_err(hba->dev, "%s: saved_err 0x%x saved_uic_err 0x%x\n",
6572 __func__, hba->saved_err,
6573 hba->saved_uic_err);
6574 ufshcd_dump_regs(hba, 0, UFSHCI_REG_SPACE_SIZE,
6576 ufshcd_print_pwr_info(hba);
6578 ufshcd_schedule_eh_work(hba);
6579 retval |= IRQ_HANDLED;
6582 * if (!queue_eh_work) -
6583 * Other errors are either non-fatal where host recovers
6584 * itself without s/w intervention or errors that will be
6585 * handled by the SCSI core layer.
6589 spin_unlock(hba->host->host_lock);
6594 * ufshcd_tmc_handler - handle task management function completion
6595 * @hba: per adapter instance
6598 * IRQ_HANDLED - If interrupt is valid
6599 * IRQ_NONE - If invalid interrupt
6601 static irqreturn_t ufshcd_tmc_handler(struct ufs_hba *hba)
6603 unsigned long flags, pending, issued;
6604 irqreturn_t ret = IRQ_NONE;
6607 spin_lock_irqsave(hba->host->host_lock, flags);
6608 pending = ufshcd_readl(hba, REG_UTP_TASK_REQ_DOOR_BELL);
6609 issued = hba->outstanding_tasks & ~pending;
6610 for_each_set_bit(tag, &issued, hba->nutmrs) {
6611 struct request *req = hba->tmf_rqs[tag];
6612 struct completion *c = req->end_io_data;
6617 spin_unlock_irqrestore(hba->host->host_lock, flags);
6623 * ufshcd_sl_intr - Interrupt service routine
6624 * @hba: per adapter instance
6625 * @intr_status: contains interrupts generated by the controller
6628 * IRQ_HANDLED - If interrupt is valid
6629 * IRQ_NONE - If invalid interrupt
6631 static irqreturn_t ufshcd_sl_intr(struct ufs_hba *hba, u32 intr_status)
6633 irqreturn_t retval = IRQ_NONE;
6635 if (intr_status & UFSHCD_UIC_MASK)
6636 retval |= ufshcd_uic_cmd_compl(hba, intr_status);
6638 if (intr_status & UFSHCD_ERROR_MASK || hba->errors)
6639 retval |= ufshcd_check_errors(hba, intr_status);
6641 if (intr_status & UTP_TASK_REQ_COMPL)
6642 retval |= ufshcd_tmc_handler(hba);
6644 if (intr_status & UTP_TRANSFER_REQ_COMPL)
6645 retval |= ufshcd_transfer_req_compl(hba);
6651 * ufshcd_intr - Main interrupt service routine
6653 * @__hba: pointer to adapter instance
6656 * IRQ_HANDLED - If interrupt is valid
6657 * IRQ_NONE - If invalid interrupt
6659 static irqreturn_t ufshcd_intr(int irq, void *__hba)
6661 u32 intr_status, enabled_intr_status = 0;
6662 irqreturn_t retval = IRQ_NONE;
6663 struct ufs_hba *hba = __hba;
6664 int retries = hba->nutrs;
6666 intr_status = ufshcd_readl(hba, REG_INTERRUPT_STATUS);
6667 hba->ufs_stats.last_intr_status = intr_status;
6668 hba->ufs_stats.last_intr_ts = local_clock();
6671 * There could be max of hba->nutrs reqs in flight and in worst case
6672 * if the reqs get finished 1 by 1 after the interrupt status is
6673 * read, make sure we handle them by checking the interrupt status
6674 * again in a loop until we process all of the reqs before returning.
6676 while (intr_status && retries--) {
6677 enabled_intr_status =
6678 intr_status & ufshcd_readl(hba, REG_INTERRUPT_ENABLE);
6679 ufshcd_writel(hba, intr_status, REG_INTERRUPT_STATUS);
6680 if (enabled_intr_status)
6681 retval |= ufshcd_sl_intr(hba, enabled_intr_status);
6683 intr_status = ufshcd_readl(hba, REG_INTERRUPT_STATUS);
6686 if (enabled_intr_status && retval == IRQ_NONE &&
6687 (!(enabled_intr_status & UTP_TRANSFER_REQ_COMPL) ||
6688 hba->outstanding_reqs) && !ufshcd_eh_in_progress(hba)) {
6689 dev_err(hba->dev, "%s: Unhandled interrupt 0x%08x (0x%08x, 0x%08x)\n",
6692 hba->ufs_stats.last_intr_status,
6693 enabled_intr_status);
6694 ufshcd_dump_regs(hba, 0, UFSHCI_REG_SPACE_SIZE, "host_regs: ");
6700 static int ufshcd_clear_tm_cmd(struct ufs_hba *hba, int tag)
6703 u32 mask = 1 << tag;
6704 unsigned long flags;
6706 if (!test_bit(tag, &hba->outstanding_tasks))
6709 spin_lock_irqsave(hba->host->host_lock, flags);
6710 ufshcd_utmrl_clear(hba, tag);
6711 spin_unlock_irqrestore(hba->host->host_lock, flags);
6713 /* poll for max. 1 sec to clear door bell register by h/w */
6714 err = ufshcd_wait_for_register(hba,
6715 REG_UTP_TASK_REQ_DOOR_BELL,
6716 mask, 0, 1000, 1000);
6718 dev_err(hba->dev, "Clearing task management function with tag %d %s\n",
6719 tag, err ? "succeeded" : "failed");
6725 static int __ufshcd_issue_tm_cmd(struct ufs_hba *hba,
6726 struct utp_task_req_desc *treq, u8 tm_function)
6728 struct request_queue *q = hba->tmf_queue;
6729 struct Scsi_Host *host = hba->host;
6730 DECLARE_COMPLETION_ONSTACK(wait);
6731 struct request *req;
6732 unsigned long flags;
6736 * blk_mq_alloc_request() is used here only to get a free tag.
6738 req = blk_mq_alloc_request(q, REQ_OP_DRV_OUT, 0);
6740 return PTR_ERR(req);
6742 req->end_io_data = &wait;
6743 ufshcd_hold(hba, false);
6745 spin_lock_irqsave(host->host_lock, flags);
6747 task_tag = req->tag;
6748 WARN_ONCE(task_tag < 0 || task_tag >= hba->nutmrs, "Invalid tag %d\n",
6750 hba->tmf_rqs[req->tag] = req;
6751 treq->upiu_req.req_header.dword_0 |= cpu_to_be32(task_tag);
6753 memcpy(hba->utmrdl_base_addr + task_tag, treq, sizeof(*treq));
6754 ufshcd_vops_setup_task_mgmt(hba, task_tag, tm_function);
6756 /* send command to the controller */
6757 __set_bit(task_tag, &hba->outstanding_tasks);
6759 ufshcd_writel(hba, 1 << task_tag, REG_UTP_TASK_REQ_DOOR_BELL);
6760 /* Make sure that doorbell is committed immediately */
6763 spin_unlock_irqrestore(host->host_lock, flags);
6765 ufshcd_add_tm_upiu_trace(hba, task_tag, UFS_TM_SEND);
6767 /* wait until the task management command is completed */
6768 err = wait_for_completion_io_timeout(&wait,
6769 msecs_to_jiffies(TM_CMD_TIMEOUT));
6771 ufshcd_add_tm_upiu_trace(hba, task_tag, UFS_TM_ERR);
6772 dev_err(hba->dev, "%s: task management cmd 0x%.2x timed-out\n",
6773 __func__, tm_function);
6774 if (ufshcd_clear_tm_cmd(hba, task_tag))
6775 dev_WARN(hba->dev, "%s: unable to clear tm cmd (slot %d) after timeout\n",
6776 __func__, task_tag);
6780 memcpy(treq, hba->utmrdl_base_addr + task_tag, sizeof(*treq));
6782 ufshcd_add_tm_upiu_trace(hba, task_tag, UFS_TM_COMP);
6785 spin_lock_irqsave(hba->host->host_lock, flags);
6786 hba->tmf_rqs[req->tag] = NULL;
6787 __clear_bit(task_tag, &hba->outstanding_tasks);
6788 spin_unlock_irqrestore(hba->host->host_lock, flags);
6790 ufshcd_release(hba);
6791 blk_mq_free_request(req);
6797 * ufshcd_issue_tm_cmd - issues task management commands to controller
6798 * @hba: per adapter instance
6799 * @lun_id: LUN ID to which TM command is sent
6800 * @task_id: task ID to which the TM command is applicable
6801 * @tm_function: task management function opcode
6802 * @tm_response: task management service response return value
6804 * Returns non-zero value on error, zero on success.
6806 static int ufshcd_issue_tm_cmd(struct ufs_hba *hba, int lun_id, int task_id,
6807 u8 tm_function, u8 *tm_response)
6809 struct utp_task_req_desc treq = { { 0 }, };
6810 enum utp_ocs ocs_value;
6813 /* Configure task request descriptor */
6814 treq.header.dword_0 = cpu_to_le32(UTP_REQ_DESC_INT_CMD);
6815 treq.header.dword_2 = cpu_to_le32(OCS_INVALID_COMMAND_STATUS);
6817 /* Configure task request UPIU */
6818 treq.upiu_req.req_header.dword_0 = cpu_to_be32(lun_id << 8) |
6819 cpu_to_be32(UPIU_TRANSACTION_TASK_REQ << 24);
6820 treq.upiu_req.req_header.dword_1 = cpu_to_be32(tm_function << 16);
6823 * The host shall provide the same value for LUN field in the basic
6824 * header and for Input Parameter.
6826 treq.upiu_req.input_param1 = cpu_to_be32(lun_id);
6827 treq.upiu_req.input_param2 = cpu_to_be32(task_id);
6829 err = __ufshcd_issue_tm_cmd(hba, &treq, tm_function);
6830 if (err == -ETIMEDOUT)
6833 ocs_value = le32_to_cpu(treq.header.dword_2) & MASK_OCS;
6834 if (ocs_value != OCS_SUCCESS)
6835 dev_err(hba->dev, "%s: failed, ocs = 0x%x\n",
6836 __func__, ocs_value);
6837 else if (tm_response)
6838 *tm_response = be32_to_cpu(treq.upiu_rsp.output_param1) &
6839 MASK_TM_SERVICE_RESP;
6844 * ufshcd_issue_devman_upiu_cmd - API for sending "utrd" type requests
6845 * @hba: per-adapter instance
6846 * @req_upiu: upiu request
6847 * @rsp_upiu: upiu reply
6848 * @desc_buff: pointer to descriptor buffer, NULL if NA
6849 * @buff_len: descriptor size, 0 if NA
6850 * @cmd_type: specifies the type (NOP, Query...)
6851 * @desc_op: descriptor operation
6853 * Those type of requests uses UTP Transfer Request Descriptor - utrd.
6854 * Therefore, it "rides" the device management infrastructure: uses its tag and
6855 * tasks work queues.
6857 * Since there is only one available tag for device management commands,
6858 * the caller is expected to hold the hba->dev_cmd.lock mutex.
6860 static int ufshcd_issue_devman_upiu_cmd(struct ufs_hba *hba,
6861 struct utp_upiu_req *req_upiu,
6862 struct utp_upiu_req *rsp_upiu,
6863 u8 *desc_buff, int *buff_len,
6864 enum dev_cmd_type cmd_type,
6865 enum query_opcode desc_op)
6867 DECLARE_COMPLETION_ONSTACK(wait);
6868 const u32 tag = hba->reserved_slot;
6869 struct ufshcd_lrb *lrbp;
6873 /* Protects use of hba->reserved_slot. */
6874 lockdep_assert_held(&hba->dev_cmd.lock);
6876 down_read(&hba->clk_scaling_lock);
6878 lrbp = &hba->lrb[tag];
6881 lrbp->task_tag = tag;
6883 lrbp->intr_cmd = true;
6884 ufshcd_prepare_lrbp_crypto(NULL, lrbp);
6885 hba->dev_cmd.type = cmd_type;
6887 if (hba->ufs_version <= ufshci_version(1, 1))
6888 lrbp->command_type = UTP_CMD_TYPE_DEV_MANAGE;
6890 lrbp->command_type = UTP_CMD_TYPE_UFS_STORAGE;
6892 /* update the task tag in the request upiu */
6893 req_upiu->header.dword_0 |= cpu_to_be32(tag);
6895 ufshcd_prepare_req_desc_hdr(lrbp, &upiu_flags, DMA_NONE, 0);
6897 /* just copy the upiu request as it is */
6898 memcpy(lrbp->ucd_req_ptr, req_upiu, sizeof(*lrbp->ucd_req_ptr));
6899 if (desc_buff && desc_op == UPIU_QUERY_OPCODE_WRITE_DESC) {
6900 /* The Data Segment Area is optional depending upon the query
6901 * function value. for WRITE DESCRIPTOR, the data segment
6902 * follows right after the tsf.
6904 memcpy(lrbp->ucd_req_ptr + 1, desc_buff, *buff_len);
6908 memset(lrbp->ucd_rsp_ptr, 0, sizeof(struct utp_upiu_rsp));
6910 hba->dev_cmd.complete = &wait;
6912 ufshcd_add_query_upiu_trace(hba, UFS_QUERY_SEND, lrbp->ucd_req_ptr);
6914 ufshcd_send_command(hba, tag);
6916 * ignore the returning value here - ufshcd_check_query_response is
6917 * bound to fail since dev_cmd.query and dev_cmd.type were left empty.
6918 * read the response directly ignoring all errors.
6920 ufshcd_wait_for_dev_cmd(hba, lrbp, QUERY_REQ_TIMEOUT);
6922 /* just copy the upiu response as it is */
6923 memcpy(rsp_upiu, lrbp->ucd_rsp_ptr, sizeof(*rsp_upiu));
6924 if (desc_buff && desc_op == UPIU_QUERY_OPCODE_READ_DESC) {
6925 u8 *descp = (u8 *)lrbp->ucd_rsp_ptr + sizeof(*rsp_upiu);
6926 u16 resp_len = be32_to_cpu(lrbp->ucd_rsp_ptr->header.dword_2) &
6927 MASK_QUERY_DATA_SEG_LEN;
6929 if (*buff_len >= resp_len) {
6930 memcpy(desc_buff, descp, resp_len);
6931 *buff_len = resp_len;
6934 "%s: rsp size %d is bigger than buffer size %d",
6935 __func__, resp_len, *buff_len);
6940 ufshcd_add_query_upiu_trace(hba, err ? UFS_QUERY_ERR : UFS_QUERY_COMP,
6941 (struct utp_upiu_req *)lrbp->ucd_rsp_ptr);
6943 up_read(&hba->clk_scaling_lock);
6948 * ufshcd_exec_raw_upiu_cmd - API function for sending raw upiu commands
6949 * @hba: per-adapter instance
6950 * @req_upiu: upiu request
6951 * @rsp_upiu: upiu reply - only 8 DW as we do not support scsi commands
6952 * @msgcode: message code, one of UPIU Transaction Codes Initiator to Target
6953 * @desc_buff: pointer to descriptor buffer, NULL if NA
6954 * @buff_len: descriptor size, 0 if NA
6955 * @desc_op: descriptor operation
6957 * Supports UTP Transfer requests (nop and query), and UTP Task
6958 * Management requests.
6959 * It is up to the caller to fill the upiu conent properly, as it will
6960 * be copied without any further input validations.
6962 int ufshcd_exec_raw_upiu_cmd(struct ufs_hba *hba,
6963 struct utp_upiu_req *req_upiu,
6964 struct utp_upiu_req *rsp_upiu,
6966 u8 *desc_buff, int *buff_len,
6967 enum query_opcode desc_op)
6970 enum dev_cmd_type cmd_type = DEV_CMD_TYPE_QUERY;
6971 struct utp_task_req_desc treq = { { 0 }, };
6972 enum utp_ocs ocs_value;
6973 u8 tm_f = be32_to_cpu(req_upiu->header.dword_1) >> 16 & MASK_TM_FUNC;
6976 case UPIU_TRANSACTION_NOP_OUT:
6977 cmd_type = DEV_CMD_TYPE_NOP;
6979 case UPIU_TRANSACTION_QUERY_REQ:
6980 ufshcd_hold(hba, false);
6981 mutex_lock(&hba->dev_cmd.lock);
6982 err = ufshcd_issue_devman_upiu_cmd(hba, req_upiu, rsp_upiu,
6983 desc_buff, buff_len,
6985 mutex_unlock(&hba->dev_cmd.lock);
6986 ufshcd_release(hba);
6989 case UPIU_TRANSACTION_TASK_REQ:
6990 treq.header.dword_0 = cpu_to_le32(UTP_REQ_DESC_INT_CMD);
6991 treq.header.dword_2 = cpu_to_le32(OCS_INVALID_COMMAND_STATUS);
6993 memcpy(&treq.upiu_req, req_upiu, sizeof(*req_upiu));
6995 err = __ufshcd_issue_tm_cmd(hba, &treq, tm_f);
6996 if (err == -ETIMEDOUT)
6999 ocs_value = le32_to_cpu(treq.header.dword_2) & MASK_OCS;
7000 if (ocs_value != OCS_SUCCESS) {
7001 dev_err(hba->dev, "%s: failed, ocs = 0x%x\n", __func__,
7006 memcpy(rsp_upiu, &treq.upiu_rsp, sizeof(*rsp_upiu));
7019 * ufshcd_advanced_rpmb_req_handler - handle advanced RPMB request
7020 * @hba: per adapter instance
7021 * @req_upiu: upiu request
7022 * @rsp_upiu: upiu reply
7023 * @req_ehs: EHS field which contains Advanced RPMB Request Message
7024 * @rsp_ehs: EHS field which returns Advanced RPMB Response Message
7025 * @sg_cnt: The number of sg lists actually used
7026 * @sg_list: Pointer to SG list when DATA IN/OUT UPIU is required in ARPMB operation
7027 * @dir: DMA direction
7029 * Returns zero on success, non-zero on failure
7031 int ufshcd_advanced_rpmb_req_handler(struct ufs_hba *hba, struct utp_upiu_req *req_upiu,
7032 struct utp_upiu_req *rsp_upiu, struct ufs_ehs *req_ehs,
7033 struct ufs_ehs *rsp_ehs, int sg_cnt, struct scatterlist *sg_list,
7034 enum dma_data_direction dir)
7036 DECLARE_COMPLETION_ONSTACK(wait);
7037 const u32 tag = hba->reserved_slot;
7038 struct ufshcd_lrb *lrbp;
7045 /* Protects use of hba->reserved_slot. */
7046 ufshcd_hold(hba, false);
7047 mutex_lock(&hba->dev_cmd.lock);
7048 down_read(&hba->clk_scaling_lock);
7050 lrbp = &hba->lrb[tag];
7053 lrbp->task_tag = tag;
7054 lrbp->lun = UFS_UPIU_RPMB_WLUN;
7056 lrbp->intr_cmd = true;
7057 ufshcd_prepare_lrbp_crypto(NULL, lrbp);
7058 hba->dev_cmd.type = DEV_CMD_TYPE_RPMB;
7060 /* Advanced RPMB starts from UFS 4.0, so its command type is UTP_CMD_TYPE_UFS_STORAGE */
7061 lrbp->command_type = UTP_CMD_TYPE_UFS_STORAGE;
7063 ufshcd_prepare_req_desc_hdr(lrbp, &upiu_flags, dir, 2);
7065 /* update the task tag and LUN in the request upiu */
7066 req_upiu->header.dword_0 |= cpu_to_be32(upiu_flags << 16 | UFS_UPIU_RPMB_WLUN << 8 | tag);
7068 /* copy the UPIU(contains CDB) request as it is */
7069 memcpy(lrbp->ucd_req_ptr, req_upiu, sizeof(*lrbp->ucd_req_ptr));
7070 /* Copy EHS, starting with byte32, immediately after the CDB package */
7071 memcpy(lrbp->ucd_req_ptr + 1, req_ehs, sizeof(*req_ehs));
7073 if (dir != DMA_NONE && sg_list)
7074 ufshcd_sgl_to_prdt(hba, lrbp, sg_cnt, sg_list);
7076 memset(lrbp->ucd_rsp_ptr, 0, sizeof(struct utp_upiu_rsp));
7078 hba->dev_cmd.complete = &wait;
7080 ufshcd_send_command(hba, tag);
7082 err = ufshcd_wait_for_dev_cmd(hba, lrbp, ADVANCED_RPMB_REQ_TIMEOUT);
7085 /* Just copy the upiu response as it is */
7086 memcpy(rsp_upiu, lrbp->ucd_rsp_ptr, sizeof(*rsp_upiu));
7087 /* Get the response UPIU result */
7088 result = ufshcd_get_rsp_upiu_result(lrbp->ucd_rsp_ptr);
7090 ehs_len = be32_to_cpu(lrbp->ucd_rsp_ptr->header.dword_2) >> 24;
7092 * Since the bLength in EHS indicates the total size of the EHS Header and EHS Data
7093 * in 32 Byte units, the value of the bLength Request/Response for Advanced RPMB
7096 if (ehs_len == 2 && rsp_ehs) {
7098 * ucd_rsp_ptr points to a buffer with a length of 512 bytes
7099 * (ALIGNED_UPIU_SIZE = 512), and the EHS data just starts from byte32
7101 ehs_data = (u8 *)lrbp->ucd_rsp_ptr + EHS_OFFSET_IN_RESPONSE;
7102 memcpy(rsp_ehs, ehs_data, ehs_len * 32);
7106 up_read(&hba->clk_scaling_lock);
7107 mutex_unlock(&hba->dev_cmd.lock);
7108 ufshcd_release(hba);
7109 return err ? : result;
7113 * ufshcd_eh_device_reset_handler() - Reset a single logical unit.
7114 * @cmd: SCSI command pointer
7116 * Returns SUCCESS/FAILED
7118 static int ufshcd_eh_device_reset_handler(struct scsi_cmnd *cmd)
7120 unsigned long flags, pending_reqs = 0, not_cleared = 0;
7121 struct Scsi_Host *host;
7122 struct ufs_hba *hba;
7127 host = cmd->device->host;
7128 hba = shost_priv(host);
7130 lun = ufshcd_scsi_to_upiu_lun(cmd->device->lun);
7131 err = ufshcd_issue_tm_cmd(hba, lun, 0, UFS_LOGICAL_RESET, &resp);
7132 if (err || resp != UPIU_TASK_MANAGEMENT_FUNC_COMPL) {
7138 /* clear the commands that were pending for corresponding LUN */
7139 spin_lock_irqsave(&hba->outstanding_lock, flags);
7140 for_each_set_bit(pos, &hba->outstanding_reqs, hba->nutrs)
7141 if (hba->lrb[pos].lun == lun)
7142 __set_bit(pos, &pending_reqs);
7143 hba->outstanding_reqs &= ~pending_reqs;
7144 spin_unlock_irqrestore(&hba->outstanding_lock, flags);
7146 if (ufshcd_clear_cmds(hba, pending_reqs) < 0) {
7147 spin_lock_irqsave(&hba->outstanding_lock, flags);
7148 not_cleared = pending_reqs &
7149 ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
7150 hba->outstanding_reqs |= not_cleared;
7151 spin_unlock_irqrestore(&hba->outstanding_lock, flags);
7153 dev_err(hba->dev, "%s: failed to clear requests %#lx\n",
7154 __func__, not_cleared);
7156 __ufshcd_transfer_req_compl(hba, pending_reqs & ~not_cleared);
7159 hba->req_abort_count = 0;
7160 ufshcd_update_evt_hist(hba, UFS_EVT_DEV_RESET, (u32)err);
7164 dev_err(hba->dev, "%s: failed with err %d\n", __func__, err);
7170 static void ufshcd_set_req_abort_skip(struct ufs_hba *hba, unsigned long bitmap)
7172 struct ufshcd_lrb *lrbp;
7175 for_each_set_bit(tag, &bitmap, hba->nutrs) {
7176 lrbp = &hba->lrb[tag];
7177 lrbp->req_abort_skip = true;
7182 * ufshcd_try_to_abort_task - abort a specific task
7183 * @hba: Pointer to adapter instance
7184 * @tag: Task tag/index to be aborted
7186 * Abort the pending command in device by sending UFS_ABORT_TASK task management
7187 * command, and in host controller by clearing the door-bell register. There can
7188 * be race between controller sending the command to the device while abort is
7189 * issued. To avoid that, first issue UFS_QUERY_TASK to check if the command is
7190 * really issued and then try to abort it.
7192 * Returns zero on success, non-zero on failure
7194 static int ufshcd_try_to_abort_task(struct ufs_hba *hba, int tag)
7196 struct ufshcd_lrb *lrbp = &hba->lrb[tag];
7202 for (poll_cnt = 100; poll_cnt; poll_cnt--) {
7203 err = ufshcd_issue_tm_cmd(hba, lrbp->lun, lrbp->task_tag,
7204 UFS_QUERY_TASK, &resp);
7205 if (!err && resp == UPIU_TASK_MANAGEMENT_FUNC_SUCCEEDED) {
7206 /* cmd pending in the device */
7207 dev_err(hba->dev, "%s: cmd pending in the device. tag = %d\n",
7210 } else if (!err && resp == UPIU_TASK_MANAGEMENT_FUNC_COMPL) {
7212 * cmd not pending in the device, check if it is
7215 dev_err(hba->dev, "%s: cmd at tag %d not pending in the device.\n",
7217 reg = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
7218 if (reg & (1 << tag)) {
7219 /* sleep for max. 200us to stabilize */
7220 usleep_range(100, 200);
7223 /* command completed already */
7224 dev_err(hba->dev, "%s: cmd at tag %d successfully cleared from DB.\n",
7229 "%s: no response from device. tag = %d, err %d\n",
7230 __func__, tag, err);
7232 err = resp; /* service response error */
7242 err = ufshcd_issue_tm_cmd(hba, lrbp->lun, lrbp->task_tag,
7243 UFS_ABORT_TASK, &resp);
7244 if (err || resp != UPIU_TASK_MANAGEMENT_FUNC_COMPL) {
7246 err = resp; /* service response error */
7247 dev_err(hba->dev, "%s: issued. tag = %d, err %d\n",
7248 __func__, tag, err);
7253 err = ufshcd_clear_cmds(hba, 1U << tag);
7255 dev_err(hba->dev, "%s: Failed clearing cmd at tag %d, err %d\n",
7256 __func__, tag, err);
7263 * ufshcd_abort - scsi host template eh_abort_handler callback
7264 * @cmd: SCSI command pointer
7266 * Returns SUCCESS/FAILED
7268 static int ufshcd_abort(struct scsi_cmnd *cmd)
7270 struct Scsi_Host *host = cmd->device->host;
7271 struct ufs_hba *hba = shost_priv(host);
7272 int tag = scsi_cmd_to_rq(cmd)->tag;
7273 struct ufshcd_lrb *lrbp = &hba->lrb[tag];
7274 unsigned long flags;
7279 WARN_ONCE(tag < 0, "Invalid tag %d\n", tag);
7281 ufshcd_hold(hba, false);
7282 reg = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
7283 /* If command is already aborted/completed, return FAILED. */
7284 if (!(test_bit(tag, &hba->outstanding_reqs))) {
7286 "%s: cmd at tag %d already completed, outstanding=0x%lx, doorbell=0x%x\n",
7287 __func__, tag, hba->outstanding_reqs, reg);
7291 /* Print Transfer Request of aborted task */
7292 dev_info(hba->dev, "%s: Device abort task at tag %d\n", __func__, tag);
7295 * Print detailed info about aborted request.
7296 * As more than one request might get aborted at the same time,
7297 * print full information only for the first aborted request in order
7298 * to reduce repeated printouts. For other aborted requests only print
7301 scsi_print_command(cmd);
7302 if (!hba->req_abort_count) {
7303 ufshcd_update_evt_hist(hba, UFS_EVT_ABORT, tag);
7304 ufshcd_print_evt_hist(hba);
7305 ufshcd_print_host_state(hba);
7306 ufshcd_print_pwr_info(hba);
7307 ufshcd_print_trs(hba, 1 << tag, true);
7309 ufshcd_print_trs(hba, 1 << tag, false);
7311 hba->req_abort_count++;
7313 if (!(reg & (1 << tag))) {
7315 "%s: cmd was completed, but without a notifying intr, tag = %d",
7317 __ufshcd_transfer_req_compl(hba, 1UL << tag);
7322 * Task abort to the device W-LUN is illegal. When this command
7323 * will fail, due to spec violation, scsi err handling next step
7324 * will be to send LU reset which, again, is a spec violation.
7325 * To avoid these unnecessary/illegal steps, first we clean up
7326 * the lrb taken by this cmd and re-set it in outstanding_reqs,
7327 * then queue the eh_work and bail.
7329 if (lrbp->lun == UFS_UPIU_UFS_DEVICE_WLUN) {
7330 ufshcd_update_evt_hist(hba, UFS_EVT_ABORT, lrbp->lun);
7332 spin_lock_irqsave(host->host_lock, flags);
7333 hba->force_reset = true;
7334 ufshcd_schedule_eh_work(hba);
7335 spin_unlock_irqrestore(host->host_lock, flags);
7339 /* Skip task abort in case previous aborts failed and report failure */
7340 if (lrbp->req_abort_skip) {
7341 dev_err(hba->dev, "%s: skipping abort\n", __func__);
7342 ufshcd_set_req_abort_skip(hba, hba->outstanding_reqs);
7346 err = ufshcd_try_to_abort_task(hba, tag);
7348 dev_err(hba->dev, "%s: failed with err %d\n", __func__, err);
7349 ufshcd_set_req_abort_skip(hba, hba->outstanding_reqs);
7355 * Clear the corresponding bit from outstanding_reqs since the command
7356 * has been aborted successfully.
7358 spin_lock_irqsave(&hba->outstanding_lock, flags);
7359 outstanding = __test_and_clear_bit(tag, &hba->outstanding_reqs);
7360 spin_unlock_irqrestore(&hba->outstanding_lock, flags);
7363 ufshcd_release_scsi_cmd(hba, lrbp);
7368 /* Matches the ufshcd_hold() call at the start of this function. */
7369 ufshcd_release(hba);
7374 * ufshcd_host_reset_and_restore - reset and restore host controller
7375 * @hba: per-adapter instance
7377 * Note that host controller reset may issue DME_RESET to
7378 * local and remote (device) Uni-Pro stack and the attributes
7379 * are reset to default state.
7381 * Returns zero on success, non-zero on failure
7383 static int ufshcd_host_reset_and_restore(struct ufs_hba *hba)
7388 * Stop the host controller and complete the requests
7391 ufshpb_toggle_state(hba, HPB_PRESENT, HPB_RESET);
7392 ufshcd_hba_stop(hba);
7393 hba->silence_err_logs = true;
7394 ufshcd_complete_requests(hba);
7395 hba->silence_err_logs = false;
7397 /* scale up clocks to max frequency before full reinitialization */
7398 ufshcd_scale_clks(hba, true);
7400 err = ufshcd_hba_enable(hba);
7402 /* Establish the link again and restore the device */
7404 err = ufshcd_probe_hba(hba, false);
7407 dev_err(hba->dev, "%s: Host init failed %d\n", __func__, err);
7408 ufshcd_update_evt_hist(hba, UFS_EVT_HOST_RESET, (u32)err);
7413 * ufshcd_reset_and_restore - reset and re-initialize host/device
7414 * @hba: per-adapter instance
7416 * Reset and recover device, host and re-establish link. This
7417 * is helpful to recover the communication in fatal error conditions.
7419 * Returns zero on success, non-zero on failure
7421 static int ufshcd_reset_and_restore(struct ufs_hba *hba)
7424 u32 saved_uic_err = 0;
7426 unsigned long flags;
7427 int retries = MAX_HOST_RESET_RETRIES;
7429 spin_lock_irqsave(hba->host->host_lock, flags);
7432 * This is a fresh start, cache and clear saved error first,
7433 * in case new error generated during reset and restore.
7435 saved_err |= hba->saved_err;
7436 saved_uic_err |= hba->saved_uic_err;
7438 hba->saved_uic_err = 0;
7439 hba->force_reset = false;
7440 hba->ufshcd_state = UFSHCD_STATE_RESET;
7441 spin_unlock_irqrestore(hba->host->host_lock, flags);
7443 /* Reset the attached device */
7444 ufshcd_device_reset(hba);
7446 err = ufshcd_host_reset_and_restore(hba);
7448 spin_lock_irqsave(hba->host->host_lock, flags);
7451 /* Do not exit unless operational or dead */
7452 if (hba->ufshcd_state != UFSHCD_STATE_OPERATIONAL &&
7453 hba->ufshcd_state != UFSHCD_STATE_ERROR &&
7454 hba->ufshcd_state != UFSHCD_STATE_EH_SCHEDULED_NON_FATAL)
7456 } while (err && --retries);
7459 * Inform scsi mid-layer that we did reset and allow to handle
7460 * Unit Attention properly.
7462 scsi_report_bus_reset(hba->host, 0);
7464 hba->ufshcd_state = UFSHCD_STATE_ERROR;
7465 hba->saved_err |= saved_err;
7466 hba->saved_uic_err |= saved_uic_err;
7468 spin_unlock_irqrestore(hba->host->host_lock, flags);
7474 * ufshcd_eh_host_reset_handler - host reset handler registered to scsi layer
7475 * @cmd: SCSI command pointer
7477 * Returns SUCCESS/FAILED
7479 static int ufshcd_eh_host_reset_handler(struct scsi_cmnd *cmd)
7482 unsigned long flags;
7483 struct ufs_hba *hba;
7485 hba = shost_priv(cmd->device->host);
7487 spin_lock_irqsave(hba->host->host_lock, flags);
7488 hba->force_reset = true;
7489 ufshcd_schedule_eh_work(hba);
7490 dev_err(hba->dev, "%s: reset in progress - 1\n", __func__);
7491 spin_unlock_irqrestore(hba->host->host_lock, flags);
7493 flush_work(&hba->eh_work);
7495 spin_lock_irqsave(hba->host->host_lock, flags);
7496 if (hba->ufshcd_state == UFSHCD_STATE_ERROR)
7498 spin_unlock_irqrestore(hba->host->host_lock, flags);
7504 * ufshcd_get_max_icc_level - calculate the ICC level
7505 * @sup_curr_uA: max. current supported by the regulator
7506 * @start_scan: row at the desc table to start scan from
7507 * @buff: power descriptor buffer
7509 * Returns calculated max ICC level for specific regulator
7511 static u32 ufshcd_get_max_icc_level(int sup_curr_uA, u32 start_scan,
7519 for (i = start_scan; i >= 0; i--) {
7520 data = get_unaligned_be16(&buff[2 * i]);
7521 unit = (data & ATTR_ICC_LVL_UNIT_MASK) >>
7522 ATTR_ICC_LVL_UNIT_OFFSET;
7523 curr_uA = data & ATTR_ICC_LVL_VALUE_MASK;
7525 case UFSHCD_NANO_AMP:
7526 curr_uA = curr_uA / 1000;
7528 case UFSHCD_MILI_AMP:
7529 curr_uA = curr_uA * 1000;
7532 curr_uA = curr_uA * 1000 * 1000;
7534 case UFSHCD_MICRO_AMP:
7538 if (sup_curr_uA >= curr_uA)
7543 pr_err("%s: Couldn't find valid icc_level = %d", __func__, i);
7550 * ufshcd_find_max_sup_active_icc_level - calculate the max ICC level
7551 * In case regulators are not initialized we'll return 0
7552 * @hba: per-adapter instance
7553 * @desc_buf: power descriptor buffer to extract ICC levels from.
7554 * @len: length of desc_buff
7556 * Returns calculated ICC level
7558 static u32 ufshcd_find_max_sup_active_icc_level(struct ufs_hba *hba,
7559 const u8 *desc_buf, int len)
7563 if (!hba->vreg_info.vcc || !hba->vreg_info.vccq ||
7564 !hba->vreg_info.vccq2) {
7566 * Using dev_dbg to avoid messages during runtime PM to avoid
7567 * never-ending cycles of messages written back to storage by
7568 * user space causing runtime resume, causing more messages and
7572 "%s: Regulator capability was not set, actvIccLevel=%d",
7573 __func__, icc_level);
7577 if (hba->vreg_info.vcc->max_uA)
7578 icc_level = ufshcd_get_max_icc_level(
7579 hba->vreg_info.vcc->max_uA,
7580 POWER_DESC_MAX_ACTV_ICC_LVLS - 1,
7581 &desc_buf[PWR_DESC_ACTIVE_LVLS_VCC_0]);
7583 if (hba->vreg_info.vccq->max_uA)
7584 icc_level = ufshcd_get_max_icc_level(
7585 hba->vreg_info.vccq->max_uA,
7587 &desc_buf[PWR_DESC_ACTIVE_LVLS_VCCQ_0]);
7589 if (hba->vreg_info.vccq2->max_uA)
7590 icc_level = ufshcd_get_max_icc_level(
7591 hba->vreg_info.vccq2->max_uA,
7593 &desc_buf[PWR_DESC_ACTIVE_LVLS_VCCQ2_0]);
7598 static void ufshcd_set_active_icc_lvl(struct ufs_hba *hba)
7601 int buff_len = hba->desc_size[QUERY_DESC_IDN_POWER];
7605 desc_buf = kmalloc(buff_len, GFP_KERNEL);
7609 ret = ufshcd_read_desc_param(hba, QUERY_DESC_IDN_POWER, 0, 0,
7610 desc_buf, buff_len);
7613 "%s: Failed reading power descriptor.len = %d ret = %d",
7614 __func__, buff_len, ret);
7618 icc_level = ufshcd_find_max_sup_active_icc_level(hba, desc_buf,
7620 dev_dbg(hba->dev, "%s: setting icc_level 0x%x", __func__, icc_level);
7622 ret = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_WRITE_ATTR,
7623 QUERY_ATTR_IDN_ACTIVE_ICC_LVL, 0, 0, &icc_level);
7627 "%s: Failed configuring bActiveICCLevel = %d ret = %d",
7628 __func__, icc_level, ret);
7634 static inline void ufshcd_blk_pm_runtime_init(struct scsi_device *sdev)
7636 scsi_autopm_get_device(sdev);
7637 blk_pm_runtime_init(sdev->request_queue, &sdev->sdev_gendev);
7638 if (sdev->rpm_autosuspend)
7639 pm_runtime_set_autosuspend_delay(&sdev->sdev_gendev,
7640 RPM_AUTOSUSPEND_DELAY_MS);
7641 scsi_autopm_put_device(sdev);
7645 * ufshcd_scsi_add_wlus - Adds required W-LUs
7646 * @hba: per-adapter instance
7648 * UFS device specification requires the UFS devices to support 4 well known
7650 * "REPORT_LUNS" (address: 01h)
7651 * "UFS Device" (address: 50h)
7652 * "RPMB" (address: 44h)
7653 * "BOOT" (address: 30h)
7654 * UFS device's power management needs to be controlled by "POWER CONDITION"
7655 * field of SSU (START STOP UNIT) command. But this "power condition" field
7656 * will take effect only when its sent to "UFS device" well known logical unit
7657 * hence we require the scsi_device instance to represent this logical unit in
7658 * order for the UFS host driver to send the SSU command for power management.
7660 * We also require the scsi_device instance for "RPMB" (Replay Protected Memory
7661 * Block) LU so user space process can control this LU. User space may also
7662 * want to have access to BOOT LU.
7664 * This function adds scsi device instances for each of all well known LUs
7665 * (except "REPORT LUNS" LU).
7667 * Returns zero on success (all required W-LUs are added successfully),
7668 * non-zero error value on failure (if failed to add any of the required W-LU).
7670 static int ufshcd_scsi_add_wlus(struct ufs_hba *hba)
7673 struct scsi_device *sdev_boot, *sdev_rpmb;
7675 hba->ufs_device_wlun = __scsi_add_device(hba->host, 0, 0,
7676 ufshcd_upiu_wlun_to_scsi_wlun(UFS_UPIU_UFS_DEVICE_WLUN), NULL);
7677 if (IS_ERR(hba->ufs_device_wlun)) {
7678 ret = PTR_ERR(hba->ufs_device_wlun);
7679 hba->ufs_device_wlun = NULL;
7682 scsi_device_put(hba->ufs_device_wlun);
7684 sdev_rpmb = __scsi_add_device(hba->host, 0, 0,
7685 ufshcd_upiu_wlun_to_scsi_wlun(UFS_UPIU_RPMB_WLUN), NULL);
7686 if (IS_ERR(sdev_rpmb)) {
7687 ret = PTR_ERR(sdev_rpmb);
7688 goto remove_ufs_device_wlun;
7690 ufshcd_blk_pm_runtime_init(sdev_rpmb);
7691 scsi_device_put(sdev_rpmb);
7693 sdev_boot = __scsi_add_device(hba->host, 0, 0,
7694 ufshcd_upiu_wlun_to_scsi_wlun(UFS_UPIU_BOOT_WLUN), NULL);
7695 if (IS_ERR(sdev_boot)) {
7696 dev_err(hba->dev, "%s: BOOT WLUN not found\n", __func__);
7698 ufshcd_blk_pm_runtime_init(sdev_boot);
7699 scsi_device_put(sdev_boot);
7703 remove_ufs_device_wlun:
7704 scsi_remove_device(hba->ufs_device_wlun);
7709 static void ufshcd_wb_probe(struct ufs_hba *hba, const u8 *desc_buf)
7711 struct ufs_dev_info *dev_info = &hba->dev_info;
7713 u32 d_lu_wb_buf_alloc;
7714 u32 ext_ufs_feature;
7716 if (!ufshcd_is_wb_allowed(hba))
7720 * Probe WB only for UFS-2.2 and UFS-3.1 (and later) devices or
7721 * UFS devices with quirk UFS_DEVICE_QUIRK_SUPPORT_EXTENDED_FEATURES
7724 if (!(dev_info->wspecversion >= 0x310 ||
7725 dev_info->wspecversion == 0x220 ||
7726 (hba->dev_quirks & UFS_DEVICE_QUIRK_SUPPORT_EXTENDED_FEATURES)))
7729 if (hba->desc_size[QUERY_DESC_IDN_DEVICE] <
7730 DEVICE_DESC_PARAM_EXT_UFS_FEATURE_SUP + 4)
7733 ext_ufs_feature = get_unaligned_be32(desc_buf +
7734 DEVICE_DESC_PARAM_EXT_UFS_FEATURE_SUP);
7736 if (!(ext_ufs_feature & UFS_DEV_WRITE_BOOSTER_SUP))
7740 * WB may be supported but not configured while provisioning. The spec
7741 * says, in dedicated wb buffer mode, a max of 1 lun would have wb
7742 * buffer configured.
7744 dev_info->wb_buffer_type = desc_buf[DEVICE_DESC_PARAM_WB_TYPE];
7746 dev_info->b_presrv_uspc_en =
7747 desc_buf[DEVICE_DESC_PARAM_WB_PRESRV_USRSPC_EN];
7749 if (dev_info->wb_buffer_type == WB_BUF_MODE_SHARED) {
7750 if (!get_unaligned_be32(desc_buf +
7751 DEVICE_DESC_PARAM_WB_SHARED_ALLOC_UNITS))
7754 for (lun = 0; lun < UFS_UPIU_MAX_WB_LUN_ID; lun++) {
7755 d_lu_wb_buf_alloc = 0;
7756 ufshcd_read_unit_desc_param(hba,
7758 UNIT_DESC_PARAM_WB_BUF_ALLOC_UNITS,
7759 (u8 *)&d_lu_wb_buf_alloc,
7760 sizeof(d_lu_wb_buf_alloc));
7761 if (d_lu_wb_buf_alloc) {
7762 dev_info->wb_dedicated_lu = lun;
7767 if (!d_lu_wb_buf_alloc)
7771 if (!ufshcd_is_wb_buf_lifetime_available(hba))
7777 hba->caps &= ~UFSHCD_CAP_WB_EN;
7780 static void ufshcd_temp_notif_probe(struct ufs_hba *hba, const u8 *desc_buf)
7782 struct ufs_dev_info *dev_info = &hba->dev_info;
7783 u32 ext_ufs_feature;
7786 if (!(hba->caps & UFSHCD_CAP_TEMP_NOTIF) || dev_info->wspecversion < 0x300)
7789 ext_ufs_feature = get_unaligned_be32(desc_buf + DEVICE_DESC_PARAM_EXT_UFS_FEATURE_SUP);
7791 if (ext_ufs_feature & UFS_DEV_LOW_TEMP_NOTIF)
7792 mask |= MASK_EE_TOO_LOW_TEMP;
7794 if (ext_ufs_feature & UFS_DEV_HIGH_TEMP_NOTIF)
7795 mask |= MASK_EE_TOO_HIGH_TEMP;
7798 ufshcd_enable_ee(hba, mask);
7799 ufs_hwmon_probe(hba, mask);
7803 void ufshcd_fixup_dev_quirks(struct ufs_hba *hba,
7804 const struct ufs_dev_quirk *fixups)
7806 const struct ufs_dev_quirk *f;
7807 struct ufs_dev_info *dev_info = &hba->dev_info;
7812 for (f = fixups; f->quirk; f++) {
7813 if ((f->wmanufacturerid == dev_info->wmanufacturerid ||
7814 f->wmanufacturerid == UFS_ANY_VENDOR) &&
7815 ((dev_info->model &&
7816 STR_PRFX_EQUAL(f->model, dev_info->model)) ||
7817 !strcmp(f->model, UFS_ANY_MODEL)))
7818 hba->dev_quirks |= f->quirk;
7821 EXPORT_SYMBOL_GPL(ufshcd_fixup_dev_quirks);
7823 static void ufs_fixup_device_setup(struct ufs_hba *hba)
7825 /* fix by general quirk table */
7826 ufshcd_fixup_dev_quirks(hba, ufs_fixups);
7828 /* allow vendors to fix quirks */
7829 ufshcd_vops_fixup_dev_quirks(hba);
7832 static int ufs_get_device_desc(struct ufs_hba *hba)
7836 u8 b_ufs_feature_sup;
7838 struct ufs_dev_info *dev_info = &hba->dev_info;
7840 desc_buf = kmalloc(QUERY_DESC_MAX_SIZE, GFP_KERNEL);
7846 err = ufshcd_read_desc_param(hba, QUERY_DESC_IDN_DEVICE, 0, 0, desc_buf,
7847 hba->desc_size[QUERY_DESC_IDN_DEVICE]);
7849 dev_err(hba->dev, "%s: Failed reading Device Desc. err = %d\n",
7855 * getting vendor (manufacturerID) and Bank Index in big endian
7858 dev_info->wmanufacturerid = desc_buf[DEVICE_DESC_PARAM_MANF_ID] << 8 |
7859 desc_buf[DEVICE_DESC_PARAM_MANF_ID + 1];
7861 /* getting Specification Version in big endian format */
7862 dev_info->wspecversion = desc_buf[DEVICE_DESC_PARAM_SPEC_VER] << 8 |
7863 desc_buf[DEVICE_DESC_PARAM_SPEC_VER + 1];
7864 b_ufs_feature_sup = desc_buf[DEVICE_DESC_PARAM_UFS_FEAT];
7866 model_index = desc_buf[DEVICE_DESC_PARAM_PRDCT_NAME];
7868 if (dev_info->wspecversion >= UFS_DEV_HPB_SUPPORT_VERSION &&
7869 (b_ufs_feature_sup & UFS_DEV_HPB_SUPPORT)) {
7870 bool hpb_en = false;
7872 ufshpb_get_dev_info(hba, desc_buf);
7874 if (!ufshpb_is_legacy(hba))
7875 err = ufshcd_query_flag_retry(hba,
7876 UPIU_QUERY_OPCODE_READ_FLAG,
7877 QUERY_FLAG_IDN_HPB_EN, 0,
7880 if (ufshpb_is_legacy(hba) || (!err && hpb_en))
7881 dev_info->hpb_enabled = true;
7884 err = ufshcd_read_string_desc(hba, model_index,
7885 &dev_info->model, SD_ASCII_STD);
7887 dev_err(hba->dev, "%s: Failed reading Product Name. err = %d\n",
7892 hba->luns_avail = desc_buf[DEVICE_DESC_PARAM_NUM_LU] +
7893 desc_buf[DEVICE_DESC_PARAM_NUM_WLU];
7895 ufs_fixup_device_setup(hba);
7897 ufshcd_wb_probe(hba, desc_buf);
7899 ufshcd_temp_notif_probe(hba, desc_buf);
7902 * ufshcd_read_string_desc returns size of the string
7903 * reset the error value
7912 static void ufs_put_device_desc(struct ufs_hba *hba)
7914 struct ufs_dev_info *dev_info = &hba->dev_info;
7916 kfree(dev_info->model);
7917 dev_info->model = NULL;
7921 * ufshcd_tune_pa_tactivate - Tunes PA_TActivate of local UniPro
7922 * @hba: per-adapter instance
7924 * PA_TActivate parameter can be tuned manually if UniPro version is less than
7925 * 1.61. PA_TActivate needs to be greater than or equal to peerM-PHY's
7926 * RX_MIN_ACTIVATETIME_CAPABILITY attribute. This optimal value can help reduce
7927 * the hibern8 exit latency.
7929 * Returns zero on success, non-zero error value on failure.
7931 static int ufshcd_tune_pa_tactivate(struct ufs_hba *hba)
7934 u32 peer_rx_min_activatetime = 0, tuned_pa_tactivate;
7936 ret = ufshcd_dme_peer_get(hba,
7938 RX_MIN_ACTIVATETIME_CAPABILITY,
7939 UIC_ARG_MPHY_RX_GEN_SEL_INDEX(0)),
7940 &peer_rx_min_activatetime);
7944 /* make sure proper unit conversion is applied */
7945 tuned_pa_tactivate =
7946 ((peer_rx_min_activatetime * RX_MIN_ACTIVATETIME_UNIT_US)
7947 / PA_TACTIVATE_TIME_UNIT_US);
7948 ret = ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TACTIVATE),
7949 tuned_pa_tactivate);
7956 * ufshcd_tune_pa_hibern8time - Tunes PA_Hibern8Time of local UniPro
7957 * @hba: per-adapter instance
7959 * PA_Hibern8Time parameter can be tuned manually if UniPro version is less than
7960 * 1.61. PA_Hibern8Time needs to be maximum of local M-PHY's
7961 * TX_HIBERN8TIME_CAPABILITY & peer M-PHY's RX_HIBERN8TIME_CAPABILITY.
7962 * This optimal value can help reduce the hibern8 exit latency.
7964 * Returns zero on success, non-zero error value on failure.
7966 static int ufshcd_tune_pa_hibern8time(struct ufs_hba *hba)
7969 u32 local_tx_hibern8_time_cap = 0, peer_rx_hibern8_time_cap = 0;
7970 u32 max_hibern8_time, tuned_pa_hibern8time;
7972 ret = ufshcd_dme_get(hba,
7973 UIC_ARG_MIB_SEL(TX_HIBERN8TIME_CAPABILITY,
7974 UIC_ARG_MPHY_TX_GEN_SEL_INDEX(0)),
7975 &local_tx_hibern8_time_cap);
7979 ret = ufshcd_dme_peer_get(hba,
7980 UIC_ARG_MIB_SEL(RX_HIBERN8TIME_CAPABILITY,
7981 UIC_ARG_MPHY_RX_GEN_SEL_INDEX(0)),
7982 &peer_rx_hibern8_time_cap);
7986 max_hibern8_time = max(local_tx_hibern8_time_cap,
7987 peer_rx_hibern8_time_cap);
7988 /* make sure proper unit conversion is applied */
7989 tuned_pa_hibern8time = ((max_hibern8_time * HIBERN8TIME_UNIT_US)
7990 / PA_HIBERN8_TIME_UNIT_US);
7991 ret = ufshcd_dme_set(hba, UIC_ARG_MIB(PA_HIBERN8TIME),
7992 tuned_pa_hibern8time);
7998 * ufshcd_quirk_tune_host_pa_tactivate - Ensures that host PA_TACTIVATE is
7999 * less than device PA_TACTIVATE time.
8000 * @hba: per-adapter instance
8002 * Some UFS devices require host PA_TACTIVATE to be lower than device
8003 * PA_TACTIVATE, we need to enable UFS_DEVICE_QUIRK_HOST_PA_TACTIVATE quirk
8006 * Returns zero on success, non-zero error value on failure.
8008 static int ufshcd_quirk_tune_host_pa_tactivate(struct ufs_hba *hba)
8011 u32 granularity, peer_granularity;
8012 u32 pa_tactivate, peer_pa_tactivate;
8013 u32 pa_tactivate_us, peer_pa_tactivate_us;
8014 static const u8 gran_to_us_table[] = {1, 4, 8, 16, 32, 100};
8016 ret = ufshcd_dme_get(hba, UIC_ARG_MIB(PA_GRANULARITY),
8021 ret = ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_GRANULARITY),
8026 if ((granularity < PA_GRANULARITY_MIN_VAL) ||
8027 (granularity > PA_GRANULARITY_MAX_VAL)) {
8028 dev_err(hba->dev, "%s: invalid host PA_GRANULARITY %d",
8029 __func__, granularity);
8033 if ((peer_granularity < PA_GRANULARITY_MIN_VAL) ||
8034 (peer_granularity > PA_GRANULARITY_MAX_VAL)) {
8035 dev_err(hba->dev, "%s: invalid device PA_GRANULARITY %d",
8036 __func__, peer_granularity);
8040 ret = ufshcd_dme_get(hba, UIC_ARG_MIB(PA_TACTIVATE), &pa_tactivate);
8044 ret = ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_TACTIVATE),
8045 &peer_pa_tactivate);
8049 pa_tactivate_us = pa_tactivate * gran_to_us_table[granularity - 1];
8050 peer_pa_tactivate_us = peer_pa_tactivate *
8051 gran_to_us_table[peer_granularity - 1];
8053 if (pa_tactivate_us >= peer_pa_tactivate_us) {
8054 u32 new_peer_pa_tactivate;
8056 new_peer_pa_tactivate = pa_tactivate_us /
8057 gran_to_us_table[peer_granularity - 1];
8058 new_peer_pa_tactivate++;
8059 ret = ufshcd_dme_peer_set(hba, UIC_ARG_MIB(PA_TACTIVATE),
8060 new_peer_pa_tactivate);
8067 static void ufshcd_tune_unipro_params(struct ufs_hba *hba)
8069 if (ufshcd_is_unipro_pa_params_tuning_req(hba)) {
8070 ufshcd_tune_pa_tactivate(hba);
8071 ufshcd_tune_pa_hibern8time(hba);
8074 ufshcd_vops_apply_dev_quirks(hba);
8076 if (hba->dev_quirks & UFS_DEVICE_QUIRK_PA_TACTIVATE)
8077 /* set 1ms timeout for PA_TACTIVATE */
8078 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TACTIVATE), 10);
8080 if (hba->dev_quirks & UFS_DEVICE_QUIRK_HOST_PA_TACTIVATE)
8081 ufshcd_quirk_tune_host_pa_tactivate(hba);
8084 static void ufshcd_clear_dbg_ufs_stats(struct ufs_hba *hba)
8086 hba->ufs_stats.hibern8_exit_cnt = 0;
8087 hba->ufs_stats.last_hibern8_exit_tstamp = ktime_set(0, 0);
8088 hba->req_abort_count = 0;
8091 static int ufshcd_device_geo_params_init(struct ufs_hba *hba)
8097 buff_len = hba->desc_size[QUERY_DESC_IDN_GEOMETRY];
8098 desc_buf = kmalloc(buff_len, GFP_KERNEL);
8104 err = ufshcd_read_desc_param(hba, QUERY_DESC_IDN_GEOMETRY, 0, 0,
8105 desc_buf, buff_len);
8107 dev_err(hba->dev, "%s: Failed reading Geometry Desc. err = %d\n",
8112 if (desc_buf[GEOMETRY_DESC_PARAM_MAX_NUM_LUN] == 1)
8113 hba->dev_info.max_lu_supported = 32;
8114 else if (desc_buf[GEOMETRY_DESC_PARAM_MAX_NUM_LUN] == 0)
8115 hba->dev_info.max_lu_supported = 8;
8117 if (hba->desc_size[QUERY_DESC_IDN_GEOMETRY] >=
8118 GEOMETRY_DESC_PARAM_HPB_MAX_ACTIVE_REGS)
8119 ufshpb_get_geo_info(hba, desc_buf);
8126 struct ufs_ref_clk {
8127 unsigned long freq_hz;
8128 enum ufs_ref_clk_freq val;
8131 static const struct ufs_ref_clk ufs_ref_clk_freqs[] = {
8132 {19200000, REF_CLK_FREQ_19_2_MHZ},
8133 {26000000, REF_CLK_FREQ_26_MHZ},
8134 {38400000, REF_CLK_FREQ_38_4_MHZ},
8135 {52000000, REF_CLK_FREQ_52_MHZ},
8136 {0, REF_CLK_FREQ_INVAL},
8139 static enum ufs_ref_clk_freq
8140 ufs_get_bref_clk_from_hz(unsigned long freq)
8144 for (i = 0; ufs_ref_clk_freqs[i].freq_hz; i++)
8145 if (ufs_ref_clk_freqs[i].freq_hz == freq)
8146 return ufs_ref_clk_freqs[i].val;
8148 return REF_CLK_FREQ_INVAL;
8151 void ufshcd_parse_dev_ref_clk_freq(struct ufs_hba *hba, struct clk *refclk)
8155 freq = clk_get_rate(refclk);
8157 hba->dev_ref_clk_freq =
8158 ufs_get_bref_clk_from_hz(freq);
8160 if (hba->dev_ref_clk_freq == REF_CLK_FREQ_INVAL)
8162 "invalid ref_clk setting = %ld\n", freq);
8165 static int ufshcd_set_dev_ref_clk(struct ufs_hba *hba)
8169 u32 freq = hba->dev_ref_clk_freq;
8171 err = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
8172 QUERY_ATTR_IDN_REF_CLK_FREQ, 0, 0, &ref_clk);
8175 dev_err(hba->dev, "failed reading bRefClkFreq. err = %d\n",
8180 if (ref_clk == freq)
8181 goto out; /* nothing to update */
8183 err = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_WRITE_ATTR,
8184 QUERY_ATTR_IDN_REF_CLK_FREQ, 0, 0, &freq);
8187 dev_err(hba->dev, "bRefClkFreq setting to %lu Hz failed\n",
8188 ufs_ref_clk_freqs[freq].freq_hz);
8192 dev_dbg(hba->dev, "bRefClkFreq setting to %lu Hz succeeded\n",
8193 ufs_ref_clk_freqs[freq].freq_hz);
8199 static int ufshcd_device_params_init(struct ufs_hba *hba)
8204 /* Init device descriptor sizes */
8205 for (i = 0; i < QUERY_DESC_IDN_MAX; i++)
8206 hba->desc_size[i] = QUERY_DESC_MAX_SIZE;
8208 /* Init UFS geometry descriptor related parameters */
8209 ret = ufshcd_device_geo_params_init(hba);
8213 /* Check and apply UFS device quirks */
8214 ret = ufs_get_device_desc(hba);
8216 dev_err(hba->dev, "%s: Failed getting device info. err = %d\n",
8221 ufshcd_get_ref_clk_gating_wait(hba);
8223 if (!ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_READ_FLAG,
8224 QUERY_FLAG_IDN_PWR_ON_WPE, 0, &flag))
8225 hba->dev_info.f_power_on_wp_en = flag;
8227 /* Probe maximum power mode co-supported by both UFS host and device */
8228 if (ufshcd_get_max_pwr_mode(hba))
8230 "%s: Failed getting max supported power mode\n",
8237 * ufshcd_add_lus - probe and add UFS logical units
8238 * @hba: per-adapter instance
8240 static int ufshcd_add_lus(struct ufs_hba *hba)
8244 /* Add required well known logical units to scsi mid layer */
8245 ret = ufshcd_scsi_add_wlus(hba);
8249 /* Initialize devfreq after UFS device is detected */
8250 if (ufshcd_is_clkscaling_supported(hba)) {
8251 memcpy(&hba->clk_scaling.saved_pwr_info.info,
8253 sizeof(struct ufs_pa_layer_attr));
8254 hba->clk_scaling.saved_pwr_info.is_valid = true;
8255 hba->clk_scaling.is_allowed = true;
8257 ret = ufshcd_devfreq_init(hba);
8261 hba->clk_scaling.is_enabled = true;
8262 ufshcd_init_clk_scaling_sysfs(hba);
8267 scsi_scan_host(hba->host);
8268 pm_runtime_put_sync(hba->dev);
8275 * ufshcd_probe_hba - probe hba to detect device and initialize it
8276 * @hba: per-adapter instance
8277 * @init_dev_params: whether or not to call ufshcd_device_params_init().
8279 * Execute link-startup and verify device initialization
8281 static int ufshcd_probe_hba(struct ufs_hba *hba, bool init_dev_params)
8284 unsigned long flags;
8285 ktime_t start = ktime_get();
8287 hba->ufshcd_state = UFSHCD_STATE_RESET;
8289 ret = ufshcd_link_startup(hba);
8293 if (hba->quirks & UFSHCD_QUIRK_SKIP_PH_CONFIGURATION)
8296 /* Debug counters initialization */
8297 ufshcd_clear_dbg_ufs_stats(hba);
8299 /* UniPro link is active now */
8300 ufshcd_set_link_active(hba);
8302 /* Verify device initialization by sending NOP OUT UPIU */
8303 ret = ufshcd_verify_dev_init(hba);
8307 /* Initiate UFS initialization, and waiting until completion */
8308 ret = ufshcd_complete_dev_init(hba);
8313 * Initialize UFS device parameters used by driver, these
8314 * parameters are associated with UFS descriptors.
8316 if (init_dev_params) {
8317 ret = ufshcd_device_params_init(hba);
8322 ufshcd_tune_unipro_params(hba);
8324 /* UFS device is also active now */
8325 ufshcd_set_ufs_dev_active(hba);
8326 ufshcd_force_reset_auto_bkops(hba);
8328 /* Gear up to HS gear if supported */
8329 if (hba->max_pwr_info.is_valid) {
8331 * Set the right value to bRefClkFreq before attempting to
8332 * switch to HS gears.
8334 if (hba->dev_ref_clk_freq != REF_CLK_FREQ_INVAL)
8335 ufshcd_set_dev_ref_clk(hba);
8336 ret = ufshcd_config_pwr_mode(hba, &hba->max_pwr_info.info);
8338 dev_err(hba->dev, "%s: Failed setting power mode, err = %d\n",
8342 ufshcd_print_pwr_info(hba);
8346 * bActiveICCLevel is volatile for UFS device (as per latest v2.1 spec)
8347 * and for removable UFS card as well, hence always set the parameter.
8348 * Note: Error handler may issue the device reset hence resetting
8349 * bActiveICCLevel as well so it is always safe to set this here.
8351 ufshcd_set_active_icc_lvl(hba);
8353 /* Enable UFS Write Booster if supported */
8354 ufshcd_configure_wb(hba);
8356 if (hba->ee_usr_mask)
8357 ufshcd_write_ee_control(hba);
8358 /* Enable Auto-Hibernate if configured */
8359 ufshcd_auto_hibern8_enable(hba);
8361 ufshpb_toggle_state(hba, HPB_RESET, HPB_PRESENT);
8363 spin_lock_irqsave(hba->host->host_lock, flags);
8365 hba->ufshcd_state = UFSHCD_STATE_ERROR;
8366 else if (hba->ufshcd_state == UFSHCD_STATE_RESET)
8367 hba->ufshcd_state = UFSHCD_STATE_OPERATIONAL;
8368 spin_unlock_irqrestore(hba->host->host_lock, flags);
8370 trace_ufshcd_init(dev_name(hba->dev), ret,
8371 ktime_to_us(ktime_sub(ktime_get(), start)),
8372 hba->curr_dev_pwr_mode, hba->uic_link_state);
8377 * ufshcd_async_scan - asynchronous execution for probing hba
8378 * @data: data pointer to pass to this function
8379 * @cookie: cookie data
8381 static void ufshcd_async_scan(void *data, async_cookie_t cookie)
8383 struct ufs_hba *hba = (struct ufs_hba *)data;
8386 down(&hba->host_sem);
8387 /* Initialize hba, detect and initialize UFS device */
8388 ret = ufshcd_probe_hba(hba, true);
8393 /* Probe and add UFS logical units */
8394 ret = ufshcd_add_lus(hba);
8397 * If we failed to initialize the device or the device is not
8398 * present, turn off the power/clocks etc.
8401 pm_runtime_put_sync(hba->dev);
8402 ufshcd_hba_exit(hba);
8406 static enum scsi_timeout_action ufshcd_eh_timed_out(struct scsi_cmnd *scmd)
8408 struct ufs_hba *hba = shost_priv(scmd->device->host);
8410 if (!hba->system_suspending) {
8411 /* Activate the error handler in the SCSI core. */
8412 return SCSI_EH_NOT_HANDLED;
8416 * If we get here we know that no TMFs are outstanding and also that
8417 * the only pending command is a START STOP UNIT command. Handle the
8418 * timeout of that command directly to prevent a deadlock between
8419 * ufshcd_set_dev_pwr_mode() and ufshcd_err_handler().
8421 ufshcd_link_recovery(hba);
8422 dev_info(hba->dev, "%s() finished; outstanding_tasks = %#lx.\n",
8423 __func__, hba->outstanding_tasks);
8425 return hba->outstanding_reqs ? SCSI_EH_RESET_TIMER : SCSI_EH_DONE;
8428 static const struct attribute_group *ufshcd_driver_groups[] = {
8429 &ufs_sysfs_unit_descriptor_group,
8430 &ufs_sysfs_lun_attributes_group,
8431 #ifdef CONFIG_SCSI_UFS_HPB
8432 &ufs_sysfs_hpb_stat_group,
8433 &ufs_sysfs_hpb_param_group,
8438 static struct ufs_hba_variant_params ufs_hba_vps = {
8439 .hba_enable_delay_us = 1000,
8440 .wb_flush_threshold = UFS_WB_BUF_REMAIN_PERCENT(40),
8441 .devfreq_profile.polling_ms = 100,
8442 .devfreq_profile.target = ufshcd_devfreq_target,
8443 .devfreq_profile.get_dev_status = ufshcd_devfreq_get_dev_status,
8444 .ondemand_data.upthreshold = 70,
8445 .ondemand_data.downdifferential = 5,
8448 static struct scsi_host_template ufshcd_driver_template = {
8449 .module = THIS_MODULE,
8451 .proc_name = UFSHCD,
8452 .map_queues = ufshcd_map_queues,
8453 .queuecommand = ufshcd_queuecommand,
8454 .mq_poll = ufshcd_poll,
8455 .slave_alloc = ufshcd_slave_alloc,
8456 .slave_configure = ufshcd_slave_configure,
8457 .slave_destroy = ufshcd_slave_destroy,
8458 .change_queue_depth = ufshcd_change_queue_depth,
8459 .eh_abort_handler = ufshcd_abort,
8460 .eh_device_reset_handler = ufshcd_eh_device_reset_handler,
8461 .eh_host_reset_handler = ufshcd_eh_host_reset_handler,
8462 .eh_timed_out = ufshcd_eh_timed_out,
8464 .sg_tablesize = SG_ALL,
8465 .cmd_per_lun = UFSHCD_CMD_PER_LUN,
8466 .can_queue = UFSHCD_CAN_QUEUE,
8467 .max_segment_size = PRDT_DATA_BYTE_COUNT_MAX,
8468 .max_sectors = (1 << 20) / SECTOR_SIZE, /* 1 MiB */
8469 .max_host_blocked = 1,
8470 .track_queue_depth = 1,
8471 .sdev_groups = ufshcd_driver_groups,
8472 .dma_boundary = PAGE_SIZE - 1,
8473 .rpm_autosuspend_delay = RPM_AUTOSUSPEND_DELAY_MS,
8476 static int ufshcd_config_vreg_load(struct device *dev, struct ufs_vreg *vreg,
8485 * "set_load" operation shall be required on those regulators
8486 * which specifically configured current limitation. Otherwise
8487 * zero max_uA may cause unexpected behavior when regulator is
8488 * enabled or set as high power mode.
8493 ret = regulator_set_load(vreg->reg, ua);
8495 dev_err(dev, "%s: %s set load (ua=%d) failed, err=%d\n",
8496 __func__, vreg->name, ua, ret);
8502 static inline int ufshcd_config_vreg_lpm(struct ufs_hba *hba,
8503 struct ufs_vreg *vreg)
8505 return ufshcd_config_vreg_load(hba->dev, vreg, UFS_VREG_LPM_LOAD_UA);
8508 static inline int ufshcd_config_vreg_hpm(struct ufs_hba *hba,
8509 struct ufs_vreg *vreg)
8514 return ufshcd_config_vreg_load(hba->dev, vreg, vreg->max_uA);
8517 static int ufshcd_config_vreg(struct device *dev,
8518 struct ufs_vreg *vreg, bool on)
8520 if (regulator_count_voltages(vreg->reg) <= 0)
8523 return ufshcd_config_vreg_load(dev, vreg, on ? vreg->max_uA : 0);
8526 static int ufshcd_enable_vreg(struct device *dev, struct ufs_vreg *vreg)
8530 if (!vreg || vreg->enabled)
8533 ret = ufshcd_config_vreg(dev, vreg, true);
8535 ret = regulator_enable(vreg->reg);
8538 vreg->enabled = true;
8540 dev_err(dev, "%s: %s enable failed, err=%d\n",
8541 __func__, vreg->name, ret);
8546 static int ufshcd_disable_vreg(struct device *dev, struct ufs_vreg *vreg)
8550 if (!vreg || !vreg->enabled || vreg->always_on)
8553 ret = regulator_disable(vreg->reg);
8556 /* ignore errors on applying disable config */
8557 ufshcd_config_vreg(dev, vreg, false);
8558 vreg->enabled = false;
8560 dev_err(dev, "%s: %s disable failed, err=%d\n",
8561 __func__, vreg->name, ret);
8567 static int ufshcd_setup_vreg(struct ufs_hba *hba, bool on)
8570 struct device *dev = hba->dev;
8571 struct ufs_vreg_info *info = &hba->vreg_info;
8573 ret = ufshcd_toggle_vreg(dev, info->vcc, on);
8577 ret = ufshcd_toggle_vreg(dev, info->vccq, on);
8581 ret = ufshcd_toggle_vreg(dev, info->vccq2, on);
8585 ufshcd_toggle_vreg(dev, info->vccq2, false);
8586 ufshcd_toggle_vreg(dev, info->vccq, false);
8587 ufshcd_toggle_vreg(dev, info->vcc, false);
8592 static int ufshcd_setup_hba_vreg(struct ufs_hba *hba, bool on)
8594 struct ufs_vreg_info *info = &hba->vreg_info;
8596 return ufshcd_toggle_vreg(hba->dev, info->vdd_hba, on);
8599 int ufshcd_get_vreg(struct device *dev, struct ufs_vreg *vreg)
8606 vreg->reg = devm_regulator_get(dev, vreg->name);
8607 if (IS_ERR(vreg->reg)) {
8608 ret = PTR_ERR(vreg->reg);
8609 dev_err(dev, "%s: %s get failed, err=%d\n",
8610 __func__, vreg->name, ret);
8615 EXPORT_SYMBOL_GPL(ufshcd_get_vreg);
8617 static int ufshcd_init_vreg(struct ufs_hba *hba)
8620 struct device *dev = hba->dev;
8621 struct ufs_vreg_info *info = &hba->vreg_info;
8623 ret = ufshcd_get_vreg(dev, info->vcc);
8627 ret = ufshcd_get_vreg(dev, info->vccq);
8629 ret = ufshcd_get_vreg(dev, info->vccq2);
8634 static int ufshcd_init_hba_vreg(struct ufs_hba *hba)
8636 struct ufs_vreg_info *info = &hba->vreg_info;
8638 return ufshcd_get_vreg(hba->dev, info->vdd_hba);
8641 static int ufshcd_setup_clocks(struct ufs_hba *hba, bool on)
8644 struct ufs_clk_info *clki;
8645 struct list_head *head = &hba->clk_list_head;
8646 unsigned long flags;
8647 ktime_t start = ktime_get();
8648 bool clk_state_changed = false;
8650 if (list_empty(head))
8653 ret = ufshcd_vops_setup_clocks(hba, on, PRE_CHANGE);
8657 list_for_each_entry(clki, head, list) {
8658 if (!IS_ERR_OR_NULL(clki->clk)) {
8660 * Don't disable clocks which are needed
8661 * to keep the link active.
8663 if (ufshcd_is_link_active(hba) &&
8664 clki->keep_link_active)
8667 clk_state_changed = on ^ clki->enabled;
8668 if (on && !clki->enabled) {
8669 ret = clk_prepare_enable(clki->clk);
8671 dev_err(hba->dev, "%s: %s prepare enable failed, %d\n",
8672 __func__, clki->name, ret);
8675 } else if (!on && clki->enabled) {
8676 clk_disable_unprepare(clki->clk);
8679 dev_dbg(hba->dev, "%s: clk: %s %sabled\n", __func__,
8680 clki->name, on ? "en" : "dis");
8684 ret = ufshcd_vops_setup_clocks(hba, on, POST_CHANGE);
8690 list_for_each_entry(clki, head, list) {
8691 if (!IS_ERR_OR_NULL(clki->clk) && clki->enabled)
8692 clk_disable_unprepare(clki->clk);
8694 } else if (!ret && on) {
8695 spin_lock_irqsave(hba->host->host_lock, flags);
8696 hba->clk_gating.state = CLKS_ON;
8697 trace_ufshcd_clk_gating(dev_name(hba->dev),
8698 hba->clk_gating.state);
8699 spin_unlock_irqrestore(hba->host->host_lock, flags);
8702 if (clk_state_changed)
8703 trace_ufshcd_profile_clk_gating(dev_name(hba->dev),
8704 (on ? "on" : "off"),
8705 ktime_to_us(ktime_sub(ktime_get(), start)), ret);
8709 static enum ufs_ref_clk_freq ufshcd_parse_ref_clk_property(struct ufs_hba *hba)
8712 int ret = device_property_read_u32(hba->dev, "ref-clk-freq", &freq);
8715 dev_dbg(hba->dev, "Cannot query 'ref-clk-freq' property = %d", ret);
8716 return REF_CLK_FREQ_INVAL;
8719 return ufs_get_bref_clk_from_hz(freq);
8722 static int ufshcd_init_clocks(struct ufs_hba *hba)
8725 struct ufs_clk_info *clki;
8726 struct device *dev = hba->dev;
8727 struct list_head *head = &hba->clk_list_head;
8729 if (list_empty(head))
8732 list_for_each_entry(clki, head, list) {
8736 clki->clk = devm_clk_get(dev, clki->name);
8737 if (IS_ERR(clki->clk)) {
8738 ret = PTR_ERR(clki->clk);
8739 dev_err(dev, "%s: %s clk get failed, %d\n",
8740 __func__, clki->name, ret);
8745 * Parse device ref clk freq as per device tree "ref_clk".
8746 * Default dev_ref_clk_freq is set to REF_CLK_FREQ_INVAL
8747 * in ufshcd_alloc_host().
8749 if (!strcmp(clki->name, "ref_clk"))
8750 ufshcd_parse_dev_ref_clk_freq(hba, clki->clk);
8752 if (clki->max_freq) {
8753 ret = clk_set_rate(clki->clk, clki->max_freq);
8755 dev_err(hba->dev, "%s: %s clk set rate(%dHz) failed, %d\n",
8756 __func__, clki->name,
8757 clki->max_freq, ret);
8760 clki->curr_freq = clki->max_freq;
8762 dev_dbg(dev, "%s: clk: %s, rate: %lu\n", __func__,
8763 clki->name, clk_get_rate(clki->clk));
8769 static int ufshcd_variant_hba_init(struct ufs_hba *hba)
8776 err = ufshcd_vops_init(hba);
8778 dev_err(hba->dev, "%s: variant %s init failed err %d\n",
8779 __func__, ufshcd_get_var_name(hba), err);
8784 static void ufshcd_variant_hba_exit(struct ufs_hba *hba)
8789 ufshcd_vops_exit(hba);
8792 static int ufshcd_hba_init(struct ufs_hba *hba)
8797 * Handle host controller power separately from the UFS device power
8798 * rails as it will help controlling the UFS host controller power
8799 * collapse easily which is different than UFS device power collapse.
8800 * Also, enable the host controller power before we go ahead with rest
8801 * of the initialization here.
8803 err = ufshcd_init_hba_vreg(hba);
8807 err = ufshcd_setup_hba_vreg(hba, true);
8811 err = ufshcd_init_clocks(hba);
8813 goto out_disable_hba_vreg;
8815 if (hba->dev_ref_clk_freq == REF_CLK_FREQ_INVAL)
8816 hba->dev_ref_clk_freq = ufshcd_parse_ref_clk_property(hba);
8818 err = ufshcd_setup_clocks(hba, true);
8820 goto out_disable_hba_vreg;
8822 err = ufshcd_init_vreg(hba);
8824 goto out_disable_clks;
8826 err = ufshcd_setup_vreg(hba, true);
8828 goto out_disable_clks;
8830 err = ufshcd_variant_hba_init(hba);
8832 goto out_disable_vreg;
8834 ufs_debugfs_hba_init(hba);
8836 hba->is_powered = true;
8840 ufshcd_setup_vreg(hba, false);
8842 ufshcd_setup_clocks(hba, false);
8843 out_disable_hba_vreg:
8844 ufshcd_setup_hba_vreg(hba, false);
8849 static void ufshcd_hba_exit(struct ufs_hba *hba)
8851 if (hba->is_powered) {
8852 ufshcd_exit_clk_scaling(hba);
8853 ufshcd_exit_clk_gating(hba);
8855 destroy_workqueue(hba->eh_wq);
8856 ufs_debugfs_hba_exit(hba);
8857 ufshcd_variant_hba_exit(hba);
8858 ufshcd_setup_vreg(hba, false);
8859 ufshcd_setup_clocks(hba, false);
8860 ufshcd_setup_hba_vreg(hba, false);
8861 hba->is_powered = false;
8862 ufs_put_device_desc(hba);
8866 static int ufshcd_execute_start_stop(struct scsi_device *sdev,
8867 enum ufs_dev_pwr_mode pwr_mode,
8868 struct scsi_sense_hdr *sshdr)
8870 unsigned char cdb[6] = { START_STOP, 0, 0, 0, pwr_mode << 4, 0 };
8871 struct request *req;
8872 struct scsi_cmnd *scmd;
8875 req = scsi_alloc_request(sdev->request_queue, REQ_OP_DRV_IN,
8878 return PTR_ERR(req);
8880 scmd = blk_mq_rq_to_pdu(req);
8881 scmd->cmd_len = COMMAND_SIZE(cdb[0]);
8882 memcpy(scmd->cmnd, cdb, scmd->cmd_len);
8883 scmd->allowed = 0/*retries*/;
8884 scmd->flags |= SCMD_FAIL_IF_RECOVERING;
8885 req->timeout = 1 * HZ;
8886 req->rq_flags |= RQF_PM | RQF_QUIET;
8888 blk_execute_rq(req, /*at_head=*/true);
8891 scsi_normalize_sense(scmd->sense_buffer, scmd->sense_len,
8895 blk_mq_free_request(req);
8901 * ufshcd_set_dev_pwr_mode - sends START STOP UNIT command to set device
8903 * @hba: per adapter instance
8904 * @pwr_mode: device power mode to set
8906 * Returns 0 if requested power mode is set successfully
8907 * Returns < 0 if failed to set the requested power mode
8909 static int ufshcd_set_dev_pwr_mode(struct ufs_hba *hba,
8910 enum ufs_dev_pwr_mode pwr_mode)
8912 struct scsi_sense_hdr sshdr;
8913 struct scsi_device *sdp;
8914 unsigned long flags;
8917 spin_lock_irqsave(hba->host->host_lock, flags);
8918 sdp = hba->ufs_device_wlun;
8919 if (sdp && scsi_device_online(sdp))
8920 ret = scsi_device_get(sdp);
8923 spin_unlock_irqrestore(hba->host->host_lock, flags);
8929 * If scsi commands fail, the scsi mid-layer schedules scsi error-
8930 * handling, which would wait for host to be resumed. Since we know
8931 * we are functional while we are here, skip host resume in error
8934 hba->host->eh_noresume = 1;
8937 * Current function would be generally called from the power management
8938 * callbacks hence set the RQF_PM flag so that it doesn't resume the
8939 * already suspended childs.
8941 for (retries = 3; retries > 0; --retries) {
8942 ret = ufshcd_execute_start_stop(sdp, pwr_mode, &sshdr);
8944 * scsi_execute() only returns a negative value if the request
8951 sdev_printk(KERN_WARNING, sdp,
8952 "START_STOP failed for power mode: %d, result %x\n",
8955 if (scsi_sense_valid(&sshdr))
8956 scsi_print_sense_hdr(sdp, NULL, &sshdr);
8960 hba->curr_dev_pwr_mode = pwr_mode;
8963 scsi_device_put(sdp);
8964 hba->host->eh_noresume = 0;
8968 static int ufshcd_link_state_transition(struct ufs_hba *hba,
8969 enum uic_link_state req_link_state,
8970 bool check_for_bkops)
8974 if (req_link_state == hba->uic_link_state)
8977 if (req_link_state == UIC_LINK_HIBERN8_STATE) {
8978 ret = ufshcd_uic_hibern8_enter(hba);
8980 ufshcd_set_link_hibern8(hba);
8982 dev_err(hba->dev, "%s: hibern8 enter failed %d\n",
8988 * If autobkops is enabled, link can't be turned off because
8989 * turning off the link would also turn off the device, except in the
8990 * case of DeepSleep where the device is expected to remain powered.
8992 else if ((req_link_state == UIC_LINK_OFF_STATE) &&
8993 (!check_for_bkops || !hba->auto_bkops_enabled)) {
8995 * Let's make sure that link is in low power mode, we are doing
8996 * this currently by putting the link in Hibern8. Otherway to
8997 * put the link in low power mode is to send the DME end point
8998 * to device and then send the DME reset command to local
8999 * unipro. But putting the link in hibern8 is much faster.
9001 * Note also that putting the link in Hibern8 is a requirement
9002 * for entering DeepSleep.
9004 ret = ufshcd_uic_hibern8_enter(hba);
9006 dev_err(hba->dev, "%s: hibern8 enter failed %d\n",
9011 * Change controller state to "reset state" which
9012 * should also put the link in off/reset state
9014 ufshcd_hba_stop(hba);
9016 * TODO: Check if we need any delay to make sure that
9017 * controller is reset
9019 ufshcd_set_link_off(hba);
9026 static void ufshcd_vreg_set_lpm(struct ufs_hba *hba)
9028 bool vcc_off = false;
9031 * It seems some UFS devices may keep drawing more than sleep current
9032 * (atleast for 500us) from UFS rails (especially from VCCQ rail).
9033 * To avoid this situation, add 2ms delay before putting these UFS
9034 * rails in LPM mode.
9036 if (!ufshcd_is_link_active(hba) &&
9037 hba->dev_quirks & UFS_DEVICE_QUIRK_DELAY_BEFORE_LPM)
9038 usleep_range(2000, 2100);
9041 * If UFS device is either in UFS_Sleep turn off VCC rail to save some
9044 * If UFS device and link is in OFF state, all power supplies (VCC,
9045 * VCCQ, VCCQ2) can be turned off if power on write protect is not
9046 * required. If UFS link is inactive (Hibern8 or OFF state) and device
9047 * is in sleep state, put VCCQ & VCCQ2 rails in LPM mode.
9049 * Ignore the error returned by ufshcd_toggle_vreg() as device is anyway
9050 * in low power state which would save some power.
9052 * If Write Booster is enabled and the device needs to flush the WB
9053 * buffer OR if bkops status is urgent for WB, keep Vcc on.
9055 if (ufshcd_is_ufs_dev_poweroff(hba) && ufshcd_is_link_off(hba) &&
9056 !hba->dev_info.is_lu_power_on_wp) {
9057 ufshcd_setup_vreg(hba, false);
9059 } else if (!ufshcd_is_ufs_dev_active(hba)) {
9060 ufshcd_toggle_vreg(hba->dev, hba->vreg_info.vcc, false);
9062 if (ufshcd_is_link_hibern8(hba) || ufshcd_is_link_off(hba)) {
9063 ufshcd_config_vreg_lpm(hba, hba->vreg_info.vccq);
9064 ufshcd_config_vreg_lpm(hba, hba->vreg_info.vccq2);
9069 * Some UFS devices require delay after VCC power rail is turned-off.
9071 if (vcc_off && hba->vreg_info.vcc &&
9072 hba->dev_quirks & UFS_DEVICE_QUIRK_DELAY_AFTER_LPM)
9073 usleep_range(5000, 5100);
9077 static int ufshcd_vreg_set_hpm(struct ufs_hba *hba)
9081 if (ufshcd_is_ufs_dev_poweroff(hba) && ufshcd_is_link_off(hba) &&
9082 !hba->dev_info.is_lu_power_on_wp) {
9083 ret = ufshcd_setup_vreg(hba, true);
9084 } else if (!ufshcd_is_ufs_dev_active(hba)) {
9085 if (!ufshcd_is_link_active(hba)) {
9086 ret = ufshcd_config_vreg_hpm(hba, hba->vreg_info.vccq);
9089 ret = ufshcd_config_vreg_hpm(hba, hba->vreg_info.vccq2);
9093 ret = ufshcd_toggle_vreg(hba->dev, hba->vreg_info.vcc, true);
9098 ufshcd_config_vreg_lpm(hba, hba->vreg_info.vccq);
9100 ufshcd_toggle_vreg(hba->dev, hba->vreg_info.vcc, false);
9104 #endif /* CONFIG_PM */
9106 static void ufshcd_hba_vreg_set_lpm(struct ufs_hba *hba)
9108 if (ufshcd_is_link_off(hba) || ufshcd_can_aggressive_pc(hba))
9109 ufshcd_setup_hba_vreg(hba, false);
9112 static void ufshcd_hba_vreg_set_hpm(struct ufs_hba *hba)
9114 if (ufshcd_is_link_off(hba) || ufshcd_can_aggressive_pc(hba))
9115 ufshcd_setup_hba_vreg(hba, true);
9118 static int __ufshcd_wl_suspend(struct ufs_hba *hba, enum ufs_pm_op pm_op)
9121 bool check_for_bkops;
9122 enum ufs_pm_level pm_lvl;
9123 enum ufs_dev_pwr_mode req_dev_pwr_mode;
9124 enum uic_link_state req_link_state;
9126 hba->pm_op_in_progress = true;
9127 if (pm_op != UFS_SHUTDOWN_PM) {
9128 pm_lvl = pm_op == UFS_RUNTIME_PM ?
9129 hba->rpm_lvl : hba->spm_lvl;
9130 req_dev_pwr_mode = ufs_get_pm_lvl_to_dev_pwr_mode(pm_lvl);
9131 req_link_state = ufs_get_pm_lvl_to_link_pwr_state(pm_lvl);
9133 req_dev_pwr_mode = UFS_POWERDOWN_PWR_MODE;
9134 req_link_state = UIC_LINK_OFF_STATE;
9137 ufshpb_suspend(hba);
9140 * If we can't transition into any of the low power modes
9141 * just gate the clocks.
9143 ufshcd_hold(hba, false);
9144 hba->clk_gating.is_suspended = true;
9146 if (ufshcd_is_clkscaling_supported(hba))
9147 ufshcd_clk_scaling_suspend(hba, true);
9149 if (req_dev_pwr_mode == UFS_ACTIVE_PWR_MODE &&
9150 req_link_state == UIC_LINK_ACTIVE_STATE) {
9154 if ((req_dev_pwr_mode == hba->curr_dev_pwr_mode) &&
9155 (req_link_state == hba->uic_link_state))
9156 goto enable_scaling;
9158 /* UFS device & link must be active before we enter in this function */
9159 if (!ufshcd_is_ufs_dev_active(hba) || !ufshcd_is_link_active(hba)) {
9161 goto enable_scaling;
9164 if (pm_op == UFS_RUNTIME_PM) {
9165 if (ufshcd_can_autobkops_during_suspend(hba)) {
9167 * The device is idle with no requests in the queue,
9168 * allow background operations if bkops status shows
9169 * that performance might be impacted.
9171 ret = ufshcd_urgent_bkops(hba);
9173 goto enable_scaling;
9175 /* make sure that auto bkops is disabled */
9176 ufshcd_disable_auto_bkops(hba);
9179 * If device needs to do BKOP or WB buffer flush during
9180 * Hibern8, keep device power mode as "active power mode"
9183 hba->dev_info.b_rpm_dev_flush_capable =
9184 hba->auto_bkops_enabled ||
9185 (((req_link_state == UIC_LINK_HIBERN8_STATE) ||
9186 ((req_link_state == UIC_LINK_ACTIVE_STATE) &&
9187 ufshcd_is_auto_hibern8_enabled(hba))) &&
9188 ufshcd_wb_need_flush(hba));
9191 flush_work(&hba->eeh_work);
9193 ret = ufshcd_vops_suspend(hba, pm_op, PRE_CHANGE);
9195 goto enable_scaling;
9197 if (req_dev_pwr_mode != hba->curr_dev_pwr_mode) {
9198 if (pm_op != UFS_RUNTIME_PM)
9199 /* ensure that bkops is disabled */
9200 ufshcd_disable_auto_bkops(hba);
9202 if (!hba->dev_info.b_rpm_dev_flush_capable) {
9203 ret = ufshcd_set_dev_pwr_mode(hba, req_dev_pwr_mode);
9205 goto enable_scaling;
9210 * In the case of DeepSleep, the device is expected to remain powered
9211 * with the link off, so do not check for bkops.
9213 check_for_bkops = !ufshcd_is_ufs_dev_deepsleep(hba);
9214 ret = ufshcd_link_state_transition(hba, req_link_state, check_for_bkops);
9216 goto set_dev_active;
9220 * Call vendor specific suspend callback. As these callbacks may access
9221 * vendor specific host controller register space call them before the
9222 * host clocks are ON.
9224 ret = ufshcd_vops_suspend(hba, pm_op, POST_CHANGE);
9226 goto set_link_active;
9231 * Device hardware reset is required to exit DeepSleep. Also, for
9232 * DeepSleep, the link is off so host reset and restore will be done
9235 if (ufshcd_is_ufs_dev_deepsleep(hba)) {
9236 ufshcd_device_reset(hba);
9237 WARN_ON(!ufshcd_is_link_off(hba));
9239 if (ufshcd_is_link_hibern8(hba) && !ufshcd_uic_hibern8_exit(hba))
9240 ufshcd_set_link_active(hba);
9241 else if (ufshcd_is_link_off(hba))
9242 ufshcd_host_reset_and_restore(hba);
9244 /* Can also get here needing to exit DeepSleep */
9245 if (ufshcd_is_ufs_dev_deepsleep(hba)) {
9246 ufshcd_device_reset(hba);
9247 ufshcd_host_reset_and_restore(hba);
9249 if (!ufshcd_set_dev_pwr_mode(hba, UFS_ACTIVE_PWR_MODE))
9250 ufshcd_disable_auto_bkops(hba);
9252 if (ufshcd_is_clkscaling_supported(hba))
9253 ufshcd_clk_scaling_suspend(hba, false);
9255 hba->dev_info.b_rpm_dev_flush_capable = false;
9257 if (hba->dev_info.b_rpm_dev_flush_capable) {
9258 schedule_delayed_work(&hba->rpm_dev_flush_recheck_work,
9259 msecs_to_jiffies(RPM_DEV_FLUSH_RECHECK_WORK_DELAY_MS));
9263 ufshcd_update_evt_hist(hba, UFS_EVT_WL_SUSP_ERR, (u32)ret);
9264 hba->clk_gating.is_suspended = false;
9265 ufshcd_release(hba);
9268 hba->pm_op_in_progress = false;
9273 static int __ufshcd_wl_resume(struct ufs_hba *hba, enum ufs_pm_op pm_op)
9276 enum uic_link_state old_link_state = hba->uic_link_state;
9278 hba->pm_op_in_progress = true;
9281 * Call vendor specific resume callback. As these callbacks may access
9282 * vendor specific host controller register space call them when the
9283 * host clocks are ON.
9285 ret = ufshcd_vops_resume(hba, pm_op);
9289 /* For DeepSleep, the only supported option is to have the link off */
9290 WARN_ON(ufshcd_is_ufs_dev_deepsleep(hba) && !ufshcd_is_link_off(hba));
9292 if (ufshcd_is_link_hibern8(hba)) {
9293 ret = ufshcd_uic_hibern8_exit(hba);
9295 ufshcd_set_link_active(hba);
9297 dev_err(hba->dev, "%s: hibern8 exit failed %d\n",
9299 goto vendor_suspend;
9301 } else if (ufshcd_is_link_off(hba)) {
9303 * A full initialization of the host and the device is
9304 * required since the link was put to off during suspend.
9305 * Note, in the case of DeepSleep, the device will exit
9306 * DeepSleep due to device reset.
9308 ret = ufshcd_reset_and_restore(hba);
9310 * ufshcd_reset_and_restore() should have already
9311 * set the link state as active
9313 if (ret || !ufshcd_is_link_active(hba))
9314 goto vendor_suspend;
9317 if (!ufshcd_is_ufs_dev_active(hba)) {
9318 ret = ufshcd_set_dev_pwr_mode(hba, UFS_ACTIVE_PWR_MODE);
9320 goto set_old_link_state;
9323 if (ufshcd_keep_autobkops_enabled_except_suspend(hba))
9324 ufshcd_enable_auto_bkops(hba);
9327 * If BKOPs operations are urgently needed at this moment then
9328 * keep auto-bkops enabled or else disable it.
9330 ufshcd_urgent_bkops(hba);
9332 if (hba->ee_usr_mask)
9333 ufshcd_write_ee_control(hba);
9335 if (ufshcd_is_clkscaling_supported(hba))
9336 ufshcd_clk_scaling_suspend(hba, false);
9338 if (hba->dev_info.b_rpm_dev_flush_capable) {
9339 hba->dev_info.b_rpm_dev_flush_capable = false;
9340 cancel_delayed_work(&hba->rpm_dev_flush_recheck_work);
9343 /* Enable Auto-Hibernate if configured */
9344 ufshcd_auto_hibern8_enable(hba);
9350 ufshcd_link_state_transition(hba, old_link_state, 0);
9352 ufshcd_vops_suspend(hba, pm_op, PRE_CHANGE);
9353 ufshcd_vops_suspend(hba, pm_op, POST_CHANGE);
9356 ufshcd_update_evt_hist(hba, UFS_EVT_WL_RES_ERR, (u32)ret);
9357 hba->clk_gating.is_suspended = false;
9358 ufshcd_release(hba);
9359 hba->pm_op_in_progress = false;
9363 static int ufshcd_wl_runtime_suspend(struct device *dev)
9365 struct scsi_device *sdev = to_scsi_device(dev);
9366 struct ufs_hba *hba;
9368 ktime_t start = ktime_get();
9370 hba = shost_priv(sdev->host);
9372 ret = __ufshcd_wl_suspend(hba, UFS_RUNTIME_PM);
9374 dev_err(&sdev->sdev_gendev, "%s failed: %d\n", __func__, ret);
9376 trace_ufshcd_wl_runtime_suspend(dev_name(dev), ret,
9377 ktime_to_us(ktime_sub(ktime_get(), start)),
9378 hba->curr_dev_pwr_mode, hba->uic_link_state);
9383 static int ufshcd_wl_runtime_resume(struct device *dev)
9385 struct scsi_device *sdev = to_scsi_device(dev);
9386 struct ufs_hba *hba;
9388 ktime_t start = ktime_get();
9390 hba = shost_priv(sdev->host);
9392 ret = __ufshcd_wl_resume(hba, UFS_RUNTIME_PM);
9394 dev_err(&sdev->sdev_gendev, "%s failed: %d\n", __func__, ret);
9396 trace_ufshcd_wl_runtime_resume(dev_name(dev), ret,
9397 ktime_to_us(ktime_sub(ktime_get(), start)),
9398 hba->curr_dev_pwr_mode, hba->uic_link_state);
9404 #ifdef CONFIG_PM_SLEEP
9405 static int ufshcd_wl_suspend(struct device *dev)
9407 struct scsi_device *sdev = to_scsi_device(dev);
9408 struct ufs_hba *hba;
9410 ktime_t start = ktime_get();
9412 hba = shost_priv(sdev->host);
9413 down(&hba->host_sem);
9414 hba->system_suspending = true;
9416 if (pm_runtime_suspended(dev))
9419 ret = __ufshcd_wl_suspend(hba, UFS_SYSTEM_PM);
9421 dev_err(&sdev->sdev_gendev, "%s failed: %d\n", __func__, ret);
9427 hba->is_sys_suspended = true;
9428 trace_ufshcd_wl_suspend(dev_name(dev), ret,
9429 ktime_to_us(ktime_sub(ktime_get(), start)),
9430 hba->curr_dev_pwr_mode, hba->uic_link_state);
9435 static int ufshcd_wl_resume(struct device *dev)
9437 struct scsi_device *sdev = to_scsi_device(dev);
9438 struct ufs_hba *hba;
9440 ktime_t start = ktime_get();
9442 hba = shost_priv(sdev->host);
9444 if (pm_runtime_suspended(dev))
9447 ret = __ufshcd_wl_resume(hba, UFS_SYSTEM_PM);
9449 dev_err(&sdev->sdev_gendev, "%s failed: %d\n", __func__, ret);
9451 trace_ufshcd_wl_resume(dev_name(dev), ret,
9452 ktime_to_us(ktime_sub(ktime_get(), start)),
9453 hba->curr_dev_pwr_mode, hba->uic_link_state);
9455 hba->is_sys_suspended = false;
9456 hba->system_suspending = false;
9462 static void ufshcd_wl_shutdown(struct device *dev)
9464 struct scsi_device *sdev = to_scsi_device(dev);
9465 struct ufs_hba *hba;
9467 hba = shost_priv(sdev->host);
9469 down(&hba->host_sem);
9470 hba->shutting_down = true;
9473 /* Turn on everything while shutting down */
9474 ufshcd_rpm_get_sync(hba);
9475 scsi_device_quiesce(sdev);
9476 shost_for_each_device(sdev, hba->host) {
9477 if (sdev == hba->ufs_device_wlun)
9479 scsi_device_quiesce(sdev);
9481 __ufshcd_wl_suspend(hba, UFS_SHUTDOWN_PM);
9485 * ufshcd_suspend - helper function for suspend operations
9486 * @hba: per adapter instance
9488 * This function will put disable irqs, turn off clocks
9489 * and set vreg and hba-vreg in lpm mode.
9491 static int ufshcd_suspend(struct ufs_hba *hba)
9495 if (!hba->is_powered)
9498 * Disable the host irq as host controller as there won't be any
9499 * host controller transaction expected till resume.
9501 ufshcd_disable_irq(hba);
9502 ret = ufshcd_setup_clocks(hba, false);
9504 ufshcd_enable_irq(hba);
9507 if (ufshcd_is_clkgating_allowed(hba)) {
9508 hba->clk_gating.state = CLKS_OFF;
9509 trace_ufshcd_clk_gating(dev_name(hba->dev),
9510 hba->clk_gating.state);
9513 ufshcd_vreg_set_lpm(hba);
9514 /* Put the host controller in low power mode if possible */
9515 ufshcd_hba_vreg_set_lpm(hba);
9521 * ufshcd_resume - helper function for resume operations
9522 * @hba: per adapter instance
9524 * This function basically turns on the regulators, clocks and
9527 * Returns 0 for success and non-zero for failure
9529 static int ufshcd_resume(struct ufs_hba *hba)
9533 if (!hba->is_powered)
9536 ufshcd_hba_vreg_set_hpm(hba);
9537 ret = ufshcd_vreg_set_hpm(hba);
9541 /* Make sure clocks are enabled before accessing controller */
9542 ret = ufshcd_setup_clocks(hba, true);
9546 /* enable the host irq as host controller would be active soon */
9547 ufshcd_enable_irq(hba);
9551 ufshcd_vreg_set_lpm(hba);
9554 ufshcd_update_evt_hist(hba, UFS_EVT_RESUME_ERR, (u32)ret);
9557 #endif /* CONFIG_PM */
9559 #ifdef CONFIG_PM_SLEEP
9561 * ufshcd_system_suspend - system suspend callback
9562 * @dev: Device associated with the UFS controller.
9564 * Executed before putting the system into a sleep state in which the contents
9565 * of main memory are preserved.
9567 * Returns 0 for success and non-zero for failure
9569 int ufshcd_system_suspend(struct device *dev)
9571 struct ufs_hba *hba = dev_get_drvdata(dev);
9573 ktime_t start = ktime_get();
9575 if (pm_runtime_suspended(hba->dev))
9578 ret = ufshcd_suspend(hba);
9580 trace_ufshcd_system_suspend(dev_name(hba->dev), ret,
9581 ktime_to_us(ktime_sub(ktime_get(), start)),
9582 hba->curr_dev_pwr_mode, hba->uic_link_state);
9585 EXPORT_SYMBOL(ufshcd_system_suspend);
9588 * ufshcd_system_resume - system resume callback
9589 * @dev: Device associated with the UFS controller.
9591 * Executed after waking the system up from a sleep state in which the contents
9592 * of main memory were preserved.
9594 * Returns 0 for success and non-zero for failure
9596 int ufshcd_system_resume(struct device *dev)
9598 struct ufs_hba *hba = dev_get_drvdata(dev);
9599 ktime_t start = ktime_get();
9602 if (pm_runtime_suspended(hba->dev))
9605 ret = ufshcd_resume(hba);
9608 trace_ufshcd_system_resume(dev_name(hba->dev), ret,
9609 ktime_to_us(ktime_sub(ktime_get(), start)),
9610 hba->curr_dev_pwr_mode, hba->uic_link_state);
9614 EXPORT_SYMBOL(ufshcd_system_resume);
9615 #endif /* CONFIG_PM_SLEEP */
9619 * ufshcd_runtime_suspend - runtime suspend callback
9620 * @dev: Device associated with the UFS controller.
9622 * Check the description of ufshcd_suspend() function for more details.
9624 * Returns 0 for success and non-zero for failure
9626 int ufshcd_runtime_suspend(struct device *dev)
9628 struct ufs_hba *hba = dev_get_drvdata(dev);
9630 ktime_t start = ktime_get();
9632 ret = ufshcd_suspend(hba);
9634 trace_ufshcd_runtime_suspend(dev_name(hba->dev), ret,
9635 ktime_to_us(ktime_sub(ktime_get(), start)),
9636 hba->curr_dev_pwr_mode, hba->uic_link_state);
9639 EXPORT_SYMBOL(ufshcd_runtime_suspend);
9642 * ufshcd_runtime_resume - runtime resume routine
9643 * @dev: Device associated with the UFS controller.
9645 * This function basically brings controller
9646 * to active state. Following operations are done in this function:
9648 * 1. Turn on all the controller related clocks
9649 * 2. Turn ON VCC rail
9651 int ufshcd_runtime_resume(struct device *dev)
9653 struct ufs_hba *hba = dev_get_drvdata(dev);
9655 ktime_t start = ktime_get();
9657 ret = ufshcd_resume(hba);
9659 trace_ufshcd_runtime_resume(dev_name(hba->dev), ret,
9660 ktime_to_us(ktime_sub(ktime_get(), start)),
9661 hba->curr_dev_pwr_mode, hba->uic_link_state);
9664 EXPORT_SYMBOL(ufshcd_runtime_resume);
9665 #endif /* CONFIG_PM */
9668 * ufshcd_shutdown - shutdown routine
9669 * @hba: per adapter instance
9671 * This function would turn off both UFS device and UFS hba
9672 * regulators. It would also disable clocks.
9674 * Returns 0 always to allow force shutdown even in case of errors.
9676 int ufshcd_shutdown(struct ufs_hba *hba)
9678 if (ufshcd_is_ufs_dev_poweroff(hba) && ufshcd_is_link_off(hba))
9679 ufshcd_suspend(hba);
9681 hba->is_powered = false;
9682 /* allow force shutdown even in case of errors */
9685 EXPORT_SYMBOL(ufshcd_shutdown);
9688 * ufshcd_remove - de-allocate SCSI host and host memory space
9689 * data structure memory
9690 * @hba: per adapter instance
9692 void ufshcd_remove(struct ufs_hba *hba)
9694 if (hba->ufs_device_wlun)
9695 ufshcd_rpm_get_sync(hba);
9696 ufs_hwmon_remove(hba);
9697 ufs_bsg_remove(hba);
9699 ufs_sysfs_remove_nodes(hba->dev);
9700 blk_mq_destroy_queue(hba->tmf_queue);
9701 blk_put_queue(hba->tmf_queue);
9702 blk_mq_free_tag_set(&hba->tmf_tag_set);
9703 scsi_remove_host(hba->host);
9704 /* disable interrupts */
9705 ufshcd_disable_intr(hba, hba->intr_mask);
9706 ufshcd_hba_stop(hba);
9707 ufshcd_hba_exit(hba);
9709 EXPORT_SYMBOL_GPL(ufshcd_remove);
9712 * ufshcd_dealloc_host - deallocate Host Bus Adapter (HBA)
9713 * @hba: pointer to Host Bus Adapter (HBA)
9715 void ufshcd_dealloc_host(struct ufs_hba *hba)
9717 scsi_host_put(hba->host);
9719 EXPORT_SYMBOL_GPL(ufshcd_dealloc_host);
9722 * ufshcd_set_dma_mask - Set dma mask based on the controller
9723 * addressing capability
9724 * @hba: per adapter instance
9726 * Returns 0 for success, non-zero for failure
9728 static int ufshcd_set_dma_mask(struct ufs_hba *hba)
9730 if (hba->capabilities & MASK_64_ADDRESSING_SUPPORT) {
9731 if (!dma_set_mask_and_coherent(hba->dev, DMA_BIT_MASK(64)))
9734 return dma_set_mask_and_coherent(hba->dev, DMA_BIT_MASK(32));
9738 * ufshcd_alloc_host - allocate Host Bus Adapter (HBA)
9739 * @dev: pointer to device handle
9740 * @hba_handle: driver private handle
9741 * Returns 0 on success, non-zero value on failure
9743 int ufshcd_alloc_host(struct device *dev, struct ufs_hba **hba_handle)
9745 struct Scsi_Host *host;
9746 struct ufs_hba *hba;
9751 "Invalid memory reference for dev is NULL\n");
9756 host = scsi_host_alloc(&ufshcd_driver_template,
9757 sizeof(struct ufs_hba));
9759 dev_err(dev, "scsi_host_alloc failed\n");
9763 host->nr_maps = HCTX_TYPE_POLL + 1;
9764 hba = shost_priv(host);
9767 hba->dev_ref_clk_freq = REF_CLK_FREQ_INVAL;
9768 hba->nop_out_timeout = NOP_OUT_TIMEOUT;
9769 INIT_LIST_HEAD(&hba->clk_list_head);
9770 spin_lock_init(&hba->outstanding_lock);
9777 EXPORT_SYMBOL(ufshcd_alloc_host);
9779 /* This function exists because blk_mq_alloc_tag_set() requires this. */
9780 static blk_status_t ufshcd_queue_tmf(struct blk_mq_hw_ctx *hctx,
9781 const struct blk_mq_queue_data *qd)
9784 return BLK_STS_NOTSUPP;
9787 static const struct blk_mq_ops ufshcd_tmf_ops = {
9788 .queue_rq = ufshcd_queue_tmf,
9792 * ufshcd_init - Driver initialization routine
9793 * @hba: per-adapter instance
9794 * @mmio_base: base register address
9795 * @irq: Interrupt line of device
9796 * Returns 0 on success, non-zero value on failure
9798 int ufshcd_init(struct ufs_hba *hba, void __iomem *mmio_base, unsigned int irq)
9801 struct Scsi_Host *host = hba->host;
9802 struct device *dev = hba->dev;
9803 char eh_wq_name[sizeof("ufs_eh_wq_00")];
9806 * dev_set_drvdata() must be called before any callbacks are registered
9807 * that use dev_get_drvdata() (frequency scaling, clock scaling, hwmon,
9810 dev_set_drvdata(dev, hba);
9814 "Invalid memory reference for mmio_base is NULL\n");
9819 hba->mmio_base = mmio_base;
9821 hba->vps = &ufs_hba_vps;
9823 err = ufshcd_hba_init(hba);
9827 /* Read capabilities registers */
9828 err = ufshcd_hba_capabilities(hba);
9832 /* Get UFS version supported by the controller */
9833 hba->ufs_version = ufshcd_get_ufs_version(hba);
9835 /* Get Interrupt bit mask per version */
9836 hba->intr_mask = ufshcd_get_intr_mask(hba);
9838 err = ufshcd_set_dma_mask(hba);
9840 dev_err(hba->dev, "set dma mask failed\n");
9844 /* Allocate memory for host memory space */
9845 err = ufshcd_memory_alloc(hba);
9847 dev_err(hba->dev, "Memory allocation failed\n");
9852 ufshcd_host_memory_configure(hba);
9854 host->can_queue = hba->nutrs - UFSHCD_NUM_RESERVED;
9855 host->cmd_per_lun = hba->nutrs - UFSHCD_NUM_RESERVED;
9856 host->max_id = UFSHCD_MAX_ID;
9857 host->max_lun = UFS_MAX_LUNS;
9858 host->max_channel = UFSHCD_MAX_CHANNEL;
9859 host->unique_id = host->host_no;
9860 host->max_cmd_len = UFS_CDB_SIZE;
9862 hba->max_pwr_info.is_valid = false;
9864 /* Initialize work queues */
9865 snprintf(eh_wq_name, sizeof(eh_wq_name), "ufs_eh_wq_%d",
9866 hba->host->host_no);
9867 hba->eh_wq = create_singlethread_workqueue(eh_wq_name);
9869 dev_err(hba->dev, "%s: failed to create eh workqueue\n",
9874 INIT_WORK(&hba->eh_work, ufshcd_err_handler);
9875 INIT_WORK(&hba->eeh_work, ufshcd_exception_event_handler);
9877 sema_init(&hba->host_sem, 1);
9879 /* Initialize UIC command mutex */
9880 mutex_init(&hba->uic_cmd_mutex);
9882 /* Initialize mutex for device management commands */
9883 mutex_init(&hba->dev_cmd.lock);
9885 /* Initialize mutex for exception event control */
9886 mutex_init(&hba->ee_ctrl_mutex);
9888 init_rwsem(&hba->clk_scaling_lock);
9890 ufshcd_init_clk_gating(hba);
9892 ufshcd_init_clk_scaling(hba);
9895 * In order to avoid any spurious interrupt immediately after
9896 * registering UFS controller interrupt handler, clear any pending UFS
9897 * interrupt status and disable all the UFS interrupts.
9899 ufshcd_writel(hba, ufshcd_readl(hba, REG_INTERRUPT_STATUS),
9900 REG_INTERRUPT_STATUS);
9901 ufshcd_writel(hba, 0, REG_INTERRUPT_ENABLE);
9903 * Make sure that UFS interrupts are disabled and any pending interrupt
9904 * status is cleared before registering UFS interrupt handler.
9908 /* IRQ registration */
9909 err = devm_request_irq(dev, irq, ufshcd_intr, IRQF_SHARED, UFSHCD, hba);
9911 dev_err(hba->dev, "request irq failed\n");
9914 hba->is_irq_enabled = true;
9917 err = scsi_add_host(host, hba->dev);
9919 dev_err(hba->dev, "scsi_add_host failed\n");
9923 hba->tmf_tag_set = (struct blk_mq_tag_set) {
9925 .queue_depth = hba->nutmrs,
9926 .ops = &ufshcd_tmf_ops,
9927 .flags = BLK_MQ_F_NO_SCHED,
9929 err = blk_mq_alloc_tag_set(&hba->tmf_tag_set);
9931 goto out_remove_scsi_host;
9932 hba->tmf_queue = blk_mq_init_queue(&hba->tmf_tag_set);
9933 if (IS_ERR(hba->tmf_queue)) {
9934 err = PTR_ERR(hba->tmf_queue);
9935 goto free_tmf_tag_set;
9937 hba->tmf_rqs = devm_kcalloc(hba->dev, hba->nutmrs,
9938 sizeof(*hba->tmf_rqs), GFP_KERNEL);
9939 if (!hba->tmf_rqs) {
9941 goto free_tmf_queue;
9944 /* Reset the attached device */
9945 ufshcd_device_reset(hba);
9947 ufshcd_init_crypto(hba);
9949 /* Host controller enable */
9950 err = ufshcd_hba_enable(hba);
9952 dev_err(hba->dev, "Host controller enable failed\n");
9953 ufshcd_print_evt_hist(hba);
9954 ufshcd_print_host_state(hba);
9955 goto free_tmf_queue;
9959 * Set the default power management level for runtime and system PM.
9960 * Default power saving mode is to keep UFS link in Hibern8 state
9961 * and UFS device in sleep state.
9963 hba->rpm_lvl = ufs_get_desired_pm_lvl_for_dev_link_state(
9965 UIC_LINK_HIBERN8_STATE);
9966 hba->spm_lvl = ufs_get_desired_pm_lvl_for_dev_link_state(
9968 UIC_LINK_HIBERN8_STATE);
9970 INIT_DELAYED_WORK(&hba->rpm_dev_flush_recheck_work,
9971 ufshcd_rpm_dev_flush_recheck_work);
9973 /* Set the default auto-hiberate idle timer value to 150 ms */
9974 if (ufshcd_is_auto_hibern8_supported(hba) && !hba->ahit) {
9975 hba->ahit = FIELD_PREP(UFSHCI_AHIBERN8_TIMER_MASK, 150) |
9976 FIELD_PREP(UFSHCI_AHIBERN8_SCALE_MASK, 3);
9979 /* Hold auto suspend until async scan completes */
9980 pm_runtime_get_sync(dev);
9981 atomic_set(&hba->scsi_block_reqs_cnt, 0);
9983 * We are assuming that device wasn't put in sleep/power-down
9984 * state exclusively during the boot stage before kernel.
9985 * This assumption helps avoid doing link startup twice during
9986 * ufshcd_probe_hba().
9988 ufshcd_set_ufs_dev_active(hba);
9990 async_schedule(ufshcd_async_scan, hba);
9991 ufs_sysfs_add_nodes(hba->dev);
9993 device_enable_async_suspend(dev);
9997 blk_mq_destroy_queue(hba->tmf_queue);
9998 blk_put_queue(hba->tmf_queue);
10000 blk_mq_free_tag_set(&hba->tmf_tag_set);
10001 out_remove_scsi_host:
10002 scsi_remove_host(hba->host);
10004 hba->is_irq_enabled = false;
10005 ufshcd_hba_exit(hba);
10009 EXPORT_SYMBOL_GPL(ufshcd_init);
10011 void ufshcd_resume_complete(struct device *dev)
10013 struct ufs_hba *hba = dev_get_drvdata(dev);
10015 if (hba->complete_put) {
10016 ufshcd_rpm_put(hba);
10017 hba->complete_put = false;
10020 EXPORT_SYMBOL_GPL(ufshcd_resume_complete);
10022 static bool ufshcd_rpm_ok_for_spm(struct ufs_hba *hba)
10024 struct device *dev = &hba->ufs_device_wlun->sdev_gendev;
10025 enum ufs_dev_pwr_mode dev_pwr_mode;
10026 enum uic_link_state link_state;
10027 unsigned long flags;
10030 spin_lock_irqsave(&dev->power.lock, flags);
10031 dev_pwr_mode = ufs_get_pm_lvl_to_dev_pwr_mode(hba->spm_lvl);
10032 link_state = ufs_get_pm_lvl_to_link_pwr_state(hba->spm_lvl);
10033 res = pm_runtime_suspended(dev) &&
10034 hba->curr_dev_pwr_mode == dev_pwr_mode &&
10035 hba->uic_link_state == link_state &&
10036 !hba->dev_info.b_rpm_dev_flush_capable;
10037 spin_unlock_irqrestore(&dev->power.lock, flags);
10042 int __ufshcd_suspend_prepare(struct device *dev, bool rpm_ok_for_spm)
10044 struct ufs_hba *hba = dev_get_drvdata(dev);
10048 * SCSI assumes that runtime-pm and system-pm for scsi drivers
10049 * are same. And it doesn't wake up the device for system-suspend
10050 * if it's runtime suspended. But ufs doesn't follow that.
10051 * Refer ufshcd_resume_complete()
10053 if (hba->ufs_device_wlun) {
10054 /* Prevent runtime suspend */
10055 ufshcd_rpm_get_noresume(hba);
10057 * Check if already runtime suspended in same state as system
10058 * suspend would be.
10060 if (!rpm_ok_for_spm || !ufshcd_rpm_ok_for_spm(hba)) {
10061 /* RPM state is not ok for SPM, so runtime resume */
10062 ret = ufshcd_rpm_resume(hba);
10063 if (ret < 0 && ret != -EACCES) {
10064 ufshcd_rpm_put(hba);
10068 hba->complete_put = true;
10072 EXPORT_SYMBOL_GPL(__ufshcd_suspend_prepare);
10074 int ufshcd_suspend_prepare(struct device *dev)
10076 return __ufshcd_suspend_prepare(dev, true);
10078 EXPORT_SYMBOL_GPL(ufshcd_suspend_prepare);
10080 #ifdef CONFIG_PM_SLEEP
10081 static int ufshcd_wl_poweroff(struct device *dev)
10083 struct scsi_device *sdev = to_scsi_device(dev);
10084 struct ufs_hba *hba = shost_priv(sdev->host);
10086 __ufshcd_wl_suspend(hba, UFS_SHUTDOWN_PM);
10091 static int ufshcd_wl_probe(struct device *dev)
10093 struct scsi_device *sdev = to_scsi_device(dev);
10095 if (!is_device_wlun(sdev))
10098 blk_pm_runtime_init(sdev->request_queue, dev);
10099 pm_runtime_set_autosuspend_delay(dev, 0);
10100 pm_runtime_allow(dev);
10105 static int ufshcd_wl_remove(struct device *dev)
10107 pm_runtime_forbid(dev);
10111 static const struct dev_pm_ops ufshcd_wl_pm_ops = {
10112 #ifdef CONFIG_PM_SLEEP
10113 .suspend = ufshcd_wl_suspend,
10114 .resume = ufshcd_wl_resume,
10115 .freeze = ufshcd_wl_suspend,
10116 .thaw = ufshcd_wl_resume,
10117 .poweroff = ufshcd_wl_poweroff,
10118 .restore = ufshcd_wl_resume,
10120 SET_RUNTIME_PM_OPS(ufshcd_wl_runtime_suspend, ufshcd_wl_runtime_resume, NULL)
10124 * ufs_dev_wlun_template - describes ufs device wlun
10125 * ufs-device wlun - used to send pm commands
10126 * All luns are consumers of ufs-device wlun.
10128 * Currently, no sd driver is present for wluns.
10129 * Hence the no specific pm operations are performed.
10130 * With ufs design, SSU should be sent to ufs-device wlun.
10131 * Hence register a scsi driver for ufs wluns only.
10133 static struct scsi_driver ufs_dev_wlun_template = {
10135 .name = "ufs_device_wlun",
10136 .owner = THIS_MODULE,
10137 .probe = ufshcd_wl_probe,
10138 .remove = ufshcd_wl_remove,
10139 .pm = &ufshcd_wl_pm_ops,
10140 .shutdown = ufshcd_wl_shutdown,
10144 static int __init ufshcd_core_init(void)
10148 /* Verify that there are no gaps in struct utp_transfer_cmd_desc. */
10149 static_assert(sizeof(struct utp_transfer_cmd_desc) ==
10150 2 * ALIGNED_UPIU_SIZE +
10151 SG_ALL * sizeof(struct ufshcd_sg_entry));
10153 ufs_debugfs_init();
10155 ret = scsi_register_driver(&ufs_dev_wlun_template.gendrv);
10157 ufs_debugfs_exit();
10161 static void __exit ufshcd_core_exit(void)
10163 ufs_debugfs_exit();
10164 scsi_unregister_driver(&ufs_dev_wlun_template.gendrv);
10167 module_init(ufshcd_core_init);
10168 module_exit(ufshcd_core_exit);
10170 MODULE_AUTHOR("Santosh Yaragnavi <santosh.sy@samsung.com>");
10171 MODULE_AUTHOR("Vinayak Holikatti <h.vinayak@samsung.com>");
10172 MODULE_DESCRIPTION("Generic UFS host controller driver Core");
10173 MODULE_LICENSE("GPL");