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 <scsi/scsi_driver.h>
21 #include "ufs_quirks.h"
23 #include "ufs-sysfs.h"
24 #include "ufs-debugfs.h"
25 #include "ufs-fault-injection.h"
27 #include "ufshcd-crypto.h"
29 #include <asm/unaligned.h>
31 #define CREATE_TRACE_POINTS
32 #include <trace/events/ufs.h>
34 #define UFSHCD_ENABLE_INTRS (UTP_TRANSFER_REQ_COMPL |\
37 /* UIC command timeout, unit: ms */
38 #define UIC_CMD_TIMEOUT 500
40 /* NOP OUT retries waiting for NOP IN response */
41 #define NOP_OUT_RETRIES 10
42 /* Timeout after 50 msecs if NOP OUT hangs without response */
43 #define NOP_OUT_TIMEOUT 50 /* msecs */
45 /* Query request retries */
46 #define QUERY_REQ_RETRIES 3
47 /* Query request timeout */
48 #define QUERY_REQ_TIMEOUT 1500 /* 1.5 seconds */
50 /* Task management command timeout */
51 #define TM_CMD_TIMEOUT 100 /* msecs */
53 /* maximum number of retries for a general UIC command */
54 #define UFS_UIC_COMMAND_RETRIES 3
56 /* maximum number of link-startup retries */
57 #define DME_LINKSTARTUP_RETRIES 3
59 /* Maximum retries for Hibern8 enter */
60 #define UIC_HIBERN8_ENTER_RETRIES 3
62 /* maximum number of reset retries before giving up */
63 #define MAX_HOST_RESET_RETRIES 5
65 /* Maximum number of error handler retries before giving up */
66 #define MAX_ERR_HANDLER_RETRIES 5
68 /* Expose the flag value from utp_upiu_query.value */
69 #define MASK_QUERY_UPIU_FLAG_LOC 0xFF
71 /* Interrupt aggregation default timeout, unit: 40us */
72 #define INT_AGGR_DEF_TO 0x02
74 /* default delay of autosuspend: 2000 ms */
75 #define RPM_AUTOSUSPEND_DELAY_MS 2000
77 /* Default delay of RPM device flush delayed work */
78 #define RPM_DEV_FLUSH_RECHECK_WORK_DELAY_MS 5000
80 /* Default value of wait time before gating device ref clock */
81 #define UFSHCD_REF_CLK_GATING_WAIT_US 0xFF /* microsecs */
83 /* Polling time to wait for fDeviceInit */
84 #define FDEVICEINIT_COMPL_TIMEOUT 1500 /* millisecs */
86 #define wlun_dev_to_hba(dv) shost_priv(to_scsi_device(dv)->host)
88 #define ufshcd_toggle_vreg(_dev, _vreg, _on) \
92 _ret = ufshcd_enable_vreg(_dev, _vreg); \
94 _ret = ufshcd_disable_vreg(_dev, _vreg); \
98 #define ufshcd_hex_dump(prefix_str, buf, len) do { \
99 size_t __len = (len); \
100 print_hex_dump(KERN_ERR, prefix_str, \
101 __len > 4 ? DUMP_PREFIX_OFFSET : DUMP_PREFIX_NONE,\
102 16, 4, buf, __len, false); \
105 int ufshcd_dump_regs(struct ufs_hba *hba, size_t offset, size_t len,
111 if (offset % 4 != 0 || len % 4 != 0) /* keep readl happy */
114 regs = kzalloc(len, GFP_ATOMIC);
118 for (pos = 0; pos < len; pos += 4)
119 regs[pos / 4] = ufshcd_readl(hba, offset + pos);
121 ufshcd_hex_dump(prefix, regs, len);
126 EXPORT_SYMBOL_GPL(ufshcd_dump_regs);
129 UFSHCD_MAX_CHANNEL = 0,
131 UFSHCD_NUM_RESERVED = 1,
132 UFSHCD_CMD_PER_LUN = 32 - UFSHCD_NUM_RESERVED,
133 UFSHCD_CAN_QUEUE = 32 - UFSHCD_NUM_RESERVED,
136 static const char *const ufshcd_state_name[] = {
137 [UFSHCD_STATE_RESET] = "reset",
138 [UFSHCD_STATE_OPERATIONAL] = "operational",
139 [UFSHCD_STATE_ERROR] = "error",
140 [UFSHCD_STATE_EH_SCHEDULED_FATAL] = "eh_fatal",
141 [UFSHCD_STATE_EH_SCHEDULED_NON_FATAL] = "eh_non_fatal",
144 /* UFSHCD error handling flags */
146 UFSHCD_EH_IN_PROGRESS = (1 << 0),
149 /* UFSHCD UIC layer error flags */
151 UFSHCD_UIC_DL_PA_INIT_ERROR = (1 << 0), /* Data link layer error */
152 UFSHCD_UIC_DL_NAC_RECEIVED_ERROR = (1 << 1), /* Data link layer error */
153 UFSHCD_UIC_DL_TCx_REPLAY_ERROR = (1 << 2), /* Data link layer error */
154 UFSHCD_UIC_NL_ERROR = (1 << 3), /* Network layer error */
155 UFSHCD_UIC_TL_ERROR = (1 << 4), /* Transport Layer error */
156 UFSHCD_UIC_DME_ERROR = (1 << 5), /* DME error */
157 UFSHCD_UIC_PA_GENERIC_ERROR = (1 << 6), /* Generic PA error */
160 #define ufshcd_set_eh_in_progress(h) \
161 ((h)->eh_flags |= UFSHCD_EH_IN_PROGRESS)
162 #define ufshcd_eh_in_progress(h) \
163 ((h)->eh_flags & UFSHCD_EH_IN_PROGRESS)
164 #define ufshcd_clear_eh_in_progress(h) \
165 ((h)->eh_flags &= ~UFSHCD_EH_IN_PROGRESS)
167 struct ufs_pm_lvl_states ufs_pm_lvl_states[] = {
168 [UFS_PM_LVL_0] = {UFS_ACTIVE_PWR_MODE, UIC_LINK_ACTIVE_STATE},
169 [UFS_PM_LVL_1] = {UFS_ACTIVE_PWR_MODE, UIC_LINK_HIBERN8_STATE},
170 [UFS_PM_LVL_2] = {UFS_SLEEP_PWR_MODE, UIC_LINK_ACTIVE_STATE},
171 [UFS_PM_LVL_3] = {UFS_SLEEP_PWR_MODE, UIC_LINK_HIBERN8_STATE},
172 [UFS_PM_LVL_4] = {UFS_POWERDOWN_PWR_MODE, UIC_LINK_HIBERN8_STATE},
173 [UFS_PM_LVL_5] = {UFS_POWERDOWN_PWR_MODE, UIC_LINK_OFF_STATE},
175 * For DeepSleep, the link is first put in hibern8 and then off.
176 * Leaving the link in hibern8 is not supported.
178 [UFS_PM_LVL_6] = {UFS_DEEPSLEEP_PWR_MODE, UIC_LINK_OFF_STATE},
181 static inline enum ufs_dev_pwr_mode
182 ufs_get_pm_lvl_to_dev_pwr_mode(enum ufs_pm_level lvl)
184 return ufs_pm_lvl_states[lvl].dev_state;
187 static inline enum uic_link_state
188 ufs_get_pm_lvl_to_link_pwr_state(enum ufs_pm_level lvl)
190 return ufs_pm_lvl_states[lvl].link_state;
193 static inline enum ufs_pm_level
194 ufs_get_desired_pm_lvl_for_dev_link_state(enum ufs_dev_pwr_mode dev_state,
195 enum uic_link_state link_state)
197 enum ufs_pm_level lvl;
199 for (lvl = UFS_PM_LVL_0; lvl < UFS_PM_LVL_MAX; lvl++) {
200 if ((ufs_pm_lvl_states[lvl].dev_state == dev_state) &&
201 (ufs_pm_lvl_states[lvl].link_state == link_state))
205 /* if no match found, return the level 0 */
209 static struct ufs_dev_fix ufs_fixups[] = {
210 /* UFS cards deviations table */
211 UFS_FIX(UFS_VENDOR_MICRON, UFS_ANY_MODEL,
212 UFS_DEVICE_QUIRK_DELAY_BEFORE_LPM |
213 UFS_DEVICE_QUIRK_SWAP_L2P_ENTRY_FOR_HPB_READ),
214 UFS_FIX(UFS_VENDOR_SAMSUNG, UFS_ANY_MODEL,
215 UFS_DEVICE_QUIRK_DELAY_BEFORE_LPM |
216 UFS_DEVICE_QUIRK_HOST_PA_TACTIVATE |
217 UFS_DEVICE_QUIRK_RECOVERY_FROM_DL_NAC_ERRORS),
218 UFS_FIX(UFS_VENDOR_SKHYNIX, UFS_ANY_MODEL,
219 UFS_DEVICE_QUIRK_HOST_PA_SAVECONFIGTIME),
220 UFS_FIX(UFS_VENDOR_SKHYNIX, "hB8aL1" /*H28U62301AMR*/,
221 UFS_DEVICE_QUIRK_HOST_VS_DEBUGSAVECONFIGTIME),
222 UFS_FIX(UFS_VENDOR_TOSHIBA, UFS_ANY_MODEL,
223 UFS_DEVICE_QUIRK_DELAY_BEFORE_LPM),
224 UFS_FIX(UFS_VENDOR_TOSHIBA, "THGLF2G9C8KBADG",
225 UFS_DEVICE_QUIRK_PA_TACTIVATE),
226 UFS_FIX(UFS_VENDOR_TOSHIBA, "THGLF2G9D8KBADG",
227 UFS_DEVICE_QUIRK_PA_TACTIVATE),
231 static irqreturn_t ufshcd_tmc_handler(struct ufs_hba *hba);
232 static void ufshcd_async_scan(void *data, async_cookie_t cookie);
233 static int ufshcd_reset_and_restore(struct ufs_hba *hba);
234 static int ufshcd_eh_host_reset_handler(struct scsi_cmnd *cmd);
235 static int ufshcd_clear_tm_cmd(struct ufs_hba *hba, int tag);
236 static void ufshcd_hba_exit(struct ufs_hba *hba);
237 static int ufshcd_probe_hba(struct ufs_hba *hba, bool init_dev_params);
238 static int ufshcd_setup_clocks(struct ufs_hba *hba, bool on);
239 static inline void ufshcd_add_delay_before_dme_cmd(struct ufs_hba *hba);
240 static int ufshcd_host_reset_and_restore(struct ufs_hba *hba);
241 static void ufshcd_resume_clkscaling(struct ufs_hba *hba);
242 static void ufshcd_suspend_clkscaling(struct ufs_hba *hba);
243 static void __ufshcd_suspend_clkscaling(struct ufs_hba *hba);
244 static int ufshcd_scale_clks(struct ufs_hba *hba, bool scale_up);
245 static irqreturn_t ufshcd_intr(int irq, void *__hba);
246 static int ufshcd_change_power_mode(struct ufs_hba *hba,
247 struct ufs_pa_layer_attr *pwr_mode);
248 static int ufshcd_setup_hba_vreg(struct ufs_hba *hba, bool on);
249 static int ufshcd_setup_vreg(struct ufs_hba *hba, bool on);
250 static inline int ufshcd_config_vreg_hpm(struct ufs_hba *hba,
251 struct ufs_vreg *vreg);
252 static int ufshcd_try_to_abort_task(struct ufs_hba *hba, int tag);
253 static void ufshcd_wb_toggle_flush_during_h8(struct ufs_hba *hba, bool set);
254 static inline void ufshcd_wb_toggle_flush(struct ufs_hba *hba, bool enable);
255 static void ufshcd_hba_vreg_set_lpm(struct ufs_hba *hba);
256 static void ufshcd_hba_vreg_set_hpm(struct ufs_hba *hba);
258 static inline void ufshcd_enable_irq(struct ufs_hba *hba)
260 if (!hba->is_irq_enabled) {
261 enable_irq(hba->irq);
262 hba->is_irq_enabled = true;
266 static inline void ufshcd_disable_irq(struct ufs_hba *hba)
268 if (hba->is_irq_enabled) {
269 disable_irq(hba->irq);
270 hba->is_irq_enabled = false;
274 static inline void ufshcd_wb_config(struct ufs_hba *hba)
276 if (!ufshcd_is_wb_allowed(hba))
279 ufshcd_wb_toggle(hba, true);
281 ufshcd_wb_toggle_flush_during_h8(hba, true);
282 if (!(hba->quirks & UFSHCI_QUIRK_SKIP_MANUAL_WB_FLUSH_CTRL))
283 ufshcd_wb_toggle_flush(hba, true);
286 static void ufshcd_scsi_unblock_requests(struct ufs_hba *hba)
288 if (atomic_dec_and_test(&hba->scsi_block_reqs_cnt))
289 scsi_unblock_requests(hba->host);
292 static void ufshcd_scsi_block_requests(struct ufs_hba *hba)
294 if (atomic_inc_return(&hba->scsi_block_reqs_cnt) == 1)
295 scsi_block_requests(hba->host);
298 static void ufshcd_add_cmd_upiu_trace(struct ufs_hba *hba, unsigned int tag,
299 enum ufs_trace_str_t str_t)
301 struct utp_upiu_req *rq = hba->lrb[tag].ucd_req_ptr;
302 struct utp_upiu_header *header;
304 if (!trace_ufshcd_upiu_enabled())
307 if (str_t == UFS_CMD_SEND)
308 header = &rq->header;
310 header = &hba->lrb[tag].ucd_rsp_ptr->header;
312 trace_ufshcd_upiu(dev_name(hba->dev), str_t, header, &rq->sc.cdb,
316 static void ufshcd_add_query_upiu_trace(struct ufs_hba *hba,
317 enum ufs_trace_str_t str_t,
318 struct utp_upiu_req *rq_rsp)
320 if (!trace_ufshcd_upiu_enabled())
323 trace_ufshcd_upiu(dev_name(hba->dev), str_t, &rq_rsp->header,
324 &rq_rsp->qr, UFS_TSF_OSF);
327 static void ufshcd_add_tm_upiu_trace(struct ufs_hba *hba, unsigned int tag,
328 enum ufs_trace_str_t str_t)
330 struct utp_task_req_desc *descp = &hba->utmrdl_base_addr[tag];
332 if (!trace_ufshcd_upiu_enabled())
335 if (str_t == UFS_TM_SEND)
336 trace_ufshcd_upiu(dev_name(hba->dev), str_t,
337 &descp->upiu_req.req_header,
338 &descp->upiu_req.input_param1,
341 trace_ufshcd_upiu(dev_name(hba->dev), str_t,
342 &descp->upiu_rsp.rsp_header,
343 &descp->upiu_rsp.output_param1,
347 static void ufshcd_add_uic_command_trace(struct ufs_hba *hba,
348 struct uic_command *ucmd,
349 enum ufs_trace_str_t str_t)
353 if (!trace_ufshcd_uic_command_enabled())
356 if (str_t == UFS_CMD_SEND)
359 cmd = ufshcd_readl(hba, REG_UIC_COMMAND);
361 trace_ufshcd_uic_command(dev_name(hba->dev), str_t, cmd,
362 ufshcd_readl(hba, REG_UIC_COMMAND_ARG_1),
363 ufshcd_readl(hba, REG_UIC_COMMAND_ARG_2),
364 ufshcd_readl(hba, REG_UIC_COMMAND_ARG_3));
367 static void ufshcd_add_command_trace(struct ufs_hba *hba, unsigned int tag,
368 enum ufs_trace_str_t str_t)
371 u8 opcode = 0, group_id = 0;
373 struct ufshcd_lrb *lrbp = &hba->lrb[tag];
374 struct scsi_cmnd *cmd = lrbp->cmd;
375 struct request *rq = scsi_cmd_to_rq(cmd);
376 int transfer_len = -1;
381 /* trace UPIU also */
382 ufshcd_add_cmd_upiu_trace(hba, tag, str_t);
383 if (!trace_ufshcd_command_enabled())
386 opcode = cmd->cmnd[0];
387 lba = scsi_get_lba(cmd);
389 if (opcode == READ_10 || opcode == WRITE_10) {
391 * Currently we only fully trace read(10) and write(10) commands
394 be32_to_cpu(lrbp->ucd_req_ptr->sc.exp_data_transfer_len);
395 if (opcode == WRITE_10)
396 group_id = lrbp->cmd->cmnd[6];
397 } else if (opcode == UNMAP) {
399 * The number of Bytes to be unmapped beginning with the lba.
401 transfer_len = blk_rq_bytes(rq);
404 intr = ufshcd_readl(hba, REG_INTERRUPT_STATUS);
405 doorbell = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
406 trace_ufshcd_command(dev_name(hba->dev), str_t, tag,
407 doorbell, transfer_len, intr, lba, opcode, group_id);
410 static void ufshcd_print_clk_freqs(struct ufs_hba *hba)
412 struct ufs_clk_info *clki;
413 struct list_head *head = &hba->clk_list_head;
415 if (list_empty(head))
418 list_for_each_entry(clki, head, list) {
419 if (!IS_ERR_OR_NULL(clki->clk) && clki->min_freq &&
421 dev_err(hba->dev, "clk: %s, rate: %u\n",
422 clki->name, clki->curr_freq);
426 static void ufshcd_print_evt(struct ufs_hba *hba, u32 id,
431 struct ufs_event_hist *e;
433 if (id >= UFS_EVT_CNT)
436 e = &hba->ufs_stats.event[id];
438 for (i = 0; i < UFS_EVENT_HIST_LENGTH; i++) {
439 int p = (i + e->pos) % UFS_EVENT_HIST_LENGTH;
441 if (e->tstamp[p] == 0)
443 dev_err(hba->dev, "%s[%d] = 0x%x at %lld us\n", err_name, p,
444 e->val[p], ktime_to_us(e->tstamp[p]));
449 dev_err(hba->dev, "No record of %s\n", err_name);
451 dev_err(hba->dev, "%s: total cnt=%llu\n", err_name, e->cnt);
454 static void ufshcd_print_evt_hist(struct ufs_hba *hba)
456 ufshcd_dump_regs(hba, 0, UFSHCI_REG_SPACE_SIZE, "host_regs: ");
458 ufshcd_print_evt(hba, UFS_EVT_PA_ERR, "pa_err");
459 ufshcd_print_evt(hba, UFS_EVT_DL_ERR, "dl_err");
460 ufshcd_print_evt(hba, UFS_EVT_NL_ERR, "nl_err");
461 ufshcd_print_evt(hba, UFS_EVT_TL_ERR, "tl_err");
462 ufshcd_print_evt(hba, UFS_EVT_DME_ERR, "dme_err");
463 ufshcd_print_evt(hba, UFS_EVT_AUTO_HIBERN8_ERR,
465 ufshcd_print_evt(hba, UFS_EVT_FATAL_ERR, "fatal_err");
466 ufshcd_print_evt(hba, UFS_EVT_LINK_STARTUP_FAIL,
467 "link_startup_fail");
468 ufshcd_print_evt(hba, UFS_EVT_RESUME_ERR, "resume_fail");
469 ufshcd_print_evt(hba, UFS_EVT_SUSPEND_ERR,
471 ufshcd_print_evt(hba, UFS_EVT_DEV_RESET, "dev_reset");
472 ufshcd_print_evt(hba, UFS_EVT_HOST_RESET, "host_reset");
473 ufshcd_print_evt(hba, UFS_EVT_ABORT, "task_abort");
475 ufshcd_vops_dbg_register_dump(hba);
479 void ufshcd_print_trs(struct ufs_hba *hba, unsigned long bitmap, bool pr_prdt)
481 struct ufshcd_lrb *lrbp;
485 for_each_set_bit(tag, &bitmap, hba->nutrs) {
486 lrbp = &hba->lrb[tag];
488 dev_err(hba->dev, "UPIU[%d] - issue time %lld us\n",
489 tag, ktime_to_us(lrbp->issue_time_stamp));
490 dev_err(hba->dev, "UPIU[%d] - complete time %lld us\n",
491 tag, ktime_to_us(lrbp->compl_time_stamp));
493 "UPIU[%d] - Transfer Request Descriptor phys@0x%llx\n",
494 tag, (u64)lrbp->utrd_dma_addr);
496 ufshcd_hex_dump("UPIU TRD: ", lrbp->utr_descriptor_ptr,
497 sizeof(struct utp_transfer_req_desc));
498 dev_err(hba->dev, "UPIU[%d] - Request UPIU phys@0x%llx\n", tag,
499 (u64)lrbp->ucd_req_dma_addr);
500 ufshcd_hex_dump("UPIU REQ: ", lrbp->ucd_req_ptr,
501 sizeof(struct utp_upiu_req));
502 dev_err(hba->dev, "UPIU[%d] - Response UPIU phys@0x%llx\n", tag,
503 (u64)lrbp->ucd_rsp_dma_addr);
504 ufshcd_hex_dump("UPIU RSP: ", lrbp->ucd_rsp_ptr,
505 sizeof(struct utp_upiu_rsp));
507 prdt_length = le16_to_cpu(
508 lrbp->utr_descriptor_ptr->prd_table_length);
509 if (hba->quirks & UFSHCD_QUIRK_PRDT_BYTE_GRAN)
510 prdt_length /= sizeof(struct ufshcd_sg_entry);
513 "UPIU[%d] - PRDT - %d entries phys@0x%llx\n",
515 (u64)lrbp->ucd_prdt_dma_addr);
518 ufshcd_hex_dump("UPIU PRDT: ", lrbp->ucd_prdt_ptr,
519 sizeof(struct ufshcd_sg_entry) * prdt_length);
523 static void ufshcd_print_tmrs(struct ufs_hba *hba, unsigned long bitmap)
527 for_each_set_bit(tag, &bitmap, hba->nutmrs) {
528 struct utp_task_req_desc *tmrdp = &hba->utmrdl_base_addr[tag];
530 dev_err(hba->dev, "TM[%d] - Task Management Header\n", tag);
531 ufshcd_hex_dump("", tmrdp, sizeof(*tmrdp));
535 static void ufshcd_print_host_state(struct ufs_hba *hba)
537 struct scsi_device *sdev_ufs = hba->sdev_ufs_device;
539 dev_err(hba->dev, "UFS Host state=%d\n", hba->ufshcd_state);
540 dev_err(hba->dev, "outstanding reqs=0x%lx tasks=0x%lx\n",
541 hba->outstanding_reqs, hba->outstanding_tasks);
542 dev_err(hba->dev, "saved_err=0x%x, saved_uic_err=0x%x\n",
543 hba->saved_err, hba->saved_uic_err);
544 dev_err(hba->dev, "Device power mode=%d, UIC link state=%d\n",
545 hba->curr_dev_pwr_mode, hba->uic_link_state);
546 dev_err(hba->dev, "PM in progress=%d, sys. suspended=%d\n",
547 hba->pm_op_in_progress, hba->is_sys_suspended);
548 dev_err(hba->dev, "Auto BKOPS=%d, Host self-block=%d\n",
549 hba->auto_bkops_enabled, hba->host->host_self_blocked);
550 dev_err(hba->dev, "Clk gate=%d\n", hba->clk_gating.state);
552 "last_hibern8_exit_tstamp at %lld us, hibern8_exit_cnt=%d\n",
553 ktime_to_us(hba->ufs_stats.last_hibern8_exit_tstamp),
554 hba->ufs_stats.hibern8_exit_cnt);
555 dev_err(hba->dev, "last intr at %lld us, last intr status=0x%x\n",
556 ktime_to_us(hba->ufs_stats.last_intr_ts),
557 hba->ufs_stats.last_intr_status);
558 dev_err(hba->dev, "error handling flags=0x%x, req. abort count=%d\n",
559 hba->eh_flags, hba->req_abort_count);
560 dev_err(hba->dev, "hba->ufs_version=0x%x, Host capabilities=0x%x, caps=0x%x\n",
561 hba->ufs_version, hba->capabilities, hba->caps);
562 dev_err(hba->dev, "quirks=0x%x, dev. quirks=0x%x\n", hba->quirks,
565 dev_err(hba->dev, "UFS dev info: %.8s %.16s rev %.4s\n",
566 sdev_ufs->vendor, sdev_ufs->model, sdev_ufs->rev);
568 ufshcd_print_clk_freqs(hba);
572 * ufshcd_print_pwr_info - print power params as saved in hba
574 * @hba: per-adapter instance
576 static void ufshcd_print_pwr_info(struct ufs_hba *hba)
578 static const char * const names[] = {
588 dev_err(hba->dev, "%s:[RX, TX]: gear=[%d, %d], lane[%d, %d], pwr[%s, %s], rate = %d\n",
590 hba->pwr_info.gear_rx, hba->pwr_info.gear_tx,
591 hba->pwr_info.lane_rx, hba->pwr_info.lane_tx,
592 names[hba->pwr_info.pwr_rx],
593 names[hba->pwr_info.pwr_tx],
594 hba->pwr_info.hs_rate);
597 static void ufshcd_device_reset(struct ufs_hba *hba)
601 err = ufshcd_vops_device_reset(hba);
604 ufshcd_set_ufs_dev_active(hba);
605 if (ufshcd_is_wb_allowed(hba)) {
606 hba->dev_info.wb_enabled = false;
607 hba->dev_info.wb_buf_flush_enabled = false;
610 if (err != -EOPNOTSUPP)
611 ufshcd_update_evt_hist(hba, UFS_EVT_DEV_RESET, err);
614 void ufshcd_delay_us(unsigned long us, unsigned long tolerance)
622 usleep_range(us, us + tolerance);
624 EXPORT_SYMBOL_GPL(ufshcd_delay_us);
627 * ufshcd_wait_for_register - wait for register value to change
628 * @hba: per-adapter interface
629 * @reg: mmio register offset
630 * @mask: mask to apply to the read register value
631 * @val: value to wait for
632 * @interval_us: polling interval in microseconds
633 * @timeout_ms: timeout in milliseconds
636 * -ETIMEDOUT on error, zero on success.
638 int ufshcd_wait_for_register(struct ufs_hba *hba, u32 reg, u32 mask,
639 u32 val, unsigned long interval_us,
640 unsigned long timeout_ms)
643 unsigned long timeout = jiffies + msecs_to_jiffies(timeout_ms);
645 /* ignore bits that we don't intend to wait on */
648 while ((ufshcd_readl(hba, reg) & mask) != val) {
649 usleep_range(interval_us, interval_us + 50);
650 if (time_after(jiffies, timeout)) {
651 if ((ufshcd_readl(hba, reg) & mask) != val)
661 * ufshcd_get_intr_mask - Get the interrupt bit mask
662 * @hba: Pointer to adapter instance
664 * Returns interrupt bit mask per version
666 static inline u32 ufshcd_get_intr_mask(struct ufs_hba *hba)
668 if (hba->ufs_version == ufshci_version(1, 0))
669 return INTERRUPT_MASK_ALL_VER_10;
670 if (hba->ufs_version <= ufshci_version(2, 0))
671 return INTERRUPT_MASK_ALL_VER_11;
673 return INTERRUPT_MASK_ALL_VER_21;
677 * ufshcd_get_ufs_version - Get the UFS version supported by the HBA
678 * @hba: Pointer to adapter instance
680 * Returns UFSHCI version supported by the controller
682 static inline u32 ufshcd_get_ufs_version(struct ufs_hba *hba)
686 if (hba->quirks & UFSHCD_QUIRK_BROKEN_UFS_HCI_VERSION)
687 ufshci_ver = ufshcd_vops_get_ufs_hci_version(hba);
689 ufshci_ver = ufshcd_readl(hba, REG_UFS_VERSION);
692 * UFSHCI v1.x uses a different version scheme, in order
693 * to allow the use of comparisons with the ufshci_version
694 * function, we convert it to the same scheme as ufs 2.0+.
696 if (ufshci_ver & 0x00010000)
697 return ufshci_version(1, ufshci_ver & 0x00000100);
703 * ufshcd_is_device_present - Check if any device connected to
704 * the host controller
705 * @hba: pointer to adapter instance
707 * Returns true if device present, false if no device detected
709 static inline bool ufshcd_is_device_present(struct ufs_hba *hba)
711 return (ufshcd_readl(hba, REG_CONTROLLER_STATUS) &
712 DEVICE_PRESENT) ? true : false;
716 * ufshcd_get_tr_ocs - Get the UTRD Overall Command Status
717 * @lrbp: pointer to local command reference block
719 * This function is used to get the OCS field from UTRD
720 * Returns the OCS field in the UTRD
722 static enum utp_ocs ufshcd_get_tr_ocs(struct ufshcd_lrb *lrbp)
724 return le32_to_cpu(lrbp->utr_descriptor_ptr->header.dword_2) & MASK_OCS;
728 * ufshcd_utrl_clear - Clear a bit in UTRLCLR register
729 * @hba: per adapter instance
730 * @pos: position of the bit to be cleared
732 static inline void ufshcd_utrl_clear(struct ufs_hba *hba, u32 pos)
734 if (hba->quirks & UFSHCI_QUIRK_BROKEN_REQ_LIST_CLR)
735 ufshcd_writel(hba, (1 << pos), REG_UTP_TRANSFER_REQ_LIST_CLEAR);
737 ufshcd_writel(hba, ~(1 << pos),
738 REG_UTP_TRANSFER_REQ_LIST_CLEAR);
742 * ufshcd_utmrl_clear - Clear a bit in UTRMLCLR register
743 * @hba: per adapter instance
744 * @pos: position of the bit to be cleared
746 static inline void ufshcd_utmrl_clear(struct ufs_hba *hba, u32 pos)
748 if (hba->quirks & UFSHCI_QUIRK_BROKEN_REQ_LIST_CLR)
749 ufshcd_writel(hba, (1 << pos), REG_UTP_TASK_REQ_LIST_CLEAR);
751 ufshcd_writel(hba, ~(1 << pos), REG_UTP_TASK_REQ_LIST_CLEAR);
755 * ufshcd_get_lists_status - Check UCRDY, UTRLRDY and UTMRLRDY
756 * @reg: Register value of host controller status
758 * Returns integer, 0 on Success and positive value if failed
760 static inline int ufshcd_get_lists_status(u32 reg)
762 return !((reg & UFSHCD_STATUS_READY) == UFSHCD_STATUS_READY);
766 * ufshcd_get_uic_cmd_result - Get the UIC command result
767 * @hba: Pointer to adapter instance
769 * This function gets the result of UIC command completion
770 * Returns 0 on success, non zero value on error
772 static inline int ufshcd_get_uic_cmd_result(struct ufs_hba *hba)
774 return ufshcd_readl(hba, REG_UIC_COMMAND_ARG_2) &
775 MASK_UIC_COMMAND_RESULT;
779 * ufshcd_get_dme_attr_val - Get the value of attribute returned by UIC command
780 * @hba: Pointer to adapter instance
782 * This function gets UIC command argument3
783 * Returns 0 on success, non zero value on error
785 static inline u32 ufshcd_get_dme_attr_val(struct ufs_hba *hba)
787 return ufshcd_readl(hba, REG_UIC_COMMAND_ARG_3);
791 * ufshcd_get_req_rsp - returns the TR response transaction type
792 * @ucd_rsp_ptr: pointer to response UPIU
795 ufshcd_get_req_rsp(struct utp_upiu_rsp *ucd_rsp_ptr)
797 return be32_to_cpu(ucd_rsp_ptr->header.dword_0) >> 24;
801 * ufshcd_get_rsp_upiu_result - Get the result from response UPIU
802 * @ucd_rsp_ptr: pointer to response UPIU
804 * This function gets the response status and scsi_status from response UPIU
805 * Returns the response result code.
808 ufshcd_get_rsp_upiu_result(struct utp_upiu_rsp *ucd_rsp_ptr)
810 return be32_to_cpu(ucd_rsp_ptr->header.dword_1) & MASK_RSP_UPIU_RESULT;
814 * ufshcd_get_rsp_upiu_data_seg_len - Get the data segment length
816 * @ucd_rsp_ptr: pointer to response UPIU
818 * Return the data segment length.
820 static inline unsigned int
821 ufshcd_get_rsp_upiu_data_seg_len(struct utp_upiu_rsp *ucd_rsp_ptr)
823 return be32_to_cpu(ucd_rsp_ptr->header.dword_2) &
824 MASK_RSP_UPIU_DATA_SEG_LEN;
828 * ufshcd_is_exception_event - Check if the device raised an exception event
829 * @ucd_rsp_ptr: pointer to response UPIU
831 * The function checks if the device raised an exception event indicated in
832 * the Device Information field of response UPIU.
834 * Returns true if exception is raised, false otherwise.
836 static inline bool ufshcd_is_exception_event(struct utp_upiu_rsp *ucd_rsp_ptr)
838 return be32_to_cpu(ucd_rsp_ptr->header.dword_2) &
839 MASK_RSP_EXCEPTION_EVENT ? true : false;
843 * ufshcd_reset_intr_aggr - Reset interrupt aggregation values.
844 * @hba: per adapter instance
847 ufshcd_reset_intr_aggr(struct ufs_hba *hba)
849 ufshcd_writel(hba, INT_AGGR_ENABLE |
850 INT_AGGR_COUNTER_AND_TIMER_RESET,
851 REG_UTP_TRANSFER_REQ_INT_AGG_CONTROL);
855 * ufshcd_config_intr_aggr - Configure interrupt aggregation values.
856 * @hba: per adapter instance
857 * @cnt: Interrupt aggregation counter threshold
858 * @tmout: Interrupt aggregation timeout value
861 ufshcd_config_intr_aggr(struct ufs_hba *hba, u8 cnt, u8 tmout)
863 ufshcd_writel(hba, INT_AGGR_ENABLE | INT_AGGR_PARAM_WRITE |
864 INT_AGGR_COUNTER_THLD_VAL(cnt) |
865 INT_AGGR_TIMEOUT_VAL(tmout),
866 REG_UTP_TRANSFER_REQ_INT_AGG_CONTROL);
870 * ufshcd_disable_intr_aggr - Disables interrupt aggregation.
871 * @hba: per adapter instance
873 static inline void ufshcd_disable_intr_aggr(struct ufs_hba *hba)
875 ufshcd_writel(hba, 0, REG_UTP_TRANSFER_REQ_INT_AGG_CONTROL);
879 * ufshcd_enable_run_stop_reg - Enable run-stop registers,
880 * When run-stop registers are set to 1, it indicates the
881 * host controller that it can process the requests
882 * @hba: per adapter instance
884 static void ufshcd_enable_run_stop_reg(struct ufs_hba *hba)
886 ufshcd_writel(hba, UTP_TASK_REQ_LIST_RUN_STOP_BIT,
887 REG_UTP_TASK_REQ_LIST_RUN_STOP);
888 ufshcd_writel(hba, UTP_TRANSFER_REQ_LIST_RUN_STOP_BIT,
889 REG_UTP_TRANSFER_REQ_LIST_RUN_STOP);
893 * ufshcd_hba_start - Start controller initialization sequence
894 * @hba: per adapter instance
896 static inline void ufshcd_hba_start(struct ufs_hba *hba)
898 u32 val = CONTROLLER_ENABLE;
900 if (ufshcd_crypto_enable(hba))
901 val |= CRYPTO_GENERAL_ENABLE;
903 ufshcd_writel(hba, val, REG_CONTROLLER_ENABLE);
907 * ufshcd_is_hba_active - Get controller state
908 * @hba: per adapter instance
910 * Returns false if controller is active, true otherwise
912 static inline bool ufshcd_is_hba_active(struct ufs_hba *hba)
914 return (ufshcd_readl(hba, REG_CONTROLLER_ENABLE) & CONTROLLER_ENABLE)
918 u32 ufshcd_get_local_unipro_ver(struct ufs_hba *hba)
920 /* HCI version 1.0 and 1.1 supports UniPro 1.41 */
921 if (hba->ufs_version <= ufshci_version(1, 1))
922 return UFS_UNIPRO_VER_1_41;
924 return UFS_UNIPRO_VER_1_6;
926 EXPORT_SYMBOL(ufshcd_get_local_unipro_ver);
928 static bool ufshcd_is_unipro_pa_params_tuning_req(struct ufs_hba *hba)
931 * If both host and device support UniPro ver1.6 or later, PA layer
932 * parameters tuning happens during link startup itself.
934 * We can manually tune PA layer parameters if either host or device
935 * doesn't support UniPro ver 1.6 or later. But to keep manual tuning
936 * logic simple, we will only do manual tuning if local unipro version
937 * doesn't support ver1.6 or later.
939 if (ufshcd_get_local_unipro_ver(hba) < UFS_UNIPRO_VER_1_6)
946 * ufshcd_set_clk_freq - set UFS controller clock frequencies
947 * @hba: per adapter instance
948 * @scale_up: If True, set max possible frequency othewise set low frequency
950 * Returns 0 if successful
951 * Returns < 0 for any other errors
953 static int ufshcd_set_clk_freq(struct ufs_hba *hba, bool scale_up)
956 struct ufs_clk_info *clki;
957 struct list_head *head = &hba->clk_list_head;
959 if (list_empty(head))
962 list_for_each_entry(clki, head, list) {
963 if (!IS_ERR_OR_NULL(clki->clk)) {
964 if (scale_up && clki->max_freq) {
965 if (clki->curr_freq == clki->max_freq)
968 ret = clk_set_rate(clki->clk, clki->max_freq);
970 dev_err(hba->dev, "%s: %s clk set rate(%dHz) failed, %d\n",
971 __func__, clki->name,
972 clki->max_freq, ret);
975 trace_ufshcd_clk_scaling(dev_name(hba->dev),
976 "scaled up", clki->name,
980 clki->curr_freq = clki->max_freq;
982 } else if (!scale_up && clki->min_freq) {
983 if (clki->curr_freq == clki->min_freq)
986 ret = clk_set_rate(clki->clk, clki->min_freq);
988 dev_err(hba->dev, "%s: %s clk set rate(%dHz) failed, %d\n",
989 __func__, clki->name,
990 clki->min_freq, ret);
993 trace_ufshcd_clk_scaling(dev_name(hba->dev),
994 "scaled down", clki->name,
997 clki->curr_freq = clki->min_freq;
1000 dev_dbg(hba->dev, "%s: clk: %s, rate: %lu\n", __func__,
1001 clki->name, clk_get_rate(clki->clk));
1009 * ufshcd_scale_clks - scale up or scale down UFS controller clocks
1010 * @hba: per adapter instance
1011 * @scale_up: True if scaling up and false if scaling down
1013 * Returns 0 if successful
1014 * Returns < 0 for any other errors
1016 static int ufshcd_scale_clks(struct ufs_hba *hba, bool scale_up)
1019 ktime_t start = ktime_get();
1021 ret = ufshcd_vops_clk_scale_notify(hba, scale_up, PRE_CHANGE);
1025 ret = ufshcd_set_clk_freq(hba, scale_up);
1029 ret = ufshcd_vops_clk_scale_notify(hba, scale_up, POST_CHANGE);
1031 ufshcd_set_clk_freq(hba, !scale_up);
1034 trace_ufshcd_profile_clk_scaling(dev_name(hba->dev),
1035 (scale_up ? "up" : "down"),
1036 ktime_to_us(ktime_sub(ktime_get(), start)), ret);
1041 * ufshcd_is_devfreq_scaling_required - check if scaling is required or not
1042 * @hba: per adapter instance
1043 * @scale_up: True if scaling up and false if scaling down
1045 * Returns true if scaling is required, false otherwise.
1047 static bool ufshcd_is_devfreq_scaling_required(struct ufs_hba *hba,
1050 struct ufs_clk_info *clki;
1051 struct list_head *head = &hba->clk_list_head;
1053 if (list_empty(head))
1056 list_for_each_entry(clki, head, list) {
1057 if (!IS_ERR_OR_NULL(clki->clk)) {
1058 if (scale_up && clki->max_freq) {
1059 if (clki->curr_freq == clki->max_freq)
1062 } else if (!scale_up && clki->min_freq) {
1063 if (clki->curr_freq == clki->min_freq)
1074 * Determine the number of pending commands by counting the bits in the SCSI
1075 * device budget maps. This approach has been selected because a bit is set in
1076 * the budget map before scsi_host_queue_ready() checks the host_self_blocked
1077 * flag. The host_self_blocked flag can be modified by calling
1078 * scsi_block_requests() or scsi_unblock_requests().
1080 static u32 ufshcd_pending_cmds(struct ufs_hba *hba)
1082 struct scsi_device *sdev;
1085 lockdep_assert_held(hba->host->host_lock);
1086 __shost_for_each_device(sdev, hba->host)
1087 pending += sbitmap_weight(&sdev->budget_map);
1092 static int ufshcd_wait_for_doorbell_clr(struct ufs_hba *hba,
1093 u64 wait_timeout_us)
1095 unsigned long flags;
1099 bool timeout = false, do_last_check = false;
1102 ufshcd_hold(hba, false);
1103 spin_lock_irqsave(hba->host->host_lock, flags);
1105 * Wait for all the outstanding tasks/transfer requests.
1106 * Verify by checking the doorbell registers are clear.
1108 start = ktime_get();
1110 if (hba->ufshcd_state != UFSHCD_STATE_OPERATIONAL) {
1115 tm_doorbell = ufshcd_readl(hba, REG_UTP_TASK_REQ_DOOR_BELL);
1116 tr_pending = ufshcd_pending_cmds(hba);
1117 if (!tm_doorbell && !tr_pending) {
1120 } else if (do_last_check) {
1124 spin_unlock_irqrestore(hba->host->host_lock, flags);
1126 if (ktime_to_us(ktime_sub(ktime_get(), start)) >
1130 * We might have scheduled out for long time so make
1131 * sure to check if doorbells are cleared by this time
1134 do_last_check = true;
1136 spin_lock_irqsave(hba->host->host_lock, flags);
1137 } while (tm_doorbell || tr_pending);
1141 "%s: timedout waiting for doorbell to clear (tm=0x%x, tr=0x%x)\n",
1142 __func__, tm_doorbell, tr_pending);
1146 spin_unlock_irqrestore(hba->host->host_lock, flags);
1147 ufshcd_release(hba);
1152 * ufshcd_scale_gear - scale up/down UFS gear
1153 * @hba: per adapter instance
1154 * @scale_up: True for scaling up gear and false for scaling down
1156 * Returns 0 for success,
1157 * Returns -EBUSY if scaling can't happen at this time
1158 * Returns non-zero for any other errors
1160 static int ufshcd_scale_gear(struct ufs_hba *hba, bool scale_up)
1163 struct ufs_pa_layer_attr new_pwr_info;
1166 memcpy(&new_pwr_info, &hba->clk_scaling.saved_pwr_info.info,
1167 sizeof(struct ufs_pa_layer_attr));
1169 memcpy(&new_pwr_info, &hba->pwr_info,
1170 sizeof(struct ufs_pa_layer_attr));
1172 if (hba->pwr_info.gear_tx > hba->clk_scaling.min_gear ||
1173 hba->pwr_info.gear_rx > hba->clk_scaling.min_gear) {
1174 /* save the current power mode */
1175 memcpy(&hba->clk_scaling.saved_pwr_info.info,
1177 sizeof(struct ufs_pa_layer_attr));
1179 /* scale down gear */
1180 new_pwr_info.gear_tx = hba->clk_scaling.min_gear;
1181 new_pwr_info.gear_rx = hba->clk_scaling.min_gear;
1185 /* check if the power mode needs to be changed or not? */
1186 ret = ufshcd_config_pwr_mode(hba, &new_pwr_info);
1188 dev_err(hba->dev, "%s: failed err %d, old gear: (tx %d rx %d), new gear: (tx %d rx %d)",
1190 hba->pwr_info.gear_tx, hba->pwr_info.gear_rx,
1191 new_pwr_info.gear_tx, new_pwr_info.gear_rx);
1196 static int ufshcd_clock_scaling_prepare(struct ufs_hba *hba)
1198 #define DOORBELL_CLR_TOUT_US (1000 * 1000) /* 1 sec */
1201 * make sure that there are no outstanding requests when
1202 * clock scaling is in progress
1204 ufshcd_scsi_block_requests(hba);
1205 down_write(&hba->clk_scaling_lock);
1207 if (!hba->clk_scaling.is_allowed ||
1208 ufshcd_wait_for_doorbell_clr(hba, DOORBELL_CLR_TOUT_US)) {
1210 up_write(&hba->clk_scaling_lock);
1211 ufshcd_scsi_unblock_requests(hba);
1215 /* let's not get into low power until clock scaling is completed */
1216 ufshcd_hold(hba, false);
1222 static void ufshcd_clock_scaling_unprepare(struct ufs_hba *hba, bool writelock)
1225 up_write(&hba->clk_scaling_lock);
1227 up_read(&hba->clk_scaling_lock);
1228 ufshcd_scsi_unblock_requests(hba);
1229 ufshcd_release(hba);
1233 * ufshcd_devfreq_scale - scale up/down UFS clocks and gear
1234 * @hba: per adapter instance
1235 * @scale_up: True for scaling up and false for scalin down
1237 * Returns 0 for success,
1238 * Returns -EBUSY if scaling can't happen at this time
1239 * Returns non-zero for any other errors
1241 static int ufshcd_devfreq_scale(struct ufs_hba *hba, bool scale_up)
1244 bool is_writelock = true;
1246 ret = ufshcd_clock_scaling_prepare(hba);
1250 /* scale down the gear before scaling down clocks */
1252 ret = ufshcd_scale_gear(hba, false);
1257 ret = ufshcd_scale_clks(hba, scale_up);
1260 ufshcd_scale_gear(hba, true);
1264 /* scale up the gear after scaling up clocks */
1266 ret = ufshcd_scale_gear(hba, true);
1268 ufshcd_scale_clks(hba, false);
1273 /* Enable Write Booster if we have scaled up else disable it */
1274 downgrade_write(&hba->clk_scaling_lock);
1275 is_writelock = false;
1276 ufshcd_wb_toggle(hba, scale_up);
1279 ufshcd_clock_scaling_unprepare(hba, is_writelock);
1283 static void ufshcd_clk_scaling_suspend_work(struct work_struct *work)
1285 struct ufs_hba *hba = container_of(work, struct ufs_hba,
1286 clk_scaling.suspend_work);
1287 unsigned long irq_flags;
1289 spin_lock_irqsave(hba->host->host_lock, irq_flags);
1290 if (hba->clk_scaling.active_reqs || hba->clk_scaling.is_suspended) {
1291 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1294 hba->clk_scaling.is_suspended = true;
1295 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1297 __ufshcd_suspend_clkscaling(hba);
1300 static void ufshcd_clk_scaling_resume_work(struct work_struct *work)
1302 struct ufs_hba *hba = container_of(work, struct ufs_hba,
1303 clk_scaling.resume_work);
1304 unsigned long irq_flags;
1306 spin_lock_irqsave(hba->host->host_lock, irq_flags);
1307 if (!hba->clk_scaling.is_suspended) {
1308 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1311 hba->clk_scaling.is_suspended = false;
1312 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1314 devfreq_resume_device(hba->devfreq);
1317 static int ufshcd_devfreq_target(struct device *dev,
1318 unsigned long *freq, u32 flags)
1321 struct ufs_hba *hba = dev_get_drvdata(dev);
1323 bool scale_up, sched_clk_scaling_suspend_work = false;
1324 struct list_head *clk_list = &hba->clk_list_head;
1325 struct ufs_clk_info *clki;
1326 unsigned long irq_flags;
1328 if (!ufshcd_is_clkscaling_supported(hba))
1331 clki = list_first_entry(&hba->clk_list_head, struct ufs_clk_info, list);
1332 /* Override with the closest supported frequency */
1333 *freq = (unsigned long) clk_round_rate(clki->clk, *freq);
1334 spin_lock_irqsave(hba->host->host_lock, irq_flags);
1335 if (ufshcd_eh_in_progress(hba)) {
1336 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1340 if (!hba->clk_scaling.active_reqs)
1341 sched_clk_scaling_suspend_work = true;
1343 if (list_empty(clk_list)) {
1344 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1348 /* Decide based on the rounded-off frequency and update */
1349 scale_up = (*freq == clki->max_freq) ? true : false;
1351 *freq = clki->min_freq;
1352 /* Update the frequency */
1353 if (!ufshcd_is_devfreq_scaling_required(hba, scale_up)) {
1354 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1356 goto out; /* no state change required */
1358 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1360 start = ktime_get();
1361 ret = ufshcd_devfreq_scale(hba, scale_up);
1363 trace_ufshcd_profile_clk_scaling(dev_name(hba->dev),
1364 (scale_up ? "up" : "down"),
1365 ktime_to_us(ktime_sub(ktime_get(), start)), ret);
1368 if (sched_clk_scaling_suspend_work)
1369 queue_work(hba->clk_scaling.workq,
1370 &hba->clk_scaling.suspend_work);
1375 static int ufshcd_devfreq_get_dev_status(struct device *dev,
1376 struct devfreq_dev_status *stat)
1378 struct ufs_hba *hba = dev_get_drvdata(dev);
1379 struct ufs_clk_scaling *scaling = &hba->clk_scaling;
1380 unsigned long flags;
1381 struct list_head *clk_list = &hba->clk_list_head;
1382 struct ufs_clk_info *clki;
1385 if (!ufshcd_is_clkscaling_supported(hba))
1388 memset(stat, 0, sizeof(*stat));
1390 spin_lock_irqsave(hba->host->host_lock, flags);
1391 curr_t = ktime_get();
1392 if (!scaling->window_start_t)
1395 clki = list_first_entry(clk_list, struct ufs_clk_info, list);
1397 * If current frequency is 0, then the ondemand governor considers
1398 * there's no initial frequency set. And it always requests to set
1399 * to max. frequency.
1401 stat->current_frequency = clki->curr_freq;
1402 if (scaling->is_busy_started)
1403 scaling->tot_busy_t += ktime_us_delta(curr_t,
1404 scaling->busy_start_t);
1406 stat->total_time = ktime_us_delta(curr_t, scaling->window_start_t);
1407 stat->busy_time = scaling->tot_busy_t;
1409 scaling->window_start_t = curr_t;
1410 scaling->tot_busy_t = 0;
1412 if (hba->outstanding_reqs) {
1413 scaling->busy_start_t = curr_t;
1414 scaling->is_busy_started = true;
1416 scaling->busy_start_t = 0;
1417 scaling->is_busy_started = false;
1419 spin_unlock_irqrestore(hba->host->host_lock, flags);
1423 static int ufshcd_devfreq_init(struct ufs_hba *hba)
1425 struct list_head *clk_list = &hba->clk_list_head;
1426 struct ufs_clk_info *clki;
1427 struct devfreq *devfreq;
1430 /* Skip devfreq if we don't have any clocks in the list */
1431 if (list_empty(clk_list))
1434 clki = list_first_entry(clk_list, struct ufs_clk_info, list);
1435 dev_pm_opp_add(hba->dev, clki->min_freq, 0);
1436 dev_pm_opp_add(hba->dev, clki->max_freq, 0);
1438 ufshcd_vops_config_scaling_param(hba, &hba->vps->devfreq_profile,
1439 &hba->vps->ondemand_data);
1440 devfreq = devfreq_add_device(hba->dev,
1441 &hba->vps->devfreq_profile,
1442 DEVFREQ_GOV_SIMPLE_ONDEMAND,
1443 &hba->vps->ondemand_data);
1444 if (IS_ERR(devfreq)) {
1445 ret = PTR_ERR(devfreq);
1446 dev_err(hba->dev, "Unable to register with devfreq %d\n", ret);
1448 dev_pm_opp_remove(hba->dev, clki->min_freq);
1449 dev_pm_opp_remove(hba->dev, clki->max_freq);
1453 hba->devfreq = devfreq;
1458 static void ufshcd_devfreq_remove(struct ufs_hba *hba)
1460 struct list_head *clk_list = &hba->clk_list_head;
1461 struct ufs_clk_info *clki;
1466 devfreq_remove_device(hba->devfreq);
1467 hba->devfreq = NULL;
1469 clki = list_first_entry(clk_list, struct ufs_clk_info, list);
1470 dev_pm_opp_remove(hba->dev, clki->min_freq);
1471 dev_pm_opp_remove(hba->dev, clki->max_freq);
1474 static void __ufshcd_suspend_clkscaling(struct ufs_hba *hba)
1476 unsigned long flags;
1478 devfreq_suspend_device(hba->devfreq);
1479 spin_lock_irqsave(hba->host->host_lock, flags);
1480 hba->clk_scaling.window_start_t = 0;
1481 spin_unlock_irqrestore(hba->host->host_lock, flags);
1484 static void ufshcd_suspend_clkscaling(struct ufs_hba *hba)
1486 unsigned long flags;
1487 bool suspend = false;
1489 cancel_work_sync(&hba->clk_scaling.suspend_work);
1490 cancel_work_sync(&hba->clk_scaling.resume_work);
1492 spin_lock_irqsave(hba->host->host_lock, flags);
1493 if (!hba->clk_scaling.is_suspended) {
1495 hba->clk_scaling.is_suspended = true;
1497 spin_unlock_irqrestore(hba->host->host_lock, flags);
1500 __ufshcd_suspend_clkscaling(hba);
1503 static void ufshcd_resume_clkscaling(struct ufs_hba *hba)
1505 unsigned long flags;
1506 bool resume = false;
1508 spin_lock_irqsave(hba->host->host_lock, flags);
1509 if (hba->clk_scaling.is_suspended) {
1511 hba->clk_scaling.is_suspended = false;
1513 spin_unlock_irqrestore(hba->host->host_lock, flags);
1516 devfreq_resume_device(hba->devfreq);
1519 static ssize_t ufshcd_clkscale_enable_show(struct device *dev,
1520 struct device_attribute *attr, char *buf)
1522 struct ufs_hba *hba = dev_get_drvdata(dev);
1524 return sysfs_emit(buf, "%d\n", hba->clk_scaling.is_enabled);
1527 static ssize_t ufshcd_clkscale_enable_store(struct device *dev,
1528 struct device_attribute *attr, const char *buf, size_t count)
1530 struct ufs_hba *hba = dev_get_drvdata(dev);
1534 if (kstrtou32(buf, 0, &value))
1537 down(&hba->host_sem);
1538 if (!ufshcd_is_user_access_allowed(hba)) {
1544 if (value == hba->clk_scaling.is_enabled)
1547 ufshcd_rpm_get_sync(hba);
1548 ufshcd_hold(hba, false);
1550 hba->clk_scaling.is_enabled = value;
1553 ufshcd_resume_clkscaling(hba);
1555 ufshcd_suspend_clkscaling(hba);
1556 err = ufshcd_devfreq_scale(hba, true);
1558 dev_err(hba->dev, "%s: failed to scale clocks up %d\n",
1562 ufshcd_release(hba);
1563 ufshcd_rpm_put_sync(hba);
1566 return err ? err : count;
1569 static void ufshcd_init_clk_scaling_sysfs(struct ufs_hba *hba)
1571 hba->clk_scaling.enable_attr.show = ufshcd_clkscale_enable_show;
1572 hba->clk_scaling.enable_attr.store = ufshcd_clkscale_enable_store;
1573 sysfs_attr_init(&hba->clk_scaling.enable_attr.attr);
1574 hba->clk_scaling.enable_attr.attr.name = "clkscale_enable";
1575 hba->clk_scaling.enable_attr.attr.mode = 0644;
1576 if (device_create_file(hba->dev, &hba->clk_scaling.enable_attr))
1577 dev_err(hba->dev, "Failed to create sysfs for clkscale_enable\n");
1580 static void ufshcd_remove_clk_scaling_sysfs(struct ufs_hba *hba)
1582 if (hba->clk_scaling.enable_attr.attr.name)
1583 device_remove_file(hba->dev, &hba->clk_scaling.enable_attr);
1586 static void ufshcd_init_clk_scaling(struct ufs_hba *hba)
1588 char wq_name[sizeof("ufs_clkscaling_00")];
1590 if (!ufshcd_is_clkscaling_supported(hba))
1593 if (!hba->clk_scaling.min_gear)
1594 hba->clk_scaling.min_gear = UFS_HS_G1;
1596 INIT_WORK(&hba->clk_scaling.suspend_work,
1597 ufshcd_clk_scaling_suspend_work);
1598 INIT_WORK(&hba->clk_scaling.resume_work,
1599 ufshcd_clk_scaling_resume_work);
1601 snprintf(wq_name, sizeof(wq_name), "ufs_clkscaling_%d",
1602 hba->host->host_no);
1603 hba->clk_scaling.workq = create_singlethread_workqueue(wq_name);
1605 hba->clk_scaling.is_initialized = true;
1608 static void ufshcd_exit_clk_scaling(struct ufs_hba *hba)
1610 if (!hba->clk_scaling.is_initialized)
1613 ufshcd_remove_clk_scaling_sysfs(hba);
1614 destroy_workqueue(hba->clk_scaling.workq);
1615 ufshcd_devfreq_remove(hba);
1616 hba->clk_scaling.is_initialized = false;
1619 static void ufshcd_ungate_work(struct work_struct *work)
1622 unsigned long flags;
1623 struct ufs_hba *hba = container_of(work, struct ufs_hba,
1624 clk_gating.ungate_work);
1626 cancel_delayed_work_sync(&hba->clk_gating.gate_work);
1628 spin_lock_irqsave(hba->host->host_lock, flags);
1629 if (hba->clk_gating.state == CLKS_ON) {
1630 spin_unlock_irqrestore(hba->host->host_lock, flags);
1634 spin_unlock_irqrestore(hba->host->host_lock, flags);
1635 ufshcd_hba_vreg_set_hpm(hba);
1636 ufshcd_setup_clocks(hba, true);
1638 ufshcd_enable_irq(hba);
1640 /* Exit from hibern8 */
1641 if (ufshcd_can_hibern8_during_gating(hba)) {
1642 /* Prevent gating in this path */
1643 hba->clk_gating.is_suspended = true;
1644 if (ufshcd_is_link_hibern8(hba)) {
1645 ret = ufshcd_uic_hibern8_exit(hba);
1647 dev_err(hba->dev, "%s: hibern8 exit failed %d\n",
1650 ufshcd_set_link_active(hba);
1652 hba->clk_gating.is_suspended = false;
1655 ufshcd_scsi_unblock_requests(hba);
1659 * ufshcd_hold - Enable clocks that were gated earlier due to ufshcd_release.
1660 * Also, exit from hibern8 mode and set the link as active.
1661 * @hba: per adapter instance
1662 * @async: This indicates whether caller should ungate clocks asynchronously.
1664 int ufshcd_hold(struct ufs_hba *hba, bool async)
1668 unsigned long flags;
1670 if (!ufshcd_is_clkgating_allowed(hba) ||
1671 !hba->clk_gating.is_initialized)
1673 spin_lock_irqsave(hba->host->host_lock, flags);
1674 hba->clk_gating.active_reqs++;
1677 switch (hba->clk_gating.state) {
1680 * Wait for the ungate work to complete if in progress.
1681 * Though the clocks may be in ON state, the link could
1682 * still be in hibner8 state if hibern8 is allowed
1683 * during clock gating.
1684 * Make sure we exit hibern8 state also in addition to
1687 if (ufshcd_can_hibern8_during_gating(hba) &&
1688 ufshcd_is_link_hibern8(hba)) {
1691 hba->clk_gating.active_reqs--;
1694 spin_unlock_irqrestore(hba->host->host_lock, flags);
1695 flush_result = flush_work(&hba->clk_gating.ungate_work);
1696 if (hba->clk_gating.is_suspended && !flush_result)
1698 spin_lock_irqsave(hba->host->host_lock, flags);
1703 if (cancel_delayed_work(&hba->clk_gating.gate_work)) {
1704 hba->clk_gating.state = CLKS_ON;
1705 trace_ufshcd_clk_gating(dev_name(hba->dev),
1706 hba->clk_gating.state);
1710 * If we are here, it means gating work is either done or
1711 * currently running. Hence, fall through to cancel gating
1712 * work and to enable clocks.
1716 hba->clk_gating.state = REQ_CLKS_ON;
1717 trace_ufshcd_clk_gating(dev_name(hba->dev),
1718 hba->clk_gating.state);
1719 if (queue_work(hba->clk_gating.clk_gating_workq,
1720 &hba->clk_gating.ungate_work))
1721 ufshcd_scsi_block_requests(hba);
1723 * fall through to check if we should wait for this
1724 * work to be done or not.
1730 hba->clk_gating.active_reqs--;
1734 spin_unlock_irqrestore(hba->host->host_lock, flags);
1735 flush_work(&hba->clk_gating.ungate_work);
1736 /* Make sure state is CLKS_ON before returning */
1737 spin_lock_irqsave(hba->host->host_lock, flags);
1740 dev_err(hba->dev, "%s: clk gating is in invalid state %d\n",
1741 __func__, hba->clk_gating.state);
1744 spin_unlock_irqrestore(hba->host->host_lock, flags);
1748 EXPORT_SYMBOL_GPL(ufshcd_hold);
1750 static void ufshcd_gate_work(struct work_struct *work)
1752 struct ufs_hba *hba = container_of(work, struct ufs_hba,
1753 clk_gating.gate_work.work);
1754 unsigned long flags;
1757 spin_lock_irqsave(hba->host->host_lock, flags);
1759 * In case you are here to cancel this work the gating state
1760 * would be marked as REQ_CLKS_ON. In this case save time by
1761 * skipping the gating work and exit after changing the clock
1764 if (hba->clk_gating.is_suspended ||
1765 (hba->clk_gating.state != REQ_CLKS_OFF)) {
1766 hba->clk_gating.state = CLKS_ON;
1767 trace_ufshcd_clk_gating(dev_name(hba->dev),
1768 hba->clk_gating.state);
1772 if (hba->clk_gating.active_reqs
1773 || hba->ufshcd_state != UFSHCD_STATE_OPERATIONAL
1774 || hba->outstanding_reqs || hba->outstanding_tasks
1775 || hba->active_uic_cmd || hba->uic_async_done)
1778 spin_unlock_irqrestore(hba->host->host_lock, flags);
1780 /* put the link into hibern8 mode before turning off clocks */
1781 if (ufshcd_can_hibern8_during_gating(hba)) {
1782 ret = ufshcd_uic_hibern8_enter(hba);
1784 hba->clk_gating.state = CLKS_ON;
1785 dev_err(hba->dev, "%s: hibern8 enter failed %d\n",
1787 trace_ufshcd_clk_gating(dev_name(hba->dev),
1788 hba->clk_gating.state);
1791 ufshcd_set_link_hibern8(hba);
1794 ufshcd_disable_irq(hba);
1796 ufshcd_setup_clocks(hba, false);
1798 /* Put the host controller in low power mode if possible */
1799 ufshcd_hba_vreg_set_lpm(hba);
1801 * In case you are here to cancel this work the gating state
1802 * would be marked as REQ_CLKS_ON. In this case keep the state
1803 * as REQ_CLKS_ON which would anyway imply that clocks are off
1804 * and a request to turn them on is pending. By doing this way,
1805 * we keep the state machine in tact and this would ultimately
1806 * prevent from doing cancel work multiple times when there are
1807 * new requests arriving before the current cancel work is done.
1809 spin_lock_irqsave(hba->host->host_lock, flags);
1810 if (hba->clk_gating.state == REQ_CLKS_OFF) {
1811 hba->clk_gating.state = CLKS_OFF;
1812 trace_ufshcd_clk_gating(dev_name(hba->dev),
1813 hba->clk_gating.state);
1816 spin_unlock_irqrestore(hba->host->host_lock, flags);
1821 /* host lock must be held before calling this variant */
1822 static void __ufshcd_release(struct ufs_hba *hba)
1824 if (!ufshcd_is_clkgating_allowed(hba))
1827 hba->clk_gating.active_reqs--;
1829 if (hba->clk_gating.active_reqs || hba->clk_gating.is_suspended ||
1830 hba->ufshcd_state != UFSHCD_STATE_OPERATIONAL ||
1831 hba->outstanding_tasks || !hba->clk_gating.is_initialized ||
1832 hba->active_uic_cmd || hba->uic_async_done ||
1833 hba->clk_gating.state == CLKS_OFF)
1836 hba->clk_gating.state = REQ_CLKS_OFF;
1837 trace_ufshcd_clk_gating(dev_name(hba->dev), hba->clk_gating.state);
1838 queue_delayed_work(hba->clk_gating.clk_gating_workq,
1839 &hba->clk_gating.gate_work,
1840 msecs_to_jiffies(hba->clk_gating.delay_ms));
1843 void ufshcd_release(struct ufs_hba *hba)
1845 unsigned long flags;
1847 spin_lock_irqsave(hba->host->host_lock, flags);
1848 __ufshcd_release(hba);
1849 spin_unlock_irqrestore(hba->host->host_lock, flags);
1851 EXPORT_SYMBOL_GPL(ufshcd_release);
1853 static ssize_t ufshcd_clkgate_delay_show(struct device *dev,
1854 struct device_attribute *attr, char *buf)
1856 struct ufs_hba *hba = dev_get_drvdata(dev);
1858 return sysfs_emit(buf, "%lu\n", hba->clk_gating.delay_ms);
1861 static ssize_t ufshcd_clkgate_delay_store(struct device *dev,
1862 struct device_attribute *attr, const char *buf, size_t count)
1864 struct ufs_hba *hba = dev_get_drvdata(dev);
1865 unsigned long flags, value;
1867 if (kstrtoul(buf, 0, &value))
1870 spin_lock_irqsave(hba->host->host_lock, flags);
1871 hba->clk_gating.delay_ms = value;
1872 spin_unlock_irqrestore(hba->host->host_lock, flags);
1876 static ssize_t ufshcd_clkgate_enable_show(struct device *dev,
1877 struct device_attribute *attr, char *buf)
1879 struct ufs_hba *hba = dev_get_drvdata(dev);
1881 return sysfs_emit(buf, "%d\n", hba->clk_gating.is_enabled);
1884 static ssize_t ufshcd_clkgate_enable_store(struct device *dev,
1885 struct device_attribute *attr, const char *buf, size_t count)
1887 struct ufs_hba *hba = dev_get_drvdata(dev);
1888 unsigned long flags;
1891 if (kstrtou32(buf, 0, &value))
1896 spin_lock_irqsave(hba->host->host_lock, flags);
1897 if (value == hba->clk_gating.is_enabled)
1901 __ufshcd_release(hba);
1903 hba->clk_gating.active_reqs++;
1905 hba->clk_gating.is_enabled = value;
1907 spin_unlock_irqrestore(hba->host->host_lock, flags);
1911 static void ufshcd_init_clk_gating_sysfs(struct ufs_hba *hba)
1913 hba->clk_gating.delay_attr.show = ufshcd_clkgate_delay_show;
1914 hba->clk_gating.delay_attr.store = ufshcd_clkgate_delay_store;
1915 sysfs_attr_init(&hba->clk_gating.delay_attr.attr);
1916 hba->clk_gating.delay_attr.attr.name = "clkgate_delay_ms";
1917 hba->clk_gating.delay_attr.attr.mode = 0644;
1918 if (device_create_file(hba->dev, &hba->clk_gating.delay_attr))
1919 dev_err(hba->dev, "Failed to create sysfs for clkgate_delay\n");
1921 hba->clk_gating.enable_attr.show = ufshcd_clkgate_enable_show;
1922 hba->clk_gating.enable_attr.store = ufshcd_clkgate_enable_store;
1923 sysfs_attr_init(&hba->clk_gating.enable_attr.attr);
1924 hba->clk_gating.enable_attr.attr.name = "clkgate_enable";
1925 hba->clk_gating.enable_attr.attr.mode = 0644;
1926 if (device_create_file(hba->dev, &hba->clk_gating.enable_attr))
1927 dev_err(hba->dev, "Failed to create sysfs for clkgate_enable\n");
1930 static void ufshcd_remove_clk_gating_sysfs(struct ufs_hba *hba)
1932 if (hba->clk_gating.delay_attr.attr.name)
1933 device_remove_file(hba->dev, &hba->clk_gating.delay_attr);
1934 if (hba->clk_gating.enable_attr.attr.name)
1935 device_remove_file(hba->dev, &hba->clk_gating.enable_attr);
1938 static void ufshcd_init_clk_gating(struct ufs_hba *hba)
1940 char wq_name[sizeof("ufs_clk_gating_00")];
1942 if (!ufshcd_is_clkgating_allowed(hba))
1945 hba->clk_gating.state = CLKS_ON;
1947 hba->clk_gating.delay_ms = 150;
1948 INIT_DELAYED_WORK(&hba->clk_gating.gate_work, ufshcd_gate_work);
1949 INIT_WORK(&hba->clk_gating.ungate_work, ufshcd_ungate_work);
1951 snprintf(wq_name, ARRAY_SIZE(wq_name), "ufs_clk_gating_%d",
1952 hba->host->host_no);
1953 hba->clk_gating.clk_gating_workq = alloc_ordered_workqueue(wq_name,
1954 WQ_MEM_RECLAIM | WQ_HIGHPRI);
1956 ufshcd_init_clk_gating_sysfs(hba);
1958 hba->clk_gating.is_enabled = true;
1959 hba->clk_gating.is_initialized = true;
1962 static void ufshcd_exit_clk_gating(struct ufs_hba *hba)
1964 if (!hba->clk_gating.is_initialized)
1967 ufshcd_remove_clk_gating_sysfs(hba);
1969 /* Ungate the clock if necessary. */
1970 ufshcd_hold(hba, false);
1971 hba->clk_gating.is_initialized = false;
1972 ufshcd_release(hba);
1974 destroy_workqueue(hba->clk_gating.clk_gating_workq);
1977 /* Must be called with host lock acquired */
1978 static void ufshcd_clk_scaling_start_busy(struct ufs_hba *hba)
1980 bool queue_resume_work = false;
1981 ktime_t curr_t = ktime_get();
1982 unsigned long flags;
1984 if (!ufshcd_is_clkscaling_supported(hba))
1987 spin_lock_irqsave(hba->host->host_lock, flags);
1988 if (!hba->clk_scaling.active_reqs++)
1989 queue_resume_work = true;
1991 if (!hba->clk_scaling.is_enabled || hba->pm_op_in_progress) {
1992 spin_unlock_irqrestore(hba->host->host_lock, flags);
1996 if (queue_resume_work)
1997 queue_work(hba->clk_scaling.workq,
1998 &hba->clk_scaling.resume_work);
2000 if (!hba->clk_scaling.window_start_t) {
2001 hba->clk_scaling.window_start_t = curr_t;
2002 hba->clk_scaling.tot_busy_t = 0;
2003 hba->clk_scaling.is_busy_started = false;
2006 if (!hba->clk_scaling.is_busy_started) {
2007 hba->clk_scaling.busy_start_t = curr_t;
2008 hba->clk_scaling.is_busy_started = true;
2010 spin_unlock_irqrestore(hba->host->host_lock, flags);
2013 static void ufshcd_clk_scaling_update_busy(struct ufs_hba *hba)
2015 struct ufs_clk_scaling *scaling = &hba->clk_scaling;
2016 unsigned long flags;
2018 if (!ufshcd_is_clkscaling_supported(hba))
2021 spin_lock_irqsave(hba->host->host_lock, flags);
2022 hba->clk_scaling.active_reqs--;
2023 if (!hba->outstanding_reqs && scaling->is_busy_started) {
2024 scaling->tot_busy_t += ktime_to_us(ktime_sub(ktime_get(),
2025 scaling->busy_start_t));
2026 scaling->busy_start_t = 0;
2027 scaling->is_busy_started = false;
2029 spin_unlock_irqrestore(hba->host->host_lock, flags);
2032 static inline int ufshcd_monitor_opcode2dir(u8 opcode)
2034 if (opcode == READ_6 || opcode == READ_10 || opcode == READ_16)
2036 else if (opcode == WRITE_6 || opcode == WRITE_10 || opcode == WRITE_16)
2042 static inline bool ufshcd_should_inform_monitor(struct ufs_hba *hba,
2043 struct ufshcd_lrb *lrbp)
2045 struct ufs_hba_monitor *m = &hba->monitor;
2047 return (m->enabled && lrbp && lrbp->cmd &&
2048 (!m->chunk_size || m->chunk_size == lrbp->cmd->sdb.length) &&
2049 ktime_before(hba->monitor.enabled_ts, lrbp->issue_time_stamp));
2052 static void ufshcd_start_monitor(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
2054 int dir = ufshcd_monitor_opcode2dir(*lrbp->cmd->cmnd);
2055 unsigned long flags;
2057 spin_lock_irqsave(hba->host->host_lock, flags);
2058 if (dir >= 0 && hba->monitor.nr_queued[dir]++ == 0)
2059 hba->monitor.busy_start_ts[dir] = ktime_get();
2060 spin_unlock_irqrestore(hba->host->host_lock, flags);
2063 static void ufshcd_update_monitor(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
2065 int dir = ufshcd_monitor_opcode2dir(*lrbp->cmd->cmnd);
2066 unsigned long flags;
2068 spin_lock_irqsave(hba->host->host_lock, flags);
2069 if (dir >= 0 && hba->monitor.nr_queued[dir] > 0) {
2070 struct request *req = scsi_cmd_to_rq(lrbp->cmd);
2071 struct ufs_hba_monitor *m = &hba->monitor;
2072 ktime_t now, inc, lat;
2074 now = lrbp->compl_time_stamp;
2075 inc = ktime_sub(now, m->busy_start_ts[dir]);
2076 m->total_busy[dir] = ktime_add(m->total_busy[dir], inc);
2077 m->nr_sec_rw[dir] += blk_rq_sectors(req);
2079 /* Update latencies */
2081 lat = ktime_sub(now, lrbp->issue_time_stamp);
2082 m->lat_sum[dir] += lat;
2083 if (m->lat_max[dir] < lat || !m->lat_max[dir])
2084 m->lat_max[dir] = lat;
2085 if (m->lat_min[dir] > lat || !m->lat_min[dir])
2086 m->lat_min[dir] = lat;
2088 m->nr_queued[dir]--;
2089 /* Push forward the busy start of monitor */
2090 m->busy_start_ts[dir] = now;
2092 spin_unlock_irqrestore(hba->host->host_lock, flags);
2096 * ufshcd_send_command - Send SCSI or device management commands
2097 * @hba: per adapter instance
2098 * @task_tag: Task tag of the command
2101 void ufshcd_send_command(struct ufs_hba *hba, unsigned int task_tag)
2103 struct ufshcd_lrb *lrbp = &hba->lrb[task_tag];
2104 unsigned long flags;
2106 lrbp->issue_time_stamp = ktime_get();
2107 lrbp->compl_time_stamp = ktime_set(0, 0);
2108 ufshcd_add_command_trace(hba, task_tag, UFS_CMD_SEND);
2109 ufshcd_clk_scaling_start_busy(hba);
2110 if (unlikely(ufshcd_should_inform_monitor(hba, lrbp)))
2111 ufshcd_start_monitor(hba, lrbp);
2113 spin_lock_irqsave(&hba->outstanding_lock, flags);
2114 if (hba->vops && hba->vops->setup_xfer_req)
2115 hba->vops->setup_xfer_req(hba, task_tag, !!lrbp->cmd);
2116 __set_bit(task_tag, &hba->outstanding_reqs);
2117 ufshcd_writel(hba, 1 << task_tag, REG_UTP_TRANSFER_REQ_DOOR_BELL);
2118 spin_unlock_irqrestore(&hba->outstanding_lock, flags);
2120 /* Make sure that doorbell is committed immediately */
2125 * ufshcd_copy_sense_data - Copy sense data in case of check condition
2126 * @lrbp: pointer to local reference block
2128 static inline void ufshcd_copy_sense_data(struct ufshcd_lrb *lrbp)
2131 if (lrbp->sense_buffer &&
2132 ufshcd_get_rsp_upiu_data_seg_len(lrbp->ucd_rsp_ptr)) {
2135 len = be16_to_cpu(lrbp->ucd_rsp_ptr->sr.sense_data_len);
2136 len_to_copy = min_t(int, UFS_SENSE_SIZE, len);
2138 memcpy(lrbp->sense_buffer, lrbp->ucd_rsp_ptr->sr.sense_data,
2144 * ufshcd_copy_query_response() - Copy the Query Response and the data
2146 * @hba: per adapter instance
2147 * @lrbp: pointer to local reference block
2150 int ufshcd_copy_query_response(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
2152 struct ufs_query_res *query_res = &hba->dev_cmd.query.response;
2154 memcpy(&query_res->upiu_res, &lrbp->ucd_rsp_ptr->qr, QUERY_OSF_SIZE);
2156 /* Get the descriptor */
2157 if (hba->dev_cmd.query.descriptor &&
2158 lrbp->ucd_rsp_ptr->qr.opcode == UPIU_QUERY_OPCODE_READ_DESC) {
2159 u8 *descp = (u8 *)lrbp->ucd_rsp_ptr +
2160 GENERAL_UPIU_REQUEST_SIZE;
2164 /* data segment length */
2165 resp_len = be32_to_cpu(lrbp->ucd_rsp_ptr->header.dword_2) &
2166 MASK_QUERY_DATA_SEG_LEN;
2167 buf_len = be16_to_cpu(
2168 hba->dev_cmd.query.request.upiu_req.length);
2169 if (likely(buf_len >= resp_len)) {
2170 memcpy(hba->dev_cmd.query.descriptor, descp, resp_len);
2173 "%s: rsp size %d is bigger than buffer size %d",
2174 __func__, resp_len, buf_len);
2183 * ufshcd_hba_capabilities - Read controller capabilities
2184 * @hba: per adapter instance
2186 * Return: 0 on success, negative on error.
2188 static inline int ufshcd_hba_capabilities(struct ufs_hba *hba)
2192 hba->capabilities = ufshcd_readl(hba, REG_CONTROLLER_CAPABILITIES);
2194 /* nutrs and nutmrs are 0 based values */
2195 hba->nutrs = (hba->capabilities & MASK_TRANSFER_REQUESTS_SLOTS) + 1;
2197 ((hba->capabilities & MASK_TASK_MANAGEMENT_REQUEST_SLOTS) >> 16) + 1;
2198 hba->reserved_slot = hba->nutrs - 1;
2200 /* Read crypto capabilities */
2201 err = ufshcd_hba_init_crypto_capabilities(hba);
2203 dev_err(hba->dev, "crypto setup failed\n");
2209 * ufshcd_ready_for_uic_cmd - Check if controller is ready
2210 * to accept UIC commands
2211 * @hba: per adapter instance
2212 * Return true on success, else false
2214 static inline bool ufshcd_ready_for_uic_cmd(struct ufs_hba *hba)
2216 if (ufshcd_readl(hba, REG_CONTROLLER_STATUS) & UIC_COMMAND_READY)
2223 * ufshcd_get_upmcrs - Get the power mode change request status
2224 * @hba: Pointer to adapter instance
2226 * This function gets the UPMCRS field of HCS register
2227 * Returns value of UPMCRS field
2229 static inline u8 ufshcd_get_upmcrs(struct ufs_hba *hba)
2231 return (ufshcd_readl(hba, REG_CONTROLLER_STATUS) >> 8) & 0x7;
2235 * ufshcd_dispatch_uic_cmd - Dispatch an UIC command to the Unipro layer
2236 * @hba: per adapter instance
2237 * @uic_cmd: UIC command
2240 ufshcd_dispatch_uic_cmd(struct ufs_hba *hba, struct uic_command *uic_cmd)
2242 lockdep_assert_held(&hba->uic_cmd_mutex);
2244 WARN_ON(hba->active_uic_cmd);
2246 hba->active_uic_cmd = uic_cmd;
2249 ufshcd_writel(hba, uic_cmd->argument1, REG_UIC_COMMAND_ARG_1);
2250 ufshcd_writel(hba, uic_cmd->argument2, REG_UIC_COMMAND_ARG_2);
2251 ufshcd_writel(hba, uic_cmd->argument3, REG_UIC_COMMAND_ARG_3);
2253 ufshcd_add_uic_command_trace(hba, uic_cmd, UFS_CMD_SEND);
2256 ufshcd_writel(hba, uic_cmd->command & COMMAND_OPCODE_MASK,
2261 * ufshcd_wait_for_uic_cmd - Wait for completion of an UIC command
2262 * @hba: per adapter instance
2263 * @uic_cmd: UIC command
2265 * Returns 0 only if success.
2268 ufshcd_wait_for_uic_cmd(struct ufs_hba *hba, struct uic_command *uic_cmd)
2271 unsigned long flags;
2273 lockdep_assert_held(&hba->uic_cmd_mutex);
2275 if (wait_for_completion_timeout(&uic_cmd->done,
2276 msecs_to_jiffies(UIC_CMD_TIMEOUT))) {
2277 ret = uic_cmd->argument2 & MASK_UIC_COMMAND_RESULT;
2281 "uic cmd 0x%x with arg3 0x%x completion timeout\n",
2282 uic_cmd->command, uic_cmd->argument3);
2284 if (!uic_cmd->cmd_active) {
2285 dev_err(hba->dev, "%s: UIC cmd has been completed, return the result\n",
2287 ret = uic_cmd->argument2 & MASK_UIC_COMMAND_RESULT;
2291 spin_lock_irqsave(hba->host->host_lock, flags);
2292 hba->active_uic_cmd = NULL;
2293 spin_unlock_irqrestore(hba->host->host_lock, flags);
2299 * __ufshcd_send_uic_cmd - Send UIC commands and retrieve the result
2300 * @hba: per adapter instance
2301 * @uic_cmd: UIC command
2302 * @completion: initialize the completion only if this is set to true
2304 * Returns 0 only if success.
2307 __ufshcd_send_uic_cmd(struct ufs_hba *hba, struct uic_command *uic_cmd,
2310 lockdep_assert_held(&hba->uic_cmd_mutex);
2311 lockdep_assert_held(hba->host->host_lock);
2313 if (!ufshcd_ready_for_uic_cmd(hba)) {
2315 "Controller not ready to accept UIC commands\n");
2320 init_completion(&uic_cmd->done);
2322 uic_cmd->cmd_active = 1;
2323 ufshcd_dispatch_uic_cmd(hba, uic_cmd);
2329 * ufshcd_send_uic_cmd - Send UIC commands and retrieve the result
2330 * @hba: per adapter instance
2331 * @uic_cmd: UIC command
2333 * Returns 0 only if success.
2335 int ufshcd_send_uic_cmd(struct ufs_hba *hba, struct uic_command *uic_cmd)
2338 unsigned long flags;
2340 if (hba->quirks & UFSHCD_QUIRK_BROKEN_UIC_CMD)
2343 ufshcd_hold(hba, false);
2344 mutex_lock(&hba->uic_cmd_mutex);
2345 ufshcd_add_delay_before_dme_cmd(hba);
2347 spin_lock_irqsave(hba->host->host_lock, flags);
2348 ret = __ufshcd_send_uic_cmd(hba, uic_cmd, true);
2349 spin_unlock_irqrestore(hba->host->host_lock, flags);
2351 ret = ufshcd_wait_for_uic_cmd(hba, uic_cmd);
2353 mutex_unlock(&hba->uic_cmd_mutex);
2355 ufshcd_release(hba);
2360 * ufshcd_map_sg - Map scatter-gather list to prdt
2361 * @hba: per adapter instance
2362 * @lrbp: pointer to local reference block
2364 * Returns 0 in case of success, non-zero value in case of failure
2366 static int ufshcd_map_sg(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
2368 struct ufshcd_sg_entry *prd_table;
2369 struct scatterlist *sg;
2370 struct scsi_cmnd *cmd;
2375 sg_segments = scsi_dma_map(cmd);
2376 if (sg_segments < 0)
2381 if (hba->quirks & UFSHCD_QUIRK_PRDT_BYTE_GRAN)
2382 lrbp->utr_descriptor_ptr->prd_table_length =
2383 cpu_to_le16((sg_segments *
2384 sizeof(struct ufshcd_sg_entry)));
2386 lrbp->utr_descriptor_ptr->prd_table_length =
2387 cpu_to_le16(sg_segments);
2389 prd_table = lrbp->ucd_prdt_ptr;
2391 scsi_for_each_sg(cmd, sg, sg_segments, i) {
2392 const unsigned int len = sg_dma_len(sg);
2395 * From the UFSHCI spec: "Data Byte Count (DBC): A '0'
2396 * based value that indicates the length, in bytes, of
2397 * the data block. A maximum of length of 256KB may
2398 * exist for any entry. Bits 1:0 of this field shall be
2399 * 11b to indicate Dword granularity. A value of '3'
2400 * indicates 4 bytes, '7' indicates 8 bytes, etc."
2402 WARN_ONCE(len > 256 * 1024, "len = %#x\n", len);
2403 prd_table[i].size = cpu_to_le32(len - 1);
2404 prd_table[i].addr = cpu_to_le64(sg->dma_address);
2405 prd_table[i].reserved = 0;
2408 lrbp->utr_descriptor_ptr->prd_table_length = 0;
2415 * ufshcd_enable_intr - enable interrupts
2416 * @hba: per adapter instance
2417 * @intrs: interrupt bits
2419 static void ufshcd_enable_intr(struct ufs_hba *hba, u32 intrs)
2421 u32 set = ufshcd_readl(hba, REG_INTERRUPT_ENABLE);
2423 if (hba->ufs_version == ufshci_version(1, 0)) {
2425 rw = set & INTERRUPT_MASK_RW_VER_10;
2426 set = rw | ((set ^ intrs) & intrs);
2431 ufshcd_writel(hba, set, REG_INTERRUPT_ENABLE);
2435 * ufshcd_disable_intr - disable interrupts
2436 * @hba: per adapter instance
2437 * @intrs: interrupt bits
2439 static void ufshcd_disable_intr(struct ufs_hba *hba, u32 intrs)
2441 u32 set = ufshcd_readl(hba, REG_INTERRUPT_ENABLE);
2443 if (hba->ufs_version == ufshci_version(1, 0)) {
2445 rw = (set & INTERRUPT_MASK_RW_VER_10) &
2446 ~(intrs & INTERRUPT_MASK_RW_VER_10);
2447 set = rw | ((set & intrs) & ~INTERRUPT_MASK_RW_VER_10);
2453 ufshcd_writel(hba, set, REG_INTERRUPT_ENABLE);
2457 * ufshcd_prepare_req_desc_hdr() - Fills the requests header
2458 * descriptor according to request
2459 * @lrbp: pointer to local reference block
2460 * @upiu_flags: flags required in the header
2461 * @cmd_dir: requests data direction
2463 static void ufshcd_prepare_req_desc_hdr(struct ufshcd_lrb *lrbp,
2464 u8 *upiu_flags, enum dma_data_direction cmd_dir)
2466 struct utp_transfer_req_desc *req_desc = lrbp->utr_descriptor_ptr;
2472 if (cmd_dir == DMA_FROM_DEVICE) {
2473 data_direction = UTP_DEVICE_TO_HOST;
2474 *upiu_flags = UPIU_CMD_FLAGS_READ;
2475 } else if (cmd_dir == DMA_TO_DEVICE) {
2476 data_direction = UTP_HOST_TO_DEVICE;
2477 *upiu_flags = UPIU_CMD_FLAGS_WRITE;
2479 data_direction = UTP_NO_DATA_TRANSFER;
2480 *upiu_flags = UPIU_CMD_FLAGS_NONE;
2483 dword_0 = data_direction | (lrbp->command_type
2484 << UPIU_COMMAND_TYPE_OFFSET);
2486 dword_0 |= UTP_REQ_DESC_INT_CMD;
2488 /* Prepare crypto related dwords */
2489 ufshcd_prepare_req_desc_hdr_crypto(lrbp, &dword_0, &dword_1, &dword_3);
2491 /* Transfer request descriptor header fields */
2492 req_desc->header.dword_0 = cpu_to_le32(dword_0);
2493 req_desc->header.dword_1 = cpu_to_le32(dword_1);
2495 * assigning invalid value for command status. Controller
2496 * updates OCS on command completion, with the command
2499 req_desc->header.dword_2 =
2500 cpu_to_le32(OCS_INVALID_COMMAND_STATUS);
2501 req_desc->header.dword_3 = cpu_to_le32(dword_3);
2503 req_desc->prd_table_length = 0;
2507 * ufshcd_prepare_utp_scsi_cmd_upiu() - fills the utp_transfer_req_desc,
2509 * @lrbp: local reference block pointer
2510 * @upiu_flags: flags
2513 void ufshcd_prepare_utp_scsi_cmd_upiu(struct ufshcd_lrb *lrbp, u8 upiu_flags)
2515 struct scsi_cmnd *cmd = lrbp->cmd;
2516 struct utp_upiu_req *ucd_req_ptr = lrbp->ucd_req_ptr;
2517 unsigned short cdb_len;
2519 /* command descriptor fields */
2520 ucd_req_ptr->header.dword_0 = UPIU_HEADER_DWORD(
2521 UPIU_TRANSACTION_COMMAND, upiu_flags,
2522 lrbp->lun, lrbp->task_tag);
2523 ucd_req_ptr->header.dword_1 = UPIU_HEADER_DWORD(
2524 UPIU_COMMAND_SET_TYPE_SCSI, 0, 0, 0);
2526 /* Total EHS length and Data segment length will be zero */
2527 ucd_req_ptr->header.dword_2 = 0;
2529 ucd_req_ptr->sc.exp_data_transfer_len = cpu_to_be32(cmd->sdb.length);
2531 cdb_len = min_t(unsigned short, cmd->cmd_len, UFS_CDB_SIZE);
2532 memset(ucd_req_ptr->sc.cdb, 0, UFS_CDB_SIZE);
2533 memcpy(ucd_req_ptr->sc.cdb, cmd->cmnd, cdb_len);
2535 memset(lrbp->ucd_rsp_ptr, 0, sizeof(struct utp_upiu_rsp));
2539 * ufshcd_prepare_utp_query_req_upiu() - fills the utp_transfer_req_desc,
2542 * @lrbp: local reference block pointer
2543 * @upiu_flags: flags
2545 static void ufshcd_prepare_utp_query_req_upiu(struct ufs_hba *hba,
2546 struct ufshcd_lrb *lrbp, u8 upiu_flags)
2548 struct utp_upiu_req *ucd_req_ptr = lrbp->ucd_req_ptr;
2549 struct ufs_query *query = &hba->dev_cmd.query;
2550 u16 len = be16_to_cpu(query->request.upiu_req.length);
2552 /* Query request header */
2553 ucd_req_ptr->header.dword_0 = UPIU_HEADER_DWORD(
2554 UPIU_TRANSACTION_QUERY_REQ, upiu_flags,
2555 lrbp->lun, lrbp->task_tag);
2556 ucd_req_ptr->header.dword_1 = UPIU_HEADER_DWORD(
2557 0, query->request.query_func, 0, 0);
2559 /* Data segment length only need for WRITE_DESC */
2560 if (query->request.upiu_req.opcode == UPIU_QUERY_OPCODE_WRITE_DESC)
2561 ucd_req_ptr->header.dword_2 =
2562 UPIU_HEADER_DWORD(0, 0, (len >> 8), (u8)len);
2564 ucd_req_ptr->header.dword_2 = 0;
2566 /* Copy the Query Request buffer as is */
2567 memcpy(&ucd_req_ptr->qr, &query->request.upiu_req,
2570 /* Copy the Descriptor */
2571 if (query->request.upiu_req.opcode == UPIU_QUERY_OPCODE_WRITE_DESC)
2572 memcpy(ucd_req_ptr + 1, query->descriptor, len);
2574 memset(lrbp->ucd_rsp_ptr, 0, sizeof(struct utp_upiu_rsp));
2577 static inline void ufshcd_prepare_utp_nop_upiu(struct ufshcd_lrb *lrbp)
2579 struct utp_upiu_req *ucd_req_ptr = lrbp->ucd_req_ptr;
2581 memset(ucd_req_ptr, 0, sizeof(struct utp_upiu_req));
2583 /* command descriptor fields */
2584 ucd_req_ptr->header.dword_0 =
2586 UPIU_TRANSACTION_NOP_OUT, 0, 0, lrbp->task_tag);
2587 /* clear rest of the fields of basic header */
2588 ucd_req_ptr->header.dword_1 = 0;
2589 ucd_req_ptr->header.dword_2 = 0;
2591 memset(lrbp->ucd_rsp_ptr, 0, sizeof(struct utp_upiu_rsp));
2595 * ufshcd_compose_devman_upiu - UFS Protocol Information Unit(UPIU)
2596 * for Device Management Purposes
2597 * @hba: per adapter instance
2598 * @lrbp: pointer to local reference block
2600 static int ufshcd_compose_devman_upiu(struct ufs_hba *hba,
2601 struct ufshcd_lrb *lrbp)
2606 if (hba->ufs_version <= ufshci_version(1, 1))
2607 lrbp->command_type = UTP_CMD_TYPE_DEV_MANAGE;
2609 lrbp->command_type = UTP_CMD_TYPE_UFS_STORAGE;
2611 ufshcd_prepare_req_desc_hdr(lrbp, &upiu_flags, DMA_NONE);
2612 if (hba->dev_cmd.type == DEV_CMD_TYPE_QUERY)
2613 ufshcd_prepare_utp_query_req_upiu(hba, lrbp, upiu_flags);
2614 else if (hba->dev_cmd.type == DEV_CMD_TYPE_NOP)
2615 ufshcd_prepare_utp_nop_upiu(lrbp);
2623 * ufshcd_comp_scsi_upiu - UFS Protocol Information Unit(UPIU)
2625 * @hba: per adapter instance
2626 * @lrbp: pointer to local reference block
2628 static int ufshcd_comp_scsi_upiu(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
2633 if (hba->ufs_version <= ufshci_version(1, 1))
2634 lrbp->command_type = UTP_CMD_TYPE_SCSI;
2636 lrbp->command_type = UTP_CMD_TYPE_UFS_STORAGE;
2638 if (likely(lrbp->cmd)) {
2639 ufshcd_prepare_req_desc_hdr(lrbp, &upiu_flags,
2640 lrbp->cmd->sc_data_direction);
2641 ufshcd_prepare_utp_scsi_cmd_upiu(lrbp, upiu_flags);
2650 * ufshcd_upiu_wlun_to_scsi_wlun - maps UPIU W-LUN id to SCSI W-LUN ID
2651 * @upiu_wlun_id: UPIU W-LUN id
2653 * Returns SCSI W-LUN id
2655 static inline u16 ufshcd_upiu_wlun_to_scsi_wlun(u8 upiu_wlun_id)
2657 return (upiu_wlun_id & ~UFS_UPIU_WLUN_ID) | SCSI_W_LUN_BASE;
2660 static inline bool is_device_wlun(struct scsi_device *sdev)
2663 ufshcd_upiu_wlun_to_scsi_wlun(UFS_UPIU_UFS_DEVICE_WLUN);
2667 * Associate the UFS controller queue with the default and poll HCTX types.
2668 * Initialize the mq_map[] arrays.
2670 static int ufshcd_map_queues(struct Scsi_Host *shost)
2674 for (i = 0; i < shost->nr_maps; i++) {
2675 struct blk_mq_queue_map *map = &shost->tag_set.map[i];
2678 case HCTX_TYPE_DEFAULT:
2679 case HCTX_TYPE_POLL:
2682 case HCTX_TYPE_READ:
2688 map->queue_offset = 0;
2689 ret = blk_mq_map_queues(map);
2696 static void ufshcd_init_lrb(struct ufs_hba *hba, struct ufshcd_lrb *lrb, int i)
2698 struct utp_transfer_cmd_desc *cmd_descp = hba->ucdl_base_addr;
2699 struct utp_transfer_req_desc *utrdlp = hba->utrdl_base_addr;
2700 dma_addr_t cmd_desc_element_addr = hba->ucdl_dma_addr +
2701 i * sizeof(struct utp_transfer_cmd_desc);
2702 u16 response_offset = offsetof(struct utp_transfer_cmd_desc,
2704 u16 prdt_offset = offsetof(struct utp_transfer_cmd_desc, prd_table);
2706 lrb->utr_descriptor_ptr = utrdlp + i;
2707 lrb->utrd_dma_addr = hba->utrdl_dma_addr +
2708 i * sizeof(struct utp_transfer_req_desc);
2709 lrb->ucd_req_ptr = (struct utp_upiu_req *)(cmd_descp + i);
2710 lrb->ucd_req_dma_addr = cmd_desc_element_addr;
2711 lrb->ucd_rsp_ptr = (struct utp_upiu_rsp *)cmd_descp[i].response_upiu;
2712 lrb->ucd_rsp_dma_addr = cmd_desc_element_addr + response_offset;
2713 lrb->ucd_prdt_ptr = cmd_descp[i].prd_table;
2714 lrb->ucd_prdt_dma_addr = cmd_desc_element_addr + prdt_offset;
2718 * ufshcd_queuecommand - main entry point for SCSI requests
2719 * @host: SCSI host pointer
2720 * @cmd: command from SCSI Midlayer
2722 * Returns 0 for success, non-zero in case of failure
2724 static int ufshcd_queuecommand(struct Scsi_Host *host, struct scsi_cmnd *cmd)
2726 struct ufs_hba *hba = shost_priv(host);
2727 int tag = scsi_cmd_to_rq(cmd)->tag;
2728 struct ufshcd_lrb *lrbp;
2731 WARN_ONCE(tag < 0 || tag >= hba->nutrs, "Invalid tag %d\n", tag);
2734 * Allows the UFS error handler to wait for prior ufshcd_queuecommand()
2739 switch (hba->ufshcd_state) {
2740 case UFSHCD_STATE_OPERATIONAL:
2742 case UFSHCD_STATE_EH_SCHEDULED_NON_FATAL:
2744 * SCSI error handler can call ->queuecommand() while UFS error
2745 * handler is in progress. Error interrupts could change the
2746 * state from UFSHCD_STATE_RESET to
2747 * UFSHCD_STATE_EH_SCHEDULED_NON_FATAL. Prevent requests
2748 * being issued in that case.
2750 if (ufshcd_eh_in_progress(hba)) {
2751 err = SCSI_MLQUEUE_HOST_BUSY;
2755 case UFSHCD_STATE_EH_SCHEDULED_FATAL:
2757 * pm_runtime_get_sync() is used at error handling preparation
2758 * stage. If a scsi cmd, e.g. the SSU cmd, is sent from hba's
2759 * PM ops, it can never be finished if we let SCSI layer keep
2760 * retrying it, which gets err handler stuck forever. Neither
2761 * can we let the scsi cmd pass through, because UFS is in bad
2762 * state, the scsi cmd may eventually time out, which will get
2763 * err handler blocked for too long. So, just fail the scsi cmd
2764 * sent from PM ops, err handler can recover PM error anyways.
2766 if (hba->pm_op_in_progress) {
2767 hba->force_reset = true;
2768 set_host_byte(cmd, DID_BAD_TARGET);
2773 case UFSHCD_STATE_RESET:
2774 err = SCSI_MLQUEUE_HOST_BUSY;
2776 case UFSHCD_STATE_ERROR:
2777 set_host_byte(cmd, DID_ERROR);
2782 hba->req_abort_count = 0;
2784 err = ufshcd_hold(hba, true);
2786 err = SCSI_MLQUEUE_HOST_BUSY;
2789 WARN_ON(ufshcd_is_clkgating_allowed(hba) &&
2790 (hba->clk_gating.state != CLKS_ON));
2792 lrbp = &hba->lrb[tag];
2795 lrbp->sense_bufflen = UFS_SENSE_SIZE;
2796 lrbp->sense_buffer = cmd->sense_buffer;
2797 lrbp->task_tag = tag;
2798 lrbp->lun = ufshcd_scsi_to_upiu_lun(cmd->device->lun);
2799 lrbp->intr_cmd = !ufshcd_is_intr_aggr_allowed(hba) ? true : false;
2801 ufshcd_prepare_lrbp_crypto(scsi_cmd_to_rq(cmd), lrbp);
2803 lrbp->req_abort_skip = false;
2805 ufshpb_prep(hba, lrbp);
2807 ufshcd_comp_scsi_upiu(hba, lrbp);
2809 err = ufshcd_map_sg(hba, lrbp);
2812 ufshcd_release(hba);
2816 ufshcd_send_command(hba, tag);
2821 if (ufs_trigger_eh()) {
2822 unsigned long flags;
2824 spin_lock_irqsave(hba->host->host_lock, flags);
2825 ufshcd_schedule_eh_work(hba);
2826 spin_unlock_irqrestore(hba->host->host_lock, flags);
2832 static int ufshcd_compose_dev_cmd(struct ufs_hba *hba,
2833 struct ufshcd_lrb *lrbp, enum dev_cmd_type cmd_type, int tag)
2836 lrbp->sense_bufflen = 0;
2837 lrbp->sense_buffer = NULL;
2838 lrbp->task_tag = tag;
2839 lrbp->lun = 0; /* device management cmd is not specific to any LUN */
2840 lrbp->intr_cmd = true; /* No interrupt aggregation */
2841 ufshcd_prepare_lrbp_crypto(NULL, lrbp);
2842 hba->dev_cmd.type = cmd_type;
2844 return ufshcd_compose_devman_upiu(hba, lrbp);
2848 ufshcd_clear_cmd(struct ufs_hba *hba, int tag)
2851 unsigned long flags;
2852 u32 mask = 1 << tag;
2854 /* clear outstanding transaction before retry */
2855 spin_lock_irqsave(hba->host->host_lock, flags);
2856 ufshcd_utrl_clear(hba, tag);
2857 spin_unlock_irqrestore(hba->host->host_lock, flags);
2860 * wait for h/w to clear corresponding bit in door-bell.
2861 * max. wait is 1 sec.
2863 err = ufshcd_wait_for_register(hba,
2864 REG_UTP_TRANSFER_REQ_DOOR_BELL,
2865 mask, ~mask, 1000, 1000);
2871 ufshcd_check_query_response(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
2873 struct ufs_query_res *query_res = &hba->dev_cmd.query.response;
2875 /* Get the UPIU response */
2876 query_res->response = ufshcd_get_rsp_upiu_result(lrbp->ucd_rsp_ptr) >>
2877 UPIU_RSP_CODE_OFFSET;
2878 return query_res->response;
2882 * ufshcd_dev_cmd_completion() - handles device management command responses
2883 * @hba: per adapter instance
2884 * @lrbp: pointer to local reference block
2887 ufshcd_dev_cmd_completion(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
2892 hba->ufs_stats.last_hibern8_exit_tstamp = ktime_set(0, 0);
2893 resp = ufshcd_get_req_rsp(lrbp->ucd_rsp_ptr);
2896 case UPIU_TRANSACTION_NOP_IN:
2897 if (hba->dev_cmd.type != DEV_CMD_TYPE_NOP) {
2899 dev_err(hba->dev, "%s: unexpected response %x\n",
2903 case UPIU_TRANSACTION_QUERY_RSP:
2904 err = ufshcd_check_query_response(hba, lrbp);
2906 err = ufshcd_copy_query_response(hba, lrbp);
2908 case UPIU_TRANSACTION_REJECT_UPIU:
2909 /* TODO: handle Reject UPIU Response */
2911 dev_err(hba->dev, "%s: Reject UPIU not fully implemented\n",
2916 dev_err(hba->dev, "%s: Invalid device management cmd response: %x\n",
2924 static int ufshcd_wait_for_dev_cmd(struct ufs_hba *hba,
2925 struct ufshcd_lrb *lrbp, int max_timeout)
2928 unsigned long time_left;
2929 unsigned long flags;
2931 time_left = wait_for_completion_timeout(hba->dev_cmd.complete,
2932 msecs_to_jiffies(max_timeout));
2934 spin_lock_irqsave(hba->host->host_lock, flags);
2935 hba->dev_cmd.complete = NULL;
2936 if (likely(time_left)) {
2937 err = ufshcd_get_tr_ocs(lrbp);
2939 err = ufshcd_dev_cmd_completion(hba, lrbp);
2941 spin_unlock_irqrestore(hba->host->host_lock, flags);
2945 dev_dbg(hba->dev, "%s: dev_cmd request timedout, tag %d\n",
2946 __func__, lrbp->task_tag);
2947 if (!ufshcd_clear_cmd(hba, lrbp->task_tag))
2948 /* successfully cleared the command, retry if needed */
2951 * in case of an error, after clearing the doorbell,
2952 * we also need to clear the outstanding_request
2955 spin_lock_irqsave(&hba->outstanding_lock, flags);
2956 __clear_bit(lrbp->task_tag, &hba->outstanding_reqs);
2957 spin_unlock_irqrestore(&hba->outstanding_lock, flags);
2964 * ufshcd_exec_dev_cmd - API for sending device management requests
2966 * @cmd_type: specifies the type (NOP, Query...)
2967 * @timeout: timeout in milliseconds
2969 * NOTE: Since there is only one available tag for device management commands,
2970 * it is expected you hold the hba->dev_cmd.lock mutex.
2972 static int ufshcd_exec_dev_cmd(struct ufs_hba *hba,
2973 enum dev_cmd_type cmd_type, int timeout)
2975 DECLARE_COMPLETION_ONSTACK(wait);
2976 const u32 tag = hba->reserved_slot;
2977 struct ufshcd_lrb *lrbp;
2980 /* Protects use of hba->reserved_slot. */
2981 lockdep_assert_held(&hba->dev_cmd.lock);
2983 down_read(&hba->clk_scaling_lock);
2985 lrbp = &hba->lrb[tag];
2987 err = ufshcd_compose_dev_cmd(hba, lrbp, cmd_type, tag);
2991 hba->dev_cmd.complete = &wait;
2993 ufshcd_add_query_upiu_trace(hba, UFS_QUERY_SEND, lrbp->ucd_req_ptr);
2995 ufshcd_send_command(hba, tag);
2996 err = ufshcd_wait_for_dev_cmd(hba, lrbp, timeout);
2997 ufshcd_add_query_upiu_trace(hba, err ? UFS_QUERY_ERR : UFS_QUERY_COMP,
2998 (struct utp_upiu_req *)lrbp->ucd_rsp_ptr);
3001 up_read(&hba->clk_scaling_lock);
3006 * ufshcd_init_query() - init the query response and request parameters
3007 * @hba: per-adapter instance
3008 * @request: address of the request pointer to be initialized
3009 * @response: address of the response pointer to be initialized
3010 * @opcode: operation to perform
3011 * @idn: flag idn to access
3012 * @index: LU number to access
3013 * @selector: query/flag/descriptor further identification
3015 static inline void ufshcd_init_query(struct ufs_hba *hba,
3016 struct ufs_query_req **request, struct ufs_query_res **response,
3017 enum query_opcode opcode, u8 idn, u8 index, u8 selector)
3019 *request = &hba->dev_cmd.query.request;
3020 *response = &hba->dev_cmd.query.response;
3021 memset(*request, 0, sizeof(struct ufs_query_req));
3022 memset(*response, 0, sizeof(struct ufs_query_res));
3023 (*request)->upiu_req.opcode = opcode;
3024 (*request)->upiu_req.idn = idn;
3025 (*request)->upiu_req.index = index;
3026 (*request)->upiu_req.selector = selector;
3029 static int ufshcd_query_flag_retry(struct ufs_hba *hba,
3030 enum query_opcode opcode, enum flag_idn idn, u8 index, bool *flag_res)
3035 for (retries = 0; retries < QUERY_REQ_RETRIES; retries++) {
3036 ret = ufshcd_query_flag(hba, opcode, idn, index, flag_res);
3039 "%s: failed with error %d, retries %d\n",
3040 __func__, ret, retries);
3047 "%s: query attribute, opcode %d, idn %d, failed with error %d after %d retires\n",
3048 __func__, opcode, idn, ret, retries);
3053 * ufshcd_query_flag() - API function for sending flag query requests
3054 * @hba: per-adapter instance
3055 * @opcode: flag query to perform
3056 * @idn: flag idn to access
3057 * @index: flag index to access
3058 * @flag_res: the flag value after the query request completes
3060 * Returns 0 for success, non-zero in case of failure
3062 int ufshcd_query_flag(struct ufs_hba *hba, enum query_opcode opcode,
3063 enum flag_idn idn, u8 index, bool *flag_res)
3065 struct ufs_query_req *request = NULL;
3066 struct ufs_query_res *response = NULL;
3067 int err, selector = 0;
3068 int timeout = QUERY_REQ_TIMEOUT;
3072 ufshcd_hold(hba, false);
3073 mutex_lock(&hba->dev_cmd.lock);
3074 ufshcd_init_query(hba, &request, &response, opcode, idn, index,
3078 case UPIU_QUERY_OPCODE_SET_FLAG:
3079 case UPIU_QUERY_OPCODE_CLEAR_FLAG:
3080 case UPIU_QUERY_OPCODE_TOGGLE_FLAG:
3081 request->query_func = UPIU_QUERY_FUNC_STANDARD_WRITE_REQUEST;
3083 case UPIU_QUERY_OPCODE_READ_FLAG:
3084 request->query_func = UPIU_QUERY_FUNC_STANDARD_READ_REQUEST;
3086 /* No dummy reads */
3087 dev_err(hba->dev, "%s: Invalid argument for read request\n",
3095 "%s: Expected query flag opcode but got = %d\n",
3101 err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_QUERY, timeout);
3105 "%s: Sending flag query for idn %d failed, err = %d\n",
3106 __func__, idn, err);
3111 *flag_res = (be32_to_cpu(response->upiu_res.value) &
3112 MASK_QUERY_UPIU_FLAG_LOC) & 0x1;
3115 mutex_unlock(&hba->dev_cmd.lock);
3116 ufshcd_release(hba);
3121 * ufshcd_query_attr - API function for sending attribute requests
3122 * @hba: per-adapter instance
3123 * @opcode: attribute opcode
3124 * @idn: attribute idn to access
3125 * @index: index field
3126 * @selector: selector field
3127 * @attr_val: the attribute value after the query request completes
3129 * Returns 0 for success, non-zero in case of failure
3131 int ufshcd_query_attr(struct ufs_hba *hba, enum query_opcode opcode,
3132 enum attr_idn idn, u8 index, u8 selector, u32 *attr_val)
3134 struct ufs_query_req *request = NULL;
3135 struct ufs_query_res *response = NULL;
3141 dev_err(hba->dev, "%s: attribute value required for opcode 0x%x\n",
3146 ufshcd_hold(hba, false);
3148 mutex_lock(&hba->dev_cmd.lock);
3149 ufshcd_init_query(hba, &request, &response, opcode, idn, index,
3153 case UPIU_QUERY_OPCODE_WRITE_ATTR:
3154 request->query_func = UPIU_QUERY_FUNC_STANDARD_WRITE_REQUEST;
3155 request->upiu_req.value = cpu_to_be32(*attr_val);
3157 case UPIU_QUERY_OPCODE_READ_ATTR:
3158 request->query_func = UPIU_QUERY_FUNC_STANDARD_READ_REQUEST;
3161 dev_err(hba->dev, "%s: Expected query attr opcode but got = 0x%.2x\n",
3167 err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_QUERY, QUERY_REQ_TIMEOUT);
3170 dev_err(hba->dev, "%s: opcode 0x%.2x for idn %d failed, index %d, err = %d\n",
3171 __func__, opcode, idn, index, err);
3175 *attr_val = be32_to_cpu(response->upiu_res.value);
3178 mutex_unlock(&hba->dev_cmd.lock);
3179 ufshcd_release(hba);
3184 * ufshcd_query_attr_retry() - API function for sending query
3185 * attribute with retries
3186 * @hba: per-adapter instance
3187 * @opcode: attribute opcode
3188 * @idn: attribute idn to access
3189 * @index: index field
3190 * @selector: selector field
3191 * @attr_val: the attribute value after the query request
3194 * Returns 0 for success, non-zero in case of failure
3196 int ufshcd_query_attr_retry(struct ufs_hba *hba,
3197 enum query_opcode opcode, enum attr_idn idn, u8 index, u8 selector,
3203 for (retries = QUERY_REQ_RETRIES; retries > 0; retries--) {
3204 ret = ufshcd_query_attr(hba, opcode, idn, index,
3205 selector, attr_val);
3207 dev_dbg(hba->dev, "%s: failed with error %d, retries %d\n",
3208 __func__, ret, retries);
3215 "%s: query attribute, idn %d, failed with error %d after %d retires\n",
3216 __func__, idn, ret, QUERY_REQ_RETRIES);
3220 static int __ufshcd_query_descriptor(struct ufs_hba *hba,
3221 enum query_opcode opcode, enum desc_idn idn, u8 index,
3222 u8 selector, u8 *desc_buf, int *buf_len)
3224 struct ufs_query_req *request = NULL;
3225 struct ufs_query_res *response = NULL;
3231 dev_err(hba->dev, "%s: descriptor buffer required for opcode 0x%x\n",
3236 if (*buf_len < QUERY_DESC_MIN_SIZE || *buf_len > QUERY_DESC_MAX_SIZE) {
3237 dev_err(hba->dev, "%s: descriptor buffer size (%d) is out of range\n",
3238 __func__, *buf_len);
3242 ufshcd_hold(hba, false);
3244 mutex_lock(&hba->dev_cmd.lock);
3245 ufshcd_init_query(hba, &request, &response, opcode, idn, index,
3247 hba->dev_cmd.query.descriptor = desc_buf;
3248 request->upiu_req.length = cpu_to_be16(*buf_len);
3251 case UPIU_QUERY_OPCODE_WRITE_DESC:
3252 request->query_func = UPIU_QUERY_FUNC_STANDARD_WRITE_REQUEST;
3254 case UPIU_QUERY_OPCODE_READ_DESC:
3255 request->query_func = UPIU_QUERY_FUNC_STANDARD_READ_REQUEST;
3259 "%s: Expected query descriptor opcode but got = 0x%.2x\n",
3265 err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_QUERY, QUERY_REQ_TIMEOUT);
3268 dev_err(hba->dev, "%s: opcode 0x%.2x for idn %d failed, index %d, err = %d\n",
3269 __func__, opcode, idn, index, err);
3273 *buf_len = be16_to_cpu(response->upiu_res.length);
3276 hba->dev_cmd.query.descriptor = NULL;
3277 mutex_unlock(&hba->dev_cmd.lock);
3278 ufshcd_release(hba);
3283 * ufshcd_query_descriptor_retry - API function for sending descriptor requests
3284 * @hba: per-adapter instance
3285 * @opcode: attribute opcode
3286 * @idn: attribute idn to access
3287 * @index: index field
3288 * @selector: selector field
3289 * @desc_buf: the buffer that contains the descriptor
3290 * @buf_len: length parameter passed to the device
3292 * Returns 0 for success, non-zero in case of failure.
3293 * The buf_len parameter will contain, on return, the length parameter
3294 * received on the response.
3296 int ufshcd_query_descriptor_retry(struct ufs_hba *hba,
3297 enum query_opcode opcode,
3298 enum desc_idn idn, u8 index,
3300 u8 *desc_buf, int *buf_len)
3305 for (retries = QUERY_REQ_RETRIES; retries > 0; retries--) {
3306 err = __ufshcd_query_descriptor(hba, opcode, idn, index,
3307 selector, desc_buf, buf_len);
3308 if (!err || err == -EINVAL)
3316 * ufshcd_map_desc_id_to_length - map descriptor IDN to its length
3317 * @hba: Pointer to adapter instance
3318 * @desc_id: descriptor idn value
3319 * @desc_len: mapped desc length (out)
3321 void ufshcd_map_desc_id_to_length(struct ufs_hba *hba, enum desc_idn desc_id,
3324 if (desc_id >= QUERY_DESC_IDN_MAX || desc_id == QUERY_DESC_IDN_RFU_0 ||
3325 desc_id == QUERY_DESC_IDN_RFU_1)
3328 *desc_len = hba->desc_size[desc_id];
3330 EXPORT_SYMBOL(ufshcd_map_desc_id_to_length);
3332 static void ufshcd_update_desc_length(struct ufs_hba *hba,
3333 enum desc_idn desc_id, int desc_index,
3334 unsigned char desc_len)
3336 if (hba->desc_size[desc_id] == QUERY_DESC_MAX_SIZE &&
3337 desc_id != QUERY_DESC_IDN_STRING && desc_index != UFS_RPMB_UNIT)
3338 /* For UFS 3.1, the normal unit descriptor is 10 bytes larger
3339 * than the RPMB unit, however, both descriptors share the same
3340 * desc_idn, to cover both unit descriptors with one length, we
3341 * choose the normal unit descriptor length by desc_index.
3343 hba->desc_size[desc_id] = desc_len;
3347 * ufshcd_read_desc_param - read the specified descriptor parameter
3348 * @hba: Pointer to adapter instance
3349 * @desc_id: descriptor idn value
3350 * @desc_index: descriptor index
3351 * @param_offset: offset of the parameter to read
3352 * @param_read_buf: pointer to buffer where parameter would be read
3353 * @param_size: sizeof(param_read_buf)
3355 * Return 0 in case of success, non-zero otherwise
3357 int ufshcd_read_desc_param(struct ufs_hba *hba,
3358 enum desc_idn desc_id,
3367 bool is_kmalloc = true;
3370 if (desc_id >= QUERY_DESC_IDN_MAX || !param_size)
3373 /* Get the length of descriptor */
3374 ufshcd_map_desc_id_to_length(hba, desc_id, &buff_len);
3376 dev_err(hba->dev, "%s: Failed to get desc length\n", __func__);
3380 if (param_offset >= buff_len) {
3381 dev_err(hba->dev, "%s: Invalid offset 0x%x in descriptor IDN 0x%x, length 0x%x\n",
3382 __func__, param_offset, desc_id, buff_len);
3386 /* Check whether we need temp memory */
3387 if (param_offset != 0 || param_size < buff_len) {
3388 desc_buf = kzalloc(buff_len, GFP_KERNEL);
3392 desc_buf = param_read_buf;
3396 /* Request for full descriptor */
3397 ret = ufshcd_query_descriptor_retry(hba, UPIU_QUERY_OPCODE_READ_DESC,
3398 desc_id, desc_index, 0,
3399 desc_buf, &buff_len);
3402 dev_err(hba->dev, "%s: Failed reading descriptor. desc_id %d, desc_index %d, param_offset %d, ret %d\n",
3403 __func__, desc_id, desc_index, param_offset, ret);
3408 if (desc_buf[QUERY_DESC_DESC_TYPE_OFFSET] != desc_id) {
3409 dev_err(hba->dev, "%s: invalid desc_id %d in descriptor header\n",
3410 __func__, desc_buf[QUERY_DESC_DESC_TYPE_OFFSET]);
3415 /* Update descriptor length */
3416 buff_len = desc_buf[QUERY_DESC_LENGTH_OFFSET];
3417 ufshcd_update_desc_length(hba, desc_id, desc_index, buff_len);
3420 /* Make sure we don't copy more data than available */
3421 if (param_offset >= buff_len)
3424 memcpy(param_read_buf, &desc_buf[param_offset],
3425 min_t(u32, param_size, buff_len - param_offset));
3434 * struct uc_string_id - unicode string
3436 * @len: size of this descriptor inclusive
3437 * @type: descriptor type
3438 * @uc: unicode string character
3440 struct uc_string_id {
3446 /* replace non-printable or non-ASCII characters with spaces */
3447 static inline char ufshcd_remove_non_printable(u8 ch)
3449 return (ch >= 0x20 && ch <= 0x7e) ? ch : ' ';
3453 * ufshcd_read_string_desc - read string descriptor
3454 * @hba: pointer to adapter instance
3455 * @desc_index: descriptor index
3456 * @buf: pointer to buffer where descriptor would be read,
3457 * the caller should free the memory.
3458 * @ascii: if true convert from unicode to ascii characters
3459 * null terminated string.
3462 * * string size on success.
3463 * * -ENOMEM: on allocation failure
3464 * * -EINVAL: on a wrong parameter
3466 int ufshcd_read_string_desc(struct ufs_hba *hba, u8 desc_index,
3467 u8 **buf, bool ascii)
3469 struct uc_string_id *uc_str;
3476 uc_str = kzalloc(QUERY_DESC_MAX_SIZE, GFP_KERNEL);
3480 ret = ufshcd_read_desc_param(hba, QUERY_DESC_IDN_STRING, desc_index, 0,
3481 (u8 *)uc_str, QUERY_DESC_MAX_SIZE);
3483 dev_err(hba->dev, "Reading String Desc failed after %d retries. err = %d\n",
3484 QUERY_REQ_RETRIES, ret);
3489 if (uc_str->len <= QUERY_DESC_HDR_SIZE) {
3490 dev_dbg(hba->dev, "String Desc is of zero length\n");
3499 /* remove header and divide by 2 to move from UTF16 to UTF8 */
3500 ascii_len = (uc_str->len - QUERY_DESC_HDR_SIZE) / 2 + 1;
3501 str = kzalloc(ascii_len, GFP_KERNEL);
3508 * the descriptor contains string in UTF16 format
3509 * we need to convert to utf-8 so it can be displayed
3511 ret = utf16s_to_utf8s(uc_str->uc,
3512 uc_str->len - QUERY_DESC_HDR_SIZE,
3513 UTF16_BIG_ENDIAN, str, ascii_len);
3515 /* replace non-printable or non-ASCII characters with spaces */
3516 for (i = 0; i < ret; i++)
3517 str[i] = ufshcd_remove_non_printable(str[i]);
3522 str = kmemdup(uc_str, uc_str->len, GFP_KERNEL);
3536 * ufshcd_read_unit_desc_param - read the specified unit descriptor parameter
3537 * @hba: Pointer to adapter instance
3539 * @param_offset: offset of the parameter to read
3540 * @param_read_buf: pointer to buffer where parameter would be read
3541 * @param_size: sizeof(param_read_buf)
3543 * Return 0 in case of success, non-zero otherwise
3545 static inline int ufshcd_read_unit_desc_param(struct ufs_hba *hba,
3547 enum unit_desc_param param_offset,
3552 * Unit descriptors are only available for general purpose LUs (LUN id
3553 * from 0 to 7) and RPMB Well known LU.
3555 if (!ufs_is_valid_unit_desc_lun(&hba->dev_info, lun, param_offset))
3558 return ufshcd_read_desc_param(hba, QUERY_DESC_IDN_UNIT, lun,
3559 param_offset, param_read_buf, param_size);
3562 static int ufshcd_get_ref_clk_gating_wait(struct ufs_hba *hba)
3565 u32 gating_wait = UFSHCD_REF_CLK_GATING_WAIT_US;
3567 if (hba->dev_info.wspecversion >= 0x300) {
3568 err = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
3569 QUERY_ATTR_IDN_REF_CLK_GATING_WAIT_TIME, 0, 0,
3572 dev_err(hba->dev, "Failed reading bRefClkGatingWait. err = %d, use default %uus\n",
3575 if (gating_wait == 0) {
3576 gating_wait = UFSHCD_REF_CLK_GATING_WAIT_US;
3577 dev_err(hba->dev, "Undefined ref clk gating wait time, use default %uus\n",
3581 hba->dev_info.clk_gating_wait_us = gating_wait;
3588 * ufshcd_memory_alloc - allocate memory for host memory space data structures
3589 * @hba: per adapter instance
3591 * 1. Allocate DMA memory for Command Descriptor array
3592 * Each command descriptor consist of Command UPIU, Response UPIU and PRDT
3593 * 2. Allocate DMA memory for UTP Transfer Request Descriptor List (UTRDL).
3594 * 3. Allocate DMA memory for UTP Task Management Request Descriptor List
3596 * 4. Allocate memory for local reference block(lrb).
3598 * Returns 0 for success, non-zero in case of failure
3600 static int ufshcd_memory_alloc(struct ufs_hba *hba)
3602 size_t utmrdl_size, utrdl_size, ucdl_size;
3604 /* Allocate memory for UTP command descriptors */
3605 ucdl_size = (sizeof(struct utp_transfer_cmd_desc) * hba->nutrs);
3606 hba->ucdl_base_addr = dmam_alloc_coherent(hba->dev,
3608 &hba->ucdl_dma_addr,
3612 * UFSHCI requires UTP command descriptor to be 128 byte aligned.
3613 * make sure hba->ucdl_dma_addr is aligned to PAGE_SIZE
3614 * if hba->ucdl_dma_addr is aligned to PAGE_SIZE, then it will
3615 * be aligned to 128 bytes as well
3617 if (!hba->ucdl_base_addr ||
3618 WARN_ON(hba->ucdl_dma_addr & (PAGE_SIZE - 1))) {
3620 "Command Descriptor Memory allocation failed\n");
3625 * Allocate memory for UTP Transfer descriptors
3626 * UFSHCI requires 1024 byte alignment of UTRD
3628 utrdl_size = (sizeof(struct utp_transfer_req_desc) * hba->nutrs);
3629 hba->utrdl_base_addr = dmam_alloc_coherent(hba->dev,
3631 &hba->utrdl_dma_addr,
3633 if (!hba->utrdl_base_addr ||
3634 WARN_ON(hba->utrdl_dma_addr & (PAGE_SIZE - 1))) {
3636 "Transfer Descriptor Memory allocation failed\n");
3641 * Allocate memory for UTP Task Management descriptors
3642 * UFSHCI requires 1024 byte alignment of UTMRD
3644 utmrdl_size = sizeof(struct utp_task_req_desc) * hba->nutmrs;
3645 hba->utmrdl_base_addr = dmam_alloc_coherent(hba->dev,
3647 &hba->utmrdl_dma_addr,
3649 if (!hba->utmrdl_base_addr ||
3650 WARN_ON(hba->utmrdl_dma_addr & (PAGE_SIZE - 1))) {
3652 "Task Management Descriptor Memory allocation failed\n");
3656 /* Allocate memory for local reference block */
3657 hba->lrb = devm_kcalloc(hba->dev,
3658 hba->nutrs, sizeof(struct ufshcd_lrb),
3661 dev_err(hba->dev, "LRB Memory allocation failed\n");
3670 * ufshcd_host_memory_configure - configure local reference block with
3672 * @hba: per adapter instance
3674 * Configure Host memory space
3675 * 1. Update Corresponding UTRD.UCDBA and UTRD.UCDBAU with UCD DMA
3677 * 2. Update each UTRD with Response UPIU offset, Response UPIU length
3679 * 3. Save the corresponding addresses of UTRD, UCD.CMD, UCD.RSP and UCD.PRDT
3680 * into local reference block.
3682 static void ufshcd_host_memory_configure(struct ufs_hba *hba)
3684 struct utp_transfer_req_desc *utrdlp;
3685 dma_addr_t cmd_desc_dma_addr;
3686 dma_addr_t cmd_desc_element_addr;
3687 u16 response_offset;
3692 utrdlp = hba->utrdl_base_addr;
3695 offsetof(struct utp_transfer_cmd_desc, response_upiu);
3697 offsetof(struct utp_transfer_cmd_desc, prd_table);
3699 cmd_desc_size = sizeof(struct utp_transfer_cmd_desc);
3700 cmd_desc_dma_addr = hba->ucdl_dma_addr;
3702 for (i = 0; i < hba->nutrs; i++) {
3703 /* Configure UTRD with command descriptor base address */
3704 cmd_desc_element_addr =
3705 (cmd_desc_dma_addr + (cmd_desc_size * i));
3706 utrdlp[i].command_desc_base_addr_lo =
3707 cpu_to_le32(lower_32_bits(cmd_desc_element_addr));
3708 utrdlp[i].command_desc_base_addr_hi =
3709 cpu_to_le32(upper_32_bits(cmd_desc_element_addr));
3711 /* Response upiu and prdt offset should be in double words */
3712 if (hba->quirks & UFSHCD_QUIRK_PRDT_BYTE_GRAN) {
3713 utrdlp[i].response_upiu_offset =
3714 cpu_to_le16(response_offset);
3715 utrdlp[i].prd_table_offset =
3716 cpu_to_le16(prdt_offset);
3717 utrdlp[i].response_upiu_length =
3718 cpu_to_le16(ALIGNED_UPIU_SIZE);
3720 utrdlp[i].response_upiu_offset =
3721 cpu_to_le16(response_offset >> 2);
3722 utrdlp[i].prd_table_offset =
3723 cpu_to_le16(prdt_offset >> 2);
3724 utrdlp[i].response_upiu_length =
3725 cpu_to_le16(ALIGNED_UPIU_SIZE >> 2);
3728 ufshcd_init_lrb(hba, &hba->lrb[i], i);
3733 * ufshcd_dme_link_startup - Notify Unipro to perform link startup
3734 * @hba: per adapter instance
3736 * UIC_CMD_DME_LINK_STARTUP command must be issued to Unipro layer,
3737 * in order to initialize the Unipro link startup procedure.
3738 * Once the Unipro links are up, the device connected to the controller
3741 * Returns 0 on success, non-zero value on failure
3743 static int ufshcd_dme_link_startup(struct ufs_hba *hba)
3745 struct uic_command uic_cmd = {0};
3748 uic_cmd.command = UIC_CMD_DME_LINK_STARTUP;
3750 ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
3753 "dme-link-startup: error code %d\n", ret);
3757 * ufshcd_dme_reset - UIC command for DME_RESET
3758 * @hba: per adapter instance
3760 * DME_RESET command is issued in order to reset UniPro stack.
3761 * This function now deals with cold reset.
3763 * Returns 0 on success, non-zero value on failure
3765 static int ufshcd_dme_reset(struct ufs_hba *hba)
3767 struct uic_command uic_cmd = {0};
3770 uic_cmd.command = UIC_CMD_DME_RESET;
3772 ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
3775 "dme-reset: error code %d\n", ret);
3780 int ufshcd_dme_configure_adapt(struct ufs_hba *hba,
3786 if (agreed_gear != UFS_HS_G4)
3787 adapt_val = PA_NO_ADAPT;
3789 ret = ufshcd_dme_set(hba,
3790 UIC_ARG_MIB(PA_TXHSADAPTTYPE),
3794 EXPORT_SYMBOL_GPL(ufshcd_dme_configure_adapt);
3797 * ufshcd_dme_enable - UIC command for DME_ENABLE
3798 * @hba: per adapter instance
3800 * DME_ENABLE command is issued in order to enable UniPro stack.
3802 * Returns 0 on success, non-zero value on failure
3804 static int ufshcd_dme_enable(struct ufs_hba *hba)
3806 struct uic_command uic_cmd = {0};
3809 uic_cmd.command = UIC_CMD_DME_ENABLE;
3811 ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
3814 "dme-enable: error code %d\n", ret);
3819 static inline void ufshcd_add_delay_before_dme_cmd(struct ufs_hba *hba)
3821 #define MIN_DELAY_BEFORE_DME_CMDS_US 1000
3822 unsigned long min_sleep_time_us;
3824 if (!(hba->quirks & UFSHCD_QUIRK_DELAY_BEFORE_DME_CMDS))
3828 * last_dme_cmd_tstamp will be 0 only for 1st call to
3831 if (unlikely(!ktime_to_us(hba->last_dme_cmd_tstamp))) {
3832 min_sleep_time_us = MIN_DELAY_BEFORE_DME_CMDS_US;
3834 unsigned long delta =
3835 (unsigned long) ktime_to_us(
3836 ktime_sub(ktime_get(),
3837 hba->last_dme_cmd_tstamp));
3839 if (delta < MIN_DELAY_BEFORE_DME_CMDS_US)
3841 MIN_DELAY_BEFORE_DME_CMDS_US - delta;
3843 return; /* no more delay required */
3846 /* allow sleep for extra 50us if needed */
3847 usleep_range(min_sleep_time_us, min_sleep_time_us + 50);
3851 * ufshcd_dme_set_attr - UIC command for DME_SET, DME_PEER_SET
3852 * @hba: per adapter instance
3853 * @attr_sel: uic command argument1
3854 * @attr_set: attribute set type as uic command argument2
3855 * @mib_val: setting value as uic command argument3
3856 * @peer: indicate whether peer or local
3858 * Returns 0 on success, non-zero value on failure
3860 int ufshcd_dme_set_attr(struct ufs_hba *hba, u32 attr_sel,
3861 u8 attr_set, u32 mib_val, u8 peer)
3863 struct uic_command uic_cmd = {0};
3864 static const char *const action[] = {
3868 const char *set = action[!!peer];
3870 int retries = UFS_UIC_COMMAND_RETRIES;
3872 uic_cmd.command = peer ?
3873 UIC_CMD_DME_PEER_SET : UIC_CMD_DME_SET;
3874 uic_cmd.argument1 = attr_sel;
3875 uic_cmd.argument2 = UIC_ARG_ATTR_TYPE(attr_set);
3876 uic_cmd.argument3 = mib_val;
3879 /* for peer attributes we retry upon failure */
3880 ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
3882 dev_dbg(hba->dev, "%s: attr-id 0x%x val 0x%x error code %d\n",
3883 set, UIC_GET_ATTR_ID(attr_sel), mib_val, ret);
3884 } while (ret && peer && --retries);
3887 dev_err(hba->dev, "%s: attr-id 0x%x val 0x%x failed %d retries\n",
3888 set, UIC_GET_ATTR_ID(attr_sel), mib_val,
3889 UFS_UIC_COMMAND_RETRIES - retries);
3893 EXPORT_SYMBOL_GPL(ufshcd_dme_set_attr);
3896 * ufshcd_dme_get_attr - UIC command for DME_GET, DME_PEER_GET
3897 * @hba: per adapter instance
3898 * @attr_sel: uic command argument1
3899 * @mib_val: the value of the attribute as returned by the UIC command
3900 * @peer: indicate whether peer or local
3902 * Returns 0 on success, non-zero value on failure
3904 int ufshcd_dme_get_attr(struct ufs_hba *hba, u32 attr_sel,
3905 u32 *mib_val, u8 peer)
3907 struct uic_command uic_cmd = {0};
3908 static const char *const action[] = {
3912 const char *get = action[!!peer];
3914 int retries = UFS_UIC_COMMAND_RETRIES;
3915 struct ufs_pa_layer_attr orig_pwr_info;
3916 struct ufs_pa_layer_attr temp_pwr_info;
3917 bool pwr_mode_change = false;
3919 if (peer && (hba->quirks & UFSHCD_QUIRK_DME_PEER_ACCESS_AUTO_MODE)) {
3920 orig_pwr_info = hba->pwr_info;
3921 temp_pwr_info = orig_pwr_info;
3923 if (orig_pwr_info.pwr_tx == FAST_MODE ||
3924 orig_pwr_info.pwr_rx == FAST_MODE) {
3925 temp_pwr_info.pwr_tx = FASTAUTO_MODE;
3926 temp_pwr_info.pwr_rx = FASTAUTO_MODE;
3927 pwr_mode_change = true;
3928 } else if (orig_pwr_info.pwr_tx == SLOW_MODE ||
3929 orig_pwr_info.pwr_rx == SLOW_MODE) {
3930 temp_pwr_info.pwr_tx = SLOWAUTO_MODE;
3931 temp_pwr_info.pwr_rx = SLOWAUTO_MODE;
3932 pwr_mode_change = true;
3934 if (pwr_mode_change) {
3935 ret = ufshcd_change_power_mode(hba, &temp_pwr_info);
3941 uic_cmd.command = peer ?
3942 UIC_CMD_DME_PEER_GET : UIC_CMD_DME_GET;
3943 uic_cmd.argument1 = attr_sel;
3946 /* for peer attributes we retry upon failure */
3947 ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
3949 dev_dbg(hba->dev, "%s: attr-id 0x%x error code %d\n",
3950 get, UIC_GET_ATTR_ID(attr_sel), ret);
3951 } while (ret && peer && --retries);
3954 dev_err(hba->dev, "%s: attr-id 0x%x failed %d retries\n",
3955 get, UIC_GET_ATTR_ID(attr_sel),
3956 UFS_UIC_COMMAND_RETRIES - retries);
3958 if (mib_val && !ret)
3959 *mib_val = uic_cmd.argument3;
3961 if (peer && (hba->quirks & UFSHCD_QUIRK_DME_PEER_ACCESS_AUTO_MODE)
3963 ufshcd_change_power_mode(hba, &orig_pwr_info);
3967 EXPORT_SYMBOL_GPL(ufshcd_dme_get_attr);
3970 * ufshcd_uic_pwr_ctrl - executes UIC commands (which affects the link power
3971 * state) and waits for it to take effect.
3973 * @hba: per adapter instance
3974 * @cmd: UIC command to execute
3976 * DME operations like DME_SET(PA_PWRMODE), DME_HIBERNATE_ENTER &
3977 * DME_HIBERNATE_EXIT commands take some time to take its effect on both host
3978 * and device UniPro link and hence it's final completion would be indicated by
3979 * dedicated status bits in Interrupt Status register (UPMS, UHES, UHXS) in
3980 * addition to normal UIC command completion Status (UCCS). This function only
3981 * returns after the relevant status bits indicate the completion.
3983 * Returns 0 on success, non-zero value on failure
3985 static int ufshcd_uic_pwr_ctrl(struct ufs_hba *hba, struct uic_command *cmd)
3987 DECLARE_COMPLETION_ONSTACK(uic_async_done);
3988 unsigned long flags;
3991 bool reenable_intr = false;
3993 mutex_lock(&hba->uic_cmd_mutex);
3994 ufshcd_add_delay_before_dme_cmd(hba);
3996 spin_lock_irqsave(hba->host->host_lock, flags);
3997 if (ufshcd_is_link_broken(hba)) {
4001 hba->uic_async_done = &uic_async_done;
4002 if (ufshcd_readl(hba, REG_INTERRUPT_ENABLE) & UIC_COMMAND_COMPL) {
4003 ufshcd_disable_intr(hba, UIC_COMMAND_COMPL);
4005 * Make sure UIC command completion interrupt is disabled before
4006 * issuing UIC command.
4009 reenable_intr = true;
4011 ret = __ufshcd_send_uic_cmd(hba, cmd, false);
4012 spin_unlock_irqrestore(hba->host->host_lock, flags);
4015 "pwr ctrl cmd 0x%x with mode 0x%x uic error %d\n",
4016 cmd->command, cmd->argument3, ret);
4020 if (!wait_for_completion_timeout(hba->uic_async_done,
4021 msecs_to_jiffies(UIC_CMD_TIMEOUT))) {
4023 "pwr ctrl cmd 0x%x with mode 0x%x completion timeout\n",
4024 cmd->command, cmd->argument3);
4026 if (!cmd->cmd_active) {
4027 dev_err(hba->dev, "%s: Power Mode Change operation has been completed, go check UPMCRS\n",
4037 status = ufshcd_get_upmcrs(hba);
4038 if (status != PWR_LOCAL) {
4040 "pwr ctrl cmd 0x%x failed, host upmcrs:0x%x\n",
4041 cmd->command, status);
4042 ret = (status != PWR_OK) ? status : -1;
4046 ufshcd_print_host_state(hba);
4047 ufshcd_print_pwr_info(hba);
4048 ufshcd_print_evt_hist(hba);
4051 spin_lock_irqsave(hba->host->host_lock, flags);
4052 hba->active_uic_cmd = NULL;
4053 hba->uic_async_done = NULL;
4055 ufshcd_enable_intr(hba, UIC_COMMAND_COMPL);
4057 ufshcd_set_link_broken(hba);
4058 ufshcd_schedule_eh_work(hba);
4061 spin_unlock_irqrestore(hba->host->host_lock, flags);
4062 mutex_unlock(&hba->uic_cmd_mutex);
4068 * ufshcd_uic_change_pwr_mode - Perform the UIC power mode chage
4069 * using DME_SET primitives.
4070 * @hba: per adapter instance
4071 * @mode: powr mode value
4073 * Returns 0 on success, non-zero value on failure
4075 static int ufshcd_uic_change_pwr_mode(struct ufs_hba *hba, u8 mode)
4077 struct uic_command uic_cmd = {0};
4080 if (hba->quirks & UFSHCD_QUIRK_BROKEN_PA_RXHSUNTERMCAP) {
4081 ret = ufshcd_dme_set(hba,
4082 UIC_ARG_MIB_SEL(PA_RXHSUNTERMCAP, 0), 1);
4084 dev_err(hba->dev, "%s: failed to enable PA_RXHSUNTERMCAP ret %d\n",
4090 uic_cmd.command = UIC_CMD_DME_SET;
4091 uic_cmd.argument1 = UIC_ARG_MIB(PA_PWRMODE);
4092 uic_cmd.argument3 = mode;
4093 ufshcd_hold(hba, false);
4094 ret = ufshcd_uic_pwr_ctrl(hba, &uic_cmd);
4095 ufshcd_release(hba);
4101 int ufshcd_link_recovery(struct ufs_hba *hba)
4104 unsigned long flags;
4106 spin_lock_irqsave(hba->host->host_lock, flags);
4107 hba->ufshcd_state = UFSHCD_STATE_RESET;
4108 ufshcd_set_eh_in_progress(hba);
4109 spin_unlock_irqrestore(hba->host->host_lock, flags);
4111 /* Reset the attached device */
4112 ufshcd_device_reset(hba);
4114 ret = ufshcd_host_reset_and_restore(hba);
4116 spin_lock_irqsave(hba->host->host_lock, flags);
4118 hba->ufshcd_state = UFSHCD_STATE_ERROR;
4119 ufshcd_clear_eh_in_progress(hba);
4120 spin_unlock_irqrestore(hba->host->host_lock, flags);
4123 dev_err(hba->dev, "%s: link recovery failed, err %d",
4128 EXPORT_SYMBOL_GPL(ufshcd_link_recovery);
4130 int ufshcd_uic_hibern8_enter(struct ufs_hba *hba)
4133 struct uic_command uic_cmd = {0};
4134 ktime_t start = ktime_get();
4136 ufshcd_vops_hibern8_notify(hba, UIC_CMD_DME_HIBER_ENTER, PRE_CHANGE);
4138 uic_cmd.command = UIC_CMD_DME_HIBER_ENTER;
4139 ret = ufshcd_uic_pwr_ctrl(hba, &uic_cmd);
4140 trace_ufshcd_profile_hibern8(dev_name(hba->dev), "enter",
4141 ktime_to_us(ktime_sub(ktime_get(), start)), ret);
4144 dev_err(hba->dev, "%s: hibern8 enter failed. ret = %d\n",
4147 ufshcd_vops_hibern8_notify(hba, UIC_CMD_DME_HIBER_ENTER,
4152 EXPORT_SYMBOL_GPL(ufshcd_uic_hibern8_enter);
4154 int ufshcd_uic_hibern8_exit(struct ufs_hba *hba)
4156 struct uic_command uic_cmd = {0};
4158 ktime_t start = ktime_get();
4160 ufshcd_vops_hibern8_notify(hba, UIC_CMD_DME_HIBER_EXIT, PRE_CHANGE);
4162 uic_cmd.command = UIC_CMD_DME_HIBER_EXIT;
4163 ret = ufshcd_uic_pwr_ctrl(hba, &uic_cmd);
4164 trace_ufshcd_profile_hibern8(dev_name(hba->dev), "exit",
4165 ktime_to_us(ktime_sub(ktime_get(), start)), ret);
4168 dev_err(hba->dev, "%s: hibern8 exit failed. ret = %d\n",
4171 ufshcd_vops_hibern8_notify(hba, UIC_CMD_DME_HIBER_EXIT,
4173 hba->ufs_stats.last_hibern8_exit_tstamp = ktime_get();
4174 hba->ufs_stats.hibern8_exit_cnt++;
4179 EXPORT_SYMBOL_GPL(ufshcd_uic_hibern8_exit);
4181 void ufshcd_auto_hibern8_update(struct ufs_hba *hba, u32 ahit)
4183 unsigned long flags;
4184 bool update = false;
4186 if (!ufshcd_is_auto_hibern8_supported(hba))
4189 spin_lock_irqsave(hba->host->host_lock, flags);
4190 if (hba->ahit != ahit) {
4194 spin_unlock_irqrestore(hba->host->host_lock, flags);
4197 !pm_runtime_suspended(&hba->sdev_ufs_device->sdev_gendev)) {
4198 ufshcd_rpm_get_sync(hba);
4199 ufshcd_hold(hba, false);
4200 ufshcd_auto_hibern8_enable(hba);
4201 ufshcd_release(hba);
4202 ufshcd_rpm_put_sync(hba);
4205 EXPORT_SYMBOL_GPL(ufshcd_auto_hibern8_update);
4207 void ufshcd_auto_hibern8_enable(struct ufs_hba *hba)
4209 unsigned long flags;
4211 if (!ufshcd_is_auto_hibern8_supported(hba))
4214 spin_lock_irqsave(hba->host->host_lock, flags);
4215 ufshcd_writel(hba, hba->ahit, REG_AUTO_HIBERNATE_IDLE_TIMER);
4216 spin_unlock_irqrestore(hba->host->host_lock, flags);
4220 * ufshcd_init_pwr_info - setting the POR (power on reset)
4221 * values in hba power info
4222 * @hba: per-adapter instance
4224 static void ufshcd_init_pwr_info(struct ufs_hba *hba)
4226 hba->pwr_info.gear_rx = UFS_PWM_G1;
4227 hba->pwr_info.gear_tx = UFS_PWM_G1;
4228 hba->pwr_info.lane_rx = 1;
4229 hba->pwr_info.lane_tx = 1;
4230 hba->pwr_info.pwr_rx = SLOWAUTO_MODE;
4231 hba->pwr_info.pwr_tx = SLOWAUTO_MODE;
4232 hba->pwr_info.hs_rate = 0;
4236 * ufshcd_get_max_pwr_mode - reads the max power mode negotiated with device
4237 * @hba: per-adapter instance
4239 static int ufshcd_get_max_pwr_mode(struct ufs_hba *hba)
4241 struct ufs_pa_layer_attr *pwr_info = &hba->max_pwr_info.info;
4243 if (hba->max_pwr_info.is_valid)
4246 pwr_info->pwr_tx = FAST_MODE;
4247 pwr_info->pwr_rx = FAST_MODE;
4248 pwr_info->hs_rate = PA_HS_MODE_B;
4250 /* Get the connected lane count */
4251 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_CONNECTEDRXDATALANES),
4252 &pwr_info->lane_rx);
4253 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_CONNECTEDTXDATALANES),
4254 &pwr_info->lane_tx);
4256 if (!pwr_info->lane_rx || !pwr_info->lane_tx) {
4257 dev_err(hba->dev, "%s: invalid connected lanes value. rx=%d, tx=%d\n",
4265 * First, get the maximum gears of HS speed.
4266 * If a zero value, it means there is no HSGEAR capability.
4267 * Then, get the maximum gears of PWM speed.
4269 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_MAXRXHSGEAR), &pwr_info->gear_rx);
4270 if (!pwr_info->gear_rx) {
4271 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_MAXRXPWMGEAR),
4272 &pwr_info->gear_rx);
4273 if (!pwr_info->gear_rx) {
4274 dev_err(hba->dev, "%s: invalid max pwm rx gear read = %d\n",
4275 __func__, pwr_info->gear_rx);
4278 pwr_info->pwr_rx = SLOW_MODE;
4281 ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_MAXRXHSGEAR),
4282 &pwr_info->gear_tx);
4283 if (!pwr_info->gear_tx) {
4284 ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_MAXRXPWMGEAR),
4285 &pwr_info->gear_tx);
4286 if (!pwr_info->gear_tx) {
4287 dev_err(hba->dev, "%s: invalid max pwm tx gear read = %d\n",
4288 __func__, pwr_info->gear_tx);
4291 pwr_info->pwr_tx = SLOW_MODE;
4294 hba->max_pwr_info.is_valid = true;
4298 static int ufshcd_change_power_mode(struct ufs_hba *hba,
4299 struct ufs_pa_layer_attr *pwr_mode)
4303 /* if already configured to the requested pwr_mode */
4304 if (!hba->force_pmc &&
4305 pwr_mode->gear_rx == hba->pwr_info.gear_rx &&
4306 pwr_mode->gear_tx == hba->pwr_info.gear_tx &&
4307 pwr_mode->lane_rx == hba->pwr_info.lane_rx &&
4308 pwr_mode->lane_tx == hba->pwr_info.lane_tx &&
4309 pwr_mode->pwr_rx == hba->pwr_info.pwr_rx &&
4310 pwr_mode->pwr_tx == hba->pwr_info.pwr_tx &&
4311 pwr_mode->hs_rate == hba->pwr_info.hs_rate) {
4312 dev_dbg(hba->dev, "%s: power already configured\n", __func__);
4317 * Configure attributes for power mode change with below.
4318 * - PA_RXGEAR, PA_ACTIVERXDATALANES, PA_RXTERMINATION,
4319 * - PA_TXGEAR, PA_ACTIVETXDATALANES, PA_TXTERMINATION,
4322 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_RXGEAR), pwr_mode->gear_rx);
4323 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_ACTIVERXDATALANES),
4325 if (pwr_mode->pwr_rx == FASTAUTO_MODE ||
4326 pwr_mode->pwr_rx == FAST_MODE)
4327 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_RXTERMINATION), TRUE);
4329 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_RXTERMINATION), FALSE);
4331 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TXGEAR), pwr_mode->gear_tx);
4332 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_ACTIVETXDATALANES),
4334 if (pwr_mode->pwr_tx == FASTAUTO_MODE ||
4335 pwr_mode->pwr_tx == FAST_MODE)
4336 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TXTERMINATION), TRUE);
4338 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TXTERMINATION), FALSE);
4340 if (pwr_mode->pwr_rx == FASTAUTO_MODE ||
4341 pwr_mode->pwr_tx == FASTAUTO_MODE ||
4342 pwr_mode->pwr_rx == FAST_MODE ||
4343 pwr_mode->pwr_tx == FAST_MODE)
4344 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_HSSERIES),
4347 if (!(hba->quirks & UFSHCD_QUIRK_SKIP_DEF_UNIPRO_TIMEOUT_SETTING)) {
4348 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_PWRMODEUSERDATA0),
4349 DL_FC0ProtectionTimeOutVal_Default);
4350 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_PWRMODEUSERDATA1),
4351 DL_TC0ReplayTimeOutVal_Default);
4352 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_PWRMODEUSERDATA2),
4353 DL_AFC0ReqTimeOutVal_Default);
4354 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_PWRMODEUSERDATA3),
4355 DL_FC1ProtectionTimeOutVal_Default);
4356 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_PWRMODEUSERDATA4),
4357 DL_TC1ReplayTimeOutVal_Default);
4358 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_PWRMODEUSERDATA5),
4359 DL_AFC1ReqTimeOutVal_Default);
4361 ufshcd_dme_set(hba, UIC_ARG_MIB(DME_LocalFC0ProtectionTimeOutVal),
4362 DL_FC0ProtectionTimeOutVal_Default);
4363 ufshcd_dme_set(hba, UIC_ARG_MIB(DME_LocalTC0ReplayTimeOutVal),
4364 DL_TC0ReplayTimeOutVal_Default);
4365 ufshcd_dme_set(hba, UIC_ARG_MIB(DME_LocalAFC0ReqTimeOutVal),
4366 DL_AFC0ReqTimeOutVal_Default);
4369 ret = ufshcd_uic_change_pwr_mode(hba, pwr_mode->pwr_rx << 4
4370 | pwr_mode->pwr_tx);
4374 "%s: power mode change failed %d\n", __func__, ret);
4376 ufshcd_vops_pwr_change_notify(hba, POST_CHANGE, NULL,
4379 memcpy(&hba->pwr_info, pwr_mode,
4380 sizeof(struct ufs_pa_layer_attr));
4387 * ufshcd_config_pwr_mode - configure a new power mode
4388 * @hba: per-adapter instance
4389 * @desired_pwr_mode: desired power configuration
4391 int ufshcd_config_pwr_mode(struct ufs_hba *hba,
4392 struct ufs_pa_layer_attr *desired_pwr_mode)
4394 struct ufs_pa_layer_attr final_params = { 0 };
4397 ret = ufshcd_vops_pwr_change_notify(hba, PRE_CHANGE,
4398 desired_pwr_mode, &final_params);
4401 memcpy(&final_params, desired_pwr_mode, sizeof(final_params));
4403 ret = ufshcd_change_power_mode(hba, &final_params);
4407 EXPORT_SYMBOL_GPL(ufshcd_config_pwr_mode);
4410 * ufshcd_complete_dev_init() - checks device readiness
4411 * @hba: per-adapter instance
4413 * Set fDeviceInit flag and poll until device toggles it.
4415 static int ufshcd_complete_dev_init(struct ufs_hba *hba)
4418 bool flag_res = true;
4421 err = ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_SET_FLAG,
4422 QUERY_FLAG_IDN_FDEVICEINIT, 0, NULL);
4425 "%s setting fDeviceInit flag failed with error %d\n",
4430 /* Poll fDeviceInit flag to be cleared */
4431 timeout = ktime_add_ms(ktime_get(), FDEVICEINIT_COMPL_TIMEOUT);
4433 err = ufshcd_query_flag(hba, UPIU_QUERY_OPCODE_READ_FLAG,
4434 QUERY_FLAG_IDN_FDEVICEINIT, 0, &flag_res);
4437 usleep_range(5000, 10000);
4438 } while (ktime_before(ktime_get(), timeout));
4442 "%s reading fDeviceInit flag failed with error %d\n",
4444 } else if (flag_res) {
4446 "%s fDeviceInit was not cleared by the device\n",
4455 * ufshcd_make_hba_operational - Make UFS controller operational
4456 * @hba: per adapter instance
4458 * To bring UFS host controller to operational state,
4459 * 1. Enable required interrupts
4460 * 2. Configure interrupt aggregation
4461 * 3. Program UTRL and UTMRL base address
4462 * 4. Configure run-stop-registers
4464 * Returns 0 on success, non-zero value on failure
4466 int ufshcd_make_hba_operational(struct ufs_hba *hba)
4471 /* Enable required interrupts */
4472 ufshcd_enable_intr(hba, UFSHCD_ENABLE_INTRS);
4474 /* Configure interrupt aggregation */
4475 if (ufshcd_is_intr_aggr_allowed(hba))
4476 ufshcd_config_intr_aggr(hba, hba->nutrs - 1, INT_AGGR_DEF_TO);
4478 ufshcd_disable_intr_aggr(hba);
4480 /* Configure UTRL and UTMRL base address registers */
4481 ufshcd_writel(hba, lower_32_bits(hba->utrdl_dma_addr),
4482 REG_UTP_TRANSFER_REQ_LIST_BASE_L);
4483 ufshcd_writel(hba, upper_32_bits(hba->utrdl_dma_addr),
4484 REG_UTP_TRANSFER_REQ_LIST_BASE_H);
4485 ufshcd_writel(hba, lower_32_bits(hba->utmrdl_dma_addr),
4486 REG_UTP_TASK_REQ_LIST_BASE_L);
4487 ufshcd_writel(hba, upper_32_bits(hba->utmrdl_dma_addr),
4488 REG_UTP_TASK_REQ_LIST_BASE_H);
4491 * Make sure base address and interrupt setup are updated before
4492 * enabling the run/stop registers below.
4497 * UCRDY, UTMRLDY and UTRLRDY bits must be 1
4499 reg = ufshcd_readl(hba, REG_CONTROLLER_STATUS);
4500 if (!(ufshcd_get_lists_status(reg))) {
4501 ufshcd_enable_run_stop_reg(hba);
4504 "Host controller not ready to process requests");
4510 EXPORT_SYMBOL_GPL(ufshcd_make_hba_operational);
4513 * ufshcd_hba_stop - Send controller to reset state
4514 * @hba: per adapter instance
4516 void ufshcd_hba_stop(struct ufs_hba *hba)
4518 unsigned long flags;
4522 * Obtain the host lock to prevent that the controller is disabled
4523 * while the UFS interrupt handler is active on another CPU.
4525 spin_lock_irqsave(hba->host->host_lock, flags);
4526 ufshcd_writel(hba, CONTROLLER_DISABLE, REG_CONTROLLER_ENABLE);
4527 spin_unlock_irqrestore(hba->host->host_lock, flags);
4529 err = ufshcd_wait_for_register(hba, REG_CONTROLLER_ENABLE,
4530 CONTROLLER_ENABLE, CONTROLLER_DISABLE,
4533 dev_err(hba->dev, "%s: Controller disable failed\n", __func__);
4535 EXPORT_SYMBOL_GPL(ufshcd_hba_stop);
4538 * ufshcd_hba_execute_hce - initialize the controller
4539 * @hba: per adapter instance
4541 * The controller resets itself and controller firmware initialization
4542 * sequence kicks off. When controller is ready it will set
4543 * the Host Controller Enable bit to 1.
4545 * Returns 0 on success, non-zero value on failure
4547 static int ufshcd_hba_execute_hce(struct ufs_hba *hba)
4549 int retry_outer = 3;
4553 if (!ufshcd_is_hba_active(hba))
4554 /* change controller state to "reset state" */
4555 ufshcd_hba_stop(hba);
4557 /* UniPro link is disabled at this point */
4558 ufshcd_set_link_off(hba);
4560 ufshcd_vops_hce_enable_notify(hba, PRE_CHANGE);
4562 /* start controller initialization sequence */
4563 ufshcd_hba_start(hba);
4566 * To initialize a UFS host controller HCE bit must be set to 1.
4567 * During initialization the HCE bit value changes from 1->0->1.
4568 * When the host controller completes initialization sequence
4569 * it sets the value of HCE bit to 1. The same HCE bit is read back
4570 * to check if the controller has completed initialization sequence.
4571 * So without this delay the value HCE = 1, set in the previous
4572 * instruction might be read back.
4573 * This delay can be changed based on the controller.
4575 ufshcd_delay_us(hba->vps->hba_enable_delay_us, 100);
4577 /* wait for the host controller to complete initialization */
4579 while (ufshcd_is_hba_active(hba)) {
4584 "Controller enable failed\n");
4591 usleep_range(1000, 1100);
4594 /* enable UIC related interrupts */
4595 ufshcd_enable_intr(hba, UFSHCD_UIC_MASK);
4597 ufshcd_vops_hce_enable_notify(hba, POST_CHANGE);
4602 int ufshcd_hba_enable(struct ufs_hba *hba)
4606 if (hba->quirks & UFSHCI_QUIRK_BROKEN_HCE) {
4607 ufshcd_set_link_off(hba);
4608 ufshcd_vops_hce_enable_notify(hba, PRE_CHANGE);
4610 /* enable UIC related interrupts */
4611 ufshcd_enable_intr(hba, UFSHCD_UIC_MASK);
4612 ret = ufshcd_dme_reset(hba);
4614 ret = ufshcd_dme_enable(hba);
4616 ufshcd_vops_hce_enable_notify(hba, POST_CHANGE);
4619 "Host controller enable failed with non-hce\n");
4622 ret = ufshcd_hba_execute_hce(hba);
4627 EXPORT_SYMBOL_GPL(ufshcd_hba_enable);
4629 static int ufshcd_disable_tx_lcc(struct ufs_hba *hba, bool peer)
4631 int tx_lanes = 0, i, err = 0;
4634 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_CONNECTEDTXDATALANES),
4637 ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_CONNECTEDTXDATALANES),
4639 for (i = 0; i < tx_lanes; i++) {
4641 err = ufshcd_dme_set(hba,
4642 UIC_ARG_MIB_SEL(TX_LCC_ENABLE,
4643 UIC_ARG_MPHY_TX_GEN_SEL_INDEX(i)),
4646 err = ufshcd_dme_peer_set(hba,
4647 UIC_ARG_MIB_SEL(TX_LCC_ENABLE,
4648 UIC_ARG_MPHY_TX_GEN_SEL_INDEX(i)),
4651 dev_err(hba->dev, "%s: TX LCC Disable failed, peer = %d, lane = %d, err = %d",
4652 __func__, peer, i, err);
4660 static inline int ufshcd_disable_device_tx_lcc(struct ufs_hba *hba)
4662 return ufshcd_disable_tx_lcc(hba, true);
4665 void ufshcd_update_evt_hist(struct ufs_hba *hba, u32 id, u32 val)
4667 struct ufs_event_hist *e;
4669 if (id >= UFS_EVT_CNT)
4672 e = &hba->ufs_stats.event[id];
4673 e->val[e->pos] = val;
4674 e->tstamp[e->pos] = ktime_get();
4676 e->pos = (e->pos + 1) % UFS_EVENT_HIST_LENGTH;
4678 ufshcd_vops_event_notify(hba, id, &val);
4680 EXPORT_SYMBOL_GPL(ufshcd_update_evt_hist);
4683 * ufshcd_link_startup - Initialize unipro link startup
4684 * @hba: per adapter instance
4686 * Returns 0 for success, non-zero in case of failure
4688 static int ufshcd_link_startup(struct ufs_hba *hba)
4691 int retries = DME_LINKSTARTUP_RETRIES;
4692 bool link_startup_again = false;
4695 * If UFS device isn't active then we will have to issue link startup
4696 * 2 times to make sure the device state move to active.
4698 if (!ufshcd_is_ufs_dev_active(hba))
4699 link_startup_again = true;
4703 ufshcd_vops_link_startup_notify(hba, PRE_CHANGE);
4705 ret = ufshcd_dme_link_startup(hba);
4707 /* check if device is detected by inter-connect layer */
4708 if (!ret && !ufshcd_is_device_present(hba)) {
4709 ufshcd_update_evt_hist(hba,
4710 UFS_EVT_LINK_STARTUP_FAIL,
4712 dev_err(hba->dev, "%s: Device not present\n", __func__);
4718 * DME link lost indication is only received when link is up,
4719 * but we can't be sure if the link is up until link startup
4720 * succeeds. So reset the local Uni-Pro and try again.
4722 if (ret && ufshcd_hba_enable(hba)) {
4723 ufshcd_update_evt_hist(hba,
4724 UFS_EVT_LINK_STARTUP_FAIL,
4728 } while (ret && retries--);
4731 /* failed to get the link up... retire */
4732 ufshcd_update_evt_hist(hba,
4733 UFS_EVT_LINK_STARTUP_FAIL,
4738 if (link_startup_again) {
4739 link_startup_again = false;
4740 retries = DME_LINKSTARTUP_RETRIES;
4744 /* Mark that link is up in PWM-G1, 1-lane, SLOW-AUTO mode */
4745 ufshcd_init_pwr_info(hba);
4746 ufshcd_print_pwr_info(hba);
4748 if (hba->quirks & UFSHCD_QUIRK_BROKEN_LCC) {
4749 ret = ufshcd_disable_device_tx_lcc(hba);
4754 /* Include any host controller configuration via UIC commands */
4755 ret = ufshcd_vops_link_startup_notify(hba, POST_CHANGE);
4759 /* Clear UECPA once due to LINERESET has happened during LINK_STARTUP */
4760 ufshcd_readl(hba, REG_UIC_ERROR_CODE_PHY_ADAPTER_LAYER);
4761 ret = ufshcd_make_hba_operational(hba);
4764 dev_err(hba->dev, "link startup failed %d\n", ret);
4765 ufshcd_print_host_state(hba);
4766 ufshcd_print_pwr_info(hba);
4767 ufshcd_print_evt_hist(hba);
4773 * ufshcd_verify_dev_init() - Verify device initialization
4774 * @hba: per-adapter instance
4776 * Send NOP OUT UPIU and wait for NOP IN response to check whether the
4777 * device Transport Protocol (UTP) layer is ready after a reset.
4778 * If the UTP layer at the device side is not initialized, it may
4779 * not respond with NOP IN UPIU within timeout of %NOP_OUT_TIMEOUT
4780 * and we retry sending NOP OUT for %NOP_OUT_RETRIES iterations.
4782 static int ufshcd_verify_dev_init(struct ufs_hba *hba)
4787 ufshcd_hold(hba, false);
4788 mutex_lock(&hba->dev_cmd.lock);
4789 for (retries = NOP_OUT_RETRIES; retries > 0; retries--) {
4790 err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_NOP,
4791 hba->nop_out_timeout);
4793 if (!err || err == -ETIMEDOUT)
4796 dev_dbg(hba->dev, "%s: error %d retrying\n", __func__, err);
4798 mutex_unlock(&hba->dev_cmd.lock);
4799 ufshcd_release(hba);
4802 dev_err(hba->dev, "%s: NOP OUT failed %d\n", __func__, err);
4807 * ufshcd_set_queue_depth - set lun queue depth
4808 * @sdev: pointer to SCSI device
4810 * Read bLUQueueDepth value and activate scsi tagged command
4811 * queueing. For WLUN, queue depth is set to 1. For best-effort
4812 * cases (bLUQueueDepth = 0) the queue depth is set to a maximum
4813 * value that host can queue.
4815 static void ufshcd_set_queue_depth(struct scsi_device *sdev)
4819 struct ufs_hba *hba;
4821 hba = shost_priv(sdev->host);
4823 lun_qdepth = hba->nutrs;
4824 ret = ufshcd_read_unit_desc_param(hba,
4825 ufshcd_scsi_to_upiu_lun(sdev->lun),
4826 UNIT_DESC_PARAM_LU_Q_DEPTH,
4828 sizeof(lun_qdepth));
4830 /* Some WLUN doesn't support unit descriptor */
4831 if (ret == -EOPNOTSUPP)
4833 else if (!lun_qdepth)
4834 /* eventually, we can figure out the real queue depth */
4835 lun_qdepth = hba->nutrs;
4837 lun_qdepth = min_t(int, lun_qdepth, hba->nutrs);
4839 dev_dbg(hba->dev, "%s: activate tcq with queue depth %d\n",
4840 __func__, lun_qdepth);
4841 scsi_change_queue_depth(sdev, lun_qdepth);
4845 * ufshcd_get_lu_wp - returns the "b_lu_write_protect" from UNIT DESCRIPTOR
4846 * @hba: per-adapter instance
4847 * @lun: UFS device lun id
4848 * @b_lu_write_protect: pointer to buffer to hold the LU's write protect info
4850 * Returns 0 in case of success and b_lu_write_protect status would be returned
4851 * @b_lu_write_protect parameter.
4852 * Returns -ENOTSUPP if reading b_lu_write_protect is not supported.
4853 * Returns -EINVAL in case of invalid parameters passed to this function.
4855 static int ufshcd_get_lu_wp(struct ufs_hba *hba,
4857 u8 *b_lu_write_protect)
4861 if (!b_lu_write_protect)
4864 * According to UFS device spec, RPMB LU can't be write
4865 * protected so skip reading bLUWriteProtect parameter for
4866 * it. For other W-LUs, UNIT DESCRIPTOR is not available.
4868 else if (lun >= hba->dev_info.max_lu_supported)
4871 ret = ufshcd_read_unit_desc_param(hba,
4873 UNIT_DESC_PARAM_LU_WR_PROTECT,
4875 sizeof(*b_lu_write_protect));
4880 * ufshcd_get_lu_power_on_wp_status - get LU's power on write protect
4882 * @hba: per-adapter instance
4883 * @sdev: pointer to SCSI device
4886 static inline void ufshcd_get_lu_power_on_wp_status(struct ufs_hba *hba,
4887 struct scsi_device *sdev)
4889 if (hba->dev_info.f_power_on_wp_en &&
4890 !hba->dev_info.is_lu_power_on_wp) {
4891 u8 b_lu_write_protect;
4893 if (!ufshcd_get_lu_wp(hba, ufshcd_scsi_to_upiu_lun(sdev->lun),
4894 &b_lu_write_protect) &&
4895 (b_lu_write_protect == UFS_LU_POWER_ON_WP))
4896 hba->dev_info.is_lu_power_on_wp = true;
4901 * ufshcd_setup_links - associate link b/w device wlun and other luns
4902 * @sdev: pointer to SCSI device
4903 * @hba: pointer to ufs hba
4905 static void ufshcd_setup_links(struct ufs_hba *hba, struct scsi_device *sdev)
4907 struct device_link *link;
4910 * Device wlun is the supplier & rest of the luns are consumers.
4911 * This ensures that device wlun suspends after all other luns.
4913 if (hba->sdev_ufs_device) {
4914 link = device_link_add(&sdev->sdev_gendev,
4915 &hba->sdev_ufs_device->sdev_gendev,
4916 DL_FLAG_PM_RUNTIME | DL_FLAG_RPM_ACTIVE);
4918 dev_err(&sdev->sdev_gendev, "Failed establishing link - %s\n",
4919 dev_name(&hba->sdev_ufs_device->sdev_gendev));
4923 /* Ignore REPORT_LUN wlun probing */
4924 if (hba->luns_avail == 1) {
4925 ufshcd_rpm_put(hba);
4930 * Device wlun is probed. The assumption is that WLUNs are
4931 * scanned before other LUNs.
4938 * ufshcd_slave_alloc - handle initial SCSI device configurations
4939 * @sdev: pointer to SCSI device
4943 static int ufshcd_slave_alloc(struct scsi_device *sdev)
4945 struct ufs_hba *hba;
4947 hba = shost_priv(sdev->host);
4949 /* Mode sense(6) is not supported by UFS, so use Mode sense(10) */
4950 sdev->use_10_for_ms = 1;
4952 /* DBD field should be set to 1 in mode sense(10) */
4953 sdev->set_dbd_for_ms = 1;
4955 /* allow SCSI layer to restart the device in case of errors */
4956 sdev->allow_restart = 1;
4958 /* REPORT SUPPORTED OPERATION CODES is not supported */
4959 sdev->no_report_opcodes = 1;
4961 /* WRITE_SAME command is not supported */
4962 sdev->no_write_same = 1;
4964 ufshcd_set_queue_depth(sdev);
4966 ufshcd_get_lu_power_on_wp_status(hba, sdev);
4968 ufshcd_setup_links(hba, sdev);
4974 * ufshcd_change_queue_depth - change queue depth
4975 * @sdev: pointer to SCSI device
4976 * @depth: required depth to set
4978 * Change queue depth and make sure the max. limits are not crossed.
4980 static int ufshcd_change_queue_depth(struct scsi_device *sdev, int depth)
4982 return scsi_change_queue_depth(sdev, min(depth, sdev->host->can_queue));
4985 static void ufshcd_hpb_destroy(struct ufs_hba *hba, struct scsi_device *sdev)
4987 /* skip well-known LU */
4988 if ((sdev->lun >= UFS_UPIU_MAX_UNIT_NUM_ID) ||
4989 !(hba->dev_info.hpb_enabled) || !ufshpb_is_allowed(hba))
4992 ufshpb_destroy_lu(hba, sdev);
4995 static void ufshcd_hpb_configure(struct ufs_hba *hba, struct scsi_device *sdev)
4997 /* skip well-known LU */
4998 if ((sdev->lun >= UFS_UPIU_MAX_UNIT_NUM_ID) ||
4999 !(hba->dev_info.hpb_enabled) || !ufshpb_is_allowed(hba))
5002 ufshpb_init_hpb_lu(hba, sdev);
5006 * ufshcd_slave_configure - adjust SCSI device configurations
5007 * @sdev: pointer to SCSI device
5009 static int ufshcd_slave_configure(struct scsi_device *sdev)
5011 struct ufs_hba *hba = shost_priv(sdev->host);
5012 struct request_queue *q = sdev->request_queue;
5014 ufshcd_hpb_configure(hba, sdev);
5016 blk_queue_update_dma_pad(q, PRDT_DATA_BYTE_COUNT_PAD - 1);
5017 if (hba->quirks & UFSHCD_QUIRK_ALIGN_SG_WITH_PAGE_SIZE)
5018 blk_queue_update_dma_alignment(q, PAGE_SIZE - 1);
5020 * Block runtime-pm until all consumers are added.
5021 * Refer ufshcd_setup_links().
5023 if (is_device_wlun(sdev))
5024 pm_runtime_get_noresume(&sdev->sdev_gendev);
5025 else if (ufshcd_is_rpm_autosuspend_allowed(hba))
5026 sdev->rpm_autosuspend = 1;
5028 ufshcd_crypto_register(hba, q);
5034 * ufshcd_slave_destroy - remove SCSI device configurations
5035 * @sdev: pointer to SCSI device
5037 static void ufshcd_slave_destroy(struct scsi_device *sdev)
5039 struct ufs_hba *hba;
5040 unsigned long flags;
5042 hba = shost_priv(sdev->host);
5044 ufshcd_hpb_destroy(hba, sdev);
5046 /* Drop the reference as it won't be needed anymore */
5047 if (ufshcd_scsi_to_upiu_lun(sdev->lun) == UFS_UPIU_UFS_DEVICE_WLUN) {
5048 spin_lock_irqsave(hba->host->host_lock, flags);
5049 hba->sdev_ufs_device = NULL;
5050 spin_unlock_irqrestore(hba->host->host_lock, flags);
5051 } else if (hba->sdev_ufs_device) {
5052 struct device *supplier = NULL;
5054 /* Ensure UFS Device WLUN exists and does not disappear */
5055 spin_lock_irqsave(hba->host->host_lock, flags);
5056 if (hba->sdev_ufs_device) {
5057 supplier = &hba->sdev_ufs_device->sdev_gendev;
5058 get_device(supplier);
5060 spin_unlock_irqrestore(hba->host->host_lock, flags);
5064 * If a LUN fails to probe (e.g. absent BOOT WLUN), the
5065 * device will not have been registered but can still
5066 * have a device link holding a reference to the device.
5068 device_link_remove(&sdev->sdev_gendev, supplier);
5069 put_device(supplier);
5075 * ufshcd_scsi_cmd_status - Update SCSI command result based on SCSI status
5076 * @lrbp: pointer to local reference block of completed command
5077 * @scsi_status: SCSI command status
5079 * Returns value base on SCSI command status
5082 ufshcd_scsi_cmd_status(struct ufshcd_lrb *lrbp, int scsi_status)
5086 switch (scsi_status) {
5087 case SAM_STAT_CHECK_CONDITION:
5088 ufshcd_copy_sense_data(lrbp);
5091 result |= DID_OK << 16 | scsi_status;
5093 case SAM_STAT_TASK_SET_FULL:
5095 case SAM_STAT_TASK_ABORTED:
5096 ufshcd_copy_sense_data(lrbp);
5097 result |= scsi_status;
5100 result |= DID_ERROR << 16;
5102 } /* end of switch */
5108 * ufshcd_transfer_rsp_status - Get overall status of the response
5109 * @hba: per adapter instance
5110 * @lrbp: pointer to local reference block of completed command
5112 * Returns result of the command to notify SCSI midlayer
5115 ufshcd_transfer_rsp_status(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
5121 /* overall command status of utrd */
5122 ocs = ufshcd_get_tr_ocs(lrbp);
5124 if (hba->quirks & UFSHCD_QUIRK_BROKEN_OCS_FATAL_ERROR) {
5125 if (be32_to_cpu(lrbp->ucd_rsp_ptr->header.dword_1) &
5126 MASK_RSP_UPIU_RESULT)
5132 result = ufshcd_get_req_rsp(lrbp->ucd_rsp_ptr);
5133 hba->ufs_stats.last_hibern8_exit_tstamp = ktime_set(0, 0);
5135 case UPIU_TRANSACTION_RESPONSE:
5137 * get the response UPIU result to extract
5138 * the SCSI command status
5140 result = ufshcd_get_rsp_upiu_result(lrbp->ucd_rsp_ptr);
5143 * get the result based on SCSI status response
5144 * to notify the SCSI midlayer of the command status
5146 scsi_status = result & MASK_SCSI_STATUS;
5147 result = ufshcd_scsi_cmd_status(lrbp, scsi_status);
5150 * Currently we are only supporting BKOPs exception
5151 * events hence we can ignore BKOPs exception event
5152 * during power management callbacks. BKOPs exception
5153 * event is not expected to be raised in runtime suspend
5154 * callback as it allows the urgent bkops.
5155 * During system suspend, we are anyway forcefully
5156 * disabling the bkops and if urgent bkops is needed
5157 * it will be enabled on system resume. Long term
5158 * solution could be to abort the system suspend if
5159 * UFS device needs urgent BKOPs.
5161 if (!hba->pm_op_in_progress &&
5162 !ufshcd_eh_in_progress(hba) &&
5163 ufshcd_is_exception_event(lrbp->ucd_rsp_ptr))
5164 /* Flushed in suspend */
5165 schedule_work(&hba->eeh_work);
5167 if (scsi_status == SAM_STAT_GOOD)
5168 ufshpb_rsp_upiu(hba, lrbp);
5170 case UPIU_TRANSACTION_REJECT_UPIU:
5171 /* TODO: handle Reject UPIU Response */
5172 result = DID_ERROR << 16;
5174 "Reject UPIU not fully implemented\n");
5178 "Unexpected request response code = %x\n",
5180 result = DID_ERROR << 16;
5185 result |= DID_ABORT << 16;
5187 case OCS_INVALID_COMMAND_STATUS:
5188 result |= DID_REQUEUE << 16;
5190 case OCS_INVALID_CMD_TABLE_ATTR:
5191 case OCS_INVALID_PRDT_ATTR:
5192 case OCS_MISMATCH_DATA_BUF_SIZE:
5193 case OCS_MISMATCH_RESP_UPIU_SIZE:
5194 case OCS_PEER_COMM_FAILURE:
5195 case OCS_FATAL_ERROR:
5196 case OCS_DEVICE_FATAL_ERROR:
5197 case OCS_INVALID_CRYPTO_CONFIG:
5198 case OCS_GENERAL_CRYPTO_ERROR:
5200 result |= DID_ERROR << 16;
5202 "OCS error from controller = %x for tag %d\n",
5203 ocs, lrbp->task_tag);
5204 ufshcd_print_evt_hist(hba);
5205 ufshcd_print_host_state(hba);
5207 } /* end of switch */
5209 if ((host_byte(result) != DID_OK) &&
5210 (host_byte(result) != DID_REQUEUE) && !hba->silence_err_logs)
5211 ufshcd_print_trs(hba, 1 << lrbp->task_tag, true);
5215 static bool ufshcd_is_auto_hibern8_error(struct ufs_hba *hba,
5218 if (!ufshcd_is_auto_hibern8_supported(hba) ||
5219 !ufshcd_is_auto_hibern8_enabled(hba))
5222 if (!(intr_mask & UFSHCD_UIC_HIBERN8_MASK))
5225 if (hba->active_uic_cmd &&
5226 (hba->active_uic_cmd->command == UIC_CMD_DME_HIBER_ENTER ||
5227 hba->active_uic_cmd->command == UIC_CMD_DME_HIBER_EXIT))
5234 * ufshcd_uic_cmd_compl - handle completion of uic command
5235 * @hba: per adapter instance
5236 * @intr_status: interrupt status generated by the controller
5239 * IRQ_HANDLED - If interrupt is valid
5240 * IRQ_NONE - If invalid interrupt
5242 static irqreturn_t ufshcd_uic_cmd_compl(struct ufs_hba *hba, u32 intr_status)
5244 irqreturn_t retval = IRQ_NONE;
5246 spin_lock(hba->host->host_lock);
5247 if (ufshcd_is_auto_hibern8_error(hba, intr_status))
5248 hba->errors |= (UFSHCD_UIC_HIBERN8_MASK & intr_status);
5250 if ((intr_status & UIC_COMMAND_COMPL) && hba->active_uic_cmd) {
5251 hba->active_uic_cmd->argument2 |=
5252 ufshcd_get_uic_cmd_result(hba);
5253 hba->active_uic_cmd->argument3 =
5254 ufshcd_get_dme_attr_val(hba);
5255 if (!hba->uic_async_done)
5256 hba->active_uic_cmd->cmd_active = 0;
5257 complete(&hba->active_uic_cmd->done);
5258 retval = IRQ_HANDLED;
5261 if ((intr_status & UFSHCD_UIC_PWR_MASK) && hba->uic_async_done) {
5262 hba->active_uic_cmd->cmd_active = 0;
5263 complete(hba->uic_async_done);
5264 retval = IRQ_HANDLED;
5267 if (retval == IRQ_HANDLED)
5268 ufshcd_add_uic_command_trace(hba, hba->active_uic_cmd,
5270 spin_unlock(hba->host->host_lock);
5274 /* Release the resources allocated for processing a SCSI command. */
5275 static void ufshcd_release_scsi_cmd(struct ufs_hba *hba,
5276 struct ufshcd_lrb *lrbp)
5278 struct scsi_cmnd *cmd = lrbp->cmd;
5280 scsi_dma_unmap(cmd);
5281 lrbp->cmd = NULL; /* Mark the command as completed. */
5282 ufshcd_release(hba);
5283 ufshcd_clk_scaling_update_busy(hba);
5287 * __ufshcd_transfer_req_compl - handle SCSI and query command completion
5288 * @hba: per adapter instance
5289 * @completed_reqs: bitmask that indicates which requests to complete
5291 static void __ufshcd_transfer_req_compl(struct ufs_hba *hba,
5292 unsigned long completed_reqs)
5294 struct ufshcd_lrb *lrbp;
5295 struct scsi_cmnd *cmd;
5298 for_each_set_bit(index, &completed_reqs, hba->nutrs) {
5299 lrbp = &hba->lrb[index];
5300 lrbp->compl_time_stamp = ktime_get();
5303 if (unlikely(ufshcd_should_inform_monitor(hba, lrbp)))
5304 ufshcd_update_monitor(hba, lrbp);
5305 ufshcd_add_command_trace(hba, index, UFS_CMD_COMP);
5306 cmd->result = ufshcd_transfer_rsp_status(hba, lrbp);
5307 ufshcd_release_scsi_cmd(hba, lrbp);
5308 /* Do not touch lrbp after scsi done */
5310 } else if (lrbp->command_type == UTP_CMD_TYPE_DEV_MANAGE ||
5311 lrbp->command_type == UTP_CMD_TYPE_UFS_STORAGE) {
5312 if (hba->dev_cmd.complete) {
5313 ufshcd_add_command_trace(hba, index,
5315 complete(hba->dev_cmd.complete);
5316 ufshcd_clk_scaling_update_busy(hba);
5323 * Returns > 0 if one or more commands have been completed or 0 if no
5324 * requests have been completed.
5326 static int ufshcd_poll(struct Scsi_Host *shost, unsigned int queue_num)
5328 struct ufs_hba *hba = shost_priv(shost);
5329 unsigned long completed_reqs, flags;
5332 spin_lock_irqsave(&hba->outstanding_lock, flags);
5333 tr_doorbell = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
5334 completed_reqs = ~tr_doorbell & hba->outstanding_reqs;
5335 WARN_ONCE(completed_reqs & ~hba->outstanding_reqs,
5336 "completed: %#lx; outstanding: %#lx\n", completed_reqs,
5337 hba->outstanding_reqs);
5338 hba->outstanding_reqs &= ~completed_reqs;
5339 spin_unlock_irqrestore(&hba->outstanding_lock, flags);
5342 __ufshcd_transfer_req_compl(hba, completed_reqs);
5344 return completed_reqs;
5348 * ufshcd_transfer_req_compl - handle SCSI and query command completion
5349 * @hba: per adapter instance
5352 * IRQ_HANDLED - If interrupt is valid
5353 * IRQ_NONE - If invalid interrupt
5355 static irqreturn_t ufshcd_transfer_req_compl(struct ufs_hba *hba)
5357 /* Resetting interrupt aggregation counters first and reading the
5358 * DOOR_BELL afterward allows us to handle all the completed requests.
5359 * In order to prevent other interrupts starvation the DB is read once
5360 * after reset. The down side of this solution is the possibility of
5361 * false interrupt if device completes another request after resetting
5362 * aggregation and before reading the DB.
5364 if (ufshcd_is_intr_aggr_allowed(hba) &&
5365 !(hba->quirks & UFSHCI_QUIRK_SKIP_RESET_INTR_AGGR))
5366 ufshcd_reset_intr_aggr(hba);
5368 if (ufs_fail_completion())
5372 * Ignore the ufshcd_poll() return value and return IRQ_HANDLED since we
5373 * do not want polling to trigger spurious interrupt complaints.
5375 ufshcd_poll(hba->host, 0);
5380 int __ufshcd_write_ee_control(struct ufs_hba *hba, u32 ee_ctrl_mask)
5382 return ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_WRITE_ATTR,
5383 QUERY_ATTR_IDN_EE_CONTROL, 0, 0,
5387 int ufshcd_write_ee_control(struct ufs_hba *hba)
5391 mutex_lock(&hba->ee_ctrl_mutex);
5392 err = __ufshcd_write_ee_control(hba, hba->ee_ctrl_mask);
5393 mutex_unlock(&hba->ee_ctrl_mutex);
5395 dev_err(hba->dev, "%s: failed to write ee control %d\n",
5400 int ufshcd_update_ee_control(struct ufs_hba *hba, u16 *mask, u16 *other_mask,
5403 u16 new_mask, ee_ctrl_mask;
5406 mutex_lock(&hba->ee_ctrl_mutex);
5407 new_mask = (*mask & ~clr) | set;
5408 ee_ctrl_mask = new_mask | *other_mask;
5409 if (ee_ctrl_mask != hba->ee_ctrl_mask)
5410 err = __ufshcd_write_ee_control(hba, ee_ctrl_mask);
5411 /* Still need to update 'mask' even if 'ee_ctrl_mask' was unchanged */
5413 hba->ee_ctrl_mask = ee_ctrl_mask;
5416 mutex_unlock(&hba->ee_ctrl_mutex);
5421 * ufshcd_disable_ee - disable exception event
5422 * @hba: per-adapter instance
5423 * @mask: exception event to disable
5425 * Disables exception event in the device so that the EVENT_ALERT
5428 * Returns zero on success, non-zero error value on failure.
5430 static inline int ufshcd_disable_ee(struct ufs_hba *hba, u16 mask)
5432 return ufshcd_update_ee_drv_mask(hba, 0, mask);
5436 * ufshcd_enable_ee - enable exception event
5437 * @hba: per-adapter instance
5438 * @mask: exception event to enable
5440 * Enable corresponding exception event in the device to allow
5441 * device to alert host in critical scenarios.
5443 * Returns zero on success, non-zero error value on failure.
5445 static inline int ufshcd_enable_ee(struct ufs_hba *hba, u16 mask)
5447 return ufshcd_update_ee_drv_mask(hba, mask, 0);
5451 * ufshcd_enable_auto_bkops - Allow device managed BKOPS
5452 * @hba: per-adapter instance
5454 * Allow device to manage background operations on its own. Enabling
5455 * this might lead to inconsistent latencies during normal data transfers
5456 * as the device is allowed to manage its own way of handling background
5459 * Returns zero on success, non-zero on failure.
5461 static int ufshcd_enable_auto_bkops(struct ufs_hba *hba)
5465 if (hba->auto_bkops_enabled)
5468 err = ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_SET_FLAG,
5469 QUERY_FLAG_IDN_BKOPS_EN, 0, NULL);
5471 dev_err(hba->dev, "%s: failed to enable bkops %d\n",
5476 hba->auto_bkops_enabled = true;
5477 trace_ufshcd_auto_bkops_state(dev_name(hba->dev), "Enabled");
5479 /* No need of URGENT_BKOPS exception from the device */
5480 err = ufshcd_disable_ee(hba, MASK_EE_URGENT_BKOPS);
5482 dev_err(hba->dev, "%s: failed to disable exception event %d\n",
5489 * ufshcd_disable_auto_bkops - block device in doing background operations
5490 * @hba: per-adapter instance
5492 * Disabling background operations improves command response latency but
5493 * has drawback of device moving into critical state where the device is
5494 * not-operable. Make sure to call ufshcd_enable_auto_bkops() whenever the
5495 * host is idle so that BKOPS are managed effectively without any negative
5498 * Returns zero on success, non-zero on failure.
5500 static int ufshcd_disable_auto_bkops(struct ufs_hba *hba)
5504 if (!hba->auto_bkops_enabled)
5508 * If host assisted BKOPs is to be enabled, make sure
5509 * urgent bkops exception is allowed.
5511 err = ufshcd_enable_ee(hba, MASK_EE_URGENT_BKOPS);
5513 dev_err(hba->dev, "%s: failed to enable exception event %d\n",
5518 err = ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_CLEAR_FLAG,
5519 QUERY_FLAG_IDN_BKOPS_EN, 0, NULL);
5521 dev_err(hba->dev, "%s: failed to disable bkops %d\n",
5523 ufshcd_disable_ee(hba, MASK_EE_URGENT_BKOPS);
5527 hba->auto_bkops_enabled = false;
5528 trace_ufshcd_auto_bkops_state(dev_name(hba->dev), "Disabled");
5529 hba->is_urgent_bkops_lvl_checked = false;
5535 * ufshcd_force_reset_auto_bkops - force reset auto bkops state
5536 * @hba: per adapter instance
5538 * After a device reset the device may toggle the BKOPS_EN flag
5539 * to default value. The s/w tracking variables should be updated
5540 * as well. This function would change the auto-bkops state based on
5541 * UFSHCD_CAP_KEEP_AUTO_BKOPS_ENABLED_EXCEPT_SUSPEND.
5543 static void ufshcd_force_reset_auto_bkops(struct ufs_hba *hba)
5545 if (ufshcd_keep_autobkops_enabled_except_suspend(hba)) {
5546 hba->auto_bkops_enabled = false;
5547 hba->ee_ctrl_mask |= MASK_EE_URGENT_BKOPS;
5548 ufshcd_enable_auto_bkops(hba);
5550 hba->auto_bkops_enabled = true;
5551 hba->ee_ctrl_mask &= ~MASK_EE_URGENT_BKOPS;
5552 ufshcd_disable_auto_bkops(hba);
5554 hba->urgent_bkops_lvl = BKOPS_STATUS_PERF_IMPACT;
5555 hba->is_urgent_bkops_lvl_checked = false;
5558 static inline int ufshcd_get_bkops_status(struct ufs_hba *hba, u32 *status)
5560 return ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
5561 QUERY_ATTR_IDN_BKOPS_STATUS, 0, 0, status);
5565 * ufshcd_bkops_ctrl - control the auto bkops based on current bkops status
5566 * @hba: per-adapter instance
5567 * @status: bkops_status value
5569 * Read the bkops_status from the UFS device and Enable fBackgroundOpsEn
5570 * flag in the device to permit background operations if the device
5571 * bkops_status is greater than or equal to "status" argument passed to
5572 * this function, disable otherwise.
5574 * Returns 0 for success, non-zero in case of failure.
5576 * NOTE: Caller of this function can check the "hba->auto_bkops_enabled" flag
5577 * to know whether auto bkops is enabled or disabled after this function
5578 * returns control to it.
5580 static int ufshcd_bkops_ctrl(struct ufs_hba *hba,
5581 enum bkops_status status)
5584 u32 curr_status = 0;
5586 err = ufshcd_get_bkops_status(hba, &curr_status);
5588 dev_err(hba->dev, "%s: failed to get BKOPS status %d\n",
5591 } else if (curr_status > BKOPS_STATUS_MAX) {
5592 dev_err(hba->dev, "%s: invalid BKOPS status %d\n",
5593 __func__, curr_status);
5598 if (curr_status >= status)
5599 err = ufshcd_enable_auto_bkops(hba);
5601 err = ufshcd_disable_auto_bkops(hba);
5607 * ufshcd_urgent_bkops - handle urgent bkops exception event
5608 * @hba: per-adapter instance
5610 * Enable fBackgroundOpsEn flag in the device to permit background
5613 * If BKOPs is enabled, this function returns 0, 1 if the bkops in not enabled
5614 * and negative error value for any other failure.
5616 static int ufshcd_urgent_bkops(struct ufs_hba *hba)
5618 return ufshcd_bkops_ctrl(hba, hba->urgent_bkops_lvl);
5621 static inline int ufshcd_get_ee_status(struct ufs_hba *hba, u32 *status)
5623 return ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
5624 QUERY_ATTR_IDN_EE_STATUS, 0, 0, status);
5627 static void ufshcd_bkops_exception_event_handler(struct ufs_hba *hba)
5630 u32 curr_status = 0;
5632 if (hba->is_urgent_bkops_lvl_checked)
5633 goto enable_auto_bkops;
5635 err = ufshcd_get_bkops_status(hba, &curr_status);
5637 dev_err(hba->dev, "%s: failed to get BKOPS status %d\n",
5643 * We are seeing that some devices are raising the urgent bkops
5644 * exception events even when BKOPS status doesn't indicate performace
5645 * impacted or critical. Handle these device by determining their urgent
5646 * bkops status at runtime.
5648 if (curr_status < BKOPS_STATUS_PERF_IMPACT) {
5649 dev_err(hba->dev, "%s: device raised urgent BKOPS exception for bkops status %d\n",
5650 __func__, curr_status);
5651 /* update the current status as the urgent bkops level */
5652 hba->urgent_bkops_lvl = curr_status;
5653 hba->is_urgent_bkops_lvl_checked = true;
5657 err = ufshcd_enable_auto_bkops(hba);
5660 dev_err(hba->dev, "%s: failed to handle urgent bkops %d\n",
5664 static void ufshcd_temp_exception_event_handler(struct ufs_hba *hba, u16 status)
5668 if (ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
5669 QUERY_ATTR_IDN_CASE_ROUGH_TEMP, 0, 0, &value))
5672 dev_info(hba->dev, "exception Tcase %d\n", value - 80);
5674 ufs_hwmon_notify_event(hba, status & MASK_EE_URGENT_TEMP);
5677 * A placeholder for the platform vendors to add whatever additional
5682 static int __ufshcd_wb_toggle(struct ufs_hba *hba, bool set, enum flag_idn idn)
5685 enum query_opcode opcode = set ? UPIU_QUERY_OPCODE_SET_FLAG :
5686 UPIU_QUERY_OPCODE_CLEAR_FLAG;
5688 index = ufshcd_wb_get_query_index(hba);
5689 return ufshcd_query_flag_retry(hba, opcode, idn, index, NULL);
5692 int ufshcd_wb_toggle(struct ufs_hba *hba, bool enable)
5696 if (!ufshcd_is_wb_allowed(hba))
5699 if (!(enable ^ hba->dev_info.wb_enabled))
5702 ret = __ufshcd_wb_toggle(hba, enable, QUERY_FLAG_IDN_WB_EN);
5704 dev_err(hba->dev, "%s Write Booster %s failed %d\n",
5705 __func__, enable ? "enable" : "disable", ret);
5709 hba->dev_info.wb_enabled = enable;
5710 dev_info(hba->dev, "%s Write Booster %s\n",
5711 __func__, enable ? "enabled" : "disabled");
5716 static void ufshcd_wb_toggle_flush_during_h8(struct ufs_hba *hba, bool set)
5720 ret = __ufshcd_wb_toggle(hba, set,
5721 QUERY_FLAG_IDN_WB_BUFF_FLUSH_DURING_HIBERN8);
5723 dev_err(hba->dev, "%s: WB-Buf Flush during H8 %s failed: %d\n",
5724 __func__, set ? "enable" : "disable", ret);
5727 dev_dbg(hba->dev, "%s WB-Buf Flush during H8 %s\n",
5728 __func__, set ? "enabled" : "disabled");
5731 static inline void ufshcd_wb_toggle_flush(struct ufs_hba *hba, bool enable)
5735 if (!ufshcd_is_wb_allowed(hba) ||
5736 hba->dev_info.wb_buf_flush_enabled == enable)
5739 ret = __ufshcd_wb_toggle(hba, enable, QUERY_FLAG_IDN_WB_BUFF_FLUSH_EN);
5741 dev_err(hba->dev, "%s WB-Buf Flush %s failed %d\n", __func__,
5742 enable ? "enable" : "disable", ret);
5746 hba->dev_info.wb_buf_flush_enabled = enable;
5748 dev_dbg(hba->dev, "%s WB-Buf Flush %s\n",
5749 __func__, enable ? "enabled" : "disabled");
5752 static bool ufshcd_wb_presrv_usrspc_keep_vcc_on(struct ufs_hba *hba,
5759 index = ufshcd_wb_get_query_index(hba);
5760 ret = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
5761 QUERY_ATTR_IDN_CURR_WB_BUFF_SIZE,
5762 index, 0, &cur_buf);
5764 dev_err(hba->dev, "%s dCurWriteBoosterBufferSize read failed %d\n",
5770 dev_info(hba->dev, "dCurWBBuf: %d WB disabled until free-space is available\n",
5774 /* Let it continue to flush when available buffer exceeds threshold */
5775 if (avail_buf < hba->vps->wb_flush_threshold)
5781 static bool ufshcd_wb_need_flush(struct ufs_hba *hba)
5787 if (!ufshcd_is_wb_allowed(hba))
5790 * The ufs device needs the vcc to be ON to flush.
5791 * With user-space reduction enabled, it's enough to enable flush
5792 * by checking only the available buffer. The threshold
5793 * defined here is > 90% full.
5794 * With user-space preserved enabled, the current-buffer
5795 * should be checked too because the wb buffer size can reduce
5796 * when disk tends to be full. This info is provided by current
5797 * buffer (dCurrentWriteBoosterBufferSize). There's no point in
5798 * keeping vcc on when current buffer is empty.
5800 index = ufshcd_wb_get_query_index(hba);
5801 ret = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
5802 QUERY_ATTR_IDN_AVAIL_WB_BUFF_SIZE,
5803 index, 0, &avail_buf);
5805 dev_warn(hba->dev, "%s dAvailableWriteBoosterBufferSize read failed %d\n",
5810 if (!hba->dev_info.b_presrv_uspc_en) {
5811 if (avail_buf <= UFS_WB_BUF_REMAIN_PERCENT(10))
5816 return ufshcd_wb_presrv_usrspc_keep_vcc_on(hba, avail_buf);
5819 static void ufshcd_rpm_dev_flush_recheck_work(struct work_struct *work)
5821 struct ufs_hba *hba = container_of(to_delayed_work(work),
5823 rpm_dev_flush_recheck_work);
5825 * To prevent unnecessary VCC power drain after device finishes
5826 * WriteBooster buffer flush or Auto BKOPs, force runtime resume
5827 * after a certain delay to recheck the threshold by next runtime
5830 ufshcd_rpm_get_sync(hba);
5831 ufshcd_rpm_put_sync(hba);
5835 * ufshcd_exception_event_handler - handle exceptions raised by device
5836 * @work: pointer to work data
5838 * Read bExceptionEventStatus attribute from the device and handle the
5839 * exception event accordingly.
5841 static void ufshcd_exception_event_handler(struct work_struct *work)
5843 struct ufs_hba *hba;
5846 hba = container_of(work, struct ufs_hba, eeh_work);
5848 ufshcd_scsi_block_requests(hba);
5849 err = ufshcd_get_ee_status(hba, &status);
5851 dev_err(hba->dev, "%s: failed to get exception status %d\n",
5856 trace_ufshcd_exception_event(dev_name(hba->dev), status);
5858 if (status & hba->ee_drv_mask & MASK_EE_URGENT_BKOPS)
5859 ufshcd_bkops_exception_event_handler(hba);
5861 if (status & hba->ee_drv_mask & MASK_EE_URGENT_TEMP)
5862 ufshcd_temp_exception_event_handler(hba, status);
5864 ufs_debugfs_exception_event(hba, status);
5866 ufshcd_scsi_unblock_requests(hba);
5869 /* Complete requests that have door-bell cleared */
5870 static void ufshcd_complete_requests(struct ufs_hba *hba)
5872 ufshcd_transfer_req_compl(hba);
5873 ufshcd_tmc_handler(hba);
5877 * ufshcd_quirk_dl_nac_errors - This function checks if error handling is
5878 * to recover from the DL NAC errors or not.
5879 * @hba: per-adapter instance
5881 * Returns true if error handling is required, false otherwise
5883 static bool ufshcd_quirk_dl_nac_errors(struct ufs_hba *hba)
5885 unsigned long flags;
5886 bool err_handling = true;
5888 spin_lock_irqsave(hba->host->host_lock, flags);
5890 * UFS_DEVICE_QUIRK_RECOVERY_FROM_DL_NAC_ERRORS only workaround the
5891 * device fatal error and/or DL NAC & REPLAY timeout errors.
5893 if (hba->saved_err & (CONTROLLER_FATAL_ERROR | SYSTEM_BUS_FATAL_ERROR))
5896 if ((hba->saved_err & DEVICE_FATAL_ERROR) ||
5897 ((hba->saved_err & UIC_ERROR) &&
5898 (hba->saved_uic_err & UFSHCD_UIC_DL_TCx_REPLAY_ERROR)))
5901 if ((hba->saved_err & UIC_ERROR) &&
5902 (hba->saved_uic_err & UFSHCD_UIC_DL_NAC_RECEIVED_ERROR)) {
5905 * wait for 50ms to see if we can get any other errors or not.
5907 spin_unlock_irqrestore(hba->host->host_lock, flags);
5909 spin_lock_irqsave(hba->host->host_lock, flags);
5912 * now check if we have got any other severe errors other than
5915 if ((hba->saved_err & INT_FATAL_ERRORS) ||
5916 ((hba->saved_err & UIC_ERROR) &&
5917 (hba->saved_uic_err & ~UFSHCD_UIC_DL_NAC_RECEIVED_ERROR)))
5921 * As DL NAC is the only error received so far, send out NOP
5922 * command to confirm if link is still active or not.
5923 * - If we don't get any response then do error recovery.
5924 * - If we get response then clear the DL NAC error bit.
5927 spin_unlock_irqrestore(hba->host->host_lock, flags);
5928 err = ufshcd_verify_dev_init(hba);
5929 spin_lock_irqsave(hba->host->host_lock, flags);
5934 /* Link seems to be alive hence ignore the DL NAC errors */
5935 if (hba->saved_uic_err == UFSHCD_UIC_DL_NAC_RECEIVED_ERROR)
5936 hba->saved_err &= ~UIC_ERROR;
5937 /* clear NAC error */
5938 hba->saved_uic_err &= ~UFSHCD_UIC_DL_NAC_RECEIVED_ERROR;
5939 if (!hba->saved_uic_err)
5940 err_handling = false;
5943 spin_unlock_irqrestore(hba->host->host_lock, flags);
5944 return err_handling;
5947 /* host lock must be held before calling this func */
5948 static inline bool ufshcd_is_saved_err_fatal(struct ufs_hba *hba)
5950 return (hba->saved_uic_err & UFSHCD_UIC_DL_PA_INIT_ERROR) ||
5951 (hba->saved_err & (INT_FATAL_ERRORS | UFSHCD_UIC_HIBERN8_MASK));
5954 void ufshcd_schedule_eh_work(struct ufs_hba *hba)
5956 lockdep_assert_held(hba->host->host_lock);
5958 /* handle fatal errors only when link is not in error state */
5959 if (hba->ufshcd_state != UFSHCD_STATE_ERROR) {
5960 if (hba->force_reset || ufshcd_is_link_broken(hba) ||
5961 ufshcd_is_saved_err_fatal(hba))
5962 hba->ufshcd_state = UFSHCD_STATE_EH_SCHEDULED_FATAL;
5964 hba->ufshcd_state = UFSHCD_STATE_EH_SCHEDULED_NON_FATAL;
5965 queue_work(hba->eh_wq, &hba->eh_work);
5969 static void ufshcd_clk_scaling_allow(struct ufs_hba *hba, bool allow)
5971 down_write(&hba->clk_scaling_lock);
5972 hba->clk_scaling.is_allowed = allow;
5973 up_write(&hba->clk_scaling_lock);
5976 static void ufshcd_clk_scaling_suspend(struct ufs_hba *hba, bool suspend)
5979 if (hba->clk_scaling.is_enabled)
5980 ufshcd_suspend_clkscaling(hba);
5981 ufshcd_clk_scaling_allow(hba, false);
5983 ufshcd_clk_scaling_allow(hba, true);
5984 if (hba->clk_scaling.is_enabled)
5985 ufshcd_resume_clkscaling(hba);
5989 static void ufshcd_err_handling_prepare(struct ufs_hba *hba)
5991 ufshcd_rpm_get_sync(hba);
5992 if (pm_runtime_status_suspended(&hba->sdev_ufs_device->sdev_gendev) ||
5993 hba->is_sys_suspended) {
5994 enum ufs_pm_op pm_op;
5997 * Don't assume anything of resume, if
5998 * resume fails, irq and clocks can be OFF, and powers
5999 * can be OFF or in LPM.
6001 ufshcd_setup_hba_vreg(hba, true);
6002 ufshcd_enable_irq(hba);
6003 ufshcd_setup_vreg(hba, true);
6004 ufshcd_config_vreg_hpm(hba, hba->vreg_info.vccq);
6005 ufshcd_config_vreg_hpm(hba, hba->vreg_info.vccq2);
6006 ufshcd_hold(hba, false);
6007 if (!ufshcd_is_clkgating_allowed(hba))
6008 ufshcd_setup_clocks(hba, true);
6009 ufshcd_release(hba);
6010 pm_op = hba->is_sys_suspended ? UFS_SYSTEM_PM : UFS_RUNTIME_PM;
6011 ufshcd_vops_resume(hba, pm_op);
6013 ufshcd_hold(hba, false);
6014 if (ufshcd_is_clkscaling_supported(hba) &&
6015 hba->clk_scaling.is_enabled)
6016 ufshcd_suspend_clkscaling(hba);
6017 ufshcd_clk_scaling_allow(hba, false);
6019 ufshcd_scsi_block_requests(hba);
6020 /* Drain ufshcd_queuecommand() */
6022 cancel_work_sync(&hba->eeh_work);
6025 static void ufshcd_err_handling_unprepare(struct ufs_hba *hba)
6027 ufshcd_scsi_unblock_requests(hba);
6028 ufshcd_release(hba);
6029 if (ufshcd_is_clkscaling_supported(hba))
6030 ufshcd_clk_scaling_suspend(hba, false);
6031 ufshcd_rpm_put(hba);
6034 static inline bool ufshcd_err_handling_should_stop(struct ufs_hba *hba)
6036 return (!hba->is_powered || hba->shutting_down ||
6037 !hba->sdev_ufs_device ||
6038 hba->ufshcd_state == UFSHCD_STATE_ERROR ||
6039 (!(hba->saved_err || hba->saved_uic_err || hba->force_reset ||
6040 ufshcd_is_link_broken(hba))));
6044 static void ufshcd_recover_pm_error(struct ufs_hba *hba)
6046 struct Scsi_Host *shost = hba->host;
6047 struct scsi_device *sdev;
6048 struct request_queue *q;
6051 hba->is_sys_suspended = false;
6053 * Set RPM status of wlun device to RPM_ACTIVE,
6054 * this also clears its runtime error.
6056 ret = pm_runtime_set_active(&hba->sdev_ufs_device->sdev_gendev);
6058 /* hba device might have a runtime error otherwise */
6060 ret = pm_runtime_set_active(hba->dev);
6062 * If wlun device had runtime error, we also need to resume those
6063 * consumer scsi devices in case any of them has failed to be
6064 * resumed due to supplier runtime resume failure. This is to unblock
6065 * blk_queue_enter in case there are bios waiting inside it.
6068 shost_for_each_device(sdev, shost) {
6069 q = sdev->request_queue;
6070 if (q->dev && (q->rpm_status == RPM_SUSPENDED ||
6071 q->rpm_status == RPM_SUSPENDING))
6072 pm_request_resume(q->dev);
6077 static inline void ufshcd_recover_pm_error(struct ufs_hba *hba)
6082 static bool ufshcd_is_pwr_mode_restore_needed(struct ufs_hba *hba)
6084 struct ufs_pa_layer_attr *pwr_info = &hba->pwr_info;
6087 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_PWRMODE), &mode);
6089 if (pwr_info->pwr_rx != ((mode >> PWRMODE_RX_OFFSET) & PWRMODE_MASK))
6092 if (pwr_info->pwr_tx != (mode & PWRMODE_MASK))
6099 * ufshcd_err_handler - handle UFS errors that require s/w attention
6100 * @work: pointer to work structure
6102 static void ufshcd_err_handler(struct work_struct *work)
6104 int retries = MAX_ERR_HANDLER_RETRIES;
6105 struct ufs_hba *hba;
6106 unsigned long flags;
6114 hba = container_of(work, struct ufs_hba, eh_work);
6117 "%s started; HBA state %s; powered %d; shutting down %d; saved_err = %d; saved_uic_err = %d; force_reset = %d%s\n",
6118 __func__, ufshcd_state_name[hba->ufshcd_state],
6119 hba->is_powered, hba->shutting_down, hba->saved_err,
6120 hba->saved_uic_err, hba->force_reset,
6121 ufshcd_is_link_broken(hba) ? "; link is broken" : "");
6123 down(&hba->host_sem);
6124 spin_lock_irqsave(hba->host->host_lock, flags);
6125 if (ufshcd_err_handling_should_stop(hba)) {
6126 if (hba->ufshcd_state != UFSHCD_STATE_ERROR)
6127 hba->ufshcd_state = UFSHCD_STATE_OPERATIONAL;
6128 spin_unlock_irqrestore(hba->host->host_lock, flags);
6132 ufshcd_set_eh_in_progress(hba);
6133 spin_unlock_irqrestore(hba->host->host_lock, flags);
6134 ufshcd_err_handling_prepare(hba);
6135 /* Complete requests that have door-bell cleared by h/w */
6136 ufshcd_complete_requests(hba);
6137 spin_lock_irqsave(hba->host->host_lock, flags);
6139 needs_restore = false;
6140 needs_reset = false;
6144 if (hba->ufshcd_state != UFSHCD_STATE_ERROR)
6145 hba->ufshcd_state = UFSHCD_STATE_RESET;
6147 * A full reset and restore might have happened after preparation
6148 * is finished, double check whether we should stop.
6150 if (ufshcd_err_handling_should_stop(hba))
6151 goto skip_err_handling;
6153 if (hba->dev_quirks & UFS_DEVICE_QUIRK_RECOVERY_FROM_DL_NAC_ERRORS) {
6156 spin_unlock_irqrestore(hba->host->host_lock, flags);
6157 /* release the lock as ufshcd_quirk_dl_nac_errors() may sleep */
6158 ret = ufshcd_quirk_dl_nac_errors(hba);
6159 spin_lock_irqsave(hba->host->host_lock, flags);
6160 if (!ret && ufshcd_err_handling_should_stop(hba))
6161 goto skip_err_handling;
6164 if ((hba->saved_err & (INT_FATAL_ERRORS | UFSHCD_UIC_HIBERN8_MASK)) ||
6165 (hba->saved_uic_err &&
6166 (hba->saved_uic_err != UFSHCD_UIC_PA_GENERIC_ERROR))) {
6167 bool pr_prdt = !!(hba->saved_err & SYSTEM_BUS_FATAL_ERROR);
6169 spin_unlock_irqrestore(hba->host->host_lock, flags);
6170 ufshcd_print_host_state(hba);
6171 ufshcd_print_pwr_info(hba);
6172 ufshcd_print_evt_hist(hba);
6173 ufshcd_print_tmrs(hba, hba->outstanding_tasks);
6174 ufshcd_print_trs(hba, hba->outstanding_reqs, pr_prdt);
6175 spin_lock_irqsave(hba->host->host_lock, flags);
6179 * if host reset is required then skip clearing the pending
6180 * transfers forcefully because they will get cleared during
6181 * host reset and restore
6183 if (hba->force_reset || ufshcd_is_link_broken(hba) ||
6184 ufshcd_is_saved_err_fatal(hba) ||
6185 ((hba->saved_err & UIC_ERROR) &&
6186 (hba->saved_uic_err & (UFSHCD_UIC_DL_NAC_RECEIVED_ERROR |
6187 UFSHCD_UIC_DL_TCx_REPLAY_ERROR)))) {
6193 * If LINERESET was caught, UFS might have been put to PWM mode,
6194 * check if power mode restore is needed.
6196 if (hba->saved_uic_err & UFSHCD_UIC_PA_GENERIC_ERROR) {
6197 hba->saved_uic_err &= ~UFSHCD_UIC_PA_GENERIC_ERROR;
6198 if (!hba->saved_uic_err)
6199 hba->saved_err &= ~UIC_ERROR;
6200 spin_unlock_irqrestore(hba->host->host_lock, flags);
6201 if (ufshcd_is_pwr_mode_restore_needed(hba))
6202 needs_restore = true;
6203 spin_lock_irqsave(hba->host->host_lock, flags);
6204 if (!hba->saved_err && !needs_restore)
6205 goto skip_err_handling;
6208 hba->silence_err_logs = true;
6209 /* release lock as clear command might sleep */
6210 spin_unlock_irqrestore(hba->host->host_lock, flags);
6211 /* Clear pending transfer requests */
6212 for_each_set_bit(tag, &hba->outstanding_reqs, hba->nutrs) {
6213 if (ufshcd_try_to_abort_task(hba, tag)) {
6215 goto lock_skip_pending_xfer_clear;
6217 dev_err(hba->dev, "Aborted tag %d / CDB %#02x\n", tag,
6218 hba->lrb[tag].cmd ? hba->lrb[tag].cmd->cmnd[0] : -1);
6221 /* Clear pending task management requests */
6222 for_each_set_bit(tag, &hba->outstanding_tasks, hba->nutmrs) {
6223 if (ufshcd_clear_tm_cmd(hba, tag)) {
6225 goto lock_skip_pending_xfer_clear;
6229 lock_skip_pending_xfer_clear:
6230 /* Complete the requests that are cleared by s/w */
6231 ufshcd_complete_requests(hba);
6233 spin_lock_irqsave(hba->host->host_lock, flags);
6234 hba->silence_err_logs = false;
6235 if (err_xfer || err_tm) {
6241 * After all reqs and tasks are cleared from doorbell,
6242 * now it is safe to retore power mode.
6244 if (needs_restore) {
6245 spin_unlock_irqrestore(hba->host->host_lock, flags);
6247 * Hold the scaling lock just in case dev cmds
6248 * are sent via bsg and/or sysfs.
6250 down_write(&hba->clk_scaling_lock);
6251 hba->force_pmc = true;
6252 pmc_err = ufshcd_config_pwr_mode(hba, &(hba->pwr_info));
6255 dev_err(hba->dev, "%s: Failed to restore power mode, err = %d\n",
6258 hba->force_pmc = false;
6259 ufshcd_print_pwr_info(hba);
6260 up_write(&hba->clk_scaling_lock);
6261 spin_lock_irqsave(hba->host->host_lock, flags);
6265 /* Fatal errors need reset */
6269 hba->force_reset = false;
6270 spin_unlock_irqrestore(hba->host->host_lock, flags);
6271 err = ufshcd_reset_and_restore(hba);
6273 dev_err(hba->dev, "%s: reset and restore failed with err %d\n",
6276 ufshcd_recover_pm_error(hba);
6277 spin_lock_irqsave(hba->host->host_lock, flags);
6282 if (hba->ufshcd_state == UFSHCD_STATE_RESET)
6283 hba->ufshcd_state = UFSHCD_STATE_OPERATIONAL;
6284 if (hba->saved_err || hba->saved_uic_err)
6285 dev_err_ratelimited(hba->dev, "%s: exit: saved_err 0x%x saved_uic_err 0x%x",
6286 __func__, hba->saved_err, hba->saved_uic_err);
6288 /* Exit in an operational state or dead */
6289 if (hba->ufshcd_state != UFSHCD_STATE_OPERATIONAL &&
6290 hba->ufshcd_state != UFSHCD_STATE_ERROR) {
6293 hba->ufshcd_state = UFSHCD_STATE_ERROR;
6295 ufshcd_clear_eh_in_progress(hba);
6296 spin_unlock_irqrestore(hba->host->host_lock, flags);
6297 ufshcd_err_handling_unprepare(hba);
6300 dev_info(hba->dev, "%s finished; HBA state %s\n", __func__,
6301 ufshcd_state_name[hba->ufshcd_state]);
6305 * ufshcd_update_uic_error - check and set fatal UIC error flags.
6306 * @hba: per-adapter instance
6309 * IRQ_HANDLED - If interrupt is valid
6310 * IRQ_NONE - If invalid interrupt
6312 static irqreturn_t ufshcd_update_uic_error(struct ufs_hba *hba)
6315 irqreturn_t retval = IRQ_NONE;
6317 /* PHY layer error */
6318 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_PHY_ADAPTER_LAYER);
6319 if ((reg & UIC_PHY_ADAPTER_LAYER_ERROR) &&
6320 (reg & UIC_PHY_ADAPTER_LAYER_ERROR_CODE_MASK)) {
6321 ufshcd_update_evt_hist(hba, UFS_EVT_PA_ERR, reg);
6323 * To know whether this error is fatal or not, DB timeout
6324 * must be checked but this error is handled separately.
6326 if (reg & UIC_PHY_ADAPTER_LAYER_LANE_ERR_MASK)
6327 dev_dbg(hba->dev, "%s: UIC Lane error reported\n",
6330 /* Got a LINERESET indication. */
6331 if (reg & UIC_PHY_ADAPTER_LAYER_GENERIC_ERROR) {
6332 struct uic_command *cmd = NULL;
6334 hba->uic_error |= UFSHCD_UIC_PA_GENERIC_ERROR;
6335 if (hba->uic_async_done && hba->active_uic_cmd)
6336 cmd = hba->active_uic_cmd;
6338 * Ignore the LINERESET during power mode change
6339 * operation via DME_SET command.
6341 if (cmd && (cmd->command == UIC_CMD_DME_SET))
6342 hba->uic_error &= ~UFSHCD_UIC_PA_GENERIC_ERROR;
6344 retval |= IRQ_HANDLED;
6347 /* PA_INIT_ERROR is fatal and needs UIC reset */
6348 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_DATA_LINK_LAYER);
6349 if ((reg & UIC_DATA_LINK_LAYER_ERROR) &&
6350 (reg & UIC_DATA_LINK_LAYER_ERROR_CODE_MASK)) {
6351 ufshcd_update_evt_hist(hba, UFS_EVT_DL_ERR, reg);
6353 if (reg & UIC_DATA_LINK_LAYER_ERROR_PA_INIT)
6354 hba->uic_error |= UFSHCD_UIC_DL_PA_INIT_ERROR;
6355 else if (hba->dev_quirks &
6356 UFS_DEVICE_QUIRK_RECOVERY_FROM_DL_NAC_ERRORS) {
6357 if (reg & UIC_DATA_LINK_LAYER_ERROR_NAC_RECEIVED)
6359 UFSHCD_UIC_DL_NAC_RECEIVED_ERROR;
6360 else if (reg & UIC_DATA_LINK_LAYER_ERROR_TCx_REPLAY_TIMEOUT)
6361 hba->uic_error |= UFSHCD_UIC_DL_TCx_REPLAY_ERROR;
6363 retval |= IRQ_HANDLED;
6366 /* UIC NL/TL/DME errors needs software retry */
6367 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_NETWORK_LAYER);
6368 if ((reg & UIC_NETWORK_LAYER_ERROR) &&
6369 (reg & UIC_NETWORK_LAYER_ERROR_CODE_MASK)) {
6370 ufshcd_update_evt_hist(hba, UFS_EVT_NL_ERR, reg);
6371 hba->uic_error |= UFSHCD_UIC_NL_ERROR;
6372 retval |= IRQ_HANDLED;
6375 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_TRANSPORT_LAYER);
6376 if ((reg & UIC_TRANSPORT_LAYER_ERROR) &&
6377 (reg & UIC_TRANSPORT_LAYER_ERROR_CODE_MASK)) {
6378 ufshcd_update_evt_hist(hba, UFS_EVT_TL_ERR, reg);
6379 hba->uic_error |= UFSHCD_UIC_TL_ERROR;
6380 retval |= IRQ_HANDLED;
6383 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_DME);
6384 if ((reg & UIC_DME_ERROR) &&
6385 (reg & UIC_DME_ERROR_CODE_MASK)) {
6386 ufshcd_update_evt_hist(hba, UFS_EVT_DME_ERR, reg);
6387 hba->uic_error |= UFSHCD_UIC_DME_ERROR;
6388 retval |= IRQ_HANDLED;
6391 dev_dbg(hba->dev, "%s: UIC error flags = 0x%08x\n",
6392 __func__, hba->uic_error);
6397 * ufshcd_check_errors - Check for errors that need s/w attention
6398 * @hba: per-adapter instance
6399 * @intr_status: interrupt status generated by the controller
6402 * IRQ_HANDLED - If interrupt is valid
6403 * IRQ_NONE - If invalid interrupt
6405 static irqreturn_t ufshcd_check_errors(struct ufs_hba *hba, u32 intr_status)
6407 bool queue_eh_work = false;
6408 irqreturn_t retval = IRQ_NONE;
6410 spin_lock(hba->host->host_lock);
6411 hba->errors |= UFSHCD_ERROR_MASK & intr_status;
6413 if (hba->errors & INT_FATAL_ERRORS) {
6414 ufshcd_update_evt_hist(hba, UFS_EVT_FATAL_ERR,
6416 queue_eh_work = true;
6419 if (hba->errors & UIC_ERROR) {
6421 retval = ufshcd_update_uic_error(hba);
6423 queue_eh_work = true;
6426 if (hba->errors & UFSHCD_UIC_HIBERN8_MASK) {
6428 "%s: Auto Hibern8 %s failed - status: 0x%08x, upmcrs: 0x%08x\n",
6429 __func__, (hba->errors & UIC_HIBERNATE_ENTER) ?
6431 hba->errors, ufshcd_get_upmcrs(hba));
6432 ufshcd_update_evt_hist(hba, UFS_EVT_AUTO_HIBERN8_ERR,
6434 ufshcd_set_link_broken(hba);
6435 queue_eh_work = true;
6438 if (queue_eh_work) {
6440 * update the transfer error masks to sticky bits, let's do this
6441 * irrespective of current ufshcd_state.
6443 hba->saved_err |= hba->errors;
6444 hba->saved_uic_err |= hba->uic_error;
6446 /* dump controller state before resetting */
6447 if ((hba->saved_err &
6448 (INT_FATAL_ERRORS | UFSHCD_UIC_HIBERN8_MASK)) ||
6449 (hba->saved_uic_err &&
6450 (hba->saved_uic_err != UFSHCD_UIC_PA_GENERIC_ERROR))) {
6451 dev_err(hba->dev, "%s: saved_err 0x%x saved_uic_err 0x%x\n",
6452 __func__, hba->saved_err,
6453 hba->saved_uic_err);
6454 ufshcd_dump_regs(hba, 0, UFSHCI_REG_SPACE_SIZE,
6456 ufshcd_print_pwr_info(hba);
6458 ufshcd_schedule_eh_work(hba);
6459 retval |= IRQ_HANDLED;
6462 * if (!queue_eh_work) -
6463 * Other errors are either non-fatal where host recovers
6464 * itself without s/w intervention or errors that will be
6465 * handled by the SCSI core layer.
6469 spin_unlock(hba->host->host_lock);
6474 * ufshcd_tmc_handler - handle task management function completion
6475 * @hba: per adapter instance
6478 * IRQ_HANDLED - If interrupt is valid
6479 * IRQ_NONE - If invalid interrupt
6481 static irqreturn_t ufshcd_tmc_handler(struct ufs_hba *hba)
6483 unsigned long flags, pending, issued;
6484 irqreturn_t ret = IRQ_NONE;
6487 spin_lock_irqsave(hba->host->host_lock, flags);
6488 pending = ufshcd_readl(hba, REG_UTP_TASK_REQ_DOOR_BELL);
6489 issued = hba->outstanding_tasks & ~pending;
6490 for_each_set_bit(tag, &issued, hba->nutmrs) {
6491 struct request *req = hba->tmf_rqs[tag];
6492 struct completion *c = req->end_io_data;
6497 spin_unlock_irqrestore(hba->host->host_lock, flags);
6503 * ufshcd_sl_intr - Interrupt service routine
6504 * @hba: per adapter instance
6505 * @intr_status: contains interrupts generated by the controller
6508 * IRQ_HANDLED - If interrupt is valid
6509 * IRQ_NONE - If invalid interrupt
6511 static irqreturn_t ufshcd_sl_intr(struct ufs_hba *hba, u32 intr_status)
6513 irqreturn_t retval = IRQ_NONE;
6515 if (intr_status & UFSHCD_UIC_MASK)
6516 retval |= ufshcd_uic_cmd_compl(hba, intr_status);
6518 if (intr_status & UFSHCD_ERROR_MASK || hba->errors)
6519 retval |= ufshcd_check_errors(hba, intr_status);
6521 if (intr_status & UTP_TASK_REQ_COMPL)
6522 retval |= ufshcd_tmc_handler(hba);
6524 if (intr_status & UTP_TRANSFER_REQ_COMPL)
6525 retval |= ufshcd_transfer_req_compl(hba);
6531 * ufshcd_intr - Main interrupt service routine
6533 * @__hba: pointer to adapter instance
6536 * IRQ_HANDLED - If interrupt is valid
6537 * IRQ_NONE - If invalid interrupt
6539 static irqreturn_t ufshcd_intr(int irq, void *__hba)
6541 u32 intr_status, enabled_intr_status = 0;
6542 irqreturn_t retval = IRQ_NONE;
6543 struct ufs_hba *hba = __hba;
6544 int retries = hba->nutrs;
6546 intr_status = ufshcd_readl(hba, REG_INTERRUPT_STATUS);
6547 hba->ufs_stats.last_intr_status = intr_status;
6548 hba->ufs_stats.last_intr_ts = ktime_get();
6551 * There could be max of hba->nutrs reqs in flight and in worst case
6552 * if the reqs get finished 1 by 1 after the interrupt status is
6553 * read, make sure we handle them by checking the interrupt status
6554 * again in a loop until we process all of the reqs before returning.
6556 while (intr_status && retries--) {
6557 enabled_intr_status =
6558 intr_status & ufshcd_readl(hba, REG_INTERRUPT_ENABLE);
6559 ufshcd_writel(hba, intr_status, REG_INTERRUPT_STATUS);
6560 if (enabled_intr_status)
6561 retval |= ufshcd_sl_intr(hba, enabled_intr_status);
6563 intr_status = ufshcd_readl(hba, REG_INTERRUPT_STATUS);
6566 if (enabled_intr_status && retval == IRQ_NONE &&
6567 (!(enabled_intr_status & UTP_TRANSFER_REQ_COMPL) ||
6568 hba->outstanding_reqs) && !ufshcd_eh_in_progress(hba)) {
6569 dev_err(hba->dev, "%s: Unhandled interrupt 0x%08x (0x%08x, 0x%08x)\n",
6572 hba->ufs_stats.last_intr_status,
6573 enabled_intr_status);
6574 ufshcd_dump_regs(hba, 0, UFSHCI_REG_SPACE_SIZE, "host_regs: ");
6580 static int ufshcd_clear_tm_cmd(struct ufs_hba *hba, int tag)
6583 u32 mask = 1 << tag;
6584 unsigned long flags;
6586 if (!test_bit(tag, &hba->outstanding_tasks))
6589 spin_lock_irqsave(hba->host->host_lock, flags);
6590 ufshcd_utmrl_clear(hba, tag);
6591 spin_unlock_irqrestore(hba->host->host_lock, flags);
6593 /* poll for max. 1 sec to clear door bell register by h/w */
6594 err = ufshcd_wait_for_register(hba,
6595 REG_UTP_TASK_REQ_DOOR_BELL,
6596 mask, 0, 1000, 1000);
6598 dev_err(hba->dev, "Clearing task management function with tag %d %s\n",
6599 tag, err ? "succeeded" : "failed");
6605 static int __ufshcd_issue_tm_cmd(struct ufs_hba *hba,
6606 struct utp_task_req_desc *treq, u8 tm_function)
6608 struct request_queue *q = hba->tmf_queue;
6609 struct Scsi_Host *host = hba->host;
6610 DECLARE_COMPLETION_ONSTACK(wait);
6611 struct request *req;
6612 unsigned long flags;
6616 * blk_mq_alloc_request() is used here only to get a free tag.
6618 req = blk_mq_alloc_request(q, REQ_OP_DRV_OUT, 0);
6620 return PTR_ERR(req);
6622 req->end_io_data = &wait;
6623 ufshcd_hold(hba, false);
6625 spin_lock_irqsave(host->host_lock, flags);
6627 task_tag = req->tag;
6628 WARN_ONCE(task_tag < 0 || task_tag >= hba->nutmrs, "Invalid tag %d\n",
6630 hba->tmf_rqs[req->tag] = req;
6631 treq->upiu_req.req_header.dword_0 |= cpu_to_be32(task_tag);
6633 memcpy(hba->utmrdl_base_addr + task_tag, treq, sizeof(*treq));
6634 ufshcd_vops_setup_task_mgmt(hba, task_tag, tm_function);
6636 /* send command to the controller */
6637 __set_bit(task_tag, &hba->outstanding_tasks);
6639 ufshcd_writel(hba, 1 << task_tag, REG_UTP_TASK_REQ_DOOR_BELL);
6640 /* Make sure that doorbell is committed immediately */
6643 spin_unlock_irqrestore(host->host_lock, flags);
6645 ufshcd_add_tm_upiu_trace(hba, task_tag, UFS_TM_SEND);
6647 /* wait until the task management command is completed */
6648 err = wait_for_completion_io_timeout(&wait,
6649 msecs_to_jiffies(TM_CMD_TIMEOUT));
6651 ufshcd_add_tm_upiu_trace(hba, task_tag, UFS_TM_ERR);
6652 dev_err(hba->dev, "%s: task management cmd 0x%.2x timed-out\n",
6653 __func__, tm_function);
6654 if (ufshcd_clear_tm_cmd(hba, task_tag))
6655 dev_WARN(hba->dev, "%s: unable to clear tm cmd (slot %d) after timeout\n",
6656 __func__, task_tag);
6660 memcpy(treq, hba->utmrdl_base_addr + task_tag, sizeof(*treq));
6662 ufshcd_add_tm_upiu_trace(hba, task_tag, UFS_TM_COMP);
6665 spin_lock_irqsave(hba->host->host_lock, flags);
6666 hba->tmf_rqs[req->tag] = NULL;
6667 __clear_bit(task_tag, &hba->outstanding_tasks);
6668 spin_unlock_irqrestore(hba->host->host_lock, flags);
6670 ufshcd_release(hba);
6671 blk_mq_free_request(req);
6677 * ufshcd_issue_tm_cmd - issues task management commands to controller
6678 * @hba: per adapter instance
6679 * @lun_id: LUN ID to which TM command is sent
6680 * @task_id: task ID to which the TM command is applicable
6681 * @tm_function: task management function opcode
6682 * @tm_response: task management service response return value
6684 * Returns non-zero value on error, zero on success.
6686 static int ufshcd_issue_tm_cmd(struct ufs_hba *hba, int lun_id, int task_id,
6687 u8 tm_function, u8 *tm_response)
6689 struct utp_task_req_desc treq = { { 0 }, };
6690 enum utp_ocs ocs_value;
6693 /* Configure task request descriptor */
6694 treq.header.dword_0 = cpu_to_le32(UTP_REQ_DESC_INT_CMD);
6695 treq.header.dword_2 = cpu_to_le32(OCS_INVALID_COMMAND_STATUS);
6697 /* Configure task request UPIU */
6698 treq.upiu_req.req_header.dword_0 = cpu_to_be32(lun_id << 8) |
6699 cpu_to_be32(UPIU_TRANSACTION_TASK_REQ << 24);
6700 treq.upiu_req.req_header.dword_1 = cpu_to_be32(tm_function << 16);
6703 * The host shall provide the same value for LUN field in the basic
6704 * header and for Input Parameter.
6706 treq.upiu_req.input_param1 = cpu_to_be32(lun_id);
6707 treq.upiu_req.input_param2 = cpu_to_be32(task_id);
6709 err = __ufshcd_issue_tm_cmd(hba, &treq, tm_function);
6710 if (err == -ETIMEDOUT)
6713 ocs_value = le32_to_cpu(treq.header.dword_2) & MASK_OCS;
6714 if (ocs_value != OCS_SUCCESS)
6715 dev_err(hba->dev, "%s: failed, ocs = 0x%x\n",
6716 __func__, ocs_value);
6717 else if (tm_response)
6718 *tm_response = be32_to_cpu(treq.upiu_rsp.output_param1) &
6719 MASK_TM_SERVICE_RESP;
6724 * ufshcd_issue_devman_upiu_cmd - API for sending "utrd" type requests
6725 * @hba: per-adapter instance
6726 * @req_upiu: upiu request
6727 * @rsp_upiu: upiu reply
6728 * @desc_buff: pointer to descriptor buffer, NULL if NA
6729 * @buff_len: descriptor size, 0 if NA
6730 * @cmd_type: specifies the type (NOP, Query...)
6731 * @desc_op: descriptor operation
6733 * Those type of requests uses UTP Transfer Request Descriptor - utrd.
6734 * Therefore, it "rides" the device management infrastructure: uses its tag and
6735 * tasks work queues.
6737 * Since there is only one available tag for device management commands,
6738 * the caller is expected to hold the hba->dev_cmd.lock mutex.
6740 static int ufshcd_issue_devman_upiu_cmd(struct ufs_hba *hba,
6741 struct utp_upiu_req *req_upiu,
6742 struct utp_upiu_req *rsp_upiu,
6743 u8 *desc_buff, int *buff_len,
6744 enum dev_cmd_type cmd_type,
6745 enum query_opcode desc_op)
6747 DECLARE_COMPLETION_ONSTACK(wait);
6748 const u32 tag = hba->reserved_slot;
6749 struct ufshcd_lrb *lrbp;
6753 /* Protects use of hba->reserved_slot. */
6754 lockdep_assert_held(&hba->dev_cmd.lock);
6756 down_read(&hba->clk_scaling_lock);
6758 lrbp = &hba->lrb[tag];
6761 lrbp->sense_bufflen = 0;
6762 lrbp->sense_buffer = NULL;
6763 lrbp->task_tag = tag;
6765 lrbp->intr_cmd = true;
6766 ufshcd_prepare_lrbp_crypto(NULL, lrbp);
6767 hba->dev_cmd.type = cmd_type;
6769 if (hba->ufs_version <= ufshci_version(1, 1))
6770 lrbp->command_type = UTP_CMD_TYPE_DEV_MANAGE;
6772 lrbp->command_type = UTP_CMD_TYPE_UFS_STORAGE;
6774 /* update the task tag in the request upiu */
6775 req_upiu->header.dword_0 |= cpu_to_be32(tag);
6777 ufshcd_prepare_req_desc_hdr(lrbp, &upiu_flags, DMA_NONE);
6779 /* just copy the upiu request as it is */
6780 memcpy(lrbp->ucd_req_ptr, req_upiu, sizeof(*lrbp->ucd_req_ptr));
6781 if (desc_buff && desc_op == UPIU_QUERY_OPCODE_WRITE_DESC) {
6782 /* The Data Segment Area is optional depending upon the query
6783 * function value. for WRITE DESCRIPTOR, the data segment
6784 * follows right after the tsf.
6786 memcpy(lrbp->ucd_req_ptr + 1, desc_buff, *buff_len);
6790 memset(lrbp->ucd_rsp_ptr, 0, sizeof(struct utp_upiu_rsp));
6792 hba->dev_cmd.complete = &wait;
6794 ufshcd_add_query_upiu_trace(hba, UFS_QUERY_SEND, lrbp->ucd_req_ptr);
6796 ufshcd_send_command(hba, tag);
6798 * ignore the returning value here - ufshcd_check_query_response is
6799 * bound to fail since dev_cmd.query and dev_cmd.type were left empty.
6800 * read the response directly ignoring all errors.
6802 ufshcd_wait_for_dev_cmd(hba, lrbp, QUERY_REQ_TIMEOUT);
6804 /* just copy the upiu response as it is */
6805 memcpy(rsp_upiu, lrbp->ucd_rsp_ptr, sizeof(*rsp_upiu));
6806 if (desc_buff && desc_op == UPIU_QUERY_OPCODE_READ_DESC) {
6807 u8 *descp = (u8 *)lrbp->ucd_rsp_ptr + sizeof(*rsp_upiu);
6808 u16 resp_len = be32_to_cpu(lrbp->ucd_rsp_ptr->header.dword_2) &
6809 MASK_QUERY_DATA_SEG_LEN;
6811 if (*buff_len >= resp_len) {
6812 memcpy(desc_buff, descp, resp_len);
6813 *buff_len = resp_len;
6816 "%s: rsp size %d is bigger than buffer size %d",
6817 __func__, resp_len, *buff_len);
6822 ufshcd_add_query_upiu_trace(hba, err ? UFS_QUERY_ERR : UFS_QUERY_COMP,
6823 (struct utp_upiu_req *)lrbp->ucd_rsp_ptr);
6825 up_read(&hba->clk_scaling_lock);
6830 * ufshcd_exec_raw_upiu_cmd - API function for sending raw upiu commands
6831 * @hba: per-adapter instance
6832 * @req_upiu: upiu request
6833 * @rsp_upiu: upiu reply - only 8 DW as we do not support scsi commands
6834 * @msgcode: message code, one of UPIU Transaction Codes Initiator to Target
6835 * @desc_buff: pointer to descriptor buffer, NULL if NA
6836 * @buff_len: descriptor size, 0 if NA
6837 * @desc_op: descriptor operation
6839 * Supports UTP Transfer requests (nop and query), and UTP Task
6840 * Management requests.
6841 * It is up to the caller to fill the upiu conent properly, as it will
6842 * be copied without any further input validations.
6844 int ufshcd_exec_raw_upiu_cmd(struct ufs_hba *hba,
6845 struct utp_upiu_req *req_upiu,
6846 struct utp_upiu_req *rsp_upiu,
6848 u8 *desc_buff, int *buff_len,
6849 enum query_opcode desc_op)
6852 enum dev_cmd_type cmd_type = DEV_CMD_TYPE_QUERY;
6853 struct utp_task_req_desc treq = { { 0 }, };
6854 enum utp_ocs ocs_value;
6855 u8 tm_f = be32_to_cpu(req_upiu->header.dword_1) >> 16 & MASK_TM_FUNC;
6858 case UPIU_TRANSACTION_NOP_OUT:
6859 cmd_type = DEV_CMD_TYPE_NOP;
6861 case UPIU_TRANSACTION_QUERY_REQ:
6862 ufshcd_hold(hba, false);
6863 mutex_lock(&hba->dev_cmd.lock);
6864 err = ufshcd_issue_devman_upiu_cmd(hba, req_upiu, rsp_upiu,
6865 desc_buff, buff_len,
6867 mutex_unlock(&hba->dev_cmd.lock);
6868 ufshcd_release(hba);
6871 case UPIU_TRANSACTION_TASK_REQ:
6872 treq.header.dword_0 = cpu_to_le32(UTP_REQ_DESC_INT_CMD);
6873 treq.header.dword_2 = cpu_to_le32(OCS_INVALID_COMMAND_STATUS);
6875 memcpy(&treq.upiu_req, req_upiu, sizeof(*req_upiu));
6877 err = __ufshcd_issue_tm_cmd(hba, &treq, tm_f);
6878 if (err == -ETIMEDOUT)
6881 ocs_value = le32_to_cpu(treq.header.dword_2) & MASK_OCS;
6882 if (ocs_value != OCS_SUCCESS) {
6883 dev_err(hba->dev, "%s: failed, ocs = 0x%x\n", __func__,
6888 memcpy(rsp_upiu, &treq.upiu_rsp, sizeof(*rsp_upiu));
6901 * ufshcd_eh_device_reset_handler - device reset handler registered to
6903 * @cmd: SCSI command pointer
6905 * Returns SUCCESS/FAILED
6907 static int ufshcd_eh_device_reset_handler(struct scsi_cmnd *cmd)
6909 struct Scsi_Host *host;
6910 struct ufs_hba *hba;
6915 host = cmd->device->host;
6916 hba = shost_priv(host);
6918 lun = ufshcd_scsi_to_upiu_lun(cmd->device->lun);
6919 err = ufshcd_issue_tm_cmd(hba, lun, 0, UFS_LOGICAL_RESET, &resp);
6920 if (err || resp != UPIU_TASK_MANAGEMENT_FUNC_COMPL) {
6926 /* clear the commands that were pending for corresponding LUN */
6927 for_each_set_bit(pos, &hba->outstanding_reqs, hba->nutrs) {
6928 if (hba->lrb[pos].lun == lun) {
6929 err = ufshcd_clear_cmd(hba, pos);
6932 __ufshcd_transfer_req_compl(hba, 1U << pos);
6937 hba->req_abort_count = 0;
6938 ufshcd_update_evt_hist(hba, UFS_EVT_DEV_RESET, (u32)err);
6942 dev_err(hba->dev, "%s: failed with err %d\n", __func__, err);
6948 static void ufshcd_set_req_abort_skip(struct ufs_hba *hba, unsigned long bitmap)
6950 struct ufshcd_lrb *lrbp;
6953 for_each_set_bit(tag, &bitmap, hba->nutrs) {
6954 lrbp = &hba->lrb[tag];
6955 lrbp->req_abort_skip = true;
6960 * ufshcd_try_to_abort_task - abort a specific task
6961 * @hba: Pointer to adapter instance
6962 * @tag: Task tag/index to be aborted
6964 * Abort the pending command in device by sending UFS_ABORT_TASK task management
6965 * command, and in host controller by clearing the door-bell register. There can
6966 * be race between controller sending the command to the device while abort is
6967 * issued. To avoid that, first issue UFS_QUERY_TASK to check if the command is
6968 * really issued and then try to abort it.
6970 * Returns zero on success, non-zero on failure
6972 static int ufshcd_try_to_abort_task(struct ufs_hba *hba, int tag)
6974 struct ufshcd_lrb *lrbp = &hba->lrb[tag];
6980 for (poll_cnt = 100; poll_cnt; poll_cnt--) {
6981 err = ufshcd_issue_tm_cmd(hba, lrbp->lun, lrbp->task_tag,
6982 UFS_QUERY_TASK, &resp);
6983 if (!err && resp == UPIU_TASK_MANAGEMENT_FUNC_SUCCEEDED) {
6984 /* cmd pending in the device */
6985 dev_err(hba->dev, "%s: cmd pending in the device. tag = %d\n",
6988 } else if (!err && resp == UPIU_TASK_MANAGEMENT_FUNC_COMPL) {
6990 * cmd not pending in the device, check if it is
6993 dev_err(hba->dev, "%s: cmd at tag %d not pending in the device.\n",
6995 reg = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
6996 if (reg & (1 << tag)) {
6997 /* sleep for max. 200us to stabilize */
6998 usleep_range(100, 200);
7001 /* command completed already */
7002 dev_err(hba->dev, "%s: cmd at tag %d successfully cleared from DB.\n",
7007 "%s: no response from device. tag = %d, err %d\n",
7008 __func__, tag, err);
7010 err = resp; /* service response error */
7020 err = ufshcd_issue_tm_cmd(hba, lrbp->lun, lrbp->task_tag,
7021 UFS_ABORT_TASK, &resp);
7022 if (err || resp != UPIU_TASK_MANAGEMENT_FUNC_COMPL) {
7024 err = resp; /* service response error */
7025 dev_err(hba->dev, "%s: issued. tag = %d, err %d\n",
7026 __func__, tag, err);
7031 err = ufshcd_clear_cmd(hba, tag);
7033 dev_err(hba->dev, "%s: Failed clearing cmd at tag %d, err %d\n",
7034 __func__, tag, err);
7041 * ufshcd_abort - scsi host template eh_abort_handler callback
7042 * @cmd: SCSI command pointer
7044 * Returns SUCCESS/FAILED
7046 static int ufshcd_abort(struct scsi_cmnd *cmd)
7048 struct Scsi_Host *host = cmd->device->host;
7049 struct ufs_hba *hba = shost_priv(host);
7050 int tag = scsi_cmd_to_rq(cmd)->tag;
7051 struct ufshcd_lrb *lrbp = &hba->lrb[tag];
7052 unsigned long flags;
7057 WARN_ONCE(tag < 0, "Invalid tag %d\n", tag);
7059 ufshcd_hold(hba, false);
7060 reg = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
7061 /* If command is already aborted/completed, return FAILED. */
7062 if (!(test_bit(tag, &hba->outstanding_reqs))) {
7064 "%s: cmd at tag %d already completed, outstanding=0x%lx, doorbell=0x%x\n",
7065 __func__, tag, hba->outstanding_reqs, reg);
7069 /* Print Transfer Request of aborted task */
7070 dev_info(hba->dev, "%s: Device abort task at tag %d\n", __func__, tag);
7073 * Print detailed info about aborted request.
7074 * As more than one request might get aborted at the same time,
7075 * print full information only for the first aborted request in order
7076 * to reduce repeated printouts. For other aborted requests only print
7079 scsi_print_command(cmd);
7080 if (!hba->req_abort_count) {
7081 ufshcd_update_evt_hist(hba, UFS_EVT_ABORT, tag);
7082 ufshcd_print_evt_hist(hba);
7083 ufshcd_print_host_state(hba);
7084 ufshcd_print_pwr_info(hba);
7085 ufshcd_print_trs(hba, 1 << tag, true);
7087 ufshcd_print_trs(hba, 1 << tag, false);
7089 hba->req_abort_count++;
7091 if (!(reg & (1 << tag))) {
7093 "%s: cmd was completed, but without a notifying intr, tag = %d",
7095 __ufshcd_transfer_req_compl(hba, 1UL << tag);
7100 * Task abort to the device W-LUN is illegal. When this command
7101 * will fail, due to spec violation, scsi err handling next step
7102 * will be to send LU reset which, again, is a spec violation.
7103 * To avoid these unnecessary/illegal steps, first we clean up
7104 * the lrb taken by this cmd and re-set it in outstanding_reqs,
7105 * then queue the eh_work and bail.
7107 if (lrbp->lun == UFS_UPIU_UFS_DEVICE_WLUN) {
7108 ufshcd_update_evt_hist(hba, UFS_EVT_ABORT, lrbp->lun);
7110 spin_lock_irqsave(host->host_lock, flags);
7111 hba->force_reset = true;
7112 ufshcd_schedule_eh_work(hba);
7113 spin_unlock_irqrestore(host->host_lock, flags);
7117 /* Skip task abort in case previous aborts failed and report failure */
7118 if (lrbp->req_abort_skip) {
7119 dev_err(hba->dev, "%s: skipping abort\n", __func__);
7120 ufshcd_set_req_abort_skip(hba, hba->outstanding_reqs);
7124 err = ufshcd_try_to_abort_task(hba, tag);
7126 dev_err(hba->dev, "%s: failed with err %d\n", __func__, err);
7127 ufshcd_set_req_abort_skip(hba, hba->outstanding_reqs);
7133 * Clear the corresponding bit from outstanding_reqs since the command
7134 * has been aborted successfully.
7136 spin_lock_irqsave(&hba->outstanding_lock, flags);
7137 outstanding = __test_and_clear_bit(tag, &hba->outstanding_reqs);
7138 spin_unlock_irqrestore(&hba->outstanding_lock, flags);
7141 ufshcd_release_scsi_cmd(hba, lrbp);
7146 /* Matches the ufshcd_hold() call at the start of this function. */
7147 ufshcd_release(hba);
7152 * ufshcd_host_reset_and_restore - reset and restore host controller
7153 * @hba: per-adapter instance
7155 * Note that host controller reset may issue DME_RESET to
7156 * local and remote (device) Uni-Pro stack and the attributes
7157 * are reset to default state.
7159 * Returns zero on success, non-zero on failure
7161 static int ufshcd_host_reset_and_restore(struct ufs_hba *hba)
7166 * Stop the host controller and complete the requests
7169 ufshpb_reset_host(hba);
7170 ufshcd_hba_stop(hba);
7171 hba->silence_err_logs = true;
7172 ufshcd_complete_requests(hba);
7173 hba->silence_err_logs = false;
7175 /* scale up clocks to max frequency before full reinitialization */
7176 ufshcd_set_clk_freq(hba, true);
7178 err = ufshcd_hba_enable(hba);
7180 /* Establish the link again and restore the device */
7182 err = ufshcd_probe_hba(hba, false);
7185 dev_err(hba->dev, "%s: Host init failed %d\n", __func__, err);
7186 ufshcd_update_evt_hist(hba, UFS_EVT_HOST_RESET, (u32)err);
7191 * ufshcd_reset_and_restore - reset and re-initialize host/device
7192 * @hba: per-adapter instance
7194 * Reset and recover device, host and re-establish link. This
7195 * is helpful to recover the communication in fatal error conditions.
7197 * Returns zero on success, non-zero on failure
7199 static int ufshcd_reset_and_restore(struct ufs_hba *hba)
7202 u32 saved_uic_err = 0;
7204 unsigned long flags;
7205 int retries = MAX_HOST_RESET_RETRIES;
7207 spin_lock_irqsave(hba->host->host_lock, flags);
7210 * This is a fresh start, cache and clear saved error first,
7211 * in case new error generated during reset and restore.
7213 saved_err |= hba->saved_err;
7214 saved_uic_err |= hba->saved_uic_err;
7216 hba->saved_uic_err = 0;
7217 hba->force_reset = false;
7218 hba->ufshcd_state = UFSHCD_STATE_RESET;
7219 spin_unlock_irqrestore(hba->host->host_lock, flags);
7221 /* Reset the attached device */
7222 ufshcd_device_reset(hba);
7224 err = ufshcd_host_reset_and_restore(hba);
7226 spin_lock_irqsave(hba->host->host_lock, flags);
7229 /* Do not exit unless operational or dead */
7230 if (hba->ufshcd_state != UFSHCD_STATE_OPERATIONAL &&
7231 hba->ufshcd_state != UFSHCD_STATE_ERROR &&
7232 hba->ufshcd_state != UFSHCD_STATE_EH_SCHEDULED_NON_FATAL)
7234 } while (err && --retries);
7237 * Inform scsi mid-layer that we did reset and allow to handle
7238 * Unit Attention properly.
7240 scsi_report_bus_reset(hba->host, 0);
7242 hba->ufshcd_state = UFSHCD_STATE_ERROR;
7243 hba->saved_err |= saved_err;
7244 hba->saved_uic_err |= saved_uic_err;
7246 spin_unlock_irqrestore(hba->host->host_lock, flags);
7252 * ufshcd_eh_host_reset_handler - host reset handler registered to scsi layer
7253 * @cmd: SCSI command pointer
7255 * Returns SUCCESS/FAILED
7257 static int ufshcd_eh_host_reset_handler(struct scsi_cmnd *cmd)
7260 unsigned long flags;
7261 struct ufs_hba *hba;
7263 hba = shost_priv(cmd->device->host);
7265 spin_lock_irqsave(hba->host->host_lock, flags);
7266 hba->force_reset = true;
7267 ufshcd_schedule_eh_work(hba);
7268 dev_err(hba->dev, "%s: reset in progress - 1\n", __func__);
7269 spin_unlock_irqrestore(hba->host->host_lock, flags);
7271 flush_work(&hba->eh_work);
7273 spin_lock_irqsave(hba->host->host_lock, flags);
7274 if (hba->ufshcd_state == UFSHCD_STATE_ERROR)
7276 spin_unlock_irqrestore(hba->host->host_lock, flags);
7282 * ufshcd_get_max_icc_level - calculate the ICC level
7283 * @sup_curr_uA: max. current supported by the regulator
7284 * @start_scan: row at the desc table to start scan from
7285 * @buff: power descriptor buffer
7287 * Returns calculated max ICC level for specific regulator
7289 static u32 ufshcd_get_max_icc_level(int sup_curr_uA, u32 start_scan, char *buff)
7296 for (i = start_scan; i >= 0; i--) {
7297 data = be16_to_cpup((__be16 *)&buff[2 * i]);
7298 unit = (data & ATTR_ICC_LVL_UNIT_MASK) >>
7299 ATTR_ICC_LVL_UNIT_OFFSET;
7300 curr_uA = data & ATTR_ICC_LVL_VALUE_MASK;
7302 case UFSHCD_NANO_AMP:
7303 curr_uA = curr_uA / 1000;
7305 case UFSHCD_MILI_AMP:
7306 curr_uA = curr_uA * 1000;
7309 curr_uA = curr_uA * 1000 * 1000;
7311 case UFSHCD_MICRO_AMP:
7315 if (sup_curr_uA >= curr_uA)
7320 pr_err("%s: Couldn't find valid icc_level = %d", __func__, i);
7327 * ufshcd_find_max_sup_active_icc_level - calculate the max ICC level
7328 * In case regulators are not initialized we'll return 0
7329 * @hba: per-adapter instance
7330 * @desc_buf: power descriptor buffer to extract ICC levels from.
7331 * @len: length of desc_buff
7333 * Returns calculated ICC level
7335 static u32 ufshcd_find_max_sup_active_icc_level(struct ufs_hba *hba,
7336 u8 *desc_buf, int len)
7340 if (!hba->vreg_info.vcc || !hba->vreg_info.vccq ||
7341 !hba->vreg_info.vccq2) {
7343 "%s: Regulator capability was not set, actvIccLevel=%d",
7344 __func__, icc_level);
7348 if (hba->vreg_info.vcc->max_uA)
7349 icc_level = ufshcd_get_max_icc_level(
7350 hba->vreg_info.vcc->max_uA,
7351 POWER_DESC_MAX_ACTV_ICC_LVLS - 1,
7352 &desc_buf[PWR_DESC_ACTIVE_LVLS_VCC_0]);
7354 if (hba->vreg_info.vccq->max_uA)
7355 icc_level = ufshcd_get_max_icc_level(
7356 hba->vreg_info.vccq->max_uA,
7358 &desc_buf[PWR_DESC_ACTIVE_LVLS_VCCQ_0]);
7360 if (hba->vreg_info.vccq2->max_uA)
7361 icc_level = ufshcd_get_max_icc_level(
7362 hba->vreg_info.vccq2->max_uA,
7364 &desc_buf[PWR_DESC_ACTIVE_LVLS_VCCQ2_0]);
7369 static void ufshcd_set_active_icc_lvl(struct ufs_hba *hba)
7372 int buff_len = hba->desc_size[QUERY_DESC_IDN_POWER];
7376 desc_buf = kmalloc(buff_len, GFP_KERNEL);
7380 ret = ufshcd_read_desc_param(hba, QUERY_DESC_IDN_POWER, 0, 0,
7381 desc_buf, buff_len);
7384 "%s: Failed reading power descriptor.len = %d ret = %d",
7385 __func__, buff_len, ret);
7389 icc_level = ufshcd_find_max_sup_active_icc_level(hba, desc_buf,
7391 dev_dbg(hba->dev, "%s: setting icc_level 0x%x", __func__, icc_level);
7393 ret = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_WRITE_ATTR,
7394 QUERY_ATTR_IDN_ACTIVE_ICC_LVL, 0, 0, &icc_level);
7398 "%s: Failed configuring bActiveICCLevel = %d ret = %d",
7399 __func__, icc_level, ret);
7405 static inline void ufshcd_blk_pm_runtime_init(struct scsi_device *sdev)
7407 scsi_autopm_get_device(sdev);
7408 blk_pm_runtime_init(sdev->request_queue, &sdev->sdev_gendev);
7409 if (sdev->rpm_autosuspend)
7410 pm_runtime_set_autosuspend_delay(&sdev->sdev_gendev,
7411 RPM_AUTOSUSPEND_DELAY_MS);
7412 scsi_autopm_put_device(sdev);
7416 * ufshcd_scsi_add_wlus - Adds required W-LUs
7417 * @hba: per-adapter instance
7419 * UFS device specification requires the UFS devices to support 4 well known
7421 * "REPORT_LUNS" (address: 01h)
7422 * "UFS Device" (address: 50h)
7423 * "RPMB" (address: 44h)
7424 * "BOOT" (address: 30h)
7425 * UFS device's power management needs to be controlled by "POWER CONDITION"
7426 * field of SSU (START STOP UNIT) command. But this "power condition" field
7427 * will take effect only when its sent to "UFS device" well known logical unit
7428 * hence we require the scsi_device instance to represent this logical unit in
7429 * order for the UFS host driver to send the SSU command for power management.
7431 * We also require the scsi_device instance for "RPMB" (Replay Protected Memory
7432 * Block) LU so user space process can control this LU. User space may also
7433 * want to have access to BOOT LU.
7435 * This function adds scsi device instances for each of all well known LUs
7436 * (except "REPORT LUNS" LU).
7438 * Returns zero on success (all required W-LUs are added successfully),
7439 * non-zero error value on failure (if failed to add any of the required W-LU).
7441 static int ufshcd_scsi_add_wlus(struct ufs_hba *hba)
7444 struct scsi_device *sdev_boot, *sdev_rpmb;
7446 hba->sdev_ufs_device = __scsi_add_device(hba->host, 0, 0,
7447 ufshcd_upiu_wlun_to_scsi_wlun(UFS_UPIU_UFS_DEVICE_WLUN), NULL);
7448 if (IS_ERR(hba->sdev_ufs_device)) {
7449 ret = PTR_ERR(hba->sdev_ufs_device);
7450 hba->sdev_ufs_device = NULL;
7453 scsi_device_put(hba->sdev_ufs_device);
7455 sdev_rpmb = __scsi_add_device(hba->host, 0, 0,
7456 ufshcd_upiu_wlun_to_scsi_wlun(UFS_UPIU_RPMB_WLUN), NULL);
7457 if (IS_ERR(sdev_rpmb)) {
7458 ret = PTR_ERR(sdev_rpmb);
7459 goto remove_sdev_ufs_device;
7461 ufshcd_blk_pm_runtime_init(sdev_rpmb);
7462 scsi_device_put(sdev_rpmb);
7464 sdev_boot = __scsi_add_device(hba->host, 0, 0,
7465 ufshcd_upiu_wlun_to_scsi_wlun(UFS_UPIU_BOOT_WLUN), NULL);
7466 if (IS_ERR(sdev_boot)) {
7467 dev_err(hba->dev, "%s: BOOT WLUN not found\n", __func__);
7469 ufshcd_blk_pm_runtime_init(sdev_boot);
7470 scsi_device_put(sdev_boot);
7474 remove_sdev_ufs_device:
7475 scsi_remove_device(hba->sdev_ufs_device);
7480 static void ufshcd_wb_probe(struct ufs_hba *hba, u8 *desc_buf)
7482 struct ufs_dev_info *dev_info = &hba->dev_info;
7484 u32 d_lu_wb_buf_alloc;
7485 u32 ext_ufs_feature;
7487 if (!ufshcd_is_wb_allowed(hba))
7490 * Probe WB only for UFS-2.2 and UFS-3.1 (and later) devices or
7491 * UFS devices with quirk UFS_DEVICE_QUIRK_SUPPORT_EXTENDED_FEATURES
7494 if (!(dev_info->wspecversion >= 0x310 ||
7495 dev_info->wspecversion == 0x220 ||
7496 (hba->dev_quirks & UFS_DEVICE_QUIRK_SUPPORT_EXTENDED_FEATURES)))
7499 if (hba->desc_size[QUERY_DESC_IDN_DEVICE] <
7500 DEVICE_DESC_PARAM_EXT_UFS_FEATURE_SUP + 4)
7503 ext_ufs_feature = get_unaligned_be32(desc_buf +
7504 DEVICE_DESC_PARAM_EXT_UFS_FEATURE_SUP);
7506 if (!(ext_ufs_feature & UFS_DEV_WRITE_BOOSTER_SUP))
7510 * WB may be supported but not configured while provisioning. The spec
7511 * says, in dedicated wb buffer mode, a max of 1 lun would have wb
7512 * buffer configured.
7514 dev_info->wb_buffer_type = desc_buf[DEVICE_DESC_PARAM_WB_TYPE];
7516 dev_info->b_presrv_uspc_en =
7517 desc_buf[DEVICE_DESC_PARAM_WB_PRESRV_USRSPC_EN];
7519 if (dev_info->wb_buffer_type == WB_BUF_MODE_SHARED) {
7520 if (!get_unaligned_be32(desc_buf +
7521 DEVICE_DESC_PARAM_WB_SHARED_ALLOC_UNITS))
7524 for (lun = 0; lun < UFS_UPIU_MAX_WB_LUN_ID; lun++) {
7525 d_lu_wb_buf_alloc = 0;
7526 ufshcd_read_unit_desc_param(hba,
7528 UNIT_DESC_PARAM_WB_BUF_ALLOC_UNITS,
7529 (u8 *)&d_lu_wb_buf_alloc,
7530 sizeof(d_lu_wb_buf_alloc));
7531 if (d_lu_wb_buf_alloc) {
7532 dev_info->wb_dedicated_lu = lun;
7537 if (!d_lu_wb_buf_alloc)
7543 hba->caps &= ~UFSHCD_CAP_WB_EN;
7546 static void ufshcd_temp_notif_probe(struct ufs_hba *hba, u8 *desc_buf)
7548 struct ufs_dev_info *dev_info = &hba->dev_info;
7549 u32 ext_ufs_feature;
7552 if (!(hba->caps & UFSHCD_CAP_TEMP_NOTIF) || dev_info->wspecversion < 0x300)
7555 ext_ufs_feature = get_unaligned_be32(desc_buf + DEVICE_DESC_PARAM_EXT_UFS_FEATURE_SUP);
7557 if (ext_ufs_feature & UFS_DEV_LOW_TEMP_NOTIF)
7558 mask |= MASK_EE_TOO_LOW_TEMP;
7560 if (ext_ufs_feature & UFS_DEV_HIGH_TEMP_NOTIF)
7561 mask |= MASK_EE_TOO_HIGH_TEMP;
7564 ufshcd_enable_ee(hba, mask);
7565 ufs_hwmon_probe(hba, mask);
7569 void ufshcd_fixup_dev_quirks(struct ufs_hba *hba, struct ufs_dev_fix *fixups)
7571 struct ufs_dev_fix *f;
7572 struct ufs_dev_info *dev_info = &hba->dev_info;
7577 for (f = fixups; f->quirk; f++) {
7578 if ((f->wmanufacturerid == dev_info->wmanufacturerid ||
7579 f->wmanufacturerid == UFS_ANY_VENDOR) &&
7580 ((dev_info->model &&
7581 STR_PRFX_EQUAL(f->model, dev_info->model)) ||
7582 !strcmp(f->model, UFS_ANY_MODEL)))
7583 hba->dev_quirks |= f->quirk;
7586 EXPORT_SYMBOL_GPL(ufshcd_fixup_dev_quirks);
7588 static void ufs_fixup_device_setup(struct ufs_hba *hba)
7590 /* fix by general quirk table */
7591 ufshcd_fixup_dev_quirks(hba, ufs_fixups);
7593 /* allow vendors to fix quirks */
7594 ufshcd_vops_fixup_dev_quirks(hba);
7597 static int ufs_get_device_desc(struct ufs_hba *hba)
7601 u8 b_ufs_feature_sup;
7603 struct ufs_dev_info *dev_info = &hba->dev_info;
7605 desc_buf = kmalloc(QUERY_DESC_MAX_SIZE, GFP_KERNEL);
7611 err = ufshcd_read_desc_param(hba, QUERY_DESC_IDN_DEVICE, 0, 0, desc_buf,
7612 hba->desc_size[QUERY_DESC_IDN_DEVICE]);
7614 dev_err(hba->dev, "%s: Failed reading Device Desc. err = %d\n",
7620 * getting vendor (manufacturerID) and Bank Index in big endian
7623 dev_info->wmanufacturerid = desc_buf[DEVICE_DESC_PARAM_MANF_ID] << 8 |
7624 desc_buf[DEVICE_DESC_PARAM_MANF_ID + 1];
7626 /* getting Specification Version in big endian format */
7627 dev_info->wspecversion = desc_buf[DEVICE_DESC_PARAM_SPEC_VER] << 8 |
7628 desc_buf[DEVICE_DESC_PARAM_SPEC_VER + 1];
7629 b_ufs_feature_sup = desc_buf[DEVICE_DESC_PARAM_UFS_FEAT];
7631 model_index = desc_buf[DEVICE_DESC_PARAM_PRDCT_NAME];
7633 if (dev_info->wspecversion >= UFS_DEV_HPB_SUPPORT_VERSION &&
7634 (b_ufs_feature_sup & UFS_DEV_HPB_SUPPORT)) {
7635 bool hpb_en = false;
7637 ufshpb_get_dev_info(hba, desc_buf);
7639 if (!ufshpb_is_legacy(hba))
7640 err = ufshcd_query_flag_retry(hba,
7641 UPIU_QUERY_OPCODE_READ_FLAG,
7642 QUERY_FLAG_IDN_HPB_EN, 0,
7645 if (ufshpb_is_legacy(hba) || (!err && hpb_en))
7646 dev_info->hpb_enabled = true;
7649 err = ufshcd_read_string_desc(hba, model_index,
7650 &dev_info->model, SD_ASCII_STD);
7652 dev_err(hba->dev, "%s: Failed reading Product Name. err = %d\n",
7657 hba->luns_avail = desc_buf[DEVICE_DESC_PARAM_NUM_LU] +
7658 desc_buf[DEVICE_DESC_PARAM_NUM_WLU];
7660 ufs_fixup_device_setup(hba);
7662 ufshcd_wb_probe(hba, desc_buf);
7664 ufshcd_temp_notif_probe(hba, desc_buf);
7667 * ufshcd_read_string_desc returns size of the string
7668 * reset the error value
7677 static void ufs_put_device_desc(struct ufs_hba *hba)
7679 struct ufs_dev_info *dev_info = &hba->dev_info;
7681 kfree(dev_info->model);
7682 dev_info->model = NULL;
7686 * ufshcd_tune_pa_tactivate - Tunes PA_TActivate of local UniPro
7687 * @hba: per-adapter instance
7689 * PA_TActivate parameter can be tuned manually if UniPro version is less than
7690 * 1.61. PA_TActivate needs to be greater than or equal to peerM-PHY's
7691 * RX_MIN_ACTIVATETIME_CAPABILITY attribute. This optimal value can help reduce
7692 * the hibern8 exit latency.
7694 * Returns zero on success, non-zero error value on failure.
7696 static int ufshcd_tune_pa_tactivate(struct ufs_hba *hba)
7699 u32 peer_rx_min_activatetime = 0, tuned_pa_tactivate;
7701 ret = ufshcd_dme_peer_get(hba,
7703 RX_MIN_ACTIVATETIME_CAPABILITY,
7704 UIC_ARG_MPHY_RX_GEN_SEL_INDEX(0)),
7705 &peer_rx_min_activatetime);
7709 /* make sure proper unit conversion is applied */
7710 tuned_pa_tactivate =
7711 ((peer_rx_min_activatetime * RX_MIN_ACTIVATETIME_UNIT_US)
7712 / PA_TACTIVATE_TIME_UNIT_US);
7713 ret = ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TACTIVATE),
7714 tuned_pa_tactivate);
7721 * ufshcd_tune_pa_hibern8time - Tunes PA_Hibern8Time of local UniPro
7722 * @hba: per-adapter instance
7724 * PA_Hibern8Time parameter can be tuned manually if UniPro version is less than
7725 * 1.61. PA_Hibern8Time needs to be maximum of local M-PHY's
7726 * TX_HIBERN8TIME_CAPABILITY & peer M-PHY's RX_HIBERN8TIME_CAPABILITY.
7727 * This optimal value can help reduce the hibern8 exit latency.
7729 * Returns zero on success, non-zero error value on failure.
7731 static int ufshcd_tune_pa_hibern8time(struct ufs_hba *hba)
7734 u32 local_tx_hibern8_time_cap = 0, peer_rx_hibern8_time_cap = 0;
7735 u32 max_hibern8_time, tuned_pa_hibern8time;
7737 ret = ufshcd_dme_get(hba,
7738 UIC_ARG_MIB_SEL(TX_HIBERN8TIME_CAPABILITY,
7739 UIC_ARG_MPHY_TX_GEN_SEL_INDEX(0)),
7740 &local_tx_hibern8_time_cap);
7744 ret = ufshcd_dme_peer_get(hba,
7745 UIC_ARG_MIB_SEL(RX_HIBERN8TIME_CAPABILITY,
7746 UIC_ARG_MPHY_RX_GEN_SEL_INDEX(0)),
7747 &peer_rx_hibern8_time_cap);
7751 max_hibern8_time = max(local_tx_hibern8_time_cap,
7752 peer_rx_hibern8_time_cap);
7753 /* make sure proper unit conversion is applied */
7754 tuned_pa_hibern8time = ((max_hibern8_time * HIBERN8TIME_UNIT_US)
7755 / PA_HIBERN8_TIME_UNIT_US);
7756 ret = ufshcd_dme_set(hba, UIC_ARG_MIB(PA_HIBERN8TIME),
7757 tuned_pa_hibern8time);
7763 * ufshcd_quirk_tune_host_pa_tactivate - Ensures that host PA_TACTIVATE is
7764 * less than device PA_TACTIVATE time.
7765 * @hba: per-adapter instance
7767 * Some UFS devices require host PA_TACTIVATE to be lower than device
7768 * PA_TACTIVATE, we need to enable UFS_DEVICE_QUIRK_HOST_PA_TACTIVATE quirk
7771 * Returns zero on success, non-zero error value on failure.
7773 static int ufshcd_quirk_tune_host_pa_tactivate(struct ufs_hba *hba)
7776 u32 granularity, peer_granularity;
7777 u32 pa_tactivate, peer_pa_tactivate;
7778 u32 pa_tactivate_us, peer_pa_tactivate_us;
7779 u8 gran_to_us_table[] = {1, 4, 8, 16, 32, 100};
7781 ret = ufshcd_dme_get(hba, UIC_ARG_MIB(PA_GRANULARITY),
7786 ret = ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_GRANULARITY),
7791 if ((granularity < PA_GRANULARITY_MIN_VAL) ||
7792 (granularity > PA_GRANULARITY_MAX_VAL)) {
7793 dev_err(hba->dev, "%s: invalid host PA_GRANULARITY %d",
7794 __func__, granularity);
7798 if ((peer_granularity < PA_GRANULARITY_MIN_VAL) ||
7799 (peer_granularity > PA_GRANULARITY_MAX_VAL)) {
7800 dev_err(hba->dev, "%s: invalid device PA_GRANULARITY %d",
7801 __func__, peer_granularity);
7805 ret = ufshcd_dme_get(hba, UIC_ARG_MIB(PA_TACTIVATE), &pa_tactivate);
7809 ret = ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_TACTIVATE),
7810 &peer_pa_tactivate);
7814 pa_tactivate_us = pa_tactivate * gran_to_us_table[granularity - 1];
7815 peer_pa_tactivate_us = peer_pa_tactivate *
7816 gran_to_us_table[peer_granularity - 1];
7818 if (pa_tactivate_us >= peer_pa_tactivate_us) {
7819 u32 new_peer_pa_tactivate;
7821 new_peer_pa_tactivate = pa_tactivate_us /
7822 gran_to_us_table[peer_granularity - 1];
7823 new_peer_pa_tactivate++;
7824 ret = ufshcd_dme_peer_set(hba, UIC_ARG_MIB(PA_TACTIVATE),
7825 new_peer_pa_tactivate);
7832 static void ufshcd_tune_unipro_params(struct ufs_hba *hba)
7834 if (ufshcd_is_unipro_pa_params_tuning_req(hba)) {
7835 ufshcd_tune_pa_tactivate(hba);
7836 ufshcd_tune_pa_hibern8time(hba);
7839 ufshcd_vops_apply_dev_quirks(hba);
7841 if (hba->dev_quirks & UFS_DEVICE_QUIRK_PA_TACTIVATE)
7842 /* set 1ms timeout for PA_TACTIVATE */
7843 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TACTIVATE), 10);
7845 if (hba->dev_quirks & UFS_DEVICE_QUIRK_HOST_PA_TACTIVATE)
7846 ufshcd_quirk_tune_host_pa_tactivate(hba);
7849 static void ufshcd_clear_dbg_ufs_stats(struct ufs_hba *hba)
7851 hba->ufs_stats.hibern8_exit_cnt = 0;
7852 hba->ufs_stats.last_hibern8_exit_tstamp = ktime_set(0, 0);
7853 hba->req_abort_count = 0;
7856 static int ufshcd_device_geo_params_init(struct ufs_hba *hba)
7862 buff_len = hba->desc_size[QUERY_DESC_IDN_GEOMETRY];
7863 desc_buf = kmalloc(buff_len, GFP_KERNEL);
7869 err = ufshcd_read_desc_param(hba, QUERY_DESC_IDN_GEOMETRY, 0, 0,
7870 desc_buf, buff_len);
7872 dev_err(hba->dev, "%s: Failed reading Geometry Desc. err = %d\n",
7877 if (desc_buf[GEOMETRY_DESC_PARAM_MAX_NUM_LUN] == 1)
7878 hba->dev_info.max_lu_supported = 32;
7879 else if (desc_buf[GEOMETRY_DESC_PARAM_MAX_NUM_LUN] == 0)
7880 hba->dev_info.max_lu_supported = 8;
7882 if (hba->desc_size[QUERY_DESC_IDN_GEOMETRY] >=
7883 GEOMETRY_DESC_PARAM_HPB_MAX_ACTIVE_REGS)
7884 ufshpb_get_geo_info(hba, desc_buf);
7891 static struct ufs_ref_clk ufs_ref_clk_freqs[] = {
7892 {19200000, REF_CLK_FREQ_19_2_MHZ},
7893 {26000000, REF_CLK_FREQ_26_MHZ},
7894 {38400000, REF_CLK_FREQ_38_4_MHZ},
7895 {52000000, REF_CLK_FREQ_52_MHZ},
7896 {0, REF_CLK_FREQ_INVAL},
7899 static enum ufs_ref_clk_freq
7900 ufs_get_bref_clk_from_hz(unsigned long freq)
7904 for (i = 0; ufs_ref_clk_freqs[i].freq_hz; i++)
7905 if (ufs_ref_clk_freqs[i].freq_hz == freq)
7906 return ufs_ref_clk_freqs[i].val;
7908 return REF_CLK_FREQ_INVAL;
7911 void ufshcd_parse_dev_ref_clk_freq(struct ufs_hba *hba, struct clk *refclk)
7915 freq = clk_get_rate(refclk);
7917 hba->dev_ref_clk_freq =
7918 ufs_get_bref_clk_from_hz(freq);
7920 if (hba->dev_ref_clk_freq == REF_CLK_FREQ_INVAL)
7922 "invalid ref_clk setting = %ld\n", freq);
7925 static int ufshcd_set_dev_ref_clk(struct ufs_hba *hba)
7929 u32 freq = hba->dev_ref_clk_freq;
7931 err = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
7932 QUERY_ATTR_IDN_REF_CLK_FREQ, 0, 0, &ref_clk);
7935 dev_err(hba->dev, "failed reading bRefClkFreq. err = %d\n",
7940 if (ref_clk == freq)
7941 goto out; /* nothing to update */
7943 err = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_WRITE_ATTR,
7944 QUERY_ATTR_IDN_REF_CLK_FREQ, 0, 0, &freq);
7947 dev_err(hba->dev, "bRefClkFreq setting to %lu Hz failed\n",
7948 ufs_ref_clk_freqs[freq].freq_hz);
7952 dev_dbg(hba->dev, "bRefClkFreq setting to %lu Hz succeeded\n",
7953 ufs_ref_clk_freqs[freq].freq_hz);
7959 static int ufshcd_device_params_init(struct ufs_hba *hba)
7964 /* Init device descriptor sizes */
7965 for (i = 0; i < QUERY_DESC_IDN_MAX; i++)
7966 hba->desc_size[i] = QUERY_DESC_MAX_SIZE;
7968 /* Init UFS geometry descriptor related parameters */
7969 ret = ufshcd_device_geo_params_init(hba);
7973 /* Check and apply UFS device quirks */
7974 ret = ufs_get_device_desc(hba);
7976 dev_err(hba->dev, "%s: Failed getting device info. err = %d\n",
7981 ufshcd_get_ref_clk_gating_wait(hba);
7983 if (!ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_READ_FLAG,
7984 QUERY_FLAG_IDN_PWR_ON_WPE, 0, &flag))
7985 hba->dev_info.f_power_on_wp_en = flag;
7987 /* Probe maximum power mode co-supported by both UFS host and device */
7988 if (ufshcd_get_max_pwr_mode(hba))
7990 "%s: Failed getting max supported power mode\n",
7997 * ufshcd_add_lus - probe and add UFS logical units
7998 * @hba: per-adapter instance
8000 static int ufshcd_add_lus(struct ufs_hba *hba)
8004 /* Add required well known logical units to scsi mid layer */
8005 ret = ufshcd_scsi_add_wlus(hba);
8009 /* Initialize devfreq after UFS device is detected */
8010 if (ufshcd_is_clkscaling_supported(hba)) {
8011 memcpy(&hba->clk_scaling.saved_pwr_info.info,
8013 sizeof(struct ufs_pa_layer_attr));
8014 hba->clk_scaling.saved_pwr_info.is_valid = true;
8015 hba->clk_scaling.is_allowed = true;
8017 ret = ufshcd_devfreq_init(hba);
8021 hba->clk_scaling.is_enabled = true;
8022 ufshcd_init_clk_scaling_sysfs(hba);
8027 scsi_scan_host(hba->host);
8028 pm_runtime_put_sync(hba->dev);
8035 * ufshcd_probe_hba - probe hba to detect device and initialize it
8036 * @hba: per-adapter instance
8037 * @init_dev_params: whether or not to call ufshcd_device_params_init().
8039 * Execute link-startup and verify device initialization
8041 static int ufshcd_probe_hba(struct ufs_hba *hba, bool init_dev_params)
8044 unsigned long flags;
8045 ktime_t start = ktime_get();
8047 hba->ufshcd_state = UFSHCD_STATE_RESET;
8049 ret = ufshcd_link_startup(hba);
8053 if (hba->quirks & UFSHCD_QUIRK_SKIP_PH_CONFIGURATION)
8056 /* Debug counters initialization */
8057 ufshcd_clear_dbg_ufs_stats(hba);
8059 /* UniPro link is active now */
8060 ufshcd_set_link_active(hba);
8062 /* Verify device initialization by sending NOP OUT UPIU */
8063 ret = ufshcd_verify_dev_init(hba);
8067 /* Initiate UFS initialization, and waiting until completion */
8068 ret = ufshcd_complete_dev_init(hba);
8073 * Initialize UFS device parameters used by driver, these
8074 * parameters are associated with UFS descriptors.
8076 if (init_dev_params) {
8077 ret = ufshcd_device_params_init(hba);
8082 ufshcd_tune_unipro_params(hba);
8084 /* UFS device is also active now */
8085 ufshcd_set_ufs_dev_active(hba);
8086 ufshcd_force_reset_auto_bkops(hba);
8088 /* Gear up to HS gear if supported */
8089 if (hba->max_pwr_info.is_valid) {
8091 * Set the right value to bRefClkFreq before attempting to
8092 * switch to HS gears.
8094 if (hba->dev_ref_clk_freq != REF_CLK_FREQ_INVAL)
8095 ufshcd_set_dev_ref_clk(hba);
8096 ret = ufshcd_config_pwr_mode(hba, &hba->max_pwr_info.info);
8098 dev_err(hba->dev, "%s: Failed setting power mode, err = %d\n",
8102 ufshcd_print_pwr_info(hba);
8106 * bActiveICCLevel is volatile for UFS device (as per latest v2.1 spec)
8107 * and for removable UFS card as well, hence always set the parameter.
8108 * Note: Error handler may issue the device reset hence resetting
8109 * bActiveICCLevel as well so it is always safe to set this here.
8111 ufshcd_set_active_icc_lvl(hba);
8113 ufshcd_wb_config(hba);
8114 if (hba->ee_usr_mask)
8115 ufshcd_write_ee_control(hba);
8116 /* Enable Auto-Hibernate if configured */
8117 ufshcd_auto_hibern8_enable(hba);
8121 spin_lock_irqsave(hba->host->host_lock, flags);
8123 hba->ufshcd_state = UFSHCD_STATE_ERROR;
8124 else if (hba->ufshcd_state == UFSHCD_STATE_RESET)
8125 hba->ufshcd_state = UFSHCD_STATE_OPERATIONAL;
8126 spin_unlock_irqrestore(hba->host->host_lock, flags);
8128 trace_ufshcd_init(dev_name(hba->dev), ret,
8129 ktime_to_us(ktime_sub(ktime_get(), start)),
8130 hba->curr_dev_pwr_mode, hba->uic_link_state);
8135 * ufshcd_async_scan - asynchronous execution for probing hba
8136 * @data: data pointer to pass to this function
8137 * @cookie: cookie data
8139 static void ufshcd_async_scan(void *data, async_cookie_t cookie)
8141 struct ufs_hba *hba = (struct ufs_hba *)data;
8144 down(&hba->host_sem);
8145 /* Initialize hba, detect and initialize UFS device */
8146 ret = ufshcd_probe_hba(hba, true);
8151 /* Probe and add UFS logical units */
8152 ret = ufshcd_add_lus(hba);
8155 * If we failed to initialize the device or the device is not
8156 * present, turn off the power/clocks etc.
8159 pm_runtime_put_sync(hba->dev);
8160 ufshcd_hba_exit(hba);
8164 static const struct attribute_group *ufshcd_driver_groups[] = {
8165 &ufs_sysfs_unit_descriptor_group,
8166 &ufs_sysfs_lun_attributes_group,
8167 #ifdef CONFIG_SCSI_UFS_HPB
8168 &ufs_sysfs_hpb_stat_group,
8169 &ufs_sysfs_hpb_param_group,
8174 static struct ufs_hba_variant_params ufs_hba_vps = {
8175 .hba_enable_delay_us = 1000,
8176 .wb_flush_threshold = UFS_WB_BUF_REMAIN_PERCENT(40),
8177 .devfreq_profile.polling_ms = 100,
8178 .devfreq_profile.target = ufshcd_devfreq_target,
8179 .devfreq_profile.get_dev_status = ufshcd_devfreq_get_dev_status,
8180 .ondemand_data.upthreshold = 70,
8181 .ondemand_data.downdifferential = 5,
8184 static struct scsi_host_template ufshcd_driver_template = {
8185 .module = THIS_MODULE,
8187 .proc_name = UFSHCD,
8188 .map_queues = ufshcd_map_queues,
8189 .queuecommand = ufshcd_queuecommand,
8190 .mq_poll = ufshcd_poll,
8191 .slave_alloc = ufshcd_slave_alloc,
8192 .slave_configure = ufshcd_slave_configure,
8193 .slave_destroy = ufshcd_slave_destroy,
8194 .change_queue_depth = ufshcd_change_queue_depth,
8195 .eh_abort_handler = ufshcd_abort,
8196 .eh_device_reset_handler = ufshcd_eh_device_reset_handler,
8197 .eh_host_reset_handler = ufshcd_eh_host_reset_handler,
8199 .sg_tablesize = SG_ALL,
8200 .cmd_per_lun = UFSHCD_CMD_PER_LUN,
8201 .can_queue = UFSHCD_CAN_QUEUE,
8202 .max_segment_size = PRDT_DATA_BYTE_COUNT_MAX,
8203 .max_host_blocked = 1,
8204 .track_queue_depth = 1,
8205 .sdev_groups = ufshcd_driver_groups,
8206 .dma_boundary = PAGE_SIZE - 1,
8207 .rpm_autosuspend_delay = RPM_AUTOSUSPEND_DELAY_MS,
8210 static int ufshcd_config_vreg_load(struct device *dev, struct ufs_vreg *vreg,
8219 * "set_load" operation shall be required on those regulators
8220 * which specifically configured current limitation. Otherwise
8221 * zero max_uA may cause unexpected behavior when regulator is
8222 * enabled or set as high power mode.
8227 ret = regulator_set_load(vreg->reg, ua);
8229 dev_err(dev, "%s: %s set load (ua=%d) failed, err=%d\n",
8230 __func__, vreg->name, ua, ret);
8236 static inline int ufshcd_config_vreg_lpm(struct ufs_hba *hba,
8237 struct ufs_vreg *vreg)
8239 return ufshcd_config_vreg_load(hba->dev, vreg, UFS_VREG_LPM_LOAD_UA);
8242 static inline int ufshcd_config_vreg_hpm(struct ufs_hba *hba,
8243 struct ufs_vreg *vreg)
8248 return ufshcd_config_vreg_load(hba->dev, vreg, vreg->max_uA);
8251 static int ufshcd_config_vreg(struct device *dev,
8252 struct ufs_vreg *vreg, bool on)
8255 struct regulator *reg;
8257 int min_uV, uA_load;
8264 if (regulator_count_voltages(reg) > 0) {
8265 uA_load = on ? vreg->max_uA : 0;
8266 ret = ufshcd_config_vreg_load(dev, vreg, uA_load);
8270 if (vreg->min_uV && vreg->max_uV) {
8271 min_uV = on ? vreg->min_uV : 0;
8272 ret = regulator_set_voltage(reg, min_uV, vreg->max_uV);
8275 "%s: %s set voltage failed, err=%d\n",
8276 __func__, name, ret);
8283 static int ufshcd_enable_vreg(struct device *dev, struct ufs_vreg *vreg)
8287 if (!vreg || vreg->enabled)
8290 ret = ufshcd_config_vreg(dev, vreg, true);
8292 ret = regulator_enable(vreg->reg);
8295 vreg->enabled = true;
8297 dev_err(dev, "%s: %s enable failed, err=%d\n",
8298 __func__, vreg->name, ret);
8303 static int ufshcd_disable_vreg(struct device *dev, struct ufs_vreg *vreg)
8307 if (!vreg || !vreg->enabled || vreg->always_on)
8310 ret = regulator_disable(vreg->reg);
8313 /* ignore errors on applying disable config */
8314 ufshcd_config_vreg(dev, vreg, false);
8315 vreg->enabled = false;
8317 dev_err(dev, "%s: %s disable failed, err=%d\n",
8318 __func__, vreg->name, ret);
8324 static int ufshcd_setup_vreg(struct ufs_hba *hba, bool on)
8327 struct device *dev = hba->dev;
8328 struct ufs_vreg_info *info = &hba->vreg_info;
8330 ret = ufshcd_toggle_vreg(dev, info->vcc, on);
8334 ret = ufshcd_toggle_vreg(dev, info->vccq, on);
8338 ret = ufshcd_toggle_vreg(dev, info->vccq2, on);
8342 ufshcd_toggle_vreg(dev, info->vccq2, false);
8343 ufshcd_toggle_vreg(dev, info->vccq, false);
8344 ufshcd_toggle_vreg(dev, info->vcc, false);
8349 static int ufshcd_setup_hba_vreg(struct ufs_hba *hba, bool on)
8351 struct ufs_vreg_info *info = &hba->vreg_info;
8353 return ufshcd_toggle_vreg(hba->dev, info->vdd_hba, on);
8356 static int ufshcd_get_vreg(struct device *dev, struct ufs_vreg *vreg)
8363 vreg->reg = devm_regulator_get(dev, vreg->name);
8364 if (IS_ERR(vreg->reg)) {
8365 ret = PTR_ERR(vreg->reg);
8366 dev_err(dev, "%s: %s get failed, err=%d\n",
8367 __func__, vreg->name, ret);
8373 static int ufshcd_init_vreg(struct ufs_hba *hba)
8376 struct device *dev = hba->dev;
8377 struct ufs_vreg_info *info = &hba->vreg_info;
8379 ret = ufshcd_get_vreg(dev, info->vcc);
8383 ret = ufshcd_get_vreg(dev, info->vccq);
8385 ret = ufshcd_get_vreg(dev, info->vccq2);
8390 static int ufshcd_init_hba_vreg(struct ufs_hba *hba)
8392 struct ufs_vreg_info *info = &hba->vreg_info;
8395 return ufshcd_get_vreg(hba->dev, info->vdd_hba);
8400 static int ufshcd_setup_clocks(struct ufs_hba *hba, bool on)
8403 struct ufs_clk_info *clki;
8404 struct list_head *head = &hba->clk_list_head;
8405 unsigned long flags;
8406 ktime_t start = ktime_get();
8407 bool clk_state_changed = false;
8409 if (list_empty(head))
8412 ret = ufshcd_vops_setup_clocks(hba, on, PRE_CHANGE);
8416 list_for_each_entry(clki, head, list) {
8417 if (!IS_ERR_OR_NULL(clki->clk)) {
8419 * Don't disable clocks which are needed
8420 * to keep the link active.
8422 if (ufshcd_is_link_active(hba) &&
8423 clki->keep_link_active)
8426 clk_state_changed = on ^ clki->enabled;
8427 if (on && !clki->enabled) {
8428 ret = clk_prepare_enable(clki->clk);
8430 dev_err(hba->dev, "%s: %s prepare enable failed, %d\n",
8431 __func__, clki->name, ret);
8434 } else if (!on && clki->enabled) {
8435 clk_disable_unprepare(clki->clk);
8438 dev_dbg(hba->dev, "%s: clk: %s %sabled\n", __func__,
8439 clki->name, on ? "en" : "dis");
8443 ret = ufshcd_vops_setup_clocks(hba, on, POST_CHANGE);
8449 list_for_each_entry(clki, head, list) {
8450 if (!IS_ERR_OR_NULL(clki->clk) && clki->enabled)
8451 clk_disable_unprepare(clki->clk);
8453 } else if (!ret && on) {
8454 spin_lock_irqsave(hba->host->host_lock, flags);
8455 hba->clk_gating.state = CLKS_ON;
8456 trace_ufshcd_clk_gating(dev_name(hba->dev),
8457 hba->clk_gating.state);
8458 spin_unlock_irqrestore(hba->host->host_lock, flags);
8461 if (clk_state_changed)
8462 trace_ufshcd_profile_clk_gating(dev_name(hba->dev),
8463 (on ? "on" : "off"),
8464 ktime_to_us(ktime_sub(ktime_get(), start)), ret);
8468 static int ufshcd_init_clocks(struct ufs_hba *hba)
8471 struct ufs_clk_info *clki;
8472 struct device *dev = hba->dev;
8473 struct list_head *head = &hba->clk_list_head;
8475 if (list_empty(head))
8478 list_for_each_entry(clki, head, list) {
8482 clki->clk = devm_clk_get(dev, clki->name);
8483 if (IS_ERR(clki->clk)) {
8484 ret = PTR_ERR(clki->clk);
8485 dev_err(dev, "%s: %s clk get failed, %d\n",
8486 __func__, clki->name, ret);
8491 * Parse device ref clk freq as per device tree "ref_clk".
8492 * Default dev_ref_clk_freq is set to REF_CLK_FREQ_INVAL
8493 * in ufshcd_alloc_host().
8495 if (!strcmp(clki->name, "ref_clk"))
8496 ufshcd_parse_dev_ref_clk_freq(hba, clki->clk);
8498 if (clki->max_freq) {
8499 ret = clk_set_rate(clki->clk, clki->max_freq);
8501 dev_err(hba->dev, "%s: %s clk set rate(%dHz) failed, %d\n",
8502 __func__, clki->name,
8503 clki->max_freq, ret);
8506 clki->curr_freq = clki->max_freq;
8508 dev_dbg(dev, "%s: clk: %s, rate: %lu\n", __func__,
8509 clki->name, clk_get_rate(clki->clk));
8515 static int ufshcd_variant_hba_init(struct ufs_hba *hba)
8522 err = ufshcd_vops_init(hba);
8524 dev_err(hba->dev, "%s: variant %s init failed err %d\n",
8525 __func__, ufshcd_get_var_name(hba), err);
8530 static void ufshcd_variant_hba_exit(struct ufs_hba *hba)
8535 ufshcd_vops_exit(hba);
8538 static int ufshcd_hba_init(struct ufs_hba *hba)
8543 * Handle host controller power separately from the UFS device power
8544 * rails as it will help controlling the UFS host controller power
8545 * collapse easily which is different than UFS device power collapse.
8546 * Also, enable the host controller power before we go ahead with rest
8547 * of the initialization here.
8549 err = ufshcd_init_hba_vreg(hba);
8553 err = ufshcd_setup_hba_vreg(hba, true);
8557 err = ufshcd_init_clocks(hba);
8559 goto out_disable_hba_vreg;
8561 err = ufshcd_setup_clocks(hba, true);
8563 goto out_disable_hba_vreg;
8565 err = ufshcd_init_vreg(hba);
8567 goto out_disable_clks;
8569 err = ufshcd_setup_vreg(hba, true);
8571 goto out_disable_clks;
8573 err = ufshcd_variant_hba_init(hba);
8575 goto out_disable_vreg;
8577 ufs_debugfs_hba_init(hba);
8579 hba->is_powered = true;
8583 ufshcd_setup_vreg(hba, false);
8585 ufshcd_setup_clocks(hba, false);
8586 out_disable_hba_vreg:
8587 ufshcd_setup_hba_vreg(hba, false);
8592 static void ufshcd_hba_exit(struct ufs_hba *hba)
8594 if (hba->is_powered) {
8595 ufshcd_exit_clk_scaling(hba);
8596 ufshcd_exit_clk_gating(hba);
8598 destroy_workqueue(hba->eh_wq);
8599 ufs_debugfs_hba_exit(hba);
8600 ufshcd_variant_hba_exit(hba);
8601 ufshcd_setup_vreg(hba, false);
8602 ufshcd_setup_clocks(hba, false);
8603 ufshcd_setup_hba_vreg(hba, false);
8604 hba->is_powered = false;
8605 ufs_put_device_desc(hba);
8610 * ufshcd_set_dev_pwr_mode - sends START STOP UNIT command to set device
8612 * @hba: per adapter instance
8613 * @pwr_mode: device power mode to set
8615 * Returns 0 if requested power mode is set successfully
8616 * Returns non-zero if failed to set the requested power mode
8618 static int ufshcd_set_dev_pwr_mode(struct ufs_hba *hba,
8619 enum ufs_dev_pwr_mode pwr_mode)
8621 unsigned char cmd[6] = { START_STOP };
8622 struct scsi_sense_hdr sshdr;
8623 struct scsi_device *sdp;
8624 unsigned long flags;
8627 spin_lock_irqsave(hba->host->host_lock, flags);
8628 sdp = hba->sdev_ufs_device;
8630 ret = scsi_device_get(sdp);
8631 if (!ret && !scsi_device_online(sdp)) {
8633 scsi_device_put(sdp);
8638 spin_unlock_irqrestore(hba->host->host_lock, flags);
8644 * If scsi commands fail, the scsi mid-layer schedules scsi error-
8645 * handling, which would wait for host to be resumed. Since we know
8646 * we are functional while we are here, skip host resume in error
8649 hba->host->eh_noresume = 1;
8651 cmd[4] = pwr_mode << 4;
8654 * Current function would be generally called from the power management
8655 * callbacks hence set the RQF_PM flag so that it doesn't resume the
8656 * already suspended childs.
8658 for (retries = 3; retries > 0; --retries) {
8659 ret = scsi_execute(sdp, cmd, DMA_NONE, NULL, 0, NULL, &sshdr,
8660 START_STOP_TIMEOUT, 0, 0, RQF_PM, NULL);
8661 if (!scsi_status_is_check_condition(ret) ||
8662 !scsi_sense_valid(&sshdr) ||
8663 sshdr.sense_key != UNIT_ATTENTION)
8667 sdev_printk(KERN_WARNING, sdp,
8668 "START_STOP failed for power mode: %d, result %x\n",
8670 if (ret > 0 && scsi_sense_valid(&sshdr))
8671 scsi_print_sense_hdr(sdp, NULL, &sshdr);
8675 hba->curr_dev_pwr_mode = pwr_mode;
8677 scsi_device_put(sdp);
8678 hba->host->eh_noresume = 0;
8682 static int ufshcd_link_state_transition(struct ufs_hba *hba,
8683 enum uic_link_state req_link_state,
8684 int check_for_bkops)
8688 if (req_link_state == hba->uic_link_state)
8691 if (req_link_state == UIC_LINK_HIBERN8_STATE) {
8692 ret = ufshcd_uic_hibern8_enter(hba);
8694 ufshcd_set_link_hibern8(hba);
8696 dev_err(hba->dev, "%s: hibern8 enter failed %d\n",
8702 * If autobkops is enabled, link can't be turned off because
8703 * turning off the link would also turn off the device, except in the
8704 * case of DeepSleep where the device is expected to remain powered.
8706 else if ((req_link_state == UIC_LINK_OFF_STATE) &&
8707 (!check_for_bkops || !hba->auto_bkops_enabled)) {
8709 * Let's make sure that link is in low power mode, we are doing
8710 * this currently by putting the link in Hibern8. Otherway to
8711 * put the link in low power mode is to send the DME end point
8712 * to device and then send the DME reset command to local
8713 * unipro. But putting the link in hibern8 is much faster.
8715 * Note also that putting the link in Hibern8 is a requirement
8716 * for entering DeepSleep.
8718 ret = ufshcd_uic_hibern8_enter(hba);
8720 dev_err(hba->dev, "%s: hibern8 enter failed %d\n",
8725 * Change controller state to "reset state" which
8726 * should also put the link in off/reset state
8728 ufshcd_hba_stop(hba);
8730 * TODO: Check if we need any delay to make sure that
8731 * controller is reset
8733 ufshcd_set_link_off(hba);
8740 static void ufshcd_vreg_set_lpm(struct ufs_hba *hba)
8742 bool vcc_off = false;
8745 * It seems some UFS devices may keep drawing more than sleep current
8746 * (atleast for 500us) from UFS rails (especially from VCCQ rail).
8747 * To avoid this situation, add 2ms delay before putting these UFS
8748 * rails in LPM mode.
8750 if (!ufshcd_is_link_active(hba) &&
8751 hba->dev_quirks & UFS_DEVICE_QUIRK_DELAY_BEFORE_LPM)
8752 usleep_range(2000, 2100);
8755 * If UFS device is either in UFS_Sleep turn off VCC rail to save some
8758 * If UFS device and link is in OFF state, all power supplies (VCC,
8759 * VCCQ, VCCQ2) can be turned off if power on write protect is not
8760 * required. If UFS link is inactive (Hibern8 or OFF state) and device
8761 * is in sleep state, put VCCQ & VCCQ2 rails in LPM mode.
8763 * Ignore the error returned by ufshcd_toggle_vreg() as device is anyway
8764 * in low power state which would save some power.
8766 * If Write Booster is enabled and the device needs to flush the WB
8767 * buffer OR if bkops status is urgent for WB, keep Vcc on.
8769 if (ufshcd_is_ufs_dev_poweroff(hba) && ufshcd_is_link_off(hba) &&
8770 !hba->dev_info.is_lu_power_on_wp) {
8771 ufshcd_setup_vreg(hba, false);
8773 } else if (!ufshcd_is_ufs_dev_active(hba)) {
8774 ufshcd_toggle_vreg(hba->dev, hba->vreg_info.vcc, false);
8776 if (ufshcd_is_link_hibern8(hba) || ufshcd_is_link_off(hba)) {
8777 ufshcd_config_vreg_lpm(hba, hba->vreg_info.vccq);
8778 ufshcd_config_vreg_lpm(hba, hba->vreg_info.vccq2);
8783 * Some UFS devices require delay after VCC power rail is turned-off.
8785 if (vcc_off && hba->vreg_info.vcc &&
8786 hba->dev_quirks & UFS_DEVICE_QUIRK_DELAY_AFTER_LPM)
8787 usleep_range(5000, 5100);
8791 static int ufshcd_vreg_set_hpm(struct ufs_hba *hba)
8795 if (ufshcd_is_ufs_dev_poweroff(hba) && ufshcd_is_link_off(hba) &&
8796 !hba->dev_info.is_lu_power_on_wp) {
8797 ret = ufshcd_setup_vreg(hba, true);
8798 } else if (!ufshcd_is_ufs_dev_active(hba)) {
8799 if (!ufshcd_is_link_active(hba)) {
8800 ret = ufshcd_config_vreg_hpm(hba, hba->vreg_info.vccq);
8803 ret = ufshcd_config_vreg_hpm(hba, hba->vreg_info.vccq2);
8807 ret = ufshcd_toggle_vreg(hba->dev, hba->vreg_info.vcc, true);
8812 ufshcd_config_vreg_lpm(hba, hba->vreg_info.vccq);
8814 ufshcd_toggle_vreg(hba->dev, hba->vreg_info.vcc, false);
8818 #endif /* CONFIG_PM */
8820 static void ufshcd_hba_vreg_set_lpm(struct ufs_hba *hba)
8822 if (ufshcd_is_link_off(hba) || ufshcd_can_aggressive_pc(hba))
8823 ufshcd_setup_hba_vreg(hba, false);
8826 static void ufshcd_hba_vreg_set_hpm(struct ufs_hba *hba)
8828 if (ufshcd_is_link_off(hba) || ufshcd_can_aggressive_pc(hba))
8829 ufshcd_setup_hba_vreg(hba, true);
8832 static int __ufshcd_wl_suspend(struct ufs_hba *hba, enum ufs_pm_op pm_op)
8835 int check_for_bkops;
8836 enum ufs_pm_level pm_lvl;
8837 enum ufs_dev_pwr_mode req_dev_pwr_mode;
8838 enum uic_link_state req_link_state;
8840 hba->pm_op_in_progress = true;
8841 if (pm_op != UFS_SHUTDOWN_PM) {
8842 pm_lvl = pm_op == UFS_RUNTIME_PM ?
8843 hba->rpm_lvl : hba->spm_lvl;
8844 req_dev_pwr_mode = ufs_get_pm_lvl_to_dev_pwr_mode(pm_lvl);
8845 req_link_state = ufs_get_pm_lvl_to_link_pwr_state(pm_lvl);
8847 req_dev_pwr_mode = UFS_POWERDOWN_PWR_MODE;
8848 req_link_state = UIC_LINK_OFF_STATE;
8851 ufshpb_suspend(hba);
8854 * If we can't transition into any of the low power modes
8855 * just gate the clocks.
8857 ufshcd_hold(hba, false);
8858 hba->clk_gating.is_suspended = true;
8860 if (ufshcd_is_clkscaling_supported(hba))
8861 ufshcd_clk_scaling_suspend(hba, true);
8863 if (req_dev_pwr_mode == UFS_ACTIVE_PWR_MODE &&
8864 req_link_state == UIC_LINK_ACTIVE_STATE) {
8868 if ((req_dev_pwr_mode == hba->curr_dev_pwr_mode) &&
8869 (req_link_state == hba->uic_link_state))
8870 goto enable_scaling;
8872 /* UFS device & link must be active before we enter in this function */
8873 if (!ufshcd_is_ufs_dev_active(hba) || !ufshcd_is_link_active(hba)) {
8875 goto enable_scaling;
8878 if (pm_op == UFS_RUNTIME_PM) {
8879 if (ufshcd_can_autobkops_during_suspend(hba)) {
8881 * The device is idle with no requests in the queue,
8882 * allow background operations if bkops status shows
8883 * that performance might be impacted.
8885 ret = ufshcd_urgent_bkops(hba);
8887 goto enable_scaling;
8889 /* make sure that auto bkops is disabled */
8890 ufshcd_disable_auto_bkops(hba);
8893 * If device needs to do BKOP or WB buffer flush during
8894 * Hibern8, keep device power mode as "active power mode"
8897 hba->dev_info.b_rpm_dev_flush_capable =
8898 hba->auto_bkops_enabled ||
8899 (((req_link_state == UIC_LINK_HIBERN8_STATE) ||
8900 ((req_link_state == UIC_LINK_ACTIVE_STATE) &&
8901 ufshcd_is_auto_hibern8_enabled(hba))) &&
8902 ufshcd_wb_need_flush(hba));
8905 flush_work(&hba->eeh_work);
8907 ret = ufshcd_vops_suspend(hba, pm_op, PRE_CHANGE);
8909 goto enable_scaling;
8911 if (req_dev_pwr_mode != hba->curr_dev_pwr_mode) {
8912 if (pm_op != UFS_RUNTIME_PM)
8913 /* ensure that bkops is disabled */
8914 ufshcd_disable_auto_bkops(hba);
8916 if (!hba->dev_info.b_rpm_dev_flush_capable) {
8917 ret = ufshcd_set_dev_pwr_mode(hba, req_dev_pwr_mode);
8919 goto enable_scaling;
8924 * In the case of DeepSleep, the device is expected to remain powered
8925 * with the link off, so do not check for bkops.
8927 check_for_bkops = !ufshcd_is_ufs_dev_deepsleep(hba);
8928 ret = ufshcd_link_state_transition(hba, req_link_state, check_for_bkops);
8930 goto set_dev_active;
8934 * Call vendor specific suspend callback. As these callbacks may access
8935 * vendor specific host controller register space call them before the
8936 * host clocks are ON.
8938 ret = ufshcd_vops_suspend(hba, pm_op, POST_CHANGE);
8940 goto set_link_active;
8945 * Device hardware reset is required to exit DeepSleep. Also, for
8946 * DeepSleep, the link is off so host reset and restore will be done
8949 if (ufshcd_is_ufs_dev_deepsleep(hba)) {
8950 ufshcd_device_reset(hba);
8951 WARN_ON(!ufshcd_is_link_off(hba));
8953 if (ufshcd_is_link_hibern8(hba) && !ufshcd_uic_hibern8_exit(hba))
8954 ufshcd_set_link_active(hba);
8955 else if (ufshcd_is_link_off(hba))
8956 ufshcd_host_reset_and_restore(hba);
8958 /* Can also get here needing to exit DeepSleep */
8959 if (ufshcd_is_ufs_dev_deepsleep(hba)) {
8960 ufshcd_device_reset(hba);
8961 ufshcd_host_reset_and_restore(hba);
8963 if (!ufshcd_set_dev_pwr_mode(hba, UFS_ACTIVE_PWR_MODE))
8964 ufshcd_disable_auto_bkops(hba);
8966 if (ufshcd_is_clkscaling_supported(hba))
8967 ufshcd_clk_scaling_suspend(hba, false);
8969 hba->dev_info.b_rpm_dev_flush_capable = false;
8971 if (hba->dev_info.b_rpm_dev_flush_capable) {
8972 schedule_delayed_work(&hba->rpm_dev_flush_recheck_work,
8973 msecs_to_jiffies(RPM_DEV_FLUSH_RECHECK_WORK_DELAY_MS));
8977 ufshcd_update_evt_hist(hba, UFS_EVT_WL_SUSP_ERR, (u32)ret);
8978 hba->clk_gating.is_suspended = false;
8979 ufshcd_release(hba);
8982 hba->pm_op_in_progress = false;
8987 static int __ufshcd_wl_resume(struct ufs_hba *hba, enum ufs_pm_op pm_op)
8990 enum uic_link_state old_link_state = hba->uic_link_state;
8992 hba->pm_op_in_progress = true;
8995 * Call vendor specific resume callback. As these callbacks may access
8996 * vendor specific host controller register space call them when the
8997 * host clocks are ON.
8999 ret = ufshcd_vops_resume(hba, pm_op);
9003 /* For DeepSleep, the only supported option is to have the link off */
9004 WARN_ON(ufshcd_is_ufs_dev_deepsleep(hba) && !ufshcd_is_link_off(hba));
9006 if (ufshcd_is_link_hibern8(hba)) {
9007 ret = ufshcd_uic_hibern8_exit(hba);
9009 ufshcd_set_link_active(hba);
9011 dev_err(hba->dev, "%s: hibern8 exit failed %d\n",
9013 goto vendor_suspend;
9015 } else if (ufshcd_is_link_off(hba)) {
9017 * A full initialization of the host and the device is
9018 * required since the link was put to off during suspend.
9019 * Note, in the case of DeepSleep, the device will exit
9020 * DeepSleep due to device reset.
9022 ret = ufshcd_reset_and_restore(hba);
9024 * ufshcd_reset_and_restore() should have already
9025 * set the link state as active
9027 if (ret || !ufshcd_is_link_active(hba))
9028 goto vendor_suspend;
9031 if (!ufshcd_is_ufs_dev_active(hba)) {
9032 ret = ufshcd_set_dev_pwr_mode(hba, UFS_ACTIVE_PWR_MODE);
9034 goto set_old_link_state;
9037 if (ufshcd_keep_autobkops_enabled_except_suspend(hba))
9038 ufshcd_enable_auto_bkops(hba);
9041 * If BKOPs operations are urgently needed at this moment then
9042 * keep auto-bkops enabled or else disable it.
9044 ufshcd_urgent_bkops(hba);
9046 if (hba->ee_usr_mask)
9047 ufshcd_write_ee_control(hba);
9049 if (ufshcd_is_clkscaling_supported(hba))
9050 ufshcd_clk_scaling_suspend(hba, false);
9052 if (hba->dev_info.b_rpm_dev_flush_capable) {
9053 hba->dev_info.b_rpm_dev_flush_capable = false;
9054 cancel_delayed_work(&hba->rpm_dev_flush_recheck_work);
9057 /* Enable Auto-Hibernate if configured */
9058 ufshcd_auto_hibern8_enable(hba);
9064 ufshcd_link_state_transition(hba, old_link_state, 0);
9066 ufshcd_vops_suspend(hba, pm_op, PRE_CHANGE);
9067 ufshcd_vops_suspend(hba, pm_op, POST_CHANGE);
9070 ufshcd_update_evt_hist(hba, UFS_EVT_WL_RES_ERR, (u32)ret);
9071 hba->clk_gating.is_suspended = false;
9072 ufshcd_release(hba);
9073 hba->pm_op_in_progress = false;
9077 static int ufshcd_wl_runtime_suspend(struct device *dev)
9079 struct scsi_device *sdev = to_scsi_device(dev);
9080 struct ufs_hba *hba;
9082 ktime_t start = ktime_get();
9084 hba = shost_priv(sdev->host);
9086 ret = __ufshcd_wl_suspend(hba, UFS_RUNTIME_PM);
9088 dev_err(&sdev->sdev_gendev, "%s failed: %d\n", __func__, ret);
9090 trace_ufshcd_wl_runtime_suspend(dev_name(dev), ret,
9091 ktime_to_us(ktime_sub(ktime_get(), start)),
9092 hba->curr_dev_pwr_mode, hba->uic_link_state);
9097 static int ufshcd_wl_runtime_resume(struct device *dev)
9099 struct scsi_device *sdev = to_scsi_device(dev);
9100 struct ufs_hba *hba;
9102 ktime_t start = ktime_get();
9104 hba = shost_priv(sdev->host);
9106 ret = __ufshcd_wl_resume(hba, UFS_RUNTIME_PM);
9108 dev_err(&sdev->sdev_gendev, "%s failed: %d\n", __func__, ret);
9110 trace_ufshcd_wl_runtime_resume(dev_name(dev), ret,
9111 ktime_to_us(ktime_sub(ktime_get(), start)),
9112 hba->curr_dev_pwr_mode, hba->uic_link_state);
9118 #ifdef CONFIG_PM_SLEEP
9119 static int ufshcd_wl_suspend(struct device *dev)
9121 struct scsi_device *sdev = to_scsi_device(dev);
9122 struct ufs_hba *hba;
9124 ktime_t start = ktime_get();
9126 hba = shost_priv(sdev->host);
9127 down(&hba->host_sem);
9129 if (pm_runtime_suspended(dev))
9132 ret = __ufshcd_wl_suspend(hba, UFS_SYSTEM_PM);
9134 dev_err(&sdev->sdev_gendev, "%s failed: %d\n", __func__, ret);
9140 hba->is_sys_suspended = true;
9141 trace_ufshcd_wl_suspend(dev_name(dev), ret,
9142 ktime_to_us(ktime_sub(ktime_get(), start)),
9143 hba->curr_dev_pwr_mode, hba->uic_link_state);
9148 static int ufshcd_wl_resume(struct device *dev)
9150 struct scsi_device *sdev = to_scsi_device(dev);
9151 struct ufs_hba *hba;
9153 ktime_t start = ktime_get();
9155 hba = shost_priv(sdev->host);
9157 if (pm_runtime_suspended(dev))
9160 ret = __ufshcd_wl_resume(hba, UFS_SYSTEM_PM);
9162 dev_err(&sdev->sdev_gendev, "%s failed: %d\n", __func__, ret);
9164 trace_ufshcd_wl_resume(dev_name(dev), ret,
9165 ktime_to_us(ktime_sub(ktime_get(), start)),
9166 hba->curr_dev_pwr_mode, hba->uic_link_state);
9168 hba->is_sys_suspended = false;
9174 static void ufshcd_wl_shutdown(struct device *dev)
9176 struct scsi_device *sdev = to_scsi_device(dev);
9177 struct ufs_hba *hba;
9179 hba = shost_priv(sdev->host);
9181 down(&hba->host_sem);
9182 hba->shutting_down = true;
9185 /* Turn on everything while shutting down */
9186 ufshcd_rpm_get_sync(hba);
9187 scsi_device_quiesce(sdev);
9188 shost_for_each_device(sdev, hba->host) {
9189 if (sdev == hba->sdev_ufs_device)
9191 scsi_device_quiesce(sdev);
9193 __ufshcd_wl_suspend(hba, UFS_SHUTDOWN_PM);
9197 * ufshcd_suspend - helper function for suspend operations
9198 * @hba: per adapter instance
9200 * This function will put disable irqs, turn off clocks
9201 * and set vreg and hba-vreg in lpm mode.
9203 static int ufshcd_suspend(struct ufs_hba *hba)
9207 if (!hba->is_powered)
9210 * Disable the host irq as host controller as there won't be any
9211 * host controller transaction expected till resume.
9213 ufshcd_disable_irq(hba);
9214 ret = ufshcd_setup_clocks(hba, false);
9216 ufshcd_enable_irq(hba);
9219 if (ufshcd_is_clkgating_allowed(hba)) {
9220 hba->clk_gating.state = CLKS_OFF;
9221 trace_ufshcd_clk_gating(dev_name(hba->dev),
9222 hba->clk_gating.state);
9225 ufshcd_vreg_set_lpm(hba);
9226 /* Put the host controller in low power mode if possible */
9227 ufshcd_hba_vreg_set_lpm(hba);
9233 * ufshcd_resume - helper function for resume operations
9234 * @hba: per adapter instance
9236 * This function basically turns on the regulators, clocks and
9239 * Returns 0 for success and non-zero for failure
9241 static int ufshcd_resume(struct ufs_hba *hba)
9245 if (!hba->is_powered)
9248 ufshcd_hba_vreg_set_hpm(hba);
9249 ret = ufshcd_vreg_set_hpm(hba);
9253 /* Make sure clocks are enabled before accessing controller */
9254 ret = ufshcd_setup_clocks(hba, true);
9258 /* enable the host irq as host controller would be active soon */
9259 ufshcd_enable_irq(hba);
9263 ufshcd_vreg_set_lpm(hba);
9266 ufshcd_update_evt_hist(hba, UFS_EVT_RESUME_ERR, (u32)ret);
9269 #endif /* CONFIG_PM */
9271 #ifdef CONFIG_PM_SLEEP
9273 * ufshcd_system_suspend - system suspend callback
9274 * @dev: Device associated with the UFS controller.
9276 * Executed before putting the system into a sleep state in which the contents
9277 * of main memory are preserved.
9279 * Returns 0 for success and non-zero for failure
9281 int ufshcd_system_suspend(struct device *dev)
9283 struct ufs_hba *hba = dev_get_drvdata(dev);
9285 ktime_t start = ktime_get();
9287 if (pm_runtime_suspended(hba->dev))
9290 ret = ufshcd_suspend(hba);
9292 trace_ufshcd_system_suspend(dev_name(hba->dev), ret,
9293 ktime_to_us(ktime_sub(ktime_get(), start)),
9294 hba->curr_dev_pwr_mode, hba->uic_link_state);
9297 EXPORT_SYMBOL(ufshcd_system_suspend);
9300 * ufshcd_system_resume - system resume callback
9301 * @dev: Device associated with the UFS controller.
9303 * Executed after waking the system up from a sleep state in which the contents
9304 * of main memory were preserved.
9306 * Returns 0 for success and non-zero for failure
9308 int ufshcd_system_resume(struct device *dev)
9310 struct ufs_hba *hba = dev_get_drvdata(dev);
9311 ktime_t start = ktime_get();
9314 if (pm_runtime_suspended(hba->dev))
9317 ret = ufshcd_resume(hba);
9320 trace_ufshcd_system_resume(dev_name(hba->dev), ret,
9321 ktime_to_us(ktime_sub(ktime_get(), start)),
9322 hba->curr_dev_pwr_mode, hba->uic_link_state);
9326 EXPORT_SYMBOL(ufshcd_system_resume);
9327 #endif /* CONFIG_PM_SLEEP */
9331 * ufshcd_runtime_suspend - runtime suspend callback
9332 * @dev: Device associated with the UFS controller.
9334 * Check the description of ufshcd_suspend() function for more details.
9336 * Returns 0 for success and non-zero for failure
9338 int ufshcd_runtime_suspend(struct device *dev)
9340 struct ufs_hba *hba = dev_get_drvdata(dev);
9342 ktime_t start = ktime_get();
9344 ret = ufshcd_suspend(hba);
9346 trace_ufshcd_runtime_suspend(dev_name(hba->dev), ret,
9347 ktime_to_us(ktime_sub(ktime_get(), start)),
9348 hba->curr_dev_pwr_mode, hba->uic_link_state);
9351 EXPORT_SYMBOL(ufshcd_runtime_suspend);
9354 * ufshcd_runtime_resume - runtime resume routine
9355 * @dev: Device associated with the UFS controller.
9357 * This function basically brings controller
9358 * to active state. Following operations are done in this function:
9360 * 1. Turn on all the controller related clocks
9361 * 2. Turn ON VCC rail
9363 int ufshcd_runtime_resume(struct device *dev)
9365 struct ufs_hba *hba = dev_get_drvdata(dev);
9367 ktime_t start = ktime_get();
9369 ret = ufshcd_resume(hba);
9371 trace_ufshcd_runtime_resume(dev_name(hba->dev), ret,
9372 ktime_to_us(ktime_sub(ktime_get(), start)),
9373 hba->curr_dev_pwr_mode, hba->uic_link_state);
9376 EXPORT_SYMBOL(ufshcd_runtime_resume);
9377 #endif /* CONFIG_PM */
9380 * ufshcd_shutdown - shutdown routine
9381 * @hba: per adapter instance
9383 * This function would turn off both UFS device and UFS hba
9384 * regulators. It would also disable clocks.
9386 * Returns 0 always to allow force shutdown even in case of errors.
9388 int ufshcd_shutdown(struct ufs_hba *hba)
9390 if (ufshcd_is_ufs_dev_poweroff(hba) && ufshcd_is_link_off(hba))
9393 pm_runtime_get_sync(hba->dev);
9395 ufshcd_suspend(hba);
9397 hba->is_powered = false;
9398 /* allow force shutdown even in case of errors */
9401 EXPORT_SYMBOL(ufshcd_shutdown);
9404 * ufshcd_remove - de-allocate SCSI host and host memory space
9405 * data structure memory
9406 * @hba: per adapter instance
9408 void ufshcd_remove(struct ufs_hba *hba)
9410 if (hba->sdev_ufs_device)
9411 ufshcd_rpm_get_sync(hba);
9412 ufs_hwmon_remove(hba);
9413 ufs_bsg_remove(hba);
9415 ufs_sysfs_remove_nodes(hba->dev);
9416 blk_cleanup_queue(hba->tmf_queue);
9417 blk_mq_free_tag_set(&hba->tmf_tag_set);
9418 scsi_remove_host(hba->host);
9419 /* disable interrupts */
9420 ufshcd_disable_intr(hba, hba->intr_mask);
9421 ufshcd_hba_stop(hba);
9422 ufshcd_hba_exit(hba);
9424 EXPORT_SYMBOL_GPL(ufshcd_remove);
9427 * ufshcd_dealloc_host - deallocate Host Bus Adapter (HBA)
9428 * @hba: pointer to Host Bus Adapter (HBA)
9430 void ufshcd_dealloc_host(struct ufs_hba *hba)
9432 scsi_host_put(hba->host);
9434 EXPORT_SYMBOL_GPL(ufshcd_dealloc_host);
9437 * ufshcd_set_dma_mask - Set dma mask based on the controller
9438 * addressing capability
9439 * @hba: per adapter instance
9441 * Returns 0 for success, non-zero for failure
9443 static int ufshcd_set_dma_mask(struct ufs_hba *hba)
9445 if (hba->capabilities & MASK_64_ADDRESSING_SUPPORT) {
9446 if (!dma_set_mask_and_coherent(hba->dev, DMA_BIT_MASK(64)))
9449 return dma_set_mask_and_coherent(hba->dev, DMA_BIT_MASK(32));
9453 * ufshcd_alloc_host - allocate Host Bus Adapter (HBA)
9454 * @dev: pointer to device handle
9455 * @hba_handle: driver private handle
9456 * Returns 0 on success, non-zero value on failure
9458 int ufshcd_alloc_host(struct device *dev, struct ufs_hba **hba_handle)
9460 struct Scsi_Host *host;
9461 struct ufs_hba *hba;
9466 "Invalid memory reference for dev is NULL\n");
9471 host = scsi_host_alloc(&ufshcd_driver_template,
9472 sizeof(struct ufs_hba));
9474 dev_err(dev, "scsi_host_alloc failed\n");
9478 host->nr_maps = HCTX_TYPE_POLL + 1;
9479 hba = shost_priv(host);
9482 hba->dev_ref_clk_freq = REF_CLK_FREQ_INVAL;
9483 hba->nop_out_timeout = NOP_OUT_TIMEOUT;
9484 INIT_LIST_HEAD(&hba->clk_list_head);
9485 spin_lock_init(&hba->outstanding_lock);
9492 EXPORT_SYMBOL(ufshcd_alloc_host);
9494 /* This function exists because blk_mq_alloc_tag_set() requires this. */
9495 static blk_status_t ufshcd_queue_tmf(struct blk_mq_hw_ctx *hctx,
9496 const struct blk_mq_queue_data *qd)
9499 return BLK_STS_NOTSUPP;
9502 static const struct blk_mq_ops ufshcd_tmf_ops = {
9503 .queue_rq = ufshcd_queue_tmf,
9507 * ufshcd_init - Driver initialization routine
9508 * @hba: per-adapter instance
9509 * @mmio_base: base register address
9510 * @irq: Interrupt line of device
9511 * Returns 0 on success, non-zero value on failure
9513 int ufshcd_init(struct ufs_hba *hba, void __iomem *mmio_base, unsigned int irq)
9516 struct Scsi_Host *host = hba->host;
9517 struct device *dev = hba->dev;
9518 char eh_wq_name[sizeof("ufs_eh_wq_00")];
9521 * dev_set_drvdata() must be called before any callbacks are registered
9522 * that use dev_get_drvdata() (frequency scaling, clock scaling, hwmon,
9525 dev_set_drvdata(dev, hba);
9529 "Invalid memory reference for mmio_base is NULL\n");
9534 hba->mmio_base = mmio_base;
9536 hba->vps = &ufs_hba_vps;
9538 err = ufshcd_hba_init(hba);
9542 /* Read capabilities registers */
9543 err = ufshcd_hba_capabilities(hba);
9547 /* Get UFS version supported by the controller */
9548 hba->ufs_version = ufshcd_get_ufs_version(hba);
9550 /* Get Interrupt bit mask per version */
9551 hba->intr_mask = ufshcd_get_intr_mask(hba);
9553 err = ufshcd_set_dma_mask(hba);
9555 dev_err(hba->dev, "set dma mask failed\n");
9559 /* Allocate memory for host memory space */
9560 err = ufshcd_memory_alloc(hba);
9562 dev_err(hba->dev, "Memory allocation failed\n");
9567 ufshcd_host_memory_configure(hba);
9569 host->can_queue = hba->nutrs - UFSHCD_NUM_RESERVED;
9570 host->cmd_per_lun = hba->nutrs - UFSHCD_NUM_RESERVED;
9571 host->max_id = UFSHCD_MAX_ID;
9572 host->max_lun = UFS_MAX_LUNS;
9573 host->max_channel = UFSHCD_MAX_CHANNEL;
9574 host->unique_id = host->host_no;
9575 host->max_cmd_len = UFS_CDB_SIZE;
9577 hba->max_pwr_info.is_valid = false;
9579 /* Initialize work queues */
9580 snprintf(eh_wq_name, sizeof(eh_wq_name), "ufs_eh_wq_%d",
9581 hba->host->host_no);
9582 hba->eh_wq = create_singlethread_workqueue(eh_wq_name);
9584 dev_err(hba->dev, "%s: failed to create eh workqueue\n",
9589 INIT_WORK(&hba->eh_work, ufshcd_err_handler);
9590 INIT_WORK(&hba->eeh_work, ufshcd_exception_event_handler);
9592 sema_init(&hba->host_sem, 1);
9594 /* Initialize UIC command mutex */
9595 mutex_init(&hba->uic_cmd_mutex);
9597 /* Initialize mutex for device management commands */
9598 mutex_init(&hba->dev_cmd.lock);
9600 /* Initialize mutex for exception event control */
9601 mutex_init(&hba->ee_ctrl_mutex);
9603 init_rwsem(&hba->clk_scaling_lock);
9605 ufshcd_init_clk_gating(hba);
9607 ufshcd_init_clk_scaling(hba);
9610 * In order to avoid any spurious interrupt immediately after
9611 * registering UFS controller interrupt handler, clear any pending UFS
9612 * interrupt status and disable all the UFS interrupts.
9614 ufshcd_writel(hba, ufshcd_readl(hba, REG_INTERRUPT_STATUS),
9615 REG_INTERRUPT_STATUS);
9616 ufshcd_writel(hba, 0, REG_INTERRUPT_ENABLE);
9618 * Make sure that UFS interrupts are disabled and any pending interrupt
9619 * status is cleared before registering UFS interrupt handler.
9623 /* IRQ registration */
9624 err = devm_request_irq(dev, irq, ufshcd_intr, IRQF_SHARED, UFSHCD, hba);
9626 dev_err(hba->dev, "request irq failed\n");
9629 hba->is_irq_enabled = true;
9632 err = scsi_add_host(host, hba->dev);
9634 dev_err(hba->dev, "scsi_add_host failed\n");
9638 hba->tmf_tag_set = (struct blk_mq_tag_set) {
9640 .queue_depth = hba->nutmrs,
9641 .ops = &ufshcd_tmf_ops,
9642 .flags = BLK_MQ_F_NO_SCHED,
9644 err = blk_mq_alloc_tag_set(&hba->tmf_tag_set);
9646 goto out_remove_scsi_host;
9647 hba->tmf_queue = blk_mq_init_queue(&hba->tmf_tag_set);
9648 if (IS_ERR(hba->tmf_queue)) {
9649 err = PTR_ERR(hba->tmf_queue);
9650 goto free_tmf_tag_set;
9652 hba->tmf_rqs = devm_kcalloc(hba->dev, hba->nutmrs,
9653 sizeof(*hba->tmf_rqs), GFP_KERNEL);
9654 if (!hba->tmf_rqs) {
9656 goto free_tmf_queue;
9659 /* Reset the attached device */
9660 ufshcd_device_reset(hba);
9662 ufshcd_init_crypto(hba);
9664 /* Host controller enable */
9665 err = ufshcd_hba_enable(hba);
9667 dev_err(hba->dev, "Host controller enable failed\n");
9668 ufshcd_print_evt_hist(hba);
9669 ufshcd_print_host_state(hba);
9670 goto free_tmf_queue;
9674 * Set the default power management level for runtime and system PM.
9675 * Default power saving mode is to keep UFS link in Hibern8 state
9676 * and UFS device in sleep state.
9678 hba->rpm_lvl = ufs_get_desired_pm_lvl_for_dev_link_state(
9680 UIC_LINK_HIBERN8_STATE);
9681 hba->spm_lvl = ufs_get_desired_pm_lvl_for_dev_link_state(
9683 UIC_LINK_HIBERN8_STATE);
9685 INIT_DELAYED_WORK(&hba->rpm_dev_flush_recheck_work,
9686 ufshcd_rpm_dev_flush_recheck_work);
9688 /* Set the default auto-hiberate idle timer value to 150 ms */
9689 if (ufshcd_is_auto_hibern8_supported(hba) && !hba->ahit) {
9690 hba->ahit = FIELD_PREP(UFSHCI_AHIBERN8_TIMER_MASK, 150) |
9691 FIELD_PREP(UFSHCI_AHIBERN8_SCALE_MASK, 3);
9694 /* Hold auto suspend until async scan completes */
9695 pm_runtime_get_sync(dev);
9696 atomic_set(&hba->scsi_block_reqs_cnt, 0);
9698 * We are assuming that device wasn't put in sleep/power-down
9699 * state exclusively during the boot stage before kernel.
9700 * This assumption helps avoid doing link startup twice during
9701 * ufshcd_probe_hba().
9703 ufshcd_set_ufs_dev_active(hba);
9705 async_schedule(ufshcd_async_scan, hba);
9706 ufs_sysfs_add_nodes(hba->dev);
9708 device_enable_async_suspend(dev);
9712 blk_cleanup_queue(hba->tmf_queue);
9714 blk_mq_free_tag_set(&hba->tmf_tag_set);
9715 out_remove_scsi_host:
9716 scsi_remove_host(hba->host);
9718 hba->is_irq_enabled = false;
9719 ufshcd_hba_exit(hba);
9723 EXPORT_SYMBOL_GPL(ufshcd_init);
9725 void ufshcd_resume_complete(struct device *dev)
9727 struct ufs_hba *hba = dev_get_drvdata(dev);
9729 if (hba->complete_put) {
9730 ufshcd_rpm_put(hba);
9731 hba->complete_put = false;
9734 EXPORT_SYMBOL_GPL(ufshcd_resume_complete);
9736 static bool ufshcd_rpm_ok_for_spm(struct ufs_hba *hba)
9738 struct device *dev = &hba->sdev_ufs_device->sdev_gendev;
9739 enum ufs_dev_pwr_mode dev_pwr_mode;
9740 enum uic_link_state link_state;
9741 unsigned long flags;
9744 spin_lock_irqsave(&dev->power.lock, flags);
9745 dev_pwr_mode = ufs_get_pm_lvl_to_dev_pwr_mode(hba->spm_lvl);
9746 link_state = ufs_get_pm_lvl_to_link_pwr_state(hba->spm_lvl);
9747 res = pm_runtime_suspended(dev) &&
9748 hba->curr_dev_pwr_mode == dev_pwr_mode &&
9749 hba->uic_link_state == link_state &&
9750 !hba->dev_info.b_rpm_dev_flush_capable;
9751 spin_unlock_irqrestore(&dev->power.lock, flags);
9756 int __ufshcd_suspend_prepare(struct device *dev, bool rpm_ok_for_spm)
9758 struct ufs_hba *hba = dev_get_drvdata(dev);
9762 * SCSI assumes that runtime-pm and system-pm for scsi drivers
9763 * are same. And it doesn't wake up the device for system-suspend
9764 * if it's runtime suspended. But ufs doesn't follow that.
9765 * Refer ufshcd_resume_complete()
9767 if (hba->sdev_ufs_device) {
9768 /* Prevent runtime suspend */
9769 ufshcd_rpm_get_noresume(hba);
9771 * Check if already runtime suspended in same state as system
9774 if (!rpm_ok_for_spm || !ufshcd_rpm_ok_for_spm(hba)) {
9775 /* RPM state is not ok for SPM, so runtime resume */
9776 ret = ufshcd_rpm_resume(hba);
9777 if (ret < 0 && ret != -EACCES) {
9778 ufshcd_rpm_put(hba);
9782 hba->complete_put = true;
9786 EXPORT_SYMBOL_GPL(__ufshcd_suspend_prepare);
9788 int ufshcd_suspend_prepare(struct device *dev)
9790 return __ufshcd_suspend_prepare(dev, true);
9792 EXPORT_SYMBOL_GPL(ufshcd_suspend_prepare);
9794 #ifdef CONFIG_PM_SLEEP
9795 static int ufshcd_wl_poweroff(struct device *dev)
9797 struct scsi_device *sdev = to_scsi_device(dev);
9798 struct ufs_hba *hba = shost_priv(sdev->host);
9800 __ufshcd_wl_suspend(hba, UFS_SHUTDOWN_PM);
9805 static int ufshcd_wl_probe(struct device *dev)
9807 struct scsi_device *sdev = to_scsi_device(dev);
9809 if (!is_device_wlun(sdev))
9812 blk_pm_runtime_init(sdev->request_queue, dev);
9813 pm_runtime_set_autosuspend_delay(dev, 0);
9814 pm_runtime_allow(dev);
9819 static int ufshcd_wl_remove(struct device *dev)
9821 pm_runtime_forbid(dev);
9825 static const struct dev_pm_ops ufshcd_wl_pm_ops = {
9826 #ifdef CONFIG_PM_SLEEP
9827 .suspend = ufshcd_wl_suspend,
9828 .resume = ufshcd_wl_resume,
9829 .freeze = ufshcd_wl_suspend,
9830 .thaw = ufshcd_wl_resume,
9831 .poweroff = ufshcd_wl_poweroff,
9832 .restore = ufshcd_wl_resume,
9834 SET_RUNTIME_PM_OPS(ufshcd_wl_runtime_suspend, ufshcd_wl_runtime_resume, NULL)
9838 * ufs_dev_wlun_template - describes ufs device wlun
9839 * ufs-device wlun - used to send pm commands
9840 * All luns are consumers of ufs-device wlun.
9842 * Currently, no sd driver is present for wluns.
9843 * Hence the no specific pm operations are performed.
9844 * With ufs design, SSU should be sent to ufs-device wlun.
9845 * Hence register a scsi driver for ufs wluns only.
9847 static struct scsi_driver ufs_dev_wlun_template = {
9849 .name = "ufs_device_wlun",
9850 .owner = THIS_MODULE,
9851 .probe = ufshcd_wl_probe,
9852 .remove = ufshcd_wl_remove,
9853 .pm = &ufshcd_wl_pm_ops,
9854 .shutdown = ufshcd_wl_shutdown,
9858 static int __init ufshcd_core_init(void)
9862 /* Verify that there are no gaps in struct utp_transfer_cmd_desc. */
9863 static_assert(sizeof(struct utp_transfer_cmd_desc) ==
9864 2 * ALIGNED_UPIU_SIZE +
9865 SG_ALL * sizeof(struct ufshcd_sg_entry));
9869 ret = scsi_register_driver(&ufs_dev_wlun_template.gendrv);
9875 static void __exit ufshcd_core_exit(void)
9878 scsi_unregister_driver(&ufs_dev_wlun_template.gendrv);
9881 module_init(ufshcd_core_init);
9882 module_exit(ufshcd_core_exit);
9884 MODULE_AUTHOR("Santosh Yaragnavi <santosh.sy@samsung.com>");
9885 MODULE_AUTHOR("Vinayak Holikatti <h.vinayak@samsung.com>");
9886 MODULE_DESCRIPTION("Generic UFS host controller driver Core");
9887 MODULE_LICENSE("GPL");
9888 MODULE_VERSION(UFSHCD_DRIVER_VERSION);