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>
20 #include <scsi/scsi_transport.h>
21 #include "../scsi_transport_api.h"
23 #include "ufs_quirks.h"
25 #include "ufs-sysfs.h"
26 #include "ufs-debugfs.h"
27 #include "ufs-fault-injection.h"
29 #include "ufshcd-crypto.h"
31 #include <asm/unaligned.h>
33 #define CREATE_TRACE_POINTS
34 #include <trace/events/ufs.h>
36 #define UFSHCD_ENABLE_INTRS (UTP_TRANSFER_REQ_COMPL |\
39 /* UIC command timeout, unit: ms */
40 #define UIC_CMD_TIMEOUT 500
42 /* NOP OUT retries waiting for NOP IN response */
43 #define NOP_OUT_RETRIES 10
44 /* Timeout after 50 msecs if NOP OUT hangs without response */
45 #define NOP_OUT_TIMEOUT 50 /* msecs */
47 /* Query request retries */
48 #define QUERY_REQ_RETRIES 3
49 /* Query request timeout */
50 #define QUERY_REQ_TIMEOUT 1500 /* 1.5 seconds */
52 /* Task management command timeout */
53 #define TM_CMD_TIMEOUT 100 /* msecs */
55 /* maximum number of retries for a general UIC command */
56 #define UFS_UIC_COMMAND_RETRIES 3
58 /* maximum number of link-startup retries */
59 #define DME_LINKSTARTUP_RETRIES 3
61 /* Maximum retries for Hibern8 enter */
62 #define UIC_HIBERN8_ENTER_RETRIES 3
64 /* maximum number of reset retries before giving up */
65 #define MAX_HOST_RESET_RETRIES 5
67 /* Expose the flag value from utp_upiu_query.value */
68 #define MASK_QUERY_UPIU_FLAG_LOC 0xFF
70 /* Interrupt aggregation default timeout, unit: 40us */
71 #define INT_AGGR_DEF_TO 0x02
73 /* default delay of autosuspend: 2000 ms */
74 #define RPM_AUTOSUSPEND_DELAY_MS 2000
76 /* Default delay of RPM device flush delayed work */
77 #define RPM_DEV_FLUSH_RECHECK_WORK_DELAY_MS 5000
79 /* Default value of wait time before gating device ref clock */
80 #define UFSHCD_REF_CLK_GATING_WAIT_US 0xFF /* microsecs */
82 /* Polling time to wait for fDeviceInit */
83 #define FDEVICEINIT_COMPL_TIMEOUT 1500 /* millisecs */
85 #define wlun_dev_to_hba(dv) shost_priv(to_scsi_device(dv)->host)
87 #define ufshcd_toggle_vreg(_dev, _vreg, _on) \
91 _ret = ufshcd_enable_vreg(_dev, _vreg); \
93 _ret = ufshcd_disable_vreg(_dev, _vreg); \
97 #define ufshcd_hex_dump(prefix_str, buf, len) do { \
98 size_t __len = (len); \
99 print_hex_dump(KERN_ERR, prefix_str, \
100 __len > 4 ? DUMP_PREFIX_OFFSET : DUMP_PREFIX_NONE,\
101 16, 4, buf, __len, false); \
104 int ufshcd_dump_regs(struct ufs_hba *hba, size_t offset, size_t len,
110 if (offset % 4 != 0 || len % 4 != 0) /* keep readl happy */
113 regs = kzalloc(len, GFP_ATOMIC);
117 for (pos = 0; pos < len; pos += 4)
118 regs[pos / 4] = ufshcd_readl(hba, offset + pos);
120 ufshcd_hex_dump(prefix, regs, len);
125 EXPORT_SYMBOL_GPL(ufshcd_dump_regs);
128 UFSHCD_MAX_CHANNEL = 0,
130 UFSHCD_CMD_PER_LUN = 32,
131 UFSHCD_CAN_QUEUE = 32,
134 /* UFSHCD error handling flags */
136 UFSHCD_EH_IN_PROGRESS = (1 << 0),
139 /* UFSHCD UIC layer error flags */
141 UFSHCD_UIC_DL_PA_INIT_ERROR = (1 << 0), /* Data link layer error */
142 UFSHCD_UIC_DL_NAC_RECEIVED_ERROR = (1 << 1), /* Data link layer error */
143 UFSHCD_UIC_DL_TCx_REPLAY_ERROR = (1 << 2), /* Data link layer error */
144 UFSHCD_UIC_NL_ERROR = (1 << 3), /* Network layer error */
145 UFSHCD_UIC_TL_ERROR = (1 << 4), /* Transport Layer error */
146 UFSHCD_UIC_DME_ERROR = (1 << 5), /* DME error */
147 UFSHCD_UIC_PA_GENERIC_ERROR = (1 << 6), /* Generic PA error */
150 #define ufshcd_set_eh_in_progress(h) \
151 ((h)->eh_flags |= UFSHCD_EH_IN_PROGRESS)
152 #define ufshcd_eh_in_progress(h) \
153 ((h)->eh_flags & UFSHCD_EH_IN_PROGRESS)
154 #define ufshcd_clear_eh_in_progress(h) \
155 ((h)->eh_flags &= ~UFSHCD_EH_IN_PROGRESS)
157 struct ufs_pm_lvl_states ufs_pm_lvl_states[] = {
158 [UFS_PM_LVL_0] = {UFS_ACTIVE_PWR_MODE, UIC_LINK_ACTIVE_STATE},
159 [UFS_PM_LVL_1] = {UFS_ACTIVE_PWR_MODE, UIC_LINK_HIBERN8_STATE},
160 [UFS_PM_LVL_2] = {UFS_SLEEP_PWR_MODE, UIC_LINK_ACTIVE_STATE},
161 [UFS_PM_LVL_3] = {UFS_SLEEP_PWR_MODE, UIC_LINK_HIBERN8_STATE},
162 [UFS_PM_LVL_4] = {UFS_POWERDOWN_PWR_MODE, UIC_LINK_HIBERN8_STATE},
163 [UFS_PM_LVL_5] = {UFS_POWERDOWN_PWR_MODE, UIC_LINK_OFF_STATE},
165 * For DeepSleep, the link is first put in hibern8 and then off.
166 * Leaving the link in hibern8 is not supported.
168 [UFS_PM_LVL_6] = {UFS_DEEPSLEEP_PWR_MODE, UIC_LINK_OFF_STATE},
171 static inline enum ufs_dev_pwr_mode
172 ufs_get_pm_lvl_to_dev_pwr_mode(enum ufs_pm_level lvl)
174 return ufs_pm_lvl_states[lvl].dev_state;
177 static inline enum uic_link_state
178 ufs_get_pm_lvl_to_link_pwr_state(enum ufs_pm_level lvl)
180 return ufs_pm_lvl_states[lvl].link_state;
183 static inline enum ufs_pm_level
184 ufs_get_desired_pm_lvl_for_dev_link_state(enum ufs_dev_pwr_mode dev_state,
185 enum uic_link_state link_state)
187 enum ufs_pm_level lvl;
189 for (lvl = UFS_PM_LVL_0; lvl < UFS_PM_LVL_MAX; lvl++) {
190 if ((ufs_pm_lvl_states[lvl].dev_state == dev_state) &&
191 (ufs_pm_lvl_states[lvl].link_state == link_state))
195 /* if no match found, return the level 0 */
199 static struct ufs_dev_fix ufs_fixups[] = {
200 /* UFS cards deviations table */
201 UFS_FIX(UFS_VENDOR_MICRON, UFS_ANY_MODEL,
202 UFS_DEVICE_QUIRK_DELAY_BEFORE_LPM),
203 UFS_FIX(UFS_VENDOR_SAMSUNG, UFS_ANY_MODEL,
204 UFS_DEVICE_QUIRK_DELAY_BEFORE_LPM |
205 UFS_DEVICE_QUIRK_HOST_PA_TACTIVATE |
206 UFS_DEVICE_QUIRK_RECOVERY_FROM_DL_NAC_ERRORS),
207 UFS_FIX(UFS_VENDOR_SKHYNIX, UFS_ANY_MODEL,
208 UFS_DEVICE_QUIRK_HOST_PA_SAVECONFIGTIME),
209 UFS_FIX(UFS_VENDOR_SKHYNIX, "hB8aL1" /*H28U62301AMR*/,
210 UFS_DEVICE_QUIRK_HOST_VS_DEBUGSAVECONFIGTIME),
211 UFS_FIX(UFS_VENDOR_TOSHIBA, UFS_ANY_MODEL,
212 UFS_DEVICE_QUIRK_DELAY_BEFORE_LPM),
213 UFS_FIX(UFS_VENDOR_TOSHIBA, "THGLF2G9C8KBADG",
214 UFS_DEVICE_QUIRK_PA_TACTIVATE),
215 UFS_FIX(UFS_VENDOR_TOSHIBA, "THGLF2G9D8KBADG",
216 UFS_DEVICE_QUIRK_PA_TACTIVATE),
220 static irqreturn_t ufshcd_tmc_handler(struct ufs_hba *hba);
221 static void ufshcd_async_scan(void *data, async_cookie_t cookie);
222 static int ufshcd_reset_and_restore(struct ufs_hba *hba);
223 static int ufshcd_eh_host_reset_handler(struct scsi_cmnd *cmd);
224 static int ufshcd_clear_tm_cmd(struct ufs_hba *hba, int tag);
225 static void ufshcd_hba_exit(struct ufs_hba *hba);
226 static int ufshcd_clear_ua_wluns(struct ufs_hba *hba);
227 static int ufshcd_probe_hba(struct ufs_hba *hba, bool async);
228 static int ufshcd_setup_clocks(struct ufs_hba *hba, bool on);
229 static int ufshcd_uic_hibern8_enter(struct ufs_hba *hba);
230 static inline void ufshcd_add_delay_before_dme_cmd(struct ufs_hba *hba);
231 static int ufshcd_host_reset_and_restore(struct ufs_hba *hba);
232 static void ufshcd_resume_clkscaling(struct ufs_hba *hba);
233 static void ufshcd_suspend_clkscaling(struct ufs_hba *hba);
234 static void __ufshcd_suspend_clkscaling(struct ufs_hba *hba);
235 static int ufshcd_scale_clks(struct ufs_hba *hba, bool scale_up);
236 static irqreturn_t ufshcd_intr(int irq, void *__hba);
237 static int ufshcd_change_power_mode(struct ufs_hba *hba,
238 struct ufs_pa_layer_attr *pwr_mode);
239 static int ufshcd_setup_hba_vreg(struct ufs_hba *hba, bool on);
240 static int ufshcd_setup_vreg(struct ufs_hba *hba, bool on);
241 static inline int ufshcd_config_vreg_hpm(struct ufs_hba *hba,
242 struct ufs_vreg *vreg);
243 static int ufshcd_try_to_abort_task(struct ufs_hba *hba, int tag);
244 static void ufshcd_wb_toggle_flush_during_h8(struct ufs_hba *hba, bool set);
245 static inline void ufshcd_wb_toggle_flush(struct ufs_hba *hba, bool enable);
246 static void ufshcd_hba_vreg_set_lpm(struct ufs_hba *hba);
247 static void ufshcd_hba_vreg_set_hpm(struct ufs_hba *hba);
249 static inline void ufshcd_enable_irq(struct ufs_hba *hba)
251 if (!hba->is_irq_enabled) {
252 enable_irq(hba->irq);
253 hba->is_irq_enabled = true;
257 static inline void ufshcd_disable_irq(struct ufs_hba *hba)
259 if (hba->is_irq_enabled) {
260 disable_irq(hba->irq);
261 hba->is_irq_enabled = false;
265 static inline void ufshcd_wb_config(struct ufs_hba *hba)
267 if (!ufshcd_is_wb_allowed(hba))
270 ufshcd_wb_toggle(hba, true);
272 ufshcd_wb_toggle_flush_during_h8(hba, true);
273 if (!(hba->quirks & UFSHCI_QUIRK_SKIP_MANUAL_WB_FLUSH_CTRL))
274 ufshcd_wb_toggle_flush(hba, true);
277 static void ufshcd_scsi_unblock_requests(struct ufs_hba *hba)
279 if (atomic_dec_and_test(&hba->scsi_block_reqs_cnt))
280 scsi_unblock_requests(hba->host);
283 static void ufshcd_scsi_block_requests(struct ufs_hba *hba)
285 if (atomic_inc_return(&hba->scsi_block_reqs_cnt) == 1)
286 scsi_block_requests(hba->host);
289 static void ufshcd_add_cmd_upiu_trace(struct ufs_hba *hba, unsigned int tag,
290 enum ufs_trace_str_t str_t)
292 struct utp_upiu_req *rq = hba->lrb[tag].ucd_req_ptr;
293 struct utp_upiu_header *header;
295 if (!trace_ufshcd_upiu_enabled())
298 if (str_t == UFS_CMD_SEND)
299 header = &rq->header;
301 header = &hba->lrb[tag].ucd_rsp_ptr->header;
303 trace_ufshcd_upiu(dev_name(hba->dev), str_t, header, &rq->sc.cdb,
307 static void ufshcd_add_query_upiu_trace(struct ufs_hba *hba,
308 enum ufs_trace_str_t str_t,
309 struct utp_upiu_req *rq_rsp)
311 if (!trace_ufshcd_upiu_enabled())
314 trace_ufshcd_upiu(dev_name(hba->dev), str_t, &rq_rsp->header,
315 &rq_rsp->qr, UFS_TSF_OSF);
318 static void ufshcd_add_tm_upiu_trace(struct ufs_hba *hba, unsigned int tag,
319 enum ufs_trace_str_t str_t)
321 int off = (int)tag - hba->nutrs;
322 struct utp_task_req_desc *descp = &hba->utmrdl_base_addr[off];
324 if (!trace_ufshcd_upiu_enabled())
327 if (str_t == UFS_TM_SEND)
328 trace_ufshcd_upiu(dev_name(hba->dev), str_t,
329 &descp->upiu_req.req_header,
330 &descp->upiu_req.input_param1,
333 trace_ufshcd_upiu(dev_name(hba->dev), str_t,
334 &descp->upiu_rsp.rsp_header,
335 &descp->upiu_rsp.output_param1,
339 static void ufshcd_add_uic_command_trace(struct ufs_hba *hba,
340 struct uic_command *ucmd,
341 enum ufs_trace_str_t str_t)
345 if (!trace_ufshcd_uic_command_enabled())
348 if (str_t == UFS_CMD_SEND)
351 cmd = ufshcd_readl(hba, REG_UIC_COMMAND);
353 trace_ufshcd_uic_command(dev_name(hba->dev), str_t, cmd,
354 ufshcd_readl(hba, REG_UIC_COMMAND_ARG_1),
355 ufshcd_readl(hba, REG_UIC_COMMAND_ARG_2),
356 ufshcd_readl(hba, REG_UIC_COMMAND_ARG_3));
359 static void ufshcd_add_command_trace(struct ufs_hba *hba, unsigned int tag,
360 enum ufs_trace_str_t str_t)
363 u8 opcode = 0, group_id = 0;
365 struct ufshcd_lrb *lrbp = &hba->lrb[tag];
366 struct scsi_cmnd *cmd = lrbp->cmd;
367 int transfer_len = -1;
372 /* trace UPIU also */
373 ufshcd_add_cmd_upiu_trace(hba, tag, str_t);
374 if (!trace_ufshcd_command_enabled())
377 opcode = cmd->cmnd[0];
378 lba = scsi_get_lba(cmd);
380 if (opcode == READ_10 || opcode == WRITE_10) {
382 * Currently we only fully trace read(10) and write(10) commands
385 be32_to_cpu(lrbp->ucd_req_ptr->sc.exp_data_transfer_len);
386 if (opcode == WRITE_10)
387 group_id = lrbp->cmd->cmnd[6];
388 } else if (opcode == UNMAP) {
390 * The number of Bytes to be unmapped beginning with the lba.
392 transfer_len = blk_rq_bytes(cmd->request);
395 intr = ufshcd_readl(hba, REG_INTERRUPT_STATUS);
396 doorbell = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
397 trace_ufshcd_command(dev_name(hba->dev), str_t, tag,
398 doorbell, transfer_len, intr, lba, opcode, group_id);
401 static void ufshcd_print_clk_freqs(struct ufs_hba *hba)
403 struct ufs_clk_info *clki;
404 struct list_head *head = &hba->clk_list_head;
406 if (list_empty(head))
409 list_for_each_entry(clki, head, list) {
410 if (!IS_ERR_OR_NULL(clki->clk) && clki->min_freq &&
412 dev_err(hba->dev, "clk: %s, rate: %u\n",
413 clki->name, clki->curr_freq);
417 static void ufshcd_print_evt(struct ufs_hba *hba, u32 id,
422 struct ufs_event_hist *e;
424 if (id >= UFS_EVT_CNT)
427 e = &hba->ufs_stats.event[id];
429 for (i = 0; i < UFS_EVENT_HIST_LENGTH; i++) {
430 int p = (i + e->pos) % UFS_EVENT_HIST_LENGTH;
432 if (e->tstamp[p] == 0)
434 dev_err(hba->dev, "%s[%d] = 0x%x at %lld us\n", err_name, p,
435 e->val[p], ktime_to_us(e->tstamp[p]));
440 dev_err(hba->dev, "No record of %s\n", err_name);
442 dev_err(hba->dev, "%s: total cnt=%llu\n", err_name, e->cnt);
445 static void ufshcd_print_evt_hist(struct ufs_hba *hba)
447 ufshcd_dump_regs(hba, 0, UFSHCI_REG_SPACE_SIZE, "host_regs: ");
449 ufshcd_print_evt(hba, UFS_EVT_PA_ERR, "pa_err");
450 ufshcd_print_evt(hba, UFS_EVT_DL_ERR, "dl_err");
451 ufshcd_print_evt(hba, UFS_EVT_NL_ERR, "nl_err");
452 ufshcd_print_evt(hba, UFS_EVT_TL_ERR, "tl_err");
453 ufshcd_print_evt(hba, UFS_EVT_DME_ERR, "dme_err");
454 ufshcd_print_evt(hba, UFS_EVT_AUTO_HIBERN8_ERR,
456 ufshcd_print_evt(hba, UFS_EVT_FATAL_ERR, "fatal_err");
457 ufshcd_print_evt(hba, UFS_EVT_LINK_STARTUP_FAIL,
458 "link_startup_fail");
459 ufshcd_print_evt(hba, UFS_EVT_RESUME_ERR, "resume_fail");
460 ufshcd_print_evt(hba, UFS_EVT_SUSPEND_ERR,
462 ufshcd_print_evt(hba, UFS_EVT_DEV_RESET, "dev_reset");
463 ufshcd_print_evt(hba, UFS_EVT_HOST_RESET, "host_reset");
464 ufshcd_print_evt(hba, UFS_EVT_ABORT, "task_abort");
466 ufshcd_vops_dbg_register_dump(hba);
470 void ufshcd_print_trs(struct ufs_hba *hba, unsigned long bitmap, bool pr_prdt)
472 struct ufshcd_lrb *lrbp;
476 for_each_set_bit(tag, &bitmap, hba->nutrs) {
477 lrbp = &hba->lrb[tag];
479 dev_err(hba->dev, "UPIU[%d] - issue time %lld us\n",
480 tag, ktime_to_us(lrbp->issue_time_stamp));
481 dev_err(hba->dev, "UPIU[%d] - complete time %lld us\n",
482 tag, ktime_to_us(lrbp->compl_time_stamp));
484 "UPIU[%d] - Transfer Request Descriptor phys@0x%llx\n",
485 tag, (u64)lrbp->utrd_dma_addr);
487 ufshcd_hex_dump("UPIU TRD: ", lrbp->utr_descriptor_ptr,
488 sizeof(struct utp_transfer_req_desc));
489 dev_err(hba->dev, "UPIU[%d] - Request UPIU phys@0x%llx\n", tag,
490 (u64)lrbp->ucd_req_dma_addr);
491 ufshcd_hex_dump("UPIU REQ: ", lrbp->ucd_req_ptr,
492 sizeof(struct utp_upiu_req));
493 dev_err(hba->dev, "UPIU[%d] - Response UPIU phys@0x%llx\n", tag,
494 (u64)lrbp->ucd_rsp_dma_addr);
495 ufshcd_hex_dump("UPIU RSP: ", lrbp->ucd_rsp_ptr,
496 sizeof(struct utp_upiu_rsp));
498 prdt_length = le16_to_cpu(
499 lrbp->utr_descriptor_ptr->prd_table_length);
500 if (hba->quirks & UFSHCD_QUIRK_PRDT_BYTE_GRAN)
501 prdt_length /= sizeof(struct ufshcd_sg_entry);
504 "UPIU[%d] - PRDT - %d entries phys@0x%llx\n",
506 (u64)lrbp->ucd_prdt_dma_addr);
509 ufshcd_hex_dump("UPIU PRDT: ", lrbp->ucd_prdt_ptr,
510 sizeof(struct ufshcd_sg_entry) * prdt_length);
514 static void ufshcd_print_tmrs(struct ufs_hba *hba, unsigned long bitmap)
518 for_each_set_bit(tag, &bitmap, hba->nutmrs) {
519 struct utp_task_req_desc *tmrdp = &hba->utmrdl_base_addr[tag];
521 dev_err(hba->dev, "TM[%d] - Task Management Header\n", tag);
522 ufshcd_hex_dump("", tmrdp, sizeof(*tmrdp));
526 static void ufshcd_print_host_state(struct ufs_hba *hba)
528 struct scsi_device *sdev_ufs = hba->sdev_ufs_device;
530 dev_err(hba->dev, "UFS Host state=%d\n", hba->ufshcd_state);
531 dev_err(hba->dev, "outstanding reqs=0x%lx tasks=0x%lx\n",
532 hba->outstanding_reqs, hba->outstanding_tasks);
533 dev_err(hba->dev, "saved_err=0x%x, saved_uic_err=0x%x\n",
534 hba->saved_err, hba->saved_uic_err);
535 dev_err(hba->dev, "Device power mode=%d, UIC link state=%d\n",
536 hba->curr_dev_pwr_mode, hba->uic_link_state);
537 dev_err(hba->dev, "PM in progress=%d, sys. suspended=%d\n",
538 hba->pm_op_in_progress, hba->is_sys_suspended);
539 dev_err(hba->dev, "Auto BKOPS=%d, Host self-block=%d\n",
540 hba->auto_bkops_enabled, hba->host->host_self_blocked);
541 dev_err(hba->dev, "Clk gate=%d\n", hba->clk_gating.state);
543 "last_hibern8_exit_tstamp at %lld us, hibern8_exit_cnt=%d\n",
544 ktime_to_us(hba->ufs_stats.last_hibern8_exit_tstamp),
545 hba->ufs_stats.hibern8_exit_cnt);
546 dev_err(hba->dev, "last intr at %lld us, last intr status=0x%x\n",
547 ktime_to_us(hba->ufs_stats.last_intr_ts),
548 hba->ufs_stats.last_intr_status);
549 dev_err(hba->dev, "error handling flags=0x%x, req. abort count=%d\n",
550 hba->eh_flags, hba->req_abort_count);
551 dev_err(hba->dev, "hba->ufs_version=0x%x, Host capabilities=0x%x, caps=0x%x\n",
552 hba->ufs_version, hba->capabilities, hba->caps);
553 dev_err(hba->dev, "quirks=0x%x, dev. quirks=0x%x\n", hba->quirks,
556 dev_err(hba->dev, "UFS dev info: %.8s %.16s rev %.4s\n",
557 sdev_ufs->vendor, sdev_ufs->model, sdev_ufs->rev);
559 ufshcd_print_clk_freqs(hba);
563 * ufshcd_print_pwr_info - print power params as saved in hba
565 * @hba: per-adapter instance
567 static void ufshcd_print_pwr_info(struct ufs_hba *hba)
569 static const char * const names[] = {
579 dev_err(hba->dev, "%s:[RX, TX]: gear=[%d, %d], lane[%d, %d], pwr[%s, %s], rate = %d\n",
581 hba->pwr_info.gear_rx, hba->pwr_info.gear_tx,
582 hba->pwr_info.lane_rx, hba->pwr_info.lane_tx,
583 names[hba->pwr_info.pwr_rx],
584 names[hba->pwr_info.pwr_tx],
585 hba->pwr_info.hs_rate);
588 static void ufshcd_device_reset(struct ufs_hba *hba)
592 err = ufshcd_vops_device_reset(hba);
595 ufshcd_set_ufs_dev_active(hba);
596 if (ufshcd_is_wb_allowed(hba)) {
597 hba->dev_info.wb_enabled = false;
598 hba->dev_info.wb_buf_flush_enabled = false;
601 if (err != -EOPNOTSUPP)
602 ufshcd_update_evt_hist(hba, UFS_EVT_DEV_RESET, err);
605 void ufshcd_delay_us(unsigned long us, unsigned long tolerance)
613 usleep_range(us, us + tolerance);
615 EXPORT_SYMBOL_GPL(ufshcd_delay_us);
618 * ufshcd_wait_for_register - wait for register value to change
619 * @hba: per-adapter interface
620 * @reg: mmio register offset
621 * @mask: mask to apply to the read register value
622 * @val: value to wait for
623 * @interval_us: polling interval in microseconds
624 * @timeout_ms: timeout in milliseconds
627 * -ETIMEDOUT on error, zero on success.
629 int ufshcd_wait_for_register(struct ufs_hba *hba, u32 reg, u32 mask,
630 u32 val, unsigned long interval_us,
631 unsigned long timeout_ms)
634 unsigned long timeout = jiffies + msecs_to_jiffies(timeout_ms);
636 /* ignore bits that we don't intend to wait on */
639 while ((ufshcd_readl(hba, reg) & mask) != val) {
640 usleep_range(interval_us, interval_us + 50);
641 if (time_after(jiffies, timeout)) {
642 if ((ufshcd_readl(hba, reg) & mask) != val)
652 * ufshcd_get_intr_mask - Get the interrupt bit mask
653 * @hba: Pointer to adapter instance
655 * Returns interrupt bit mask per version
657 static inline u32 ufshcd_get_intr_mask(struct ufs_hba *hba)
659 if (hba->ufs_version == ufshci_version(1, 0))
660 return INTERRUPT_MASK_ALL_VER_10;
661 if (hba->ufs_version <= ufshci_version(2, 0))
662 return INTERRUPT_MASK_ALL_VER_11;
664 return INTERRUPT_MASK_ALL_VER_21;
668 * ufshcd_get_ufs_version - Get the UFS version supported by the HBA
669 * @hba: Pointer to adapter instance
671 * Returns UFSHCI version supported by the controller
673 static inline u32 ufshcd_get_ufs_version(struct ufs_hba *hba)
677 if (hba->quirks & UFSHCD_QUIRK_BROKEN_UFS_HCI_VERSION)
678 ufshci_ver = ufshcd_vops_get_ufs_hci_version(hba);
680 ufshci_ver = ufshcd_readl(hba, REG_UFS_VERSION);
683 * UFSHCI v1.x uses a different version scheme, in order
684 * to allow the use of comparisons with the ufshci_version
685 * function, we convert it to the same scheme as ufs 2.0+.
687 if (ufshci_ver & 0x00010000)
688 return ufshci_version(1, ufshci_ver & 0x00000100);
694 * ufshcd_is_device_present - Check if any device connected to
695 * the host controller
696 * @hba: pointer to adapter instance
698 * Returns true if device present, false if no device detected
700 static inline bool ufshcd_is_device_present(struct ufs_hba *hba)
702 return (ufshcd_readl(hba, REG_CONTROLLER_STATUS) &
703 DEVICE_PRESENT) ? true : false;
707 * ufshcd_get_tr_ocs - Get the UTRD Overall Command Status
708 * @lrbp: pointer to local command reference block
710 * This function is used to get the OCS field from UTRD
711 * Returns the OCS field in the UTRD
713 static inline int ufshcd_get_tr_ocs(struct ufshcd_lrb *lrbp)
715 return le32_to_cpu(lrbp->utr_descriptor_ptr->header.dword_2) & MASK_OCS;
719 * ufshcd_utrl_clear - Clear a bit in UTRLCLR register
720 * @hba: per adapter instance
721 * @pos: position of the bit to be cleared
723 static inline void ufshcd_utrl_clear(struct ufs_hba *hba, u32 pos)
725 if (hba->quirks & UFSHCI_QUIRK_BROKEN_REQ_LIST_CLR)
726 ufshcd_writel(hba, (1 << pos), REG_UTP_TRANSFER_REQ_LIST_CLEAR);
728 ufshcd_writel(hba, ~(1 << pos),
729 REG_UTP_TRANSFER_REQ_LIST_CLEAR);
733 * ufshcd_utmrl_clear - Clear a bit in UTRMLCLR register
734 * @hba: per adapter instance
735 * @pos: position of the bit to be cleared
737 static inline void ufshcd_utmrl_clear(struct ufs_hba *hba, u32 pos)
739 if (hba->quirks & UFSHCI_QUIRK_BROKEN_REQ_LIST_CLR)
740 ufshcd_writel(hba, (1 << pos), REG_UTP_TASK_REQ_LIST_CLEAR);
742 ufshcd_writel(hba, ~(1 << pos), REG_UTP_TASK_REQ_LIST_CLEAR);
746 * ufshcd_get_lists_status - Check UCRDY, UTRLRDY and UTMRLRDY
747 * @reg: Register value of host controller status
749 * Returns integer, 0 on Success and positive value if failed
751 static inline int ufshcd_get_lists_status(u32 reg)
753 return !((reg & UFSHCD_STATUS_READY) == UFSHCD_STATUS_READY);
757 * ufshcd_get_uic_cmd_result - Get the UIC command result
758 * @hba: Pointer to adapter instance
760 * This function gets the result of UIC command completion
761 * Returns 0 on success, non zero value on error
763 static inline int ufshcd_get_uic_cmd_result(struct ufs_hba *hba)
765 return ufshcd_readl(hba, REG_UIC_COMMAND_ARG_2) &
766 MASK_UIC_COMMAND_RESULT;
770 * ufshcd_get_dme_attr_val - Get the value of attribute returned by UIC command
771 * @hba: Pointer to adapter instance
773 * This function gets UIC command argument3
774 * Returns 0 on success, non zero value on error
776 static inline u32 ufshcd_get_dme_attr_val(struct ufs_hba *hba)
778 return ufshcd_readl(hba, REG_UIC_COMMAND_ARG_3);
782 * ufshcd_get_req_rsp - returns the TR response transaction type
783 * @ucd_rsp_ptr: pointer to response UPIU
786 ufshcd_get_req_rsp(struct utp_upiu_rsp *ucd_rsp_ptr)
788 return be32_to_cpu(ucd_rsp_ptr->header.dword_0) >> 24;
792 * ufshcd_get_rsp_upiu_result - Get the result from response UPIU
793 * @ucd_rsp_ptr: pointer to response UPIU
795 * This function gets the response status and scsi_status from response UPIU
796 * Returns the response result code.
799 ufshcd_get_rsp_upiu_result(struct utp_upiu_rsp *ucd_rsp_ptr)
801 return be32_to_cpu(ucd_rsp_ptr->header.dword_1) & MASK_RSP_UPIU_RESULT;
805 * ufshcd_get_rsp_upiu_data_seg_len - Get the data segment length
807 * @ucd_rsp_ptr: pointer to response UPIU
809 * Return the data segment length.
811 static inline unsigned int
812 ufshcd_get_rsp_upiu_data_seg_len(struct utp_upiu_rsp *ucd_rsp_ptr)
814 return be32_to_cpu(ucd_rsp_ptr->header.dword_2) &
815 MASK_RSP_UPIU_DATA_SEG_LEN;
819 * ufshcd_is_exception_event - Check if the device raised an exception event
820 * @ucd_rsp_ptr: pointer to response UPIU
822 * The function checks if the device raised an exception event indicated in
823 * the Device Information field of response UPIU.
825 * Returns true if exception is raised, false otherwise.
827 static inline bool ufshcd_is_exception_event(struct utp_upiu_rsp *ucd_rsp_ptr)
829 return be32_to_cpu(ucd_rsp_ptr->header.dword_2) &
830 MASK_RSP_EXCEPTION_EVENT ? true : false;
834 * ufshcd_reset_intr_aggr - Reset interrupt aggregation values.
835 * @hba: per adapter instance
838 ufshcd_reset_intr_aggr(struct ufs_hba *hba)
840 ufshcd_writel(hba, INT_AGGR_ENABLE |
841 INT_AGGR_COUNTER_AND_TIMER_RESET,
842 REG_UTP_TRANSFER_REQ_INT_AGG_CONTROL);
846 * ufshcd_config_intr_aggr - Configure interrupt aggregation values.
847 * @hba: per adapter instance
848 * @cnt: Interrupt aggregation counter threshold
849 * @tmout: Interrupt aggregation timeout value
852 ufshcd_config_intr_aggr(struct ufs_hba *hba, u8 cnt, u8 tmout)
854 ufshcd_writel(hba, INT_AGGR_ENABLE | INT_AGGR_PARAM_WRITE |
855 INT_AGGR_COUNTER_THLD_VAL(cnt) |
856 INT_AGGR_TIMEOUT_VAL(tmout),
857 REG_UTP_TRANSFER_REQ_INT_AGG_CONTROL);
861 * ufshcd_disable_intr_aggr - Disables interrupt aggregation.
862 * @hba: per adapter instance
864 static inline void ufshcd_disable_intr_aggr(struct ufs_hba *hba)
866 ufshcd_writel(hba, 0, REG_UTP_TRANSFER_REQ_INT_AGG_CONTROL);
870 * ufshcd_enable_run_stop_reg - Enable run-stop registers,
871 * When run-stop registers are set to 1, it indicates the
872 * host controller that it can process the requests
873 * @hba: per adapter instance
875 static void ufshcd_enable_run_stop_reg(struct ufs_hba *hba)
877 ufshcd_writel(hba, UTP_TASK_REQ_LIST_RUN_STOP_BIT,
878 REG_UTP_TASK_REQ_LIST_RUN_STOP);
879 ufshcd_writel(hba, UTP_TRANSFER_REQ_LIST_RUN_STOP_BIT,
880 REG_UTP_TRANSFER_REQ_LIST_RUN_STOP);
884 * ufshcd_hba_start - Start controller initialization sequence
885 * @hba: per adapter instance
887 static inline void ufshcd_hba_start(struct ufs_hba *hba)
889 u32 val = CONTROLLER_ENABLE;
891 if (ufshcd_crypto_enable(hba))
892 val |= CRYPTO_GENERAL_ENABLE;
894 ufshcd_writel(hba, val, REG_CONTROLLER_ENABLE);
898 * ufshcd_is_hba_active - Get controller state
899 * @hba: per adapter instance
901 * Returns false if controller is active, true otherwise
903 static inline bool ufshcd_is_hba_active(struct ufs_hba *hba)
905 return (ufshcd_readl(hba, REG_CONTROLLER_ENABLE) & CONTROLLER_ENABLE)
909 u32 ufshcd_get_local_unipro_ver(struct ufs_hba *hba)
911 /* HCI version 1.0 and 1.1 supports UniPro 1.41 */
912 if (hba->ufs_version <= ufshci_version(1, 1))
913 return UFS_UNIPRO_VER_1_41;
915 return UFS_UNIPRO_VER_1_6;
917 EXPORT_SYMBOL(ufshcd_get_local_unipro_ver);
919 static bool ufshcd_is_unipro_pa_params_tuning_req(struct ufs_hba *hba)
922 * If both host and device support UniPro ver1.6 or later, PA layer
923 * parameters tuning happens during link startup itself.
925 * We can manually tune PA layer parameters if either host or device
926 * doesn't support UniPro ver 1.6 or later. But to keep manual tuning
927 * logic simple, we will only do manual tuning if local unipro version
928 * doesn't support ver1.6 or later.
930 if (ufshcd_get_local_unipro_ver(hba) < UFS_UNIPRO_VER_1_6)
937 * ufshcd_set_clk_freq - set UFS controller clock frequencies
938 * @hba: per adapter instance
939 * @scale_up: If True, set max possible frequency othewise set low frequency
941 * Returns 0 if successful
942 * Returns < 0 for any other errors
944 static int ufshcd_set_clk_freq(struct ufs_hba *hba, bool scale_up)
947 struct ufs_clk_info *clki;
948 struct list_head *head = &hba->clk_list_head;
950 if (list_empty(head))
953 list_for_each_entry(clki, head, list) {
954 if (!IS_ERR_OR_NULL(clki->clk)) {
955 if (scale_up && clki->max_freq) {
956 if (clki->curr_freq == clki->max_freq)
959 ret = clk_set_rate(clki->clk, clki->max_freq);
961 dev_err(hba->dev, "%s: %s clk set rate(%dHz) failed, %d\n",
962 __func__, clki->name,
963 clki->max_freq, ret);
966 trace_ufshcd_clk_scaling(dev_name(hba->dev),
967 "scaled up", clki->name,
971 clki->curr_freq = clki->max_freq;
973 } else if (!scale_up && clki->min_freq) {
974 if (clki->curr_freq == clki->min_freq)
977 ret = clk_set_rate(clki->clk, clki->min_freq);
979 dev_err(hba->dev, "%s: %s clk set rate(%dHz) failed, %d\n",
980 __func__, clki->name,
981 clki->min_freq, ret);
984 trace_ufshcd_clk_scaling(dev_name(hba->dev),
985 "scaled down", clki->name,
988 clki->curr_freq = clki->min_freq;
991 dev_dbg(hba->dev, "%s: clk: %s, rate: %lu\n", __func__,
992 clki->name, clk_get_rate(clki->clk));
1000 * ufshcd_scale_clks - scale up or scale down UFS controller clocks
1001 * @hba: per adapter instance
1002 * @scale_up: True if scaling up and false if scaling down
1004 * Returns 0 if successful
1005 * Returns < 0 for any other errors
1007 static int ufshcd_scale_clks(struct ufs_hba *hba, bool scale_up)
1010 ktime_t start = ktime_get();
1012 ret = ufshcd_vops_clk_scale_notify(hba, scale_up, PRE_CHANGE);
1016 ret = ufshcd_set_clk_freq(hba, scale_up);
1020 ret = ufshcd_vops_clk_scale_notify(hba, scale_up, POST_CHANGE);
1022 ufshcd_set_clk_freq(hba, !scale_up);
1025 trace_ufshcd_profile_clk_scaling(dev_name(hba->dev),
1026 (scale_up ? "up" : "down"),
1027 ktime_to_us(ktime_sub(ktime_get(), start)), ret);
1032 * ufshcd_is_devfreq_scaling_required - check if scaling is required or not
1033 * @hba: per adapter instance
1034 * @scale_up: True if scaling up and false if scaling down
1036 * Returns true if scaling is required, false otherwise.
1038 static bool ufshcd_is_devfreq_scaling_required(struct ufs_hba *hba,
1041 struct ufs_clk_info *clki;
1042 struct list_head *head = &hba->clk_list_head;
1044 if (list_empty(head))
1047 list_for_each_entry(clki, head, list) {
1048 if (!IS_ERR_OR_NULL(clki->clk)) {
1049 if (scale_up && clki->max_freq) {
1050 if (clki->curr_freq == clki->max_freq)
1053 } else if (!scale_up && clki->min_freq) {
1054 if (clki->curr_freq == clki->min_freq)
1064 static int ufshcd_wait_for_doorbell_clr(struct ufs_hba *hba,
1065 u64 wait_timeout_us)
1067 unsigned long flags;
1071 bool timeout = false, do_last_check = false;
1074 ufshcd_hold(hba, false);
1075 spin_lock_irqsave(hba->host->host_lock, flags);
1077 * Wait for all the outstanding tasks/transfer requests.
1078 * Verify by checking the doorbell registers are clear.
1080 start = ktime_get();
1082 if (hba->ufshcd_state != UFSHCD_STATE_OPERATIONAL) {
1087 tm_doorbell = ufshcd_readl(hba, REG_UTP_TASK_REQ_DOOR_BELL);
1088 tr_doorbell = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
1089 if (!tm_doorbell && !tr_doorbell) {
1092 } else if (do_last_check) {
1096 spin_unlock_irqrestore(hba->host->host_lock, flags);
1098 if (ktime_to_us(ktime_sub(ktime_get(), start)) >
1102 * We might have scheduled out for long time so make
1103 * sure to check if doorbells are cleared by this time
1106 do_last_check = true;
1108 spin_lock_irqsave(hba->host->host_lock, flags);
1109 } while (tm_doorbell || tr_doorbell);
1113 "%s: timedout waiting for doorbell to clear (tm=0x%x, tr=0x%x)\n",
1114 __func__, tm_doorbell, tr_doorbell);
1118 spin_unlock_irqrestore(hba->host->host_lock, flags);
1119 ufshcd_release(hba);
1124 * ufshcd_scale_gear - scale up/down UFS gear
1125 * @hba: per adapter instance
1126 * @scale_up: True for scaling up gear and false for scaling down
1128 * Returns 0 for success,
1129 * Returns -EBUSY if scaling can't happen at this time
1130 * Returns non-zero for any other errors
1132 static int ufshcd_scale_gear(struct ufs_hba *hba, bool scale_up)
1135 struct ufs_pa_layer_attr new_pwr_info;
1138 memcpy(&new_pwr_info, &hba->clk_scaling.saved_pwr_info.info,
1139 sizeof(struct ufs_pa_layer_attr));
1141 memcpy(&new_pwr_info, &hba->pwr_info,
1142 sizeof(struct ufs_pa_layer_attr));
1144 if (hba->pwr_info.gear_tx > hba->clk_scaling.min_gear ||
1145 hba->pwr_info.gear_rx > hba->clk_scaling.min_gear) {
1146 /* save the current power mode */
1147 memcpy(&hba->clk_scaling.saved_pwr_info.info,
1149 sizeof(struct ufs_pa_layer_attr));
1151 /* scale down gear */
1152 new_pwr_info.gear_tx = hba->clk_scaling.min_gear;
1153 new_pwr_info.gear_rx = hba->clk_scaling.min_gear;
1157 /* check if the power mode needs to be changed or not? */
1158 ret = ufshcd_config_pwr_mode(hba, &new_pwr_info);
1160 dev_err(hba->dev, "%s: failed err %d, old gear: (tx %d rx %d), new gear: (tx %d rx %d)",
1162 hba->pwr_info.gear_tx, hba->pwr_info.gear_rx,
1163 new_pwr_info.gear_tx, new_pwr_info.gear_rx);
1168 static int ufshcd_clock_scaling_prepare(struct ufs_hba *hba)
1170 #define DOORBELL_CLR_TOUT_US (1000 * 1000) /* 1 sec */
1173 * make sure that there are no outstanding requests when
1174 * clock scaling is in progress
1176 ufshcd_scsi_block_requests(hba);
1177 down_write(&hba->clk_scaling_lock);
1179 if (!hba->clk_scaling.is_allowed ||
1180 ufshcd_wait_for_doorbell_clr(hba, DOORBELL_CLR_TOUT_US)) {
1182 up_write(&hba->clk_scaling_lock);
1183 ufshcd_scsi_unblock_requests(hba);
1187 /* let's not get into low power until clock scaling is completed */
1188 ufshcd_hold(hba, false);
1194 static void ufshcd_clock_scaling_unprepare(struct ufs_hba *hba, bool writelock)
1197 up_write(&hba->clk_scaling_lock);
1199 up_read(&hba->clk_scaling_lock);
1200 ufshcd_scsi_unblock_requests(hba);
1201 ufshcd_release(hba);
1205 * ufshcd_devfreq_scale - scale up/down UFS clocks and gear
1206 * @hba: per adapter instance
1207 * @scale_up: True for scaling up and false for scalin down
1209 * Returns 0 for success,
1210 * Returns -EBUSY if scaling can't happen at this time
1211 * Returns non-zero for any other errors
1213 static int ufshcd_devfreq_scale(struct ufs_hba *hba, bool scale_up)
1216 bool is_writelock = true;
1218 ret = ufshcd_clock_scaling_prepare(hba);
1222 /* scale down the gear before scaling down clocks */
1224 ret = ufshcd_scale_gear(hba, false);
1229 ret = ufshcd_scale_clks(hba, scale_up);
1232 ufshcd_scale_gear(hba, true);
1236 /* scale up the gear after scaling up clocks */
1238 ret = ufshcd_scale_gear(hba, true);
1240 ufshcd_scale_clks(hba, false);
1245 /* Enable Write Booster if we have scaled up else disable it */
1246 downgrade_write(&hba->clk_scaling_lock);
1247 is_writelock = false;
1248 ufshcd_wb_toggle(hba, scale_up);
1251 ufshcd_clock_scaling_unprepare(hba, is_writelock);
1255 static void ufshcd_clk_scaling_suspend_work(struct work_struct *work)
1257 struct ufs_hba *hba = container_of(work, struct ufs_hba,
1258 clk_scaling.suspend_work);
1259 unsigned long irq_flags;
1261 spin_lock_irqsave(hba->host->host_lock, irq_flags);
1262 if (hba->clk_scaling.active_reqs || hba->clk_scaling.is_suspended) {
1263 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1266 hba->clk_scaling.is_suspended = true;
1267 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1269 __ufshcd_suspend_clkscaling(hba);
1272 static void ufshcd_clk_scaling_resume_work(struct work_struct *work)
1274 struct ufs_hba *hba = container_of(work, struct ufs_hba,
1275 clk_scaling.resume_work);
1276 unsigned long irq_flags;
1278 spin_lock_irqsave(hba->host->host_lock, irq_flags);
1279 if (!hba->clk_scaling.is_suspended) {
1280 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1283 hba->clk_scaling.is_suspended = false;
1284 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1286 devfreq_resume_device(hba->devfreq);
1289 static int ufshcd_devfreq_target(struct device *dev,
1290 unsigned long *freq, u32 flags)
1293 struct ufs_hba *hba = dev_get_drvdata(dev);
1295 bool scale_up, sched_clk_scaling_suspend_work = false;
1296 struct list_head *clk_list = &hba->clk_list_head;
1297 struct ufs_clk_info *clki;
1298 unsigned long irq_flags;
1300 if (!ufshcd_is_clkscaling_supported(hba))
1303 clki = list_first_entry(&hba->clk_list_head, struct ufs_clk_info, list);
1304 /* Override with the closest supported frequency */
1305 *freq = (unsigned long) clk_round_rate(clki->clk, *freq);
1306 spin_lock_irqsave(hba->host->host_lock, irq_flags);
1307 if (ufshcd_eh_in_progress(hba)) {
1308 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1312 if (!hba->clk_scaling.active_reqs)
1313 sched_clk_scaling_suspend_work = true;
1315 if (list_empty(clk_list)) {
1316 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1320 /* Decide based on the rounded-off frequency and update */
1321 scale_up = (*freq == clki->max_freq) ? true : false;
1323 *freq = clki->min_freq;
1324 /* Update the frequency */
1325 if (!ufshcd_is_devfreq_scaling_required(hba, scale_up)) {
1326 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1328 goto out; /* no state change required */
1330 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1332 start = ktime_get();
1333 ret = ufshcd_devfreq_scale(hba, scale_up);
1335 trace_ufshcd_profile_clk_scaling(dev_name(hba->dev),
1336 (scale_up ? "up" : "down"),
1337 ktime_to_us(ktime_sub(ktime_get(), start)), ret);
1340 if (sched_clk_scaling_suspend_work)
1341 queue_work(hba->clk_scaling.workq,
1342 &hba->clk_scaling.suspend_work);
1347 static bool ufshcd_is_busy(struct request *req, void *priv, bool reserved)
1351 WARN_ON_ONCE(reserved);
1356 /* Whether or not any tag is in use by a request that is in progress. */
1357 static bool ufshcd_any_tag_in_use(struct ufs_hba *hba)
1359 struct request_queue *q = hba->cmd_queue;
1362 blk_mq_tagset_busy_iter(q->tag_set, ufshcd_is_busy, &busy);
1366 static int ufshcd_devfreq_get_dev_status(struct device *dev,
1367 struct devfreq_dev_status *stat)
1369 struct ufs_hba *hba = dev_get_drvdata(dev);
1370 struct ufs_clk_scaling *scaling = &hba->clk_scaling;
1371 unsigned long flags;
1372 struct list_head *clk_list = &hba->clk_list_head;
1373 struct ufs_clk_info *clki;
1376 if (!ufshcd_is_clkscaling_supported(hba))
1379 memset(stat, 0, sizeof(*stat));
1381 spin_lock_irqsave(hba->host->host_lock, flags);
1382 curr_t = ktime_get();
1383 if (!scaling->window_start_t)
1386 clki = list_first_entry(clk_list, struct ufs_clk_info, list);
1388 * If current frequency is 0, then the ondemand governor considers
1389 * there's no initial frequency set. And it always requests to set
1390 * to max. frequency.
1392 stat->current_frequency = clki->curr_freq;
1393 if (scaling->is_busy_started)
1394 scaling->tot_busy_t += ktime_us_delta(curr_t,
1395 scaling->busy_start_t);
1397 stat->total_time = ktime_us_delta(curr_t, scaling->window_start_t);
1398 stat->busy_time = scaling->tot_busy_t;
1400 scaling->window_start_t = curr_t;
1401 scaling->tot_busy_t = 0;
1403 if (hba->outstanding_reqs) {
1404 scaling->busy_start_t = curr_t;
1405 scaling->is_busy_started = true;
1407 scaling->busy_start_t = 0;
1408 scaling->is_busy_started = false;
1410 spin_unlock_irqrestore(hba->host->host_lock, flags);
1414 static int ufshcd_devfreq_init(struct ufs_hba *hba)
1416 struct list_head *clk_list = &hba->clk_list_head;
1417 struct ufs_clk_info *clki;
1418 struct devfreq *devfreq;
1421 /* Skip devfreq if we don't have any clocks in the list */
1422 if (list_empty(clk_list))
1425 clki = list_first_entry(clk_list, struct ufs_clk_info, list);
1426 dev_pm_opp_add(hba->dev, clki->min_freq, 0);
1427 dev_pm_opp_add(hba->dev, clki->max_freq, 0);
1429 ufshcd_vops_config_scaling_param(hba, &hba->vps->devfreq_profile,
1430 &hba->vps->ondemand_data);
1431 devfreq = devfreq_add_device(hba->dev,
1432 &hba->vps->devfreq_profile,
1433 DEVFREQ_GOV_SIMPLE_ONDEMAND,
1434 &hba->vps->ondemand_data);
1435 if (IS_ERR(devfreq)) {
1436 ret = PTR_ERR(devfreq);
1437 dev_err(hba->dev, "Unable to register with devfreq %d\n", ret);
1439 dev_pm_opp_remove(hba->dev, clki->min_freq);
1440 dev_pm_opp_remove(hba->dev, clki->max_freq);
1444 hba->devfreq = devfreq;
1449 static void ufshcd_devfreq_remove(struct ufs_hba *hba)
1451 struct list_head *clk_list = &hba->clk_list_head;
1452 struct ufs_clk_info *clki;
1457 devfreq_remove_device(hba->devfreq);
1458 hba->devfreq = NULL;
1460 clki = list_first_entry(clk_list, struct ufs_clk_info, list);
1461 dev_pm_opp_remove(hba->dev, clki->min_freq);
1462 dev_pm_opp_remove(hba->dev, clki->max_freq);
1465 static void __ufshcd_suspend_clkscaling(struct ufs_hba *hba)
1467 unsigned long flags;
1469 devfreq_suspend_device(hba->devfreq);
1470 spin_lock_irqsave(hba->host->host_lock, flags);
1471 hba->clk_scaling.window_start_t = 0;
1472 spin_unlock_irqrestore(hba->host->host_lock, flags);
1475 static void ufshcd_suspend_clkscaling(struct ufs_hba *hba)
1477 unsigned long flags;
1478 bool suspend = false;
1480 cancel_work_sync(&hba->clk_scaling.suspend_work);
1481 cancel_work_sync(&hba->clk_scaling.resume_work);
1483 spin_lock_irqsave(hba->host->host_lock, flags);
1484 if (!hba->clk_scaling.is_suspended) {
1486 hba->clk_scaling.is_suspended = true;
1488 spin_unlock_irqrestore(hba->host->host_lock, flags);
1491 __ufshcd_suspend_clkscaling(hba);
1494 static void ufshcd_resume_clkscaling(struct ufs_hba *hba)
1496 unsigned long flags;
1497 bool resume = false;
1499 spin_lock_irqsave(hba->host->host_lock, flags);
1500 if (hba->clk_scaling.is_suspended) {
1502 hba->clk_scaling.is_suspended = false;
1504 spin_unlock_irqrestore(hba->host->host_lock, flags);
1507 devfreq_resume_device(hba->devfreq);
1510 static ssize_t ufshcd_clkscale_enable_show(struct device *dev,
1511 struct device_attribute *attr, char *buf)
1513 struct ufs_hba *hba = dev_get_drvdata(dev);
1515 return sysfs_emit(buf, "%d\n", hba->clk_scaling.is_enabled);
1518 static ssize_t ufshcd_clkscale_enable_store(struct device *dev,
1519 struct device_attribute *attr, const char *buf, size_t count)
1521 struct ufs_hba *hba = dev_get_drvdata(dev);
1525 if (kstrtou32(buf, 0, &value))
1528 down(&hba->host_sem);
1529 if (!ufshcd_is_user_access_allowed(hba)) {
1535 if (value == hba->clk_scaling.is_enabled)
1538 ufshcd_rpm_get_sync(hba);
1539 ufshcd_hold(hba, false);
1541 hba->clk_scaling.is_enabled = value;
1544 ufshcd_resume_clkscaling(hba);
1546 ufshcd_suspend_clkscaling(hba);
1547 err = ufshcd_devfreq_scale(hba, true);
1549 dev_err(hba->dev, "%s: failed to scale clocks up %d\n",
1553 ufshcd_release(hba);
1554 ufshcd_rpm_put_sync(hba);
1557 return err ? err : count;
1560 static void ufshcd_init_clk_scaling_sysfs(struct ufs_hba *hba)
1562 hba->clk_scaling.enable_attr.show = ufshcd_clkscale_enable_show;
1563 hba->clk_scaling.enable_attr.store = ufshcd_clkscale_enable_store;
1564 sysfs_attr_init(&hba->clk_scaling.enable_attr.attr);
1565 hba->clk_scaling.enable_attr.attr.name = "clkscale_enable";
1566 hba->clk_scaling.enable_attr.attr.mode = 0644;
1567 if (device_create_file(hba->dev, &hba->clk_scaling.enable_attr))
1568 dev_err(hba->dev, "Failed to create sysfs for clkscale_enable\n");
1571 static void ufshcd_remove_clk_scaling_sysfs(struct ufs_hba *hba)
1573 if (hba->clk_scaling.enable_attr.attr.name)
1574 device_remove_file(hba->dev, &hba->clk_scaling.enable_attr);
1577 static void ufshcd_init_clk_scaling(struct ufs_hba *hba)
1579 char wq_name[sizeof("ufs_clkscaling_00")];
1581 if (!ufshcd_is_clkscaling_supported(hba))
1584 if (!hba->clk_scaling.min_gear)
1585 hba->clk_scaling.min_gear = UFS_HS_G1;
1587 INIT_WORK(&hba->clk_scaling.suspend_work,
1588 ufshcd_clk_scaling_suspend_work);
1589 INIT_WORK(&hba->clk_scaling.resume_work,
1590 ufshcd_clk_scaling_resume_work);
1592 snprintf(wq_name, sizeof(wq_name), "ufs_clkscaling_%d",
1593 hba->host->host_no);
1594 hba->clk_scaling.workq = create_singlethread_workqueue(wq_name);
1596 hba->clk_scaling.is_initialized = true;
1599 static void ufshcd_exit_clk_scaling(struct ufs_hba *hba)
1601 if (!hba->clk_scaling.is_initialized)
1604 ufshcd_remove_clk_scaling_sysfs(hba);
1605 destroy_workqueue(hba->clk_scaling.workq);
1606 ufshcd_devfreq_remove(hba);
1607 hba->clk_scaling.is_initialized = false;
1610 static void ufshcd_ungate_work(struct work_struct *work)
1613 unsigned long flags;
1614 struct ufs_hba *hba = container_of(work, struct ufs_hba,
1615 clk_gating.ungate_work);
1617 cancel_delayed_work_sync(&hba->clk_gating.gate_work);
1619 spin_lock_irqsave(hba->host->host_lock, flags);
1620 if (hba->clk_gating.state == CLKS_ON) {
1621 spin_unlock_irqrestore(hba->host->host_lock, flags);
1625 spin_unlock_irqrestore(hba->host->host_lock, flags);
1626 ufshcd_hba_vreg_set_hpm(hba);
1627 ufshcd_setup_clocks(hba, true);
1629 ufshcd_enable_irq(hba);
1631 /* Exit from hibern8 */
1632 if (ufshcd_can_hibern8_during_gating(hba)) {
1633 /* Prevent gating in this path */
1634 hba->clk_gating.is_suspended = true;
1635 if (ufshcd_is_link_hibern8(hba)) {
1636 ret = ufshcd_uic_hibern8_exit(hba);
1638 dev_err(hba->dev, "%s: hibern8 exit failed %d\n",
1641 ufshcd_set_link_active(hba);
1643 hba->clk_gating.is_suspended = false;
1646 ufshcd_scsi_unblock_requests(hba);
1650 * ufshcd_hold - Enable clocks that were gated earlier due to ufshcd_release.
1651 * Also, exit from hibern8 mode and set the link as active.
1652 * @hba: per adapter instance
1653 * @async: This indicates whether caller should ungate clocks asynchronously.
1655 int ufshcd_hold(struct ufs_hba *hba, bool async)
1659 unsigned long flags;
1661 if (!ufshcd_is_clkgating_allowed(hba))
1663 spin_lock_irqsave(hba->host->host_lock, flags);
1664 hba->clk_gating.active_reqs++;
1667 switch (hba->clk_gating.state) {
1670 * Wait for the ungate work to complete if in progress.
1671 * Though the clocks may be in ON state, the link could
1672 * still be in hibner8 state if hibern8 is allowed
1673 * during clock gating.
1674 * Make sure we exit hibern8 state also in addition to
1677 if (ufshcd_can_hibern8_during_gating(hba) &&
1678 ufshcd_is_link_hibern8(hba)) {
1681 hba->clk_gating.active_reqs--;
1684 spin_unlock_irqrestore(hba->host->host_lock, flags);
1685 flush_result = flush_work(&hba->clk_gating.ungate_work);
1686 if (hba->clk_gating.is_suspended && !flush_result)
1688 spin_lock_irqsave(hba->host->host_lock, flags);
1693 if (cancel_delayed_work(&hba->clk_gating.gate_work)) {
1694 hba->clk_gating.state = CLKS_ON;
1695 trace_ufshcd_clk_gating(dev_name(hba->dev),
1696 hba->clk_gating.state);
1700 * If we are here, it means gating work is either done or
1701 * currently running. Hence, fall through to cancel gating
1702 * work and to enable clocks.
1706 hba->clk_gating.state = REQ_CLKS_ON;
1707 trace_ufshcd_clk_gating(dev_name(hba->dev),
1708 hba->clk_gating.state);
1709 if (queue_work(hba->clk_gating.clk_gating_workq,
1710 &hba->clk_gating.ungate_work))
1711 ufshcd_scsi_block_requests(hba);
1713 * fall through to check if we should wait for this
1714 * work to be done or not.
1720 hba->clk_gating.active_reqs--;
1724 spin_unlock_irqrestore(hba->host->host_lock, flags);
1725 flush_work(&hba->clk_gating.ungate_work);
1726 /* Make sure state is CLKS_ON before returning */
1727 spin_lock_irqsave(hba->host->host_lock, flags);
1730 dev_err(hba->dev, "%s: clk gating is in invalid state %d\n",
1731 __func__, hba->clk_gating.state);
1734 spin_unlock_irqrestore(hba->host->host_lock, flags);
1738 EXPORT_SYMBOL_GPL(ufshcd_hold);
1740 static void ufshcd_gate_work(struct work_struct *work)
1742 struct ufs_hba *hba = container_of(work, struct ufs_hba,
1743 clk_gating.gate_work.work);
1744 unsigned long flags;
1747 spin_lock_irqsave(hba->host->host_lock, flags);
1749 * In case you are here to cancel this work the gating state
1750 * would be marked as REQ_CLKS_ON. In this case save time by
1751 * skipping the gating work and exit after changing the clock
1754 if (hba->clk_gating.is_suspended ||
1755 (hba->clk_gating.state != REQ_CLKS_OFF)) {
1756 hba->clk_gating.state = CLKS_ON;
1757 trace_ufshcd_clk_gating(dev_name(hba->dev),
1758 hba->clk_gating.state);
1762 if (hba->clk_gating.active_reqs
1763 || hba->ufshcd_state != UFSHCD_STATE_OPERATIONAL
1764 || ufshcd_any_tag_in_use(hba) || hba->outstanding_tasks
1765 || hba->active_uic_cmd || hba->uic_async_done)
1768 spin_unlock_irqrestore(hba->host->host_lock, flags);
1770 /* put the link into hibern8 mode before turning off clocks */
1771 if (ufshcd_can_hibern8_during_gating(hba)) {
1772 ret = ufshcd_uic_hibern8_enter(hba);
1774 hba->clk_gating.state = CLKS_ON;
1775 dev_err(hba->dev, "%s: hibern8 enter failed %d\n",
1777 trace_ufshcd_clk_gating(dev_name(hba->dev),
1778 hba->clk_gating.state);
1781 ufshcd_set_link_hibern8(hba);
1784 ufshcd_disable_irq(hba);
1786 ufshcd_setup_clocks(hba, false);
1788 /* Put the host controller in low power mode if possible */
1789 ufshcd_hba_vreg_set_lpm(hba);
1791 * In case you are here to cancel this work the gating state
1792 * would be marked as REQ_CLKS_ON. In this case keep the state
1793 * as REQ_CLKS_ON which would anyway imply that clocks are off
1794 * and a request to turn them on is pending. By doing this way,
1795 * we keep the state machine in tact and this would ultimately
1796 * prevent from doing cancel work multiple times when there are
1797 * new requests arriving before the current cancel work is done.
1799 spin_lock_irqsave(hba->host->host_lock, flags);
1800 if (hba->clk_gating.state == REQ_CLKS_OFF) {
1801 hba->clk_gating.state = CLKS_OFF;
1802 trace_ufshcd_clk_gating(dev_name(hba->dev),
1803 hba->clk_gating.state);
1806 spin_unlock_irqrestore(hba->host->host_lock, flags);
1811 /* host lock must be held before calling this variant */
1812 static void __ufshcd_release(struct ufs_hba *hba)
1814 if (!ufshcd_is_clkgating_allowed(hba))
1817 hba->clk_gating.active_reqs--;
1819 if (hba->clk_gating.active_reqs || hba->clk_gating.is_suspended ||
1820 hba->ufshcd_state != UFSHCD_STATE_OPERATIONAL ||
1821 hba->outstanding_tasks ||
1822 hba->active_uic_cmd || hba->uic_async_done ||
1823 hba->clk_gating.state == CLKS_OFF)
1826 hba->clk_gating.state = REQ_CLKS_OFF;
1827 trace_ufshcd_clk_gating(dev_name(hba->dev), hba->clk_gating.state);
1828 queue_delayed_work(hba->clk_gating.clk_gating_workq,
1829 &hba->clk_gating.gate_work,
1830 msecs_to_jiffies(hba->clk_gating.delay_ms));
1833 void ufshcd_release(struct ufs_hba *hba)
1835 unsigned long flags;
1837 spin_lock_irqsave(hba->host->host_lock, flags);
1838 __ufshcd_release(hba);
1839 spin_unlock_irqrestore(hba->host->host_lock, flags);
1841 EXPORT_SYMBOL_GPL(ufshcd_release);
1843 static ssize_t ufshcd_clkgate_delay_show(struct device *dev,
1844 struct device_attribute *attr, char *buf)
1846 struct ufs_hba *hba = dev_get_drvdata(dev);
1848 return sysfs_emit(buf, "%lu\n", hba->clk_gating.delay_ms);
1851 static ssize_t ufshcd_clkgate_delay_store(struct device *dev,
1852 struct device_attribute *attr, const char *buf, size_t count)
1854 struct ufs_hba *hba = dev_get_drvdata(dev);
1855 unsigned long flags, value;
1857 if (kstrtoul(buf, 0, &value))
1860 spin_lock_irqsave(hba->host->host_lock, flags);
1861 hba->clk_gating.delay_ms = value;
1862 spin_unlock_irqrestore(hba->host->host_lock, flags);
1866 static ssize_t ufshcd_clkgate_enable_show(struct device *dev,
1867 struct device_attribute *attr, char *buf)
1869 struct ufs_hba *hba = dev_get_drvdata(dev);
1871 return sysfs_emit(buf, "%d\n", hba->clk_gating.is_enabled);
1874 static ssize_t ufshcd_clkgate_enable_store(struct device *dev,
1875 struct device_attribute *attr, const char *buf, size_t count)
1877 struct ufs_hba *hba = dev_get_drvdata(dev);
1878 unsigned long flags;
1881 if (kstrtou32(buf, 0, &value))
1886 spin_lock_irqsave(hba->host->host_lock, flags);
1887 if (value == hba->clk_gating.is_enabled)
1891 __ufshcd_release(hba);
1893 hba->clk_gating.active_reqs++;
1895 hba->clk_gating.is_enabled = value;
1897 spin_unlock_irqrestore(hba->host->host_lock, flags);
1901 static void ufshcd_init_clk_gating_sysfs(struct ufs_hba *hba)
1903 hba->clk_gating.delay_attr.show = ufshcd_clkgate_delay_show;
1904 hba->clk_gating.delay_attr.store = ufshcd_clkgate_delay_store;
1905 sysfs_attr_init(&hba->clk_gating.delay_attr.attr);
1906 hba->clk_gating.delay_attr.attr.name = "clkgate_delay_ms";
1907 hba->clk_gating.delay_attr.attr.mode = 0644;
1908 if (device_create_file(hba->dev, &hba->clk_gating.delay_attr))
1909 dev_err(hba->dev, "Failed to create sysfs for clkgate_delay\n");
1911 hba->clk_gating.enable_attr.show = ufshcd_clkgate_enable_show;
1912 hba->clk_gating.enable_attr.store = ufshcd_clkgate_enable_store;
1913 sysfs_attr_init(&hba->clk_gating.enable_attr.attr);
1914 hba->clk_gating.enable_attr.attr.name = "clkgate_enable";
1915 hba->clk_gating.enable_attr.attr.mode = 0644;
1916 if (device_create_file(hba->dev, &hba->clk_gating.enable_attr))
1917 dev_err(hba->dev, "Failed to create sysfs for clkgate_enable\n");
1920 static void ufshcd_remove_clk_gating_sysfs(struct ufs_hba *hba)
1922 if (hba->clk_gating.delay_attr.attr.name)
1923 device_remove_file(hba->dev, &hba->clk_gating.delay_attr);
1924 if (hba->clk_gating.enable_attr.attr.name)
1925 device_remove_file(hba->dev, &hba->clk_gating.enable_attr);
1928 static void ufshcd_init_clk_gating(struct ufs_hba *hba)
1930 char wq_name[sizeof("ufs_clk_gating_00")];
1932 if (!ufshcd_is_clkgating_allowed(hba))
1935 hba->clk_gating.state = CLKS_ON;
1937 hba->clk_gating.delay_ms = 150;
1938 INIT_DELAYED_WORK(&hba->clk_gating.gate_work, ufshcd_gate_work);
1939 INIT_WORK(&hba->clk_gating.ungate_work, ufshcd_ungate_work);
1941 snprintf(wq_name, ARRAY_SIZE(wq_name), "ufs_clk_gating_%d",
1942 hba->host->host_no);
1943 hba->clk_gating.clk_gating_workq = alloc_ordered_workqueue(wq_name,
1944 WQ_MEM_RECLAIM | WQ_HIGHPRI);
1946 ufshcd_init_clk_gating_sysfs(hba);
1948 hba->clk_gating.is_enabled = true;
1949 hba->clk_gating.is_initialized = true;
1952 static void ufshcd_exit_clk_gating(struct ufs_hba *hba)
1954 if (!hba->clk_gating.is_initialized)
1956 ufshcd_remove_clk_gating_sysfs(hba);
1957 cancel_work_sync(&hba->clk_gating.ungate_work);
1958 cancel_delayed_work_sync(&hba->clk_gating.gate_work);
1959 destroy_workqueue(hba->clk_gating.clk_gating_workq);
1960 hba->clk_gating.is_initialized = false;
1963 /* Must be called with host lock acquired */
1964 static void ufshcd_clk_scaling_start_busy(struct ufs_hba *hba)
1966 bool queue_resume_work = false;
1967 ktime_t curr_t = ktime_get();
1968 unsigned long flags;
1970 if (!ufshcd_is_clkscaling_supported(hba))
1973 spin_lock_irqsave(hba->host->host_lock, flags);
1974 if (!hba->clk_scaling.active_reqs++)
1975 queue_resume_work = true;
1977 if (!hba->clk_scaling.is_enabled || hba->pm_op_in_progress) {
1978 spin_unlock_irqrestore(hba->host->host_lock, flags);
1982 if (queue_resume_work)
1983 queue_work(hba->clk_scaling.workq,
1984 &hba->clk_scaling.resume_work);
1986 if (!hba->clk_scaling.window_start_t) {
1987 hba->clk_scaling.window_start_t = curr_t;
1988 hba->clk_scaling.tot_busy_t = 0;
1989 hba->clk_scaling.is_busy_started = false;
1992 if (!hba->clk_scaling.is_busy_started) {
1993 hba->clk_scaling.busy_start_t = curr_t;
1994 hba->clk_scaling.is_busy_started = true;
1996 spin_unlock_irqrestore(hba->host->host_lock, flags);
1999 static void ufshcd_clk_scaling_update_busy(struct ufs_hba *hba)
2001 struct ufs_clk_scaling *scaling = &hba->clk_scaling;
2002 unsigned long flags;
2004 if (!ufshcd_is_clkscaling_supported(hba))
2007 spin_lock_irqsave(hba->host->host_lock, flags);
2008 hba->clk_scaling.active_reqs--;
2009 if (!hba->outstanding_reqs && scaling->is_busy_started) {
2010 scaling->tot_busy_t += ktime_to_us(ktime_sub(ktime_get(),
2011 scaling->busy_start_t));
2012 scaling->busy_start_t = 0;
2013 scaling->is_busy_started = false;
2015 spin_unlock_irqrestore(hba->host->host_lock, flags);
2018 static inline int ufshcd_monitor_opcode2dir(u8 opcode)
2020 if (opcode == READ_6 || opcode == READ_10 || opcode == READ_16)
2022 else if (opcode == WRITE_6 || opcode == WRITE_10 || opcode == WRITE_16)
2028 static inline bool ufshcd_should_inform_monitor(struct ufs_hba *hba,
2029 struct ufshcd_lrb *lrbp)
2031 struct ufs_hba_monitor *m = &hba->monitor;
2033 return (m->enabled && lrbp && lrbp->cmd &&
2034 (!m->chunk_size || m->chunk_size == lrbp->cmd->sdb.length) &&
2035 ktime_before(hba->monitor.enabled_ts, lrbp->issue_time_stamp));
2038 static void ufshcd_start_monitor(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
2040 int dir = ufshcd_monitor_opcode2dir(*lrbp->cmd->cmnd);
2041 unsigned long flags;
2043 spin_lock_irqsave(hba->host->host_lock, flags);
2044 if (dir >= 0 && hba->monitor.nr_queued[dir]++ == 0)
2045 hba->monitor.busy_start_ts[dir] = ktime_get();
2046 spin_unlock_irqrestore(hba->host->host_lock, flags);
2049 static void ufshcd_update_monitor(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
2051 int dir = ufshcd_monitor_opcode2dir(*lrbp->cmd->cmnd);
2052 unsigned long flags;
2054 spin_lock_irqsave(hba->host->host_lock, flags);
2055 if (dir >= 0 && hba->monitor.nr_queued[dir] > 0) {
2056 struct request *req = lrbp->cmd->request;
2057 struct ufs_hba_monitor *m = &hba->monitor;
2058 ktime_t now, inc, lat;
2060 now = lrbp->compl_time_stamp;
2061 inc = ktime_sub(now, m->busy_start_ts[dir]);
2062 m->total_busy[dir] = ktime_add(m->total_busy[dir], inc);
2063 m->nr_sec_rw[dir] += blk_rq_sectors(req);
2065 /* Update latencies */
2067 lat = ktime_sub(now, lrbp->issue_time_stamp);
2068 m->lat_sum[dir] += lat;
2069 if (m->lat_max[dir] < lat || !m->lat_max[dir])
2070 m->lat_max[dir] = lat;
2071 if (m->lat_min[dir] > lat || !m->lat_min[dir])
2072 m->lat_min[dir] = lat;
2074 m->nr_queued[dir]--;
2075 /* Push forward the busy start of monitor */
2076 m->busy_start_ts[dir] = now;
2078 spin_unlock_irqrestore(hba->host->host_lock, flags);
2082 * ufshcd_send_command - Send SCSI or device management commands
2083 * @hba: per adapter instance
2084 * @task_tag: Task tag of the command
2087 void ufshcd_send_command(struct ufs_hba *hba, unsigned int task_tag)
2089 struct ufshcd_lrb *lrbp = &hba->lrb[task_tag];
2090 unsigned long flags;
2092 lrbp->issue_time_stamp = ktime_get();
2093 lrbp->compl_time_stamp = ktime_set(0, 0);
2094 ufshcd_add_command_trace(hba, task_tag, UFS_CMD_SEND);
2095 ufshcd_clk_scaling_start_busy(hba);
2096 if (unlikely(ufshcd_should_inform_monitor(hba, lrbp)))
2097 ufshcd_start_monitor(hba, lrbp);
2099 spin_lock_irqsave(&hba->outstanding_lock, flags);
2100 if (hba->vops && hba->vops->setup_xfer_req)
2101 hba->vops->setup_xfer_req(hba, task_tag, !!lrbp->cmd);
2102 __set_bit(task_tag, &hba->outstanding_reqs);
2103 ufshcd_writel(hba, 1 << task_tag, REG_UTP_TRANSFER_REQ_DOOR_BELL);
2104 spin_unlock_irqrestore(&hba->outstanding_lock, flags);
2106 /* Make sure that doorbell is committed immediately */
2111 * ufshcd_copy_sense_data - Copy sense data in case of check condition
2112 * @lrbp: pointer to local reference block
2114 static inline void ufshcd_copy_sense_data(struct ufshcd_lrb *lrbp)
2117 if (lrbp->sense_buffer &&
2118 ufshcd_get_rsp_upiu_data_seg_len(lrbp->ucd_rsp_ptr)) {
2121 len = be16_to_cpu(lrbp->ucd_rsp_ptr->sr.sense_data_len);
2122 len_to_copy = min_t(int, UFS_SENSE_SIZE, len);
2124 memcpy(lrbp->sense_buffer, lrbp->ucd_rsp_ptr->sr.sense_data,
2130 * ufshcd_copy_query_response() - Copy the Query Response and the data
2132 * @hba: per adapter instance
2133 * @lrbp: pointer to local reference block
2136 int ufshcd_copy_query_response(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
2138 struct ufs_query_res *query_res = &hba->dev_cmd.query.response;
2140 memcpy(&query_res->upiu_res, &lrbp->ucd_rsp_ptr->qr, QUERY_OSF_SIZE);
2142 /* Get the descriptor */
2143 if (hba->dev_cmd.query.descriptor &&
2144 lrbp->ucd_rsp_ptr->qr.opcode == UPIU_QUERY_OPCODE_READ_DESC) {
2145 u8 *descp = (u8 *)lrbp->ucd_rsp_ptr +
2146 GENERAL_UPIU_REQUEST_SIZE;
2150 /* data segment length */
2151 resp_len = be32_to_cpu(lrbp->ucd_rsp_ptr->header.dword_2) &
2152 MASK_QUERY_DATA_SEG_LEN;
2153 buf_len = be16_to_cpu(
2154 hba->dev_cmd.query.request.upiu_req.length);
2155 if (likely(buf_len >= resp_len)) {
2156 memcpy(hba->dev_cmd.query.descriptor, descp, resp_len);
2159 "%s: rsp size %d is bigger than buffer size %d",
2160 __func__, resp_len, buf_len);
2169 * ufshcd_hba_capabilities - Read controller capabilities
2170 * @hba: per adapter instance
2172 * Return: 0 on success, negative on error.
2174 static inline int ufshcd_hba_capabilities(struct ufs_hba *hba)
2178 hba->capabilities = ufshcd_readl(hba, REG_CONTROLLER_CAPABILITIES);
2180 /* nutrs and nutmrs are 0 based values */
2181 hba->nutrs = (hba->capabilities & MASK_TRANSFER_REQUESTS_SLOTS) + 1;
2183 ((hba->capabilities & MASK_TASK_MANAGEMENT_REQUEST_SLOTS) >> 16) + 1;
2185 /* Read crypto capabilities */
2186 err = ufshcd_hba_init_crypto_capabilities(hba);
2188 dev_err(hba->dev, "crypto setup failed\n");
2194 * ufshcd_ready_for_uic_cmd - Check if controller is ready
2195 * to accept UIC commands
2196 * @hba: per adapter instance
2197 * Return true on success, else false
2199 static inline bool ufshcd_ready_for_uic_cmd(struct ufs_hba *hba)
2201 if (ufshcd_readl(hba, REG_CONTROLLER_STATUS) & UIC_COMMAND_READY)
2208 * ufshcd_get_upmcrs - Get the power mode change request status
2209 * @hba: Pointer to adapter instance
2211 * This function gets the UPMCRS field of HCS register
2212 * Returns value of UPMCRS field
2214 static inline u8 ufshcd_get_upmcrs(struct ufs_hba *hba)
2216 return (ufshcd_readl(hba, REG_CONTROLLER_STATUS) >> 8) & 0x7;
2220 * ufshcd_dispatch_uic_cmd - Dispatch an UIC command to the Unipro layer
2221 * @hba: per adapter instance
2222 * @uic_cmd: UIC command
2225 ufshcd_dispatch_uic_cmd(struct ufs_hba *hba, struct uic_command *uic_cmd)
2227 lockdep_assert_held(&hba->uic_cmd_mutex);
2229 WARN_ON(hba->active_uic_cmd);
2231 hba->active_uic_cmd = uic_cmd;
2234 ufshcd_writel(hba, uic_cmd->argument1, REG_UIC_COMMAND_ARG_1);
2235 ufshcd_writel(hba, uic_cmd->argument2, REG_UIC_COMMAND_ARG_2);
2236 ufshcd_writel(hba, uic_cmd->argument3, REG_UIC_COMMAND_ARG_3);
2238 ufshcd_add_uic_command_trace(hba, uic_cmd, UFS_CMD_SEND);
2241 ufshcd_writel(hba, uic_cmd->command & COMMAND_OPCODE_MASK,
2246 * ufshcd_wait_for_uic_cmd - Wait for completion of an UIC command
2247 * @hba: per adapter instance
2248 * @uic_cmd: UIC command
2250 * Returns 0 only if success.
2253 ufshcd_wait_for_uic_cmd(struct ufs_hba *hba, struct uic_command *uic_cmd)
2256 unsigned long flags;
2258 lockdep_assert_held(&hba->uic_cmd_mutex);
2260 if (wait_for_completion_timeout(&uic_cmd->done,
2261 msecs_to_jiffies(UIC_CMD_TIMEOUT))) {
2262 ret = uic_cmd->argument2 & MASK_UIC_COMMAND_RESULT;
2266 "uic cmd 0x%x with arg3 0x%x completion timeout\n",
2267 uic_cmd->command, uic_cmd->argument3);
2269 if (!uic_cmd->cmd_active) {
2270 dev_err(hba->dev, "%s: UIC cmd has been completed, return the result\n",
2272 ret = uic_cmd->argument2 & MASK_UIC_COMMAND_RESULT;
2276 spin_lock_irqsave(hba->host->host_lock, flags);
2277 hba->active_uic_cmd = NULL;
2278 spin_unlock_irqrestore(hba->host->host_lock, flags);
2284 * __ufshcd_send_uic_cmd - Send UIC commands and retrieve the result
2285 * @hba: per adapter instance
2286 * @uic_cmd: UIC command
2287 * @completion: initialize the completion only if this is set to true
2289 * Returns 0 only if success.
2292 __ufshcd_send_uic_cmd(struct ufs_hba *hba, struct uic_command *uic_cmd,
2295 lockdep_assert_held(&hba->uic_cmd_mutex);
2296 lockdep_assert_held(hba->host->host_lock);
2298 if (!ufshcd_ready_for_uic_cmd(hba)) {
2300 "Controller not ready to accept UIC commands\n");
2305 init_completion(&uic_cmd->done);
2307 uic_cmd->cmd_active = 1;
2308 ufshcd_dispatch_uic_cmd(hba, uic_cmd);
2314 * ufshcd_send_uic_cmd - Send UIC commands and retrieve the result
2315 * @hba: per adapter instance
2316 * @uic_cmd: UIC command
2318 * Returns 0 only if success.
2320 int ufshcd_send_uic_cmd(struct ufs_hba *hba, struct uic_command *uic_cmd)
2323 unsigned long flags;
2325 ufshcd_hold(hba, false);
2326 mutex_lock(&hba->uic_cmd_mutex);
2327 ufshcd_add_delay_before_dme_cmd(hba);
2329 spin_lock_irqsave(hba->host->host_lock, flags);
2330 ret = __ufshcd_send_uic_cmd(hba, uic_cmd, true);
2331 spin_unlock_irqrestore(hba->host->host_lock, flags);
2333 ret = ufshcd_wait_for_uic_cmd(hba, uic_cmd);
2335 mutex_unlock(&hba->uic_cmd_mutex);
2337 ufshcd_release(hba);
2342 * ufshcd_map_sg - Map scatter-gather list to prdt
2343 * @hba: per adapter instance
2344 * @lrbp: pointer to local reference block
2346 * Returns 0 in case of success, non-zero value in case of failure
2348 static int ufshcd_map_sg(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
2350 struct ufshcd_sg_entry *prd_table;
2351 struct scatterlist *sg;
2352 struct scsi_cmnd *cmd;
2357 sg_segments = scsi_dma_map(cmd);
2358 if (sg_segments < 0)
2363 if (hba->quirks & UFSHCD_QUIRK_PRDT_BYTE_GRAN)
2364 lrbp->utr_descriptor_ptr->prd_table_length =
2365 cpu_to_le16((sg_segments *
2366 sizeof(struct ufshcd_sg_entry)));
2368 lrbp->utr_descriptor_ptr->prd_table_length =
2369 cpu_to_le16((u16) (sg_segments));
2371 prd_table = (struct ufshcd_sg_entry *)lrbp->ucd_prdt_ptr;
2373 scsi_for_each_sg(cmd, sg, sg_segments, i) {
2375 cpu_to_le32(((u32) sg_dma_len(sg))-1);
2376 prd_table[i].base_addr =
2377 cpu_to_le32(lower_32_bits(sg->dma_address));
2378 prd_table[i].upper_addr =
2379 cpu_to_le32(upper_32_bits(sg->dma_address));
2380 prd_table[i].reserved = 0;
2383 lrbp->utr_descriptor_ptr->prd_table_length = 0;
2390 * ufshcd_enable_intr - enable interrupts
2391 * @hba: per adapter instance
2392 * @intrs: interrupt bits
2394 static void ufshcd_enable_intr(struct ufs_hba *hba, u32 intrs)
2396 u32 set = ufshcd_readl(hba, REG_INTERRUPT_ENABLE);
2398 if (hba->ufs_version == ufshci_version(1, 0)) {
2400 rw = set & INTERRUPT_MASK_RW_VER_10;
2401 set = rw | ((set ^ intrs) & intrs);
2406 ufshcd_writel(hba, set, REG_INTERRUPT_ENABLE);
2410 * ufshcd_disable_intr - disable interrupts
2411 * @hba: per adapter instance
2412 * @intrs: interrupt bits
2414 static void ufshcd_disable_intr(struct ufs_hba *hba, u32 intrs)
2416 u32 set = ufshcd_readl(hba, REG_INTERRUPT_ENABLE);
2418 if (hba->ufs_version == ufshci_version(1, 0)) {
2420 rw = (set & INTERRUPT_MASK_RW_VER_10) &
2421 ~(intrs & INTERRUPT_MASK_RW_VER_10);
2422 set = rw | ((set & intrs) & ~INTERRUPT_MASK_RW_VER_10);
2428 ufshcd_writel(hba, set, REG_INTERRUPT_ENABLE);
2432 * ufshcd_prepare_req_desc_hdr() - Fills the requests header
2433 * descriptor according to request
2434 * @lrbp: pointer to local reference block
2435 * @upiu_flags: flags required in the header
2436 * @cmd_dir: requests data direction
2438 static void ufshcd_prepare_req_desc_hdr(struct ufshcd_lrb *lrbp,
2439 u8 *upiu_flags, enum dma_data_direction cmd_dir)
2441 struct utp_transfer_req_desc *req_desc = lrbp->utr_descriptor_ptr;
2447 if (cmd_dir == DMA_FROM_DEVICE) {
2448 data_direction = UTP_DEVICE_TO_HOST;
2449 *upiu_flags = UPIU_CMD_FLAGS_READ;
2450 } else if (cmd_dir == DMA_TO_DEVICE) {
2451 data_direction = UTP_HOST_TO_DEVICE;
2452 *upiu_flags = UPIU_CMD_FLAGS_WRITE;
2454 data_direction = UTP_NO_DATA_TRANSFER;
2455 *upiu_flags = UPIU_CMD_FLAGS_NONE;
2458 dword_0 = data_direction | (lrbp->command_type
2459 << UPIU_COMMAND_TYPE_OFFSET);
2461 dword_0 |= UTP_REQ_DESC_INT_CMD;
2463 /* Prepare crypto related dwords */
2464 ufshcd_prepare_req_desc_hdr_crypto(lrbp, &dword_0, &dword_1, &dword_3);
2466 /* Transfer request descriptor header fields */
2467 req_desc->header.dword_0 = cpu_to_le32(dword_0);
2468 req_desc->header.dword_1 = cpu_to_le32(dword_1);
2470 * assigning invalid value for command status. Controller
2471 * updates OCS on command completion, with the command
2474 req_desc->header.dword_2 =
2475 cpu_to_le32(OCS_INVALID_COMMAND_STATUS);
2476 req_desc->header.dword_3 = cpu_to_le32(dword_3);
2478 req_desc->prd_table_length = 0;
2482 * ufshcd_prepare_utp_scsi_cmd_upiu() - fills the utp_transfer_req_desc,
2484 * @lrbp: local reference block pointer
2485 * @upiu_flags: flags
2488 void ufshcd_prepare_utp_scsi_cmd_upiu(struct ufshcd_lrb *lrbp, u8 upiu_flags)
2490 struct scsi_cmnd *cmd = lrbp->cmd;
2491 struct utp_upiu_req *ucd_req_ptr = lrbp->ucd_req_ptr;
2492 unsigned short cdb_len;
2494 /* command descriptor fields */
2495 ucd_req_ptr->header.dword_0 = UPIU_HEADER_DWORD(
2496 UPIU_TRANSACTION_COMMAND, upiu_flags,
2497 lrbp->lun, lrbp->task_tag);
2498 ucd_req_ptr->header.dword_1 = UPIU_HEADER_DWORD(
2499 UPIU_COMMAND_SET_TYPE_SCSI, 0, 0, 0);
2501 /* Total EHS length and Data segment length will be zero */
2502 ucd_req_ptr->header.dword_2 = 0;
2504 ucd_req_ptr->sc.exp_data_transfer_len = cpu_to_be32(cmd->sdb.length);
2506 cdb_len = min_t(unsigned short, cmd->cmd_len, UFS_CDB_SIZE);
2507 memset(ucd_req_ptr->sc.cdb, 0, UFS_CDB_SIZE);
2508 memcpy(ucd_req_ptr->sc.cdb, cmd->cmnd, cdb_len);
2510 memset(lrbp->ucd_rsp_ptr, 0, sizeof(struct utp_upiu_rsp));
2514 * ufshcd_prepare_utp_query_req_upiu() - fills the utp_transfer_req_desc,
2517 * @lrbp: local reference block pointer
2518 * @upiu_flags: flags
2520 static void ufshcd_prepare_utp_query_req_upiu(struct ufs_hba *hba,
2521 struct ufshcd_lrb *lrbp, u8 upiu_flags)
2523 struct utp_upiu_req *ucd_req_ptr = lrbp->ucd_req_ptr;
2524 struct ufs_query *query = &hba->dev_cmd.query;
2525 u16 len = be16_to_cpu(query->request.upiu_req.length);
2527 /* Query request header */
2528 ucd_req_ptr->header.dword_0 = UPIU_HEADER_DWORD(
2529 UPIU_TRANSACTION_QUERY_REQ, upiu_flags,
2530 lrbp->lun, lrbp->task_tag);
2531 ucd_req_ptr->header.dword_1 = UPIU_HEADER_DWORD(
2532 0, query->request.query_func, 0, 0);
2534 /* Data segment length only need for WRITE_DESC */
2535 if (query->request.upiu_req.opcode == UPIU_QUERY_OPCODE_WRITE_DESC)
2536 ucd_req_ptr->header.dword_2 =
2537 UPIU_HEADER_DWORD(0, 0, (len >> 8), (u8)len);
2539 ucd_req_ptr->header.dword_2 = 0;
2541 /* Copy the Query Request buffer as is */
2542 memcpy(&ucd_req_ptr->qr, &query->request.upiu_req,
2545 /* Copy the Descriptor */
2546 if (query->request.upiu_req.opcode == UPIU_QUERY_OPCODE_WRITE_DESC)
2547 memcpy(ucd_req_ptr + 1, query->descriptor, len);
2549 memset(lrbp->ucd_rsp_ptr, 0, sizeof(struct utp_upiu_rsp));
2552 static inline void ufshcd_prepare_utp_nop_upiu(struct ufshcd_lrb *lrbp)
2554 struct utp_upiu_req *ucd_req_ptr = lrbp->ucd_req_ptr;
2556 memset(ucd_req_ptr, 0, sizeof(struct utp_upiu_req));
2558 /* command descriptor fields */
2559 ucd_req_ptr->header.dword_0 =
2561 UPIU_TRANSACTION_NOP_OUT, 0, 0, lrbp->task_tag);
2562 /* clear rest of the fields of basic header */
2563 ucd_req_ptr->header.dword_1 = 0;
2564 ucd_req_ptr->header.dword_2 = 0;
2566 memset(lrbp->ucd_rsp_ptr, 0, sizeof(struct utp_upiu_rsp));
2570 * ufshcd_compose_devman_upiu - UFS Protocol Information Unit(UPIU)
2571 * for Device Management Purposes
2572 * @hba: per adapter instance
2573 * @lrbp: pointer to local reference block
2575 static int ufshcd_compose_devman_upiu(struct ufs_hba *hba,
2576 struct ufshcd_lrb *lrbp)
2581 if (hba->ufs_version <= ufshci_version(1, 1))
2582 lrbp->command_type = UTP_CMD_TYPE_DEV_MANAGE;
2584 lrbp->command_type = UTP_CMD_TYPE_UFS_STORAGE;
2586 ufshcd_prepare_req_desc_hdr(lrbp, &upiu_flags, DMA_NONE);
2587 if (hba->dev_cmd.type == DEV_CMD_TYPE_QUERY)
2588 ufshcd_prepare_utp_query_req_upiu(hba, lrbp, upiu_flags);
2589 else if (hba->dev_cmd.type == DEV_CMD_TYPE_NOP)
2590 ufshcd_prepare_utp_nop_upiu(lrbp);
2598 * ufshcd_comp_scsi_upiu - UFS Protocol Information Unit(UPIU)
2600 * @hba: per adapter instance
2601 * @lrbp: pointer to local reference block
2603 static int ufshcd_comp_scsi_upiu(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
2608 if (hba->ufs_version <= ufshci_version(1, 1))
2609 lrbp->command_type = UTP_CMD_TYPE_SCSI;
2611 lrbp->command_type = UTP_CMD_TYPE_UFS_STORAGE;
2613 if (likely(lrbp->cmd)) {
2614 ufshcd_prepare_req_desc_hdr(lrbp, &upiu_flags,
2615 lrbp->cmd->sc_data_direction);
2616 ufshcd_prepare_utp_scsi_cmd_upiu(lrbp, upiu_flags);
2625 * ufshcd_upiu_wlun_to_scsi_wlun - maps UPIU W-LUN id to SCSI W-LUN ID
2626 * @upiu_wlun_id: UPIU W-LUN id
2628 * Returns SCSI W-LUN id
2630 static inline u16 ufshcd_upiu_wlun_to_scsi_wlun(u8 upiu_wlun_id)
2632 return (upiu_wlun_id & ~UFS_UPIU_WLUN_ID) | SCSI_W_LUN_BASE;
2635 static inline bool is_rpmb_wlun(struct scsi_device *sdev)
2637 return sdev->lun == ufshcd_upiu_wlun_to_scsi_wlun(UFS_UPIU_RPMB_WLUN);
2640 static inline bool is_device_wlun(struct scsi_device *sdev)
2643 ufshcd_upiu_wlun_to_scsi_wlun(UFS_UPIU_UFS_DEVICE_WLUN);
2646 static void ufshcd_init_lrb(struct ufs_hba *hba, struct ufshcd_lrb *lrb, int i)
2648 struct utp_transfer_cmd_desc *cmd_descp = hba->ucdl_base_addr;
2649 struct utp_transfer_req_desc *utrdlp = hba->utrdl_base_addr;
2650 dma_addr_t cmd_desc_element_addr = hba->ucdl_dma_addr +
2651 i * sizeof(struct utp_transfer_cmd_desc);
2652 u16 response_offset = offsetof(struct utp_transfer_cmd_desc,
2654 u16 prdt_offset = offsetof(struct utp_transfer_cmd_desc, prd_table);
2656 lrb->utr_descriptor_ptr = utrdlp + i;
2657 lrb->utrd_dma_addr = hba->utrdl_dma_addr +
2658 i * sizeof(struct utp_transfer_req_desc);
2659 lrb->ucd_req_ptr = (struct utp_upiu_req *)(cmd_descp + i);
2660 lrb->ucd_req_dma_addr = cmd_desc_element_addr;
2661 lrb->ucd_rsp_ptr = (struct utp_upiu_rsp *)cmd_descp[i].response_upiu;
2662 lrb->ucd_rsp_dma_addr = cmd_desc_element_addr + response_offset;
2663 lrb->ucd_prdt_ptr = (struct ufshcd_sg_entry *)cmd_descp[i].prd_table;
2664 lrb->ucd_prdt_dma_addr = cmd_desc_element_addr + prdt_offset;
2668 * ufshcd_queuecommand - main entry point for SCSI requests
2669 * @host: SCSI host pointer
2670 * @cmd: command from SCSI Midlayer
2672 * Returns 0 for success, non-zero in case of failure
2674 static int ufshcd_queuecommand(struct Scsi_Host *host, struct scsi_cmnd *cmd)
2676 struct ufs_hba *hba = shost_priv(host);
2677 int tag = cmd->request->tag;
2678 struct ufshcd_lrb *lrbp;
2681 WARN_ONCE(tag < 0, "Invalid tag %d\n", tag);
2683 if (!down_read_trylock(&hba->clk_scaling_lock))
2684 return SCSI_MLQUEUE_HOST_BUSY;
2686 switch (hba->ufshcd_state) {
2687 case UFSHCD_STATE_OPERATIONAL:
2688 case UFSHCD_STATE_EH_SCHEDULED_NON_FATAL:
2690 case UFSHCD_STATE_EH_SCHEDULED_FATAL:
2692 * pm_runtime_get_sync() is used at error handling preparation
2693 * stage. If a scsi cmd, e.g. the SSU cmd, is sent from hba's
2694 * PM ops, it can never be finished if we let SCSI layer keep
2695 * retrying it, which gets err handler stuck forever. Neither
2696 * can we let the scsi cmd pass through, because UFS is in bad
2697 * state, the scsi cmd may eventually time out, which will get
2698 * err handler blocked for too long. So, just fail the scsi cmd
2699 * sent from PM ops, err handler can recover PM error anyways.
2701 if (hba->pm_op_in_progress) {
2702 hba->force_reset = true;
2703 set_host_byte(cmd, DID_BAD_TARGET);
2704 cmd->scsi_done(cmd);
2708 case UFSHCD_STATE_RESET:
2709 err = SCSI_MLQUEUE_HOST_BUSY;
2711 case UFSHCD_STATE_ERROR:
2712 set_host_byte(cmd, DID_ERROR);
2713 cmd->scsi_done(cmd);
2717 hba->req_abort_count = 0;
2719 err = ufshcd_hold(hba, true);
2721 err = SCSI_MLQUEUE_HOST_BUSY;
2724 WARN_ON(ufshcd_is_clkgating_allowed(hba) &&
2725 (hba->clk_gating.state != CLKS_ON));
2727 lrbp = &hba->lrb[tag];
2730 lrbp->sense_bufflen = UFS_SENSE_SIZE;
2731 lrbp->sense_buffer = cmd->sense_buffer;
2732 lrbp->task_tag = tag;
2733 lrbp->lun = ufshcd_scsi_to_upiu_lun(cmd->device->lun);
2734 lrbp->intr_cmd = !ufshcd_is_intr_aggr_allowed(hba) ? true : false;
2736 ufshcd_prepare_lrbp_crypto(cmd->request, lrbp);
2738 lrbp->req_abort_skip = false;
2740 err = ufshpb_prep(hba, lrbp);
2741 if (err == -EAGAIN) {
2743 ufshcd_release(hba);
2747 ufshcd_comp_scsi_upiu(hba, lrbp);
2749 err = ufshcd_map_sg(hba, lrbp);
2752 ufshcd_release(hba);
2756 ufshcd_send_command(hba, tag);
2758 up_read(&hba->clk_scaling_lock);
2760 if (ufs_trigger_eh())
2761 scsi_schedule_eh(hba->host);
2766 static int ufshcd_compose_dev_cmd(struct ufs_hba *hba,
2767 struct ufshcd_lrb *lrbp, enum dev_cmd_type cmd_type, int tag)
2770 lrbp->sense_bufflen = 0;
2771 lrbp->sense_buffer = NULL;
2772 lrbp->task_tag = tag;
2773 lrbp->lun = 0; /* device management cmd is not specific to any LUN */
2774 lrbp->intr_cmd = true; /* No interrupt aggregation */
2775 ufshcd_prepare_lrbp_crypto(NULL, lrbp);
2776 hba->dev_cmd.type = cmd_type;
2778 return ufshcd_compose_devman_upiu(hba, lrbp);
2782 ufshcd_clear_cmd(struct ufs_hba *hba, int tag)
2785 unsigned long flags;
2786 u32 mask = 1 << tag;
2788 /* clear outstanding transaction before retry */
2789 spin_lock_irqsave(hba->host->host_lock, flags);
2790 ufshcd_utrl_clear(hba, tag);
2791 spin_unlock_irqrestore(hba->host->host_lock, flags);
2794 * wait for h/w to clear corresponding bit in door-bell.
2795 * max. wait is 1 sec.
2797 err = ufshcd_wait_for_register(hba,
2798 REG_UTP_TRANSFER_REQ_DOOR_BELL,
2799 mask, ~mask, 1000, 1000);
2805 ufshcd_check_query_response(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
2807 struct ufs_query_res *query_res = &hba->dev_cmd.query.response;
2809 /* Get the UPIU response */
2810 query_res->response = ufshcd_get_rsp_upiu_result(lrbp->ucd_rsp_ptr) >>
2811 UPIU_RSP_CODE_OFFSET;
2812 return query_res->response;
2816 * ufshcd_dev_cmd_completion() - handles device management command responses
2817 * @hba: per adapter instance
2818 * @lrbp: pointer to local reference block
2821 ufshcd_dev_cmd_completion(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
2826 hba->ufs_stats.last_hibern8_exit_tstamp = ktime_set(0, 0);
2827 resp = ufshcd_get_req_rsp(lrbp->ucd_rsp_ptr);
2830 case UPIU_TRANSACTION_NOP_IN:
2831 if (hba->dev_cmd.type != DEV_CMD_TYPE_NOP) {
2833 dev_err(hba->dev, "%s: unexpected response %x\n",
2837 case UPIU_TRANSACTION_QUERY_RSP:
2838 err = ufshcd_check_query_response(hba, lrbp);
2840 err = ufshcd_copy_query_response(hba, lrbp);
2842 case UPIU_TRANSACTION_REJECT_UPIU:
2843 /* TODO: handle Reject UPIU Response */
2845 dev_err(hba->dev, "%s: Reject UPIU not fully implemented\n",
2850 dev_err(hba->dev, "%s: Invalid device management cmd response: %x\n",
2858 static int ufshcd_wait_for_dev_cmd(struct ufs_hba *hba,
2859 struct ufshcd_lrb *lrbp, int max_timeout)
2862 unsigned long time_left;
2863 unsigned long flags;
2865 time_left = wait_for_completion_timeout(hba->dev_cmd.complete,
2866 msecs_to_jiffies(max_timeout));
2868 spin_lock_irqsave(hba->host->host_lock, flags);
2869 hba->dev_cmd.complete = NULL;
2870 if (likely(time_left)) {
2871 err = ufshcd_get_tr_ocs(lrbp);
2873 err = ufshcd_dev_cmd_completion(hba, lrbp);
2875 spin_unlock_irqrestore(hba->host->host_lock, flags);
2879 dev_dbg(hba->dev, "%s: dev_cmd request timedout, tag %d\n",
2880 __func__, lrbp->task_tag);
2881 if (!ufshcd_clear_cmd(hba, lrbp->task_tag))
2882 /* successfully cleared the command, retry if needed */
2885 * in case of an error, after clearing the doorbell,
2886 * we also need to clear the outstanding_request
2889 spin_lock_irqsave(&hba->outstanding_lock, flags);
2890 __clear_bit(lrbp->task_tag, &hba->outstanding_reqs);
2891 spin_unlock_irqrestore(&hba->outstanding_lock, flags);
2898 * ufshcd_exec_dev_cmd - API for sending device management requests
2900 * @cmd_type: specifies the type (NOP, Query...)
2901 * @timeout: timeout in milliseconds
2903 * NOTE: Since there is only one available tag for device management commands,
2904 * it is expected you hold the hba->dev_cmd.lock mutex.
2906 static int ufshcd_exec_dev_cmd(struct ufs_hba *hba,
2907 enum dev_cmd_type cmd_type, int timeout)
2909 struct request_queue *q = hba->cmd_queue;
2910 DECLARE_COMPLETION_ONSTACK(wait);
2911 struct request *req;
2912 struct ufshcd_lrb *lrbp;
2916 down_read(&hba->clk_scaling_lock);
2919 * Get free slot, sleep if slots are unavailable.
2920 * Even though we use wait_event() which sleeps indefinitely,
2921 * the maximum wait time is bounded by SCSI request timeout.
2923 req = blk_get_request(q, REQ_OP_DRV_OUT, 0);
2929 WARN_ONCE(tag < 0, "Invalid tag %d\n", tag);
2930 /* Set the timeout such that the SCSI error handler is not activated. */
2931 req->timeout = msecs_to_jiffies(2 * timeout);
2932 blk_mq_start_request(req);
2934 lrbp = &hba->lrb[tag];
2936 err = ufshcd_compose_dev_cmd(hba, lrbp, cmd_type, tag);
2940 hba->dev_cmd.complete = &wait;
2942 ufshcd_add_query_upiu_trace(hba, UFS_QUERY_SEND, lrbp->ucd_req_ptr);
2944 ufshcd_send_command(hba, tag);
2945 err = ufshcd_wait_for_dev_cmd(hba, lrbp, timeout);
2946 ufshcd_add_query_upiu_trace(hba, err ? UFS_QUERY_ERR : UFS_QUERY_COMP,
2947 (struct utp_upiu_req *)lrbp->ucd_rsp_ptr);
2950 blk_put_request(req);
2952 up_read(&hba->clk_scaling_lock);
2957 * ufshcd_init_query() - init the query response and request parameters
2958 * @hba: per-adapter instance
2959 * @request: address of the request pointer to be initialized
2960 * @response: address of the response pointer to be initialized
2961 * @opcode: operation to perform
2962 * @idn: flag idn to access
2963 * @index: LU number to access
2964 * @selector: query/flag/descriptor further identification
2966 static inline void ufshcd_init_query(struct ufs_hba *hba,
2967 struct ufs_query_req **request, struct ufs_query_res **response,
2968 enum query_opcode opcode, u8 idn, u8 index, u8 selector)
2970 *request = &hba->dev_cmd.query.request;
2971 *response = &hba->dev_cmd.query.response;
2972 memset(*request, 0, sizeof(struct ufs_query_req));
2973 memset(*response, 0, sizeof(struct ufs_query_res));
2974 (*request)->upiu_req.opcode = opcode;
2975 (*request)->upiu_req.idn = idn;
2976 (*request)->upiu_req.index = index;
2977 (*request)->upiu_req.selector = selector;
2980 static int ufshcd_query_flag_retry(struct ufs_hba *hba,
2981 enum query_opcode opcode, enum flag_idn idn, u8 index, bool *flag_res)
2986 for (retries = 0; retries < QUERY_REQ_RETRIES; retries++) {
2987 ret = ufshcd_query_flag(hba, opcode, idn, index, flag_res);
2990 "%s: failed with error %d, retries %d\n",
2991 __func__, ret, retries);
2998 "%s: query attribute, opcode %d, idn %d, failed with error %d after %d retires\n",
2999 __func__, opcode, idn, ret, retries);
3004 * ufshcd_query_flag() - API function for sending flag query requests
3005 * @hba: per-adapter instance
3006 * @opcode: flag query to perform
3007 * @idn: flag idn to access
3008 * @index: flag index to access
3009 * @flag_res: the flag value after the query request completes
3011 * Returns 0 for success, non-zero in case of failure
3013 int ufshcd_query_flag(struct ufs_hba *hba, enum query_opcode opcode,
3014 enum flag_idn idn, u8 index, bool *flag_res)
3016 struct ufs_query_req *request = NULL;
3017 struct ufs_query_res *response = NULL;
3018 int err, selector = 0;
3019 int timeout = QUERY_REQ_TIMEOUT;
3023 ufshcd_hold(hba, false);
3024 mutex_lock(&hba->dev_cmd.lock);
3025 ufshcd_init_query(hba, &request, &response, opcode, idn, index,
3029 case UPIU_QUERY_OPCODE_SET_FLAG:
3030 case UPIU_QUERY_OPCODE_CLEAR_FLAG:
3031 case UPIU_QUERY_OPCODE_TOGGLE_FLAG:
3032 request->query_func = UPIU_QUERY_FUNC_STANDARD_WRITE_REQUEST;
3034 case UPIU_QUERY_OPCODE_READ_FLAG:
3035 request->query_func = UPIU_QUERY_FUNC_STANDARD_READ_REQUEST;
3037 /* No dummy reads */
3038 dev_err(hba->dev, "%s: Invalid argument for read request\n",
3046 "%s: Expected query flag opcode but got = %d\n",
3052 err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_QUERY, timeout);
3056 "%s: Sending flag query for idn %d failed, err = %d\n",
3057 __func__, idn, err);
3062 *flag_res = (be32_to_cpu(response->upiu_res.value) &
3063 MASK_QUERY_UPIU_FLAG_LOC) & 0x1;
3066 mutex_unlock(&hba->dev_cmd.lock);
3067 ufshcd_release(hba);
3072 * ufshcd_query_attr - API function for sending attribute requests
3073 * @hba: per-adapter instance
3074 * @opcode: attribute opcode
3075 * @idn: attribute idn to access
3076 * @index: index field
3077 * @selector: selector field
3078 * @attr_val: the attribute value after the query request completes
3080 * Returns 0 for success, non-zero in case of failure
3082 int ufshcd_query_attr(struct ufs_hba *hba, enum query_opcode opcode,
3083 enum attr_idn idn, u8 index, u8 selector, u32 *attr_val)
3085 struct ufs_query_req *request = NULL;
3086 struct ufs_query_res *response = NULL;
3092 dev_err(hba->dev, "%s: attribute value required for opcode 0x%x\n",
3097 ufshcd_hold(hba, false);
3099 mutex_lock(&hba->dev_cmd.lock);
3100 ufshcd_init_query(hba, &request, &response, opcode, idn, index,
3104 case UPIU_QUERY_OPCODE_WRITE_ATTR:
3105 request->query_func = UPIU_QUERY_FUNC_STANDARD_WRITE_REQUEST;
3106 request->upiu_req.value = cpu_to_be32(*attr_val);
3108 case UPIU_QUERY_OPCODE_READ_ATTR:
3109 request->query_func = UPIU_QUERY_FUNC_STANDARD_READ_REQUEST;
3112 dev_err(hba->dev, "%s: Expected query attr opcode but got = 0x%.2x\n",
3118 err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_QUERY, QUERY_REQ_TIMEOUT);
3121 dev_err(hba->dev, "%s: opcode 0x%.2x for idn %d failed, index %d, err = %d\n",
3122 __func__, opcode, idn, index, err);
3126 *attr_val = be32_to_cpu(response->upiu_res.value);
3129 mutex_unlock(&hba->dev_cmd.lock);
3130 ufshcd_release(hba);
3135 * ufshcd_query_attr_retry() - API function for sending query
3136 * attribute with retries
3137 * @hba: per-adapter instance
3138 * @opcode: attribute opcode
3139 * @idn: attribute idn to access
3140 * @index: index field
3141 * @selector: selector field
3142 * @attr_val: the attribute value after the query request
3145 * Returns 0 for success, non-zero in case of failure
3147 int ufshcd_query_attr_retry(struct ufs_hba *hba,
3148 enum query_opcode opcode, enum attr_idn idn, u8 index, u8 selector,
3154 for (retries = QUERY_REQ_RETRIES; retries > 0; retries--) {
3155 ret = ufshcd_query_attr(hba, opcode, idn, index,
3156 selector, attr_val);
3158 dev_dbg(hba->dev, "%s: failed with error %d, retries %d\n",
3159 __func__, ret, retries);
3166 "%s: query attribute, idn %d, failed with error %d after %d retires\n",
3167 __func__, idn, ret, QUERY_REQ_RETRIES);
3171 static int __ufshcd_query_descriptor(struct ufs_hba *hba,
3172 enum query_opcode opcode, enum desc_idn idn, u8 index,
3173 u8 selector, u8 *desc_buf, int *buf_len)
3175 struct ufs_query_req *request = NULL;
3176 struct ufs_query_res *response = NULL;
3182 dev_err(hba->dev, "%s: descriptor buffer required for opcode 0x%x\n",
3187 if (*buf_len < QUERY_DESC_MIN_SIZE || *buf_len > QUERY_DESC_MAX_SIZE) {
3188 dev_err(hba->dev, "%s: descriptor buffer size (%d) is out of range\n",
3189 __func__, *buf_len);
3193 ufshcd_hold(hba, false);
3195 mutex_lock(&hba->dev_cmd.lock);
3196 ufshcd_init_query(hba, &request, &response, opcode, idn, index,
3198 hba->dev_cmd.query.descriptor = desc_buf;
3199 request->upiu_req.length = cpu_to_be16(*buf_len);
3202 case UPIU_QUERY_OPCODE_WRITE_DESC:
3203 request->query_func = UPIU_QUERY_FUNC_STANDARD_WRITE_REQUEST;
3205 case UPIU_QUERY_OPCODE_READ_DESC:
3206 request->query_func = UPIU_QUERY_FUNC_STANDARD_READ_REQUEST;
3210 "%s: Expected query descriptor opcode but got = 0x%.2x\n",
3216 err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_QUERY, QUERY_REQ_TIMEOUT);
3219 dev_err(hba->dev, "%s: opcode 0x%.2x for idn %d failed, index %d, err = %d\n",
3220 __func__, opcode, idn, index, err);
3224 *buf_len = be16_to_cpu(response->upiu_res.length);
3227 hba->dev_cmd.query.descriptor = NULL;
3228 mutex_unlock(&hba->dev_cmd.lock);
3229 ufshcd_release(hba);
3234 * ufshcd_query_descriptor_retry - API function for sending descriptor requests
3235 * @hba: per-adapter instance
3236 * @opcode: attribute opcode
3237 * @idn: attribute idn to access
3238 * @index: index field
3239 * @selector: selector field
3240 * @desc_buf: the buffer that contains the descriptor
3241 * @buf_len: length parameter passed to the device
3243 * Returns 0 for success, non-zero in case of failure.
3244 * The buf_len parameter will contain, on return, the length parameter
3245 * received on the response.
3247 int ufshcd_query_descriptor_retry(struct ufs_hba *hba,
3248 enum query_opcode opcode,
3249 enum desc_idn idn, u8 index,
3251 u8 *desc_buf, int *buf_len)
3256 for (retries = QUERY_REQ_RETRIES; retries > 0; retries--) {
3257 err = __ufshcd_query_descriptor(hba, opcode, idn, index,
3258 selector, desc_buf, buf_len);
3259 if (!err || err == -EINVAL)
3267 * ufshcd_map_desc_id_to_length - map descriptor IDN to its length
3268 * @hba: Pointer to adapter instance
3269 * @desc_id: descriptor idn value
3270 * @desc_len: mapped desc length (out)
3272 void ufshcd_map_desc_id_to_length(struct ufs_hba *hba, enum desc_idn desc_id,
3275 if (desc_id >= QUERY_DESC_IDN_MAX || desc_id == QUERY_DESC_IDN_RFU_0 ||
3276 desc_id == QUERY_DESC_IDN_RFU_1)
3279 *desc_len = hba->desc_size[desc_id];
3281 EXPORT_SYMBOL(ufshcd_map_desc_id_to_length);
3283 static void ufshcd_update_desc_length(struct ufs_hba *hba,
3284 enum desc_idn desc_id, int desc_index,
3285 unsigned char desc_len)
3287 if (hba->desc_size[desc_id] == QUERY_DESC_MAX_SIZE &&
3288 desc_id != QUERY_DESC_IDN_STRING && desc_index != UFS_RPMB_UNIT)
3289 /* For UFS 3.1, the normal unit descriptor is 10 bytes larger
3290 * than the RPMB unit, however, both descriptors share the same
3291 * desc_idn, to cover both unit descriptors with one length, we
3292 * choose the normal unit descriptor length by desc_index.
3294 hba->desc_size[desc_id] = desc_len;
3298 * ufshcd_read_desc_param - read the specified descriptor parameter
3299 * @hba: Pointer to adapter instance
3300 * @desc_id: descriptor idn value
3301 * @desc_index: descriptor index
3302 * @param_offset: offset of the parameter to read
3303 * @param_read_buf: pointer to buffer where parameter would be read
3304 * @param_size: sizeof(param_read_buf)
3306 * Return 0 in case of success, non-zero otherwise
3308 int ufshcd_read_desc_param(struct ufs_hba *hba,
3309 enum desc_idn desc_id,
3318 bool is_kmalloc = true;
3321 if (desc_id >= QUERY_DESC_IDN_MAX || !param_size)
3324 /* Get the length of descriptor */
3325 ufshcd_map_desc_id_to_length(hba, desc_id, &buff_len);
3327 dev_err(hba->dev, "%s: Failed to get desc length\n", __func__);
3331 if (param_offset >= buff_len) {
3332 dev_err(hba->dev, "%s: Invalid offset 0x%x in descriptor IDN 0x%x, length 0x%x\n",
3333 __func__, param_offset, desc_id, buff_len);
3337 /* Check whether we need temp memory */
3338 if (param_offset != 0 || param_size < buff_len) {
3339 desc_buf = kzalloc(buff_len, GFP_KERNEL);
3343 desc_buf = param_read_buf;
3347 /* Request for full descriptor */
3348 ret = ufshcd_query_descriptor_retry(hba, UPIU_QUERY_OPCODE_READ_DESC,
3349 desc_id, desc_index, 0,
3350 desc_buf, &buff_len);
3353 dev_err(hba->dev, "%s: Failed reading descriptor. desc_id %d, desc_index %d, param_offset %d, ret %d\n",
3354 __func__, desc_id, desc_index, param_offset, ret);
3359 if (desc_buf[QUERY_DESC_DESC_TYPE_OFFSET] != desc_id) {
3360 dev_err(hba->dev, "%s: invalid desc_id %d in descriptor header\n",
3361 __func__, desc_buf[QUERY_DESC_DESC_TYPE_OFFSET]);
3366 /* Update descriptor length */
3367 buff_len = desc_buf[QUERY_DESC_LENGTH_OFFSET];
3368 ufshcd_update_desc_length(hba, desc_id, desc_index, buff_len);
3371 /* Make sure we don't copy more data than available */
3372 if (param_offset >= buff_len)
3375 memcpy(param_read_buf, &desc_buf[param_offset],
3376 min_t(u32, param_size, buff_len - param_offset));
3385 * struct uc_string_id - unicode string
3387 * @len: size of this descriptor inclusive
3388 * @type: descriptor type
3389 * @uc: unicode string character
3391 struct uc_string_id {
3397 /* replace non-printable or non-ASCII characters with spaces */
3398 static inline char ufshcd_remove_non_printable(u8 ch)
3400 return (ch >= 0x20 && ch <= 0x7e) ? ch : ' ';
3404 * ufshcd_read_string_desc - read string descriptor
3405 * @hba: pointer to adapter instance
3406 * @desc_index: descriptor index
3407 * @buf: pointer to buffer where descriptor would be read,
3408 * the caller should free the memory.
3409 * @ascii: if true convert from unicode to ascii characters
3410 * null terminated string.
3413 * * string size on success.
3414 * * -ENOMEM: on allocation failure
3415 * * -EINVAL: on a wrong parameter
3417 int ufshcd_read_string_desc(struct ufs_hba *hba, u8 desc_index,
3418 u8 **buf, bool ascii)
3420 struct uc_string_id *uc_str;
3427 uc_str = kzalloc(QUERY_DESC_MAX_SIZE, GFP_KERNEL);
3431 ret = ufshcd_read_desc_param(hba, QUERY_DESC_IDN_STRING, desc_index, 0,
3432 (u8 *)uc_str, QUERY_DESC_MAX_SIZE);
3434 dev_err(hba->dev, "Reading String Desc failed after %d retries. err = %d\n",
3435 QUERY_REQ_RETRIES, ret);
3440 if (uc_str->len <= QUERY_DESC_HDR_SIZE) {
3441 dev_dbg(hba->dev, "String Desc is of zero length\n");
3450 /* remove header and divide by 2 to move from UTF16 to UTF8 */
3451 ascii_len = (uc_str->len - QUERY_DESC_HDR_SIZE) / 2 + 1;
3452 str = kzalloc(ascii_len, GFP_KERNEL);
3459 * the descriptor contains string in UTF16 format
3460 * we need to convert to utf-8 so it can be displayed
3462 ret = utf16s_to_utf8s(uc_str->uc,
3463 uc_str->len - QUERY_DESC_HDR_SIZE,
3464 UTF16_BIG_ENDIAN, str, ascii_len);
3466 /* replace non-printable or non-ASCII characters with spaces */
3467 for (i = 0; i < ret; i++)
3468 str[i] = ufshcd_remove_non_printable(str[i]);
3473 str = kmemdup(uc_str, uc_str->len, GFP_KERNEL);
3487 * ufshcd_read_unit_desc_param - read the specified unit descriptor parameter
3488 * @hba: Pointer to adapter instance
3490 * @param_offset: offset of the parameter to read
3491 * @param_read_buf: pointer to buffer where parameter would be read
3492 * @param_size: sizeof(param_read_buf)
3494 * Return 0 in case of success, non-zero otherwise
3496 static inline int ufshcd_read_unit_desc_param(struct ufs_hba *hba,
3498 enum unit_desc_param param_offset,
3503 * Unit descriptors are only available for general purpose LUs (LUN id
3504 * from 0 to 7) and RPMB Well known LU.
3506 if (!ufs_is_valid_unit_desc_lun(&hba->dev_info, lun, param_offset))
3509 return ufshcd_read_desc_param(hba, QUERY_DESC_IDN_UNIT, lun,
3510 param_offset, param_read_buf, param_size);
3513 static int ufshcd_get_ref_clk_gating_wait(struct ufs_hba *hba)
3516 u32 gating_wait = UFSHCD_REF_CLK_GATING_WAIT_US;
3518 if (hba->dev_info.wspecversion >= 0x300) {
3519 err = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
3520 QUERY_ATTR_IDN_REF_CLK_GATING_WAIT_TIME, 0, 0,
3523 dev_err(hba->dev, "Failed reading bRefClkGatingWait. err = %d, use default %uus\n",
3526 if (gating_wait == 0) {
3527 gating_wait = UFSHCD_REF_CLK_GATING_WAIT_US;
3528 dev_err(hba->dev, "Undefined ref clk gating wait time, use default %uus\n",
3532 hba->dev_info.clk_gating_wait_us = gating_wait;
3539 * ufshcd_memory_alloc - allocate memory for host memory space data structures
3540 * @hba: per adapter instance
3542 * 1. Allocate DMA memory for Command Descriptor array
3543 * Each command descriptor consist of Command UPIU, Response UPIU and PRDT
3544 * 2. Allocate DMA memory for UTP Transfer Request Descriptor List (UTRDL).
3545 * 3. Allocate DMA memory for UTP Task Management Request Descriptor List
3547 * 4. Allocate memory for local reference block(lrb).
3549 * Returns 0 for success, non-zero in case of failure
3551 static int ufshcd_memory_alloc(struct ufs_hba *hba)
3553 size_t utmrdl_size, utrdl_size, ucdl_size;
3555 /* Allocate memory for UTP command descriptors */
3556 ucdl_size = (sizeof(struct utp_transfer_cmd_desc) * hba->nutrs);
3557 hba->ucdl_base_addr = dmam_alloc_coherent(hba->dev,
3559 &hba->ucdl_dma_addr,
3563 * UFSHCI requires UTP command descriptor to be 128 byte aligned.
3564 * make sure hba->ucdl_dma_addr is aligned to PAGE_SIZE
3565 * if hba->ucdl_dma_addr is aligned to PAGE_SIZE, then it will
3566 * be aligned to 128 bytes as well
3568 if (!hba->ucdl_base_addr ||
3569 WARN_ON(hba->ucdl_dma_addr & (PAGE_SIZE - 1))) {
3571 "Command Descriptor Memory allocation failed\n");
3576 * Allocate memory for UTP Transfer descriptors
3577 * UFSHCI requires 1024 byte alignment of UTRD
3579 utrdl_size = (sizeof(struct utp_transfer_req_desc) * hba->nutrs);
3580 hba->utrdl_base_addr = dmam_alloc_coherent(hba->dev,
3582 &hba->utrdl_dma_addr,
3584 if (!hba->utrdl_base_addr ||
3585 WARN_ON(hba->utrdl_dma_addr & (PAGE_SIZE - 1))) {
3587 "Transfer Descriptor Memory allocation failed\n");
3592 * Allocate memory for UTP Task Management descriptors
3593 * UFSHCI requires 1024 byte alignment of UTMRD
3595 utmrdl_size = sizeof(struct utp_task_req_desc) * hba->nutmrs;
3596 hba->utmrdl_base_addr = dmam_alloc_coherent(hba->dev,
3598 &hba->utmrdl_dma_addr,
3600 if (!hba->utmrdl_base_addr ||
3601 WARN_ON(hba->utmrdl_dma_addr & (PAGE_SIZE - 1))) {
3603 "Task Management Descriptor Memory allocation failed\n");
3607 /* Allocate memory for local reference block */
3608 hba->lrb = devm_kcalloc(hba->dev,
3609 hba->nutrs, sizeof(struct ufshcd_lrb),
3612 dev_err(hba->dev, "LRB Memory allocation failed\n");
3621 * ufshcd_host_memory_configure - configure local reference block with
3623 * @hba: per adapter instance
3625 * Configure Host memory space
3626 * 1. Update Corresponding UTRD.UCDBA and UTRD.UCDBAU with UCD DMA
3628 * 2. Update each UTRD with Response UPIU offset, Response UPIU length
3630 * 3. Save the corresponding addresses of UTRD, UCD.CMD, UCD.RSP and UCD.PRDT
3631 * into local reference block.
3633 static void ufshcd_host_memory_configure(struct ufs_hba *hba)
3635 struct utp_transfer_req_desc *utrdlp;
3636 dma_addr_t cmd_desc_dma_addr;
3637 dma_addr_t cmd_desc_element_addr;
3638 u16 response_offset;
3643 utrdlp = hba->utrdl_base_addr;
3646 offsetof(struct utp_transfer_cmd_desc, response_upiu);
3648 offsetof(struct utp_transfer_cmd_desc, prd_table);
3650 cmd_desc_size = sizeof(struct utp_transfer_cmd_desc);
3651 cmd_desc_dma_addr = hba->ucdl_dma_addr;
3653 for (i = 0; i < hba->nutrs; i++) {
3654 /* Configure UTRD with command descriptor base address */
3655 cmd_desc_element_addr =
3656 (cmd_desc_dma_addr + (cmd_desc_size * i));
3657 utrdlp[i].command_desc_base_addr_lo =
3658 cpu_to_le32(lower_32_bits(cmd_desc_element_addr));
3659 utrdlp[i].command_desc_base_addr_hi =
3660 cpu_to_le32(upper_32_bits(cmd_desc_element_addr));
3662 /* Response upiu and prdt offset should be in double words */
3663 if (hba->quirks & UFSHCD_QUIRK_PRDT_BYTE_GRAN) {
3664 utrdlp[i].response_upiu_offset =
3665 cpu_to_le16(response_offset);
3666 utrdlp[i].prd_table_offset =
3667 cpu_to_le16(prdt_offset);
3668 utrdlp[i].response_upiu_length =
3669 cpu_to_le16(ALIGNED_UPIU_SIZE);
3671 utrdlp[i].response_upiu_offset =
3672 cpu_to_le16(response_offset >> 2);
3673 utrdlp[i].prd_table_offset =
3674 cpu_to_le16(prdt_offset >> 2);
3675 utrdlp[i].response_upiu_length =
3676 cpu_to_le16(ALIGNED_UPIU_SIZE >> 2);
3679 ufshcd_init_lrb(hba, &hba->lrb[i], i);
3684 * ufshcd_dme_link_startup - Notify Unipro to perform link startup
3685 * @hba: per adapter instance
3687 * UIC_CMD_DME_LINK_STARTUP command must be issued to Unipro layer,
3688 * in order to initialize the Unipro link startup procedure.
3689 * Once the Unipro links are up, the device connected to the controller
3692 * Returns 0 on success, non-zero value on failure
3694 static int ufshcd_dme_link_startup(struct ufs_hba *hba)
3696 struct uic_command uic_cmd = {0};
3699 uic_cmd.command = UIC_CMD_DME_LINK_STARTUP;
3701 ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
3704 "dme-link-startup: error code %d\n", ret);
3708 * ufshcd_dme_reset - UIC command for DME_RESET
3709 * @hba: per adapter instance
3711 * DME_RESET command is issued in order to reset UniPro stack.
3712 * This function now deals with cold reset.
3714 * Returns 0 on success, non-zero value on failure
3716 static int ufshcd_dme_reset(struct ufs_hba *hba)
3718 struct uic_command uic_cmd = {0};
3721 uic_cmd.command = UIC_CMD_DME_RESET;
3723 ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
3726 "dme-reset: error code %d\n", ret);
3731 int ufshcd_dme_configure_adapt(struct ufs_hba *hba,
3737 if (agreed_gear != UFS_HS_G4)
3738 adapt_val = PA_NO_ADAPT;
3740 ret = ufshcd_dme_set(hba,
3741 UIC_ARG_MIB(PA_TXHSADAPTTYPE),
3745 EXPORT_SYMBOL_GPL(ufshcd_dme_configure_adapt);
3748 * ufshcd_dme_enable - UIC command for DME_ENABLE
3749 * @hba: per adapter instance
3751 * DME_ENABLE command is issued in order to enable UniPro stack.
3753 * Returns 0 on success, non-zero value on failure
3755 static int ufshcd_dme_enable(struct ufs_hba *hba)
3757 struct uic_command uic_cmd = {0};
3760 uic_cmd.command = UIC_CMD_DME_ENABLE;
3762 ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
3765 "dme-enable: error code %d\n", ret);
3770 static inline void ufshcd_add_delay_before_dme_cmd(struct ufs_hba *hba)
3772 #define MIN_DELAY_BEFORE_DME_CMDS_US 1000
3773 unsigned long min_sleep_time_us;
3775 if (!(hba->quirks & UFSHCD_QUIRK_DELAY_BEFORE_DME_CMDS))
3779 * last_dme_cmd_tstamp will be 0 only for 1st call to
3782 if (unlikely(!ktime_to_us(hba->last_dme_cmd_tstamp))) {
3783 min_sleep_time_us = MIN_DELAY_BEFORE_DME_CMDS_US;
3785 unsigned long delta =
3786 (unsigned long) ktime_to_us(
3787 ktime_sub(ktime_get(),
3788 hba->last_dme_cmd_tstamp));
3790 if (delta < MIN_DELAY_BEFORE_DME_CMDS_US)
3792 MIN_DELAY_BEFORE_DME_CMDS_US - delta;
3794 return; /* no more delay required */
3797 /* allow sleep for extra 50us if needed */
3798 usleep_range(min_sleep_time_us, min_sleep_time_us + 50);
3802 * ufshcd_dme_set_attr - UIC command for DME_SET, DME_PEER_SET
3803 * @hba: per adapter instance
3804 * @attr_sel: uic command argument1
3805 * @attr_set: attribute set type as uic command argument2
3806 * @mib_val: setting value as uic command argument3
3807 * @peer: indicate whether peer or local
3809 * Returns 0 on success, non-zero value on failure
3811 int ufshcd_dme_set_attr(struct ufs_hba *hba, u32 attr_sel,
3812 u8 attr_set, u32 mib_val, u8 peer)
3814 struct uic_command uic_cmd = {0};
3815 static const char *const action[] = {
3819 const char *set = action[!!peer];
3821 int retries = UFS_UIC_COMMAND_RETRIES;
3823 uic_cmd.command = peer ?
3824 UIC_CMD_DME_PEER_SET : UIC_CMD_DME_SET;
3825 uic_cmd.argument1 = attr_sel;
3826 uic_cmd.argument2 = UIC_ARG_ATTR_TYPE(attr_set);
3827 uic_cmd.argument3 = mib_val;
3830 /* for peer attributes we retry upon failure */
3831 ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
3833 dev_dbg(hba->dev, "%s: attr-id 0x%x val 0x%x error code %d\n",
3834 set, UIC_GET_ATTR_ID(attr_sel), mib_val, ret);
3835 } while (ret && peer && --retries);
3838 dev_err(hba->dev, "%s: attr-id 0x%x val 0x%x failed %d retries\n",
3839 set, UIC_GET_ATTR_ID(attr_sel), mib_val,
3840 UFS_UIC_COMMAND_RETRIES - retries);
3844 EXPORT_SYMBOL_GPL(ufshcd_dme_set_attr);
3847 * ufshcd_dme_get_attr - UIC command for DME_GET, DME_PEER_GET
3848 * @hba: per adapter instance
3849 * @attr_sel: uic command argument1
3850 * @mib_val: the value of the attribute as returned by the UIC command
3851 * @peer: indicate whether peer or local
3853 * Returns 0 on success, non-zero value on failure
3855 int ufshcd_dme_get_attr(struct ufs_hba *hba, u32 attr_sel,
3856 u32 *mib_val, u8 peer)
3858 struct uic_command uic_cmd = {0};
3859 static const char *const action[] = {
3863 const char *get = action[!!peer];
3865 int retries = UFS_UIC_COMMAND_RETRIES;
3866 struct ufs_pa_layer_attr orig_pwr_info;
3867 struct ufs_pa_layer_attr temp_pwr_info;
3868 bool pwr_mode_change = false;
3870 if (peer && (hba->quirks & UFSHCD_QUIRK_DME_PEER_ACCESS_AUTO_MODE)) {
3871 orig_pwr_info = hba->pwr_info;
3872 temp_pwr_info = orig_pwr_info;
3874 if (orig_pwr_info.pwr_tx == FAST_MODE ||
3875 orig_pwr_info.pwr_rx == FAST_MODE) {
3876 temp_pwr_info.pwr_tx = FASTAUTO_MODE;
3877 temp_pwr_info.pwr_rx = FASTAUTO_MODE;
3878 pwr_mode_change = true;
3879 } else if (orig_pwr_info.pwr_tx == SLOW_MODE ||
3880 orig_pwr_info.pwr_rx == SLOW_MODE) {
3881 temp_pwr_info.pwr_tx = SLOWAUTO_MODE;
3882 temp_pwr_info.pwr_rx = SLOWAUTO_MODE;
3883 pwr_mode_change = true;
3885 if (pwr_mode_change) {
3886 ret = ufshcd_change_power_mode(hba, &temp_pwr_info);
3892 uic_cmd.command = peer ?
3893 UIC_CMD_DME_PEER_GET : UIC_CMD_DME_GET;
3894 uic_cmd.argument1 = attr_sel;
3897 /* for peer attributes we retry upon failure */
3898 ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
3900 dev_dbg(hba->dev, "%s: attr-id 0x%x error code %d\n",
3901 get, UIC_GET_ATTR_ID(attr_sel), ret);
3902 } while (ret && peer && --retries);
3905 dev_err(hba->dev, "%s: attr-id 0x%x failed %d retries\n",
3906 get, UIC_GET_ATTR_ID(attr_sel),
3907 UFS_UIC_COMMAND_RETRIES - retries);
3909 if (mib_val && !ret)
3910 *mib_val = uic_cmd.argument3;
3912 if (peer && (hba->quirks & UFSHCD_QUIRK_DME_PEER_ACCESS_AUTO_MODE)
3914 ufshcd_change_power_mode(hba, &orig_pwr_info);
3918 EXPORT_SYMBOL_GPL(ufshcd_dme_get_attr);
3920 static inline bool ufshcd_is_saved_err_fatal(struct ufs_hba *hba)
3922 lockdep_assert_held(hba->host->host_lock);
3924 return (hba->saved_uic_err & UFSHCD_UIC_DL_PA_INIT_ERROR) ||
3925 (hba->saved_err & (INT_FATAL_ERRORS | UFSHCD_UIC_HIBERN8_MASK));
3928 static void ufshcd_schedule_eh(struct ufs_hba *hba)
3930 bool schedule_eh = false;
3931 unsigned long flags;
3933 spin_lock_irqsave(hba->host->host_lock, flags);
3934 /* handle fatal errors only when link is not in error state */
3935 if (hba->ufshcd_state != UFSHCD_STATE_ERROR) {
3936 if (hba->force_reset || ufshcd_is_link_broken(hba) ||
3937 ufshcd_is_saved_err_fatal(hba))
3938 hba->ufshcd_state = UFSHCD_STATE_EH_SCHEDULED_FATAL;
3940 hba->ufshcd_state = UFSHCD_STATE_EH_SCHEDULED_NON_FATAL;
3943 spin_unlock_irqrestore(hba->host->host_lock, flags);
3946 scsi_schedule_eh(hba->host);
3950 * ufshcd_uic_pwr_ctrl - executes UIC commands (which affects the link power
3951 * state) and waits for it to take effect.
3953 * @hba: per adapter instance
3954 * @cmd: UIC command to execute
3956 * DME operations like DME_SET(PA_PWRMODE), DME_HIBERNATE_ENTER &
3957 * DME_HIBERNATE_EXIT commands take some time to take its effect on both host
3958 * and device UniPro link and hence it's final completion would be indicated by
3959 * dedicated status bits in Interrupt Status register (UPMS, UHES, UHXS) in
3960 * addition to normal UIC command completion Status (UCCS). This function only
3961 * returns after the relevant status bits indicate the completion.
3963 * Returns 0 on success, non-zero value on failure
3965 static int ufshcd_uic_pwr_ctrl(struct ufs_hba *hba, struct uic_command *cmd)
3967 DECLARE_COMPLETION_ONSTACK(uic_async_done);
3968 unsigned long flags;
3969 bool schedule_eh = false;
3972 bool reenable_intr = false;
3974 mutex_lock(&hba->uic_cmd_mutex);
3975 ufshcd_add_delay_before_dme_cmd(hba);
3977 spin_lock_irqsave(hba->host->host_lock, flags);
3978 if (ufshcd_is_link_broken(hba)) {
3982 hba->uic_async_done = &uic_async_done;
3983 if (ufshcd_readl(hba, REG_INTERRUPT_ENABLE) & UIC_COMMAND_COMPL) {
3984 ufshcd_disable_intr(hba, UIC_COMMAND_COMPL);
3986 * Make sure UIC command completion interrupt is disabled before
3987 * issuing UIC command.
3990 reenable_intr = true;
3992 ret = __ufshcd_send_uic_cmd(hba, cmd, false);
3993 spin_unlock_irqrestore(hba->host->host_lock, flags);
3996 "pwr ctrl cmd 0x%x with mode 0x%x uic error %d\n",
3997 cmd->command, cmd->argument3, ret);
4001 if (!wait_for_completion_timeout(hba->uic_async_done,
4002 msecs_to_jiffies(UIC_CMD_TIMEOUT))) {
4004 "pwr ctrl cmd 0x%x with mode 0x%x completion timeout\n",
4005 cmd->command, cmd->argument3);
4007 if (!cmd->cmd_active) {
4008 dev_err(hba->dev, "%s: Power Mode Change operation has been completed, go check UPMCRS\n",
4018 status = ufshcd_get_upmcrs(hba);
4019 if (status != PWR_LOCAL) {
4021 "pwr ctrl cmd 0x%x failed, host upmcrs:0x%x\n",
4022 cmd->command, status);
4023 ret = (status != PWR_OK) ? status : -1;
4027 ufshcd_print_host_state(hba);
4028 ufshcd_print_pwr_info(hba);
4029 ufshcd_print_evt_hist(hba);
4032 spin_lock_irqsave(hba->host->host_lock, flags);
4033 hba->active_uic_cmd = NULL;
4034 hba->uic_async_done = NULL;
4036 ufshcd_enable_intr(hba, UIC_COMMAND_COMPL);
4038 ufshcd_set_link_broken(hba);
4043 spin_unlock_irqrestore(hba->host->host_lock, flags);
4046 ufshcd_schedule_eh(hba);
4047 mutex_unlock(&hba->uic_cmd_mutex);
4053 * ufshcd_uic_change_pwr_mode - Perform the UIC power mode chage
4054 * using DME_SET primitives.
4055 * @hba: per adapter instance
4056 * @mode: powr mode value
4058 * Returns 0 on success, non-zero value on failure
4060 static int ufshcd_uic_change_pwr_mode(struct ufs_hba *hba, u8 mode)
4062 struct uic_command uic_cmd = {0};
4065 if (hba->quirks & UFSHCD_QUIRK_BROKEN_PA_RXHSUNTERMCAP) {
4066 ret = ufshcd_dme_set(hba,
4067 UIC_ARG_MIB_SEL(PA_RXHSUNTERMCAP, 0), 1);
4069 dev_err(hba->dev, "%s: failed to enable PA_RXHSUNTERMCAP ret %d\n",
4075 uic_cmd.command = UIC_CMD_DME_SET;
4076 uic_cmd.argument1 = UIC_ARG_MIB(PA_PWRMODE);
4077 uic_cmd.argument3 = mode;
4078 ufshcd_hold(hba, false);
4079 ret = ufshcd_uic_pwr_ctrl(hba, &uic_cmd);
4080 ufshcd_release(hba);
4086 int ufshcd_link_recovery(struct ufs_hba *hba)
4089 unsigned long flags;
4091 spin_lock_irqsave(hba->host->host_lock, flags);
4092 hba->ufshcd_state = UFSHCD_STATE_RESET;
4093 ufshcd_set_eh_in_progress(hba);
4094 spin_unlock_irqrestore(hba->host->host_lock, flags);
4096 /* Reset the attached device */
4097 ufshcd_device_reset(hba);
4099 ret = ufshcd_host_reset_and_restore(hba);
4101 spin_lock_irqsave(hba->host->host_lock, flags);
4103 hba->ufshcd_state = UFSHCD_STATE_ERROR;
4104 ufshcd_clear_eh_in_progress(hba);
4105 spin_unlock_irqrestore(hba->host->host_lock, flags);
4108 dev_err(hba->dev, "%s: link recovery failed, err %d",
4111 ufshcd_clear_ua_wluns(hba);
4115 EXPORT_SYMBOL_GPL(ufshcd_link_recovery);
4117 static int ufshcd_uic_hibern8_enter(struct ufs_hba *hba)
4120 struct uic_command uic_cmd = {0};
4121 ktime_t start = ktime_get();
4123 ufshcd_vops_hibern8_notify(hba, UIC_CMD_DME_HIBER_ENTER, PRE_CHANGE);
4125 uic_cmd.command = UIC_CMD_DME_HIBER_ENTER;
4126 ret = ufshcd_uic_pwr_ctrl(hba, &uic_cmd);
4127 trace_ufshcd_profile_hibern8(dev_name(hba->dev), "enter",
4128 ktime_to_us(ktime_sub(ktime_get(), start)), ret);
4131 dev_err(hba->dev, "%s: hibern8 enter failed. ret = %d\n",
4134 ufshcd_vops_hibern8_notify(hba, UIC_CMD_DME_HIBER_ENTER,
4140 int ufshcd_uic_hibern8_exit(struct ufs_hba *hba)
4142 struct uic_command uic_cmd = {0};
4144 ktime_t start = ktime_get();
4146 ufshcd_vops_hibern8_notify(hba, UIC_CMD_DME_HIBER_EXIT, PRE_CHANGE);
4148 uic_cmd.command = UIC_CMD_DME_HIBER_EXIT;
4149 ret = ufshcd_uic_pwr_ctrl(hba, &uic_cmd);
4150 trace_ufshcd_profile_hibern8(dev_name(hba->dev), "exit",
4151 ktime_to_us(ktime_sub(ktime_get(), start)), ret);
4154 dev_err(hba->dev, "%s: hibern8 exit failed. ret = %d\n",
4157 ufshcd_vops_hibern8_notify(hba, UIC_CMD_DME_HIBER_EXIT,
4159 hba->ufs_stats.last_hibern8_exit_tstamp = ktime_get();
4160 hba->ufs_stats.hibern8_exit_cnt++;
4165 EXPORT_SYMBOL_GPL(ufshcd_uic_hibern8_exit);
4167 void ufshcd_auto_hibern8_update(struct ufs_hba *hba, u32 ahit)
4169 unsigned long flags;
4170 bool update = false;
4172 if (!ufshcd_is_auto_hibern8_supported(hba))
4175 spin_lock_irqsave(hba->host->host_lock, flags);
4176 if (hba->ahit != ahit) {
4180 spin_unlock_irqrestore(hba->host->host_lock, flags);
4183 !pm_runtime_suspended(&hba->sdev_ufs_device->sdev_gendev)) {
4184 ufshcd_rpm_get_sync(hba);
4185 ufshcd_hold(hba, false);
4186 ufshcd_auto_hibern8_enable(hba);
4187 ufshcd_release(hba);
4188 ufshcd_rpm_put_sync(hba);
4191 EXPORT_SYMBOL_GPL(ufshcd_auto_hibern8_update);
4193 void ufshcd_auto_hibern8_enable(struct ufs_hba *hba)
4195 unsigned long flags;
4197 if (!ufshcd_is_auto_hibern8_supported(hba))
4200 spin_lock_irqsave(hba->host->host_lock, flags);
4201 ufshcd_writel(hba, hba->ahit, REG_AUTO_HIBERNATE_IDLE_TIMER);
4202 spin_unlock_irqrestore(hba->host->host_lock, flags);
4206 * ufshcd_init_pwr_info - setting the POR (power on reset)
4207 * values in hba power info
4208 * @hba: per-adapter instance
4210 static void ufshcd_init_pwr_info(struct ufs_hba *hba)
4212 hba->pwr_info.gear_rx = UFS_PWM_G1;
4213 hba->pwr_info.gear_tx = UFS_PWM_G1;
4214 hba->pwr_info.lane_rx = 1;
4215 hba->pwr_info.lane_tx = 1;
4216 hba->pwr_info.pwr_rx = SLOWAUTO_MODE;
4217 hba->pwr_info.pwr_tx = SLOWAUTO_MODE;
4218 hba->pwr_info.hs_rate = 0;
4222 * ufshcd_get_max_pwr_mode - reads the max power mode negotiated with device
4223 * @hba: per-adapter instance
4225 static int ufshcd_get_max_pwr_mode(struct ufs_hba *hba)
4227 struct ufs_pa_layer_attr *pwr_info = &hba->max_pwr_info.info;
4229 if (hba->max_pwr_info.is_valid)
4232 pwr_info->pwr_tx = FAST_MODE;
4233 pwr_info->pwr_rx = FAST_MODE;
4234 pwr_info->hs_rate = PA_HS_MODE_B;
4236 /* Get the connected lane count */
4237 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_CONNECTEDRXDATALANES),
4238 &pwr_info->lane_rx);
4239 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_CONNECTEDTXDATALANES),
4240 &pwr_info->lane_tx);
4242 if (!pwr_info->lane_rx || !pwr_info->lane_tx) {
4243 dev_err(hba->dev, "%s: invalid connected lanes value. rx=%d, tx=%d\n",
4251 * First, get the maximum gears of HS speed.
4252 * If a zero value, it means there is no HSGEAR capability.
4253 * Then, get the maximum gears of PWM speed.
4255 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_MAXRXHSGEAR), &pwr_info->gear_rx);
4256 if (!pwr_info->gear_rx) {
4257 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_MAXRXPWMGEAR),
4258 &pwr_info->gear_rx);
4259 if (!pwr_info->gear_rx) {
4260 dev_err(hba->dev, "%s: invalid max pwm rx gear read = %d\n",
4261 __func__, pwr_info->gear_rx);
4264 pwr_info->pwr_rx = SLOW_MODE;
4267 ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_MAXRXHSGEAR),
4268 &pwr_info->gear_tx);
4269 if (!pwr_info->gear_tx) {
4270 ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_MAXRXPWMGEAR),
4271 &pwr_info->gear_tx);
4272 if (!pwr_info->gear_tx) {
4273 dev_err(hba->dev, "%s: invalid max pwm tx gear read = %d\n",
4274 __func__, pwr_info->gear_tx);
4277 pwr_info->pwr_tx = SLOW_MODE;
4280 hba->max_pwr_info.is_valid = true;
4284 static int ufshcd_change_power_mode(struct ufs_hba *hba,
4285 struct ufs_pa_layer_attr *pwr_mode)
4289 /* if already configured to the requested pwr_mode */
4290 if (!hba->force_pmc &&
4291 pwr_mode->gear_rx == hba->pwr_info.gear_rx &&
4292 pwr_mode->gear_tx == hba->pwr_info.gear_tx &&
4293 pwr_mode->lane_rx == hba->pwr_info.lane_rx &&
4294 pwr_mode->lane_tx == hba->pwr_info.lane_tx &&
4295 pwr_mode->pwr_rx == hba->pwr_info.pwr_rx &&
4296 pwr_mode->pwr_tx == hba->pwr_info.pwr_tx &&
4297 pwr_mode->hs_rate == hba->pwr_info.hs_rate) {
4298 dev_dbg(hba->dev, "%s: power already configured\n", __func__);
4303 * Configure attributes for power mode change with below.
4304 * - PA_RXGEAR, PA_ACTIVERXDATALANES, PA_RXTERMINATION,
4305 * - PA_TXGEAR, PA_ACTIVETXDATALANES, PA_TXTERMINATION,
4308 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_RXGEAR), pwr_mode->gear_rx);
4309 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_ACTIVERXDATALANES),
4311 if (pwr_mode->pwr_rx == FASTAUTO_MODE ||
4312 pwr_mode->pwr_rx == FAST_MODE)
4313 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_RXTERMINATION), TRUE);
4315 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_RXTERMINATION), FALSE);
4317 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TXGEAR), pwr_mode->gear_tx);
4318 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_ACTIVETXDATALANES),
4320 if (pwr_mode->pwr_tx == FASTAUTO_MODE ||
4321 pwr_mode->pwr_tx == FAST_MODE)
4322 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TXTERMINATION), TRUE);
4324 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TXTERMINATION), FALSE);
4326 if (pwr_mode->pwr_rx == FASTAUTO_MODE ||
4327 pwr_mode->pwr_tx == FASTAUTO_MODE ||
4328 pwr_mode->pwr_rx == FAST_MODE ||
4329 pwr_mode->pwr_tx == FAST_MODE)
4330 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_HSSERIES),
4333 if (!(hba->quirks & UFSHCD_QUIRK_SKIP_DEF_UNIPRO_TIMEOUT_SETTING)) {
4334 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_PWRMODEUSERDATA0),
4335 DL_FC0ProtectionTimeOutVal_Default);
4336 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_PWRMODEUSERDATA1),
4337 DL_TC0ReplayTimeOutVal_Default);
4338 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_PWRMODEUSERDATA2),
4339 DL_AFC0ReqTimeOutVal_Default);
4340 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_PWRMODEUSERDATA3),
4341 DL_FC1ProtectionTimeOutVal_Default);
4342 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_PWRMODEUSERDATA4),
4343 DL_TC1ReplayTimeOutVal_Default);
4344 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_PWRMODEUSERDATA5),
4345 DL_AFC1ReqTimeOutVal_Default);
4347 ufshcd_dme_set(hba, UIC_ARG_MIB(DME_LocalFC0ProtectionTimeOutVal),
4348 DL_FC0ProtectionTimeOutVal_Default);
4349 ufshcd_dme_set(hba, UIC_ARG_MIB(DME_LocalTC0ReplayTimeOutVal),
4350 DL_TC0ReplayTimeOutVal_Default);
4351 ufshcd_dme_set(hba, UIC_ARG_MIB(DME_LocalAFC0ReqTimeOutVal),
4352 DL_AFC0ReqTimeOutVal_Default);
4355 ret = ufshcd_uic_change_pwr_mode(hba, pwr_mode->pwr_rx << 4
4356 | pwr_mode->pwr_tx);
4360 "%s: power mode change failed %d\n", __func__, ret);
4362 ufshcd_vops_pwr_change_notify(hba, POST_CHANGE, NULL,
4365 memcpy(&hba->pwr_info, pwr_mode,
4366 sizeof(struct ufs_pa_layer_attr));
4373 * ufshcd_config_pwr_mode - configure a new power mode
4374 * @hba: per-adapter instance
4375 * @desired_pwr_mode: desired power configuration
4377 int ufshcd_config_pwr_mode(struct ufs_hba *hba,
4378 struct ufs_pa_layer_attr *desired_pwr_mode)
4380 struct ufs_pa_layer_attr final_params = { 0 };
4383 ret = ufshcd_vops_pwr_change_notify(hba, PRE_CHANGE,
4384 desired_pwr_mode, &final_params);
4387 memcpy(&final_params, desired_pwr_mode, sizeof(final_params));
4389 ret = ufshcd_change_power_mode(hba, &final_params);
4393 EXPORT_SYMBOL_GPL(ufshcd_config_pwr_mode);
4396 * ufshcd_complete_dev_init() - checks device readiness
4397 * @hba: per-adapter instance
4399 * Set fDeviceInit flag and poll until device toggles it.
4401 static int ufshcd_complete_dev_init(struct ufs_hba *hba)
4404 bool flag_res = true;
4407 err = ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_SET_FLAG,
4408 QUERY_FLAG_IDN_FDEVICEINIT, 0, NULL);
4411 "%s setting fDeviceInit flag failed with error %d\n",
4416 /* Poll fDeviceInit flag to be cleared */
4417 timeout = ktime_add_ms(ktime_get(), FDEVICEINIT_COMPL_TIMEOUT);
4419 err = ufshcd_query_flag(hba, UPIU_QUERY_OPCODE_READ_FLAG,
4420 QUERY_FLAG_IDN_FDEVICEINIT, 0, &flag_res);
4423 usleep_range(5000, 10000);
4424 } while (ktime_before(ktime_get(), timeout));
4428 "%s reading fDeviceInit flag failed with error %d\n",
4430 } else if (flag_res) {
4432 "%s fDeviceInit was not cleared by the device\n",
4441 * ufshcd_make_hba_operational - Make UFS controller operational
4442 * @hba: per adapter instance
4444 * To bring UFS host controller to operational state,
4445 * 1. Enable required interrupts
4446 * 2. Configure interrupt aggregation
4447 * 3. Program UTRL and UTMRL base address
4448 * 4. Configure run-stop-registers
4450 * Returns 0 on success, non-zero value on failure
4452 int ufshcd_make_hba_operational(struct ufs_hba *hba)
4457 /* Enable required interrupts */
4458 ufshcd_enable_intr(hba, UFSHCD_ENABLE_INTRS);
4460 /* Configure interrupt aggregation */
4461 if (ufshcd_is_intr_aggr_allowed(hba))
4462 ufshcd_config_intr_aggr(hba, hba->nutrs - 1, INT_AGGR_DEF_TO);
4464 ufshcd_disable_intr_aggr(hba);
4466 /* Configure UTRL and UTMRL base address registers */
4467 ufshcd_writel(hba, lower_32_bits(hba->utrdl_dma_addr),
4468 REG_UTP_TRANSFER_REQ_LIST_BASE_L);
4469 ufshcd_writel(hba, upper_32_bits(hba->utrdl_dma_addr),
4470 REG_UTP_TRANSFER_REQ_LIST_BASE_H);
4471 ufshcd_writel(hba, lower_32_bits(hba->utmrdl_dma_addr),
4472 REG_UTP_TASK_REQ_LIST_BASE_L);
4473 ufshcd_writel(hba, upper_32_bits(hba->utmrdl_dma_addr),
4474 REG_UTP_TASK_REQ_LIST_BASE_H);
4477 * Make sure base address and interrupt setup are updated before
4478 * enabling the run/stop registers below.
4483 * UCRDY, UTMRLDY and UTRLRDY bits must be 1
4485 reg = ufshcd_readl(hba, REG_CONTROLLER_STATUS);
4486 if (!(ufshcd_get_lists_status(reg))) {
4487 ufshcd_enable_run_stop_reg(hba);
4490 "Host controller not ready to process requests");
4496 EXPORT_SYMBOL_GPL(ufshcd_make_hba_operational);
4499 * ufshcd_hba_stop - Send controller to reset state
4500 * @hba: per adapter instance
4502 void ufshcd_hba_stop(struct ufs_hba *hba)
4504 unsigned long flags;
4508 * Obtain the host lock to prevent that the controller is disabled
4509 * while the UFS interrupt handler is active on another CPU.
4511 spin_lock_irqsave(hba->host->host_lock, flags);
4512 ufshcd_writel(hba, CONTROLLER_DISABLE, REG_CONTROLLER_ENABLE);
4513 spin_unlock_irqrestore(hba->host->host_lock, flags);
4515 err = ufshcd_wait_for_register(hba, REG_CONTROLLER_ENABLE,
4516 CONTROLLER_ENABLE, CONTROLLER_DISABLE,
4519 dev_err(hba->dev, "%s: Controller disable failed\n", __func__);
4521 EXPORT_SYMBOL_GPL(ufshcd_hba_stop);
4524 * ufshcd_hba_execute_hce - initialize the controller
4525 * @hba: per adapter instance
4527 * The controller resets itself and controller firmware initialization
4528 * sequence kicks off. When controller is ready it will set
4529 * the Host Controller Enable bit to 1.
4531 * Returns 0 on success, non-zero value on failure
4533 static int ufshcd_hba_execute_hce(struct ufs_hba *hba)
4535 int retry_outer = 3;
4539 if (!ufshcd_is_hba_active(hba))
4540 /* change controller state to "reset state" */
4541 ufshcd_hba_stop(hba);
4543 /* UniPro link is disabled at this point */
4544 ufshcd_set_link_off(hba);
4546 ufshcd_vops_hce_enable_notify(hba, PRE_CHANGE);
4548 /* start controller initialization sequence */
4549 ufshcd_hba_start(hba);
4552 * To initialize a UFS host controller HCE bit must be set to 1.
4553 * During initialization the HCE bit value changes from 1->0->1.
4554 * When the host controller completes initialization sequence
4555 * it sets the value of HCE bit to 1. The same HCE bit is read back
4556 * to check if the controller has completed initialization sequence.
4557 * So without this delay the value HCE = 1, set in the previous
4558 * instruction might be read back.
4559 * This delay can be changed based on the controller.
4561 ufshcd_delay_us(hba->vps->hba_enable_delay_us, 100);
4563 /* wait for the host controller to complete initialization */
4565 while (ufshcd_is_hba_active(hba)) {
4570 "Controller enable failed\n");
4577 usleep_range(1000, 1100);
4580 /* enable UIC related interrupts */
4581 ufshcd_enable_intr(hba, UFSHCD_UIC_MASK);
4583 ufshcd_vops_hce_enable_notify(hba, POST_CHANGE);
4588 int ufshcd_hba_enable(struct ufs_hba *hba)
4592 if (hba->quirks & UFSHCI_QUIRK_BROKEN_HCE) {
4593 ufshcd_set_link_off(hba);
4594 ufshcd_vops_hce_enable_notify(hba, PRE_CHANGE);
4596 /* enable UIC related interrupts */
4597 ufshcd_enable_intr(hba, UFSHCD_UIC_MASK);
4598 ret = ufshcd_dme_reset(hba);
4600 ret = ufshcd_dme_enable(hba);
4602 ufshcd_vops_hce_enable_notify(hba, POST_CHANGE);
4605 "Host controller enable failed with non-hce\n");
4608 ret = ufshcd_hba_execute_hce(hba);
4613 EXPORT_SYMBOL_GPL(ufshcd_hba_enable);
4615 static int ufshcd_disable_tx_lcc(struct ufs_hba *hba, bool peer)
4617 int tx_lanes = 0, i, err = 0;
4620 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_CONNECTEDTXDATALANES),
4623 ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_CONNECTEDTXDATALANES),
4625 for (i = 0; i < tx_lanes; i++) {
4627 err = ufshcd_dme_set(hba,
4628 UIC_ARG_MIB_SEL(TX_LCC_ENABLE,
4629 UIC_ARG_MPHY_TX_GEN_SEL_INDEX(i)),
4632 err = ufshcd_dme_peer_set(hba,
4633 UIC_ARG_MIB_SEL(TX_LCC_ENABLE,
4634 UIC_ARG_MPHY_TX_GEN_SEL_INDEX(i)),
4637 dev_err(hba->dev, "%s: TX LCC Disable failed, peer = %d, lane = %d, err = %d",
4638 __func__, peer, i, err);
4646 static inline int ufshcd_disable_device_tx_lcc(struct ufs_hba *hba)
4648 return ufshcd_disable_tx_lcc(hba, true);
4651 void ufshcd_update_evt_hist(struct ufs_hba *hba, u32 id, u32 val)
4653 struct ufs_event_hist *e;
4655 if (id >= UFS_EVT_CNT)
4658 e = &hba->ufs_stats.event[id];
4659 e->val[e->pos] = val;
4660 e->tstamp[e->pos] = ktime_get();
4662 e->pos = (e->pos + 1) % UFS_EVENT_HIST_LENGTH;
4664 ufshcd_vops_event_notify(hba, id, &val);
4666 EXPORT_SYMBOL_GPL(ufshcd_update_evt_hist);
4669 * ufshcd_link_startup - Initialize unipro link startup
4670 * @hba: per adapter instance
4672 * Returns 0 for success, non-zero in case of failure
4674 static int ufshcd_link_startup(struct ufs_hba *hba)
4677 int retries = DME_LINKSTARTUP_RETRIES;
4678 bool link_startup_again = false;
4681 * If UFS device isn't active then we will have to issue link startup
4682 * 2 times to make sure the device state move to active.
4684 if (!ufshcd_is_ufs_dev_active(hba))
4685 link_startup_again = true;
4689 ufshcd_vops_link_startup_notify(hba, PRE_CHANGE);
4691 ret = ufshcd_dme_link_startup(hba);
4693 /* check if device is detected by inter-connect layer */
4694 if (!ret && !ufshcd_is_device_present(hba)) {
4695 ufshcd_update_evt_hist(hba,
4696 UFS_EVT_LINK_STARTUP_FAIL,
4698 dev_err(hba->dev, "%s: Device not present\n", __func__);
4704 * DME link lost indication is only received when link is up,
4705 * but we can't be sure if the link is up until link startup
4706 * succeeds. So reset the local Uni-Pro and try again.
4708 if (ret && ufshcd_hba_enable(hba)) {
4709 ufshcd_update_evt_hist(hba,
4710 UFS_EVT_LINK_STARTUP_FAIL,
4714 } while (ret && retries--);
4717 /* failed to get the link up... retire */
4718 ufshcd_update_evt_hist(hba,
4719 UFS_EVT_LINK_STARTUP_FAIL,
4724 if (link_startup_again) {
4725 link_startup_again = false;
4726 retries = DME_LINKSTARTUP_RETRIES;
4730 /* Mark that link is up in PWM-G1, 1-lane, SLOW-AUTO mode */
4731 ufshcd_init_pwr_info(hba);
4732 ufshcd_print_pwr_info(hba);
4734 if (hba->quirks & UFSHCD_QUIRK_BROKEN_LCC) {
4735 ret = ufshcd_disable_device_tx_lcc(hba);
4740 /* Include any host controller configuration via UIC commands */
4741 ret = ufshcd_vops_link_startup_notify(hba, POST_CHANGE);
4745 /* Clear UECPA once due to LINERESET has happened during LINK_STARTUP */
4746 ufshcd_readl(hba, REG_UIC_ERROR_CODE_PHY_ADAPTER_LAYER);
4747 ret = ufshcd_make_hba_operational(hba);
4750 dev_err(hba->dev, "link startup failed %d\n", ret);
4751 ufshcd_print_host_state(hba);
4752 ufshcd_print_pwr_info(hba);
4753 ufshcd_print_evt_hist(hba);
4759 * ufshcd_verify_dev_init() - Verify device initialization
4760 * @hba: per-adapter instance
4762 * Send NOP OUT UPIU and wait for NOP IN response to check whether the
4763 * device Transport Protocol (UTP) layer is ready after a reset.
4764 * If the UTP layer at the device side is not initialized, it may
4765 * not respond with NOP IN UPIU within timeout of %NOP_OUT_TIMEOUT
4766 * and we retry sending NOP OUT for %NOP_OUT_RETRIES iterations.
4768 static int ufshcd_verify_dev_init(struct ufs_hba *hba)
4773 ufshcd_hold(hba, false);
4774 mutex_lock(&hba->dev_cmd.lock);
4775 for (retries = NOP_OUT_RETRIES; retries > 0; retries--) {
4776 err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_NOP,
4779 if (!err || err == -ETIMEDOUT)
4782 dev_dbg(hba->dev, "%s: error %d retrying\n", __func__, err);
4784 mutex_unlock(&hba->dev_cmd.lock);
4785 ufshcd_release(hba);
4788 dev_err(hba->dev, "%s: NOP OUT failed %d\n", __func__, err);
4793 * ufshcd_set_queue_depth - set lun queue depth
4794 * @sdev: pointer to SCSI device
4796 * Read bLUQueueDepth value and activate scsi tagged command
4797 * queueing. For WLUN, queue depth is set to 1. For best-effort
4798 * cases (bLUQueueDepth = 0) the queue depth is set to a maximum
4799 * value that host can queue.
4801 static void ufshcd_set_queue_depth(struct scsi_device *sdev)
4805 struct ufs_hba *hba;
4807 hba = shost_priv(sdev->host);
4809 lun_qdepth = hba->nutrs;
4810 ret = ufshcd_read_unit_desc_param(hba,
4811 ufshcd_scsi_to_upiu_lun(sdev->lun),
4812 UNIT_DESC_PARAM_LU_Q_DEPTH,
4814 sizeof(lun_qdepth));
4816 /* Some WLUN doesn't support unit descriptor */
4817 if (ret == -EOPNOTSUPP)
4819 else if (!lun_qdepth)
4820 /* eventually, we can figure out the real queue depth */
4821 lun_qdepth = hba->nutrs;
4823 lun_qdepth = min_t(int, lun_qdepth, hba->nutrs);
4825 dev_dbg(hba->dev, "%s: activate tcq with queue depth %d\n",
4826 __func__, lun_qdepth);
4827 scsi_change_queue_depth(sdev, lun_qdepth);
4831 * ufshcd_get_lu_wp - returns the "b_lu_write_protect" from UNIT DESCRIPTOR
4832 * @hba: per-adapter instance
4833 * @lun: UFS device lun id
4834 * @b_lu_write_protect: pointer to buffer to hold the LU's write protect info
4836 * Returns 0 in case of success and b_lu_write_protect status would be returned
4837 * @b_lu_write_protect parameter.
4838 * Returns -ENOTSUPP if reading b_lu_write_protect is not supported.
4839 * Returns -EINVAL in case of invalid parameters passed to this function.
4841 static int ufshcd_get_lu_wp(struct ufs_hba *hba,
4843 u8 *b_lu_write_protect)
4847 if (!b_lu_write_protect)
4850 * According to UFS device spec, RPMB LU can't be write
4851 * protected so skip reading bLUWriteProtect parameter for
4852 * it. For other W-LUs, UNIT DESCRIPTOR is not available.
4854 else if (lun >= hba->dev_info.max_lu_supported)
4857 ret = ufshcd_read_unit_desc_param(hba,
4859 UNIT_DESC_PARAM_LU_WR_PROTECT,
4861 sizeof(*b_lu_write_protect));
4866 * ufshcd_get_lu_power_on_wp_status - get LU's power on write protect
4868 * @hba: per-adapter instance
4869 * @sdev: pointer to SCSI device
4872 static inline void ufshcd_get_lu_power_on_wp_status(struct ufs_hba *hba,
4873 struct scsi_device *sdev)
4875 if (hba->dev_info.f_power_on_wp_en &&
4876 !hba->dev_info.is_lu_power_on_wp) {
4877 u8 b_lu_write_protect;
4879 if (!ufshcd_get_lu_wp(hba, ufshcd_scsi_to_upiu_lun(sdev->lun),
4880 &b_lu_write_protect) &&
4881 (b_lu_write_protect == UFS_LU_POWER_ON_WP))
4882 hba->dev_info.is_lu_power_on_wp = true;
4887 * ufshcd_setup_links - associate link b/w device wlun and other luns
4888 * @sdev: pointer to SCSI device
4889 * @hba: pointer to ufs hba
4891 static void ufshcd_setup_links(struct ufs_hba *hba, struct scsi_device *sdev)
4893 struct device_link *link;
4896 * Device wlun is the supplier & rest of the luns are consumers.
4897 * This ensures that device wlun suspends after all other luns.
4899 if (hba->sdev_ufs_device) {
4900 link = device_link_add(&sdev->sdev_gendev,
4901 &hba->sdev_ufs_device->sdev_gendev,
4902 DL_FLAG_PM_RUNTIME | DL_FLAG_RPM_ACTIVE);
4904 dev_err(&sdev->sdev_gendev, "Failed establishing link - %s\n",
4905 dev_name(&hba->sdev_ufs_device->sdev_gendev));
4909 /* Ignore REPORT_LUN wlun probing */
4910 if (hba->luns_avail == 1) {
4911 ufshcd_rpm_put(hba);
4916 * Device wlun is probed. The assumption is that WLUNs are
4917 * scanned before other LUNs.
4924 * ufshcd_slave_alloc - handle initial SCSI device configurations
4925 * @sdev: pointer to SCSI device
4929 static int ufshcd_slave_alloc(struct scsi_device *sdev)
4931 struct ufs_hba *hba;
4933 hba = shost_priv(sdev->host);
4935 /* Mode sense(6) is not supported by UFS, so use Mode sense(10) */
4936 sdev->use_10_for_ms = 1;
4938 /* DBD field should be set to 1 in mode sense(10) */
4939 sdev->set_dbd_for_ms = 1;
4941 /* allow SCSI layer to restart the device in case of errors */
4942 sdev->allow_restart = 1;
4944 /* REPORT SUPPORTED OPERATION CODES is not supported */
4945 sdev->no_report_opcodes = 1;
4947 /* WRITE_SAME command is not supported */
4948 sdev->no_write_same = 1;
4950 ufshcd_set_queue_depth(sdev);
4952 ufshcd_get_lu_power_on_wp_status(hba, sdev);
4954 ufshcd_setup_links(hba, sdev);
4960 * ufshcd_change_queue_depth - change queue depth
4961 * @sdev: pointer to SCSI device
4962 * @depth: required depth to set
4964 * Change queue depth and make sure the max. limits are not crossed.
4966 static int ufshcd_change_queue_depth(struct scsi_device *sdev, int depth)
4968 struct ufs_hba *hba = shost_priv(sdev->host);
4970 if (depth > hba->nutrs)
4972 return scsi_change_queue_depth(sdev, depth);
4975 static void ufshcd_hpb_destroy(struct ufs_hba *hba, struct scsi_device *sdev)
4977 /* skip well-known LU */
4978 if ((sdev->lun >= UFS_UPIU_MAX_UNIT_NUM_ID) ||
4979 !(hba->dev_info.hpb_enabled) || !ufshpb_is_allowed(hba))
4982 ufshpb_destroy_lu(hba, sdev);
4985 static void ufshcd_hpb_configure(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_init_hpb_lu(hba, sdev);
4996 * ufshcd_slave_configure - adjust SCSI device configurations
4997 * @sdev: pointer to SCSI device
4999 static int ufshcd_slave_configure(struct scsi_device *sdev)
5001 struct ufs_hba *hba = shost_priv(sdev->host);
5002 struct request_queue *q = sdev->request_queue;
5004 ufshcd_hpb_configure(hba, sdev);
5006 blk_queue_update_dma_pad(q, PRDT_DATA_BYTE_COUNT_PAD - 1);
5007 if (hba->quirks & UFSHCD_QUIRK_ALIGN_SG_WITH_PAGE_SIZE)
5008 blk_queue_update_dma_alignment(q, PAGE_SIZE - 1);
5010 * Block runtime-pm until all consumers are added.
5011 * Refer ufshcd_setup_links().
5013 if (is_device_wlun(sdev))
5014 pm_runtime_get_noresume(&sdev->sdev_gendev);
5015 else if (ufshcd_is_rpm_autosuspend_allowed(hba))
5016 sdev->rpm_autosuspend = 1;
5018 ufshcd_crypto_setup_rq_keyslot_manager(hba, q);
5024 * ufshcd_slave_destroy - remove SCSI device configurations
5025 * @sdev: pointer to SCSI device
5027 static void ufshcd_slave_destroy(struct scsi_device *sdev)
5029 struct ufs_hba *hba;
5031 hba = shost_priv(sdev->host);
5033 ufshcd_hpb_destroy(hba, sdev);
5035 /* Drop the reference as it won't be needed anymore */
5036 if (ufshcd_scsi_to_upiu_lun(sdev->lun) == UFS_UPIU_UFS_DEVICE_WLUN) {
5037 unsigned long flags;
5039 spin_lock_irqsave(hba->host->host_lock, flags);
5040 hba->sdev_ufs_device = NULL;
5041 spin_unlock_irqrestore(hba->host->host_lock, flags);
5046 * ufshcd_scsi_cmd_status - Update SCSI command result based on SCSI status
5047 * @lrbp: pointer to local reference block of completed command
5048 * @scsi_status: SCSI command status
5050 * Returns value base on SCSI command status
5053 ufshcd_scsi_cmd_status(struct ufshcd_lrb *lrbp, int scsi_status)
5057 switch (scsi_status) {
5058 case SAM_STAT_CHECK_CONDITION:
5059 ufshcd_copy_sense_data(lrbp);
5062 result |= DID_OK << 16 | scsi_status;
5064 case SAM_STAT_TASK_SET_FULL:
5066 case SAM_STAT_TASK_ABORTED:
5067 ufshcd_copy_sense_data(lrbp);
5068 result |= scsi_status;
5071 result |= DID_ERROR << 16;
5073 } /* end of switch */
5079 * ufshcd_transfer_rsp_status - Get overall status of the response
5080 * @hba: per adapter instance
5081 * @lrbp: pointer to local reference block of completed command
5083 * Returns result of the command to notify SCSI midlayer
5086 ufshcd_transfer_rsp_status(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
5092 /* overall command status of utrd */
5093 ocs = ufshcd_get_tr_ocs(lrbp);
5095 if (hba->quirks & UFSHCD_QUIRK_BROKEN_OCS_FATAL_ERROR) {
5096 if (be32_to_cpu(lrbp->ucd_rsp_ptr->header.dword_1) &
5097 MASK_RSP_UPIU_RESULT)
5103 result = ufshcd_get_req_rsp(lrbp->ucd_rsp_ptr);
5104 hba->ufs_stats.last_hibern8_exit_tstamp = ktime_set(0, 0);
5106 case UPIU_TRANSACTION_RESPONSE:
5108 * get the response UPIU result to extract
5109 * the SCSI command status
5111 result = ufshcd_get_rsp_upiu_result(lrbp->ucd_rsp_ptr);
5114 * get the result based on SCSI status response
5115 * to notify the SCSI midlayer of the command status
5117 scsi_status = result & MASK_SCSI_STATUS;
5118 result = ufshcd_scsi_cmd_status(lrbp, scsi_status);
5121 * Currently we are only supporting BKOPs exception
5122 * events hence we can ignore BKOPs exception event
5123 * during power management callbacks. BKOPs exception
5124 * event is not expected to be raised in runtime suspend
5125 * callback as it allows the urgent bkops.
5126 * During system suspend, we are anyway forcefully
5127 * disabling the bkops and if urgent bkops is needed
5128 * it will be enabled on system resume. Long term
5129 * solution could be to abort the system suspend if
5130 * UFS device needs urgent BKOPs.
5132 if (!hba->pm_op_in_progress &&
5133 !ufshcd_eh_in_progress(hba) &&
5134 ufshcd_is_exception_event(lrbp->ucd_rsp_ptr))
5135 /* Flushed in suspend */
5136 schedule_work(&hba->eeh_work);
5138 if (scsi_status == SAM_STAT_GOOD)
5139 ufshpb_rsp_upiu(hba, lrbp);
5141 case UPIU_TRANSACTION_REJECT_UPIU:
5142 /* TODO: handle Reject UPIU Response */
5143 result = DID_ERROR << 16;
5145 "Reject UPIU not fully implemented\n");
5149 "Unexpected request response code = %x\n",
5151 result = DID_ERROR << 16;
5156 result |= DID_ABORT << 16;
5158 case OCS_INVALID_COMMAND_STATUS:
5159 result |= DID_REQUEUE << 16;
5161 case OCS_INVALID_CMD_TABLE_ATTR:
5162 case OCS_INVALID_PRDT_ATTR:
5163 case OCS_MISMATCH_DATA_BUF_SIZE:
5164 case OCS_MISMATCH_RESP_UPIU_SIZE:
5165 case OCS_PEER_COMM_FAILURE:
5166 case OCS_FATAL_ERROR:
5167 case OCS_DEVICE_FATAL_ERROR:
5168 case OCS_INVALID_CRYPTO_CONFIG:
5169 case OCS_GENERAL_CRYPTO_ERROR:
5171 result |= DID_ERROR << 16;
5173 "OCS error from controller = %x for tag %d\n",
5174 ocs, lrbp->task_tag);
5175 ufshcd_print_evt_hist(hba);
5176 ufshcd_print_host_state(hba);
5178 } /* end of switch */
5180 if ((host_byte(result) != DID_OK) &&
5181 (host_byte(result) != DID_REQUEUE) && !hba->silence_err_logs)
5182 ufshcd_print_trs(hba, 1 << lrbp->task_tag, true);
5186 static bool ufshcd_is_auto_hibern8_error(struct ufs_hba *hba,
5189 if (!ufshcd_is_auto_hibern8_supported(hba) ||
5190 !ufshcd_is_auto_hibern8_enabled(hba))
5193 if (!(intr_mask & UFSHCD_UIC_HIBERN8_MASK))
5196 if (hba->active_uic_cmd &&
5197 (hba->active_uic_cmd->command == UIC_CMD_DME_HIBER_ENTER ||
5198 hba->active_uic_cmd->command == UIC_CMD_DME_HIBER_EXIT))
5205 * ufshcd_uic_cmd_compl - handle completion of uic command
5206 * @hba: per adapter instance
5207 * @intr_status: interrupt status generated by the controller
5210 * IRQ_HANDLED - If interrupt is valid
5211 * IRQ_NONE - If invalid interrupt
5213 static irqreturn_t ufshcd_uic_cmd_compl(struct ufs_hba *hba, u32 intr_status)
5215 irqreturn_t retval = IRQ_NONE;
5217 spin_lock(hba->host->host_lock);
5218 if (ufshcd_is_auto_hibern8_error(hba, intr_status))
5219 hba->errors |= (UFSHCD_UIC_HIBERN8_MASK & intr_status);
5221 if ((intr_status & UIC_COMMAND_COMPL) && hba->active_uic_cmd) {
5222 hba->active_uic_cmd->argument2 |=
5223 ufshcd_get_uic_cmd_result(hba);
5224 hba->active_uic_cmd->argument3 =
5225 ufshcd_get_dme_attr_val(hba);
5226 if (!hba->uic_async_done)
5227 hba->active_uic_cmd->cmd_active = 0;
5228 complete(&hba->active_uic_cmd->done);
5229 retval = IRQ_HANDLED;
5232 if ((intr_status & UFSHCD_UIC_PWR_MASK) && hba->uic_async_done) {
5233 hba->active_uic_cmd->cmd_active = 0;
5234 complete(hba->uic_async_done);
5235 retval = IRQ_HANDLED;
5238 if (retval == IRQ_HANDLED)
5239 ufshcd_add_uic_command_trace(hba, hba->active_uic_cmd,
5241 spin_unlock(hba->host->host_lock);
5246 * __ufshcd_transfer_req_compl - handle SCSI and query command completion
5247 * @hba: per adapter instance
5248 * @completed_reqs: bitmask that indicates which requests to complete
5249 * @retry_requests: whether to ask the SCSI core to retry completed requests
5251 static void __ufshcd_transfer_req_compl(struct ufs_hba *hba,
5252 unsigned long completed_reqs,
5253 bool retry_requests)
5255 struct ufshcd_lrb *lrbp;
5256 struct scsi_cmnd *cmd;
5259 bool update_scaling = false;
5261 for_each_set_bit(index, &completed_reqs, hba->nutrs) {
5262 lrbp = &hba->lrb[index];
5263 lrbp->compl_time_stamp = ktime_get();
5266 if (unlikely(ufshcd_should_inform_monitor(hba, lrbp)))
5267 ufshcd_update_monitor(hba, lrbp);
5268 ufshcd_add_command_trace(hba, index, UFS_CMD_COMP);
5269 result = retry_requests ? DID_BUS_BUSY << 16 :
5270 ufshcd_transfer_rsp_status(hba, lrbp);
5271 scsi_dma_unmap(cmd);
5272 cmd->result = result;
5273 /* Mark completed command as NULL in LRB */
5275 /* Do not touch lrbp after scsi done */
5276 cmd->scsi_done(cmd);
5277 ufshcd_release(hba);
5278 update_scaling = true;
5279 } else if (lrbp->command_type == UTP_CMD_TYPE_DEV_MANAGE ||
5280 lrbp->command_type == UTP_CMD_TYPE_UFS_STORAGE) {
5281 if (hba->dev_cmd.complete) {
5282 ufshcd_add_command_trace(hba, index,
5284 complete(hba->dev_cmd.complete);
5285 update_scaling = true;
5289 ufshcd_clk_scaling_update_busy(hba);
5294 * ufshcd_transfer_req_compl - handle SCSI and query command completion
5295 * @hba: per adapter instance
5296 * @retry_requests: whether or not to ask to retry requests
5299 * IRQ_HANDLED - If interrupt is valid
5300 * IRQ_NONE - If invalid interrupt
5302 static irqreturn_t ufshcd_transfer_req_compl(struct ufs_hba *hba,
5303 bool retry_requests)
5305 unsigned long completed_reqs, flags;
5308 /* Resetting interrupt aggregation counters first and reading the
5309 * DOOR_BELL afterward allows us to handle all the completed requests.
5310 * In order to prevent other interrupts starvation the DB is read once
5311 * after reset. The down side of this solution is the possibility of
5312 * false interrupt if device completes another request after resetting
5313 * aggregation and before reading the DB.
5315 if (ufshcd_is_intr_aggr_allowed(hba) &&
5316 !(hba->quirks & UFSHCI_QUIRK_SKIP_RESET_INTR_AGGR))
5317 ufshcd_reset_intr_aggr(hba);
5319 if (ufs_fail_completion())
5322 spin_lock_irqsave(&hba->outstanding_lock, flags);
5323 tr_doorbell = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
5324 completed_reqs = ~tr_doorbell & hba->outstanding_reqs;
5325 WARN_ONCE(completed_reqs & ~hba->outstanding_reqs,
5326 "completed: %#lx; outstanding: %#lx\n", completed_reqs,
5327 hba->outstanding_reqs);
5328 hba->outstanding_reqs &= ~completed_reqs;
5329 spin_unlock_irqrestore(&hba->outstanding_lock, flags);
5331 if (completed_reqs) {
5332 __ufshcd_transfer_req_compl(hba, completed_reqs,
5340 int __ufshcd_write_ee_control(struct ufs_hba *hba, u32 ee_ctrl_mask)
5342 return ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_WRITE_ATTR,
5343 QUERY_ATTR_IDN_EE_CONTROL, 0, 0,
5347 int ufshcd_write_ee_control(struct ufs_hba *hba)
5351 mutex_lock(&hba->ee_ctrl_mutex);
5352 err = __ufshcd_write_ee_control(hba, hba->ee_ctrl_mask);
5353 mutex_unlock(&hba->ee_ctrl_mutex);
5355 dev_err(hba->dev, "%s: failed to write ee control %d\n",
5360 int ufshcd_update_ee_control(struct ufs_hba *hba, u16 *mask, u16 *other_mask,
5363 u16 new_mask, ee_ctrl_mask;
5366 mutex_lock(&hba->ee_ctrl_mutex);
5367 new_mask = (*mask & ~clr) | set;
5368 ee_ctrl_mask = new_mask | *other_mask;
5369 if (ee_ctrl_mask != hba->ee_ctrl_mask)
5370 err = __ufshcd_write_ee_control(hba, ee_ctrl_mask);
5371 /* Still need to update 'mask' even if 'ee_ctrl_mask' was unchanged */
5373 hba->ee_ctrl_mask = ee_ctrl_mask;
5376 mutex_unlock(&hba->ee_ctrl_mutex);
5381 * ufshcd_disable_ee - disable exception event
5382 * @hba: per-adapter instance
5383 * @mask: exception event to disable
5385 * Disables exception event in the device so that the EVENT_ALERT
5388 * Returns zero on success, non-zero error value on failure.
5390 static inline int ufshcd_disable_ee(struct ufs_hba *hba, u16 mask)
5392 return ufshcd_update_ee_drv_mask(hba, 0, mask);
5396 * ufshcd_enable_ee - enable exception event
5397 * @hba: per-adapter instance
5398 * @mask: exception event to enable
5400 * Enable corresponding exception event in the device to allow
5401 * device to alert host in critical scenarios.
5403 * Returns zero on success, non-zero error value on failure.
5405 static inline int ufshcd_enable_ee(struct ufs_hba *hba, u16 mask)
5407 return ufshcd_update_ee_drv_mask(hba, mask, 0);
5411 * ufshcd_enable_auto_bkops - Allow device managed BKOPS
5412 * @hba: per-adapter instance
5414 * Allow device to manage background operations on its own. Enabling
5415 * this might lead to inconsistent latencies during normal data transfers
5416 * as the device is allowed to manage its own way of handling background
5419 * Returns zero on success, non-zero on failure.
5421 static int ufshcd_enable_auto_bkops(struct ufs_hba *hba)
5425 if (hba->auto_bkops_enabled)
5428 err = ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_SET_FLAG,
5429 QUERY_FLAG_IDN_BKOPS_EN, 0, NULL);
5431 dev_err(hba->dev, "%s: failed to enable bkops %d\n",
5436 hba->auto_bkops_enabled = true;
5437 trace_ufshcd_auto_bkops_state(dev_name(hba->dev), "Enabled");
5439 /* No need of URGENT_BKOPS exception from the device */
5440 err = ufshcd_disable_ee(hba, MASK_EE_URGENT_BKOPS);
5442 dev_err(hba->dev, "%s: failed to disable exception event %d\n",
5449 * ufshcd_disable_auto_bkops - block device in doing background operations
5450 * @hba: per-adapter instance
5452 * Disabling background operations improves command response latency but
5453 * has drawback of device moving into critical state where the device is
5454 * not-operable. Make sure to call ufshcd_enable_auto_bkops() whenever the
5455 * host is idle so that BKOPS are managed effectively without any negative
5458 * Returns zero on success, non-zero on failure.
5460 static int ufshcd_disable_auto_bkops(struct ufs_hba *hba)
5464 if (!hba->auto_bkops_enabled)
5468 * If host assisted BKOPs is to be enabled, make sure
5469 * urgent bkops exception is allowed.
5471 err = ufshcd_enable_ee(hba, MASK_EE_URGENT_BKOPS);
5473 dev_err(hba->dev, "%s: failed to enable exception event %d\n",
5478 err = ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_CLEAR_FLAG,
5479 QUERY_FLAG_IDN_BKOPS_EN, 0, NULL);
5481 dev_err(hba->dev, "%s: failed to disable bkops %d\n",
5483 ufshcd_disable_ee(hba, MASK_EE_URGENT_BKOPS);
5487 hba->auto_bkops_enabled = false;
5488 trace_ufshcd_auto_bkops_state(dev_name(hba->dev), "Disabled");
5489 hba->is_urgent_bkops_lvl_checked = false;
5495 * ufshcd_force_reset_auto_bkops - force reset auto bkops state
5496 * @hba: per adapter instance
5498 * After a device reset the device may toggle the BKOPS_EN flag
5499 * to default value. The s/w tracking variables should be updated
5500 * as well. This function would change the auto-bkops state based on
5501 * UFSHCD_CAP_KEEP_AUTO_BKOPS_ENABLED_EXCEPT_SUSPEND.
5503 static void ufshcd_force_reset_auto_bkops(struct ufs_hba *hba)
5505 if (ufshcd_keep_autobkops_enabled_except_suspend(hba)) {
5506 hba->auto_bkops_enabled = false;
5507 hba->ee_ctrl_mask |= MASK_EE_URGENT_BKOPS;
5508 ufshcd_enable_auto_bkops(hba);
5510 hba->auto_bkops_enabled = true;
5511 hba->ee_ctrl_mask &= ~MASK_EE_URGENT_BKOPS;
5512 ufshcd_disable_auto_bkops(hba);
5514 hba->urgent_bkops_lvl = BKOPS_STATUS_PERF_IMPACT;
5515 hba->is_urgent_bkops_lvl_checked = false;
5518 static inline int ufshcd_get_bkops_status(struct ufs_hba *hba, u32 *status)
5520 return ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
5521 QUERY_ATTR_IDN_BKOPS_STATUS, 0, 0, status);
5525 * ufshcd_bkops_ctrl - control the auto bkops based on current bkops status
5526 * @hba: per-adapter instance
5527 * @status: bkops_status value
5529 * Read the bkops_status from the UFS device and Enable fBackgroundOpsEn
5530 * flag in the device to permit background operations if the device
5531 * bkops_status is greater than or equal to "status" argument passed to
5532 * this function, disable otherwise.
5534 * Returns 0 for success, non-zero in case of failure.
5536 * NOTE: Caller of this function can check the "hba->auto_bkops_enabled" flag
5537 * to know whether auto bkops is enabled or disabled after this function
5538 * returns control to it.
5540 static int ufshcd_bkops_ctrl(struct ufs_hba *hba,
5541 enum bkops_status status)
5544 u32 curr_status = 0;
5546 err = ufshcd_get_bkops_status(hba, &curr_status);
5548 dev_err(hba->dev, "%s: failed to get BKOPS status %d\n",
5551 } else if (curr_status > BKOPS_STATUS_MAX) {
5552 dev_err(hba->dev, "%s: invalid BKOPS status %d\n",
5553 __func__, curr_status);
5558 if (curr_status >= status)
5559 err = ufshcd_enable_auto_bkops(hba);
5561 err = ufshcd_disable_auto_bkops(hba);
5567 * ufshcd_urgent_bkops - handle urgent bkops exception event
5568 * @hba: per-adapter instance
5570 * Enable fBackgroundOpsEn flag in the device to permit background
5573 * If BKOPs is enabled, this function returns 0, 1 if the bkops in not enabled
5574 * and negative error value for any other failure.
5576 static int ufshcd_urgent_bkops(struct ufs_hba *hba)
5578 return ufshcd_bkops_ctrl(hba, hba->urgent_bkops_lvl);
5581 static inline int ufshcd_get_ee_status(struct ufs_hba *hba, u32 *status)
5583 return ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
5584 QUERY_ATTR_IDN_EE_STATUS, 0, 0, status);
5587 static void ufshcd_bkops_exception_event_handler(struct ufs_hba *hba)
5590 u32 curr_status = 0;
5592 if (hba->is_urgent_bkops_lvl_checked)
5593 goto enable_auto_bkops;
5595 err = ufshcd_get_bkops_status(hba, &curr_status);
5597 dev_err(hba->dev, "%s: failed to get BKOPS status %d\n",
5603 * We are seeing that some devices are raising the urgent bkops
5604 * exception events even when BKOPS status doesn't indicate performace
5605 * impacted or critical. Handle these device by determining their urgent
5606 * bkops status at runtime.
5608 if (curr_status < BKOPS_STATUS_PERF_IMPACT) {
5609 dev_err(hba->dev, "%s: device raised urgent BKOPS exception for bkops status %d\n",
5610 __func__, curr_status);
5611 /* update the current status as the urgent bkops level */
5612 hba->urgent_bkops_lvl = curr_status;
5613 hba->is_urgent_bkops_lvl_checked = true;
5617 err = ufshcd_enable_auto_bkops(hba);
5620 dev_err(hba->dev, "%s: failed to handle urgent bkops %d\n",
5624 static int __ufshcd_wb_toggle(struct ufs_hba *hba, bool set, enum flag_idn idn)
5627 enum query_opcode opcode = set ? UPIU_QUERY_OPCODE_SET_FLAG :
5628 UPIU_QUERY_OPCODE_CLEAR_FLAG;
5630 index = ufshcd_wb_get_query_index(hba);
5631 return ufshcd_query_flag_retry(hba, opcode, idn, index, NULL);
5634 int ufshcd_wb_toggle(struct ufs_hba *hba, bool enable)
5638 if (!ufshcd_is_wb_allowed(hba))
5641 if (!(enable ^ hba->dev_info.wb_enabled))
5644 ret = __ufshcd_wb_toggle(hba, enable, QUERY_FLAG_IDN_WB_EN);
5646 dev_err(hba->dev, "%s Write Booster %s failed %d\n",
5647 __func__, enable ? "enable" : "disable", ret);
5651 hba->dev_info.wb_enabled = enable;
5652 dev_info(hba->dev, "%s Write Booster %s\n",
5653 __func__, enable ? "enabled" : "disabled");
5658 static void ufshcd_wb_toggle_flush_during_h8(struct ufs_hba *hba, bool set)
5662 ret = __ufshcd_wb_toggle(hba, set,
5663 QUERY_FLAG_IDN_WB_BUFF_FLUSH_DURING_HIBERN8);
5665 dev_err(hba->dev, "%s: WB-Buf Flush during H8 %s failed: %d\n",
5666 __func__, set ? "enable" : "disable", ret);
5669 dev_dbg(hba->dev, "%s WB-Buf Flush during H8 %s\n",
5670 __func__, set ? "enabled" : "disabled");
5673 static inline void ufshcd_wb_toggle_flush(struct ufs_hba *hba, bool enable)
5677 if (!ufshcd_is_wb_allowed(hba) ||
5678 hba->dev_info.wb_buf_flush_enabled == enable)
5681 ret = __ufshcd_wb_toggle(hba, enable, QUERY_FLAG_IDN_WB_BUFF_FLUSH_EN);
5683 dev_err(hba->dev, "%s WB-Buf Flush %s failed %d\n", __func__,
5684 enable ? "enable" : "disable", ret);
5688 hba->dev_info.wb_buf_flush_enabled = enable;
5690 dev_dbg(hba->dev, "%s WB-Buf Flush %s\n",
5691 __func__, enable ? "enabled" : "disabled");
5694 static bool ufshcd_wb_presrv_usrspc_keep_vcc_on(struct ufs_hba *hba,
5701 index = ufshcd_wb_get_query_index(hba);
5702 ret = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
5703 QUERY_ATTR_IDN_CURR_WB_BUFF_SIZE,
5704 index, 0, &cur_buf);
5706 dev_err(hba->dev, "%s dCurWriteBoosterBufferSize read failed %d\n",
5712 dev_info(hba->dev, "dCurWBBuf: %d WB disabled until free-space is available\n",
5716 /* Let it continue to flush when available buffer exceeds threshold */
5717 if (avail_buf < hba->vps->wb_flush_threshold)
5723 static bool ufshcd_wb_need_flush(struct ufs_hba *hba)
5729 if (!ufshcd_is_wb_allowed(hba))
5732 * The ufs device needs the vcc to be ON to flush.
5733 * With user-space reduction enabled, it's enough to enable flush
5734 * by checking only the available buffer. The threshold
5735 * defined here is > 90% full.
5736 * With user-space preserved enabled, the current-buffer
5737 * should be checked too because the wb buffer size can reduce
5738 * when disk tends to be full. This info is provided by current
5739 * buffer (dCurrentWriteBoosterBufferSize). There's no point in
5740 * keeping vcc on when current buffer is empty.
5742 index = ufshcd_wb_get_query_index(hba);
5743 ret = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
5744 QUERY_ATTR_IDN_AVAIL_WB_BUFF_SIZE,
5745 index, 0, &avail_buf);
5747 dev_warn(hba->dev, "%s dAvailableWriteBoosterBufferSize read failed %d\n",
5752 if (!hba->dev_info.b_presrv_uspc_en) {
5753 if (avail_buf <= UFS_WB_BUF_REMAIN_PERCENT(10))
5758 return ufshcd_wb_presrv_usrspc_keep_vcc_on(hba, avail_buf);
5761 static void ufshcd_rpm_dev_flush_recheck_work(struct work_struct *work)
5763 struct ufs_hba *hba = container_of(to_delayed_work(work),
5765 rpm_dev_flush_recheck_work);
5767 * To prevent unnecessary VCC power drain after device finishes
5768 * WriteBooster buffer flush or Auto BKOPs, force runtime resume
5769 * after a certain delay to recheck the threshold by next runtime
5772 ufshcd_rpm_get_sync(hba);
5773 ufshcd_rpm_put_sync(hba);
5777 * ufshcd_exception_event_handler - handle exceptions raised by device
5778 * @work: pointer to work data
5780 * Read bExceptionEventStatus attribute from the device and handle the
5781 * exception event accordingly.
5783 static void ufshcd_exception_event_handler(struct work_struct *work)
5785 struct ufs_hba *hba;
5788 hba = container_of(work, struct ufs_hba, eeh_work);
5790 ufshcd_scsi_block_requests(hba);
5791 err = ufshcd_get_ee_status(hba, &status);
5793 dev_err(hba->dev, "%s: failed to get exception status %d\n",
5798 trace_ufshcd_exception_event(dev_name(hba->dev), status);
5800 if (status & hba->ee_drv_mask & MASK_EE_URGENT_BKOPS)
5801 ufshcd_bkops_exception_event_handler(hba);
5803 ufs_debugfs_exception_event(hba, status);
5805 ufshcd_scsi_unblock_requests(hba);
5809 /* Complete requests that have door-bell cleared */
5810 static void ufshcd_complete_requests(struct ufs_hba *hba)
5812 ufshcd_transfer_req_compl(hba, /*retry_requests=*/false);
5813 ufshcd_tmc_handler(hba);
5816 static void ufshcd_retry_aborted_requests(struct ufs_hba *hba)
5818 ufshcd_transfer_req_compl(hba, /*retry_requests=*/true);
5819 ufshcd_tmc_handler(hba);
5823 * ufshcd_quirk_dl_nac_errors - This function checks if error handling is
5824 * to recover from the DL NAC errors or not.
5825 * @hba: per-adapter instance
5827 * Returns true if error handling is required, false otherwise
5829 static bool ufshcd_quirk_dl_nac_errors(struct ufs_hba *hba)
5831 unsigned long flags;
5832 bool err_handling = true;
5834 spin_lock_irqsave(hba->host->host_lock, flags);
5836 * UFS_DEVICE_QUIRK_RECOVERY_FROM_DL_NAC_ERRORS only workaround the
5837 * device fatal error and/or DL NAC & REPLAY timeout errors.
5839 if (hba->saved_err & (CONTROLLER_FATAL_ERROR | SYSTEM_BUS_FATAL_ERROR))
5842 if ((hba->saved_err & DEVICE_FATAL_ERROR) ||
5843 ((hba->saved_err & UIC_ERROR) &&
5844 (hba->saved_uic_err & UFSHCD_UIC_DL_TCx_REPLAY_ERROR)))
5847 if ((hba->saved_err & UIC_ERROR) &&
5848 (hba->saved_uic_err & UFSHCD_UIC_DL_NAC_RECEIVED_ERROR)) {
5851 * wait for 50ms to see if we can get any other errors or not.
5853 spin_unlock_irqrestore(hba->host->host_lock, flags);
5855 spin_lock_irqsave(hba->host->host_lock, flags);
5858 * now check if we have got any other severe errors other than
5861 if ((hba->saved_err & INT_FATAL_ERRORS) ||
5862 ((hba->saved_err & UIC_ERROR) &&
5863 (hba->saved_uic_err & ~UFSHCD_UIC_DL_NAC_RECEIVED_ERROR)))
5867 * As DL NAC is the only error received so far, send out NOP
5868 * command to confirm if link is still active or not.
5869 * - If we don't get any response then do error recovery.
5870 * - If we get response then clear the DL NAC error bit.
5873 spin_unlock_irqrestore(hba->host->host_lock, flags);
5874 err = ufshcd_verify_dev_init(hba);
5875 spin_lock_irqsave(hba->host->host_lock, flags);
5880 /* Link seems to be alive hence ignore the DL NAC errors */
5881 if (hba->saved_uic_err == UFSHCD_UIC_DL_NAC_RECEIVED_ERROR)
5882 hba->saved_err &= ~UIC_ERROR;
5883 /* clear NAC error */
5884 hba->saved_uic_err &= ~UFSHCD_UIC_DL_NAC_RECEIVED_ERROR;
5885 if (!hba->saved_uic_err)
5886 err_handling = false;
5889 spin_unlock_irqrestore(hba->host->host_lock, flags);
5890 return err_handling;
5893 static void ufshcd_clk_scaling_allow(struct ufs_hba *hba, bool allow)
5895 down_write(&hba->clk_scaling_lock);
5896 hba->clk_scaling.is_allowed = allow;
5897 up_write(&hba->clk_scaling_lock);
5900 static void ufshcd_clk_scaling_suspend(struct ufs_hba *hba, bool suspend)
5903 if (hba->clk_scaling.is_enabled)
5904 ufshcd_suspend_clkscaling(hba);
5905 ufshcd_clk_scaling_allow(hba, false);
5907 ufshcd_clk_scaling_allow(hba, true);
5908 if (hba->clk_scaling.is_enabled)
5909 ufshcd_resume_clkscaling(hba);
5913 static void ufshcd_err_handling_prepare(struct ufs_hba *hba)
5915 ufshcd_rpm_get_sync(hba);
5916 if (pm_runtime_status_suspended(&hba->sdev_ufs_device->sdev_gendev) ||
5917 hba->is_sys_suspended) {
5918 enum ufs_pm_op pm_op;
5921 * Don't assume anything of resume, if
5922 * resume fails, irq and clocks can be OFF, and powers
5923 * can be OFF or in LPM.
5925 ufshcd_setup_hba_vreg(hba, true);
5926 ufshcd_enable_irq(hba);
5927 ufshcd_setup_vreg(hba, true);
5928 ufshcd_config_vreg_hpm(hba, hba->vreg_info.vccq);
5929 ufshcd_config_vreg_hpm(hba, hba->vreg_info.vccq2);
5930 ufshcd_hold(hba, false);
5931 if (!ufshcd_is_clkgating_allowed(hba))
5932 ufshcd_setup_clocks(hba, true);
5933 ufshcd_release(hba);
5934 pm_op = hba->is_sys_suspended ? UFS_SYSTEM_PM : UFS_RUNTIME_PM;
5935 ufshcd_vops_resume(hba, pm_op);
5937 ufshcd_hold(hba, false);
5938 if (ufshcd_is_clkscaling_supported(hba) &&
5939 hba->clk_scaling.is_enabled)
5940 ufshcd_suspend_clkscaling(hba);
5941 ufshcd_clk_scaling_allow(hba, false);
5943 ufshcd_scsi_block_requests(hba);
5944 /* Drain ufshcd_queuecommand() */
5945 down_write(&hba->clk_scaling_lock);
5946 up_write(&hba->clk_scaling_lock);
5947 cancel_work_sync(&hba->eeh_work);
5950 static void ufshcd_err_handling_unprepare(struct ufs_hba *hba)
5952 ufshcd_scsi_unblock_requests(hba);
5953 ufshcd_release(hba);
5954 if (ufshcd_is_clkscaling_supported(hba))
5955 ufshcd_clk_scaling_suspend(hba, false);
5956 ufshcd_clear_ua_wluns(hba);
5957 ufshcd_rpm_put(hba);
5960 static inline bool ufshcd_err_handling_should_stop(struct ufs_hba *hba)
5962 return (!hba->is_powered || hba->shutting_down ||
5963 !hba->sdev_ufs_device ||
5964 hba->ufshcd_state == UFSHCD_STATE_ERROR ||
5965 (!(hba->saved_err || hba->saved_uic_err || hba->force_reset ||
5966 ufshcd_is_link_broken(hba))));
5970 static void ufshcd_recover_pm_error(struct ufs_hba *hba)
5972 struct Scsi_Host *shost = hba->host;
5973 struct scsi_device *sdev;
5974 struct request_queue *q;
5977 hba->is_sys_suspended = false;
5979 * Set RPM status of wlun device to RPM_ACTIVE,
5980 * this also clears its runtime error.
5982 ret = pm_runtime_set_active(&hba->sdev_ufs_device->sdev_gendev);
5984 /* hba device might have a runtime error otherwise */
5986 ret = pm_runtime_set_active(hba->dev);
5988 * If wlun device had runtime error, we also need to resume those
5989 * consumer scsi devices in case any of them has failed to be
5990 * resumed due to supplier runtime resume failure. This is to unblock
5991 * blk_queue_enter in case there are bios waiting inside it.
5994 shost_for_each_device(sdev, shost) {
5995 q = sdev->request_queue;
5996 if (q->dev && (q->rpm_status == RPM_SUSPENDED ||
5997 q->rpm_status == RPM_SUSPENDING))
5998 pm_request_resume(q->dev);
6003 static inline void ufshcd_recover_pm_error(struct ufs_hba *hba)
6008 static bool ufshcd_is_pwr_mode_restore_needed(struct ufs_hba *hba)
6010 struct ufs_pa_layer_attr *pwr_info = &hba->pwr_info;
6013 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_PWRMODE), &mode);
6015 if (pwr_info->pwr_rx != ((mode >> PWRMODE_RX_OFFSET) & PWRMODE_MASK))
6018 if (pwr_info->pwr_tx != (mode & PWRMODE_MASK))
6025 * ufshcd_err_handler - handle UFS errors that require s/w attention
6026 * @host: SCSI host pointer
6028 static void ufshcd_err_handler(struct Scsi_Host *host)
6030 struct ufs_hba *hba = shost_priv(host);
6031 unsigned long flags;
6032 bool err_xfer = false;
6033 bool err_tm = false;
6034 int err = 0, pmc_err;
6036 bool needs_reset = false, needs_restore = false;
6038 down(&hba->host_sem);
6039 spin_lock_irqsave(hba->host->host_lock, flags);
6040 hba->host->host_eh_scheduled = 0;
6041 if (ufshcd_err_handling_should_stop(hba)) {
6042 if (hba->ufshcd_state != UFSHCD_STATE_ERROR)
6043 hba->ufshcd_state = UFSHCD_STATE_OPERATIONAL;
6044 spin_unlock_irqrestore(hba->host->host_lock, flags);
6048 ufshcd_set_eh_in_progress(hba);
6049 spin_unlock_irqrestore(hba->host->host_lock, flags);
6050 ufshcd_err_handling_prepare(hba);
6051 /* Complete requests that have door-bell cleared by h/w */
6052 ufshcd_complete_requests(hba);
6053 spin_lock_irqsave(hba->host->host_lock, flags);
6054 if (hba->ufshcd_state != UFSHCD_STATE_ERROR)
6055 hba->ufshcd_state = UFSHCD_STATE_RESET;
6057 * A full reset and restore might have happened after preparation
6058 * is finished, double check whether we should stop.
6060 if (ufshcd_err_handling_should_stop(hba))
6061 goto skip_err_handling;
6063 if (hba->dev_quirks & UFS_DEVICE_QUIRK_RECOVERY_FROM_DL_NAC_ERRORS) {
6066 spin_unlock_irqrestore(hba->host->host_lock, flags);
6067 /* release the lock as ufshcd_quirk_dl_nac_errors() may sleep */
6068 ret = ufshcd_quirk_dl_nac_errors(hba);
6069 spin_lock_irqsave(hba->host->host_lock, flags);
6070 if (!ret && ufshcd_err_handling_should_stop(hba))
6071 goto skip_err_handling;
6074 if ((hba->saved_err & (INT_FATAL_ERRORS | UFSHCD_UIC_HIBERN8_MASK)) ||
6075 (hba->saved_uic_err &&
6076 (hba->saved_uic_err != UFSHCD_UIC_PA_GENERIC_ERROR))) {
6077 bool pr_prdt = !!(hba->saved_err & SYSTEM_BUS_FATAL_ERROR);
6079 spin_unlock_irqrestore(hba->host->host_lock, flags);
6080 ufshcd_print_host_state(hba);
6081 ufshcd_print_pwr_info(hba);
6082 ufshcd_print_evt_hist(hba);
6083 ufshcd_print_tmrs(hba, hba->outstanding_tasks);
6084 ufshcd_print_trs(hba, hba->outstanding_reqs, pr_prdt);
6085 spin_lock_irqsave(hba->host->host_lock, flags);
6089 * if host reset is required then skip clearing the pending
6090 * transfers forcefully because they will get cleared during
6091 * host reset and restore
6093 if (hba->force_reset || ufshcd_is_link_broken(hba) ||
6094 ufshcd_is_saved_err_fatal(hba) ||
6095 ((hba->saved_err & UIC_ERROR) &&
6096 (hba->saved_uic_err & (UFSHCD_UIC_DL_NAC_RECEIVED_ERROR |
6097 UFSHCD_UIC_DL_TCx_REPLAY_ERROR)))) {
6103 * If LINERESET was caught, UFS might have been put to PWM mode,
6104 * check if power mode restore is needed.
6106 if (hba->saved_uic_err & UFSHCD_UIC_PA_GENERIC_ERROR) {
6107 hba->saved_uic_err &= ~UFSHCD_UIC_PA_GENERIC_ERROR;
6108 if (!hba->saved_uic_err)
6109 hba->saved_err &= ~UIC_ERROR;
6110 spin_unlock_irqrestore(hba->host->host_lock, flags);
6111 if (ufshcd_is_pwr_mode_restore_needed(hba))
6112 needs_restore = true;
6113 spin_lock_irqsave(hba->host->host_lock, flags);
6114 if (!hba->saved_err && !needs_restore)
6115 goto skip_err_handling;
6118 hba->silence_err_logs = true;
6119 /* release lock as clear command might sleep */
6120 spin_unlock_irqrestore(hba->host->host_lock, flags);
6121 /* Clear pending transfer requests */
6122 for_each_set_bit(tag, &hba->outstanding_reqs, hba->nutrs) {
6123 if (ufshcd_try_to_abort_task(hba, tag)) {
6125 goto lock_skip_pending_xfer_clear;
6129 /* Clear pending task management requests */
6130 for_each_set_bit(tag, &hba->outstanding_tasks, hba->nutmrs) {
6131 if (ufshcd_clear_tm_cmd(hba, tag)) {
6133 goto lock_skip_pending_xfer_clear;
6137 lock_skip_pending_xfer_clear:
6138 ufshcd_retry_aborted_requests(hba);
6140 spin_lock_irqsave(hba->host->host_lock, flags);
6141 hba->silence_err_logs = false;
6142 if (err_xfer || err_tm) {
6148 * After all reqs and tasks are cleared from doorbell,
6149 * now it is safe to retore power mode.
6151 if (needs_restore) {
6152 spin_unlock_irqrestore(hba->host->host_lock, flags);
6154 * Hold the scaling lock just in case dev cmds
6155 * are sent via bsg and/or sysfs.
6157 down_write(&hba->clk_scaling_lock);
6158 hba->force_pmc = true;
6159 pmc_err = ufshcd_config_pwr_mode(hba, &(hba->pwr_info));
6162 dev_err(hba->dev, "%s: Failed to restore power mode, err = %d\n",
6165 hba->force_pmc = false;
6166 ufshcd_print_pwr_info(hba);
6167 up_write(&hba->clk_scaling_lock);
6168 spin_lock_irqsave(hba->host->host_lock, flags);
6172 /* Fatal errors need reset */
6174 hba->force_reset = false;
6175 spin_unlock_irqrestore(hba->host->host_lock, flags);
6176 err = ufshcd_reset_and_restore(hba);
6178 dev_err(hba->dev, "%s: reset and restore failed with err %d\n",
6181 ufshcd_recover_pm_error(hba);
6182 spin_lock_irqsave(hba->host->host_lock, flags);
6187 if (hba->ufshcd_state == UFSHCD_STATE_RESET)
6188 hba->ufshcd_state = UFSHCD_STATE_OPERATIONAL;
6189 if (hba->saved_err || hba->saved_uic_err)
6190 dev_err_ratelimited(hba->dev, "%s: exit: saved_err 0x%x saved_uic_err 0x%x",
6191 __func__, hba->saved_err, hba->saved_uic_err);
6193 ufshcd_clear_eh_in_progress(hba);
6194 spin_unlock_irqrestore(hba->host->host_lock, flags);
6195 ufshcd_err_handling_unprepare(hba);
6200 * ufshcd_update_uic_error - check and set fatal UIC error flags.
6201 * @hba: per-adapter instance
6204 * IRQ_HANDLED - If interrupt is valid
6205 * IRQ_NONE - If invalid interrupt
6207 static irqreturn_t ufshcd_update_uic_error(struct ufs_hba *hba)
6210 irqreturn_t retval = IRQ_NONE;
6212 /* PHY layer error */
6213 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_PHY_ADAPTER_LAYER);
6214 if ((reg & UIC_PHY_ADAPTER_LAYER_ERROR) &&
6215 (reg & UIC_PHY_ADAPTER_LAYER_ERROR_CODE_MASK)) {
6216 ufshcd_update_evt_hist(hba, UFS_EVT_PA_ERR, reg);
6218 * To know whether this error is fatal or not, DB timeout
6219 * must be checked but this error is handled separately.
6221 if (reg & UIC_PHY_ADAPTER_LAYER_LANE_ERR_MASK)
6222 dev_dbg(hba->dev, "%s: UIC Lane error reported\n",
6225 /* Got a LINERESET indication. */
6226 if (reg & UIC_PHY_ADAPTER_LAYER_GENERIC_ERROR) {
6227 struct uic_command *cmd = NULL;
6229 hba->uic_error |= UFSHCD_UIC_PA_GENERIC_ERROR;
6230 if (hba->uic_async_done && hba->active_uic_cmd)
6231 cmd = hba->active_uic_cmd;
6233 * Ignore the LINERESET during power mode change
6234 * operation via DME_SET command.
6236 if (cmd && (cmd->command == UIC_CMD_DME_SET))
6237 hba->uic_error &= ~UFSHCD_UIC_PA_GENERIC_ERROR;
6239 retval |= IRQ_HANDLED;
6242 /* PA_INIT_ERROR is fatal and needs UIC reset */
6243 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_DATA_LINK_LAYER);
6244 if ((reg & UIC_DATA_LINK_LAYER_ERROR) &&
6245 (reg & UIC_DATA_LINK_LAYER_ERROR_CODE_MASK)) {
6246 ufshcd_update_evt_hist(hba, UFS_EVT_DL_ERR, reg);
6248 if (reg & UIC_DATA_LINK_LAYER_ERROR_PA_INIT)
6249 hba->uic_error |= UFSHCD_UIC_DL_PA_INIT_ERROR;
6250 else if (hba->dev_quirks &
6251 UFS_DEVICE_QUIRK_RECOVERY_FROM_DL_NAC_ERRORS) {
6252 if (reg & UIC_DATA_LINK_LAYER_ERROR_NAC_RECEIVED)
6254 UFSHCD_UIC_DL_NAC_RECEIVED_ERROR;
6255 else if (reg & UIC_DATA_LINK_LAYER_ERROR_TCx_REPLAY_TIMEOUT)
6256 hba->uic_error |= UFSHCD_UIC_DL_TCx_REPLAY_ERROR;
6258 retval |= IRQ_HANDLED;
6261 /* UIC NL/TL/DME errors needs software retry */
6262 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_NETWORK_LAYER);
6263 if ((reg & UIC_NETWORK_LAYER_ERROR) &&
6264 (reg & UIC_NETWORK_LAYER_ERROR_CODE_MASK)) {
6265 ufshcd_update_evt_hist(hba, UFS_EVT_NL_ERR, reg);
6266 hba->uic_error |= UFSHCD_UIC_NL_ERROR;
6267 retval |= IRQ_HANDLED;
6270 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_TRANSPORT_LAYER);
6271 if ((reg & UIC_TRANSPORT_LAYER_ERROR) &&
6272 (reg & UIC_TRANSPORT_LAYER_ERROR_CODE_MASK)) {
6273 ufshcd_update_evt_hist(hba, UFS_EVT_TL_ERR, reg);
6274 hba->uic_error |= UFSHCD_UIC_TL_ERROR;
6275 retval |= IRQ_HANDLED;
6278 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_DME);
6279 if ((reg & UIC_DME_ERROR) &&
6280 (reg & UIC_DME_ERROR_CODE_MASK)) {
6281 ufshcd_update_evt_hist(hba, UFS_EVT_DME_ERR, reg);
6282 hba->uic_error |= UFSHCD_UIC_DME_ERROR;
6283 retval |= IRQ_HANDLED;
6286 dev_dbg(hba->dev, "%s: UIC error flags = 0x%08x\n",
6287 __func__, hba->uic_error);
6292 * ufshcd_check_errors - Check for errors that need s/w attention
6293 * @hba: per-adapter instance
6294 * @intr_status: interrupt status generated by the controller
6297 * IRQ_HANDLED - If interrupt is valid
6298 * IRQ_NONE - If invalid interrupt
6300 static irqreturn_t ufshcd_check_errors(struct ufs_hba *hba, u32 intr_status)
6302 bool queue_eh_work = false;
6303 irqreturn_t retval = IRQ_NONE;
6305 spin_lock(hba->host->host_lock);
6306 hba->errors |= UFSHCD_ERROR_MASK & intr_status;
6308 if (hba->errors & INT_FATAL_ERRORS) {
6309 ufshcd_update_evt_hist(hba, UFS_EVT_FATAL_ERR,
6311 queue_eh_work = true;
6314 if (hba->errors & UIC_ERROR) {
6316 retval = ufshcd_update_uic_error(hba);
6318 queue_eh_work = true;
6321 if (hba->errors & UFSHCD_UIC_HIBERN8_MASK) {
6323 "%s: Auto Hibern8 %s failed - status: 0x%08x, upmcrs: 0x%08x\n",
6324 __func__, (hba->errors & UIC_HIBERNATE_ENTER) ?
6326 hba->errors, ufshcd_get_upmcrs(hba));
6327 ufshcd_update_evt_hist(hba, UFS_EVT_AUTO_HIBERN8_ERR,
6329 ufshcd_set_link_broken(hba);
6330 queue_eh_work = true;
6333 if (queue_eh_work) {
6335 * update the transfer error masks to sticky bits, let's do this
6336 * irrespective of current ufshcd_state.
6338 hba->saved_err |= hba->errors;
6339 hba->saved_uic_err |= hba->uic_error;
6341 /* dump controller state before resetting */
6342 if ((hba->saved_err &
6343 (INT_FATAL_ERRORS | UFSHCD_UIC_HIBERN8_MASK)) ||
6344 (hba->saved_uic_err &&
6345 (hba->saved_uic_err != UFSHCD_UIC_PA_GENERIC_ERROR))) {
6346 dev_err(hba->dev, "%s: saved_err 0x%x saved_uic_err 0x%x\n",
6347 __func__, hba->saved_err,
6348 hba->saved_uic_err);
6349 ufshcd_dump_regs(hba, 0, UFSHCI_REG_SPACE_SIZE,
6351 ufshcd_print_pwr_info(hba);
6353 retval |= IRQ_HANDLED;
6356 * if (!queue_eh_work) -
6357 * Other errors are either non-fatal where host recovers
6358 * itself without s/w intervention or errors that will be
6359 * handled by the SCSI core layer.
6363 spin_unlock(hba->host->host_lock);
6366 ufshcd_schedule_eh(hba);
6372 struct ufs_hba *hba;
6373 unsigned long pending;
6377 static bool ufshcd_compl_tm(struct request *req, void *priv, bool reserved)
6379 struct ctm_info *const ci = priv;
6380 struct completion *c;
6382 WARN_ON_ONCE(reserved);
6383 if (test_bit(req->tag, &ci->pending))
6386 c = req->end_io_data;
6393 * ufshcd_tmc_handler - handle task management function completion
6394 * @hba: per adapter instance
6397 * IRQ_HANDLED - If interrupt is valid
6398 * IRQ_NONE - If invalid interrupt
6400 static irqreturn_t ufshcd_tmc_handler(struct ufs_hba *hba)
6402 unsigned long flags;
6403 struct request_queue *q = hba->tmf_queue;
6404 struct ctm_info ci = {
6408 spin_lock_irqsave(hba->host->host_lock, flags);
6409 ci.pending = ufshcd_readl(hba, REG_UTP_TASK_REQ_DOOR_BELL);
6410 blk_mq_tagset_busy_iter(q->tag_set, ufshcd_compl_tm, &ci);
6411 spin_unlock_irqrestore(hba->host->host_lock, flags);
6413 return ci.ncpl ? IRQ_HANDLED : IRQ_NONE;
6417 * ufshcd_sl_intr - Interrupt service routine
6418 * @hba: per adapter instance
6419 * @intr_status: contains interrupts generated by the controller
6422 * IRQ_HANDLED - If interrupt is valid
6423 * IRQ_NONE - If invalid interrupt
6425 static irqreturn_t ufshcd_sl_intr(struct ufs_hba *hba, u32 intr_status)
6427 irqreturn_t retval = IRQ_NONE;
6429 if (intr_status & UFSHCD_UIC_MASK)
6430 retval |= ufshcd_uic_cmd_compl(hba, intr_status);
6432 if (intr_status & UFSHCD_ERROR_MASK || hba->errors)
6433 retval |= ufshcd_check_errors(hba, intr_status);
6435 if (intr_status & UTP_TASK_REQ_COMPL)
6436 retval |= ufshcd_tmc_handler(hba);
6438 if (intr_status & UTP_TRANSFER_REQ_COMPL)
6439 retval |= ufshcd_transfer_req_compl(hba, /*retry_requests=*/false);
6445 * ufshcd_intr - Main interrupt service routine
6447 * @__hba: pointer to adapter instance
6450 * IRQ_HANDLED - If interrupt is valid
6451 * IRQ_NONE - If invalid interrupt
6453 static irqreturn_t ufshcd_intr(int irq, void *__hba)
6455 u32 intr_status, enabled_intr_status = 0;
6456 irqreturn_t retval = IRQ_NONE;
6457 struct ufs_hba *hba = __hba;
6458 int retries = hba->nutrs;
6460 intr_status = ufshcd_readl(hba, REG_INTERRUPT_STATUS);
6461 hba->ufs_stats.last_intr_status = intr_status;
6462 hba->ufs_stats.last_intr_ts = ktime_get();
6465 * There could be max of hba->nutrs reqs in flight and in worst case
6466 * if the reqs get finished 1 by 1 after the interrupt status is
6467 * read, make sure we handle them by checking the interrupt status
6468 * again in a loop until we process all of the reqs before returning.
6470 while (intr_status && retries--) {
6471 enabled_intr_status =
6472 intr_status & ufshcd_readl(hba, REG_INTERRUPT_ENABLE);
6473 ufshcd_writel(hba, intr_status, REG_INTERRUPT_STATUS);
6474 if (enabled_intr_status)
6475 retval |= ufshcd_sl_intr(hba, enabled_intr_status);
6477 intr_status = ufshcd_readl(hba, REG_INTERRUPT_STATUS);
6480 if (enabled_intr_status && retval == IRQ_NONE &&
6481 (!(enabled_intr_status & UTP_TRANSFER_REQ_COMPL) ||
6482 hba->outstanding_reqs) && !ufshcd_eh_in_progress(hba)) {
6483 dev_err(hba->dev, "%s: Unhandled interrupt 0x%08x (0x%08x, 0x%08x)\n",
6486 hba->ufs_stats.last_intr_status,
6487 enabled_intr_status);
6488 ufshcd_dump_regs(hba, 0, UFSHCI_REG_SPACE_SIZE, "host_regs: ");
6494 static int ufshcd_clear_tm_cmd(struct ufs_hba *hba, int tag)
6497 u32 mask = 1 << tag;
6498 unsigned long flags;
6500 if (!test_bit(tag, &hba->outstanding_tasks))
6503 spin_lock_irqsave(hba->host->host_lock, flags);
6504 ufshcd_utmrl_clear(hba, tag);
6505 spin_unlock_irqrestore(hba->host->host_lock, flags);
6507 /* poll for max. 1 sec to clear door bell register by h/w */
6508 err = ufshcd_wait_for_register(hba,
6509 REG_UTP_TASK_REQ_DOOR_BELL,
6510 mask, 0, 1000, 1000);
6515 static int __ufshcd_issue_tm_cmd(struct ufs_hba *hba,
6516 struct utp_task_req_desc *treq, u8 tm_function)
6518 struct request_queue *q = hba->tmf_queue;
6519 struct Scsi_Host *host = hba->host;
6520 DECLARE_COMPLETION_ONSTACK(wait);
6521 struct request *req;
6522 unsigned long flags;
6526 * blk_get_request() is used here only to get a free tag.
6528 req = blk_get_request(q, REQ_OP_DRV_OUT, 0);
6530 return PTR_ERR(req);
6532 req->end_io_data = &wait;
6533 ufshcd_hold(hba, false);
6535 spin_lock_irqsave(host->host_lock, flags);
6536 blk_mq_start_request(req);
6538 task_tag = req->tag;
6539 treq->upiu_req.req_header.dword_0 |= cpu_to_be32(task_tag);
6541 memcpy(hba->utmrdl_base_addr + task_tag, treq, sizeof(*treq));
6542 ufshcd_vops_setup_task_mgmt(hba, task_tag, tm_function);
6544 /* send command to the controller */
6545 __set_bit(task_tag, &hba->outstanding_tasks);
6547 ufshcd_writel(hba, 1 << task_tag, REG_UTP_TASK_REQ_DOOR_BELL);
6548 /* Make sure that doorbell is committed immediately */
6551 spin_unlock_irqrestore(host->host_lock, flags);
6553 ufshcd_add_tm_upiu_trace(hba, task_tag, UFS_TM_SEND);
6555 /* wait until the task management command is completed */
6556 err = wait_for_completion_io_timeout(&wait,
6557 msecs_to_jiffies(TM_CMD_TIMEOUT));
6560 * Make sure that ufshcd_compl_tm() does not trigger a
6563 req->end_io_data = NULL;
6564 ufshcd_add_tm_upiu_trace(hba, task_tag, UFS_TM_ERR);
6565 dev_err(hba->dev, "%s: task management cmd 0x%.2x timed-out\n",
6566 __func__, tm_function);
6567 if (ufshcd_clear_tm_cmd(hba, task_tag))
6568 dev_WARN(hba->dev, "%s: unable to clear tm cmd (slot %d) after timeout\n",
6569 __func__, task_tag);
6573 memcpy(treq, hba->utmrdl_base_addr + task_tag, sizeof(*treq));
6575 ufshcd_add_tm_upiu_trace(hba, task_tag, UFS_TM_COMP);
6578 spin_lock_irqsave(hba->host->host_lock, flags);
6579 __clear_bit(task_tag, &hba->outstanding_tasks);
6580 spin_unlock_irqrestore(hba->host->host_lock, flags);
6582 ufshcd_release(hba);
6583 blk_put_request(req);
6589 * ufshcd_issue_tm_cmd - issues task management commands to controller
6590 * @hba: per adapter instance
6591 * @lun_id: LUN ID to which TM command is sent
6592 * @task_id: task ID to which the TM command is applicable
6593 * @tm_function: task management function opcode
6594 * @tm_response: task management service response return value
6596 * Returns non-zero value on error, zero on success.
6598 static int ufshcd_issue_tm_cmd(struct ufs_hba *hba, int lun_id, int task_id,
6599 u8 tm_function, u8 *tm_response)
6601 struct utp_task_req_desc treq = { { 0 }, };
6604 /* Configure task request descriptor */
6605 treq.header.dword_0 = cpu_to_le32(UTP_REQ_DESC_INT_CMD);
6606 treq.header.dword_2 = cpu_to_le32(OCS_INVALID_COMMAND_STATUS);
6608 /* Configure task request UPIU */
6609 treq.upiu_req.req_header.dword_0 = cpu_to_be32(lun_id << 8) |
6610 cpu_to_be32(UPIU_TRANSACTION_TASK_REQ << 24);
6611 treq.upiu_req.req_header.dword_1 = cpu_to_be32(tm_function << 16);
6614 * The host shall provide the same value for LUN field in the basic
6615 * header and for Input Parameter.
6617 treq.upiu_req.input_param1 = cpu_to_be32(lun_id);
6618 treq.upiu_req.input_param2 = cpu_to_be32(task_id);
6620 err = __ufshcd_issue_tm_cmd(hba, &treq, tm_function);
6621 if (err == -ETIMEDOUT)
6624 ocs_value = le32_to_cpu(treq.header.dword_2) & MASK_OCS;
6625 if (ocs_value != OCS_SUCCESS)
6626 dev_err(hba->dev, "%s: failed, ocs = 0x%x\n",
6627 __func__, ocs_value);
6628 else if (tm_response)
6629 *tm_response = be32_to_cpu(treq.upiu_rsp.output_param1) &
6630 MASK_TM_SERVICE_RESP;
6635 * ufshcd_issue_devman_upiu_cmd - API for sending "utrd" type requests
6636 * @hba: per-adapter instance
6637 * @req_upiu: upiu request
6638 * @rsp_upiu: upiu reply
6639 * @desc_buff: pointer to descriptor buffer, NULL if NA
6640 * @buff_len: descriptor size, 0 if NA
6641 * @cmd_type: specifies the type (NOP, Query...)
6642 * @desc_op: descriptor operation
6644 * Those type of requests uses UTP Transfer Request Descriptor - utrd.
6645 * Therefore, it "rides" the device management infrastructure: uses its tag and
6646 * tasks work queues.
6648 * Since there is only one available tag for device management commands,
6649 * the caller is expected to hold the hba->dev_cmd.lock mutex.
6651 static int ufshcd_issue_devman_upiu_cmd(struct ufs_hba *hba,
6652 struct utp_upiu_req *req_upiu,
6653 struct utp_upiu_req *rsp_upiu,
6654 u8 *desc_buff, int *buff_len,
6655 enum dev_cmd_type cmd_type,
6656 enum query_opcode desc_op)
6658 struct request_queue *q = hba->cmd_queue;
6659 DECLARE_COMPLETION_ONSTACK(wait);
6660 struct request *req;
6661 struct ufshcd_lrb *lrbp;
6666 down_read(&hba->clk_scaling_lock);
6668 req = blk_get_request(q, REQ_OP_DRV_OUT, 0);
6674 WARN_ONCE(tag < 0, "Invalid tag %d\n", tag);
6676 if (unlikely(test_bit(tag, &hba->outstanding_reqs))) {
6681 lrbp = &hba->lrb[tag];
6684 lrbp->sense_bufflen = 0;
6685 lrbp->sense_buffer = NULL;
6686 lrbp->task_tag = tag;
6688 lrbp->intr_cmd = true;
6689 ufshcd_prepare_lrbp_crypto(NULL, lrbp);
6690 hba->dev_cmd.type = cmd_type;
6692 if (hba->ufs_version <= ufshci_version(1, 1))
6693 lrbp->command_type = UTP_CMD_TYPE_DEV_MANAGE;
6695 lrbp->command_type = UTP_CMD_TYPE_UFS_STORAGE;
6697 /* update the task tag in the request upiu */
6698 req_upiu->header.dword_0 |= cpu_to_be32(tag);
6700 ufshcd_prepare_req_desc_hdr(lrbp, &upiu_flags, DMA_NONE);
6702 /* just copy the upiu request as it is */
6703 memcpy(lrbp->ucd_req_ptr, req_upiu, sizeof(*lrbp->ucd_req_ptr));
6704 if (desc_buff && desc_op == UPIU_QUERY_OPCODE_WRITE_DESC) {
6705 /* The Data Segment Area is optional depending upon the query
6706 * function value. for WRITE DESCRIPTOR, the data segment
6707 * follows right after the tsf.
6709 memcpy(lrbp->ucd_req_ptr + 1, desc_buff, *buff_len);
6713 memset(lrbp->ucd_rsp_ptr, 0, sizeof(struct utp_upiu_rsp));
6715 hba->dev_cmd.complete = &wait;
6717 ufshcd_add_query_upiu_trace(hba, UFS_QUERY_SEND, lrbp->ucd_req_ptr);
6719 ufshcd_send_command(hba, tag);
6721 * ignore the returning value here - ufshcd_check_query_response is
6722 * bound to fail since dev_cmd.query and dev_cmd.type were left empty.
6723 * read the response directly ignoring all errors.
6725 ufshcd_wait_for_dev_cmd(hba, lrbp, QUERY_REQ_TIMEOUT);
6727 /* just copy the upiu response as it is */
6728 memcpy(rsp_upiu, lrbp->ucd_rsp_ptr, sizeof(*rsp_upiu));
6729 if (desc_buff && desc_op == UPIU_QUERY_OPCODE_READ_DESC) {
6730 u8 *descp = (u8 *)lrbp->ucd_rsp_ptr + sizeof(*rsp_upiu);
6731 u16 resp_len = be32_to_cpu(lrbp->ucd_rsp_ptr->header.dword_2) &
6732 MASK_QUERY_DATA_SEG_LEN;
6734 if (*buff_len >= resp_len) {
6735 memcpy(desc_buff, descp, resp_len);
6736 *buff_len = resp_len;
6739 "%s: rsp size %d is bigger than buffer size %d",
6740 __func__, resp_len, *buff_len);
6745 ufshcd_add_query_upiu_trace(hba, err ? UFS_QUERY_ERR : UFS_QUERY_COMP,
6746 (struct utp_upiu_req *)lrbp->ucd_rsp_ptr);
6749 blk_put_request(req);
6751 up_read(&hba->clk_scaling_lock);
6756 * ufshcd_exec_raw_upiu_cmd - API function for sending raw upiu commands
6757 * @hba: per-adapter instance
6758 * @req_upiu: upiu request
6759 * @rsp_upiu: upiu reply - only 8 DW as we do not support scsi commands
6760 * @msgcode: message code, one of UPIU Transaction Codes Initiator to Target
6761 * @desc_buff: pointer to descriptor buffer, NULL if NA
6762 * @buff_len: descriptor size, 0 if NA
6763 * @desc_op: descriptor operation
6765 * Supports UTP Transfer requests (nop and query), and UTP Task
6766 * Management requests.
6767 * It is up to the caller to fill the upiu conent properly, as it will
6768 * be copied without any further input validations.
6770 int ufshcd_exec_raw_upiu_cmd(struct ufs_hba *hba,
6771 struct utp_upiu_req *req_upiu,
6772 struct utp_upiu_req *rsp_upiu,
6774 u8 *desc_buff, int *buff_len,
6775 enum query_opcode desc_op)
6778 enum dev_cmd_type cmd_type = DEV_CMD_TYPE_QUERY;
6779 struct utp_task_req_desc treq = { { 0 }, };
6781 u8 tm_f = be32_to_cpu(req_upiu->header.dword_1) >> 16 & MASK_TM_FUNC;
6784 case UPIU_TRANSACTION_NOP_OUT:
6785 cmd_type = DEV_CMD_TYPE_NOP;
6787 case UPIU_TRANSACTION_QUERY_REQ:
6788 ufshcd_hold(hba, false);
6789 mutex_lock(&hba->dev_cmd.lock);
6790 err = ufshcd_issue_devman_upiu_cmd(hba, req_upiu, rsp_upiu,
6791 desc_buff, buff_len,
6793 mutex_unlock(&hba->dev_cmd.lock);
6794 ufshcd_release(hba);
6797 case UPIU_TRANSACTION_TASK_REQ:
6798 treq.header.dword_0 = cpu_to_le32(UTP_REQ_DESC_INT_CMD);
6799 treq.header.dword_2 = cpu_to_le32(OCS_INVALID_COMMAND_STATUS);
6801 memcpy(&treq.upiu_req, req_upiu, sizeof(*req_upiu));
6803 err = __ufshcd_issue_tm_cmd(hba, &treq, tm_f);
6804 if (err == -ETIMEDOUT)
6807 ocs_value = le32_to_cpu(treq.header.dword_2) & MASK_OCS;
6808 if (ocs_value != OCS_SUCCESS) {
6809 dev_err(hba->dev, "%s: failed, ocs = 0x%x\n", __func__,
6814 memcpy(rsp_upiu, &treq.upiu_rsp, sizeof(*rsp_upiu));
6827 * ufshcd_eh_device_reset_handler - device reset handler registered to
6829 * @cmd: SCSI command pointer
6831 * Returns SUCCESS/FAILED
6833 static int ufshcd_eh_device_reset_handler(struct scsi_cmnd *cmd)
6835 struct Scsi_Host *host;
6836 struct ufs_hba *hba;
6841 host = cmd->device->host;
6842 hba = shost_priv(host);
6844 lun = ufshcd_scsi_to_upiu_lun(cmd->device->lun);
6845 err = ufshcd_issue_tm_cmd(hba, lun, 0, UFS_LOGICAL_RESET, &resp);
6846 if (err || resp != UPIU_TASK_MANAGEMENT_FUNC_COMPL) {
6852 /* clear the commands that were pending for corresponding LUN */
6853 for_each_set_bit(pos, &hba->outstanding_reqs, hba->nutrs) {
6854 if (hba->lrb[pos].lun == lun) {
6855 err = ufshcd_clear_cmd(hba, pos);
6858 __ufshcd_transfer_req_compl(hba, pos, /*retry_requests=*/true);
6863 hba->req_abort_count = 0;
6864 ufshcd_update_evt_hist(hba, UFS_EVT_DEV_RESET, (u32)err);
6868 dev_err(hba->dev, "%s: failed with err %d\n", __func__, err);
6874 static void ufshcd_set_req_abort_skip(struct ufs_hba *hba, unsigned long bitmap)
6876 struct ufshcd_lrb *lrbp;
6879 for_each_set_bit(tag, &bitmap, hba->nutrs) {
6880 lrbp = &hba->lrb[tag];
6881 lrbp->req_abort_skip = true;
6886 * ufshcd_try_to_abort_task - abort a specific task
6887 * @hba: Pointer to adapter instance
6888 * @tag: Task tag/index to be aborted
6890 * Abort the pending command in device by sending UFS_ABORT_TASK task management
6891 * command, and in host controller by clearing the door-bell register. There can
6892 * be race between controller sending the command to the device while abort is
6893 * issued. To avoid that, first issue UFS_QUERY_TASK to check if the command is
6894 * really issued and then try to abort it.
6896 * Returns zero on success, non-zero on failure
6898 static int ufshcd_try_to_abort_task(struct ufs_hba *hba, int tag)
6900 struct ufshcd_lrb *lrbp = &hba->lrb[tag];
6906 for (poll_cnt = 100; poll_cnt; poll_cnt--) {
6907 err = ufshcd_issue_tm_cmd(hba, lrbp->lun, lrbp->task_tag,
6908 UFS_QUERY_TASK, &resp);
6909 if (!err && resp == UPIU_TASK_MANAGEMENT_FUNC_SUCCEEDED) {
6910 /* cmd pending in the device */
6911 dev_err(hba->dev, "%s: cmd pending in the device. tag = %d\n",
6914 } else if (!err && resp == UPIU_TASK_MANAGEMENT_FUNC_COMPL) {
6916 * cmd not pending in the device, check if it is
6919 dev_err(hba->dev, "%s: cmd at tag %d not pending in the device.\n",
6921 reg = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
6922 if (reg & (1 << tag)) {
6923 /* sleep for max. 200us to stabilize */
6924 usleep_range(100, 200);
6927 /* command completed already */
6928 dev_err(hba->dev, "%s: cmd at tag %d successfully cleared from DB.\n",
6933 "%s: no response from device. tag = %d, err %d\n",
6934 __func__, tag, err);
6936 err = resp; /* service response error */
6946 err = ufshcd_issue_tm_cmd(hba, lrbp->lun, lrbp->task_tag,
6947 UFS_ABORT_TASK, &resp);
6948 if (err || resp != UPIU_TASK_MANAGEMENT_FUNC_COMPL) {
6950 err = resp; /* service response error */
6951 dev_err(hba->dev, "%s: issued. tag = %d, err %d\n",
6952 __func__, tag, err);
6957 err = ufshcd_clear_cmd(hba, tag);
6959 dev_err(hba->dev, "%s: Failed clearing cmd at tag %d, err %d\n",
6960 __func__, tag, err);
6967 * ufshcd_abort - scsi host template eh_abort_handler callback
6968 * @cmd: SCSI command pointer
6970 * Returns SUCCESS/FAILED
6972 static int ufshcd_abort(struct scsi_cmnd *cmd)
6974 struct Scsi_Host *host = cmd->device->host;
6975 struct ufs_hba *hba = shost_priv(host);
6976 unsigned int tag = cmd->request->tag;
6977 struct ufshcd_lrb *lrbp = &hba->lrb[tag];
6978 unsigned long flags;
6982 WARN_ONCE(tag < 0, "Invalid tag %d\n", tag);
6984 ufshcd_hold(hba, false);
6985 reg = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
6986 /* If command is already aborted/completed, return FAILED. */
6987 if (!(test_bit(tag, &hba->outstanding_reqs))) {
6989 "%s: cmd at tag %d already completed, outstanding=0x%lx, doorbell=0x%x\n",
6990 __func__, tag, hba->outstanding_reqs, reg);
6994 /* Print Transfer Request of aborted task */
6995 dev_info(hba->dev, "%s: Device abort task at tag %d\n", __func__, tag);
6998 * Print detailed info about aborted request.
6999 * As more than one request might get aborted at the same time,
7000 * print full information only for the first aborted request in order
7001 * to reduce repeated printouts. For other aborted requests only print
7004 scsi_print_command(cmd);
7005 if (!hba->req_abort_count) {
7006 ufshcd_update_evt_hist(hba, UFS_EVT_ABORT, tag);
7007 ufshcd_print_evt_hist(hba);
7008 ufshcd_print_host_state(hba);
7009 ufshcd_print_pwr_info(hba);
7010 ufshcd_print_trs(hba, 1 << tag, true);
7012 ufshcd_print_trs(hba, 1 << tag, false);
7014 hba->req_abort_count++;
7016 if (!(reg & (1 << tag))) {
7018 "%s: cmd was completed, but without a notifying intr, tag = %d",
7020 __ufshcd_transfer_req_compl(hba, 1UL << tag, /*retry_requests=*/false);
7025 * Task abort to the device W-LUN is illegal. When this command
7026 * will fail, due to spec violation, scsi err handling next step
7027 * will be to send LU reset which, again, is a spec violation.
7028 * To avoid these unnecessary/illegal steps, first we clean up
7029 * the lrb taken by this cmd and re-set it in outstanding_reqs,
7030 * then queue the error handler and bail.
7032 if (lrbp->lun == UFS_UPIU_UFS_DEVICE_WLUN) {
7033 ufshcd_update_evt_hist(hba, UFS_EVT_ABORT, lrbp->lun);
7035 spin_lock_irqsave(host->host_lock, flags);
7036 hba->force_reset = true;
7037 spin_unlock_irqrestore(host->host_lock, flags);
7039 ufshcd_schedule_eh(hba);
7044 /* Skip task abort in case previous aborts failed and report failure */
7045 if (lrbp->req_abort_skip) {
7046 dev_err(hba->dev, "%s: skipping abort\n", __func__);
7047 ufshcd_set_req_abort_skip(hba, hba->outstanding_reqs);
7051 err = ufshcd_try_to_abort_task(hba, tag);
7053 dev_err(hba->dev, "%s: failed with err %d\n", __func__, err);
7054 ufshcd_set_req_abort_skip(hba, hba->outstanding_reqs);
7062 /* Matches the ufshcd_hold() call at the start of this function. */
7063 ufshcd_release(hba);
7068 * ufshcd_host_reset_and_restore - reset and restore host controller
7069 * @hba: per-adapter instance
7071 * Note that host controller reset may issue DME_RESET to
7072 * local and remote (device) Uni-Pro stack and the attributes
7073 * are reset to default state.
7075 * Returns zero on success, non-zero on failure
7077 static int ufshcd_host_reset_and_restore(struct ufs_hba *hba)
7082 * Stop the host controller and complete the requests
7085 ufshpb_reset_host(hba);
7086 ufshcd_hba_stop(hba);
7087 hba->silence_err_logs = true;
7088 ufshcd_retry_aborted_requests(hba);
7089 hba->silence_err_logs = false;
7091 /* scale up clocks to max frequency before full reinitialization */
7092 ufshcd_set_clk_freq(hba, true);
7094 err = ufshcd_hba_enable(hba);
7096 /* Establish the link again and restore the device */
7098 err = ufshcd_probe_hba(hba, false);
7101 dev_err(hba->dev, "%s: Host init failed %d\n", __func__, err);
7102 ufshcd_update_evt_hist(hba, UFS_EVT_HOST_RESET, (u32)err);
7107 * ufshcd_reset_and_restore - reset and re-initialize host/device
7108 * @hba: per-adapter instance
7110 * Reset and recover device, host and re-establish link. This
7111 * is helpful to recover the communication in fatal error conditions.
7113 * Returns zero on success, non-zero on failure
7115 static int ufshcd_reset_and_restore(struct ufs_hba *hba)
7120 unsigned long flags;
7121 int retries = MAX_HOST_RESET_RETRIES;
7124 * This is a fresh start, cache and clear saved error first,
7125 * in case new error generated during reset and restore.
7127 spin_lock_irqsave(hba->host->host_lock, flags);
7128 saved_err = hba->saved_err;
7129 saved_uic_err = hba->saved_uic_err;
7131 hba->saved_uic_err = 0;
7132 spin_unlock_irqrestore(hba->host->host_lock, flags);
7135 /* Reset the attached device */
7136 ufshcd_device_reset(hba);
7138 err = ufshcd_host_reset_and_restore(hba);
7139 } while (err && --retries);
7141 spin_lock_irqsave(hba->host->host_lock, flags);
7143 * Inform scsi mid-layer that we did reset and allow to handle
7144 * Unit Attention properly.
7146 scsi_report_bus_reset(hba->host, 0);
7148 hba->ufshcd_state = UFSHCD_STATE_ERROR;
7149 hba->saved_err |= saved_err;
7150 hba->saved_uic_err |= saved_uic_err;
7152 spin_unlock_irqrestore(hba->host->host_lock, flags);
7158 * ufshcd_eh_host_reset_handler - host reset handler registered to scsi layer
7159 * @cmd: SCSI command pointer
7161 * Returns SUCCESS/FAILED
7163 static int ufshcd_eh_host_reset_handler(struct scsi_cmnd *cmd)
7166 unsigned long flags;
7167 struct ufs_hba *hba;
7169 hba = shost_priv(cmd->device->host);
7171 spin_lock_irqsave(hba->host->host_lock, flags);
7172 hba->force_reset = true;
7173 dev_err(hba->dev, "%s: reset in progress - 1\n", __func__);
7174 spin_unlock_irqrestore(hba->host->host_lock, flags);
7176 ufshcd_err_handler(hba->host);
7178 spin_lock_irqsave(hba->host->host_lock, flags);
7179 if (hba->ufshcd_state == UFSHCD_STATE_ERROR)
7181 spin_unlock_irqrestore(hba->host->host_lock, flags);
7187 * ufshcd_get_max_icc_level - calculate the ICC level
7188 * @sup_curr_uA: max. current supported by the regulator
7189 * @start_scan: row at the desc table to start scan from
7190 * @buff: power descriptor buffer
7192 * Returns calculated max ICC level for specific regulator
7194 static u32 ufshcd_get_max_icc_level(int sup_curr_uA, u32 start_scan, char *buff)
7201 for (i = start_scan; i >= 0; i--) {
7202 data = be16_to_cpup((__be16 *)&buff[2 * i]);
7203 unit = (data & ATTR_ICC_LVL_UNIT_MASK) >>
7204 ATTR_ICC_LVL_UNIT_OFFSET;
7205 curr_uA = data & ATTR_ICC_LVL_VALUE_MASK;
7207 case UFSHCD_NANO_AMP:
7208 curr_uA = curr_uA / 1000;
7210 case UFSHCD_MILI_AMP:
7211 curr_uA = curr_uA * 1000;
7214 curr_uA = curr_uA * 1000 * 1000;
7216 case UFSHCD_MICRO_AMP:
7220 if (sup_curr_uA >= curr_uA)
7225 pr_err("%s: Couldn't find valid icc_level = %d", __func__, i);
7232 * ufshcd_find_max_sup_active_icc_level - calculate the max ICC level
7233 * In case regulators are not initialized we'll return 0
7234 * @hba: per-adapter instance
7235 * @desc_buf: power descriptor buffer to extract ICC levels from.
7236 * @len: length of desc_buff
7238 * Returns calculated ICC level
7240 static u32 ufshcd_find_max_sup_active_icc_level(struct ufs_hba *hba,
7241 u8 *desc_buf, int len)
7245 if (!hba->vreg_info.vcc || !hba->vreg_info.vccq ||
7246 !hba->vreg_info.vccq2) {
7248 "%s: Regulator capability was not set, actvIccLevel=%d",
7249 __func__, icc_level);
7253 if (hba->vreg_info.vcc->max_uA)
7254 icc_level = ufshcd_get_max_icc_level(
7255 hba->vreg_info.vcc->max_uA,
7256 POWER_DESC_MAX_ACTV_ICC_LVLS - 1,
7257 &desc_buf[PWR_DESC_ACTIVE_LVLS_VCC_0]);
7259 if (hba->vreg_info.vccq->max_uA)
7260 icc_level = ufshcd_get_max_icc_level(
7261 hba->vreg_info.vccq->max_uA,
7263 &desc_buf[PWR_DESC_ACTIVE_LVLS_VCCQ_0]);
7265 if (hba->vreg_info.vccq2->max_uA)
7266 icc_level = ufshcd_get_max_icc_level(
7267 hba->vreg_info.vccq2->max_uA,
7269 &desc_buf[PWR_DESC_ACTIVE_LVLS_VCCQ2_0]);
7274 static void ufshcd_set_active_icc_lvl(struct ufs_hba *hba)
7277 int buff_len = hba->desc_size[QUERY_DESC_IDN_POWER];
7281 desc_buf = kmalloc(buff_len, GFP_KERNEL);
7285 ret = ufshcd_read_desc_param(hba, QUERY_DESC_IDN_POWER, 0, 0,
7286 desc_buf, buff_len);
7289 "%s: Failed reading power descriptor.len = %d ret = %d",
7290 __func__, buff_len, ret);
7294 icc_level = ufshcd_find_max_sup_active_icc_level(hba, desc_buf,
7296 dev_dbg(hba->dev, "%s: setting icc_level 0x%x", __func__, icc_level);
7298 ret = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_WRITE_ATTR,
7299 QUERY_ATTR_IDN_ACTIVE_ICC_LVL, 0, 0, &icc_level);
7303 "%s: Failed configuring bActiveICCLevel = %d ret = %d",
7304 __func__, icc_level, ret);
7310 static inline void ufshcd_blk_pm_runtime_init(struct scsi_device *sdev)
7312 scsi_autopm_get_device(sdev);
7313 blk_pm_runtime_init(sdev->request_queue, &sdev->sdev_gendev);
7314 if (sdev->rpm_autosuspend)
7315 pm_runtime_set_autosuspend_delay(&sdev->sdev_gendev,
7316 RPM_AUTOSUSPEND_DELAY_MS);
7317 scsi_autopm_put_device(sdev);
7321 * ufshcd_scsi_add_wlus - Adds required W-LUs
7322 * @hba: per-adapter instance
7324 * UFS device specification requires the UFS devices to support 4 well known
7326 * "REPORT_LUNS" (address: 01h)
7327 * "UFS Device" (address: 50h)
7328 * "RPMB" (address: 44h)
7329 * "BOOT" (address: 30h)
7330 * UFS device's power management needs to be controlled by "POWER CONDITION"
7331 * field of SSU (START STOP UNIT) command. But this "power condition" field
7332 * will take effect only when its sent to "UFS device" well known logical unit
7333 * hence we require the scsi_device instance to represent this logical unit in
7334 * order for the UFS host driver to send the SSU command for power management.
7336 * We also require the scsi_device instance for "RPMB" (Replay Protected Memory
7337 * Block) LU so user space process can control this LU. User space may also
7338 * want to have access to BOOT LU.
7340 * This function adds scsi device instances for each of all well known LUs
7341 * (except "REPORT LUNS" LU).
7343 * Returns zero on success (all required W-LUs are added successfully),
7344 * non-zero error value on failure (if failed to add any of the required W-LU).
7346 static int ufshcd_scsi_add_wlus(struct ufs_hba *hba)
7349 struct scsi_device *sdev_boot;
7351 hba->sdev_ufs_device = __scsi_add_device(hba->host, 0, 0,
7352 ufshcd_upiu_wlun_to_scsi_wlun(UFS_UPIU_UFS_DEVICE_WLUN), NULL);
7353 if (IS_ERR(hba->sdev_ufs_device)) {
7354 ret = PTR_ERR(hba->sdev_ufs_device);
7355 hba->sdev_ufs_device = NULL;
7358 scsi_device_put(hba->sdev_ufs_device);
7360 hba->sdev_rpmb = __scsi_add_device(hba->host, 0, 0,
7361 ufshcd_upiu_wlun_to_scsi_wlun(UFS_UPIU_RPMB_WLUN), NULL);
7362 if (IS_ERR(hba->sdev_rpmb)) {
7363 ret = PTR_ERR(hba->sdev_rpmb);
7364 goto remove_sdev_ufs_device;
7366 ufshcd_blk_pm_runtime_init(hba->sdev_rpmb);
7367 scsi_device_put(hba->sdev_rpmb);
7369 sdev_boot = __scsi_add_device(hba->host, 0, 0,
7370 ufshcd_upiu_wlun_to_scsi_wlun(UFS_UPIU_BOOT_WLUN), NULL);
7371 if (IS_ERR(sdev_boot)) {
7372 dev_err(hba->dev, "%s: BOOT WLUN not found\n", __func__);
7374 ufshcd_blk_pm_runtime_init(sdev_boot);
7375 scsi_device_put(sdev_boot);
7379 remove_sdev_ufs_device:
7380 scsi_remove_device(hba->sdev_ufs_device);
7385 static void ufshcd_wb_probe(struct ufs_hba *hba, u8 *desc_buf)
7387 struct ufs_dev_info *dev_info = &hba->dev_info;
7389 u32 d_lu_wb_buf_alloc;
7390 u32 ext_ufs_feature;
7392 if (!ufshcd_is_wb_allowed(hba))
7395 * Probe WB only for UFS-2.2 and UFS-3.1 (and later) devices or
7396 * UFS devices with quirk UFS_DEVICE_QUIRK_SUPPORT_EXTENDED_FEATURES
7399 if (!(dev_info->wspecversion >= 0x310 ||
7400 dev_info->wspecversion == 0x220 ||
7401 (hba->dev_quirks & UFS_DEVICE_QUIRK_SUPPORT_EXTENDED_FEATURES)))
7404 if (hba->desc_size[QUERY_DESC_IDN_DEVICE] <
7405 DEVICE_DESC_PARAM_EXT_UFS_FEATURE_SUP + 4)
7408 ext_ufs_feature = get_unaligned_be32(desc_buf +
7409 DEVICE_DESC_PARAM_EXT_UFS_FEATURE_SUP);
7411 if (!(ext_ufs_feature & UFS_DEV_WRITE_BOOSTER_SUP))
7415 * WB may be supported but not configured while provisioning. The spec
7416 * says, in dedicated wb buffer mode, a max of 1 lun would have wb
7417 * buffer configured.
7419 dev_info->wb_buffer_type = desc_buf[DEVICE_DESC_PARAM_WB_TYPE];
7421 dev_info->b_presrv_uspc_en =
7422 desc_buf[DEVICE_DESC_PARAM_WB_PRESRV_USRSPC_EN];
7424 if (dev_info->wb_buffer_type == WB_BUF_MODE_SHARED) {
7425 if (!get_unaligned_be32(desc_buf +
7426 DEVICE_DESC_PARAM_WB_SHARED_ALLOC_UNITS))
7429 for (lun = 0; lun < UFS_UPIU_MAX_WB_LUN_ID; lun++) {
7430 d_lu_wb_buf_alloc = 0;
7431 ufshcd_read_unit_desc_param(hba,
7433 UNIT_DESC_PARAM_WB_BUF_ALLOC_UNITS,
7434 (u8 *)&d_lu_wb_buf_alloc,
7435 sizeof(d_lu_wb_buf_alloc));
7436 if (d_lu_wb_buf_alloc) {
7437 dev_info->wb_dedicated_lu = lun;
7442 if (!d_lu_wb_buf_alloc)
7448 hba->caps &= ~UFSHCD_CAP_WB_EN;
7451 void ufshcd_fixup_dev_quirks(struct ufs_hba *hba, struct ufs_dev_fix *fixups)
7453 struct ufs_dev_fix *f;
7454 struct ufs_dev_info *dev_info = &hba->dev_info;
7459 for (f = fixups; f->quirk; f++) {
7460 if ((f->wmanufacturerid == dev_info->wmanufacturerid ||
7461 f->wmanufacturerid == UFS_ANY_VENDOR) &&
7462 ((dev_info->model &&
7463 STR_PRFX_EQUAL(f->model, dev_info->model)) ||
7464 !strcmp(f->model, UFS_ANY_MODEL)))
7465 hba->dev_quirks |= f->quirk;
7468 EXPORT_SYMBOL_GPL(ufshcd_fixup_dev_quirks);
7470 static void ufs_fixup_device_setup(struct ufs_hba *hba)
7472 /* fix by general quirk table */
7473 ufshcd_fixup_dev_quirks(hba, ufs_fixups);
7475 /* allow vendors to fix quirks */
7476 ufshcd_vops_fixup_dev_quirks(hba);
7479 static int ufs_get_device_desc(struct ufs_hba *hba)
7483 u8 b_ufs_feature_sup;
7485 struct ufs_dev_info *dev_info = &hba->dev_info;
7487 desc_buf = kmalloc(QUERY_DESC_MAX_SIZE, GFP_KERNEL);
7493 err = ufshcd_read_desc_param(hba, QUERY_DESC_IDN_DEVICE, 0, 0, desc_buf,
7494 hba->desc_size[QUERY_DESC_IDN_DEVICE]);
7496 dev_err(hba->dev, "%s: Failed reading Device Desc. err = %d\n",
7502 * getting vendor (manufacturerID) and Bank Index in big endian
7505 dev_info->wmanufacturerid = desc_buf[DEVICE_DESC_PARAM_MANF_ID] << 8 |
7506 desc_buf[DEVICE_DESC_PARAM_MANF_ID + 1];
7508 /* getting Specification Version in big endian format */
7509 dev_info->wspecversion = desc_buf[DEVICE_DESC_PARAM_SPEC_VER] << 8 |
7510 desc_buf[DEVICE_DESC_PARAM_SPEC_VER + 1];
7511 b_ufs_feature_sup = desc_buf[DEVICE_DESC_PARAM_UFS_FEAT];
7513 model_index = desc_buf[DEVICE_DESC_PARAM_PRDCT_NAME];
7515 if (dev_info->wspecversion >= UFS_DEV_HPB_SUPPORT_VERSION &&
7516 (b_ufs_feature_sup & UFS_DEV_HPB_SUPPORT)) {
7517 bool hpb_en = false;
7519 ufshpb_get_dev_info(hba, desc_buf);
7521 if (!ufshpb_is_legacy(hba))
7522 err = ufshcd_query_flag_retry(hba,
7523 UPIU_QUERY_OPCODE_READ_FLAG,
7524 QUERY_FLAG_IDN_HPB_EN, 0,
7527 if (ufshpb_is_legacy(hba) || (!err && hpb_en))
7528 dev_info->hpb_enabled = true;
7531 err = ufshcd_read_string_desc(hba, model_index,
7532 &dev_info->model, SD_ASCII_STD);
7534 dev_err(hba->dev, "%s: Failed reading Product Name. err = %d\n",
7539 hba->luns_avail = desc_buf[DEVICE_DESC_PARAM_NUM_LU] +
7540 desc_buf[DEVICE_DESC_PARAM_NUM_WLU];
7542 ufs_fixup_device_setup(hba);
7544 ufshcd_wb_probe(hba, desc_buf);
7547 * ufshcd_read_string_desc returns size of the string
7548 * reset the error value
7557 static void ufs_put_device_desc(struct ufs_hba *hba)
7559 struct ufs_dev_info *dev_info = &hba->dev_info;
7561 kfree(dev_info->model);
7562 dev_info->model = NULL;
7566 * ufshcd_tune_pa_tactivate - Tunes PA_TActivate of local UniPro
7567 * @hba: per-adapter instance
7569 * PA_TActivate parameter can be tuned manually if UniPro version is less than
7570 * 1.61. PA_TActivate needs to be greater than or equal to peerM-PHY's
7571 * RX_MIN_ACTIVATETIME_CAPABILITY attribute. This optimal value can help reduce
7572 * the hibern8 exit latency.
7574 * Returns zero on success, non-zero error value on failure.
7576 static int ufshcd_tune_pa_tactivate(struct ufs_hba *hba)
7579 u32 peer_rx_min_activatetime = 0, tuned_pa_tactivate;
7581 ret = ufshcd_dme_peer_get(hba,
7583 RX_MIN_ACTIVATETIME_CAPABILITY,
7584 UIC_ARG_MPHY_RX_GEN_SEL_INDEX(0)),
7585 &peer_rx_min_activatetime);
7589 /* make sure proper unit conversion is applied */
7590 tuned_pa_tactivate =
7591 ((peer_rx_min_activatetime * RX_MIN_ACTIVATETIME_UNIT_US)
7592 / PA_TACTIVATE_TIME_UNIT_US);
7593 ret = ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TACTIVATE),
7594 tuned_pa_tactivate);
7601 * ufshcd_tune_pa_hibern8time - Tunes PA_Hibern8Time of local UniPro
7602 * @hba: per-adapter instance
7604 * PA_Hibern8Time parameter can be tuned manually if UniPro version is less than
7605 * 1.61. PA_Hibern8Time needs to be maximum of local M-PHY's
7606 * TX_HIBERN8TIME_CAPABILITY & peer M-PHY's RX_HIBERN8TIME_CAPABILITY.
7607 * This optimal value can help reduce the hibern8 exit latency.
7609 * Returns zero on success, non-zero error value on failure.
7611 static int ufshcd_tune_pa_hibern8time(struct ufs_hba *hba)
7614 u32 local_tx_hibern8_time_cap = 0, peer_rx_hibern8_time_cap = 0;
7615 u32 max_hibern8_time, tuned_pa_hibern8time;
7617 ret = ufshcd_dme_get(hba,
7618 UIC_ARG_MIB_SEL(TX_HIBERN8TIME_CAPABILITY,
7619 UIC_ARG_MPHY_TX_GEN_SEL_INDEX(0)),
7620 &local_tx_hibern8_time_cap);
7624 ret = ufshcd_dme_peer_get(hba,
7625 UIC_ARG_MIB_SEL(RX_HIBERN8TIME_CAPABILITY,
7626 UIC_ARG_MPHY_RX_GEN_SEL_INDEX(0)),
7627 &peer_rx_hibern8_time_cap);
7631 max_hibern8_time = max(local_tx_hibern8_time_cap,
7632 peer_rx_hibern8_time_cap);
7633 /* make sure proper unit conversion is applied */
7634 tuned_pa_hibern8time = ((max_hibern8_time * HIBERN8TIME_UNIT_US)
7635 / PA_HIBERN8_TIME_UNIT_US);
7636 ret = ufshcd_dme_set(hba, UIC_ARG_MIB(PA_HIBERN8TIME),
7637 tuned_pa_hibern8time);
7643 * ufshcd_quirk_tune_host_pa_tactivate - Ensures that host PA_TACTIVATE is
7644 * less than device PA_TACTIVATE time.
7645 * @hba: per-adapter instance
7647 * Some UFS devices require host PA_TACTIVATE to be lower than device
7648 * PA_TACTIVATE, we need to enable UFS_DEVICE_QUIRK_HOST_PA_TACTIVATE quirk
7651 * Returns zero on success, non-zero error value on failure.
7653 static int ufshcd_quirk_tune_host_pa_tactivate(struct ufs_hba *hba)
7656 u32 granularity, peer_granularity;
7657 u32 pa_tactivate, peer_pa_tactivate;
7658 u32 pa_tactivate_us, peer_pa_tactivate_us;
7659 u8 gran_to_us_table[] = {1, 4, 8, 16, 32, 100};
7661 ret = ufshcd_dme_get(hba, UIC_ARG_MIB(PA_GRANULARITY),
7666 ret = ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_GRANULARITY),
7671 if ((granularity < PA_GRANULARITY_MIN_VAL) ||
7672 (granularity > PA_GRANULARITY_MAX_VAL)) {
7673 dev_err(hba->dev, "%s: invalid host PA_GRANULARITY %d",
7674 __func__, granularity);
7678 if ((peer_granularity < PA_GRANULARITY_MIN_VAL) ||
7679 (peer_granularity > PA_GRANULARITY_MAX_VAL)) {
7680 dev_err(hba->dev, "%s: invalid device PA_GRANULARITY %d",
7681 __func__, peer_granularity);
7685 ret = ufshcd_dme_get(hba, UIC_ARG_MIB(PA_TACTIVATE), &pa_tactivate);
7689 ret = ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_TACTIVATE),
7690 &peer_pa_tactivate);
7694 pa_tactivate_us = pa_tactivate * gran_to_us_table[granularity - 1];
7695 peer_pa_tactivate_us = peer_pa_tactivate *
7696 gran_to_us_table[peer_granularity - 1];
7698 if (pa_tactivate_us > peer_pa_tactivate_us) {
7699 u32 new_peer_pa_tactivate;
7701 new_peer_pa_tactivate = pa_tactivate_us /
7702 gran_to_us_table[peer_granularity - 1];
7703 new_peer_pa_tactivate++;
7704 ret = ufshcd_dme_peer_set(hba, UIC_ARG_MIB(PA_TACTIVATE),
7705 new_peer_pa_tactivate);
7712 static void ufshcd_tune_unipro_params(struct ufs_hba *hba)
7714 if (ufshcd_is_unipro_pa_params_tuning_req(hba)) {
7715 ufshcd_tune_pa_tactivate(hba);
7716 ufshcd_tune_pa_hibern8time(hba);
7719 ufshcd_vops_apply_dev_quirks(hba);
7721 if (hba->dev_quirks & UFS_DEVICE_QUIRK_PA_TACTIVATE)
7722 /* set 1ms timeout for PA_TACTIVATE */
7723 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TACTIVATE), 10);
7725 if (hba->dev_quirks & UFS_DEVICE_QUIRK_HOST_PA_TACTIVATE)
7726 ufshcd_quirk_tune_host_pa_tactivate(hba);
7729 static void ufshcd_clear_dbg_ufs_stats(struct ufs_hba *hba)
7731 hba->ufs_stats.hibern8_exit_cnt = 0;
7732 hba->ufs_stats.last_hibern8_exit_tstamp = ktime_set(0, 0);
7733 hba->req_abort_count = 0;
7736 static int ufshcd_device_geo_params_init(struct ufs_hba *hba)
7742 buff_len = hba->desc_size[QUERY_DESC_IDN_GEOMETRY];
7743 desc_buf = kmalloc(buff_len, GFP_KERNEL);
7749 err = ufshcd_read_desc_param(hba, QUERY_DESC_IDN_GEOMETRY, 0, 0,
7750 desc_buf, buff_len);
7752 dev_err(hba->dev, "%s: Failed reading Geometry Desc. err = %d\n",
7757 if (desc_buf[GEOMETRY_DESC_PARAM_MAX_NUM_LUN] == 1)
7758 hba->dev_info.max_lu_supported = 32;
7759 else if (desc_buf[GEOMETRY_DESC_PARAM_MAX_NUM_LUN] == 0)
7760 hba->dev_info.max_lu_supported = 8;
7762 if (hba->desc_size[QUERY_DESC_IDN_GEOMETRY] >=
7763 GEOMETRY_DESC_PARAM_HPB_MAX_ACTIVE_REGS)
7764 ufshpb_get_geo_info(hba, desc_buf);
7771 static struct ufs_ref_clk ufs_ref_clk_freqs[] = {
7772 {19200000, REF_CLK_FREQ_19_2_MHZ},
7773 {26000000, REF_CLK_FREQ_26_MHZ},
7774 {38400000, REF_CLK_FREQ_38_4_MHZ},
7775 {52000000, REF_CLK_FREQ_52_MHZ},
7776 {0, REF_CLK_FREQ_INVAL},
7779 static enum ufs_ref_clk_freq
7780 ufs_get_bref_clk_from_hz(unsigned long freq)
7784 for (i = 0; ufs_ref_clk_freqs[i].freq_hz; i++)
7785 if (ufs_ref_clk_freqs[i].freq_hz == freq)
7786 return ufs_ref_clk_freqs[i].val;
7788 return REF_CLK_FREQ_INVAL;
7791 void ufshcd_parse_dev_ref_clk_freq(struct ufs_hba *hba, struct clk *refclk)
7795 freq = clk_get_rate(refclk);
7797 hba->dev_ref_clk_freq =
7798 ufs_get_bref_clk_from_hz(freq);
7800 if (hba->dev_ref_clk_freq == REF_CLK_FREQ_INVAL)
7802 "invalid ref_clk setting = %ld\n", freq);
7805 static int ufshcd_set_dev_ref_clk(struct ufs_hba *hba)
7809 u32 freq = hba->dev_ref_clk_freq;
7811 err = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
7812 QUERY_ATTR_IDN_REF_CLK_FREQ, 0, 0, &ref_clk);
7815 dev_err(hba->dev, "failed reading bRefClkFreq. err = %d\n",
7820 if (ref_clk == freq)
7821 goto out; /* nothing to update */
7823 err = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_WRITE_ATTR,
7824 QUERY_ATTR_IDN_REF_CLK_FREQ, 0, 0, &freq);
7827 dev_err(hba->dev, "bRefClkFreq setting to %lu Hz failed\n",
7828 ufs_ref_clk_freqs[freq].freq_hz);
7832 dev_dbg(hba->dev, "bRefClkFreq setting to %lu Hz succeeded\n",
7833 ufs_ref_clk_freqs[freq].freq_hz);
7839 static int ufshcd_device_params_init(struct ufs_hba *hba)
7844 /* Init device descriptor sizes */
7845 for (i = 0; i < QUERY_DESC_IDN_MAX; i++)
7846 hba->desc_size[i] = QUERY_DESC_MAX_SIZE;
7848 /* Init UFS geometry descriptor related parameters */
7849 ret = ufshcd_device_geo_params_init(hba);
7853 /* Check and apply UFS device quirks */
7854 ret = ufs_get_device_desc(hba);
7856 dev_err(hba->dev, "%s: Failed getting device info. err = %d\n",
7861 ufshcd_get_ref_clk_gating_wait(hba);
7863 if (!ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_READ_FLAG,
7864 QUERY_FLAG_IDN_PWR_ON_WPE, 0, &flag))
7865 hba->dev_info.f_power_on_wp_en = flag;
7867 /* Probe maximum power mode co-supported by both UFS host and device */
7868 if (ufshcd_get_max_pwr_mode(hba))
7870 "%s: Failed getting max supported power mode\n",
7877 * ufshcd_add_lus - probe and add UFS logical units
7878 * @hba: per-adapter instance
7880 static int ufshcd_add_lus(struct ufs_hba *hba)
7884 /* Add required well known logical units to scsi mid layer */
7885 ret = ufshcd_scsi_add_wlus(hba);
7889 ufshcd_clear_ua_wluns(hba);
7891 /* Initialize devfreq after UFS device is detected */
7892 if (ufshcd_is_clkscaling_supported(hba)) {
7893 memcpy(&hba->clk_scaling.saved_pwr_info.info,
7895 sizeof(struct ufs_pa_layer_attr));
7896 hba->clk_scaling.saved_pwr_info.is_valid = true;
7897 hba->clk_scaling.is_allowed = true;
7899 ret = ufshcd_devfreq_init(hba);
7903 hba->clk_scaling.is_enabled = true;
7904 ufshcd_init_clk_scaling_sysfs(hba);
7909 scsi_scan_host(hba->host);
7910 pm_runtime_put_sync(hba->dev);
7916 static void ufshcd_request_sense_done(struct request *rq, blk_status_t error)
7918 if (error != BLK_STS_OK)
7919 pr_err("%s: REQUEST SENSE failed (%d)", __func__, error);
7920 blk_put_request(rq);
7924 ufshcd_request_sense_async(struct ufs_hba *hba, struct scsi_device *sdev)
7927 * From SPC-6: the REQUEST SENSE command with any allocation length
7928 * clears the sense data.
7930 static const u8 cmd[6] = {REQUEST_SENSE, 0, 0, 0, 0, 0};
7931 struct scsi_request *rq;
7932 struct request *req;
7934 req = blk_get_request(sdev->request_queue, REQ_OP_DRV_IN, /*flags=*/0);
7936 return PTR_ERR(req);
7939 rq->cmd_len = ARRAY_SIZE(cmd);
7940 memcpy(rq->cmd, cmd, rq->cmd_len);
7942 req->timeout = 1 * HZ;
7943 req->rq_flags |= RQF_PM | RQF_QUIET;
7945 blk_execute_rq_nowait(/*bd_disk=*/NULL, req, /*at_head=*/true,
7946 ufshcd_request_sense_done);
7950 static int ufshcd_clear_ua_wlun(struct ufs_hba *hba, u8 wlun)
7952 struct scsi_device *sdp;
7953 unsigned long flags;
7956 spin_lock_irqsave(hba->host->host_lock, flags);
7957 if (wlun == UFS_UPIU_UFS_DEVICE_WLUN)
7958 sdp = hba->sdev_ufs_device;
7959 else if (wlun == UFS_UPIU_RPMB_WLUN)
7960 sdp = hba->sdev_rpmb;
7964 ret = scsi_device_get(sdp);
7965 if (!ret && !scsi_device_online(sdp)) {
7967 scsi_device_put(sdp);
7972 spin_unlock_irqrestore(hba->host->host_lock, flags);
7976 ret = ufshcd_request_sense_async(hba, sdp);
7977 scsi_device_put(sdp);
7980 dev_err(hba->dev, "%s: UAC clear LU=%x ret = %d\n",
7981 __func__, wlun, ret);
7985 static int ufshcd_clear_ua_wluns(struct ufs_hba *hba)
7989 if (!hba->wlun_dev_clr_ua)
7992 ret = ufshcd_clear_ua_wlun(hba, UFS_UPIU_UFS_DEVICE_WLUN);
7994 ret = ufshcd_clear_ua_wlun(hba, UFS_UPIU_RPMB_WLUN);
7996 hba->wlun_dev_clr_ua = false;
7999 dev_err(hba->dev, "%s: Failed to clear UAC WLUNS ret = %d\n",
8005 * ufshcd_probe_hba - probe hba to detect device and initialize it
8006 * @hba: per-adapter instance
8007 * @init_dev_params: whether or not to call ufshcd_device_params_init().
8009 * Execute link-startup and verify device initialization
8011 static int ufshcd_probe_hba(struct ufs_hba *hba, bool init_dev_params)
8014 unsigned long flags;
8015 ktime_t start = ktime_get();
8017 hba->ufshcd_state = UFSHCD_STATE_RESET;
8019 ret = ufshcd_link_startup(hba);
8023 /* Debug counters initialization */
8024 ufshcd_clear_dbg_ufs_stats(hba);
8026 /* UniPro link is active now */
8027 ufshcd_set_link_active(hba);
8029 /* Verify device initialization by sending NOP OUT UPIU */
8030 ret = ufshcd_verify_dev_init(hba);
8034 /* Initiate UFS initialization, and waiting until completion */
8035 ret = ufshcd_complete_dev_init(hba);
8040 * Initialize UFS device parameters used by driver, these
8041 * parameters are associated with UFS descriptors.
8043 if (init_dev_params) {
8044 ret = ufshcd_device_params_init(hba);
8049 ufshcd_tune_unipro_params(hba);
8051 /* UFS device is also active now */
8052 ufshcd_set_ufs_dev_active(hba);
8053 ufshcd_force_reset_auto_bkops(hba);
8054 hba->wlun_dev_clr_ua = true;
8055 hba->wlun_rpmb_clr_ua = true;
8057 /* Gear up to HS gear if supported */
8058 if (hba->max_pwr_info.is_valid) {
8060 * Set the right value to bRefClkFreq before attempting to
8061 * switch to HS gears.
8063 if (hba->dev_ref_clk_freq != REF_CLK_FREQ_INVAL)
8064 ufshcd_set_dev_ref_clk(hba);
8065 ret = ufshcd_config_pwr_mode(hba, &hba->max_pwr_info.info);
8067 dev_err(hba->dev, "%s: Failed setting power mode, err = %d\n",
8071 ufshcd_print_pwr_info(hba);
8075 * bActiveICCLevel is volatile for UFS device (as per latest v2.1 spec)
8076 * and for removable UFS card as well, hence always set the parameter.
8077 * Note: Error handler may issue the device reset hence resetting
8078 * bActiveICCLevel as well so it is always safe to set this here.
8080 ufshcd_set_active_icc_lvl(hba);
8082 ufshcd_wb_config(hba);
8083 if (hba->ee_usr_mask)
8084 ufshcd_write_ee_control(hba);
8085 /* Enable Auto-Hibernate if configured */
8086 ufshcd_auto_hibern8_enable(hba);
8090 spin_lock_irqsave(hba->host->host_lock, flags);
8092 hba->ufshcd_state = UFSHCD_STATE_ERROR;
8093 else if (hba->ufshcd_state == UFSHCD_STATE_RESET)
8094 hba->ufshcd_state = UFSHCD_STATE_OPERATIONAL;
8095 spin_unlock_irqrestore(hba->host->host_lock, flags);
8097 trace_ufshcd_init(dev_name(hba->dev), ret,
8098 ktime_to_us(ktime_sub(ktime_get(), start)),
8099 hba->curr_dev_pwr_mode, hba->uic_link_state);
8104 * ufshcd_async_scan - asynchronous execution for probing hba
8105 * @data: data pointer to pass to this function
8106 * @cookie: cookie data
8108 static void ufshcd_async_scan(void *data, async_cookie_t cookie)
8110 struct ufs_hba *hba = (struct ufs_hba *)data;
8113 down(&hba->host_sem);
8114 /* Initialize hba, detect and initialize UFS device */
8115 ret = ufshcd_probe_hba(hba, true);
8120 /* Probe and add UFS logical units */
8121 ret = ufshcd_add_lus(hba);
8124 * If we failed to initialize the device or the device is not
8125 * present, turn off the power/clocks etc.
8128 pm_runtime_put_sync(hba->dev);
8129 ufshcd_hba_exit(hba);
8133 static const struct attribute_group *ufshcd_driver_groups[] = {
8134 &ufs_sysfs_unit_descriptor_group,
8135 &ufs_sysfs_lun_attributes_group,
8136 #ifdef CONFIG_SCSI_UFS_HPB
8137 &ufs_sysfs_hpb_stat_group,
8138 &ufs_sysfs_hpb_param_group,
8143 static struct ufs_hba_variant_params ufs_hba_vps = {
8144 .hba_enable_delay_us = 1000,
8145 .wb_flush_threshold = UFS_WB_BUF_REMAIN_PERCENT(40),
8146 .devfreq_profile.polling_ms = 100,
8147 .devfreq_profile.target = ufshcd_devfreq_target,
8148 .devfreq_profile.get_dev_status = ufshcd_devfreq_get_dev_status,
8149 .ondemand_data.upthreshold = 70,
8150 .ondemand_data.downdifferential = 5,
8153 static struct scsi_host_template ufshcd_driver_template = {
8154 .module = THIS_MODULE,
8156 .proc_name = UFSHCD,
8157 .queuecommand = ufshcd_queuecommand,
8158 .slave_alloc = ufshcd_slave_alloc,
8159 .slave_configure = ufshcd_slave_configure,
8160 .slave_destroy = ufshcd_slave_destroy,
8161 .change_queue_depth = ufshcd_change_queue_depth,
8162 .eh_abort_handler = ufshcd_abort,
8163 .eh_device_reset_handler = ufshcd_eh_device_reset_handler,
8164 .eh_host_reset_handler = ufshcd_eh_host_reset_handler,
8166 .sg_tablesize = SG_ALL,
8167 .cmd_per_lun = UFSHCD_CMD_PER_LUN,
8168 .can_queue = UFSHCD_CAN_QUEUE,
8169 .max_segment_size = PRDT_DATA_BYTE_COUNT_MAX,
8170 .max_host_blocked = 1,
8171 .track_queue_depth = 1,
8172 .sdev_groups = ufshcd_driver_groups,
8173 .dma_boundary = PAGE_SIZE - 1,
8174 .rpm_autosuspend_delay = RPM_AUTOSUSPEND_DELAY_MS,
8177 static int ufshcd_config_vreg_load(struct device *dev, struct ufs_vreg *vreg,
8186 * "set_load" operation shall be required on those regulators
8187 * which specifically configured current limitation. Otherwise
8188 * zero max_uA may cause unexpected behavior when regulator is
8189 * enabled or set as high power mode.
8194 ret = regulator_set_load(vreg->reg, ua);
8196 dev_err(dev, "%s: %s set load (ua=%d) failed, err=%d\n",
8197 __func__, vreg->name, ua, ret);
8203 static inline int ufshcd_config_vreg_lpm(struct ufs_hba *hba,
8204 struct ufs_vreg *vreg)
8206 return ufshcd_config_vreg_load(hba->dev, vreg, UFS_VREG_LPM_LOAD_UA);
8209 static inline int ufshcd_config_vreg_hpm(struct ufs_hba *hba,
8210 struct ufs_vreg *vreg)
8215 return ufshcd_config_vreg_load(hba->dev, vreg, vreg->max_uA);
8218 static int ufshcd_config_vreg(struct device *dev,
8219 struct ufs_vreg *vreg, bool on)
8222 struct regulator *reg;
8224 int min_uV, uA_load;
8231 if (regulator_count_voltages(reg) > 0) {
8232 uA_load = on ? vreg->max_uA : 0;
8233 ret = ufshcd_config_vreg_load(dev, vreg, uA_load);
8237 if (vreg->min_uV && vreg->max_uV) {
8238 min_uV = on ? vreg->min_uV : 0;
8239 ret = regulator_set_voltage(reg, min_uV, vreg->max_uV);
8242 "%s: %s set voltage failed, err=%d\n",
8243 __func__, name, ret);
8250 static int ufshcd_enable_vreg(struct device *dev, struct ufs_vreg *vreg)
8254 if (!vreg || vreg->enabled)
8257 ret = ufshcd_config_vreg(dev, vreg, true);
8259 ret = regulator_enable(vreg->reg);
8262 vreg->enabled = true;
8264 dev_err(dev, "%s: %s enable failed, err=%d\n",
8265 __func__, vreg->name, ret);
8270 static int ufshcd_disable_vreg(struct device *dev, struct ufs_vreg *vreg)
8274 if (!vreg || !vreg->enabled || vreg->always_on)
8277 ret = regulator_disable(vreg->reg);
8280 /* ignore errors on applying disable config */
8281 ufshcd_config_vreg(dev, vreg, false);
8282 vreg->enabled = false;
8284 dev_err(dev, "%s: %s disable failed, err=%d\n",
8285 __func__, vreg->name, ret);
8291 static int ufshcd_setup_vreg(struct ufs_hba *hba, bool on)
8294 struct device *dev = hba->dev;
8295 struct ufs_vreg_info *info = &hba->vreg_info;
8297 ret = ufshcd_toggle_vreg(dev, info->vcc, on);
8301 ret = ufshcd_toggle_vreg(dev, info->vccq, on);
8305 ret = ufshcd_toggle_vreg(dev, info->vccq2, on);
8309 ufshcd_toggle_vreg(dev, info->vccq2, false);
8310 ufshcd_toggle_vreg(dev, info->vccq, false);
8311 ufshcd_toggle_vreg(dev, info->vcc, false);
8316 static int ufshcd_setup_hba_vreg(struct ufs_hba *hba, bool on)
8318 struct ufs_vreg_info *info = &hba->vreg_info;
8320 return ufshcd_toggle_vreg(hba->dev, info->vdd_hba, on);
8323 static int ufshcd_get_vreg(struct device *dev, struct ufs_vreg *vreg)
8330 vreg->reg = devm_regulator_get(dev, vreg->name);
8331 if (IS_ERR(vreg->reg)) {
8332 ret = PTR_ERR(vreg->reg);
8333 dev_err(dev, "%s: %s get failed, err=%d\n",
8334 __func__, vreg->name, ret);
8340 static int ufshcd_init_vreg(struct ufs_hba *hba)
8343 struct device *dev = hba->dev;
8344 struct ufs_vreg_info *info = &hba->vreg_info;
8346 ret = ufshcd_get_vreg(dev, info->vcc);
8350 ret = ufshcd_get_vreg(dev, info->vccq);
8352 ret = ufshcd_get_vreg(dev, info->vccq2);
8357 static int ufshcd_init_hba_vreg(struct ufs_hba *hba)
8359 struct ufs_vreg_info *info = &hba->vreg_info;
8362 return ufshcd_get_vreg(hba->dev, info->vdd_hba);
8367 static int ufshcd_setup_clocks(struct ufs_hba *hba, bool on)
8370 struct ufs_clk_info *clki;
8371 struct list_head *head = &hba->clk_list_head;
8372 unsigned long flags;
8373 ktime_t start = ktime_get();
8374 bool clk_state_changed = false;
8376 if (list_empty(head))
8379 ret = ufshcd_vops_setup_clocks(hba, on, PRE_CHANGE);
8383 list_for_each_entry(clki, head, list) {
8384 if (!IS_ERR_OR_NULL(clki->clk)) {
8386 * Don't disable clocks which are needed
8387 * to keep the link active.
8389 if (ufshcd_is_link_active(hba) &&
8390 clki->keep_link_active)
8393 clk_state_changed = on ^ clki->enabled;
8394 if (on && !clki->enabled) {
8395 ret = clk_prepare_enable(clki->clk);
8397 dev_err(hba->dev, "%s: %s prepare enable failed, %d\n",
8398 __func__, clki->name, ret);
8401 } else if (!on && clki->enabled) {
8402 clk_disable_unprepare(clki->clk);
8405 dev_dbg(hba->dev, "%s: clk: %s %sabled\n", __func__,
8406 clki->name, on ? "en" : "dis");
8410 ret = ufshcd_vops_setup_clocks(hba, on, POST_CHANGE);
8416 list_for_each_entry(clki, head, list) {
8417 if (!IS_ERR_OR_NULL(clki->clk) && clki->enabled)
8418 clk_disable_unprepare(clki->clk);
8420 } else if (!ret && on) {
8421 spin_lock_irqsave(hba->host->host_lock, flags);
8422 hba->clk_gating.state = CLKS_ON;
8423 trace_ufshcd_clk_gating(dev_name(hba->dev),
8424 hba->clk_gating.state);
8425 spin_unlock_irqrestore(hba->host->host_lock, flags);
8428 if (clk_state_changed)
8429 trace_ufshcd_profile_clk_gating(dev_name(hba->dev),
8430 (on ? "on" : "off"),
8431 ktime_to_us(ktime_sub(ktime_get(), start)), ret);
8435 static int ufshcd_init_clocks(struct ufs_hba *hba)
8438 struct ufs_clk_info *clki;
8439 struct device *dev = hba->dev;
8440 struct list_head *head = &hba->clk_list_head;
8442 if (list_empty(head))
8445 list_for_each_entry(clki, head, list) {
8449 clki->clk = devm_clk_get(dev, clki->name);
8450 if (IS_ERR(clki->clk)) {
8451 ret = PTR_ERR(clki->clk);
8452 dev_err(dev, "%s: %s clk get failed, %d\n",
8453 __func__, clki->name, ret);
8458 * Parse device ref clk freq as per device tree "ref_clk".
8459 * Default dev_ref_clk_freq is set to REF_CLK_FREQ_INVAL
8460 * in ufshcd_alloc_host().
8462 if (!strcmp(clki->name, "ref_clk"))
8463 ufshcd_parse_dev_ref_clk_freq(hba, clki->clk);
8465 if (clki->max_freq) {
8466 ret = clk_set_rate(clki->clk, clki->max_freq);
8468 dev_err(hba->dev, "%s: %s clk set rate(%dHz) failed, %d\n",
8469 __func__, clki->name,
8470 clki->max_freq, ret);
8473 clki->curr_freq = clki->max_freq;
8475 dev_dbg(dev, "%s: clk: %s, rate: %lu\n", __func__,
8476 clki->name, clk_get_rate(clki->clk));
8482 static int ufshcd_variant_hba_init(struct ufs_hba *hba)
8489 err = ufshcd_vops_init(hba);
8491 dev_err(hba->dev, "%s: variant %s init failed err %d\n",
8492 __func__, ufshcd_get_var_name(hba), err);
8497 static void ufshcd_variant_hba_exit(struct ufs_hba *hba)
8502 ufshcd_vops_exit(hba);
8505 static int ufshcd_hba_init(struct ufs_hba *hba)
8510 * Handle host controller power separately from the UFS device power
8511 * rails as it will help controlling the UFS host controller power
8512 * collapse easily which is different than UFS device power collapse.
8513 * Also, enable the host controller power before we go ahead with rest
8514 * of the initialization here.
8516 err = ufshcd_init_hba_vreg(hba);
8520 err = ufshcd_setup_hba_vreg(hba, true);
8524 err = ufshcd_init_clocks(hba);
8526 goto out_disable_hba_vreg;
8528 err = ufshcd_setup_clocks(hba, true);
8530 goto out_disable_hba_vreg;
8532 err = ufshcd_init_vreg(hba);
8534 goto out_disable_clks;
8536 err = ufshcd_setup_vreg(hba, true);
8538 goto out_disable_clks;
8540 err = ufshcd_variant_hba_init(hba);
8542 goto out_disable_vreg;
8544 ufs_debugfs_hba_init(hba);
8546 hba->is_powered = true;
8550 ufshcd_setup_vreg(hba, false);
8552 ufshcd_setup_clocks(hba, false);
8553 out_disable_hba_vreg:
8554 ufshcd_setup_hba_vreg(hba, false);
8559 static void ufshcd_hba_exit(struct ufs_hba *hba)
8561 if (hba->is_powered) {
8562 ufshcd_exit_clk_scaling(hba);
8563 ufshcd_exit_clk_gating(hba);
8564 ufs_debugfs_hba_exit(hba);
8565 ufshcd_variant_hba_exit(hba);
8566 ufshcd_setup_vreg(hba, false);
8567 ufshcd_setup_clocks(hba, false);
8568 ufshcd_setup_hba_vreg(hba, false);
8569 hba->is_powered = false;
8570 ufs_put_device_desc(hba);
8575 * ufshcd_set_dev_pwr_mode - sends START STOP UNIT command to set device
8577 * @hba: per adapter instance
8578 * @pwr_mode: device power mode to set
8580 * Returns 0 if requested power mode is set successfully
8581 * Returns non-zero if failed to set the requested power mode
8583 static int ufshcd_set_dev_pwr_mode(struct ufs_hba *hba,
8584 enum ufs_dev_pwr_mode pwr_mode)
8586 unsigned char cmd[6] = { START_STOP };
8587 struct scsi_sense_hdr sshdr;
8588 struct scsi_device *sdp;
8589 unsigned long flags;
8592 spin_lock_irqsave(hba->host->host_lock, flags);
8593 sdp = hba->sdev_ufs_device;
8595 ret = scsi_device_get(sdp);
8596 if (!ret && !scsi_device_online(sdp)) {
8598 scsi_device_put(sdp);
8603 spin_unlock_irqrestore(hba->host->host_lock, flags);
8609 * If scsi commands fail, the scsi mid-layer schedules scsi error-
8610 * handling, which would wait for host to be resumed. Since we know
8611 * we are functional while we are here, skip host resume in error
8614 hba->host->eh_noresume = 1;
8615 if (hba->wlun_dev_clr_ua)
8616 ufshcd_clear_ua_wlun(hba, UFS_UPIU_UFS_DEVICE_WLUN);
8618 cmd[4] = pwr_mode << 4;
8621 * Current function would be generally called from the power management
8622 * callbacks hence set the RQF_PM flag so that it doesn't resume the
8623 * already suspended childs.
8625 ret = scsi_execute(sdp, cmd, DMA_NONE, NULL, 0, NULL, &sshdr,
8626 START_STOP_TIMEOUT, 0, 0, RQF_PM, NULL);
8628 sdev_printk(KERN_WARNING, sdp,
8629 "START_STOP failed for power mode: %d, result %x\n",
8631 if (ret > 0 && scsi_sense_valid(&sshdr))
8632 scsi_print_sense_hdr(sdp, NULL, &sshdr);
8636 hba->curr_dev_pwr_mode = pwr_mode;
8638 scsi_device_put(sdp);
8639 hba->host->eh_noresume = 0;
8643 static int ufshcd_link_state_transition(struct ufs_hba *hba,
8644 enum uic_link_state req_link_state,
8645 int check_for_bkops)
8649 if (req_link_state == hba->uic_link_state)
8652 if (req_link_state == UIC_LINK_HIBERN8_STATE) {
8653 ret = ufshcd_uic_hibern8_enter(hba);
8655 ufshcd_set_link_hibern8(hba);
8657 dev_err(hba->dev, "%s: hibern8 enter failed %d\n",
8663 * If autobkops is enabled, link can't be turned off because
8664 * turning off the link would also turn off the device, except in the
8665 * case of DeepSleep where the device is expected to remain powered.
8667 else if ((req_link_state == UIC_LINK_OFF_STATE) &&
8668 (!check_for_bkops || !hba->auto_bkops_enabled)) {
8670 * Let's make sure that link is in low power mode, we are doing
8671 * this currently by putting the link in Hibern8. Otherway to
8672 * put the link in low power mode is to send the DME end point
8673 * to device and then send the DME reset command to local
8674 * unipro. But putting the link in hibern8 is much faster.
8676 * Note also that putting the link in Hibern8 is a requirement
8677 * for entering DeepSleep.
8679 ret = ufshcd_uic_hibern8_enter(hba);
8681 dev_err(hba->dev, "%s: hibern8 enter failed %d\n",
8686 * Change controller state to "reset state" which
8687 * should also put the link in off/reset state
8689 ufshcd_hba_stop(hba);
8691 * TODO: Check if we need any delay to make sure that
8692 * controller is reset
8694 ufshcd_set_link_off(hba);
8701 static void ufshcd_vreg_set_lpm(struct ufs_hba *hba)
8703 bool vcc_off = false;
8706 * It seems some UFS devices may keep drawing more than sleep current
8707 * (atleast for 500us) from UFS rails (especially from VCCQ rail).
8708 * To avoid this situation, add 2ms delay before putting these UFS
8709 * rails in LPM mode.
8711 if (!ufshcd_is_link_active(hba) &&
8712 hba->dev_quirks & UFS_DEVICE_QUIRK_DELAY_BEFORE_LPM)
8713 usleep_range(2000, 2100);
8716 * If UFS device is either in UFS_Sleep turn off VCC rail to save some
8719 * If UFS device and link is in OFF state, all power supplies (VCC,
8720 * VCCQ, VCCQ2) can be turned off if power on write protect is not
8721 * required. If UFS link is inactive (Hibern8 or OFF state) and device
8722 * is in sleep state, put VCCQ & VCCQ2 rails in LPM mode.
8724 * Ignore the error returned by ufshcd_toggle_vreg() as device is anyway
8725 * in low power state which would save some power.
8727 * If Write Booster is enabled and the device needs to flush the WB
8728 * buffer OR if bkops status is urgent for WB, keep Vcc on.
8730 if (ufshcd_is_ufs_dev_poweroff(hba) && ufshcd_is_link_off(hba) &&
8731 !hba->dev_info.is_lu_power_on_wp) {
8732 ufshcd_setup_vreg(hba, false);
8734 } else if (!ufshcd_is_ufs_dev_active(hba)) {
8735 ufshcd_toggle_vreg(hba->dev, hba->vreg_info.vcc, false);
8737 if (ufshcd_is_link_hibern8(hba) || ufshcd_is_link_off(hba)) {
8738 ufshcd_config_vreg_lpm(hba, hba->vreg_info.vccq);
8739 ufshcd_config_vreg_lpm(hba, hba->vreg_info.vccq2);
8744 * Some UFS devices require delay after VCC power rail is turned-off.
8746 if (vcc_off && hba->vreg_info.vcc &&
8747 hba->dev_quirks & UFS_DEVICE_QUIRK_DELAY_AFTER_LPM)
8748 usleep_range(5000, 5100);
8752 static int ufshcd_vreg_set_hpm(struct ufs_hba *hba)
8756 if (ufshcd_is_ufs_dev_poweroff(hba) && ufshcd_is_link_off(hba) &&
8757 !hba->dev_info.is_lu_power_on_wp) {
8758 ret = ufshcd_setup_vreg(hba, true);
8759 } else if (!ufshcd_is_ufs_dev_active(hba)) {
8760 if (!ufshcd_is_link_active(hba)) {
8761 ret = ufshcd_config_vreg_hpm(hba, hba->vreg_info.vccq);
8764 ret = ufshcd_config_vreg_hpm(hba, hba->vreg_info.vccq2);
8768 ret = ufshcd_toggle_vreg(hba->dev, hba->vreg_info.vcc, true);
8773 ufshcd_config_vreg_lpm(hba, hba->vreg_info.vccq);
8775 ufshcd_toggle_vreg(hba->dev, hba->vreg_info.vcc, false);
8779 #endif /* CONFIG_PM */
8781 static void ufshcd_hba_vreg_set_lpm(struct ufs_hba *hba)
8783 if (ufshcd_is_link_off(hba) || ufshcd_can_aggressive_pc(hba))
8784 ufshcd_setup_hba_vreg(hba, false);
8787 static void ufshcd_hba_vreg_set_hpm(struct ufs_hba *hba)
8789 if (ufshcd_is_link_off(hba) || ufshcd_can_aggressive_pc(hba))
8790 ufshcd_setup_hba_vreg(hba, true);
8793 static int __ufshcd_wl_suspend(struct ufs_hba *hba, enum ufs_pm_op pm_op)
8796 int check_for_bkops;
8797 enum ufs_pm_level pm_lvl;
8798 enum ufs_dev_pwr_mode req_dev_pwr_mode;
8799 enum uic_link_state req_link_state;
8801 hba->pm_op_in_progress = true;
8802 if (pm_op != UFS_SHUTDOWN_PM) {
8803 pm_lvl = pm_op == UFS_RUNTIME_PM ?
8804 hba->rpm_lvl : hba->spm_lvl;
8805 req_dev_pwr_mode = ufs_get_pm_lvl_to_dev_pwr_mode(pm_lvl);
8806 req_link_state = ufs_get_pm_lvl_to_link_pwr_state(pm_lvl);
8808 req_dev_pwr_mode = UFS_POWERDOWN_PWR_MODE;
8809 req_link_state = UIC_LINK_OFF_STATE;
8812 ufshpb_suspend(hba);
8815 * If we can't transition into any of the low power modes
8816 * just gate the clocks.
8818 ufshcd_hold(hba, false);
8819 hba->clk_gating.is_suspended = true;
8821 if (ufshcd_is_clkscaling_supported(hba))
8822 ufshcd_clk_scaling_suspend(hba, true);
8824 if (req_dev_pwr_mode == UFS_ACTIVE_PWR_MODE &&
8825 req_link_state == UIC_LINK_ACTIVE_STATE) {
8829 if ((req_dev_pwr_mode == hba->curr_dev_pwr_mode) &&
8830 (req_link_state == hba->uic_link_state))
8831 goto enable_scaling;
8833 /* UFS device & link must be active before we enter in this function */
8834 if (!ufshcd_is_ufs_dev_active(hba) || !ufshcd_is_link_active(hba)) {
8836 goto enable_scaling;
8839 if (pm_op == UFS_RUNTIME_PM) {
8840 if (ufshcd_can_autobkops_during_suspend(hba)) {
8842 * The device is idle with no requests in the queue,
8843 * allow background operations if bkops status shows
8844 * that performance might be impacted.
8846 ret = ufshcd_urgent_bkops(hba);
8848 goto enable_scaling;
8850 /* make sure that auto bkops is disabled */
8851 ufshcd_disable_auto_bkops(hba);
8854 * If device needs to do BKOP or WB buffer flush during
8855 * Hibern8, keep device power mode as "active power mode"
8858 hba->dev_info.b_rpm_dev_flush_capable =
8859 hba->auto_bkops_enabled ||
8860 (((req_link_state == UIC_LINK_HIBERN8_STATE) ||
8861 ((req_link_state == UIC_LINK_ACTIVE_STATE) &&
8862 ufshcd_is_auto_hibern8_enabled(hba))) &&
8863 ufshcd_wb_need_flush(hba));
8866 flush_work(&hba->eeh_work);
8868 if (req_dev_pwr_mode != hba->curr_dev_pwr_mode) {
8869 if (pm_op != UFS_RUNTIME_PM)
8870 /* ensure that bkops is disabled */
8871 ufshcd_disable_auto_bkops(hba);
8873 if (!hba->dev_info.b_rpm_dev_flush_capable) {
8874 ret = ufshcd_set_dev_pwr_mode(hba, req_dev_pwr_mode);
8876 goto enable_scaling;
8881 * In the case of DeepSleep, the device is expected to remain powered
8882 * with the link off, so do not check for bkops.
8884 check_for_bkops = !ufshcd_is_ufs_dev_deepsleep(hba);
8885 ret = ufshcd_link_state_transition(hba, req_link_state, check_for_bkops);
8887 goto set_dev_active;
8891 * Call vendor specific suspend callback. As these callbacks may access
8892 * vendor specific host controller register space call them before the
8893 * host clocks are ON.
8895 ret = ufshcd_vops_suspend(hba, pm_op);
8897 goto set_link_active;
8902 * Device hardware reset is required to exit DeepSleep. Also, for
8903 * DeepSleep, the link is off so host reset and restore will be done
8906 if (ufshcd_is_ufs_dev_deepsleep(hba)) {
8907 ufshcd_device_reset(hba);
8908 WARN_ON(!ufshcd_is_link_off(hba));
8910 if (ufshcd_is_link_hibern8(hba) && !ufshcd_uic_hibern8_exit(hba))
8911 ufshcd_set_link_active(hba);
8912 else if (ufshcd_is_link_off(hba))
8913 ufshcd_host_reset_and_restore(hba);
8915 /* Can also get here needing to exit DeepSleep */
8916 if (ufshcd_is_ufs_dev_deepsleep(hba)) {
8917 ufshcd_device_reset(hba);
8918 ufshcd_host_reset_and_restore(hba);
8920 if (!ufshcd_set_dev_pwr_mode(hba, UFS_ACTIVE_PWR_MODE))
8921 ufshcd_disable_auto_bkops(hba);
8923 if (ufshcd_is_clkscaling_supported(hba))
8924 ufshcd_clk_scaling_suspend(hba, false);
8926 hba->dev_info.b_rpm_dev_flush_capable = false;
8928 if (hba->dev_info.b_rpm_dev_flush_capable) {
8929 schedule_delayed_work(&hba->rpm_dev_flush_recheck_work,
8930 msecs_to_jiffies(RPM_DEV_FLUSH_RECHECK_WORK_DELAY_MS));
8934 ufshcd_update_evt_hist(hba, UFS_EVT_WL_SUSP_ERR, (u32)ret);
8935 hba->clk_gating.is_suspended = false;
8936 ufshcd_release(hba);
8939 hba->pm_op_in_progress = false;
8944 static int __ufshcd_wl_resume(struct ufs_hba *hba, enum ufs_pm_op pm_op)
8947 enum uic_link_state old_link_state = hba->uic_link_state;
8949 hba->pm_op_in_progress = true;
8952 * Call vendor specific resume callback. As these callbacks may access
8953 * vendor specific host controller register space call them when the
8954 * host clocks are ON.
8956 ret = ufshcd_vops_resume(hba, pm_op);
8960 /* For DeepSleep, the only supported option is to have the link off */
8961 WARN_ON(ufshcd_is_ufs_dev_deepsleep(hba) && !ufshcd_is_link_off(hba));
8963 if (ufshcd_is_link_hibern8(hba)) {
8964 ret = ufshcd_uic_hibern8_exit(hba);
8966 ufshcd_set_link_active(hba);
8968 dev_err(hba->dev, "%s: hibern8 exit failed %d\n",
8970 goto vendor_suspend;
8972 } else if (ufshcd_is_link_off(hba)) {
8974 * A full initialization of the host and the device is
8975 * required since the link was put to off during suspend.
8976 * Note, in the case of DeepSleep, the device will exit
8977 * DeepSleep due to device reset.
8979 ret = ufshcd_reset_and_restore(hba);
8981 * ufshcd_reset_and_restore() should have already
8982 * set the link state as active
8984 if (ret || !ufshcd_is_link_active(hba))
8985 goto vendor_suspend;
8988 if (!ufshcd_is_ufs_dev_active(hba)) {
8989 ret = ufshcd_set_dev_pwr_mode(hba, UFS_ACTIVE_PWR_MODE);
8991 goto set_old_link_state;
8994 if (ufshcd_keep_autobkops_enabled_except_suspend(hba))
8995 ufshcd_enable_auto_bkops(hba);
8998 * If BKOPs operations are urgently needed at this moment then
8999 * keep auto-bkops enabled or else disable it.
9001 ufshcd_urgent_bkops(hba);
9003 if (hba->ee_usr_mask)
9004 ufshcd_write_ee_control(hba);
9006 if (ufshcd_is_clkscaling_supported(hba))
9007 ufshcd_clk_scaling_suspend(hba, false);
9009 if (hba->dev_info.b_rpm_dev_flush_capable) {
9010 hba->dev_info.b_rpm_dev_flush_capable = false;
9011 cancel_delayed_work(&hba->rpm_dev_flush_recheck_work);
9014 /* Enable Auto-Hibernate if configured */
9015 ufshcd_auto_hibern8_enable(hba);
9021 ufshcd_link_state_transition(hba, old_link_state, 0);
9023 ufshcd_vops_suspend(hba, pm_op);
9026 ufshcd_update_evt_hist(hba, UFS_EVT_WL_RES_ERR, (u32)ret);
9027 hba->clk_gating.is_suspended = false;
9028 ufshcd_release(hba);
9029 hba->pm_op_in_progress = false;
9033 static int ufshcd_wl_runtime_suspend(struct device *dev)
9035 struct scsi_device *sdev = to_scsi_device(dev);
9036 struct ufs_hba *hba;
9038 ktime_t start = ktime_get();
9040 hba = shost_priv(sdev->host);
9042 ret = __ufshcd_wl_suspend(hba, UFS_RUNTIME_PM);
9044 dev_err(&sdev->sdev_gendev, "%s failed: %d\n", __func__, ret);
9046 trace_ufshcd_wl_runtime_suspend(dev_name(dev), ret,
9047 ktime_to_us(ktime_sub(ktime_get(), start)),
9048 hba->curr_dev_pwr_mode, hba->uic_link_state);
9053 static int ufshcd_wl_runtime_resume(struct device *dev)
9055 struct scsi_device *sdev = to_scsi_device(dev);
9056 struct ufs_hba *hba;
9058 ktime_t start = ktime_get();
9060 hba = shost_priv(sdev->host);
9062 ret = __ufshcd_wl_resume(hba, UFS_RUNTIME_PM);
9064 dev_err(&sdev->sdev_gendev, "%s failed: %d\n", __func__, ret);
9066 trace_ufshcd_wl_runtime_resume(dev_name(dev), ret,
9067 ktime_to_us(ktime_sub(ktime_get(), start)),
9068 hba->curr_dev_pwr_mode, hba->uic_link_state);
9074 #ifdef CONFIG_PM_SLEEP
9075 static int ufshcd_wl_suspend(struct device *dev)
9077 struct scsi_device *sdev = to_scsi_device(dev);
9078 struct ufs_hba *hba;
9080 ktime_t start = ktime_get();
9082 hba = shost_priv(sdev->host);
9083 down(&hba->host_sem);
9085 if (pm_runtime_suspended(dev))
9088 ret = __ufshcd_wl_suspend(hba, UFS_SYSTEM_PM);
9090 dev_err(&sdev->sdev_gendev, "%s failed: %d\n", __func__, ret);
9096 hba->is_sys_suspended = true;
9097 trace_ufshcd_wl_suspend(dev_name(dev), ret,
9098 ktime_to_us(ktime_sub(ktime_get(), start)),
9099 hba->curr_dev_pwr_mode, hba->uic_link_state);
9104 static int ufshcd_wl_resume(struct device *dev)
9106 struct scsi_device *sdev = to_scsi_device(dev);
9107 struct ufs_hba *hba;
9109 ktime_t start = ktime_get();
9111 hba = shost_priv(sdev->host);
9113 if (pm_runtime_suspended(dev))
9116 ret = __ufshcd_wl_resume(hba, UFS_SYSTEM_PM);
9118 dev_err(&sdev->sdev_gendev, "%s failed: %d\n", __func__, ret);
9120 trace_ufshcd_wl_resume(dev_name(dev), ret,
9121 ktime_to_us(ktime_sub(ktime_get(), start)),
9122 hba->curr_dev_pwr_mode, hba->uic_link_state);
9124 hba->is_sys_suspended = false;
9130 static void ufshcd_wl_shutdown(struct device *dev)
9132 struct scsi_device *sdev = to_scsi_device(dev);
9133 struct ufs_hba *hba;
9135 hba = shost_priv(sdev->host);
9137 down(&hba->host_sem);
9138 hba->shutting_down = true;
9141 /* Turn on everything while shutting down */
9142 ufshcd_rpm_get_sync(hba);
9143 scsi_device_quiesce(sdev);
9144 shost_for_each_device(sdev, hba->host) {
9145 if (sdev == hba->sdev_ufs_device)
9147 scsi_device_quiesce(sdev);
9149 __ufshcd_wl_suspend(hba, UFS_SHUTDOWN_PM);
9153 * ufshcd_suspend - helper function for suspend operations
9154 * @hba: per adapter instance
9156 * This function will put disable irqs, turn off clocks
9157 * and set vreg and hba-vreg in lpm mode.
9159 static int ufshcd_suspend(struct ufs_hba *hba)
9163 if (!hba->is_powered)
9166 * Disable the host irq as host controller as there won't be any
9167 * host controller transaction expected till resume.
9169 ufshcd_disable_irq(hba);
9170 ret = ufshcd_setup_clocks(hba, false);
9172 ufshcd_enable_irq(hba);
9175 if (ufshcd_is_clkgating_allowed(hba)) {
9176 hba->clk_gating.state = CLKS_OFF;
9177 trace_ufshcd_clk_gating(dev_name(hba->dev),
9178 hba->clk_gating.state);
9181 ufshcd_vreg_set_lpm(hba);
9182 /* Put the host controller in low power mode if possible */
9183 ufshcd_hba_vreg_set_lpm(hba);
9189 * ufshcd_resume - helper function for resume operations
9190 * @hba: per adapter instance
9192 * This function basically turns on the regulators, clocks and
9195 * Returns 0 for success and non-zero for failure
9197 static int ufshcd_resume(struct ufs_hba *hba)
9201 if (!hba->is_powered)
9204 ufshcd_hba_vreg_set_hpm(hba);
9205 ret = ufshcd_vreg_set_hpm(hba);
9209 /* Make sure clocks are enabled before accessing controller */
9210 ret = ufshcd_setup_clocks(hba, true);
9214 /* enable the host irq as host controller would be active soon */
9215 ufshcd_enable_irq(hba);
9219 ufshcd_vreg_set_lpm(hba);
9222 ufshcd_update_evt_hist(hba, UFS_EVT_RESUME_ERR, (u32)ret);
9225 #endif /* CONFIG_PM */
9227 #ifdef CONFIG_PM_SLEEP
9229 * ufshcd_system_suspend - system suspend callback
9230 * @dev: Device associated with the UFS controller.
9232 * Executed before putting the system into a sleep state in which the contents
9233 * of main memory are preserved.
9235 * Returns 0 for success and non-zero for failure
9237 int ufshcd_system_suspend(struct device *dev)
9239 struct ufs_hba *hba = dev_get_drvdata(dev);
9241 ktime_t start = ktime_get();
9243 if (pm_runtime_suspended(hba->dev))
9246 ret = ufshcd_suspend(hba);
9248 trace_ufshcd_system_suspend(dev_name(hba->dev), ret,
9249 ktime_to_us(ktime_sub(ktime_get(), start)),
9250 hba->curr_dev_pwr_mode, hba->uic_link_state);
9253 EXPORT_SYMBOL(ufshcd_system_suspend);
9256 * ufshcd_system_resume - system resume callback
9257 * @dev: Device associated with the UFS controller.
9259 * Executed after waking the system up from a sleep state in which the contents
9260 * of main memory were preserved.
9262 * Returns 0 for success and non-zero for failure
9264 int ufshcd_system_resume(struct device *dev)
9266 struct ufs_hba *hba = dev_get_drvdata(dev);
9267 ktime_t start = ktime_get();
9270 if (pm_runtime_suspended(hba->dev))
9273 ret = ufshcd_resume(hba);
9276 trace_ufshcd_system_resume(dev_name(hba->dev), ret,
9277 ktime_to_us(ktime_sub(ktime_get(), start)),
9278 hba->curr_dev_pwr_mode, hba->uic_link_state);
9282 EXPORT_SYMBOL(ufshcd_system_resume);
9283 #endif /* CONFIG_PM_SLEEP */
9287 * ufshcd_runtime_suspend - runtime suspend callback
9288 * @dev: Device associated with the UFS controller.
9290 * Check the description of ufshcd_suspend() function for more details.
9292 * Returns 0 for success and non-zero for failure
9294 int ufshcd_runtime_suspend(struct device *dev)
9296 struct ufs_hba *hba = dev_get_drvdata(dev);
9298 ktime_t start = ktime_get();
9300 ret = ufshcd_suspend(hba);
9302 trace_ufshcd_runtime_suspend(dev_name(hba->dev), ret,
9303 ktime_to_us(ktime_sub(ktime_get(), start)),
9304 hba->curr_dev_pwr_mode, hba->uic_link_state);
9307 EXPORT_SYMBOL(ufshcd_runtime_suspend);
9310 * ufshcd_runtime_resume - runtime resume routine
9311 * @dev: Device associated with the UFS controller.
9313 * This function basically brings controller
9314 * to active state. Following operations are done in this function:
9316 * 1. Turn on all the controller related clocks
9317 * 2. Turn ON VCC rail
9319 int ufshcd_runtime_resume(struct device *dev)
9321 struct ufs_hba *hba = dev_get_drvdata(dev);
9323 ktime_t start = ktime_get();
9325 ret = ufshcd_resume(hba);
9327 trace_ufshcd_runtime_resume(dev_name(hba->dev), ret,
9328 ktime_to_us(ktime_sub(ktime_get(), start)),
9329 hba->curr_dev_pwr_mode, hba->uic_link_state);
9332 EXPORT_SYMBOL(ufshcd_runtime_resume);
9333 #endif /* CONFIG_PM */
9336 * ufshcd_shutdown - shutdown routine
9337 * @hba: per adapter instance
9339 * This function would turn off both UFS device and UFS hba
9340 * regulators. It would also disable clocks.
9342 * Returns 0 always to allow force shutdown even in case of errors.
9344 int ufshcd_shutdown(struct ufs_hba *hba)
9346 if (ufshcd_is_ufs_dev_poweroff(hba) && ufshcd_is_link_off(hba))
9349 pm_runtime_get_sync(hba->dev);
9351 ufshcd_suspend(hba);
9353 hba->is_powered = false;
9354 /* allow force shutdown even in case of errors */
9357 EXPORT_SYMBOL(ufshcd_shutdown);
9360 * ufshcd_remove - de-allocate SCSI host and host memory space
9361 * data structure memory
9362 * @hba: per adapter instance
9364 void ufshcd_remove(struct ufs_hba *hba)
9366 if (hba->sdev_ufs_device)
9367 ufshcd_rpm_get_sync(hba);
9368 ufs_bsg_remove(hba);
9370 ufs_sysfs_remove_nodes(hba->dev);
9371 blk_cleanup_queue(hba->tmf_queue);
9372 blk_mq_free_tag_set(&hba->tmf_tag_set);
9373 blk_cleanup_queue(hba->cmd_queue);
9374 scsi_remove_host(hba->host);
9375 /* disable interrupts */
9376 ufshcd_disable_intr(hba, hba->intr_mask);
9377 ufshcd_hba_stop(hba);
9378 ufshcd_hba_exit(hba);
9380 EXPORT_SYMBOL_GPL(ufshcd_remove);
9383 * ufshcd_dealloc_host - deallocate Host Bus Adapter (HBA)
9384 * @hba: pointer to Host Bus Adapter (HBA)
9386 void ufshcd_dealloc_host(struct ufs_hba *hba)
9388 scsi_host_put(hba->host);
9390 EXPORT_SYMBOL_GPL(ufshcd_dealloc_host);
9393 * ufshcd_set_dma_mask - Set dma mask based on the controller
9394 * addressing capability
9395 * @hba: per adapter instance
9397 * Returns 0 for success, non-zero for failure
9399 static int ufshcd_set_dma_mask(struct ufs_hba *hba)
9401 if (hba->capabilities & MASK_64_ADDRESSING_SUPPORT) {
9402 if (!dma_set_mask_and_coherent(hba->dev, DMA_BIT_MASK(64)))
9405 return dma_set_mask_and_coherent(hba->dev, DMA_BIT_MASK(32));
9408 static struct scsi_transport_template ufshcd_transport_template = {
9409 .eh_strategy_handler = ufshcd_err_handler,
9413 * ufshcd_alloc_host - allocate Host Bus Adapter (HBA)
9414 * @dev: pointer to device handle
9415 * @hba_handle: driver private handle
9416 * Returns 0 on success, non-zero value on failure
9418 int ufshcd_alloc_host(struct device *dev, struct ufs_hba **hba_handle)
9420 struct Scsi_Host *host;
9421 struct ufs_hba *hba;
9426 "Invalid memory reference for dev is NULL\n");
9431 host = scsi_host_alloc(&ufshcd_driver_template,
9432 sizeof(struct ufs_hba));
9434 dev_err(dev, "scsi_host_alloc failed\n");
9438 host->transportt = &ufshcd_transport_template;
9439 hba = shost_priv(host);
9442 hba->dev_ref_clk_freq = REF_CLK_FREQ_INVAL;
9443 INIT_LIST_HEAD(&hba->clk_list_head);
9444 spin_lock_init(&hba->outstanding_lock);
9451 EXPORT_SYMBOL(ufshcd_alloc_host);
9453 /* This function exists because blk_mq_alloc_tag_set() requires this. */
9454 static blk_status_t ufshcd_queue_tmf(struct blk_mq_hw_ctx *hctx,
9455 const struct blk_mq_queue_data *qd)
9458 return BLK_STS_NOTSUPP;
9461 static const struct blk_mq_ops ufshcd_tmf_ops = {
9462 .queue_rq = ufshcd_queue_tmf,
9466 * ufshcd_init - Driver initialization routine
9467 * @hba: per-adapter instance
9468 * @mmio_base: base register address
9469 * @irq: Interrupt line of device
9470 * Returns 0 on success, non-zero value on failure
9472 int ufshcd_init(struct ufs_hba *hba, void __iomem *mmio_base, unsigned int irq)
9475 struct Scsi_Host *host = hba->host;
9476 struct device *dev = hba->dev;
9480 "Invalid memory reference for mmio_base is NULL\n");
9485 hba->mmio_base = mmio_base;
9487 hba->vps = &ufs_hba_vps;
9489 err = ufshcd_hba_init(hba);
9493 /* Read capabilities registers */
9494 err = ufshcd_hba_capabilities(hba);
9498 /* Get UFS version supported by the controller */
9499 hba->ufs_version = ufshcd_get_ufs_version(hba);
9501 /* Get Interrupt bit mask per version */
9502 hba->intr_mask = ufshcd_get_intr_mask(hba);
9504 err = ufshcd_set_dma_mask(hba);
9506 dev_err(hba->dev, "set dma mask failed\n");
9510 /* Allocate memory for host memory space */
9511 err = ufshcd_memory_alloc(hba);
9513 dev_err(hba->dev, "Memory allocation failed\n");
9518 ufshcd_host_memory_configure(hba);
9520 host->can_queue = hba->nutrs;
9521 host->cmd_per_lun = hba->nutrs;
9522 host->max_id = UFSHCD_MAX_ID;
9523 host->max_lun = UFS_MAX_LUNS;
9524 host->max_channel = UFSHCD_MAX_CHANNEL;
9525 host->unique_id = host->host_no;
9526 host->max_cmd_len = UFS_CDB_SIZE;
9528 hba->max_pwr_info.is_valid = false;
9530 INIT_WORK(&hba->eeh_work, ufshcd_exception_event_handler);
9532 sema_init(&hba->host_sem, 1);
9534 /* Initialize UIC command mutex */
9535 mutex_init(&hba->uic_cmd_mutex);
9537 /* Initialize mutex for device management commands */
9538 mutex_init(&hba->dev_cmd.lock);
9540 /* Initialize mutex for exception event control */
9541 mutex_init(&hba->ee_ctrl_mutex);
9543 init_rwsem(&hba->clk_scaling_lock);
9545 ufshcd_init_clk_gating(hba);
9547 ufshcd_init_clk_scaling(hba);
9550 * In order to avoid any spurious interrupt immediately after
9551 * registering UFS controller interrupt handler, clear any pending UFS
9552 * interrupt status and disable all the UFS interrupts.
9554 ufshcd_writel(hba, ufshcd_readl(hba, REG_INTERRUPT_STATUS),
9555 REG_INTERRUPT_STATUS);
9556 ufshcd_writel(hba, 0, REG_INTERRUPT_ENABLE);
9558 * Make sure that UFS interrupts are disabled and any pending interrupt
9559 * status is cleared before registering UFS interrupt handler.
9563 /* IRQ registration */
9564 err = devm_request_irq(dev, irq, ufshcd_intr, IRQF_SHARED, UFSHCD, hba);
9566 dev_err(hba->dev, "request irq failed\n");
9569 hba->is_irq_enabled = true;
9572 err = scsi_add_host(host, hba->dev);
9574 dev_err(hba->dev, "scsi_add_host failed\n");
9578 hba->cmd_queue = blk_mq_init_queue(&hba->host->tag_set);
9579 if (IS_ERR(hba->cmd_queue)) {
9580 err = PTR_ERR(hba->cmd_queue);
9581 goto out_remove_scsi_host;
9584 hba->tmf_tag_set = (struct blk_mq_tag_set) {
9586 .queue_depth = hba->nutmrs,
9587 .ops = &ufshcd_tmf_ops,
9588 .flags = BLK_MQ_F_NO_SCHED,
9590 err = blk_mq_alloc_tag_set(&hba->tmf_tag_set);
9592 goto free_cmd_queue;
9593 hba->tmf_queue = blk_mq_init_queue(&hba->tmf_tag_set);
9594 if (IS_ERR(hba->tmf_queue)) {
9595 err = PTR_ERR(hba->tmf_queue);
9596 goto free_tmf_tag_set;
9599 /* Reset the attached device */
9600 ufshcd_device_reset(hba);
9602 ufshcd_init_crypto(hba);
9604 /* Host controller enable */
9605 err = ufshcd_hba_enable(hba);
9607 dev_err(hba->dev, "Host controller enable failed\n");
9608 ufshcd_print_evt_hist(hba);
9609 ufshcd_print_host_state(hba);
9610 goto free_tmf_queue;
9614 * Set the default power management level for runtime and system PM.
9615 * Default power saving mode is to keep UFS link in Hibern8 state
9616 * and UFS device in sleep state.
9618 hba->rpm_lvl = ufs_get_desired_pm_lvl_for_dev_link_state(
9620 UIC_LINK_HIBERN8_STATE);
9621 hba->spm_lvl = ufs_get_desired_pm_lvl_for_dev_link_state(
9623 UIC_LINK_HIBERN8_STATE);
9625 INIT_DELAYED_WORK(&hba->rpm_dev_flush_recheck_work,
9626 ufshcd_rpm_dev_flush_recheck_work);
9628 /* Set the default auto-hiberate idle timer value to 150 ms */
9629 if (ufshcd_is_auto_hibern8_supported(hba) && !hba->ahit) {
9630 hba->ahit = FIELD_PREP(UFSHCI_AHIBERN8_TIMER_MASK, 150) |
9631 FIELD_PREP(UFSHCI_AHIBERN8_SCALE_MASK, 3);
9634 /* Hold auto suspend until async scan completes */
9635 pm_runtime_get_sync(dev);
9636 atomic_set(&hba->scsi_block_reqs_cnt, 0);
9638 * We are assuming that device wasn't put in sleep/power-down
9639 * state exclusively during the boot stage before kernel.
9640 * This assumption helps avoid doing link startup twice during
9641 * ufshcd_probe_hba().
9643 ufshcd_set_ufs_dev_active(hba);
9645 async_schedule(ufshcd_async_scan, hba);
9646 ufs_sysfs_add_nodes(hba->dev);
9648 device_enable_async_suspend(dev);
9652 blk_cleanup_queue(hba->tmf_queue);
9654 blk_mq_free_tag_set(&hba->tmf_tag_set);
9656 blk_cleanup_queue(hba->cmd_queue);
9657 out_remove_scsi_host:
9658 scsi_remove_host(hba->host);
9660 hba->is_irq_enabled = false;
9661 ufshcd_hba_exit(hba);
9665 EXPORT_SYMBOL_GPL(ufshcd_init);
9667 void ufshcd_resume_complete(struct device *dev)
9669 struct ufs_hba *hba = dev_get_drvdata(dev);
9671 if (hba->complete_put) {
9672 ufshcd_rpm_put(hba);
9673 hba->complete_put = false;
9675 if (hba->rpmb_complete_put) {
9676 ufshcd_rpmb_rpm_put(hba);
9677 hba->rpmb_complete_put = false;
9680 EXPORT_SYMBOL_GPL(ufshcd_resume_complete);
9682 int ufshcd_suspend_prepare(struct device *dev)
9684 struct ufs_hba *hba = dev_get_drvdata(dev);
9688 * SCSI assumes that runtime-pm and system-pm for scsi drivers
9689 * are same. And it doesn't wake up the device for system-suspend
9690 * if it's runtime suspended. But ufs doesn't follow that.
9691 * Refer ufshcd_resume_complete()
9693 if (hba->sdev_ufs_device) {
9694 ret = ufshcd_rpm_get_sync(hba);
9695 if (ret < 0 && ret != -EACCES) {
9696 ufshcd_rpm_put(hba);
9699 hba->complete_put = true;
9701 if (hba->sdev_rpmb) {
9702 ufshcd_rpmb_rpm_get_sync(hba);
9703 hba->rpmb_complete_put = true;
9707 EXPORT_SYMBOL_GPL(ufshcd_suspend_prepare);
9709 #ifdef CONFIG_PM_SLEEP
9710 static int ufshcd_wl_poweroff(struct device *dev)
9712 struct scsi_device *sdev = to_scsi_device(dev);
9713 struct ufs_hba *hba = shost_priv(sdev->host);
9715 __ufshcd_wl_suspend(hba, UFS_SHUTDOWN_PM);
9720 static int ufshcd_wl_probe(struct device *dev)
9722 struct scsi_device *sdev = to_scsi_device(dev);
9724 if (!is_device_wlun(sdev))
9727 blk_pm_runtime_init(sdev->request_queue, dev);
9728 pm_runtime_set_autosuspend_delay(dev, 0);
9729 pm_runtime_allow(dev);
9734 static int ufshcd_wl_remove(struct device *dev)
9736 pm_runtime_forbid(dev);
9740 static const struct dev_pm_ops ufshcd_wl_pm_ops = {
9741 #ifdef CONFIG_PM_SLEEP
9742 .suspend = ufshcd_wl_suspend,
9743 .resume = ufshcd_wl_resume,
9744 .freeze = ufshcd_wl_suspend,
9745 .thaw = ufshcd_wl_resume,
9746 .poweroff = ufshcd_wl_poweroff,
9747 .restore = ufshcd_wl_resume,
9749 SET_RUNTIME_PM_OPS(ufshcd_wl_runtime_suspend, ufshcd_wl_runtime_resume, NULL)
9753 * ufs_dev_wlun_template - describes ufs device wlun
9754 * ufs-device wlun - used to send pm commands
9755 * All luns are consumers of ufs-device wlun.
9757 * Currently, no sd driver is present for wluns.
9758 * Hence the no specific pm operations are performed.
9759 * With ufs design, SSU should be sent to ufs-device wlun.
9760 * Hence register a scsi driver for ufs wluns only.
9762 static struct scsi_driver ufs_dev_wlun_template = {
9764 .name = "ufs_device_wlun",
9765 .owner = THIS_MODULE,
9766 .probe = ufshcd_wl_probe,
9767 .remove = ufshcd_wl_remove,
9768 .pm = &ufshcd_wl_pm_ops,
9769 .shutdown = ufshcd_wl_shutdown,
9773 static int ufshcd_rpmb_probe(struct device *dev)
9775 return is_rpmb_wlun(to_scsi_device(dev)) ? 0 : -ENODEV;
9778 static inline int ufshcd_clear_rpmb_uac(struct ufs_hba *hba)
9782 if (!hba->wlun_rpmb_clr_ua)
9784 ret = ufshcd_clear_ua_wlun(hba, UFS_UPIU_RPMB_WLUN);
9786 hba->wlun_rpmb_clr_ua = 0;
9791 static int ufshcd_rpmb_resume(struct device *dev)
9793 struct ufs_hba *hba = wlun_dev_to_hba(dev);
9796 ufshcd_clear_rpmb_uac(hba);
9801 static const struct dev_pm_ops ufs_rpmb_pm_ops = {
9802 SET_RUNTIME_PM_OPS(NULL, ufshcd_rpmb_resume, NULL)
9803 SET_SYSTEM_SLEEP_PM_OPS(NULL, ufshcd_rpmb_resume)
9806 /* ufs_rpmb_wlun_template - Describes UFS RPMB WLUN. Used only to send UAC. */
9807 static struct scsi_driver ufs_rpmb_wlun_template = {
9809 .name = "ufs_rpmb_wlun",
9810 .owner = THIS_MODULE,
9811 .probe = ufshcd_rpmb_probe,
9812 .pm = &ufs_rpmb_pm_ops,
9816 static int __init ufshcd_core_init(void)
9822 ret = scsi_register_driver(&ufs_dev_wlun_template.gendrv);
9826 ret = scsi_register_driver(&ufs_rpmb_wlun_template.gendrv);
9832 scsi_unregister_driver(&ufs_dev_wlun_template.gendrv);
9838 static void __exit ufshcd_core_exit(void)
9841 scsi_unregister_driver(&ufs_rpmb_wlun_template.gendrv);
9842 scsi_unregister_driver(&ufs_dev_wlun_template.gendrv);
9845 module_init(ufshcd_core_init);
9846 module_exit(ufshcd_core_exit);
9848 MODULE_AUTHOR("Santosh Yaragnavi <santosh.sy@samsung.com>");
9849 MODULE_AUTHOR("Vinayak Holikatti <h.vinayak@samsung.com>");
9850 MODULE_DESCRIPTION("Generic UFS host controller driver Core");
9851 MODULE_LICENSE("GPL");
9852 MODULE_VERSION(UFSHCD_DRIVER_VERSION);