1 // SPDX-License-Identifier: GPL-2.0-or-later
3 * Universal Flash Storage Host controller driver Core
4 * Copyright (C) 2011-2013 Samsung India Software Operations
5 * Copyright (c) 2013-2016, The Linux Foundation. All rights reserved.
8 * Santosh Yaraganavi <santosh.sy@samsung.com>
9 * Vinayak Holikatti <h.vinayak@samsung.com>
12 #include <linux/async.h>
13 #include <linux/devfreq.h>
14 #include <linux/nls.h>
16 #include <linux/bitfield.h>
17 #include <linux/blk-pm.h>
18 #include <linux/blkdev.h>
19 #include <scsi/scsi_driver.h>
21 #include "ufs_quirks.h"
23 #include "ufs-sysfs.h"
24 #include "ufs-debugfs.h"
26 #include "ufshcd-crypto.h"
28 #include <asm/unaligned.h>
30 #define CREATE_TRACE_POINTS
31 #include <trace/events/ufs.h>
33 #define UFSHCD_ENABLE_INTRS (UTP_TRANSFER_REQ_COMPL |\
36 /* UIC command timeout, unit: ms */
37 #define UIC_CMD_TIMEOUT 500
39 /* NOP OUT retries waiting for NOP IN response */
40 #define NOP_OUT_RETRIES 10
41 /* Timeout after 50 msecs if NOP OUT hangs without response */
42 #define NOP_OUT_TIMEOUT 50 /* msecs */
44 /* Query request retries */
45 #define QUERY_REQ_RETRIES 3
46 /* Query request timeout */
47 #define QUERY_REQ_TIMEOUT 1500 /* 1.5 seconds */
49 /* Task management command timeout */
50 #define TM_CMD_TIMEOUT 100 /* msecs */
52 /* maximum number of retries for a general UIC command */
53 #define UFS_UIC_COMMAND_RETRIES 3
55 /* maximum number of link-startup retries */
56 #define DME_LINKSTARTUP_RETRIES 3
58 /* Maximum retries for Hibern8 enter */
59 #define UIC_HIBERN8_ENTER_RETRIES 3
61 /* maximum number of reset retries before giving up */
62 #define MAX_HOST_RESET_RETRIES 5
64 /* Expose the flag value from utp_upiu_query.value */
65 #define MASK_QUERY_UPIU_FLAG_LOC 0xFF
67 /* Interrupt aggregation default timeout, unit: 40us */
68 #define INT_AGGR_DEF_TO 0x02
70 /* default delay of autosuspend: 2000 ms */
71 #define RPM_AUTOSUSPEND_DELAY_MS 2000
73 /* Default delay of RPM device flush delayed work */
74 #define RPM_DEV_FLUSH_RECHECK_WORK_DELAY_MS 5000
76 /* Default value of wait time before gating device ref clock */
77 #define UFSHCD_REF_CLK_GATING_WAIT_US 0xFF /* microsecs */
79 /* Polling time to wait for fDeviceInit */
80 #define FDEVICEINIT_COMPL_TIMEOUT 1500 /* millisecs */
82 #define wlun_dev_to_hba(dv) shost_priv(to_scsi_device(dv)->host)
84 #define ufshcd_toggle_vreg(_dev, _vreg, _on) \
88 _ret = ufshcd_enable_vreg(_dev, _vreg); \
90 _ret = ufshcd_disable_vreg(_dev, _vreg); \
94 #define ufshcd_hex_dump(prefix_str, buf, len) do { \
95 size_t __len = (len); \
96 print_hex_dump(KERN_ERR, prefix_str, \
97 __len > 4 ? DUMP_PREFIX_OFFSET : DUMP_PREFIX_NONE,\
98 16, 4, buf, __len, false); \
101 int ufshcd_dump_regs(struct ufs_hba *hba, size_t offset, size_t len,
107 if (offset % 4 != 0 || len % 4 != 0) /* keep readl happy */
110 regs = kzalloc(len, GFP_ATOMIC);
114 for (pos = 0; pos < len; pos += 4)
115 regs[pos / 4] = ufshcd_readl(hba, offset + pos);
117 ufshcd_hex_dump(prefix, regs, len);
122 EXPORT_SYMBOL_GPL(ufshcd_dump_regs);
125 UFSHCD_MAX_CHANNEL = 0,
127 UFSHCD_CMD_PER_LUN = 32,
128 UFSHCD_CAN_QUEUE = 32,
135 UFSHCD_STATE_OPERATIONAL,
136 UFSHCD_STATE_EH_SCHEDULED_FATAL,
137 UFSHCD_STATE_EH_SCHEDULED_NON_FATAL,
140 /* UFSHCD error handling flags */
142 UFSHCD_EH_IN_PROGRESS = (1 << 0),
145 /* UFSHCD UIC layer error flags */
147 UFSHCD_UIC_DL_PA_INIT_ERROR = (1 << 0), /* Data link layer error */
148 UFSHCD_UIC_DL_NAC_RECEIVED_ERROR = (1 << 1), /* Data link layer error */
149 UFSHCD_UIC_DL_TCx_REPLAY_ERROR = (1 << 2), /* Data link layer error */
150 UFSHCD_UIC_NL_ERROR = (1 << 3), /* Network layer error */
151 UFSHCD_UIC_TL_ERROR = (1 << 4), /* Transport Layer error */
152 UFSHCD_UIC_DME_ERROR = (1 << 5), /* DME error */
153 UFSHCD_UIC_PA_GENERIC_ERROR = (1 << 6), /* Generic PA error */
156 #define ufshcd_set_eh_in_progress(h) \
157 ((h)->eh_flags |= UFSHCD_EH_IN_PROGRESS)
158 #define ufshcd_eh_in_progress(h) \
159 ((h)->eh_flags & UFSHCD_EH_IN_PROGRESS)
160 #define ufshcd_clear_eh_in_progress(h) \
161 ((h)->eh_flags &= ~UFSHCD_EH_IN_PROGRESS)
163 struct ufs_pm_lvl_states ufs_pm_lvl_states[] = {
164 [UFS_PM_LVL_0] = {UFS_ACTIVE_PWR_MODE, UIC_LINK_ACTIVE_STATE},
165 [UFS_PM_LVL_1] = {UFS_ACTIVE_PWR_MODE, UIC_LINK_HIBERN8_STATE},
166 [UFS_PM_LVL_2] = {UFS_SLEEP_PWR_MODE, UIC_LINK_ACTIVE_STATE},
167 [UFS_PM_LVL_3] = {UFS_SLEEP_PWR_MODE, UIC_LINK_HIBERN8_STATE},
168 [UFS_PM_LVL_4] = {UFS_POWERDOWN_PWR_MODE, UIC_LINK_HIBERN8_STATE},
169 [UFS_PM_LVL_5] = {UFS_POWERDOWN_PWR_MODE, UIC_LINK_OFF_STATE},
171 * For DeepSleep, the link is first put in hibern8 and then off.
172 * Leaving the link in hibern8 is not supported.
174 [UFS_PM_LVL_6] = {UFS_DEEPSLEEP_PWR_MODE, UIC_LINK_OFF_STATE},
177 static inline enum ufs_dev_pwr_mode
178 ufs_get_pm_lvl_to_dev_pwr_mode(enum ufs_pm_level lvl)
180 return ufs_pm_lvl_states[lvl].dev_state;
183 static inline enum uic_link_state
184 ufs_get_pm_lvl_to_link_pwr_state(enum ufs_pm_level lvl)
186 return ufs_pm_lvl_states[lvl].link_state;
189 static inline enum ufs_pm_level
190 ufs_get_desired_pm_lvl_for_dev_link_state(enum ufs_dev_pwr_mode dev_state,
191 enum uic_link_state link_state)
193 enum ufs_pm_level lvl;
195 for (lvl = UFS_PM_LVL_0; lvl < UFS_PM_LVL_MAX; lvl++) {
196 if ((ufs_pm_lvl_states[lvl].dev_state == dev_state) &&
197 (ufs_pm_lvl_states[lvl].link_state == link_state))
201 /* if no match found, return the level 0 */
205 static struct ufs_dev_fix ufs_fixups[] = {
206 /* UFS cards deviations table */
207 UFS_FIX(UFS_VENDOR_MICRON, UFS_ANY_MODEL,
208 UFS_DEVICE_QUIRK_DELAY_BEFORE_LPM),
209 UFS_FIX(UFS_VENDOR_SAMSUNG, UFS_ANY_MODEL,
210 UFS_DEVICE_QUIRK_DELAY_BEFORE_LPM |
211 UFS_DEVICE_QUIRK_HOST_PA_TACTIVATE |
212 UFS_DEVICE_QUIRK_RECOVERY_FROM_DL_NAC_ERRORS),
213 UFS_FIX(UFS_VENDOR_SKHYNIX, UFS_ANY_MODEL,
214 UFS_DEVICE_QUIRK_HOST_PA_SAVECONFIGTIME),
215 UFS_FIX(UFS_VENDOR_SKHYNIX, "hB8aL1" /*H28U62301AMR*/,
216 UFS_DEVICE_QUIRK_HOST_VS_DEBUGSAVECONFIGTIME),
217 UFS_FIX(UFS_VENDOR_TOSHIBA, UFS_ANY_MODEL,
218 UFS_DEVICE_QUIRK_DELAY_BEFORE_LPM),
219 UFS_FIX(UFS_VENDOR_TOSHIBA, "THGLF2G9C8KBADG",
220 UFS_DEVICE_QUIRK_PA_TACTIVATE),
221 UFS_FIX(UFS_VENDOR_TOSHIBA, "THGLF2G9D8KBADG",
222 UFS_DEVICE_QUIRK_PA_TACTIVATE),
226 static irqreturn_t ufshcd_tmc_handler(struct ufs_hba *hba);
227 static void ufshcd_async_scan(void *data, async_cookie_t cookie);
228 static int ufshcd_reset_and_restore(struct ufs_hba *hba);
229 static int ufshcd_eh_host_reset_handler(struct scsi_cmnd *cmd);
230 static int ufshcd_clear_tm_cmd(struct ufs_hba *hba, int tag);
231 static void ufshcd_hba_exit(struct ufs_hba *hba);
232 static int ufshcd_clear_ua_wluns(struct ufs_hba *hba);
233 static int ufshcd_probe_hba(struct ufs_hba *hba, bool async);
234 static int ufshcd_setup_clocks(struct ufs_hba *hba, bool on);
235 static int ufshcd_uic_hibern8_enter(struct ufs_hba *hba);
236 static inline void ufshcd_add_delay_before_dme_cmd(struct ufs_hba *hba);
237 static int ufshcd_host_reset_and_restore(struct ufs_hba *hba);
238 static void ufshcd_resume_clkscaling(struct ufs_hba *hba);
239 static void ufshcd_suspend_clkscaling(struct ufs_hba *hba);
240 static void __ufshcd_suspend_clkscaling(struct ufs_hba *hba);
241 static int ufshcd_scale_clks(struct ufs_hba *hba, bool scale_up);
242 static irqreturn_t ufshcd_intr(int irq, void *__hba);
243 static int ufshcd_change_power_mode(struct ufs_hba *hba,
244 struct ufs_pa_layer_attr *pwr_mode);
245 static void ufshcd_schedule_eh_work(struct ufs_hba *hba);
246 static int ufshcd_setup_hba_vreg(struct ufs_hba *hba, bool on);
247 static int ufshcd_setup_vreg(struct ufs_hba *hba, bool on);
248 static inline int ufshcd_config_vreg_hpm(struct ufs_hba *hba,
249 struct ufs_vreg *vreg);
250 static int ufshcd_try_to_abort_task(struct ufs_hba *hba, int tag);
251 static void ufshcd_wb_toggle_flush_during_h8(struct ufs_hba *hba, bool set);
252 static inline void ufshcd_wb_toggle_flush(struct ufs_hba *hba, bool enable);
253 static void ufshcd_hba_vreg_set_lpm(struct ufs_hba *hba);
254 static void ufshcd_hba_vreg_set_hpm(struct ufs_hba *hba);
256 static inline void ufshcd_enable_irq(struct ufs_hba *hba)
258 if (!hba->is_irq_enabled) {
259 enable_irq(hba->irq);
260 hba->is_irq_enabled = true;
264 static inline void ufshcd_disable_irq(struct ufs_hba *hba)
266 if (hba->is_irq_enabled) {
267 disable_irq(hba->irq);
268 hba->is_irq_enabled = false;
272 static inline void ufshcd_wb_config(struct ufs_hba *hba)
274 if (!ufshcd_is_wb_allowed(hba))
277 ufshcd_wb_toggle(hba, true);
279 ufshcd_wb_toggle_flush_during_h8(hba, true);
280 if (!(hba->quirks & UFSHCI_QUIRK_SKIP_MANUAL_WB_FLUSH_CTRL))
281 ufshcd_wb_toggle_flush(hba, true);
284 static void ufshcd_scsi_unblock_requests(struct ufs_hba *hba)
286 if (atomic_dec_and_test(&hba->scsi_block_reqs_cnt))
287 scsi_unblock_requests(hba->host);
290 static void ufshcd_scsi_block_requests(struct ufs_hba *hba)
292 if (atomic_inc_return(&hba->scsi_block_reqs_cnt) == 1)
293 scsi_block_requests(hba->host);
296 static void ufshcd_add_cmd_upiu_trace(struct ufs_hba *hba, unsigned int tag,
297 enum ufs_trace_str_t str_t)
299 struct utp_upiu_req *rq = hba->lrb[tag].ucd_req_ptr;
300 struct utp_upiu_header *header;
302 if (!trace_ufshcd_upiu_enabled())
305 if (str_t == UFS_CMD_SEND)
306 header = &rq->header;
308 header = &hba->lrb[tag].ucd_rsp_ptr->header;
310 trace_ufshcd_upiu(dev_name(hba->dev), str_t, header, &rq->sc.cdb,
314 static void ufshcd_add_query_upiu_trace(struct ufs_hba *hba,
315 enum ufs_trace_str_t str_t,
316 struct utp_upiu_req *rq_rsp)
318 if (!trace_ufshcd_upiu_enabled())
321 trace_ufshcd_upiu(dev_name(hba->dev), str_t, &rq_rsp->header,
322 &rq_rsp->qr, UFS_TSF_OSF);
325 static void ufshcd_add_tm_upiu_trace(struct ufs_hba *hba, unsigned int tag,
326 enum ufs_trace_str_t str_t)
328 int off = (int)tag - hba->nutrs;
329 struct utp_task_req_desc *descp = &hba->utmrdl_base_addr[off];
331 if (!trace_ufshcd_upiu_enabled())
334 if (str_t == UFS_TM_SEND)
335 trace_ufshcd_upiu(dev_name(hba->dev), str_t,
336 &descp->upiu_req.req_header,
337 &descp->upiu_req.input_param1,
340 trace_ufshcd_upiu(dev_name(hba->dev), str_t,
341 &descp->upiu_rsp.rsp_header,
342 &descp->upiu_rsp.output_param1,
346 static void ufshcd_add_uic_command_trace(struct ufs_hba *hba,
347 struct uic_command *ucmd,
348 enum ufs_trace_str_t str_t)
352 if (!trace_ufshcd_uic_command_enabled())
355 if (str_t == UFS_CMD_SEND)
358 cmd = ufshcd_readl(hba, REG_UIC_COMMAND);
360 trace_ufshcd_uic_command(dev_name(hba->dev), str_t, cmd,
361 ufshcd_readl(hba, REG_UIC_COMMAND_ARG_1),
362 ufshcd_readl(hba, REG_UIC_COMMAND_ARG_2),
363 ufshcd_readl(hba, REG_UIC_COMMAND_ARG_3));
366 static void ufshcd_add_command_trace(struct ufs_hba *hba, unsigned int tag,
367 enum ufs_trace_str_t str_t)
370 u8 opcode = 0, group_id = 0;
372 struct ufshcd_lrb *lrbp = &hba->lrb[tag];
373 struct scsi_cmnd *cmd = lrbp->cmd;
374 int transfer_len = -1;
379 if (!trace_ufshcd_command_enabled()) {
380 /* trace UPIU W/O tracing command */
381 ufshcd_add_cmd_upiu_trace(hba, tag, str_t);
385 /* trace UPIU also */
386 ufshcd_add_cmd_upiu_trace(hba, tag, str_t);
387 opcode = cmd->cmnd[0];
388 lba = scsi_get_lba(cmd);
390 if (opcode == READ_10 || opcode == WRITE_10) {
392 * Currently we only fully trace read(10) and write(10) commands
395 be32_to_cpu(lrbp->ucd_req_ptr->sc.exp_data_transfer_len);
396 if (opcode == WRITE_10)
397 group_id = lrbp->cmd->cmnd[6];
398 } else if (opcode == UNMAP) {
400 * The number of Bytes to be unmapped beginning with the lba.
402 transfer_len = blk_rq_bytes(cmd->request);
405 intr = ufshcd_readl(hba, REG_INTERRUPT_STATUS);
406 doorbell = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
407 trace_ufshcd_command(dev_name(hba->dev), str_t, tag,
408 doorbell, transfer_len, intr, lba, opcode, group_id);
411 static void ufshcd_print_clk_freqs(struct ufs_hba *hba)
413 struct ufs_clk_info *clki;
414 struct list_head *head = &hba->clk_list_head;
416 if (list_empty(head))
419 list_for_each_entry(clki, head, list) {
420 if (!IS_ERR_OR_NULL(clki->clk) && clki->min_freq &&
422 dev_err(hba->dev, "clk: %s, rate: %u\n",
423 clki->name, clki->curr_freq);
427 static void ufshcd_print_evt(struct ufs_hba *hba, u32 id,
432 struct ufs_event_hist *e;
434 if (id >= UFS_EVT_CNT)
437 e = &hba->ufs_stats.event[id];
439 for (i = 0; i < UFS_EVENT_HIST_LENGTH; i++) {
440 int p = (i + e->pos) % UFS_EVENT_HIST_LENGTH;
442 if (e->tstamp[p] == 0)
444 dev_err(hba->dev, "%s[%d] = 0x%x at %lld us\n", err_name, p,
445 e->val[p], ktime_to_us(e->tstamp[p]));
450 dev_err(hba->dev, "No record of %s\n", err_name);
452 dev_err(hba->dev, "%s: total cnt=%llu\n", err_name, e->cnt);
455 static void ufshcd_print_evt_hist(struct ufs_hba *hba)
457 ufshcd_dump_regs(hba, 0, UFSHCI_REG_SPACE_SIZE, "host_regs: ");
459 ufshcd_print_evt(hba, UFS_EVT_PA_ERR, "pa_err");
460 ufshcd_print_evt(hba, UFS_EVT_DL_ERR, "dl_err");
461 ufshcd_print_evt(hba, UFS_EVT_NL_ERR, "nl_err");
462 ufshcd_print_evt(hba, UFS_EVT_TL_ERR, "tl_err");
463 ufshcd_print_evt(hba, UFS_EVT_DME_ERR, "dme_err");
464 ufshcd_print_evt(hba, UFS_EVT_AUTO_HIBERN8_ERR,
466 ufshcd_print_evt(hba, UFS_EVT_FATAL_ERR, "fatal_err");
467 ufshcd_print_evt(hba, UFS_EVT_LINK_STARTUP_FAIL,
468 "link_startup_fail");
469 ufshcd_print_evt(hba, UFS_EVT_RESUME_ERR, "resume_fail");
470 ufshcd_print_evt(hba, UFS_EVT_SUSPEND_ERR,
472 ufshcd_print_evt(hba, UFS_EVT_DEV_RESET, "dev_reset");
473 ufshcd_print_evt(hba, UFS_EVT_HOST_RESET, "host_reset");
474 ufshcd_print_evt(hba, UFS_EVT_ABORT, "task_abort");
476 ufshcd_vops_dbg_register_dump(hba);
480 void ufshcd_print_trs(struct ufs_hba *hba, unsigned long bitmap, bool pr_prdt)
482 struct ufshcd_lrb *lrbp;
486 for_each_set_bit(tag, &bitmap, hba->nutrs) {
487 lrbp = &hba->lrb[tag];
489 dev_err(hba->dev, "UPIU[%d] - issue time %lld us\n",
490 tag, ktime_to_us(lrbp->issue_time_stamp));
491 dev_err(hba->dev, "UPIU[%d] - complete time %lld us\n",
492 tag, ktime_to_us(lrbp->compl_time_stamp));
494 "UPIU[%d] - Transfer Request Descriptor phys@0x%llx\n",
495 tag, (u64)lrbp->utrd_dma_addr);
497 ufshcd_hex_dump("UPIU TRD: ", lrbp->utr_descriptor_ptr,
498 sizeof(struct utp_transfer_req_desc));
499 dev_err(hba->dev, "UPIU[%d] - Request UPIU phys@0x%llx\n", tag,
500 (u64)lrbp->ucd_req_dma_addr);
501 ufshcd_hex_dump("UPIU REQ: ", lrbp->ucd_req_ptr,
502 sizeof(struct utp_upiu_req));
503 dev_err(hba->dev, "UPIU[%d] - Response UPIU phys@0x%llx\n", tag,
504 (u64)lrbp->ucd_rsp_dma_addr);
505 ufshcd_hex_dump("UPIU RSP: ", lrbp->ucd_rsp_ptr,
506 sizeof(struct utp_upiu_rsp));
508 prdt_length = le16_to_cpu(
509 lrbp->utr_descriptor_ptr->prd_table_length);
510 if (hba->quirks & UFSHCD_QUIRK_PRDT_BYTE_GRAN)
511 prdt_length /= sizeof(struct ufshcd_sg_entry);
514 "UPIU[%d] - PRDT - %d entries phys@0x%llx\n",
516 (u64)lrbp->ucd_prdt_dma_addr);
519 ufshcd_hex_dump("UPIU PRDT: ", lrbp->ucd_prdt_ptr,
520 sizeof(struct ufshcd_sg_entry) * prdt_length);
524 static void ufshcd_print_tmrs(struct ufs_hba *hba, unsigned long bitmap)
528 for_each_set_bit(tag, &bitmap, hba->nutmrs) {
529 struct utp_task_req_desc *tmrdp = &hba->utmrdl_base_addr[tag];
531 dev_err(hba->dev, "TM[%d] - Task Management Header\n", tag);
532 ufshcd_hex_dump("", tmrdp, sizeof(*tmrdp));
536 static void ufshcd_print_host_state(struct ufs_hba *hba)
538 struct scsi_device *sdev_ufs = hba->sdev_ufs_device;
540 dev_err(hba->dev, "UFS Host state=%d\n", hba->ufshcd_state);
541 dev_err(hba->dev, "outstanding reqs=0x%lx tasks=0x%lx\n",
542 hba->outstanding_reqs, hba->outstanding_tasks);
543 dev_err(hba->dev, "saved_err=0x%x, saved_uic_err=0x%x\n",
544 hba->saved_err, hba->saved_uic_err);
545 dev_err(hba->dev, "Device power mode=%d, UIC link state=%d\n",
546 hba->curr_dev_pwr_mode, hba->uic_link_state);
547 dev_err(hba->dev, "PM in progress=%d, sys. suspended=%d\n",
548 hba->pm_op_in_progress, hba->is_sys_suspended);
549 dev_err(hba->dev, "Auto BKOPS=%d, Host self-block=%d\n",
550 hba->auto_bkops_enabled, hba->host->host_self_blocked);
551 dev_err(hba->dev, "Clk gate=%d\n", hba->clk_gating.state);
553 "last_hibern8_exit_tstamp at %lld us, hibern8_exit_cnt=%d\n",
554 ktime_to_us(hba->ufs_stats.last_hibern8_exit_tstamp),
555 hba->ufs_stats.hibern8_exit_cnt);
556 dev_err(hba->dev, "last intr at %lld us, last intr status=0x%x\n",
557 ktime_to_us(hba->ufs_stats.last_intr_ts),
558 hba->ufs_stats.last_intr_status);
559 dev_err(hba->dev, "error handling flags=0x%x, req. abort count=%d\n",
560 hba->eh_flags, hba->req_abort_count);
561 dev_err(hba->dev, "hba->ufs_version=0x%x, Host capabilities=0x%x, caps=0x%x\n",
562 hba->ufs_version, hba->capabilities, hba->caps);
563 dev_err(hba->dev, "quirks=0x%x, dev. quirks=0x%x\n", hba->quirks,
566 dev_err(hba->dev, "UFS dev info: %.8s %.16s rev %.4s\n",
567 sdev_ufs->vendor, sdev_ufs->model, sdev_ufs->rev);
569 ufshcd_print_clk_freqs(hba);
573 * ufshcd_print_pwr_info - print power params as saved in hba
575 * @hba: per-adapter instance
577 static void ufshcd_print_pwr_info(struct ufs_hba *hba)
579 static const char * const names[] = {
589 dev_err(hba->dev, "%s:[RX, TX]: gear=[%d, %d], lane[%d, %d], pwr[%s, %s], rate = %d\n",
591 hba->pwr_info.gear_rx, hba->pwr_info.gear_tx,
592 hba->pwr_info.lane_rx, hba->pwr_info.lane_tx,
593 names[hba->pwr_info.pwr_rx],
594 names[hba->pwr_info.pwr_tx],
595 hba->pwr_info.hs_rate);
598 static void ufshcd_device_reset(struct ufs_hba *hba)
602 err = ufshcd_vops_device_reset(hba);
605 ufshcd_set_ufs_dev_active(hba);
606 if (ufshcd_is_wb_allowed(hba)) {
607 hba->dev_info.wb_enabled = false;
608 hba->dev_info.wb_buf_flush_enabled = false;
611 if (err != -EOPNOTSUPP)
612 ufshcd_update_evt_hist(hba, UFS_EVT_DEV_RESET, err);
615 void ufshcd_delay_us(unsigned long us, unsigned long tolerance)
623 usleep_range(us, us + tolerance);
625 EXPORT_SYMBOL_GPL(ufshcd_delay_us);
628 * ufshcd_wait_for_register - wait for register value to change
629 * @hba: per-adapter interface
630 * @reg: mmio register offset
631 * @mask: mask to apply to the read register value
632 * @val: value to wait for
633 * @interval_us: polling interval in microseconds
634 * @timeout_ms: timeout in milliseconds
637 * -ETIMEDOUT on error, zero on success.
639 int ufshcd_wait_for_register(struct ufs_hba *hba, u32 reg, u32 mask,
640 u32 val, unsigned long interval_us,
641 unsigned long timeout_ms)
644 unsigned long timeout = jiffies + msecs_to_jiffies(timeout_ms);
646 /* ignore bits that we don't intend to wait on */
649 while ((ufshcd_readl(hba, reg) & mask) != val) {
650 usleep_range(interval_us, interval_us + 50);
651 if (time_after(jiffies, timeout)) {
652 if ((ufshcd_readl(hba, reg) & mask) != val)
662 * ufshcd_get_intr_mask - Get the interrupt bit mask
663 * @hba: Pointer to adapter instance
665 * Returns interrupt bit mask per version
667 static inline u32 ufshcd_get_intr_mask(struct ufs_hba *hba)
669 if (hba->ufs_version == ufshci_version(1, 0))
670 return INTERRUPT_MASK_ALL_VER_10;
671 if (hba->ufs_version <= ufshci_version(2, 0))
672 return INTERRUPT_MASK_ALL_VER_11;
674 return INTERRUPT_MASK_ALL_VER_21;
678 * ufshcd_get_ufs_version - Get the UFS version supported by the HBA
679 * @hba: Pointer to adapter instance
681 * Returns UFSHCI version supported by the controller
683 static inline u32 ufshcd_get_ufs_version(struct ufs_hba *hba)
687 if (hba->quirks & UFSHCD_QUIRK_BROKEN_UFS_HCI_VERSION)
688 ufshci_ver = ufshcd_vops_get_ufs_hci_version(hba);
690 ufshci_ver = ufshcd_readl(hba, REG_UFS_VERSION);
693 * UFSHCI v1.x uses a different version scheme, in order
694 * to allow the use of comparisons with the ufshci_version
695 * function, we convert it to the same scheme as ufs 2.0+.
697 if (ufshci_ver & 0x00010000)
698 return ufshci_version(1, ufshci_ver & 0x00000100);
704 * ufshcd_is_device_present - Check if any device connected to
705 * the host controller
706 * @hba: pointer to adapter instance
708 * Returns true if device present, false if no device detected
710 static inline bool ufshcd_is_device_present(struct ufs_hba *hba)
712 return (ufshcd_readl(hba, REG_CONTROLLER_STATUS) &
713 DEVICE_PRESENT) ? true : false;
717 * ufshcd_get_tr_ocs - Get the UTRD Overall Command Status
718 * @lrbp: pointer to local command reference block
720 * This function is used to get the OCS field from UTRD
721 * Returns the OCS field in the UTRD
723 static inline int ufshcd_get_tr_ocs(struct ufshcd_lrb *lrbp)
725 return le32_to_cpu(lrbp->utr_descriptor_ptr->header.dword_2) & MASK_OCS;
729 * ufshcd_utrl_clear - Clear a bit in UTRLCLR register
730 * @hba: per adapter instance
731 * @pos: position of the bit to be cleared
733 static inline void ufshcd_utrl_clear(struct ufs_hba *hba, u32 pos)
735 if (hba->quirks & UFSHCI_QUIRK_BROKEN_REQ_LIST_CLR)
736 ufshcd_writel(hba, (1 << pos), REG_UTP_TRANSFER_REQ_LIST_CLEAR);
738 ufshcd_writel(hba, ~(1 << pos),
739 REG_UTP_TRANSFER_REQ_LIST_CLEAR);
743 * ufshcd_utmrl_clear - Clear a bit in UTRMLCLR register
744 * @hba: per adapter instance
745 * @pos: position of the bit to be cleared
747 static inline void ufshcd_utmrl_clear(struct ufs_hba *hba, u32 pos)
749 if (hba->quirks & UFSHCI_QUIRK_BROKEN_REQ_LIST_CLR)
750 ufshcd_writel(hba, (1 << pos), REG_UTP_TASK_REQ_LIST_CLEAR);
752 ufshcd_writel(hba, ~(1 << pos), REG_UTP_TASK_REQ_LIST_CLEAR);
756 * ufshcd_outstanding_req_clear - Clear a bit in outstanding request field
757 * @hba: per adapter instance
758 * @tag: position of the bit to be cleared
760 static inline void ufshcd_outstanding_req_clear(struct ufs_hba *hba, int tag)
762 clear_bit(tag, &hba->outstanding_reqs);
766 * ufshcd_get_lists_status - Check UCRDY, UTRLRDY and UTMRLRDY
767 * @reg: Register value of host controller status
769 * Returns integer, 0 on Success and positive value if failed
771 static inline int ufshcd_get_lists_status(u32 reg)
773 return !((reg & UFSHCD_STATUS_READY) == UFSHCD_STATUS_READY);
777 * ufshcd_get_uic_cmd_result - Get the UIC command result
778 * @hba: Pointer to adapter instance
780 * This function gets the result of UIC command completion
781 * Returns 0 on success, non zero value on error
783 static inline int ufshcd_get_uic_cmd_result(struct ufs_hba *hba)
785 return ufshcd_readl(hba, REG_UIC_COMMAND_ARG_2) &
786 MASK_UIC_COMMAND_RESULT;
790 * ufshcd_get_dme_attr_val - Get the value of attribute returned by UIC command
791 * @hba: Pointer to adapter instance
793 * This function gets UIC command argument3
794 * Returns 0 on success, non zero value on error
796 static inline u32 ufshcd_get_dme_attr_val(struct ufs_hba *hba)
798 return ufshcd_readl(hba, REG_UIC_COMMAND_ARG_3);
802 * ufshcd_get_req_rsp - returns the TR response transaction type
803 * @ucd_rsp_ptr: pointer to response UPIU
806 ufshcd_get_req_rsp(struct utp_upiu_rsp *ucd_rsp_ptr)
808 return be32_to_cpu(ucd_rsp_ptr->header.dword_0) >> 24;
812 * ufshcd_get_rsp_upiu_result - Get the result from response UPIU
813 * @ucd_rsp_ptr: pointer to response UPIU
815 * This function gets the response status and scsi_status from response UPIU
816 * Returns the response result code.
819 ufshcd_get_rsp_upiu_result(struct utp_upiu_rsp *ucd_rsp_ptr)
821 return be32_to_cpu(ucd_rsp_ptr->header.dword_1) & MASK_RSP_UPIU_RESULT;
825 * ufshcd_get_rsp_upiu_data_seg_len - Get the data segment length
827 * @ucd_rsp_ptr: pointer to response UPIU
829 * Return the data segment length.
831 static inline unsigned int
832 ufshcd_get_rsp_upiu_data_seg_len(struct utp_upiu_rsp *ucd_rsp_ptr)
834 return be32_to_cpu(ucd_rsp_ptr->header.dword_2) &
835 MASK_RSP_UPIU_DATA_SEG_LEN;
839 * ufshcd_is_exception_event - Check if the device raised an exception event
840 * @ucd_rsp_ptr: pointer to response UPIU
842 * The function checks if the device raised an exception event indicated in
843 * the Device Information field of response UPIU.
845 * Returns true if exception is raised, false otherwise.
847 static inline bool ufshcd_is_exception_event(struct utp_upiu_rsp *ucd_rsp_ptr)
849 return be32_to_cpu(ucd_rsp_ptr->header.dword_2) &
850 MASK_RSP_EXCEPTION_EVENT ? true : false;
854 * ufshcd_reset_intr_aggr - Reset interrupt aggregation values.
855 * @hba: per adapter instance
858 ufshcd_reset_intr_aggr(struct ufs_hba *hba)
860 ufshcd_writel(hba, INT_AGGR_ENABLE |
861 INT_AGGR_COUNTER_AND_TIMER_RESET,
862 REG_UTP_TRANSFER_REQ_INT_AGG_CONTROL);
866 * ufshcd_config_intr_aggr - Configure interrupt aggregation values.
867 * @hba: per adapter instance
868 * @cnt: Interrupt aggregation counter threshold
869 * @tmout: Interrupt aggregation timeout value
872 ufshcd_config_intr_aggr(struct ufs_hba *hba, u8 cnt, u8 tmout)
874 ufshcd_writel(hba, INT_AGGR_ENABLE | INT_AGGR_PARAM_WRITE |
875 INT_AGGR_COUNTER_THLD_VAL(cnt) |
876 INT_AGGR_TIMEOUT_VAL(tmout),
877 REG_UTP_TRANSFER_REQ_INT_AGG_CONTROL);
881 * ufshcd_disable_intr_aggr - Disables interrupt aggregation.
882 * @hba: per adapter instance
884 static inline void ufshcd_disable_intr_aggr(struct ufs_hba *hba)
886 ufshcd_writel(hba, 0, REG_UTP_TRANSFER_REQ_INT_AGG_CONTROL);
890 * ufshcd_enable_run_stop_reg - Enable run-stop registers,
891 * When run-stop registers are set to 1, it indicates the
892 * host controller that it can process the requests
893 * @hba: per adapter instance
895 static void ufshcd_enable_run_stop_reg(struct ufs_hba *hba)
897 ufshcd_writel(hba, UTP_TASK_REQ_LIST_RUN_STOP_BIT,
898 REG_UTP_TASK_REQ_LIST_RUN_STOP);
899 ufshcd_writel(hba, UTP_TRANSFER_REQ_LIST_RUN_STOP_BIT,
900 REG_UTP_TRANSFER_REQ_LIST_RUN_STOP);
904 * ufshcd_hba_start - Start controller initialization sequence
905 * @hba: per adapter instance
907 static inline void ufshcd_hba_start(struct ufs_hba *hba)
909 u32 val = CONTROLLER_ENABLE;
911 if (ufshcd_crypto_enable(hba))
912 val |= CRYPTO_GENERAL_ENABLE;
914 ufshcd_writel(hba, val, REG_CONTROLLER_ENABLE);
918 * ufshcd_is_hba_active - Get controller state
919 * @hba: per adapter instance
921 * Returns false if controller is active, true otherwise
923 static inline bool ufshcd_is_hba_active(struct ufs_hba *hba)
925 return (ufshcd_readl(hba, REG_CONTROLLER_ENABLE) & CONTROLLER_ENABLE)
929 u32 ufshcd_get_local_unipro_ver(struct ufs_hba *hba)
931 /* HCI version 1.0 and 1.1 supports UniPro 1.41 */
932 if (hba->ufs_version <= ufshci_version(1, 1))
933 return UFS_UNIPRO_VER_1_41;
935 return UFS_UNIPRO_VER_1_6;
937 EXPORT_SYMBOL(ufshcd_get_local_unipro_ver);
939 static bool ufshcd_is_unipro_pa_params_tuning_req(struct ufs_hba *hba)
942 * If both host and device support UniPro ver1.6 or later, PA layer
943 * parameters tuning happens during link startup itself.
945 * We can manually tune PA layer parameters if either host or device
946 * doesn't support UniPro ver 1.6 or later. But to keep manual tuning
947 * logic simple, we will only do manual tuning if local unipro version
948 * doesn't support ver1.6 or later.
950 if (ufshcd_get_local_unipro_ver(hba) < UFS_UNIPRO_VER_1_6)
957 * ufshcd_set_clk_freq - set UFS controller clock frequencies
958 * @hba: per adapter instance
959 * @scale_up: If True, set max possible frequency othewise set low frequency
961 * Returns 0 if successful
962 * Returns < 0 for any other errors
964 static int ufshcd_set_clk_freq(struct ufs_hba *hba, bool scale_up)
967 struct ufs_clk_info *clki;
968 struct list_head *head = &hba->clk_list_head;
970 if (list_empty(head))
973 list_for_each_entry(clki, head, list) {
974 if (!IS_ERR_OR_NULL(clki->clk)) {
975 if (scale_up && clki->max_freq) {
976 if (clki->curr_freq == clki->max_freq)
979 ret = clk_set_rate(clki->clk, clki->max_freq);
981 dev_err(hba->dev, "%s: %s clk set rate(%dHz) failed, %d\n",
982 __func__, clki->name,
983 clki->max_freq, ret);
986 trace_ufshcd_clk_scaling(dev_name(hba->dev),
987 "scaled up", clki->name,
991 clki->curr_freq = clki->max_freq;
993 } else if (!scale_up && clki->min_freq) {
994 if (clki->curr_freq == clki->min_freq)
997 ret = clk_set_rate(clki->clk, clki->min_freq);
999 dev_err(hba->dev, "%s: %s clk set rate(%dHz) failed, %d\n",
1000 __func__, clki->name,
1001 clki->min_freq, ret);
1004 trace_ufshcd_clk_scaling(dev_name(hba->dev),
1005 "scaled down", clki->name,
1008 clki->curr_freq = clki->min_freq;
1011 dev_dbg(hba->dev, "%s: clk: %s, rate: %lu\n", __func__,
1012 clki->name, clk_get_rate(clki->clk));
1020 * ufshcd_scale_clks - scale up or scale down UFS controller clocks
1021 * @hba: per adapter instance
1022 * @scale_up: True if scaling up and false if scaling down
1024 * Returns 0 if successful
1025 * Returns < 0 for any other errors
1027 static int ufshcd_scale_clks(struct ufs_hba *hba, bool scale_up)
1030 ktime_t start = ktime_get();
1032 ret = ufshcd_vops_clk_scale_notify(hba, scale_up, PRE_CHANGE);
1036 ret = ufshcd_set_clk_freq(hba, scale_up);
1040 ret = ufshcd_vops_clk_scale_notify(hba, scale_up, POST_CHANGE);
1042 ufshcd_set_clk_freq(hba, !scale_up);
1045 trace_ufshcd_profile_clk_scaling(dev_name(hba->dev),
1046 (scale_up ? "up" : "down"),
1047 ktime_to_us(ktime_sub(ktime_get(), start)), ret);
1052 * ufshcd_is_devfreq_scaling_required - check if scaling is required or not
1053 * @hba: per adapter instance
1054 * @scale_up: True if scaling up and false if scaling down
1056 * Returns true if scaling is required, false otherwise.
1058 static bool ufshcd_is_devfreq_scaling_required(struct ufs_hba *hba,
1061 struct ufs_clk_info *clki;
1062 struct list_head *head = &hba->clk_list_head;
1064 if (list_empty(head))
1067 list_for_each_entry(clki, head, list) {
1068 if (!IS_ERR_OR_NULL(clki->clk)) {
1069 if (scale_up && clki->max_freq) {
1070 if (clki->curr_freq == clki->max_freq)
1073 } else if (!scale_up && clki->min_freq) {
1074 if (clki->curr_freq == clki->min_freq)
1084 static int ufshcd_wait_for_doorbell_clr(struct ufs_hba *hba,
1085 u64 wait_timeout_us)
1087 unsigned long flags;
1091 bool timeout = false, do_last_check = false;
1094 ufshcd_hold(hba, false);
1095 spin_lock_irqsave(hba->host->host_lock, flags);
1097 * Wait for all the outstanding tasks/transfer requests.
1098 * Verify by checking the doorbell registers are clear.
1100 start = ktime_get();
1102 if (hba->ufshcd_state != UFSHCD_STATE_OPERATIONAL) {
1107 tm_doorbell = ufshcd_readl(hba, REG_UTP_TASK_REQ_DOOR_BELL);
1108 tr_doorbell = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
1109 if (!tm_doorbell && !tr_doorbell) {
1112 } else if (do_last_check) {
1116 spin_unlock_irqrestore(hba->host->host_lock, flags);
1118 if (ktime_to_us(ktime_sub(ktime_get(), start)) >
1122 * We might have scheduled out for long time so make
1123 * sure to check if doorbells are cleared by this time
1126 do_last_check = true;
1128 spin_lock_irqsave(hba->host->host_lock, flags);
1129 } while (tm_doorbell || tr_doorbell);
1133 "%s: timedout waiting for doorbell to clear (tm=0x%x, tr=0x%x)\n",
1134 __func__, tm_doorbell, tr_doorbell);
1138 spin_unlock_irqrestore(hba->host->host_lock, flags);
1139 ufshcd_release(hba);
1144 * ufshcd_scale_gear - scale up/down UFS gear
1145 * @hba: per adapter instance
1146 * @scale_up: True for scaling up gear and false for scaling down
1148 * Returns 0 for success,
1149 * Returns -EBUSY if scaling can't happen at this time
1150 * Returns non-zero for any other errors
1152 static int ufshcd_scale_gear(struct ufs_hba *hba, bool scale_up)
1155 struct ufs_pa_layer_attr new_pwr_info;
1158 memcpy(&new_pwr_info, &hba->clk_scaling.saved_pwr_info.info,
1159 sizeof(struct ufs_pa_layer_attr));
1161 memcpy(&new_pwr_info, &hba->pwr_info,
1162 sizeof(struct ufs_pa_layer_attr));
1164 if (hba->pwr_info.gear_tx > hba->clk_scaling.min_gear ||
1165 hba->pwr_info.gear_rx > hba->clk_scaling.min_gear) {
1166 /* save the current power mode */
1167 memcpy(&hba->clk_scaling.saved_pwr_info.info,
1169 sizeof(struct ufs_pa_layer_attr));
1171 /* scale down gear */
1172 new_pwr_info.gear_tx = hba->clk_scaling.min_gear;
1173 new_pwr_info.gear_rx = hba->clk_scaling.min_gear;
1177 /* check if the power mode needs to be changed or not? */
1178 ret = ufshcd_config_pwr_mode(hba, &new_pwr_info);
1180 dev_err(hba->dev, "%s: failed err %d, old gear: (tx %d rx %d), new gear: (tx %d rx %d)",
1182 hba->pwr_info.gear_tx, hba->pwr_info.gear_rx,
1183 new_pwr_info.gear_tx, new_pwr_info.gear_rx);
1188 static int ufshcd_clock_scaling_prepare(struct ufs_hba *hba)
1190 #define DOORBELL_CLR_TOUT_US (1000 * 1000) /* 1 sec */
1193 * make sure that there are no outstanding requests when
1194 * clock scaling is in progress
1196 ufshcd_scsi_block_requests(hba);
1197 down_write(&hba->clk_scaling_lock);
1199 if (!hba->clk_scaling.is_allowed ||
1200 ufshcd_wait_for_doorbell_clr(hba, DOORBELL_CLR_TOUT_US)) {
1202 up_write(&hba->clk_scaling_lock);
1203 ufshcd_scsi_unblock_requests(hba);
1207 /* let's not get into low power until clock scaling is completed */
1208 ufshcd_hold(hba, false);
1214 static void ufshcd_clock_scaling_unprepare(struct ufs_hba *hba, bool writelock)
1217 up_write(&hba->clk_scaling_lock);
1219 up_read(&hba->clk_scaling_lock);
1220 ufshcd_scsi_unblock_requests(hba);
1221 ufshcd_release(hba);
1225 * ufshcd_devfreq_scale - scale up/down UFS clocks and gear
1226 * @hba: per adapter instance
1227 * @scale_up: True for scaling up and false for scalin down
1229 * Returns 0 for success,
1230 * Returns -EBUSY if scaling can't happen at this time
1231 * Returns non-zero for any other errors
1233 static int ufshcd_devfreq_scale(struct ufs_hba *hba, bool scale_up)
1236 bool is_writelock = true;
1238 ret = ufshcd_clock_scaling_prepare(hba);
1242 /* scale down the gear before scaling down clocks */
1244 ret = ufshcd_scale_gear(hba, false);
1249 ret = ufshcd_scale_clks(hba, scale_up);
1252 ufshcd_scale_gear(hba, true);
1256 /* scale up the gear after scaling up clocks */
1258 ret = ufshcd_scale_gear(hba, true);
1260 ufshcd_scale_clks(hba, false);
1265 /* Enable Write Booster if we have scaled up else disable it */
1266 downgrade_write(&hba->clk_scaling_lock);
1267 is_writelock = false;
1268 ufshcd_wb_toggle(hba, scale_up);
1271 ufshcd_clock_scaling_unprepare(hba, is_writelock);
1275 static void ufshcd_clk_scaling_suspend_work(struct work_struct *work)
1277 struct ufs_hba *hba = container_of(work, struct ufs_hba,
1278 clk_scaling.suspend_work);
1279 unsigned long irq_flags;
1281 spin_lock_irqsave(hba->host->host_lock, irq_flags);
1282 if (hba->clk_scaling.active_reqs || hba->clk_scaling.is_suspended) {
1283 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1286 hba->clk_scaling.is_suspended = true;
1287 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1289 __ufshcd_suspend_clkscaling(hba);
1292 static void ufshcd_clk_scaling_resume_work(struct work_struct *work)
1294 struct ufs_hba *hba = container_of(work, struct ufs_hba,
1295 clk_scaling.resume_work);
1296 unsigned long irq_flags;
1298 spin_lock_irqsave(hba->host->host_lock, irq_flags);
1299 if (!hba->clk_scaling.is_suspended) {
1300 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1303 hba->clk_scaling.is_suspended = false;
1304 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1306 devfreq_resume_device(hba->devfreq);
1309 static int ufshcd_devfreq_target(struct device *dev,
1310 unsigned long *freq, u32 flags)
1313 struct ufs_hba *hba = dev_get_drvdata(dev);
1315 bool scale_up, sched_clk_scaling_suspend_work = false;
1316 struct list_head *clk_list = &hba->clk_list_head;
1317 struct ufs_clk_info *clki;
1318 unsigned long irq_flags;
1320 if (!ufshcd_is_clkscaling_supported(hba))
1323 clki = list_first_entry(&hba->clk_list_head, struct ufs_clk_info, list);
1324 /* Override with the closest supported frequency */
1325 *freq = (unsigned long) clk_round_rate(clki->clk, *freq);
1326 spin_lock_irqsave(hba->host->host_lock, irq_flags);
1327 if (ufshcd_eh_in_progress(hba)) {
1328 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1332 if (!hba->clk_scaling.active_reqs)
1333 sched_clk_scaling_suspend_work = true;
1335 if (list_empty(clk_list)) {
1336 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1340 /* Decide based on the rounded-off frequency and update */
1341 scale_up = (*freq == clki->max_freq) ? true : false;
1343 *freq = clki->min_freq;
1344 /* Update the frequency */
1345 if (!ufshcd_is_devfreq_scaling_required(hba, scale_up)) {
1346 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1348 goto out; /* no state change required */
1350 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1352 start = ktime_get();
1353 ret = ufshcd_devfreq_scale(hba, scale_up);
1355 trace_ufshcd_profile_clk_scaling(dev_name(hba->dev),
1356 (scale_up ? "up" : "down"),
1357 ktime_to_us(ktime_sub(ktime_get(), start)), ret);
1360 if (sched_clk_scaling_suspend_work)
1361 queue_work(hba->clk_scaling.workq,
1362 &hba->clk_scaling.suspend_work);
1367 static bool ufshcd_is_busy(struct request *req, void *priv, bool reserved)
1371 WARN_ON_ONCE(reserved);
1376 /* Whether or not any tag is in use by a request that is in progress. */
1377 static bool ufshcd_any_tag_in_use(struct ufs_hba *hba)
1379 struct request_queue *q = hba->cmd_queue;
1382 blk_mq_tagset_busy_iter(q->tag_set, ufshcd_is_busy, &busy);
1386 static int ufshcd_devfreq_get_dev_status(struct device *dev,
1387 struct devfreq_dev_status *stat)
1389 struct ufs_hba *hba = dev_get_drvdata(dev);
1390 struct ufs_clk_scaling *scaling = &hba->clk_scaling;
1391 unsigned long flags;
1392 struct list_head *clk_list = &hba->clk_list_head;
1393 struct ufs_clk_info *clki;
1396 if (!ufshcd_is_clkscaling_supported(hba))
1399 memset(stat, 0, sizeof(*stat));
1401 spin_lock_irqsave(hba->host->host_lock, flags);
1402 curr_t = ktime_get();
1403 if (!scaling->window_start_t)
1406 clki = list_first_entry(clk_list, struct ufs_clk_info, list);
1408 * If current frequency is 0, then the ondemand governor considers
1409 * there's no initial frequency set. And it always requests to set
1410 * to max. frequency.
1412 stat->current_frequency = clki->curr_freq;
1413 if (scaling->is_busy_started)
1414 scaling->tot_busy_t += ktime_us_delta(curr_t,
1415 scaling->busy_start_t);
1417 stat->total_time = ktime_us_delta(curr_t, scaling->window_start_t);
1418 stat->busy_time = scaling->tot_busy_t;
1420 scaling->window_start_t = curr_t;
1421 scaling->tot_busy_t = 0;
1423 if (hba->outstanding_reqs) {
1424 scaling->busy_start_t = curr_t;
1425 scaling->is_busy_started = true;
1427 scaling->busy_start_t = 0;
1428 scaling->is_busy_started = false;
1430 spin_unlock_irqrestore(hba->host->host_lock, flags);
1434 static int ufshcd_devfreq_init(struct ufs_hba *hba)
1436 struct list_head *clk_list = &hba->clk_list_head;
1437 struct ufs_clk_info *clki;
1438 struct devfreq *devfreq;
1441 /* Skip devfreq if we don't have any clocks in the list */
1442 if (list_empty(clk_list))
1445 clki = list_first_entry(clk_list, struct ufs_clk_info, list);
1446 dev_pm_opp_add(hba->dev, clki->min_freq, 0);
1447 dev_pm_opp_add(hba->dev, clki->max_freq, 0);
1449 ufshcd_vops_config_scaling_param(hba, &hba->vps->devfreq_profile,
1450 &hba->vps->ondemand_data);
1451 devfreq = devfreq_add_device(hba->dev,
1452 &hba->vps->devfreq_profile,
1453 DEVFREQ_GOV_SIMPLE_ONDEMAND,
1454 &hba->vps->ondemand_data);
1455 if (IS_ERR(devfreq)) {
1456 ret = PTR_ERR(devfreq);
1457 dev_err(hba->dev, "Unable to register with devfreq %d\n", ret);
1459 dev_pm_opp_remove(hba->dev, clki->min_freq);
1460 dev_pm_opp_remove(hba->dev, clki->max_freq);
1464 hba->devfreq = devfreq;
1469 static void ufshcd_devfreq_remove(struct ufs_hba *hba)
1471 struct list_head *clk_list = &hba->clk_list_head;
1472 struct ufs_clk_info *clki;
1477 devfreq_remove_device(hba->devfreq);
1478 hba->devfreq = NULL;
1480 clki = list_first_entry(clk_list, struct ufs_clk_info, list);
1481 dev_pm_opp_remove(hba->dev, clki->min_freq);
1482 dev_pm_opp_remove(hba->dev, clki->max_freq);
1485 static void __ufshcd_suspend_clkscaling(struct ufs_hba *hba)
1487 unsigned long flags;
1489 devfreq_suspend_device(hba->devfreq);
1490 spin_lock_irqsave(hba->host->host_lock, flags);
1491 hba->clk_scaling.window_start_t = 0;
1492 spin_unlock_irqrestore(hba->host->host_lock, flags);
1495 static void ufshcd_suspend_clkscaling(struct ufs_hba *hba)
1497 unsigned long flags;
1498 bool suspend = false;
1500 cancel_work_sync(&hba->clk_scaling.suspend_work);
1501 cancel_work_sync(&hba->clk_scaling.resume_work);
1503 spin_lock_irqsave(hba->host->host_lock, flags);
1504 if (!hba->clk_scaling.is_suspended) {
1506 hba->clk_scaling.is_suspended = true;
1508 spin_unlock_irqrestore(hba->host->host_lock, flags);
1511 __ufshcd_suspend_clkscaling(hba);
1514 static void ufshcd_resume_clkscaling(struct ufs_hba *hba)
1516 unsigned long flags;
1517 bool resume = false;
1519 spin_lock_irqsave(hba->host->host_lock, flags);
1520 if (hba->clk_scaling.is_suspended) {
1522 hba->clk_scaling.is_suspended = false;
1524 spin_unlock_irqrestore(hba->host->host_lock, flags);
1527 devfreq_resume_device(hba->devfreq);
1530 static ssize_t ufshcd_clkscale_enable_show(struct device *dev,
1531 struct device_attribute *attr, char *buf)
1533 struct ufs_hba *hba = dev_get_drvdata(dev);
1535 return sysfs_emit(buf, "%d\n", hba->clk_scaling.is_enabled);
1538 static ssize_t ufshcd_clkscale_enable_store(struct device *dev,
1539 struct device_attribute *attr, const char *buf, size_t count)
1541 struct ufs_hba *hba = dev_get_drvdata(dev);
1545 if (kstrtou32(buf, 0, &value))
1548 down(&hba->host_sem);
1549 if (!ufshcd_is_user_access_allowed(hba)) {
1555 if (value == hba->clk_scaling.is_enabled)
1558 ufshcd_rpm_get_sync(hba);
1559 ufshcd_hold(hba, false);
1561 hba->clk_scaling.is_enabled = value;
1564 ufshcd_resume_clkscaling(hba);
1566 ufshcd_suspend_clkscaling(hba);
1567 err = ufshcd_devfreq_scale(hba, true);
1569 dev_err(hba->dev, "%s: failed to scale clocks up %d\n",
1573 ufshcd_release(hba);
1574 ufshcd_rpm_put_sync(hba);
1577 return err ? err : count;
1580 static void ufshcd_init_clk_scaling_sysfs(struct ufs_hba *hba)
1582 hba->clk_scaling.enable_attr.show = ufshcd_clkscale_enable_show;
1583 hba->clk_scaling.enable_attr.store = ufshcd_clkscale_enable_store;
1584 sysfs_attr_init(&hba->clk_scaling.enable_attr.attr);
1585 hba->clk_scaling.enable_attr.attr.name = "clkscale_enable";
1586 hba->clk_scaling.enable_attr.attr.mode = 0644;
1587 if (device_create_file(hba->dev, &hba->clk_scaling.enable_attr))
1588 dev_err(hba->dev, "Failed to create sysfs for clkscale_enable\n");
1591 static void ufshcd_remove_clk_scaling_sysfs(struct ufs_hba *hba)
1593 if (hba->clk_scaling.enable_attr.attr.name)
1594 device_remove_file(hba->dev, &hba->clk_scaling.enable_attr);
1597 static void ufshcd_init_clk_scaling(struct ufs_hba *hba)
1599 char wq_name[sizeof("ufs_clkscaling_00")];
1601 if (!ufshcd_is_clkscaling_supported(hba))
1604 if (!hba->clk_scaling.min_gear)
1605 hba->clk_scaling.min_gear = UFS_HS_G1;
1607 INIT_WORK(&hba->clk_scaling.suspend_work,
1608 ufshcd_clk_scaling_suspend_work);
1609 INIT_WORK(&hba->clk_scaling.resume_work,
1610 ufshcd_clk_scaling_resume_work);
1612 snprintf(wq_name, sizeof(wq_name), "ufs_clkscaling_%d",
1613 hba->host->host_no);
1614 hba->clk_scaling.workq = create_singlethread_workqueue(wq_name);
1616 hba->clk_scaling.is_initialized = true;
1619 static void ufshcd_exit_clk_scaling(struct ufs_hba *hba)
1621 if (!hba->clk_scaling.is_initialized)
1624 ufshcd_remove_clk_scaling_sysfs(hba);
1625 destroy_workqueue(hba->clk_scaling.workq);
1626 ufshcd_devfreq_remove(hba);
1627 hba->clk_scaling.is_initialized = false;
1630 static void ufshcd_ungate_work(struct work_struct *work)
1633 unsigned long flags;
1634 struct ufs_hba *hba = container_of(work, struct ufs_hba,
1635 clk_gating.ungate_work);
1637 cancel_delayed_work_sync(&hba->clk_gating.gate_work);
1639 spin_lock_irqsave(hba->host->host_lock, flags);
1640 if (hba->clk_gating.state == CLKS_ON) {
1641 spin_unlock_irqrestore(hba->host->host_lock, flags);
1645 spin_unlock_irqrestore(hba->host->host_lock, flags);
1646 ufshcd_hba_vreg_set_hpm(hba);
1647 ufshcd_setup_clocks(hba, true);
1649 ufshcd_enable_irq(hba);
1651 /* Exit from hibern8 */
1652 if (ufshcd_can_hibern8_during_gating(hba)) {
1653 /* Prevent gating in this path */
1654 hba->clk_gating.is_suspended = true;
1655 if (ufshcd_is_link_hibern8(hba)) {
1656 ret = ufshcd_uic_hibern8_exit(hba);
1658 dev_err(hba->dev, "%s: hibern8 exit failed %d\n",
1661 ufshcd_set_link_active(hba);
1663 hba->clk_gating.is_suspended = false;
1666 ufshcd_scsi_unblock_requests(hba);
1670 * ufshcd_hold - Enable clocks that were gated earlier due to ufshcd_release.
1671 * Also, exit from hibern8 mode and set the link as active.
1672 * @hba: per adapter instance
1673 * @async: This indicates whether caller should ungate clocks asynchronously.
1675 int ufshcd_hold(struct ufs_hba *hba, bool async)
1679 unsigned long flags;
1681 if (!ufshcd_is_clkgating_allowed(hba))
1683 spin_lock_irqsave(hba->host->host_lock, flags);
1684 hba->clk_gating.active_reqs++;
1687 switch (hba->clk_gating.state) {
1690 * Wait for the ungate work to complete if in progress.
1691 * Though the clocks may be in ON state, the link could
1692 * still be in hibner8 state if hibern8 is allowed
1693 * during clock gating.
1694 * Make sure we exit hibern8 state also in addition to
1697 if (ufshcd_can_hibern8_during_gating(hba) &&
1698 ufshcd_is_link_hibern8(hba)) {
1701 hba->clk_gating.active_reqs--;
1704 spin_unlock_irqrestore(hba->host->host_lock, flags);
1705 flush_result = flush_work(&hba->clk_gating.ungate_work);
1706 if (hba->clk_gating.is_suspended && !flush_result)
1708 spin_lock_irqsave(hba->host->host_lock, flags);
1713 if (cancel_delayed_work(&hba->clk_gating.gate_work)) {
1714 hba->clk_gating.state = CLKS_ON;
1715 trace_ufshcd_clk_gating(dev_name(hba->dev),
1716 hba->clk_gating.state);
1720 * If we are here, it means gating work is either done or
1721 * currently running. Hence, fall through to cancel gating
1722 * work and to enable clocks.
1726 hba->clk_gating.state = REQ_CLKS_ON;
1727 trace_ufshcd_clk_gating(dev_name(hba->dev),
1728 hba->clk_gating.state);
1729 if (queue_work(hba->clk_gating.clk_gating_workq,
1730 &hba->clk_gating.ungate_work))
1731 ufshcd_scsi_block_requests(hba);
1733 * fall through to check if we should wait for this
1734 * work to be done or not.
1740 hba->clk_gating.active_reqs--;
1744 spin_unlock_irqrestore(hba->host->host_lock, flags);
1745 flush_work(&hba->clk_gating.ungate_work);
1746 /* Make sure state is CLKS_ON before returning */
1747 spin_lock_irqsave(hba->host->host_lock, flags);
1750 dev_err(hba->dev, "%s: clk gating is in invalid state %d\n",
1751 __func__, hba->clk_gating.state);
1754 spin_unlock_irqrestore(hba->host->host_lock, flags);
1758 EXPORT_SYMBOL_GPL(ufshcd_hold);
1760 static void ufshcd_gate_work(struct work_struct *work)
1762 struct ufs_hba *hba = container_of(work, struct ufs_hba,
1763 clk_gating.gate_work.work);
1764 unsigned long flags;
1767 spin_lock_irqsave(hba->host->host_lock, flags);
1769 * In case you are here to cancel this work the gating state
1770 * would be marked as REQ_CLKS_ON. In this case save time by
1771 * skipping the gating work and exit after changing the clock
1774 if (hba->clk_gating.is_suspended ||
1775 (hba->clk_gating.state != REQ_CLKS_OFF)) {
1776 hba->clk_gating.state = CLKS_ON;
1777 trace_ufshcd_clk_gating(dev_name(hba->dev),
1778 hba->clk_gating.state);
1782 if (hba->clk_gating.active_reqs
1783 || hba->ufshcd_state != UFSHCD_STATE_OPERATIONAL
1784 || ufshcd_any_tag_in_use(hba) || hba->outstanding_tasks
1785 || hba->active_uic_cmd || hba->uic_async_done)
1788 spin_unlock_irqrestore(hba->host->host_lock, flags);
1790 /* put the link into hibern8 mode before turning off clocks */
1791 if (ufshcd_can_hibern8_during_gating(hba)) {
1792 ret = ufshcd_uic_hibern8_enter(hba);
1794 hba->clk_gating.state = CLKS_ON;
1795 dev_err(hba->dev, "%s: hibern8 enter failed %d\n",
1797 trace_ufshcd_clk_gating(dev_name(hba->dev),
1798 hba->clk_gating.state);
1801 ufshcd_set_link_hibern8(hba);
1804 ufshcd_disable_irq(hba);
1806 ufshcd_setup_clocks(hba, false);
1808 /* Put the host controller in low power mode if possible */
1809 ufshcd_hba_vreg_set_lpm(hba);
1811 * In case you are here to cancel this work the gating state
1812 * would be marked as REQ_CLKS_ON. In this case keep the state
1813 * as REQ_CLKS_ON which would anyway imply that clocks are off
1814 * and a request to turn them on is pending. By doing this way,
1815 * we keep the state machine in tact and this would ultimately
1816 * prevent from doing cancel work multiple times when there are
1817 * new requests arriving before the current cancel work is done.
1819 spin_lock_irqsave(hba->host->host_lock, flags);
1820 if (hba->clk_gating.state == REQ_CLKS_OFF) {
1821 hba->clk_gating.state = CLKS_OFF;
1822 trace_ufshcd_clk_gating(dev_name(hba->dev),
1823 hba->clk_gating.state);
1826 spin_unlock_irqrestore(hba->host->host_lock, flags);
1831 /* host lock must be held before calling this variant */
1832 static void __ufshcd_release(struct ufs_hba *hba)
1834 if (!ufshcd_is_clkgating_allowed(hba))
1837 hba->clk_gating.active_reqs--;
1839 if (hba->clk_gating.active_reqs || hba->clk_gating.is_suspended ||
1840 hba->ufshcd_state != UFSHCD_STATE_OPERATIONAL ||
1841 hba->outstanding_tasks ||
1842 hba->active_uic_cmd || hba->uic_async_done ||
1843 hba->clk_gating.state == CLKS_OFF)
1846 hba->clk_gating.state = REQ_CLKS_OFF;
1847 trace_ufshcd_clk_gating(dev_name(hba->dev), hba->clk_gating.state);
1848 queue_delayed_work(hba->clk_gating.clk_gating_workq,
1849 &hba->clk_gating.gate_work,
1850 msecs_to_jiffies(hba->clk_gating.delay_ms));
1853 void ufshcd_release(struct ufs_hba *hba)
1855 unsigned long flags;
1857 spin_lock_irqsave(hba->host->host_lock, flags);
1858 __ufshcd_release(hba);
1859 spin_unlock_irqrestore(hba->host->host_lock, flags);
1861 EXPORT_SYMBOL_GPL(ufshcd_release);
1863 static ssize_t ufshcd_clkgate_delay_show(struct device *dev,
1864 struct device_attribute *attr, char *buf)
1866 struct ufs_hba *hba = dev_get_drvdata(dev);
1868 return sysfs_emit(buf, "%lu\n", hba->clk_gating.delay_ms);
1871 static ssize_t ufshcd_clkgate_delay_store(struct device *dev,
1872 struct device_attribute *attr, const char *buf, size_t count)
1874 struct ufs_hba *hba = dev_get_drvdata(dev);
1875 unsigned long flags, value;
1877 if (kstrtoul(buf, 0, &value))
1880 spin_lock_irqsave(hba->host->host_lock, flags);
1881 hba->clk_gating.delay_ms = value;
1882 spin_unlock_irqrestore(hba->host->host_lock, flags);
1886 static ssize_t ufshcd_clkgate_enable_show(struct device *dev,
1887 struct device_attribute *attr, char *buf)
1889 struct ufs_hba *hba = dev_get_drvdata(dev);
1891 return sysfs_emit(buf, "%d\n", hba->clk_gating.is_enabled);
1894 static ssize_t ufshcd_clkgate_enable_store(struct device *dev,
1895 struct device_attribute *attr, const char *buf, size_t count)
1897 struct ufs_hba *hba = dev_get_drvdata(dev);
1898 unsigned long flags;
1901 if (kstrtou32(buf, 0, &value))
1906 spin_lock_irqsave(hba->host->host_lock, flags);
1907 if (value == hba->clk_gating.is_enabled)
1911 __ufshcd_release(hba);
1913 hba->clk_gating.active_reqs++;
1915 hba->clk_gating.is_enabled = value;
1917 spin_unlock_irqrestore(hba->host->host_lock, flags);
1921 static void ufshcd_init_clk_gating_sysfs(struct ufs_hba *hba)
1923 hba->clk_gating.delay_attr.show = ufshcd_clkgate_delay_show;
1924 hba->clk_gating.delay_attr.store = ufshcd_clkgate_delay_store;
1925 sysfs_attr_init(&hba->clk_gating.delay_attr.attr);
1926 hba->clk_gating.delay_attr.attr.name = "clkgate_delay_ms";
1927 hba->clk_gating.delay_attr.attr.mode = 0644;
1928 if (device_create_file(hba->dev, &hba->clk_gating.delay_attr))
1929 dev_err(hba->dev, "Failed to create sysfs for clkgate_delay\n");
1931 hba->clk_gating.enable_attr.show = ufshcd_clkgate_enable_show;
1932 hba->clk_gating.enable_attr.store = ufshcd_clkgate_enable_store;
1933 sysfs_attr_init(&hba->clk_gating.enable_attr.attr);
1934 hba->clk_gating.enable_attr.attr.name = "clkgate_enable";
1935 hba->clk_gating.enable_attr.attr.mode = 0644;
1936 if (device_create_file(hba->dev, &hba->clk_gating.enable_attr))
1937 dev_err(hba->dev, "Failed to create sysfs for clkgate_enable\n");
1940 static void ufshcd_remove_clk_gating_sysfs(struct ufs_hba *hba)
1942 if (hba->clk_gating.delay_attr.attr.name)
1943 device_remove_file(hba->dev, &hba->clk_gating.delay_attr);
1944 if (hba->clk_gating.enable_attr.attr.name)
1945 device_remove_file(hba->dev, &hba->clk_gating.enable_attr);
1948 static void ufshcd_init_clk_gating(struct ufs_hba *hba)
1950 char wq_name[sizeof("ufs_clk_gating_00")];
1952 if (!ufshcd_is_clkgating_allowed(hba))
1955 hba->clk_gating.state = CLKS_ON;
1957 hba->clk_gating.delay_ms = 150;
1958 INIT_DELAYED_WORK(&hba->clk_gating.gate_work, ufshcd_gate_work);
1959 INIT_WORK(&hba->clk_gating.ungate_work, ufshcd_ungate_work);
1961 snprintf(wq_name, ARRAY_SIZE(wq_name), "ufs_clk_gating_%d",
1962 hba->host->host_no);
1963 hba->clk_gating.clk_gating_workq = alloc_ordered_workqueue(wq_name,
1964 WQ_MEM_RECLAIM | WQ_HIGHPRI);
1966 ufshcd_init_clk_gating_sysfs(hba);
1968 hba->clk_gating.is_enabled = true;
1969 hba->clk_gating.is_initialized = true;
1972 static void ufshcd_exit_clk_gating(struct ufs_hba *hba)
1974 if (!hba->clk_gating.is_initialized)
1976 ufshcd_remove_clk_gating_sysfs(hba);
1977 cancel_work_sync(&hba->clk_gating.ungate_work);
1978 cancel_delayed_work_sync(&hba->clk_gating.gate_work);
1979 destroy_workqueue(hba->clk_gating.clk_gating_workq);
1980 hba->clk_gating.is_initialized = false;
1983 /* Must be called with host lock acquired */
1984 static void ufshcd_clk_scaling_start_busy(struct ufs_hba *hba)
1986 bool queue_resume_work = false;
1987 ktime_t curr_t = ktime_get();
1988 unsigned long flags;
1990 if (!ufshcd_is_clkscaling_supported(hba))
1993 spin_lock_irqsave(hba->host->host_lock, flags);
1994 if (!hba->clk_scaling.active_reqs++)
1995 queue_resume_work = true;
1997 if (!hba->clk_scaling.is_enabled || hba->pm_op_in_progress) {
1998 spin_unlock_irqrestore(hba->host->host_lock, flags);
2002 if (queue_resume_work)
2003 queue_work(hba->clk_scaling.workq,
2004 &hba->clk_scaling.resume_work);
2006 if (!hba->clk_scaling.window_start_t) {
2007 hba->clk_scaling.window_start_t = curr_t;
2008 hba->clk_scaling.tot_busy_t = 0;
2009 hba->clk_scaling.is_busy_started = false;
2012 if (!hba->clk_scaling.is_busy_started) {
2013 hba->clk_scaling.busy_start_t = curr_t;
2014 hba->clk_scaling.is_busy_started = true;
2016 spin_unlock_irqrestore(hba->host->host_lock, flags);
2019 static void ufshcd_clk_scaling_update_busy(struct ufs_hba *hba)
2021 struct ufs_clk_scaling *scaling = &hba->clk_scaling;
2022 unsigned long flags;
2024 if (!ufshcd_is_clkscaling_supported(hba))
2027 spin_lock_irqsave(hba->host->host_lock, flags);
2028 hba->clk_scaling.active_reqs--;
2029 if (!hba->outstanding_reqs && scaling->is_busy_started) {
2030 scaling->tot_busy_t += ktime_to_us(ktime_sub(ktime_get(),
2031 scaling->busy_start_t));
2032 scaling->busy_start_t = 0;
2033 scaling->is_busy_started = false;
2035 spin_unlock_irqrestore(hba->host->host_lock, flags);
2038 static inline int ufshcd_monitor_opcode2dir(u8 opcode)
2040 if (opcode == READ_6 || opcode == READ_10 || opcode == READ_16)
2042 else if (opcode == WRITE_6 || opcode == WRITE_10 || opcode == WRITE_16)
2048 static inline bool ufshcd_should_inform_monitor(struct ufs_hba *hba,
2049 struct ufshcd_lrb *lrbp)
2051 struct ufs_hba_monitor *m = &hba->monitor;
2053 return (m->enabled && lrbp && lrbp->cmd &&
2054 (!m->chunk_size || m->chunk_size == lrbp->cmd->sdb.length) &&
2055 ktime_before(hba->monitor.enabled_ts, lrbp->issue_time_stamp));
2058 static void ufshcd_start_monitor(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
2060 int dir = ufshcd_monitor_opcode2dir(*lrbp->cmd->cmnd);
2061 unsigned long flags;
2063 spin_lock_irqsave(hba->host->host_lock, flags);
2064 if (dir >= 0 && hba->monitor.nr_queued[dir]++ == 0)
2065 hba->monitor.busy_start_ts[dir] = ktime_get();
2066 spin_unlock_irqrestore(hba->host->host_lock, flags);
2069 static void ufshcd_update_monitor(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
2071 int dir = ufshcd_monitor_opcode2dir(*lrbp->cmd->cmnd);
2072 unsigned long flags;
2074 spin_lock_irqsave(hba->host->host_lock, flags);
2075 if (dir >= 0 && hba->monitor.nr_queued[dir] > 0) {
2076 struct request *req = lrbp->cmd->request;
2077 struct ufs_hba_monitor *m = &hba->monitor;
2078 ktime_t now, inc, lat;
2080 now = lrbp->compl_time_stamp;
2081 inc = ktime_sub(now, m->busy_start_ts[dir]);
2082 m->total_busy[dir] = ktime_add(m->total_busy[dir], inc);
2083 m->nr_sec_rw[dir] += blk_rq_sectors(req);
2085 /* Update latencies */
2087 lat = ktime_sub(now, lrbp->issue_time_stamp);
2088 m->lat_sum[dir] += lat;
2089 if (m->lat_max[dir] < lat || !m->lat_max[dir])
2090 m->lat_max[dir] = lat;
2091 if (m->lat_min[dir] > lat || !m->lat_min[dir])
2092 m->lat_min[dir] = lat;
2094 m->nr_queued[dir]--;
2095 /* Push forward the busy start of monitor */
2096 m->busy_start_ts[dir] = now;
2098 spin_unlock_irqrestore(hba->host->host_lock, flags);
2102 * ufshcd_send_command - Send SCSI or device management commands
2103 * @hba: per adapter instance
2104 * @task_tag: Task tag of the command
2107 void ufshcd_send_command(struct ufs_hba *hba, unsigned int task_tag)
2109 struct ufshcd_lrb *lrbp = &hba->lrb[task_tag];
2111 lrbp->issue_time_stamp = ktime_get();
2112 lrbp->compl_time_stamp = ktime_set(0, 0);
2113 ufshcd_vops_setup_xfer_req(hba, task_tag, (lrbp->cmd ? true : false));
2114 ufshcd_add_command_trace(hba, task_tag, UFS_CMD_SEND);
2115 ufshcd_clk_scaling_start_busy(hba);
2116 if (unlikely(ufshcd_should_inform_monitor(hba, lrbp)))
2117 ufshcd_start_monitor(hba, lrbp);
2118 if (ufshcd_has_utrlcnr(hba)) {
2119 set_bit(task_tag, &hba->outstanding_reqs);
2120 ufshcd_writel(hba, 1 << task_tag,
2121 REG_UTP_TRANSFER_REQ_DOOR_BELL);
2123 unsigned long flags;
2125 spin_lock_irqsave(hba->host->host_lock, flags);
2126 set_bit(task_tag, &hba->outstanding_reqs);
2127 ufshcd_writel(hba, 1 << task_tag,
2128 REG_UTP_TRANSFER_REQ_DOOR_BELL);
2129 spin_unlock_irqrestore(hba->host->host_lock, flags);
2131 /* Make sure that doorbell is committed immediately */
2136 * ufshcd_copy_sense_data - Copy sense data in case of check condition
2137 * @lrbp: pointer to local reference block
2139 static inline void ufshcd_copy_sense_data(struct ufshcd_lrb *lrbp)
2142 if (lrbp->sense_buffer &&
2143 ufshcd_get_rsp_upiu_data_seg_len(lrbp->ucd_rsp_ptr)) {
2146 len = be16_to_cpu(lrbp->ucd_rsp_ptr->sr.sense_data_len);
2147 len_to_copy = min_t(int, UFS_SENSE_SIZE, len);
2149 memcpy(lrbp->sense_buffer, lrbp->ucd_rsp_ptr->sr.sense_data,
2155 * ufshcd_copy_query_response() - Copy the Query Response and the data
2157 * @hba: per adapter instance
2158 * @lrbp: pointer to local reference block
2161 int ufshcd_copy_query_response(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
2163 struct ufs_query_res *query_res = &hba->dev_cmd.query.response;
2165 memcpy(&query_res->upiu_res, &lrbp->ucd_rsp_ptr->qr, QUERY_OSF_SIZE);
2167 /* Get the descriptor */
2168 if (hba->dev_cmd.query.descriptor &&
2169 lrbp->ucd_rsp_ptr->qr.opcode == UPIU_QUERY_OPCODE_READ_DESC) {
2170 u8 *descp = (u8 *)lrbp->ucd_rsp_ptr +
2171 GENERAL_UPIU_REQUEST_SIZE;
2175 /* data segment length */
2176 resp_len = be32_to_cpu(lrbp->ucd_rsp_ptr->header.dword_2) &
2177 MASK_QUERY_DATA_SEG_LEN;
2178 buf_len = be16_to_cpu(
2179 hba->dev_cmd.query.request.upiu_req.length);
2180 if (likely(buf_len >= resp_len)) {
2181 memcpy(hba->dev_cmd.query.descriptor, descp, resp_len);
2184 "%s: rsp size %d is bigger than buffer size %d",
2185 __func__, resp_len, buf_len);
2194 * ufshcd_hba_capabilities - Read controller capabilities
2195 * @hba: per adapter instance
2197 * Return: 0 on success, negative on error.
2199 static inline int ufshcd_hba_capabilities(struct ufs_hba *hba)
2203 hba->capabilities = ufshcd_readl(hba, REG_CONTROLLER_CAPABILITIES);
2205 /* nutrs and nutmrs are 0 based values */
2206 hba->nutrs = (hba->capabilities & MASK_TRANSFER_REQUESTS_SLOTS) + 1;
2208 ((hba->capabilities & MASK_TASK_MANAGEMENT_REQUEST_SLOTS) >> 16) + 1;
2210 /* Read crypto capabilities */
2211 err = ufshcd_hba_init_crypto_capabilities(hba);
2213 dev_err(hba->dev, "crypto setup failed\n");
2219 * ufshcd_ready_for_uic_cmd - Check if controller is ready
2220 * to accept UIC commands
2221 * @hba: per adapter instance
2222 * Return true on success, else false
2224 static inline bool ufshcd_ready_for_uic_cmd(struct ufs_hba *hba)
2226 if (ufshcd_readl(hba, REG_CONTROLLER_STATUS) & UIC_COMMAND_READY)
2233 * ufshcd_get_upmcrs - Get the power mode change request status
2234 * @hba: Pointer to adapter instance
2236 * This function gets the UPMCRS field of HCS register
2237 * Returns value of UPMCRS field
2239 static inline u8 ufshcd_get_upmcrs(struct ufs_hba *hba)
2241 return (ufshcd_readl(hba, REG_CONTROLLER_STATUS) >> 8) & 0x7;
2245 * ufshcd_dispatch_uic_cmd - Dispatch an UIC command to the Unipro layer
2246 * @hba: per adapter instance
2247 * @uic_cmd: UIC command
2250 ufshcd_dispatch_uic_cmd(struct ufs_hba *hba, struct uic_command *uic_cmd)
2252 lockdep_assert_held(&hba->uic_cmd_mutex);
2254 WARN_ON(hba->active_uic_cmd);
2256 hba->active_uic_cmd = uic_cmd;
2259 ufshcd_writel(hba, uic_cmd->argument1, REG_UIC_COMMAND_ARG_1);
2260 ufshcd_writel(hba, uic_cmd->argument2, REG_UIC_COMMAND_ARG_2);
2261 ufshcd_writel(hba, uic_cmd->argument3, REG_UIC_COMMAND_ARG_3);
2263 ufshcd_add_uic_command_trace(hba, uic_cmd, UFS_CMD_SEND);
2266 ufshcd_writel(hba, uic_cmd->command & COMMAND_OPCODE_MASK,
2271 * ufshcd_wait_for_uic_cmd - Wait for completion of an UIC command
2272 * @hba: per adapter instance
2273 * @uic_cmd: UIC command
2275 * Returns 0 only if success.
2278 ufshcd_wait_for_uic_cmd(struct ufs_hba *hba, struct uic_command *uic_cmd)
2281 unsigned long flags;
2283 lockdep_assert_held(&hba->uic_cmd_mutex);
2285 if (wait_for_completion_timeout(&uic_cmd->done,
2286 msecs_to_jiffies(UIC_CMD_TIMEOUT))) {
2287 ret = uic_cmd->argument2 & MASK_UIC_COMMAND_RESULT;
2291 "uic cmd 0x%x with arg3 0x%x completion timeout\n",
2292 uic_cmd->command, uic_cmd->argument3);
2294 if (!uic_cmd->cmd_active) {
2295 dev_err(hba->dev, "%s: UIC cmd has been completed, return the result\n",
2297 ret = uic_cmd->argument2 & MASK_UIC_COMMAND_RESULT;
2301 spin_lock_irqsave(hba->host->host_lock, flags);
2302 hba->active_uic_cmd = NULL;
2303 spin_unlock_irqrestore(hba->host->host_lock, flags);
2309 * __ufshcd_send_uic_cmd - Send UIC commands and retrieve the result
2310 * @hba: per adapter instance
2311 * @uic_cmd: UIC command
2312 * @completion: initialize the completion only if this is set to true
2314 * Returns 0 only if success.
2317 __ufshcd_send_uic_cmd(struct ufs_hba *hba, struct uic_command *uic_cmd,
2320 lockdep_assert_held(&hba->uic_cmd_mutex);
2321 lockdep_assert_held(hba->host->host_lock);
2323 if (!ufshcd_ready_for_uic_cmd(hba)) {
2325 "Controller not ready to accept UIC commands\n");
2330 init_completion(&uic_cmd->done);
2332 uic_cmd->cmd_active = 1;
2333 ufshcd_dispatch_uic_cmd(hba, uic_cmd);
2339 * ufshcd_send_uic_cmd - Send UIC commands and retrieve the result
2340 * @hba: per adapter instance
2341 * @uic_cmd: UIC command
2343 * Returns 0 only if success.
2345 int ufshcd_send_uic_cmd(struct ufs_hba *hba, struct uic_command *uic_cmd)
2348 unsigned long flags;
2350 ufshcd_hold(hba, false);
2351 mutex_lock(&hba->uic_cmd_mutex);
2352 ufshcd_add_delay_before_dme_cmd(hba);
2354 spin_lock_irqsave(hba->host->host_lock, flags);
2355 ret = __ufshcd_send_uic_cmd(hba, uic_cmd, true);
2356 spin_unlock_irqrestore(hba->host->host_lock, flags);
2358 ret = ufshcd_wait_for_uic_cmd(hba, uic_cmd);
2360 mutex_unlock(&hba->uic_cmd_mutex);
2362 ufshcd_release(hba);
2367 * ufshcd_map_sg - Map scatter-gather list to prdt
2368 * @hba: per adapter instance
2369 * @lrbp: pointer to local reference block
2371 * Returns 0 in case of success, non-zero value in case of failure
2373 static int ufshcd_map_sg(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
2375 struct ufshcd_sg_entry *prd_table;
2376 struct scatterlist *sg;
2377 struct scsi_cmnd *cmd;
2382 sg_segments = scsi_dma_map(cmd);
2383 if (sg_segments < 0)
2388 if (hba->quirks & UFSHCD_QUIRK_PRDT_BYTE_GRAN)
2389 lrbp->utr_descriptor_ptr->prd_table_length =
2390 cpu_to_le16((sg_segments *
2391 sizeof(struct ufshcd_sg_entry)));
2393 lrbp->utr_descriptor_ptr->prd_table_length =
2394 cpu_to_le16((u16) (sg_segments));
2396 prd_table = (struct ufshcd_sg_entry *)lrbp->ucd_prdt_ptr;
2398 scsi_for_each_sg(cmd, sg, sg_segments, i) {
2400 cpu_to_le32(((u32) sg_dma_len(sg))-1);
2401 prd_table[i].base_addr =
2402 cpu_to_le32(lower_32_bits(sg->dma_address));
2403 prd_table[i].upper_addr =
2404 cpu_to_le32(upper_32_bits(sg->dma_address));
2405 prd_table[i].reserved = 0;
2408 lrbp->utr_descriptor_ptr->prd_table_length = 0;
2415 * ufshcd_enable_intr - enable interrupts
2416 * @hba: per adapter instance
2417 * @intrs: interrupt bits
2419 static void ufshcd_enable_intr(struct ufs_hba *hba, u32 intrs)
2421 u32 set = ufshcd_readl(hba, REG_INTERRUPT_ENABLE);
2423 if (hba->ufs_version == ufshci_version(1, 0)) {
2425 rw = set & INTERRUPT_MASK_RW_VER_10;
2426 set = rw | ((set ^ intrs) & intrs);
2431 ufshcd_writel(hba, set, REG_INTERRUPT_ENABLE);
2435 * ufshcd_disable_intr - disable interrupts
2436 * @hba: per adapter instance
2437 * @intrs: interrupt bits
2439 static void ufshcd_disable_intr(struct ufs_hba *hba, u32 intrs)
2441 u32 set = ufshcd_readl(hba, REG_INTERRUPT_ENABLE);
2443 if (hba->ufs_version == ufshci_version(1, 0)) {
2445 rw = (set & INTERRUPT_MASK_RW_VER_10) &
2446 ~(intrs & INTERRUPT_MASK_RW_VER_10);
2447 set = rw | ((set & intrs) & ~INTERRUPT_MASK_RW_VER_10);
2453 ufshcd_writel(hba, set, REG_INTERRUPT_ENABLE);
2457 * ufshcd_prepare_req_desc_hdr() - Fills the requests header
2458 * descriptor according to request
2459 * @lrbp: pointer to local reference block
2460 * @upiu_flags: flags required in the header
2461 * @cmd_dir: requests data direction
2463 static void ufshcd_prepare_req_desc_hdr(struct ufshcd_lrb *lrbp,
2464 u8 *upiu_flags, enum dma_data_direction cmd_dir)
2466 struct utp_transfer_req_desc *req_desc = lrbp->utr_descriptor_ptr;
2472 if (cmd_dir == DMA_FROM_DEVICE) {
2473 data_direction = UTP_DEVICE_TO_HOST;
2474 *upiu_flags = UPIU_CMD_FLAGS_READ;
2475 } else if (cmd_dir == DMA_TO_DEVICE) {
2476 data_direction = UTP_HOST_TO_DEVICE;
2477 *upiu_flags = UPIU_CMD_FLAGS_WRITE;
2479 data_direction = UTP_NO_DATA_TRANSFER;
2480 *upiu_flags = UPIU_CMD_FLAGS_NONE;
2483 dword_0 = data_direction | (lrbp->command_type
2484 << UPIU_COMMAND_TYPE_OFFSET);
2486 dword_0 |= UTP_REQ_DESC_INT_CMD;
2488 /* Prepare crypto related dwords */
2489 ufshcd_prepare_req_desc_hdr_crypto(lrbp, &dword_0, &dword_1, &dword_3);
2491 /* Transfer request descriptor header fields */
2492 req_desc->header.dword_0 = cpu_to_le32(dword_0);
2493 req_desc->header.dword_1 = cpu_to_le32(dword_1);
2495 * assigning invalid value for command status. Controller
2496 * updates OCS on command completion, with the command
2499 req_desc->header.dword_2 =
2500 cpu_to_le32(OCS_INVALID_COMMAND_STATUS);
2501 req_desc->header.dword_3 = cpu_to_le32(dword_3);
2503 req_desc->prd_table_length = 0;
2507 * ufshcd_prepare_utp_scsi_cmd_upiu() - fills the utp_transfer_req_desc,
2509 * @lrbp: local reference block pointer
2510 * @upiu_flags: flags
2513 void ufshcd_prepare_utp_scsi_cmd_upiu(struct ufshcd_lrb *lrbp, u8 upiu_flags)
2515 struct scsi_cmnd *cmd = lrbp->cmd;
2516 struct utp_upiu_req *ucd_req_ptr = lrbp->ucd_req_ptr;
2517 unsigned short cdb_len;
2519 /* command descriptor fields */
2520 ucd_req_ptr->header.dword_0 = UPIU_HEADER_DWORD(
2521 UPIU_TRANSACTION_COMMAND, upiu_flags,
2522 lrbp->lun, lrbp->task_tag);
2523 ucd_req_ptr->header.dword_1 = UPIU_HEADER_DWORD(
2524 UPIU_COMMAND_SET_TYPE_SCSI, 0, 0, 0);
2526 /* Total EHS length and Data segment length will be zero */
2527 ucd_req_ptr->header.dword_2 = 0;
2529 ucd_req_ptr->sc.exp_data_transfer_len = cpu_to_be32(cmd->sdb.length);
2531 cdb_len = min_t(unsigned short, cmd->cmd_len, UFS_CDB_SIZE);
2532 memset(ucd_req_ptr->sc.cdb, 0, UFS_CDB_SIZE);
2533 memcpy(ucd_req_ptr->sc.cdb, cmd->cmnd, cdb_len);
2535 memset(lrbp->ucd_rsp_ptr, 0, sizeof(struct utp_upiu_rsp));
2539 * ufshcd_prepare_utp_query_req_upiu() - fills the utp_transfer_req_desc,
2542 * @lrbp: local reference block pointer
2543 * @upiu_flags: flags
2545 static void ufshcd_prepare_utp_query_req_upiu(struct ufs_hba *hba,
2546 struct ufshcd_lrb *lrbp, u8 upiu_flags)
2548 struct utp_upiu_req *ucd_req_ptr = lrbp->ucd_req_ptr;
2549 struct ufs_query *query = &hba->dev_cmd.query;
2550 u16 len = be16_to_cpu(query->request.upiu_req.length);
2552 /* Query request header */
2553 ucd_req_ptr->header.dword_0 = UPIU_HEADER_DWORD(
2554 UPIU_TRANSACTION_QUERY_REQ, upiu_flags,
2555 lrbp->lun, lrbp->task_tag);
2556 ucd_req_ptr->header.dword_1 = UPIU_HEADER_DWORD(
2557 0, query->request.query_func, 0, 0);
2559 /* Data segment length only need for WRITE_DESC */
2560 if (query->request.upiu_req.opcode == UPIU_QUERY_OPCODE_WRITE_DESC)
2561 ucd_req_ptr->header.dword_2 =
2562 UPIU_HEADER_DWORD(0, 0, (len >> 8), (u8)len);
2564 ucd_req_ptr->header.dword_2 = 0;
2566 /* Copy the Query Request buffer as is */
2567 memcpy(&ucd_req_ptr->qr, &query->request.upiu_req,
2570 /* Copy the Descriptor */
2571 if (query->request.upiu_req.opcode == UPIU_QUERY_OPCODE_WRITE_DESC)
2572 memcpy(ucd_req_ptr + 1, query->descriptor, len);
2574 memset(lrbp->ucd_rsp_ptr, 0, sizeof(struct utp_upiu_rsp));
2577 static inline void ufshcd_prepare_utp_nop_upiu(struct ufshcd_lrb *lrbp)
2579 struct utp_upiu_req *ucd_req_ptr = lrbp->ucd_req_ptr;
2581 memset(ucd_req_ptr, 0, sizeof(struct utp_upiu_req));
2583 /* command descriptor fields */
2584 ucd_req_ptr->header.dword_0 =
2586 UPIU_TRANSACTION_NOP_OUT, 0, 0, lrbp->task_tag);
2587 /* clear rest of the fields of basic header */
2588 ucd_req_ptr->header.dword_1 = 0;
2589 ucd_req_ptr->header.dword_2 = 0;
2591 memset(lrbp->ucd_rsp_ptr, 0, sizeof(struct utp_upiu_rsp));
2595 * ufshcd_compose_devman_upiu - UFS Protocol Information Unit(UPIU)
2596 * for Device Management Purposes
2597 * @hba: per adapter instance
2598 * @lrbp: pointer to local reference block
2600 static int ufshcd_compose_devman_upiu(struct ufs_hba *hba,
2601 struct ufshcd_lrb *lrbp)
2606 if (hba->ufs_version <= ufshci_version(1, 1))
2607 lrbp->command_type = UTP_CMD_TYPE_DEV_MANAGE;
2609 lrbp->command_type = UTP_CMD_TYPE_UFS_STORAGE;
2611 ufshcd_prepare_req_desc_hdr(lrbp, &upiu_flags, DMA_NONE);
2612 if (hba->dev_cmd.type == DEV_CMD_TYPE_QUERY)
2613 ufshcd_prepare_utp_query_req_upiu(hba, lrbp, upiu_flags);
2614 else if (hba->dev_cmd.type == DEV_CMD_TYPE_NOP)
2615 ufshcd_prepare_utp_nop_upiu(lrbp);
2623 * ufshcd_comp_scsi_upiu - UFS Protocol Information Unit(UPIU)
2625 * @hba: per adapter instance
2626 * @lrbp: pointer to local reference block
2628 static int ufshcd_comp_scsi_upiu(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
2633 if (hba->ufs_version <= ufshci_version(1, 1))
2634 lrbp->command_type = UTP_CMD_TYPE_SCSI;
2636 lrbp->command_type = UTP_CMD_TYPE_UFS_STORAGE;
2638 if (likely(lrbp->cmd)) {
2639 ufshcd_prepare_req_desc_hdr(lrbp, &upiu_flags,
2640 lrbp->cmd->sc_data_direction);
2641 ufshcd_prepare_utp_scsi_cmd_upiu(lrbp, upiu_flags);
2650 * ufshcd_upiu_wlun_to_scsi_wlun - maps UPIU W-LUN id to SCSI W-LUN ID
2651 * @upiu_wlun_id: UPIU W-LUN id
2653 * Returns SCSI W-LUN id
2655 static inline u16 ufshcd_upiu_wlun_to_scsi_wlun(u8 upiu_wlun_id)
2657 return (upiu_wlun_id & ~UFS_UPIU_WLUN_ID) | SCSI_W_LUN_BASE;
2660 static inline bool is_rpmb_wlun(struct scsi_device *sdev)
2662 return sdev->lun == ufshcd_upiu_wlun_to_scsi_wlun(UFS_UPIU_RPMB_WLUN);
2665 static inline bool is_device_wlun(struct scsi_device *sdev)
2668 ufshcd_upiu_wlun_to_scsi_wlun(UFS_UPIU_UFS_DEVICE_WLUN);
2671 static void ufshcd_init_lrb(struct ufs_hba *hba, struct ufshcd_lrb *lrb, int i)
2673 struct utp_transfer_cmd_desc *cmd_descp = hba->ucdl_base_addr;
2674 struct utp_transfer_req_desc *utrdlp = hba->utrdl_base_addr;
2675 dma_addr_t cmd_desc_element_addr = hba->ucdl_dma_addr +
2676 i * sizeof(struct utp_transfer_cmd_desc);
2677 u16 response_offset = offsetof(struct utp_transfer_cmd_desc,
2679 u16 prdt_offset = offsetof(struct utp_transfer_cmd_desc, prd_table);
2681 lrb->utr_descriptor_ptr = utrdlp + i;
2682 lrb->utrd_dma_addr = hba->utrdl_dma_addr +
2683 i * sizeof(struct utp_transfer_req_desc);
2684 lrb->ucd_req_ptr = (struct utp_upiu_req *)(cmd_descp + i);
2685 lrb->ucd_req_dma_addr = cmd_desc_element_addr;
2686 lrb->ucd_rsp_ptr = (struct utp_upiu_rsp *)cmd_descp[i].response_upiu;
2687 lrb->ucd_rsp_dma_addr = cmd_desc_element_addr + response_offset;
2688 lrb->ucd_prdt_ptr = (struct ufshcd_sg_entry *)cmd_descp[i].prd_table;
2689 lrb->ucd_prdt_dma_addr = cmd_desc_element_addr + prdt_offset;
2693 * ufshcd_queuecommand - main entry point for SCSI requests
2694 * @host: SCSI host pointer
2695 * @cmd: command from SCSI Midlayer
2697 * Returns 0 for success, non-zero in case of failure
2699 static int ufshcd_queuecommand(struct Scsi_Host *host, struct scsi_cmnd *cmd)
2701 struct ufs_hba *hba = shost_priv(host);
2702 int tag = cmd->request->tag;
2703 struct ufshcd_lrb *lrbp;
2706 WARN_ONCE(tag < 0, "Invalid tag %d\n", tag);
2708 if (!down_read_trylock(&hba->clk_scaling_lock))
2709 return SCSI_MLQUEUE_HOST_BUSY;
2711 switch (hba->ufshcd_state) {
2712 case UFSHCD_STATE_OPERATIONAL:
2713 case UFSHCD_STATE_EH_SCHEDULED_NON_FATAL:
2715 case UFSHCD_STATE_EH_SCHEDULED_FATAL:
2717 * pm_runtime_get_sync() is used at error handling preparation
2718 * stage. If a scsi cmd, e.g. the SSU cmd, is sent from hba's
2719 * PM ops, it can never be finished if we let SCSI layer keep
2720 * retrying it, which gets err handler stuck forever. Neither
2721 * can we let the scsi cmd pass through, because UFS is in bad
2722 * state, the scsi cmd may eventually time out, which will get
2723 * err handler blocked for too long. So, just fail the scsi cmd
2724 * sent from PM ops, err handler can recover PM error anyways.
2726 if (hba->pm_op_in_progress) {
2727 hba->force_reset = true;
2728 set_host_byte(cmd, DID_BAD_TARGET);
2729 cmd->scsi_done(cmd);
2733 case UFSHCD_STATE_RESET:
2734 err = SCSI_MLQUEUE_HOST_BUSY;
2736 case UFSHCD_STATE_ERROR:
2737 set_host_byte(cmd, DID_ERROR);
2738 cmd->scsi_done(cmd);
2741 dev_WARN_ONCE(hba->dev, 1, "%s: invalid state %d\n",
2742 __func__, hba->ufshcd_state);
2743 set_host_byte(cmd, DID_BAD_TARGET);
2744 cmd->scsi_done(cmd);
2748 hba->req_abort_count = 0;
2750 err = ufshcd_hold(hba, true);
2752 err = SCSI_MLQUEUE_HOST_BUSY;
2755 WARN_ON(ufshcd_is_clkgating_allowed(hba) &&
2756 (hba->clk_gating.state != CLKS_ON));
2758 if (unlikely(test_bit(tag, &hba->outstanding_reqs))) {
2759 if (hba->pm_op_in_progress)
2760 set_host_byte(cmd, DID_BAD_TARGET);
2762 err = SCSI_MLQUEUE_HOST_BUSY;
2763 ufshcd_release(hba);
2767 lrbp = &hba->lrb[tag];
2770 lrbp->sense_bufflen = UFS_SENSE_SIZE;
2771 lrbp->sense_buffer = cmd->sense_buffer;
2772 lrbp->task_tag = tag;
2773 lrbp->lun = ufshcd_scsi_to_upiu_lun(cmd->device->lun);
2774 lrbp->intr_cmd = !ufshcd_is_intr_aggr_allowed(hba) ? true : false;
2776 ufshcd_prepare_lrbp_crypto(cmd->request, lrbp);
2778 lrbp->req_abort_skip = false;
2780 err = ufshpb_prep(hba, lrbp);
2781 if (err == -EAGAIN) {
2783 ufshcd_release(hba);
2787 ufshcd_comp_scsi_upiu(hba, lrbp);
2789 err = ufshcd_map_sg(hba, lrbp);
2792 ufshcd_release(hba);
2795 /* Make sure descriptors are ready before ringing the doorbell */
2798 ufshcd_send_command(hba, tag);
2800 up_read(&hba->clk_scaling_lock);
2804 static int ufshcd_compose_dev_cmd(struct ufs_hba *hba,
2805 struct ufshcd_lrb *lrbp, enum dev_cmd_type cmd_type, int tag)
2808 lrbp->sense_bufflen = 0;
2809 lrbp->sense_buffer = NULL;
2810 lrbp->task_tag = tag;
2811 lrbp->lun = 0; /* device management cmd is not specific to any LUN */
2812 lrbp->intr_cmd = true; /* No interrupt aggregation */
2813 ufshcd_prepare_lrbp_crypto(NULL, lrbp);
2814 hba->dev_cmd.type = cmd_type;
2816 return ufshcd_compose_devman_upiu(hba, lrbp);
2820 ufshcd_clear_cmd(struct ufs_hba *hba, int tag)
2823 unsigned long flags;
2824 u32 mask = 1 << tag;
2826 /* clear outstanding transaction before retry */
2827 spin_lock_irqsave(hba->host->host_lock, flags);
2828 ufshcd_utrl_clear(hba, tag);
2829 spin_unlock_irqrestore(hba->host->host_lock, flags);
2832 * wait for h/w to clear corresponding bit in door-bell.
2833 * max. wait is 1 sec.
2835 err = ufshcd_wait_for_register(hba,
2836 REG_UTP_TRANSFER_REQ_DOOR_BELL,
2837 mask, ~mask, 1000, 1000);
2843 ufshcd_check_query_response(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
2845 struct ufs_query_res *query_res = &hba->dev_cmd.query.response;
2847 /* Get the UPIU response */
2848 query_res->response = ufshcd_get_rsp_upiu_result(lrbp->ucd_rsp_ptr) >>
2849 UPIU_RSP_CODE_OFFSET;
2850 return query_res->response;
2854 * ufshcd_dev_cmd_completion() - handles device management command responses
2855 * @hba: per adapter instance
2856 * @lrbp: pointer to local reference block
2859 ufshcd_dev_cmd_completion(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
2864 hba->ufs_stats.last_hibern8_exit_tstamp = ktime_set(0, 0);
2865 resp = ufshcd_get_req_rsp(lrbp->ucd_rsp_ptr);
2868 case UPIU_TRANSACTION_NOP_IN:
2869 if (hba->dev_cmd.type != DEV_CMD_TYPE_NOP) {
2871 dev_err(hba->dev, "%s: unexpected response %x\n",
2875 case UPIU_TRANSACTION_QUERY_RSP:
2876 err = ufshcd_check_query_response(hba, lrbp);
2878 err = ufshcd_copy_query_response(hba, lrbp);
2880 case UPIU_TRANSACTION_REJECT_UPIU:
2881 /* TODO: handle Reject UPIU Response */
2883 dev_err(hba->dev, "%s: Reject UPIU not fully implemented\n",
2888 dev_err(hba->dev, "%s: Invalid device management cmd response: %x\n",
2896 static int ufshcd_wait_for_dev_cmd(struct ufs_hba *hba,
2897 struct ufshcd_lrb *lrbp, int max_timeout)
2900 unsigned long time_left;
2901 unsigned long flags;
2903 time_left = wait_for_completion_timeout(hba->dev_cmd.complete,
2904 msecs_to_jiffies(max_timeout));
2906 /* Make sure descriptors are ready before ringing the doorbell */
2908 spin_lock_irqsave(hba->host->host_lock, flags);
2909 hba->dev_cmd.complete = NULL;
2910 if (likely(time_left)) {
2911 err = ufshcd_get_tr_ocs(lrbp);
2913 err = ufshcd_dev_cmd_completion(hba, lrbp);
2915 spin_unlock_irqrestore(hba->host->host_lock, flags);
2919 dev_dbg(hba->dev, "%s: dev_cmd request timedout, tag %d\n",
2920 __func__, lrbp->task_tag);
2921 if (!ufshcd_clear_cmd(hba, lrbp->task_tag))
2922 /* successfully cleared the command, retry if needed */
2925 * in case of an error, after clearing the doorbell,
2926 * we also need to clear the outstanding_request
2929 ufshcd_outstanding_req_clear(hba, lrbp->task_tag);
2936 * ufshcd_exec_dev_cmd - API for sending device management requests
2938 * @cmd_type: specifies the type (NOP, Query...)
2939 * @timeout: timeout in milliseconds
2941 * NOTE: Since there is only one available tag for device management commands,
2942 * it is expected you hold the hba->dev_cmd.lock mutex.
2944 static int ufshcd_exec_dev_cmd(struct ufs_hba *hba,
2945 enum dev_cmd_type cmd_type, int timeout)
2947 struct request_queue *q = hba->cmd_queue;
2948 DECLARE_COMPLETION_ONSTACK(wait);
2949 struct request *req;
2950 struct ufshcd_lrb *lrbp;
2954 down_read(&hba->clk_scaling_lock);
2957 * Get free slot, sleep if slots are unavailable.
2958 * Even though we use wait_event() which sleeps indefinitely,
2959 * the maximum wait time is bounded by SCSI request timeout.
2961 req = blk_get_request(q, REQ_OP_DRV_OUT, 0);
2967 WARN_ONCE(tag < 0, "Invalid tag %d\n", tag);
2968 /* Set the timeout such that the SCSI error handler is not activated. */
2969 req->timeout = msecs_to_jiffies(2 * timeout);
2970 blk_mq_start_request(req);
2972 if (unlikely(test_bit(tag, &hba->outstanding_reqs))) {
2977 lrbp = &hba->lrb[tag];
2979 err = ufshcd_compose_dev_cmd(hba, lrbp, cmd_type, tag);
2983 hba->dev_cmd.complete = &wait;
2985 ufshcd_add_query_upiu_trace(hba, UFS_QUERY_SEND, lrbp->ucd_req_ptr);
2986 /* Make sure descriptors are ready before ringing the doorbell */
2989 ufshcd_send_command(hba, tag);
2990 err = ufshcd_wait_for_dev_cmd(hba, lrbp, timeout);
2991 ufshcd_add_query_upiu_trace(hba, err ? UFS_QUERY_ERR : UFS_QUERY_COMP,
2992 (struct utp_upiu_req *)lrbp->ucd_rsp_ptr);
2995 blk_put_request(req);
2997 up_read(&hba->clk_scaling_lock);
3002 * ufshcd_init_query() - init the query response and request parameters
3003 * @hba: per-adapter instance
3004 * @request: address of the request pointer to be initialized
3005 * @response: address of the response pointer to be initialized
3006 * @opcode: operation to perform
3007 * @idn: flag idn to access
3008 * @index: LU number to access
3009 * @selector: query/flag/descriptor further identification
3011 static inline void ufshcd_init_query(struct ufs_hba *hba,
3012 struct ufs_query_req **request, struct ufs_query_res **response,
3013 enum query_opcode opcode, u8 idn, u8 index, u8 selector)
3015 *request = &hba->dev_cmd.query.request;
3016 *response = &hba->dev_cmd.query.response;
3017 memset(*request, 0, sizeof(struct ufs_query_req));
3018 memset(*response, 0, sizeof(struct ufs_query_res));
3019 (*request)->upiu_req.opcode = opcode;
3020 (*request)->upiu_req.idn = idn;
3021 (*request)->upiu_req.index = index;
3022 (*request)->upiu_req.selector = selector;
3025 static int ufshcd_query_flag_retry(struct ufs_hba *hba,
3026 enum query_opcode opcode, enum flag_idn idn, u8 index, bool *flag_res)
3031 for (retries = 0; retries < QUERY_REQ_RETRIES; retries++) {
3032 ret = ufshcd_query_flag(hba, opcode, idn, index, flag_res);
3035 "%s: failed with error %d, retries %d\n",
3036 __func__, ret, retries);
3043 "%s: query attribute, opcode %d, idn %d, failed with error %d after %d retires\n",
3044 __func__, opcode, idn, ret, retries);
3049 * ufshcd_query_flag() - API function for sending flag query requests
3050 * @hba: per-adapter instance
3051 * @opcode: flag query to perform
3052 * @idn: flag idn to access
3053 * @index: flag index to access
3054 * @flag_res: the flag value after the query request completes
3056 * Returns 0 for success, non-zero in case of failure
3058 int ufshcd_query_flag(struct ufs_hba *hba, enum query_opcode opcode,
3059 enum flag_idn idn, u8 index, bool *flag_res)
3061 struct ufs_query_req *request = NULL;
3062 struct ufs_query_res *response = NULL;
3063 int err, selector = 0;
3064 int timeout = QUERY_REQ_TIMEOUT;
3068 ufshcd_hold(hba, false);
3069 mutex_lock(&hba->dev_cmd.lock);
3070 ufshcd_init_query(hba, &request, &response, opcode, idn, index,
3074 case UPIU_QUERY_OPCODE_SET_FLAG:
3075 case UPIU_QUERY_OPCODE_CLEAR_FLAG:
3076 case UPIU_QUERY_OPCODE_TOGGLE_FLAG:
3077 request->query_func = UPIU_QUERY_FUNC_STANDARD_WRITE_REQUEST;
3079 case UPIU_QUERY_OPCODE_READ_FLAG:
3080 request->query_func = UPIU_QUERY_FUNC_STANDARD_READ_REQUEST;
3082 /* No dummy reads */
3083 dev_err(hba->dev, "%s: Invalid argument for read request\n",
3091 "%s: Expected query flag opcode but got = %d\n",
3097 err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_QUERY, timeout);
3101 "%s: Sending flag query for idn %d failed, err = %d\n",
3102 __func__, idn, err);
3107 *flag_res = (be32_to_cpu(response->upiu_res.value) &
3108 MASK_QUERY_UPIU_FLAG_LOC) & 0x1;
3111 mutex_unlock(&hba->dev_cmd.lock);
3112 ufshcd_release(hba);
3117 * ufshcd_query_attr - API function for sending attribute requests
3118 * @hba: per-adapter instance
3119 * @opcode: attribute opcode
3120 * @idn: attribute idn to access
3121 * @index: index field
3122 * @selector: selector field
3123 * @attr_val: the attribute value after the query request completes
3125 * Returns 0 for success, non-zero in case of failure
3127 int ufshcd_query_attr(struct ufs_hba *hba, enum query_opcode opcode,
3128 enum attr_idn idn, u8 index, u8 selector, u32 *attr_val)
3130 struct ufs_query_req *request = NULL;
3131 struct ufs_query_res *response = NULL;
3137 dev_err(hba->dev, "%s: attribute value required for opcode 0x%x\n",
3142 ufshcd_hold(hba, false);
3144 mutex_lock(&hba->dev_cmd.lock);
3145 ufshcd_init_query(hba, &request, &response, opcode, idn, index,
3149 case UPIU_QUERY_OPCODE_WRITE_ATTR:
3150 request->query_func = UPIU_QUERY_FUNC_STANDARD_WRITE_REQUEST;
3151 request->upiu_req.value = cpu_to_be32(*attr_val);
3153 case UPIU_QUERY_OPCODE_READ_ATTR:
3154 request->query_func = UPIU_QUERY_FUNC_STANDARD_READ_REQUEST;
3157 dev_err(hba->dev, "%s: Expected query attr opcode but got = 0x%.2x\n",
3163 err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_QUERY, QUERY_REQ_TIMEOUT);
3166 dev_err(hba->dev, "%s: opcode 0x%.2x for idn %d failed, index %d, err = %d\n",
3167 __func__, opcode, idn, index, err);
3171 *attr_val = be32_to_cpu(response->upiu_res.value);
3174 mutex_unlock(&hba->dev_cmd.lock);
3175 ufshcd_release(hba);
3180 * ufshcd_query_attr_retry() - API function for sending query
3181 * attribute with retries
3182 * @hba: per-adapter instance
3183 * @opcode: attribute opcode
3184 * @idn: attribute idn to access
3185 * @index: index field
3186 * @selector: selector field
3187 * @attr_val: the attribute value after the query request
3190 * Returns 0 for success, non-zero in case of failure
3192 int ufshcd_query_attr_retry(struct ufs_hba *hba,
3193 enum query_opcode opcode, enum attr_idn idn, u8 index, u8 selector,
3199 for (retries = QUERY_REQ_RETRIES; retries > 0; retries--) {
3200 ret = ufshcd_query_attr(hba, opcode, idn, index,
3201 selector, attr_val);
3203 dev_dbg(hba->dev, "%s: failed with error %d, retries %d\n",
3204 __func__, ret, retries);
3211 "%s: query attribute, idn %d, failed with error %d after %d retires\n",
3212 __func__, idn, ret, QUERY_REQ_RETRIES);
3216 static int __ufshcd_query_descriptor(struct ufs_hba *hba,
3217 enum query_opcode opcode, enum desc_idn idn, u8 index,
3218 u8 selector, u8 *desc_buf, int *buf_len)
3220 struct ufs_query_req *request = NULL;
3221 struct ufs_query_res *response = NULL;
3227 dev_err(hba->dev, "%s: descriptor buffer required for opcode 0x%x\n",
3232 if (*buf_len < QUERY_DESC_MIN_SIZE || *buf_len > QUERY_DESC_MAX_SIZE) {
3233 dev_err(hba->dev, "%s: descriptor buffer size (%d) is out of range\n",
3234 __func__, *buf_len);
3238 ufshcd_hold(hba, false);
3240 mutex_lock(&hba->dev_cmd.lock);
3241 ufshcd_init_query(hba, &request, &response, opcode, idn, index,
3243 hba->dev_cmd.query.descriptor = desc_buf;
3244 request->upiu_req.length = cpu_to_be16(*buf_len);
3247 case UPIU_QUERY_OPCODE_WRITE_DESC:
3248 request->query_func = UPIU_QUERY_FUNC_STANDARD_WRITE_REQUEST;
3250 case UPIU_QUERY_OPCODE_READ_DESC:
3251 request->query_func = UPIU_QUERY_FUNC_STANDARD_READ_REQUEST;
3255 "%s: Expected query descriptor opcode but got = 0x%.2x\n",
3261 err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_QUERY, QUERY_REQ_TIMEOUT);
3264 dev_err(hba->dev, "%s: opcode 0x%.2x for idn %d failed, index %d, err = %d\n",
3265 __func__, opcode, idn, index, err);
3269 *buf_len = be16_to_cpu(response->upiu_res.length);
3272 hba->dev_cmd.query.descriptor = NULL;
3273 mutex_unlock(&hba->dev_cmd.lock);
3274 ufshcd_release(hba);
3279 * ufshcd_query_descriptor_retry - API function for sending descriptor requests
3280 * @hba: per-adapter instance
3281 * @opcode: attribute opcode
3282 * @idn: attribute idn to access
3283 * @index: index field
3284 * @selector: selector field
3285 * @desc_buf: the buffer that contains the descriptor
3286 * @buf_len: length parameter passed to the device
3288 * Returns 0 for success, non-zero in case of failure.
3289 * The buf_len parameter will contain, on return, the length parameter
3290 * received on the response.
3292 int ufshcd_query_descriptor_retry(struct ufs_hba *hba,
3293 enum query_opcode opcode,
3294 enum desc_idn idn, u8 index,
3296 u8 *desc_buf, int *buf_len)
3301 for (retries = QUERY_REQ_RETRIES; retries > 0; retries--) {
3302 err = __ufshcd_query_descriptor(hba, opcode, idn, index,
3303 selector, desc_buf, buf_len);
3304 if (!err || err == -EINVAL)
3312 * ufshcd_map_desc_id_to_length - map descriptor IDN to its length
3313 * @hba: Pointer to adapter instance
3314 * @desc_id: descriptor idn value
3315 * @desc_len: mapped desc length (out)
3317 void ufshcd_map_desc_id_to_length(struct ufs_hba *hba, enum desc_idn desc_id,
3320 if (desc_id >= QUERY_DESC_IDN_MAX || desc_id == QUERY_DESC_IDN_RFU_0 ||
3321 desc_id == QUERY_DESC_IDN_RFU_1)
3324 *desc_len = hba->desc_size[desc_id];
3326 EXPORT_SYMBOL(ufshcd_map_desc_id_to_length);
3328 static void ufshcd_update_desc_length(struct ufs_hba *hba,
3329 enum desc_idn desc_id, int desc_index,
3330 unsigned char desc_len)
3332 if (hba->desc_size[desc_id] == QUERY_DESC_MAX_SIZE &&
3333 desc_id != QUERY_DESC_IDN_STRING && desc_index != UFS_RPMB_UNIT)
3334 /* For UFS 3.1, the normal unit descriptor is 10 bytes larger
3335 * than the RPMB unit, however, both descriptors share the same
3336 * desc_idn, to cover both unit descriptors with one length, we
3337 * choose the normal unit descriptor length by desc_index.
3339 hba->desc_size[desc_id] = desc_len;
3343 * ufshcd_read_desc_param - read the specified descriptor parameter
3344 * @hba: Pointer to adapter instance
3345 * @desc_id: descriptor idn value
3346 * @desc_index: descriptor index
3347 * @param_offset: offset of the parameter to read
3348 * @param_read_buf: pointer to buffer where parameter would be read
3349 * @param_size: sizeof(param_read_buf)
3351 * Return 0 in case of success, non-zero otherwise
3353 int ufshcd_read_desc_param(struct ufs_hba *hba,
3354 enum desc_idn desc_id,
3363 bool is_kmalloc = true;
3366 if (desc_id >= QUERY_DESC_IDN_MAX || !param_size)
3369 /* Get the length of descriptor */
3370 ufshcd_map_desc_id_to_length(hba, desc_id, &buff_len);
3372 dev_err(hba->dev, "%s: Failed to get desc length\n", __func__);
3376 if (param_offset >= buff_len) {
3377 dev_err(hba->dev, "%s: Invalid offset 0x%x in descriptor IDN 0x%x, length 0x%x\n",
3378 __func__, param_offset, desc_id, buff_len);
3382 /* Check whether we need temp memory */
3383 if (param_offset != 0 || param_size < buff_len) {
3384 desc_buf = kzalloc(buff_len, GFP_KERNEL);
3388 desc_buf = param_read_buf;
3392 /* Request for full descriptor */
3393 ret = ufshcd_query_descriptor_retry(hba, UPIU_QUERY_OPCODE_READ_DESC,
3394 desc_id, desc_index, 0,
3395 desc_buf, &buff_len);
3398 dev_err(hba->dev, "%s: Failed reading descriptor. desc_id %d, desc_index %d, param_offset %d, ret %d\n",
3399 __func__, desc_id, desc_index, param_offset, ret);
3404 if (desc_buf[QUERY_DESC_DESC_TYPE_OFFSET] != desc_id) {
3405 dev_err(hba->dev, "%s: invalid desc_id %d in descriptor header\n",
3406 __func__, desc_buf[QUERY_DESC_DESC_TYPE_OFFSET]);
3411 /* Update descriptor length */
3412 buff_len = desc_buf[QUERY_DESC_LENGTH_OFFSET];
3413 ufshcd_update_desc_length(hba, desc_id, desc_index, buff_len);
3416 /* Make sure we don't copy more data than available */
3417 if (param_offset >= buff_len)
3420 memcpy(param_read_buf, &desc_buf[param_offset],
3421 min_t(u32, param_size, buff_len - param_offset));
3430 * struct uc_string_id - unicode string
3432 * @len: size of this descriptor inclusive
3433 * @type: descriptor type
3434 * @uc: unicode string character
3436 struct uc_string_id {
3442 /* replace non-printable or non-ASCII characters with spaces */
3443 static inline char ufshcd_remove_non_printable(u8 ch)
3445 return (ch >= 0x20 && ch <= 0x7e) ? ch : ' ';
3449 * ufshcd_read_string_desc - read string descriptor
3450 * @hba: pointer to adapter instance
3451 * @desc_index: descriptor index
3452 * @buf: pointer to buffer where descriptor would be read,
3453 * the caller should free the memory.
3454 * @ascii: if true convert from unicode to ascii characters
3455 * null terminated string.
3458 * * string size on success.
3459 * * -ENOMEM: on allocation failure
3460 * * -EINVAL: on a wrong parameter
3462 int ufshcd_read_string_desc(struct ufs_hba *hba, u8 desc_index,
3463 u8 **buf, bool ascii)
3465 struct uc_string_id *uc_str;
3472 uc_str = kzalloc(QUERY_DESC_MAX_SIZE, GFP_KERNEL);
3476 ret = ufshcd_read_desc_param(hba, QUERY_DESC_IDN_STRING, desc_index, 0,
3477 (u8 *)uc_str, QUERY_DESC_MAX_SIZE);
3479 dev_err(hba->dev, "Reading String Desc failed after %d retries. err = %d\n",
3480 QUERY_REQ_RETRIES, ret);
3485 if (uc_str->len <= QUERY_DESC_HDR_SIZE) {
3486 dev_dbg(hba->dev, "String Desc is of zero length\n");
3495 /* remove header and divide by 2 to move from UTF16 to UTF8 */
3496 ascii_len = (uc_str->len - QUERY_DESC_HDR_SIZE) / 2 + 1;
3497 str = kzalloc(ascii_len, GFP_KERNEL);
3504 * the descriptor contains string in UTF16 format
3505 * we need to convert to utf-8 so it can be displayed
3507 ret = utf16s_to_utf8s(uc_str->uc,
3508 uc_str->len - QUERY_DESC_HDR_SIZE,
3509 UTF16_BIG_ENDIAN, str, ascii_len);
3511 /* replace non-printable or non-ASCII characters with spaces */
3512 for (i = 0; i < ret; i++)
3513 str[i] = ufshcd_remove_non_printable(str[i]);
3518 str = kmemdup(uc_str, uc_str->len, GFP_KERNEL);
3532 * ufshcd_read_unit_desc_param - read the specified unit descriptor parameter
3533 * @hba: Pointer to adapter instance
3535 * @param_offset: offset of the parameter to read
3536 * @param_read_buf: pointer to buffer where parameter would be read
3537 * @param_size: sizeof(param_read_buf)
3539 * Return 0 in case of success, non-zero otherwise
3541 static inline int ufshcd_read_unit_desc_param(struct ufs_hba *hba,
3543 enum unit_desc_param param_offset,
3548 * Unit descriptors are only available for general purpose LUs (LUN id
3549 * from 0 to 7) and RPMB Well known LU.
3551 if (!ufs_is_valid_unit_desc_lun(&hba->dev_info, lun, param_offset))
3554 return ufshcd_read_desc_param(hba, QUERY_DESC_IDN_UNIT, lun,
3555 param_offset, param_read_buf, param_size);
3558 static int ufshcd_get_ref_clk_gating_wait(struct ufs_hba *hba)
3561 u32 gating_wait = UFSHCD_REF_CLK_GATING_WAIT_US;
3563 if (hba->dev_info.wspecversion >= 0x300) {
3564 err = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
3565 QUERY_ATTR_IDN_REF_CLK_GATING_WAIT_TIME, 0, 0,
3568 dev_err(hba->dev, "Failed reading bRefClkGatingWait. err = %d, use default %uus\n",
3571 if (gating_wait == 0) {
3572 gating_wait = UFSHCD_REF_CLK_GATING_WAIT_US;
3573 dev_err(hba->dev, "Undefined ref clk gating wait time, use default %uus\n",
3577 hba->dev_info.clk_gating_wait_us = gating_wait;
3584 * ufshcd_memory_alloc - allocate memory for host memory space data structures
3585 * @hba: per adapter instance
3587 * 1. Allocate DMA memory for Command Descriptor array
3588 * Each command descriptor consist of Command UPIU, Response UPIU and PRDT
3589 * 2. Allocate DMA memory for UTP Transfer Request Descriptor List (UTRDL).
3590 * 3. Allocate DMA memory for UTP Task Management Request Descriptor List
3592 * 4. Allocate memory for local reference block(lrb).
3594 * Returns 0 for success, non-zero in case of failure
3596 static int ufshcd_memory_alloc(struct ufs_hba *hba)
3598 size_t utmrdl_size, utrdl_size, ucdl_size;
3600 /* Allocate memory for UTP command descriptors */
3601 ucdl_size = (sizeof(struct utp_transfer_cmd_desc) * hba->nutrs);
3602 hba->ucdl_base_addr = dmam_alloc_coherent(hba->dev,
3604 &hba->ucdl_dma_addr,
3608 * UFSHCI requires UTP command descriptor to be 128 byte aligned.
3609 * make sure hba->ucdl_dma_addr is aligned to PAGE_SIZE
3610 * if hba->ucdl_dma_addr is aligned to PAGE_SIZE, then it will
3611 * be aligned to 128 bytes as well
3613 if (!hba->ucdl_base_addr ||
3614 WARN_ON(hba->ucdl_dma_addr & (PAGE_SIZE - 1))) {
3616 "Command Descriptor Memory allocation failed\n");
3621 * Allocate memory for UTP Transfer descriptors
3622 * UFSHCI requires 1024 byte alignment of UTRD
3624 utrdl_size = (sizeof(struct utp_transfer_req_desc) * hba->nutrs);
3625 hba->utrdl_base_addr = dmam_alloc_coherent(hba->dev,
3627 &hba->utrdl_dma_addr,
3629 if (!hba->utrdl_base_addr ||
3630 WARN_ON(hba->utrdl_dma_addr & (PAGE_SIZE - 1))) {
3632 "Transfer Descriptor Memory allocation failed\n");
3637 * Allocate memory for UTP Task Management descriptors
3638 * UFSHCI requires 1024 byte alignment of UTMRD
3640 utmrdl_size = sizeof(struct utp_task_req_desc) * hba->nutmrs;
3641 hba->utmrdl_base_addr = dmam_alloc_coherent(hba->dev,
3643 &hba->utmrdl_dma_addr,
3645 if (!hba->utmrdl_base_addr ||
3646 WARN_ON(hba->utmrdl_dma_addr & (PAGE_SIZE - 1))) {
3648 "Task Management Descriptor Memory allocation failed\n");
3652 /* Allocate memory for local reference block */
3653 hba->lrb = devm_kcalloc(hba->dev,
3654 hba->nutrs, sizeof(struct ufshcd_lrb),
3657 dev_err(hba->dev, "LRB Memory allocation failed\n");
3666 * ufshcd_host_memory_configure - configure local reference block with
3668 * @hba: per adapter instance
3670 * Configure Host memory space
3671 * 1. Update Corresponding UTRD.UCDBA and UTRD.UCDBAU with UCD DMA
3673 * 2. Update each UTRD with Response UPIU offset, Response UPIU length
3675 * 3. Save the corresponding addresses of UTRD, UCD.CMD, UCD.RSP and UCD.PRDT
3676 * into local reference block.
3678 static void ufshcd_host_memory_configure(struct ufs_hba *hba)
3680 struct utp_transfer_req_desc *utrdlp;
3681 dma_addr_t cmd_desc_dma_addr;
3682 dma_addr_t cmd_desc_element_addr;
3683 u16 response_offset;
3688 utrdlp = hba->utrdl_base_addr;
3691 offsetof(struct utp_transfer_cmd_desc, response_upiu);
3693 offsetof(struct utp_transfer_cmd_desc, prd_table);
3695 cmd_desc_size = sizeof(struct utp_transfer_cmd_desc);
3696 cmd_desc_dma_addr = hba->ucdl_dma_addr;
3698 for (i = 0; i < hba->nutrs; i++) {
3699 /* Configure UTRD with command descriptor base address */
3700 cmd_desc_element_addr =
3701 (cmd_desc_dma_addr + (cmd_desc_size * i));
3702 utrdlp[i].command_desc_base_addr_lo =
3703 cpu_to_le32(lower_32_bits(cmd_desc_element_addr));
3704 utrdlp[i].command_desc_base_addr_hi =
3705 cpu_to_le32(upper_32_bits(cmd_desc_element_addr));
3707 /* Response upiu and prdt offset should be in double words */
3708 if (hba->quirks & UFSHCD_QUIRK_PRDT_BYTE_GRAN) {
3709 utrdlp[i].response_upiu_offset =
3710 cpu_to_le16(response_offset);
3711 utrdlp[i].prd_table_offset =
3712 cpu_to_le16(prdt_offset);
3713 utrdlp[i].response_upiu_length =
3714 cpu_to_le16(ALIGNED_UPIU_SIZE);
3716 utrdlp[i].response_upiu_offset =
3717 cpu_to_le16(response_offset >> 2);
3718 utrdlp[i].prd_table_offset =
3719 cpu_to_le16(prdt_offset >> 2);
3720 utrdlp[i].response_upiu_length =
3721 cpu_to_le16(ALIGNED_UPIU_SIZE >> 2);
3724 ufshcd_init_lrb(hba, &hba->lrb[i], i);
3729 * ufshcd_dme_link_startup - Notify Unipro to perform link startup
3730 * @hba: per adapter instance
3732 * UIC_CMD_DME_LINK_STARTUP command must be issued to Unipro layer,
3733 * in order to initialize the Unipro link startup procedure.
3734 * Once the Unipro links are up, the device connected to the controller
3737 * Returns 0 on success, non-zero value on failure
3739 static int ufshcd_dme_link_startup(struct ufs_hba *hba)
3741 struct uic_command uic_cmd = {0};
3744 uic_cmd.command = UIC_CMD_DME_LINK_STARTUP;
3746 ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
3749 "dme-link-startup: error code %d\n", ret);
3753 * ufshcd_dme_reset - UIC command for DME_RESET
3754 * @hba: per adapter instance
3756 * DME_RESET command is issued in order to reset UniPro stack.
3757 * This function now deals with cold reset.
3759 * Returns 0 on success, non-zero value on failure
3761 static int ufshcd_dme_reset(struct ufs_hba *hba)
3763 struct uic_command uic_cmd = {0};
3766 uic_cmd.command = UIC_CMD_DME_RESET;
3768 ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
3771 "dme-reset: error code %d\n", ret);
3776 int ufshcd_dme_configure_adapt(struct ufs_hba *hba,
3782 if (agreed_gear != UFS_HS_G4)
3783 adapt_val = PA_NO_ADAPT;
3785 ret = ufshcd_dme_set(hba,
3786 UIC_ARG_MIB(PA_TXHSADAPTTYPE),
3790 EXPORT_SYMBOL_GPL(ufshcd_dme_configure_adapt);
3793 * ufshcd_dme_enable - UIC command for DME_ENABLE
3794 * @hba: per adapter instance
3796 * DME_ENABLE command is issued in order to enable UniPro stack.
3798 * Returns 0 on success, non-zero value on failure
3800 static int ufshcd_dme_enable(struct ufs_hba *hba)
3802 struct uic_command uic_cmd = {0};
3805 uic_cmd.command = UIC_CMD_DME_ENABLE;
3807 ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
3810 "dme-enable: error code %d\n", ret);
3815 static inline void ufshcd_add_delay_before_dme_cmd(struct ufs_hba *hba)
3817 #define MIN_DELAY_BEFORE_DME_CMDS_US 1000
3818 unsigned long min_sleep_time_us;
3820 if (!(hba->quirks & UFSHCD_QUIRK_DELAY_BEFORE_DME_CMDS))
3824 * last_dme_cmd_tstamp will be 0 only for 1st call to
3827 if (unlikely(!ktime_to_us(hba->last_dme_cmd_tstamp))) {
3828 min_sleep_time_us = MIN_DELAY_BEFORE_DME_CMDS_US;
3830 unsigned long delta =
3831 (unsigned long) ktime_to_us(
3832 ktime_sub(ktime_get(),
3833 hba->last_dme_cmd_tstamp));
3835 if (delta < MIN_DELAY_BEFORE_DME_CMDS_US)
3837 MIN_DELAY_BEFORE_DME_CMDS_US - delta;
3839 return; /* no more delay required */
3842 /* allow sleep for extra 50us if needed */
3843 usleep_range(min_sleep_time_us, min_sleep_time_us + 50);
3847 * ufshcd_dme_set_attr - UIC command for DME_SET, DME_PEER_SET
3848 * @hba: per adapter instance
3849 * @attr_sel: uic command argument1
3850 * @attr_set: attribute set type as uic command argument2
3851 * @mib_val: setting value as uic command argument3
3852 * @peer: indicate whether peer or local
3854 * Returns 0 on success, non-zero value on failure
3856 int ufshcd_dme_set_attr(struct ufs_hba *hba, u32 attr_sel,
3857 u8 attr_set, u32 mib_val, u8 peer)
3859 struct uic_command uic_cmd = {0};
3860 static const char *const action[] = {
3864 const char *set = action[!!peer];
3866 int retries = UFS_UIC_COMMAND_RETRIES;
3868 uic_cmd.command = peer ?
3869 UIC_CMD_DME_PEER_SET : UIC_CMD_DME_SET;
3870 uic_cmd.argument1 = attr_sel;
3871 uic_cmd.argument2 = UIC_ARG_ATTR_TYPE(attr_set);
3872 uic_cmd.argument3 = mib_val;
3875 /* for peer attributes we retry upon failure */
3876 ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
3878 dev_dbg(hba->dev, "%s: attr-id 0x%x val 0x%x error code %d\n",
3879 set, UIC_GET_ATTR_ID(attr_sel), mib_val, ret);
3880 } while (ret && peer && --retries);
3883 dev_err(hba->dev, "%s: attr-id 0x%x val 0x%x failed %d retries\n",
3884 set, UIC_GET_ATTR_ID(attr_sel), mib_val,
3885 UFS_UIC_COMMAND_RETRIES - retries);
3889 EXPORT_SYMBOL_GPL(ufshcd_dme_set_attr);
3892 * ufshcd_dme_get_attr - UIC command for DME_GET, DME_PEER_GET
3893 * @hba: per adapter instance
3894 * @attr_sel: uic command argument1
3895 * @mib_val: the value of the attribute as returned by the UIC command
3896 * @peer: indicate whether peer or local
3898 * Returns 0 on success, non-zero value on failure
3900 int ufshcd_dme_get_attr(struct ufs_hba *hba, u32 attr_sel,
3901 u32 *mib_val, u8 peer)
3903 struct uic_command uic_cmd = {0};
3904 static const char *const action[] = {
3908 const char *get = action[!!peer];
3910 int retries = UFS_UIC_COMMAND_RETRIES;
3911 struct ufs_pa_layer_attr orig_pwr_info;
3912 struct ufs_pa_layer_attr temp_pwr_info;
3913 bool pwr_mode_change = false;
3915 if (peer && (hba->quirks & UFSHCD_QUIRK_DME_PEER_ACCESS_AUTO_MODE)) {
3916 orig_pwr_info = hba->pwr_info;
3917 temp_pwr_info = orig_pwr_info;
3919 if (orig_pwr_info.pwr_tx == FAST_MODE ||
3920 orig_pwr_info.pwr_rx == FAST_MODE) {
3921 temp_pwr_info.pwr_tx = FASTAUTO_MODE;
3922 temp_pwr_info.pwr_rx = FASTAUTO_MODE;
3923 pwr_mode_change = true;
3924 } else if (orig_pwr_info.pwr_tx == SLOW_MODE ||
3925 orig_pwr_info.pwr_rx == SLOW_MODE) {
3926 temp_pwr_info.pwr_tx = SLOWAUTO_MODE;
3927 temp_pwr_info.pwr_rx = SLOWAUTO_MODE;
3928 pwr_mode_change = true;
3930 if (pwr_mode_change) {
3931 ret = ufshcd_change_power_mode(hba, &temp_pwr_info);
3937 uic_cmd.command = peer ?
3938 UIC_CMD_DME_PEER_GET : UIC_CMD_DME_GET;
3939 uic_cmd.argument1 = attr_sel;
3942 /* for peer attributes we retry upon failure */
3943 ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
3945 dev_dbg(hba->dev, "%s: attr-id 0x%x error code %d\n",
3946 get, UIC_GET_ATTR_ID(attr_sel), ret);
3947 } while (ret && peer && --retries);
3950 dev_err(hba->dev, "%s: attr-id 0x%x failed %d retries\n",
3951 get, UIC_GET_ATTR_ID(attr_sel),
3952 UFS_UIC_COMMAND_RETRIES - retries);
3954 if (mib_val && !ret)
3955 *mib_val = uic_cmd.argument3;
3957 if (peer && (hba->quirks & UFSHCD_QUIRK_DME_PEER_ACCESS_AUTO_MODE)
3959 ufshcd_change_power_mode(hba, &orig_pwr_info);
3963 EXPORT_SYMBOL_GPL(ufshcd_dme_get_attr);
3966 * ufshcd_uic_pwr_ctrl - executes UIC commands (which affects the link power
3967 * state) and waits for it to take effect.
3969 * @hba: per adapter instance
3970 * @cmd: UIC command to execute
3972 * DME operations like DME_SET(PA_PWRMODE), DME_HIBERNATE_ENTER &
3973 * DME_HIBERNATE_EXIT commands take some time to take its effect on both host
3974 * and device UniPro link and hence it's final completion would be indicated by
3975 * dedicated status bits in Interrupt Status register (UPMS, UHES, UHXS) in
3976 * addition to normal UIC command completion Status (UCCS). This function only
3977 * returns after the relevant status bits indicate the completion.
3979 * Returns 0 on success, non-zero value on failure
3981 static int ufshcd_uic_pwr_ctrl(struct ufs_hba *hba, struct uic_command *cmd)
3983 DECLARE_COMPLETION_ONSTACK(uic_async_done);
3984 unsigned long flags;
3987 bool reenable_intr = false;
3989 mutex_lock(&hba->uic_cmd_mutex);
3990 ufshcd_add_delay_before_dme_cmd(hba);
3992 spin_lock_irqsave(hba->host->host_lock, flags);
3993 if (ufshcd_is_link_broken(hba)) {
3997 hba->uic_async_done = &uic_async_done;
3998 if (ufshcd_readl(hba, REG_INTERRUPT_ENABLE) & UIC_COMMAND_COMPL) {
3999 ufshcd_disable_intr(hba, UIC_COMMAND_COMPL);
4001 * Make sure UIC command completion interrupt is disabled before
4002 * issuing UIC command.
4005 reenable_intr = true;
4007 ret = __ufshcd_send_uic_cmd(hba, cmd, false);
4008 spin_unlock_irqrestore(hba->host->host_lock, flags);
4011 "pwr ctrl cmd 0x%x with mode 0x%x uic error %d\n",
4012 cmd->command, cmd->argument3, ret);
4016 if (!wait_for_completion_timeout(hba->uic_async_done,
4017 msecs_to_jiffies(UIC_CMD_TIMEOUT))) {
4019 "pwr ctrl cmd 0x%x with mode 0x%x completion timeout\n",
4020 cmd->command, cmd->argument3);
4022 if (!cmd->cmd_active) {
4023 dev_err(hba->dev, "%s: Power Mode Change operation has been completed, go check UPMCRS\n",
4033 status = ufshcd_get_upmcrs(hba);
4034 if (status != PWR_LOCAL) {
4036 "pwr ctrl cmd 0x%x failed, host upmcrs:0x%x\n",
4037 cmd->command, status);
4038 ret = (status != PWR_OK) ? status : -1;
4042 ufshcd_print_host_state(hba);
4043 ufshcd_print_pwr_info(hba);
4044 ufshcd_print_evt_hist(hba);
4047 spin_lock_irqsave(hba->host->host_lock, flags);
4048 hba->active_uic_cmd = NULL;
4049 hba->uic_async_done = NULL;
4051 ufshcd_enable_intr(hba, UIC_COMMAND_COMPL);
4053 ufshcd_set_link_broken(hba);
4054 ufshcd_schedule_eh_work(hba);
4057 spin_unlock_irqrestore(hba->host->host_lock, flags);
4058 mutex_unlock(&hba->uic_cmd_mutex);
4064 * ufshcd_uic_change_pwr_mode - Perform the UIC power mode chage
4065 * using DME_SET primitives.
4066 * @hba: per adapter instance
4067 * @mode: powr mode value
4069 * Returns 0 on success, non-zero value on failure
4071 static int ufshcd_uic_change_pwr_mode(struct ufs_hba *hba, u8 mode)
4073 struct uic_command uic_cmd = {0};
4076 if (hba->quirks & UFSHCD_QUIRK_BROKEN_PA_RXHSUNTERMCAP) {
4077 ret = ufshcd_dme_set(hba,
4078 UIC_ARG_MIB_SEL(PA_RXHSUNTERMCAP, 0), 1);
4080 dev_err(hba->dev, "%s: failed to enable PA_RXHSUNTERMCAP ret %d\n",
4086 uic_cmd.command = UIC_CMD_DME_SET;
4087 uic_cmd.argument1 = UIC_ARG_MIB(PA_PWRMODE);
4088 uic_cmd.argument3 = mode;
4089 ufshcd_hold(hba, false);
4090 ret = ufshcd_uic_pwr_ctrl(hba, &uic_cmd);
4091 ufshcd_release(hba);
4097 int ufshcd_link_recovery(struct ufs_hba *hba)
4100 unsigned long flags;
4102 spin_lock_irqsave(hba->host->host_lock, flags);
4103 hba->ufshcd_state = UFSHCD_STATE_RESET;
4104 ufshcd_set_eh_in_progress(hba);
4105 spin_unlock_irqrestore(hba->host->host_lock, flags);
4107 /* Reset the attached device */
4108 ufshcd_device_reset(hba);
4110 ret = ufshcd_host_reset_and_restore(hba);
4112 spin_lock_irqsave(hba->host->host_lock, flags);
4114 hba->ufshcd_state = UFSHCD_STATE_ERROR;
4115 ufshcd_clear_eh_in_progress(hba);
4116 spin_unlock_irqrestore(hba->host->host_lock, flags);
4119 dev_err(hba->dev, "%s: link recovery failed, err %d",
4122 ufshcd_clear_ua_wluns(hba);
4126 EXPORT_SYMBOL_GPL(ufshcd_link_recovery);
4128 static int ufshcd_uic_hibern8_enter(struct ufs_hba *hba)
4131 struct uic_command uic_cmd = {0};
4132 ktime_t start = ktime_get();
4134 ufshcd_vops_hibern8_notify(hba, UIC_CMD_DME_HIBER_ENTER, PRE_CHANGE);
4136 uic_cmd.command = UIC_CMD_DME_HIBER_ENTER;
4137 ret = ufshcd_uic_pwr_ctrl(hba, &uic_cmd);
4138 trace_ufshcd_profile_hibern8(dev_name(hba->dev), "enter",
4139 ktime_to_us(ktime_sub(ktime_get(), start)), ret);
4142 dev_err(hba->dev, "%s: hibern8 enter failed. ret = %d\n",
4145 ufshcd_vops_hibern8_notify(hba, UIC_CMD_DME_HIBER_ENTER,
4151 int ufshcd_uic_hibern8_exit(struct ufs_hba *hba)
4153 struct uic_command uic_cmd = {0};
4155 ktime_t start = ktime_get();
4157 ufshcd_vops_hibern8_notify(hba, UIC_CMD_DME_HIBER_EXIT, PRE_CHANGE);
4159 uic_cmd.command = UIC_CMD_DME_HIBER_EXIT;
4160 ret = ufshcd_uic_pwr_ctrl(hba, &uic_cmd);
4161 trace_ufshcd_profile_hibern8(dev_name(hba->dev), "exit",
4162 ktime_to_us(ktime_sub(ktime_get(), start)), ret);
4165 dev_err(hba->dev, "%s: hibern8 exit failed. ret = %d\n",
4168 ufshcd_vops_hibern8_notify(hba, UIC_CMD_DME_HIBER_EXIT,
4170 hba->ufs_stats.last_hibern8_exit_tstamp = ktime_get();
4171 hba->ufs_stats.hibern8_exit_cnt++;
4176 EXPORT_SYMBOL_GPL(ufshcd_uic_hibern8_exit);
4178 void ufshcd_auto_hibern8_update(struct ufs_hba *hba, u32 ahit)
4180 unsigned long flags;
4181 bool update = false;
4183 if (!ufshcd_is_auto_hibern8_supported(hba))
4186 spin_lock_irqsave(hba->host->host_lock, flags);
4187 if (hba->ahit != ahit) {
4191 spin_unlock_irqrestore(hba->host->host_lock, flags);
4194 !pm_runtime_suspended(&hba->sdev_ufs_device->sdev_gendev)) {
4195 ufshcd_rpm_get_sync(hba);
4196 ufshcd_hold(hba, false);
4197 ufshcd_auto_hibern8_enable(hba);
4198 ufshcd_release(hba);
4199 ufshcd_rpm_put_sync(hba);
4202 EXPORT_SYMBOL_GPL(ufshcd_auto_hibern8_update);
4204 void ufshcd_auto_hibern8_enable(struct ufs_hba *hba)
4206 unsigned long flags;
4208 if (!ufshcd_is_auto_hibern8_supported(hba))
4211 spin_lock_irqsave(hba->host->host_lock, flags);
4212 ufshcd_writel(hba, hba->ahit, REG_AUTO_HIBERNATE_IDLE_TIMER);
4213 spin_unlock_irqrestore(hba->host->host_lock, flags);
4217 * ufshcd_init_pwr_info - setting the POR (power on reset)
4218 * values in hba power info
4219 * @hba: per-adapter instance
4221 static void ufshcd_init_pwr_info(struct ufs_hba *hba)
4223 hba->pwr_info.gear_rx = UFS_PWM_G1;
4224 hba->pwr_info.gear_tx = UFS_PWM_G1;
4225 hba->pwr_info.lane_rx = 1;
4226 hba->pwr_info.lane_tx = 1;
4227 hba->pwr_info.pwr_rx = SLOWAUTO_MODE;
4228 hba->pwr_info.pwr_tx = SLOWAUTO_MODE;
4229 hba->pwr_info.hs_rate = 0;
4233 * ufshcd_get_max_pwr_mode - reads the max power mode negotiated with device
4234 * @hba: per-adapter instance
4236 static int ufshcd_get_max_pwr_mode(struct ufs_hba *hba)
4238 struct ufs_pa_layer_attr *pwr_info = &hba->max_pwr_info.info;
4240 if (hba->max_pwr_info.is_valid)
4243 pwr_info->pwr_tx = FAST_MODE;
4244 pwr_info->pwr_rx = FAST_MODE;
4245 pwr_info->hs_rate = PA_HS_MODE_B;
4247 /* Get the connected lane count */
4248 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_CONNECTEDRXDATALANES),
4249 &pwr_info->lane_rx);
4250 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_CONNECTEDTXDATALANES),
4251 &pwr_info->lane_tx);
4253 if (!pwr_info->lane_rx || !pwr_info->lane_tx) {
4254 dev_err(hba->dev, "%s: invalid connected lanes value. rx=%d, tx=%d\n",
4262 * First, get the maximum gears of HS speed.
4263 * If a zero value, it means there is no HSGEAR capability.
4264 * Then, get the maximum gears of PWM speed.
4266 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_MAXRXHSGEAR), &pwr_info->gear_rx);
4267 if (!pwr_info->gear_rx) {
4268 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_MAXRXPWMGEAR),
4269 &pwr_info->gear_rx);
4270 if (!pwr_info->gear_rx) {
4271 dev_err(hba->dev, "%s: invalid max pwm rx gear read = %d\n",
4272 __func__, pwr_info->gear_rx);
4275 pwr_info->pwr_rx = SLOW_MODE;
4278 ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_MAXRXHSGEAR),
4279 &pwr_info->gear_tx);
4280 if (!pwr_info->gear_tx) {
4281 ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_MAXRXPWMGEAR),
4282 &pwr_info->gear_tx);
4283 if (!pwr_info->gear_tx) {
4284 dev_err(hba->dev, "%s: invalid max pwm tx gear read = %d\n",
4285 __func__, pwr_info->gear_tx);
4288 pwr_info->pwr_tx = SLOW_MODE;
4291 hba->max_pwr_info.is_valid = true;
4295 static int ufshcd_change_power_mode(struct ufs_hba *hba,
4296 struct ufs_pa_layer_attr *pwr_mode)
4300 /* if already configured to the requested pwr_mode */
4301 if (!hba->force_pmc &&
4302 pwr_mode->gear_rx == hba->pwr_info.gear_rx &&
4303 pwr_mode->gear_tx == hba->pwr_info.gear_tx &&
4304 pwr_mode->lane_rx == hba->pwr_info.lane_rx &&
4305 pwr_mode->lane_tx == hba->pwr_info.lane_tx &&
4306 pwr_mode->pwr_rx == hba->pwr_info.pwr_rx &&
4307 pwr_mode->pwr_tx == hba->pwr_info.pwr_tx &&
4308 pwr_mode->hs_rate == hba->pwr_info.hs_rate) {
4309 dev_dbg(hba->dev, "%s: power already configured\n", __func__);
4314 * Configure attributes for power mode change with below.
4315 * - PA_RXGEAR, PA_ACTIVERXDATALANES, PA_RXTERMINATION,
4316 * - PA_TXGEAR, PA_ACTIVETXDATALANES, PA_TXTERMINATION,
4319 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_RXGEAR), pwr_mode->gear_rx);
4320 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_ACTIVERXDATALANES),
4322 if (pwr_mode->pwr_rx == FASTAUTO_MODE ||
4323 pwr_mode->pwr_rx == FAST_MODE)
4324 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_RXTERMINATION), TRUE);
4326 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_RXTERMINATION), FALSE);
4328 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TXGEAR), pwr_mode->gear_tx);
4329 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_ACTIVETXDATALANES),
4331 if (pwr_mode->pwr_tx == FASTAUTO_MODE ||
4332 pwr_mode->pwr_tx == FAST_MODE)
4333 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TXTERMINATION), TRUE);
4335 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TXTERMINATION), FALSE);
4337 if (pwr_mode->pwr_rx == FASTAUTO_MODE ||
4338 pwr_mode->pwr_tx == FASTAUTO_MODE ||
4339 pwr_mode->pwr_rx == FAST_MODE ||
4340 pwr_mode->pwr_tx == FAST_MODE)
4341 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_HSSERIES),
4344 if (!(hba->quirks & UFSHCD_QUIRK_SKIP_DEF_UNIPRO_TIMEOUT_SETTING)) {
4345 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_PWRMODEUSERDATA0),
4346 DL_FC0ProtectionTimeOutVal_Default);
4347 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_PWRMODEUSERDATA1),
4348 DL_TC0ReplayTimeOutVal_Default);
4349 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_PWRMODEUSERDATA2),
4350 DL_AFC0ReqTimeOutVal_Default);
4351 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_PWRMODEUSERDATA3),
4352 DL_FC1ProtectionTimeOutVal_Default);
4353 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_PWRMODEUSERDATA4),
4354 DL_TC1ReplayTimeOutVal_Default);
4355 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_PWRMODEUSERDATA5),
4356 DL_AFC1ReqTimeOutVal_Default);
4358 ufshcd_dme_set(hba, UIC_ARG_MIB(DME_LocalFC0ProtectionTimeOutVal),
4359 DL_FC0ProtectionTimeOutVal_Default);
4360 ufshcd_dme_set(hba, UIC_ARG_MIB(DME_LocalTC0ReplayTimeOutVal),
4361 DL_TC0ReplayTimeOutVal_Default);
4362 ufshcd_dme_set(hba, UIC_ARG_MIB(DME_LocalAFC0ReqTimeOutVal),
4363 DL_AFC0ReqTimeOutVal_Default);
4366 ret = ufshcd_uic_change_pwr_mode(hba, pwr_mode->pwr_rx << 4
4367 | pwr_mode->pwr_tx);
4371 "%s: power mode change failed %d\n", __func__, ret);
4373 ufshcd_vops_pwr_change_notify(hba, POST_CHANGE, NULL,
4376 memcpy(&hba->pwr_info, pwr_mode,
4377 sizeof(struct ufs_pa_layer_attr));
4384 * ufshcd_config_pwr_mode - configure a new power mode
4385 * @hba: per-adapter instance
4386 * @desired_pwr_mode: desired power configuration
4388 int ufshcd_config_pwr_mode(struct ufs_hba *hba,
4389 struct ufs_pa_layer_attr *desired_pwr_mode)
4391 struct ufs_pa_layer_attr final_params = { 0 };
4394 ret = ufshcd_vops_pwr_change_notify(hba, PRE_CHANGE,
4395 desired_pwr_mode, &final_params);
4398 memcpy(&final_params, desired_pwr_mode, sizeof(final_params));
4400 ret = ufshcd_change_power_mode(hba, &final_params);
4404 EXPORT_SYMBOL_GPL(ufshcd_config_pwr_mode);
4407 * ufshcd_complete_dev_init() - checks device readiness
4408 * @hba: per-adapter instance
4410 * Set fDeviceInit flag and poll until device toggles it.
4412 static int ufshcd_complete_dev_init(struct ufs_hba *hba)
4415 bool flag_res = true;
4418 err = ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_SET_FLAG,
4419 QUERY_FLAG_IDN_FDEVICEINIT, 0, NULL);
4422 "%s setting fDeviceInit flag failed with error %d\n",
4427 /* Poll fDeviceInit flag to be cleared */
4428 timeout = ktime_add_ms(ktime_get(), FDEVICEINIT_COMPL_TIMEOUT);
4430 err = ufshcd_query_flag(hba, UPIU_QUERY_OPCODE_READ_FLAG,
4431 QUERY_FLAG_IDN_FDEVICEINIT, 0, &flag_res);
4434 usleep_range(5000, 10000);
4435 } while (ktime_before(ktime_get(), timeout));
4439 "%s reading fDeviceInit flag failed with error %d\n",
4441 } else if (flag_res) {
4443 "%s fDeviceInit was not cleared by the device\n",
4452 * ufshcd_make_hba_operational - Make UFS controller operational
4453 * @hba: per adapter instance
4455 * To bring UFS host controller to operational state,
4456 * 1. Enable required interrupts
4457 * 2. Configure interrupt aggregation
4458 * 3. Program UTRL and UTMRL base address
4459 * 4. Configure run-stop-registers
4461 * Returns 0 on success, non-zero value on failure
4463 int ufshcd_make_hba_operational(struct ufs_hba *hba)
4468 /* Enable required interrupts */
4469 ufshcd_enable_intr(hba, UFSHCD_ENABLE_INTRS);
4471 /* Configure interrupt aggregation */
4472 if (ufshcd_is_intr_aggr_allowed(hba))
4473 ufshcd_config_intr_aggr(hba, hba->nutrs - 1, INT_AGGR_DEF_TO);
4475 ufshcd_disable_intr_aggr(hba);
4477 /* Configure UTRL and UTMRL base address registers */
4478 ufshcd_writel(hba, lower_32_bits(hba->utrdl_dma_addr),
4479 REG_UTP_TRANSFER_REQ_LIST_BASE_L);
4480 ufshcd_writel(hba, upper_32_bits(hba->utrdl_dma_addr),
4481 REG_UTP_TRANSFER_REQ_LIST_BASE_H);
4482 ufshcd_writel(hba, lower_32_bits(hba->utmrdl_dma_addr),
4483 REG_UTP_TASK_REQ_LIST_BASE_L);
4484 ufshcd_writel(hba, upper_32_bits(hba->utmrdl_dma_addr),
4485 REG_UTP_TASK_REQ_LIST_BASE_H);
4488 * Make sure base address and interrupt setup are updated before
4489 * enabling the run/stop registers below.
4494 * UCRDY, UTMRLDY and UTRLRDY bits must be 1
4496 reg = ufshcd_readl(hba, REG_CONTROLLER_STATUS);
4497 if (!(ufshcd_get_lists_status(reg))) {
4498 ufshcd_enable_run_stop_reg(hba);
4501 "Host controller not ready to process requests");
4507 EXPORT_SYMBOL_GPL(ufshcd_make_hba_operational);
4510 * ufshcd_hba_stop - Send controller to reset state
4511 * @hba: per adapter instance
4513 void ufshcd_hba_stop(struct ufs_hba *hba)
4515 unsigned long flags;
4519 * Obtain the host lock to prevent that the controller is disabled
4520 * while the UFS interrupt handler is active on another CPU.
4522 spin_lock_irqsave(hba->host->host_lock, flags);
4523 ufshcd_writel(hba, CONTROLLER_DISABLE, REG_CONTROLLER_ENABLE);
4524 spin_unlock_irqrestore(hba->host->host_lock, flags);
4526 err = ufshcd_wait_for_register(hba, REG_CONTROLLER_ENABLE,
4527 CONTROLLER_ENABLE, CONTROLLER_DISABLE,
4530 dev_err(hba->dev, "%s: Controller disable failed\n", __func__);
4532 EXPORT_SYMBOL_GPL(ufshcd_hba_stop);
4535 * ufshcd_hba_execute_hce - initialize the controller
4536 * @hba: per adapter instance
4538 * The controller resets itself and controller firmware initialization
4539 * sequence kicks off. When controller is ready it will set
4540 * the Host Controller Enable bit to 1.
4542 * Returns 0 on success, non-zero value on failure
4544 static int ufshcd_hba_execute_hce(struct ufs_hba *hba)
4546 int retry_outer = 3;
4550 if (!ufshcd_is_hba_active(hba))
4551 /* change controller state to "reset state" */
4552 ufshcd_hba_stop(hba);
4554 /* UniPro link is disabled at this point */
4555 ufshcd_set_link_off(hba);
4557 ufshcd_vops_hce_enable_notify(hba, PRE_CHANGE);
4559 /* start controller initialization sequence */
4560 ufshcd_hba_start(hba);
4563 * To initialize a UFS host controller HCE bit must be set to 1.
4564 * During initialization the HCE bit value changes from 1->0->1.
4565 * When the host controller completes initialization sequence
4566 * it sets the value of HCE bit to 1. The same HCE bit is read back
4567 * to check if the controller has completed initialization sequence.
4568 * So without this delay the value HCE = 1, set in the previous
4569 * instruction might be read back.
4570 * This delay can be changed based on the controller.
4572 ufshcd_delay_us(hba->vps->hba_enable_delay_us, 100);
4574 /* wait for the host controller to complete initialization */
4576 while (ufshcd_is_hba_active(hba)) {
4581 "Controller enable failed\n");
4588 usleep_range(1000, 1100);
4591 /* enable UIC related interrupts */
4592 ufshcd_enable_intr(hba, UFSHCD_UIC_MASK);
4594 ufshcd_vops_hce_enable_notify(hba, POST_CHANGE);
4599 int ufshcd_hba_enable(struct ufs_hba *hba)
4603 if (hba->quirks & UFSHCI_QUIRK_BROKEN_HCE) {
4604 ufshcd_set_link_off(hba);
4605 ufshcd_vops_hce_enable_notify(hba, PRE_CHANGE);
4607 /* enable UIC related interrupts */
4608 ufshcd_enable_intr(hba, UFSHCD_UIC_MASK);
4609 ret = ufshcd_dme_reset(hba);
4611 ret = ufshcd_dme_enable(hba);
4613 ufshcd_vops_hce_enable_notify(hba, POST_CHANGE);
4616 "Host controller enable failed with non-hce\n");
4619 ret = ufshcd_hba_execute_hce(hba);
4624 EXPORT_SYMBOL_GPL(ufshcd_hba_enable);
4626 static int ufshcd_disable_tx_lcc(struct ufs_hba *hba, bool peer)
4628 int tx_lanes = 0, i, err = 0;
4631 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_CONNECTEDTXDATALANES),
4634 ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_CONNECTEDTXDATALANES),
4636 for (i = 0; i < tx_lanes; i++) {
4638 err = ufshcd_dme_set(hba,
4639 UIC_ARG_MIB_SEL(TX_LCC_ENABLE,
4640 UIC_ARG_MPHY_TX_GEN_SEL_INDEX(i)),
4643 err = ufshcd_dme_peer_set(hba,
4644 UIC_ARG_MIB_SEL(TX_LCC_ENABLE,
4645 UIC_ARG_MPHY_TX_GEN_SEL_INDEX(i)),
4648 dev_err(hba->dev, "%s: TX LCC Disable failed, peer = %d, lane = %d, err = %d",
4649 __func__, peer, i, err);
4657 static inline int ufshcd_disable_device_tx_lcc(struct ufs_hba *hba)
4659 return ufshcd_disable_tx_lcc(hba, true);
4662 void ufshcd_update_evt_hist(struct ufs_hba *hba, u32 id, u32 val)
4664 struct ufs_event_hist *e;
4666 if (id >= UFS_EVT_CNT)
4669 e = &hba->ufs_stats.event[id];
4670 e->val[e->pos] = val;
4671 e->tstamp[e->pos] = ktime_get();
4673 e->pos = (e->pos + 1) % UFS_EVENT_HIST_LENGTH;
4675 ufshcd_vops_event_notify(hba, id, &val);
4677 EXPORT_SYMBOL_GPL(ufshcd_update_evt_hist);
4680 * ufshcd_link_startup - Initialize unipro link startup
4681 * @hba: per adapter instance
4683 * Returns 0 for success, non-zero in case of failure
4685 static int ufshcd_link_startup(struct ufs_hba *hba)
4688 int retries = DME_LINKSTARTUP_RETRIES;
4689 bool link_startup_again = false;
4692 * If UFS device isn't active then we will have to issue link startup
4693 * 2 times to make sure the device state move to active.
4695 if (!ufshcd_is_ufs_dev_active(hba))
4696 link_startup_again = true;
4700 ufshcd_vops_link_startup_notify(hba, PRE_CHANGE);
4702 ret = ufshcd_dme_link_startup(hba);
4704 /* check if device is detected by inter-connect layer */
4705 if (!ret && !ufshcd_is_device_present(hba)) {
4706 ufshcd_update_evt_hist(hba,
4707 UFS_EVT_LINK_STARTUP_FAIL,
4709 dev_err(hba->dev, "%s: Device not present\n", __func__);
4715 * DME link lost indication is only received when link is up,
4716 * but we can't be sure if the link is up until link startup
4717 * succeeds. So reset the local Uni-Pro and try again.
4719 if (ret && ufshcd_hba_enable(hba)) {
4720 ufshcd_update_evt_hist(hba,
4721 UFS_EVT_LINK_STARTUP_FAIL,
4725 } while (ret && retries--);
4728 /* failed to get the link up... retire */
4729 ufshcd_update_evt_hist(hba,
4730 UFS_EVT_LINK_STARTUP_FAIL,
4735 if (link_startup_again) {
4736 link_startup_again = false;
4737 retries = DME_LINKSTARTUP_RETRIES;
4741 /* Mark that link is up in PWM-G1, 1-lane, SLOW-AUTO mode */
4742 ufshcd_init_pwr_info(hba);
4743 ufshcd_print_pwr_info(hba);
4745 if (hba->quirks & UFSHCD_QUIRK_BROKEN_LCC) {
4746 ret = ufshcd_disable_device_tx_lcc(hba);
4751 /* Include any host controller configuration via UIC commands */
4752 ret = ufshcd_vops_link_startup_notify(hba, POST_CHANGE);
4756 /* Clear UECPA once due to LINERESET has happened during LINK_STARTUP */
4757 ufshcd_readl(hba, REG_UIC_ERROR_CODE_PHY_ADAPTER_LAYER);
4758 ret = ufshcd_make_hba_operational(hba);
4761 dev_err(hba->dev, "link startup failed %d\n", ret);
4762 ufshcd_print_host_state(hba);
4763 ufshcd_print_pwr_info(hba);
4764 ufshcd_print_evt_hist(hba);
4770 * ufshcd_verify_dev_init() - Verify device initialization
4771 * @hba: per-adapter instance
4773 * Send NOP OUT UPIU and wait for NOP IN response to check whether the
4774 * device Transport Protocol (UTP) layer is ready after a reset.
4775 * If the UTP layer at the device side is not initialized, it may
4776 * not respond with NOP IN UPIU within timeout of %NOP_OUT_TIMEOUT
4777 * and we retry sending NOP OUT for %NOP_OUT_RETRIES iterations.
4779 static int ufshcd_verify_dev_init(struct ufs_hba *hba)
4784 ufshcd_hold(hba, false);
4785 mutex_lock(&hba->dev_cmd.lock);
4786 for (retries = NOP_OUT_RETRIES; retries > 0; retries--) {
4787 err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_NOP,
4790 if (!err || err == -ETIMEDOUT)
4793 dev_dbg(hba->dev, "%s: error %d retrying\n", __func__, err);
4795 mutex_unlock(&hba->dev_cmd.lock);
4796 ufshcd_release(hba);
4799 dev_err(hba->dev, "%s: NOP OUT failed %d\n", __func__, err);
4804 * ufshcd_set_queue_depth - set lun queue depth
4805 * @sdev: pointer to SCSI device
4807 * Read bLUQueueDepth value and activate scsi tagged command
4808 * queueing. For WLUN, queue depth is set to 1. For best-effort
4809 * cases (bLUQueueDepth = 0) the queue depth is set to a maximum
4810 * value that host can queue.
4812 static void ufshcd_set_queue_depth(struct scsi_device *sdev)
4816 struct ufs_hba *hba;
4818 hba = shost_priv(sdev->host);
4820 lun_qdepth = hba->nutrs;
4821 ret = ufshcd_read_unit_desc_param(hba,
4822 ufshcd_scsi_to_upiu_lun(sdev->lun),
4823 UNIT_DESC_PARAM_LU_Q_DEPTH,
4825 sizeof(lun_qdepth));
4827 /* Some WLUN doesn't support unit descriptor */
4828 if (ret == -EOPNOTSUPP)
4830 else if (!lun_qdepth)
4831 /* eventually, we can figure out the real queue depth */
4832 lun_qdepth = hba->nutrs;
4834 lun_qdepth = min_t(int, lun_qdepth, hba->nutrs);
4836 dev_dbg(hba->dev, "%s: activate tcq with queue depth %d\n",
4837 __func__, lun_qdepth);
4838 scsi_change_queue_depth(sdev, lun_qdepth);
4842 * ufshcd_get_lu_wp - returns the "b_lu_write_protect" from UNIT DESCRIPTOR
4843 * @hba: per-adapter instance
4844 * @lun: UFS device lun id
4845 * @b_lu_write_protect: pointer to buffer to hold the LU's write protect info
4847 * Returns 0 in case of success and b_lu_write_protect status would be returned
4848 * @b_lu_write_protect parameter.
4849 * Returns -ENOTSUPP if reading b_lu_write_protect is not supported.
4850 * Returns -EINVAL in case of invalid parameters passed to this function.
4852 static int ufshcd_get_lu_wp(struct ufs_hba *hba,
4854 u8 *b_lu_write_protect)
4858 if (!b_lu_write_protect)
4861 * According to UFS device spec, RPMB LU can't be write
4862 * protected so skip reading bLUWriteProtect parameter for
4863 * it. For other W-LUs, UNIT DESCRIPTOR is not available.
4865 else if (lun >= hba->dev_info.max_lu_supported)
4868 ret = ufshcd_read_unit_desc_param(hba,
4870 UNIT_DESC_PARAM_LU_WR_PROTECT,
4872 sizeof(*b_lu_write_protect));
4877 * ufshcd_get_lu_power_on_wp_status - get LU's power on write protect
4879 * @hba: per-adapter instance
4880 * @sdev: pointer to SCSI device
4883 static inline void ufshcd_get_lu_power_on_wp_status(struct ufs_hba *hba,
4884 struct scsi_device *sdev)
4886 if (hba->dev_info.f_power_on_wp_en &&
4887 !hba->dev_info.is_lu_power_on_wp) {
4888 u8 b_lu_write_protect;
4890 if (!ufshcd_get_lu_wp(hba, ufshcd_scsi_to_upiu_lun(sdev->lun),
4891 &b_lu_write_protect) &&
4892 (b_lu_write_protect == UFS_LU_POWER_ON_WP))
4893 hba->dev_info.is_lu_power_on_wp = true;
4898 * ufshcd_setup_links - associate link b/w device wlun and other luns
4899 * @sdev: pointer to SCSI device
4900 * @hba: pointer to ufs hba
4902 static void ufshcd_setup_links(struct ufs_hba *hba, struct scsi_device *sdev)
4904 struct device_link *link;
4907 * Device wlun is the supplier & rest of the luns are consumers.
4908 * This ensures that device wlun suspends after all other luns.
4910 if (hba->sdev_ufs_device) {
4911 link = device_link_add(&sdev->sdev_gendev,
4912 &hba->sdev_ufs_device->sdev_gendev,
4913 DL_FLAG_PM_RUNTIME | DL_FLAG_RPM_ACTIVE);
4915 dev_err(&sdev->sdev_gendev, "Failed establishing link - %s\n",
4916 dev_name(&hba->sdev_ufs_device->sdev_gendev));
4920 /* Ignore REPORT_LUN wlun probing */
4921 if (hba->luns_avail == 1) {
4922 ufshcd_rpm_put(hba);
4927 * Device wlun is probed. The assumption is that WLUNs are
4928 * scanned before other LUNs.
4935 * ufshcd_slave_alloc - handle initial SCSI device configurations
4936 * @sdev: pointer to SCSI device
4940 static int ufshcd_slave_alloc(struct scsi_device *sdev)
4942 struct ufs_hba *hba;
4944 hba = shost_priv(sdev->host);
4946 /* Mode sense(6) is not supported by UFS, so use Mode sense(10) */
4947 sdev->use_10_for_ms = 1;
4949 /* DBD field should be set to 1 in mode sense(10) */
4950 sdev->set_dbd_for_ms = 1;
4952 /* allow SCSI layer to restart the device in case of errors */
4953 sdev->allow_restart = 1;
4955 /* REPORT SUPPORTED OPERATION CODES is not supported */
4956 sdev->no_report_opcodes = 1;
4958 /* WRITE_SAME command is not supported */
4959 sdev->no_write_same = 1;
4961 ufshcd_set_queue_depth(sdev);
4963 ufshcd_get_lu_power_on_wp_status(hba, sdev);
4965 ufshcd_setup_links(hba, sdev);
4971 * ufshcd_change_queue_depth - change queue depth
4972 * @sdev: pointer to SCSI device
4973 * @depth: required depth to set
4975 * Change queue depth and make sure the max. limits are not crossed.
4977 static int ufshcd_change_queue_depth(struct scsi_device *sdev, int depth)
4979 struct ufs_hba *hba = shost_priv(sdev->host);
4981 if (depth > hba->nutrs)
4983 return scsi_change_queue_depth(sdev, depth);
4986 static void ufshcd_hpb_destroy(struct ufs_hba *hba, struct scsi_device *sdev)
4988 /* skip well-known LU */
4989 if ((sdev->lun >= UFS_UPIU_MAX_UNIT_NUM_ID) ||
4990 !(hba->dev_info.hpb_enabled) || !ufshpb_is_allowed(hba))
4993 ufshpb_destroy_lu(hba, sdev);
4996 static void ufshcd_hpb_configure(struct ufs_hba *hba, struct scsi_device *sdev)
4998 /* skip well-known LU */
4999 if ((sdev->lun >= UFS_UPIU_MAX_UNIT_NUM_ID) ||
5000 !(hba->dev_info.hpb_enabled) || !ufshpb_is_allowed(hba))
5003 ufshpb_init_hpb_lu(hba, sdev);
5007 * ufshcd_slave_configure - adjust SCSI device configurations
5008 * @sdev: pointer to SCSI device
5010 static int ufshcd_slave_configure(struct scsi_device *sdev)
5012 struct ufs_hba *hba = shost_priv(sdev->host);
5013 struct request_queue *q = sdev->request_queue;
5015 ufshcd_hpb_configure(hba, sdev);
5017 blk_queue_update_dma_pad(q, PRDT_DATA_BYTE_COUNT_PAD - 1);
5018 if (hba->quirks & UFSHCD_QUIRK_ALIGN_SG_WITH_PAGE_SIZE)
5019 blk_queue_update_dma_alignment(q, PAGE_SIZE - 1);
5021 * Block runtime-pm until all consumers are added.
5022 * Refer ufshcd_setup_links().
5024 if (is_device_wlun(sdev))
5025 pm_runtime_get_noresume(&sdev->sdev_gendev);
5026 else if (ufshcd_is_rpm_autosuspend_allowed(hba))
5027 sdev->rpm_autosuspend = 1;
5029 ufshcd_crypto_setup_rq_keyslot_manager(hba, q);
5035 * ufshcd_slave_destroy - remove SCSI device configurations
5036 * @sdev: pointer to SCSI device
5038 static void ufshcd_slave_destroy(struct scsi_device *sdev)
5040 struct ufs_hba *hba;
5042 hba = shost_priv(sdev->host);
5044 ufshcd_hpb_destroy(hba, sdev);
5046 /* Drop the reference as it won't be needed anymore */
5047 if (ufshcd_scsi_to_upiu_lun(sdev->lun) == UFS_UPIU_UFS_DEVICE_WLUN) {
5048 unsigned long flags;
5050 spin_lock_irqsave(hba->host->host_lock, flags);
5051 hba->sdev_ufs_device = NULL;
5052 spin_unlock_irqrestore(hba->host->host_lock, flags);
5057 * ufshcd_scsi_cmd_status - Update SCSI command result based on SCSI status
5058 * @lrbp: pointer to local reference block of completed command
5059 * @scsi_status: SCSI command status
5061 * Returns value base on SCSI command status
5064 ufshcd_scsi_cmd_status(struct ufshcd_lrb *lrbp, int scsi_status)
5068 switch (scsi_status) {
5069 case SAM_STAT_CHECK_CONDITION:
5070 ufshcd_copy_sense_data(lrbp);
5073 result |= DID_OK << 16 | scsi_status;
5075 case SAM_STAT_TASK_SET_FULL:
5077 case SAM_STAT_TASK_ABORTED:
5078 ufshcd_copy_sense_data(lrbp);
5079 result |= scsi_status;
5082 result |= DID_ERROR << 16;
5084 } /* end of switch */
5090 * ufshcd_transfer_rsp_status - Get overall status of the response
5091 * @hba: per adapter instance
5092 * @lrbp: pointer to local reference block of completed command
5094 * Returns result of the command to notify SCSI midlayer
5097 ufshcd_transfer_rsp_status(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
5103 /* overall command status of utrd */
5104 ocs = ufshcd_get_tr_ocs(lrbp);
5106 if (hba->quirks & UFSHCD_QUIRK_BROKEN_OCS_FATAL_ERROR) {
5107 if (be32_to_cpu(lrbp->ucd_rsp_ptr->header.dword_1) &
5108 MASK_RSP_UPIU_RESULT)
5114 result = ufshcd_get_req_rsp(lrbp->ucd_rsp_ptr);
5115 hba->ufs_stats.last_hibern8_exit_tstamp = ktime_set(0, 0);
5117 case UPIU_TRANSACTION_RESPONSE:
5119 * get the response UPIU result to extract
5120 * the SCSI command status
5122 result = ufshcd_get_rsp_upiu_result(lrbp->ucd_rsp_ptr);
5125 * get the result based on SCSI status response
5126 * to notify the SCSI midlayer of the command status
5128 scsi_status = result & MASK_SCSI_STATUS;
5129 result = ufshcd_scsi_cmd_status(lrbp, scsi_status);
5132 * Currently we are only supporting BKOPs exception
5133 * events hence we can ignore BKOPs exception event
5134 * during power management callbacks. BKOPs exception
5135 * event is not expected to be raised in runtime suspend
5136 * callback as it allows the urgent bkops.
5137 * During system suspend, we are anyway forcefully
5138 * disabling the bkops and if urgent bkops is needed
5139 * it will be enabled on system resume. Long term
5140 * solution could be to abort the system suspend if
5141 * UFS device needs urgent BKOPs.
5143 if (!hba->pm_op_in_progress &&
5144 !ufshcd_eh_in_progress(hba) &&
5145 ufshcd_is_exception_event(lrbp->ucd_rsp_ptr))
5146 /* Flushed in suspend */
5147 schedule_work(&hba->eeh_work);
5149 if (scsi_status == SAM_STAT_GOOD)
5150 ufshpb_rsp_upiu(hba, lrbp);
5152 case UPIU_TRANSACTION_REJECT_UPIU:
5153 /* TODO: handle Reject UPIU Response */
5154 result = DID_ERROR << 16;
5156 "Reject UPIU not fully implemented\n");
5160 "Unexpected request response code = %x\n",
5162 result = DID_ERROR << 16;
5167 result |= DID_ABORT << 16;
5169 case OCS_INVALID_COMMAND_STATUS:
5170 result |= DID_REQUEUE << 16;
5172 case OCS_INVALID_CMD_TABLE_ATTR:
5173 case OCS_INVALID_PRDT_ATTR:
5174 case OCS_MISMATCH_DATA_BUF_SIZE:
5175 case OCS_MISMATCH_RESP_UPIU_SIZE:
5176 case OCS_PEER_COMM_FAILURE:
5177 case OCS_FATAL_ERROR:
5178 case OCS_DEVICE_FATAL_ERROR:
5179 case OCS_INVALID_CRYPTO_CONFIG:
5180 case OCS_GENERAL_CRYPTO_ERROR:
5182 result |= DID_ERROR << 16;
5184 "OCS error from controller = %x for tag %d\n",
5185 ocs, lrbp->task_tag);
5186 ufshcd_print_evt_hist(hba);
5187 ufshcd_print_host_state(hba);
5189 } /* end of switch */
5191 if ((host_byte(result) != DID_OK) &&
5192 (host_byte(result) != DID_REQUEUE) && !hba->silence_err_logs)
5193 ufshcd_print_trs(hba, 1 << lrbp->task_tag, true);
5197 static bool ufshcd_is_auto_hibern8_error(struct ufs_hba *hba,
5200 if (!ufshcd_is_auto_hibern8_supported(hba) ||
5201 !ufshcd_is_auto_hibern8_enabled(hba))
5204 if (!(intr_mask & UFSHCD_UIC_HIBERN8_MASK))
5207 if (hba->active_uic_cmd &&
5208 (hba->active_uic_cmd->command == UIC_CMD_DME_HIBER_ENTER ||
5209 hba->active_uic_cmd->command == UIC_CMD_DME_HIBER_EXIT))
5216 * ufshcd_uic_cmd_compl - handle completion of uic command
5217 * @hba: per adapter instance
5218 * @intr_status: interrupt status generated by the controller
5221 * IRQ_HANDLED - If interrupt is valid
5222 * IRQ_NONE - If invalid interrupt
5224 static irqreturn_t ufshcd_uic_cmd_compl(struct ufs_hba *hba, u32 intr_status)
5226 irqreturn_t retval = IRQ_NONE;
5228 spin_lock(hba->host->host_lock);
5229 if (ufshcd_is_auto_hibern8_error(hba, intr_status))
5230 hba->errors |= (UFSHCD_UIC_HIBERN8_MASK & intr_status);
5232 if ((intr_status & UIC_COMMAND_COMPL) && hba->active_uic_cmd) {
5233 hba->active_uic_cmd->argument2 |=
5234 ufshcd_get_uic_cmd_result(hba);
5235 hba->active_uic_cmd->argument3 =
5236 ufshcd_get_dme_attr_val(hba);
5237 if (!hba->uic_async_done)
5238 hba->active_uic_cmd->cmd_active = 0;
5239 complete(&hba->active_uic_cmd->done);
5240 retval = IRQ_HANDLED;
5243 if ((intr_status & UFSHCD_UIC_PWR_MASK) && hba->uic_async_done) {
5244 hba->active_uic_cmd->cmd_active = 0;
5245 complete(hba->uic_async_done);
5246 retval = IRQ_HANDLED;
5249 if (retval == IRQ_HANDLED)
5250 ufshcd_add_uic_command_trace(hba, hba->active_uic_cmd,
5252 spin_unlock(hba->host->host_lock);
5257 * __ufshcd_transfer_req_compl - handle SCSI and query command completion
5258 * @hba: per adapter instance
5259 * @completed_reqs: requests to complete
5261 static void __ufshcd_transfer_req_compl(struct ufs_hba *hba,
5262 unsigned long completed_reqs)
5264 struct ufshcd_lrb *lrbp;
5265 struct scsi_cmnd *cmd;
5268 bool update_scaling = false;
5270 for_each_set_bit(index, &completed_reqs, hba->nutrs) {
5271 if (!test_and_clear_bit(index, &hba->outstanding_reqs))
5273 lrbp = &hba->lrb[index];
5274 lrbp->compl_time_stamp = ktime_get();
5277 if (unlikely(ufshcd_should_inform_monitor(hba, lrbp)))
5278 ufshcd_update_monitor(hba, lrbp);
5279 ufshcd_add_command_trace(hba, index, UFS_CMD_COMP);
5280 result = ufshcd_transfer_rsp_status(hba, lrbp);
5281 scsi_dma_unmap(cmd);
5282 cmd->result = result;
5283 /* Mark completed command as NULL in LRB */
5285 /* Do not touch lrbp after scsi done */
5286 cmd->scsi_done(cmd);
5287 ufshcd_release(hba);
5288 update_scaling = true;
5289 } else if (lrbp->command_type == UTP_CMD_TYPE_DEV_MANAGE ||
5290 lrbp->command_type == UTP_CMD_TYPE_UFS_STORAGE) {
5291 if (hba->dev_cmd.complete) {
5292 ufshcd_add_command_trace(hba, index,
5294 complete(hba->dev_cmd.complete);
5295 update_scaling = true;
5299 ufshcd_clk_scaling_update_busy(hba);
5304 * ufshcd_trc_handler - handle transfer requests completion
5305 * @hba: per adapter instance
5306 * @use_utrlcnr: get completed requests from UTRLCNR
5309 * IRQ_HANDLED - If interrupt is valid
5310 * IRQ_NONE - If invalid interrupt
5312 static irqreturn_t ufshcd_trc_handler(struct ufs_hba *hba, bool use_utrlcnr)
5314 unsigned long completed_reqs = 0;
5316 /* Resetting interrupt aggregation counters first and reading the
5317 * DOOR_BELL afterward allows us to handle all the completed requests.
5318 * In order to prevent other interrupts starvation the DB is read once
5319 * after reset. The down side of this solution is the possibility of
5320 * false interrupt if device completes another request after resetting
5321 * aggregation and before reading the DB.
5323 if (ufshcd_is_intr_aggr_allowed(hba) &&
5324 !(hba->quirks & UFSHCI_QUIRK_SKIP_RESET_INTR_AGGR))
5325 ufshcd_reset_intr_aggr(hba);
5330 utrlcnr = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_LIST_COMPL);
5332 ufshcd_writel(hba, utrlcnr,
5333 REG_UTP_TRANSFER_REQ_LIST_COMPL);
5334 completed_reqs = utrlcnr;
5337 unsigned long flags;
5340 spin_lock_irqsave(hba->host->host_lock, flags);
5341 tr_doorbell = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
5342 completed_reqs = tr_doorbell ^ hba->outstanding_reqs;
5343 spin_unlock_irqrestore(hba->host->host_lock, flags);
5346 if (completed_reqs) {
5347 __ufshcd_transfer_req_compl(hba, completed_reqs);
5354 int __ufshcd_write_ee_control(struct ufs_hba *hba, u32 ee_ctrl_mask)
5356 return ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_WRITE_ATTR,
5357 QUERY_ATTR_IDN_EE_CONTROL, 0, 0,
5361 int ufshcd_write_ee_control(struct ufs_hba *hba)
5365 mutex_lock(&hba->ee_ctrl_mutex);
5366 err = __ufshcd_write_ee_control(hba, hba->ee_ctrl_mask);
5367 mutex_unlock(&hba->ee_ctrl_mutex);
5369 dev_err(hba->dev, "%s: failed to write ee control %d\n",
5374 int ufshcd_update_ee_control(struct ufs_hba *hba, u16 *mask, u16 *other_mask,
5377 u16 new_mask, ee_ctrl_mask;
5380 mutex_lock(&hba->ee_ctrl_mutex);
5381 new_mask = (*mask & ~clr) | set;
5382 ee_ctrl_mask = new_mask | *other_mask;
5383 if (ee_ctrl_mask != hba->ee_ctrl_mask)
5384 err = __ufshcd_write_ee_control(hba, ee_ctrl_mask);
5385 /* Still need to update 'mask' even if 'ee_ctrl_mask' was unchanged */
5387 hba->ee_ctrl_mask = ee_ctrl_mask;
5390 mutex_unlock(&hba->ee_ctrl_mutex);
5395 * ufshcd_disable_ee - disable exception event
5396 * @hba: per-adapter instance
5397 * @mask: exception event to disable
5399 * Disables exception event in the device so that the EVENT_ALERT
5402 * Returns zero on success, non-zero error value on failure.
5404 static inline int ufshcd_disable_ee(struct ufs_hba *hba, u16 mask)
5406 return ufshcd_update_ee_drv_mask(hba, 0, mask);
5410 * ufshcd_enable_ee - enable exception event
5411 * @hba: per-adapter instance
5412 * @mask: exception event to enable
5414 * Enable corresponding exception event in the device to allow
5415 * device to alert host in critical scenarios.
5417 * Returns zero on success, non-zero error value on failure.
5419 static inline int ufshcd_enable_ee(struct ufs_hba *hba, u16 mask)
5421 return ufshcd_update_ee_drv_mask(hba, mask, 0);
5425 * ufshcd_enable_auto_bkops - Allow device managed BKOPS
5426 * @hba: per-adapter instance
5428 * Allow device to manage background operations on its own. Enabling
5429 * this might lead to inconsistent latencies during normal data transfers
5430 * as the device is allowed to manage its own way of handling background
5433 * Returns zero on success, non-zero on failure.
5435 static int ufshcd_enable_auto_bkops(struct ufs_hba *hba)
5439 if (hba->auto_bkops_enabled)
5442 err = ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_SET_FLAG,
5443 QUERY_FLAG_IDN_BKOPS_EN, 0, NULL);
5445 dev_err(hba->dev, "%s: failed to enable bkops %d\n",
5450 hba->auto_bkops_enabled = true;
5451 trace_ufshcd_auto_bkops_state(dev_name(hba->dev), "Enabled");
5453 /* No need of URGENT_BKOPS exception from the device */
5454 err = ufshcd_disable_ee(hba, MASK_EE_URGENT_BKOPS);
5456 dev_err(hba->dev, "%s: failed to disable exception event %d\n",
5463 * ufshcd_disable_auto_bkops - block device in doing background operations
5464 * @hba: per-adapter instance
5466 * Disabling background operations improves command response latency but
5467 * has drawback of device moving into critical state where the device is
5468 * not-operable. Make sure to call ufshcd_enable_auto_bkops() whenever the
5469 * host is idle so that BKOPS are managed effectively without any negative
5472 * Returns zero on success, non-zero on failure.
5474 static int ufshcd_disable_auto_bkops(struct ufs_hba *hba)
5478 if (!hba->auto_bkops_enabled)
5482 * If host assisted BKOPs is to be enabled, make sure
5483 * urgent bkops exception is allowed.
5485 err = ufshcd_enable_ee(hba, MASK_EE_URGENT_BKOPS);
5487 dev_err(hba->dev, "%s: failed to enable exception event %d\n",
5492 err = ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_CLEAR_FLAG,
5493 QUERY_FLAG_IDN_BKOPS_EN, 0, NULL);
5495 dev_err(hba->dev, "%s: failed to disable bkops %d\n",
5497 ufshcd_disable_ee(hba, MASK_EE_URGENT_BKOPS);
5501 hba->auto_bkops_enabled = false;
5502 trace_ufshcd_auto_bkops_state(dev_name(hba->dev), "Disabled");
5503 hba->is_urgent_bkops_lvl_checked = false;
5509 * ufshcd_force_reset_auto_bkops - force reset auto bkops state
5510 * @hba: per adapter instance
5512 * After a device reset the device may toggle the BKOPS_EN flag
5513 * to default value. The s/w tracking variables should be updated
5514 * as well. This function would change the auto-bkops state based on
5515 * UFSHCD_CAP_KEEP_AUTO_BKOPS_ENABLED_EXCEPT_SUSPEND.
5517 static void ufshcd_force_reset_auto_bkops(struct ufs_hba *hba)
5519 if (ufshcd_keep_autobkops_enabled_except_suspend(hba)) {
5520 hba->auto_bkops_enabled = false;
5521 hba->ee_ctrl_mask |= MASK_EE_URGENT_BKOPS;
5522 ufshcd_enable_auto_bkops(hba);
5524 hba->auto_bkops_enabled = true;
5525 hba->ee_ctrl_mask &= ~MASK_EE_URGENT_BKOPS;
5526 ufshcd_disable_auto_bkops(hba);
5528 hba->urgent_bkops_lvl = BKOPS_STATUS_PERF_IMPACT;
5529 hba->is_urgent_bkops_lvl_checked = false;
5532 static inline int ufshcd_get_bkops_status(struct ufs_hba *hba, u32 *status)
5534 return ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
5535 QUERY_ATTR_IDN_BKOPS_STATUS, 0, 0, status);
5539 * ufshcd_bkops_ctrl - control the auto bkops based on current bkops status
5540 * @hba: per-adapter instance
5541 * @status: bkops_status value
5543 * Read the bkops_status from the UFS device and Enable fBackgroundOpsEn
5544 * flag in the device to permit background operations if the device
5545 * bkops_status is greater than or equal to "status" argument passed to
5546 * this function, disable otherwise.
5548 * Returns 0 for success, non-zero in case of failure.
5550 * NOTE: Caller of this function can check the "hba->auto_bkops_enabled" flag
5551 * to know whether auto bkops is enabled or disabled after this function
5552 * returns control to it.
5554 static int ufshcd_bkops_ctrl(struct ufs_hba *hba,
5555 enum bkops_status status)
5558 u32 curr_status = 0;
5560 err = ufshcd_get_bkops_status(hba, &curr_status);
5562 dev_err(hba->dev, "%s: failed to get BKOPS status %d\n",
5565 } else if (curr_status > BKOPS_STATUS_MAX) {
5566 dev_err(hba->dev, "%s: invalid BKOPS status %d\n",
5567 __func__, curr_status);
5572 if (curr_status >= status)
5573 err = ufshcd_enable_auto_bkops(hba);
5575 err = ufshcd_disable_auto_bkops(hba);
5581 * ufshcd_urgent_bkops - handle urgent bkops exception event
5582 * @hba: per-adapter instance
5584 * Enable fBackgroundOpsEn flag in the device to permit background
5587 * If BKOPs is enabled, this function returns 0, 1 if the bkops in not enabled
5588 * and negative error value for any other failure.
5590 static int ufshcd_urgent_bkops(struct ufs_hba *hba)
5592 return ufshcd_bkops_ctrl(hba, hba->urgent_bkops_lvl);
5595 static inline int ufshcd_get_ee_status(struct ufs_hba *hba, u32 *status)
5597 return ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
5598 QUERY_ATTR_IDN_EE_STATUS, 0, 0, status);
5601 static void ufshcd_bkops_exception_event_handler(struct ufs_hba *hba)
5604 u32 curr_status = 0;
5606 if (hba->is_urgent_bkops_lvl_checked)
5607 goto enable_auto_bkops;
5609 err = ufshcd_get_bkops_status(hba, &curr_status);
5611 dev_err(hba->dev, "%s: failed to get BKOPS status %d\n",
5617 * We are seeing that some devices are raising the urgent bkops
5618 * exception events even when BKOPS status doesn't indicate performace
5619 * impacted or critical. Handle these device by determining their urgent
5620 * bkops status at runtime.
5622 if (curr_status < BKOPS_STATUS_PERF_IMPACT) {
5623 dev_err(hba->dev, "%s: device raised urgent BKOPS exception for bkops status %d\n",
5624 __func__, curr_status);
5625 /* update the current status as the urgent bkops level */
5626 hba->urgent_bkops_lvl = curr_status;
5627 hba->is_urgent_bkops_lvl_checked = true;
5631 err = ufshcd_enable_auto_bkops(hba);
5634 dev_err(hba->dev, "%s: failed to handle urgent bkops %d\n",
5638 static int __ufshcd_wb_toggle(struct ufs_hba *hba, bool set, enum flag_idn idn)
5641 enum query_opcode opcode = set ? UPIU_QUERY_OPCODE_SET_FLAG :
5642 UPIU_QUERY_OPCODE_CLEAR_FLAG;
5644 index = ufshcd_wb_get_query_index(hba);
5645 return ufshcd_query_flag_retry(hba, opcode, idn, index, NULL);
5648 int ufshcd_wb_toggle(struct ufs_hba *hba, bool enable)
5652 if (!ufshcd_is_wb_allowed(hba))
5655 if (!(enable ^ hba->dev_info.wb_enabled))
5658 ret = __ufshcd_wb_toggle(hba, enable, QUERY_FLAG_IDN_WB_EN);
5660 dev_err(hba->dev, "%s Write Booster %s failed %d\n",
5661 __func__, enable ? "enable" : "disable", ret);
5665 hba->dev_info.wb_enabled = enable;
5666 dev_info(hba->dev, "%s Write Booster %s\n",
5667 __func__, enable ? "enabled" : "disabled");
5672 static void ufshcd_wb_toggle_flush_during_h8(struct ufs_hba *hba, bool set)
5676 ret = __ufshcd_wb_toggle(hba, set,
5677 QUERY_FLAG_IDN_WB_BUFF_FLUSH_DURING_HIBERN8);
5679 dev_err(hba->dev, "%s: WB-Buf Flush during H8 %s failed: %d\n",
5680 __func__, set ? "enable" : "disable", ret);
5683 dev_dbg(hba->dev, "%s WB-Buf Flush during H8 %s\n",
5684 __func__, set ? "enabled" : "disabled");
5687 static inline void ufshcd_wb_toggle_flush(struct ufs_hba *hba, bool enable)
5691 if (!ufshcd_is_wb_allowed(hba) ||
5692 hba->dev_info.wb_buf_flush_enabled == enable)
5695 ret = __ufshcd_wb_toggle(hba, enable, QUERY_FLAG_IDN_WB_BUFF_FLUSH_EN);
5697 dev_err(hba->dev, "%s WB-Buf Flush %s failed %d\n", __func__,
5698 enable ? "enable" : "disable", ret);
5702 hba->dev_info.wb_buf_flush_enabled = enable;
5704 dev_dbg(hba->dev, "%s WB-Buf Flush %s\n",
5705 __func__, enable ? "enabled" : "disabled");
5708 static bool ufshcd_wb_presrv_usrspc_keep_vcc_on(struct ufs_hba *hba,
5715 index = ufshcd_wb_get_query_index(hba);
5716 ret = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
5717 QUERY_ATTR_IDN_CURR_WB_BUFF_SIZE,
5718 index, 0, &cur_buf);
5720 dev_err(hba->dev, "%s dCurWriteBoosterBufferSize read failed %d\n",
5726 dev_info(hba->dev, "dCurWBBuf: %d WB disabled until free-space is available\n",
5730 /* Let it continue to flush when available buffer exceeds threshold */
5731 if (avail_buf < hba->vps->wb_flush_threshold)
5737 static bool ufshcd_wb_need_flush(struct ufs_hba *hba)
5743 if (!ufshcd_is_wb_allowed(hba))
5746 * The ufs device needs the vcc to be ON to flush.
5747 * With user-space reduction enabled, it's enough to enable flush
5748 * by checking only the available buffer. The threshold
5749 * defined here is > 90% full.
5750 * With user-space preserved enabled, the current-buffer
5751 * should be checked too because the wb buffer size can reduce
5752 * when disk tends to be full. This info is provided by current
5753 * buffer (dCurrentWriteBoosterBufferSize). There's no point in
5754 * keeping vcc on when current buffer is empty.
5756 index = ufshcd_wb_get_query_index(hba);
5757 ret = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
5758 QUERY_ATTR_IDN_AVAIL_WB_BUFF_SIZE,
5759 index, 0, &avail_buf);
5761 dev_warn(hba->dev, "%s dAvailableWriteBoosterBufferSize read failed %d\n",
5766 if (!hba->dev_info.b_presrv_uspc_en) {
5767 if (avail_buf <= UFS_WB_BUF_REMAIN_PERCENT(10))
5772 return ufshcd_wb_presrv_usrspc_keep_vcc_on(hba, avail_buf);
5775 static void ufshcd_rpm_dev_flush_recheck_work(struct work_struct *work)
5777 struct ufs_hba *hba = container_of(to_delayed_work(work),
5779 rpm_dev_flush_recheck_work);
5781 * To prevent unnecessary VCC power drain after device finishes
5782 * WriteBooster buffer flush or Auto BKOPs, force runtime resume
5783 * after a certain delay to recheck the threshold by next runtime
5786 ufshcd_rpm_get_sync(hba);
5787 ufshcd_rpm_put_sync(hba);
5791 * ufshcd_exception_event_handler - handle exceptions raised by device
5792 * @work: pointer to work data
5794 * Read bExceptionEventStatus attribute from the device and handle the
5795 * exception event accordingly.
5797 static void ufshcd_exception_event_handler(struct work_struct *work)
5799 struct ufs_hba *hba;
5802 hba = container_of(work, struct ufs_hba, eeh_work);
5804 ufshcd_scsi_block_requests(hba);
5805 err = ufshcd_get_ee_status(hba, &status);
5807 dev_err(hba->dev, "%s: failed to get exception status %d\n",
5812 trace_ufshcd_exception_event(dev_name(hba->dev), status);
5814 if (status & hba->ee_drv_mask & MASK_EE_URGENT_BKOPS)
5815 ufshcd_bkops_exception_event_handler(hba);
5817 ufs_debugfs_exception_event(hba, status);
5819 ufshcd_scsi_unblock_requests(hba);
5823 /* Complete requests that have door-bell cleared */
5824 static void ufshcd_complete_requests(struct ufs_hba *hba)
5826 ufshcd_trc_handler(hba, false);
5827 ufshcd_tmc_handler(hba);
5831 * ufshcd_quirk_dl_nac_errors - This function checks if error handling is
5832 * to recover from the DL NAC errors or not.
5833 * @hba: per-adapter instance
5835 * Returns true if error handling is required, false otherwise
5837 static bool ufshcd_quirk_dl_nac_errors(struct ufs_hba *hba)
5839 unsigned long flags;
5840 bool err_handling = true;
5842 spin_lock_irqsave(hba->host->host_lock, flags);
5844 * UFS_DEVICE_QUIRK_RECOVERY_FROM_DL_NAC_ERRORS only workaround the
5845 * device fatal error and/or DL NAC & REPLAY timeout errors.
5847 if (hba->saved_err & (CONTROLLER_FATAL_ERROR | SYSTEM_BUS_FATAL_ERROR))
5850 if ((hba->saved_err & DEVICE_FATAL_ERROR) ||
5851 ((hba->saved_err & UIC_ERROR) &&
5852 (hba->saved_uic_err & UFSHCD_UIC_DL_TCx_REPLAY_ERROR)))
5855 if ((hba->saved_err & UIC_ERROR) &&
5856 (hba->saved_uic_err & UFSHCD_UIC_DL_NAC_RECEIVED_ERROR)) {
5859 * wait for 50ms to see if we can get any other errors or not.
5861 spin_unlock_irqrestore(hba->host->host_lock, flags);
5863 spin_lock_irqsave(hba->host->host_lock, flags);
5866 * now check if we have got any other severe errors other than
5869 if ((hba->saved_err & INT_FATAL_ERRORS) ||
5870 ((hba->saved_err & UIC_ERROR) &&
5871 (hba->saved_uic_err & ~UFSHCD_UIC_DL_NAC_RECEIVED_ERROR)))
5875 * As DL NAC is the only error received so far, send out NOP
5876 * command to confirm if link is still active or not.
5877 * - If we don't get any response then do error recovery.
5878 * - If we get response then clear the DL NAC error bit.
5881 spin_unlock_irqrestore(hba->host->host_lock, flags);
5882 err = ufshcd_verify_dev_init(hba);
5883 spin_lock_irqsave(hba->host->host_lock, flags);
5888 /* Link seems to be alive hence ignore the DL NAC errors */
5889 if (hba->saved_uic_err == UFSHCD_UIC_DL_NAC_RECEIVED_ERROR)
5890 hba->saved_err &= ~UIC_ERROR;
5891 /* clear NAC error */
5892 hba->saved_uic_err &= ~UFSHCD_UIC_DL_NAC_RECEIVED_ERROR;
5893 if (!hba->saved_uic_err)
5894 err_handling = false;
5897 spin_unlock_irqrestore(hba->host->host_lock, flags);
5898 return err_handling;
5901 /* host lock must be held before calling this func */
5902 static inline bool ufshcd_is_saved_err_fatal(struct ufs_hba *hba)
5904 return (hba->saved_uic_err & UFSHCD_UIC_DL_PA_INIT_ERROR) ||
5905 (hba->saved_err & (INT_FATAL_ERRORS | UFSHCD_UIC_HIBERN8_MASK));
5908 /* host lock must be held before calling this func */
5909 static inline void ufshcd_schedule_eh_work(struct ufs_hba *hba)
5911 /* handle fatal errors only when link is not in error state */
5912 if (hba->ufshcd_state != UFSHCD_STATE_ERROR) {
5913 if (hba->force_reset || ufshcd_is_link_broken(hba) ||
5914 ufshcd_is_saved_err_fatal(hba))
5915 hba->ufshcd_state = UFSHCD_STATE_EH_SCHEDULED_FATAL;
5917 hba->ufshcd_state = UFSHCD_STATE_EH_SCHEDULED_NON_FATAL;
5918 queue_work(hba->eh_wq, &hba->eh_work);
5922 static void ufshcd_clk_scaling_allow(struct ufs_hba *hba, bool allow)
5924 down_write(&hba->clk_scaling_lock);
5925 hba->clk_scaling.is_allowed = allow;
5926 up_write(&hba->clk_scaling_lock);
5929 static void ufshcd_clk_scaling_suspend(struct ufs_hba *hba, bool suspend)
5932 if (hba->clk_scaling.is_enabled)
5933 ufshcd_suspend_clkscaling(hba);
5934 ufshcd_clk_scaling_allow(hba, false);
5936 ufshcd_clk_scaling_allow(hba, true);
5937 if (hba->clk_scaling.is_enabled)
5938 ufshcd_resume_clkscaling(hba);
5942 static void ufshcd_err_handling_prepare(struct ufs_hba *hba)
5944 ufshcd_rpm_get_sync(hba);
5945 if (pm_runtime_status_suspended(&hba->sdev_ufs_device->sdev_gendev) ||
5946 hba->is_sys_suspended) {
5947 enum ufs_pm_op pm_op;
5950 * Don't assume anything of resume, if
5951 * resume fails, irq and clocks can be OFF, and powers
5952 * can be OFF or in LPM.
5954 ufshcd_setup_hba_vreg(hba, true);
5955 ufshcd_enable_irq(hba);
5956 ufshcd_setup_vreg(hba, true);
5957 ufshcd_config_vreg_hpm(hba, hba->vreg_info.vccq);
5958 ufshcd_config_vreg_hpm(hba, hba->vreg_info.vccq2);
5959 ufshcd_hold(hba, false);
5960 if (!ufshcd_is_clkgating_allowed(hba))
5961 ufshcd_setup_clocks(hba, true);
5962 ufshcd_release(hba);
5963 pm_op = hba->is_sys_suspended ? UFS_SYSTEM_PM : UFS_RUNTIME_PM;
5964 ufshcd_vops_resume(hba, pm_op);
5966 ufshcd_hold(hba, false);
5967 if (ufshcd_is_clkscaling_supported(hba) &&
5968 hba->clk_scaling.is_enabled)
5969 ufshcd_suspend_clkscaling(hba);
5970 ufshcd_clk_scaling_allow(hba, false);
5972 ufshcd_scsi_block_requests(hba);
5973 /* Drain ufshcd_queuecommand() */
5974 down_write(&hba->clk_scaling_lock);
5975 up_write(&hba->clk_scaling_lock);
5976 cancel_work_sync(&hba->eeh_work);
5979 static void ufshcd_err_handling_unprepare(struct ufs_hba *hba)
5981 ufshcd_scsi_unblock_requests(hba);
5982 ufshcd_release(hba);
5983 if (ufshcd_is_clkscaling_supported(hba))
5984 ufshcd_clk_scaling_suspend(hba, false);
5985 ufshcd_clear_ua_wluns(hba);
5986 ufshcd_rpm_put(hba);
5989 static inline bool ufshcd_err_handling_should_stop(struct ufs_hba *hba)
5991 return (!hba->is_powered || hba->shutting_down ||
5992 !hba->sdev_ufs_device ||
5993 hba->ufshcd_state == UFSHCD_STATE_ERROR ||
5994 (!(hba->saved_err || hba->saved_uic_err || hba->force_reset ||
5995 ufshcd_is_link_broken(hba))));
5999 static void ufshcd_recover_pm_error(struct ufs_hba *hba)
6001 struct Scsi_Host *shost = hba->host;
6002 struct scsi_device *sdev;
6003 struct request_queue *q;
6006 hba->is_sys_suspended = false;
6008 * Set RPM status of wlun device to RPM_ACTIVE,
6009 * this also clears its runtime error.
6011 ret = pm_runtime_set_active(&hba->sdev_ufs_device->sdev_gendev);
6013 /* hba device might have a runtime error otherwise */
6015 ret = pm_runtime_set_active(hba->dev);
6017 * If wlun device had runtime error, we also need to resume those
6018 * consumer scsi devices in case any of them has failed to be
6019 * resumed due to supplier runtime resume failure. This is to unblock
6020 * blk_queue_enter in case there are bios waiting inside it.
6023 shost_for_each_device(sdev, shost) {
6024 q = sdev->request_queue;
6025 if (q->dev && (q->rpm_status == RPM_SUSPENDED ||
6026 q->rpm_status == RPM_SUSPENDING))
6027 pm_request_resume(q->dev);
6032 static inline void ufshcd_recover_pm_error(struct ufs_hba *hba)
6037 static bool ufshcd_is_pwr_mode_restore_needed(struct ufs_hba *hba)
6039 struct ufs_pa_layer_attr *pwr_info = &hba->pwr_info;
6042 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_PWRMODE), &mode);
6044 if (pwr_info->pwr_rx != ((mode >> PWRMODE_RX_OFFSET) & PWRMODE_MASK))
6047 if (pwr_info->pwr_tx != (mode & PWRMODE_MASK))
6054 * ufshcd_err_handler - handle UFS errors that require s/w attention
6055 * @work: pointer to work structure
6057 static void ufshcd_err_handler(struct work_struct *work)
6059 struct ufs_hba *hba;
6060 unsigned long flags;
6061 bool err_xfer = false;
6062 bool err_tm = false;
6063 int err = 0, pmc_err;
6065 bool needs_reset = false, needs_restore = false;
6067 hba = container_of(work, struct ufs_hba, eh_work);
6069 down(&hba->host_sem);
6070 spin_lock_irqsave(hba->host->host_lock, flags);
6071 if (ufshcd_err_handling_should_stop(hba)) {
6072 if (hba->ufshcd_state != UFSHCD_STATE_ERROR)
6073 hba->ufshcd_state = UFSHCD_STATE_OPERATIONAL;
6074 spin_unlock_irqrestore(hba->host->host_lock, flags);
6078 ufshcd_set_eh_in_progress(hba);
6079 spin_unlock_irqrestore(hba->host->host_lock, flags);
6080 ufshcd_err_handling_prepare(hba);
6081 /* Complete requests that have door-bell cleared by h/w */
6082 ufshcd_complete_requests(hba);
6083 spin_lock_irqsave(hba->host->host_lock, flags);
6084 if (hba->ufshcd_state != UFSHCD_STATE_ERROR)
6085 hba->ufshcd_state = UFSHCD_STATE_RESET;
6087 * A full reset and restore might have happened after preparation
6088 * is finished, double check whether we should stop.
6090 if (ufshcd_err_handling_should_stop(hba))
6091 goto skip_err_handling;
6093 if (hba->dev_quirks & UFS_DEVICE_QUIRK_RECOVERY_FROM_DL_NAC_ERRORS) {
6096 spin_unlock_irqrestore(hba->host->host_lock, flags);
6097 /* release the lock as ufshcd_quirk_dl_nac_errors() may sleep */
6098 ret = ufshcd_quirk_dl_nac_errors(hba);
6099 spin_lock_irqsave(hba->host->host_lock, flags);
6100 if (!ret && ufshcd_err_handling_should_stop(hba))
6101 goto skip_err_handling;
6104 if ((hba->saved_err & (INT_FATAL_ERRORS | UFSHCD_UIC_HIBERN8_MASK)) ||
6105 (hba->saved_uic_err &&
6106 (hba->saved_uic_err != UFSHCD_UIC_PA_GENERIC_ERROR))) {
6107 bool pr_prdt = !!(hba->saved_err & SYSTEM_BUS_FATAL_ERROR);
6109 spin_unlock_irqrestore(hba->host->host_lock, flags);
6110 ufshcd_print_host_state(hba);
6111 ufshcd_print_pwr_info(hba);
6112 ufshcd_print_evt_hist(hba);
6113 ufshcd_print_tmrs(hba, hba->outstanding_tasks);
6114 ufshcd_print_trs(hba, hba->outstanding_reqs, pr_prdt);
6115 spin_lock_irqsave(hba->host->host_lock, flags);
6119 * if host reset is required then skip clearing the pending
6120 * transfers forcefully because they will get cleared during
6121 * host reset and restore
6123 if (hba->force_reset || ufshcd_is_link_broken(hba) ||
6124 ufshcd_is_saved_err_fatal(hba) ||
6125 ((hba->saved_err & UIC_ERROR) &&
6126 (hba->saved_uic_err & (UFSHCD_UIC_DL_NAC_RECEIVED_ERROR |
6127 UFSHCD_UIC_DL_TCx_REPLAY_ERROR)))) {
6133 * If LINERESET was caught, UFS might have been put to PWM mode,
6134 * check if power mode restore is needed.
6136 if (hba->saved_uic_err & UFSHCD_UIC_PA_GENERIC_ERROR) {
6137 hba->saved_uic_err &= ~UFSHCD_UIC_PA_GENERIC_ERROR;
6138 if (!hba->saved_uic_err)
6139 hba->saved_err &= ~UIC_ERROR;
6140 spin_unlock_irqrestore(hba->host->host_lock, flags);
6141 if (ufshcd_is_pwr_mode_restore_needed(hba))
6142 needs_restore = true;
6143 spin_lock_irqsave(hba->host->host_lock, flags);
6144 if (!hba->saved_err && !needs_restore)
6145 goto skip_err_handling;
6148 hba->silence_err_logs = true;
6149 /* release lock as clear command might sleep */
6150 spin_unlock_irqrestore(hba->host->host_lock, flags);
6151 /* Clear pending transfer requests */
6152 for_each_set_bit(tag, &hba->outstanding_reqs, hba->nutrs) {
6153 if (ufshcd_try_to_abort_task(hba, tag)) {
6155 goto lock_skip_pending_xfer_clear;
6159 /* Clear pending task management requests */
6160 for_each_set_bit(tag, &hba->outstanding_tasks, hba->nutmrs) {
6161 if (ufshcd_clear_tm_cmd(hba, tag)) {
6163 goto lock_skip_pending_xfer_clear;
6167 lock_skip_pending_xfer_clear:
6168 /* Complete the requests that are cleared by s/w */
6169 ufshcd_complete_requests(hba);
6171 spin_lock_irqsave(hba->host->host_lock, flags);
6172 hba->silence_err_logs = false;
6173 if (err_xfer || err_tm) {
6179 * After all reqs and tasks are cleared from doorbell,
6180 * now it is safe to retore power mode.
6182 if (needs_restore) {
6183 spin_unlock_irqrestore(hba->host->host_lock, flags);
6185 * Hold the scaling lock just in case dev cmds
6186 * are sent via bsg and/or sysfs.
6188 down_write(&hba->clk_scaling_lock);
6189 hba->force_pmc = true;
6190 pmc_err = ufshcd_config_pwr_mode(hba, &(hba->pwr_info));
6193 dev_err(hba->dev, "%s: Failed to restore power mode, err = %d\n",
6196 hba->force_pmc = false;
6197 ufshcd_print_pwr_info(hba);
6198 up_write(&hba->clk_scaling_lock);
6199 spin_lock_irqsave(hba->host->host_lock, flags);
6203 /* Fatal errors need reset */
6205 hba->force_reset = false;
6206 spin_unlock_irqrestore(hba->host->host_lock, flags);
6207 err = ufshcd_reset_and_restore(hba);
6209 dev_err(hba->dev, "%s: reset and restore failed with err %d\n",
6212 ufshcd_recover_pm_error(hba);
6213 spin_lock_irqsave(hba->host->host_lock, flags);
6218 if (hba->ufshcd_state == UFSHCD_STATE_RESET)
6219 hba->ufshcd_state = UFSHCD_STATE_OPERATIONAL;
6220 if (hba->saved_err || hba->saved_uic_err)
6221 dev_err_ratelimited(hba->dev, "%s: exit: saved_err 0x%x saved_uic_err 0x%x",
6222 __func__, hba->saved_err, hba->saved_uic_err);
6224 ufshcd_clear_eh_in_progress(hba);
6225 spin_unlock_irqrestore(hba->host->host_lock, flags);
6226 ufshcd_err_handling_unprepare(hba);
6231 * ufshcd_update_uic_error - check and set fatal UIC error flags.
6232 * @hba: per-adapter instance
6235 * IRQ_HANDLED - If interrupt is valid
6236 * IRQ_NONE - If invalid interrupt
6238 static irqreturn_t ufshcd_update_uic_error(struct ufs_hba *hba)
6241 irqreturn_t retval = IRQ_NONE;
6243 /* PHY layer error */
6244 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_PHY_ADAPTER_LAYER);
6245 if ((reg & UIC_PHY_ADAPTER_LAYER_ERROR) &&
6246 (reg & UIC_PHY_ADAPTER_LAYER_ERROR_CODE_MASK)) {
6247 ufshcd_update_evt_hist(hba, UFS_EVT_PA_ERR, reg);
6249 * To know whether this error is fatal or not, DB timeout
6250 * must be checked but this error is handled separately.
6252 if (reg & UIC_PHY_ADAPTER_LAYER_LANE_ERR_MASK)
6253 dev_dbg(hba->dev, "%s: UIC Lane error reported\n",
6256 /* Got a LINERESET indication. */
6257 if (reg & UIC_PHY_ADAPTER_LAYER_GENERIC_ERROR) {
6258 struct uic_command *cmd = NULL;
6260 hba->uic_error |= UFSHCD_UIC_PA_GENERIC_ERROR;
6261 if (hba->uic_async_done && hba->active_uic_cmd)
6262 cmd = hba->active_uic_cmd;
6264 * Ignore the LINERESET during power mode change
6265 * operation via DME_SET command.
6267 if (cmd && (cmd->command == UIC_CMD_DME_SET))
6268 hba->uic_error &= ~UFSHCD_UIC_PA_GENERIC_ERROR;
6270 retval |= IRQ_HANDLED;
6273 /* PA_INIT_ERROR is fatal and needs UIC reset */
6274 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_DATA_LINK_LAYER);
6275 if ((reg & UIC_DATA_LINK_LAYER_ERROR) &&
6276 (reg & UIC_DATA_LINK_LAYER_ERROR_CODE_MASK)) {
6277 ufshcd_update_evt_hist(hba, UFS_EVT_DL_ERR, reg);
6279 if (reg & UIC_DATA_LINK_LAYER_ERROR_PA_INIT)
6280 hba->uic_error |= UFSHCD_UIC_DL_PA_INIT_ERROR;
6281 else if (hba->dev_quirks &
6282 UFS_DEVICE_QUIRK_RECOVERY_FROM_DL_NAC_ERRORS) {
6283 if (reg & UIC_DATA_LINK_LAYER_ERROR_NAC_RECEIVED)
6285 UFSHCD_UIC_DL_NAC_RECEIVED_ERROR;
6286 else if (reg & UIC_DATA_LINK_LAYER_ERROR_TCx_REPLAY_TIMEOUT)
6287 hba->uic_error |= UFSHCD_UIC_DL_TCx_REPLAY_ERROR;
6289 retval |= IRQ_HANDLED;
6292 /* UIC NL/TL/DME errors needs software retry */
6293 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_NETWORK_LAYER);
6294 if ((reg & UIC_NETWORK_LAYER_ERROR) &&
6295 (reg & UIC_NETWORK_LAYER_ERROR_CODE_MASK)) {
6296 ufshcd_update_evt_hist(hba, UFS_EVT_NL_ERR, reg);
6297 hba->uic_error |= UFSHCD_UIC_NL_ERROR;
6298 retval |= IRQ_HANDLED;
6301 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_TRANSPORT_LAYER);
6302 if ((reg & UIC_TRANSPORT_LAYER_ERROR) &&
6303 (reg & UIC_TRANSPORT_LAYER_ERROR_CODE_MASK)) {
6304 ufshcd_update_evt_hist(hba, UFS_EVT_TL_ERR, reg);
6305 hba->uic_error |= UFSHCD_UIC_TL_ERROR;
6306 retval |= IRQ_HANDLED;
6309 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_DME);
6310 if ((reg & UIC_DME_ERROR) &&
6311 (reg & UIC_DME_ERROR_CODE_MASK)) {
6312 ufshcd_update_evt_hist(hba, UFS_EVT_DME_ERR, reg);
6313 hba->uic_error |= UFSHCD_UIC_DME_ERROR;
6314 retval |= IRQ_HANDLED;
6317 dev_dbg(hba->dev, "%s: UIC error flags = 0x%08x\n",
6318 __func__, hba->uic_error);
6323 * ufshcd_check_errors - Check for errors that need s/w attention
6324 * @hba: per-adapter instance
6325 * @intr_status: interrupt status generated by the controller
6328 * IRQ_HANDLED - If interrupt is valid
6329 * IRQ_NONE - If invalid interrupt
6331 static irqreturn_t ufshcd_check_errors(struct ufs_hba *hba, u32 intr_status)
6333 bool queue_eh_work = false;
6334 irqreturn_t retval = IRQ_NONE;
6336 spin_lock(hba->host->host_lock);
6337 hba->errors |= UFSHCD_ERROR_MASK & intr_status;
6339 if (hba->errors & INT_FATAL_ERRORS) {
6340 ufshcd_update_evt_hist(hba, UFS_EVT_FATAL_ERR,
6342 queue_eh_work = true;
6345 if (hba->errors & UIC_ERROR) {
6347 retval = ufshcd_update_uic_error(hba);
6349 queue_eh_work = true;
6352 if (hba->errors & UFSHCD_UIC_HIBERN8_MASK) {
6354 "%s: Auto Hibern8 %s failed - status: 0x%08x, upmcrs: 0x%08x\n",
6355 __func__, (hba->errors & UIC_HIBERNATE_ENTER) ?
6357 hba->errors, ufshcd_get_upmcrs(hba));
6358 ufshcd_update_evt_hist(hba, UFS_EVT_AUTO_HIBERN8_ERR,
6360 ufshcd_set_link_broken(hba);
6361 queue_eh_work = true;
6364 if (queue_eh_work) {
6366 * update the transfer error masks to sticky bits, let's do this
6367 * irrespective of current ufshcd_state.
6369 hba->saved_err |= hba->errors;
6370 hba->saved_uic_err |= hba->uic_error;
6372 /* dump controller state before resetting */
6373 if ((hba->saved_err &
6374 (INT_FATAL_ERRORS | UFSHCD_UIC_HIBERN8_MASK)) ||
6375 (hba->saved_uic_err &&
6376 (hba->saved_uic_err != UFSHCD_UIC_PA_GENERIC_ERROR))) {
6377 dev_err(hba->dev, "%s: saved_err 0x%x saved_uic_err 0x%x\n",
6378 __func__, hba->saved_err,
6379 hba->saved_uic_err);
6380 ufshcd_dump_regs(hba, 0, UFSHCI_REG_SPACE_SIZE,
6382 ufshcd_print_pwr_info(hba);
6384 ufshcd_schedule_eh_work(hba);
6385 retval |= IRQ_HANDLED;
6388 * if (!queue_eh_work) -
6389 * Other errors are either non-fatal where host recovers
6390 * itself without s/w intervention or errors that will be
6391 * handled by the SCSI core layer.
6395 spin_unlock(hba->host->host_lock);
6400 struct ufs_hba *hba;
6401 unsigned long pending;
6405 static bool ufshcd_compl_tm(struct request *req, void *priv, bool reserved)
6407 struct ctm_info *const ci = priv;
6408 struct completion *c;
6410 WARN_ON_ONCE(reserved);
6411 if (test_bit(req->tag, &ci->pending))
6414 c = req->end_io_data;
6421 * ufshcd_tmc_handler - handle task management function completion
6422 * @hba: per adapter instance
6425 * IRQ_HANDLED - If interrupt is valid
6426 * IRQ_NONE - If invalid interrupt
6428 static irqreturn_t ufshcd_tmc_handler(struct ufs_hba *hba)
6430 unsigned long flags;
6431 struct request_queue *q = hba->tmf_queue;
6432 struct ctm_info ci = {
6436 spin_lock_irqsave(hba->host->host_lock, flags);
6437 ci.pending = ufshcd_readl(hba, REG_UTP_TASK_REQ_DOOR_BELL);
6438 blk_mq_tagset_busy_iter(q->tag_set, ufshcd_compl_tm, &ci);
6439 spin_unlock_irqrestore(hba->host->host_lock, flags);
6441 return ci.ncpl ? IRQ_HANDLED : IRQ_NONE;
6445 * ufshcd_sl_intr - Interrupt service routine
6446 * @hba: per adapter instance
6447 * @intr_status: contains interrupts generated by the controller
6450 * IRQ_HANDLED - If interrupt is valid
6451 * IRQ_NONE - If invalid interrupt
6453 static irqreturn_t ufshcd_sl_intr(struct ufs_hba *hba, u32 intr_status)
6455 irqreturn_t retval = IRQ_NONE;
6457 if (intr_status & UFSHCD_UIC_MASK)
6458 retval |= ufshcd_uic_cmd_compl(hba, intr_status);
6460 if (intr_status & UFSHCD_ERROR_MASK || hba->errors)
6461 retval |= ufshcd_check_errors(hba, intr_status);
6463 if (intr_status & UTP_TASK_REQ_COMPL)
6464 retval |= ufshcd_tmc_handler(hba);
6466 if (intr_status & UTP_TRANSFER_REQ_COMPL)
6467 retval |= ufshcd_trc_handler(hba, ufshcd_has_utrlcnr(hba));
6473 * ufshcd_intr - Main interrupt service routine
6475 * @__hba: pointer to adapter instance
6478 * IRQ_HANDLED - If interrupt is valid
6479 * IRQ_NONE - If invalid interrupt
6481 static irqreturn_t ufshcd_intr(int irq, void *__hba)
6483 u32 intr_status, enabled_intr_status = 0;
6484 irqreturn_t retval = IRQ_NONE;
6485 struct ufs_hba *hba = __hba;
6486 int retries = hba->nutrs;
6488 intr_status = ufshcd_readl(hba, REG_INTERRUPT_STATUS);
6489 hba->ufs_stats.last_intr_status = intr_status;
6490 hba->ufs_stats.last_intr_ts = ktime_get();
6493 * There could be max of hba->nutrs reqs in flight and in worst case
6494 * if the reqs get finished 1 by 1 after the interrupt status is
6495 * read, make sure we handle them by checking the interrupt status
6496 * again in a loop until we process all of the reqs before returning.
6498 while (intr_status && retries--) {
6499 enabled_intr_status =
6500 intr_status & ufshcd_readl(hba, REG_INTERRUPT_ENABLE);
6501 ufshcd_writel(hba, intr_status, REG_INTERRUPT_STATUS);
6502 if (enabled_intr_status)
6503 retval |= ufshcd_sl_intr(hba, enabled_intr_status);
6505 intr_status = ufshcd_readl(hba, REG_INTERRUPT_STATUS);
6508 if (enabled_intr_status && retval == IRQ_NONE &&
6509 (!(enabled_intr_status & UTP_TRANSFER_REQ_COMPL) ||
6510 hba->outstanding_reqs) && !ufshcd_eh_in_progress(hba)) {
6511 dev_err(hba->dev, "%s: Unhandled interrupt 0x%08x (0x%08x, 0x%08x)\n",
6514 hba->ufs_stats.last_intr_status,
6515 enabled_intr_status);
6516 ufshcd_dump_regs(hba, 0, UFSHCI_REG_SPACE_SIZE, "host_regs: ");
6522 static int ufshcd_clear_tm_cmd(struct ufs_hba *hba, int tag)
6525 u32 mask = 1 << tag;
6526 unsigned long flags;
6528 if (!test_bit(tag, &hba->outstanding_tasks))
6531 spin_lock_irqsave(hba->host->host_lock, flags);
6532 ufshcd_utmrl_clear(hba, tag);
6533 spin_unlock_irqrestore(hba->host->host_lock, flags);
6535 /* poll for max. 1 sec to clear door bell register by h/w */
6536 err = ufshcd_wait_for_register(hba,
6537 REG_UTP_TASK_REQ_DOOR_BELL,
6538 mask, 0, 1000, 1000);
6543 static int __ufshcd_issue_tm_cmd(struct ufs_hba *hba,
6544 struct utp_task_req_desc *treq, u8 tm_function)
6546 struct request_queue *q = hba->tmf_queue;
6547 struct Scsi_Host *host = hba->host;
6548 DECLARE_COMPLETION_ONSTACK(wait);
6549 struct request *req;
6550 unsigned long flags;
6554 * blk_get_request() is used here only to get a free tag.
6556 req = blk_get_request(q, REQ_OP_DRV_OUT, 0);
6558 return PTR_ERR(req);
6560 req->end_io_data = &wait;
6561 ufshcd_hold(hba, false);
6563 spin_lock_irqsave(host->host_lock, flags);
6564 blk_mq_start_request(req);
6566 task_tag = req->tag;
6567 treq->upiu_req.req_header.dword_0 |= cpu_to_be32(task_tag);
6569 memcpy(hba->utmrdl_base_addr + task_tag, treq, sizeof(*treq));
6570 ufshcd_vops_setup_task_mgmt(hba, task_tag, tm_function);
6572 /* send command to the controller */
6573 __set_bit(task_tag, &hba->outstanding_tasks);
6575 /* Make sure descriptors are ready before ringing the task doorbell */
6578 ufshcd_writel(hba, 1 << task_tag, REG_UTP_TASK_REQ_DOOR_BELL);
6579 /* Make sure that doorbell is committed immediately */
6582 spin_unlock_irqrestore(host->host_lock, flags);
6584 ufshcd_add_tm_upiu_trace(hba, task_tag, UFS_TM_SEND);
6586 /* wait until the task management command is completed */
6587 err = wait_for_completion_io_timeout(&wait,
6588 msecs_to_jiffies(TM_CMD_TIMEOUT));
6591 * Make sure that ufshcd_compl_tm() does not trigger a
6594 req->end_io_data = NULL;
6595 ufshcd_add_tm_upiu_trace(hba, task_tag, UFS_TM_ERR);
6596 dev_err(hba->dev, "%s: task management cmd 0x%.2x timed-out\n",
6597 __func__, tm_function);
6598 if (ufshcd_clear_tm_cmd(hba, task_tag))
6599 dev_WARN(hba->dev, "%s: unable to clear tm cmd (slot %d) after timeout\n",
6600 __func__, task_tag);
6604 memcpy(treq, hba->utmrdl_base_addr + task_tag, sizeof(*treq));
6606 ufshcd_add_tm_upiu_trace(hba, task_tag, UFS_TM_COMP);
6609 spin_lock_irqsave(hba->host->host_lock, flags);
6610 __clear_bit(task_tag, &hba->outstanding_tasks);
6611 spin_unlock_irqrestore(hba->host->host_lock, flags);
6613 ufshcd_release(hba);
6614 blk_put_request(req);
6620 * ufshcd_issue_tm_cmd - issues task management commands to controller
6621 * @hba: per adapter instance
6622 * @lun_id: LUN ID to which TM command is sent
6623 * @task_id: task ID to which the TM command is applicable
6624 * @tm_function: task management function opcode
6625 * @tm_response: task management service response return value
6627 * Returns non-zero value on error, zero on success.
6629 static int ufshcd_issue_tm_cmd(struct ufs_hba *hba, int lun_id, int task_id,
6630 u8 tm_function, u8 *tm_response)
6632 struct utp_task_req_desc treq = { { 0 }, };
6635 /* Configure task request descriptor */
6636 treq.header.dword_0 = cpu_to_le32(UTP_REQ_DESC_INT_CMD);
6637 treq.header.dword_2 = cpu_to_le32(OCS_INVALID_COMMAND_STATUS);
6639 /* Configure task request UPIU */
6640 treq.upiu_req.req_header.dword_0 = cpu_to_be32(lun_id << 8) |
6641 cpu_to_be32(UPIU_TRANSACTION_TASK_REQ << 24);
6642 treq.upiu_req.req_header.dword_1 = cpu_to_be32(tm_function << 16);
6645 * The host shall provide the same value for LUN field in the basic
6646 * header and for Input Parameter.
6648 treq.upiu_req.input_param1 = cpu_to_be32(lun_id);
6649 treq.upiu_req.input_param2 = cpu_to_be32(task_id);
6651 err = __ufshcd_issue_tm_cmd(hba, &treq, tm_function);
6652 if (err == -ETIMEDOUT)
6655 ocs_value = le32_to_cpu(treq.header.dword_2) & MASK_OCS;
6656 if (ocs_value != OCS_SUCCESS)
6657 dev_err(hba->dev, "%s: failed, ocs = 0x%x\n",
6658 __func__, ocs_value);
6659 else if (tm_response)
6660 *tm_response = be32_to_cpu(treq.upiu_rsp.output_param1) &
6661 MASK_TM_SERVICE_RESP;
6666 * ufshcd_issue_devman_upiu_cmd - API for sending "utrd" type requests
6667 * @hba: per-adapter instance
6668 * @req_upiu: upiu request
6669 * @rsp_upiu: upiu reply
6670 * @desc_buff: pointer to descriptor buffer, NULL if NA
6671 * @buff_len: descriptor size, 0 if NA
6672 * @cmd_type: specifies the type (NOP, Query...)
6673 * @desc_op: descriptor operation
6675 * Those type of requests uses UTP Transfer Request Descriptor - utrd.
6676 * Therefore, it "rides" the device management infrastructure: uses its tag and
6677 * tasks work queues.
6679 * Since there is only one available tag for device management commands,
6680 * the caller is expected to hold the hba->dev_cmd.lock mutex.
6682 static int ufshcd_issue_devman_upiu_cmd(struct ufs_hba *hba,
6683 struct utp_upiu_req *req_upiu,
6684 struct utp_upiu_req *rsp_upiu,
6685 u8 *desc_buff, int *buff_len,
6686 enum dev_cmd_type cmd_type,
6687 enum query_opcode desc_op)
6689 struct request_queue *q = hba->cmd_queue;
6690 DECLARE_COMPLETION_ONSTACK(wait);
6691 struct request *req;
6692 struct ufshcd_lrb *lrbp;
6697 down_read(&hba->clk_scaling_lock);
6699 req = blk_get_request(q, REQ_OP_DRV_OUT, 0);
6705 WARN_ONCE(tag < 0, "Invalid tag %d\n", tag);
6707 if (unlikely(test_bit(tag, &hba->outstanding_reqs))) {
6712 lrbp = &hba->lrb[tag];
6715 lrbp->sense_bufflen = 0;
6716 lrbp->sense_buffer = NULL;
6717 lrbp->task_tag = tag;
6719 lrbp->intr_cmd = true;
6720 ufshcd_prepare_lrbp_crypto(NULL, lrbp);
6721 hba->dev_cmd.type = cmd_type;
6723 if (hba->ufs_version <= ufshci_version(1, 1))
6724 lrbp->command_type = UTP_CMD_TYPE_DEV_MANAGE;
6726 lrbp->command_type = UTP_CMD_TYPE_UFS_STORAGE;
6728 /* update the task tag in the request upiu */
6729 req_upiu->header.dword_0 |= cpu_to_be32(tag);
6731 ufshcd_prepare_req_desc_hdr(lrbp, &upiu_flags, DMA_NONE);
6733 /* just copy the upiu request as it is */
6734 memcpy(lrbp->ucd_req_ptr, req_upiu, sizeof(*lrbp->ucd_req_ptr));
6735 if (desc_buff && desc_op == UPIU_QUERY_OPCODE_WRITE_DESC) {
6736 /* The Data Segment Area is optional depending upon the query
6737 * function value. for WRITE DESCRIPTOR, the data segment
6738 * follows right after the tsf.
6740 memcpy(lrbp->ucd_req_ptr + 1, desc_buff, *buff_len);
6744 memset(lrbp->ucd_rsp_ptr, 0, sizeof(struct utp_upiu_rsp));
6746 hba->dev_cmd.complete = &wait;
6748 ufshcd_add_query_upiu_trace(hba, UFS_QUERY_SEND, lrbp->ucd_req_ptr);
6749 /* Make sure descriptors are ready before ringing the doorbell */
6752 ufshcd_send_command(hba, tag);
6754 * ignore the returning value here - ufshcd_check_query_response is
6755 * bound to fail since dev_cmd.query and dev_cmd.type were left empty.
6756 * read the response directly ignoring all errors.
6758 ufshcd_wait_for_dev_cmd(hba, lrbp, QUERY_REQ_TIMEOUT);
6760 /* just copy the upiu response as it is */
6761 memcpy(rsp_upiu, lrbp->ucd_rsp_ptr, sizeof(*rsp_upiu));
6762 if (desc_buff && desc_op == UPIU_QUERY_OPCODE_READ_DESC) {
6763 u8 *descp = (u8 *)lrbp->ucd_rsp_ptr + sizeof(*rsp_upiu);
6764 u16 resp_len = be32_to_cpu(lrbp->ucd_rsp_ptr->header.dword_2) &
6765 MASK_QUERY_DATA_SEG_LEN;
6767 if (*buff_len >= resp_len) {
6768 memcpy(desc_buff, descp, resp_len);
6769 *buff_len = resp_len;
6772 "%s: rsp size %d is bigger than buffer size %d",
6773 __func__, resp_len, *buff_len);
6778 ufshcd_add_query_upiu_trace(hba, err ? UFS_QUERY_ERR : UFS_QUERY_COMP,
6779 (struct utp_upiu_req *)lrbp->ucd_rsp_ptr);
6782 blk_put_request(req);
6784 up_read(&hba->clk_scaling_lock);
6789 * ufshcd_exec_raw_upiu_cmd - API function for sending raw upiu commands
6790 * @hba: per-adapter instance
6791 * @req_upiu: upiu request
6792 * @rsp_upiu: upiu reply - only 8 DW as we do not support scsi commands
6793 * @msgcode: message code, one of UPIU Transaction Codes Initiator to Target
6794 * @desc_buff: pointer to descriptor buffer, NULL if NA
6795 * @buff_len: descriptor size, 0 if NA
6796 * @desc_op: descriptor operation
6798 * Supports UTP Transfer requests (nop and query), and UTP Task
6799 * Management requests.
6800 * It is up to the caller to fill the upiu conent properly, as it will
6801 * be copied without any further input validations.
6803 int ufshcd_exec_raw_upiu_cmd(struct ufs_hba *hba,
6804 struct utp_upiu_req *req_upiu,
6805 struct utp_upiu_req *rsp_upiu,
6807 u8 *desc_buff, int *buff_len,
6808 enum query_opcode desc_op)
6811 enum dev_cmd_type cmd_type = DEV_CMD_TYPE_QUERY;
6812 struct utp_task_req_desc treq = { { 0 }, };
6814 u8 tm_f = be32_to_cpu(req_upiu->header.dword_1) >> 16 & MASK_TM_FUNC;
6817 case UPIU_TRANSACTION_NOP_OUT:
6818 cmd_type = DEV_CMD_TYPE_NOP;
6820 case UPIU_TRANSACTION_QUERY_REQ:
6821 ufshcd_hold(hba, false);
6822 mutex_lock(&hba->dev_cmd.lock);
6823 err = ufshcd_issue_devman_upiu_cmd(hba, req_upiu, rsp_upiu,
6824 desc_buff, buff_len,
6826 mutex_unlock(&hba->dev_cmd.lock);
6827 ufshcd_release(hba);
6830 case UPIU_TRANSACTION_TASK_REQ:
6831 treq.header.dword_0 = cpu_to_le32(UTP_REQ_DESC_INT_CMD);
6832 treq.header.dword_2 = cpu_to_le32(OCS_INVALID_COMMAND_STATUS);
6834 memcpy(&treq.upiu_req, req_upiu, sizeof(*req_upiu));
6836 err = __ufshcd_issue_tm_cmd(hba, &treq, tm_f);
6837 if (err == -ETIMEDOUT)
6840 ocs_value = le32_to_cpu(treq.header.dword_2) & MASK_OCS;
6841 if (ocs_value != OCS_SUCCESS) {
6842 dev_err(hba->dev, "%s: failed, ocs = 0x%x\n", __func__,
6847 memcpy(rsp_upiu, &treq.upiu_rsp, sizeof(*rsp_upiu));
6860 * ufshcd_eh_device_reset_handler - device reset handler registered to
6862 * @cmd: SCSI command pointer
6864 * Returns SUCCESS/FAILED
6866 static int ufshcd_eh_device_reset_handler(struct scsi_cmnd *cmd)
6868 struct Scsi_Host *host;
6869 struct ufs_hba *hba;
6874 host = cmd->device->host;
6875 hba = shost_priv(host);
6877 lun = ufshcd_scsi_to_upiu_lun(cmd->device->lun);
6878 err = ufshcd_issue_tm_cmd(hba, lun, 0, UFS_LOGICAL_RESET, &resp);
6879 if (err || resp != UPIU_TASK_MANAGEMENT_FUNC_COMPL) {
6885 /* clear the commands that were pending for corresponding LUN */
6886 for_each_set_bit(pos, &hba->outstanding_reqs, hba->nutrs) {
6887 if (hba->lrb[pos].lun == lun) {
6888 err = ufshcd_clear_cmd(hba, pos);
6891 __ufshcd_transfer_req_compl(hba, pos);
6896 hba->req_abort_count = 0;
6897 ufshcd_update_evt_hist(hba, UFS_EVT_DEV_RESET, (u32)err);
6901 dev_err(hba->dev, "%s: failed with err %d\n", __func__, err);
6907 static void ufshcd_set_req_abort_skip(struct ufs_hba *hba, unsigned long bitmap)
6909 struct ufshcd_lrb *lrbp;
6912 for_each_set_bit(tag, &bitmap, hba->nutrs) {
6913 lrbp = &hba->lrb[tag];
6914 lrbp->req_abort_skip = true;
6919 * ufshcd_try_to_abort_task - abort a specific task
6920 * @hba: Pointer to adapter instance
6921 * @tag: Task tag/index to be aborted
6923 * Abort the pending command in device by sending UFS_ABORT_TASK task management
6924 * command, and in host controller by clearing the door-bell register. There can
6925 * be race between controller sending the command to the device while abort is
6926 * issued. To avoid that, first issue UFS_QUERY_TASK to check if the command is
6927 * really issued and then try to abort it.
6929 * Returns zero on success, non-zero on failure
6931 static int ufshcd_try_to_abort_task(struct ufs_hba *hba, int tag)
6933 struct ufshcd_lrb *lrbp = &hba->lrb[tag];
6939 for (poll_cnt = 100; poll_cnt; poll_cnt--) {
6940 err = ufshcd_issue_tm_cmd(hba, lrbp->lun, lrbp->task_tag,
6941 UFS_QUERY_TASK, &resp);
6942 if (!err && resp == UPIU_TASK_MANAGEMENT_FUNC_SUCCEEDED) {
6943 /* cmd pending in the device */
6944 dev_err(hba->dev, "%s: cmd pending in the device. tag = %d\n",
6947 } else if (!err && resp == UPIU_TASK_MANAGEMENT_FUNC_COMPL) {
6949 * cmd not pending in the device, check if it is
6952 dev_err(hba->dev, "%s: cmd at tag %d not pending in the device.\n",
6954 reg = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
6955 if (reg & (1 << tag)) {
6956 /* sleep for max. 200us to stabilize */
6957 usleep_range(100, 200);
6960 /* command completed already */
6961 dev_err(hba->dev, "%s: cmd at tag %d successfully cleared from DB.\n",
6966 "%s: no response from device. tag = %d, err %d\n",
6967 __func__, tag, err);
6969 err = resp; /* service response error */
6979 err = ufshcd_issue_tm_cmd(hba, lrbp->lun, lrbp->task_tag,
6980 UFS_ABORT_TASK, &resp);
6981 if (err || resp != UPIU_TASK_MANAGEMENT_FUNC_COMPL) {
6983 err = resp; /* service response error */
6984 dev_err(hba->dev, "%s: issued. tag = %d, err %d\n",
6985 __func__, tag, err);
6990 err = ufshcd_clear_cmd(hba, tag);
6992 dev_err(hba->dev, "%s: Failed clearing cmd at tag %d, err %d\n",
6993 __func__, tag, err);
7000 * ufshcd_abort - scsi host template eh_abort_handler callback
7001 * @cmd: SCSI command pointer
7003 * Returns SUCCESS/FAILED
7005 static int ufshcd_abort(struct scsi_cmnd *cmd)
7007 struct Scsi_Host *host = cmd->device->host;
7008 struct ufs_hba *hba = shost_priv(host);
7009 unsigned int tag = cmd->request->tag;
7010 struct ufshcd_lrb *lrbp = &hba->lrb[tag];
7011 unsigned long flags;
7015 WARN_ONCE(tag < 0, "Invalid tag %d\n", tag);
7017 ufshcd_hold(hba, false);
7018 reg = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
7019 /* If command is already aborted/completed, return SUCCESS */
7020 if (!(test_bit(tag, &hba->outstanding_reqs))) {
7022 "%s: cmd at tag %d already completed, outstanding=0x%lx, doorbell=0x%x\n",
7023 __func__, tag, hba->outstanding_reqs, reg);
7027 /* Print Transfer Request of aborted task */
7028 dev_info(hba->dev, "%s: Device abort task at tag %d\n", __func__, tag);
7031 * Print detailed info about aborted request.
7032 * As more than one request might get aborted at the same time,
7033 * print full information only for the first aborted request in order
7034 * to reduce repeated printouts. For other aborted requests only print
7037 scsi_print_command(cmd);
7038 if (!hba->req_abort_count) {
7039 ufshcd_update_evt_hist(hba, UFS_EVT_ABORT, tag);
7040 ufshcd_print_evt_hist(hba);
7041 ufshcd_print_host_state(hba);
7042 ufshcd_print_pwr_info(hba);
7043 ufshcd_print_trs(hba, 1 << tag, true);
7045 ufshcd_print_trs(hba, 1 << tag, false);
7047 hba->req_abort_count++;
7049 if (!(reg & (1 << tag))) {
7051 "%s: cmd was completed, but without a notifying intr, tag = %d",
7057 * Task abort to the device W-LUN is illegal. When this command
7058 * will fail, due to spec violation, scsi err handling next step
7059 * will be to send LU reset which, again, is a spec violation.
7060 * To avoid these unnecessary/illegal steps, first we clean up
7061 * the lrb taken by this cmd and re-set it in outstanding_reqs,
7062 * then queue the eh_work and bail.
7064 if (lrbp->lun == UFS_UPIU_UFS_DEVICE_WLUN) {
7065 ufshcd_update_evt_hist(hba, UFS_EVT_ABORT, lrbp->lun);
7066 __ufshcd_transfer_req_compl(hba, (1UL << tag));
7067 set_bit(tag, &hba->outstanding_reqs);
7068 spin_lock_irqsave(host->host_lock, flags);
7069 hba->force_reset = true;
7070 ufshcd_schedule_eh_work(hba);
7071 spin_unlock_irqrestore(host->host_lock, flags);
7075 /* Skip task abort in case previous aborts failed and report failure */
7076 if (lrbp->req_abort_skip)
7079 err = ufshcd_try_to_abort_task(hba, tag);
7083 __ufshcd_transfer_req_compl(hba, (1UL << tag));
7087 dev_err(hba->dev, "%s: failed with err %d\n", __func__, err);
7088 ufshcd_set_req_abort_skip(hba, hba->outstanding_reqs);
7093 * This ufshcd_release() corresponds to the original scsi cmd that got
7094 * aborted here (as we won't get any IRQ for it).
7096 ufshcd_release(hba);
7101 * ufshcd_host_reset_and_restore - reset and restore host controller
7102 * @hba: per-adapter instance
7104 * Note that host controller reset may issue DME_RESET to
7105 * local and remote (device) Uni-Pro stack and the attributes
7106 * are reset to default state.
7108 * Returns zero on success, non-zero on failure
7110 static int ufshcd_host_reset_and_restore(struct ufs_hba *hba)
7115 * Stop the host controller and complete the requests
7118 ufshpb_reset_host(hba);
7119 ufshcd_hba_stop(hba);
7120 hba->silence_err_logs = true;
7121 ufshcd_complete_requests(hba);
7122 hba->silence_err_logs = false;
7124 /* scale up clocks to max frequency before full reinitialization */
7125 ufshcd_set_clk_freq(hba, true);
7127 err = ufshcd_hba_enable(hba);
7129 /* Establish the link again and restore the device */
7131 err = ufshcd_probe_hba(hba, false);
7134 dev_err(hba->dev, "%s: Host init failed %d\n", __func__, err);
7135 ufshcd_update_evt_hist(hba, UFS_EVT_HOST_RESET, (u32)err);
7140 * ufshcd_reset_and_restore - reset and re-initialize host/device
7141 * @hba: per-adapter instance
7143 * Reset and recover device, host and re-establish link. This
7144 * is helpful to recover the communication in fatal error conditions.
7146 * Returns zero on success, non-zero on failure
7148 static int ufshcd_reset_and_restore(struct ufs_hba *hba)
7153 unsigned long flags;
7154 int retries = MAX_HOST_RESET_RETRIES;
7157 * This is a fresh start, cache and clear saved error first,
7158 * in case new error generated during reset and restore.
7160 spin_lock_irqsave(hba->host->host_lock, flags);
7161 saved_err = hba->saved_err;
7162 saved_uic_err = hba->saved_uic_err;
7164 hba->saved_uic_err = 0;
7165 spin_unlock_irqrestore(hba->host->host_lock, flags);
7168 /* Reset the attached device */
7169 ufshcd_device_reset(hba);
7171 err = ufshcd_host_reset_and_restore(hba);
7172 } while (err && --retries);
7174 spin_lock_irqsave(hba->host->host_lock, flags);
7176 * Inform scsi mid-layer that we did reset and allow to handle
7177 * Unit Attention properly.
7179 scsi_report_bus_reset(hba->host, 0);
7181 hba->ufshcd_state = UFSHCD_STATE_ERROR;
7182 hba->saved_err |= saved_err;
7183 hba->saved_uic_err |= saved_uic_err;
7185 spin_unlock_irqrestore(hba->host->host_lock, flags);
7191 * ufshcd_eh_host_reset_handler - host reset handler registered to scsi layer
7192 * @cmd: SCSI command pointer
7194 * Returns SUCCESS/FAILED
7196 static int ufshcd_eh_host_reset_handler(struct scsi_cmnd *cmd)
7199 unsigned long flags;
7200 struct ufs_hba *hba;
7202 hba = shost_priv(cmd->device->host);
7204 spin_lock_irqsave(hba->host->host_lock, flags);
7205 hba->force_reset = true;
7206 ufshcd_schedule_eh_work(hba);
7207 dev_err(hba->dev, "%s: reset in progress - 1\n", __func__);
7208 spin_unlock_irqrestore(hba->host->host_lock, flags);
7210 flush_work(&hba->eh_work);
7212 spin_lock_irqsave(hba->host->host_lock, flags);
7213 if (hba->ufshcd_state == UFSHCD_STATE_ERROR)
7215 spin_unlock_irqrestore(hba->host->host_lock, flags);
7221 * ufshcd_get_max_icc_level - calculate the ICC level
7222 * @sup_curr_uA: max. current supported by the regulator
7223 * @start_scan: row at the desc table to start scan from
7224 * @buff: power descriptor buffer
7226 * Returns calculated max ICC level for specific regulator
7228 static u32 ufshcd_get_max_icc_level(int sup_curr_uA, u32 start_scan, char *buff)
7235 for (i = start_scan; i >= 0; i--) {
7236 data = be16_to_cpup((__be16 *)&buff[2 * i]);
7237 unit = (data & ATTR_ICC_LVL_UNIT_MASK) >>
7238 ATTR_ICC_LVL_UNIT_OFFSET;
7239 curr_uA = data & ATTR_ICC_LVL_VALUE_MASK;
7241 case UFSHCD_NANO_AMP:
7242 curr_uA = curr_uA / 1000;
7244 case UFSHCD_MILI_AMP:
7245 curr_uA = curr_uA * 1000;
7248 curr_uA = curr_uA * 1000 * 1000;
7250 case UFSHCD_MICRO_AMP:
7254 if (sup_curr_uA >= curr_uA)
7259 pr_err("%s: Couldn't find valid icc_level = %d", __func__, i);
7266 * ufshcd_find_max_sup_active_icc_level - calculate the max ICC level
7267 * In case regulators are not initialized we'll return 0
7268 * @hba: per-adapter instance
7269 * @desc_buf: power descriptor buffer to extract ICC levels from.
7270 * @len: length of desc_buff
7272 * Returns calculated ICC level
7274 static u32 ufshcd_find_max_sup_active_icc_level(struct ufs_hba *hba,
7275 u8 *desc_buf, int len)
7279 if (!hba->vreg_info.vcc || !hba->vreg_info.vccq ||
7280 !hba->vreg_info.vccq2) {
7282 "%s: Regulator capability was not set, actvIccLevel=%d",
7283 __func__, icc_level);
7287 if (hba->vreg_info.vcc->max_uA)
7288 icc_level = ufshcd_get_max_icc_level(
7289 hba->vreg_info.vcc->max_uA,
7290 POWER_DESC_MAX_ACTV_ICC_LVLS - 1,
7291 &desc_buf[PWR_DESC_ACTIVE_LVLS_VCC_0]);
7293 if (hba->vreg_info.vccq->max_uA)
7294 icc_level = ufshcd_get_max_icc_level(
7295 hba->vreg_info.vccq->max_uA,
7297 &desc_buf[PWR_DESC_ACTIVE_LVLS_VCCQ_0]);
7299 if (hba->vreg_info.vccq2->max_uA)
7300 icc_level = ufshcd_get_max_icc_level(
7301 hba->vreg_info.vccq2->max_uA,
7303 &desc_buf[PWR_DESC_ACTIVE_LVLS_VCCQ2_0]);
7308 static void ufshcd_set_active_icc_lvl(struct ufs_hba *hba)
7311 int buff_len = hba->desc_size[QUERY_DESC_IDN_POWER];
7315 desc_buf = kmalloc(buff_len, GFP_KERNEL);
7319 ret = ufshcd_read_desc_param(hba, QUERY_DESC_IDN_POWER, 0, 0,
7320 desc_buf, buff_len);
7323 "%s: Failed reading power descriptor.len = %d ret = %d",
7324 __func__, buff_len, ret);
7328 icc_level = ufshcd_find_max_sup_active_icc_level(hba, desc_buf,
7330 dev_dbg(hba->dev, "%s: setting icc_level 0x%x", __func__, icc_level);
7332 ret = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_WRITE_ATTR,
7333 QUERY_ATTR_IDN_ACTIVE_ICC_LVL, 0, 0, &icc_level);
7337 "%s: Failed configuring bActiveICCLevel = %d ret = %d",
7338 __func__, icc_level, ret);
7344 static inline void ufshcd_blk_pm_runtime_init(struct scsi_device *sdev)
7346 scsi_autopm_get_device(sdev);
7347 blk_pm_runtime_init(sdev->request_queue, &sdev->sdev_gendev);
7348 if (sdev->rpm_autosuspend)
7349 pm_runtime_set_autosuspend_delay(&sdev->sdev_gendev,
7350 RPM_AUTOSUSPEND_DELAY_MS);
7351 scsi_autopm_put_device(sdev);
7355 * ufshcd_scsi_add_wlus - Adds required W-LUs
7356 * @hba: per-adapter instance
7358 * UFS device specification requires the UFS devices to support 4 well known
7360 * "REPORT_LUNS" (address: 01h)
7361 * "UFS Device" (address: 50h)
7362 * "RPMB" (address: 44h)
7363 * "BOOT" (address: 30h)
7364 * UFS device's power management needs to be controlled by "POWER CONDITION"
7365 * field of SSU (START STOP UNIT) command. But this "power condition" field
7366 * will take effect only when its sent to "UFS device" well known logical unit
7367 * hence we require the scsi_device instance to represent this logical unit in
7368 * order for the UFS host driver to send the SSU command for power management.
7370 * We also require the scsi_device instance for "RPMB" (Replay Protected Memory
7371 * Block) LU so user space process can control this LU. User space may also
7372 * want to have access to BOOT LU.
7374 * This function adds scsi device instances for each of all well known LUs
7375 * (except "REPORT LUNS" LU).
7377 * Returns zero on success (all required W-LUs are added successfully),
7378 * non-zero error value on failure (if failed to add any of the required W-LU).
7380 static int ufshcd_scsi_add_wlus(struct ufs_hba *hba)
7383 struct scsi_device *sdev_boot;
7385 hba->sdev_ufs_device = __scsi_add_device(hba->host, 0, 0,
7386 ufshcd_upiu_wlun_to_scsi_wlun(UFS_UPIU_UFS_DEVICE_WLUN), NULL);
7387 if (IS_ERR(hba->sdev_ufs_device)) {
7388 ret = PTR_ERR(hba->sdev_ufs_device);
7389 hba->sdev_ufs_device = NULL;
7392 scsi_device_put(hba->sdev_ufs_device);
7394 hba->sdev_rpmb = __scsi_add_device(hba->host, 0, 0,
7395 ufshcd_upiu_wlun_to_scsi_wlun(UFS_UPIU_RPMB_WLUN), NULL);
7396 if (IS_ERR(hba->sdev_rpmb)) {
7397 ret = PTR_ERR(hba->sdev_rpmb);
7398 goto remove_sdev_ufs_device;
7400 ufshcd_blk_pm_runtime_init(hba->sdev_rpmb);
7401 scsi_device_put(hba->sdev_rpmb);
7403 sdev_boot = __scsi_add_device(hba->host, 0, 0,
7404 ufshcd_upiu_wlun_to_scsi_wlun(UFS_UPIU_BOOT_WLUN), NULL);
7405 if (IS_ERR(sdev_boot)) {
7406 dev_err(hba->dev, "%s: BOOT WLUN not found\n", __func__);
7408 ufshcd_blk_pm_runtime_init(sdev_boot);
7409 scsi_device_put(sdev_boot);
7413 remove_sdev_ufs_device:
7414 scsi_remove_device(hba->sdev_ufs_device);
7419 static void ufshcd_wb_probe(struct ufs_hba *hba, u8 *desc_buf)
7421 struct ufs_dev_info *dev_info = &hba->dev_info;
7423 u32 d_lu_wb_buf_alloc;
7424 u32 ext_ufs_feature;
7426 if (!ufshcd_is_wb_allowed(hba))
7429 * Probe WB only for UFS-2.2 and UFS-3.1 (and later) devices or
7430 * UFS devices with quirk UFS_DEVICE_QUIRK_SUPPORT_EXTENDED_FEATURES
7433 if (!(dev_info->wspecversion >= 0x310 ||
7434 dev_info->wspecversion == 0x220 ||
7435 (hba->dev_quirks & UFS_DEVICE_QUIRK_SUPPORT_EXTENDED_FEATURES)))
7438 if (hba->desc_size[QUERY_DESC_IDN_DEVICE] <
7439 DEVICE_DESC_PARAM_EXT_UFS_FEATURE_SUP + 4)
7442 ext_ufs_feature = get_unaligned_be32(desc_buf +
7443 DEVICE_DESC_PARAM_EXT_UFS_FEATURE_SUP);
7445 if (!(ext_ufs_feature & UFS_DEV_WRITE_BOOSTER_SUP))
7449 * WB may be supported but not configured while provisioning. The spec
7450 * says, in dedicated wb buffer mode, a max of 1 lun would have wb
7451 * buffer configured.
7453 dev_info->wb_buffer_type = desc_buf[DEVICE_DESC_PARAM_WB_TYPE];
7455 dev_info->b_presrv_uspc_en =
7456 desc_buf[DEVICE_DESC_PARAM_WB_PRESRV_USRSPC_EN];
7458 if (dev_info->wb_buffer_type == WB_BUF_MODE_SHARED) {
7459 if (!get_unaligned_be32(desc_buf +
7460 DEVICE_DESC_PARAM_WB_SHARED_ALLOC_UNITS))
7463 for (lun = 0; lun < UFS_UPIU_MAX_WB_LUN_ID; lun++) {
7464 d_lu_wb_buf_alloc = 0;
7465 ufshcd_read_unit_desc_param(hba,
7467 UNIT_DESC_PARAM_WB_BUF_ALLOC_UNITS,
7468 (u8 *)&d_lu_wb_buf_alloc,
7469 sizeof(d_lu_wb_buf_alloc));
7470 if (d_lu_wb_buf_alloc) {
7471 dev_info->wb_dedicated_lu = lun;
7476 if (!d_lu_wb_buf_alloc)
7482 hba->caps &= ~UFSHCD_CAP_WB_EN;
7485 void ufshcd_fixup_dev_quirks(struct ufs_hba *hba, struct ufs_dev_fix *fixups)
7487 struct ufs_dev_fix *f;
7488 struct ufs_dev_info *dev_info = &hba->dev_info;
7493 for (f = fixups; f->quirk; f++) {
7494 if ((f->wmanufacturerid == dev_info->wmanufacturerid ||
7495 f->wmanufacturerid == UFS_ANY_VENDOR) &&
7496 ((dev_info->model &&
7497 STR_PRFX_EQUAL(f->model, dev_info->model)) ||
7498 !strcmp(f->model, UFS_ANY_MODEL)))
7499 hba->dev_quirks |= f->quirk;
7502 EXPORT_SYMBOL_GPL(ufshcd_fixup_dev_quirks);
7504 static void ufs_fixup_device_setup(struct ufs_hba *hba)
7506 /* fix by general quirk table */
7507 ufshcd_fixup_dev_quirks(hba, ufs_fixups);
7509 /* allow vendors to fix quirks */
7510 ufshcd_vops_fixup_dev_quirks(hba);
7513 static int ufs_get_device_desc(struct ufs_hba *hba)
7517 u8 b_ufs_feature_sup;
7519 struct ufs_dev_info *dev_info = &hba->dev_info;
7521 desc_buf = kmalloc(QUERY_DESC_MAX_SIZE, GFP_KERNEL);
7527 err = ufshcd_read_desc_param(hba, QUERY_DESC_IDN_DEVICE, 0, 0, desc_buf,
7528 hba->desc_size[QUERY_DESC_IDN_DEVICE]);
7530 dev_err(hba->dev, "%s: Failed reading Device Desc. err = %d\n",
7536 * getting vendor (manufacturerID) and Bank Index in big endian
7539 dev_info->wmanufacturerid = desc_buf[DEVICE_DESC_PARAM_MANF_ID] << 8 |
7540 desc_buf[DEVICE_DESC_PARAM_MANF_ID + 1];
7542 /* getting Specification Version in big endian format */
7543 dev_info->wspecversion = desc_buf[DEVICE_DESC_PARAM_SPEC_VER] << 8 |
7544 desc_buf[DEVICE_DESC_PARAM_SPEC_VER + 1];
7545 b_ufs_feature_sup = desc_buf[DEVICE_DESC_PARAM_UFS_FEAT];
7547 model_index = desc_buf[DEVICE_DESC_PARAM_PRDCT_NAME];
7549 if (dev_info->wspecversion >= UFS_DEV_HPB_SUPPORT_VERSION &&
7550 (b_ufs_feature_sup & UFS_DEV_HPB_SUPPORT)) {
7551 bool hpb_en = false;
7553 ufshpb_get_dev_info(hba, desc_buf);
7555 if (!ufshpb_is_legacy(hba))
7556 err = ufshcd_query_flag_retry(hba,
7557 UPIU_QUERY_OPCODE_READ_FLAG,
7558 QUERY_FLAG_IDN_HPB_EN, 0,
7561 if (ufshpb_is_legacy(hba) || (!err && hpb_en))
7562 dev_info->hpb_enabled = true;
7565 err = ufshcd_read_string_desc(hba, model_index,
7566 &dev_info->model, SD_ASCII_STD);
7568 dev_err(hba->dev, "%s: Failed reading Product Name. err = %d\n",
7573 hba->luns_avail = desc_buf[DEVICE_DESC_PARAM_NUM_LU] +
7574 desc_buf[DEVICE_DESC_PARAM_NUM_WLU];
7576 ufs_fixup_device_setup(hba);
7578 ufshcd_wb_probe(hba, desc_buf);
7581 * ufshcd_read_string_desc returns size of the string
7582 * reset the error value
7591 static void ufs_put_device_desc(struct ufs_hba *hba)
7593 struct ufs_dev_info *dev_info = &hba->dev_info;
7595 kfree(dev_info->model);
7596 dev_info->model = NULL;
7600 * ufshcd_tune_pa_tactivate - Tunes PA_TActivate of local UniPro
7601 * @hba: per-adapter instance
7603 * PA_TActivate parameter can be tuned manually if UniPro version is less than
7604 * 1.61. PA_TActivate needs to be greater than or equal to peerM-PHY's
7605 * RX_MIN_ACTIVATETIME_CAPABILITY attribute. This optimal value can help reduce
7606 * the hibern8 exit latency.
7608 * Returns zero on success, non-zero error value on failure.
7610 static int ufshcd_tune_pa_tactivate(struct ufs_hba *hba)
7613 u32 peer_rx_min_activatetime = 0, tuned_pa_tactivate;
7615 ret = ufshcd_dme_peer_get(hba,
7617 RX_MIN_ACTIVATETIME_CAPABILITY,
7618 UIC_ARG_MPHY_RX_GEN_SEL_INDEX(0)),
7619 &peer_rx_min_activatetime);
7623 /* make sure proper unit conversion is applied */
7624 tuned_pa_tactivate =
7625 ((peer_rx_min_activatetime * RX_MIN_ACTIVATETIME_UNIT_US)
7626 / PA_TACTIVATE_TIME_UNIT_US);
7627 ret = ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TACTIVATE),
7628 tuned_pa_tactivate);
7635 * ufshcd_tune_pa_hibern8time - Tunes PA_Hibern8Time of local UniPro
7636 * @hba: per-adapter instance
7638 * PA_Hibern8Time parameter can be tuned manually if UniPro version is less than
7639 * 1.61. PA_Hibern8Time needs to be maximum of local M-PHY's
7640 * TX_HIBERN8TIME_CAPABILITY & peer M-PHY's RX_HIBERN8TIME_CAPABILITY.
7641 * This optimal value can help reduce the hibern8 exit latency.
7643 * Returns zero on success, non-zero error value on failure.
7645 static int ufshcd_tune_pa_hibern8time(struct ufs_hba *hba)
7648 u32 local_tx_hibern8_time_cap = 0, peer_rx_hibern8_time_cap = 0;
7649 u32 max_hibern8_time, tuned_pa_hibern8time;
7651 ret = ufshcd_dme_get(hba,
7652 UIC_ARG_MIB_SEL(TX_HIBERN8TIME_CAPABILITY,
7653 UIC_ARG_MPHY_TX_GEN_SEL_INDEX(0)),
7654 &local_tx_hibern8_time_cap);
7658 ret = ufshcd_dme_peer_get(hba,
7659 UIC_ARG_MIB_SEL(RX_HIBERN8TIME_CAPABILITY,
7660 UIC_ARG_MPHY_RX_GEN_SEL_INDEX(0)),
7661 &peer_rx_hibern8_time_cap);
7665 max_hibern8_time = max(local_tx_hibern8_time_cap,
7666 peer_rx_hibern8_time_cap);
7667 /* make sure proper unit conversion is applied */
7668 tuned_pa_hibern8time = ((max_hibern8_time * HIBERN8TIME_UNIT_US)
7669 / PA_HIBERN8_TIME_UNIT_US);
7670 ret = ufshcd_dme_set(hba, UIC_ARG_MIB(PA_HIBERN8TIME),
7671 tuned_pa_hibern8time);
7677 * ufshcd_quirk_tune_host_pa_tactivate - Ensures that host PA_TACTIVATE is
7678 * less than device PA_TACTIVATE time.
7679 * @hba: per-adapter instance
7681 * Some UFS devices require host PA_TACTIVATE to be lower than device
7682 * PA_TACTIVATE, we need to enable UFS_DEVICE_QUIRK_HOST_PA_TACTIVATE quirk
7685 * Returns zero on success, non-zero error value on failure.
7687 static int ufshcd_quirk_tune_host_pa_tactivate(struct ufs_hba *hba)
7690 u32 granularity, peer_granularity;
7691 u32 pa_tactivate, peer_pa_tactivate;
7692 u32 pa_tactivate_us, peer_pa_tactivate_us;
7693 u8 gran_to_us_table[] = {1, 4, 8, 16, 32, 100};
7695 ret = ufshcd_dme_get(hba, UIC_ARG_MIB(PA_GRANULARITY),
7700 ret = ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_GRANULARITY),
7705 if ((granularity < PA_GRANULARITY_MIN_VAL) ||
7706 (granularity > PA_GRANULARITY_MAX_VAL)) {
7707 dev_err(hba->dev, "%s: invalid host PA_GRANULARITY %d",
7708 __func__, granularity);
7712 if ((peer_granularity < PA_GRANULARITY_MIN_VAL) ||
7713 (peer_granularity > PA_GRANULARITY_MAX_VAL)) {
7714 dev_err(hba->dev, "%s: invalid device PA_GRANULARITY %d",
7715 __func__, peer_granularity);
7719 ret = ufshcd_dme_get(hba, UIC_ARG_MIB(PA_TACTIVATE), &pa_tactivate);
7723 ret = ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_TACTIVATE),
7724 &peer_pa_tactivate);
7728 pa_tactivate_us = pa_tactivate * gran_to_us_table[granularity - 1];
7729 peer_pa_tactivate_us = peer_pa_tactivate *
7730 gran_to_us_table[peer_granularity - 1];
7732 if (pa_tactivate_us > peer_pa_tactivate_us) {
7733 u32 new_peer_pa_tactivate;
7735 new_peer_pa_tactivate = pa_tactivate_us /
7736 gran_to_us_table[peer_granularity - 1];
7737 new_peer_pa_tactivate++;
7738 ret = ufshcd_dme_peer_set(hba, UIC_ARG_MIB(PA_TACTIVATE),
7739 new_peer_pa_tactivate);
7746 static void ufshcd_tune_unipro_params(struct ufs_hba *hba)
7748 if (ufshcd_is_unipro_pa_params_tuning_req(hba)) {
7749 ufshcd_tune_pa_tactivate(hba);
7750 ufshcd_tune_pa_hibern8time(hba);
7753 ufshcd_vops_apply_dev_quirks(hba);
7755 if (hba->dev_quirks & UFS_DEVICE_QUIRK_PA_TACTIVATE)
7756 /* set 1ms timeout for PA_TACTIVATE */
7757 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TACTIVATE), 10);
7759 if (hba->dev_quirks & UFS_DEVICE_QUIRK_HOST_PA_TACTIVATE)
7760 ufshcd_quirk_tune_host_pa_tactivate(hba);
7763 static void ufshcd_clear_dbg_ufs_stats(struct ufs_hba *hba)
7765 hba->ufs_stats.hibern8_exit_cnt = 0;
7766 hba->ufs_stats.last_hibern8_exit_tstamp = ktime_set(0, 0);
7767 hba->req_abort_count = 0;
7770 static int ufshcd_device_geo_params_init(struct ufs_hba *hba)
7776 buff_len = hba->desc_size[QUERY_DESC_IDN_GEOMETRY];
7777 desc_buf = kmalloc(buff_len, GFP_KERNEL);
7783 err = ufshcd_read_desc_param(hba, QUERY_DESC_IDN_GEOMETRY, 0, 0,
7784 desc_buf, buff_len);
7786 dev_err(hba->dev, "%s: Failed reading Geometry Desc. err = %d\n",
7791 if (desc_buf[GEOMETRY_DESC_PARAM_MAX_NUM_LUN] == 1)
7792 hba->dev_info.max_lu_supported = 32;
7793 else if (desc_buf[GEOMETRY_DESC_PARAM_MAX_NUM_LUN] == 0)
7794 hba->dev_info.max_lu_supported = 8;
7796 if (hba->desc_size[QUERY_DESC_IDN_GEOMETRY] >=
7797 GEOMETRY_DESC_PARAM_HPB_MAX_ACTIVE_REGS)
7798 ufshpb_get_geo_info(hba, desc_buf);
7805 static struct ufs_ref_clk ufs_ref_clk_freqs[] = {
7806 {19200000, REF_CLK_FREQ_19_2_MHZ},
7807 {26000000, REF_CLK_FREQ_26_MHZ},
7808 {38400000, REF_CLK_FREQ_38_4_MHZ},
7809 {52000000, REF_CLK_FREQ_52_MHZ},
7810 {0, REF_CLK_FREQ_INVAL},
7813 static enum ufs_ref_clk_freq
7814 ufs_get_bref_clk_from_hz(unsigned long freq)
7818 for (i = 0; ufs_ref_clk_freqs[i].freq_hz; i++)
7819 if (ufs_ref_clk_freqs[i].freq_hz == freq)
7820 return ufs_ref_clk_freqs[i].val;
7822 return REF_CLK_FREQ_INVAL;
7825 void ufshcd_parse_dev_ref_clk_freq(struct ufs_hba *hba, struct clk *refclk)
7829 freq = clk_get_rate(refclk);
7831 hba->dev_ref_clk_freq =
7832 ufs_get_bref_clk_from_hz(freq);
7834 if (hba->dev_ref_clk_freq == REF_CLK_FREQ_INVAL)
7836 "invalid ref_clk setting = %ld\n", freq);
7839 static int ufshcd_set_dev_ref_clk(struct ufs_hba *hba)
7843 u32 freq = hba->dev_ref_clk_freq;
7845 err = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
7846 QUERY_ATTR_IDN_REF_CLK_FREQ, 0, 0, &ref_clk);
7849 dev_err(hba->dev, "failed reading bRefClkFreq. err = %d\n",
7854 if (ref_clk == freq)
7855 goto out; /* nothing to update */
7857 err = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_WRITE_ATTR,
7858 QUERY_ATTR_IDN_REF_CLK_FREQ, 0, 0, &freq);
7861 dev_err(hba->dev, "bRefClkFreq setting to %lu Hz failed\n",
7862 ufs_ref_clk_freqs[freq].freq_hz);
7866 dev_dbg(hba->dev, "bRefClkFreq setting to %lu Hz succeeded\n",
7867 ufs_ref_clk_freqs[freq].freq_hz);
7873 static int ufshcd_device_params_init(struct ufs_hba *hba)
7878 /* Init device descriptor sizes */
7879 for (i = 0; i < QUERY_DESC_IDN_MAX; i++)
7880 hba->desc_size[i] = QUERY_DESC_MAX_SIZE;
7882 /* Init UFS geometry descriptor related parameters */
7883 ret = ufshcd_device_geo_params_init(hba);
7887 /* Check and apply UFS device quirks */
7888 ret = ufs_get_device_desc(hba);
7890 dev_err(hba->dev, "%s: Failed getting device info. err = %d\n",
7895 ufshcd_get_ref_clk_gating_wait(hba);
7897 if (!ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_READ_FLAG,
7898 QUERY_FLAG_IDN_PWR_ON_WPE, 0, &flag))
7899 hba->dev_info.f_power_on_wp_en = flag;
7901 /* Probe maximum power mode co-supported by both UFS host and device */
7902 if (ufshcd_get_max_pwr_mode(hba))
7904 "%s: Failed getting max supported power mode\n",
7911 * ufshcd_add_lus - probe and add UFS logical units
7912 * @hba: per-adapter instance
7914 static int ufshcd_add_lus(struct ufs_hba *hba)
7918 /* Add required well known logical units to scsi mid layer */
7919 ret = ufshcd_scsi_add_wlus(hba);
7923 ufshcd_clear_ua_wluns(hba);
7925 /* Initialize devfreq after UFS device is detected */
7926 if (ufshcd_is_clkscaling_supported(hba)) {
7927 memcpy(&hba->clk_scaling.saved_pwr_info.info,
7929 sizeof(struct ufs_pa_layer_attr));
7930 hba->clk_scaling.saved_pwr_info.is_valid = true;
7931 hba->clk_scaling.is_allowed = true;
7933 ret = ufshcd_devfreq_init(hba);
7937 hba->clk_scaling.is_enabled = true;
7938 ufshcd_init_clk_scaling_sysfs(hba);
7943 scsi_scan_host(hba->host);
7944 pm_runtime_put_sync(hba->dev);
7951 ufshcd_send_request_sense(struct ufs_hba *hba, struct scsi_device *sdp);
7953 static int ufshcd_clear_ua_wlun(struct ufs_hba *hba, u8 wlun)
7955 struct scsi_device *sdp;
7956 unsigned long flags;
7959 spin_lock_irqsave(hba->host->host_lock, flags);
7960 if (wlun == UFS_UPIU_UFS_DEVICE_WLUN)
7961 sdp = hba->sdev_ufs_device;
7962 else if (wlun == UFS_UPIU_RPMB_WLUN)
7963 sdp = hba->sdev_rpmb;
7967 ret = scsi_device_get(sdp);
7968 if (!ret && !scsi_device_online(sdp)) {
7970 scsi_device_put(sdp);
7975 spin_unlock_irqrestore(hba->host->host_lock, flags);
7979 ret = ufshcd_send_request_sense(hba, sdp);
7980 scsi_device_put(sdp);
7983 dev_err(hba->dev, "%s: UAC clear LU=%x ret = %d\n",
7984 __func__, wlun, ret);
7988 static int ufshcd_clear_ua_wluns(struct ufs_hba *hba)
7992 if (!hba->wlun_dev_clr_ua)
7995 ret = ufshcd_clear_ua_wlun(hba, UFS_UPIU_UFS_DEVICE_WLUN);
7997 ret = ufshcd_clear_ua_wlun(hba, UFS_UPIU_RPMB_WLUN);
7999 hba->wlun_dev_clr_ua = false;
8002 dev_err(hba->dev, "%s: Failed to clear UAC WLUNS ret = %d\n",
8008 * ufshcd_probe_hba - probe hba to detect device and initialize it
8009 * @hba: per-adapter instance
8010 * @init_dev_params: whether or not to call ufshcd_device_params_init().
8012 * Execute link-startup and verify device initialization
8014 static int ufshcd_probe_hba(struct ufs_hba *hba, bool init_dev_params)
8017 unsigned long flags;
8018 ktime_t start = ktime_get();
8020 hba->ufshcd_state = UFSHCD_STATE_RESET;
8022 ret = ufshcd_link_startup(hba);
8026 /* Debug counters initialization */
8027 ufshcd_clear_dbg_ufs_stats(hba);
8029 /* UniPro link is active now */
8030 ufshcd_set_link_active(hba);
8032 /* Verify device initialization by sending NOP OUT UPIU */
8033 ret = ufshcd_verify_dev_init(hba);
8037 /* Initiate UFS initialization, and waiting until completion */
8038 ret = ufshcd_complete_dev_init(hba);
8043 * Initialize UFS device parameters used by driver, these
8044 * parameters are associated with UFS descriptors.
8046 if (init_dev_params) {
8047 ret = ufshcd_device_params_init(hba);
8052 ufshcd_tune_unipro_params(hba);
8054 /* UFS device is also active now */
8055 ufshcd_set_ufs_dev_active(hba);
8056 ufshcd_force_reset_auto_bkops(hba);
8057 hba->wlun_dev_clr_ua = true;
8058 hba->wlun_rpmb_clr_ua = true;
8060 /* Gear up to HS gear if supported */
8061 if (hba->max_pwr_info.is_valid) {
8063 * Set the right value to bRefClkFreq before attempting to
8064 * switch to HS gears.
8066 if (hba->dev_ref_clk_freq != REF_CLK_FREQ_INVAL)
8067 ufshcd_set_dev_ref_clk(hba);
8068 ret = ufshcd_config_pwr_mode(hba, &hba->max_pwr_info.info);
8070 dev_err(hba->dev, "%s: Failed setting power mode, err = %d\n",
8074 ufshcd_print_pwr_info(hba);
8078 * bActiveICCLevel is volatile for UFS device (as per latest v2.1 spec)
8079 * and for removable UFS card as well, hence always set the parameter.
8080 * Note: Error handler may issue the device reset hence resetting
8081 * bActiveICCLevel as well so it is always safe to set this here.
8083 ufshcd_set_active_icc_lvl(hba);
8085 ufshcd_wb_config(hba);
8086 if (hba->ee_usr_mask)
8087 ufshcd_write_ee_control(hba);
8088 /* Enable Auto-Hibernate if configured */
8089 ufshcd_auto_hibern8_enable(hba);
8093 spin_lock_irqsave(hba->host->host_lock, flags);
8095 hba->ufshcd_state = UFSHCD_STATE_ERROR;
8096 else if (hba->ufshcd_state == UFSHCD_STATE_RESET)
8097 hba->ufshcd_state = UFSHCD_STATE_OPERATIONAL;
8098 spin_unlock_irqrestore(hba->host->host_lock, flags);
8100 trace_ufshcd_init(dev_name(hba->dev), ret,
8101 ktime_to_us(ktime_sub(ktime_get(), start)),
8102 hba->curr_dev_pwr_mode, hba->uic_link_state);
8107 * ufshcd_async_scan - asynchronous execution for probing hba
8108 * @data: data pointer to pass to this function
8109 * @cookie: cookie data
8111 static void ufshcd_async_scan(void *data, async_cookie_t cookie)
8113 struct ufs_hba *hba = (struct ufs_hba *)data;
8116 down(&hba->host_sem);
8117 /* Initialize hba, detect and initialize UFS device */
8118 ret = ufshcd_probe_hba(hba, true);
8123 /* Probe and add UFS logical units */
8124 ret = ufshcd_add_lus(hba);
8127 * If we failed to initialize the device or the device is not
8128 * present, turn off the power/clocks etc.
8131 pm_runtime_put_sync(hba->dev);
8132 ufshcd_hba_exit(hba);
8136 static const struct attribute_group *ufshcd_driver_groups[] = {
8137 &ufs_sysfs_unit_descriptor_group,
8138 &ufs_sysfs_lun_attributes_group,
8139 #ifdef CONFIG_SCSI_UFS_HPB
8140 &ufs_sysfs_hpb_stat_group,
8141 &ufs_sysfs_hpb_param_group,
8146 static struct ufs_hba_variant_params ufs_hba_vps = {
8147 .hba_enable_delay_us = 1000,
8148 .wb_flush_threshold = UFS_WB_BUF_REMAIN_PERCENT(40),
8149 .devfreq_profile.polling_ms = 100,
8150 .devfreq_profile.target = ufshcd_devfreq_target,
8151 .devfreq_profile.get_dev_status = ufshcd_devfreq_get_dev_status,
8152 .ondemand_data.upthreshold = 70,
8153 .ondemand_data.downdifferential = 5,
8156 static struct scsi_host_template ufshcd_driver_template = {
8157 .module = THIS_MODULE,
8159 .proc_name = UFSHCD,
8160 .queuecommand = ufshcd_queuecommand,
8161 .slave_alloc = ufshcd_slave_alloc,
8162 .slave_configure = ufshcd_slave_configure,
8163 .slave_destroy = ufshcd_slave_destroy,
8164 .change_queue_depth = ufshcd_change_queue_depth,
8165 .eh_abort_handler = ufshcd_abort,
8166 .eh_device_reset_handler = ufshcd_eh_device_reset_handler,
8167 .eh_host_reset_handler = ufshcd_eh_host_reset_handler,
8169 .sg_tablesize = SG_ALL,
8170 .cmd_per_lun = UFSHCD_CMD_PER_LUN,
8171 .can_queue = UFSHCD_CAN_QUEUE,
8172 .max_segment_size = PRDT_DATA_BYTE_COUNT_MAX,
8173 .max_host_blocked = 1,
8174 .track_queue_depth = 1,
8175 .sdev_groups = ufshcd_driver_groups,
8176 .dma_boundary = PAGE_SIZE - 1,
8177 .rpm_autosuspend_delay = RPM_AUTOSUSPEND_DELAY_MS,
8180 static int ufshcd_config_vreg_load(struct device *dev, struct ufs_vreg *vreg,
8189 * "set_load" operation shall be required on those regulators
8190 * which specifically configured current limitation. Otherwise
8191 * zero max_uA may cause unexpected behavior when regulator is
8192 * enabled or set as high power mode.
8197 ret = regulator_set_load(vreg->reg, ua);
8199 dev_err(dev, "%s: %s set load (ua=%d) failed, err=%d\n",
8200 __func__, vreg->name, ua, ret);
8206 static inline int ufshcd_config_vreg_lpm(struct ufs_hba *hba,
8207 struct ufs_vreg *vreg)
8209 return ufshcd_config_vreg_load(hba->dev, vreg, UFS_VREG_LPM_LOAD_UA);
8212 static inline int ufshcd_config_vreg_hpm(struct ufs_hba *hba,
8213 struct ufs_vreg *vreg)
8218 return ufshcd_config_vreg_load(hba->dev, vreg, vreg->max_uA);
8221 static int ufshcd_config_vreg(struct device *dev,
8222 struct ufs_vreg *vreg, bool on)
8225 struct regulator *reg;
8227 int min_uV, uA_load;
8234 if (regulator_count_voltages(reg) > 0) {
8235 uA_load = on ? vreg->max_uA : 0;
8236 ret = ufshcd_config_vreg_load(dev, vreg, uA_load);
8240 if (vreg->min_uV && vreg->max_uV) {
8241 min_uV = on ? vreg->min_uV : 0;
8242 ret = regulator_set_voltage(reg, min_uV, vreg->max_uV);
8245 "%s: %s set voltage failed, err=%d\n",
8246 __func__, name, ret);
8253 static int ufshcd_enable_vreg(struct device *dev, struct ufs_vreg *vreg)
8257 if (!vreg || vreg->enabled)
8260 ret = ufshcd_config_vreg(dev, vreg, true);
8262 ret = regulator_enable(vreg->reg);
8265 vreg->enabled = true;
8267 dev_err(dev, "%s: %s enable failed, err=%d\n",
8268 __func__, vreg->name, ret);
8273 static int ufshcd_disable_vreg(struct device *dev, struct ufs_vreg *vreg)
8277 if (!vreg || !vreg->enabled || vreg->always_on)
8280 ret = regulator_disable(vreg->reg);
8283 /* ignore errors on applying disable config */
8284 ufshcd_config_vreg(dev, vreg, false);
8285 vreg->enabled = false;
8287 dev_err(dev, "%s: %s disable failed, err=%d\n",
8288 __func__, vreg->name, ret);
8294 static int ufshcd_setup_vreg(struct ufs_hba *hba, bool on)
8297 struct device *dev = hba->dev;
8298 struct ufs_vreg_info *info = &hba->vreg_info;
8300 ret = ufshcd_toggle_vreg(dev, info->vcc, on);
8304 ret = ufshcd_toggle_vreg(dev, info->vccq, on);
8308 ret = ufshcd_toggle_vreg(dev, info->vccq2, on);
8312 ufshcd_toggle_vreg(dev, info->vccq2, false);
8313 ufshcd_toggle_vreg(dev, info->vccq, false);
8314 ufshcd_toggle_vreg(dev, info->vcc, false);
8319 static int ufshcd_setup_hba_vreg(struct ufs_hba *hba, bool on)
8321 struct ufs_vreg_info *info = &hba->vreg_info;
8323 return ufshcd_toggle_vreg(hba->dev, info->vdd_hba, on);
8326 static int ufshcd_get_vreg(struct device *dev, struct ufs_vreg *vreg)
8333 vreg->reg = devm_regulator_get(dev, vreg->name);
8334 if (IS_ERR(vreg->reg)) {
8335 ret = PTR_ERR(vreg->reg);
8336 dev_err(dev, "%s: %s get failed, err=%d\n",
8337 __func__, vreg->name, ret);
8343 static int ufshcd_init_vreg(struct ufs_hba *hba)
8346 struct device *dev = hba->dev;
8347 struct ufs_vreg_info *info = &hba->vreg_info;
8349 ret = ufshcd_get_vreg(dev, info->vcc);
8353 ret = ufshcd_get_vreg(dev, info->vccq);
8355 ret = ufshcd_get_vreg(dev, info->vccq2);
8360 static int ufshcd_init_hba_vreg(struct ufs_hba *hba)
8362 struct ufs_vreg_info *info = &hba->vreg_info;
8365 return ufshcd_get_vreg(hba->dev, info->vdd_hba);
8370 static int ufshcd_setup_clocks(struct ufs_hba *hba, bool on)
8373 struct ufs_clk_info *clki;
8374 struct list_head *head = &hba->clk_list_head;
8375 unsigned long flags;
8376 ktime_t start = ktime_get();
8377 bool clk_state_changed = false;
8379 if (list_empty(head))
8382 ret = ufshcd_vops_setup_clocks(hba, on, PRE_CHANGE);
8386 list_for_each_entry(clki, head, list) {
8387 if (!IS_ERR_OR_NULL(clki->clk)) {
8389 * Don't disable clocks which are needed
8390 * to keep the link active.
8392 if (ufshcd_is_link_active(hba) &&
8393 clki->keep_link_active)
8396 clk_state_changed = on ^ clki->enabled;
8397 if (on && !clki->enabled) {
8398 ret = clk_prepare_enable(clki->clk);
8400 dev_err(hba->dev, "%s: %s prepare enable failed, %d\n",
8401 __func__, clki->name, ret);
8404 } else if (!on && clki->enabled) {
8405 clk_disable_unprepare(clki->clk);
8408 dev_dbg(hba->dev, "%s: clk: %s %sabled\n", __func__,
8409 clki->name, on ? "en" : "dis");
8413 ret = ufshcd_vops_setup_clocks(hba, on, POST_CHANGE);
8419 list_for_each_entry(clki, head, list) {
8420 if (!IS_ERR_OR_NULL(clki->clk) && clki->enabled)
8421 clk_disable_unprepare(clki->clk);
8423 } else if (!ret && on) {
8424 spin_lock_irqsave(hba->host->host_lock, flags);
8425 hba->clk_gating.state = CLKS_ON;
8426 trace_ufshcd_clk_gating(dev_name(hba->dev),
8427 hba->clk_gating.state);
8428 spin_unlock_irqrestore(hba->host->host_lock, flags);
8431 if (clk_state_changed)
8432 trace_ufshcd_profile_clk_gating(dev_name(hba->dev),
8433 (on ? "on" : "off"),
8434 ktime_to_us(ktime_sub(ktime_get(), start)), ret);
8438 static int ufshcd_init_clocks(struct ufs_hba *hba)
8441 struct ufs_clk_info *clki;
8442 struct device *dev = hba->dev;
8443 struct list_head *head = &hba->clk_list_head;
8445 if (list_empty(head))
8448 list_for_each_entry(clki, head, list) {
8452 clki->clk = devm_clk_get(dev, clki->name);
8453 if (IS_ERR(clki->clk)) {
8454 ret = PTR_ERR(clki->clk);
8455 dev_err(dev, "%s: %s clk get failed, %d\n",
8456 __func__, clki->name, ret);
8461 * Parse device ref clk freq as per device tree "ref_clk".
8462 * Default dev_ref_clk_freq is set to REF_CLK_FREQ_INVAL
8463 * in ufshcd_alloc_host().
8465 if (!strcmp(clki->name, "ref_clk"))
8466 ufshcd_parse_dev_ref_clk_freq(hba, clki->clk);
8468 if (clki->max_freq) {
8469 ret = clk_set_rate(clki->clk, clki->max_freq);
8471 dev_err(hba->dev, "%s: %s clk set rate(%dHz) failed, %d\n",
8472 __func__, clki->name,
8473 clki->max_freq, ret);
8476 clki->curr_freq = clki->max_freq;
8478 dev_dbg(dev, "%s: clk: %s, rate: %lu\n", __func__,
8479 clki->name, clk_get_rate(clki->clk));
8485 static int ufshcd_variant_hba_init(struct ufs_hba *hba)
8492 err = ufshcd_vops_init(hba);
8494 dev_err(hba->dev, "%s: variant %s init failed err %d\n",
8495 __func__, ufshcd_get_var_name(hba), err);
8500 static void ufshcd_variant_hba_exit(struct ufs_hba *hba)
8505 ufshcd_vops_exit(hba);
8508 static int ufshcd_hba_init(struct ufs_hba *hba)
8513 * Handle host controller power separately from the UFS device power
8514 * rails as it will help controlling the UFS host controller power
8515 * collapse easily which is different than UFS device power collapse.
8516 * Also, enable the host controller power before we go ahead with rest
8517 * of the initialization here.
8519 err = ufshcd_init_hba_vreg(hba);
8523 err = ufshcd_setup_hba_vreg(hba, true);
8527 err = ufshcd_init_clocks(hba);
8529 goto out_disable_hba_vreg;
8531 err = ufshcd_setup_clocks(hba, true);
8533 goto out_disable_hba_vreg;
8535 err = ufshcd_init_vreg(hba);
8537 goto out_disable_clks;
8539 err = ufshcd_setup_vreg(hba, true);
8541 goto out_disable_clks;
8543 err = ufshcd_variant_hba_init(hba);
8545 goto out_disable_vreg;
8547 ufs_debugfs_hba_init(hba);
8549 hba->is_powered = true;
8553 ufshcd_setup_vreg(hba, false);
8555 ufshcd_setup_clocks(hba, false);
8556 out_disable_hba_vreg:
8557 ufshcd_setup_hba_vreg(hba, false);
8562 static void ufshcd_hba_exit(struct ufs_hba *hba)
8564 if (hba->is_powered) {
8565 ufshcd_exit_clk_scaling(hba);
8566 ufshcd_exit_clk_gating(hba);
8568 destroy_workqueue(hba->eh_wq);
8569 ufs_debugfs_hba_exit(hba);
8570 ufshcd_variant_hba_exit(hba);
8571 ufshcd_setup_vreg(hba, false);
8572 ufshcd_setup_clocks(hba, false);
8573 ufshcd_setup_hba_vreg(hba, false);
8574 hba->is_powered = false;
8575 ufs_put_device_desc(hba);
8580 ufshcd_send_request_sense(struct ufs_hba *hba, struct scsi_device *sdp)
8582 unsigned char cmd[6] = {REQUEST_SENSE,
8591 buffer = kzalloc(UFS_SENSE_SIZE, GFP_KERNEL);
8597 ret = scsi_execute(sdp, cmd, DMA_FROM_DEVICE, buffer,
8598 UFS_SENSE_SIZE, NULL, NULL,
8599 msecs_to_jiffies(1000), 3, 0, RQF_PM, NULL);
8601 pr_err("%s: failed with err %d\n", __func__, ret);
8609 * ufshcd_set_dev_pwr_mode - sends START STOP UNIT command to set device
8611 * @hba: per adapter instance
8612 * @pwr_mode: device power mode to set
8614 * Returns 0 if requested power mode is set successfully
8615 * Returns non-zero if failed to set the requested power mode
8617 static int ufshcd_set_dev_pwr_mode(struct ufs_hba *hba,
8618 enum ufs_dev_pwr_mode pwr_mode)
8620 unsigned char cmd[6] = { START_STOP };
8621 struct scsi_sense_hdr sshdr;
8622 struct scsi_device *sdp;
8623 unsigned long flags;
8626 spin_lock_irqsave(hba->host->host_lock, flags);
8627 sdp = hba->sdev_ufs_device;
8629 ret = scsi_device_get(sdp);
8630 if (!ret && !scsi_device_online(sdp)) {
8632 scsi_device_put(sdp);
8637 spin_unlock_irqrestore(hba->host->host_lock, flags);
8643 * If scsi commands fail, the scsi mid-layer schedules scsi error-
8644 * handling, which would wait for host to be resumed. Since we know
8645 * we are functional while we are here, skip host resume in error
8648 hba->host->eh_noresume = 1;
8649 if (hba->wlun_dev_clr_ua)
8650 ufshcd_clear_ua_wlun(hba, UFS_UPIU_UFS_DEVICE_WLUN);
8652 cmd[4] = pwr_mode << 4;
8655 * Current function would be generally called from the power management
8656 * callbacks hence set the RQF_PM flag so that it doesn't resume the
8657 * already suspended childs.
8659 ret = scsi_execute(sdp, cmd, DMA_NONE, NULL, 0, NULL, &sshdr,
8660 START_STOP_TIMEOUT, 0, 0, RQF_PM, NULL);
8662 sdev_printk(KERN_WARNING, sdp,
8663 "START_STOP failed for power mode: %d, result %x\n",
8665 if (ret > 0 && scsi_sense_valid(&sshdr))
8666 scsi_print_sense_hdr(sdp, NULL, &sshdr);
8670 hba->curr_dev_pwr_mode = pwr_mode;
8672 scsi_device_put(sdp);
8673 hba->host->eh_noresume = 0;
8677 static int ufshcd_link_state_transition(struct ufs_hba *hba,
8678 enum uic_link_state req_link_state,
8679 int check_for_bkops)
8683 if (req_link_state == hba->uic_link_state)
8686 if (req_link_state == UIC_LINK_HIBERN8_STATE) {
8687 ret = ufshcd_uic_hibern8_enter(hba);
8689 ufshcd_set_link_hibern8(hba);
8691 dev_err(hba->dev, "%s: hibern8 enter failed %d\n",
8697 * If autobkops is enabled, link can't be turned off because
8698 * turning off the link would also turn off the device, except in the
8699 * case of DeepSleep where the device is expected to remain powered.
8701 else if ((req_link_state == UIC_LINK_OFF_STATE) &&
8702 (!check_for_bkops || !hba->auto_bkops_enabled)) {
8704 * Let's make sure that link is in low power mode, we are doing
8705 * this currently by putting the link in Hibern8. Otherway to
8706 * put the link in low power mode is to send the DME end point
8707 * to device and then send the DME reset command to local
8708 * unipro. But putting the link in hibern8 is much faster.
8710 * Note also that putting the link in Hibern8 is a requirement
8711 * for entering DeepSleep.
8713 ret = ufshcd_uic_hibern8_enter(hba);
8715 dev_err(hba->dev, "%s: hibern8 enter failed %d\n",
8720 * Change controller state to "reset state" which
8721 * should also put the link in off/reset state
8723 ufshcd_hba_stop(hba);
8725 * TODO: Check if we need any delay to make sure that
8726 * controller is reset
8728 ufshcd_set_link_off(hba);
8735 static void ufshcd_vreg_set_lpm(struct ufs_hba *hba)
8737 bool vcc_off = false;
8740 * It seems some UFS devices may keep drawing more than sleep current
8741 * (atleast for 500us) from UFS rails (especially from VCCQ rail).
8742 * To avoid this situation, add 2ms delay before putting these UFS
8743 * rails in LPM mode.
8745 if (!ufshcd_is_link_active(hba) &&
8746 hba->dev_quirks & UFS_DEVICE_QUIRK_DELAY_BEFORE_LPM)
8747 usleep_range(2000, 2100);
8750 * If UFS device is either in UFS_Sleep turn off VCC rail to save some
8753 * If UFS device and link is in OFF state, all power supplies (VCC,
8754 * VCCQ, VCCQ2) can be turned off if power on write protect is not
8755 * required. If UFS link is inactive (Hibern8 or OFF state) and device
8756 * is in sleep state, put VCCQ & VCCQ2 rails in LPM mode.
8758 * Ignore the error returned by ufshcd_toggle_vreg() as device is anyway
8759 * in low power state which would save some power.
8761 * If Write Booster is enabled and the device needs to flush the WB
8762 * buffer OR if bkops status is urgent for WB, keep Vcc on.
8764 if (ufshcd_is_ufs_dev_poweroff(hba) && ufshcd_is_link_off(hba) &&
8765 !hba->dev_info.is_lu_power_on_wp) {
8766 ufshcd_setup_vreg(hba, false);
8768 } else if (!ufshcd_is_ufs_dev_active(hba)) {
8769 ufshcd_toggle_vreg(hba->dev, hba->vreg_info.vcc, false);
8771 if (ufshcd_is_link_hibern8(hba) || ufshcd_is_link_off(hba)) {
8772 ufshcd_config_vreg_lpm(hba, hba->vreg_info.vccq);
8773 ufshcd_config_vreg_lpm(hba, hba->vreg_info.vccq2);
8778 * Some UFS devices require delay after VCC power rail is turned-off.
8780 if (vcc_off && hba->vreg_info.vcc &&
8781 hba->dev_quirks & UFS_DEVICE_QUIRK_DELAY_AFTER_LPM)
8782 usleep_range(5000, 5100);
8786 static int ufshcd_vreg_set_hpm(struct ufs_hba *hba)
8790 if (ufshcd_is_ufs_dev_poweroff(hba) && ufshcd_is_link_off(hba) &&
8791 !hba->dev_info.is_lu_power_on_wp) {
8792 ret = ufshcd_setup_vreg(hba, true);
8793 } else if (!ufshcd_is_ufs_dev_active(hba)) {
8794 if (!ufshcd_is_link_active(hba)) {
8795 ret = ufshcd_config_vreg_hpm(hba, hba->vreg_info.vccq);
8798 ret = ufshcd_config_vreg_hpm(hba, hba->vreg_info.vccq2);
8802 ret = ufshcd_toggle_vreg(hba->dev, hba->vreg_info.vcc, true);
8807 ufshcd_config_vreg_lpm(hba, hba->vreg_info.vccq);
8809 ufshcd_toggle_vreg(hba->dev, hba->vreg_info.vcc, false);
8813 #endif /* CONFIG_PM */
8815 static void ufshcd_hba_vreg_set_lpm(struct ufs_hba *hba)
8817 if (ufshcd_is_link_off(hba) || ufshcd_can_aggressive_pc(hba))
8818 ufshcd_setup_hba_vreg(hba, false);
8821 static void ufshcd_hba_vreg_set_hpm(struct ufs_hba *hba)
8823 if (ufshcd_is_link_off(hba) || ufshcd_can_aggressive_pc(hba))
8824 ufshcd_setup_hba_vreg(hba, true);
8827 static int __ufshcd_wl_suspend(struct ufs_hba *hba, enum ufs_pm_op pm_op)
8830 int check_for_bkops;
8831 enum ufs_pm_level pm_lvl;
8832 enum ufs_dev_pwr_mode req_dev_pwr_mode;
8833 enum uic_link_state req_link_state;
8835 hba->pm_op_in_progress = true;
8836 if (pm_op != UFS_SHUTDOWN_PM) {
8837 pm_lvl = pm_op == UFS_RUNTIME_PM ?
8838 hba->rpm_lvl : hba->spm_lvl;
8839 req_dev_pwr_mode = ufs_get_pm_lvl_to_dev_pwr_mode(pm_lvl);
8840 req_link_state = ufs_get_pm_lvl_to_link_pwr_state(pm_lvl);
8842 req_dev_pwr_mode = UFS_POWERDOWN_PWR_MODE;
8843 req_link_state = UIC_LINK_OFF_STATE;
8846 ufshpb_suspend(hba);
8849 * If we can't transition into any of the low power modes
8850 * just gate the clocks.
8852 ufshcd_hold(hba, false);
8853 hba->clk_gating.is_suspended = true;
8855 if (ufshcd_is_clkscaling_supported(hba))
8856 ufshcd_clk_scaling_suspend(hba, true);
8858 if (req_dev_pwr_mode == UFS_ACTIVE_PWR_MODE &&
8859 req_link_state == UIC_LINK_ACTIVE_STATE) {
8863 if ((req_dev_pwr_mode == hba->curr_dev_pwr_mode) &&
8864 (req_link_state == hba->uic_link_state))
8865 goto enable_scaling;
8867 /* UFS device & link must be active before we enter in this function */
8868 if (!ufshcd_is_ufs_dev_active(hba) || !ufshcd_is_link_active(hba)) {
8870 goto enable_scaling;
8873 if (pm_op == UFS_RUNTIME_PM) {
8874 if (ufshcd_can_autobkops_during_suspend(hba)) {
8876 * The device is idle with no requests in the queue,
8877 * allow background operations if bkops status shows
8878 * that performance might be impacted.
8880 ret = ufshcd_urgent_bkops(hba);
8882 goto enable_scaling;
8884 /* make sure that auto bkops is disabled */
8885 ufshcd_disable_auto_bkops(hba);
8888 * If device needs to do BKOP or WB buffer flush during
8889 * Hibern8, keep device power mode as "active power mode"
8892 hba->dev_info.b_rpm_dev_flush_capable =
8893 hba->auto_bkops_enabled ||
8894 (((req_link_state == UIC_LINK_HIBERN8_STATE) ||
8895 ((req_link_state == UIC_LINK_ACTIVE_STATE) &&
8896 ufshcd_is_auto_hibern8_enabled(hba))) &&
8897 ufshcd_wb_need_flush(hba));
8900 flush_work(&hba->eeh_work);
8902 if (req_dev_pwr_mode != hba->curr_dev_pwr_mode) {
8903 if (pm_op != UFS_RUNTIME_PM)
8904 /* ensure that bkops is disabled */
8905 ufshcd_disable_auto_bkops(hba);
8907 if (!hba->dev_info.b_rpm_dev_flush_capable) {
8908 ret = ufshcd_set_dev_pwr_mode(hba, req_dev_pwr_mode);
8910 goto enable_scaling;
8915 * In the case of DeepSleep, the device is expected to remain powered
8916 * with the link off, so do not check for bkops.
8918 check_for_bkops = !ufshcd_is_ufs_dev_deepsleep(hba);
8919 ret = ufshcd_link_state_transition(hba, req_link_state, check_for_bkops);
8921 goto set_dev_active;
8925 * Call vendor specific suspend callback. As these callbacks may access
8926 * vendor specific host controller register space call them before the
8927 * host clocks are ON.
8929 ret = ufshcd_vops_suspend(hba, pm_op);
8931 goto set_link_active;
8936 * Device hardware reset is required to exit DeepSleep. Also, for
8937 * DeepSleep, the link is off so host reset and restore will be done
8940 if (ufshcd_is_ufs_dev_deepsleep(hba)) {
8941 ufshcd_device_reset(hba);
8942 WARN_ON(!ufshcd_is_link_off(hba));
8944 if (ufshcd_is_link_hibern8(hba) && !ufshcd_uic_hibern8_exit(hba))
8945 ufshcd_set_link_active(hba);
8946 else if (ufshcd_is_link_off(hba))
8947 ufshcd_host_reset_and_restore(hba);
8949 /* Can also get here needing to exit DeepSleep */
8950 if (ufshcd_is_ufs_dev_deepsleep(hba)) {
8951 ufshcd_device_reset(hba);
8952 ufshcd_host_reset_and_restore(hba);
8954 if (!ufshcd_set_dev_pwr_mode(hba, UFS_ACTIVE_PWR_MODE))
8955 ufshcd_disable_auto_bkops(hba);
8957 if (ufshcd_is_clkscaling_supported(hba))
8958 ufshcd_clk_scaling_suspend(hba, false);
8960 hba->dev_info.b_rpm_dev_flush_capable = false;
8962 if (hba->dev_info.b_rpm_dev_flush_capable) {
8963 schedule_delayed_work(&hba->rpm_dev_flush_recheck_work,
8964 msecs_to_jiffies(RPM_DEV_FLUSH_RECHECK_WORK_DELAY_MS));
8968 ufshcd_update_evt_hist(hba, UFS_EVT_WL_SUSP_ERR, (u32)ret);
8969 hba->clk_gating.is_suspended = false;
8970 ufshcd_release(hba);
8973 hba->pm_op_in_progress = false;
8978 static int __ufshcd_wl_resume(struct ufs_hba *hba, enum ufs_pm_op pm_op)
8981 enum uic_link_state old_link_state = hba->uic_link_state;
8983 hba->pm_op_in_progress = true;
8986 * Call vendor specific resume callback. As these callbacks may access
8987 * vendor specific host controller register space call them when the
8988 * host clocks are ON.
8990 ret = ufshcd_vops_resume(hba, pm_op);
8994 /* For DeepSleep, the only supported option is to have the link off */
8995 WARN_ON(ufshcd_is_ufs_dev_deepsleep(hba) && !ufshcd_is_link_off(hba));
8997 if (ufshcd_is_link_hibern8(hba)) {
8998 ret = ufshcd_uic_hibern8_exit(hba);
9000 ufshcd_set_link_active(hba);
9002 dev_err(hba->dev, "%s: hibern8 exit failed %d\n",
9004 goto vendor_suspend;
9006 } else if (ufshcd_is_link_off(hba)) {
9008 * A full initialization of the host and the device is
9009 * required since the link was put to off during suspend.
9010 * Note, in the case of DeepSleep, the device will exit
9011 * DeepSleep due to device reset.
9013 ret = ufshcd_reset_and_restore(hba);
9015 * ufshcd_reset_and_restore() should have already
9016 * set the link state as active
9018 if (ret || !ufshcd_is_link_active(hba))
9019 goto vendor_suspend;
9022 if (!ufshcd_is_ufs_dev_active(hba)) {
9023 ret = ufshcd_set_dev_pwr_mode(hba, UFS_ACTIVE_PWR_MODE);
9025 goto set_old_link_state;
9028 if (ufshcd_keep_autobkops_enabled_except_suspend(hba))
9029 ufshcd_enable_auto_bkops(hba);
9032 * If BKOPs operations are urgently needed at this moment then
9033 * keep auto-bkops enabled or else disable it.
9035 ufshcd_urgent_bkops(hba);
9037 if (hba->ee_usr_mask)
9038 ufshcd_write_ee_control(hba);
9040 if (ufshcd_is_clkscaling_supported(hba))
9041 ufshcd_clk_scaling_suspend(hba, false);
9043 if (hba->dev_info.b_rpm_dev_flush_capable) {
9044 hba->dev_info.b_rpm_dev_flush_capable = false;
9045 cancel_delayed_work(&hba->rpm_dev_flush_recheck_work);
9048 /* Enable Auto-Hibernate if configured */
9049 ufshcd_auto_hibern8_enable(hba);
9055 ufshcd_link_state_transition(hba, old_link_state, 0);
9057 ufshcd_vops_suspend(hba, pm_op);
9060 ufshcd_update_evt_hist(hba, UFS_EVT_WL_RES_ERR, (u32)ret);
9061 hba->clk_gating.is_suspended = false;
9062 ufshcd_release(hba);
9063 hba->pm_op_in_progress = false;
9067 static int ufshcd_wl_runtime_suspend(struct device *dev)
9069 struct scsi_device *sdev = to_scsi_device(dev);
9070 struct ufs_hba *hba;
9072 ktime_t start = ktime_get();
9074 hba = shost_priv(sdev->host);
9076 ret = __ufshcd_wl_suspend(hba, UFS_RUNTIME_PM);
9078 dev_err(&sdev->sdev_gendev, "%s failed: %d\n", __func__, ret);
9080 trace_ufshcd_wl_runtime_suspend(dev_name(dev), ret,
9081 ktime_to_us(ktime_sub(ktime_get(), start)),
9082 hba->curr_dev_pwr_mode, hba->uic_link_state);
9087 static int ufshcd_wl_runtime_resume(struct device *dev)
9089 struct scsi_device *sdev = to_scsi_device(dev);
9090 struct ufs_hba *hba;
9092 ktime_t start = ktime_get();
9094 hba = shost_priv(sdev->host);
9096 ret = __ufshcd_wl_resume(hba, UFS_RUNTIME_PM);
9098 dev_err(&sdev->sdev_gendev, "%s failed: %d\n", __func__, ret);
9100 trace_ufshcd_wl_runtime_resume(dev_name(dev), ret,
9101 ktime_to_us(ktime_sub(ktime_get(), start)),
9102 hba->curr_dev_pwr_mode, hba->uic_link_state);
9108 #ifdef CONFIG_PM_SLEEP
9109 static int ufshcd_wl_suspend(struct device *dev)
9111 struct scsi_device *sdev = to_scsi_device(dev);
9112 struct ufs_hba *hba;
9114 ktime_t start = ktime_get();
9116 hba = shost_priv(sdev->host);
9117 down(&hba->host_sem);
9119 if (pm_runtime_suspended(dev))
9122 ret = __ufshcd_wl_suspend(hba, UFS_SYSTEM_PM);
9124 dev_err(&sdev->sdev_gendev, "%s failed: %d\n", __func__, ret);
9130 hba->is_sys_suspended = true;
9131 trace_ufshcd_wl_suspend(dev_name(dev), ret,
9132 ktime_to_us(ktime_sub(ktime_get(), start)),
9133 hba->curr_dev_pwr_mode, hba->uic_link_state);
9138 static int ufshcd_wl_resume(struct device *dev)
9140 struct scsi_device *sdev = to_scsi_device(dev);
9141 struct ufs_hba *hba;
9143 ktime_t start = ktime_get();
9145 hba = shost_priv(sdev->host);
9147 if (pm_runtime_suspended(dev))
9150 ret = __ufshcd_wl_resume(hba, UFS_SYSTEM_PM);
9152 dev_err(&sdev->sdev_gendev, "%s failed: %d\n", __func__, ret);
9154 trace_ufshcd_wl_resume(dev_name(dev), ret,
9155 ktime_to_us(ktime_sub(ktime_get(), start)),
9156 hba->curr_dev_pwr_mode, hba->uic_link_state);
9158 hba->is_sys_suspended = false;
9164 static void ufshcd_wl_shutdown(struct device *dev)
9166 struct scsi_device *sdev = to_scsi_device(dev);
9167 struct ufs_hba *hba;
9169 hba = shost_priv(sdev->host);
9171 down(&hba->host_sem);
9172 hba->shutting_down = true;
9175 /* Turn on everything while shutting down */
9176 ufshcd_rpm_get_sync(hba);
9177 scsi_device_quiesce(sdev);
9178 shost_for_each_device(sdev, hba->host) {
9179 if (sdev == hba->sdev_ufs_device)
9181 scsi_device_quiesce(sdev);
9183 __ufshcd_wl_suspend(hba, UFS_SHUTDOWN_PM);
9187 * ufshcd_suspend - helper function for suspend operations
9188 * @hba: per adapter instance
9190 * This function will put disable irqs, turn off clocks
9191 * and set vreg and hba-vreg in lpm mode.
9193 static int ufshcd_suspend(struct ufs_hba *hba)
9197 if (!hba->is_powered)
9200 * Disable the host irq as host controller as there won't be any
9201 * host controller transaction expected till resume.
9203 ufshcd_disable_irq(hba);
9204 ret = ufshcd_setup_clocks(hba, false);
9206 ufshcd_enable_irq(hba);
9209 if (ufshcd_is_clkgating_allowed(hba)) {
9210 hba->clk_gating.state = CLKS_OFF;
9211 trace_ufshcd_clk_gating(dev_name(hba->dev),
9212 hba->clk_gating.state);
9215 ufshcd_vreg_set_lpm(hba);
9216 /* Put the host controller in low power mode if possible */
9217 ufshcd_hba_vreg_set_lpm(hba);
9223 * ufshcd_resume - helper function for resume operations
9224 * @hba: per adapter instance
9226 * This function basically turns on the regulators, clocks and
9229 * Returns 0 for success and non-zero for failure
9231 static int ufshcd_resume(struct ufs_hba *hba)
9235 if (!hba->is_powered)
9238 ufshcd_hba_vreg_set_hpm(hba);
9239 ret = ufshcd_vreg_set_hpm(hba);
9243 /* Make sure clocks are enabled before accessing controller */
9244 ret = ufshcd_setup_clocks(hba, true);
9248 /* enable the host irq as host controller would be active soon */
9249 ufshcd_enable_irq(hba);
9253 ufshcd_vreg_set_lpm(hba);
9256 ufshcd_update_evt_hist(hba, UFS_EVT_RESUME_ERR, (u32)ret);
9259 #endif /* CONFIG_PM */
9261 #ifdef CONFIG_PM_SLEEP
9263 * ufshcd_system_suspend - system suspend callback
9264 * @dev: Device associated with the UFS controller.
9266 * Executed before putting the system into a sleep state in which the contents
9267 * of main memory are preserved.
9269 * Returns 0 for success and non-zero for failure
9271 int ufshcd_system_suspend(struct device *dev)
9273 struct ufs_hba *hba = dev_get_drvdata(dev);
9275 ktime_t start = ktime_get();
9277 if (pm_runtime_suspended(hba->dev))
9280 ret = ufshcd_suspend(hba);
9282 trace_ufshcd_system_suspend(dev_name(hba->dev), ret,
9283 ktime_to_us(ktime_sub(ktime_get(), start)),
9284 hba->curr_dev_pwr_mode, hba->uic_link_state);
9287 EXPORT_SYMBOL(ufshcd_system_suspend);
9290 * ufshcd_system_resume - system resume callback
9291 * @dev: Device associated with the UFS controller.
9293 * Executed after waking the system up from a sleep state in which the contents
9294 * of main memory were preserved.
9296 * Returns 0 for success and non-zero for failure
9298 int ufshcd_system_resume(struct device *dev)
9300 struct ufs_hba *hba = dev_get_drvdata(dev);
9301 ktime_t start = ktime_get();
9304 if (pm_runtime_suspended(hba->dev))
9307 ret = ufshcd_resume(hba);
9310 trace_ufshcd_system_resume(dev_name(hba->dev), ret,
9311 ktime_to_us(ktime_sub(ktime_get(), start)),
9312 hba->curr_dev_pwr_mode, hba->uic_link_state);
9316 EXPORT_SYMBOL(ufshcd_system_resume);
9317 #endif /* CONFIG_PM_SLEEP */
9321 * ufshcd_runtime_suspend - runtime suspend callback
9322 * @dev: Device associated with the UFS controller.
9324 * Check the description of ufshcd_suspend() function for more details.
9326 * Returns 0 for success and non-zero for failure
9328 int ufshcd_runtime_suspend(struct device *dev)
9330 struct ufs_hba *hba = dev_get_drvdata(dev);
9332 ktime_t start = ktime_get();
9334 ret = ufshcd_suspend(hba);
9336 trace_ufshcd_runtime_suspend(dev_name(hba->dev), ret,
9337 ktime_to_us(ktime_sub(ktime_get(), start)),
9338 hba->curr_dev_pwr_mode, hba->uic_link_state);
9341 EXPORT_SYMBOL(ufshcd_runtime_suspend);
9344 * ufshcd_runtime_resume - runtime resume routine
9345 * @dev: Device associated with the UFS controller.
9347 * This function basically brings controller
9348 * to active state. Following operations are done in this function:
9350 * 1. Turn on all the controller related clocks
9351 * 2. Turn ON VCC rail
9353 int ufshcd_runtime_resume(struct device *dev)
9355 struct ufs_hba *hba = dev_get_drvdata(dev);
9357 ktime_t start = ktime_get();
9359 ret = ufshcd_resume(hba);
9361 trace_ufshcd_runtime_resume(dev_name(hba->dev), ret,
9362 ktime_to_us(ktime_sub(ktime_get(), start)),
9363 hba->curr_dev_pwr_mode, hba->uic_link_state);
9366 EXPORT_SYMBOL(ufshcd_runtime_resume);
9367 #endif /* CONFIG_PM */
9370 * ufshcd_shutdown - shutdown routine
9371 * @hba: per adapter instance
9373 * This function would turn off both UFS device and UFS hba
9374 * regulators. It would also disable clocks.
9376 * Returns 0 always to allow force shutdown even in case of errors.
9378 int ufshcd_shutdown(struct ufs_hba *hba)
9380 if (ufshcd_is_ufs_dev_poweroff(hba) && ufshcd_is_link_off(hba))
9383 pm_runtime_get_sync(hba->dev);
9385 ufshcd_suspend(hba);
9387 hba->is_powered = false;
9388 /* allow force shutdown even in case of errors */
9391 EXPORT_SYMBOL(ufshcd_shutdown);
9394 * ufshcd_remove - de-allocate SCSI host and host memory space
9395 * data structure memory
9396 * @hba: per adapter instance
9398 void ufshcd_remove(struct ufs_hba *hba)
9400 if (hba->sdev_ufs_device)
9401 ufshcd_rpm_get_sync(hba);
9402 ufs_bsg_remove(hba);
9404 ufs_sysfs_remove_nodes(hba->dev);
9405 blk_cleanup_queue(hba->tmf_queue);
9406 blk_mq_free_tag_set(&hba->tmf_tag_set);
9407 blk_cleanup_queue(hba->cmd_queue);
9408 scsi_remove_host(hba->host);
9409 /* disable interrupts */
9410 ufshcd_disable_intr(hba, hba->intr_mask);
9411 ufshcd_hba_stop(hba);
9412 ufshcd_hba_exit(hba);
9414 EXPORT_SYMBOL_GPL(ufshcd_remove);
9417 * ufshcd_dealloc_host - deallocate Host Bus Adapter (HBA)
9418 * @hba: pointer to Host Bus Adapter (HBA)
9420 void ufshcd_dealloc_host(struct ufs_hba *hba)
9422 scsi_host_put(hba->host);
9424 EXPORT_SYMBOL_GPL(ufshcd_dealloc_host);
9427 * ufshcd_set_dma_mask - Set dma mask based on the controller
9428 * addressing capability
9429 * @hba: per adapter instance
9431 * Returns 0 for success, non-zero for failure
9433 static int ufshcd_set_dma_mask(struct ufs_hba *hba)
9435 if (hba->capabilities & MASK_64_ADDRESSING_SUPPORT) {
9436 if (!dma_set_mask_and_coherent(hba->dev, DMA_BIT_MASK(64)))
9439 return dma_set_mask_and_coherent(hba->dev, DMA_BIT_MASK(32));
9443 * ufshcd_alloc_host - allocate Host Bus Adapter (HBA)
9444 * @dev: pointer to device handle
9445 * @hba_handle: driver private handle
9446 * Returns 0 on success, non-zero value on failure
9448 int ufshcd_alloc_host(struct device *dev, struct ufs_hba **hba_handle)
9450 struct Scsi_Host *host;
9451 struct ufs_hba *hba;
9456 "Invalid memory reference for dev is NULL\n");
9461 host = scsi_host_alloc(&ufshcd_driver_template,
9462 sizeof(struct ufs_hba));
9464 dev_err(dev, "scsi_host_alloc failed\n");
9468 hba = shost_priv(host);
9472 hba->dev_ref_clk_freq = REF_CLK_FREQ_INVAL;
9474 INIT_LIST_HEAD(&hba->clk_list_head);
9479 EXPORT_SYMBOL(ufshcd_alloc_host);
9481 /* This function exists because blk_mq_alloc_tag_set() requires this. */
9482 static blk_status_t ufshcd_queue_tmf(struct blk_mq_hw_ctx *hctx,
9483 const struct blk_mq_queue_data *qd)
9486 return BLK_STS_NOTSUPP;
9489 static const struct blk_mq_ops ufshcd_tmf_ops = {
9490 .queue_rq = ufshcd_queue_tmf,
9494 * ufshcd_init - Driver initialization routine
9495 * @hba: per-adapter instance
9496 * @mmio_base: base register address
9497 * @irq: Interrupt line of device
9498 * Returns 0 on success, non-zero value on failure
9500 int ufshcd_init(struct ufs_hba *hba, void __iomem *mmio_base, unsigned int irq)
9503 struct Scsi_Host *host = hba->host;
9504 struct device *dev = hba->dev;
9505 char eh_wq_name[sizeof("ufs_eh_wq_00")];
9509 "Invalid memory reference for mmio_base is NULL\n");
9514 hba->mmio_base = mmio_base;
9516 hba->vps = &ufs_hba_vps;
9518 err = ufshcd_hba_init(hba);
9522 /* Read capabilities registers */
9523 err = ufshcd_hba_capabilities(hba);
9527 /* Get UFS version supported by the controller */
9528 hba->ufs_version = ufshcd_get_ufs_version(hba);
9530 /* Get Interrupt bit mask per version */
9531 hba->intr_mask = ufshcd_get_intr_mask(hba);
9533 err = ufshcd_set_dma_mask(hba);
9535 dev_err(hba->dev, "set dma mask failed\n");
9539 /* Allocate memory for host memory space */
9540 err = ufshcd_memory_alloc(hba);
9542 dev_err(hba->dev, "Memory allocation failed\n");
9547 ufshcd_host_memory_configure(hba);
9549 host->can_queue = hba->nutrs;
9550 host->cmd_per_lun = hba->nutrs;
9551 host->max_id = UFSHCD_MAX_ID;
9552 host->max_lun = UFS_MAX_LUNS;
9553 host->max_channel = UFSHCD_MAX_CHANNEL;
9554 host->unique_id = host->host_no;
9555 host->max_cmd_len = UFS_CDB_SIZE;
9557 hba->max_pwr_info.is_valid = false;
9559 /* Initialize work queues */
9560 snprintf(eh_wq_name, sizeof(eh_wq_name), "ufs_eh_wq_%d",
9561 hba->host->host_no);
9562 hba->eh_wq = create_singlethread_workqueue(eh_wq_name);
9564 dev_err(hba->dev, "%s: failed to create eh workqueue\n",
9569 INIT_WORK(&hba->eh_work, ufshcd_err_handler);
9570 INIT_WORK(&hba->eeh_work, ufshcd_exception_event_handler);
9572 sema_init(&hba->host_sem, 1);
9574 /* Initialize UIC command mutex */
9575 mutex_init(&hba->uic_cmd_mutex);
9577 /* Initialize mutex for device management commands */
9578 mutex_init(&hba->dev_cmd.lock);
9580 /* Initialize mutex for exception event control */
9581 mutex_init(&hba->ee_ctrl_mutex);
9583 init_rwsem(&hba->clk_scaling_lock);
9585 ufshcd_init_clk_gating(hba);
9587 ufshcd_init_clk_scaling(hba);
9590 * In order to avoid any spurious interrupt immediately after
9591 * registering UFS controller interrupt handler, clear any pending UFS
9592 * interrupt status and disable all the UFS interrupts.
9594 ufshcd_writel(hba, ufshcd_readl(hba, REG_INTERRUPT_STATUS),
9595 REG_INTERRUPT_STATUS);
9596 ufshcd_writel(hba, 0, REG_INTERRUPT_ENABLE);
9598 * Make sure that UFS interrupts are disabled and any pending interrupt
9599 * status is cleared before registering UFS interrupt handler.
9603 /* IRQ registration */
9604 err = devm_request_irq(dev, irq, ufshcd_intr, IRQF_SHARED, UFSHCD, hba);
9606 dev_err(hba->dev, "request irq failed\n");
9609 hba->is_irq_enabled = true;
9612 err = scsi_add_host(host, hba->dev);
9614 dev_err(hba->dev, "scsi_add_host failed\n");
9618 hba->cmd_queue = blk_mq_init_queue(&hba->host->tag_set);
9619 if (IS_ERR(hba->cmd_queue)) {
9620 err = PTR_ERR(hba->cmd_queue);
9621 goto out_remove_scsi_host;
9624 hba->tmf_tag_set = (struct blk_mq_tag_set) {
9626 .queue_depth = hba->nutmrs,
9627 .ops = &ufshcd_tmf_ops,
9628 .flags = BLK_MQ_F_NO_SCHED,
9630 err = blk_mq_alloc_tag_set(&hba->tmf_tag_set);
9632 goto free_cmd_queue;
9633 hba->tmf_queue = blk_mq_init_queue(&hba->tmf_tag_set);
9634 if (IS_ERR(hba->tmf_queue)) {
9635 err = PTR_ERR(hba->tmf_queue);
9636 goto free_tmf_tag_set;
9639 /* Reset the attached device */
9640 ufshcd_device_reset(hba);
9642 ufshcd_init_crypto(hba);
9644 /* Host controller enable */
9645 err = ufshcd_hba_enable(hba);
9647 dev_err(hba->dev, "Host controller enable failed\n");
9648 ufshcd_print_evt_hist(hba);
9649 ufshcd_print_host_state(hba);
9650 goto free_tmf_queue;
9654 * Set the default power management level for runtime and system PM.
9655 * Default power saving mode is to keep UFS link in Hibern8 state
9656 * and UFS device in sleep state.
9658 hba->rpm_lvl = ufs_get_desired_pm_lvl_for_dev_link_state(
9660 UIC_LINK_HIBERN8_STATE);
9661 hba->spm_lvl = ufs_get_desired_pm_lvl_for_dev_link_state(
9663 UIC_LINK_HIBERN8_STATE);
9665 INIT_DELAYED_WORK(&hba->rpm_dev_flush_recheck_work,
9666 ufshcd_rpm_dev_flush_recheck_work);
9668 /* Set the default auto-hiberate idle timer value to 150 ms */
9669 if (ufshcd_is_auto_hibern8_supported(hba) && !hba->ahit) {
9670 hba->ahit = FIELD_PREP(UFSHCI_AHIBERN8_TIMER_MASK, 150) |
9671 FIELD_PREP(UFSHCI_AHIBERN8_SCALE_MASK, 3);
9674 /* Hold auto suspend until async scan completes */
9675 pm_runtime_get_sync(dev);
9676 atomic_set(&hba->scsi_block_reqs_cnt, 0);
9678 * We are assuming that device wasn't put in sleep/power-down
9679 * state exclusively during the boot stage before kernel.
9680 * This assumption helps avoid doing link startup twice during
9681 * ufshcd_probe_hba().
9683 ufshcd_set_ufs_dev_active(hba);
9685 async_schedule(ufshcd_async_scan, hba);
9686 ufs_sysfs_add_nodes(hba->dev);
9688 device_enable_async_suspend(dev);
9692 blk_cleanup_queue(hba->tmf_queue);
9694 blk_mq_free_tag_set(&hba->tmf_tag_set);
9696 blk_cleanup_queue(hba->cmd_queue);
9697 out_remove_scsi_host:
9698 scsi_remove_host(hba->host);
9700 hba->is_irq_enabled = false;
9701 ufshcd_hba_exit(hba);
9705 EXPORT_SYMBOL_GPL(ufshcd_init);
9707 void ufshcd_resume_complete(struct device *dev)
9709 struct ufs_hba *hba = dev_get_drvdata(dev);
9711 if (hba->complete_put) {
9712 ufshcd_rpm_put(hba);
9713 hba->complete_put = false;
9715 if (hba->rpmb_complete_put) {
9716 ufshcd_rpmb_rpm_put(hba);
9717 hba->rpmb_complete_put = false;
9720 EXPORT_SYMBOL_GPL(ufshcd_resume_complete);
9722 int ufshcd_suspend_prepare(struct device *dev)
9724 struct ufs_hba *hba = dev_get_drvdata(dev);
9728 * SCSI assumes that runtime-pm and system-pm for scsi drivers
9729 * are same. And it doesn't wake up the device for system-suspend
9730 * if it's runtime suspended. But ufs doesn't follow that.
9731 * Refer ufshcd_resume_complete()
9733 if (hba->sdev_ufs_device) {
9734 ret = ufshcd_rpm_get_sync(hba);
9735 if (ret < 0 && ret != -EACCES) {
9736 ufshcd_rpm_put(hba);
9739 hba->complete_put = true;
9741 if (hba->sdev_rpmb) {
9742 ufshcd_rpmb_rpm_get_sync(hba);
9743 hba->rpmb_complete_put = true;
9747 EXPORT_SYMBOL_GPL(ufshcd_suspend_prepare);
9749 #ifdef CONFIG_PM_SLEEP
9750 static int ufshcd_wl_poweroff(struct device *dev)
9752 struct scsi_device *sdev = to_scsi_device(dev);
9753 struct ufs_hba *hba = shost_priv(sdev->host);
9755 __ufshcd_wl_suspend(hba, UFS_SHUTDOWN_PM);
9760 static int ufshcd_wl_probe(struct device *dev)
9762 struct scsi_device *sdev = to_scsi_device(dev);
9764 if (!is_device_wlun(sdev))
9767 blk_pm_runtime_init(sdev->request_queue, dev);
9768 pm_runtime_set_autosuspend_delay(dev, 0);
9769 pm_runtime_allow(dev);
9774 static int ufshcd_wl_remove(struct device *dev)
9776 pm_runtime_forbid(dev);
9780 static const struct dev_pm_ops ufshcd_wl_pm_ops = {
9781 #ifdef CONFIG_PM_SLEEP
9782 .suspend = ufshcd_wl_suspend,
9783 .resume = ufshcd_wl_resume,
9784 .freeze = ufshcd_wl_suspend,
9785 .thaw = ufshcd_wl_resume,
9786 .poweroff = ufshcd_wl_poweroff,
9787 .restore = ufshcd_wl_resume,
9789 SET_RUNTIME_PM_OPS(ufshcd_wl_runtime_suspend, ufshcd_wl_runtime_resume, NULL)
9793 * ufs_dev_wlun_template - describes ufs device wlun
9794 * ufs-device wlun - used to send pm commands
9795 * All luns are consumers of ufs-device wlun.
9797 * Currently, no sd driver is present for wluns.
9798 * Hence the no specific pm operations are performed.
9799 * With ufs design, SSU should be sent to ufs-device wlun.
9800 * Hence register a scsi driver for ufs wluns only.
9802 static struct scsi_driver ufs_dev_wlun_template = {
9804 .name = "ufs_device_wlun",
9805 .owner = THIS_MODULE,
9806 .probe = ufshcd_wl_probe,
9807 .remove = ufshcd_wl_remove,
9808 .pm = &ufshcd_wl_pm_ops,
9809 .shutdown = ufshcd_wl_shutdown,
9813 static int ufshcd_rpmb_probe(struct device *dev)
9815 return is_rpmb_wlun(to_scsi_device(dev)) ? 0 : -ENODEV;
9818 static inline int ufshcd_clear_rpmb_uac(struct ufs_hba *hba)
9822 if (!hba->wlun_rpmb_clr_ua)
9824 ret = ufshcd_clear_ua_wlun(hba, UFS_UPIU_RPMB_WLUN);
9826 hba->wlun_rpmb_clr_ua = 0;
9831 static int ufshcd_rpmb_resume(struct device *dev)
9833 struct ufs_hba *hba = wlun_dev_to_hba(dev);
9836 ufshcd_clear_rpmb_uac(hba);
9841 static const struct dev_pm_ops ufs_rpmb_pm_ops = {
9842 SET_RUNTIME_PM_OPS(NULL, ufshcd_rpmb_resume, NULL)
9843 SET_SYSTEM_SLEEP_PM_OPS(NULL, ufshcd_rpmb_resume)
9846 /* ufs_rpmb_wlun_template - Describes UFS RPMB WLUN. Used only to send UAC. */
9847 static struct scsi_driver ufs_rpmb_wlun_template = {
9849 .name = "ufs_rpmb_wlun",
9850 .owner = THIS_MODULE,
9851 .probe = ufshcd_rpmb_probe,
9852 .pm = &ufs_rpmb_pm_ops,
9856 static int __init ufshcd_core_init(void)
9862 ret = scsi_register_driver(&ufs_dev_wlun_template.gendrv);
9866 ret = scsi_register_driver(&ufs_rpmb_wlun_template.gendrv);
9872 scsi_unregister_driver(&ufs_dev_wlun_template.gendrv);
9878 static void __exit ufshcd_core_exit(void)
9881 scsi_unregister_driver(&ufs_rpmb_wlun_template.gendrv);
9882 scsi_unregister_driver(&ufs_dev_wlun_template.gendrv);
9885 module_init(ufshcd_core_init);
9886 module_exit(ufshcd_core_exit);
9888 MODULE_AUTHOR("Santosh Yaragnavi <santosh.sy@samsung.com>");
9889 MODULE_AUTHOR("Vinayak Holikatti <h.vinayak@samsung.com>");
9890 MODULE_DESCRIPTION("Generic UFS host controller driver Core");
9891 MODULE_LICENSE("GPL");
9892 MODULE_VERSION(UFSHCD_DRIVER_VERSION);