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/pm_opp.h>
24 #include <linux/regulator/consumer.h>
25 #include <linux/sched/clock.h>
26 #include <linux/iopoll.h>
27 #include <scsi/scsi_cmnd.h>
28 #include <scsi/scsi_dbg.h>
29 #include <scsi/scsi_driver.h>
30 #include <scsi/scsi_eh.h>
31 #include "ufshcd-priv.h"
32 #include <ufs/ufs_quirks.h>
33 #include <ufs/unipro.h>
34 #include "ufs-sysfs.h"
35 #include "ufs-debugfs.h"
36 #include "ufs-fault-injection.h"
38 #include "ufshcd-crypto.h"
39 #include <asm/unaligned.h>
41 #define CREATE_TRACE_POINTS
42 #include <trace/events/ufs.h>
44 #define UFSHCD_ENABLE_INTRS (UTP_TRANSFER_REQ_COMPL |\
48 #define UFSHCD_ENABLE_MCQ_INTRS (UTP_TASK_REQ_COMPL |\
53 /* UIC command timeout, unit: ms */
54 #define UIC_CMD_TIMEOUT 500
56 /* NOP OUT retries waiting for NOP IN response */
57 #define NOP_OUT_RETRIES 10
58 /* Timeout after 50 msecs if NOP OUT hangs without response */
59 #define NOP_OUT_TIMEOUT 50 /* msecs */
61 /* Query request retries */
62 #define QUERY_REQ_RETRIES 3
63 /* Query request timeout */
64 #define QUERY_REQ_TIMEOUT 1500 /* 1.5 seconds */
66 /* Advanced RPMB request timeout */
67 #define ADVANCED_RPMB_REQ_TIMEOUT 3000 /* 3 seconds */
69 /* Task management command timeout */
70 #define TM_CMD_TIMEOUT 100 /* msecs */
72 /* maximum number of retries for a general UIC command */
73 #define UFS_UIC_COMMAND_RETRIES 3
75 /* maximum number of link-startup retries */
76 #define DME_LINKSTARTUP_RETRIES 3
78 /* maximum number of reset retries before giving up */
79 #define MAX_HOST_RESET_RETRIES 5
81 /* Maximum number of error handler retries before giving up */
82 #define MAX_ERR_HANDLER_RETRIES 5
84 /* Expose the flag value from utp_upiu_query.value */
85 #define MASK_QUERY_UPIU_FLAG_LOC 0xFF
87 /* Interrupt aggregation default timeout, unit: 40us */
88 #define INT_AGGR_DEF_TO 0x02
90 /* default delay of autosuspend: 2000 ms */
91 #define RPM_AUTOSUSPEND_DELAY_MS 2000
93 /* Default delay of RPM device flush delayed work */
94 #define RPM_DEV_FLUSH_RECHECK_WORK_DELAY_MS 5000
96 /* Default value of wait time before gating device ref clock */
97 #define UFSHCD_REF_CLK_GATING_WAIT_US 0xFF /* microsecs */
99 /* Polling time to wait for fDeviceInit */
100 #define FDEVICEINIT_COMPL_TIMEOUT 1500 /* millisecs */
102 /* Default RTC update every 10 seconds */
103 #define UFS_RTC_UPDATE_INTERVAL_MS (10 * MSEC_PER_SEC)
105 /* UFSHC 4.0 compliant HC support this mode. */
106 static bool use_mcq_mode = true;
108 static bool is_mcq_supported(struct ufs_hba *hba)
110 return hba->mcq_sup && use_mcq_mode;
113 module_param(use_mcq_mode, bool, 0644);
114 MODULE_PARM_DESC(use_mcq_mode, "Control MCQ mode for controllers starting from UFSHCI 4.0. 1 - enable MCQ, 0 - disable MCQ. MCQ is enabled by default");
116 #define ufshcd_toggle_vreg(_dev, _vreg, _on) \
120 _ret = ufshcd_enable_vreg(_dev, _vreg); \
122 _ret = ufshcd_disable_vreg(_dev, _vreg); \
126 #define ufshcd_hex_dump(prefix_str, buf, len) do { \
127 size_t __len = (len); \
128 print_hex_dump(KERN_ERR, prefix_str, \
129 __len > 4 ? DUMP_PREFIX_OFFSET : DUMP_PREFIX_NONE,\
130 16, 4, buf, __len, false); \
133 int ufshcd_dump_regs(struct ufs_hba *hba, size_t offset, size_t len,
139 if (offset % 4 != 0 || len % 4 != 0) /* keep readl happy */
142 regs = kzalloc(len, GFP_ATOMIC);
146 for (pos = 0; pos < len; pos += 4) {
148 pos >= REG_UIC_ERROR_CODE_PHY_ADAPTER_LAYER &&
149 pos <= REG_UIC_ERROR_CODE_DME)
151 regs[pos / 4] = ufshcd_readl(hba, offset + pos);
154 ufshcd_hex_dump(prefix, regs, len);
159 EXPORT_SYMBOL_GPL(ufshcd_dump_regs);
162 UFSHCD_MAX_CHANNEL = 0,
164 UFSHCD_CMD_PER_LUN = 32 - UFSHCD_NUM_RESERVED,
165 UFSHCD_CAN_QUEUE = 32 - UFSHCD_NUM_RESERVED,
168 static const char *const ufshcd_state_name[] = {
169 [UFSHCD_STATE_RESET] = "reset",
170 [UFSHCD_STATE_OPERATIONAL] = "operational",
171 [UFSHCD_STATE_ERROR] = "error",
172 [UFSHCD_STATE_EH_SCHEDULED_FATAL] = "eh_fatal",
173 [UFSHCD_STATE_EH_SCHEDULED_NON_FATAL] = "eh_non_fatal",
176 /* UFSHCD error handling flags */
178 UFSHCD_EH_IN_PROGRESS = (1 << 0),
181 /* UFSHCD UIC layer error flags */
183 UFSHCD_UIC_DL_PA_INIT_ERROR = (1 << 0), /* Data link layer error */
184 UFSHCD_UIC_DL_NAC_RECEIVED_ERROR = (1 << 1), /* Data link layer error */
185 UFSHCD_UIC_DL_TCx_REPLAY_ERROR = (1 << 2), /* Data link layer error */
186 UFSHCD_UIC_NL_ERROR = (1 << 3), /* Network layer error */
187 UFSHCD_UIC_TL_ERROR = (1 << 4), /* Transport Layer error */
188 UFSHCD_UIC_DME_ERROR = (1 << 5), /* DME error */
189 UFSHCD_UIC_PA_GENERIC_ERROR = (1 << 6), /* Generic PA error */
192 #define ufshcd_set_eh_in_progress(h) \
193 ((h)->eh_flags |= UFSHCD_EH_IN_PROGRESS)
194 #define ufshcd_eh_in_progress(h) \
195 ((h)->eh_flags & UFSHCD_EH_IN_PROGRESS)
196 #define ufshcd_clear_eh_in_progress(h) \
197 ((h)->eh_flags &= ~UFSHCD_EH_IN_PROGRESS)
199 const struct ufs_pm_lvl_states ufs_pm_lvl_states[] = {
200 [UFS_PM_LVL_0] = {UFS_ACTIVE_PWR_MODE, UIC_LINK_ACTIVE_STATE},
201 [UFS_PM_LVL_1] = {UFS_ACTIVE_PWR_MODE, UIC_LINK_HIBERN8_STATE},
202 [UFS_PM_LVL_2] = {UFS_SLEEP_PWR_MODE, UIC_LINK_ACTIVE_STATE},
203 [UFS_PM_LVL_3] = {UFS_SLEEP_PWR_MODE, UIC_LINK_HIBERN8_STATE},
204 [UFS_PM_LVL_4] = {UFS_POWERDOWN_PWR_MODE, UIC_LINK_HIBERN8_STATE},
205 [UFS_PM_LVL_5] = {UFS_POWERDOWN_PWR_MODE, UIC_LINK_OFF_STATE},
207 * For DeepSleep, the link is first put in hibern8 and then off.
208 * Leaving the link in hibern8 is not supported.
210 [UFS_PM_LVL_6] = {UFS_DEEPSLEEP_PWR_MODE, UIC_LINK_OFF_STATE},
213 static inline enum ufs_dev_pwr_mode
214 ufs_get_pm_lvl_to_dev_pwr_mode(enum ufs_pm_level lvl)
216 return ufs_pm_lvl_states[lvl].dev_state;
219 static inline enum uic_link_state
220 ufs_get_pm_lvl_to_link_pwr_state(enum ufs_pm_level lvl)
222 return ufs_pm_lvl_states[lvl].link_state;
225 static inline enum ufs_pm_level
226 ufs_get_desired_pm_lvl_for_dev_link_state(enum ufs_dev_pwr_mode dev_state,
227 enum uic_link_state link_state)
229 enum ufs_pm_level lvl;
231 for (lvl = UFS_PM_LVL_0; lvl < UFS_PM_LVL_MAX; lvl++) {
232 if ((ufs_pm_lvl_states[lvl].dev_state == dev_state) &&
233 (ufs_pm_lvl_states[lvl].link_state == link_state))
237 /* if no match found, return the level 0 */
241 static bool ufshcd_is_ufs_dev_busy(struct ufs_hba *hba)
243 return (hba->clk_gating.active_reqs || hba->outstanding_reqs || hba->outstanding_tasks ||
244 hba->active_uic_cmd || hba->uic_async_done);
247 static const struct ufs_dev_quirk ufs_fixups[] = {
248 /* UFS cards deviations table */
249 { .wmanufacturerid = UFS_VENDOR_MICRON,
250 .model = UFS_ANY_MODEL,
251 .quirk = UFS_DEVICE_QUIRK_DELAY_BEFORE_LPM },
252 { .wmanufacturerid = UFS_VENDOR_SAMSUNG,
253 .model = UFS_ANY_MODEL,
254 .quirk = UFS_DEVICE_QUIRK_DELAY_BEFORE_LPM |
255 UFS_DEVICE_QUIRK_HOST_PA_TACTIVATE |
256 UFS_DEVICE_QUIRK_RECOVERY_FROM_DL_NAC_ERRORS },
257 { .wmanufacturerid = UFS_VENDOR_SKHYNIX,
258 .model = UFS_ANY_MODEL,
259 .quirk = UFS_DEVICE_QUIRK_HOST_PA_SAVECONFIGTIME },
260 { .wmanufacturerid = UFS_VENDOR_SKHYNIX,
261 .model = "hB8aL1" /*H28U62301AMR*/,
262 .quirk = UFS_DEVICE_QUIRK_HOST_VS_DEBUGSAVECONFIGTIME },
263 { .wmanufacturerid = UFS_VENDOR_TOSHIBA,
264 .model = UFS_ANY_MODEL,
265 .quirk = UFS_DEVICE_QUIRK_DELAY_BEFORE_LPM },
266 { .wmanufacturerid = UFS_VENDOR_TOSHIBA,
267 .model = "THGLF2G9C8KBADG",
268 .quirk = UFS_DEVICE_QUIRK_PA_TACTIVATE },
269 { .wmanufacturerid = UFS_VENDOR_TOSHIBA,
270 .model = "THGLF2G9D8KBADG",
271 .quirk = UFS_DEVICE_QUIRK_PA_TACTIVATE },
275 static irqreturn_t ufshcd_tmc_handler(struct ufs_hba *hba);
276 static void ufshcd_async_scan(void *data, async_cookie_t cookie);
277 static int ufshcd_reset_and_restore(struct ufs_hba *hba);
278 static int ufshcd_eh_host_reset_handler(struct scsi_cmnd *cmd);
279 static int ufshcd_clear_tm_cmd(struct ufs_hba *hba, int tag);
280 static void ufshcd_hba_exit(struct ufs_hba *hba);
281 static int ufshcd_probe_hba(struct ufs_hba *hba, bool init_dev_params);
282 static int ufshcd_setup_clocks(struct ufs_hba *hba, bool on);
283 static inline void ufshcd_add_delay_before_dme_cmd(struct ufs_hba *hba);
284 static int ufshcd_host_reset_and_restore(struct ufs_hba *hba);
285 static void ufshcd_resume_clkscaling(struct ufs_hba *hba);
286 static void ufshcd_suspend_clkscaling(struct ufs_hba *hba);
287 static int ufshcd_scale_clks(struct ufs_hba *hba, unsigned long freq,
289 static irqreturn_t ufshcd_intr(int irq, void *__hba);
290 static int ufshcd_change_power_mode(struct ufs_hba *hba,
291 struct ufs_pa_layer_attr *pwr_mode);
292 static int ufshcd_setup_hba_vreg(struct ufs_hba *hba, bool on);
293 static int ufshcd_setup_vreg(struct ufs_hba *hba, bool on);
294 static inline int ufshcd_config_vreg_hpm(struct ufs_hba *hba,
295 struct ufs_vreg *vreg);
296 static void ufshcd_wb_toggle_buf_flush_during_h8(struct ufs_hba *hba,
298 static void ufshcd_hba_vreg_set_lpm(struct ufs_hba *hba);
299 static void ufshcd_hba_vreg_set_hpm(struct ufs_hba *hba);
301 void ufshcd_enable_irq(struct ufs_hba *hba)
303 if (!hba->is_irq_enabled) {
304 enable_irq(hba->irq);
305 hba->is_irq_enabled = true;
308 EXPORT_SYMBOL_GPL(ufshcd_enable_irq);
310 void ufshcd_disable_irq(struct ufs_hba *hba)
312 if (hba->is_irq_enabled) {
313 disable_irq(hba->irq);
314 hba->is_irq_enabled = false;
317 EXPORT_SYMBOL_GPL(ufshcd_disable_irq);
319 static void ufshcd_configure_wb(struct ufs_hba *hba)
321 if (!ufshcd_is_wb_allowed(hba))
324 ufshcd_wb_toggle(hba, true);
326 ufshcd_wb_toggle_buf_flush_during_h8(hba, true);
328 if (ufshcd_is_wb_buf_flush_allowed(hba))
329 ufshcd_wb_toggle_buf_flush(hba, true);
332 static void ufshcd_scsi_unblock_requests(struct ufs_hba *hba)
334 if (atomic_dec_and_test(&hba->scsi_block_reqs_cnt))
335 scsi_unblock_requests(hba->host);
338 static void ufshcd_scsi_block_requests(struct ufs_hba *hba)
340 if (atomic_inc_return(&hba->scsi_block_reqs_cnt) == 1)
341 scsi_block_requests(hba->host);
344 static void ufshcd_add_cmd_upiu_trace(struct ufs_hba *hba, unsigned int tag,
345 enum ufs_trace_str_t str_t)
347 struct utp_upiu_req *rq = hba->lrb[tag].ucd_req_ptr;
348 struct utp_upiu_header *header;
350 if (!trace_ufshcd_upiu_enabled())
353 if (str_t == UFS_CMD_SEND)
354 header = &rq->header;
356 header = &hba->lrb[tag].ucd_rsp_ptr->header;
358 trace_ufshcd_upiu(dev_name(hba->dev), str_t, header, &rq->sc.cdb,
362 static void ufshcd_add_query_upiu_trace(struct ufs_hba *hba,
363 enum ufs_trace_str_t str_t,
364 struct utp_upiu_req *rq_rsp)
366 if (!trace_ufshcd_upiu_enabled())
369 trace_ufshcd_upiu(dev_name(hba->dev), str_t, &rq_rsp->header,
370 &rq_rsp->qr, UFS_TSF_OSF);
373 static void ufshcd_add_tm_upiu_trace(struct ufs_hba *hba, unsigned int tag,
374 enum ufs_trace_str_t str_t)
376 struct utp_task_req_desc *descp = &hba->utmrdl_base_addr[tag];
378 if (!trace_ufshcd_upiu_enabled())
381 if (str_t == UFS_TM_SEND)
382 trace_ufshcd_upiu(dev_name(hba->dev), str_t,
383 &descp->upiu_req.req_header,
384 &descp->upiu_req.input_param1,
387 trace_ufshcd_upiu(dev_name(hba->dev), str_t,
388 &descp->upiu_rsp.rsp_header,
389 &descp->upiu_rsp.output_param1,
393 static void ufshcd_add_uic_command_trace(struct ufs_hba *hba,
394 const struct uic_command *ucmd,
395 enum ufs_trace_str_t str_t)
399 if (!trace_ufshcd_uic_command_enabled())
402 if (str_t == UFS_CMD_SEND)
405 cmd = ufshcd_readl(hba, REG_UIC_COMMAND);
407 trace_ufshcd_uic_command(dev_name(hba->dev), str_t, cmd,
408 ufshcd_readl(hba, REG_UIC_COMMAND_ARG_1),
409 ufshcd_readl(hba, REG_UIC_COMMAND_ARG_2),
410 ufshcd_readl(hba, REG_UIC_COMMAND_ARG_3));
413 static void ufshcd_add_command_trace(struct ufs_hba *hba, unsigned int tag,
414 enum ufs_trace_str_t str_t)
417 u8 opcode = 0, group_id = 0;
421 struct ufshcd_lrb *lrbp = &hba->lrb[tag];
422 struct scsi_cmnd *cmd = lrbp->cmd;
423 struct request *rq = scsi_cmd_to_rq(cmd);
424 int transfer_len = -1;
429 /* trace UPIU also */
430 ufshcd_add_cmd_upiu_trace(hba, tag, str_t);
431 if (!trace_ufshcd_command_enabled())
434 opcode = cmd->cmnd[0];
436 if (opcode == READ_10 || opcode == WRITE_10) {
438 * Currently we only fully trace read(10) and write(10) commands
441 be32_to_cpu(lrbp->ucd_req_ptr->sc.exp_data_transfer_len);
442 lba = scsi_get_lba(cmd);
443 if (opcode == WRITE_10)
444 group_id = lrbp->cmd->cmnd[6];
445 } else if (opcode == UNMAP) {
447 * The number of Bytes to be unmapped beginning with the lba.
449 transfer_len = blk_rq_bytes(rq);
450 lba = scsi_get_lba(cmd);
453 intr = ufshcd_readl(hba, REG_INTERRUPT_STATUS);
455 if (is_mcq_enabled(hba)) {
456 struct ufs_hw_queue *hwq = ufshcd_mcq_req_to_hwq(hba, rq);
460 doorbell = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
462 trace_ufshcd_command(cmd->device, str_t, tag, doorbell, hwq_id,
463 transfer_len, intr, lba, opcode, group_id);
466 static void ufshcd_print_clk_freqs(struct ufs_hba *hba)
468 struct ufs_clk_info *clki;
469 struct list_head *head = &hba->clk_list_head;
471 if (list_empty(head))
474 list_for_each_entry(clki, head, list) {
475 if (!IS_ERR_OR_NULL(clki->clk) && clki->min_freq &&
477 dev_err(hba->dev, "clk: %s, rate: %u\n",
478 clki->name, clki->curr_freq);
482 static void ufshcd_print_evt(struct ufs_hba *hba, u32 id,
483 const char *err_name)
487 const struct ufs_event_hist *e;
489 if (id >= UFS_EVT_CNT)
492 e = &hba->ufs_stats.event[id];
494 for (i = 0; i < UFS_EVENT_HIST_LENGTH; i++) {
495 int p = (i + e->pos) % UFS_EVENT_HIST_LENGTH;
497 if (e->tstamp[p] == 0)
499 dev_err(hba->dev, "%s[%d] = 0x%x at %lld us\n", err_name, p,
500 e->val[p], div_u64(e->tstamp[p], 1000));
505 dev_err(hba->dev, "No record of %s\n", err_name);
507 dev_err(hba->dev, "%s: total cnt=%llu\n", err_name, e->cnt);
510 static void ufshcd_print_evt_hist(struct ufs_hba *hba)
512 ufshcd_dump_regs(hba, 0, UFSHCI_REG_SPACE_SIZE, "host_regs: ");
514 ufshcd_print_evt(hba, UFS_EVT_PA_ERR, "pa_err");
515 ufshcd_print_evt(hba, UFS_EVT_DL_ERR, "dl_err");
516 ufshcd_print_evt(hba, UFS_EVT_NL_ERR, "nl_err");
517 ufshcd_print_evt(hba, UFS_EVT_TL_ERR, "tl_err");
518 ufshcd_print_evt(hba, UFS_EVT_DME_ERR, "dme_err");
519 ufshcd_print_evt(hba, UFS_EVT_AUTO_HIBERN8_ERR,
521 ufshcd_print_evt(hba, UFS_EVT_FATAL_ERR, "fatal_err");
522 ufshcd_print_evt(hba, UFS_EVT_LINK_STARTUP_FAIL,
523 "link_startup_fail");
524 ufshcd_print_evt(hba, UFS_EVT_RESUME_ERR, "resume_fail");
525 ufshcd_print_evt(hba, UFS_EVT_SUSPEND_ERR,
527 ufshcd_print_evt(hba, UFS_EVT_WL_RES_ERR, "wlun resume_fail");
528 ufshcd_print_evt(hba, UFS_EVT_WL_SUSP_ERR,
529 "wlun suspend_fail");
530 ufshcd_print_evt(hba, UFS_EVT_DEV_RESET, "dev_reset");
531 ufshcd_print_evt(hba, UFS_EVT_HOST_RESET, "host_reset");
532 ufshcd_print_evt(hba, UFS_EVT_ABORT, "task_abort");
534 ufshcd_vops_dbg_register_dump(hba);
538 void ufshcd_print_tr(struct ufs_hba *hba, int tag, bool pr_prdt)
540 const struct ufshcd_lrb *lrbp;
543 lrbp = &hba->lrb[tag];
545 dev_err(hba->dev, "UPIU[%d] - issue time %lld us\n",
546 tag, div_u64(lrbp->issue_time_stamp_local_clock, 1000));
547 dev_err(hba->dev, "UPIU[%d] - complete time %lld us\n",
548 tag, div_u64(lrbp->compl_time_stamp_local_clock, 1000));
550 "UPIU[%d] - Transfer Request Descriptor phys@0x%llx\n",
551 tag, (u64)lrbp->utrd_dma_addr);
553 ufshcd_hex_dump("UPIU TRD: ", lrbp->utr_descriptor_ptr,
554 sizeof(struct utp_transfer_req_desc));
555 dev_err(hba->dev, "UPIU[%d] - Request UPIU phys@0x%llx\n", tag,
556 (u64)lrbp->ucd_req_dma_addr);
557 ufshcd_hex_dump("UPIU REQ: ", lrbp->ucd_req_ptr,
558 sizeof(struct utp_upiu_req));
559 dev_err(hba->dev, "UPIU[%d] - Response UPIU phys@0x%llx\n", tag,
560 (u64)lrbp->ucd_rsp_dma_addr);
561 ufshcd_hex_dump("UPIU RSP: ", lrbp->ucd_rsp_ptr,
562 sizeof(struct utp_upiu_rsp));
564 prdt_length = le16_to_cpu(
565 lrbp->utr_descriptor_ptr->prd_table_length);
566 if (hba->quirks & UFSHCD_QUIRK_PRDT_BYTE_GRAN)
567 prdt_length /= ufshcd_sg_entry_size(hba);
570 "UPIU[%d] - PRDT - %d entries phys@0x%llx\n",
572 (u64)lrbp->ucd_prdt_dma_addr);
575 ufshcd_hex_dump("UPIU PRDT: ", lrbp->ucd_prdt_ptr,
576 ufshcd_sg_entry_size(hba) * prdt_length);
579 static bool ufshcd_print_tr_iter(struct request *req, void *priv)
581 struct scsi_device *sdev = req->q->queuedata;
582 struct Scsi_Host *shost = sdev->host;
583 struct ufs_hba *hba = shost_priv(shost);
585 ufshcd_print_tr(hba, req->tag, *(bool *)priv);
591 * ufshcd_print_trs_all - print trs for all started requests.
592 * @hba: per-adapter instance.
593 * @pr_prdt: need to print prdt or not.
595 static void ufshcd_print_trs_all(struct ufs_hba *hba, bool pr_prdt)
597 blk_mq_tagset_busy_iter(&hba->host->tag_set, ufshcd_print_tr_iter, &pr_prdt);
600 static void ufshcd_print_tmrs(struct ufs_hba *hba, unsigned long bitmap)
604 for_each_set_bit(tag, &bitmap, hba->nutmrs) {
605 struct utp_task_req_desc *tmrdp = &hba->utmrdl_base_addr[tag];
607 dev_err(hba->dev, "TM[%d] - Task Management Header\n", tag);
608 ufshcd_hex_dump("", tmrdp, sizeof(*tmrdp));
612 static void ufshcd_print_host_state(struct ufs_hba *hba)
614 const struct scsi_device *sdev_ufs = hba->ufs_device_wlun;
616 dev_err(hba->dev, "UFS Host state=%d\n", hba->ufshcd_state);
617 dev_err(hba->dev, "outstanding reqs=0x%lx tasks=0x%lx\n",
618 hba->outstanding_reqs, hba->outstanding_tasks);
619 dev_err(hba->dev, "saved_err=0x%x, saved_uic_err=0x%x\n",
620 hba->saved_err, hba->saved_uic_err);
621 dev_err(hba->dev, "Device power mode=%d, UIC link state=%d\n",
622 hba->curr_dev_pwr_mode, hba->uic_link_state);
623 dev_err(hba->dev, "PM in progress=%d, sys. suspended=%d\n",
624 hba->pm_op_in_progress, hba->is_sys_suspended);
625 dev_err(hba->dev, "Auto BKOPS=%d, Host self-block=%d\n",
626 hba->auto_bkops_enabled, hba->host->host_self_blocked);
627 dev_err(hba->dev, "Clk gate=%d\n", hba->clk_gating.state);
629 "last_hibern8_exit_tstamp at %lld us, hibern8_exit_cnt=%d\n",
630 div_u64(hba->ufs_stats.last_hibern8_exit_tstamp, 1000),
631 hba->ufs_stats.hibern8_exit_cnt);
632 dev_err(hba->dev, "last intr at %lld us, last intr status=0x%x\n",
633 div_u64(hba->ufs_stats.last_intr_ts, 1000),
634 hba->ufs_stats.last_intr_status);
635 dev_err(hba->dev, "error handling flags=0x%x, req. abort count=%d\n",
636 hba->eh_flags, hba->req_abort_count);
637 dev_err(hba->dev, "hba->ufs_version=0x%x, Host capabilities=0x%x, caps=0x%x\n",
638 hba->ufs_version, hba->capabilities, hba->caps);
639 dev_err(hba->dev, "quirks=0x%x, dev. quirks=0x%x\n", hba->quirks,
642 dev_err(hba->dev, "UFS dev info: %.8s %.16s rev %.4s\n",
643 sdev_ufs->vendor, sdev_ufs->model, sdev_ufs->rev);
645 ufshcd_print_clk_freqs(hba);
649 * ufshcd_print_pwr_info - print power params as saved in hba
651 * @hba: per-adapter instance
653 static void ufshcd_print_pwr_info(struct ufs_hba *hba)
655 static const char * const names[] = {
666 * Using dev_dbg to avoid messages during runtime PM to avoid
667 * never-ending cycles of messages written back to storage by user space
668 * causing runtime resume, causing more messages and so on.
670 dev_dbg(hba->dev, "%s:[RX, TX]: gear=[%d, %d], lane[%d, %d], pwr[%s, %s], rate = %d\n",
672 hba->pwr_info.gear_rx, hba->pwr_info.gear_tx,
673 hba->pwr_info.lane_rx, hba->pwr_info.lane_tx,
674 names[hba->pwr_info.pwr_rx],
675 names[hba->pwr_info.pwr_tx],
676 hba->pwr_info.hs_rate);
679 static void ufshcd_device_reset(struct ufs_hba *hba)
683 err = ufshcd_vops_device_reset(hba);
686 ufshcd_set_ufs_dev_active(hba);
687 if (ufshcd_is_wb_allowed(hba)) {
688 hba->dev_info.wb_enabled = false;
689 hba->dev_info.wb_buf_flush_enabled = false;
691 if (hba->dev_info.rtc_type == UFS_RTC_RELATIVE)
692 hba->dev_info.rtc_time_baseline = 0;
694 if (err != -EOPNOTSUPP)
695 ufshcd_update_evt_hist(hba, UFS_EVT_DEV_RESET, err);
698 void ufshcd_delay_us(unsigned long us, unsigned long tolerance)
706 usleep_range(us, us + tolerance);
708 EXPORT_SYMBOL_GPL(ufshcd_delay_us);
711 * ufshcd_wait_for_register - wait for register value to change
712 * @hba: per-adapter interface
713 * @reg: mmio register offset
714 * @mask: mask to apply to the read register value
715 * @val: value to wait for
716 * @interval_us: polling interval in microseconds
717 * @timeout_ms: timeout in milliseconds
719 * Return: -ETIMEDOUT on error, zero on success.
721 static int ufshcd_wait_for_register(struct ufs_hba *hba, u32 reg, u32 mask,
722 u32 val, unsigned long interval_us,
723 unsigned long timeout_ms)
726 unsigned long timeout = jiffies + msecs_to_jiffies(timeout_ms);
728 /* ignore bits that we don't intend to wait on */
731 while ((ufshcd_readl(hba, reg) & mask) != val) {
732 usleep_range(interval_us, interval_us + 50);
733 if (time_after(jiffies, timeout)) {
734 if ((ufshcd_readl(hba, reg) & mask) != val)
744 * ufshcd_get_intr_mask - Get the interrupt bit mask
745 * @hba: Pointer to adapter instance
747 * Return: interrupt bit mask per version
749 static inline u32 ufshcd_get_intr_mask(struct ufs_hba *hba)
751 if (hba->ufs_version == ufshci_version(1, 0))
752 return INTERRUPT_MASK_ALL_VER_10;
753 if (hba->ufs_version <= ufshci_version(2, 0))
754 return INTERRUPT_MASK_ALL_VER_11;
756 return INTERRUPT_MASK_ALL_VER_21;
760 * ufshcd_get_ufs_version - Get the UFS version supported by the HBA
761 * @hba: Pointer to adapter instance
763 * Return: UFSHCI version supported by the controller
765 static inline u32 ufshcd_get_ufs_version(struct ufs_hba *hba)
769 if (hba->quirks & UFSHCD_QUIRK_BROKEN_UFS_HCI_VERSION)
770 ufshci_ver = ufshcd_vops_get_ufs_hci_version(hba);
772 ufshci_ver = ufshcd_readl(hba, REG_UFS_VERSION);
775 * UFSHCI v1.x uses a different version scheme, in order
776 * to allow the use of comparisons with the ufshci_version
777 * function, we convert it to the same scheme as ufs 2.0+.
779 if (ufshci_ver & 0x00010000)
780 return ufshci_version(1, ufshci_ver & 0x00000100);
786 * ufshcd_is_device_present - Check if any device connected to
787 * the host controller
788 * @hba: pointer to adapter instance
790 * Return: true if device present, false if no device detected
792 static inline bool ufshcd_is_device_present(struct ufs_hba *hba)
794 return ufshcd_readl(hba, REG_CONTROLLER_STATUS) & DEVICE_PRESENT;
798 * ufshcd_get_tr_ocs - Get the UTRD Overall Command Status
799 * @lrbp: pointer to local command reference block
800 * @cqe: pointer to the completion queue entry
802 * This function is used to get the OCS field from UTRD
804 * Return: the OCS field in the UTRD.
806 static enum utp_ocs ufshcd_get_tr_ocs(struct ufshcd_lrb *lrbp,
807 struct cq_entry *cqe)
810 return le32_to_cpu(cqe->status) & MASK_OCS;
812 return lrbp->utr_descriptor_ptr->header.ocs & MASK_OCS;
816 * ufshcd_utrl_clear() - Clear requests from the controller request list.
817 * @hba: per adapter instance
818 * @mask: mask with one bit set for each request to be cleared
820 static inline void ufshcd_utrl_clear(struct ufs_hba *hba, u32 mask)
822 if (hba->quirks & UFSHCI_QUIRK_BROKEN_REQ_LIST_CLR)
825 * From the UFSHCI specification: "UTP Transfer Request List CLear
826 * Register (UTRLCLR): This field is bit significant. Each bit
827 * corresponds to a slot in the UTP Transfer Request List, where bit 0
828 * corresponds to request slot 0. A bit in this field is set to ‘0’
829 * by host software to indicate to the host controller that a transfer
830 * request slot is cleared. The host controller
831 * shall free up any resources associated to the request slot
832 * immediately, and shall set the associated bit in UTRLDBR to ‘0’. The
833 * host software indicates no change to request slots by setting the
834 * associated bits in this field to ‘1’. Bits in this field shall only
835 * be set ‘1’ or ‘0’ by host software when UTRLRSR is set to ‘1’."
837 ufshcd_writel(hba, ~mask, REG_UTP_TRANSFER_REQ_LIST_CLEAR);
841 * ufshcd_utmrl_clear - Clear a bit in UTMRLCLR register
842 * @hba: per adapter instance
843 * @pos: position of the bit to be cleared
845 static inline void ufshcd_utmrl_clear(struct ufs_hba *hba, u32 pos)
847 if (hba->quirks & UFSHCI_QUIRK_BROKEN_REQ_LIST_CLR)
848 ufshcd_writel(hba, (1 << pos), REG_UTP_TASK_REQ_LIST_CLEAR);
850 ufshcd_writel(hba, ~(1 << pos), REG_UTP_TASK_REQ_LIST_CLEAR);
854 * ufshcd_get_lists_status - Check UCRDY, UTRLRDY and UTMRLRDY
855 * @reg: Register value of host controller status
857 * Return: 0 on success; a positive value if failed.
859 static inline int ufshcd_get_lists_status(u32 reg)
861 return !((reg & UFSHCD_STATUS_READY) == UFSHCD_STATUS_READY);
865 * ufshcd_get_uic_cmd_result - Get the UIC command result
866 * @hba: Pointer to adapter instance
868 * This function gets the result of UIC command completion
870 * Return: 0 on success; non-zero value on error.
872 static inline int ufshcd_get_uic_cmd_result(struct ufs_hba *hba)
874 return ufshcd_readl(hba, REG_UIC_COMMAND_ARG_2) &
875 MASK_UIC_COMMAND_RESULT;
879 * ufshcd_get_dme_attr_val - Get the value of attribute returned by UIC command
880 * @hba: Pointer to adapter instance
882 * This function gets UIC command argument3
884 * Return: 0 on success; non-zero value on error.
886 static inline u32 ufshcd_get_dme_attr_val(struct ufs_hba *hba)
888 return ufshcd_readl(hba, REG_UIC_COMMAND_ARG_3);
892 * ufshcd_get_req_rsp - returns the TR response transaction type
893 * @ucd_rsp_ptr: pointer to response UPIU
897 static inline enum upiu_response_transaction
898 ufshcd_get_req_rsp(struct utp_upiu_rsp *ucd_rsp_ptr)
900 return ucd_rsp_ptr->header.transaction_code;
904 * ufshcd_is_exception_event - Check if the device raised an exception event
905 * @ucd_rsp_ptr: pointer to response UPIU
907 * The function checks if the device raised an exception event indicated in
908 * the Device Information field of response UPIU.
910 * Return: true if exception is raised, false otherwise.
912 static inline bool ufshcd_is_exception_event(struct utp_upiu_rsp *ucd_rsp_ptr)
914 return ucd_rsp_ptr->header.device_information & 1;
918 * ufshcd_reset_intr_aggr - Reset interrupt aggregation values.
919 * @hba: per adapter instance
922 ufshcd_reset_intr_aggr(struct ufs_hba *hba)
924 ufshcd_writel(hba, INT_AGGR_ENABLE |
925 INT_AGGR_COUNTER_AND_TIMER_RESET,
926 REG_UTP_TRANSFER_REQ_INT_AGG_CONTROL);
930 * ufshcd_config_intr_aggr - Configure interrupt aggregation values.
931 * @hba: per adapter instance
932 * @cnt: Interrupt aggregation counter threshold
933 * @tmout: Interrupt aggregation timeout value
936 ufshcd_config_intr_aggr(struct ufs_hba *hba, u8 cnt, u8 tmout)
938 ufshcd_writel(hba, INT_AGGR_ENABLE | INT_AGGR_PARAM_WRITE |
939 INT_AGGR_COUNTER_THLD_VAL(cnt) |
940 INT_AGGR_TIMEOUT_VAL(tmout),
941 REG_UTP_TRANSFER_REQ_INT_AGG_CONTROL);
945 * ufshcd_disable_intr_aggr - Disables interrupt aggregation.
946 * @hba: per adapter instance
948 static inline void ufshcd_disable_intr_aggr(struct ufs_hba *hba)
950 ufshcd_writel(hba, 0, REG_UTP_TRANSFER_REQ_INT_AGG_CONTROL);
954 * ufshcd_enable_run_stop_reg - Enable run-stop registers,
955 * When run-stop registers are set to 1, it indicates the
956 * host controller that it can process the requests
957 * @hba: per adapter instance
959 static void ufshcd_enable_run_stop_reg(struct ufs_hba *hba)
961 ufshcd_writel(hba, UTP_TASK_REQ_LIST_RUN_STOP_BIT,
962 REG_UTP_TASK_REQ_LIST_RUN_STOP);
963 ufshcd_writel(hba, UTP_TRANSFER_REQ_LIST_RUN_STOP_BIT,
964 REG_UTP_TRANSFER_REQ_LIST_RUN_STOP);
968 * ufshcd_hba_start - Start controller initialization sequence
969 * @hba: per adapter instance
971 static inline void ufshcd_hba_start(struct ufs_hba *hba)
973 u32 val = CONTROLLER_ENABLE;
975 if (ufshcd_crypto_enable(hba))
976 val |= CRYPTO_GENERAL_ENABLE;
978 ufshcd_writel(hba, val, REG_CONTROLLER_ENABLE);
982 * ufshcd_is_hba_active - Get controller state
983 * @hba: per adapter instance
985 * Return: true if and only if the controller is active.
987 bool ufshcd_is_hba_active(struct ufs_hba *hba)
989 return ufshcd_readl(hba, REG_CONTROLLER_ENABLE) & CONTROLLER_ENABLE;
991 EXPORT_SYMBOL_GPL(ufshcd_is_hba_active);
993 u32 ufshcd_get_local_unipro_ver(struct ufs_hba *hba)
995 /* HCI version 1.0 and 1.1 supports UniPro 1.41 */
996 if (hba->ufs_version <= ufshci_version(1, 1))
997 return UFS_UNIPRO_VER_1_41;
999 return UFS_UNIPRO_VER_1_6;
1001 EXPORT_SYMBOL(ufshcd_get_local_unipro_ver);
1003 static bool ufshcd_is_unipro_pa_params_tuning_req(struct ufs_hba *hba)
1006 * If both host and device support UniPro ver1.6 or later, PA layer
1007 * parameters tuning happens during link startup itself.
1009 * We can manually tune PA layer parameters if either host or device
1010 * doesn't support UniPro ver 1.6 or later. But to keep manual tuning
1011 * logic simple, we will only do manual tuning if local unipro version
1012 * doesn't support ver1.6 or later.
1014 return ufshcd_get_local_unipro_ver(hba) < UFS_UNIPRO_VER_1_6;
1018 * ufshcd_pm_qos_init - initialize PM QoS request
1019 * @hba: per adapter instance
1021 void ufshcd_pm_qos_init(struct ufs_hba *hba)
1024 if (hba->pm_qos_enabled)
1027 cpu_latency_qos_add_request(&hba->pm_qos_req, PM_QOS_DEFAULT_VALUE);
1029 if (cpu_latency_qos_request_active(&hba->pm_qos_req))
1030 hba->pm_qos_enabled = true;
1034 * ufshcd_pm_qos_exit - remove request from PM QoS
1035 * @hba: per adapter instance
1037 void ufshcd_pm_qos_exit(struct ufs_hba *hba)
1039 if (!hba->pm_qos_enabled)
1042 cpu_latency_qos_remove_request(&hba->pm_qos_req);
1043 hba->pm_qos_enabled = false;
1047 * ufshcd_pm_qos_update - update PM QoS request
1048 * @hba: per adapter instance
1049 * @on: If True, vote for perf PM QoS mode otherwise power save mode
1051 static void ufshcd_pm_qos_update(struct ufs_hba *hba, bool on)
1053 if (!hba->pm_qos_enabled)
1056 cpu_latency_qos_update_request(&hba->pm_qos_req, on ? 0 : PM_QOS_DEFAULT_VALUE);
1060 * ufshcd_set_clk_freq - set UFS controller clock frequencies
1061 * @hba: per adapter instance
1062 * @scale_up: If True, set max possible frequency othewise set low frequency
1064 * Return: 0 if successful; < 0 upon failure.
1066 static int ufshcd_set_clk_freq(struct ufs_hba *hba, bool scale_up)
1069 struct ufs_clk_info *clki;
1070 struct list_head *head = &hba->clk_list_head;
1072 if (list_empty(head))
1075 list_for_each_entry(clki, head, list) {
1076 if (!IS_ERR_OR_NULL(clki->clk)) {
1077 if (scale_up && clki->max_freq) {
1078 if (clki->curr_freq == clki->max_freq)
1081 ret = clk_set_rate(clki->clk, clki->max_freq);
1083 dev_err(hba->dev, "%s: %s clk set rate(%dHz) failed, %d\n",
1084 __func__, clki->name,
1085 clki->max_freq, ret);
1088 trace_ufshcd_clk_scaling(dev_name(hba->dev),
1089 "scaled up", clki->name,
1093 clki->curr_freq = clki->max_freq;
1095 } else if (!scale_up && clki->min_freq) {
1096 if (clki->curr_freq == clki->min_freq)
1099 ret = clk_set_rate(clki->clk, clki->min_freq);
1101 dev_err(hba->dev, "%s: %s clk set rate(%dHz) failed, %d\n",
1102 __func__, clki->name,
1103 clki->min_freq, ret);
1106 trace_ufshcd_clk_scaling(dev_name(hba->dev),
1107 "scaled down", clki->name,
1110 clki->curr_freq = clki->min_freq;
1113 dev_dbg(hba->dev, "%s: clk: %s, rate: %lu\n", __func__,
1114 clki->name, clk_get_rate(clki->clk));
1121 int ufshcd_opp_config_clks(struct device *dev, struct opp_table *opp_table,
1122 struct dev_pm_opp *opp, void *data,
1125 struct ufs_hba *hba = dev_get_drvdata(dev);
1126 struct list_head *head = &hba->clk_list_head;
1127 struct ufs_clk_info *clki;
1132 list_for_each_entry(clki, head, list) {
1133 if (!IS_ERR_OR_NULL(clki->clk)) {
1134 freq = dev_pm_opp_get_freq_indexed(opp, idx++);
1136 /* Do not set rate for clocks having frequency as 0 */
1140 ret = clk_set_rate(clki->clk, freq);
1142 dev_err(dev, "%s: %s clk set rate(%ldHz) failed, %d\n",
1143 __func__, clki->name, freq, ret);
1147 trace_ufshcd_clk_scaling(dev_name(dev),
1148 (scaling_down ? "scaled down" : "scaled up"),
1149 clki->name, hba->clk_scaling.target_freq, freq);
1155 EXPORT_SYMBOL_GPL(ufshcd_opp_config_clks);
1157 static int ufshcd_opp_set_rate(struct ufs_hba *hba, unsigned long freq)
1159 struct dev_pm_opp *opp;
1162 opp = dev_pm_opp_find_freq_floor_indexed(hba->dev,
1165 return PTR_ERR(opp);
1167 ret = dev_pm_opp_set_opp(hba->dev, opp);
1168 dev_pm_opp_put(opp);
1174 * ufshcd_scale_clks - scale up or scale down UFS controller clocks
1175 * @hba: per adapter instance
1176 * @freq: frequency to scale
1177 * @scale_up: True if scaling up and false if scaling down
1179 * Return: 0 if successful; < 0 upon failure.
1181 static int ufshcd_scale_clks(struct ufs_hba *hba, unsigned long freq,
1185 ktime_t start = ktime_get();
1187 ret = ufshcd_vops_clk_scale_notify(hba, scale_up, PRE_CHANGE);
1191 if (hba->use_pm_opp)
1192 ret = ufshcd_opp_set_rate(hba, freq);
1194 ret = ufshcd_set_clk_freq(hba, scale_up);
1198 ret = ufshcd_vops_clk_scale_notify(hba, scale_up, POST_CHANGE);
1200 if (hba->use_pm_opp)
1201 ufshcd_opp_set_rate(hba,
1202 hba->devfreq->previous_freq);
1204 ufshcd_set_clk_freq(hba, !scale_up);
1208 ufshcd_pm_qos_update(hba, scale_up);
1211 trace_ufshcd_profile_clk_scaling(dev_name(hba->dev),
1212 (scale_up ? "up" : "down"),
1213 ktime_to_us(ktime_sub(ktime_get(), start)), ret);
1218 * ufshcd_is_devfreq_scaling_required - check if scaling is required or not
1219 * @hba: per adapter instance
1220 * @freq: frequency to scale
1221 * @scale_up: True if scaling up and false if scaling down
1223 * Return: true if scaling is required, false otherwise.
1225 static bool ufshcd_is_devfreq_scaling_required(struct ufs_hba *hba,
1226 unsigned long freq, bool scale_up)
1228 struct ufs_clk_info *clki;
1229 struct list_head *head = &hba->clk_list_head;
1231 if (list_empty(head))
1234 if (hba->use_pm_opp)
1235 return freq != hba->clk_scaling.target_freq;
1237 list_for_each_entry(clki, head, list) {
1238 if (!IS_ERR_OR_NULL(clki->clk)) {
1239 if (scale_up && clki->max_freq) {
1240 if (clki->curr_freq == clki->max_freq)
1243 } else if (!scale_up && clki->min_freq) {
1244 if (clki->curr_freq == clki->min_freq)
1255 * Determine the number of pending commands by counting the bits in the SCSI
1256 * device budget maps. This approach has been selected because a bit is set in
1257 * the budget map before scsi_host_queue_ready() checks the host_self_blocked
1258 * flag. The host_self_blocked flag can be modified by calling
1259 * scsi_block_requests() or scsi_unblock_requests().
1261 static u32 ufshcd_pending_cmds(struct ufs_hba *hba)
1263 const struct scsi_device *sdev;
1266 lockdep_assert_held(hba->host->host_lock);
1267 __shost_for_each_device(sdev, hba->host)
1268 pending += sbitmap_weight(&sdev->budget_map);
1274 * Wait until all pending SCSI commands and TMFs have finished or the timeout
1277 * Return: 0 upon success; -EBUSY upon timeout.
1279 static int ufshcd_wait_for_doorbell_clr(struct ufs_hba *hba,
1280 u64 wait_timeout_us)
1282 unsigned long flags;
1286 bool timeout = false, do_last_check = false;
1290 spin_lock_irqsave(hba->host->host_lock, flags);
1292 * Wait for all the outstanding tasks/transfer requests.
1293 * Verify by checking the doorbell registers are clear.
1295 start = ktime_get();
1297 if (hba->ufshcd_state != UFSHCD_STATE_OPERATIONAL) {
1302 tm_doorbell = ufshcd_readl(hba, REG_UTP_TASK_REQ_DOOR_BELL);
1303 tr_pending = ufshcd_pending_cmds(hba);
1304 if (!tm_doorbell && !tr_pending) {
1307 } else if (do_last_check) {
1311 spin_unlock_irqrestore(hba->host->host_lock, flags);
1312 io_schedule_timeout(msecs_to_jiffies(20));
1313 if (ktime_to_us(ktime_sub(ktime_get(), start)) >
1317 * We might have scheduled out for long time so make
1318 * sure to check if doorbells are cleared by this time
1321 do_last_check = true;
1323 spin_lock_irqsave(hba->host->host_lock, flags);
1324 } while (tm_doorbell || tr_pending);
1328 "%s: timedout waiting for doorbell to clear (tm=0x%x, tr=0x%x)\n",
1329 __func__, tm_doorbell, tr_pending);
1333 spin_unlock_irqrestore(hba->host->host_lock, flags);
1334 ufshcd_release(hba);
1339 * ufshcd_scale_gear - scale up/down UFS gear
1340 * @hba: per adapter instance
1341 * @scale_up: True for scaling up gear and false for scaling down
1343 * Return: 0 for success; -EBUSY if scaling can't happen at this time;
1344 * non-zero for any other errors.
1346 static int ufshcd_scale_gear(struct ufs_hba *hba, bool scale_up)
1349 struct ufs_pa_layer_attr new_pwr_info;
1352 memcpy(&new_pwr_info, &hba->clk_scaling.saved_pwr_info,
1353 sizeof(struct ufs_pa_layer_attr));
1355 memcpy(&new_pwr_info, &hba->pwr_info,
1356 sizeof(struct ufs_pa_layer_attr));
1358 if (hba->pwr_info.gear_tx > hba->clk_scaling.min_gear ||
1359 hba->pwr_info.gear_rx > hba->clk_scaling.min_gear) {
1360 /* save the current power mode */
1361 memcpy(&hba->clk_scaling.saved_pwr_info,
1363 sizeof(struct ufs_pa_layer_attr));
1365 /* scale down gear */
1366 new_pwr_info.gear_tx = hba->clk_scaling.min_gear;
1367 new_pwr_info.gear_rx = hba->clk_scaling.min_gear;
1371 /* check if the power mode needs to be changed or not? */
1372 ret = ufshcd_config_pwr_mode(hba, &new_pwr_info);
1374 dev_err(hba->dev, "%s: failed err %d, old gear: (tx %d rx %d), new gear: (tx %d rx %d)",
1376 hba->pwr_info.gear_tx, hba->pwr_info.gear_rx,
1377 new_pwr_info.gear_tx, new_pwr_info.gear_rx);
1383 * Wait until all pending SCSI commands and TMFs have finished or the timeout
1386 * Return: 0 upon success; -EBUSY upon timeout.
1388 static int ufshcd_clock_scaling_prepare(struct ufs_hba *hba, u64 timeout_us)
1392 * make sure that there are no outstanding requests when
1393 * clock scaling is in progress
1395 ufshcd_scsi_block_requests(hba);
1396 mutex_lock(&hba->wb_mutex);
1397 down_write(&hba->clk_scaling_lock);
1399 if (!hba->clk_scaling.is_allowed ||
1400 ufshcd_wait_for_doorbell_clr(hba, timeout_us)) {
1402 up_write(&hba->clk_scaling_lock);
1403 mutex_unlock(&hba->wb_mutex);
1404 ufshcd_scsi_unblock_requests(hba);
1408 /* let's not get into low power until clock scaling is completed */
1415 static void ufshcd_clock_scaling_unprepare(struct ufs_hba *hba, int err, bool scale_up)
1417 up_write(&hba->clk_scaling_lock);
1419 /* Enable Write Booster if we have scaled up else disable it */
1420 if (ufshcd_enable_wb_if_scaling_up(hba) && !err)
1421 ufshcd_wb_toggle(hba, scale_up);
1423 mutex_unlock(&hba->wb_mutex);
1425 ufshcd_scsi_unblock_requests(hba);
1426 ufshcd_release(hba);
1430 * ufshcd_devfreq_scale - scale up/down UFS clocks and gear
1431 * @hba: per adapter instance
1432 * @freq: frequency to scale
1433 * @scale_up: True for scaling up and false for scalin down
1435 * Return: 0 for success; -EBUSY if scaling can't happen at this time; non-zero
1436 * for any other errors.
1438 static int ufshcd_devfreq_scale(struct ufs_hba *hba, unsigned long freq,
1443 ret = ufshcd_clock_scaling_prepare(hba, 1 * USEC_PER_SEC);
1447 /* scale down the gear before scaling down clocks */
1449 ret = ufshcd_scale_gear(hba, false);
1454 ret = ufshcd_scale_clks(hba, freq, scale_up);
1457 ufshcd_scale_gear(hba, true);
1461 /* scale up the gear after scaling up clocks */
1463 ret = ufshcd_scale_gear(hba, true);
1465 ufshcd_scale_clks(hba, hba->devfreq->previous_freq,
1472 ufshcd_clock_scaling_unprepare(hba, ret, scale_up);
1476 static void ufshcd_clk_scaling_suspend_work(struct work_struct *work)
1478 struct ufs_hba *hba = container_of(work, struct ufs_hba,
1479 clk_scaling.suspend_work);
1480 unsigned long irq_flags;
1482 spin_lock_irqsave(hba->host->host_lock, irq_flags);
1483 if (hba->clk_scaling.active_reqs || hba->clk_scaling.is_suspended) {
1484 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1487 hba->clk_scaling.is_suspended = true;
1488 hba->clk_scaling.window_start_t = 0;
1489 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1491 devfreq_suspend_device(hba->devfreq);
1494 static void ufshcd_clk_scaling_resume_work(struct work_struct *work)
1496 struct ufs_hba *hba = container_of(work, struct ufs_hba,
1497 clk_scaling.resume_work);
1498 unsigned long irq_flags;
1500 spin_lock_irqsave(hba->host->host_lock, irq_flags);
1501 if (!hba->clk_scaling.is_suspended) {
1502 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1505 hba->clk_scaling.is_suspended = false;
1506 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1508 devfreq_resume_device(hba->devfreq);
1511 static int ufshcd_devfreq_target(struct device *dev,
1512 unsigned long *freq, u32 flags)
1515 struct ufs_hba *hba = dev_get_drvdata(dev);
1517 bool scale_up = false, sched_clk_scaling_suspend_work = false;
1518 struct list_head *clk_list = &hba->clk_list_head;
1519 struct ufs_clk_info *clki;
1520 unsigned long irq_flags;
1522 if (!ufshcd_is_clkscaling_supported(hba))
1525 if (hba->use_pm_opp) {
1526 struct dev_pm_opp *opp;
1528 /* Get the recommended frequency from OPP framework */
1529 opp = devfreq_recommended_opp(dev, freq, flags);
1531 return PTR_ERR(opp);
1533 dev_pm_opp_put(opp);
1535 /* Override with the closest supported frequency */
1536 clki = list_first_entry(&hba->clk_list_head, struct ufs_clk_info,
1538 *freq = (unsigned long) clk_round_rate(clki->clk, *freq);
1541 spin_lock_irqsave(hba->host->host_lock, irq_flags);
1542 if (ufshcd_eh_in_progress(hba)) {
1543 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1547 /* Skip scaling clock when clock scaling is suspended */
1548 if (hba->clk_scaling.is_suspended) {
1549 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1550 dev_warn(hba->dev, "clock scaling is suspended, skip");
1554 if (!hba->clk_scaling.active_reqs)
1555 sched_clk_scaling_suspend_work = true;
1557 if (list_empty(clk_list)) {
1558 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1562 /* Decide based on the target or rounded-off frequency and update */
1563 if (hba->use_pm_opp)
1564 scale_up = *freq > hba->clk_scaling.target_freq;
1566 scale_up = *freq == clki->max_freq;
1568 if (!hba->use_pm_opp && !scale_up)
1569 *freq = clki->min_freq;
1571 /* Update the frequency */
1572 if (!ufshcd_is_devfreq_scaling_required(hba, *freq, scale_up)) {
1573 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1575 goto out; /* no state change required */
1577 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1579 start = ktime_get();
1580 ret = ufshcd_devfreq_scale(hba, *freq, scale_up);
1582 hba->clk_scaling.target_freq = *freq;
1584 trace_ufshcd_profile_clk_scaling(dev_name(hba->dev),
1585 (scale_up ? "up" : "down"),
1586 ktime_to_us(ktime_sub(ktime_get(), start)), ret);
1589 if (sched_clk_scaling_suspend_work && !scale_up)
1590 queue_work(hba->clk_scaling.workq,
1591 &hba->clk_scaling.suspend_work);
1596 static int ufshcd_devfreq_get_dev_status(struct device *dev,
1597 struct devfreq_dev_status *stat)
1599 struct ufs_hba *hba = dev_get_drvdata(dev);
1600 struct ufs_clk_scaling *scaling = &hba->clk_scaling;
1601 unsigned long flags;
1604 if (!ufshcd_is_clkscaling_supported(hba))
1607 memset(stat, 0, sizeof(*stat));
1609 spin_lock_irqsave(hba->host->host_lock, flags);
1610 curr_t = ktime_get();
1611 if (!scaling->window_start_t)
1615 * If current frequency is 0, then the ondemand governor considers
1616 * there's no initial frequency set. And it always requests to set
1617 * to max. frequency.
1619 if (hba->use_pm_opp) {
1620 stat->current_frequency = hba->clk_scaling.target_freq;
1622 struct list_head *clk_list = &hba->clk_list_head;
1623 struct ufs_clk_info *clki;
1625 clki = list_first_entry(clk_list, struct ufs_clk_info, list);
1626 stat->current_frequency = clki->curr_freq;
1629 if (scaling->is_busy_started)
1630 scaling->tot_busy_t += ktime_us_delta(curr_t,
1631 scaling->busy_start_t);
1632 stat->total_time = ktime_us_delta(curr_t, scaling->window_start_t);
1633 stat->busy_time = scaling->tot_busy_t;
1635 scaling->window_start_t = curr_t;
1636 scaling->tot_busy_t = 0;
1638 if (scaling->active_reqs) {
1639 scaling->busy_start_t = curr_t;
1640 scaling->is_busy_started = true;
1642 scaling->busy_start_t = 0;
1643 scaling->is_busy_started = false;
1645 spin_unlock_irqrestore(hba->host->host_lock, flags);
1649 static int ufshcd_devfreq_init(struct ufs_hba *hba)
1651 struct list_head *clk_list = &hba->clk_list_head;
1652 struct ufs_clk_info *clki;
1653 struct devfreq *devfreq;
1656 /* Skip devfreq if we don't have any clocks in the list */
1657 if (list_empty(clk_list))
1660 if (!hba->use_pm_opp) {
1661 clki = list_first_entry(clk_list, struct ufs_clk_info, list);
1662 dev_pm_opp_add(hba->dev, clki->min_freq, 0);
1663 dev_pm_opp_add(hba->dev, clki->max_freq, 0);
1666 ufshcd_vops_config_scaling_param(hba, &hba->vps->devfreq_profile,
1667 &hba->vps->ondemand_data);
1668 devfreq = devfreq_add_device(hba->dev,
1669 &hba->vps->devfreq_profile,
1670 DEVFREQ_GOV_SIMPLE_ONDEMAND,
1671 &hba->vps->ondemand_data);
1672 if (IS_ERR(devfreq)) {
1673 ret = PTR_ERR(devfreq);
1674 dev_err(hba->dev, "Unable to register with devfreq %d\n", ret);
1676 if (!hba->use_pm_opp) {
1677 dev_pm_opp_remove(hba->dev, clki->min_freq);
1678 dev_pm_opp_remove(hba->dev, clki->max_freq);
1683 hba->devfreq = devfreq;
1688 static void ufshcd_devfreq_remove(struct ufs_hba *hba)
1690 struct list_head *clk_list = &hba->clk_list_head;
1695 devfreq_remove_device(hba->devfreq);
1696 hba->devfreq = NULL;
1698 if (!hba->use_pm_opp) {
1699 struct ufs_clk_info *clki;
1701 clki = list_first_entry(clk_list, struct ufs_clk_info, list);
1702 dev_pm_opp_remove(hba->dev, clki->min_freq);
1703 dev_pm_opp_remove(hba->dev, clki->max_freq);
1707 static void ufshcd_suspend_clkscaling(struct ufs_hba *hba)
1709 unsigned long flags;
1710 bool suspend = false;
1712 cancel_work_sync(&hba->clk_scaling.suspend_work);
1713 cancel_work_sync(&hba->clk_scaling.resume_work);
1715 spin_lock_irqsave(hba->host->host_lock, flags);
1716 if (!hba->clk_scaling.is_suspended) {
1718 hba->clk_scaling.is_suspended = true;
1719 hba->clk_scaling.window_start_t = 0;
1721 spin_unlock_irqrestore(hba->host->host_lock, flags);
1724 devfreq_suspend_device(hba->devfreq);
1727 static void ufshcd_resume_clkscaling(struct ufs_hba *hba)
1729 unsigned long flags;
1730 bool resume = false;
1732 spin_lock_irqsave(hba->host->host_lock, flags);
1733 if (hba->clk_scaling.is_suspended) {
1735 hba->clk_scaling.is_suspended = false;
1737 spin_unlock_irqrestore(hba->host->host_lock, flags);
1740 devfreq_resume_device(hba->devfreq);
1743 static ssize_t ufshcd_clkscale_enable_show(struct device *dev,
1744 struct device_attribute *attr, char *buf)
1746 struct ufs_hba *hba = dev_get_drvdata(dev);
1748 return sysfs_emit(buf, "%d\n", hba->clk_scaling.is_enabled);
1751 static ssize_t ufshcd_clkscale_enable_store(struct device *dev,
1752 struct device_attribute *attr, const char *buf, size_t count)
1754 struct ufs_hba *hba = dev_get_drvdata(dev);
1758 if (kstrtou32(buf, 0, &value))
1761 down(&hba->host_sem);
1762 if (!ufshcd_is_user_access_allowed(hba)) {
1768 if (value == hba->clk_scaling.is_enabled)
1771 ufshcd_rpm_get_sync(hba);
1774 hba->clk_scaling.is_enabled = value;
1777 ufshcd_resume_clkscaling(hba);
1779 ufshcd_suspend_clkscaling(hba);
1780 err = ufshcd_devfreq_scale(hba, ULONG_MAX, true);
1782 dev_err(hba->dev, "%s: failed to scale clocks up %d\n",
1786 ufshcd_release(hba);
1787 ufshcd_rpm_put_sync(hba);
1790 return err ? err : count;
1793 static void ufshcd_init_clk_scaling_sysfs(struct ufs_hba *hba)
1795 hba->clk_scaling.enable_attr.show = ufshcd_clkscale_enable_show;
1796 hba->clk_scaling.enable_attr.store = ufshcd_clkscale_enable_store;
1797 sysfs_attr_init(&hba->clk_scaling.enable_attr.attr);
1798 hba->clk_scaling.enable_attr.attr.name = "clkscale_enable";
1799 hba->clk_scaling.enable_attr.attr.mode = 0644;
1800 if (device_create_file(hba->dev, &hba->clk_scaling.enable_attr))
1801 dev_err(hba->dev, "Failed to create sysfs for clkscale_enable\n");
1804 static void ufshcd_remove_clk_scaling_sysfs(struct ufs_hba *hba)
1806 if (hba->clk_scaling.enable_attr.attr.name)
1807 device_remove_file(hba->dev, &hba->clk_scaling.enable_attr);
1810 static void ufshcd_init_clk_scaling(struct ufs_hba *hba)
1812 char wq_name[sizeof("ufs_clkscaling_00")];
1814 if (!ufshcd_is_clkscaling_supported(hba))
1817 if (!hba->clk_scaling.min_gear)
1818 hba->clk_scaling.min_gear = UFS_HS_G1;
1820 INIT_WORK(&hba->clk_scaling.suspend_work,
1821 ufshcd_clk_scaling_suspend_work);
1822 INIT_WORK(&hba->clk_scaling.resume_work,
1823 ufshcd_clk_scaling_resume_work);
1825 snprintf(wq_name, sizeof(wq_name), "ufs_clkscaling_%d",
1826 hba->host->host_no);
1827 hba->clk_scaling.workq = create_singlethread_workqueue(wq_name);
1829 hba->clk_scaling.is_initialized = true;
1832 static void ufshcd_exit_clk_scaling(struct ufs_hba *hba)
1834 if (!hba->clk_scaling.is_initialized)
1837 ufshcd_remove_clk_scaling_sysfs(hba);
1838 destroy_workqueue(hba->clk_scaling.workq);
1839 ufshcd_devfreq_remove(hba);
1840 hba->clk_scaling.is_initialized = false;
1843 static void ufshcd_ungate_work(struct work_struct *work)
1846 unsigned long flags;
1847 struct ufs_hba *hba = container_of(work, struct ufs_hba,
1848 clk_gating.ungate_work);
1850 cancel_delayed_work_sync(&hba->clk_gating.gate_work);
1852 spin_lock_irqsave(hba->host->host_lock, flags);
1853 if (hba->clk_gating.state == CLKS_ON) {
1854 spin_unlock_irqrestore(hba->host->host_lock, flags);
1858 spin_unlock_irqrestore(hba->host->host_lock, flags);
1859 ufshcd_hba_vreg_set_hpm(hba);
1860 ufshcd_setup_clocks(hba, true);
1862 ufshcd_enable_irq(hba);
1864 /* Exit from hibern8 */
1865 if (ufshcd_can_hibern8_during_gating(hba)) {
1866 /* Prevent gating in this path */
1867 hba->clk_gating.is_suspended = true;
1868 if (ufshcd_is_link_hibern8(hba)) {
1869 ret = ufshcd_uic_hibern8_exit(hba);
1871 dev_err(hba->dev, "%s: hibern8 exit failed %d\n",
1874 ufshcd_set_link_active(hba);
1876 hba->clk_gating.is_suspended = false;
1881 * ufshcd_hold - Enable clocks that were gated earlier due to ufshcd_release.
1882 * Also, exit from hibern8 mode and set the link as active.
1883 * @hba: per adapter instance
1885 void ufshcd_hold(struct ufs_hba *hba)
1888 unsigned long flags;
1890 if (!ufshcd_is_clkgating_allowed(hba) ||
1891 !hba->clk_gating.is_initialized)
1893 spin_lock_irqsave(hba->host->host_lock, flags);
1894 hba->clk_gating.active_reqs++;
1897 switch (hba->clk_gating.state) {
1900 * Wait for the ungate work to complete if in progress.
1901 * Though the clocks may be in ON state, the link could
1902 * still be in hibner8 state if hibern8 is allowed
1903 * during clock gating.
1904 * Make sure we exit hibern8 state also in addition to
1907 if (ufshcd_can_hibern8_during_gating(hba) &&
1908 ufshcd_is_link_hibern8(hba)) {
1909 spin_unlock_irqrestore(hba->host->host_lock, flags);
1910 flush_result = flush_work(&hba->clk_gating.ungate_work);
1911 if (hba->clk_gating.is_suspended && !flush_result)
1913 spin_lock_irqsave(hba->host->host_lock, flags);
1918 if (cancel_delayed_work(&hba->clk_gating.gate_work)) {
1919 hba->clk_gating.state = CLKS_ON;
1920 trace_ufshcd_clk_gating(dev_name(hba->dev),
1921 hba->clk_gating.state);
1925 * If we are here, it means gating work is either done or
1926 * currently running. Hence, fall through to cancel gating
1927 * work and to enable clocks.
1931 hba->clk_gating.state = REQ_CLKS_ON;
1932 trace_ufshcd_clk_gating(dev_name(hba->dev),
1933 hba->clk_gating.state);
1934 queue_work(hba->clk_gating.clk_gating_workq,
1935 &hba->clk_gating.ungate_work);
1937 * fall through to check if we should wait for this
1938 * work to be done or not.
1942 spin_unlock_irqrestore(hba->host->host_lock, flags);
1943 flush_work(&hba->clk_gating.ungate_work);
1944 /* Make sure state is CLKS_ON before returning */
1945 spin_lock_irqsave(hba->host->host_lock, flags);
1948 dev_err(hba->dev, "%s: clk gating is in invalid state %d\n",
1949 __func__, hba->clk_gating.state);
1952 spin_unlock_irqrestore(hba->host->host_lock, flags);
1954 EXPORT_SYMBOL_GPL(ufshcd_hold);
1956 static void ufshcd_gate_work(struct work_struct *work)
1958 struct ufs_hba *hba = container_of(work, struct ufs_hba,
1959 clk_gating.gate_work.work);
1960 unsigned long flags;
1963 spin_lock_irqsave(hba->host->host_lock, flags);
1965 * In case you are here to cancel this work the gating state
1966 * would be marked as REQ_CLKS_ON. In this case save time by
1967 * skipping the gating work and exit after changing the clock
1970 if (hba->clk_gating.is_suspended ||
1971 (hba->clk_gating.state != REQ_CLKS_OFF)) {
1972 hba->clk_gating.state = CLKS_ON;
1973 trace_ufshcd_clk_gating(dev_name(hba->dev),
1974 hba->clk_gating.state);
1978 if (ufshcd_is_ufs_dev_busy(hba) || hba->ufshcd_state != UFSHCD_STATE_OPERATIONAL)
1981 spin_unlock_irqrestore(hba->host->host_lock, flags);
1983 /* put the link into hibern8 mode before turning off clocks */
1984 if (ufshcd_can_hibern8_during_gating(hba)) {
1985 ret = ufshcd_uic_hibern8_enter(hba);
1987 hba->clk_gating.state = CLKS_ON;
1988 dev_err(hba->dev, "%s: hibern8 enter failed %d\n",
1990 trace_ufshcd_clk_gating(dev_name(hba->dev),
1991 hba->clk_gating.state);
1994 ufshcd_set_link_hibern8(hba);
1997 ufshcd_disable_irq(hba);
1999 ufshcd_setup_clocks(hba, false);
2001 /* Put the host controller in low power mode if possible */
2002 ufshcd_hba_vreg_set_lpm(hba);
2004 * In case you are here to cancel this work the gating state
2005 * would be marked as REQ_CLKS_ON. In this case keep the state
2006 * as REQ_CLKS_ON which would anyway imply that clocks are off
2007 * and a request to turn them on is pending. By doing this way,
2008 * we keep the state machine in tact and this would ultimately
2009 * prevent from doing cancel work multiple times when there are
2010 * new requests arriving before the current cancel work is done.
2012 spin_lock_irqsave(hba->host->host_lock, flags);
2013 if (hba->clk_gating.state == REQ_CLKS_OFF) {
2014 hba->clk_gating.state = CLKS_OFF;
2015 trace_ufshcd_clk_gating(dev_name(hba->dev),
2016 hba->clk_gating.state);
2019 spin_unlock_irqrestore(hba->host->host_lock, flags);
2024 /* host lock must be held before calling this variant */
2025 static void __ufshcd_release(struct ufs_hba *hba)
2027 if (!ufshcd_is_clkgating_allowed(hba))
2030 hba->clk_gating.active_reqs--;
2032 if (hba->clk_gating.active_reqs || hba->clk_gating.is_suspended ||
2033 hba->ufshcd_state != UFSHCD_STATE_OPERATIONAL ||
2034 hba->outstanding_tasks || !hba->clk_gating.is_initialized ||
2035 hba->active_uic_cmd || hba->uic_async_done ||
2036 hba->clk_gating.state == CLKS_OFF)
2039 hba->clk_gating.state = REQ_CLKS_OFF;
2040 trace_ufshcd_clk_gating(dev_name(hba->dev), hba->clk_gating.state);
2041 queue_delayed_work(hba->clk_gating.clk_gating_workq,
2042 &hba->clk_gating.gate_work,
2043 msecs_to_jiffies(hba->clk_gating.delay_ms));
2046 void ufshcd_release(struct ufs_hba *hba)
2048 unsigned long flags;
2050 spin_lock_irqsave(hba->host->host_lock, flags);
2051 __ufshcd_release(hba);
2052 spin_unlock_irqrestore(hba->host->host_lock, flags);
2054 EXPORT_SYMBOL_GPL(ufshcd_release);
2056 static ssize_t ufshcd_clkgate_delay_show(struct device *dev,
2057 struct device_attribute *attr, char *buf)
2059 struct ufs_hba *hba = dev_get_drvdata(dev);
2061 return sysfs_emit(buf, "%lu\n", hba->clk_gating.delay_ms);
2064 void ufshcd_clkgate_delay_set(struct device *dev, unsigned long value)
2066 struct ufs_hba *hba = dev_get_drvdata(dev);
2067 unsigned long flags;
2069 spin_lock_irqsave(hba->host->host_lock, flags);
2070 hba->clk_gating.delay_ms = value;
2071 spin_unlock_irqrestore(hba->host->host_lock, flags);
2073 EXPORT_SYMBOL_GPL(ufshcd_clkgate_delay_set);
2075 static ssize_t ufshcd_clkgate_delay_store(struct device *dev,
2076 struct device_attribute *attr, const char *buf, size_t count)
2078 unsigned long value;
2080 if (kstrtoul(buf, 0, &value))
2083 ufshcd_clkgate_delay_set(dev, value);
2087 static ssize_t ufshcd_clkgate_enable_show(struct device *dev,
2088 struct device_attribute *attr, char *buf)
2090 struct ufs_hba *hba = dev_get_drvdata(dev);
2092 return sysfs_emit(buf, "%d\n", hba->clk_gating.is_enabled);
2095 static ssize_t ufshcd_clkgate_enable_store(struct device *dev,
2096 struct device_attribute *attr, const char *buf, size_t count)
2098 struct ufs_hba *hba = dev_get_drvdata(dev);
2099 unsigned long flags;
2102 if (kstrtou32(buf, 0, &value))
2107 spin_lock_irqsave(hba->host->host_lock, flags);
2108 if (value == hba->clk_gating.is_enabled)
2112 __ufshcd_release(hba);
2114 hba->clk_gating.active_reqs++;
2116 hba->clk_gating.is_enabled = value;
2118 spin_unlock_irqrestore(hba->host->host_lock, flags);
2122 static void ufshcd_init_clk_gating_sysfs(struct ufs_hba *hba)
2124 hba->clk_gating.delay_attr.show = ufshcd_clkgate_delay_show;
2125 hba->clk_gating.delay_attr.store = ufshcd_clkgate_delay_store;
2126 sysfs_attr_init(&hba->clk_gating.delay_attr.attr);
2127 hba->clk_gating.delay_attr.attr.name = "clkgate_delay_ms";
2128 hba->clk_gating.delay_attr.attr.mode = 0644;
2129 if (device_create_file(hba->dev, &hba->clk_gating.delay_attr))
2130 dev_err(hba->dev, "Failed to create sysfs for clkgate_delay\n");
2132 hba->clk_gating.enable_attr.show = ufshcd_clkgate_enable_show;
2133 hba->clk_gating.enable_attr.store = ufshcd_clkgate_enable_store;
2134 sysfs_attr_init(&hba->clk_gating.enable_attr.attr);
2135 hba->clk_gating.enable_attr.attr.name = "clkgate_enable";
2136 hba->clk_gating.enable_attr.attr.mode = 0644;
2137 if (device_create_file(hba->dev, &hba->clk_gating.enable_attr))
2138 dev_err(hba->dev, "Failed to create sysfs for clkgate_enable\n");
2141 static void ufshcd_remove_clk_gating_sysfs(struct ufs_hba *hba)
2143 if (hba->clk_gating.delay_attr.attr.name)
2144 device_remove_file(hba->dev, &hba->clk_gating.delay_attr);
2145 if (hba->clk_gating.enable_attr.attr.name)
2146 device_remove_file(hba->dev, &hba->clk_gating.enable_attr);
2149 static void ufshcd_init_clk_gating(struct ufs_hba *hba)
2151 char wq_name[sizeof("ufs_clk_gating_00")];
2153 if (!ufshcd_is_clkgating_allowed(hba))
2156 hba->clk_gating.state = CLKS_ON;
2158 hba->clk_gating.delay_ms = 150;
2159 INIT_DELAYED_WORK(&hba->clk_gating.gate_work, ufshcd_gate_work);
2160 INIT_WORK(&hba->clk_gating.ungate_work, ufshcd_ungate_work);
2162 snprintf(wq_name, ARRAY_SIZE(wq_name), "ufs_clk_gating_%d",
2163 hba->host->host_no);
2164 hba->clk_gating.clk_gating_workq = alloc_ordered_workqueue(wq_name,
2165 WQ_MEM_RECLAIM | WQ_HIGHPRI);
2167 ufshcd_init_clk_gating_sysfs(hba);
2169 hba->clk_gating.is_enabled = true;
2170 hba->clk_gating.is_initialized = true;
2173 static void ufshcd_exit_clk_gating(struct ufs_hba *hba)
2175 if (!hba->clk_gating.is_initialized)
2178 ufshcd_remove_clk_gating_sysfs(hba);
2180 /* Ungate the clock if necessary. */
2182 hba->clk_gating.is_initialized = false;
2183 ufshcd_release(hba);
2185 destroy_workqueue(hba->clk_gating.clk_gating_workq);
2188 static void ufshcd_clk_scaling_start_busy(struct ufs_hba *hba)
2190 bool queue_resume_work = false;
2191 ktime_t curr_t = ktime_get();
2192 unsigned long flags;
2194 if (!ufshcd_is_clkscaling_supported(hba))
2197 spin_lock_irqsave(hba->host->host_lock, flags);
2198 if (!hba->clk_scaling.active_reqs++)
2199 queue_resume_work = true;
2201 if (!hba->clk_scaling.is_enabled || hba->pm_op_in_progress) {
2202 spin_unlock_irqrestore(hba->host->host_lock, flags);
2206 if (queue_resume_work)
2207 queue_work(hba->clk_scaling.workq,
2208 &hba->clk_scaling.resume_work);
2210 if (!hba->clk_scaling.window_start_t) {
2211 hba->clk_scaling.window_start_t = curr_t;
2212 hba->clk_scaling.tot_busy_t = 0;
2213 hba->clk_scaling.is_busy_started = false;
2216 if (!hba->clk_scaling.is_busy_started) {
2217 hba->clk_scaling.busy_start_t = curr_t;
2218 hba->clk_scaling.is_busy_started = true;
2220 spin_unlock_irqrestore(hba->host->host_lock, flags);
2223 static void ufshcd_clk_scaling_update_busy(struct ufs_hba *hba)
2225 struct ufs_clk_scaling *scaling = &hba->clk_scaling;
2226 unsigned long flags;
2228 if (!ufshcd_is_clkscaling_supported(hba))
2231 spin_lock_irqsave(hba->host->host_lock, flags);
2232 hba->clk_scaling.active_reqs--;
2233 if (!scaling->active_reqs && scaling->is_busy_started) {
2234 scaling->tot_busy_t += ktime_to_us(ktime_sub(ktime_get(),
2235 scaling->busy_start_t));
2236 scaling->busy_start_t = 0;
2237 scaling->is_busy_started = false;
2239 spin_unlock_irqrestore(hba->host->host_lock, flags);
2242 static inline int ufshcd_monitor_opcode2dir(u8 opcode)
2244 if (opcode == READ_6 || opcode == READ_10 || opcode == READ_16)
2246 else if (opcode == WRITE_6 || opcode == WRITE_10 || opcode == WRITE_16)
2252 static inline bool ufshcd_should_inform_monitor(struct ufs_hba *hba,
2253 struct ufshcd_lrb *lrbp)
2255 const struct ufs_hba_monitor *m = &hba->monitor;
2257 return (m->enabled && lrbp && lrbp->cmd &&
2258 (!m->chunk_size || m->chunk_size == lrbp->cmd->sdb.length) &&
2259 ktime_before(hba->monitor.enabled_ts, lrbp->issue_time_stamp));
2262 static void ufshcd_start_monitor(struct ufs_hba *hba,
2263 const struct ufshcd_lrb *lrbp)
2265 int dir = ufshcd_monitor_opcode2dir(*lrbp->cmd->cmnd);
2266 unsigned long flags;
2268 spin_lock_irqsave(hba->host->host_lock, flags);
2269 if (dir >= 0 && hba->monitor.nr_queued[dir]++ == 0)
2270 hba->monitor.busy_start_ts[dir] = ktime_get();
2271 spin_unlock_irqrestore(hba->host->host_lock, flags);
2274 static void ufshcd_update_monitor(struct ufs_hba *hba, const struct ufshcd_lrb *lrbp)
2276 int dir = ufshcd_monitor_opcode2dir(*lrbp->cmd->cmnd);
2277 unsigned long flags;
2279 spin_lock_irqsave(hba->host->host_lock, flags);
2280 if (dir >= 0 && hba->monitor.nr_queued[dir] > 0) {
2281 const struct request *req = scsi_cmd_to_rq(lrbp->cmd);
2282 struct ufs_hba_monitor *m = &hba->monitor;
2283 ktime_t now, inc, lat;
2285 now = lrbp->compl_time_stamp;
2286 inc = ktime_sub(now, m->busy_start_ts[dir]);
2287 m->total_busy[dir] = ktime_add(m->total_busy[dir], inc);
2288 m->nr_sec_rw[dir] += blk_rq_sectors(req);
2290 /* Update latencies */
2292 lat = ktime_sub(now, lrbp->issue_time_stamp);
2293 m->lat_sum[dir] += lat;
2294 if (m->lat_max[dir] < lat || !m->lat_max[dir])
2295 m->lat_max[dir] = lat;
2296 if (m->lat_min[dir] > lat || !m->lat_min[dir])
2297 m->lat_min[dir] = lat;
2299 m->nr_queued[dir]--;
2300 /* Push forward the busy start of monitor */
2301 m->busy_start_ts[dir] = now;
2303 spin_unlock_irqrestore(hba->host->host_lock, flags);
2307 * ufshcd_send_command - Send SCSI or device management commands
2308 * @hba: per adapter instance
2309 * @task_tag: Task tag of the command
2310 * @hwq: pointer to hardware queue instance
2313 void ufshcd_send_command(struct ufs_hba *hba, unsigned int task_tag,
2314 struct ufs_hw_queue *hwq)
2316 struct ufshcd_lrb *lrbp = &hba->lrb[task_tag];
2317 unsigned long flags;
2319 lrbp->issue_time_stamp = ktime_get();
2320 lrbp->issue_time_stamp_local_clock = local_clock();
2321 lrbp->compl_time_stamp = ktime_set(0, 0);
2322 lrbp->compl_time_stamp_local_clock = 0;
2323 ufshcd_add_command_trace(hba, task_tag, UFS_CMD_SEND);
2325 ufshcd_clk_scaling_start_busy(hba);
2326 if (unlikely(ufshcd_should_inform_monitor(hba, lrbp)))
2327 ufshcd_start_monitor(hba, lrbp);
2329 if (is_mcq_enabled(hba)) {
2330 int utrd_size = sizeof(struct utp_transfer_req_desc);
2331 struct utp_transfer_req_desc *src = lrbp->utr_descriptor_ptr;
2332 struct utp_transfer_req_desc *dest;
2334 spin_lock(&hwq->sq_lock);
2335 dest = hwq->sqe_base_addr + hwq->sq_tail_slot;
2336 memcpy(dest, src, utrd_size);
2337 ufshcd_inc_sq_tail(hwq);
2338 spin_unlock(&hwq->sq_lock);
2340 spin_lock_irqsave(&hba->outstanding_lock, flags);
2341 if (hba->vops && hba->vops->setup_xfer_req)
2342 hba->vops->setup_xfer_req(hba, lrbp->task_tag,
2344 __set_bit(lrbp->task_tag, &hba->outstanding_reqs);
2345 ufshcd_writel(hba, 1 << lrbp->task_tag,
2346 REG_UTP_TRANSFER_REQ_DOOR_BELL);
2347 spin_unlock_irqrestore(&hba->outstanding_lock, flags);
2352 * ufshcd_copy_sense_data - Copy sense data in case of check condition
2353 * @lrbp: pointer to local reference block
2355 static inline void ufshcd_copy_sense_data(struct ufshcd_lrb *lrbp)
2357 u8 *const sense_buffer = lrbp->cmd->sense_buffer;
2361 resp_len = be16_to_cpu(lrbp->ucd_rsp_ptr->header.data_segment_length);
2362 if (sense_buffer && resp_len) {
2365 len = be16_to_cpu(lrbp->ucd_rsp_ptr->sr.sense_data_len);
2366 len_to_copy = min_t(int, UFS_SENSE_SIZE, len);
2368 memcpy(sense_buffer, lrbp->ucd_rsp_ptr->sr.sense_data,
2374 * ufshcd_copy_query_response() - Copy the Query Response and the data
2376 * @hba: per adapter instance
2377 * @lrbp: pointer to local reference block
2379 * Return: 0 upon success; < 0 upon failure.
2382 int ufshcd_copy_query_response(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
2384 struct ufs_query_res *query_res = &hba->dev_cmd.query.response;
2386 memcpy(&query_res->upiu_res, &lrbp->ucd_rsp_ptr->qr, QUERY_OSF_SIZE);
2388 /* Get the descriptor */
2389 if (hba->dev_cmd.query.descriptor &&
2390 lrbp->ucd_rsp_ptr->qr.opcode == UPIU_QUERY_OPCODE_READ_DESC) {
2391 u8 *descp = (u8 *)lrbp->ucd_rsp_ptr +
2392 GENERAL_UPIU_REQUEST_SIZE;
2396 /* data segment length */
2397 resp_len = be16_to_cpu(lrbp->ucd_rsp_ptr->header
2398 .data_segment_length);
2399 buf_len = be16_to_cpu(
2400 hba->dev_cmd.query.request.upiu_req.length);
2401 if (likely(buf_len >= resp_len)) {
2402 memcpy(hba->dev_cmd.query.descriptor, descp, resp_len);
2405 "%s: rsp size %d is bigger than buffer size %d",
2406 __func__, resp_len, buf_len);
2415 * ufshcd_hba_capabilities - Read controller capabilities
2416 * @hba: per adapter instance
2418 * Return: 0 on success, negative on error.
2420 static inline int ufshcd_hba_capabilities(struct ufs_hba *hba)
2424 hba->capabilities = ufshcd_readl(hba, REG_CONTROLLER_CAPABILITIES);
2425 if (hba->quirks & UFSHCD_QUIRK_BROKEN_64BIT_ADDRESS)
2426 hba->capabilities &= ~MASK_64_ADDRESSING_SUPPORT;
2428 /* nutrs and nutmrs are 0 based values */
2429 hba->nutrs = (hba->capabilities & MASK_TRANSFER_REQUESTS_SLOTS) + 1;
2431 ((hba->capabilities & MASK_TASK_MANAGEMENT_REQUEST_SLOTS) >> 16) + 1;
2432 hba->reserved_slot = hba->nutrs - 1;
2434 /* Read crypto capabilities */
2435 err = ufshcd_hba_init_crypto_capabilities(hba);
2437 dev_err(hba->dev, "crypto setup failed\n");
2441 hba->mcq_sup = FIELD_GET(MASK_MCQ_SUPPORT, hba->capabilities);
2445 hba->mcq_capabilities = ufshcd_readl(hba, REG_MCQCAP);
2446 hba->ext_iid_sup = FIELD_GET(MASK_EXT_IID_SUPPORT,
2447 hba->mcq_capabilities);
2453 * ufshcd_ready_for_uic_cmd - Check if controller is ready
2454 * to accept UIC commands
2455 * @hba: per adapter instance
2457 * Return: true on success, else false.
2459 static inline bool ufshcd_ready_for_uic_cmd(struct ufs_hba *hba)
2462 int ret = read_poll_timeout(ufshcd_readl, val, val & UIC_COMMAND_READY,
2463 500, UIC_CMD_TIMEOUT * 1000, false, hba,
2464 REG_CONTROLLER_STATUS);
2469 * ufshcd_get_upmcrs - Get the power mode change request status
2470 * @hba: Pointer to adapter instance
2472 * This function gets the UPMCRS field of HCS register
2474 * Return: value of UPMCRS field.
2476 static inline u8 ufshcd_get_upmcrs(struct ufs_hba *hba)
2478 return (ufshcd_readl(hba, REG_CONTROLLER_STATUS) >> 8) & 0x7;
2482 * ufshcd_dispatch_uic_cmd - Dispatch an UIC command to the Unipro layer
2483 * @hba: per adapter instance
2484 * @uic_cmd: UIC command
2487 ufshcd_dispatch_uic_cmd(struct ufs_hba *hba, struct uic_command *uic_cmd)
2489 lockdep_assert_held(&hba->uic_cmd_mutex);
2491 WARN_ON(hba->active_uic_cmd);
2493 hba->active_uic_cmd = uic_cmd;
2496 ufshcd_writel(hba, uic_cmd->argument1, REG_UIC_COMMAND_ARG_1);
2497 ufshcd_writel(hba, uic_cmd->argument2, REG_UIC_COMMAND_ARG_2);
2498 ufshcd_writel(hba, uic_cmd->argument3, REG_UIC_COMMAND_ARG_3);
2500 ufshcd_add_uic_command_trace(hba, uic_cmd, UFS_CMD_SEND);
2503 ufshcd_writel(hba, uic_cmd->command & COMMAND_OPCODE_MASK,
2508 * ufshcd_wait_for_uic_cmd - Wait for completion of an UIC command
2509 * @hba: per adapter instance
2510 * @uic_cmd: UIC command
2512 * Return: 0 only if success.
2515 ufshcd_wait_for_uic_cmd(struct ufs_hba *hba, struct uic_command *uic_cmd)
2518 unsigned long flags;
2520 lockdep_assert_held(&hba->uic_cmd_mutex);
2522 if (wait_for_completion_timeout(&uic_cmd->done,
2523 msecs_to_jiffies(UIC_CMD_TIMEOUT))) {
2524 ret = uic_cmd->argument2 & MASK_UIC_COMMAND_RESULT;
2528 "uic cmd 0x%x with arg3 0x%x completion timeout\n",
2529 uic_cmd->command, uic_cmd->argument3);
2531 if (!uic_cmd->cmd_active) {
2532 dev_err(hba->dev, "%s: UIC cmd has been completed, return the result\n",
2534 ret = uic_cmd->argument2 & MASK_UIC_COMMAND_RESULT;
2538 spin_lock_irqsave(hba->host->host_lock, flags);
2539 hba->active_uic_cmd = NULL;
2540 spin_unlock_irqrestore(hba->host->host_lock, flags);
2546 * __ufshcd_send_uic_cmd - Send UIC commands and retrieve the result
2547 * @hba: per adapter instance
2548 * @uic_cmd: UIC command
2549 * @completion: initialize the completion only if this is set to true
2551 * Return: 0 only if success.
2554 __ufshcd_send_uic_cmd(struct ufs_hba *hba, struct uic_command *uic_cmd,
2557 lockdep_assert_held(&hba->uic_cmd_mutex);
2559 if (!ufshcd_ready_for_uic_cmd(hba)) {
2561 "Controller not ready to accept UIC commands\n");
2566 init_completion(&uic_cmd->done);
2568 uic_cmd->cmd_active = 1;
2569 ufshcd_dispatch_uic_cmd(hba, uic_cmd);
2575 * ufshcd_send_uic_cmd - Send UIC commands and retrieve the result
2576 * @hba: per adapter instance
2577 * @uic_cmd: UIC command
2579 * Return: 0 only if success.
2581 int ufshcd_send_uic_cmd(struct ufs_hba *hba, struct uic_command *uic_cmd)
2585 if (hba->quirks & UFSHCD_QUIRK_BROKEN_UIC_CMD)
2589 mutex_lock(&hba->uic_cmd_mutex);
2590 ufshcd_add_delay_before_dme_cmd(hba);
2592 ret = __ufshcd_send_uic_cmd(hba, uic_cmd, true);
2594 ret = ufshcd_wait_for_uic_cmd(hba, uic_cmd);
2596 mutex_unlock(&hba->uic_cmd_mutex);
2598 ufshcd_release(hba);
2603 * ufshcd_sgl_to_prdt - SG list to PRTD (Physical Region Description Table, 4DW format)
2604 * @hba: per-adapter instance
2605 * @lrbp: pointer to local reference block
2606 * @sg_entries: The number of sg lists actually used
2607 * @sg_list: Pointer to SG list
2609 static void ufshcd_sgl_to_prdt(struct ufs_hba *hba, struct ufshcd_lrb *lrbp, int sg_entries,
2610 struct scatterlist *sg_list)
2612 struct ufshcd_sg_entry *prd;
2613 struct scatterlist *sg;
2618 if (hba->quirks & UFSHCD_QUIRK_PRDT_BYTE_GRAN)
2619 lrbp->utr_descriptor_ptr->prd_table_length =
2620 cpu_to_le16(sg_entries * ufshcd_sg_entry_size(hba));
2622 lrbp->utr_descriptor_ptr->prd_table_length = cpu_to_le16(sg_entries);
2624 prd = lrbp->ucd_prdt_ptr;
2626 for_each_sg(sg_list, sg, sg_entries, i) {
2627 const unsigned int len = sg_dma_len(sg);
2630 * From the UFSHCI spec: "Data Byte Count (DBC): A '0'
2631 * based value that indicates the length, in bytes, of
2632 * the data block. A maximum of length of 256KB may
2633 * exist for any entry. Bits 1:0 of this field shall be
2634 * 11b to indicate Dword granularity. A value of '3'
2635 * indicates 4 bytes, '7' indicates 8 bytes, etc."
2637 WARN_ONCE(len > SZ_256K, "len = %#x\n", len);
2638 prd->size = cpu_to_le32(len - 1);
2639 prd->addr = cpu_to_le64(sg->dma_address);
2641 prd = (void *)prd + ufshcd_sg_entry_size(hba);
2644 lrbp->utr_descriptor_ptr->prd_table_length = 0;
2649 * ufshcd_map_sg - Map scatter-gather list to prdt
2650 * @hba: per adapter instance
2651 * @lrbp: pointer to local reference block
2653 * Return: 0 in case of success, non-zero value in case of failure.
2655 static int ufshcd_map_sg(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
2657 struct scsi_cmnd *cmd = lrbp->cmd;
2658 int sg_segments = scsi_dma_map(cmd);
2660 if (sg_segments < 0)
2663 ufshcd_sgl_to_prdt(hba, lrbp, sg_segments, scsi_sglist(cmd));
2669 * ufshcd_enable_intr - enable interrupts
2670 * @hba: per adapter instance
2671 * @intrs: interrupt bits
2673 static void ufshcd_enable_intr(struct ufs_hba *hba, u32 intrs)
2675 u32 set = ufshcd_readl(hba, REG_INTERRUPT_ENABLE);
2677 if (hba->ufs_version == ufshci_version(1, 0)) {
2679 rw = set & INTERRUPT_MASK_RW_VER_10;
2680 set = rw | ((set ^ intrs) & intrs);
2685 ufshcd_writel(hba, set, REG_INTERRUPT_ENABLE);
2689 * ufshcd_disable_intr - disable interrupts
2690 * @hba: per adapter instance
2691 * @intrs: interrupt bits
2693 static void ufshcd_disable_intr(struct ufs_hba *hba, u32 intrs)
2695 u32 set = ufshcd_readl(hba, REG_INTERRUPT_ENABLE);
2697 if (hba->ufs_version == ufshci_version(1, 0)) {
2699 rw = (set & INTERRUPT_MASK_RW_VER_10) &
2700 ~(intrs & INTERRUPT_MASK_RW_VER_10);
2701 set = rw | ((set & intrs) & ~INTERRUPT_MASK_RW_VER_10);
2707 ufshcd_writel(hba, set, REG_INTERRUPT_ENABLE);
2711 * ufshcd_prepare_req_desc_hdr - Fill UTP Transfer request descriptor header according to request
2712 * descriptor according to request
2713 * @lrbp: pointer to local reference block
2714 * @upiu_flags: flags required in the header
2715 * @cmd_dir: requests data direction
2716 * @ehs_length: Total EHS Length (in 32‐bytes units of all Extra Header Segments)
2718 static void ufshcd_prepare_req_desc_hdr(struct ufshcd_lrb *lrbp, u8 *upiu_flags,
2719 enum dma_data_direction cmd_dir, int ehs_length)
2721 struct utp_transfer_req_desc *req_desc = lrbp->utr_descriptor_ptr;
2722 struct request_desc_header *h = &req_desc->header;
2723 enum utp_data_direction data_direction;
2725 *h = (typeof(*h)){ };
2727 if (cmd_dir == DMA_FROM_DEVICE) {
2728 data_direction = UTP_DEVICE_TO_HOST;
2729 *upiu_flags = UPIU_CMD_FLAGS_READ;
2730 } else if (cmd_dir == DMA_TO_DEVICE) {
2731 data_direction = UTP_HOST_TO_DEVICE;
2732 *upiu_flags = UPIU_CMD_FLAGS_WRITE;
2734 data_direction = UTP_NO_DATA_TRANSFER;
2735 *upiu_flags = UPIU_CMD_FLAGS_NONE;
2738 h->command_type = lrbp->command_type;
2739 h->data_direction = data_direction;
2740 h->ehs_length = ehs_length;
2745 /* Prepare crypto related dwords */
2746 ufshcd_prepare_req_desc_hdr_crypto(lrbp, h);
2749 * assigning invalid value for command status. Controller
2750 * updates OCS on command completion, with the command
2753 h->ocs = OCS_INVALID_COMMAND_STATUS;
2755 req_desc->prd_table_length = 0;
2759 * ufshcd_prepare_utp_scsi_cmd_upiu() - fills the utp_transfer_req_desc,
2761 * @lrbp: local reference block pointer
2762 * @upiu_flags: flags
2765 void ufshcd_prepare_utp_scsi_cmd_upiu(struct ufshcd_lrb *lrbp, u8 upiu_flags)
2767 struct scsi_cmnd *cmd = lrbp->cmd;
2768 struct utp_upiu_req *ucd_req_ptr = lrbp->ucd_req_ptr;
2769 unsigned short cdb_len;
2771 ucd_req_ptr->header = (struct utp_upiu_header){
2772 .transaction_code = UPIU_TRANSACTION_COMMAND,
2773 .flags = upiu_flags,
2775 .task_tag = lrbp->task_tag,
2776 .command_set_type = UPIU_COMMAND_SET_TYPE_SCSI,
2779 WARN_ON_ONCE(ucd_req_ptr->header.task_tag != lrbp->task_tag);
2781 ucd_req_ptr->sc.exp_data_transfer_len = cpu_to_be32(cmd->sdb.length);
2783 cdb_len = min_t(unsigned short, cmd->cmd_len, UFS_CDB_SIZE);
2784 memset(ucd_req_ptr->sc.cdb, 0, UFS_CDB_SIZE);
2785 memcpy(ucd_req_ptr->sc.cdb, cmd->cmnd, cdb_len);
2787 memset(lrbp->ucd_rsp_ptr, 0, sizeof(struct utp_upiu_rsp));
2791 * ufshcd_prepare_utp_query_req_upiu() - fill the utp_transfer_req_desc for query request
2793 * @lrbp: local reference block pointer
2794 * @upiu_flags: flags
2796 static void ufshcd_prepare_utp_query_req_upiu(struct ufs_hba *hba,
2797 struct ufshcd_lrb *lrbp, u8 upiu_flags)
2799 struct utp_upiu_req *ucd_req_ptr = lrbp->ucd_req_ptr;
2800 struct ufs_query *query = &hba->dev_cmd.query;
2801 u16 len = be16_to_cpu(query->request.upiu_req.length);
2803 /* Query request header */
2804 ucd_req_ptr->header = (struct utp_upiu_header){
2805 .transaction_code = UPIU_TRANSACTION_QUERY_REQ,
2806 .flags = upiu_flags,
2808 .task_tag = lrbp->task_tag,
2809 .query_function = query->request.query_func,
2810 /* Data segment length only need for WRITE_DESC */
2811 .data_segment_length =
2812 query->request.upiu_req.opcode ==
2813 UPIU_QUERY_OPCODE_WRITE_DESC ?
2818 /* Copy the Query Request buffer as is */
2819 memcpy(&ucd_req_ptr->qr, &query->request.upiu_req,
2822 /* Copy the Descriptor */
2823 if (query->request.upiu_req.opcode == UPIU_QUERY_OPCODE_WRITE_DESC)
2824 memcpy(ucd_req_ptr + 1, query->descriptor, len);
2826 memset(lrbp->ucd_rsp_ptr, 0, sizeof(struct utp_upiu_rsp));
2829 static inline void ufshcd_prepare_utp_nop_upiu(struct ufshcd_lrb *lrbp)
2831 struct utp_upiu_req *ucd_req_ptr = lrbp->ucd_req_ptr;
2833 memset(ucd_req_ptr, 0, sizeof(struct utp_upiu_req));
2835 ucd_req_ptr->header = (struct utp_upiu_header){
2836 .transaction_code = UPIU_TRANSACTION_NOP_OUT,
2837 .task_tag = lrbp->task_tag,
2840 memset(lrbp->ucd_rsp_ptr, 0, sizeof(struct utp_upiu_rsp));
2844 * ufshcd_compose_devman_upiu - UFS Protocol Information Unit(UPIU)
2845 * for Device Management Purposes
2846 * @hba: per adapter instance
2847 * @lrbp: pointer to local reference block
2849 * Return: 0 upon success; < 0 upon failure.
2851 static int ufshcd_compose_devman_upiu(struct ufs_hba *hba,
2852 struct ufshcd_lrb *lrbp)
2857 if (hba->ufs_version <= ufshci_version(1, 1))
2858 lrbp->command_type = UTP_CMD_TYPE_DEV_MANAGE;
2860 lrbp->command_type = UTP_CMD_TYPE_UFS_STORAGE;
2862 ufshcd_prepare_req_desc_hdr(lrbp, &upiu_flags, DMA_NONE, 0);
2863 if (hba->dev_cmd.type == DEV_CMD_TYPE_QUERY)
2864 ufshcd_prepare_utp_query_req_upiu(hba, lrbp, upiu_flags);
2865 else if (hba->dev_cmd.type == DEV_CMD_TYPE_NOP)
2866 ufshcd_prepare_utp_nop_upiu(lrbp);
2874 * ufshcd_comp_scsi_upiu - UFS Protocol Information Unit(UPIU)
2876 * @hba: per adapter instance
2877 * @lrbp: pointer to local reference block
2879 static void ufshcd_comp_scsi_upiu(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
2881 struct request *rq = scsi_cmd_to_rq(lrbp->cmd);
2882 unsigned int ioprio_class = IOPRIO_PRIO_CLASS(req_get_ioprio(rq));
2885 if (hba->ufs_version <= ufshci_version(1, 1))
2886 lrbp->command_type = UTP_CMD_TYPE_SCSI;
2888 lrbp->command_type = UTP_CMD_TYPE_UFS_STORAGE;
2890 ufshcd_prepare_req_desc_hdr(lrbp, &upiu_flags,
2891 lrbp->cmd->sc_data_direction, 0);
2892 if (ioprio_class == IOPRIO_CLASS_RT)
2893 upiu_flags |= UPIU_CMD_FLAGS_CP;
2894 ufshcd_prepare_utp_scsi_cmd_upiu(lrbp, upiu_flags);
2898 * ufshcd_upiu_wlun_to_scsi_wlun - maps UPIU W-LUN id to SCSI W-LUN ID
2899 * @upiu_wlun_id: UPIU W-LUN id
2901 * Return: SCSI W-LUN id.
2903 static inline u16 ufshcd_upiu_wlun_to_scsi_wlun(u8 upiu_wlun_id)
2905 return (upiu_wlun_id & ~UFS_UPIU_WLUN_ID) | SCSI_W_LUN_BASE;
2908 static inline bool is_device_wlun(struct scsi_device *sdev)
2911 ufshcd_upiu_wlun_to_scsi_wlun(UFS_UPIU_UFS_DEVICE_WLUN);
2915 * Associate the UFS controller queue with the default and poll HCTX types.
2916 * Initialize the mq_map[] arrays.
2918 static void ufshcd_map_queues(struct Scsi_Host *shost)
2920 struct ufs_hba *hba = shost_priv(shost);
2921 int i, queue_offset = 0;
2923 if (!is_mcq_supported(hba)) {
2924 hba->nr_queues[HCTX_TYPE_DEFAULT] = 1;
2925 hba->nr_queues[HCTX_TYPE_READ] = 0;
2926 hba->nr_queues[HCTX_TYPE_POLL] = 1;
2927 hba->nr_hw_queues = 1;
2930 for (i = 0; i < shost->nr_maps; i++) {
2931 struct blk_mq_queue_map *map = &shost->tag_set.map[i];
2933 map->nr_queues = hba->nr_queues[i];
2934 if (!map->nr_queues)
2936 map->queue_offset = queue_offset;
2937 if (i == HCTX_TYPE_POLL && !is_mcq_supported(hba))
2938 map->queue_offset = 0;
2940 blk_mq_map_queues(map);
2941 queue_offset += map->nr_queues;
2945 static void ufshcd_init_lrb(struct ufs_hba *hba, struct ufshcd_lrb *lrb, int i)
2947 struct utp_transfer_cmd_desc *cmd_descp = (void *)hba->ucdl_base_addr +
2948 i * ufshcd_get_ucd_size(hba);
2949 struct utp_transfer_req_desc *utrdlp = hba->utrdl_base_addr;
2950 dma_addr_t cmd_desc_element_addr = hba->ucdl_dma_addr +
2951 i * ufshcd_get_ucd_size(hba);
2952 u16 response_offset = offsetof(struct utp_transfer_cmd_desc,
2954 u16 prdt_offset = offsetof(struct utp_transfer_cmd_desc, prd_table);
2956 lrb->utr_descriptor_ptr = utrdlp + i;
2957 lrb->utrd_dma_addr = hba->utrdl_dma_addr +
2958 i * sizeof(struct utp_transfer_req_desc);
2959 lrb->ucd_req_ptr = (struct utp_upiu_req *)cmd_descp->command_upiu;
2960 lrb->ucd_req_dma_addr = cmd_desc_element_addr;
2961 lrb->ucd_rsp_ptr = (struct utp_upiu_rsp *)cmd_descp->response_upiu;
2962 lrb->ucd_rsp_dma_addr = cmd_desc_element_addr + response_offset;
2963 lrb->ucd_prdt_ptr = (struct ufshcd_sg_entry *)cmd_descp->prd_table;
2964 lrb->ucd_prdt_dma_addr = cmd_desc_element_addr + prdt_offset;
2968 * ufshcd_queuecommand - main entry point for SCSI requests
2969 * @host: SCSI host pointer
2970 * @cmd: command from SCSI Midlayer
2972 * Return: 0 for success, non-zero in case of failure.
2974 static int ufshcd_queuecommand(struct Scsi_Host *host, struct scsi_cmnd *cmd)
2976 struct ufs_hba *hba = shost_priv(host);
2977 int tag = scsi_cmd_to_rq(cmd)->tag;
2978 struct ufshcd_lrb *lrbp;
2980 struct ufs_hw_queue *hwq = NULL;
2982 switch (hba->ufshcd_state) {
2983 case UFSHCD_STATE_OPERATIONAL:
2985 case UFSHCD_STATE_EH_SCHEDULED_NON_FATAL:
2987 * SCSI error handler can call ->queuecommand() while UFS error
2988 * handler is in progress. Error interrupts could change the
2989 * state from UFSHCD_STATE_RESET to
2990 * UFSHCD_STATE_EH_SCHEDULED_NON_FATAL. Prevent requests
2991 * being issued in that case.
2993 if (ufshcd_eh_in_progress(hba)) {
2994 err = SCSI_MLQUEUE_HOST_BUSY;
2998 case UFSHCD_STATE_EH_SCHEDULED_FATAL:
3000 * pm_runtime_get_sync() is used at error handling preparation
3001 * stage. If a scsi cmd, e.g. the SSU cmd, is sent from hba's
3002 * PM ops, it can never be finished if we let SCSI layer keep
3003 * retrying it, which gets err handler stuck forever. Neither
3004 * can we let the scsi cmd pass through, because UFS is in bad
3005 * state, the scsi cmd may eventually time out, which will get
3006 * err handler blocked for too long. So, just fail the scsi cmd
3007 * sent from PM ops, err handler can recover PM error anyways.
3009 if (hba->pm_op_in_progress) {
3010 hba->force_reset = true;
3011 set_host_byte(cmd, DID_BAD_TARGET);
3016 case UFSHCD_STATE_RESET:
3017 err = SCSI_MLQUEUE_HOST_BUSY;
3019 case UFSHCD_STATE_ERROR:
3020 set_host_byte(cmd, DID_ERROR);
3025 hba->req_abort_count = 0;
3029 lrbp = &hba->lrb[tag];
3031 lrbp->task_tag = tag;
3032 lrbp->lun = ufshcd_scsi_to_upiu_lun(cmd->device->lun);
3033 lrbp->intr_cmd = !ufshcd_is_intr_aggr_allowed(hba);
3035 ufshcd_prepare_lrbp_crypto(scsi_cmd_to_rq(cmd), lrbp);
3037 lrbp->req_abort_skip = false;
3039 ufshcd_comp_scsi_upiu(hba, lrbp);
3041 err = ufshcd_map_sg(hba, lrbp);
3043 ufshcd_release(hba);
3047 if (is_mcq_enabled(hba))
3048 hwq = ufshcd_mcq_req_to_hwq(hba, scsi_cmd_to_rq(cmd));
3050 ufshcd_send_command(hba, tag, hwq);
3053 if (ufs_trigger_eh(hba)) {
3054 unsigned long flags;
3056 spin_lock_irqsave(hba->host->host_lock, flags);
3057 ufshcd_schedule_eh_work(hba);
3058 spin_unlock_irqrestore(hba->host->host_lock, flags);
3064 static int ufshcd_compose_dev_cmd(struct ufs_hba *hba,
3065 struct ufshcd_lrb *lrbp, enum dev_cmd_type cmd_type, int tag)
3068 lrbp->task_tag = tag;
3069 lrbp->lun = 0; /* device management cmd is not specific to any LUN */
3070 lrbp->intr_cmd = true; /* No interrupt aggregation */
3071 ufshcd_prepare_lrbp_crypto(NULL, lrbp);
3072 hba->dev_cmd.type = cmd_type;
3074 return ufshcd_compose_devman_upiu(hba, lrbp);
3078 * Check with the block layer if the command is inflight
3079 * @cmd: command to check.
3081 * Return: true if command is inflight; false if not.
3083 bool ufshcd_cmd_inflight(struct scsi_cmnd *cmd)
3090 rq = scsi_cmd_to_rq(cmd);
3091 if (!blk_mq_request_started(rq))
3098 * Clear the pending command in the controller and wait until
3099 * the controller confirms that the command has been cleared.
3100 * @hba: per adapter instance
3101 * @task_tag: The tag number of the command to be cleared.
3103 static int ufshcd_clear_cmd(struct ufs_hba *hba, u32 task_tag)
3106 unsigned long flags;
3109 if (is_mcq_enabled(hba)) {
3111 * MCQ mode. Clean up the MCQ resources similar to
3112 * what the ufshcd_utrl_clear() does for SDB mode.
3114 err = ufshcd_mcq_sq_cleanup(hba, task_tag);
3116 dev_err(hba->dev, "%s: failed tag=%d. err=%d\n",
3117 __func__, task_tag, err);
3123 mask = 1U << task_tag;
3125 /* clear outstanding transaction before retry */
3126 spin_lock_irqsave(hba->host->host_lock, flags);
3127 ufshcd_utrl_clear(hba, mask);
3128 spin_unlock_irqrestore(hba->host->host_lock, flags);
3131 * wait for h/w to clear corresponding bit in door-bell.
3132 * max. wait is 1 sec.
3134 return ufshcd_wait_for_register(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL,
3135 mask, ~mask, 1000, 1000);
3139 * ufshcd_dev_cmd_completion() - handles device management command responses
3140 * @hba: per adapter instance
3141 * @lrbp: pointer to local reference block
3143 * Return: 0 upon success; < 0 upon failure.
3146 ufshcd_dev_cmd_completion(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
3148 enum upiu_response_transaction resp;
3151 hba->ufs_stats.last_hibern8_exit_tstamp = ktime_set(0, 0);
3152 resp = ufshcd_get_req_rsp(lrbp->ucd_rsp_ptr);
3155 case UPIU_TRANSACTION_NOP_IN:
3156 if (hba->dev_cmd.type != DEV_CMD_TYPE_NOP) {
3158 dev_err(hba->dev, "%s: unexpected response %x\n",
3162 case UPIU_TRANSACTION_QUERY_RSP: {
3163 u8 response = lrbp->ucd_rsp_ptr->header.response;
3166 err = ufshcd_copy_query_response(hba, lrbp);
3169 case UPIU_TRANSACTION_REJECT_UPIU:
3170 /* TODO: handle Reject UPIU Response */
3172 dev_err(hba->dev, "%s: Reject UPIU not fully implemented\n",
3175 case UPIU_TRANSACTION_RESPONSE:
3176 if (hba->dev_cmd.type != DEV_CMD_TYPE_RPMB) {
3178 dev_err(hba->dev, "%s: unexpected response %x\n", __func__, resp);
3183 dev_err(hba->dev, "%s: Invalid device management cmd response: %x\n",
3191 static int ufshcd_wait_for_dev_cmd(struct ufs_hba *hba,
3192 struct ufshcd_lrb *lrbp, int max_timeout)
3194 unsigned long time_left = msecs_to_jiffies(max_timeout);
3195 unsigned long flags;
3200 time_left = wait_for_completion_timeout(hba->dev_cmd.complete,
3203 if (likely(time_left)) {
3205 * The completion handler called complete() and the caller of
3206 * this function still owns the @lrbp tag so the code below does
3207 * not trigger any race conditions.
3209 hba->dev_cmd.complete = NULL;
3210 err = ufshcd_get_tr_ocs(lrbp, NULL);
3212 err = ufshcd_dev_cmd_completion(hba, lrbp);
3215 dev_dbg(hba->dev, "%s: dev_cmd request timedout, tag %d\n",
3216 __func__, lrbp->task_tag);
3219 if (is_mcq_enabled(hba)) {
3220 err = ufshcd_clear_cmd(hba, lrbp->task_tag);
3221 hba->dev_cmd.complete = NULL;
3226 if (ufshcd_clear_cmd(hba, lrbp->task_tag) == 0) {
3227 /* successfully cleared the command, retry if needed */
3230 * Since clearing the command succeeded we also need to
3231 * clear the task tag bit from the outstanding_reqs
3234 spin_lock_irqsave(&hba->outstanding_lock, flags);
3235 pending = test_bit(lrbp->task_tag,
3236 &hba->outstanding_reqs);
3238 hba->dev_cmd.complete = NULL;
3239 __clear_bit(lrbp->task_tag,
3240 &hba->outstanding_reqs);
3242 spin_unlock_irqrestore(&hba->outstanding_lock, flags);
3246 * The completion handler ran while we tried to
3247 * clear the command.
3253 dev_err(hba->dev, "%s: failed to clear tag %d\n",
3254 __func__, lrbp->task_tag);
3256 spin_lock_irqsave(&hba->outstanding_lock, flags);
3257 pending = test_bit(lrbp->task_tag,
3258 &hba->outstanding_reqs);
3260 hba->dev_cmd.complete = NULL;
3261 spin_unlock_irqrestore(&hba->outstanding_lock, flags);
3265 * The completion handler ran while we tried to
3266 * clear the command.
3278 * ufshcd_exec_dev_cmd - API for sending device management requests
3280 * @cmd_type: specifies the type (NOP, Query...)
3281 * @timeout: timeout in milliseconds
3283 * Return: 0 upon success; < 0 upon failure.
3285 * NOTE: Since there is only one available tag for device management commands,
3286 * it is expected you hold the hba->dev_cmd.lock mutex.
3288 static int ufshcd_exec_dev_cmd(struct ufs_hba *hba,
3289 enum dev_cmd_type cmd_type, int timeout)
3291 DECLARE_COMPLETION_ONSTACK(wait);
3292 const u32 tag = hba->reserved_slot;
3293 struct ufshcd_lrb *lrbp;
3296 /* Protects use of hba->reserved_slot. */
3297 lockdep_assert_held(&hba->dev_cmd.lock);
3299 down_read(&hba->clk_scaling_lock);
3301 lrbp = &hba->lrb[tag];
3303 err = ufshcd_compose_dev_cmd(hba, lrbp, cmd_type, tag);
3307 hba->dev_cmd.complete = &wait;
3309 ufshcd_add_query_upiu_trace(hba, UFS_QUERY_SEND, lrbp->ucd_req_ptr);
3311 ufshcd_send_command(hba, tag, hba->dev_cmd_queue);
3312 err = ufshcd_wait_for_dev_cmd(hba, lrbp, timeout);
3313 ufshcd_add_query_upiu_trace(hba, err ? UFS_QUERY_ERR : UFS_QUERY_COMP,
3314 (struct utp_upiu_req *)lrbp->ucd_rsp_ptr);
3317 up_read(&hba->clk_scaling_lock);
3322 * ufshcd_init_query() - init the query response and request parameters
3323 * @hba: per-adapter instance
3324 * @request: address of the request pointer to be initialized
3325 * @response: address of the response pointer to be initialized
3326 * @opcode: operation to perform
3327 * @idn: flag idn to access
3328 * @index: LU number to access
3329 * @selector: query/flag/descriptor further identification
3331 static inline void ufshcd_init_query(struct ufs_hba *hba,
3332 struct ufs_query_req **request, struct ufs_query_res **response,
3333 enum query_opcode opcode, u8 idn, u8 index, u8 selector)
3335 *request = &hba->dev_cmd.query.request;
3336 *response = &hba->dev_cmd.query.response;
3337 memset(*request, 0, sizeof(struct ufs_query_req));
3338 memset(*response, 0, sizeof(struct ufs_query_res));
3339 (*request)->upiu_req.opcode = opcode;
3340 (*request)->upiu_req.idn = idn;
3341 (*request)->upiu_req.index = index;
3342 (*request)->upiu_req.selector = selector;
3345 static int ufshcd_query_flag_retry(struct ufs_hba *hba,
3346 enum query_opcode opcode, enum flag_idn idn, u8 index, bool *flag_res)
3351 for (retries = 0; retries < QUERY_REQ_RETRIES; retries++) {
3352 ret = ufshcd_query_flag(hba, opcode, idn, index, flag_res);
3355 "%s: failed with error %d, retries %d\n",
3356 __func__, ret, retries);
3363 "%s: query flag, opcode %d, idn %d, failed with error %d after %d retries\n",
3364 __func__, opcode, idn, ret, retries);
3369 * ufshcd_query_flag() - API function for sending flag query requests
3370 * @hba: per-adapter instance
3371 * @opcode: flag query to perform
3372 * @idn: flag idn to access
3373 * @index: flag index to access
3374 * @flag_res: the flag value after the query request completes
3376 * Return: 0 for success, non-zero in case of failure.
3378 int ufshcd_query_flag(struct ufs_hba *hba, enum query_opcode opcode,
3379 enum flag_idn idn, u8 index, bool *flag_res)
3381 struct ufs_query_req *request = NULL;
3382 struct ufs_query_res *response = NULL;
3383 int err, selector = 0;
3384 int timeout = QUERY_REQ_TIMEOUT;
3389 mutex_lock(&hba->dev_cmd.lock);
3390 ufshcd_init_query(hba, &request, &response, opcode, idn, index,
3394 case UPIU_QUERY_OPCODE_SET_FLAG:
3395 case UPIU_QUERY_OPCODE_CLEAR_FLAG:
3396 case UPIU_QUERY_OPCODE_TOGGLE_FLAG:
3397 request->query_func = UPIU_QUERY_FUNC_STANDARD_WRITE_REQUEST;
3399 case UPIU_QUERY_OPCODE_READ_FLAG:
3400 request->query_func = UPIU_QUERY_FUNC_STANDARD_READ_REQUEST;
3402 /* No dummy reads */
3403 dev_err(hba->dev, "%s: Invalid argument for read request\n",
3411 "%s: Expected query flag opcode but got = %d\n",
3417 err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_QUERY, timeout);
3421 "%s: Sending flag query for idn %d failed, err = %d\n",
3422 __func__, idn, err);
3427 *flag_res = (be32_to_cpu(response->upiu_res.value) &
3428 MASK_QUERY_UPIU_FLAG_LOC) & 0x1;
3431 mutex_unlock(&hba->dev_cmd.lock);
3432 ufshcd_release(hba);
3437 * ufshcd_query_attr - API function for sending attribute requests
3438 * @hba: per-adapter instance
3439 * @opcode: attribute opcode
3440 * @idn: attribute idn to access
3441 * @index: index field
3442 * @selector: selector field
3443 * @attr_val: the attribute value after the query request completes
3445 * Return: 0 for success, non-zero in case of failure.
3447 int ufshcd_query_attr(struct ufs_hba *hba, enum query_opcode opcode,
3448 enum attr_idn idn, u8 index, u8 selector, u32 *attr_val)
3450 struct ufs_query_req *request = NULL;
3451 struct ufs_query_res *response = NULL;
3457 dev_err(hba->dev, "%s: attribute value required for opcode 0x%x\n",
3464 mutex_lock(&hba->dev_cmd.lock);
3465 ufshcd_init_query(hba, &request, &response, opcode, idn, index,
3469 case UPIU_QUERY_OPCODE_WRITE_ATTR:
3470 request->query_func = UPIU_QUERY_FUNC_STANDARD_WRITE_REQUEST;
3471 request->upiu_req.value = cpu_to_be32(*attr_val);
3473 case UPIU_QUERY_OPCODE_READ_ATTR:
3474 request->query_func = UPIU_QUERY_FUNC_STANDARD_READ_REQUEST;
3477 dev_err(hba->dev, "%s: Expected query attr opcode but got = 0x%.2x\n",
3483 err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_QUERY, QUERY_REQ_TIMEOUT);
3486 dev_err(hba->dev, "%s: opcode 0x%.2x for idn %d failed, index %d, err = %d\n",
3487 __func__, opcode, idn, index, err);
3491 *attr_val = be32_to_cpu(response->upiu_res.value);
3494 mutex_unlock(&hba->dev_cmd.lock);
3495 ufshcd_release(hba);
3500 * ufshcd_query_attr_retry() - API function for sending query
3501 * attribute with retries
3502 * @hba: per-adapter instance
3503 * @opcode: attribute opcode
3504 * @idn: attribute idn to access
3505 * @index: index field
3506 * @selector: selector field
3507 * @attr_val: the attribute value after the query request
3510 * Return: 0 for success, non-zero in case of failure.
3512 int ufshcd_query_attr_retry(struct ufs_hba *hba,
3513 enum query_opcode opcode, enum attr_idn idn, u8 index, u8 selector,
3519 for (retries = QUERY_REQ_RETRIES; retries > 0; retries--) {
3520 ret = ufshcd_query_attr(hba, opcode, idn, index,
3521 selector, attr_val);
3523 dev_dbg(hba->dev, "%s: failed with error %d, retries %d\n",
3524 __func__, ret, retries);
3531 "%s: query attribute, idn %d, failed with error %d after %d retries\n",
3532 __func__, idn, ret, QUERY_REQ_RETRIES);
3536 static int __ufshcd_query_descriptor(struct ufs_hba *hba,
3537 enum query_opcode opcode, enum desc_idn idn, u8 index,
3538 u8 selector, u8 *desc_buf, int *buf_len)
3540 struct ufs_query_req *request = NULL;
3541 struct ufs_query_res *response = NULL;
3547 dev_err(hba->dev, "%s: descriptor buffer required for opcode 0x%x\n",
3552 if (*buf_len < QUERY_DESC_MIN_SIZE || *buf_len > QUERY_DESC_MAX_SIZE) {
3553 dev_err(hba->dev, "%s: descriptor buffer size (%d) is out of range\n",
3554 __func__, *buf_len);
3560 mutex_lock(&hba->dev_cmd.lock);
3561 ufshcd_init_query(hba, &request, &response, opcode, idn, index,
3563 hba->dev_cmd.query.descriptor = desc_buf;
3564 request->upiu_req.length = cpu_to_be16(*buf_len);
3567 case UPIU_QUERY_OPCODE_WRITE_DESC:
3568 request->query_func = UPIU_QUERY_FUNC_STANDARD_WRITE_REQUEST;
3570 case UPIU_QUERY_OPCODE_READ_DESC:
3571 request->query_func = UPIU_QUERY_FUNC_STANDARD_READ_REQUEST;
3575 "%s: Expected query descriptor opcode but got = 0x%.2x\n",
3581 err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_QUERY, QUERY_REQ_TIMEOUT);
3584 dev_err(hba->dev, "%s: opcode 0x%.2x for idn %d failed, index %d, err = %d\n",
3585 __func__, opcode, idn, index, err);
3589 *buf_len = be16_to_cpu(response->upiu_res.length);
3592 hba->dev_cmd.query.descriptor = NULL;
3593 mutex_unlock(&hba->dev_cmd.lock);
3594 ufshcd_release(hba);
3599 * ufshcd_query_descriptor_retry - API function for sending descriptor requests
3600 * @hba: per-adapter instance
3601 * @opcode: attribute opcode
3602 * @idn: attribute idn to access
3603 * @index: index field
3604 * @selector: selector field
3605 * @desc_buf: the buffer that contains the descriptor
3606 * @buf_len: length parameter passed to the device
3608 * The buf_len parameter will contain, on return, the length parameter
3609 * received on the response.
3611 * Return: 0 for success, non-zero in case of failure.
3613 int ufshcd_query_descriptor_retry(struct ufs_hba *hba,
3614 enum query_opcode opcode,
3615 enum desc_idn idn, u8 index,
3617 u8 *desc_buf, int *buf_len)
3622 for (retries = QUERY_REQ_RETRIES; retries > 0; retries--) {
3623 err = __ufshcd_query_descriptor(hba, opcode, idn, index,
3624 selector, desc_buf, buf_len);
3625 if (!err || err == -EINVAL)
3633 * ufshcd_read_desc_param - read the specified descriptor parameter
3634 * @hba: Pointer to adapter instance
3635 * @desc_id: descriptor idn value
3636 * @desc_index: descriptor index
3637 * @param_offset: offset of the parameter to read
3638 * @param_read_buf: pointer to buffer where parameter would be read
3639 * @param_size: sizeof(param_read_buf)
3641 * Return: 0 in case of success, non-zero otherwise.
3643 int ufshcd_read_desc_param(struct ufs_hba *hba,
3644 enum desc_idn desc_id,
3652 int buff_len = QUERY_DESC_MAX_SIZE;
3653 bool is_kmalloc = true;
3656 if (desc_id >= QUERY_DESC_IDN_MAX || !param_size)
3659 /* Check whether we need temp memory */
3660 if (param_offset != 0 || param_size < buff_len) {
3661 desc_buf = kzalloc(buff_len, GFP_KERNEL);
3665 desc_buf = param_read_buf;
3669 /* Request for full descriptor */
3670 ret = ufshcd_query_descriptor_retry(hba, UPIU_QUERY_OPCODE_READ_DESC,
3671 desc_id, desc_index, 0,
3672 desc_buf, &buff_len);
3674 dev_err(hba->dev, "%s: Failed reading descriptor. desc_id %d, desc_index %d, param_offset %d, ret %d\n",
3675 __func__, desc_id, desc_index, param_offset, ret);
3679 /* Update descriptor length */
3680 buff_len = desc_buf[QUERY_DESC_LENGTH_OFFSET];
3682 if (param_offset >= buff_len) {
3683 dev_err(hba->dev, "%s: Invalid offset 0x%x in descriptor IDN 0x%x, length 0x%x\n",
3684 __func__, param_offset, desc_id, buff_len);
3690 if (desc_buf[QUERY_DESC_DESC_TYPE_OFFSET] != desc_id) {
3691 dev_err(hba->dev, "%s: invalid desc_id %d in descriptor header\n",
3692 __func__, desc_buf[QUERY_DESC_DESC_TYPE_OFFSET]);
3698 /* Make sure we don't copy more data than available */
3699 if (param_offset >= buff_len)
3702 memcpy(param_read_buf, &desc_buf[param_offset],
3703 min_t(u32, param_size, buff_len - param_offset));
3712 * struct uc_string_id - unicode string
3714 * @len: size of this descriptor inclusive
3715 * @type: descriptor type
3716 * @uc: unicode string character
3718 struct uc_string_id {
3724 /* replace non-printable or non-ASCII characters with spaces */
3725 static inline char ufshcd_remove_non_printable(u8 ch)
3727 return (ch >= 0x20 && ch <= 0x7e) ? ch : ' ';
3731 * ufshcd_read_string_desc - read string descriptor
3732 * @hba: pointer to adapter instance
3733 * @desc_index: descriptor index
3734 * @buf: pointer to buffer where descriptor would be read,
3735 * the caller should free the memory.
3736 * @ascii: if true convert from unicode to ascii characters
3737 * null terminated string.
3740 * * string size on success.
3741 * * -ENOMEM: on allocation failure
3742 * * -EINVAL: on a wrong parameter
3744 int ufshcd_read_string_desc(struct ufs_hba *hba, u8 desc_index,
3745 u8 **buf, bool ascii)
3747 struct uc_string_id *uc_str;
3754 uc_str = kzalloc(QUERY_DESC_MAX_SIZE, GFP_KERNEL);
3758 ret = ufshcd_read_desc_param(hba, QUERY_DESC_IDN_STRING, desc_index, 0,
3759 (u8 *)uc_str, QUERY_DESC_MAX_SIZE);
3761 dev_err(hba->dev, "Reading String Desc failed after %d retries. err = %d\n",
3762 QUERY_REQ_RETRIES, ret);
3767 if (uc_str->len <= QUERY_DESC_HDR_SIZE) {
3768 dev_dbg(hba->dev, "String Desc is of zero length\n");
3777 /* remove header and divide by 2 to move from UTF16 to UTF8 */
3778 ascii_len = (uc_str->len - QUERY_DESC_HDR_SIZE) / 2 + 1;
3779 str = kzalloc(ascii_len, GFP_KERNEL);
3786 * the descriptor contains string in UTF16 format
3787 * we need to convert to utf-8 so it can be displayed
3789 ret = utf16s_to_utf8s(uc_str->uc,
3790 uc_str->len - QUERY_DESC_HDR_SIZE,
3791 UTF16_BIG_ENDIAN, str, ascii_len - 1);
3793 /* replace non-printable or non-ASCII characters with spaces */
3794 for (i = 0; i < ret; i++)
3795 str[i] = ufshcd_remove_non_printable(str[i]);
3800 str = kmemdup(uc_str, uc_str->len, GFP_KERNEL);
3814 * ufshcd_read_unit_desc_param - read the specified unit descriptor parameter
3815 * @hba: Pointer to adapter instance
3817 * @param_offset: offset of the parameter to read
3818 * @param_read_buf: pointer to buffer where parameter would be read
3819 * @param_size: sizeof(param_read_buf)
3821 * Return: 0 in case of success, non-zero otherwise.
3823 static inline int ufshcd_read_unit_desc_param(struct ufs_hba *hba,
3825 enum unit_desc_param param_offset,
3830 * Unit descriptors are only available for general purpose LUs (LUN id
3831 * from 0 to 7) and RPMB Well known LU.
3833 if (!ufs_is_valid_unit_desc_lun(&hba->dev_info, lun))
3836 return ufshcd_read_desc_param(hba, QUERY_DESC_IDN_UNIT, lun,
3837 param_offset, param_read_buf, param_size);
3840 static int ufshcd_get_ref_clk_gating_wait(struct ufs_hba *hba)
3843 u32 gating_wait = UFSHCD_REF_CLK_GATING_WAIT_US;
3845 if (hba->dev_info.wspecversion >= 0x300) {
3846 err = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
3847 QUERY_ATTR_IDN_REF_CLK_GATING_WAIT_TIME, 0, 0,
3850 dev_err(hba->dev, "Failed reading bRefClkGatingWait. err = %d, use default %uus\n",
3853 if (gating_wait == 0) {
3854 gating_wait = UFSHCD_REF_CLK_GATING_WAIT_US;
3855 dev_err(hba->dev, "Undefined ref clk gating wait time, use default %uus\n",
3859 hba->dev_info.clk_gating_wait_us = gating_wait;
3866 * ufshcd_memory_alloc - allocate memory for host memory space data structures
3867 * @hba: per adapter instance
3869 * 1. Allocate DMA memory for Command Descriptor array
3870 * Each command descriptor consist of Command UPIU, Response UPIU and PRDT
3871 * 2. Allocate DMA memory for UTP Transfer Request Descriptor List (UTRDL).
3872 * 3. Allocate DMA memory for UTP Task Management Request Descriptor List
3874 * 4. Allocate memory for local reference block(lrb).
3876 * Return: 0 for success, non-zero in case of failure.
3878 static int ufshcd_memory_alloc(struct ufs_hba *hba)
3880 size_t utmrdl_size, utrdl_size, ucdl_size;
3882 /* Allocate memory for UTP command descriptors */
3883 ucdl_size = ufshcd_get_ucd_size(hba) * hba->nutrs;
3884 hba->ucdl_base_addr = dmam_alloc_coherent(hba->dev,
3886 &hba->ucdl_dma_addr,
3890 * UFSHCI requires UTP command descriptor to be 128 byte aligned.
3892 if (!hba->ucdl_base_addr ||
3893 WARN_ON(hba->ucdl_dma_addr & (128 - 1))) {
3895 "Command Descriptor Memory allocation failed\n");
3900 * Allocate memory for UTP Transfer descriptors
3901 * UFSHCI requires 1KB alignment of UTRD
3903 utrdl_size = (sizeof(struct utp_transfer_req_desc) * hba->nutrs);
3904 hba->utrdl_base_addr = dmam_alloc_coherent(hba->dev,
3906 &hba->utrdl_dma_addr,
3908 if (!hba->utrdl_base_addr ||
3909 WARN_ON(hba->utrdl_dma_addr & (SZ_1K - 1))) {
3911 "Transfer Descriptor Memory allocation failed\n");
3916 * Skip utmrdl allocation; it may have been
3917 * allocated during first pass and not released during
3918 * MCQ memory allocation.
3919 * See ufshcd_release_sdb_queue() and ufshcd_config_mcq()
3921 if (hba->utmrdl_base_addr)
3924 * Allocate memory for UTP Task Management descriptors
3925 * UFSHCI requires 1KB alignment of UTMRD
3927 utmrdl_size = sizeof(struct utp_task_req_desc) * hba->nutmrs;
3928 hba->utmrdl_base_addr = dmam_alloc_coherent(hba->dev,
3930 &hba->utmrdl_dma_addr,
3932 if (!hba->utmrdl_base_addr ||
3933 WARN_ON(hba->utmrdl_dma_addr & (SZ_1K - 1))) {
3935 "Task Management Descriptor Memory allocation failed\n");
3940 /* Allocate memory for local reference block */
3941 hba->lrb = devm_kcalloc(hba->dev,
3942 hba->nutrs, sizeof(struct ufshcd_lrb),
3945 dev_err(hba->dev, "LRB Memory allocation failed\n");
3954 * ufshcd_host_memory_configure - configure local reference block with
3956 * @hba: per adapter instance
3958 * Configure Host memory space
3959 * 1. Update Corresponding UTRD.UCDBA and UTRD.UCDBAU with UCD DMA
3961 * 2. Update each UTRD with Response UPIU offset, Response UPIU length
3963 * 3. Save the corresponding addresses of UTRD, UCD.CMD, UCD.RSP and UCD.PRDT
3964 * into local reference block.
3966 static void ufshcd_host_memory_configure(struct ufs_hba *hba)
3968 struct utp_transfer_req_desc *utrdlp;
3969 dma_addr_t cmd_desc_dma_addr;
3970 dma_addr_t cmd_desc_element_addr;
3971 u16 response_offset;
3976 utrdlp = hba->utrdl_base_addr;
3979 offsetof(struct utp_transfer_cmd_desc, response_upiu);
3981 offsetof(struct utp_transfer_cmd_desc, prd_table);
3983 cmd_desc_size = ufshcd_get_ucd_size(hba);
3984 cmd_desc_dma_addr = hba->ucdl_dma_addr;
3986 for (i = 0; i < hba->nutrs; i++) {
3987 /* Configure UTRD with command descriptor base address */
3988 cmd_desc_element_addr =
3989 (cmd_desc_dma_addr + (cmd_desc_size * i));
3990 utrdlp[i].command_desc_base_addr =
3991 cpu_to_le64(cmd_desc_element_addr);
3993 /* Response upiu and prdt offset should be in double words */
3994 if (hba->quirks & UFSHCD_QUIRK_PRDT_BYTE_GRAN) {
3995 utrdlp[i].response_upiu_offset =
3996 cpu_to_le16(response_offset);
3997 utrdlp[i].prd_table_offset =
3998 cpu_to_le16(prdt_offset);
3999 utrdlp[i].response_upiu_length =
4000 cpu_to_le16(ALIGNED_UPIU_SIZE);
4002 utrdlp[i].response_upiu_offset =
4003 cpu_to_le16(response_offset >> 2);
4004 utrdlp[i].prd_table_offset =
4005 cpu_to_le16(prdt_offset >> 2);
4006 utrdlp[i].response_upiu_length =
4007 cpu_to_le16(ALIGNED_UPIU_SIZE >> 2);
4010 ufshcd_init_lrb(hba, &hba->lrb[i], i);
4015 * ufshcd_dme_link_startup - Notify Unipro to perform link startup
4016 * @hba: per adapter instance
4018 * UIC_CMD_DME_LINK_STARTUP command must be issued to Unipro layer,
4019 * in order to initialize the Unipro link startup procedure.
4020 * Once the Unipro links are up, the device connected to the controller
4023 * Return: 0 on success, non-zero value on failure.
4025 static int ufshcd_dme_link_startup(struct ufs_hba *hba)
4027 struct uic_command uic_cmd = {0};
4030 uic_cmd.command = UIC_CMD_DME_LINK_STARTUP;
4032 ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
4035 "dme-link-startup: error code %d\n", ret);
4039 * ufshcd_dme_reset - UIC command for DME_RESET
4040 * @hba: per adapter instance
4042 * DME_RESET command is issued in order to reset UniPro stack.
4043 * This function now deals with cold reset.
4045 * Return: 0 on success, non-zero value on failure.
4047 static int ufshcd_dme_reset(struct ufs_hba *hba)
4049 struct uic_command uic_cmd = {0};
4052 uic_cmd.command = UIC_CMD_DME_RESET;
4054 ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
4057 "dme-reset: error code %d\n", ret);
4062 int ufshcd_dme_configure_adapt(struct ufs_hba *hba,
4068 if (agreed_gear < UFS_HS_G4)
4069 adapt_val = PA_NO_ADAPT;
4071 ret = ufshcd_dme_set(hba,
4072 UIC_ARG_MIB(PA_TXHSADAPTTYPE),
4076 EXPORT_SYMBOL_GPL(ufshcd_dme_configure_adapt);
4079 * ufshcd_dme_enable - UIC command for DME_ENABLE
4080 * @hba: per adapter instance
4082 * DME_ENABLE command is issued in order to enable UniPro stack.
4084 * Return: 0 on success, non-zero value on failure.
4086 static int ufshcd_dme_enable(struct ufs_hba *hba)
4088 struct uic_command uic_cmd = {0};
4091 uic_cmd.command = UIC_CMD_DME_ENABLE;
4093 ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
4096 "dme-enable: error code %d\n", ret);
4101 static inline void ufshcd_add_delay_before_dme_cmd(struct ufs_hba *hba)
4103 #define MIN_DELAY_BEFORE_DME_CMDS_US 1000
4104 unsigned long min_sleep_time_us;
4106 if (!(hba->quirks & UFSHCD_QUIRK_DELAY_BEFORE_DME_CMDS))
4110 * last_dme_cmd_tstamp will be 0 only for 1st call to
4113 if (unlikely(!ktime_to_us(hba->last_dme_cmd_tstamp))) {
4114 min_sleep_time_us = MIN_DELAY_BEFORE_DME_CMDS_US;
4116 unsigned long delta =
4117 (unsigned long) ktime_to_us(
4118 ktime_sub(ktime_get(),
4119 hba->last_dme_cmd_tstamp));
4121 if (delta < MIN_DELAY_BEFORE_DME_CMDS_US)
4123 MIN_DELAY_BEFORE_DME_CMDS_US - delta;
4125 return; /* no more delay required */
4128 /* allow sleep for extra 50us if needed */
4129 usleep_range(min_sleep_time_us, min_sleep_time_us + 50);
4133 * ufshcd_dme_set_attr - UIC command for DME_SET, DME_PEER_SET
4134 * @hba: per adapter instance
4135 * @attr_sel: uic command argument1
4136 * @attr_set: attribute set type as uic command argument2
4137 * @mib_val: setting value as uic command argument3
4138 * @peer: indicate whether peer or local
4140 * Return: 0 on success, non-zero value on failure.
4142 int ufshcd_dme_set_attr(struct ufs_hba *hba, u32 attr_sel,
4143 u8 attr_set, u32 mib_val, u8 peer)
4145 struct uic_command uic_cmd = {0};
4146 static const char *const action[] = {
4150 const char *set = action[!!peer];
4152 int retries = UFS_UIC_COMMAND_RETRIES;
4154 uic_cmd.command = peer ?
4155 UIC_CMD_DME_PEER_SET : UIC_CMD_DME_SET;
4156 uic_cmd.argument1 = attr_sel;
4157 uic_cmd.argument2 = UIC_ARG_ATTR_TYPE(attr_set);
4158 uic_cmd.argument3 = mib_val;
4161 /* for peer attributes we retry upon failure */
4162 ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
4164 dev_dbg(hba->dev, "%s: attr-id 0x%x val 0x%x error code %d\n",
4165 set, UIC_GET_ATTR_ID(attr_sel), mib_val, ret);
4166 } while (ret && peer && --retries);
4169 dev_err(hba->dev, "%s: attr-id 0x%x val 0x%x failed %d retries\n",
4170 set, UIC_GET_ATTR_ID(attr_sel), mib_val,
4171 UFS_UIC_COMMAND_RETRIES - retries);
4175 EXPORT_SYMBOL_GPL(ufshcd_dme_set_attr);
4178 * ufshcd_dme_get_attr - UIC command for DME_GET, DME_PEER_GET
4179 * @hba: per adapter instance
4180 * @attr_sel: uic command argument1
4181 * @mib_val: the value of the attribute as returned by the UIC command
4182 * @peer: indicate whether peer or local
4184 * Return: 0 on success, non-zero value on failure.
4186 int ufshcd_dme_get_attr(struct ufs_hba *hba, u32 attr_sel,
4187 u32 *mib_val, u8 peer)
4189 struct uic_command uic_cmd = {0};
4190 static const char *const action[] = {
4194 const char *get = action[!!peer];
4196 int retries = UFS_UIC_COMMAND_RETRIES;
4197 struct ufs_pa_layer_attr orig_pwr_info;
4198 struct ufs_pa_layer_attr temp_pwr_info;
4199 bool pwr_mode_change = false;
4201 if (peer && (hba->quirks & UFSHCD_QUIRK_DME_PEER_ACCESS_AUTO_MODE)) {
4202 orig_pwr_info = hba->pwr_info;
4203 temp_pwr_info = orig_pwr_info;
4205 if (orig_pwr_info.pwr_tx == FAST_MODE ||
4206 orig_pwr_info.pwr_rx == FAST_MODE) {
4207 temp_pwr_info.pwr_tx = FASTAUTO_MODE;
4208 temp_pwr_info.pwr_rx = FASTAUTO_MODE;
4209 pwr_mode_change = true;
4210 } else if (orig_pwr_info.pwr_tx == SLOW_MODE ||
4211 orig_pwr_info.pwr_rx == SLOW_MODE) {
4212 temp_pwr_info.pwr_tx = SLOWAUTO_MODE;
4213 temp_pwr_info.pwr_rx = SLOWAUTO_MODE;
4214 pwr_mode_change = true;
4216 if (pwr_mode_change) {
4217 ret = ufshcd_change_power_mode(hba, &temp_pwr_info);
4223 uic_cmd.command = peer ?
4224 UIC_CMD_DME_PEER_GET : UIC_CMD_DME_GET;
4225 uic_cmd.argument1 = attr_sel;
4228 /* for peer attributes we retry upon failure */
4229 ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
4231 dev_dbg(hba->dev, "%s: attr-id 0x%x error code %d\n",
4232 get, UIC_GET_ATTR_ID(attr_sel), ret);
4233 } while (ret && peer && --retries);
4236 dev_err(hba->dev, "%s: attr-id 0x%x failed %d retries\n",
4237 get, UIC_GET_ATTR_ID(attr_sel),
4238 UFS_UIC_COMMAND_RETRIES - retries);
4240 if (mib_val && !ret)
4241 *mib_val = uic_cmd.argument3;
4243 if (peer && (hba->quirks & UFSHCD_QUIRK_DME_PEER_ACCESS_AUTO_MODE)
4245 ufshcd_change_power_mode(hba, &orig_pwr_info);
4249 EXPORT_SYMBOL_GPL(ufshcd_dme_get_attr);
4252 * ufshcd_uic_pwr_ctrl - executes UIC commands (which affects the link power
4253 * state) and waits for it to take effect.
4255 * @hba: per adapter instance
4256 * @cmd: UIC command to execute
4258 * DME operations like DME_SET(PA_PWRMODE), DME_HIBERNATE_ENTER &
4259 * DME_HIBERNATE_EXIT commands take some time to take its effect on both host
4260 * and device UniPro link and hence it's final completion would be indicated by
4261 * dedicated status bits in Interrupt Status register (UPMS, UHES, UHXS) in
4262 * addition to normal UIC command completion Status (UCCS). This function only
4263 * returns after the relevant status bits indicate the completion.
4265 * Return: 0 on success, non-zero value on failure.
4267 static int ufshcd_uic_pwr_ctrl(struct ufs_hba *hba, struct uic_command *cmd)
4269 DECLARE_COMPLETION_ONSTACK(uic_async_done);
4270 unsigned long flags;
4273 bool reenable_intr = false;
4275 mutex_lock(&hba->uic_cmd_mutex);
4276 ufshcd_add_delay_before_dme_cmd(hba);
4278 spin_lock_irqsave(hba->host->host_lock, flags);
4279 if (ufshcd_is_link_broken(hba)) {
4283 hba->uic_async_done = &uic_async_done;
4284 if (ufshcd_readl(hba, REG_INTERRUPT_ENABLE) & UIC_COMMAND_COMPL) {
4285 ufshcd_disable_intr(hba, UIC_COMMAND_COMPL);
4287 * Make sure UIC command completion interrupt is disabled before
4288 * issuing UIC command.
4291 reenable_intr = true;
4293 spin_unlock_irqrestore(hba->host->host_lock, flags);
4294 ret = __ufshcd_send_uic_cmd(hba, cmd, false);
4297 "pwr ctrl cmd 0x%x with mode 0x%x uic error %d\n",
4298 cmd->command, cmd->argument3, ret);
4302 if (!wait_for_completion_timeout(hba->uic_async_done,
4303 msecs_to_jiffies(UIC_CMD_TIMEOUT))) {
4305 "pwr ctrl cmd 0x%x with mode 0x%x completion timeout\n",
4306 cmd->command, cmd->argument3);
4308 if (!cmd->cmd_active) {
4309 dev_err(hba->dev, "%s: Power Mode Change operation has been completed, go check UPMCRS\n",
4319 status = ufshcd_get_upmcrs(hba);
4320 if (status != PWR_LOCAL) {
4322 "pwr ctrl cmd 0x%x failed, host upmcrs:0x%x\n",
4323 cmd->command, status);
4324 ret = (status != PWR_OK) ? status : -1;
4328 ufshcd_print_host_state(hba);
4329 ufshcd_print_pwr_info(hba);
4330 ufshcd_print_evt_hist(hba);
4333 spin_lock_irqsave(hba->host->host_lock, flags);
4334 hba->active_uic_cmd = NULL;
4335 hba->uic_async_done = NULL;
4337 ufshcd_enable_intr(hba, UIC_COMMAND_COMPL);
4339 ufshcd_set_link_broken(hba);
4340 ufshcd_schedule_eh_work(hba);
4343 spin_unlock_irqrestore(hba->host->host_lock, flags);
4344 mutex_unlock(&hba->uic_cmd_mutex);
4350 * ufshcd_uic_change_pwr_mode - Perform the UIC power mode chage
4351 * using DME_SET primitives.
4352 * @hba: per adapter instance
4353 * @mode: powr mode value
4355 * Return: 0 on success, non-zero value on failure.
4357 int ufshcd_uic_change_pwr_mode(struct ufs_hba *hba, u8 mode)
4359 struct uic_command uic_cmd = {0};
4362 if (hba->quirks & UFSHCD_QUIRK_BROKEN_PA_RXHSUNTERMCAP) {
4363 ret = ufshcd_dme_set(hba,
4364 UIC_ARG_MIB_SEL(PA_RXHSUNTERMCAP, 0), 1);
4366 dev_err(hba->dev, "%s: failed to enable PA_RXHSUNTERMCAP ret %d\n",
4372 uic_cmd.command = UIC_CMD_DME_SET;
4373 uic_cmd.argument1 = UIC_ARG_MIB(PA_PWRMODE);
4374 uic_cmd.argument3 = mode;
4376 ret = ufshcd_uic_pwr_ctrl(hba, &uic_cmd);
4377 ufshcd_release(hba);
4382 EXPORT_SYMBOL_GPL(ufshcd_uic_change_pwr_mode);
4384 int ufshcd_link_recovery(struct ufs_hba *hba)
4387 unsigned long flags;
4389 spin_lock_irqsave(hba->host->host_lock, flags);
4390 hba->ufshcd_state = UFSHCD_STATE_RESET;
4391 ufshcd_set_eh_in_progress(hba);
4392 spin_unlock_irqrestore(hba->host->host_lock, flags);
4394 /* Reset the attached device */
4395 ufshcd_device_reset(hba);
4397 ret = ufshcd_host_reset_and_restore(hba);
4399 spin_lock_irqsave(hba->host->host_lock, flags);
4401 hba->ufshcd_state = UFSHCD_STATE_ERROR;
4402 ufshcd_clear_eh_in_progress(hba);
4403 spin_unlock_irqrestore(hba->host->host_lock, flags);
4406 dev_err(hba->dev, "%s: link recovery failed, err %d",
4411 EXPORT_SYMBOL_GPL(ufshcd_link_recovery);
4413 int ufshcd_uic_hibern8_enter(struct ufs_hba *hba)
4416 struct uic_command uic_cmd = {0};
4417 ktime_t start = ktime_get();
4419 ufshcd_vops_hibern8_notify(hba, UIC_CMD_DME_HIBER_ENTER, PRE_CHANGE);
4421 uic_cmd.command = UIC_CMD_DME_HIBER_ENTER;
4422 ret = ufshcd_uic_pwr_ctrl(hba, &uic_cmd);
4423 trace_ufshcd_profile_hibern8(dev_name(hba->dev), "enter",
4424 ktime_to_us(ktime_sub(ktime_get(), start)), ret);
4427 dev_err(hba->dev, "%s: hibern8 enter failed. ret = %d\n",
4430 ufshcd_vops_hibern8_notify(hba, UIC_CMD_DME_HIBER_ENTER,
4435 EXPORT_SYMBOL_GPL(ufshcd_uic_hibern8_enter);
4437 int ufshcd_uic_hibern8_exit(struct ufs_hba *hba)
4439 struct uic_command uic_cmd = {0};
4441 ktime_t start = ktime_get();
4443 ufshcd_vops_hibern8_notify(hba, UIC_CMD_DME_HIBER_EXIT, PRE_CHANGE);
4445 uic_cmd.command = UIC_CMD_DME_HIBER_EXIT;
4446 ret = ufshcd_uic_pwr_ctrl(hba, &uic_cmd);
4447 trace_ufshcd_profile_hibern8(dev_name(hba->dev), "exit",
4448 ktime_to_us(ktime_sub(ktime_get(), start)), ret);
4451 dev_err(hba->dev, "%s: hibern8 exit failed. ret = %d\n",
4454 ufshcd_vops_hibern8_notify(hba, UIC_CMD_DME_HIBER_EXIT,
4456 hba->ufs_stats.last_hibern8_exit_tstamp = local_clock();
4457 hba->ufs_stats.hibern8_exit_cnt++;
4462 EXPORT_SYMBOL_GPL(ufshcd_uic_hibern8_exit);
4464 static void ufshcd_configure_auto_hibern8(struct ufs_hba *hba)
4466 if (!ufshcd_is_auto_hibern8_supported(hba))
4469 ufshcd_writel(hba, hba->ahit, REG_AUTO_HIBERNATE_IDLE_TIMER);
4472 void ufshcd_auto_hibern8_update(struct ufs_hba *hba, u32 ahit)
4474 const u32 cur_ahit = READ_ONCE(hba->ahit);
4476 if (!ufshcd_is_auto_hibern8_supported(hba) || cur_ahit == ahit)
4479 WRITE_ONCE(hba->ahit, ahit);
4480 if (!pm_runtime_suspended(&hba->ufs_device_wlun->sdev_gendev)) {
4481 ufshcd_rpm_get_sync(hba);
4483 ufshcd_configure_auto_hibern8(hba);
4484 ufshcd_release(hba);
4485 ufshcd_rpm_put_sync(hba);
4488 EXPORT_SYMBOL_GPL(ufshcd_auto_hibern8_update);
4491 * ufshcd_init_pwr_info - setting the POR (power on reset)
4492 * values in hba power info
4493 * @hba: per-adapter instance
4495 static void ufshcd_init_pwr_info(struct ufs_hba *hba)
4497 hba->pwr_info.gear_rx = UFS_PWM_G1;
4498 hba->pwr_info.gear_tx = UFS_PWM_G1;
4499 hba->pwr_info.lane_rx = UFS_LANE_1;
4500 hba->pwr_info.lane_tx = UFS_LANE_1;
4501 hba->pwr_info.pwr_rx = SLOWAUTO_MODE;
4502 hba->pwr_info.pwr_tx = SLOWAUTO_MODE;
4503 hba->pwr_info.hs_rate = 0;
4507 * ufshcd_get_max_pwr_mode - reads the max power mode negotiated with device
4508 * @hba: per-adapter instance
4510 * Return: 0 upon success; < 0 upon failure.
4512 static int ufshcd_get_max_pwr_mode(struct ufs_hba *hba)
4514 struct ufs_pa_layer_attr *pwr_info = &hba->max_pwr_info.info;
4516 if (hba->max_pwr_info.is_valid)
4519 if (hba->quirks & UFSHCD_QUIRK_HIBERN_FASTAUTO) {
4520 pwr_info->pwr_tx = FASTAUTO_MODE;
4521 pwr_info->pwr_rx = FASTAUTO_MODE;
4523 pwr_info->pwr_tx = FAST_MODE;
4524 pwr_info->pwr_rx = FAST_MODE;
4526 pwr_info->hs_rate = PA_HS_MODE_B;
4528 /* Get the connected lane count */
4529 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_CONNECTEDRXDATALANES),
4530 &pwr_info->lane_rx);
4531 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_CONNECTEDTXDATALANES),
4532 &pwr_info->lane_tx);
4534 if (!pwr_info->lane_rx || !pwr_info->lane_tx) {
4535 dev_err(hba->dev, "%s: invalid connected lanes value. rx=%d, tx=%d\n",
4543 * First, get the maximum gears of HS speed.
4544 * If a zero value, it means there is no HSGEAR capability.
4545 * Then, get the maximum gears of PWM speed.
4547 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_MAXRXHSGEAR), &pwr_info->gear_rx);
4548 if (!pwr_info->gear_rx) {
4549 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_MAXRXPWMGEAR),
4550 &pwr_info->gear_rx);
4551 if (!pwr_info->gear_rx) {
4552 dev_err(hba->dev, "%s: invalid max pwm rx gear read = %d\n",
4553 __func__, pwr_info->gear_rx);
4556 pwr_info->pwr_rx = SLOW_MODE;
4559 ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_MAXRXHSGEAR),
4560 &pwr_info->gear_tx);
4561 if (!pwr_info->gear_tx) {
4562 ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_MAXRXPWMGEAR),
4563 &pwr_info->gear_tx);
4564 if (!pwr_info->gear_tx) {
4565 dev_err(hba->dev, "%s: invalid max pwm tx gear read = %d\n",
4566 __func__, pwr_info->gear_tx);
4569 pwr_info->pwr_tx = SLOW_MODE;
4572 hba->max_pwr_info.is_valid = true;
4576 static int ufshcd_change_power_mode(struct ufs_hba *hba,
4577 struct ufs_pa_layer_attr *pwr_mode)
4581 /* if already configured to the requested pwr_mode */
4582 if (!hba->force_pmc &&
4583 pwr_mode->gear_rx == hba->pwr_info.gear_rx &&
4584 pwr_mode->gear_tx == hba->pwr_info.gear_tx &&
4585 pwr_mode->lane_rx == hba->pwr_info.lane_rx &&
4586 pwr_mode->lane_tx == hba->pwr_info.lane_tx &&
4587 pwr_mode->pwr_rx == hba->pwr_info.pwr_rx &&
4588 pwr_mode->pwr_tx == hba->pwr_info.pwr_tx &&
4589 pwr_mode->hs_rate == hba->pwr_info.hs_rate) {
4590 dev_dbg(hba->dev, "%s: power already configured\n", __func__);
4595 * Configure attributes for power mode change with below.
4596 * - PA_RXGEAR, PA_ACTIVERXDATALANES, PA_RXTERMINATION,
4597 * - PA_TXGEAR, PA_ACTIVETXDATALANES, PA_TXTERMINATION,
4600 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_RXGEAR), pwr_mode->gear_rx);
4601 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_ACTIVERXDATALANES),
4603 if (pwr_mode->pwr_rx == FASTAUTO_MODE ||
4604 pwr_mode->pwr_rx == FAST_MODE)
4605 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_RXTERMINATION), true);
4607 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_RXTERMINATION), false);
4609 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TXGEAR), pwr_mode->gear_tx);
4610 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_ACTIVETXDATALANES),
4612 if (pwr_mode->pwr_tx == FASTAUTO_MODE ||
4613 pwr_mode->pwr_tx == FAST_MODE)
4614 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TXTERMINATION), true);
4616 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TXTERMINATION), false);
4618 if (pwr_mode->pwr_rx == FASTAUTO_MODE ||
4619 pwr_mode->pwr_tx == FASTAUTO_MODE ||
4620 pwr_mode->pwr_rx == FAST_MODE ||
4621 pwr_mode->pwr_tx == FAST_MODE)
4622 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_HSSERIES),
4625 if (!(hba->quirks & UFSHCD_QUIRK_SKIP_DEF_UNIPRO_TIMEOUT_SETTING)) {
4626 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_PWRMODEUSERDATA0),
4627 DL_FC0ProtectionTimeOutVal_Default);
4628 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_PWRMODEUSERDATA1),
4629 DL_TC0ReplayTimeOutVal_Default);
4630 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_PWRMODEUSERDATA2),
4631 DL_AFC0ReqTimeOutVal_Default);
4632 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_PWRMODEUSERDATA3),
4633 DL_FC1ProtectionTimeOutVal_Default);
4634 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_PWRMODEUSERDATA4),
4635 DL_TC1ReplayTimeOutVal_Default);
4636 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_PWRMODEUSERDATA5),
4637 DL_AFC1ReqTimeOutVal_Default);
4639 ufshcd_dme_set(hba, UIC_ARG_MIB(DME_LocalFC0ProtectionTimeOutVal),
4640 DL_FC0ProtectionTimeOutVal_Default);
4641 ufshcd_dme_set(hba, UIC_ARG_MIB(DME_LocalTC0ReplayTimeOutVal),
4642 DL_TC0ReplayTimeOutVal_Default);
4643 ufshcd_dme_set(hba, UIC_ARG_MIB(DME_LocalAFC0ReqTimeOutVal),
4644 DL_AFC0ReqTimeOutVal_Default);
4647 ret = ufshcd_uic_change_pwr_mode(hba, pwr_mode->pwr_rx << 4
4648 | pwr_mode->pwr_tx);
4652 "%s: power mode change failed %d\n", __func__, ret);
4654 ufshcd_vops_pwr_change_notify(hba, POST_CHANGE, NULL,
4657 memcpy(&hba->pwr_info, pwr_mode,
4658 sizeof(struct ufs_pa_layer_attr));
4665 * ufshcd_config_pwr_mode - configure a new power mode
4666 * @hba: per-adapter instance
4667 * @desired_pwr_mode: desired power configuration
4669 * Return: 0 upon success; < 0 upon failure.
4671 int ufshcd_config_pwr_mode(struct ufs_hba *hba,
4672 struct ufs_pa_layer_attr *desired_pwr_mode)
4674 struct ufs_pa_layer_attr final_params = { 0 };
4677 ret = ufshcd_vops_pwr_change_notify(hba, PRE_CHANGE,
4678 desired_pwr_mode, &final_params);
4681 memcpy(&final_params, desired_pwr_mode, sizeof(final_params));
4683 ret = ufshcd_change_power_mode(hba, &final_params);
4687 EXPORT_SYMBOL_GPL(ufshcd_config_pwr_mode);
4690 * ufshcd_complete_dev_init() - checks device readiness
4691 * @hba: per-adapter instance
4693 * Set fDeviceInit flag and poll until device toggles it.
4695 * Return: 0 upon success; < 0 upon failure.
4697 static int ufshcd_complete_dev_init(struct ufs_hba *hba)
4700 bool flag_res = true;
4703 err = ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_SET_FLAG,
4704 QUERY_FLAG_IDN_FDEVICEINIT, 0, NULL);
4707 "%s: setting fDeviceInit flag failed with error %d\n",
4712 /* Poll fDeviceInit flag to be cleared */
4713 timeout = ktime_add_ms(ktime_get(), FDEVICEINIT_COMPL_TIMEOUT);
4715 err = ufshcd_query_flag(hba, UPIU_QUERY_OPCODE_READ_FLAG,
4716 QUERY_FLAG_IDN_FDEVICEINIT, 0, &flag_res);
4719 usleep_range(500, 1000);
4720 } while (ktime_before(ktime_get(), timeout));
4724 "%s: reading fDeviceInit flag failed with error %d\n",
4726 } else if (flag_res) {
4728 "%s: fDeviceInit was not cleared by the device\n",
4737 * ufshcd_make_hba_operational - Make UFS controller operational
4738 * @hba: per adapter instance
4740 * To bring UFS host controller to operational state,
4741 * 1. Enable required interrupts
4742 * 2. Configure interrupt aggregation
4743 * 3. Program UTRL and UTMRL base address
4744 * 4. Configure run-stop-registers
4746 * Return: 0 on success, non-zero value on failure.
4748 int ufshcd_make_hba_operational(struct ufs_hba *hba)
4753 /* Enable required interrupts */
4754 ufshcd_enable_intr(hba, UFSHCD_ENABLE_INTRS);
4756 /* Configure interrupt aggregation */
4757 if (ufshcd_is_intr_aggr_allowed(hba))
4758 ufshcd_config_intr_aggr(hba, hba->nutrs - 1, INT_AGGR_DEF_TO);
4760 ufshcd_disable_intr_aggr(hba);
4762 /* Configure UTRL and UTMRL base address registers */
4763 ufshcd_writel(hba, lower_32_bits(hba->utrdl_dma_addr),
4764 REG_UTP_TRANSFER_REQ_LIST_BASE_L);
4765 ufshcd_writel(hba, upper_32_bits(hba->utrdl_dma_addr),
4766 REG_UTP_TRANSFER_REQ_LIST_BASE_H);
4767 ufshcd_writel(hba, lower_32_bits(hba->utmrdl_dma_addr),
4768 REG_UTP_TASK_REQ_LIST_BASE_L);
4769 ufshcd_writel(hba, upper_32_bits(hba->utmrdl_dma_addr),
4770 REG_UTP_TASK_REQ_LIST_BASE_H);
4773 * Make sure base address and interrupt setup are updated before
4774 * enabling the run/stop registers below.
4779 * UCRDY, UTMRLDY and UTRLRDY bits must be 1
4781 reg = ufshcd_readl(hba, REG_CONTROLLER_STATUS);
4782 if (!(ufshcd_get_lists_status(reg))) {
4783 ufshcd_enable_run_stop_reg(hba);
4786 "Host controller not ready to process requests");
4792 EXPORT_SYMBOL_GPL(ufshcd_make_hba_operational);
4795 * ufshcd_hba_stop - Send controller to reset state
4796 * @hba: per adapter instance
4798 void ufshcd_hba_stop(struct ufs_hba *hba)
4800 unsigned long flags;
4804 * Obtain the host lock to prevent that the controller is disabled
4805 * while the UFS interrupt handler is active on another CPU.
4807 spin_lock_irqsave(hba->host->host_lock, flags);
4808 ufshcd_writel(hba, CONTROLLER_DISABLE, REG_CONTROLLER_ENABLE);
4809 spin_unlock_irqrestore(hba->host->host_lock, flags);
4811 err = ufshcd_wait_for_register(hba, REG_CONTROLLER_ENABLE,
4812 CONTROLLER_ENABLE, CONTROLLER_DISABLE,
4815 dev_err(hba->dev, "%s: Controller disable failed\n", __func__);
4817 EXPORT_SYMBOL_GPL(ufshcd_hba_stop);
4820 * ufshcd_hba_execute_hce - initialize the controller
4821 * @hba: per adapter instance
4823 * The controller resets itself and controller firmware initialization
4824 * sequence kicks off. When controller is ready it will set
4825 * the Host Controller Enable bit to 1.
4827 * Return: 0 on success, non-zero value on failure.
4829 static int ufshcd_hba_execute_hce(struct ufs_hba *hba)
4831 int retry_outer = 3;
4835 if (ufshcd_is_hba_active(hba))
4836 /* change controller state to "reset state" */
4837 ufshcd_hba_stop(hba);
4839 /* UniPro link is disabled at this point */
4840 ufshcd_set_link_off(hba);
4842 ufshcd_vops_hce_enable_notify(hba, PRE_CHANGE);
4844 /* start controller initialization sequence */
4845 ufshcd_hba_start(hba);
4848 * To initialize a UFS host controller HCE bit must be set to 1.
4849 * During initialization the HCE bit value changes from 1->0->1.
4850 * When the host controller completes initialization sequence
4851 * it sets the value of HCE bit to 1. The same HCE bit is read back
4852 * to check if the controller has completed initialization sequence.
4853 * So without this delay the value HCE = 1, set in the previous
4854 * instruction might be read back.
4855 * This delay can be changed based on the controller.
4857 ufshcd_delay_us(hba->vps->hba_enable_delay_us, 100);
4859 /* wait for the host controller to complete initialization */
4861 while (!ufshcd_is_hba_active(hba)) {
4866 "Controller enable failed\n");
4873 usleep_range(1000, 1100);
4876 /* enable UIC related interrupts */
4877 ufshcd_enable_intr(hba, UFSHCD_UIC_MASK);
4879 ufshcd_vops_hce_enable_notify(hba, POST_CHANGE);
4884 int ufshcd_hba_enable(struct ufs_hba *hba)
4888 if (hba->quirks & UFSHCI_QUIRK_BROKEN_HCE) {
4889 ufshcd_set_link_off(hba);
4890 ufshcd_vops_hce_enable_notify(hba, PRE_CHANGE);
4892 /* enable UIC related interrupts */
4893 ufshcd_enable_intr(hba, UFSHCD_UIC_MASK);
4894 ret = ufshcd_dme_reset(hba);
4896 dev_err(hba->dev, "DME_RESET failed\n");
4900 ret = ufshcd_dme_enable(hba);
4902 dev_err(hba->dev, "Enabling DME failed\n");
4906 ufshcd_vops_hce_enable_notify(hba, POST_CHANGE);
4908 ret = ufshcd_hba_execute_hce(hba);
4913 EXPORT_SYMBOL_GPL(ufshcd_hba_enable);
4915 static int ufshcd_disable_tx_lcc(struct ufs_hba *hba, bool peer)
4917 int tx_lanes = 0, i, err = 0;
4920 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_CONNECTEDTXDATALANES),
4923 ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_CONNECTEDTXDATALANES),
4925 for (i = 0; i < tx_lanes; i++) {
4927 err = ufshcd_dme_set(hba,
4928 UIC_ARG_MIB_SEL(TX_LCC_ENABLE,
4929 UIC_ARG_MPHY_TX_GEN_SEL_INDEX(i)),
4932 err = ufshcd_dme_peer_set(hba,
4933 UIC_ARG_MIB_SEL(TX_LCC_ENABLE,
4934 UIC_ARG_MPHY_TX_GEN_SEL_INDEX(i)),
4937 dev_err(hba->dev, "%s: TX LCC Disable failed, peer = %d, lane = %d, err = %d",
4938 __func__, peer, i, err);
4946 static inline int ufshcd_disable_device_tx_lcc(struct ufs_hba *hba)
4948 return ufshcd_disable_tx_lcc(hba, true);
4951 void ufshcd_update_evt_hist(struct ufs_hba *hba, u32 id, u32 val)
4953 struct ufs_event_hist *e;
4955 if (id >= UFS_EVT_CNT)
4958 e = &hba->ufs_stats.event[id];
4959 e->val[e->pos] = val;
4960 e->tstamp[e->pos] = local_clock();
4962 e->pos = (e->pos + 1) % UFS_EVENT_HIST_LENGTH;
4964 ufshcd_vops_event_notify(hba, id, &val);
4966 EXPORT_SYMBOL_GPL(ufshcd_update_evt_hist);
4969 * ufshcd_link_startup - Initialize unipro link startup
4970 * @hba: per adapter instance
4972 * Return: 0 for success, non-zero in case of failure.
4974 static int ufshcd_link_startup(struct ufs_hba *hba)
4977 int retries = DME_LINKSTARTUP_RETRIES;
4978 bool link_startup_again = false;
4981 * If UFS device isn't active then we will have to issue link startup
4982 * 2 times to make sure the device state move to active.
4984 if (!ufshcd_is_ufs_dev_active(hba))
4985 link_startup_again = true;
4989 ufshcd_vops_link_startup_notify(hba, PRE_CHANGE);
4991 ret = ufshcd_dme_link_startup(hba);
4993 /* check if device is detected by inter-connect layer */
4994 if (!ret && !ufshcd_is_device_present(hba)) {
4995 ufshcd_update_evt_hist(hba,
4996 UFS_EVT_LINK_STARTUP_FAIL,
4998 dev_err(hba->dev, "%s: Device not present\n", __func__);
5004 * DME link lost indication is only received when link is up,
5005 * but we can't be sure if the link is up until link startup
5006 * succeeds. So reset the local Uni-Pro and try again.
5008 if (ret && retries && ufshcd_hba_enable(hba)) {
5009 ufshcd_update_evt_hist(hba,
5010 UFS_EVT_LINK_STARTUP_FAIL,
5014 } while (ret && retries--);
5017 /* failed to get the link up... retire */
5018 ufshcd_update_evt_hist(hba,
5019 UFS_EVT_LINK_STARTUP_FAIL,
5024 if (link_startup_again) {
5025 link_startup_again = false;
5026 retries = DME_LINKSTARTUP_RETRIES;
5030 /* Mark that link is up in PWM-G1, 1-lane, SLOW-AUTO mode */
5031 ufshcd_init_pwr_info(hba);
5032 ufshcd_print_pwr_info(hba);
5034 if (hba->quirks & UFSHCD_QUIRK_BROKEN_LCC) {
5035 ret = ufshcd_disable_device_tx_lcc(hba);
5040 /* Include any host controller configuration via UIC commands */
5041 ret = ufshcd_vops_link_startup_notify(hba, POST_CHANGE);
5045 /* Clear UECPA once due to LINERESET has happened during LINK_STARTUP */
5046 ufshcd_readl(hba, REG_UIC_ERROR_CODE_PHY_ADAPTER_LAYER);
5047 ret = ufshcd_make_hba_operational(hba);
5050 dev_err(hba->dev, "link startup failed %d\n", ret);
5051 ufshcd_print_host_state(hba);
5052 ufshcd_print_pwr_info(hba);
5053 ufshcd_print_evt_hist(hba);
5059 * ufshcd_verify_dev_init() - Verify device initialization
5060 * @hba: per-adapter instance
5062 * Send NOP OUT UPIU and wait for NOP IN response to check whether the
5063 * device Transport Protocol (UTP) layer is ready after a reset.
5064 * If the UTP layer at the device side is not initialized, it may
5065 * not respond with NOP IN UPIU within timeout of %NOP_OUT_TIMEOUT
5066 * and we retry sending NOP OUT for %NOP_OUT_RETRIES iterations.
5068 * Return: 0 upon success; < 0 upon failure.
5070 static int ufshcd_verify_dev_init(struct ufs_hba *hba)
5076 mutex_lock(&hba->dev_cmd.lock);
5077 for (retries = NOP_OUT_RETRIES; retries > 0; retries--) {
5078 err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_NOP,
5079 hba->nop_out_timeout);
5081 if (!err || err == -ETIMEDOUT)
5084 dev_dbg(hba->dev, "%s: error %d retrying\n", __func__, err);
5086 mutex_unlock(&hba->dev_cmd.lock);
5087 ufshcd_release(hba);
5090 dev_err(hba->dev, "%s: NOP OUT failed %d\n", __func__, err);
5095 * ufshcd_setup_links - associate link b/w device wlun and other luns
5096 * @sdev: pointer to SCSI device
5097 * @hba: pointer to ufs hba
5099 static void ufshcd_setup_links(struct ufs_hba *hba, struct scsi_device *sdev)
5101 struct device_link *link;
5104 * Device wlun is the supplier & rest of the luns are consumers.
5105 * This ensures that device wlun suspends after all other luns.
5107 if (hba->ufs_device_wlun) {
5108 link = device_link_add(&sdev->sdev_gendev,
5109 &hba->ufs_device_wlun->sdev_gendev,
5110 DL_FLAG_PM_RUNTIME | DL_FLAG_RPM_ACTIVE);
5112 dev_err(&sdev->sdev_gendev, "Failed establishing link - %s\n",
5113 dev_name(&hba->ufs_device_wlun->sdev_gendev));
5117 /* Ignore REPORT_LUN wlun probing */
5118 if (hba->luns_avail == 1) {
5119 ufshcd_rpm_put(hba);
5124 * Device wlun is probed. The assumption is that WLUNs are
5125 * scanned before other LUNs.
5132 * ufshcd_lu_init - Initialize the relevant parameters of the LU
5133 * @hba: per-adapter instance
5134 * @sdev: pointer to SCSI device
5136 static void ufshcd_lu_init(struct ufs_hba *hba, struct scsi_device *sdev)
5138 int len = QUERY_DESC_MAX_SIZE;
5139 u8 lun = ufshcd_scsi_to_upiu_lun(sdev->lun);
5140 u8 lun_qdepth = hba->nutrs;
5144 desc_buf = kzalloc(len, GFP_KERNEL);
5148 ret = ufshcd_read_unit_desc_param(hba, lun, 0, desc_buf, len);
5150 if (ret == -EOPNOTSUPP)
5151 /* If LU doesn't support unit descriptor, its queue depth is set to 1 */
5157 if (desc_buf[UNIT_DESC_PARAM_LU_Q_DEPTH]) {
5159 * In per-LU queueing architecture, bLUQueueDepth will not be 0, then we will
5160 * use the smaller between UFSHCI CAP.NUTRS and UFS LU bLUQueueDepth
5162 lun_qdepth = min_t(int, desc_buf[UNIT_DESC_PARAM_LU_Q_DEPTH], hba->nutrs);
5165 * According to UFS device specification, the write protection mode is only supported by
5166 * normal LU, not supported by WLUN.
5168 if (hba->dev_info.f_power_on_wp_en && lun < hba->dev_info.max_lu_supported &&
5169 !hba->dev_info.is_lu_power_on_wp &&
5170 desc_buf[UNIT_DESC_PARAM_LU_WR_PROTECT] == UFS_LU_POWER_ON_WP)
5171 hba->dev_info.is_lu_power_on_wp = true;
5173 /* In case of RPMB LU, check if advanced RPMB mode is enabled */
5174 if (desc_buf[UNIT_DESC_PARAM_UNIT_INDEX] == UFS_UPIU_RPMB_WLUN &&
5175 desc_buf[RPMB_UNIT_DESC_PARAM_REGION_EN] & BIT(4))
5176 hba->dev_info.b_advanced_rpmb_en = true;
5182 * For WLUNs that don't support unit descriptor, queue depth is set to 1. For LUs whose
5183 * bLUQueueDepth == 0, the queue depth is set to a maximum value that host can queue.
5185 dev_dbg(hba->dev, "Set LU %x queue depth %d\n", lun, lun_qdepth);
5186 scsi_change_queue_depth(sdev, lun_qdepth);
5190 * ufshcd_slave_alloc - handle initial SCSI device configurations
5191 * @sdev: pointer to SCSI device
5195 static int ufshcd_slave_alloc(struct scsi_device *sdev)
5197 struct ufs_hba *hba;
5199 hba = shost_priv(sdev->host);
5201 /* Mode sense(6) is not supported by UFS, so use Mode sense(10) */
5202 sdev->use_10_for_ms = 1;
5204 /* DBD field should be set to 1 in mode sense(10) */
5205 sdev->set_dbd_for_ms = 1;
5207 /* allow SCSI layer to restart the device in case of errors */
5208 sdev->allow_restart = 1;
5210 /* REPORT SUPPORTED OPERATION CODES is not supported */
5211 sdev->no_report_opcodes = 1;
5213 /* WRITE_SAME command is not supported */
5214 sdev->no_write_same = 1;
5216 ufshcd_lu_init(hba, sdev);
5218 ufshcd_setup_links(hba, sdev);
5224 * ufshcd_change_queue_depth - change queue depth
5225 * @sdev: pointer to SCSI device
5226 * @depth: required depth to set
5228 * Change queue depth and make sure the max. limits are not crossed.
5230 * Return: new queue depth.
5232 static int ufshcd_change_queue_depth(struct scsi_device *sdev, int depth)
5234 return scsi_change_queue_depth(sdev, min(depth, sdev->host->can_queue));
5238 * ufshcd_slave_configure - adjust SCSI device configurations
5239 * @sdev: pointer to SCSI device
5241 * Return: 0 (success).
5243 static int ufshcd_slave_configure(struct scsi_device *sdev)
5245 struct ufs_hba *hba = shost_priv(sdev->host);
5246 struct request_queue *q = sdev->request_queue;
5248 blk_queue_update_dma_pad(q, PRDT_DATA_BYTE_COUNT_PAD - 1);
5251 * Block runtime-pm until all consumers are added.
5252 * Refer ufshcd_setup_links().
5254 if (is_device_wlun(sdev))
5255 pm_runtime_get_noresume(&sdev->sdev_gendev);
5256 else if (ufshcd_is_rpm_autosuspend_allowed(hba))
5257 sdev->rpm_autosuspend = 1;
5259 * Do not print messages during runtime PM to avoid never-ending cycles
5260 * of messages written back to storage by user space causing runtime
5261 * resume, causing more messages and so on.
5263 sdev->silence_suspend = 1;
5265 if (hba->vops && hba->vops->config_scsi_dev)
5266 hba->vops->config_scsi_dev(sdev);
5268 ufshcd_crypto_register(hba, q);
5274 * ufshcd_slave_destroy - remove SCSI device configurations
5275 * @sdev: pointer to SCSI device
5277 static void ufshcd_slave_destroy(struct scsi_device *sdev)
5279 struct ufs_hba *hba;
5280 unsigned long flags;
5282 hba = shost_priv(sdev->host);
5284 /* Drop the reference as it won't be needed anymore */
5285 if (ufshcd_scsi_to_upiu_lun(sdev->lun) == UFS_UPIU_UFS_DEVICE_WLUN) {
5286 spin_lock_irqsave(hba->host->host_lock, flags);
5287 hba->ufs_device_wlun = NULL;
5288 spin_unlock_irqrestore(hba->host->host_lock, flags);
5289 } else if (hba->ufs_device_wlun) {
5290 struct device *supplier = NULL;
5292 /* Ensure UFS Device WLUN exists and does not disappear */
5293 spin_lock_irqsave(hba->host->host_lock, flags);
5294 if (hba->ufs_device_wlun) {
5295 supplier = &hba->ufs_device_wlun->sdev_gendev;
5296 get_device(supplier);
5298 spin_unlock_irqrestore(hba->host->host_lock, flags);
5302 * If a LUN fails to probe (e.g. absent BOOT WLUN), the
5303 * device will not have been registered but can still
5304 * have a device link holding a reference to the device.
5306 device_link_remove(&sdev->sdev_gendev, supplier);
5307 put_device(supplier);
5313 * ufshcd_scsi_cmd_status - Update SCSI command result based on SCSI status
5314 * @lrbp: pointer to local reference block of completed command
5315 * @scsi_status: SCSI command status
5317 * Return: value base on SCSI command status.
5320 ufshcd_scsi_cmd_status(struct ufshcd_lrb *lrbp, int scsi_status)
5324 switch (scsi_status) {
5325 case SAM_STAT_CHECK_CONDITION:
5326 ufshcd_copy_sense_data(lrbp);
5329 result |= DID_OK << 16 | scsi_status;
5331 case SAM_STAT_TASK_SET_FULL:
5333 case SAM_STAT_TASK_ABORTED:
5334 ufshcd_copy_sense_data(lrbp);
5335 result |= scsi_status;
5338 result |= DID_ERROR << 16;
5340 } /* end of switch */
5346 * ufshcd_transfer_rsp_status - Get overall status of the response
5347 * @hba: per adapter instance
5348 * @lrbp: pointer to local reference block of completed command
5349 * @cqe: pointer to the completion queue entry
5351 * Return: result of the command to notify SCSI midlayer.
5354 ufshcd_transfer_rsp_status(struct ufs_hba *hba, struct ufshcd_lrb *lrbp,
5355 struct cq_entry *cqe)
5363 upiu_flags = lrbp->ucd_rsp_ptr->header.flags;
5364 resid = be32_to_cpu(lrbp->ucd_rsp_ptr->sr.residual_transfer_count);
5366 * Test !overflow instead of underflow to support UFS devices that do
5367 * not set either flag.
5369 if (resid && !(upiu_flags & UPIU_RSP_FLAG_OVERFLOW))
5370 scsi_set_resid(lrbp->cmd, resid);
5372 /* overall command status of utrd */
5373 ocs = ufshcd_get_tr_ocs(lrbp, cqe);
5375 if (hba->quirks & UFSHCD_QUIRK_BROKEN_OCS_FATAL_ERROR) {
5376 if (lrbp->ucd_rsp_ptr->header.response ||
5377 lrbp->ucd_rsp_ptr->header.status)
5383 hba->ufs_stats.last_hibern8_exit_tstamp = ktime_set(0, 0);
5384 switch (ufshcd_get_req_rsp(lrbp->ucd_rsp_ptr)) {
5385 case UPIU_TRANSACTION_RESPONSE:
5387 * get the result based on SCSI status response
5388 * to notify the SCSI midlayer of the command status
5390 scsi_status = lrbp->ucd_rsp_ptr->header.status;
5391 result = ufshcd_scsi_cmd_status(lrbp, scsi_status);
5394 * Currently we are only supporting BKOPs exception
5395 * events hence we can ignore BKOPs exception event
5396 * during power management callbacks. BKOPs exception
5397 * event is not expected to be raised in runtime suspend
5398 * callback as it allows the urgent bkops.
5399 * During system suspend, we are anyway forcefully
5400 * disabling the bkops and if urgent bkops is needed
5401 * it will be enabled on system resume. Long term
5402 * solution could be to abort the system suspend if
5403 * UFS device needs urgent BKOPs.
5405 if (!hba->pm_op_in_progress &&
5406 !ufshcd_eh_in_progress(hba) &&
5407 ufshcd_is_exception_event(lrbp->ucd_rsp_ptr))
5408 /* Flushed in suspend */
5409 schedule_work(&hba->eeh_work);
5411 case UPIU_TRANSACTION_REJECT_UPIU:
5412 /* TODO: handle Reject UPIU Response */
5413 result = DID_ERROR << 16;
5415 "Reject UPIU not fully implemented\n");
5419 "Unexpected request response code = %x\n",
5421 result = DID_ERROR << 16;
5426 result |= DID_ABORT << 16;
5428 case OCS_INVALID_COMMAND_STATUS:
5429 result |= DID_REQUEUE << 16;
5431 case OCS_INVALID_CMD_TABLE_ATTR:
5432 case OCS_INVALID_PRDT_ATTR:
5433 case OCS_MISMATCH_DATA_BUF_SIZE:
5434 case OCS_MISMATCH_RESP_UPIU_SIZE:
5435 case OCS_PEER_COMM_FAILURE:
5436 case OCS_FATAL_ERROR:
5437 case OCS_DEVICE_FATAL_ERROR:
5438 case OCS_INVALID_CRYPTO_CONFIG:
5439 case OCS_GENERAL_CRYPTO_ERROR:
5441 result |= DID_ERROR << 16;
5443 "OCS error from controller = %x for tag %d\n",
5444 ocs, lrbp->task_tag);
5445 ufshcd_print_evt_hist(hba);
5446 ufshcd_print_host_state(hba);
5448 } /* end of switch */
5450 if ((host_byte(result) != DID_OK) &&
5451 (host_byte(result) != DID_REQUEUE) && !hba->silence_err_logs)
5452 ufshcd_print_tr(hba, lrbp->task_tag, true);
5456 static bool ufshcd_is_auto_hibern8_error(struct ufs_hba *hba,
5459 if (!ufshcd_is_auto_hibern8_supported(hba) ||
5460 !ufshcd_is_auto_hibern8_enabled(hba))
5463 if (!(intr_mask & UFSHCD_UIC_HIBERN8_MASK))
5466 if (hba->active_uic_cmd &&
5467 (hba->active_uic_cmd->command == UIC_CMD_DME_HIBER_ENTER ||
5468 hba->active_uic_cmd->command == UIC_CMD_DME_HIBER_EXIT))
5475 * ufshcd_uic_cmd_compl - handle completion of uic command
5476 * @hba: per adapter instance
5477 * @intr_status: interrupt status generated by the controller
5480 * IRQ_HANDLED - If interrupt is valid
5481 * IRQ_NONE - If invalid interrupt
5483 static irqreturn_t ufshcd_uic_cmd_compl(struct ufs_hba *hba, u32 intr_status)
5485 irqreturn_t retval = IRQ_NONE;
5487 spin_lock(hba->host->host_lock);
5488 if (ufshcd_is_auto_hibern8_error(hba, intr_status))
5489 hba->errors |= (UFSHCD_UIC_HIBERN8_MASK & intr_status);
5491 if ((intr_status & UIC_COMMAND_COMPL) && hba->active_uic_cmd) {
5492 hba->active_uic_cmd->argument2 |=
5493 ufshcd_get_uic_cmd_result(hba);
5494 hba->active_uic_cmd->argument3 =
5495 ufshcd_get_dme_attr_val(hba);
5496 if (!hba->uic_async_done)
5497 hba->active_uic_cmd->cmd_active = 0;
5498 complete(&hba->active_uic_cmd->done);
5499 retval = IRQ_HANDLED;
5502 if ((intr_status & UFSHCD_UIC_PWR_MASK) && hba->uic_async_done) {
5503 hba->active_uic_cmd->cmd_active = 0;
5504 complete(hba->uic_async_done);
5505 retval = IRQ_HANDLED;
5508 if (retval == IRQ_HANDLED)
5509 ufshcd_add_uic_command_trace(hba, hba->active_uic_cmd,
5511 spin_unlock(hba->host->host_lock);
5515 /* Release the resources allocated for processing a SCSI command. */
5516 void ufshcd_release_scsi_cmd(struct ufs_hba *hba,
5517 struct ufshcd_lrb *lrbp)
5519 struct scsi_cmnd *cmd = lrbp->cmd;
5521 scsi_dma_unmap(cmd);
5522 ufshcd_release(hba);
5523 ufshcd_clk_scaling_update_busy(hba);
5527 * ufshcd_compl_one_cqe - handle a completion queue entry
5528 * @hba: per adapter instance
5529 * @task_tag: the task tag of the request to be completed
5530 * @cqe: pointer to the completion queue entry
5532 void ufshcd_compl_one_cqe(struct ufs_hba *hba, int task_tag,
5533 struct cq_entry *cqe)
5535 struct ufshcd_lrb *lrbp;
5536 struct scsi_cmnd *cmd;
5539 lrbp = &hba->lrb[task_tag];
5540 lrbp->compl_time_stamp = ktime_get();
5543 if (unlikely(ufshcd_should_inform_monitor(hba, lrbp)))
5544 ufshcd_update_monitor(hba, lrbp);
5545 ufshcd_add_command_trace(hba, task_tag, UFS_CMD_COMP);
5546 cmd->result = ufshcd_transfer_rsp_status(hba, lrbp, cqe);
5547 ufshcd_release_scsi_cmd(hba, lrbp);
5548 /* Do not touch lrbp after scsi done */
5550 } else if (lrbp->command_type == UTP_CMD_TYPE_DEV_MANAGE ||
5551 lrbp->command_type == UTP_CMD_TYPE_UFS_STORAGE) {
5552 if (hba->dev_cmd.complete) {
5554 ocs = le32_to_cpu(cqe->status) & MASK_OCS;
5555 lrbp->utr_descriptor_ptr->header.ocs = ocs;
5557 complete(hba->dev_cmd.complete);
5563 * __ufshcd_transfer_req_compl - handle SCSI and query command completion
5564 * @hba: per adapter instance
5565 * @completed_reqs: bitmask that indicates which requests to complete
5567 static void __ufshcd_transfer_req_compl(struct ufs_hba *hba,
5568 unsigned long completed_reqs)
5572 for_each_set_bit(tag, &completed_reqs, hba->nutrs)
5573 ufshcd_compl_one_cqe(hba, tag, NULL);
5576 /* Any value that is not an existing queue number is fine for this constant. */
5578 UFSHCD_POLL_FROM_INTERRUPT_CONTEXT = -1
5581 static void ufshcd_clear_polled(struct ufs_hba *hba,
5582 unsigned long *completed_reqs)
5586 for_each_set_bit(tag, completed_reqs, hba->nutrs) {
5587 struct scsi_cmnd *cmd = hba->lrb[tag].cmd;
5591 if (scsi_cmd_to_rq(cmd)->cmd_flags & REQ_POLLED)
5592 __clear_bit(tag, completed_reqs);
5597 * Return: > 0 if one or more commands have been completed or 0 if no
5598 * requests have been completed.
5600 static int ufshcd_poll(struct Scsi_Host *shost, unsigned int queue_num)
5602 struct ufs_hba *hba = shost_priv(shost);
5603 unsigned long completed_reqs, flags;
5605 struct ufs_hw_queue *hwq;
5607 if (is_mcq_enabled(hba)) {
5608 hwq = &hba->uhq[queue_num];
5610 return ufshcd_mcq_poll_cqe_lock(hba, hwq);
5613 spin_lock_irqsave(&hba->outstanding_lock, flags);
5614 tr_doorbell = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
5615 completed_reqs = ~tr_doorbell & hba->outstanding_reqs;
5616 WARN_ONCE(completed_reqs & ~hba->outstanding_reqs,
5617 "completed: %#lx; outstanding: %#lx\n", completed_reqs,
5618 hba->outstanding_reqs);
5619 if (queue_num == UFSHCD_POLL_FROM_INTERRUPT_CONTEXT) {
5620 /* Do not complete polled requests from interrupt context. */
5621 ufshcd_clear_polled(hba, &completed_reqs);
5623 hba->outstanding_reqs &= ~completed_reqs;
5624 spin_unlock_irqrestore(&hba->outstanding_lock, flags);
5627 __ufshcd_transfer_req_compl(hba, completed_reqs);
5629 return completed_reqs != 0;
5633 * ufshcd_mcq_compl_pending_transfer - MCQ mode function. It is
5634 * invoked from the error handler context or ufshcd_host_reset_and_restore()
5635 * to complete the pending transfers and free the resources associated with
5638 * @hba: per adapter instance
5639 * @force_compl: This flag is set to true when invoked
5640 * from ufshcd_host_reset_and_restore() in which case it requires special
5641 * handling because the host controller has been reset by ufshcd_hba_stop().
5643 static void ufshcd_mcq_compl_pending_transfer(struct ufs_hba *hba,
5646 struct ufs_hw_queue *hwq;
5647 struct ufshcd_lrb *lrbp;
5648 struct scsi_cmnd *cmd;
5649 unsigned long flags;
5652 for (tag = 0; tag < hba->nutrs; tag++) {
5653 lrbp = &hba->lrb[tag];
5655 if (!ufshcd_cmd_inflight(cmd) ||
5656 test_bit(SCMD_STATE_COMPLETE, &cmd->state))
5659 hwq = ufshcd_mcq_req_to_hwq(hba, scsi_cmd_to_rq(cmd));
5662 ufshcd_mcq_compl_all_cqes_lock(hba, hwq);
5664 * For those cmds of which the cqes are not present
5665 * in the cq, complete them explicitly.
5667 spin_lock_irqsave(&hwq->cq_lock, flags);
5668 if (cmd && !test_bit(SCMD_STATE_COMPLETE, &cmd->state)) {
5669 set_host_byte(cmd, DID_REQUEUE);
5670 ufshcd_release_scsi_cmd(hba, lrbp);
5673 spin_unlock_irqrestore(&hwq->cq_lock, flags);
5675 ufshcd_mcq_poll_cqe_lock(hba, hwq);
5681 * ufshcd_transfer_req_compl - handle SCSI and query command completion
5682 * @hba: per adapter instance
5685 * IRQ_HANDLED - If interrupt is valid
5686 * IRQ_NONE - If invalid interrupt
5688 static irqreturn_t ufshcd_transfer_req_compl(struct ufs_hba *hba)
5690 /* Resetting interrupt aggregation counters first and reading the
5691 * DOOR_BELL afterward allows us to handle all the completed requests.
5692 * In order to prevent other interrupts starvation the DB is read once
5693 * after reset. The down side of this solution is the possibility of
5694 * false interrupt if device completes another request after resetting
5695 * aggregation and before reading the DB.
5697 if (ufshcd_is_intr_aggr_allowed(hba) &&
5698 !(hba->quirks & UFSHCI_QUIRK_SKIP_RESET_INTR_AGGR))
5699 ufshcd_reset_intr_aggr(hba);
5701 if (ufs_fail_completion(hba))
5705 * Ignore the ufshcd_poll() return value and return IRQ_HANDLED since we
5706 * do not want polling to trigger spurious interrupt complaints.
5708 ufshcd_poll(hba->host, UFSHCD_POLL_FROM_INTERRUPT_CONTEXT);
5713 int __ufshcd_write_ee_control(struct ufs_hba *hba, u32 ee_ctrl_mask)
5715 return ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_WRITE_ATTR,
5716 QUERY_ATTR_IDN_EE_CONTROL, 0, 0,
5720 int ufshcd_write_ee_control(struct ufs_hba *hba)
5724 mutex_lock(&hba->ee_ctrl_mutex);
5725 err = __ufshcd_write_ee_control(hba, hba->ee_ctrl_mask);
5726 mutex_unlock(&hba->ee_ctrl_mutex);
5728 dev_err(hba->dev, "%s: failed to write ee control %d\n",
5733 int ufshcd_update_ee_control(struct ufs_hba *hba, u16 *mask,
5734 const u16 *other_mask, u16 set, u16 clr)
5736 u16 new_mask, ee_ctrl_mask;
5739 mutex_lock(&hba->ee_ctrl_mutex);
5740 new_mask = (*mask & ~clr) | set;
5741 ee_ctrl_mask = new_mask | *other_mask;
5742 if (ee_ctrl_mask != hba->ee_ctrl_mask)
5743 err = __ufshcd_write_ee_control(hba, ee_ctrl_mask);
5744 /* Still need to update 'mask' even if 'ee_ctrl_mask' was unchanged */
5746 hba->ee_ctrl_mask = ee_ctrl_mask;
5749 mutex_unlock(&hba->ee_ctrl_mutex);
5754 * ufshcd_disable_ee - disable exception event
5755 * @hba: per-adapter instance
5756 * @mask: exception event to disable
5758 * Disables exception event in the device so that the EVENT_ALERT
5761 * Return: zero on success, non-zero error value on failure.
5763 static inline int ufshcd_disable_ee(struct ufs_hba *hba, u16 mask)
5765 return ufshcd_update_ee_drv_mask(hba, 0, mask);
5769 * ufshcd_enable_ee - enable exception event
5770 * @hba: per-adapter instance
5771 * @mask: exception event to enable
5773 * Enable corresponding exception event in the device to allow
5774 * device to alert host in critical scenarios.
5776 * Return: zero on success, non-zero error value on failure.
5778 static inline int ufshcd_enable_ee(struct ufs_hba *hba, u16 mask)
5780 return ufshcd_update_ee_drv_mask(hba, mask, 0);
5784 * ufshcd_enable_auto_bkops - Allow device managed BKOPS
5785 * @hba: per-adapter instance
5787 * Allow device to manage background operations on its own. Enabling
5788 * this might lead to inconsistent latencies during normal data transfers
5789 * as the device is allowed to manage its own way of handling background
5792 * Return: zero on success, non-zero on failure.
5794 static int ufshcd_enable_auto_bkops(struct ufs_hba *hba)
5798 if (hba->auto_bkops_enabled)
5801 err = ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_SET_FLAG,
5802 QUERY_FLAG_IDN_BKOPS_EN, 0, NULL);
5804 dev_err(hba->dev, "%s: failed to enable bkops %d\n",
5809 hba->auto_bkops_enabled = true;
5810 trace_ufshcd_auto_bkops_state(dev_name(hba->dev), "Enabled");
5812 /* No need of URGENT_BKOPS exception from the device */
5813 err = ufshcd_disable_ee(hba, MASK_EE_URGENT_BKOPS);
5815 dev_err(hba->dev, "%s: failed to disable exception event %d\n",
5822 * ufshcd_disable_auto_bkops - block device in doing background operations
5823 * @hba: per-adapter instance
5825 * Disabling background operations improves command response latency but
5826 * has drawback of device moving into critical state where the device is
5827 * not-operable. Make sure to call ufshcd_enable_auto_bkops() whenever the
5828 * host is idle so that BKOPS are managed effectively without any negative
5831 * Return: zero on success, non-zero on failure.
5833 static int ufshcd_disable_auto_bkops(struct ufs_hba *hba)
5837 if (!hba->auto_bkops_enabled)
5841 * If host assisted BKOPs is to be enabled, make sure
5842 * urgent bkops exception is allowed.
5844 err = ufshcd_enable_ee(hba, MASK_EE_URGENT_BKOPS);
5846 dev_err(hba->dev, "%s: failed to enable exception event %d\n",
5851 err = ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_CLEAR_FLAG,
5852 QUERY_FLAG_IDN_BKOPS_EN, 0, NULL);
5854 dev_err(hba->dev, "%s: failed to disable bkops %d\n",
5856 ufshcd_disable_ee(hba, MASK_EE_URGENT_BKOPS);
5860 hba->auto_bkops_enabled = false;
5861 trace_ufshcd_auto_bkops_state(dev_name(hba->dev), "Disabled");
5862 hba->is_urgent_bkops_lvl_checked = false;
5868 * ufshcd_force_reset_auto_bkops - force reset auto bkops state
5869 * @hba: per adapter instance
5871 * After a device reset the device may toggle the BKOPS_EN flag
5872 * to default value. The s/w tracking variables should be updated
5873 * as well. This function would change the auto-bkops state based on
5874 * UFSHCD_CAP_KEEP_AUTO_BKOPS_ENABLED_EXCEPT_SUSPEND.
5876 static void ufshcd_force_reset_auto_bkops(struct ufs_hba *hba)
5878 if (ufshcd_keep_autobkops_enabled_except_suspend(hba)) {
5879 hba->auto_bkops_enabled = false;
5880 hba->ee_ctrl_mask |= MASK_EE_URGENT_BKOPS;
5881 ufshcd_enable_auto_bkops(hba);
5883 hba->auto_bkops_enabled = true;
5884 hba->ee_ctrl_mask &= ~MASK_EE_URGENT_BKOPS;
5885 ufshcd_disable_auto_bkops(hba);
5887 hba->urgent_bkops_lvl = BKOPS_STATUS_PERF_IMPACT;
5888 hba->is_urgent_bkops_lvl_checked = false;
5891 static inline int ufshcd_get_bkops_status(struct ufs_hba *hba, u32 *status)
5893 return ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
5894 QUERY_ATTR_IDN_BKOPS_STATUS, 0, 0, status);
5898 * ufshcd_bkops_ctrl - control the auto bkops based on current bkops status
5899 * @hba: per-adapter instance
5900 * @status: bkops_status value
5902 * Read the bkops_status from the UFS device and Enable fBackgroundOpsEn
5903 * flag in the device to permit background operations if the device
5904 * bkops_status is greater than or equal to "status" argument passed to
5905 * this function, disable otherwise.
5907 * Return: 0 for success, non-zero in case of failure.
5909 * NOTE: Caller of this function can check the "hba->auto_bkops_enabled" flag
5910 * to know whether auto bkops is enabled or disabled after this function
5911 * returns control to it.
5913 static int ufshcd_bkops_ctrl(struct ufs_hba *hba,
5914 enum bkops_status status)
5917 u32 curr_status = 0;
5919 err = ufshcd_get_bkops_status(hba, &curr_status);
5921 dev_err(hba->dev, "%s: failed to get BKOPS status %d\n",
5924 } else if (curr_status > BKOPS_STATUS_MAX) {
5925 dev_err(hba->dev, "%s: invalid BKOPS status %d\n",
5926 __func__, curr_status);
5931 if (curr_status >= status)
5932 err = ufshcd_enable_auto_bkops(hba);
5934 err = ufshcd_disable_auto_bkops(hba);
5940 * ufshcd_urgent_bkops - handle urgent bkops exception event
5941 * @hba: per-adapter instance
5943 * Enable fBackgroundOpsEn flag in the device to permit background
5946 * If BKOPs is enabled, this function returns 0, 1 if the bkops in not enabled
5947 * and negative error value for any other failure.
5949 * Return: 0 upon success; < 0 upon failure.
5951 static int ufshcd_urgent_bkops(struct ufs_hba *hba)
5953 return ufshcd_bkops_ctrl(hba, hba->urgent_bkops_lvl);
5956 static inline int ufshcd_get_ee_status(struct ufs_hba *hba, u32 *status)
5958 return ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
5959 QUERY_ATTR_IDN_EE_STATUS, 0, 0, status);
5962 static void ufshcd_bkops_exception_event_handler(struct ufs_hba *hba)
5965 u32 curr_status = 0;
5967 if (hba->is_urgent_bkops_lvl_checked)
5968 goto enable_auto_bkops;
5970 err = ufshcd_get_bkops_status(hba, &curr_status);
5972 dev_err(hba->dev, "%s: failed to get BKOPS status %d\n",
5978 * We are seeing that some devices are raising the urgent bkops
5979 * exception events even when BKOPS status doesn't indicate performace
5980 * impacted or critical. Handle these device by determining their urgent
5981 * bkops status at runtime.
5983 if (curr_status < BKOPS_STATUS_PERF_IMPACT) {
5984 dev_err(hba->dev, "%s: device raised urgent BKOPS exception for bkops status %d\n",
5985 __func__, curr_status);
5986 /* update the current status as the urgent bkops level */
5987 hba->urgent_bkops_lvl = curr_status;
5988 hba->is_urgent_bkops_lvl_checked = true;
5992 err = ufshcd_enable_auto_bkops(hba);
5995 dev_err(hba->dev, "%s: failed to handle urgent bkops %d\n",
5999 static void ufshcd_temp_exception_event_handler(struct ufs_hba *hba, u16 status)
6003 if (ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
6004 QUERY_ATTR_IDN_CASE_ROUGH_TEMP, 0, 0, &value))
6007 dev_info(hba->dev, "exception Tcase %d\n", value - 80);
6009 ufs_hwmon_notify_event(hba, status & MASK_EE_URGENT_TEMP);
6012 * A placeholder for the platform vendors to add whatever additional
6017 static int __ufshcd_wb_toggle(struct ufs_hba *hba, bool set, enum flag_idn idn)
6020 enum query_opcode opcode = set ? UPIU_QUERY_OPCODE_SET_FLAG :
6021 UPIU_QUERY_OPCODE_CLEAR_FLAG;
6023 index = ufshcd_wb_get_query_index(hba);
6024 return ufshcd_query_flag_retry(hba, opcode, idn, index, NULL);
6027 int ufshcd_wb_toggle(struct ufs_hba *hba, bool enable)
6031 if (!ufshcd_is_wb_allowed(hba) ||
6032 hba->dev_info.wb_enabled == enable)
6035 ret = __ufshcd_wb_toggle(hba, enable, QUERY_FLAG_IDN_WB_EN);
6037 dev_err(hba->dev, "%s: Write Booster %s failed %d\n",
6038 __func__, enable ? "enabling" : "disabling", ret);
6042 hba->dev_info.wb_enabled = enable;
6043 dev_dbg(hba->dev, "%s: Write Booster %s\n",
6044 __func__, enable ? "enabled" : "disabled");
6049 static void ufshcd_wb_toggle_buf_flush_during_h8(struct ufs_hba *hba,
6054 ret = __ufshcd_wb_toggle(hba, enable,
6055 QUERY_FLAG_IDN_WB_BUFF_FLUSH_DURING_HIBERN8);
6057 dev_err(hba->dev, "%s: WB-Buf Flush during H8 %s failed %d\n",
6058 __func__, enable ? "enabling" : "disabling", ret);
6061 dev_dbg(hba->dev, "%s: WB-Buf Flush during H8 %s\n",
6062 __func__, enable ? "enabled" : "disabled");
6065 int ufshcd_wb_toggle_buf_flush(struct ufs_hba *hba, bool enable)
6069 if (!ufshcd_is_wb_allowed(hba) ||
6070 hba->dev_info.wb_buf_flush_enabled == enable)
6073 ret = __ufshcd_wb_toggle(hba, enable, QUERY_FLAG_IDN_WB_BUFF_FLUSH_EN);
6075 dev_err(hba->dev, "%s: WB-Buf Flush %s failed %d\n",
6076 __func__, enable ? "enabling" : "disabling", ret);
6080 hba->dev_info.wb_buf_flush_enabled = enable;
6081 dev_dbg(hba->dev, "%s: WB-Buf Flush %s\n",
6082 __func__, enable ? "enabled" : "disabled");
6087 static bool ufshcd_wb_presrv_usrspc_keep_vcc_on(struct ufs_hba *hba,
6094 index = ufshcd_wb_get_query_index(hba);
6095 ret = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
6096 QUERY_ATTR_IDN_CURR_WB_BUFF_SIZE,
6097 index, 0, &cur_buf);
6099 dev_err(hba->dev, "%s: dCurWriteBoosterBufferSize read failed %d\n",
6105 dev_info(hba->dev, "dCurWBBuf: %d WB disabled until free-space is available\n",
6109 /* Let it continue to flush when available buffer exceeds threshold */
6110 return avail_buf < hba->vps->wb_flush_threshold;
6113 static void ufshcd_wb_force_disable(struct ufs_hba *hba)
6115 if (ufshcd_is_wb_buf_flush_allowed(hba))
6116 ufshcd_wb_toggle_buf_flush(hba, false);
6118 ufshcd_wb_toggle_buf_flush_during_h8(hba, false);
6119 ufshcd_wb_toggle(hba, false);
6120 hba->caps &= ~UFSHCD_CAP_WB_EN;
6122 dev_info(hba->dev, "%s: WB force disabled\n", __func__);
6125 static bool ufshcd_is_wb_buf_lifetime_available(struct ufs_hba *hba)
6131 index = ufshcd_wb_get_query_index(hba);
6132 ret = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
6133 QUERY_ATTR_IDN_WB_BUFF_LIFE_TIME_EST,
6134 index, 0, &lifetime);
6137 "%s: bWriteBoosterBufferLifeTimeEst read failed %d\n",
6142 if (lifetime == UFS_WB_EXCEED_LIFETIME) {
6143 dev_err(hba->dev, "%s: WB buf lifetime is exhausted 0x%02X\n",
6144 __func__, lifetime);
6148 dev_dbg(hba->dev, "%s: WB buf lifetime is 0x%02X\n",
6149 __func__, lifetime);
6154 static bool ufshcd_wb_need_flush(struct ufs_hba *hba)
6160 if (!ufshcd_is_wb_allowed(hba))
6163 if (!ufshcd_is_wb_buf_lifetime_available(hba)) {
6164 ufshcd_wb_force_disable(hba);
6169 * The ufs device needs the vcc to be ON to flush.
6170 * With user-space reduction enabled, it's enough to enable flush
6171 * by checking only the available buffer. The threshold
6172 * defined here is > 90% full.
6173 * With user-space preserved enabled, the current-buffer
6174 * should be checked too because the wb buffer size can reduce
6175 * when disk tends to be full. This info is provided by current
6176 * buffer (dCurrentWriteBoosterBufferSize). There's no point in
6177 * keeping vcc on when current buffer is empty.
6179 index = ufshcd_wb_get_query_index(hba);
6180 ret = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
6181 QUERY_ATTR_IDN_AVAIL_WB_BUFF_SIZE,
6182 index, 0, &avail_buf);
6184 dev_warn(hba->dev, "%s: dAvailableWriteBoosterBufferSize read failed %d\n",
6189 if (!hba->dev_info.b_presrv_uspc_en)
6190 return avail_buf <= UFS_WB_BUF_REMAIN_PERCENT(10);
6192 return ufshcd_wb_presrv_usrspc_keep_vcc_on(hba, avail_buf);
6195 static void ufshcd_rpm_dev_flush_recheck_work(struct work_struct *work)
6197 struct ufs_hba *hba = container_of(to_delayed_work(work),
6199 rpm_dev_flush_recheck_work);
6201 * To prevent unnecessary VCC power drain after device finishes
6202 * WriteBooster buffer flush or Auto BKOPs, force runtime resume
6203 * after a certain delay to recheck the threshold by next runtime
6206 ufshcd_rpm_get_sync(hba);
6207 ufshcd_rpm_put_sync(hba);
6211 * ufshcd_exception_event_handler - handle exceptions raised by device
6212 * @work: pointer to work data
6214 * Read bExceptionEventStatus attribute from the device and handle the
6215 * exception event accordingly.
6217 static void ufshcd_exception_event_handler(struct work_struct *work)
6219 struct ufs_hba *hba;
6222 hba = container_of(work, struct ufs_hba, eeh_work);
6224 ufshcd_scsi_block_requests(hba);
6225 err = ufshcd_get_ee_status(hba, &status);
6227 dev_err(hba->dev, "%s: failed to get exception status %d\n",
6232 trace_ufshcd_exception_event(dev_name(hba->dev), status);
6234 if (status & hba->ee_drv_mask & MASK_EE_URGENT_BKOPS)
6235 ufshcd_bkops_exception_event_handler(hba);
6237 if (status & hba->ee_drv_mask & MASK_EE_URGENT_TEMP)
6238 ufshcd_temp_exception_event_handler(hba, status);
6240 ufs_debugfs_exception_event(hba, status);
6242 ufshcd_scsi_unblock_requests(hba);
6245 /* Complete requests that have door-bell cleared */
6246 static void ufshcd_complete_requests(struct ufs_hba *hba, bool force_compl)
6248 if (is_mcq_enabled(hba))
6249 ufshcd_mcq_compl_pending_transfer(hba, force_compl);
6251 ufshcd_transfer_req_compl(hba);
6253 ufshcd_tmc_handler(hba);
6257 * ufshcd_quirk_dl_nac_errors - This function checks if error handling is
6258 * to recover from the DL NAC errors or not.
6259 * @hba: per-adapter instance
6261 * Return: true if error handling is required, false otherwise.
6263 static bool ufshcd_quirk_dl_nac_errors(struct ufs_hba *hba)
6265 unsigned long flags;
6266 bool err_handling = true;
6268 spin_lock_irqsave(hba->host->host_lock, flags);
6270 * UFS_DEVICE_QUIRK_RECOVERY_FROM_DL_NAC_ERRORS only workaround the
6271 * device fatal error and/or DL NAC & REPLAY timeout errors.
6273 if (hba->saved_err & (CONTROLLER_FATAL_ERROR | SYSTEM_BUS_FATAL_ERROR))
6276 if ((hba->saved_err & DEVICE_FATAL_ERROR) ||
6277 ((hba->saved_err & UIC_ERROR) &&
6278 (hba->saved_uic_err & UFSHCD_UIC_DL_TCx_REPLAY_ERROR)))
6281 if ((hba->saved_err & UIC_ERROR) &&
6282 (hba->saved_uic_err & UFSHCD_UIC_DL_NAC_RECEIVED_ERROR)) {
6285 * wait for 50ms to see if we can get any other errors or not.
6287 spin_unlock_irqrestore(hba->host->host_lock, flags);
6289 spin_lock_irqsave(hba->host->host_lock, flags);
6292 * now check if we have got any other severe errors other than
6295 if ((hba->saved_err & INT_FATAL_ERRORS) ||
6296 ((hba->saved_err & UIC_ERROR) &&
6297 (hba->saved_uic_err & ~UFSHCD_UIC_DL_NAC_RECEIVED_ERROR)))
6301 * As DL NAC is the only error received so far, send out NOP
6302 * command to confirm if link is still active or not.
6303 * - If we don't get any response then do error recovery.
6304 * - If we get response then clear the DL NAC error bit.
6307 spin_unlock_irqrestore(hba->host->host_lock, flags);
6308 err = ufshcd_verify_dev_init(hba);
6309 spin_lock_irqsave(hba->host->host_lock, flags);
6314 /* Link seems to be alive hence ignore the DL NAC errors */
6315 if (hba->saved_uic_err == UFSHCD_UIC_DL_NAC_RECEIVED_ERROR)
6316 hba->saved_err &= ~UIC_ERROR;
6317 /* clear NAC error */
6318 hba->saved_uic_err &= ~UFSHCD_UIC_DL_NAC_RECEIVED_ERROR;
6319 if (!hba->saved_uic_err)
6320 err_handling = false;
6323 spin_unlock_irqrestore(hba->host->host_lock, flags);
6324 return err_handling;
6327 /* host lock must be held before calling this func */
6328 static inline bool ufshcd_is_saved_err_fatal(struct ufs_hba *hba)
6330 return (hba->saved_uic_err & UFSHCD_UIC_DL_PA_INIT_ERROR) ||
6331 (hba->saved_err & (INT_FATAL_ERRORS | UFSHCD_UIC_HIBERN8_MASK));
6334 void ufshcd_schedule_eh_work(struct ufs_hba *hba)
6336 lockdep_assert_held(hba->host->host_lock);
6338 /* handle fatal errors only when link is not in error state */
6339 if (hba->ufshcd_state != UFSHCD_STATE_ERROR) {
6340 if (hba->force_reset || ufshcd_is_link_broken(hba) ||
6341 ufshcd_is_saved_err_fatal(hba))
6342 hba->ufshcd_state = UFSHCD_STATE_EH_SCHEDULED_FATAL;
6344 hba->ufshcd_state = UFSHCD_STATE_EH_SCHEDULED_NON_FATAL;
6345 queue_work(hba->eh_wq, &hba->eh_work);
6349 static void ufshcd_force_error_recovery(struct ufs_hba *hba)
6351 spin_lock_irq(hba->host->host_lock);
6352 hba->force_reset = true;
6353 ufshcd_schedule_eh_work(hba);
6354 spin_unlock_irq(hba->host->host_lock);
6357 static void ufshcd_clk_scaling_allow(struct ufs_hba *hba, bool allow)
6359 mutex_lock(&hba->wb_mutex);
6360 down_write(&hba->clk_scaling_lock);
6361 hba->clk_scaling.is_allowed = allow;
6362 up_write(&hba->clk_scaling_lock);
6363 mutex_unlock(&hba->wb_mutex);
6366 static void ufshcd_clk_scaling_suspend(struct ufs_hba *hba, bool suspend)
6369 if (hba->clk_scaling.is_enabled)
6370 ufshcd_suspend_clkscaling(hba);
6371 ufshcd_clk_scaling_allow(hba, false);
6373 ufshcd_clk_scaling_allow(hba, true);
6374 if (hba->clk_scaling.is_enabled)
6375 ufshcd_resume_clkscaling(hba);
6379 static void ufshcd_err_handling_prepare(struct ufs_hba *hba)
6381 ufshcd_rpm_get_sync(hba);
6382 if (pm_runtime_status_suspended(&hba->ufs_device_wlun->sdev_gendev) ||
6383 hba->is_sys_suspended) {
6384 enum ufs_pm_op pm_op;
6387 * Don't assume anything of resume, if
6388 * resume fails, irq and clocks can be OFF, and powers
6389 * can be OFF or in LPM.
6391 ufshcd_setup_hba_vreg(hba, true);
6392 ufshcd_enable_irq(hba);
6393 ufshcd_setup_vreg(hba, true);
6394 ufshcd_config_vreg_hpm(hba, hba->vreg_info.vccq);
6395 ufshcd_config_vreg_hpm(hba, hba->vreg_info.vccq2);
6397 if (!ufshcd_is_clkgating_allowed(hba))
6398 ufshcd_setup_clocks(hba, true);
6399 pm_op = hba->is_sys_suspended ? UFS_SYSTEM_PM : UFS_RUNTIME_PM;
6400 ufshcd_vops_resume(hba, pm_op);
6403 if (ufshcd_is_clkscaling_supported(hba) &&
6404 hba->clk_scaling.is_enabled)
6405 ufshcd_suspend_clkscaling(hba);
6406 ufshcd_clk_scaling_allow(hba, false);
6408 ufshcd_scsi_block_requests(hba);
6409 /* Wait for ongoing ufshcd_queuecommand() calls to finish. */
6410 blk_mq_wait_quiesce_done(&hba->host->tag_set);
6411 cancel_work_sync(&hba->eeh_work);
6414 static void ufshcd_err_handling_unprepare(struct ufs_hba *hba)
6416 ufshcd_scsi_unblock_requests(hba);
6417 ufshcd_release(hba);
6418 if (ufshcd_is_clkscaling_supported(hba))
6419 ufshcd_clk_scaling_suspend(hba, false);
6420 ufshcd_rpm_put(hba);
6423 static inline bool ufshcd_err_handling_should_stop(struct ufs_hba *hba)
6425 return (!hba->is_powered || hba->shutting_down ||
6426 !hba->ufs_device_wlun ||
6427 hba->ufshcd_state == UFSHCD_STATE_ERROR ||
6428 (!(hba->saved_err || hba->saved_uic_err || hba->force_reset ||
6429 ufshcd_is_link_broken(hba))));
6433 static void ufshcd_recover_pm_error(struct ufs_hba *hba)
6435 struct Scsi_Host *shost = hba->host;
6436 struct scsi_device *sdev;
6437 struct request_queue *q;
6440 hba->is_sys_suspended = false;
6442 * Set RPM status of wlun device to RPM_ACTIVE,
6443 * this also clears its runtime error.
6445 ret = pm_runtime_set_active(&hba->ufs_device_wlun->sdev_gendev);
6447 /* hba device might have a runtime error otherwise */
6449 ret = pm_runtime_set_active(hba->dev);
6451 * If wlun device had runtime error, we also need to resume those
6452 * consumer scsi devices in case any of them has failed to be
6453 * resumed due to supplier runtime resume failure. This is to unblock
6454 * blk_queue_enter in case there are bios waiting inside it.
6457 shost_for_each_device(sdev, shost) {
6458 q = sdev->request_queue;
6459 if (q->dev && (q->rpm_status == RPM_SUSPENDED ||
6460 q->rpm_status == RPM_SUSPENDING))
6461 pm_request_resume(q->dev);
6466 static inline void ufshcd_recover_pm_error(struct ufs_hba *hba)
6471 static bool ufshcd_is_pwr_mode_restore_needed(struct ufs_hba *hba)
6473 struct ufs_pa_layer_attr *pwr_info = &hba->pwr_info;
6476 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_PWRMODE), &mode);
6478 if (pwr_info->pwr_rx != ((mode >> PWRMODE_RX_OFFSET) & PWRMODE_MASK))
6481 if (pwr_info->pwr_tx != (mode & PWRMODE_MASK))
6487 static bool ufshcd_abort_one(struct request *rq, void *priv)
6491 struct scsi_cmnd *cmd = blk_mq_rq_to_pdu(rq);
6492 struct scsi_device *sdev = cmd->device;
6493 struct Scsi_Host *shost = sdev->host;
6494 struct ufs_hba *hba = shost_priv(shost);
6495 struct ufshcd_lrb *lrbp = &hba->lrb[tag];
6496 struct ufs_hw_queue *hwq;
6497 unsigned long flags;
6499 *ret = ufshcd_try_to_abort_task(hba, tag);
6500 dev_err(hba->dev, "Aborting tag %d / CDB %#02x %s\n", tag,
6501 hba->lrb[tag].cmd ? hba->lrb[tag].cmd->cmnd[0] : -1,
6502 *ret ? "failed" : "succeeded");
6504 /* Release cmd in MCQ mode if abort succeeds */
6505 if (is_mcq_enabled(hba) && (*ret == 0)) {
6506 hwq = ufshcd_mcq_req_to_hwq(hba, scsi_cmd_to_rq(lrbp->cmd));
6507 spin_lock_irqsave(&hwq->cq_lock, flags);
6508 if (ufshcd_cmd_inflight(lrbp->cmd))
6509 ufshcd_release_scsi_cmd(hba, lrbp);
6510 spin_unlock_irqrestore(&hwq->cq_lock, flags);
6517 * ufshcd_abort_all - Abort all pending commands.
6518 * @hba: Host bus adapter pointer.
6520 * Return: true if and only if the host controller needs to be reset.
6522 static bool ufshcd_abort_all(struct ufs_hba *hba)
6526 blk_mq_tagset_busy_iter(&hba->host->tag_set, ufshcd_abort_one, &ret);
6530 /* Clear pending task management requests */
6531 for_each_set_bit(tag, &hba->outstanding_tasks, hba->nutmrs) {
6532 ret = ufshcd_clear_tm_cmd(hba, tag);
6538 /* Complete the requests that are cleared by s/w */
6539 ufshcd_complete_requests(hba, false);
6545 * ufshcd_err_handler - handle UFS errors that require s/w attention
6546 * @work: pointer to work structure
6548 static void ufshcd_err_handler(struct work_struct *work)
6550 int retries = MAX_ERR_HANDLER_RETRIES;
6551 struct ufs_hba *hba;
6552 unsigned long flags;
6557 hba = container_of(work, struct ufs_hba, eh_work);
6560 "%s started; HBA state %s; powered %d; shutting down %d; saved_err = %d; saved_uic_err = %d; force_reset = %d%s\n",
6561 __func__, ufshcd_state_name[hba->ufshcd_state],
6562 hba->is_powered, hba->shutting_down, hba->saved_err,
6563 hba->saved_uic_err, hba->force_reset,
6564 ufshcd_is_link_broken(hba) ? "; link is broken" : "");
6566 down(&hba->host_sem);
6567 spin_lock_irqsave(hba->host->host_lock, flags);
6568 if (ufshcd_err_handling_should_stop(hba)) {
6569 if (hba->ufshcd_state != UFSHCD_STATE_ERROR)
6570 hba->ufshcd_state = UFSHCD_STATE_OPERATIONAL;
6571 spin_unlock_irqrestore(hba->host->host_lock, flags);
6575 ufshcd_set_eh_in_progress(hba);
6576 spin_unlock_irqrestore(hba->host->host_lock, flags);
6577 ufshcd_err_handling_prepare(hba);
6578 /* Complete requests that have door-bell cleared by h/w */
6579 ufshcd_complete_requests(hba, false);
6580 spin_lock_irqsave(hba->host->host_lock, flags);
6582 needs_restore = false;
6583 needs_reset = false;
6585 if (hba->ufshcd_state != UFSHCD_STATE_ERROR)
6586 hba->ufshcd_state = UFSHCD_STATE_RESET;
6588 * A full reset and restore might have happened after preparation
6589 * is finished, double check whether we should stop.
6591 if (ufshcd_err_handling_should_stop(hba))
6592 goto skip_err_handling;
6594 if (hba->dev_quirks & UFS_DEVICE_QUIRK_RECOVERY_FROM_DL_NAC_ERRORS) {
6597 spin_unlock_irqrestore(hba->host->host_lock, flags);
6598 /* release the lock as ufshcd_quirk_dl_nac_errors() may sleep */
6599 ret = ufshcd_quirk_dl_nac_errors(hba);
6600 spin_lock_irqsave(hba->host->host_lock, flags);
6601 if (!ret && ufshcd_err_handling_should_stop(hba))
6602 goto skip_err_handling;
6605 if ((hba->saved_err & (INT_FATAL_ERRORS | UFSHCD_UIC_HIBERN8_MASK)) ||
6606 (hba->saved_uic_err &&
6607 (hba->saved_uic_err != UFSHCD_UIC_PA_GENERIC_ERROR))) {
6608 bool pr_prdt = !!(hba->saved_err & SYSTEM_BUS_FATAL_ERROR);
6610 spin_unlock_irqrestore(hba->host->host_lock, flags);
6611 ufshcd_print_host_state(hba);
6612 ufshcd_print_pwr_info(hba);
6613 ufshcd_print_evt_hist(hba);
6614 ufshcd_print_tmrs(hba, hba->outstanding_tasks);
6615 ufshcd_print_trs_all(hba, pr_prdt);
6616 spin_lock_irqsave(hba->host->host_lock, flags);
6620 * if host reset is required then skip clearing the pending
6621 * transfers forcefully because they will get cleared during
6622 * host reset and restore
6624 if (hba->force_reset || ufshcd_is_link_broken(hba) ||
6625 ufshcd_is_saved_err_fatal(hba) ||
6626 ((hba->saved_err & UIC_ERROR) &&
6627 (hba->saved_uic_err & (UFSHCD_UIC_DL_NAC_RECEIVED_ERROR |
6628 UFSHCD_UIC_DL_TCx_REPLAY_ERROR)))) {
6634 * If LINERESET was caught, UFS might have been put to PWM mode,
6635 * check if power mode restore is needed.
6637 if (hba->saved_uic_err & UFSHCD_UIC_PA_GENERIC_ERROR) {
6638 hba->saved_uic_err &= ~UFSHCD_UIC_PA_GENERIC_ERROR;
6639 if (!hba->saved_uic_err)
6640 hba->saved_err &= ~UIC_ERROR;
6641 spin_unlock_irqrestore(hba->host->host_lock, flags);
6642 if (ufshcd_is_pwr_mode_restore_needed(hba))
6643 needs_restore = true;
6644 spin_lock_irqsave(hba->host->host_lock, flags);
6645 if (!hba->saved_err && !needs_restore)
6646 goto skip_err_handling;
6649 hba->silence_err_logs = true;
6650 /* release lock as clear command might sleep */
6651 spin_unlock_irqrestore(hba->host->host_lock, flags);
6653 needs_reset = ufshcd_abort_all(hba);
6655 spin_lock_irqsave(hba->host->host_lock, flags);
6656 hba->silence_err_logs = false;
6661 * After all reqs and tasks are cleared from doorbell,
6662 * now it is safe to retore power mode.
6664 if (needs_restore) {
6665 spin_unlock_irqrestore(hba->host->host_lock, flags);
6667 * Hold the scaling lock just in case dev cmds
6668 * are sent via bsg and/or sysfs.
6670 down_write(&hba->clk_scaling_lock);
6671 hba->force_pmc = true;
6672 pmc_err = ufshcd_config_pwr_mode(hba, &(hba->pwr_info));
6675 dev_err(hba->dev, "%s: Failed to restore power mode, err = %d\n",
6678 hba->force_pmc = false;
6679 ufshcd_print_pwr_info(hba);
6680 up_write(&hba->clk_scaling_lock);
6681 spin_lock_irqsave(hba->host->host_lock, flags);
6685 /* Fatal errors need reset */
6689 hba->force_reset = false;
6690 spin_unlock_irqrestore(hba->host->host_lock, flags);
6691 err = ufshcd_reset_and_restore(hba);
6693 dev_err(hba->dev, "%s: reset and restore failed with err %d\n",
6696 ufshcd_recover_pm_error(hba);
6697 spin_lock_irqsave(hba->host->host_lock, flags);
6702 if (hba->ufshcd_state == UFSHCD_STATE_RESET)
6703 hba->ufshcd_state = UFSHCD_STATE_OPERATIONAL;
6704 if (hba->saved_err || hba->saved_uic_err)
6705 dev_err_ratelimited(hba->dev, "%s: exit: saved_err 0x%x saved_uic_err 0x%x",
6706 __func__, hba->saved_err, hba->saved_uic_err);
6708 /* Exit in an operational state or dead */
6709 if (hba->ufshcd_state != UFSHCD_STATE_OPERATIONAL &&
6710 hba->ufshcd_state != UFSHCD_STATE_ERROR) {
6713 hba->ufshcd_state = UFSHCD_STATE_ERROR;
6715 ufshcd_clear_eh_in_progress(hba);
6716 spin_unlock_irqrestore(hba->host->host_lock, flags);
6717 ufshcd_err_handling_unprepare(hba);
6720 dev_info(hba->dev, "%s finished; HBA state %s\n", __func__,
6721 ufshcd_state_name[hba->ufshcd_state]);
6725 * ufshcd_update_uic_error - check and set fatal UIC error flags.
6726 * @hba: per-adapter instance
6729 * IRQ_HANDLED - If interrupt is valid
6730 * IRQ_NONE - If invalid interrupt
6732 static irqreturn_t ufshcd_update_uic_error(struct ufs_hba *hba)
6735 irqreturn_t retval = IRQ_NONE;
6737 /* PHY layer error */
6738 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_PHY_ADAPTER_LAYER);
6739 if ((reg & UIC_PHY_ADAPTER_LAYER_ERROR) &&
6740 (reg & UIC_PHY_ADAPTER_LAYER_ERROR_CODE_MASK)) {
6741 ufshcd_update_evt_hist(hba, UFS_EVT_PA_ERR, reg);
6743 * To know whether this error is fatal or not, DB timeout
6744 * must be checked but this error is handled separately.
6746 if (reg & UIC_PHY_ADAPTER_LAYER_LANE_ERR_MASK)
6747 dev_dbg(hba->dev, "%s: UIC Lane error reported\n",
6750 /* Got a LINERESET indication. */
6751 if (reg & UIC_PHY_ADAPTER_LAYER_GENERIC_ERROR) {
6752 struct uic_command *cmd = NULL;
6754 hba->uic_error |= UFSHCD_UIC_PA_GENERIC_ERROR;
6755 if (hba->uic_async_done && hba->active_uic_cmd)
6756 cmd = hba->active_uic_cmd;
6758 * Ignore the LINERESET during power mode change
6759 * operation via DME_SET command.
6761 if (cmd && (cmd->command == UIC_CMD_DME_SET))
6762 hba->uic_error &= ~UFSHCD_UIC_PA_GENERIC_ERROR;
6764 retval |= IRQ_HANDLED;
6767 /* PA_INIT_ERROR is fatal and needs UIC reset */
6768 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_DATA_LINK_LAYER);
6769 if ((reg & UIC_DATA_LINK_LAYER_ERROR) &&
6770 (reg & UIC_DATA_LINK_LAYER_ERROR_CODE_MASK)) {
6771 ufshcd_update_evt_hist(hba, UFS_EVT_DL_ERR, reg);
6773 if (reg & UIC_DATA_LINK_LAYER_ERROR_PA_INIT)
6774 hba->uic_error |= UFSHCD_UIC_DL_PA_INIT_ERROR;
6775 else if (hba->dev_quirks &
6776 UFS_DEVICE_QUIRK_RECOVERY_FROM_DL_NAC_ERRORS) {
6777 if (reg & UIC_DATA_LINK_LAYER_ERROR_NAC_RECEIVED)
6779 UFSHCD_UIC_DL_NAC_RECEIVED_ERROR;
6780 else if (reg & UIC_DATA_LINK_LAYER_ERROR_TCx_REPLAY_TIMEOUT)
6781 hba->uic_error |= UFSHCD_UIC_DL_TCx_REPLAY_ERROR;
6783 retval |= IRQ_HANDLED;
6786 /* UIC NL/TL/DME errors needs software retry */
6787 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_NETWORK_LAYER);
6788 if ((reg & UIC_NETWORK_LAYER_ERROR) &&
6789 (reg & UIC_NETWORK_LAYER_ERROR_CODE_MASK)) {
6790 ufshcd_update_evt_hist(hba, UFS_EVT_NL_ERR, reg);
6791 hba->uic_error |= UFSHCD_UIC_NL_ERROR;
6792 retval |= IRQ_HANDLED;
6795 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_TRANSPORT_LAYER);
6796 if ((reg & UIC_TRANSPORT_LAYER_ERROR) &&
6797 (reg & UIC_TRANSPORT_LAYER_ERROR_CODE_MASK)) {
6798 ufshcd_update_evt_hist(hba, UFS_EVT_TL_ERR, reg);
6799 hba->uic_error |= UFSHCD_UIC_TL_ERROR;
6800 retval |= IRQ_HANDLED;
6803 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_DME);
6804 if ((reg & UIC_DME_ERROR) &&
6805 (reg & UIC_DME_ERROR_CODE_MASK)) {
6806 ufshcd_update_evt_hist(hba, UFS_EVT_DME_ERR, reg);
6807 hba->uic_error |= UFSHCD_UIC_DME_ERROR;
6808 retval |= IRQ_HANDLED;
6811 dev_dbg(hba->dev, "%s: UIC error flags = 0x%08x\n",
6812 __func__, hba->uic_error);
6817 * ufshcd_check_errors - Check for errors that need s/w attention
6818 * @hba: per-adapter instance
6819 * @intr_status: interrupt status generated by the controller
6822 * IRQ_HANDLED - If interrupt is valid
6823 * IRQ_NONE - If invalid interrupt
6825 static irqreturn_t ufshcd_check_errors(struct ufs_hba *hba, u32 intr_status)
6827 bool queue_eh_work = false;
6828 irqreturn_t retval = IRQ_NONE;
6830 spin_lock(hba->host->host_lock);
6831 hba->errors |= UFSHCD_ERROR_MASK & intr_status;
6833 if (hba->errors & INT_FATAL_ERRORS) {
6834 ufshcd_update_evt_hist(hba, UFS_EVT_FATAL_ERR,
6836 queue_eh_work = true;
6839 if (hba->errors & UIC_ERROR) {
6841 retval = ufshcd_update_uic_error(hba);
6843 queue_eh_work = true;
6846 if (hba->errors & UFSHCD_UIC_HIBERN8_MASK) {
6848 "%s: Auto Hibern8 %s failed - status: 0x%08x, upmcrs: 0x%08x\n",
6849 __func__, (hba->errors & UIC_HIBERNATE_ENTER) ?
6851 hba->errors, ufshcd_get_upmcrs(hba));
6852 ufshcd_update_evt_hist(hba, UFS_EVT_AUTO_HIBERN8_ERR,
6854 ufshcd_set_link_broken(hba);
6855 queue_eh_work = true;
6858 if (queue_eh_work) {
6860 * update the transfer error masks to sticky bits, let's do this
6861 * irrespective of current ufshcd_state.
6863 hba->saved_err |= hba->errors;
6864 hba->saved_uic_err |= hba->uic_error;
6866 /* dump controller state before resetting */
6867 if ((hba->saved_err &
6868 (INT_FATAL_ERRORS | UFSHCD_UIC_HIBERN8_MASK)) ||
6869 (hba->saved_uic_err &&
6870 (hba->saved_uic_err != UFSHCD_UIC_PA_GENERIC_ERROR))) {
6871 dev_err(hba->dev, "%s: saved_err 0x%x saved_uic_err 0x%x\n",
6872 __func__, hba->saved_err,
6873 hba->saved_uic_err);
6874 ufshcd_dump_regs(hba, 0, UFSHCI_REG_SPACE_SIZE,
6876 ufshcd_print_pwr_info(hba);
6878 ufshcd_schedule_eh_work(hba);
6879 retval |= IRQ_HANDLED;
6882 * if (!queue_eh_work) -
6883 * Other errors are either non-fatal where host recovers
6884 * itself without s/w intervention or errors that will be
6885 * handled by the SCSI core layer.
6889 spin_unlock(hba->host->host_lock);
6894 * ufshcd_tmc_handler - handle task management function completion
6895 * @hba: per adapter instance
6898 * IRQ_HANDLED - If interrupt is valid
6899 * IRQ_NONE - If invalid interrupt
6901 static irqreturn_t ufshcd_tmc_handler(struct ufs_hba *hba)
6903 unsigned long flags, pending, issued;
6904 irqreturn_t ret = IRQ_NONE;
6907 spin_lock_irqsave(hba->host->host_lock, flags);
6908 pending = ufshcd_readl(hba, REG_UTP_TASK_REQ_DOOR_BELL);
6909 issued = hba->outstanding_tasks & ~pending;
6910 for_each_set_bit(tag, &issued, hba->nutmrs) {
6911 struct request *req = hba->tmf_rqs[tag];
6912 struct completion *c = req->end_io_data;
6917 spin_unlock_irqrestore(hba->host->host_lock, flags);
6923 * ufshcd_handle_mcq_cq_events - handle MCQ completion queue events
6924 * @hba: per adapter instance
6926 * Return: IRQ_HANDLED if interrupt is handled.
6928 static irqreturn_t ufshcd_handle_mcq_cq_events(struct ufs_hba *hba)
6930 struct ufs_hw_queue *hwq;
6931 unsigned long outstanding_cqs;
6932 unsigned int nr_queues;
6936 ret = ufshcd_vops_get_outstanding_cqs(hba, &outstanding_cqs);
6938 outstanding_cqs = (1U << hba->nr_hw_queues) - 1;
6940 /* Exclude the poll queues */
6941 nr_queues = hba->nr_hw_queues - hba->nr_queues[HCTX_TYPE_POLL];
6942 for_each_set_bit(i, &outstanding_cqs, nr_queues) {
6945 events = ufshcd_mcq_read_cqis(hba, i);
6947 ufshcd_mcq_write_cqis(hba, events, i);
6949 if (events & UFSHCD_MCQ_CQIS_TAIL_ENT_PUSH_STS)
6950 ufshcd_mcq_poll_cqe_lock(hba, hwq);
6957 * ufshcd_sl_intr - Interrupt service routine
6958 * @hba: per adapter instance
6959 * @intr_status: contains interrupts generated by the controller
6962 * IRQ_HANDLED - If interrupt is valid
6963 * IRQ_NONE - If invalid interrupt
6965 static irqreturn_t ufshcd_sl_intr(struct ufs_hba *hba, u32 intr_status)
6967 irqreturn_t retval = IRQ_NONE;
6969 if (intr_status & UFSHCD_UIC_MASK)
6970 retval |= ufshcd_uic_cmd_compl(hba, intr_status);
6972 if (intr_status & UFSHCD_ERROR_MASK || hba->errors)
6973 retval |= ufshcd_check_errors(hba, intr_status);
6975 if (intr_status & UTP_TASK_REQ_COMPL)
6976 retval |= ufshcd_tmc_handler(hba);
6978 if (intr_status & UTP_TRANSFER_REQ_COMPL)
6979 retval |= ufshcd_transfer_req_compl(hba);
6981 if (intr_status & MCQ_CQ_EVENT_STATUS)
6982 retval |= ufshcd_handle_mcq_cq_events(hba);
6988 * ufshcd_intr - Main interrupt service routine
6990 * @__hba: pointer to adapter instance
6993 * IRQ_HANDLED - If interrupt is valid
6994 * IRQ_NONE - If invalid interrupt
6996 static irqreturn_t ufshcd_intr(int irq, void *__hba)
6998 u32 intr_status, enabled_intr_status = 0;
6999 irqreturn_t retval = IRQ_NONE;
7000 struct ufs_hba *hba = __hba;
7001 int retries = hba->nutrs;
7003 intr_status = ufshcd_readl(hba, REG_INTERRUPT_STATUS);
7004 hba->ufs_stats.last_intr_status = intr_status;
7005 hba->ufs_stats.last_intr_ts = local_clock();
7008 * There could be max of hba->nutrs reqs in flight and in worst case
7009 * if the reqs get finished 1 by 1 after the interrupt status is
7010 * read, make sure we handle them by checking the interrupt status
7011 * again in a loop until we process all of the reqs before returning.
7013 while (intr_status && retries--) {
7014 enabled_intr_status =
7015 intr_status & ufshcd_readl(hba, REG_INTERRUPT_ENABLE);
7016 ufshcd_writel(hba, intr_status, REG_INTERRUPT_STATUS);
7017 if (enabled_intr_status)
7018 retval |= ufshcd_sl_intr(hba, enabled_intr_status);
7020 intr_status = ufshcd_readl(hba, REG_INTERRUPT_STATUS);
7023 if (enabled_intr_status && retval == IRQ_NONE &&
7024 (!(enabled_intr_status & UTP_TRANSFER_REQ_COMPL) ||
7025 hba->outstanding_reqs) && !ufshcd_eh_in_progress(hba)) {
7026 dev_err(hba->dev, "%s: Unhandled interrupt 0x%08x (0x%08x, 0x%08x)\n",
7029 hba->ufs_stats.last_intr_status,
7030 enabled_intr_status);
7031 ufshcd_dump_regs(hba, 0, UFSHCI_REG_SPACE_SIZE, "host_regs: ");
7037 static int ufshcd_clear_tm_cmd(struct ufs_hba *hba, int tag)
7040 u32 mask = 1 << tag;
7041 unsigned long flags;
7043 if (!test_bit(tag, &hba->outstanding_tasks))
7046 spin_lock_irqsave(hba->host->host_lock, flags);
7047 ufshcd_utmrl_clear(hba, tag);
7048 spin_unlock_irqrestore(hba->host->host_lock, flags);
7050 /* poll for max. 1 sec to clear door bell register by h/w */
7051 err = ufshcd_wait_for_register(hba,
7052 REG_UTP_TASK_REQ_DOOR_BELL,
7053 mask, 0, 1000, 1000);
7055 dev_err(hba->dev, "Clearing task management function with tag %d %s\n",
7056 tag, err < 0 ? "failed" : "succeeded");
7062 static int __ufshcd_issue_tm_cmd(struct ufs_hba *hba,
7063 struct utp_task_req_desc *treq, u8 tm_function)
7065 struct request_queue *q = hba->tmf_queue;
7066 struct Scsi_Host *host = hba->host;
7067 DECLARE_COMPLETION_ONSTACK(wait);
7068 struct request *req;
7069 unsigned long flags;
7073 * blk_mq_alloc_request() is used here only to get a free tag.
7075 req = blk_mq_alloc_request(q, REQ_OP_DRV_OUT, 0);
7077 return PTR_ERR(req);
7079 req->end_io_data = &wait;
7082 spin_lock_irqsave(host->host_lock, flags);
7084 task_tag = req->tag;
7085 hba->tmf_rqs[req->tag] = req;
7086 treq->upiu_req.req_header.task_tag = task_tag;
7088 memcpy(hba->utmrdl_base_addr + task_tag, treq, sizeof(*treq));
7089 ufshcd_vops_setup_task_mgmt(hba, task_tag, tm_function);
7091 /* send command to the controller */
7092 __set_bit(task_tag, &hba->outstanding_tasks);
7094 ufshcd_writel(hba, 1 << task_tag, REG_UTP_TASK_REQ_DOOR_BELL);
7095 /* Make sure that doorbell is committed immediately */
7098 spin_unlock_irqrestore(host->host_lock, flags);
7100 ufshcd_add_tm_upiu_trace(hba, task_tag, UFS_TM_SEND);
7102 /* wait until the task management command is completed */
7103 err = wait_for_completion_io_timeout(&wait,
7104 msecs_to_jiffies(TM_CMD_TIMEOUT));
7106 ufshcd_add_tm_upiu_trace(hba, task_tag, UFS_TM_ERR);
7107 dev_err(hba->dev, "%s: task management cmd 0x%.2x timed-out\n",
7108 __func__, tm_function);
7109 if (ufshcd_clear_tm_cmd(hba, task_tag))
7110 dev_WARN(hba->dev, "%s: unable to clear tm cmd (slot %d) after timeout\n",
7111 __func__, task_tag);
7115 memcpy(treq, hba->utmrdl_base_addr + task_tag, sizeof(*treq));
7117 ufshcd_add_tm_upiu_trace(hba, task_tag, UFS_TM_COMP);
7120 spin_lock_irqsave(hba->host->host_lock, flags);
7121 hba->tmf_rqs[req->tag] = NULL;
7122 __clear_bit(task_tag, &hba->outstanding_tasks);
7123 spin_unlock_irqrestore(hba->host->host_lock, flags);
7125 ufshcd_release(hba);
7126 blk_mq_free_request(req);
7132 * ufshcd_issue_tm_cmd - issues task management commands to controller
7133 * @hba: per adapter instance
7134 * @lun_id: LUN ID to which TM command is sent
7135 * @task_id: task ID to which the TM command is applicable
7136 * @tm_function: task management function opcode
7137 * @tm_response: task management service response return value
7139 * Return: non-zero value on error, zero on success.
7141 static int ufshcd_issue_tm_cmd(struct ufs_hba *hba, int lun_id, int task_id,
7142 u8 tm_function, u8 *tm_response)
7144 struct utp_task_req_desc treq = { };
7145 enum utp_ocs ocs_value;
7148 /* Configure task request descriptor */
7149 treq.header.interrupt = 1;
7150 treq.header.ocs = OCS_INVALID_COMMAND_STATUS;
7152 /* Configure task request UPIU */
7153 treq.upiu_req.req_header.transaction_code = UPIU_TRANSACTION_TASK_REQ;
7154 treq.upiu_req.req_header.lun = lun_id;
7155 treq.upiu_req.req_header.tm_function = tm_function;
7158 * The host shall provide the same value for LUN field in the basic
7159 * header and for Input Parameter.
7161 treq.upiu_req.input_param1 = cpu_to_be32(lun_id);
7162 treq.upiu_req.input_param2 = cpu_to_be32(task_id);
7164 err = __ufshcd_issue_tm_cmd(hba, &treq, tm_function);
7165 if (err == -ETIMEDOUT)
7168 ocs_value = treq.header.ocs & MASK_OCS;
7169 if (ocs_value != OCS_SUCCESS)
7170 dev_err(hba->dev, "%s: failed, ocs = 0x%x\n",
7171 __func__, ocs_value);
7172 else if (tm_response)
7173 *tm_response = be32_to_cpu(treq.upiu_rsp.output_param1) &
7174 MASK_TM_SERVICE_RESP;
7179 * ufshcd_issue_devman_upiu_cmd - API for sending "utrd" type requests
7180 * @hba: per-adapter instance
7181 * @req_upiu: upiu request
7182 * @rsp_upiu: upiu reply
7183 * @desc_buff: pointer to descriptor buffer, NULL if NA
7184 * @buff_len: descriptor size, 0 if NA
7185 * @cmd_type: specifies the type (NOP, Query...)
7186 * @desc_op: descriptor operation
7188 * Those type of requests uses UTP Transfer Request Descriptor - utrd.
7189 * Therefore, it "rides" the device management infrastructure: uses its tag and
7190 * tasks work queues.
7192 * Since there is only one available tag for device management commands,
7193 * the caller is expected to hold the hba->dev_cmd.lock mutex.
7195 * Return: 0 upon success; < 0 upon failure.
7197 static int ufshcd_issue_devman_upiu_cmd(struct ufs_hba *hba,
7198 struct utp_upiu_req *req_upiu,
7199 struct utp_upiu_req *rsp_upiu,
7200 u8 *desc_buff, int *buff_len,
7201 enum dev_cmd_type cmd_type,
7202 enum query_opcode desc_op)
7204 DECLARE_COMPLETION_ONSTACK(wait);
7205 const u32 tag = hba->reserved_slot;
7206 struct ufshcd_lrb *lrbp;
7210 /* Protects use of hba->reserved_slot. */
7211 lockdep_assert_held(&hba->dev_cmd.lock);
7213 down_read(&hba->clk_scaling_lock);
7215 lrbp = &hba->lrb[tag];
7217 lrbp->task_tag = tag;
7219 lrbp->intr_cmd = true;
7220 ufshcd_prepare_lrbp_crypto(NULL, lrbp);
7221 hba->dev_cmd.type = cmd_type;
7223 if (hba->ufs_version <= ufshci_version(1, 1))
7224 lrbp->command_type = UTP_CMD_TYPE_DEV_MANAGE;
7226 lrbp->command_type = UTP_CMD_TYPE_UFS_STORAGE;
7228 /* update the task tag in the request upiu */
7229 req_upiu->header.task_tag = tag;
7231 ufshcd_prepare_req_desc_hdr(lrbp, &upiu_flags, DMA_NONE, 0);
7233 /* just copy the upiu request as it is */
7234 memcpy(lrbp->ucd_req_ptr, req_upiu, sizeof(*lrbp->ucd_req_ptr));
7235 if (desc_buff && desc_op == UPIU_QUERY_OPCODE_WRITE_DESC) {
7236 /* The Data Segment Area is optional depending upon the query
7237 * function value. for WRITE DESCRIPTOR, the data segment
7238 * follows right after the tsf.
7240 memcpy(lrbp->ucd_req_ptr + 1, desc_buff, *buff_len);
7244 memset(lrbp->ucd_rsp_ptr, 0, sizeof(struct utp_upiu_rsp));
7246 hba->dev_cmd.complete = &wait;
7248 ufshcd_add_query_upiu_trace(hba, UFS_QUERY_SEND, lrbp->ucd_req_ptr);
7250 ufshcd_send_command(hba, tag, hba->dev_cmd_queue);
7252 * ignore the returning value here - ufshcd_check_query_response is
7253 * bound to fail since dev_cmd.query and dev_cmd.type were left empty.
7254 * read the response directly ignoring all errors.
7256 ufshcd_wait_for_dev_cmd(hba, lrbp, QUERY_REQ_TIMEOUT);
7258 /* just copy the upiu response as it is */
7259 memcpy(rsp_upiu, lrbp->ucd_rsp_ptr, sizeof(*rsp_upiu));
7260 if (desc_buff && desc_op == UPIU_QUERY_OPCODE_READ_DESC) {
7261 u8 *descp = (u8 *)lrbp->ucd_rsp_ptr + sizeof(*rsp_upiu);
7262 u16 resp_len = be16_to_cpu(lrbp->ucd_rsp_ptr->header
7263 .data_segment_length);
7265 if (*buff_len >= resp_len) {
7266 memcpy(desc_buff, descp, resp_len);
7267 *buff_len = resp_len;
7270 "%s: rsp size %d is bigger than buffer size %d",
7271 __func__, resp_len, *buff_len);
7276 ufshcd_add_query_upiu_trace(hba, err ? UFS_QUERY_ERR : UFS_QUERY_COMP,
7277 (struct utp_upiu_req *)lrbp->ucd_rsp_ptr);
7279 up_read(&hba->clk_scaling_lock);
7284 * ufshcd_exec_raw_upiu_cmd - API function for sending raw upiu commands
7285 * @hba: per-adapter instance
7286 * @req_upiu: upiu request
7287 * @rsp_upiu: upiu reply - only 8 DW as we do not support scsi commands
7288 * @msgcode: message code, one of UPIU Transaction Codes Initiator to Target
7289 * @desc_buff: pointer to descriptor buffer, NULL if NA
7290 * @buff_len: descriptor size, 0 if NA
7291 * @desc_op: descriptor operation
7293 * Supports UTP Transfer requests (nop and query), and UTP Task
7294 * Management requests.
7295 * It is up to the caller to fill the upiu conent properly, as it will
7296 * be copied without any further input validations.
7298 * Return: 0 upon success; < 0 upon failure.
7300 int ufshcd_exec_raw_upiu_cmd(struct ufs_hba *hba,
7301 struct utp_upiu_req *req_upiu,
7302 struct utp_upiu_req *rsp_upiu,
7303 enum upiu_request_transaction msgcode,
7304 u8 *desc_buff, int *buff_len,
7305 enum query_opcode desc_op)
7308 enum dev_cmd_type cmd_type = DEV_CMD_TYPE_QUERY;
7309 struct utp_task_req_desc treq = { };
7310 enum utp_ocs ocs_value;
7311 u8 tm_f = req_upiu->header.tm_function;
7314 case UPIU_TRANSACTION_NOP_OUT:
7315 cmd_type = DEV_CMD_TYPE_NOP;
7317 case UPIU_TRANSACTION_QUERY_REQ:
7319 mutex_lock(&hba->dev_cmd.lock);
7320 err = ufshcd_issue_devman_upiu_cmd(hba, req_upiu, rsp_upiu,
7321 desc_buff, buff_len,
7323 mutex_unlock(&hba->dev_cmd.lock);
7324 ufshcd_release(hba);
7327 case UPIU_TRANSACTION_TASK_REQ:
7328 treq.header.interrupt = 1;
7329 treq.header.ocs = OCS_INVALID_COMMAND_STATUS;
7331 memcpy(&treq.upiu_req, req_upiu, sizeof(*req_upiu));
7333 err = __ufshcd_issue_tm_cmd(hba, &treq, tm_f);
7334 if (err == -ETIMEDOUT)
7337 ocs_value = treq.header.ocs & MASK_OCS;
7338 if (ocs_value != OCS_SUCCESS) {
7339 dev_err(hba->dev, "%s: failed, ocs = 0x%x\n", __func__,
7344 memcpy(rsp_upiu, &treq.upiu_rsp, sizeof(*rsp_upiu));
7357 * ufshcd_advanced_rpmb_req_handler - handle advanced RPMB request
7358 * @hba: per adapter instance
7359 * @req_upiu: upiu request
7360 * @rsp_upiu: upiu reply
7361 * @req_ehs: EHS field which contains Advanced RPMB Request Message
7362 * @rsp_ehs: EHS field which returns Advanced RPMB Response Message
7363 * @sg_cnt: The number of sg lists actually used
7364 * @sg_list: Pointer to SG list when DATA IN/OUT UPIU is required in ARPMB operation
7365 * @dir: DMA direction
7367 * Return: zero on success, non-zero on failure.
7369 int ufshcd_advanced_rpmb_req_handler(struct ufs_hba *hba, struct utp_upiu_req *req_upiu,
7370 struct utp_upiu_req *rsp_upiu, struct ufs_ehs *req_ehs,
7371 struct ufs_ehs *rsp_ehs, int sg_cnt, struct scatterlist *sg_list,
7372 enum dma_data_direction dir)
7374 DECLARE_COMPLETION_ONSTACK(wait);
7375 const u32 tag = hba->reserved_slot;
7376 struct ufshcd_lrb *lrbp;
7383 /* Protects use of hba->reserved_slot. */
7385 mutex_lock(&hba->dev_cmd.lock);
7386 down_read(&hba->clk_scaling_lock);
7388 lrbp = &hba->lrb[tag];
7390 lrbp->task_tag = tag;
7391 lrbp->lun = UFS_UPIU_RPMB_WLUN;
7393 lrbp->intr_cmd = true;
7394 ufshcd_prepare_lrbp_crypto(NULL, lrbp);
7395 hba->dev_cmd.type = DEV_CMD_TYPE_RPMB;
7397 /* Advanced RPMB starts from UFS 4.0, so its command type is UTP_CMD_TYPE_UFS_STORAGE */
7398 lrbp->command_type = UTP_CMD_TYPE_UFS_STORAGE;
7401 * According to UFSHCI 4.0 specification page 24, if EHSLUTRDS is 0, host controller takes
7402 * EHS length from CMD UPIU, and SW driver use EHS Length field in CMD UPIU. if it is 1,
7403 * HW controller takes EHS length from UTRD.
7405 if (hba->capabilities & MASK_EHSLUTRD_SUPPORTED)
7406 ufshcd_prepare_req_desc_hdr(lrbp, &upiu_flags, dir, 2);
7408 ufshcd_prepare_req_desc_hdr(lrbp, &upiu_flags, dir, 0);
7410 /* update the task tag */
7411 req_upiu->header.task_tag = tag;
7413 /* copy the UPIU(contains CDB) request as it is */
7414 memcpy(lrbp->ucd_req_ptr, req_upiu, sizeof(*lrbp->ucd_req_ptr));
7415 /* Copy EHS, starting with byte32, immediately after the CDB package */
7416 memcpy(lrbp->ucd_req_ptr + 1, req_ehs, sizeof(*req_ehs));
7418 if (dir != DMA_NONE && sg_list)
7419 ufshcd_sgl_to_prdt(hba, lrbp, sg_cnt, sg_list);
7421 memset(lrbp->ucd_rsp_ptr, 0, sizeof(struct utp_upiu_rsp));
7423 hba->dev_cmd.complete = &wait;
7425 ufshcd_send_command(hba, tag, hba->dev_cmd_queue);
7427 err = ufshcd_wait_for_dev_cmd(hba, lrbp, ADVANCED_RPMB_REQ_TIMEOUT);
7430 /* Just copy the upiu response as it is */
7431 memcpy(rsp_upiu, lrbp->ucd_rsp_ptr, sizeof(*rsp_upiu));
7432 /* Get the response UPIU result */
7433 result = (lrbp->ucd_rsp_ptr->header.response << 8) |
7434 lrbp->ucd_rsp_ptr->header.status;
7436 ehs_len = lrbp->ucd_rsp_ptr->header.ehs_length;
7438 * Since the bLength in EHS indicates the total size of the EHS Header and EHS Data
7439 * in 32 Byte units, the value of the bLength Request/Response for Advanced RPMB
7442 if (ehs_len == 2 && rsp_ehs) {
7444 * ucd_rsp_ptr points to a buffer with a length of 512 bytes
7445 * (ALIGNED_UPIU_SIZE = 512), and the EHS data just starts from byte32
7447 ehs_data = (u8 *)lrbp->ucd_rsp_ptr + EHS_OFFSET_IN_RESPONSE;
7448 memcpy(rsp_ehs, ehs_data, ehs_len * 32);
7452 up_read(&hba->clk_scaling_lock);
7453 mutex_unlock(&hba->dev_cmd.lock);
7454 ufshcd_release(hba);
7455 return err ? : result;
7459 * ufshcd_eh_device_reset_handler() - Reset a single logical unit.
7460 * @cmd: SCSI command pointer
7462 * Return: SUCCESS or FAILED.
7464 static int ufshcd_eh_device_reset_handler(struct scsi_cmnd *cmd)
7466 unsigned long flags, pending_reqs = 0, not_cleared = 0;
7467 struct Scsi_Host *host;
7468 struct ufs_hba *hba;
7469 struct ufs_hw_queue *hwq;
7470 struct ufshcd_lrb *lrbp;
7471 u32 pos, not_cleared_mask = 0;
7475 host = cmd->device->host;
7476 hba = shost_priv(host);
7478 lun = ufshcd_scsi_to_upiu_lun(cmd->device->lun);
7479 err = ufshcd_issue_tm_cmd(hba, lun, 0, UFS_LOGICAL_RESET, &resp);
7480 if (err || resp != UPIU_TASK_MANAGEMENT_FUNC_COMPL) {
7486 if (is_mcq_enabled(hba)) {
7487 for (pos = 0; pos < hba->nutrs; pos++) {
7488 lrbp = &hba->lrb[pos];
7489 if (ufshcd_cmd_inflight(lrbp->cmd) &&
7491 ufshcd_clear_cmd(hba, pos);
7492 hwq = ufshcd_mcq_req_to_hwq(hba, scsi_cmd_to_rq(lrbp->cmd));
7493 ufshcd_mcq_poll_cqe_lock(hba, hwq);
7500 /* clear the commands that were pending for corresponding LUN */
7501 spin_lock_irqsave(&hba->outstanding_lock, flags);
7502 for_each_set_bit(pos, &hba->outstanding_reqs, hba->nutrs)
7503 if (hba->lrb[pos].lun == lun)
7504 __set_bit(pos, &pending_reqs);
7505 hba->outstanding_reqs &= ~pending_reqs;
7506 spin_unlock_irqrestore(&hba->outstanding_lock, flags);
7508 for_each_set_bit(pos, &pending_reqs, hba->nutrs) {
7509 if (ufshcd_clear_cmd(hba, pos) < 0) {
7510 spin_lock_irqsave(&hba->outstanding_lock, flags);
7511 not_cleared = 1U << pos &
7512 ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
7513 hba->outstanding_reqs |= not_cleared;
7514 not_cleared_mask |= not_cleared;
7515 spin_unlock_irqrestore(&hba->outstanding_lock, flags);
7517 dev_err(hba->dev, "%s: failed to clear request %d\n",
7521 __ufshcd_transfer_req_compl(hba, pending_reqs & ~not_cleared_mask);
7524 hba->req_abort_count = 0;
7525 ufshcd_update_evt_hist(hba, UFS_EVT_DEV_RESET, (u32)err);
7529 dev_err(hba->dev, "%s: failed with err %d\n", __func__, err);
7535 static void ufshcd_set_req_abort_skip(struct ufs_hba *hba, unsigned long bitmap)
7537 struct ufshcd_lrb *lrbp;
7540 for_each_set_bit(tag, &bitmap, hba->nutrs) {
7541 lrbp = &hba->lrb[tag];
7542 lrbp->req_abort_skip = true;
7547 * ufshcd_try_to_abort_task - abort a specific task
7548 * @hba: Pointer to adapter instance
7549 * @tag: Task tag/index to be aborted
7551 * Abort the pending command in device by sending UFS_ABORT_TASK task management
7552 * command, and in host controller by clearing the door-bell register. There can
7553 * be race between controller sending the command to the device while abort is
7554 * issued. To avoid that, first issue UFS_QUERY_TASK to check if the command is
7555 * really issued and then try to abort it.
7557 * Return: zero on success, non-zero on failure.
7559 int ufshcd_try_to_abort_task(struct ufs_hba *hba, int tag)
7561 struct ufshcd_lrb *lrbp = &hba->lrb[tag];
7567 for (poll_cnt = 100; poll_cnt; poll_cnt--) {
7568 err = ufshcd_issue_tm_cmd(hba, lrbp->lun, lrbp->task_tag,
7569 UFS_QUERY_TASK, &resp);
7570 if (!err && resp == UPIU_TASK_MANAGEMENT_FUNC_SUCCEEDED) {
7571 /* cmd pending in the device */
7572 dev_err(hba->dev, "%s: cmd pending in the device. tag = %d\n",
7575 } else if (!err && resp == UPIU_TASK_MANAGEMENT_FUNC_COMPL) {
7577 * cmd not pending in the device, check if it is
7580 dev_err(hba->dev, "%s: cmd at tag %d not pending in the device.\n",
7582 if (is_mcq_enabled(hba)) {
7584 if (ufshcd_cmd_inflight(lrbp->cmd)) {
7585 /* sleep for max. 200us same delay as in SDB mode */
7586 usleep_range(100, 200);
7589 /* command completed already */
7590 dev_err(hba->dev, "%s: cmd at tag=%d is cleared.\n",
7595 /* Single Doorbell Mode */
7596 reg = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
7597 if (reg & (1 << tag)) {
7598 /* sleep for max. 200us to stabilize */
7599 usleep_range(100, 200);
7602 /* command completed already */
7603 dev_err(hba->dev, "%s: cmd at tag %d successfully cleared from DB.\n",
7608 "%s: no response from device. tag = %d, err %d\n",
7609 __func__, tag, err);
7611 err = resp; /* service response error */
7621 err = ufshcd_issue_tm_cmd(hba, lrbp->lun, lrbp->task_tag,
7622 UFS_ABORT_TASK, &resp);
7623 if (err || resp != UPIU_TASK_MANAGEMENT_FUNC_COMPL) {
7625 err = resp; /* service response error */
7626 dev_err(hba->dev, "%s: issued. tag = %d, err %d\n",
7627 __func__, tag, err);
7632 err = ufshcd_clear_cmd(hba, tag);
7634 dev_err(hba->dev, "%s: Failed clearing cmd at tag %d, err %d\n",
7635 __func__, tag, err);
7642 * ufshcd_abort - scsi host template eh_abort_handler callback
7643 * @cmd: SCSI command pointer
7645 * Return: SUCCESS or FAILED.
7647 static int ufshcd_abort(struct scsi_cmnd *cmd)
7649 struct Scsi_Host *host = cmd->device->host;
7650 struct ufs_hba *hba = shost_priv(host);
7651 int tag = scsi_cmd_to_rq(cmd)->tag;
7652 struct ufshcd_lrb *lrbp = &hba->lrb[tag];
7653 unsigned long flags;
7660 if (!is_mcq_enabled(hba)) {
7661 reg = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
7662 if (!test_bit(tag, &hba->outstanding_reqs)) {
7663 /* If command is already aborted/completed, return FAILED. */
7665 "%s: cmd at tag %d already completed, outstanding=0x%lx, doorbell=0x%x\n",
7666 __func__, tag, hba->outstanding_reqs, reg);
7671 /* Print Transfer Request of aborted task */
7672 dev_info(hba->dev, "%s: Device abort task at tag %d\n", __func__, tag);
7675 * Print detailed info about aborted request.
7676 * As more than one request might get aborted at the same time,
7677 * print full information only for the first aborted request in order
7678 * to reduce repeated printouts. For other aborted requests only print
7681 scsi_print_command(cmd);
7682 if (!hba->req_abort_count) {
7683 ufshcd_update_evt_hist(hba, UFS_EVT_ABORT, tag);
7684 ufshcd_print_evt_hist(hba);
7685 ufshcd_print_host_state(hba);
7686 ufshcd_print_pwr_info(hba);
7687 ufshcd_print_tr(hba, tag, true);
7689 ufshcd_print_tr(hba, tag, false);
7691 hba->req_abort_count++;
7693 if (!is_mcq_enabled(hba) && !(reg & (1 << tag))) {
7694 /* only execute this code in single doorbell mode */
7696 "%s: cmd was completed, but without a notifying intr, tag = %d",
7698 __ufshcd_transfer_req_compl(hba, 1UL << tag);
7703 * Task abort to the device W-LUN is illegal. When this command
7704 * will fail, due to spec violation, scsi err handling next step
7705 * will be to send LU reset which, again, is a spec violation.
7706 * To avoid these unnecessary/illegal steps, first we clean up
7707 * the lrb taken by this cmd and re-set it in outstanding_reqs,
7708 * then queue the eh_work and bail.
7710 if (lrbp->lun == UFS_UPIU_UFS_DEVICE_WLUN) {
7711 ufshcd_update_evt_hist(hba, UFS_EVT_ABORT, lrbp->lun);
7713 spin_lock_irqsave(host->host_lock, flags);
7714 hba->force_reset = true;
7715 ufshcd_schedule_eh_work(hba);
7716 spin_unlock_irqrestore(host->host_lock, flags);
7720 if (is_mcq_enabled(hba)) {
7721 /* MCQ mode. Branch off to handle abort for mcq mode */
7722 err = ufshcd_mcq_abort(cmd);
7726 /* Skip task abort in case previous aborts failed and report failure */
7727 if (lrbp->req_abort_skip) {
7728 dev_err(hba->dev, "%s: skipping abort\n", __func__);
7729 ufshcd_set_req_abort_skip(hba, hba->outstanding_reqs);
7733 err = ufshcd_try_to_abort_task(hba, tag);
7735 dev_err(hba->dev, "%s: failed with err %d\n", __func__, err);
7736 ufshcd_set_req_abort_skip(hba, hba->outstanding_reqs);
7742 * Clear the corresponding bit from outstanding_reqs since the command
7743 * has been aborted successfully.
7745 spin_lock_irqsave(&hba->outstanding_lock, flags);
7746 outstanding = __test_and_clear_bit(tag, &hba->outstanding_reqs);
7747 spin_unlock_irqrestore(&hba->outstanding_lock, flags);
7750 ufshcd_release_scsi_cmd(hba, lrbp);
7755 /* Matches the ufshcd_hold() call at the start of this function. */
7756 ufshcd_release(hba);
7761 * ufshcd_host_reset_and_restore - reset and restore host controller
7762 * @hba: per-adapter instance
7764 * Note that host controller reset may issue DME_RESET to
7765 * local and remote (device) Uni-Pro stack and the attributes
7766 * are reset to default state.
7768 * Return: zero on success, non-zero on failure.
7770 static int ufshcd_host_reset_and_restore(struct ufs_hba *hba)
7775 * Stop the host controller and complete the requests
7778 ufshcd_hba_stop(hba);
7779 hba->silence_err_logs = true;
7780 ufshcd_complete_requests(hba, true);
7781 hba->silence_err_logs = false;
7783 /* scale up clocks to max frequency before full reinitialization */
7784 ufshcd_scale_clks(hba, ULONG_MAX, true);
7786 err = ufshcd_hba_enable(hba);
7788 /* Establish the link again and restore the device */
7790 err = ufshcd_probe_hba(hba, false);
7793 dev_err(hba->dev, "%s: Host init failed %d\n", __func__, err);
7794 ufshcd_update_evt_hist(hba, UFS_EVT_HOST_RESET, (u32)err);
7799 * ufshcd_reset_and_restore - reset and re-initialize host/device
7800 * @hba: per-adapter instance
7802 * Reset and recover device, host and re-establish link. This
7803 * is helpful to recover the communication in fatal error conditions.
7805 * Return: zero on success, non-zero on failure.
7807 static int ufshcd_reset_and_restore(struct ufs_hba *hba)
7810 u32 saved_uic_err = 0;
7812 unsigned long flags;
7813 int retries = MAX_HOST_RESET_RETRIES;
7815 spin_lock_irqsave(hba->host->host_lock, flags);
7818 * This is a fresh start, cache and clear saved error first,
7819 * in case new error generated during reset and restore.
7821 saved_err |= hba->saved_err;
7822 saved_uic_err |= hba->saved_uic_err;
7824 hba->saved_uic_err = 0;
7825 hba->force_reset = false;
7826 hba->ufshcd_state = UFSHCD_STATE_RESET;
7827 spin_unlock_irqrestore(hba->host->host_lock, flags);
7829 /* Reset the attached device */
7830 ufshcd_device_reset(hba);
7832 err = ufshcd_host_reset_and_restore(hba);
7834 spin_lock_irqsave(hba->host->host_lock, flags);
7837 /* Do not exit unless operational or dead */
7838 if (hba->ufshcd_state != UFSHCD_STATE_OPERATIONAL &&
7839 hba->ufshcd_state != UFSHCD_STATE_ERROR &&
7840 hba->ufshcd_state != UFSHCD_STATE_EH_SCHEDULED_NON_FATAL)
7842 } while (err && --retries);
7845 * Inform scsi mid-layer that we did reset and allow to handle
7846 * Unit Attention properly.
7848 scsi_report_bus_reset(hba->host, 0);
7850 hba->ufshcd_state = UFSHCD_STATE_ERROR;
7851 hba->saved_err |= saved_err;
7852 hba->saved_uic_err |= saved_uic_err;
7854 spin_unlock_irqrestore(hba->host->host_lock, flags);
7860 * ufshcd_eh_host_reset_handler - host reset handler registered to scsi layer
7861 * @cmd: SCSI command pointer
7863 * Return: SUCCESS or FAILED.
7865 static int ufshcd_eh_host_reset_handler(struct scsi_cmnd *cmd)
7868 unsigned long flags;
7869 struct ufs_hba *hba;
7871 hba = shost_priv(cmd->device->host);
7874 * If runtime PM sent SSU and got a timeout, scsi_error_handler is
7875 * stuck in this function waiting for flush_work(&hba->eh_work). And
7876 * ufshcd_err_handler(eh_work) is stuck waiting for runtime PM. Do
7877 * ufshcd_link_recovery instead of eh_work to prevent deadlock.
7879 if (hba->pm_op_in_progress) {
7880 if (ufshcd_link_recovery(hba))
7886 spin_lock_irqsave(hba->host->host_lock, flags);
7887 hba->force_reset = true;
7888 ufshcd_schedule_eh_work(hba);
7889 dev_err(hba->dev, "%s: reset in progress - 1\n", __func__);
7890 spin_unlock_irqrestore(hba->host->host_lock, flags);
7892 flush_work(&hba->eh_work);
7894 spin_lock_irqsave(hba->host->host_lock, flags);
7895 if (hba->ufshcd_state == UFSHCD_STATE_ERROR)
7897 spin_unlock_irqrestore(hba->host->host_lock, flags);
7903 * ufshcd_get_max_icc_level - calculate the ICC level
7904 * @sup_curr_uA: max. current supported by the regulator
7905 * @start_scan: row at the desc table to start scan from
7906 * @buff: power descriptor buffer
7908 * Return: calculated max ICC level for specific regulator.
7910 static u32 ufshcd_get_max_icc_level(int sup_curr_uA, u32 start_scan,
7918 for (i = start_scan; i >= 0; i--) {
7919 data = get_unaligned_be16(&buff[2 * i]);
7920 unit = (data & ATTR_ICC_LVL_UNIT_MASK) >>
7921 ATTR_ICC_LVL_UNIT_OFFSET;
7922 curr_uA = data & ATTR_ICC_LVL_VALUE_MASK;
7924 case UFSHCD_NANO_AMP:
7925 curr_uA = curr_uA / 1000;
7927 case UFSHCD_MILI_AMP:
7928 curr_uA = curr_uA * 1000;
7931 curr_uA = curr_uA * 1000 * 1000;
7933 case UFSHCD_MICRO_AMP:
7937 if (sup_curr_uA >= curr_uA)
7942 pr_err("%s: Couldn't find valid icc_level = %d", __func__, i);
7949 * ufshcd_find_max_sup_active_icc_level - calculate the max ICC level
7950 * In case regulators are not initialized we'll return 0
7951 * @hba: per-adapter instance
7952 * @desc_buf: power descriptor buffer to extract ICC levels from.
7954 * Return: calculated ICC level.
7956 static u32 ufshcd_find_max_sup_active_icc_level(struct ufs_hba *hba,
7961 if (!hba->vreg_info.vcc || !hba->vreg_info.vccq ||
7962 !hba->vreg_info.vccq2) {
7964 * Using dev_dbg to avoid messages during runtime PM to avoid
7965 * never-ending cycles of messages written back to storage by
7966 * user space causing runtime resume, causing more messages and
7970 "%s: Regulator capability was not set, actvIccLevel=%d",
7971 __func__, icc_level);
7975 if (hba->vreg_info.vcc->max_uA)
7976 icc_level = ufshcd_get_max_icc_level(
7977 hba->vreg_info.vcc->max_uA,
7978 POWER_DESC_MAX_ACTV_ICC_LVLS - 1,
7979 &desc_buf[PWR_DESC_ACTIVE_LVLS_VCC_0]);
7981 if (hba->vreg_info.vccq->max_uA)
7982 icc_level = ufshcd_get_max_icc_level(
7983 hba->vreg_info.vccq->max_uA,
7985 &desc_buf[PWR_DESC_ACTIVE_LVLS_VCCQ_0]);
7987 if (hba->vreg_info.vccq2->max_uA)
7988 icc_level = ufshcd_get_max_icc_level(
7989 hba->vreg_info.vccq2->max_uA,
7991 &desc_buf[PWR_DESC_ACTIVE_LVLS_VCCQ2_0]);
7996 static void ufshcd_set_active_icc_lvl(struct ufs_hba *hba)
8002 desc_buf = kzalloc(QUERY_DESC_MAX_SIZE, GFP_KERNEL);
8006 ret = ufshcd_read_desc_param(hba, QUERY_DESC_IDN_POWER, 0, 0,
8007 desc_buf, QUERY_DESC_MAX_SIZE);
8010 "%s: Failed reading power descriptor ret = %d",
8015 icc_level = ufshcd_find_max_sup_active_icc_level(hba, desc_buf);
8016 dev_dbg(hba->dev, "%s: setting icc_level 0x%x", __func__, icc_level);
8018 ret = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_WRITE_ATTR,
8019 QUERY_ATTR_IDN_ACTIVE_ICC_LVL, 0, 0, &icc_level);
8023 "%s: Failed configuring bActiveICCLevel = %d ret = %d",
8024 __func__, icc_level, ret);
8030 static inline void ufshcd_blk_pm_runtime_init(struct scsi_device *sdev)
8032 struct Scsi_Host *shost = sdev->host;
8034 scsi_autopm_get_device(sdev);
8035 blk_pm_runtime_init(sdev->request_queue, &sdev->sdev_gendev);
8036 if (sdev->rpm_autosuspend)
8037 pm_runtime_set_autosuspend_delay(&sdev->sdev_gendev,
8038 shost->rpm_autosuspend_delay);
8039 scsi_autopm_put_device(sdev);
8043 * ufshcd_scsi_add_wlus - Adds required W-LUs
8044 * @hba: per-adapter instance
8046 * UFS device specification requires the UFS devices to support 4 well known
8048 * "REPORT_LUNS" (address: 01h)
8049 * "UFS Device" (address: 50h)
8050 * "RPMB" (address: 44h)
8051 * "BOOT" (address: 30h)
8052 * UFS device's power management needs to be controlled by "POWER CONDITION"
8053 * field of SSU (START STOP UNIT) command. But this "power condition" field
8054 * will take effect only when its sent to "UFS device" well known logical unit
8055 * hence we require the scsi_device instance to represent this logical unit in
8056 * order for the UFS host driver to send the SSU command for power management.
8058 * We also require the scsi_device instance for "RPMB" (Replay Protected Memory
8059 * Block) LU so user space process can control this LU. User space may also
8060 * want to have access to BOOT LU.
8062 * This function adds scsi device instances for each of all well known LUs
8063 * (except "REPORT LUNS" LU).
8065 * Return: zero on success (all required W-LUs are added successfully),
8066 * non-zero error value on failure (if failed to add any of the required W-LU).
8068 static int ufshcd_scsi_add_wlus(struct ufs_hba *hba)
8071 struct scsi_device *sdev_boot, *sdev_rpmb;
8073 hba->ufs_device_wlun = __scsi_add_device(hba->host, 0, 0,
8074 ufshcd_upiu_wlun_to_scsi_wlun(UFS_UPIU_UFS_DEVICE_WLUN), NULL);
8075 if (IS_ERR(hba->ufs_device_wlun)) {
8076 ret = PTR_ERR(hba->ufs_device_wlun);
8077 hba->ufs_device_wlun = NULL;
8080 scsi_device_put(hba->ufs_device_wlun);
8082 sdev_rpmb = __scsi_add_device(hba->host, 0, 0,
8083 ufshcd_upiu_wlun_to_scsi_wlun(UFS_UPIU_RPMB_WLUN), NULL);
8084 if (IS_ERR(sdev_rpmb)) {
8085 ret = PTR_ERR(sdev_rpmb);
8086 goto remove_ufs_device_wlun;
8088 ufshcd_blk_pm_runtime_init(sdev_rpmb);
8089 scsi_device_put(sdev_rpmb);
8091 sdev_boot = __scsi_add_device(hba->host, 0, 0,
8092 ufshcd_upiu_wlun_to_scsi_wlun(UFS_UPIU_BOOT_WLUN), NULL);
8093 if (IS_ERR(sdev_boot)) {
8094 dev_err(hba->dev, "%s: BOOT WLUN not found\n", __func__);
8096 ufshcd_blk_pm_runtime_init(sdev_boot);
8097 scsi_device_put(sdev_boot);
8101 remove_ufs_device_wlun:
8102 scsi_remove_device(hba->ufs_device_wlun);
8107 static void ufshcd_wb_probe(struct ufs_hba *hba, const u8 *desc_buf)
8109 struct ufs_dev_info *dev_info = &hba->dev_info;
8111 u32 d_lu_wb_buf_alloc;
8112 u32 ext_ufs_feature;
8114 if (!ufshcd_is_wb_allowed(hba))
8118 * Probe WB only for UFS-2.2 and UFS-3.1 (and later) devices or
8119 * UFS devices with quirk UFS_DEVICE_QUIRK_SUPPORT_EXTENDED_FEATURES
8122 if (!(dev_info->wspecversion >= 0x310 ||
8123 dev_info->wspecversion == 0x220 ||
8124 (hba->dev_quirks & UFS_DEVICE_QUIRK_SUPPORT_EXTENDED_FEATURES)))
8127 ext_ufs_feature = get_unaligned_be32(desc_buf +
8128 DEVICE_DESC_PARAM_EXT_UFS_FEATURE_SUP);
8130 if (!(ext_ufs_feature & UFS_DEV_WRITE_BOOSTER_SUP))
8134 * WB may be supported but not configured while provisioning. The spec
8135 * says, in dedicated wb buffer mode, a max of 1 lun would have wb
8136 * buffer configured.
8138 dev_info->wb_buffer_type = desc_buf[DEVICE_DESC_PARAM_WB_TYPE];
8140 dev_info->b_presrv_uspc_en =
8141 desc_buf[DEVICE_DESC_PARAM_WB_PRESRV_USRSPC_EN];
8143 if (dev_info->wb_buffer_type == WB_BUF_MODE_SHARED) {
8144 if (!get_unaligned_be32(desc_buf +
8145 DEVICE_DESC_PARAM_WB_SHARED_ALLOC_UNITS))
8148 for (lun = 0; lun < UFS_UPIU_MAX_WB_LUN_ID; lun++) {
8149 d_lu_wb_buf_alloc = 0;
8150 ufshcd_read_unit_desc_param(hba,
8152 UNIT_DESC_PARAM_WB_BUF_ALLOC_UNITS,
8153 (u8 *)&d_lu_wb_buf_alloc,
8154 sizeof(d_lu_wb_buf_alloc));
8155 if (d_lu_wb_buf_alloc) {
8156 dev_info->wb_dedicated_lu = lun;
8161 if (!d_lu_wb_buf_alloc)
8165 if (!ufshcd_is_wb_buf_lifetime_available(hba))
8171 hba->caps &= ~UFSHCD_CAP_WB_EN;
8174 static void ufshcd_temp_notif_probe(struct ufs_hba *hba, const u8 *desc_buf)
8176 struct ufs_dev_info *dev_info = &hba->dev_info;
8177 u32 ext_ufs_feature;
8180 if (!(hba->caps & UFSHCD_CAP_TEMP_NOTIF) || dev_info->wspecversion < 0x300)
8183 ext_ufs_feature = get_unaligned_be32(desc_buf + DEVICE_DESC_PARAM_EXT_UFS_FEATURE_SUP);
8185 if (ext_ufs_feature & UFS_DEV_LOW_TEMP_NOTIF)
8186 mask |= MASK_EE_TOO_LOW_TEMP;
8188 if (ext_ufs_feature & UFS_DEV_HIGH_TEMP_NOTIF)
8189 mask |= MASK_EE_TOO_HIGH_TEMP;
8192 ufshcd_enable_ee(hba, mask);
8193 ufs_hwmon_probe(hba, mask);
8197 static void ufshcd_ext_iid_probe(struct ufs_hba *hba, u8 *desc_buf)
8199 struct ufs_dev_info *dev_info = &hba->dev_info;
8200 u32 ext_ufs_feature;
8204 /* Only UFS-4.0 and above may support EXT_IID */
8205 if (dev_info->wspecversion < 0x400)
8208 ext_ufs_feature = get_unaligned_be32(desc_buf +
8209 DEVICE_DESC_PARAM_EXT_UFS_FEATURE_SUP);
8210 if (!(ext_ufs_feature & UFS_DEV_EXT_IID_SUP))
8213 err = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
8214 QUERY_ATTR_IDN_EXT_IID_EN, 0, 0, &ext_iid_en);
8216 dev_err(hba->dev, "failed reading bEXTIIDEn. err = %d\n", err);
8219 dev_info->b_ext_iid_en = ext_iid_en;
8222 void ufshcd_fixup_dev_quirks(struct ufs_hba *hba,
8223 const struct ufs_dev_quirk *fixups)
8225 const struct ufs_dev_quirk *f;
8226 struct ufs_dev_info *dev_info = &hba->dev_info;
8231 for (f = fixups; f->quirk; f++) {
8232 if ((f->wmanufacturerid == dev_info->wmanufacturerid ||
8233 f->wmanufacturerid == UFS_ANY_VENDOR) &&
8234 ((dev_info->model &&
8235 STR_PRFX_EQUAL(f->model, dev_info->model)) ||
8236 !strcmp(f->model, UFS_ANY_MODEL)))
8237 hba->dev_quirks |= f->quirk;
8240 EXPORT_SYMBOL_GPL(ufshcd_fixup_dev_quirks);
8242 static void ufs_fixup_device_setup(struct ufs_hba *hba)
8244 /* fix by general quirk table */
8245 ufshcd_fixup_dev_quirks(hba, ufs_fixups);
8247 /* allow vendors to fix quirks */
8248 ufshcd_vops_fixup_dev_quirks(hba);
8251 static void ufshcd_update_rtc(struct ufs_hba *hba)
8253 struct timespec64 ts64;
8257 ktime_get_real_ts64(&ts64);
8259 if (ts64.tv_sec < hba->dev_info.rtc_time_baseline) {
8260 dev_warn_once(hba->dev, "%s: Current time precedes previous setting!\n", __func__);
8265 * The Absolute RTC mode has a 136-year limit, spanning from 2010 to 2146. If a time beyond
8266 * 2146 is required, it is recommended to choose the relative RTC mode.
8268 val = ts64.tv_sec - hba->dev_info.rtc_time_baseline;
8270 ufshcd_rpm_get_sync(hba);
8271 err = ufshcd_query_attr(hba, UPIU_QUERY_OPCODE_WRITE_ATTR, QUERY_ATTR_IDN_SECONDS_PASSED,
8273 ufshcd_rpm_put_sync(hba);
8276 dev_err(hba->dev, "%s: Failed to update rtc %d\n", __func__, err);
8277 else if (hba->dev_info.rtc_type == UFS_RTC_RELATIVE)
8278 hba->dev_info.rtc_time_baseline = ts64.tv_sec;
8281 static void ufshcd_rtc_work(struct work_struct *work)
8283 struct ufs_hba *hba;
8285 hba = container_of(to_delayed_work(work), struct ufs_hba, ufs_rtc_update_work);
8287 /* Update RTC only when there are no requests in progress and UFSHCI is operational */
8288 if (!ufshcd_is_ufs_dev_busy(hba) && hba->ufshcd_state == UFSHCD_STATE_OPERATIONAL)
8289 ufshcd_update_rtc(hba);
8291 if (ufshcd_is_ufs_dev_active(hba) && hba->dev_info.rtc_update_period)
8292 schedule_delayed_work(&hba->ufs_rtc_update_work,
8293 msecs_to_jiffies(hba->dev_info.rtc_update_period));
8296 static void ufs_init_rtc(struct ufs_hba *hba, u8 *desc_buf)
8298 u16 periodic_rtc_update = get_unaligned_be16(&desc_buf[DEVICE_DESC_PARAM_FRQ_RTC]);
8299 struct ufs_dev_info *dev_info = &hba->dev_info;
8301 if (periodic_rtc_update & UFS_RTC_TIME_BASELINE) {
8302 dev_info->rtc_type = UFS_RTC_ABSOLUTE;
8305 * The concept of measuring time in Linux as the number of seconds elapsed since
8306 * 00:00:00 UTC on January 1, 1970, and UFS ABS RTC is elapsed from January 1st
8307 * 2010 00:00, here we need to adjust ABS baseline.
8309 dev_info->rtc_time_baseline = mktime64(2010, 1, 1, 0, 0, 0) -
8310 mktime64(1970, 1, 1, 0, 0, 0);
8312 dev_info->rtc_type = UFS_RTC_RELATIVE;
8313 dev_info->rtc_time_baseline = 0;
8317 * We ignore TIME_PERIOD defined in wPeriodicRTCUpdate because Spec does not clearly state
8318 * how to calculate the specific update period for each time unit. And we disable periodic
8319 * RTC update work, let user configure by sysfs node according to specific circumstance.
8321 dev_info->rtc_update_period = 0;
8324 static int ufs_get_device_desc(struct ufs_hba *hba)
8329 struct ufs_dev_info *dev_info = &hba->dev_info;
8331 desc_buf = kzalloc(QUERY_DESC_MAX_SIZE, GFP_KERNEL);
8337 err = ufshcd_read_desc_param(hba, QUERY_DESC_IDN_DEVICE, 0, 0, desc_buf,
8338 QUERY_DESC_MAX_SIZE);
8340 dev_err(hba->dev, "%s: Failed reading Device Desc. err = %d\n",
8346 * getting vendor (manufacturerID) and Bank Index in big endian
8349 dev_info->wmanufacturerid = desc_buf[DEVICE_DESC_PARAM_MANF_ID] << 8 |
8350 desc_buf[DEVICE_DESC_PARAM_MANF_ID + 1];
8352 /* getting Specification Version in big endian format */
8353 dev_info->wspecversion = desc_buf[DEVICE_DESC_PARAM_SPEC_VER] << 8 |
8354 desc_buf[DEVICE_DESC_PARAM_SPEC_VER + 1];
8355 dev_info->bqueuedepth = desc_buf[DEVICE_DESC_PARAM_Q_DPTH];
8357 model_index = desc_buf[DEVICE_DESC_PARAM_PRDCT_NAME];
8359 err = ufshcd_read_string_desc(hba, model_index,
8360 &dev_info->model, SD_ASCII_STD);
8362 dev_err(hba->dev, "%s: Failed reading Product Name. err = %d\n",
8367 hba->luns_avail = desc_buf[DEVICE_DESC_PARAM_NUM_LU] +
8368 desc_buf[DEVICE_DESC_PARAM_NUM_WLU];
8370 ufs_fixup_device_setup(hba);
8372 ufshcd_wb_probe(hba, desc_buf);
8374 ufshcd_temp_notif_probe(hba, desc_buf);
8376 ufs_init_rtc(hba, desc_buf);
8378 if (hba->ext_iid_sup)
8379 ufshcd_ext_iid_probe(hba, desc_buf);
8382 * ufshcd_read_string_desc returns size of the string
8383 * reset the error value
8392 static void ufs_put_device_desc(struct ufs_hba *hba)
8394 struct ufs_dev_info *dev_info = &hba->dev_info;
8396 kfree(dev_info->model);
8397 dev_info->model = NULL;
8401 * ufshcd_tune_pa_tactivate - Tunes PA_TActivate of local UniPro
8402 * @hba: per-adapter instance
8404 * PA_TActivate parameter can be tuned manually if UniPro version is less than
8405 * 1.61. PA_TActivate needs to be greater than or equal to peerM-PHY's
8406 * RX_MIN_ACTIVATETIME_CAPABILITY attribute. This optimal value can help reduce
8407 * the hibern8 exit latency.
8409 * Return: zero on success, non-zero error value on failure.
8411 static int ufshcd_tune_pa_tactivate(struct ufs_hba *hba)
8414 u32 peer_rx_min_activatetime = 0, tuned_pa_tactivate;
8416 ret = ufshcd_dme_peer_get(hba,
8418 RX_MIN_ACTIVATETIME_CAPABILITY,
8419 UIC_ARG_MPHY_RX_GEN_SEL_INDEX(0)),
8420 &peer_rx_min_activatetime);
8424 /* make sure proper unit conversion is applied */
8425 tuned_pa_tactivate =
8426 ((peer_rx_min_activatetime * RX_MIN_ACTIVATETIME_UNIT_US)
8427 / PA_TACTIVATE_TIME_UNIT_US);
8428 ret = ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TACTIVATE),
8429 tuned_pa_tactivate);
8436 * ufshcd_tune_pa_hibern8time - Tunes PA_Hibern8Time of local UniPro
8437 * @hba: per-adapter instance
8439 * PA_Hibern8Time parameter can be tuned manually if UniPro version is less than
8440 * 1.61. PA_Hibern8Time needs to be maximum of local M-PHY's
8441 * TX_HIBERN8TIME_CAPABILITY & peer M-PHY's RX_HIBERN8TIME_CAPABILITY.
8442 * This optimal value can help reduce the hibern8 exit latency.
8444 * Return: zero on success, non-zero error value on failure.
8446 static int ufshcd_tune_pa_hibern8time(struct ufs_hba *hba)
8449 u32 local_tx_hibern8_time_cap = 0, peer_rx_hibern8_time_cap = 0;
8450 u32 max_hibern8_time, tuned_pa_hibern8time;
8452 ret = ufshcd_dme_get(hba,
8453 UIC_ARG_MIB_SEL(TX_HIBERN8TIME_CAPABILITY,
8454 UIC_ARG_MPHY_TX_GEN_SEL_INDEX(0)),
8455 &local_tx_hibern8_time_cap);
8459 ret = ufshcd_dme_peer_get(hba,
8460 UIC_ARG_MIB_SEL(RX_HIBERN8TIME_CAPABILITY,
8461 UIC_ARG_MPHY_RX_GEN_SEL_INDEX(0)),
8462 &peer_rx_hibern8_time_cap);
8466 max_hibern8_time = max(local_tx_hibern8_time_cap,
8467 peer_rx_hibern8_time_cap);
8468 /* make sure proper unit conversion is applied */
8469 tuned_pa_hibern8time = ((max_hibern8_time * HIBERN8TIME_UNIT_US)
8470 / PA_HIBERN8_TIME_UNIT_US);
8471 ret = ufshcd_dme_set(hba, UIC_ARG_MIB(PA_HIBERN8TIME),
8472 tuned_pa_hibern8time);
8478 * ufshcd_quirk_tune_host_pa_tactivate - Ensures that host PA_TACTIVATE is
8479 * less than device PA_TACTIVATE time.
8480 * @hba: per-adapter instance
8482 * Some UFS devices require host PA_TACTIVATE to be lower than device
8483 * PA_TACTIVATE, we need to enable UFS_DEVICE_QUIRK_HOST_PA_TACTIVATE quirk
8486 * Return: zero on success, non-zero error value on failure.
8488 static int ufshcd_quirk_tune_host_pa_tactivate(struct ufs_hba *hba)
8491 u32 granularity, peer_granularity;
8492 u32 pa_tactivate, peer_pa_tactivate;
8493 u32 pa_tactivate_us, peer_pa_tactivate_us;
8494 static const u8 gran_to_us_table[] = {1, 4, 8, 16, 32, 100};
8496 ret = ufshcd_dme_get(hba, UIC_ARG_MIB(PA_GRANULARITY),
8501 ret = ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_GRANULARITY),
8506 if ((granularity < PA_GRANULARITY_MIN_VAL) ||
8507 (granularity > PA_GRANULARITY_MAX_VAL)) {
8508 dev_err(hba->dev, "%s: invalid host PA_GRANULARITY %d",
8509 __func__, granularity);
8513 if ((peer_granularity < PA_GRANULARITY_MIN_VAL) ||
8514 (peer_granularity > PA_GRANULARITY_MAX_VAL)) {
8515 dev_err(hba->dev, "%s: invalid device PA_GRANULARITY %d",
8516 __func__, peer_granularity);
8520 ret = ufshcd_dme_get(hba, UIC_ARG_MIB(PA_TACTIVATE), &pa_tactivate);
8524 ret = ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_TACTIVATE),
8525 &peer_pa_tactivate);
8529 pa_tactivate_us = pa_tactivate * gran_to_us_table[granularity - 1];
8530 peer_pa_tactivate_us = peer_pa_tactivate *
8531 gran_to_us_table[peer_granularity - 1];
8533 if (pa_tactivate_us >= peer_pa_tactivate_us) {
8534 u32 new_peer_pa_tactivate;
8536 new_peer_pa_tactivate = pa_tactivate_us /
8537 gran_to_us_table[peer_granularity - 1];
8538 new_peer_pa_tactivate++;
8539 ret = ufshcd_dme_peer_set(hba, UIC_ARG_MIB(PA_TACTIVATE),
8540 new_peer_pa_tactivate);
8547 static void ufshcd_tune_unipro_params(struct ufs_hba *hba)
8549 if (ufshcd_is_unipro_pa_params_tuning_req(hba)) {
8550 ufshcd_tune_pa_tactivate(hba);
8551 ufshcd_tune_pa_hibern8time(hba);
8554 ufshcd_vops_apply_dev_quirks(hba);
8556 if (hba->dev_quirks & UFS_DEVICE_QUIRK_PA_TACTIVATE)
8557 /* set 1ms timeout for PA_TACTIVATE */
8558 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TACTIVATE), 10);
8560 if (hba->dev_quirks & UFS_DEVICE_QUIRK_HOST_PA_TACTIVATE)
8561 ufshcd_quirk_tune_host_pa_tactivate(hba);
8564 static void ufshcd_clear_dbg_ufs_stats(struct ufs_hba *hba)
8566 hba->ufs_stats.hibern8_exit_cnt = 0;
8567 hba->ufs_stats.last_hibern8_exit_tstamp = ktime_set(0, 0);
8568 hba->req_abort_count = 0;
8571 static int ufshcd_device_geo_params_init(struct ufs_hba *hba)
8576 desc_buf = kzalloc(QUERY_DESC_MAX_SIZE, GFP_KERNEL);
8582 err = ufshcd_read_desc_param(hba, QUERY_DESC_IDN_GEOMETRY, 0, 0,
8583 desc_buf, QUERY_DESC_MAX_SIZE);
8585 dev_err(hba->dev, "%s: Failed reading Geometry Desc. err = %d\n",
8590 if (desc_buf[GEOMETRY_DESC_PARAM_MAX_NUM_LUN] == 1)
8591 hba->dev_info.max_lu_supported = 32;
8592 else if (desc_buf[GEOMETRY_DESC_PARAM_MAX_NUM_LUN] == 0)
8593 hba->dev_info.max_lu_supported = 8;
8600 struct ufs_ref_clk {
8601 unsigned long freq_hz;
8602 enum ufs_ref_clk_freq val;
8605 static const struct ufs_ref_clk ufs_ref_clk_freqs[] = {
8606 {19200000, REF_CLK_FREQ_19_2_MHZ},
8607 {26000000, REF_CLK_FREQ_26_MHZ},
8608 {38400000, REF_CLK_FREQ_38_4_MHZ},
8609 {52000000, REF_CLK_FREQ_52_MHZ},
8610 {0, REF_CLK_FREQ_INVAL},
8613 static enum ufs_ref_clk_freq
8614 ufs_get_bref_clk_from_hz(unsigned long freq)
8618 for (i = 0; ufs_ref_clk_freqs[i].freq_hz; i++)
8619 if (ufs_ref_clk_freqs[i].freq_hz == freq)
8620 return ufs_ref_clk_freqs[i].val;
8622 return REF_CLK_FREQ_INVAL;
8625 void ufshcd_parse_dev_ref_clk_freq(struct ufs_hba *hba, struct clk *refclk)
8629 freq = clk_get_rate(refclk);
8631 hba->dev_ref_clk_freq =
8632 ufs_get_bref_clk_from_hz(freq);
8634 if (hba->dev_ref_clk_freq == REF_CLK_FREQ_INVAL)
8636 "invalid ref_clk setting = %ld\n", freq);
8639 static int ufshcd_set_dev_ref_clk(struct ufs_hba *hba)
8643 u32 freq = hba->dev_ref_clk_freq;
8645 err = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
8646 QUERY_ATTR_IDN_REF_CLK_FREQ, 0, 0, &ref_clk);
8649 dev_err(hba->dev, "failed reading bRefClkFreq. err = %d\n",
8654 if (ref_clk == freq)
8655 goto out; /* nothing to update */
8657 err = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_WRITE_ATTR,
8658 QUERY_ATTR_IDN_REF_CLK_FREQ, 0, 0, &freq);
8661 dev_err(hba->dev, "bRefClkFreq setting to %lu Hz failed\n",
8662 ufs_ref_clk_freqs[freq].freq_hz);
8666 dev_dbg(hba->dev, "bRefClkFreq setting to %lu Hz succeeded\n",
8667 ufs_ref_clk_freqs[freq].freq_hz);
8673 static int ufshcd_device_params_init(struct ufs_hba *hba)
8678 /* Init UFS geometry descriptor related parameters */
8679 ret = ufshcd_device_geo_params_init(hba);
8683 /* Check and apply UFS device quirks */
8684 ret = ufs_get_device_desc(hba);
8686 dev_err(hba->dev, "%s: Failed getting device info. err = %d\n",
8691 ufshcd_get_ref_clk_gating_wait(hba);
8693 if (!ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_READ_FLAG,
8694 QUERY_FLAG_IDN_PWR_ON_WPE, 0, &flag))
8695 hba->dev_info.f_power_on_wp_en = flag;
8697 /* Probe maximum power mode co-supported by both UFS host and device */
8698 if (ufshcd_get_max_pwr_mode(hba))
8700 "%s: Failed getting max supported power mode\n",
8706 static void ufshcd_set_timestamp_attr(struct ufs_hba *hba)
8709 struct ufs_query_req *request = NULL;
8710 struct ufs_query_res *response = NULL;
8711 struct ufs_dev_info *dev_info = &hba->dev_info;
8712 struct utp_upiu_query_v4_0 *upiu_data;
8714 if (dev_info->wspecversion < 0x400)
8719 mutex_lock(&hba->dev_cmd.lock);
8721 ufshcd_init_query(hba, &request, &response,
8722 UPIU_QUERY_OPCODE_WRITE_ATTR,
8723 QUERY_ATTR_IDN_TIMESTAMP, 0, 0);
8725 request->query_func = UPIU_QUERY_FUNC_STANDARD_WRITE_REQUEST;
8727 upiu_data = (struct utp_upiu_query_v4_0 *)&request->upiu_req;
8729 put_unaligned_be64(ktime_get_real_ns(), &upiu_data->osf3);
8731 err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_QUERY, QUERY_REQ_TIMEOUT);
8734 dev_err(hba->dev, "%s: failed to set timestamp %d\n",
8737 mutex_unlock(&hba->dev_cmd.lock);
8738 ufshcd_release(hba);
8742 * ufshcd_add_lus - probe and add UFS logical units
8743 * @hba: per-adapter instance
8745 * Return: 0 upon success; < 0 upon failure.
8747 static int ufshcd_add_lus(struct ufs_hba *hba)
8751 /* Add required well known logical units to scsi mid layer */
8752 ret = ufshcd_scsi_add_wlus(hba);
8756 /* Initialize devfreq after UFS device is detected */
8757 if (ufshcd_is_clkscaling_supported(hba)) {
8758 memcpy(&hba->clk_scaling.saved_pwr_info,
8760 sizeof(struct ufs_pa_layer_attr));
8761 hba->clk_scaling.is_allowed = true;
8763 ret = ufshcd_devfreq_init(hba);
8767 hba->clk_scaling.is_enabled = true;
8768 ufshcd_init_clk_scaling_sysfs(hba);
8772 scsi_scan_host(hba->host);
8778 /* SDB - Single Doorbell */
8779 static void ufshcd_release_sdb_queue(struct ufs_hba *hba, int nutrs)
8781 size_t ucdl_size, utrdl_size;
8783 ucdl_size = ufshcd_get_ucd_size(hba) * nutrs;
8784 dmam_free_coherent(hba->dev, ucdl_size, hba->ucdl_base_addr,
8785 hba->ucdl_dma_addr);
8787 utrdl_size = sizeof(struct utp_transfer_req_desc) * nutrs;
8788 dmam_free_coherent(hba->dev, utrdl_size, hba->utrdl_base_addr,
8789 hba->utrdl_dma_addr);
8791 devm_kfree(hba->dev, hba->lrb);
8794 static int ufshcd_alloc_mcq(struct ufs_hba *hba)
8797 int old_nutrs = hba->nutrs;
8799 ret = ufshcd_mcq_decide_queue_depth(hba);
8804 ret = ufshcd_mcq_init(hba);
8809 * Previously allocated memory for nutrs may not be enough in MCQ mode.
8810 * Number of supported tags in MCQ mode may be larger than SDB mode.
8812 if (hba->nutrs != old_nutrs) {
8813 ufshcd_release_sdb_queue(hba, old_nutrs);
8814 ret = ufshcd_memory_alloc(hba);
8817 ufshcd_host_memory_configure(hba);
8820 ret = ufshcd_mcq_memory_alloc(hba);
8826 hba->nutrs = old_nutrs;
8830 static void ufshcd_config_mcq(struct ufs_hba *hba)
8835 ret = ufshcd_mcq_vops_config_esi(hba);
8836 dev_info(hba->dev, "ESI %sconfigured\n", ret ? "is not " : "");
8838 intrs = UFSHCD_ENABLE_MCQ_INTRS;
8839 if (hba->quirks & UFSHCD_QUIRK_MCQ_BROKEN_INTR)
8840 intrs &= ~MCQ_CQ_EVENT_STATUS;
8841 ufshcd_enable_intr(hba, intrs);
8842 ufshcd_mcq_make_queues_operational(hba);
8843 ufshcd_mcq_config_mac(hba, hba->nutrs);
8845 hba->host->can_queue = hba->nutrs - UFSHCD_NUM_RESERVED;
8846 hba->reserved_slot = hba->nutrs - UFSHCD_NUM_RESERVED;
8848 ufshcd_mcq_enable(hba);
8849 hba->mcq_enabled = true;
8851 dev_info(hba->dev, "MCQ configured, nr_queues=%d, io_queues=%d, read_queue=%d, poll_queues=%d, queue_depth=%d\n",
8852 hba->nr_hw_queues, hba->nr_queues[HCTX_TYPE_DEFAULT],
8853 hba->nr_queues[HCTX_TYPE_READ], hba->nr_queues[HCTX_TYPE_POLL],
8857 static int ufshcd_device_init(struct ufs_hba *hba, bool init_dev_params)
8860 struct Scsi_Host *host = hba->host;
8862 hba->ufshcd_state = UFSHCD_STATE_RESET;
8864 ret = ufshcd_link_startup(hba);
8868 if (hba->quirks & UFSHCD_QUIRK_SKIP_PH_CONFIGURATION)
8871 /* Debug counters initialization */
8872 ufshcd_clear_dbg_ufs_stats(hba);
8874 /* UniPro link is active now */
8875 ufshcd_set_link_active(hba);
8877 /* Reconfigure MCQ upon reset */
8878 if (is_mcq_enabled(hba) && !init_dev_params)
8879 ufshcd_config_mcq(hba);
8881 /* Verify device initialization by sending NOP OUT UPIU */
8882 ret = ufshcd_verify_dev_init(hba);
8886 /* Initiate UFS initialization, and waiting until completion */
8887 ret = ufshcd_complete_dev_init(hba);
8892 * Initialize UFS device parameters used by driver, these
8893 * parameters are associated with UFS descriptors.
8895 if (init_dev_params) {
8896 ret = ufshcd_device_params_init(hba);
8899 if (is_mcq_supported(hba) && !hba->scsi_host_added) {
8900 ret = ufshcd_alloc_mcq(hba);
8902 ufshcd_config_mcq(hba);
8904 /* Continue with SDB mode */
8905 use_mcq_mode = false;
8906 dev_err(hba->dev, "MCQ mode is disabled, err=%d\n",
8909 ret = scsi_add_host(host, hba->dev);
8911 dev_err(hba->dev, "scsi_add_host failed\n");
8914 hba->scsi_host_added = true;
8915 } else if (is_mcq_supported(hba)) {
8916 /* UFSHCD_QUIRK_REINIT_AFTER_MAX_GEAR_SWITCH is set */
8917 ufshcd_config_mcq(hba);
8921 ufshcd_tune_unipro_params(hba);
8923 /* UFS device is also active now */
8924 ufshcd_set_ufs_dev_active(hba);
8925 ufshcd_force_reset_auto_bkops(hba);
8927 ufshcd_set_timestamp_attr(hba);
8928 schedule_delayed_work(&hba->ufs_rtc_update_work,
8929 msecs_to_jiffies(UFS_RTC_UPDATE_INTERVAL_MS));
8931 /* Gear up to HS gear if supported */
8932 if (hba->max_pwr_info.is_valid) {
8934 * Set the right value to bRefClkFreq before attempting to
8935 * switch to HS gears.
8937 if (hba->dev_ref_clk_freq != REF_CLK_FREQ_INVAL)
8938 ufshcd_set_dev_ref_clk(hba);
8939 ret = ufshcd_config_pwr_mode(hba, &hba->max_pwr_info.info);
8941 dev_err(hba->dev, "%s: Failed setting power mode, err = %d\n",
8951 * ufshcd_probe_hba - probe hba to detect device and initialize it
8952 * @hba: per-adapter instance
8953 * @init_dev_params: whether or not to call ufshcd_device_params_init().
8955 * Execute link-startup and verify device initialization
8957 * Return: 0 upon success; < 0 upon failure.
8959 static int ufshcd_probe_hba(struct ufs_hba *hba, bool init_dev_params)
8961 ktime_t start = ktime_get();
8962 unsigned long flags;
8965 ret = ufshcd_device_init(hba, init_dev_params);
8969 if (!hba->pm_op_in_progress &&
8970 (hba->quirks & UFSHCD_QUIRK_REINIT_AFTER_MAX_GEAR_SWITCH)) {
8971 /* Reset the device and controller before doing reinit */
8972 ufshcd_device_reset(hba);
8973 ufshcd_hba_stop(hba);
8974 ufshcd_vops_reinit_notify(hba);
8975 ret = ufshcd_hba_enable(hba);
8977 dev_err(hba->dev, "Host controller enable failed\n");
8978 ufshcd_print_evt_hist(hba);
8979 ufshcd_print_host_state(hba);
8983 /* Reinit the device */
8984 ret = ufshcd_device_init(hba, init_dev_params);
8989 ufshcd_print_pwr_info(hba);
8992 * bActiveICCLevel is volatile for UFS device (as per latest v2.1 spec)
8993 * and for removable UFS card as well, hence always set the parameter.
8994 * Note: Error handler may issue the device reset hence resetting
8995 * bActiveICCLevel as well so it is always safe to set this here.
8997 ufshcd_set_active_icc_lvl(hba);
8999 /* Enable UFS Write Booster if supported */
9000 ufshcd_configure_wb(hba);
9002 if (hba->ee_usr_mask)
9003 ufshcd_write_ee_control(hba);
9004 ufshcd_configure_auto_hibern8(hba);
9007 spin_lock_irqsave(hba->host->host_lock, flags);
9009 hba->ufshcd_state = UFSHCD_STATE_ERROR;
9010 else if (hba->ufshcd_state == UFSHCD_STATE_RESET)
9011 hba->ufshcd_state = UFSHCD_STATE_OPERATIONAL;
9012 spin_unlock_irqrestore(hba->host->host_lock, flags);
9014 trace_ufshcd_init(dev_name(hba->dev), ret,
9015 ktime_to_us(ktime_sub(ktime_get(), start)),
9016 hba->curr_dev_pwr_mode, hba->uic_link_state);
9021 * ufshcd_async_scan - asynchronous execution for probing hba
9022 * @data: data pointer to pass to this function
9023 * @cookie: cookie data
9025 static void ufshcd_async_scan(void *data, async_cookie_t cookie)
9027 struct ufs_hba *hba = (struct ufs_hba *)data;
9030 down(&hba->host_sem);
9031 /* Initialize hba, detect and initialize UFS device */
9032 ret = ufshcd_probe_hba(hba, true);
9037 /* Probe and add UFS logical units */
9038 ret = ufshcd_add_lus(hba);
9041 pm_runtime_put_sync(hba->dev);
9044 dev_err(hba->dev, "%s failed: %d\n", __func__, ret);
9047 static enum scsi_timeout_action ufshcd_eh_timed_out(struct scsi_cmnd *scmd)
9049 struct ufs_hba *hba = shost_priv(scmd->device->host);
9051 if (!hba->system_suspending) {
9052 /* Activate the error handler in the SCSI core. */
9053 return SCSI_EH_NOT_HANDLED;
9057 * If we get here we know that no TMFs are outstanding and also that
9058 * the only pending command is a START STOP UNIT command. Handle the
9059 * timeout of that command directly to prevent a deadlock between
9060 * ufshcd_set_dev_pwr_mode() and ufshcd_err_handler().
9062 ufshcd_link_recovery(hba);
9063 dev_info(hba->dev, "%s() finished; outstanding_tasks = %#lx.\n",
9064 __func__, hba->outstanding_tasks);
9066 return hba->outstanding_reqs ? SCSI_EH_RESET_TIMER : SCSI_EH_DONE;
9069 static const struct attribute_group *ufshcd_driver_groups[] = {
9070 &ufs_sysfs_unit_descriptor_group,
9071 &ufs_sysfs_lun_attributes_group,
9075 static struct ufs_hba_variant_params ufs_hba_vps = {
9076 .hba_enable_delay_us = 1000,
9077 .wb_flush_threshold = UFS_WB_BUF_REMAIN_PERCENT(40),
9078 .devfreq_profile.polling_ms = 100,
9079 .devfreq_profile.target = ufshcd_devfreq_target,
9080 .devfreq_profile.get_dev_status = ufshcd_devfreq_get_dev_status,
9081 .ondemand_data.upthreshold = 70,
9082 .ondemand_data.downdifferential = 5,
9085 static const struct scsi_host_template ufshcd_driver_template = {
9086 .module = THIS_MODULE,
9088 .proc_name = UFSHCD,
9089 .map_queues = ufshcd_map_queues,
9090 .queuecommand = ufshcd_queuecommand,
9091 .mq_poll = ufshcd_poll,
9092 .slave_alloc = ufshcd_slave_alloc,
9093 .slave_configure = ufshcd_slave_configure,
9094 .slave_destroy = ufshcd_slave_destroy,
9095 .change_queue_depth = ufshcd_change_queue_depth,
9096 .eh_abort_handler = ufshcd_abort,
9097 .eh_device_reset_handler = ufshcd_eh_device_reset_handler,
9098 .eh_host_reset_handler = ufshcd_eh_host_reset_handler,
9099 .eh_timed_out = ufshcd_eh_timed_out,
9101 .sg_tablesize = SG_ALL,
9102 .cmd_per_lun = UFSHCD_CMD_PER_LUN,
9103 .can_queue = UFSHCD_CAN_QUEUE,
9104 .max_segment_size = PRDT_DATA_BYTE_COUNT_MAX,
9105 .max_sectors = SZ_1M / SECTOR_SIZE,
9106 .max_host_blocked = 1,
9107 .track_queue_depth = 1,
9108 .skip_settle_delay = 1,
9109 .sdev_groups = ufshcd_driver_groups,
9112 static int ufshcd_config_vreg_load(struct device *dev, struct ufs_vreg *vreg,
9121 * "set_load" operation shall be required on those regulators
9122 * which specifically configured current limitation. Otherwise
9123 * zero max_uA may cause unexpected behavior when regulator is
9124 * enabled or set as high power mode.
9129 ret = regulator_set_load(vreg->reg, ua);
9131 dev_err(dev, "%s: %s set load (ua=%d) failed, err=%d\n",
9132 __func__, vreg->name, ua, ret);
9138 static inline int ufshcd_config_vreg_lpm(struct ufs_hba *hba,
9139 struct ufs_vreg *vreg)
9141 return ufshcd_config_vreg_load(hba->dev, vreg, UFS_VREG_LPM_LOAD_UA);
9144 static inline int ufshcd_config_vreg_hpm(struct ufs_hba *hba,
9145 struct ufs_vreg *vreg)
9150 return ufshcd_config_vreg_load(hba->dev, vreg, vreg->max_uA);
9153 static int ufshcd_config_vreg(struct device *dev,
9154 struct ufs_vreg *vreg, bool on)
9156 if (regulator_count_voltages(vreg->reg) <= 0)
9159 return ufshcd_config_vreg_load(dev, vreg, on ? vreg->max_uA : 0);
9162 static int ufshcd_enable_vreg(struct device *dev, struct ufs_vreg *vreg)
9166 if (!vreg || vreg->enabled)
9169 ret = ufshcd_config_vreg(dev, vreg, true);
9171 ret = regulator_enable(vreg->reg);
9174 vreg->enabled = true;
9176 dev_err(dev, "%s: %s enable failed, err=%d\n",
9177 __func__, vreg->name, ret);
9182 static int ufshcd_disable_vreg(struct device *dev, struct ufs_vreg *vreg)
9186 if (!vreg || !vreg->enabled || vreg->always_on)
9189 ret = regulator_disable(vreg->reg);
9192 /* ignore errors on applying disable config */
9193 ufshcd_config_vreg(dev, vreg, false);
9194 vreg->enabled = false;
9196 dev_err(dev, "%s: %s disable failed, err=%d\n",
9197 __func__, vreg->name, ret);
9203 static int ufshcd_setup_vreg(struct ufs_hba *hba, bool on)
9206 struct device *dev = hba->dev;
9207 struct ufs_vreg_info *info = &hba->vreg_info;
9209 ret = ufshcd_toggle_vreg(dev, info->vcc, on);
9213 ret = ufshcd_toggle_vreg(dev, info->vccq, on);
9217 ret = ufshcd_toggle_vreg(dev, info->vccq2, on);
9221 ufshcd_toggle_vreg(dev, info->vccq2, false);
9222 ufshcd_toggle_vreg(dev, info->vccq, false);
9223 ufshcd_toggle_vreg(dev, info->vcc, false);
9228 static int ufshcd_setup_hba_vreg(struct ufs_hba *hba, bool on)
9230 struct ufs_vreg_info *info = &hba->vreg_info;
9232 return ufshcd_toggle_vreg(hba->dev, info->vdd_hba, on);
9235 int ufshcd_get_vreg(struct device *dev, struct ufs_vreg *vreg)
9242 vreg->reg = devm_regulator_get(dev, vreg->name);
9243 if (IS_ERR(vreg->reg)) {
9244 ret = PTR_ERR(vreg->reg);
9245 dev_err(dev, "%s: %s get failed, err=%d\n",
9246 __func__, vreg->name, ret);
9251 EXPORT_SYMBOL_GPL(ufshcd_get_vreg);
9253 static int ufshcd_init_vreg(struct ufs_hba *hba)
9256 struct device *dev = hba->dev;
9257 struct ufs_vreg_info *info = &hba->vreg_info;
9259 ret = ufshcd_get_vreg(dev, info->vcc);
9263 ret = ufshcd_get_vreg(dev, info->vccq);
9265 ret = ufshcd_get_vreg(dev, info->vccq2);
9270 static int ufshcd_init_hba_vreg(struct ufs_hba *hba)
9272 struct ufs_vreg_info *info = &hba->vreg_info;
9274 return ufshcd_get_vreg(hba->dev, info->vdd_hba);
9277 static int ufshcd_setup_clocks(struct ufs_hba *hba, bool on)
9280 struct ufs_clk_info *clki;
9281 struct list_head *head = &hba->clk_list_head;
9282 unsigned long flags;
9283 ktime_t start = ktime_get();
9284 bool clk_state_changed = false;
9286 if (list_empty(head))
9289 ret = ufshcd_vops_setup_clocks(hba, on, PRE_CHANGE);
9293 list_for_each_entry(clki, head, list) {
9294 if (!IS_ERR_OR_NULL(clki->clk)) {
9296 * Don't disable clocks which are needed
9297 * to keep the link active.
9299 if (ufshcd_is_link_active(hba) &&
9300 clki->keep_link_active)
9303 clk_state_changed = on ^ clki->enabled;
9304 if (on && !clki->enabled) {
9305 ret = clk_prepare_enable(clki->clk);
9307 dev_err(hba->dev, "%s: %s prepare enable failed, %d\n",
9308 __func__, clki->name, ret);
9311 } else if (!on && clki->enabled) {
9312 clk_disable_unprepare(clki->clk);
9315 dev_dbg(hba->dev, "%s: clk: %s %sabled\n", __func__,
9316 clki->name, on ? "en" : "dis");
9320 ret = ufshcd_vops_setup_clocks(hba, on, POST_CHANGE);
9324 if (!ufshcd_is_clkscaling_supported(hba))
9325 ufshcd_pm_qos_update(hba, on);
9328 list_for_each_entry(clki, head, list) {
9329 if (!IS_ERR_OR_NULL(clki->clk) && clki->enabled)
9330 clk_disable_unprepare(clki->clk);
9332 } else if (!ret && on) {
9333 spin_lock_irqsave(hba->host->host_lock, flags);
9334 hba->clk_gating.state = CLKS_ON;
9335 trace_ufshcd_clk_gating(dev_name(hba->dev),
9336 hba->clk_gating.state);
9337 spin_unlock_irqrestore(hba->host->host_lock, flags);
9340 if (clk_state_changed)
9341 trace_ufshcd_profile_clk_gating(dev_name(hba->dev),
9342 (on ? "on" : "off"),
9343 ktime_to_us(ktime_sub(ktime_get(), start)), ret);
9347 static enum ufs_ref_clk_freq ufshcd_parse_ref_clk_property(struct ufs_hba *hba)
9350 int ret = device_property_read_u32(hba->dev, "ref-clk-freq", &freq);
9353 dev_dbg(hba->dev, "Cannot query 'ref-clk-freq' property = %d", ret);
9354 return REF_CLK_FREQ_INVAL;
9357 return ufs_get_bref_clk_from_hz(freq);
9360 static int ufshcd_init_clocks(struct ufs_hba *hba)
9363 struct ufs_clk_info *clki;
9364 struct device *dev = hba->dev;
9365 struct list_head *head = &hba->clk_list_head;
9367 if (list_empty(head))
9370 list_for_each_entry(clki, head, list) {
9374 clki->clk = devm_clk_get(dev, clki->name);
9375 if (IS_ERR(clki->clk)) {
9376 ret = PTR_ERR(clki->clk);
9377 dev_err(dev, "%s: %s clk get failed, %d\n",
9378 __func__, clki->name, ret);
9383 * Parse device ref clk freq as per device tree "ref_clk".
9384 * Default dev_ref_clk_freq is set to REF_CLK_FREQ_INVAL
9385 * in ufshcd_alloc_host().
9387 if (!strcmp(clki->name, "ref_clk"))
9388 ufshcd_parse_dev_ref_clk_freq(hba, clki->clk);
9390 if (clki->max_freq) {
9391 ret = clk_set_rate(clki->clk, clki->max_freq);
9393 dev_err(hba->dev, "%s: %s clk set rate(%dHz) failed, %d\n",
9394 __func__, clki->name,
9395 clki->max_freq, ret);
9398 clki->curr_freq = clki->max_freq;
9400 dev_dbg(dev, "%s: clk: %s, rate: %lu\n", __func__,
9401 clki->name, clk_get_rate(clki->clk));
9404 /* Set Max. frequency for all clocks */
9405 if (hba->use_pm_opp) {
9406 ret = ufshcd_opp_set_rate(hba, ULONG_MAX);
9408 dev_err(hba->dev, "%s: failed to set OPP: %d", __func__,
9418 static int ufshcd_variant_hba_init(struct ufs_hba *hba)
9425 err = ufshcd_vops_init(hba);
9427 dev_err_probe(hba->dev, err,
9428 "%s: variant %s init failed with err %d\n",
9429 __func__, ufshcd_get_var_name(hba), err);
9434 static void ufshcd_variant_hba_exit(struct ufs_hba *hba)
9439 ufshcd_vops_exit(hba);
9442 static int ufshcd_hba_init(struct ufs_hba *hba)
9447 * Handle host controller power separately from the UFS device power
9448 * rails as it will help controlling the UFS host controller power
9449 * collapse easily which is different than UFS device power collapse.
9450 * Also, enable the host controller power before we go ahead with rest
9451 * of the initialization here.
9453 err = ufshcd_init_hba_vreg(hba);
9457 err = ufshcd_setup_hba_vreg(hba, true);
9461 err = ufshcd_init_clocks(hba);
9463 goto out_disable_hba_vreg;
9465 if (hba->dev_ref_clk_freq == REF_CLK_FREQ_INVAL)
9466 hba->dev_ref_clk_freq = ufshcd_parse_ref_clk_property(hba);
9468 err = ufshcd_setup_clocks(hba, true);
9470 goto out_disable_hba_vreg;
9472 err = ufshcd_init_vreg(hba);
9474 goto out_disable_clks;
9476 err = ufshcd_setup_vreg(hba, true);
9478 goto out_disable_clks;
9480 err = ufshcd_variant_hba_init(hba);
9482 goto out_disable_vreg;
9484 ufs_debugfs_hba_init(hba);
9485 ufs_fault_inject_hba_init(hba);
9487 hba->is_powered = true;
9491 ufshcd_setup_vreg(hba, false);
9493 ufshcd_setup_clocks(hba, false);
9494 out_disable_hba_vreg:
9495 ufshcd_setup_hba_vreg(hba, false);
9500 static void ufshcd_hba_exit(struct ufs_hba *hba)
9502 if (hba->is_powered) {
9503 ufshcd_pm_qos_exit(hba);
9504 ufshcd_exit_clk_scaling(hba);
9505 ufshcd_exit_clk_gating(hba);
9507 destroy_workqueue(hba->eh_wq);
9508 ufs_debugfs_hba_exit(hba);
9509 ufshcd_variant_hba_exit(hba);
9510 ufshcd_setup_vreg(hba, false);
9511 ufshcd_setup_clocks(hba, false);
9512 ufshcd_setup_hba_vreg(hba, false);
9513 hba->is_powered = false;
9514 ufs_put_device_desc(hba);
9518 static int ufshcd_execute_start_stop(struct scsi_device *sdev,
9519 enum ufs_dev_pwr_mode pwr_mode,
9520 struct scsi_sense_hdr *sshdr)
9522 const unsigned char cdb[6] = { START_STOP, 0, 0, 0, pwr_mode << 4, 0 };
9523 struct scsi_failure failure_defs[] = {
9526 .result = SCMD_FAILURE_RESULT_ANY,
9529 struct scsi_failures failures = {
9530 .failure_definitions = failure_defs,
9532 const struct scsi_exec_args args = {
9533 .failures = &failures,
9535 .req_flags = BLK_MQ_REQ_PM,
9536 .scmd_flags = SCMD_FAIL_IF_RECOVERING,
9539 return scsi_execute_cmd(sdev, cdb, REQ_OP_DRV_IN, /*buffer=*/NULL,
9540 /*bufflen=*/0, /*timeout=*/10 * HZ, /*retries=*/0,
9545 * ufshcd_set_dev_pwr_mode - sends START STOP UNIT command to set device
9547 * @hba: per adapter instance
9548 * @pwr_mode: device power mode to set
9550 * Return: 0 if requested power mode is set successfully;
9551 * < 0 if failed to set the requested power mode.
9553 static int ufshcd_set_dev_pwr_mode(struct ufs_hba *hba,
9554 enum ufs_dev_pwr_mode pwr_mode)
9556 struct scsi_sense_hdr sshdr;
9557 struct scsi_device *sdp;
9558 unsigned long flags;
9561 spin_lock_irqsave(hba->host->host_lock, flags);
9562 sdp = hba->ufs_device_wlun;
9563 if (sdp && scsi_device_online(sdp))
9564 ret = scsi_device_get(sdp);
9567 spin_unlock_irqrestore(hba->host->host_lock, flags);
9573 * If scsi commands fail, the scsi mid-layer schedules scsi error-
9574 * handling, which would wait for host to be resumed. Since we know
9575 * we are functional while we are here, skip host resume in error
9578 hba->host->eh_noresume = 1;
9581 * Current function would be generally called from the power management
9582 * callbacks hence set the RQF_PM flag so that it doesn't resume the
9583 * already suspended childs.
9585 ret = ufshcd_execute_start_stop(sdp, pwr_mode, &sshdr);
9587 sdev_printk(KERN_WARNING, sdp,
9588 "START_STOP failed for power mode: %d, result %x\n",
9591 if (scsi_sense_valid(&sshdr))
9592 scsi_print_sense_hdr(sdp, NULL, &sshdr);
9596 hba->curr_dev_pwr_mode = pwr_mode;
9599 scsi_device_put(sdp);
9600 hba->host->eh_noresume = 0;
9604 static int ufshcd_link_state_transition(struct ufs_hba *hba,
9605 enum uic_link_state req_link_state,
9606 bool check_for_bkops)
9610 if (req_link_state == hba->uic_link_state)
9613 if (req_link_state == UIC_LINK_HIBERN8_STATE) {
9614 ret = ufshcd_uic_hibern8_enter(hba);
9616 ufshcd_set_link_hibern8(hba);
9618 dev_err(hba->dev, "%s: hibern8 enter failed %d\n",
9624 * If autobkops is enabled, link can't be turned off because
9625 * turning off the link would also turn off the device, except in the
9626 * case of DeepSleep where the device is expected to remain powered.
9628 else if ((req_link_state == UIC_LINK_OFF_STATE) &&
9629 (!check_for_bkops || !hba->auto_bkops_enabled)) {
9631 * Let's make sure that link is in low power mode, we are doing
9632 * this currently by putting the link in Hibern8. Otherway to
9633 * put the link in low power mode is to send the DME end point
9634 * to device and then send the DME reset command to local
9635 * unipro. But putting the link in hibern8 is much faster.
9637 * Note also that putting the link in Hibern8 is a requirement
9638 * for entering DeepSleep.
9640 ret = ufshcd_uic_hibern8_enter(hba);
9642 dev_err(hba->dev, "%s: hibern8 enter failed %d\n",
9647 * Change controller state to "reset state" which
9648 * should also put the link in off/reset state
9650 ufshcd_hba_stop(hba);
9652 * TODO: Check if we need any delay to make sure that
9653 * controller is reset
9655 ufshcd_set_link_off(hba);
9662 static void ufshcd_vreg_set_lpm(struct ufs_hba *hba)
9664 bool vcc_off = false;
9667 * It seems some UFS devices may keep drawing more than sleep current
9668 * (atleast for 500us) from UFS rails (especially from VCCQ rail).
9669 * To avoid this situation, add 2ms delay before putting these UFS
9670 * rails in LPM mode.
9672 if (!ufshcd_is_link_active(hba) &&
9673 hba->dev_quirks & UFS_DEVICE_QUIRK_DELAY_BEFORE_LPM)
9674 usleep_range(2000, 2100);
9677 * If UFS device is either in UFS_Sleep turn off VCC rail to save some
9680 * If UFS device and link is in OFF state, all power supplies (VCC,
9681 * VCCQ, VCCQ2) can be turned off if power on write protect is not
9682 * required. If UFS link is inactive (Hibern8 or OFF state) and device
9683 * is in sleep state, put VCCQ & VCCQ2 rails in LPM mode.
9685 * Ignore the error returned by ufshcd_toggle_vreg() as device is anyway
9686 * in low power state which would save some power.
9688 * If Write Booster is enabled and the device needs to flush the WB
9689 * buffer OR if bkops status is urgent for WB, keep Vcc on.
9691 if (ufshcd_is_ufs_dev_poweroff(hba) && ufshcd_is_link_off(hba) &&
9692 !hba->dev_info.is_lu_power_on_wp) {
9693 ufshcd_setup_vreg(hba, false);
9695 } else if (!ufshcd_is_ufs_dev_active(hba)) {
9696 ufshcd_toggle_vreg(hba->dev, hba->vreg_info.vcc, false);
9698 if (ufshcd_is_link_hibern8(hba) || ufshcd_is_link_off(hba)) {
9699 ufshcd_config_vreg_lpm(hba, hba->vreg_info.vccq);
9700 ufshcd_config_vreg_lpm(hba, hba->vreg_info.vccq2);
9705 * Some UFS devices require delay after VCC power rail is turned-off.
9707 if (vcc_off && hba->vreg_info.vcc &&
9708 hba->dev_quirks & UFS_DEVICE_QUIRK_DELAY_AFTER_LPM)
9709 usleep_range(5000, 5100);
9713 static int ufshcd_vreg_set_hpm(struct ufs_hba *hba)
9717 if (ufshcd_is_ufs_dev_poweroff(hba) && ufshcd_is_link_off(hba) &&
9718 !hba->dev_info.is_lu_power_on_wp) {
9719 ret = ufshcd_setup_vreg(hba, true);
9720 } else if (!ufshcd_is_ufs_dev_active(hba)) {
9721 if (!ufshcd_is_link_active(hba)) {
9722 ret = ufshcd_config_vreg_hpm(hba, hba->vreg_info.vccq);
9725 ret = ufshcd_config_vreg_hpm(hba, hba->vreg_info.vccq2);
9729 ret = ufshcd_toggle_vreg(hba->dev, hba->vreg_info.vcc, true);
9734 ufshcd_config_vreg_lpm(hba, hba->vreg_info.vccq);
9736 ufshcd_toggle_vreg(hba->dev, hba->vreg_info.vcc, false);
9740 #endif /* CONFIG_PM */
9742 static void ufshcd_hba_vreg_set_lpm(struct ufs_hba *hba)
9744 if (ufshcd_is_link_off(hba) || ufshcd_can_aggressive_pc(hba))
9745 ufshcd_setup_hba_vreg(hba, false);
9748 static void ufshcd_hba_vreg_set_hpm(struct ufs_hba *hba)
9750 if (ufshcd_is_link_off(hba) || ufshcd_can_aggressive_pc(hba))
9751 ufshcd_setup_hba_vreg(hba, true);
9754 static int __ufshcd_wl_suspend(struct ufs_hba *hba, enum ufs_pm_op pm_op)
9757 bool check_for_bkops;
9758 enum ufs_pm_level pm_lvl;
9759 enum ufs_dev_pwr_mode req_dev_pwr_mode;
9760 enum uic_link_state req_link_state;
9762 hba->pm_op_in_progress = true;
9763 if (pm_op != UFS_SHUTDOWN_PM) {
9764 pm_lvl = pm_op == UFS_RUNTIME_PM ?
9765 hba->rpm_lvl : hba->spm_lvl;
9766 req_dev_pwr_mode = ufs_get_pm_lvl_to_dev_pwr_mode(pm_lvl);
9767 req_link_state = ufs_get_pm_lvl_to_link_pwr_state(pm_lvl);
9769 req_dev_pwr_mode = UFS_POWERDOWN_PWR_MODE;
9770 req_link_state = UIC_LINK_OFF_STATE;
9774 * If we can't transition into any of the low power modes
9775 * just gate the clocks.
9778 hba->clk_gating.is_suspended = true;
9780 if (ufshcd_is_clkscaling_supported(hba))
9781 ufshcd_clk_scaling_suspend(hba, true);
9783 if (req_dev_pwr_mode == UFS_ACTIVE_PWR_MODE &&
9784 req_link_state == UIC_LINK_ACTIVE_STATE) {
9788 if ((req_dev_pwr_mode == hba->curr_dev_pwr_mode) &&
9789 (req_link_state == hba->uic_link_state))
9790 goto enable_scaling;
9792 /* UFS device & link must be active before we enter in this function */
9793 if (!ufshcd_is_ufs_dev_active(hba) || !ufshcd_is_link_active(hba)) {
9795 goto enable_scaling;
9798 if (pm_op == UFS_RUNTIME_PM) {
9799 if (ufshcd_can_autobkops_during_suspend(hba)) {
9801 * The device is idle with no requests in the queue,
9802 * allow background operations if bkops status shows
9803 * that performance might be impacted.
9805 ret = ufshcd_urgent_bkops(hba);
9808 * If return err in suspend flow, IO will hang.
9809 * Trigger error handler and break suspend for
9812 ufshcd_force_error_recovery(hba);
9814 goto enable_scaling;
9817 /* make sure that auto bkops is disabled */
9818 ufshcd_disable_auto_bkops(hba);
9821 * If device needs to do BKOP or WB buffer flush during
9822 * Hibern8, keep device power mode as "active power mode"
9825 hba->dev_info.b_rpm_dev_flush_capable =
9826 hba->auto_bkops_enabled ||
9827 (((req_link_state == UIC_LINK_HIBERN8_STATE) ||
9828 ((req_link_state == UIC_LINK_ACTIVE_STATE) &&
9829 ufshcd_is_auto_hibern8_enabled(hba))) &&
9830 ufshcd_wb_need_flush(hba));
9833 flush_work(&hba->eeh_work);
9835 ret = ufshcd_vops_suspend(hba, pm_op, PRE_CHANGE);
9837 goto enable_scaling;
9839 if (req_dev_pwr_mode != hba->curr_dev_pwr_mode) {
9840 if (pm_op != UFS_RUNTIME_PM)
9841 /* ensure that bkops is disabled */
9842 ufshcd_disable_auto_bkops(hba);
9844 if (!hba->dev_info.b_rpm_dev_flush_capable) {
9845 ret = ufshcd_set_dev_pwr_mode(hba, req_dev_pwr_mode);
9846 if (ret && pm_op != UFS_SHUTDOWN_PM) {
9848 * If return err in suspend flow, IO will hang.
9849 * Trigger error handler and break suspend for
9852 ufshcd_force_error_recovery(hba);
9856 goto enable_scaling;
9861 * In the case of DeepSleep, the device is expected to remain powered
9862 * with the link off, so do not check for bkops.
9864 check_for_bkops = !ufshcd_is_ufs_dev_deepsleep(hba);
9865 ret = ufshcd_link_state_transition(hba, req_link_state, check_for_bkops);
9866 if (ret && pm_op != UFS_SHUTDOWN_PM) {
9868 * If return err in suspend flow, IO will hang.
9869 * Trigger error handler and break suspend for
9872 ufshcd_force_error_recovery(hba);
9876 goto set_dev_active;
9880 * Call vendor specific suspend callback. As these callbacks may access
9881 * vendor specific host controller register space call them before the
9882 * host clocks are ON.
9884 ret = ufshcd_vops_suspend(hba, pm_op, POST_CHANGE);
9886 goto set_link_active;
9888 cancel_delayed_work_sync(&hba->ufs_rtc_update_work);
9893 * Device hardware reset is required to exit DeepSleep. Also, for
9894 * DeepSleep, the link is off so host reset and restore will be done
9897 if (ufshcd_is_ufs_dev_deepsleep(hba)) {
9898 ufshcd_device_reset(hba);
9899 WARN_ON(!ufshcd_is_link_off(hba));
9901 if (ufshcd_is_link_hibern8(hba) && !ufshcd_uic_hibern8_exit(hba))
9902 ufshcd_set_link_active(hba);
9903 else if (ufshcd_is_link_off(hba))
9904 ufshcd_host_reset_and_restore(hba);
9906 /* Can also get here needing to exit DeepSleep */
9907 if (ufshcd_is_ufs_dev_deepsleep(hba)) {
9908 ufshcd_device_reset(hba);
9909 ufshcd_host_reset_and_restore(hba);
9911 if (!ufshcd_set_dev_pwr_mode(hba, UFS_ACTIVE_PWR_MODE))
9912 ufshcd_disable_auto_bkops(hba);
9914 if (ufshcd_is_clkscaling_supported(hba))
9915 ufshcd_clk_scaling_suspend(hba, false);
9917 hba->dev_info.b_rpm_dev_flush_capable = false;
9919 if (hba->dev_info.b_rpm_dev_flush_capable) {
9920 schedule_delayed_work(&hba->rpm_dev_flush_recheck_work,
9921 msecs_to_jiffies(RPM_DEV_FLUSH_RECHECK_WORK_DELAY_MS));
9925 ufshcd_update_evt_hist(hba, UFS_EVT_WL_SUSP_ERR, (u32)ret);
9926 hba->clk_gating.is_suspended = false;
9927 ufshcd_release(hba);
9929 hba->pm_op_in_progress = false;
9934 static int __ufshcd_wl_resume(struct ufs_hba *hba, enum ufs_pm_op pm_op)
9937 enum uic_link_state old_link_state = hba->uic_link_state;
9939 hba->pm_op_in_progress = true;
9942 * Call vendor specific resume callback. As these callbacks may access
9943 * vendor specific host controller register space call them when the
9944 * host clocks are ON.
9946 ret = ufshcd_vops_resume(hba, pm_op);
9950 /* For DeepSleep, the only supported option is to have the link off */
9951 WARN_ON(ufshcd_is_ufs_dev_deepsleep(hba) && !ufshcd_is_link_off(hba));
9953 if (ufshcd_is_link_hibern8(hba)) {
9954 ret = ufshcd_uic_hibern8_exit(hba);
9956 ufshcd_set_link_active(hba);
9958 dev_err(hba->dev, "%s: hibern8 exit failed %d\n",
9960 goto vendor_suspend;
9962 } else if (ufshcd_is_link_off(hba)) {
9964 * A full initialization of the host and the device is
9965 * required since the link was put to off during suspend.
9966 * Note, in the case of DeepSleep, the device will exit
9967 * DeepSleep due to device reset.
9969 ret = ufshcd_reset_and_restore(hba);
9971 * ufshcd_reset_and_restore() should have already
9972 * set the link state as active
9974 if (ret || !ufshcd_is_link_active(hba))
9975 goto vendor_suspend;
9978 if (!ufshcd_is_ufs_dev_active(hba)) {
9979 ret = ufshcd_set_dev_pwr_mode(hba, UFS_ACTIVE_PWR_MODE);
9981 goto set_old_link_state;
9982 ufshcd_set_timestamp_attr(hba);
9983 schedule_delayed_work(&hba->ufs_rtc_update_work,
9984 msecs_to_jiffies(UFS_RTC_UPDATE_INTERVAL_MS));
9987 if (ufshcd_keep_autobkops_enabled_except_suspend(hba))
9988 ufshcd_enable_auto_bkops(hba);
9991 * If BKOPs operations are urgently needed at this moment then
9992 * keep auto-bkops enabled or else disable it.
9994 ufshcd_urgent_bkops(hba);
9996 if (hba->ee_usr_mask)
9997 ufshcd_write_ee_control(hba);
9999 if (ufshcd_is_clkscaling_supported(hba))
10000 ufshcd_clk_scaling_suspend(hba, false);
10002 if (hba->dev_info.b_rpm_dev_flush_capable) {
10003 hba->dev_info.b_rpm_dev_flush_capable = false;
10004 cancel_delayed_work(&hba->rpm_dev_flush_recheck_work);
10007 ufshcd_configure_auto_hibern8(hba);
10011 set_old_link_state:
10012 ufshcd_link_state_transition(hba, old_link_state, 0);
10014 ufshcd_vops_suspend(hba, pm_op, PRE_CHANGE);
10015 ufshcd_vops_suspend(hba, pm_op, POST_CHANGE);
10018 ufshcd_update_evt_hist(hba, UFS_EVT_WL_RES_ERR, (u32)ret);
10019 hba->clk_gating.is_suspended = false;
10020 ufshcd_release(hba);
10021 hba->pm_op_in_progress = false;
10025 static int ufshcd_wl_runtime_suspend(struct device *dev)
10027 struct scsi_device *sdev = to_scsi_device(dev);
10028 struct ufs_hba *hba;
10030 ktime_t start = ktime_get();
10032 hba = shost_priv(sdev->host);
10034 ret = __ufshcd_wl_suspend(hba, UFS_RUNTIME_PM);
10036 dev_err(&sdev->sdev_gendev, "%s failed: %d\n", __func__, ret);
10038 trace_ufshcd_wl_runtime_suspend(dev_name(dev), ret,
10039 ktime_to_us(ktime_sub(ktime_get(), start)),
10040 hba->curr_dev_pwr_mode, hba->uic_link_state);
10045 static int ufshcd_wl_runtime_resume(struct device *dev)
10047 struct scsi_device *sdev = to_scsi_device(dev);
10048 struct ufs_hba *hba;
10050 ktime_t start = ktime_get();
10052 hba = shost_priv(sdev->host);
10054 ret = __ufshcd_wl_resume(hba, UFS_RUNTIME_PM);
10056 dev_err(&sdev->sdev_gendev, "%s failed: %d\n", __func__, ret);
10058 trace_ufshcd_wl_runtime_resume(dev_name(dev), ret,
10059 ktime_to_us(ktime_sub(ktime_get(), start)),
10060 hba->curr_dev_pwr_mode, hba->uic_link_state);
10066 #ifdef CONFIG_PM_SLEEP
10067 static int ufshcd_wl_suspend(struct device *dev)
10069 struct scsi_device *sdev = to_scsi_device(dev);
10070 struct ufs_hba *hba;
10072 ktime_t start = ktime_get();
10074 hba = shost_priv(sdev->host);
10075 down(&hba->host_sem);
10076 hba->system_suspending = true;
10078 if (pm_runtime_suspended(dev))
10081 ret = __ufshcd_wl_suspend(hba, UFS_SYSTEM_PM);
10083 dev_err(&sdev->sdev_gendev, "%s failed: %d\n", __func__, ret);
10084 up(&hba->host_sem);
10089 hba->is_sys_suspended = true;
10090 trace_ufshcd_wl_suspend(dev_name(dev), ret,
10091 ktime_to_us(ktime_sub(ktime_get(), start)),
10092 hba->curr_dev_pwr_mode, hba->uic_link_state);
10097 static int ufshcd_wl_resume(struct device *dev)
10099 struct scsi_device *sdev = to_scsi_device(dev);
10100 struct ufs_hba *hba;
10102 ktime_t start = ktime_get();
10104 hba = shost_priv(sdev->host);
10106 if (pm_runtime_suspended(dev))
10109 ret = __ufshcd_wl_resume(hba, UFS_SYSTEM_PM);
10111 dev_err(&sdev->sdev_gendev, "%s failed: %d\n", __func__, ret);
10113 trace_ufshcd_wl_resume(dev_name(dev), ret,
10114 ktime_to_us(ktime_sub(ktime_get(), start)),
10115 hba->curr_dev_pwr_mode, hba->uic_link_state);
10117 hba->is_sys_suspended = false;
10118 hba->system_suspending = false;
10119 up(&hba->host_sem);
10125 * ufshcd_suspend - helper function for suspend operations
10126 * @hba: per adapter instance
10128 * This function will put disable irqs, turn off clocks
10129 * and set vreg and hba-vreg in lpm mode.
10131 * Return: 0 upon success; < 0 upon failure.
10133 static int ufshcd_suspend(struct ufs_hba *hba)
10137 if (!hba->is_powered)
10140 * Disable the host irq as host controller as there won't be any
10141 * host controller transaction expected till resume.
10143 ufshcd_disable_irq(hba);
10144 ret = ufshcd_setup_clocks(hba, false);
10146 ufshcd_enable_irq(hba);
10149 if (ufshcd_is_clkgating_allowed(hba)) {
10150 hba->clk_gating.state = CLKS_OFF;
10151 trace_ufshcd_clk_gating(dev_name(hba->dev),
10152 hba->clk_gating.state);
10155 ufshcd_vreg_set_lpm(hba);
10156 /* Put the host controller in low power mode if possible */
10157 ufshcd_hba_vreg_set_lpm(hba);
10158 ufshcd_pm_qos_update(hba, false);
10164 * ufshcd_resume - helper function for resume operations
10165 * @hba: per adapter instance
10167 * This function basically turns on the regulators, clocks and
10170 * Return: 0 for success and non-zero for failure.
10172 static int ufshcd_resume(struct ufs_hba *hba)
10176 if (!hba->is_powered)
10179 ufshcd_hba_vreg_set_hpm(hba);
10180 ret = ufshcd_vreg_set_hpm(hba);
10184 /* Make sure clocks are enabled before accessing controller */
10185 ret = ufshcd_setup_clocks(hba, true);
10189 /* enable the host irq as host controller would be active soon */
10190 ufshcd_enable_irq(hba);
10195 ufshcd_vreg_set_lpm(hba);
10198 ufshcd_update_evt_hist(hba, UFS_EVT_RESUME_ERR, (u32)ret);
10201 #endif /* CONFIG_PM */
10203 #ifdef CONFIG_PM_SLEEP
10205 * ufshcd_system_suspend - system suspend callback
10206 * @dev: Device associated with the UFS controller.
10208 * Executed before putting the system into a sleep state in which the contents
10209 * of main memory are preserved.
10211 * Return: 0 for success and non-zero for failure.
10213 int ufshcd_system_suspend(struct device *dev)
10215 struct ufs_hba *hba = dev_get_drvdata(dev);
10217 ktime_t start = ktime_get();
10219 if (pm_runtime_suspended(hba->dev))
10222 ret = ufshcd_suspend(hba);
10224 trace_ufshcd_system_suspend(dev_name(hba->dev), ret,
10225 ktime_to_us(ktime_sub(ktime_get(), start)),
10226 hba->curr_dev_pwr_mode, hba->uic_link_state);
10229 EXPORT_SYMBOL(ufshcd_system_suspend);
10232 * ufshcd_system_resume - system resume callback
10233 * @dev: Device associated with the UFS controller.
10235 * Executed after waking the system up from a sleep state in which the contents
10236 * of main memory were preserved.
10238 * Return: 0 for success and non-zero for failure.
10240 int ufshcd_system_resume(struct device *dev)
10242 struct ufs_hba *hba = dev_get_drvdata(dev);
10243 ktime_t start = ktime_get();
10246 if (pm_runtime_suspended(hba->dev))
10249 ret = ufshcd_resume(hba);
10252 trace_ufshcd_system_resume(dev_name(hba->dev), ret,
10253 ktime_to_us(ktime_sub(ktime_get(), start)),
10254 hba->curr_dev_pwr_mode, hba->uic_link_state);
10258 EXPORT_SYMBOL(ufshcd_system_resume);
10259 #endif /* CONFIG_PM_SLEEP */
10263 * ufshcd_runtime_suspend - runtime suspend callback
10264 * @dev: Device associated with the UFS controller.
10266 * Check the description of ufshcd_suspend() function for more details.
10268 * Return: 0 for success and non-zero for failure.
10270 int ufshcd_runtime_suspend(struct device *dev)
10272 struct ufs_hba *hba = dev_get_drvdata(dev);
10274 ktime_t start = ktime_get();
10276 ret = ufshcd_suspend(hba);
10278 trace_ufshcd_runtime_suspend(dev_name(hba->dev), ret,
10279 ktime_to_us(ktime_sub(ktime_get(), start)),
10280 hba->curr_dev_pwr_mode, hba->uic_link_state);
10283 EXPORT_SYMBOL(ufshcd_runtime_suspend);
10286 * ufshcd_runtime_resume - runtime resume routine
10287 * @dev: Device associated with the UFS controller.
10289 * This function basically brings controller
10290 * to active state. Following operations are done in this function:
10292 * 1. Turn on all the controller related clocks
10293 * 2. Turn ON VCC rail
10295 * Return: 0 upon success; < 0 upon failure.
10297 int ufshcd_runtime_resume(struct device *dev)
10299 struct ufs_hba *hba = dev_get_drvdata(dev);
10301 ktime_t start = ktime_get();
10303 ret = ufshcd_resume(hba);
10305 trace_ufshcd_runtime_resume(dev_name(hba->dev), ret,
10306 ktime_to_us(ktime_sub(ktime_get(), start)),
10307 hba->curr_dev_pwr_mode, hba->uic_link_state);
10310 EXPORT_SYMBOL(ufshcd_runtime_resume);
10311 #endif /* CONFIG_PM */
10313 static void ufshcd_wl_shutdown(struct device *dev)
10315 struct scsi_device *sdev = to_scsi_device(dev);
10316 struct ufs_hba *hba = shost_priv(sdev->host);
10318 down(&hba->host_sem);
10319 hba->shutting_down = true;
10320 up(&hba->host_sem);
10322 /* Turn on everything while shutting down */
10323 ufshcd_rpm_get_sync(hba);
10324 scsi_device_quiesce(sdev);
10325 shost_for_each_device(sdev, hba->host) {
10326 if (sdev == hba->ufs_device_wlun)
10328 scsi_device_quiesce(sdev);
10330 __ufshcd_wl_suspend(hba, UFS_SHUTDOWN_PM);
10333 * Next, turn off the UFS controller and the UFS regulators. Disable
10336 if (ufshcd_is_ufs_dev_poweroff(hba) && ufshcd_is_link_off(hba))
10337 ufshcd_suspend(hba);
10339 hba->is_powered = false;
10343 * ufshcd_remove - de-allocate SCSI host and host memory space
10344 * data structure memory
10345 * @hba: per adapter instance
10347 void ufshcd_remove(struct ufs_hba *hba)
10349 if (hba->ufs_device_wlun)
10350 ufshcd_rpm_get_sync(hba);
10351 ufs_hwmon_remove(hba);
10352 ufs_bsg_remove(hba);
10353 ufs_sysfs_remove_nodes(hba->dev);
10354 blk_mq_destroy_queue(hba->tmf_queue);
10355 blk_put_queue(hba->tmf_queue);
10356 blk_mq_free_tag_set(&hba->tmf_tag_set);
10357 scsi_remove_host(hba->host);
10358 /* disable interrupts */
10359 ufshcd_disable_intr(hba, hba->intr_mask);
10360 ufshcd_hba_stop(hba);
10361 ufshcd_hba_exit(hba);
10363 EXPORT_SYMBOL_GPL(ufshcd_remove);
10365 #ifdef CONFIG_PM_SLEEP
10366 int ufshcd_system_freeze(struct device *dev)
10369 return ufshcd_system_suspend(dev);
10372 EXPORT_SYMBOL_GPL(ufshcd_system_freeze);
10374 int ufshcd_system_restore(struct device *dev)
10377 struct ufs_hba *hba = dev_get_drvdata(dev);
10380 ret = ufshcd_system_resume(dev);
10384 /* Configure UTRL and UTMRL base address registers */
10385 ufshcd_writel(hba, lower_32_bits(hba->utrdl_dma_addr),
10386 REG_UTP_TRANSFER_REQ_LIST_BASE_L);
10387 ufshcd_writel(hba, upper_32_bits(hba->utrdl_dma_addr),
10388 REG_UTP_TRANSFER_REQ_LIST_BASE_H);
10389 ufshcd_writel(hba, lower_32_bits(hba->utmrdl_dma_addr),
10390 REG_UTP_TASK_REQ_LIST_BASE_L);
10391 ufshcd_writel(hba, upper_32_bits(hba->utmrdl_dma_addr),
10392 REG_UTP_TASK_REQ_LIST_BASE_H);
10394 * Make sure that UTRL and UTMRL base address registers
10395 * are updated with the latest queue addresses. Only after
10396 * updating these addresses, we can queue the new commands.
10400 /* Resuming from hibernate, assume that link was OFF */
10401 ufshcd_set_link_off(hba);
10406 EXPORT_SYMBOL_GPL(ufshcd_system_restore);
10408 int ufshcd_system_thaw(struct device *dev)
10410 return ufshcd_system_resume(dev);
10412 EXPORT_SYMBOL_GPL(ufshcd_system_thaw);
10413 #endif /* CONFIG_PM_SLEEP */
10416 * ufshcd_dealloc_host - deallocate Host Bus Adapter (HBA)
10417 * @hba: pointer to Host Bus Adapter (HBA)
10419 void ufshcd_dealloc_host(struct ufs_hba *hba)
10421 scsi_host_put(hba->host);
10423 EXPORT_SYMBOL_GPL(ufshcd_dealloc_host);
10426 * ufshcd_set_dma_mask - Set dma mask based on the controller
10427 * addressing capability
10428 * @hba: per adapter instance
10430 * Return: 0 for success, non-zero for failure.
10432 static int ufshcd_set_dma_mask(struct ufs_hba *hba)
10434 if (hba->capabilities & MASK_64_ADDRESSING_SUPPORT) {
10435 if (!dma_set_mask_and_coherent(hba->dev, DMA_BIT_MASK(64)))
10438 return dma_set_mask_and_coherent(hba->dev, DMA_BIT_MASK(32));
10442 * ufshcd_alloc_host - allocate Host Bus Adapter (HBA)
10443 * @dev: pointer to device handle
10444 * @hba_handle: driver private handle
10446 * Return: 0 on success, non-zero value on failure.
10448 int ufshcd_alloc_host(struct device *dev, struct ufs_hba **hba_handle)
10450 struct Scsi_Host *host;
10451 struct ufs_hba *hba;
10456 "Invalid memory reference for dev is NULL\n");
10461 host = scsi_host_alloc(&ufshcd_driver_template,
10462 sizeof(struct ufs_hba));
10464 dev_err(dev, "scsi_host_alloc failed\n");
10468 host->nr_maps = HCTX_TYPE_POLL + 1;
10469 hba = shost_priv(host);
10472 hba->dev_ref_clk_freq = REF_CLK_FREQ_INVAL;
10473 hba->nop_out_timeout = NOP_OUT_TIMEOUT;
10474 ufshcd_set_sg_entry_size(hba, sizeof(struct ufshcd_sg_entry));
10475 INIT_LIST_HEAD(&hba->clk_list_head);
10476 spin_lock_init(&hba->outstanding_lock);
10483 EXPORT_SYMBOL(ufshcd_alloc_host);
10485 /* This function exists because blk_mq_alloc_tag_set() requires this. */
10486 static blk_status_t ufshcd_queue_tmf(struct blk_mq_hw_ctx *hctx,
10487 const struct blk_mq_queue_data *qd)
10489 WARN_ON_ONCE(true);
10490 return BLK_STS_NOTSUPP;
10493 static const struct blk_mq_ops ufshcd_tmf_ops = {
10494 .queue_rq = ufshcd_queue_tmf,
10498 * ufshcd_init - Driver initialization routine
10499 * @hba: per-adapter instance
10500 * @mmio_base: base register address
10501 * @irq: Interrupt line of device
10503 * Return: 0 on success, non-zero value on failure.
10505 int ufshcd_init(struct ufs_hba *hba, void __iomem *mmio_base, unsigned int irq)
10508 struct Scsi_Host *host = hba->host;
10509 struct device *dev = hba->dev;
10510 char eh_wq_name[sizeof("ufs_eh_wq_00")];
10513 * dev_set_drvdata() must be called before any callbacks are registered
10514 * that use dev_get_drvdata() (frequency scaling, clock scaling, hwmon,
10517 dev_set_drvdata(dev, hba);
10521 "Invalid memory reference for mmio_base is NULL\n");
10526 hba->mmio_base = mmio_base;
10528 hba->vps = &ufs_hba_vps;
10530 err = ufshcd_hba_init(hba);
10534 /* Read capabilities registers */
10535 err = ufshcd_hba_capabilities(hba);
10539 /* Get UFS version supported by the controller */
10540 hba->ufs_version = ufshcd_get_ufs_version(hba);
10542 /* Get Interrupt bit mask per version */
10543 hba->intr_mask = ufshcd_get_intr_mask(hba);
10545 err = ufshcd_set_dma_mask(hba);
10547 dev_err(hba->dev, "set dma mask failed\n");
10551 /* Allocate memory for host memory space */
10552 err = ufshcd_memory_alloc(hba);
10554 dev_err(hba->dev, "Memory allocation failed\n");
10558 /* Configure LRB */
10559 ufshcd_host_memory_configure(hba);
10561 host->can_queue = hba->nutrs - UFSHCD_NUM_RESERVED;
10562 host->cmd_per_lun = hba->nutrs - UFSHCD_NUM_RESERVED;
10563 host->max_id = UFSHCD_MAX_ID;
10564 host->max_lun = UFS_MAX_LUNS;
10565 host->max_channel = UFSHCD_MAX_CHANNEL;
10566 host->unique_id = host->host_no;
10567 host->max_cmd_len = UFS_CDB_SIZE;
10568 host->queuecommand_may_block = !!(hba->caps & UFSHCD_CAP_CLK_GATING);
10570 /* Use default RPM delay if host not set */
10571 if (host->rpm_autosuspend_delay == 0)
10572 host->rpm_autosuspend_delay = RPM_AUTOSUSPEND_DELAY_MS;
10574 hba->max_pwr_info.is_valid = false;
10576 /* Initialize work queues */
10577 snprintf(eh_wq_name, sizeof(eh_wq_name), "ufs_eh_wq_%d",
10578 hba->host->host_no);
10579 hba->eh_wq = create_singlethread_workqueue(eh_wq_name);
10581 dev_err(hba->dev, "%s: failed to create eh workqueue\n",
10586 INIT_WORK(&hba->eh_work, ufshcd_err_handler);
10587 INIT_WORK(&hba->eeh_work, ufshcd_exception_event_handler);
10589 sema_init(&hba->host_sem, 1);
10591 /* Initialize UIC command mutex */
10592 mutex_init(&hba->uic_cmd_mutex);
10594 /* Initialize mutex for device management commands */
10595 mutex_init(&hba->dev_cmd.lock);
10597 /* Initialize mutex for exception event control */
10598 mutex_init(&hba->ee_ctrl_mutex);
10600 mutex_init(&hba->wb_mutex);
10601 init_rwsem(&hba->clk_scaling_lock);
10603 ufshcd_init_clk_gating(hba);
10605 ufshcd_init_clk_scaling(hba);
10608 * In order to avoid any spurious interrupt immediately after
10609 * registering UFS controller interrupt handler, clear any pending UFS
10610 * interrupt status and disable all the UFS interrupts.
10612 ufshcd_writel(hba, ufshcd_readl(hba, REG_INTERRUPT_STATUS),
10613 REG_INTERRUPT_STATUS);
10614 ufshcd_writel(hba, 0, REG_INTERRUPT_ENABLE);
10616 * Make sure that UFS interrupts are disabled and any pending interrupt
10617 * status is cleared before registering UFS interrupt handler.
10621 /* IRQ registration */
10622 err = devm_request_irq(dev, irq, ufshcd_intr, IRQF_SHARED, UFSHCD, hba);
10624 dev_err(hba->dev, "request irq failed\n");
10627 hba->is_irq_enabled = true;
10630 if (!is_mcq_supported(hba)) {
10631 err = scsi_add_host(host, hba->dev);
10633 dev_err(hba->dev, "scsi_add_host failed\n");
10638 hba->tmf_tag_set = (struct blk_mq_tag_set) {
10640 .queue_depth = hba->nutmrs,
10641 .ops = &ufshcd_tmf_ops,
10642 .flags = BLK_MQ_F_NO_SCHED,
10644 err = blk_mq_alloc_tag_set(&hba->tmf_tag_set);
10646 goto out_remove_scsi_host;
10647 hba->tmf_queue = blk_mq_alloc_queue(&hba->tmf_tag_set, NULL, NULL);
10648 if (IS_ERR(hba->tmf_queue)) {
10649 err = PTR_ERR(hba->tmf_queue);
10650 goto free_tmf_tag_set;
10652 hba->tmf_rqs = devm_kcalloc(hba->dev, hba->nutmrs,
10653 sizeof(*hba->tmf_rqs), GFP_KERNEL);
10654 if (!hba->tmf_rqs) {
10656 goto free_tmf_queue;
10659 /* Reset the attached device */
10660 ufshcd_device_reset(hba);
10662 ufshcd_init_crypto(hba);
10664 /* Host controller enable */
10665 err = ufshcd_hba_enable(hba);
10667 dev_err(hba->dev, "Host controller enable failed\n");
10668 ufshcd_print_evt_hist(hba);
10669 ufshcd_print_host_state(hba);
10670 goto free_tmf_queue;
10674 * Set the default power management level for runtime and system PM.
10675 * Default power saving mode is to keep UFS link in Hibern8 state
10676 * and UFS device in sleep state.
10678 hba->rpm_lvl = ufs_get_desired_pm_lvl_for_dev_link_state(
10679 UFS_SLEEP_PWR_MODE,
10680 UIC_LINK_HIBERN8_STATE);
10681 hba->spm_lvl = ufs_get_desired_pm_lvl_for_dev_link_state(
10682 UFS_SLEEP_PWR_MODE,
10683 UIC_LINK_HIBERN8_STATE);
10685 INIT_DELAYED_WORK(&hba->rpm_dev_flush_recheck_work, ufshcd_rpm_dev_flush_recheck_work);
10686 INIT_DELAYED_WORK(&hba->ufs_rtc_update_work, ufshcd_rtc_work);
10688 /* Set the default auto-hiberate idle timer value to 150 ms */
10689 if (ufshcd_is_auto_hibern8_supported(hba) && !hba->ahit) {
10690 hba->ahit = FIELD_PREP(UFSHCI_AHIBERN8_TIMER_MASK, 150) |
10691 FIELD_PREP(UFSHCI_AHIBERN8_SCALE_MASK, 3);
10694 /* Hold auto suspend until async scan completes */
10695 pm_runtime_get_sync(dev);
10696 atomic_set(&hba->scsi_block_reqs_cnt, 0);
10698 * We are assuming that device wasn't put in sleep/power-down
10699 * state exclusively during the boot stage before kernel.
10700 * This assumption helps avoid doing link startup twice during
10701 * ufshcd_probe_hba().
10703 ufshcd_set_ufs_dev_active(hba);
10705 async_schedule(ufshcd_async_scan, hba);
10706 ufs_sysfs_add_nodes(hba->dev);
10708 device_enable_async_suspend(dev);
10709 ufshcd_pm_qos_init(hba);
10713 blk_mq_destroy_queue(hba->tmf_queue);
10714 blk_put_queue(hba->tmf_queue);
10716 blk_mq_free_tag_set(&hba->tmf_tag_set);
10717 out_remove_scsi_host:
10718 scsi_remove_host(hba->host);
10720 hba->is_irq_enabled = false;
10721 ufshcd_hba_exit(hba);
10725 EXPORT_SYMBOL_GPL(ufshcd_init);
10727 void ufshcd_resume_complete(struct device *dev)
10729 struct ufs_hba *hba = dev_get_drvdata(dev);
10731 if (hba->complete_put) {
10732 ufshcd_rpm_put(hba);
10733 hba->complete_put = false;
10736 EXPORT_SYMBOL_GPL(ufshcd_resume_complete);
10738 static bool ufshcd_rpm_ok_for_spm(struct ufs_hba *hba)
10740 struct device *dev = &hba->ufs_device_wlun->sdev_gendev;
10741 enum ufs_dev_pwr_mode dev_pwr_mode;
10742 enum uic_link_state link_state;
10743 unsigned long flags;
10746 spin_lock_irqsave(&dev->power.lock, flags);
10747 dev_pwr_mode = ufs_get_pm_lvl_to_dev_pwr_mode(hba->spm_lvl);
10748 link_state = ufs_get_pm_lvl_to_link_pwr_state(hba->spm_lvl);
10749 res = pm_runtime_suspended(dev) &&
10750 hba->curr_dev_pwr_mode == dev_pwr_mode &&
10751 hba->uic_link_state == link_state &&
10752 !hba->dev_info.b_rpm_dev_flush_capable;
10753 spin_unlock_irqrestore(&dev->power.lock, flags);
10758 int __ufshcd_suspend_prepare(struct device *dev, bool rpm_ok_for_spm)
10760 struct ufs_hba *hba = dev_get_drvdata(dev);
10764 * SCSI assumes that runtime-pm and system-pm for scsi drivers
10765 * are same. And it doesn't wake up the device for system-suspend
10766 * if it's runtime suspended. But ufs doesn't follow that.
10767 * Refer ufshcd_resume_complete()
10769 if (hba->ufs_device_wlun) {
10770 /* Prevent runtime suspend */
10771 ufshcd_rpm_get_noresume(hba);
10773 * Check if already runtime suspended in same state as system
10774 * suspend would be.
10776 if (!rpm_ok_for_spm || !ufshcd_rpm_ok_for_spm(hba)) {
10777 /* RPM state is not ok for SPM, so runtime resume */
10778 ret = ufshcd_rpm_resume(hba);
10779 if (ret < 0 && ret != -EACCES) {
10780 ufshcd_rpm_put(hba);
10784 hba->complete_put = true;
10788 EXPORT_SYMBOL_GPL(__ufshcd_suspend_prepare);
10790 int ufshcd_suspend_prepare(struct device *dev)
10792 return __ufshcd_suspend_prepare(dev, true);
10794 EXPORT_SYMBOL_GPL(ufshcd_suspend_prepare);
10796 #ifdef CONFIG_PM_SLEEP
10797 static int ufshcd_wl_poweroff(struct device *dev)
10799 struct scsi_device *sdev = to_scsi_device(dev);
10800 struct ufs_hba *hba = shost_priv(sdev->host);
10802 __ufshcd_wl_suspend(hba, UFS_SHUTDOWN_PM);
10807 static int ufshcd_wl_probe(struct device *dev)
10809 struct scsi_device *sdev = to_scsi_device(dev);
10811 if (!is_device_wlun(sdev))
10814 blk_pm_runtime_init(sdev->request_queue, dev);
10815 pm_runtime_set_autosuspend_delay(dev, 0);
10816 pm_runtime_allow(dev);
10821 static int ufshcd_wl_remove(struct device *dev)
10823 pm_runtime_forbid(dev);
10827 static const struct dev_pm_ops ufshcd_wl_pm_ops = {
10828 #ifdef CONFIG_PM_SLEEP
10829 .suspend = ufshcd_wl_suspend,
10830 .resume = ufshcd_wl_resume,
10831 .freeze = ufshcd_wl_suspend,
10832 .thaw = ufshcd_wl_resume,
10833 .poweroff = ufshcd_wl_poweroff,
10834 .restore = ufshcd_wl_resume,
10836 SET_RUNTIME_PM_OPS(ufshcd_wl_runtime_suspend, ufshcd_wl_runtime_resume, NULL)
10839 static void ufshcd_check_header_layout(void)
10842 * gcc compilers before version 10 cannot do constant-folding for
10843 * sub-byte bitfields. Hence skip the layout checks for gcc 9 and
10846 if (IS_ENABLED(CONFIG_CC_IS_GCC) && CONFIG_GCC_VERSION < 100000)
10849 BUILD_BUG_ON(((u8 *)&(struct request_desc_header){
10850 .cci = 3})[0] != 3);
10852 BUILD_BUG_ON(((u8 *)&(struct request_desc_header){
10853 .ehs_length = 2})[1] != 2);
10855 BUILD_BUG_ON(((u8 *)&(struct request_desc_header){
10856 .enable_crypto = 1})[2]
10859 BUILD_BUG_ON((((u8 *)&(struct request_desc_header){
10861 .data_direction = 3,
10863 })[3]) != ((5 << 4) | (3 << 1) | 1));
10865 BUILD_BUG_ON(((__le32 *)&(struct request_desc_header){
10866 .dunl = cpu_to_le32(0xdeadbeef)})[1] !=
10867 cpu_to_le32(0xdeadbeef));
10869 BUILD_BUG_ON(((u8 *)&(struct request_desc_header){
10870 .ocs = 4})[8] != 4);
10872 BUILD_BUG_ON(((u8 *)&(struct request_desc_header){
10873 .cds = 5})[9] != 5);
10875 BUILD_BUG_ON(((__le32 *)&(struct request_desc_header){
10876 .dunu = cpu_to_le32(0xbadcafe)})[3] !=
10877 cpu_to_le32(0xbadcafe));
10879 BUILD_BUG_ON(((u8 *)&(struct utp_upiu_header){
10880 .iid = 0xf })[4] != 0xf0);
10882 BUILD_BUG_ON(((u8 *)&(struct utp_upiu_header){
10883 .command_set_type = 0xf })[4] != 0xf);
10887 * ufs_dev_wlun_template - describes ufs device wlun
10888 * ufs-device wlun - used to send pm commands
10889 * All luns are consumers of ufs-device wlun.
10891 * Currently, no sd driver is present for wluns.
10892 * Hence the no specific pm operations are performed.
10893 * With ufs design, SSU should be sent to ufs-device wlun.
10894 * Hence register a scsi driver for ufs wluns only.
10896 static struct scsi_driver ufs_dev_wlun_template = {
10898 .name = "ufs_device_wlun",
10899 .owner = THIS_MODULE,
10900 .probe = ufshcd_wl_probe,
10901 .remove = ufshcd_wl_remove,
10902 .pm = &ufshcd_wl_pm_ops,
10903 .shutdown = ufshcd_wl_shutdown,
10907 static int __init ufshcd_core_init(void)
10911 ufshcd_check_header_layout();
10913 ufs_debugfs_init();
10915 ret = scsi_register_driver(&ufs_dev_wlun_template.gendrv);
10917 ufs_debugfs_exit();
10921 static void __exit ufshcd_core_exit(void)
10923 ufs_debugfs_exit();
10924 scsi_unregister_driver(&ufs_dev_wlun_template.gendrv);
10927 module_init(ufshcd_core_init);
10928 module_exit(ufshcd_core_exit);
10930 MODULE_AUTHOR("Santosh Yaragnavi <santosh.sy@samsung.com>");
10931 MODULE_AUTHOR("Vinayak Holikatti <h.vinayak@samsung.com>");
10932 MODULE_DESCRIPTION("Generic UFS host controller driver Core");
10933 MODULE_SOFTDEP("pre: governor_simpleondemand");
10934 MODULE_LICENSE("GPL");