1 // SPDX-License-Identifier: GPL-2.0-or-later
3 * Universal Flash Storage Host controller driver Core
4 * Copyright (C) 2011-2013 Samsung India Software Operations
5 * Copyright (c) 2013-2016, The Linux Foundation. All rights reserved.
8 * Santosh Yaraganavi <santosh.sy@samsung.com>
9 * Vinayak Holikatti <h.vinayak@samsung.com>
12 #include <linux/async.h>
13 #include <linux/devfreq.h>
14 #include <linux/nls.h>
16 #include <linux/bitfield.h>
17 #include <linux/blk-pm.h>
18 #include <linux/blkdev.h>
19 #include <scsi/scsi_driver.h>
20 #include <scsi/scsi_transport.h>
21 #include "../scsi_transport_api.h"
23 #include "ufs_quirks.h"
25 #include "ufs-sysfs.h"
26 #include "ufs-debugfs.h"
27 #include "ufs-fault-injection.h"
29 #include "ufshcd-crypto.h"
31 #include <asm/unaligned.h>
33 #define CREATE_TRACE_POINTS
34 #include <trace/events/ufs.h>
36 #define UFSHCD_ENABLE_INTRS (UTP_TRANSFER_REQ_COMPL |\
39 /* UIC command timeout, unit: ms */
40 #define UIC_CMD_TIMEOUT 500
42 /* NOP OUT retries waiting for NOP IN response */
43 #define NOP_OUT_RETRIES 10
44 /* Timeout after 50 msecs if NOP OUT hangs without response */
45 #define NOP_OUT_TIMEOUT 50 /* msecs */
47 /* Query request retries */
48 #define QUERY_REQ_RETRIES 3
49 /* Query request timeout */
50 #define QUERY_REQ_TIMEOUT 1500 /* 1.5 seconds */
52 /* Task management command timeout */
53 #define TM_CMD_TIMEOUT 100 /* msecs */
55 /* maximum number of retries for a general UIC command */
56 #define UFS_UIC_COMMAND_RETRIES 3
58 /* maximum number of link-startup retries */
59 #define DME_LINKSTARTUP_RETRIES 3
61 /* Maximum retries for Hibern8 enter */
62 #define UIC_HIBERN8_ENTER_RETRIES 3
64 /* maximum number of reset retries before giving up */
65 #define MAX_HOST_RESET_RETRIES 5
67 /* Maximum number of error handler retries before giving up */
68 #define MAX_ERR_HANDLER_RETRIES 5
70 /* Expose the flag value from utp_upiu_query.value */
71 #define MASK_QUERY_UPIU_FLAG_LOC 0xFF
73 /* Interrupt aggregation default timeout, unit: 40us */
74 #define INT_AGGR_DEF_TO 0x02
76 /* default delay of autosuspend: 2000 ms */
77 #define RPM_AUTOSUSPEND_DELAY_MS 2000
79 /* Default delay of RPM device flush delayed work */
80 #define RPM_DEV_FLUSH_RECHECK_WORK_DELAY_MS 5000
82 /* Default value of wait time before gating device ref clock */
83 #define UFSHCD_REF_CLK_GATING_WAIT_US 0xFF /* microsecs */
85 /* Polling time to wait for fDeviceInit */
86 #define FDEVICEINIT_COMPL_TIMEOUT 1500 /* millisecs */
88 #define wlun_dev_to_hba(dv) shost_priv(to_scsi_device(dv)->host)
90 #define ufshcd_toggle_vreg(_dev, _vreg, _on) \
94 _ret = ufshcd_enable_vreg(_dev, _vreg); \
96 _ret = ufshcd_disable_vreg(_dev, _vreg); \
100 #define ufshcd_hex_dump(prefix_str, buf, len) do { \
101 size_t __len = (len); \
102 print_hex_dump(KERN_ERR, prefix_str, \
103 __len > 4 ? DUMP_PREFIX_OFFSET : DUMP_PREFIX_NONE,\
104 16, 4, buf, __len, false); \
107 int ufshcd_dump_regs(struct ufs_hba *hba, size_t offset, size_t len,
113 if (offset % 4 != 0 || len % 4 != 0) /* keep readl happy */
116 regs = kzalloc(len, GFP_ATOMIC);
120 for (pos = 0; pos < len; pos += 4)
121 regs[pos / 4] = ufshcd_readl(hba, offset + pos);
123 ufshcd_hex_dump(prefix, regs, len);
128 EXPORT_SYMBOL_GPL(ufshcd_dump_regs);
131 UFSHCD_MAX_CHANNEL = 0,
133 UFSHCD_CMD_PER_LUN = 32,
134 UFSHCD_CAN_QUEUE = 32,
137 /* UFSHCD error handling flags */
139 UFSHCD_EH_IN_PROGRESS = (1 << 0),
142 /* UFSHCD UIC layer error flags */
144 UFSHCD_UIC_DL_PA_INIT_ERROR = (1 << 0), /* Data link layer error */
145 UFSHCD_UIC_DL_NAC_RECEIVED_ERROR = (1 << 1), /* Data link layer error */
146 UFSHCD_UIC_DL_TCx_REPLAY_ERROR = (1 << 2), /* Data link layer error */
147 UFSHCD_UIC_NL_ERROR = (1 << 3), /* Network layer error */
148 UFSHCD_UIC_TL_ERROR = (1 << 4), /* Transport Layer error */
149 UFSHCD_UIC_DME_ERROR = (1 << 5), /* DME error */
150 UFSHCD_UIC_PA_GENERIC_ERROR = (1 << 6), /* Generic PA error */
153 #define ufshcd_set_eh_in_progress(h) \
154 ((h)->eh_flags |= UFSHCD_EH_IN_PROGRESS)
155 #define ufshcd_eh_in_progress(h) \
156 ((h)->eh_flags & UFSHCD_EH_IN_PROGRESS)
157 #define ufshcd_clear_eh_in_progress(h) \
158 ((h)->eh_flags &= ~UFSHCD_EH_IN_PROGRESS)
160 struct ufs_pm_lvl_states ufs_pm_lvl_states[] = {
161 [UFS_PM_LVL_0] = {UFS_ACTIVE_PWR_MODE, UIC_LINK_ACTIVE_STATE},
162 [UFS_PM_LVL_1] = {UFS_ACTIVE_PWR_MODE, UIC_LINK_HIBERN8_STATE},
163 [UFS_PM_LVL_2] = {UFS_SLEEP_PWR_MODE, UIC_LINK_ACTIVE_STATE},
164 [UFS_PM_LVL_3] = {UFS_SLEEP_PWR_MODE, UIC_LINK_HIBERN8_STATE},
165 [UFS_PM_LVL_4] = {UFS_POWERDOWN_PWR_MODE, UIC_LINK_HIBERN8_STATE},
166 [UFS_PM_LVL_5] = {UFS_POWERDOWN_PWR_MODE, UIC_LINK_OFF_STATE},
168 * For DeepSleep, the link is first put in hibern8 and then off.
169 * Leaving the link in hibern8 is not supported.
171 [UFS_PM_LVL_6] = {UFS_DEEPSLEEP_PWR_MODE, UIC_LINK_OFF_STATE},
174 static inline enum ufs_dev_pwr_mode
175 ufs_get_pm_lvl_to_dev_pwr_mode(enum ufs_pm_level lvl)
177 return ufs_pm_lvl_states[lvl].dev_state;
180 static inline enum uic_link_state
181 ufs_get_pm_lvl_to_link_pwr_state(enum ufs_pm_level lvl)
183 return ufs_pm_lvl_states[lvl].link_state;
186 static inline enum ufs_pm_level
187 ufs_get_desired_pm_lvl_for_dev_link_state(enum ufs_dev_pwr_mode dev_state,
188 enum uic_link_state link_state)
190 enum ufs_pm_level lvl;
192 for (lvl = UFS_PM_LVL_0; lvl < UFS_PM_LVL_MAX; lvl++) {
193 if ((ufs_pm_lvl_states[lvl].dev_state == dev_state) &&
194 (ufs_pm_lvl_states[lvl].link_state == link_state))
198 /* if no match found, return the level 0 */
202 static struct ufs_dev_fix ufs_fixups[] = {
203 /* UFS cards deviations table */
204 UFS_FIX(UFS_VENDOR_MICRON, UFS_ANY_MODEL,
205 UFS_DEVICE_QUIRK_DELAY_BEFORE_LPM |
206 UFS_DEVICE_QUIRK_SWAP_L2P_ENTRY_FOR_HPB_READ),
207 UFS_FIX(UFS_VENDOR_SAMSUNG, UFS_ANY_MODEL,
208 UFS_DEVICE_QUIRK_DELAY_BEFORE_LPM |
209 UFS_DEVICE_QUIRK_HOST_PA_TACTIVATE |
210 UFS_DEVICE_QUIRK_RECOVERY_FROM_DL_NAC_ERRORS),
211 UFS_FIX(UFS_VENDOR_SKHYNIX, UFS_ANY_MODEL,
212 UFS_DEVICE_QUIRK_HOST_PA_SAVECONFIGTIME),
213 UFS_FIX(UFS_VENDOR_SKHYNIX, "hB8aL1" /*H28U62301AMR*/,
214 UFS_DEVICE_QUIRK_HOST_VS_DEBUGSAVECONFIGTIME),
215 UFS_FIX(UFS_VENDOR_TOSHIBA, UFS_ANY_MODEL,
216 UFS_DEVICE_QUIRK_DELAY_BEFORE_LPM),
217 UFS_FIX(UFS_VENDOR_TOSHIBA, "THGLF2G9C8KBADG",
218 UFS_DEVICE_QUIRK_PA_TACTIVATE),
219 UFS_FIX(UFS_VENDOR_TOSHIBA, "THGLF2G9D8KBADG",
220 UFS_DEVICE_QUIRK_PA_TACTIVATE),
224 static irqreturn_t ufshcd_tmc_handler(struct ufs_hba *hba);
225 static void ufshcd_async_scan(void *data, async_cookie_t cookie);
226 static int ufshcd_reset_and_restore(struct ufs_hba *hba);
227 static int ufshcd_eh_host_reset_handler(struct scsi_cmnd *cmd);
228 static int ufshcd_clear_tm_cmd(struct ufs_hba *hba, int tag);
229 static void ufshcd_hba_exit(struct ufs_hba *hba);
230 static int ufshcd_probe_hba(struct ufs_hba *hba, bool init_dev_params);
231 static int ufshcd_setup_clocks(struct ufs_hba *hba, bool on);
232 static inline void ufshcd_add_delay_before_dme_cmd(struct ufs_hba *hba);
233 static int ufshcd_host_reset_and_restore(struct ufs_hba *hba);
234 static void ufshcd_resume_clkscaling(struct ufs_hba *hba);
235 static void ufshcd_suspend_clkscaling(struct ufs_hba *hba);
236 static void __ufshcd_suspend_clkscaling(struct ufs_hba *hba);
237 static int ufshcd_scale_clks(struct ufs_hba *hba, bool scale_up);
238 static irqreturn_t ufshcd_intr(int irq, void *__hba);
239 static int ufshcd_change_power_mode(struct ufs_hba *hba,
240 struct ufs_pa_layer_attr *pwr_mode);
241 static int ufshcd_setup_hba_vreg(struct ufs_hba *hba, bool on);
242 static int ufshcd_setup_vreg(struct ufs_hba *hba, bool on);
243 static inline int ufshcd_config_vreg_hpm(struct ufs_hba *hba,
244 struct ufs_vreg *vreg);
245 static int ufshcd_try_to_abort_task(struct ufs_hba *hba, int tag);
246 static void ufshcd_wb_toggle_flush_during_h8(struct ufs_hba *hba, bool set);
247 static inline void ufshcd_wb_toggle_flush(struct ufs_hba *hba, bool enable);
248 static void ufshcd_hba_vreg_set_lpm(struct ufs_hba *hba);
249 static void ufshcd_hba_vreg_set_hpm(struct ufs_hba *hba);
251 static inline void ufshcd_enable_irq(struct ufs_hba *hba)
253 if (!hba->is_irq_enabled) {
254 enable_irq(hba->irq);
255 hba->is_irq_enabled = true;
259 static inline void ufshcd_disable_irq(struct ufs_hba *hba)
261 if (hba->is_irq_enabled) {
262 disable_irq(hba->irq);
263 hba->is_irq_enabled = false;
267 static inline void ufshcd_wb_config(struct ufs_hba *hba)
269 if (!ufshcd_is_wb_allowed(hba))
272 ufshcd_wb_toggle(hba, true);
274 ufshcd_wb_toggle_flush_during_h8(hba, true);
275 if (!(hba->quirks & UFSHCI_QUIRK_SKIP_MANUAL_WB_FLUSH_CTRL))
276 ufshcd_wb_toggle_flush(hba, true);
279 static void ufshcd_scsi_unblock_requests(struct ufs_hba *hba)
281 if (atomic_dec_and_test(&hba->scsi_block_reqs_cnt))
282 scsi_unblock_requests(hba->host);
285 static void ufshcd_scsi_block_requests(struct ufs_hba *hba)
287 if (atomic_inc_return(&hba->scsi_block_reqs_cnt) == 1)
288 scsi_block_requests(hba->host);
291 static void ufshcd_add_cmd_upiu_trace(struct ufs_hba *hba, unsigned int tag,
292 enum ufs_trace_str_t str_t)
294 struct utp_upiu_req *rq = hba->lrb[tag].ucd_req_ptr;
295 struct utp_upiu_header *header;
297 if (!trace_ufshcd_upiu_enabled())
300 if (str_t == UFS_CMD_SEND)
301 header = &rq->header;
303 header = &hba->lrb[tag].ucd_rsp_ptr->header;
305 trace_ufshcd_upiu(dev_name(hba->dev), str_t, header, &rq->sc.cdb,
309 static void ufshcd_add_query_upiu_trace(struct ufs_hba *hba,
310 enum ufs_trace_str_t str_t,
311 struct utp_upiu_req *rq_rsp)
313 if (!trace_ufshcd_upiu_enabled())
316 trace_ufshcd_upiu(dev_name(hba->dev), str_t, &rq_rsp->header,
317 &rq_rsp->qr, UFS_TSF_OSF);
320 static void ufshcd_add_tm_upiu_trace(struct ufs_hba *hba, unsigned int tag,
321 enum ufs_trace_str_t str_t)
323 int off = (int)tag - hba->nutrs;
324 struct utp_task_req_desc *descp = &hba->utmrdl_base_addr[off];
326 if (!trace_ufshcd_upiu_enabled())
329 if (str_t == UFS_TM_SEND)
330 trace_ufshcd_upiu(dev_name(hba->dev), str_t,
331 &descp->upiu_req.req_header,
332 &descp->upiu_req.input_param1,
335 trace_ufshcd_upiu(dev_name(hba->dev), str_t,
336 &descp->upiu_rsp.rsp_header,
337 &descp->upiu_rsp.output_param1,
341 static void ufshcd_add_uic_command_trace(struct ufs_hba *hba,
342 struct uic_command *ucmd,
343 enum ufs_trace_str_t str_t)
347 if (!trace_ufshcd_uic_command_enabled())
350 if (str_t == UFS_CMD_SEND)
353 cmd = ufshcd_readl(hba, REG_UIC_COMMAND);
355 trace_ufshcd_uic_command(dev_name(hba->dev), str_t, cmd,
356 ufshcd_readl(hba, REG_UIC_COMMAND_ARG_1),
357 ufshcd_readl(hba, REG_UIC_COMMAND_ARG_2),
358 ufshcd_readl(hba, REG_UIC_COMMAND_ARG_3));
361 static void ufshcd_add_command_trace(struct ufs_hba *hba, unsigned int tag,
362 enum ufs_trace_str_t str_t)
365 u8 opcode = 0, group_id = 0;
367 struct ufshcd_lrb *lrbp = &hba->lrb[tag];
368 struct scsi_cmnd *cmd = lrbp->cmd;
369 struct request *rq = scsi_cmd_to_rq(cmd);
370 int transfer_len = -1;
375 /* trace UPIU also */
376 ufshcd_add_cmd_upiu_trace(hba, tag, str_t);
377 if (!trace_ufshcd_command_enabled())
380 opcode = cmd->cmnd[0];
381 lba = scsi_get_lba(cmd);
383 if (opcode == READ_10 || opcode == WRITE_10) {
385 * Currently we only fully trace read(10) and write(10) commands
388 be32_to_cpu(lrbp->ucd_req_ptr->sc.exp_data_transfer_len);
389 if (opcode == WRITE_10)
390 group_id = lrbp->cmd->cmnd[6];
391 } else if (opcode == UNMAP) {
393 * The number of Bytes to be unmapped beginning with the lba.
395 transfer_len = blk_rq_bytes(rq);
398 intr = ufshcd_readl(hba, REG_INTERRUPT_STATUS);
399 doorbell = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
400 trace_ufshcd_command(dev_name(hba->dev), str_t, tag,
401 doorbell, transfer_len, intr, lba, opcode, group_id);
404 static void ufshcd_print_clk_freqs(struct ufs_hba *hba)
406 struct ufs_clk_info *clki;
407 struct list_head *head = &hba->clk_list_head;
409 if (list_empty(head))
412 list_for_each_entry(clki, head, list) {
413 if (!IS_ERR_OR_NULL(clki->clk) && clki->min_freq &&
415 dev_err(hba->dev, "clk: %s, rate: %u\n",
416 clki->name, clki->curr_freq);
420 static void ufshcd_print_evt(struct ufs_hba *hba, u32 id,
425 struct ufs_event_hist *e;
427 if (id >= UFS_EVT_CNT)
430 e = &hba->ufs_stats.event[id];
432 for (i = 0; i < UFS_EVENT_HIST_LENGTH; i++) {
433 int p = (i + e->pos) % UFS_EVENT_HIST_LENGTH;
435 if (e->tstamp[p] == 0)
437 dev_err(hba->dev, "%s[%d] = 0x%x at %lld us\n", err_name, p,
438 e->val[p], ktime_to_us(e->tstamp[p]));
443 dev_err(hba->dev, "No record of %s\n", err_name);
445 dev_err(hba->dev, "%s: total cnt=%llu\n", err_name, e->cnt);
448 static void ufshcd_print_evt_hist(struct ufs_hba *hba)
450 ufshcd_dump_regs(hba, 0, UFSHCI_REG_SPACE_SIZE, "host_regs: ");
452 ufshcd_print_evt(hba, UFS_EVT_PA_ERR, "pa_err");
453 ufshcd_print_evt(hba, UFS_EVT_DL_ERR, "dl_err");
454 ufshcd_print_evt(hba, UFS_EVT_NL_ERR, "nl_err");
455 ufshcd_print_evt(hba, UFS_EVT_TL_ERR, "tl_err");
456 ufshcd_print_evt(hba, UFS_EVT_DME_ERR, "dme_err");
457 ufshcd_print_evt(hba, UFS_EVT_AUTO_HIBERN8_ERR,
459 ufshcd_print_evt(hba, UFS_EVT_FATAL_ERR, "fatal_err");
460 ufshcd_print_evt(hba, UFS_EVT_LINK_STARTUP_FAIL,
461 "link_startup_fail");
462 ufshcd_print_evt(hba, UFS_EVT_RESUME_ERR, "resume_fail");
463 ufshcd_print_evt(hba, UFS_EVT_SUSPEND_ERR,
465 ufshcd_print_evt(hba, UFS_EVT_DEV_RESET, "dev_reset");
466 ufshcd_print_evt(hba, UFS_EVT_HOST_RESET, "host_reset");
467 ufshcd_print_evt(hba, UFS_EVT_ABORT, "task_abort");
469 ufshcd_vops_dbg_register_dump(hba);
473 void ufshcd_print_trs(struct ufs_hba *hba, unsigned long bitmap, bool pr_prdt)
475 struct ufshcd_lrb *lrbp;
479 for_each_set_bit(tag, &bitmap, hba->nutrs) {
480 lrbp = &hba->lrb[tag];
482 dev_err(hba->dev, "UPIU[%d] - issue time %lld us\n",
483 tag, ktime_to_us(lrbp->issue_time_stamp));
484 dev_err(hba->dev, "UPIU[%d] - complete time %lld us\n",
485 tag, ktime_to_us(lrbp->compl_time_stamp));
487 "UPIU[%d] - Transfer Request Descriptor phys@0x%llx\n",
488 tag, (u64)lrbp->utrd_dma_addr);
490 ufshcd_hex_dump("UPIU TRD: ", lrbp->utr_descriptor_ptr,
491 sizeof(struct utp_transfer_req_desc));
492 dev_err(hba->dev, "UPIU[%d] - Request UPIU phys@0x%llx\n", tag,
493 (u64)lrbp->ucd_req_dma_addr);
494 ufshcd_hex_dump("UPIU REQ: ", lrbp->ucd_req_ptr,
495 sizeof(struct utp_upiu_req));
496 dev_err(hba->dev, "UPIU[%d] - Response UPIU phys@0x%llx\n", tag,
497 (u64)lrbp->ucd_rsp_dma_addr);
498 ufshcd_hex_dump("UPIU RSP: ", lrbp->ucd_rsp_ptr,
499 sizeof(struct utp_upiu_rsp));
501 prdt_length = le16_to_cpu(
502 lrbp->utr_descriptor_ptr->prd_table_length);
503 if (hba->quirks & UFSHCD_QUIRK_PRDT_BYTE_GRAN)
504 prdt_length /= sizeof(struct ufshcd_sg_entry);
507 "UPIU[%d] - PRDT - %d entries phys@0x%llx\n",
509 (u64)lrbp->ucd_prdt_dma_addr);
512 ufshcd_hex_dump("UPIU PRDT: ", lrbp->ucd_prdt_ptr,
513 sizeof(struct ufshcd_sg_entry) * prdt_length);
517 static void ufshcd_print_tmrs(struct ufs_hba *hba, unsigned long bitmap)
521 for_each_set_bit(tag, &bitmap, hba->nutmrs) {
522 struct utp_task_req_desc *tmrdp = &hba->utmrdl_base_addr[tag];
524 dev_err(hba->dev, "TM[%d] - Task Management Header\n", tag);
525 ufshcd_hex_dump("", tmrdp, sizeof(*tmrdp));
529 static void ufshcd_print_host_state(struct ufs_hba *hba)
531 struct scsi_device *sdev_ufs = hba->sdev_ufs_device;
533 dev_err(hba->dev, "UFS Host state=%d\n", hba->ufshcd_state);
534 dev_err(hba->dev, "outstanding reqs=0x%lx tasks=0x%lx\n",
535 hba->outstanding_reqs, hba->outstanding_tasks);
536 dev_err(hba->dev, "saved_err=0x%x, saved_uic_err=0x%x\n",
537 hba->saved_err, hba->saved_uic_err);
538 dev_err(hba->dev, "Device power mode=%d, UIC link state=%d\n",
539 hba->curr_dev_pwr_mode, hba->uic_link_state);
540 dev_err(hba->dev, "PM in progress=%d, sys. suspended=%d\n",
541 hba->pm_op_in_progress, hba->is_sys_suspended);
542 dev_err(hba->dev, "Auto BKOPS=%d, Host self-block=%d\n",
543 hba->auto_bkops_enabled, hba->host->host_self_blocked);
544 dev_err(hba->dev, "Clk gate=%d\n", hba->clk_gating.state);
546 "last_hibern8_exit_tstamp at %lld us, hibern8_exit_cnt=%d\n",
547 ktime_to_us(hba->ufs_stats.last_hibern8_exit_tstamp),
548 hba->ufs_stats.hibern8_exit_cnt);
549 dev_err(hba->dev, "last intr at %lld us, last intr status=0x%x\n",
550 ktime_to_us(hba->ufs_stats.last_intr_ts),
551 hba->ufs_stats.last_intr_status);
552 dev_err(hba->dev, "error handling flags=0x%x, req. abort count=%d\n",
553 hba->eh_flags, hba->req_abort_count);
554 dev_err(hba->dev, "hba->ufs_version=0x%x, Host capabilities=0x%x, caps=0x%x\n",
555 hba->ufs_version, hba->capabilities, hba->caps);
556 dev_err(hba->dev, "quirks=0x%x, dev. quirks=0x%x\n", hba->quirks,
559 dev_err(hba->dev, "UFS dev info: %.8s %.16s rev %.4s\n",
560 sdev_ufs->vendor, sdev_ufs->model, sdev_ufs->rev);
562 ufshcd_print_clk_freqs(hba);
566 * ufshcd_print_pwr_info - print power params as saved in hba
568 * @hba: per-adapter instance
570 static void ufshcd_print_pwr_info(struct ufs_hba *hba)
572 static const char * const names[] = {
582 dev_err(hba->dev, "%s:[RX, TX]: gear=[%d, %d], lane[%d, %d], pwr[%s, %s], rate = %d\n",
584 hba->pwr_info.gear_rx, hba->pwr_info.gear_tx,
585 hba->pwr_info.lane_rx, hba->pwr_info.lane_tx,
586 names[hba->pwr_info.pwr_rx],
587 names[hba->pwr_info.pwr_tx],
588 hba->pwr_info.hs_rate);
591 static void ufshcd_device_reset(struct ufs_hba *hba)
595 err = ufshcd_vops_device_reset(hba);
598 ufshcd_set_ufs_dev_active(hba);
599 if (ufshcd_is_wb_allowed(hba)) {
600 hba->dev_info.wb_enabled = false;
601 hba->dev_info.wb_buf_flush_enabled = false;
604 if (err != -EOPNOTSUPP)
605 ufshcd_update_evt_hist(hba, UFS_EVT_DEV_RESET, err);
608 void ufshcd_delay_us(unsigned long us, unsigned long tolerance)
616 usleep_range(us, us + tolerance);
618 EXPORT_SYMBOL_GPL(ufshcd_delay_us);
621 * ufshcd_wait_for_register - wait for register value to change
622 * @hba: per-adapter interface
623 * @reg: mmio register offset
624 * @mask: mask to apply to the read register value
625 * @val: value to wait for
626 * @interval_us: polling interval in microseconds
627 * @timeout_ms: timeout in milliseconds
630 * -ETIMEDOUT on error, zero on success.
632 int ufshcd_wait_for_register(struct ufs_hba *hba, u32 reg, u32 mask,
633 u32 val, unsigned long interval_us,
634 unsigned long timeout_ms)
637 unsigned long timeout = jiffies + msecs_to_jiffies(timeout_ms);
639 /* ignore bits that we don't intend to wait on */
642 while ((ufshcd_readl(hba, reg) & mask) != val) {
643 usleep_range(interval_us, interval_us + 50);
644 if (time_after(jiffies, timeout)) {
645 if ((ufshcd_readl(hba, reg) & mask) != val)
655 * ufshcd_get_intr_mask - Get the interrupt bit mask
656 * @hba: Pointer to adapter instance
658 * Returns interrupt bit mask per version
660 static inline u32 ufshcd_get_intr_mask(struct ufs_hba *hba)
662 if (hba->ufs_version == ufshci_version(1, 0))
663 return INTERRUPT_MASK_ALL_VER_10;
664 if (hba->ufs_version <= ufshci_version(2, 0))
665 return INTERRUPT_MASK_ALL_VER_11;
667 return INTERRUPT_MASK_ALL_VER_21;
671 * ufshcd_get_ufs_version - Get the UFS version supported by the HBA
672 * @hba: Pointer to adapter instance
674 * Returns UFSHCI version supported by the controller
676 static inline u32 ufshcd_get_ufs_version(struct ufs_hba *hba)
680 if (hba->quirks & UFSHCD_QUIRK_BROKEN_UFS_HCI_VERSION)
681 ufshci_ver = ufshcd_vops_get_ufs_hci_version(hba);
683 ufshci_ver = ufshcd_readl(hba, REG_UFS_VERSION);
686 * UFSHCI v1.x uses a different version scheme, in order
687 * to allow the use of comparisons with the ufshci_version
688 * function, we convert it to the same scheme as ufs 2.0+.
690 if (ufshci_ver & 0x00010000)
691 return ufshci_version(1, ufshci_ver & 0x00000100);
697 * ufshcd_is_device_present - Check if any device connected to
698 * the host controller
699 * @hba: pointer to adapter instance
701 * Returns true if device present, false if no device detected
703 static inline bool ufshcd_is_device_present(struct ufs_hba *hba)
705 return (ufshcd_readl(hba, REG_CONTROLLER_STATUS) &
706 DEVICE_PRESENT) ? true : false;
710 * ufshcd_get_tr_ocs - Get the UTRD Overall Command Status
711 * @lrbp: pointer to local command reference block
713 * This function is used to get the OCS field from UTRD
714 * Returns the OCS field in the UTRD
716 static inline int ufshcd_get_tr_ocs(struct ufshcd_lrb *lrbp)
718 return le32_to_cpu(lrbp->utr_descriptor_ptr->header.dword_2) & MASK_OCS;
722 * ufshcd_utrl_clear - Clear a bit in UTRLCLR register
723 * @hba: per adapter instance
724 * @pos: position of the bit to be cleared
726 static inline void ufshcd_utrl_clear(struct ufs_hba *hba, u32 pos)
728 if (hba->quirks & UFSHCI_QUIRK_BROKEN_REQ_LIST_CLR)
729 ufshcd_writel(hba, (1 << pos), REG_UTP_TRANSFER_REQ_LIST_CLEAR);
731 ufshcd_writel(hba, ~(1 << pos),
732 REG_UTP_TRANSFER_REQ_LIST_CLEAR);
736 * ufshcd_utmrl_clear - Clear a bit in UTRMLCLR register
737 * @hba: per adapter instance
738 * @pos: position of the bit to be cleared
740 static inline void ufshcd_utmrl_clear(struct ufs_hba *hba, u32 pos)
742 if (hba->quirks & UFSHCI_QUIRK_BROKEN_REQ_LIST_CLR)
743 ufshcd_writel(hba, (1 << pos), REG_UTP_TASK_REQ_LIST_CLEAR);
745 ufshcd_writel(hba, ~(1 << pos), REG_UTP_TASK_REQ_LIST_CLEAR);
749 * ufshcd_get_lists_status - Check UCRDY, UTRLRDY and UTMRLRDY
750 * @reg: Register value of host controller status
752 * Returns integer, 0 on Success and positive value if failed
754 static inline int ufshcd_get_lists_status(u32 reg)
756 return !((reg & UFSHCD_STATUS_READY) == UFSHCD_STATUS_READY);
760 * ufshcd_get_uic_cmd_result - Get the UIC command result
761 * @hba: Pointer to adapter instance
763 * This function gets the result of UIC command completion
764 * Returns 0 on success, non zero value on error
766 static inline int ufshcd_get_uic_cmd_result(struct ufs_hba *hba)
768 return ufshcd_readl(hba, REG_UIC_COMMAND_ARG_2) &
769 MASK_UIC_COMMAND_RESULT;
773 * ufshcd_get_dme_attr_val - Get the value of attribute returned by UIC command
774 * @hba: Pointer to adapter instance
776 * This function gets UIC command argument3
777 * Returns 0 on success, non zero value on error
779 static inline u32 ufshcd_get_dme_attr_val(struct ufs_hba *hba)
781 return ufshcd_readl(hba, REG_UIC_COMMAND_ARG_3);
785 * ufshcd_get_req_rsp - returns the TR response transaction type
786 * @ucd_rsp_ptr: pointer to response UPIU
789 ufshcd_get_req_rsp(struct utp_upiu_rsp *ucd_rsp_ptr)
791 return be32_to_cpu(ucd_rsp_ptr->header.dword_0) >> 24;
795 * ufshcd_get_rsp_upiu_result - Get the result from response UPIU
796 * @ucd_rsp_ptr: pointer to response UPIU
798 * This function gets the response status and scsi_status from response UPIU
799 * Returns the response result code.
802 ufshcd_get_rsp_upiu_result(struct utp_upiu_rsp *ucd_rsp_ptr)
804 return be32_to_cpu(ucd_rsp_ptr->header.dword_1) & MASK_RSP_UPIU_RESULT;
808 * ufshcd_get_rsp_upiu_data_seg_len - Get the data segment length
810 * @ucd_rsp_ptr: pointer to response UPIU
812 * Return the data segment length.
814 static inline unsigned int
815 ufshcd_get_rsp_upiu_data_seg_len(struct utp_upiu_rsp *ucd_rsp_ptr)
817 return be32_to_cpu(ucd_rsp_ptr->header.dword_2) &
818 MASK_RSP_UPIU_DATA_SEG_LEN;
822 * ufshcd_is_exception_event - Check if the device raised an exception event
823 * @ucd_rsp_ptr: pointer to response UPIU
825 * The function checks if the device raised an exception event indicated in
826 * the Device Information field of response UPIU.
828 * Returns true if exception is raised, false otherwise.
830 static inline bool ufshcd_is_exception_event(struct utp_upiu_rsp *ucd_rsp_ptr)
832 return be32_to_cpu(ucd_rsp_ptr->header.dword_2) &
833 MASK_RSP_EXCEPTION_EVENT ? true : false;
837 * ufshcd_reset_intr_aggr - Reset interrupt aggregation values.
838 * @hba: per adapter instance
841 ufshcd_reset_intr_aggr(struct ufs_hba *hba)
843 ufshcd_writel(hba, INT_AGGR_ENABLE |
844 INT_AGGR_COUNTER_AND_TIMER_RESET,
845 REG_UTP_TRANSFER_REQ_INT_AGG_CONTROL);
849 * ufshcd_config_intr_aggr - Configure interrupt aggregation values.
850 * @hba: per adapter instance
851 * @cnt: Interrupt aggregation counter threshold
852 * @tmout: Interrupt aggregation timeout value
855 ufshcd_config_intr_aggr(struct ufs_hba *hba, u8 cnt, u8 tmout)
857 ufshcd_writel(hba, INT_AGGR_ENABLE | INT_AGGR_PARAM_WRITE |
858 INT_AGGR_COUNTER_THLD_VAL(cnt) |
859 INT_AGGR_TIMEOUT_VAL(tmout),
860 REG_UTP_TRANSFER_REQ_INT_AGG_CONTROL);
864 * ufshcd_disable_intr_aggr - Disables interrupt aggregation.
865 * @hba: per adapter instance
867 static inline void ufshcd_disable_intr_aggr(struct ufs_hba *hba)
869 ufshcd_writel(hba, 0, REG_UTP_TRANSFER_REQ_INT_AGG_CONTROL);
873 * ufshcd_enable_run_stop_reg - Enable run-stop registers,
874 * When run-stop registers are set to 1, it indicates the
875 * host controller that it can process the requests
876 * @hba: per adapter instance
878 static void ufshcd_enable_run_stop_reg(struct ufs_hba *hba)
880 ufshcd_writel(hba, UTP_TASK_REQ_LIST_RUN_STOP_BIT,
881 REG_UTP_TASK_REQ_LIST_RUN_STOP);
882 ufshcd_writel(hba, UTP_TRANSFER_REQ_LIST_RUN_STOP_BIT,
883 REG_UTP_TRANSFER_REQ_LIST_RUN_STOP);
887 * ufshcd_hba_start - Start controller initialization sequence
888 * @hba: per adapter instance
890 static inline void ufshcd_hba_start(struct ufs_hba *hba)
892 u32 val = CONTROLLER_ENABLE;
894 if (ufshcd_crypto_enable(hba))
895 val |= CRYPTO_GENERAL_ENABLE;
897 ufshcd_writel(hba, val, REG_CONTROLLER_ENABLE);
901 * ufshcd_is_hba_active - Get controller state
902 * @hba: per adapter instance
904 * Returns false if controller is active, true otherwise
906 static inline bool ufshcd_is_hba_active(struct ufs_hba *hba)
908 return (ufshcd_readl(hba, REG_CONTROLLER_ENABLE) & CONTROLLER_ENABLE)
912 u32 ufshcd_get_local_unipro_ver(struct ufs_hba *hba)
914 /* HCI version 1.0 and 1.1 supports UniPro 1.41 */
915 if (hba->ufs_version <= ufshci_version(1, 1))
916 return UFS_UNIPRO_VER_1_41;
918 return UFS_UNIPRO_VER_1_6;
920 EXPORT_SYMBOL(ufshcd_get_local_unipro_ver);
922 static bool ufshcd_is_unipro_pa_params_tuning_req(struct ufs_hba *hba)
925 * If both host and device support UniPro ver1.6 or later, PA layer
926 * parameters tuning happens during link startup itself.
928 * We can manually tune PA layer parameters if either host or device
929 * doesn't support UniPro ver 1.6 or later. But to keep manual tuning
930 * logic simple, we will only do manual tuning if local unipro version
931 * doesn't support ver1.6 or later.
933 if (ufshcd_get_local_unipro_ver(hba) < UFS_UNIPRO_VER_1_6)
940 * ufshcd_set_clk_freq - set UFS controller clock frequencies
941 * @hba: per adapter instance
942 * @scale_up: If True, set max possible frequency othewise set low frequency
944 * Returns 0 if successful
945 * Returns < 0 for any other errors
947 static int ufshcd_set_clk_freq(struct ufs_hba *hba, bool scale_up)
950 struct ufs_clk_info *clki;
951 struct list_head *head = &hba->clk_list_head;
953 if (list_empty(head))
956 list_for_each_entry(clki, head, list) {
957 if (!IS_ERR_OR_NULL(clki->clk)) {
958 if (scale_up && clki->max_freq) {
959 if (clki->curr_freq == clki->max_freq)
962 ret = clk_set_rate(clki->clk, clki->max_freq);
964 dev_err(hba->dev, "%s: %s clk set rate(%dHz) failed, %d\n",
965 __func__, clki->name,
966 clki->max_freq, ret);
969 trace_ufshcd_clk_scaling(dev_name(hba->dev),
970 "scaled up", clki->name,
974 clki->curr_freq = clki->max_freq;
976 } else if (!scale_up && clki->min_freq) {
977 if (clki->curr_freq == clki->min_freq)
980 ret = clk_set_rate(clki->clk, clki->min_freq);
982 dev_err(hba->dev, "%s: %s clk set rate(%dHz) failed, %d\n",
983 __func__, clki->name,
984 clki->min_freq, ret);
987 trace_ufshcd_clk_scaling(dev_name(hba->dev),
988 "scaled down", clki->name,
991 clki->curr_freq = clki->min_freq;
994 dev_dbg(hba->dev, "%s: clk: %s, rate: %lu\n", __func__,
995 clki->name, clk_get_rate(clki->clk));
1003 * ufshcd_scale_clks - scale up or scale down UFS controller clocks
1004 * @hba: per adapter instance
1005 * @scale_up: True if scaling up and false if scaling down
1007 * Returns 0 if successful
1008 * Returns < 0 for any other errors
1010 static int ufshcd_scale_clks(struct ufs_hba *hba, bool scale_up)
1013 ktime_t start = ktime_get();
1015 ret = ufshcd_vops_clk_scale_notify(hba, scale_up, PRE_CHANGE);
1019 ret = ufshcd_set_clk_freq(hba, scale_up);
1023 ret = ufshcd_vops_clk_scale_notify(hba, scale_up, POST_CHANGE);
1025 ufshcd_set_clk_freq(hba, !scale_up);
1028 trace_ufshcd_profile_clk_scaling(dev_name(hba->dev),
1029 (scale_up ? "up" : "down"),
1030 ktime_to_us(ktime_sub(ktime_get(), start)), ret);
1035 * ufshcd_is_devfreq_scaling_required - check if scaling is required or not
1036 * @hba: per adapter instance
1037 * @scale_up: True if scaling up and false if scaling down
1039 * Returns true if scaling is required, false otherwise.
1041 static bool ufshcd_is_devfreq_scaling_required(struct ufs_hba *hba,
1044 struct ufs_clk_info *clki;
1045 struct list_head *head = &hba->clk_list_head;
1047 if (list_empty(head))
1050 list_for_each_entry(clki, head, list) {
1051 if (!IS_ERR_OR_NULL(clki->clk)) {
1052 if (scale_up && clki->max_freq) {
1053 if (clki->curr_freq == clki->max_freq)
1056 } else if (!scale_up && clki->min_freq) {
1057 if (clki->curr_freq == clki->min_freq)
1067 static int ufshcd_wait_for_doorbell_clr(struct ufs_hba *hba,
1068 u64 wait_timeout_us)
1070 unsigned long flags;
1074 bool timeout = false, do_last_check = false;
1077 ufshcd_hold(hba, false);
1078 spin_lock_irqsave(hba->host->host_lock, flags);
1080 * Wait for all the outstanding tasks/transfer requests.
1081 * Verify by checking the doorbell registers are clear.
1083 start = ktime_get();
1085 if (hba->ufshcd_state != UFSHCD_STATE_OPERATIONAL) {
1090 tm_doorbell = ufshcd_readl(hba, REG_UTP_TASK_REQ_DOOR_BELL);
1091 tr_doorbell = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
1092 if (!tm_doorbell && !tr_doorbell) {
1095 } else if (do_last_check) {
1099 spin_unlock_irqrestore(hba->host->host_lock, flags);
1101 if (ktime_to_us(ktime_sub(ktime_get(), start)) >
1105 * We might have scheduled out for long time so make
1106 * sure to check if doorbells are cleared by this time
1109 do_last_check = true;
1111 spin_lock_irqsave(hba->host->host_lock, flags);
1112 } while (tm_doorbell || tr_doorbell);
1116 "%s: timedout waiting for doorbell to clear (tm=0x%x, tr=0x%x)\n",
1117 __func__, tm_doorbell, tr_doorbell);
1121 spin_unlock_irqrestore(hba->host->host_lock, flags);
1122 ufshcd_release(hba);
1127 * ufshcd_scale_gear - scale up/down UFS gear
1128 * @hba: per adapter instance
1129 * @scale_up: True for scaling up gear and false for scaling down
1131 * Returns 0 for success,
1132 * Returns -EBUSY if scaling can't happen at this time
1133 * Returns non-zero for any other errors
1135 static int ufshcd_scale_gear(struct ufs_hba *hba, bool scale_up)
1138 struct ufs_pa_layer_attr new_pwr_info;
1141 memcpy(&new_pwr_info, &hba->clk_scaling.saved_pwr_info.info,
1142 sizeof(struct ufs_pa_layer_attr));
1144 memcpy(&new_pwr_info, &hba->pwr_info,
1145 sizeof(struct ufs_pa_layer_attr));
1147 if (hba->pwr_info.gear_tx > hba->clk_scaling.min_gear ||
1148 hba->pwr_info.gear_rx > hba->clk_scaling.min_gear) {
1149 /* save the current power mode */
1150 memcpy(&hba->clk_scaling.saved_pwr_info.info,
1152 sizeof(struct ufs_pa_layer_attr));
1154 /* scale down gear */
1155 new_pwr_info.gear_tx = hba->clk_scaling.min_gear;
1156 new_pwr_info.gear_rx = hba->clk_scaling.min_gear;
1160 /* check if the power mode needs to be changed or not? */
1161 ret = ufshcd_config_pwr_mode(hba, &new_pwr_info);
1163 dev_err(hba->dev, "%s: failed err %d, old gear: (tx %d rx %d), new gear: (tx %d rx %d)",
1165 hba->pwr_info.gear_tx, hba->pwr_info.gear_rx,
1166 new_pwr_info.gear_tx, new_pwr_info.gear_rx);
1171 static int ufshcd_clock_scaling_prepare(struct ufs_hba *hba)
1173 #define DOORBELL_CLR_TOUT_US (1000 * 1000) /* 1 sec */
1176 * make sure that there are no outstanding requests when
1177 * clock scaling is in progress
1179 ufshcd_scsi_block_requests(hba);
1180 down_write(&hba->clk_scaling_lock);
1182 if (!hba->clk_scaling.is_allowed ||
1183 ufshcd_wait_for_doorbell_clr(hba, DOORBELL_CLR_TOUT_US)) {
1185 up_write(&hba->clk_scaling_lock);
1186 ufshcd_scsi_unblock_requests(hba);
1190 /* let's not get into low power until clock scaling is completed */
1191 ufshcd_hold(hba, false);
1197 static void ufshcd_clock_scaling_unprepare(struct ufs_hba *hba, bool writelock)
1200 up_write(&hba->clk_scaling_lock);
1202 up_read(&hba->clk_scaling_lock);
1203 ufshcd_scsi_unblock_requests(hba);
1204 ufshcd_release(hba);
1208 * ufshcd_devfreq_scale - scale up/down UFS clocks and gear
1209 * @hba: per adapter instance
1210 * @scale_up: True for scaling up and false for scalin down
1212 * Returns 0 for success,
1213 * Returns -EBUSY if scaling can't happen at this time
1214 * Returns non-zero for any other errors
1216 static int ufshcd_devfreq_scale(struct ufs_hba *hba, bool scale_up)
1219 bool is_writelock = true;
1221 ret = ufshcd_clock_scaling_prepare(hba);
1225 /* scale down the gear before scaling down clocks */
1227 ret = ufshcd_scale_gear(hba, false);
1232 ret = ufshcd_scale_clks(hba, scale_up);
1235 ufshcd_scale_gear(hba, true);
1239 /* scale up the gear after scaling up clocks */
1241 ret = ufshcd_scale_gear(hba, true);
1243 ufshcd_scale_clks(hba, false);
1248 /* Enable Write Booster if we have scaled up else disable it */
1249 downgrade_write(&hba->clk_scaling_lock);
1250 is_writelock = false;
1251 ufshcd_wb_toggle(hba, scale_up);
1254 ufshcd_clock_scaling_unprepare(hba, is_writelock);
1258 static void ufshcd_clk_scaling_suspend_work(struct work_struct *work)
1260 struct ufs_hba *hba = container_of(work, struct ufs_hba,
1261 clk_scaling.suspend_work);
1262 unsigned long irq_flags;
1264 spin_lock_irqsave(hba->host->host_lock, irq_flags);
1265 if (hba->clk_scaling.active_reqs || hba->clk_scaling.is_suspended) {
1266 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1269 hba->clk_scaling.is_suspended = true;
1270 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1272 __ufshcd_suspend_clkscaling(hba);
1275 static void ufshcd_clk_scaling_resume_work(struct work_struct *work)
1277 struct ufs_hba *hba = container_of(work, struct ufs_hba,
1278 clk_scaling.resume_work);
1279 unsigned long irq_flags;
1281 spin_lock_irqsave(hba->host->host_lock, irq_flags);
1282 if (!hba->clk_scaling.is_suspended) {
1283 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1286 hba->clk_scaling.is_suspended = false;
1287 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1289 devfreq_resume_device(hba->devfreq);
1292 static int ufshcd_devfreq_target(struct device *dev,
1293 unsigned long *freq, u32 flags)
1296 struct ufs_hba *hba = dev_get_drvdata(dev);
1298 bool scale_up, sched_clk_scaling_suspend_work = false;
1299 struct list_head *clk_list = &hba->clk_list_head;
1300 struct ufs_clk_info *clki;
1301 unsigned long irq_flags;
1303 if (!ufshcd_is_clkscaling_supported(hba))
1306 clki = list_first_entry(&hba->clk_list_head, struct ufs_clk_info, list);
1307 /* Override with the closest supported frequency */
1308 *freq = (unsigned long) clk_round_rate(clki->clk, *freq);
1309 spin_lock_irqsave(hba->host->host_lock, irq_flags);
1310 if (ufshcd_eh_in_progress(hba)) {
1311 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1315 if (!hba->clk_scaling.active_reqs)
1316 sched_clk_scaling_suspend_work = true;
1318 if (list_empty(clk_list)) {
1319 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1323 /* Decide based on the rounded-off frequency and update */
1324 scale_up = (*freq == clki->max_freq) ? true : false;
1326 *freq = clki->min_freq;
1327 /* Update the frequency */
1328 if (!ufshcd_is_devfreq_scaling_required(hba, scale_up)) {
1329 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1331 goto out; /* no state change required */
1333 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1335 start = ktime_get();
1336 ret = ufshcd_devfreq_scale(hba, scale_up);
1338 trace_ufshcd_profile_clk_scaling(dev_name(hba->dev),
1339 (scale_up ? "up" : "down"),
1340 ktime_to_us(ktime_sub(ktime_get(), start)), ret);
1343 if (sched_clk_scaling_suspend_work)
1344 queue_work(hba->clk_scaling.workq,
1345 &hba->clk_scaling.suspend_work);
1350 static bool ufshcd_is_busy(struct request *req, void *priv, bool reserved)
1354 WARN_ON_ONCE(reserved);
1359 /* Whether or not any tag is in use by a request that is in progress. */
1360 static bool ufshcd_any_tag_in_use(struct ufs_hba *hba)
1362 struct request_queue *q = hba->cmd_queue;
1365 blk_mq_tagset_busy_iter(q->tag_set, ufshcd_is_busy, &busy);
1369 static int ufshcd_devfreq_get_dev_status(struct device *dev,
1370 struct devfreq_dev_status *stat)
1372 struct ufs_hba *hba = dev_get_drvdata(dev);
1373 struct ufs_clk_scaling *scaling = &hba->clk_scaling;
1374 unsigned long flags;
1375 struct list_head *clk_list = &hba->clk_list_head;
1376 struct ufs_clk_info *clki;
1379 if (!ufshcd_is_clkscaling_supported(hba))
1382 memset(stat, 0, sizeof(*stat));
1384 spin_lock_irqsave(hba->host->host_lock, flags);
1385 curr_t = ktime_get();
1386 if (!scaling->window_start_t)
1389 clki = list_first_entry(clk_list, struct ufs_clk_info, list);
1391 * If current frequency is 0, then the ondemand governor considers
1392 * there's no initial frequency set. And it always requests to set
1393 * to max. frequency.
1395 stat->current_frequency = clki->curr_freq;
1396 if (scaling->is_busy_started)
1397 scaling->tot_busy_t += ktime_us_delta(curr_t,
1398 scaling->busy_start_t);
1400 stat->total_time = ktime_us_delta(curr_t, scaling->window_start_t);
1401 stat->busy_time = scaling->tot_busy_t;
1403 scaling->window_start_t = curr_t;
1404 scaling->tot_busy_t = 0;
1406 if (hba->outstanding_reqs) {
1407 scaling->busy_start_t = curr_t;
1408 scaling->is_busy_started = true;
1410 scaling->busy_start_t = 0;
1411 scaling->is_busy_started = false;
1413 spin_unlock_irqrestore(hba->host->host_lock, flags);
1417 static int ufshcd_devfreq_init(struct ufs_hba *hba)
1419 struct list_head *clk_list = &hba->clk_list_head;
1420 struct ufs_clk_info *clki;
1421 struct devfreq *devfreq;
1424 /* Skip devfreq if we don't have any clocks in the list */
1425 if (list_empty(clk_list))
1428 clki = list_first_entry(clk_list, struct ufs_clk_info, list);
1429 dev_pm_opp_add(hba->dev, clki->min_freq, 0);
1430 dev_pm_opp_add(hba->dev, clki->max_freq, 0);
1432 ufshcd_vops_config_scaling_param(hba, &hba->vps->devfreq_profile,
1433 &hba->vps->ondemand_data);
1434 devfreq = devfreq_add_device(hba->dev,
1435 &hba->vps->devfreq_profile,
1436 DEVFREQ_GOV_SIMPLE_ONDEMAND,
1437 &hba->vps->ondemand_data);
1438 if (IS_ERR(devfreq)) {
1439 ret = PTR_ERR(devfreq);
1440 dev_err(hba->dev, "Unable to register with devfreq %d\n", ret);
1442 dev_pm_opp_remove(hba->dev, clki->min_freq);
1443 dev_pm_opp_remove(hba->dev, clki->max_freq);
1447 hba->devfreq = devfreq;
1452 static void ufshcd_devfreq_remove(struct ufs_hba *hba)
1454 struct list_head *clk_list = &hba->clk_list_head;
1455 struct ufs_clk_info *clki;
1460 devfreq_remove_device(hba->devfreq);
1461 hba->devfreq = NULL;
1463 clki = list_first_entry(clk_list, struct ufs_clk_info, list);
1464 dev_pm_opp_remove(hba->dev, clki->min_freq);
1465 dev_pm_opp_remove(hba->dev, clki->max_freq);
1468 static void __ufshcd_suspend_clkscaling(struct ufs_hba *hba)
1470 unsigned long flags;
1472 devfreq_suspend_device(hba->devfreq);
1473 spin_lock_irqsave(hba->host->host_lock, flags);
1474 hba->clk_scaling.window_start_t = 0;
1475 spin_unlock_irqrestore(hba->host->host_lock, flags);
1478 static void ufshcd_suspend_clkscaling(struct ufs_hba *hba)
1480 unsigned long flags;
1481 bool suspend = false;
1483 cancel_work_sync(&hba->clk_scaling.suspend_work);
1484 cancel_work_sync(&hba->clk_scaling.resume_work);
1486 spin_lock_irqsave(hba->host->host_lock, flags);
1487 if (!hba->clk_scaling.is_suspended) {
1489 hba->clk_scaling.is_suspended = true;
1491 spin_unlock_irqrestore(hba->host->host_lock, flags);
1494 __ufshcd_suspend_clkscaling(hba);
1497 static void ufshcd_resume_clkscaling(struct ufs_hba *hba)
1499 unsigned long flags;
1500 bool resume = false;
1502 spin_lock_irqsave(hba->host->host_lock, flags);
1503 if (hba->clk_scaling.is_suspended) {
1505 hba->clk_scaling.is_suspended = false;
1507 spin_unlock_irqrestore(hba->host->host_lock, flags);
1510 devfreq_resume_device(hba->devfreq);
1513 static ssize_t ufshcd_clkscale_enable_show(struct device *dev,
1514 struct device_attribute *attr, char *buf)
1516 struct ufs_hba *hba = dev_get_drvdata(dev);
1518 return sysfs_emit(buf, "%d\n", hba->clk_scaling.is_enabled);
1521 static ssize_t ufshcd_clkscale_enable_store(struct device *dev,
1522 struct device_attribute *attr, const char *buf, size_t count)
1524 struct ufs_hba *hba = dev_get_drvdata(dev);
1528 if (kstrtou32(buf, 0, &value))
1531 down(&hba->host_sem);
1532 if (!ufshcd_is_user_access_allowed(hba)) {
1538 if (value == hba->clk_scaling.is_enabled)
1541 ufshcd_rpm_get_sync(hba);
1542 ufshcd_hold(hba, false);
1544 hba->clk_scaling.is_enabled = value;
1547 ufshcd_resume_clkscaling(hba);
1549 ufshcd_suspend_clkscaling(hba);
1550 err = ufshcd_devfreq_scale(hba, true);
1552 dev_err(hba->dev, "%s: failed to scale clocks up %d\n",
1556 ufshcd_release(hba);
1557 ufshcd_rpm_put_sync(hba);
1560 return err ? err : count;
1563 static void ufshcd_init_clk_scaling_sysfs(struct ufs_hba *hba)
1565 hba->clk_scaling.enable_attr.show = ufshcd_clkscale_enable_show;
1566 hba->clk_scaling.enable_attr.store = ufshcd_clkscale_enable_store;
1567 sysfs_attr_init(&hba->clk_scaling.enable_attr.attr);
1568 hba->clk_scaling.enable_attr.attr.name = "clkscale_enable";
1569 hba->clk_scaling.enable_attr.attr.mode = 0644;
1570 if (device_create_file(hba->dev, &hba->clk_scaling.enable_attr))
1571 dev_err(hba->dev, "Failed to create sysfs for clkscale_enable\n");
1574 static void ufshcd_remove_clk_scaling_sysfs(struct ufs_hba *hba)
1576 if (hba->clk_scaling.enable_attr.attr.name)
1577 device_remove_file(hba->dev, &hba->clk_scaling.enable_attr);
1580 static void ufshcd_init_clk_scaling(struct ufs_hba *hba)
1582 char wq_name[sizeof("ufs_clkscaling_00")];
1584 if (!ufshcd_is_clkscaling_supported(hba))
1587 if (!hba->clk_scaling.min_gear)
1588 hba->clk_scaling.min_gear = UFS_HS_G1;
1590 INIT_WORK(&hba->clk_scaling.suspend_work,
1591 ufshcd_clk_scaling_suspend_work);
1592 INIT_WORK(&hba->clk_scaling.resume_work,
1593 ufshcd_clk_scaling_resume_work);
1595 snprintf(wq_name, sizeof(wq_name), "ufs_clkscaling_%d",
1596 hba->host->host_no);
1597 hba->clk_scaling.workq = create_singlethread_workqueue(wq_name);
1599 hba->clk_scaling.is_initialized = true;
1602 static void ufshcd_exit_clk_scaling(struct ufs_hba *hba)
1604 if (!hba->clk_scaling.is_initialized)
1607 ufshcd_remove_clk_scaling_sysfs(hba);
1608 destroy_workqueue(hba->clk_scaling.workq);
1609 ufshcd_devfreq_remove(hba);
1610 hba->clk_scaling.is_initialized = false;
1613 static void ufshcd_ungate_work(struct work_struct *work)
1616 unsigned long flags;
1617 struct ufs_hba *hba = container_of(work, struct ufs_hba,
1618 clk_gating.ungate_work);
1620 cancel_delayed_work_sync(&hba->clk_gating.gate_work);
1622 spin_lock_irqsave(hba->host->host_lock, flags);
1623 if (hba->clk_gating.state == CLKS_ON) {
1624 spin_unlock_irqrestore(hba->host->host_lock, flags);
1628 spin_unlock_irqrestore(hba->host->host_lock, flags);
1629 ufshcd_hba_vreg_set_hpm(hba);
1630 ufshcd_setup_clocks(hba, true);
1632 ufshcd_enable_irq(hba);
1634 /* Exit from hibern8 */
1635 if (ufshcd_can_hibern8_during_gating(hba)) {
1636 /* Prevent gating in this path */
1637 hba->clk_gating.is_suspended = true;
1638 if (ufshcd_is_link_hibern8(hba)) {
1639 ret = ufshcd_uic_hibern8_exit(hba);
1641 dev_err(hba->dev, "%s: hibern8 exit failed %d\n",
1644 ufshcd_set_link_active(hba);
1646 hba->clk_gating.is_suspended = false;
1649 ufshcd_scsi_unblock_requests(hba);
1653 * ufshcd_hold - Enable clocks that were gated earlier due to ufshcd_release.
1654 * Also, exit from hibern8 mode and set the link as active.
1655 * @hba: per adapter instance
1656 * @async: This indicates whether caller should ungate clocks asynchronously.
1658 int ufshcd_hold(struct ufs_hba *hba, bool async)
1662 unsigned long flags;
1664 if (!ufshcd_is_clkgating_allowed(hba))
1666 spin_lock_irqsave(hba->host->host_lock, flags);
1667 hba->clk_gating.active_reqs++;
1670 switch (hba->clk_gating.state) {
1673 * Wait for the ungate work to complete if in progress.
1674 * Though the clocks may be in ON state, the link could
1675 * still be in hibner8 state if hibern8 is allowed
1676 * during clock gating.
1677 * Make sure we exit hibern8 state also in addition to
1680 if (ufshcd_can_hibern8_during_gating(hba) &&
1681 ufshcd_is_link_hibern8(hba)) {
1684 hba->clk_gating.active_reqs--;
1687 spin_unlock_irqrestore(hba->host->host_lock, flags);
1688 flush_result = flush_work(&hba->clk_gating.ungate_work);
1689 if (hba->clk_gating.is_suspended && !flush_result)
1691 spin_lock_irqsave(hba->host->host_lock, flags);
1696 if (cancel_delayed_work(&hba->clk_gating.gate_work)) {
1697 hba->clk_gating.state = CLKS_ON;
1698 trace_ufshcd_clk_gating(dev_name(hba->dev),
1699 hba->clk_gating.state);
1703 * If we are here, it means gating work is either done or
1704 * currently running. Hence, fall through to cancel gating
1705 * work and to enable clocks.
1709 hba->clk_gating.state = REQ_CLKS_ON;
1710 trace_ufshcd_clk_gating(dev_name(hba->dev),
1711 hba->clk_gating.state);
1712 if (queue_work(hba->clk_gating.clk_gating_workq,
1713 &hba->clk_gating.ungate_work))
1714 ufshcd_scsi_block_requests(hba);
1716 * fall through to check if we should wait for this
1717 * work to be done or not.
1723 hba->clk_gating.active_reqs--;
1727 spin_unlock_irqrestore(hba->host->host_lock, flags);
1728 flush_work(&hba->clk_gating.ungate_work);
1729 /* Make sure state is CLKS_ON before returning */
1730 spin_lock_irqsave(hba->host->host_lock, flags);
1733 dev_err(hba->dev, "%s: clk gating is in invalid state %d\n",
1734 __func__, hba->clk_gating.state);
1737 spin_unlock_irqrestore(hba->host->host_lock, flags);
1741 EXPORT_SYMBOL_GPL(ufshcd_hold);
1743 static void ufshcd_gate_work(struct work_struct *work)
1745 struct ufs_hba *hba = container_of(work, struct ufs_hba,
1746 clk_gating.gate_work.work);
1747 unsigned long flags;
1750 spin_lock_irqsave(hba->host->host_lock, flags);
1752 * In case you are here to cancel this work the gating state
1753 * would be marked as REQ_CLKS_ON. In this case save time by
1754 * skipping the gating work and exit after changing the clock
1757 if (hba->clk_gating.is_suspended ||
1758 (hba->clk_gating.state != REQ_CLKS_OFF)) {
1759 hba->clk_gating.state = CLKS_ON;
1760 trace_ufshcd_clk_gating(dev_name(hba->dev),
1761 hba->clk_gating.state);
1765 if (hba->clk_gating.active_reqs
1766 || hba->ufshcd_state != UFSHCD_STATE_OPERATIONAL
1767 || ufshcd_any_tag_in_use(hba) || hba->outstanding_tasks
1768 || hba->active_uic_cmd || hba->uic_async_done)
1771 spin_unlock_irqrestore(hba->host->host_lock, flags);
1773 /* put the link into hibern8 mode before turning off clocks */
1774 if (ufshcd_can_hibern8_during_gating(hba)) {
1775 ret = ufshcd_uic_hibern8_enter(hba);
1777 hba->clk_gating.state = CLKS_ON;
1778 dev_err(hba->dev, "%s: hibern8 enter failed %d\n",
1780 trace_ufshcd_clk_gating(dev_name(hba->dev),
1781 hba->clk_gating.state);
1784 ufshcd_set_link_hibern8(hba);
1787 ufshcd_disable_irq(hba);
1789 ufshcd_setup_clocks(hba, false);
1791 /* Put the host controller in low power mode if possible */
1792 ufshcd_hba_vreg_set_lpm(hba);
1794 * In case you are here to cancel this work the gating state
1795 * would be marked as REQ_CLKS_ON. In this case keep the state
1796 * as REQ_CLKS_ON which would anyway imply that clocks are off
1797 * and a request to turn them on is pending. By doing this way,
1798 * we keep the state machine in tact and this would ultimately
1799 * prevent from doing cancel work multiple times when there are
1800 * new requests arriving before the current cancel work is done.
1802 spin_lock_irqsave(hba->host->host_lock, flags);
1803 if (hba->clk_gating.state == REQ_CLKS_OFF) {
1804 hba->clk_gating.state = CLKS_OFF;
1805 trace_ufshcd_clk_gating(dev_name(hba->dev),
1806 hba->clk_gating.state);
1809 spin_unlock_irqrestore(hba->host->host_lock, flags);
1814 /* host lock must be held before calling this variant */
1815 static void __ufshcd_release(struct ufs_hba *hba)
1817 if (!ufshcd_is_clkgating_allowed(hba))
1820 hba->clk_gating.active_reqs--;
1822 if (hba->clk_gating.active_reqs || hba->clk_gating.is_suspended ||
1823 hba->ufshcd_state != UFSHCD_STATE_OPERATIONAL ||
1824 hba->outstanding_tasks ||
1825 hba->active_uic_cmd || hba->uic_async_done ||
1826 hba->clk_gating.state == CLKS_OFF)
1829 hba->clk_gating.state = REQ_CLKS_OFF;
1830 trace_ufshcd_clk_gating(dev_name(hba->dev), hba->clk_gating.state);
1831 queue_delayed_work(hba->clk_gating.clk_gating_workq,
1832 &hba->clk_gating.gate_work,
1833 msecs_to_jiffies(hba->clk_gating.delay_ms));
1836 void ufshcd_release(struct ufs_hba *hba)
1838 unsigned long flags;
1840 spin_lock_irqsave(hba->host->host_lock, flags);
1841 __ufshcd_release(hba);
1842 spin_unlock_irqrestore(hba->host->host_lock, flags);
1844 EXPORT_SYMBOL_GPL(ufshcd_release);
1846 static ssize_t ufshcd_clkgate_delay_show(struct device *dev,
1847 struct device_attribute *attr, char *buf)
1849 struct ufs_hba *hba = dev_get_drvdata(dev);
1851 return sysfs_emit(buf, "%lu\n", hba->clk_gating.delay_ms);
1854 static ssize_t ufshcd_clkgate_delay_store(struct device *dev,
1855 struct device_attribute *attr, const char *buf, size_t count)
1857 struct ufs_hba *hba = dev_get_drvdata(dev);
1858 unsigned long flags, value;
1860 if (kstrtoul(buf, 0, &value))
1863 spin_lock_irqsave(hba->host->host_lock, flags);
1864 hba->clk_gating.delay_ms = value;
1865 spin_unlock_irqrestore(hba->host->host_lock, flags);
1869 static ssize_t ufshcd_clkgate_enable_show(struct device *dev,
1870 struct device_attribute *attr, char *buf)
1872 struct ufs_hba *hba = dev_get_drvdata(dev);
1874 return sysfs_emit(buf, "%d\n", hba->clk_gating.is_enabled);
1877 static ssize_t ufshcd_clkgate_enable_store(struct device *dev,
1878 struct device_attribute *attr, const char *buf, size_t count)
1880 struct ufs_hba *hba = dev_get_drvdata(dev);
1881 unsigned long flags;
1884 if (kstrtou32(buf, 0, &value))
1889 spin_lock_irqsave(hba->host->host_lock, flags);
1890 if (value == hba->clk_gating.is_enabled)
1894 __ufshcd_release(hba);
1896 hba->clk_gating.active_reqs++;
1898 hba->clk_gating.is_enabled = value;
1900 spin_unlock_irqrestore(hba->host->host_lock, flags);
1904 static void ufshcd_init_clk_gating_sysfs(struct ufs_hba *hba)
1906 hba->clk_gating.delay_attr.show = ufshcd_clkgate_delay_show;
1907 hba->clk_gating.delay_attr.store = ufshcd_clkgate_delay_store;
1908 sysfs_attr_init(&hba->clk_gating.delay_attr.attr);
1909 hba->clk_gating.delay_attr.attr.name = "clkgate_delay_ms";
1910 hba->clk_gating.delay_attr.attr.mode = 0644;
1911 if (device_create_file(hba->dev, &hba->clk_gating.delay_attr))
1912 dev_err(hba->dev, "Failed to create sysfs for clkgate_delay\n");
1914 hba->clk_gating.enable_attr.show = ufshcd_clkgate_enable_show;
1915 hba->clk_gating.enable_attr.store = ufshcd_clkgate_enable_store;
1916 sysfs_attr_init(&hba->clk_gating.enable_attr.attr);
1917 hba->clk_gating.enable_attr.attr.name = "clkgate_enable";
1918 hba->clk_gating.enable_attr.attr.mode = 0644;
1919 if (device_create_file(hba->dev, &hba->clk_gating.enable_attr))
1920 dev_err(hba->dev, "Failed to create sysfs for clkgate_enable\n");
1923 static void ufshcd_remove_clk_gating_sysfs(struct ufs_hba *hba)
1925 if (hba->clk_gating.delay_attr.attr.name)
1926 device_remove_file(hba->dev, &hba->clk_gating.delay_attr);
1927 if (hba->clk_gating.enable_attr.attr.name)
1928 device_remove_file(hba->dev, &hba->clk_gating.enable_attr);
1931 static void ufshcd_init_clk_gating(struct ufs_hba *hba)
1933 char wq_name[sizeof("ufs_clk_gating_00")];
1935 if (!ufshcd_is_clkgating_allowed(hba))
1938 hba->clk_gating.state = CLKS_ON;
1940 hba->clk_gating.delay_ms = 150;
1941 INIT_DELAYED_WORK(&hba->clk_gating.gate_work, ufshcd_gate_work);
1942 INIT_WORK(&hba->clk_gating.ungate_work, ufshcd_ungate_work);
1944 snprintf(wq_name, ARRAY_SIZE(wq_name), "ufs_clk_gating_%d",
1945 hba->host->host_no);
1946 hba->clk_gating.clk_gating_workq = alloc_ordered_workqueue(wq_name,
1947 WQ_MEM_RECLAIM | WQ_HIGHPRI);
1949 ufshcd_init_clk_gating_sysfs(hba);
1951 hba->clk_gating.is_enabled = true;
1952 hba->clk_gating.is_initialized = true;
1955 static void ufshcd_exit_clk_gating(struct ufs_hba *hba)
1957 if (!hba->clk_gating.is_initialized)
1959 ufshcd_remove_clk_gating_sysfs(hba);
1960 cancel_work_sync(&hba->clk_gating.ungate_work);
1961 cancel_delayed_work_sync(&hba->clk_gating.gate_work);
1962 destroy_workqueue(hba->clk_gating.clk_gating_workq);
1963 hba->clk_gating.is_initialized = false;
1966 /* Must be called with host lock acquired */
1967 static void ufshcd_clk_scaling_start_busy(struct ufs_hba *hba)
1969 bool queue_resume_work = false;
1970 ktime_t curr_t = ktime_get();
1971 unsigned long flags;
1973 if (!ufshcd_is_clkscaling_supported(hba))
1976 spin_lock_irqsave(hba->host->host_lock, flags);
1977 if (!hba->clk_scaling.active_reqs++)
1978 queue_resume_work = true;
1980 if (!hba->clk_scaling.is_enabled || hba->pm_op_in_progress) {
1981 spin_unlock_irqrestore(hba->host->host_lock, flags);
1985 if (queue_resume_work)
1986 queue_work(hba->clk_scaling.workq,
1987 &hba->clk_scaling.resume_work);
1989 if (!hba->clk_scaling.window_start_t) {
1990 hba->clk_scaling.window_start_t = curr_t;
1991 hba->clk_scaling.tot_busy_t = 0;
1992 hba->clk_scaling.is_busy_started = false;
1995 if (!hba->clk_scaling.is_busy_started) {
1996 hba->clk_scaling.busy_start_t = curr_t;
1997 hba->clk_scaling.is_busy_started = true;
1999 spin_unlock_irqrestore(hba->host->host_lock, flags);
2002 static void ufshcd_clk_scaling_update_busy(struct ufs_hba *hba)
2004 struct ufs_clk_scaling *scaling = &hba->clk_scaling;
2005 unsigned long flags;
2007 if (!ufshcd_is_clkscaling_supported(hba))
2010 spin_lock_irqsave(hba->host->host_lock, flags);
2011 hba->clk_scaling.active_reqs--;
2012 if (!hba->outstanding_reqs && scaling->is_busy_started) {
2013 scaling->tot_busy_t += ktime_to_us(ktime_sub(ktime_get(),
2014 scaling->busy_start_t));
2015 scaling->busy_start_t = 0;
2016 scaling->is_busy_started = false;
2018 spin_unlock_irqrestore(hba->host->host_lock, flags);
2021 static inline int ufshcd_monitor_opcode2dir(u8 opcode)
2023 if (opcode == READ_6 || opcode == READ_10 || opcode == READ_16)
2025 else if (opcode == WRITE_6 || opcode == WRITE_10 || opcode == WRITE_16)
2031 static inline bool ufshcd_should_inform_monitor(struct ufs_hba *hba,
2032 struct ufshcd_lrb *lrbp)
2034 struct ufs_hba_monitor *m = &hba->monitor;
2036 return (m->enabled && lrbp && lrbp->cmd &&
2037 (!m->chunk_size || m->chunk_size == lrbp->cmd->sdb.length) &&
2038 ktime_before(hba->monitor.enabled_ts, lrbp->issue_time_stamp));
2041 static void ufshcd_start_monitor(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
2043 int dir = ufshcd_monitor_opcode2dir(*lrbp->cmd->cmnd);
2044 unsigned long flags;
2046 spin_lock_irqsave(hba->host->host_lock, flags);
2047 if (dir >= 0 && hba->monitor.nr_queued[dir]++ == 0)
2048 hba->monitor.busy_start_ts[dir] = ktime_get();
2049 spin_unlock_irqrestore(hba->host->host_lock, flags);
2052 static void ufshcd_update_monitor(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
2054 int dir = ufshcd_monitor_opcode2dir(*lrbp->cmd->cmnd);
2055 unsigned long flags;
2057 spin_lock_irqsave(hba->host->host_lock, flags);
2058 if (dir >= 0 && hba->monitor.nr_queued[dir] > 0) {
2059 struct request *req = scsi_cmd_to_rq(lrbp->cmd);
2060 struct ufs_hba_monitor *m = &hba->monitor;
2061 ktime_t now, inc, lat;
2063 now = lrbp->compl_time_stamp;
2064 inc = ktime_sub(now, m->busy_start_ts[dir]);
2065 m->total_busy[dir] = ktime_add(m->total_busy[dir], inc);
2066 m->nr_sec_rw[dir] += blk_rq_sectors(req);
2068 /* Update latencies */
2070 lat = ktime_sub(now, lrbp->issue_time_stamp);
2071 m->lat_sum[dir] += lat;
2072 if (m->lat_max[dir] < lat || !m->lat_max[dir])
2073 m->lat_max[dir] = lat;
2074 if (m->lat_min[dir] > lat || !m->lat_min[dir])
2075 m->lat_min[dir] = lat;
2077 m->nr_queued[dir]--;
2078 /* Push forward the busy start of monitor */
2079 m->busy_start_ts[dir] = now;
2081 spin_unlock_irqrestore(hba->host->host_lock, flags);
2085 * ufshcd_send_command - Send SCSI or device management commands
2086 * @hba: per adapter instance
2087 * @task_tag: Task tag of the command
2090 void ufshcd_send_command(struct ufs_hba *hba, unsigned int task_tag)
2092 struct ufshcd_lrb *lrbp = &hba->lrb[task_tag];
2093 unsigned long flags;
2095 lrbp->issue_time_stamp = ktime_get();
2096 lrbp->compl_time_stamp = ktime_set(0, 0);
2097 ufshcd_add_command_trace(hba, task_tag, UFS_CMD_SEND);
2098 ufshcd_clk_scaling_start_busy(hba);
2099 if (unlikely(ufshcd_should_inform_monitor(hba, lrbp)))
2100 ufshcd_start_monitor(hba, lrbp);
2102 spin_lock_irqsave(&hba->outstanding_lock, flags);
2103 if (hba->vops && hba->vops->setup_xfer_req)
2104 hba->vops->setup_xfer_req(hba, task_tag, !!lrbp->cmd);
2105 __set_bit(task_tag, &hba->outstanding_reqs);
2106 ufshcd_writel(hba, 1 << task_tag, REG_UTP_TRANSFER_REQ_DOOR_BELL);
2107 spin_unlock_irqrestore(&hba->outstanding_lock, flags);
2109 /* Make sure that doorbell is committed immediately */
2114 * ufshcd_copy_sense_data - Copy sense data in case of check condition
2115 * @lrbp: pointer to local reference block
2117 static inline void ufshcd_copy_sense_data(struct ufshcd_lrb *lrbp)
2120 if (lrbp->sense_buffer &&
2121 ufshcd_get_rsp_upiu_data_seg_len(lrbp->ucd_rsp_ptr)) {
2124 len = be16_to_cpu(lrbp->ucd_rsp_ptr->sr.sense_data_len);
2125 len_to_copy = min_t(int, UFS_SENSE_SIZE, len);
2127 memcpy(lrbp->sense_buffer, lrbp->ucd_rsp_ptr->sr.sense_data,
2133 * ufshcd_copy_query_response() - Copy the Query Response and the data
2135 * @hba: per adapter instance
2136 * @lrbp: pointer to local reference block
2139 int ufshcd_copy_query_response(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
2141 struct ufs_query_res *query_res = &hba->dev_cmd.query.response;
2143 memcpy(&query_res->upiu_res, &lrbp->ucd_rsp_ptr->qr, QUERY_OSF_SIZE);
2145 /* Get the descriptor */
2146 if (hba->dev_cmd.query.descriptor &&
2147 lrbp->ucd_rsp_ptr->qr.opcode == UPIU_QUERY_OPCODE_READ_DESC) {
2148 u8 *descp = (u8 *)lrbp->ucd_rsp_ptr +
2149 GENERAL_UPIU_REQUEST_SIZE;
2153 /* data segment length */
2154 resp_len = be32_to_cpu(lrbp->ucd_rsp_ptr->header.dword_2) &
2155 MASK_QUERY_DATA_SEG_LEN;
2156 buf_len = be16_to_cpu(
2157 hba->dev_cmd.query.request.upiu_req.length);
2158 if (likely(buf_len >= resp_len)) {
2159 memcpy(hba->dev_cmd.query.descriptor, descp, resp_len);
2162 "%s: rsp size %d is bigger than buffer size %d",
2163 __func__, resp_len, buf_len);
2172 * ufshcd_hba_capabilities - Read controller capabilities
2173 * @hba: per adapter instance
2175 * Return: 0 on success, negative on error.
2177 static inline int ufshcd_hba_capabilities(struct ufs_hba *hba)
2181 hba->capabilities = ufshcd_readl(hba, REG_CONTROLLER_CAPABILITIES);
2183 /* nutrs and nutmrs are 0 based values */
2184 hba->nutrs = (hba->capabilities & MASK_TRANSFER_REQUESTS_SLOTS) + 1;
2186 ((hba->capabilities & MASK_TASK_MANAGEMENT_REQUEST_SLOTS) >> 16) + 1;
2188 /* Read crypto capabilities */
2189 err = ufshcd_hba_init_crypto_capabilities(hba);
2191 dev_err(hba->dev, "crypto setup failed\n");
2197 * ufshcd_ready_for_uic_cmd - Check if controller is ready
2198 * to accept UIC commands
2199 * @hba: per adapter instance
2200 * Return true on success, else false
2202 static inline bool ufshcd_ready_for_uic_cmd(struct ufs_hba *hba)
2204 if (ufshcd_readl(hba, REG_CONTROLLER_STATUS) & UIC_COMMAND_READY)
2211 * ufshcd_get_upmcrs - Get the power mode change request status
2212 * @hba: Pointer to adapter instance
2214 * This function gets the UPMCRS field of HCS register
2215 * Returns value of UPMCRS field
2217 static inline u8 ufshcd_get_upmcrs(struct ufs_hba *hba)
2219 return (ufshcd_readl(hba, REG_CONTROLLER_STATUS) >> 8) & 0x7;
2223 * ufshcd_dispatch_uic_cmd - Dispatch an UIC command to the Unipro layer
2224 * @hba: per adapter instance
2225 * @uic_cmd: UIC command
2228 ufshcd_dispatch_uic_cmd(struct ufs_hba *hba, struct uic_command *uic_cmd)
2230 lockdep_assert_held(&hba->uic_cmd_mutex);
2232 WARN_ON(hba->active_uic_cmd);
2234 hba->active_uic_cmd = uic_cmd;
2237 ufshcd_writel(hba, uic_cmd->argument1, REG_UIC_COMMAND_ARG_1);
2238 ufshcd_writel(hba, uic_cmd->argument2, REG_UIC_COMMAND_ARG_2);
2239 ufshcd_writel(hba, uic_cmd->argument3, REG_UIC_COMMAND_ARG_3);
2241 ufshcd_add_uic_command_trace(hba, uic_cmd, UFS_CMD_SEND);
2244 ufshcd_writel(hba, uic_cmd->command & COMMAND_OPCODE_MASK,
2249 * ufshcd_wait_for_uic_cmd - Wait for completion of an UIC command
2250 * @hba: per adapter instance
2251 * @uic_cmd: UIC command
2253 * Returns 0 only if success.
2256 ufshcd_wait_for_uic_cmd(struct ufs_hba *hba, struct uic_command *uic_cmd)
2259 unsigned long flags;
2261 lockdep_assert_held(&hba->uic_cmd_mutex);
2263 if (wait_for_completion_timeout(&uic_cmd->done,
2264 msecs_to_jiffies(UIC_CMD_TIMEOUT))) {
2265 ret = uic_cmd->argument2 & MASK_UIC_COMMAND_RESULT;
2269 "uic cmd 0x%x with arg3 0x%x completion timeout\n",
2270 uic_cmd->command, uic_cmd->argument3);
2272 if (!uic_cmd->cmd_active) {
2273 dev_err(hba->dev, "%s: UIC cmd has been completed, return the result\n",
2275 ret = uic_cmd->argument2 & MASK_UIC_COMMAND_RESULT;
2279 spin_lock_irqsave(hba->host->host_lock, flags);
2280 hba->active_uic_cmd = NULL;
2281 spin_unlock_irqrestore(hba->host->host_lock, flags);
2287 * __ufshcd_send_uic_cmd - Send UIC commands and retrieve the result
2288 * @hba: per adapter instance
2289 * @uic_cmd: UIC command
2290 * @completion: initialize the completion only if this is set to true
2292 * Returns 0 only if success.
2295 __ufshcd_send_uic_cmd(struct ufs_hba *hba, struct uic_command *uic_cmd,
2298 lockdep_assert_held(&hba->uic_cmd_mutex);
2299 lockdep_assert_held(hba->host->host_lock);
2301 if (!ufshcd_ready_for_uic_cmd(hba)) {
2303 "Controller not ready to accept UIC commands\n");
2308 init_completion(&uic_cmd->done);
2310 uic_cmd->cmd_active = 1;
2311 ufshcd_dispatch_uic_cmd(hba, uic_cmd);
2317 * ufshcd_send_uic_cmd - Send UIC commands and retrieve the result
2318 * @hba: per adapter instance
2319 * @uic_cmd: UIC command
2321 * Returns 0 only if success.
2323 int ufshcd_send_uic_cmd(struct ufs_hba *hba, struct uic_command *uic_cmd)
2326 unsigned long flags;
2328 ufshcd_hold(hba, false);
2329 mutex_lock(&hba->uic_cmd_mutex);
2330 ufshcd_add_delay_before_dme_cmd(hba);
2332 spin_lock_irqsave(hba->host->host_lock, flags);
2333 ret = __ufshcd_send_uic_cmd(hba, uic_cmd, true);
2334 spin_unlock_irqrestore(hba->host->host_lock, flags);
2336 ret = ufshcd_wait_for_uic_cmd(hba, uic_cmd);
2338 mutex_unlock(&hba->uic_cmd_mutex);
2340 ufshcd_release(hba);
2345 * ufshcd_map_sg - Map scatter-gather list to prdt
2346 * @hba: per adapter instance
2347 * @lrbp: pointer to local reference block
2349 * Returns 0 in case of success, non-zero value in case of failure
2351 static int ufshcd_map_sg(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
2353 struct ufshcd_sg_entry *prd_table;
2354 struct scatterlist *sg;
2355 struct scsi_cmnd *cmd;
2360 sg_segments = scsi_dma_map(cmd);
2361 if (sg_segments < 0)
2366 if (hba->quirks & UFSHCD_QUIRK_PRDT_BYTE_GRAN)
2367 lrbp->utr_descriptor_ptr->prd_table_length =
2368 cpu_to_le16((sg_segments *
2369 sizeof(struct ufshcd_sg_entry)));
2371 lrbp->utr_descriptor_ptr->prd_table_length =
2372 cpu_to_le16((u16) (sg_segments));
2374 prd_table = (struct ufshcd_sg_entry *)lrbp->ucd_prdt_ptr;
2376 scsi_for_each_sg(cmd, sg, sg_segments, i) {
2378 cpu_to_le32(((u32) sg_dma_len(sg))-1);
2379 prd_table[i].base_addr =
2380 cpu_to_le32(lower_32_bits(sg->dma_address));
2381 prd_table[i].upper_addr =
2382 cpu_to_le32(upper_32_bits(sg->dma_address));
2383 prd_table[i].reserved = 0;
2386 lrbp->utr_descriptor_ptr->prd_table_length = 0;
2393 * ufshcd_enable_intr - enable interrupts
2394 * @hba: per adapter instance
2395 * @intrs: interrupt bits
2397 static void ufshcd_enable_intr(struct ufs_hba *hba, u32 intrs)
2399 u32 set = ufshcd_readl(hba, REG_INTERRUPT_ENABLE);
2401 if (hba->ufs_version == ufshci_version(1, 0)) {
2403 rw = set & INTERRUPT_MASK_RW_VER_10;
2404 set = rw | ((set ^ intrs) & intrs);
2409 ufshcd_writel(hba, set, REG_INTERRUPT_ENABLE);
2413 * ufshcd_disable_intr - disable interrupts
2414 * @hba: per adapter instance
2415 * @intrs: interrupt bits
2417 static void ufshcd_disable_intr(struct ufs_hba *hba, u32 intrs)
2419 u32 set = ufshcd_readl(hba, REG_INTERRUPT_ENABLE);
2421 if (hba->ufs_version == ufshci_version(1, 0)) {
2423 rw = (set & INTERRUPT_MASK_RW_VER_10) &
2424 ~(intrs & INTERRUPT_MASK_RW_VER_10);
2425 set = rw | ((set & intrs) & ~INTERRUPT_MASK_RW_VER_10);
2431 ufshcd_writel(hba, set, REG_INTERRUPT_ENABLE);
2435 * ufshcd_prepare_req_desc_hdr() - Fills the requests header
2436 * descriptor according to request
2437 * @lrbp: pointer to local reference block
2438 * @upiu_flags: flags required in the header
2439 * @cmd_dir: requests data direction
2441 static void ufshcd_prepare_req_desc_hdr(struct ufshcd_lrb *lrbp,
2442 u8 *upiu_flags, enum dma_data_direction cmd_dir)
2444 struct utp_transfer_req_desc *req_desc = lrbp->utr_descriptor_ptr;
2450 if (cmd_dir == DMA_FROM_DEVICE) {
2451 data_direction = UTP_DEVICE_TO_HOST;
2452 *upiu_flags = UPIU_CMD_FLAGS_READ;
2453 } else if (cmd_dir == DMA_TO_DEVICE) {
2454 data_direction = UTP_HOST_TO_DEVICE;
2455 *upiu_flags = UPIU_CMD_FLAGS_WRITE;
2457 data_direction = UTP_NO_DATA_TRANSFER;
2458 *upiu_flags = UPIU_CMD_FLAGS_NONE;
2461 dword_0 = data_direction | (lrbp->command_type
2462 << UPIU_COMMAND_TYPE_OFFSET);
2464 dword_0 |= UTP_REQ_DESC_INT_CMD;
2466 /* Prepare crypto related dwords */
2467 ufshcd_prepare_req_desc_hdr_crypto(lrbp, &dword_0, &dword_1, &dword_3);
2469 /* Transfer request descriptor header fields */
2470 req_desc->header.dword_0 = cpu_to_le32(dword_0);
2471 req_desc->header.dword_1 = cpu_to_le32(dword_1);
2473 * assigning invalid value for command status. Controller
2474 * updates OCS on command completion, with the command
2477 req_desc->header.dword_2 =
2478 cpu_to_le32(OCS_INVALID_COMMAND_STATUS);
2479 req_desc->header.dword_3 = cpu_to_le32(dword_3);
2481 req_desc->prd_table_length = 0;
2485 * ufshcd_prepare_utp_scsi_cmd_upiu() - fills the utp_transfer_req_desc,
2487 * @lrbp: local reference block pointer
2488 * @upiu_flags: flags
2491 void ufshcd_prepare_utp_scsi_cmd_upiu(struct ufshcd_lrb *lrbp, u8 upiu_flags)
2493 struct scsi_cmnd *cmd = lrbp->cmd;
2494 struct utp_upiu_req *ucd_req_ptr = lrbp->ucd_req_ptr;
2495 unsigned short cdb_len;
2497 /* command descriptor fields */
2498 ucd_req_ptr->header.dword_0 = UPIU_HEADER_DWORD(
2499 UPIU_TRANSACTION_COMMAND, upiu_flags,
2500 lrbp->lun, lrbp->task_tag);
2501 ucd_req_ptr->header.dword_1 = UPIU_HEADER_DWORD(
2502 UPIU_COMMAND_SET_TYPE_SCSI, 0, 0, 0);
2504 /* Total EHS length and Data segment length will be zero */
2505 ucd_req_ptr->header.dword_2 = 0;
2507 ucd_req_ptr->sc.exp_data_transfer_len = cpu_to_be32(cmd->sdb.length);
2509 cdb_len = min_t(unsigned short, cmd->cmd_len, UFS_CDB_SIZE);
2510 memset(ucd_req_ptr->sc.cdb, 0, UFS_CDB_SIZE);
2511 memcpy(ucd_req_ptr->sc.cdb, cmd->cmnd, cdb_len);
2513 memset(lrbp->ucd_rsp_ptr, 0, sizeof(struct utp_upiu_rsp));
2517 * ufshcd_prepare_utp_query_req_upiu() - fills the utp_transfer_req_desc,
2520 * @lrbp: local reference block pointer
2521 * @upiu_flags: flags
2523 static void ufshcd_prepare_utp_query_req_upiu(struct ufs_hba *hba,
2524 struct ufshcd_lrb *lrbp, u8 upiu_flags)
2526 struct utp_upiu_req *ucd_req_ptr = lrbp->ucd_req_ptr;
2527 struct ufs_query *query = &hba->dev_cmd.query;
2528 u16 len = be16_to_cpu(query->request.upiu_req.length);
2530 /* Query request header */
2531 ucd_req_ptr->header.dword_0 = UPIU_HEADER_DWORD(
2532 UPIU_TRANSACTION_QUERY_REQ, upiu_flags,
2533 lrbp->lun, lrbp->task_tag);
2534 ucd_req_ptr->header.dword_1 = UPIU_HEADER_DWORD(
2535 0, query->request.query_func, 0, 0);
2537 /* Data segment length only need for WRITE_DESC */
2538 if (query->request.upiu_req.opcode == UPIU_QUERY_OPCODE_WRITE_DESC)
2539 ucd_req_ptr->header.dword_2 =
2540 UPIU_HEADER_DWORD(0, 0, (len >> 8), (u8)len);
2542 ucd_req_ptr->header.dword_2 = 0;
2544 /* Copy the Query Request buffer as is */
2545 memcpy(&ucd_req_ptr->qr, &query->request.upiu_req,
2548 /* Copy the Descriptor */
2549 if (query->request.upiu_req.opcode == UPIU_QUERY_OPCODE_WRITE_DESC)
2550 memcpy(ucd_req_ptr + 1, query->descriptor, len);
2552 memset(lrbp->ucd_rsp_ptr, 0, sizeof(struct utp_upiu_rsp));
2555 static inline void ufshcd_prepare_utp_nop_upiu(struct ufshcd_lrb *lrbp)
2557 struct utp_upiu_req *ucd_req_ptr = lrbp->ucd_req_ptr;
2559 memset(ucd_req_ptr, 0, sizeof(struct utp_upiu_req));
2561 /* command descriptor fields */
2562 ucd_req_ptr->header.dword_0 =
2564 UPIU_TRANSACTION_NOP_OUT, 0, 0, lrbp->task_tag);
2565 /* clear rest of the fields of basic header */
2566 ucd_req_ptr->header.dword_1 = 0;
2567 ucd_req_ptr->header.dword_2 = 0;
2569 memset(lrbp->ucd_rsp_ptr, 0, sizeof(struct utp_upiu_rsp));
2573 * ufshcd_compose_devman_upiu - UFS Protocol Information Unit(UPIU)
2574 * for Device Management Purposes
2575 * @hba: per adapter instance
2576 * @lrbp: pointer to local reference block
2578 static int ufshcd_compose_devman_upiu(struct ufs_hba *hba,
2579 struct ufshcd_lrb *lrbp)
2584 if (hba->ufs_version <= ufshci_version(1, 1))
2585 lrbp->command_type = UTP_CMD_TYPE_DEV_MANAGE;
2587 lrbp->command_type = UTP_CMD_TYPE_UFS_STORAGE;
2589 ufshcd_prepare_req_desc_hdr(lrbp, &upiu_flags, DMA_NONE);
2590 if (hba->dev_cmd.type == DEV_CMD_TYPE_QUERY)
2591 ufshcd_prepare_utp_query_req_upiu(hba, lrbp, upiu_flags);
2592 else if (hba->dev_cmd.type == DEV_CMD_TYPE_NOP)
2593 ufshcd_prepare_utp_nop_upiu(lrbp);
2601 * ufshcd_comp_scsi_upiu - UFS Protocol Information Unit(UPIU)
2603 * @hba: per adapter instance
2604 * @lrbp: pointer to local reference block
2606 static int ufshcd_comp_scsi_upiu(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
2611 if (hba->ufs_version <= ufshci_version(1, 1))
2612 lrbp->command_type = UTP_CMD_TYPE_SCSI;
2614 lrbp->command_type = UTP_CMD_TYPE_UFS_STORAGE;
2616 if (likely(lrbp->cmd)) {
2617 ufshcd_prepare_req_desc_hdr(lrbp, &upiu_flags,
2618 lrbp->cmd->sc_data_direction);
2619 ufshcd_prepare_utp_scsi_cmd_upiu(lrbp, upiu_flags);
2628 * ufshcd_upiu_wlun_to_scsi_wlun - maps UPIU W-LUN id to SCSI W-LUN ID
2629 * @upiu_wlun_id: UPIU W-LUN id
2631 * Returns SCSI W-LUN id
2633 static inline u16 ufshcd_upiu_wlun_to_scsi_wlun(u8 upiu_wlun_id)
2635 return (upiu_wlun_id & ~UFS_UPIU_WLUN_ID) | SCSI_W_LUN_BASE;
2638 static inline bool is_rpmb_wlun(struct scsi_device *sdev)
2640 return sdev->lun == ufshcd_upiu_wlun_to_scsi_wlun(UFS_UPIU_RPMB_WLUN);
2643 static inline bool is_device_wlun(struct scsi_device *sdev)
2646 ufshcd_upiu_wlun_to_scsi_wlun(UFS_UPIU_UFS_DEVICE_WLUN);
2649 static void ufshcd_init_lrb(struct ufs_hba *hba, struct ufshcd_lrb *lrb, int i)
2651 struct utp_transfer_cmd_desc *cmd_descp = hba->ucdl_base_addr;
2652 struct utp_transfer_req_desc *utrdlp = hba->utrdl_base_addr;
2653 dma_addr_t cmd_desc_element_addr = hba->ucdl_dma_addr +
2654 i * sizeof(struct utp_transfer_cmd_desc);
2655 u16 response_offset = offsetof(struct utp_transfer_cmd_desc,
2657 u16 prdt_offset = offsetof(struct utp_transfer_cmd_desc, prd_table);
2659 lrb->utr_descriptor_ptr = utrdlp + i;
2660 lrb->utrd_dma_addr = hba->utrdl_dma_addr +
2661 i * sizeof(struct utp_transfer_req_desc);
2662 lrb->ucd_req_ptr = (struct utp_upiu_req *)(cmd_descp + i);
2663 lrb->ucd_req_dma_addr = cmd_desc_element_addr;
2664 lrb->ucd_rsp_ptr = (struct utp_upiu_rsp *)cmd_descp[i].response_upiu;
2665 lrb->ucd_rsp_dma_addr = cmd_desc_element_addr + response_offset;
2666 lrb->ucd_prdt_ptr = (struct ufshcd_sg_entry *)cmd_descp[i].prd_table;
2667 lrb->ucd_prdt_dma_addr = cmd_desc_element_addr + prdt_offset;
2671 * ufshcd_queuecommand - main entry point for SCSI requests
2672 * @host: SCSI host pointer
2673 * @cmd: command from SCSI Midlayer
2675 * Returns 0 for success, non-zero in case of failure
2677 static int ufshcd_queuecommand(struct Scsi_Host *host, struct scsi_cmnd *cmd)
2679 struct ufs_hba *hba = shost_priv(host);
2680 int tag = scsi_cmd_to_rq(cmd)->tag;
2681 struct ufshcd_lrb *lrbp;
2684 WARN_ONCE(tag < 0, "Invalid tag %d\n", tag);
2686 if (!down_read_trylock(&hba->clk_scaling_lock))
2687 return SCSI_MLQUEUE_HOST_BUSY;
2689 switch (hba->ufshcd_state) {
2690 case UFSHCD_STATE_OPERATIONAL:
2691 case UFSHCD_STATE_EH_SCHEDULED_NON_FATAL:
2693 case UFSHCD_STATE_EH_SCHEDULED_FATAL:
2695 * pm_runtime_get_sync() is used at error handling preparation
2696 * stage. If a scsi cmd, e.g. the SSU cmd, is sent from hba's
2697 * PM ops, it can never be finished if we let SCSI layer keep
2698 * retrying it, which gets err handler stuck forever. Neither
2699 * can we let the scsi cmd pass through, because UFS is in bad
2700 * state, the scsi cmd may eventually time out, which will get
2701 * err handler blocked for too long. So, just fail the scsi cmd
2702 * sent from PM ops, err handler can recover PM error anyways.
2704 if (hba->pm_op_in_progress) {
2705 hba->force_reset = true;
2706 set_host_byte(cmd, DID_BAD_TARGET);
2707 cmd->scsi_done(cmd);
2711 case UFSHCD_STATE_RESET:
2712 err = SCSI_MLQUEUE_HOST_BUSY;
2714 case UFSHCD_STATE_ERROR:
2715 set_host_byte(cmd, DID_ERROR);
2716 cmd->scsi_done(cmd);
2720 hba->req_abort_count = 0;
2722 err = ufshcd_hold(hba, true);
2724 err = SCSI_MLQUEUE_HOST_BUSY;
2727 WARN_ON(ufshcd_is_clkgating_allowed(hba) &&
2728 (hba->clk_gating.state != CLKS_ON));
2730 lrbp = &hba->lrb[tag];
2733 lrbp->sense_bufflen = UFS_SENSE_SIZE;
2734 lrbp->sense_buffer = cmd->sense_buffer;
2735 lrbp->task_tag = tag;
2736 lrbp->lun = ufshcd_scsi_to_upiu_lun(cmd->device->lun);
2737 lrbp->intr_cmd = !ufshcd_is_intr_aggr_allowed(hba) ? true : false;
2739 ufshcd_prepare_lrbp_crypto(scsi_cmd_to_rq(cmd), lrbp);
2741 lrbp->req_abort_skip = false;
2743 err = ufshpb_prep(hba, lrbp);
2744 if (err == -EAGAIN) {
2746 ufshcd_release(hba);
2750 ufshcd_comp_scsi_upiu(hba, lrbp);
2752 err = ufshcd_map_sg(hba, lrbp);
2755 ufshcd_release(hba);
2759 ufshcd_send_command(hba, tag);
2761 up_read(&hba->clk_scaling_lock);
2763 if (ufs_trigger_eh())
2764 scsi_schedule_eh(hba->host);
2769 static int ufshcd_compose_dev_cmd(struct ufs_hba *hba,
2770 struct ufshcd_lrb *lrbp, enum dev_cmd_type cmd_type, int tag)
2773 lrbp->sense_bufflen = 0;
2774 lrbp->sense_buffer = NULL;
2775 lrbp->task_tag = tag;
2776 lrbp->lun = 0; /* device management cmd is not specific to any LUN */
2777 lrbp->intr_cmd = true; /* No interrupt aggregation */
2778 ufshcd_prepare_lrbp_crypto(NULL, lrbp);
2779 hba->dev_cmd.type = cmd_type;
2781 return ufshcd_compose_devman_upiu(hba, lrbp);
2785 ufshcd_clear_cmd(struct ufs_hba *hba, int tag)
2788 unsigned long flags;
2789 u32 mask = 1 << tag;
2791 /* clear outstanding transaction before retry */
2792 spin_lock_irqsave(hba->host->host_lock, flags);
2793 ufshcd_utrl_clear(hba, tag);
2794 spin_unlock_irqrestore(hba->host->host_lock, flags);
2797 * wait for h/w to clear corresponding bit in door-bell.
2798 * max. wait is 1 sec.
2800 err = ufshcd_wait_for_register(hba,
2801 REG_UTP_TRANSFER_REQ_DOOR_BELL,
2802 mask, ~mask, 1000, 1000);
2808 ufshcd_check_query_response(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
2810 struct ufs_query_res *query_res = &hba->dev_cmd.query.response;
2812 /* Get the UPIU response */
2813 query_res->response = ufshcd_get_rsp_upiu_result(lrbp->ucd_rsp_ptr) >>
2814 UPIU_RSP_CODE_OFFSET;
2815 return query_res->response;
2819 * ufshcd_dev_cmd_completion() - handles device management command responses
2820 * @hba: per adapter instance
2821 * @lrbp: pointer to local reference block
2824 ufshcd_dev_cmd_completion(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
2829 hba->ufs_stats.last_hibern8_exit_tstamp = ktime_set(0, 0);
2830 resp = ufshcd_get_req_rsp(lrbp->ucd_rsp_ptr);
2833 case UPIU_TRANSACTION_NOP_IN:
2834 if (hba->dev_cmd.type != DEV_CMD_TYPE_NOP) {
2836 dev_err(hba->dev, "%s: unexpected response %x\n",
2840 case UPIU_TRANSACTION_QUERY_RSP:
2841 err = ufshcd_check_query_response(hba, lrbp);
2843 err = ufshcd_copy_query_response(hba, lrbp);
2845 case UPIU_TRANSACTION_REJECT_UPIU:
2846 /* TODO: handle Reject UPIU Response */
2848 dev_err(hba->dev, "%s: Reject UPIU not fully implemented\n",
2853 dev_err(hba->dev, "%s: Invalid device management cmd response: %x\n",
2861 static int ufshcd_wait_for_dev_cmd(struct ufs_hba *hba,
2862 struct ufshcd_lrb *lrbp, int max_timeout)
2865 unsigned long time_left;
2866 unsigned long flags;
2868 time_left = wait_for_completion_timeout(hba->dev_cmd.complete,
2869 msecs_to_jiffies(max_timeout));
2871 spin_lock_irqsave(hba->host->host_lock, flags);
2872 hba->dev_cmd.complete = NULL;
2873 if (likely(time_left)) {
2874 err = ufshcd_get_tr_ocs(lrbp);
2876 err = ufshcd_dev_cmd_completion(hba, lrbp);
2878 spin_unlock_irqrestore(hba->host->host_lock, flags);
2882 dev_dbg(hba->dev, "%s: dev_cmd request timedout, tag %d\n",
2883 __func__, lrbp->task_tag);
2884 if (!ufshcd_clear_cmd(hba, lrbp->task_tag))
2885 /* successfully cleared the command, retry if needed */
2888 * in case of an error, after clearing the doorbell,
2889 * we also need to clear the outstanding_request
2892 spin_lock_irqsave(&hba->outstanding_lock, flags);
2893 __clear_bit(lrbp->task_tag, &hba->outstanding_reqs);
2894 spin_unlock_irqrestore(&hba->outstanding_lock, flags);
2901 * ufshcd_exec_dev_cmd - API for sending device management requests
2903 * @cmd_type: specifies the type (NOP, Query...)
2904 * @timeout: timeout in milliseconds
2906 * NOTE: Since there is only one available tag for device management commands,
2907 * it is expected you hold the hba->dev_cmd.lock mutex.
2909 static int ufshcd_exec_dev_cmd(struct ufs_hba *hba,
2910 enum dev_cmd_type cmd_type, int timeout)
2912 struct request_queue *q = hba->cmd_queue;
2913 DECLARE_COMPLETION_ONSTACK(wait);
2914 struct request *req;
2915 struct ufshcd_lrb *lrbp;
2919 down_read(&hba->clk_scaling_lock);
2922 * Get free slot, sleep if slots are unavailable.
2923 * Even though we use wait_event() which sleeps indefinitely,
2924 * the maximum wait time is bounded by SCSI request timeout.
2926 req = blk_get_request(q, REQ_OP_DRV_OUT, 0);
2932 WARN_ONCE(tag < 0, "Invalid tag %d\n", tag);
2933 /* Set the timeout such that the SCSI error handler is not activated. */
2934 req->timeout = msecs_to_jiffies(2 * timeout);
2935 blk_mq_start_request(req);
2937 lrbp = &hba->lrb[tag];
2939 err = ufshcd_compose_dev_cmd(hba, lrbp, cmd_type, tag);
2943 hba->dev_cmd.complete = &wait;
2945 ufshcd_add_query_upiu_trace(hba, UFS_QUERY_SEND, lrbp->ucd_req_ptr);
2947 ufshcd_send_command(hba, tag);
2948 err = ufshcd_wait_for_dev_cmd(hba, lrbp, timeout);
2949 ufshcd_add_query_upiu_trace(hba, err ? UFS_QUERY_ERR : UFS_QUERY_COMP,
2950 (struct utp_upiu_req *)lrbp->ucd_rsp_ptr);
2953 blk_put_request(req);
2955 up_read(&hba->clk_scaling_lock);
2960 * ufshcd_init_query() - init the query response and request parameters
2961 * @hba: per-adapter instance
2962 * @request: address of the request pointer to be initialized
2963 * @response: address of the response pointer to be initialized
2964 * @opcode: operation to perform
2965 * @idn: flag idn to access
2966 * @index: LU number to access
2967 * @selector: query/flag/descriptor further identification
2969 static inline void ufshcd_init_query(struct ufs_hba *hba,
2970 struct ufs_query_req **request, struct ufs_query_res **response,
2971 enum query_opcode opcode, u8 idn, u8 index, u8 selector)
2973 *request = &hba->dev_cmd.query.request;
2974 *response = &hba->dev_cmd.query.response;
2975 memset(*request, 0, sizeof(struct ufs_query_req));
2976 memset(*response, 0, sizeof(struct ufs_query_res));
2977 (*request)->upiu_req.opcode = opcode;
2978 (*request)->upiu_req.idn = idn;
2979 (*request)->upiu_req.index = index;
2980 (*request)->upiu_req.selector = selector;
2983 static int ufshcd_query_flag_retry(struct ufs_hba *hba,
2984 enum query_opcode opcode, enum flag_idn idn, u8 index, bool *flag_res)
2989 for (retries = 0; retries < QUERY_REQ_RETRIES; retries++) {
2990 ret = ufshcd_query_flag(hba, opcode, idn, index, flag_res);
2993 "%s: failed with error %d, retries %d\n",
2994 __func__, ret, retries);
3001 "%s: query attribute, opcode %d, idn %d, failed with error %d after %d retires\n",
3002 __func__, opcode, idn, ret, retries);
3007 * ufshcd_query_flag() - API function for sending flag query requests
3008 * @hba: per-adapter instance
3009 * @opcode: flag query to perform
3010 * @idn: flag idn to access
3011 * @index: flag index to access
3012 * @flag_res: the flag value after the query request completes
3014 * Returns 0 for success, non-zero in case of failure
3016 int ufshcd_query_flag(struct ufs_hba *hba, enum query_opcode opcode,
3017 enum flag_idn idn, u8 index, bool *flag_res)
3019 struct ufs_query_req *request = NULL;
3020 struct ufs_query_res *response = NULL;
3021 int err, selector = 0;
3022 int timeout = QUERY_REQ_TIMEOUT;
3026 ufshcd_hold(hba, false);
3027 mutex_lock(&hba->dev_cmd.lock);
3028 ufshcd_init_query(hba, &request, &response, opcode, idn, index,
3032 case UPIU_QUERY_OPCODE_SET_FLAG:
3033 case UPIU_QUERY_OPCODE_CLEAR_FLAG:
3034 case UPIU_QUERY_OPCODE_TOGGLE_FLAG:
3035 request->query_func = UPIU_QUERY_FUNC_STANDARD_WRITE_REQUEST;
3037 case UPIU_QUERY_OPCODE_READ_FLAG:
3038 request->query_func = UPIU_QUERY_FUNC_STANDARD_READ_REQUEST;
3040 /* No dummy reads */
3041 dev_err(hba->dev, "%s: Invalid argument for read request\n",
3049 "%s: Expected query flag opcode but got = %d\n",
3055 err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_QUERY, timeout);
3059 "%s: Sending flag query for idn %d failed, err = %d\n",
3060 __func__, idn, err);
3065 *flag_res = (be32_to_cpu(response->upiu_res.value) &
3066 MASK_QUERY_UPIU_FLAG_LOC) & 0x1;
3069 mutex_unlock(&hba->dev_cmd.lock);
3070 ufshcd_release(hba);
3075 * ufshcd_query_attr - API function for sending attribute requests
3076 * @hba: per-adapter instance
3077 * @opcode: attribute opcode
3078 * @idn: attribute idn to access
3079 * @index: index field
3080 * @selector: selector field
3081 * @attr_val: the attribute value after the query request completes
3083 * Returns 0 for success, non-zero in case of failure
3085 int ufshcd_query_attr(struct ufs_hba *hba, enum query_opcode opcode,
3086 enum attr_idn idn, u8 index, u8 selector, u32 *attr_val)
3088 struct ufs_query_req *request = NULL;
3089 struct ufs_query_res *response = NULL;
3095 dev_err(hba->dev, "%s: attribute value required for opcode 0x%x\n",
3100 ufshcd_hold(hba, false);
3102 mutex_lock(&hba->dev_cmd.lock);
3103 ufshcd_init_query(hba, &request, &response, opcode, idn, index,
3107 case UPIU_QUERY_OPCODE_WRITE_ATTR:
3108 request->query_func = UPIU_QUERY_FUNC_STANDARD_WRITE_REQUEST;
3109 request->upiu_req.value = cpu_to_be32(*attr_val);
3111 case UPIU_QUERY_OPCODE_READ_ATTR:
3112 request->query_func = UPIU_QUERY_FUNC_STANDARD_READ_REQUEST;
3115 dev_err(hba->dev, "%s: Expected query attr opcode but got = 0x%.2x\n",
3121 err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_QUERY, QUERY_REQ_TIMEOUT);
3124 dev_err(hba->dev, "%s: opcode 0x%.2x for idn %d failed, index %d, err = %d\n",
3125 __func__, opcode, idn, index, err);
3129 *attr_val = be32_to_cpu(response->upiu_res.value);
3132 mutex_unlock(&hba->dev_cmd.lock);
3133 ufshcd_release(hba);
3138 * ufshcd_query_attr_retry() - API function for sending query
3139 * attribute with retries
3140 * @hba: per-adapter instance
3141 * @opcode: attribute opcode
3142 * @idn: attribute idn to access
3143 * @index: index field
3144 * @selector: selector field
3145 * @attr_val: the attribute value after the query request
3148 * Returns 0 for success, non-zero in case of failure
3150 int ufshcd_query_attr_retry(struct ufs_hba *hba,
3151 enum query_opcode opcode, enum attr_idn idn, u8 index, u8 selector,
3157 for (retries = QUERY_REQ_RETRIES; retries > 0; retries--) {
3158 ret = ufshcd_query_attr(hba, opcode, idn, index,
3159 selector, attr_val);
3161 dev_dbg(hba->dev, "%s: failed with error %d, retries %d\n",
3162 __func__, ret, retries);
3169 "%s: query attribute, idn %d, failed with error %d after %d retires\n",
3170 __func__, idn, ret, QUERY_REQ_RETRIES);
3174 static int __ufshcd_query_descriptor(struct ufs_hba *hba,
3175 enum query_opcode opcode, enum desc_idn idn, u8 index,
3176 u8 selector, u8 *desc_buf, int *buf_len)
3178 struct ufs_query_req *request = NULL;
3179 struct ufs_query_res *response = NULL;
3185 dev_err(hba->dev, "%s: descriptor buffer required for opcode 0x%x\n",
3190 if (*buf_len < QUERY_DESC_MIN_SIZE || *buf_len > QUERY_DESC_MAX_SIZE) {
3191 dev_err(hba->dev, "%s: descriptor buffer size (%d) is out of range\n",
3192 __func__, *buf_len);
3196 ufshcd_hold(hba, false);
3198 mutex_lock(&hba->dev_cmd.lock);
3199 ufshcd_init_query(hba, &request, &response, opcode, idn, index,
3201 hba->dev_cmd.query.descriptor = desc_buf;
3202 request->upiu_req.length = cpu_to_be16(*buf_len);
3205 case UPIU_QUERY_OPCODE_WRITE_DESC:
3206 request->query_func = UPIU_QUERY_FUNC_STANDARD_WRITE_REQUEST;
3208 case UPIU_QUERY_OPCODE_READ_DESC:
3209 request->query_func = UPIU_QUERY_FUNC_STANDARD_READ_REQUEST;
3213 "%s: Expected query descriptor opcode but got = 0x%.2x\n",
3219 err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_QUERY, QUERY_REQ_TIMEOUT);
3222 dev_err(hba->dev, "%s: opcode 0x%.2x for idn %d failed, index %d, err = %d\n",
3223 __func__, opcode, idn, index, err);
3227 *buf_len = be16_to_cpu(response->upiu_res.length);
3230 hba->dev_cmd.query.descriptor = NULL;
3231 mutex_unlock(&hba->dev_cmd.lock);
3232 ufshcd_release(hba);
3237 * ufshcd_query_descriptor_retry - API function for sending descriptor requests
3238 * @hba: per-adapter instance
3239 * @opcode: attribute opcode
3240 * @idn: attribute idn to access
3241 * @index: index field
3242 * @selector: selector field
3243 * @desc_buf: the buffer that contains the descriptor
3244 * @buf_len: length parameter passed to the device
3246 * Returns 0 for success, non-zero in case of failure.
3247 * The buf_len parameter will contain, on return, the length parameter
3248 * received on the response.
3250 int ufshcd_query_descriptor_retry(struct ufs_hba *hba,
3251 enum query_opcode opcode,
3252 enum desc_idn idn, u8 index,
3254 u8 *desc_buf, int *buf_len)
3259 for (retries = QUERY_REQ_RETRIES; retries > 0; retries--) {
3260 err = __ufshcd_query_descriptor(hba, opcode, idn, index,
3261 selector, desc_buf, buf_len);
3262 if (!err || err == -EINVAL)
3270 * ufshcd_map_desc_id_to_length - map descriptor IDN to its length
3271 * @hba: Pointer to adapter instance
3272 * @desc_id: descriptor idn value
3273 * @desc_len: mapped desc length (out)
3275 void ufshcd_map_desc_id_to_length(struct ufs_hba *hba, enum desc_idn desc_id,
3278 if (desc_id >= QUERY_DESC_IDN_MAX || desc_id == QUERY_DESC_IDN_RFU_0 ||
3279 desc_id == QUERY_DESC_IDN_RFU_1)
3282 *desc_len = hba->desc_size[desc_id];
3284 EXPORT_SYMBOL(ufshcd_map_desc_id_to_length);
3286 static void ufshcd_update_desc_length(struct ufs_hba *hba,
3287 enum desc_idn desc_id, int desc_index,
3288 unsigned char desc_len)
3290 if (hba->desc_size[desc_id] == QUERY_DESC_MAX_SIZE &&
3291 desc_id != QUERY_DESC_IDN_STRING && desc_index != UFS_RPMB_UNIT)
3292 /* For UFS 3.1, the normal unit descriptor is 10 bytes larger
3293 * than the RPMB unit, however, both descriptors share the same
3294 * desc_idn, to cover both unit descriptors with one length, we
3295 * choose the normal unit descriptor length by desc_index.
3297 hba->desc_size[desc_id] = desc_len;
3301 * ufshcd_read_desc_param - read the specified descriptor parameter
3302 * @hba: Pointer to adapter instance
3303 * @desc_id: descriptor idn value
3304 * @desc_index: descriptor index
3305 * @param_offset: offset of the parameter to read
3306 * @param_read_buf: pointer to buffer where parameter would be read
3307 * @param_size: sizeof(param_read_buf)
3309 * Return 0 in case of success, non-zero otherwise
3311 int ufshcd_read_desc_param(struct ufs_hba *hba,
3312 enum desc_idn desc_id,
3321 bool is_kmalloc = true;
3324 if (desc_id >= QUERY_DESC_IDN_MAX || !param_size)
3327 /* Get the length of descriptor */
3328 ufshcd_map_desc_id_to_length(hba, desc_id, &buff_len);
3330 dev_err(hba->dev, "%s: Failed to get desc length\n", __func__);
3334 if (param_offset >= buff_len) {
3335 dev_err(hba->dev, "%s: Invalid offset 0x%x in descriptor IDN 0x%x, length 0x%x\n",
3336 __func__, param_offset, desc_id, buff_len);
3340 /* Check whether we need temp memory */
3341 if (param_offset != 0 || param_size < buff_len) {
3342 desc_buf = kzalloc(buff_len, GFP_KERNEL);
3346 desc_buf = param_read_buf;
3350 /* Request for full descriptor */
3351 ret = ufshcd_query_descriptor_retry(hba, UPIU_QUERY_OPCODE_READ_DESC,
3352 desc_id, desc_index, 0,
3353 desc_buf, &buff_len);
3356 dev_err(hba->dev, "%s: Failed reading descriptor. desc_id %d, desc_index %d, param_offset %d, ret %d\n",
3357 __func__, desc_id, desc_index, param_offset, ret);
3362 if (desc_buf[QUERY_DESC_DESC_TYPE_OFFSET] != desc_id) {
3363 dev_err(hba->dev, "%s: invalid desc_id %d in descriptor header\n",
3364 __func__, desc_buf[QUERY_DESC_DESC_TYPE_OFFSET]);
3369 /* Update descriptor length */
3370 buff_len = desc_buf[QUERY_DESC_LENGTH_OFFSET];
3371 ufshcd_update_desc_length(hba, desc_id, desc_index, buff_len);
3374 /* Make sure we don't copy more data than available */
3375 if (param_offset >= buff_len)
3378 memcpy(param_read_buf, &desc_buf[param_offset],
3379 min_t(u32, param_size, buff_len - param_offset));
3388 * struct uc_string_id - unicode string
3390 * @len: size of this descriptor inclusive
3391 * @type: descriptor type
3392 * @uc: unicode string character
3394 struct uc_string_id {
3400 /* replace non-printable or non-ASCII characters with spaces */
3401 static inline char ufshcd_remove_non_printable(u8 ch)
3403 return (ch >= 0x20 && ch <= 0x7e) ? ch : ' ';
3407 * ufshcd_read_string_desc - read string descriptor
3408 * @hba: pointer to adapter instance
3409 * @desc_index: descriptor index
3410 * @buf: pointer to buffer where descriptor would be read,
3411 * the caller should free the memory.
3412 * @ascii: if true convert from unicode to ascii characters
3413 * null terminated string.
3416 * * string size on success.
3417 * * -ENOMEM: on allocation failure
3418 * * -EINVAL: on a wrong parameter
3420 int ufshcd_read_string_desc(struct ufs_hba *hba, u8 desc_index,
3421 u8 **buf, bool ascii)
3423 struct uc_string_id *uc_str;
3430 uc_str = kzalloc(QUERY_DESC_MAX_SIZE, GFP_KERNEL);
3434 ret = ufshcd_read_desc_param(hba, QUERY_DESC_IDN_STRING, desc_index, 0,
3435 (u8 *)uc_str, QUERY_DESC_MAX_SIZE);
3437 dev_err(hba->dev, "Reading String Desc failed after %d retries. err = %d\n",
3438 QUERY_REQ_RETRIES, ret);
3443 if (uc_str->len <= QUERY_DESC_HDR_SIZE) {
3444 dev_dbg(hba->dev, "String Desc is of zero length\n");
3453 /* remove header and divide by 2 to move from UTF16 to UTF8 */
3454 ascii_len = (uc_str->len - QUERY_DESC_HDR_SIZE) / 2 + 1;
3455 str = kzalloc(ascii_len, GFP_KERNEL);
3462 * the descriptor contains string in UTF16 format
3463 * we need to convert to utf-8 so it can be displayed
3465 ret = utf16s_to_utf8s(uc_str->uc,
3466 uc_str->len - QUERY_DESC_HDR_SIZE,
3467 UTF16_BIG_ENDIAN, str, ascii_len);
3469 /* replace non-printable or non-ASCII characters with spaces */
3470 for (i = 0; i < ret; i++)
3471 str[i] = ufshcd_remove_non_printable(str[i]);
3476 str = kmemdup(uc_str, uc_str->len, GFP_KERNEL);
3490 * ufshcd_read_unit_desc_param - read the specified unit descriptor parameter
3491 * @hba: Pointer to adapter instance
3493 * @param_offset: offset of the parameter to read
3494 * @param_read_buf: pointer to buffer where parameter would be read
3495 * @param_size: sizeof(param_read_buf)
3497 * Return 0 in case of success, non-zero otherwise
3499 static inline int ufshcd_read_unit_desc_param(struct ufs_hba *hba,
3501 enum unit_desc_param param_offset,
3506 * Unit descriptors are only available for general purpose LUs (LUN id
3507 * from 0 to 7) and RPMB Well known LU.
3509 if (!ufs_is_valid_unit_desc_lun(&hba->dev_info, lun, param_offset))
3512 return ufshcd_read_desc_param(hba, QUERY_DESC_IDN_UNIT, lun,
3513 param_offset, param_read_buf, param_size);
3516 static int ufshcd_get_ref_clk_gating_wait(struct ufs_hba *hba)
3519 u32 gating_wait = UFSHCD_REF_CLK_GATING_WAIT_US;
3521 if (hba->dev_info.wspecversion >= 0x300) {
3522 err = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
3523 QUERY_ATTR_IDN_REF_CLK_GATING_WAIT_TIME, 0, 0,
3526 dev_err(hba->dev, "Failed reading bRefClkGatingWait. err = %d, use default %uus\n",
3529 if (gating_wait == 0) {
3530 gating_wait = UFSHCD_REF_CLK_GATING_WAIT_US;
3531 dev_err(hba->dev, "Undefined ref clk gating wait time, use default %uus\n",
3535 hba->dev_info.clk_gating_wait_us = gating_wait;
3542 * ufshcd_memory_alloc - allocate memory for host memory space data structures
3543 * @hba: per adapter instance
3545 * 1. Allocate DMA memory for Command Descriptor array
3546 * Each command descriptor consist of Command UPIU, Response UPIU and PRDT
3547 * 2. Allocate DMA memory for UTP Transfer Request Descriptor List (UTRDL).
3548 * 3. Allocate DMA memory for UTP Task Management Request Descriptor List
3550 * 4. Allocate memory for local reference block(lrb).
3552 * Returns 0 for success, non-zero in case of failure
3554 static int ufshcd_memory_alloc(struct ufs_hba *hba)
3556 size_t utmrdl_size, utrdl_size, ucdl_size;
3558 /* Allocate memory for UTP command descriptors */
3559 ucdl_size = (sizeof(struct utp_transfer_cmd_desc) * hba->nutrs);
3560 hba->ucdl_base_addr = dmam_alloc_coherent(hba->dev,
3562 &hba->ucdl_dma_addr,
3566 * UFSHCI requires UTP command descriptor to be 128 byte aligned.
3567 * make sure hba->ucdl_dma_addr is aligned to PAGE_SIZE
3568 * if hba->ucdl_dma_addr is aligned to PAGE_SIZE, then it will
3569 * be aligned to 128 bytes as well
3571 if (!hba->ucdl_base_addr ||
3572 WARN_ON(hba->ucdl_dma_addr & (PAGE_SIZE - 1))) {
3574 "Command Descriptor Memory allocation failed\n");
3579 * Allocate memory for UTP Transfer descriptors
3580 * UFSHCI requires 1024 byte alignment of UTRD
3582 utrdl_size = (sizeof(struct utp_transfer_req_desc) * hba->nutrs);
3583 hba->utrdl_base_addr = dmam_alloc_coherent(hba->dev,
3585 &hba->utrdl_dma_addr,
3587 if (!hba->utrdl_base_addr ||
3588 WARN_ON(hba->utrdl_dma_addr & (PAGE_SIZE - 1))) {
3590 "Transfer Descriptor Memory allocation failed\n");
3595 * Allocate memory for UTP Task Management descriptors
3596 * UFSHCI requires 1024 byte alignment of UTMRD
3598 utmrdl_size = sizeof(struct utp_task_req_desc) * hba->nutmrs;
3599 hba->utmrdl_base_addr = dmam_alloc_coherent(hba->dev,
3601 &hba->utmrdl_dma_addr,
3603 if (!hba->utmrdl_base_addr ||
3604 WARN_ON(hba->utmrdl_dma_addr & (PAGE_SIZE - 1))) {
3606 "Task Management Descriptor Memory allocation failed\n");
3610 /* Allocate memory for local reference block */
3611 hba->lrb = devm_kcalloc(hba->dev,
3612 hba->nutrs, sizeof(struct ufshcd_lrb),
3615 dev_err(hba->dev, "LRB Memory allocation failed\n");
3624 * ufshcd_host_memory_configure - configure local reference block with
3626 * @hba: per adapter instance
3628 * Configure Host memory space
3629 * 1. Update Corresponding UTRD.UCDBA and UTRD.UCDBAU with UCD DMA
3631 * 2. Update each UTRD with Response UPIU offset, Response UPIU length
3633 * 3. Save the corresponding addresses of UTRD, UCD.CMD, UCD.RSP and UCD.PRDT
3634 * into local reference block.
3636 static void ufshcd_host_memory_configure(struct ufs_hba *hba)
3638 struct utp_transfer_req_desc *utrdlp;
3639 dma_addr_t cmd_desc_dma_addr;
3640 dma_addr_t cmd_desc_element_addr;
3641 u16 response_offset;
3646 utrdlp = hba->utrdl_base_addr;
3649 offsetof(struct utp_transfer_cmd_desc, response_upiu);
3651 offsetof(struct utp_transfer_cmd_desc, prd_table);
3653 cmd_desc_size = sizeof(struct utp_transfer_cmd_desc);
3654 cmd_desc_dma_addr = hba->ucdl_dma_addr;
3656 for (i = 0; i < hba->nutrs; i++) {
3657 /* Configure UTRD with command descriptor base address */
3658 cmd_desc_element_addr =
3659 (cmd_desc_dma_addr + (cmd_desc_size * i));
3660 utrdlp[i].command_desc_base_addr_lo =
3661 cpu_to_le32(lower_32_bits(cmd_desc_element_addr));
3662 utrdlp[i].command_desc_base_addr_hi =
3663 cpu_to_le32(upper_32_bits(cmd_desc_element_addr));
3665 /* Response upiu and prdt offset should be in double words */
3666 if (hba->quirks & UFSHCD_QUIRK_PRDT_BYTE_GRAN) {
3667 utrdlp[i].response_upiu_offset =
3668 cpu_to_le16(response_offset);
3669 utrdlp[i].prd_table_offset =
3670 cpu_to_le16(prdt_offset);
3671 utrdlp[i].response_upiu_length =
3672 cpu_to_le16(ALIGNED_UPIU_SIZE);
3674 utrdlp[i].response_upiu_offset =
3675 cpu_to_le16(response_offset >> 2);
3676 utrdlp[i].prd_table_offset =
3677 cpu_to_le16(prdt_offset >> 2);
3678 utrdlp[i].response_upiu_length =
3679 cpu_to_le16(ALIGNED_UPIU_SIZE >> 2);
3682 ufshcd_init_lrb(hba, &hba->lrb[i], i);
3687 * ufshcd_dme_link_startup - Notify Unipro to perform link startup
3688 * @hba: per adapter instance
3690 * UIC_CMD_DME_LINK_STARTUP command must be issued to Unipro layer,
3691 * in order to initialize the Unipro link startup procedure.
3692 * Once the Unipro links are up, the device connected to the controller
3695 * Returns 0 on success, non-zero value on failure
3697 static int ufshcd_dme_link_startup(struct ufs_hba *hba)
3699 struct uic_command uic_cmd = {0};
3702 uic_cmd.command = UIC_CMD_DME_LINK_STARTUP;
3704 ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
3707 "dme-link-startup: error code %d\n", ret);
3711 * ufshcd_dme_reset - UIC command for DME_RESET
3712 * @hba: per adapter instance
3714 * DME_RESET command is issued in order to reset UniPro stack.
3715 * This function now deals with cold reset.
3717 * Returns 0 on success, non-zero value on failure
3719 static int ufshcd_dme_reset(struct ufs_hba *hba)
3721 struct uic_command uic_cmd = {0};
3724 uic_cmd.command = UIC_CMD_DME_RESET;
3726 ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
3729 "dme-reset: error code %d\n", ret);
3734 int ufshcd_dme_configure_adapt(struct ufs_hba *hba,
3740 if (agreed_gear != UFS_HS_G4)
3741 adapt_val = PA_NO_ADAPT;
3743 ret = ufshcd_dme_set(hba,
3744 UIC_ARG_MIB(PA_TXHSADAPTTYPE),
3748 EXPORT_SYMBOL_GPL(ufshcd_dme_configure_adapt);
3751 * ufshcd_dme_enable - UIC command for DME_ENABLE
3752 * @hba: per adapter instance
3754 * DME_ENABLE command is issued in order to enable UniPro stack.
3756 * Returns 0 on success, non-zero value on failure
3758 static int ufshcd_dme_enable(struct ufs_hba *hba)
3760 struct uic_command uic_cmd = {0};
3763 uic_cmd.command = UIC_CMD_DME_ENABLE;
3765 ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
3768 "dme-enable: error code %d\n", ret);
3773 static inline void ufshcd_add_delay_before_dme_cmd(struct ufs_hba *hba)
3775 #define MIN_DELAY_BEFORE_DME_CMDS_US 1000
3776 unsigned long min_sleep_time_us;
3778 if (!(hba->quirks & UFSHCD_QUIRK_DELAY_BEFORE_DME_CMDS))
3782 * last_dme_cmd_tstamp will be 0 only for 1st call to
3785 if (unlikely(!ktime_to_us(hba->last_dme_cmd_tstamp))) {
3786 min_sleep_time_us = MIN_DELAY_BEFORE_DME_CMDS_US;
3788 unsigned long delta =
3789 (unsigned long) ktime_to_us(
3790 ktime_sub(ktime_get(),
3791 hba->last_dme_cmd_tstamp));
3793 if (delta < MIN_DELAY_BEFORE_DME_CMDS_US)
3795 MIN_DELAY_BEFORE_DME_CMDS_US - delta;
3797 return; /* no more delay required */
3800 /* allow sleep for extra 50us if needed */
3801 usleep_range(min_sleep_time_us, min_sleep_time_us + 50);
3805 * ufshcd_dme_set_attr - UIC command for DME_SET, DME_PEER_SET
3806 * @hba: per adapter instance
3807 * @attr_sel: uic command argument1
3808 * @attr_set: attribute set type as uic command argument2
3809 * @mib_val: setting value as uic command argument3
3810 * @peer: indicate whether peer or local
3812 * Returns 0 on success, non-zero value on failure
3814 int ufshcd_dme_set_attr(struct ufs_hba *hba, u32 attr_sel,
3815 u8 attr_set, u32 mib_val, u8 peer)
3817 struct uic_command uic_cmd = {0};
3818 static const char *const action[] = {
3822 const char *set = action[!!peer];
3824 int retries = UFS_UIC_COMMAND_RETRIES;
3826 uic_cmd.command = peer ?
3827 UIC_CMD_DME_PEER_SET : UIC_CMD_DME_SET;
3828 uic_cmd.argument1 = attr_sel;
3829 uic_cmd.argument2 = UIC_ARG_ATTR_TYPE(attr_set);
3830 uic_cmd.argument3 = mib_val;
3833 /* for peer attributes we retry upon failure */
3834 ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
3836 dev_dbg(hba->dev, "%s: attr-id 0x%x val 0x%x error code %d\n",
3837 set, UIC_GET_ATTR_ID(attr_sel), mib_val, ret);
3838 } while (ret && peer && --retries);
3841 dev_err(hba->dev, "%s: attr-id 0x%x val 0x%x failed %d retries\n",
3842 set, UIC_GET_ATTR_ID(attr_sel), mib_val,
3843 UFS_UIC_COMMAND_RETRIES - retries);
3847 EXPORT_SYMBOL_GPL(ufshcd_dme_set_attr);
3850 * ufshcd_dme_get_attr - UIC command for DME_GET, DME_PEER_GET
3851 * @hba: per adapter instance
3852 * @attr_sel: uic command argument1
3853 * @mib_val: the value of the attribute as returned by the UIC command
3854 * @peer: indicate whether peer or local
3856 * Returns 0 on success, non-zero value on failure
3858 int ufshcd_dme_get_attr(struct ufs_hba *hba, u32 attr_sel,
3859 u32 *mib_val, u8 peer)
3861 struct uic_command uic_cmd = {0};
3862 static const char *const action[] = {
3866 const char *get = action[!!peer];
3868 int retries = UFS_UIC_COMMAND_RETRIES;
3869 struct ufs_pa_layer_attr orig_pwr_info;
3870 struct ufs_pa_layer_attr temp_pwr_info;
3871 bool pwr_mode_change = false;
3873 if (peer && (hba->quirks & UFSHCD_QUIRK_DME_PEER_ACCESS_AUTO_MODE)) {
3874 orig_pwr_info = hba->pwr_info;
3875 temp_pwr_info = orig_pwr_info;
3877 if (orig_pwr_info.pwr_tx == FAST_MODE ||
3878 orig_pwr_info.pwr_rx == FAST_MODE) {
3879 temp_pwr_info.pwr_tx = FASTAUTO_MODE;
3880 temp_pwr_info.pwr_rx = FASTAUTO_MODE;
3881 pwr_mode_change = true;
3882 } else if (orig_pwr_info.pwr_tx == SLOW_MODE ||
3883 orig_pwr_info.pwr_rx == SLOW_MODE) {
3884 temp_pwr_info.pwr_tx = SLOWAUTO_MODE;
3885 temp_pwr_info.pwr_rx = SLOWAUTO_MODE;
3886 pwr_mode_change = true;
3888 if (pwr_mode_change) {
3889 ret = ufshcd_change_power_mode(hba, &temp_pwr_info);
3895 uic_cmd.command = peer ?
3896 UIC_CMD_DME_PEER_GET : UIC_CMD_DME_GET;
3897 uic_cmd.argument1 = attr_sel;
3900 /* for peer attributes we retry upon failure */
3901 ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
3903 dev_dbg(hba->dev, "%s: attr-id 0x%x error code %d\n",
3904 get, UIC_GET_ATTR_ID(attr_sel), ret);
3905 } while (ret && peer && --retries);
3908 dev_err(hba->dev, "%s: attr-id 0x%x failed %d retries\n",
3909 get, UIC_GET_ATTR_ID(attr_sel),
3910 UFS_UIC_COMMAND_RETRIES - retries);
3912 if (mib_val && !ret)
3913 *mib_val = uic_cmd.argument3;
3915 if (peer && (hba->quirks & UFSHCD_QUIRK_DME_PEER_ACCESS_AUTO_MODE)
3917 ufshcd_change_power_mode(hba, &orig_pwr_info);
3921 EXPORT_SYMBOL_GPL(ufshcd_dme_get_attr);
3923 static inline bool ufshcd_is_saved_err_fatal(struct ufs_hba *hba)
3925 lockdep_assert_held(hba->host->host_lock);
3927 return (hba->saved_uic_err & UFSHCD_UIC_DL_PA_INIT_ERROR) ||
3928 (hba->saved_err & (INT_FATAL_ERRORS | UFSHCD_UIC_HIBERN8_MASK));
3931 static void ufshcd_schedule_eh(struct ufs_hba *hba)
3933 bool schedule_eh = false;
3934 unsigned long flags;
3936 spin_lock_irqsave(hba->host->host_lock, flags);
3937 /* handle fatal errors only when link is not in error state */
3938 if (hba->ufshcd_state != UFSHCD_STATE_ERROR) {
3939 if (hba->force_reset || ufshcd_is_link_broken(hba) ||
3940 ufshcd_is_saved_err_fatal(hba))
3941 hba->ufshcd_state = UFSHCD_STATE_EH_SCHEDULED_FATAL;
3943 hba->ufshcd_state = UFSHCD_STATE_EH_SCHEDULED_NON_FATAL;
3946 spin_unlock_irqrestore(hba->host->host_lock, flags);
3949 scsi_schedule_eh(hba->host);
3953 * ufshcd_uic_pwr_ctrl - executes UIC commands (which affects the link power
3954 * state) and waits for it to take effect.
3956 * @hba: per adapter instance
3957 * @cmd: UIC command to execute
3959 * DME operations like DME_SET(PA_PWRMODE), DME_HIBERNATE_ENTER &
3960 * DME_HIBERNATE_EXIT commands take some time to take its effect on both host
3961 * and device UniPro link and hence it's final completion would be indicated by
3962 * dedicated status bits in Interrupt Status register (UPMS, UHES, UHXS) in
3963 * addition to normal UIC command completion Status (UCCS). This function only
3964 * returns after the relevant status bits indicate the completion.
3966 * Returns 0 on success, non-zero value on failure
3968 static int ufshcd_uic_pwr_ctrl(struct ufs_hba *hba, struct uic_command *cmd)
3970 DECLARE_COMPLETION_ONSTACK(uic_async_done);
3971 unsigned long flags;
3972 bool schedule_eh = false;
3975 bool reenable_intr = false;
3977 mutex_lock(&hba->uic_cmd_mutex);
3978 ufshcd_add_delay_before_dme_cmd(hba);
3980 spin_lock_irqsave(hba->host->host_lock, flags);
3981 if (ufshcd_is_link_broken(hba)) {
3985 hba->uic_async_done = &uic_async_done;
3986 if (ufshcd_readl(hba, REG_INTERRUPT_ENABLE) & UIC_COMMAND_COMPL) {
3987 ufshcd_disable_intr(hba, UIC_COMMAND_COMPL);
3989 * Make sure UIC command completion interrupt is disabled before
3990 * issuing UIC command.
3993 reenable_intr = true;
3995 ret = __ufshcd_send_uic_cmd(hba, cmd, false);
3996 spin_unlock_irqrestore(hba->host->host_lock, flags);
3999 "pwr ctrl cmd 0x%x with mode 0x%x uic error %d\n",
4000 cmd->command, cmd->argument3, ret);
4004 if (!wait_for_completion_timeout(hba->uic_async_done,
4005 msecs_to_jiffies(UIC_CMD_TIMEOUT))) {
4007 "pwr ctrl cmd 0x%x with mode 0x%x completion timeout\n",
4008 cmd->command, cmd->argument3);
4010 if (!cmd->cmd_active) {
4011 dev_err(hba->dev, "%s: Power Mode Change operation has been completed, go check UPMCRS\n",
4021 status = ufshcd_get_upmcrs(hba);
4022 if (status != PWR_LOCAL) {
4024 "pwr ctrl cmd 0x%x failed, host upmcrs:0x%x\n",
4025 cmd->command, status);
4026 ret = (status != PWR_OK) ? status : -1;
4030 ufshcd_print_host_state(hba);
4031 ufshcd_print_pwr_info(hba);
4032 ufshcd_print_evt_hist(hba);
4035 spin_lock_irqsave(hba->host->host_lock, flags);
4036 hba->active_uic_cmd = NULL;
4037 hba->uic_async_done = NULL;
4039 ufshcd_enable_intr(hba, UIC_COMMAND_COMPL);
4041 ufshcd_set_link_broken(hba);
4046 spin_unlock_irqrestore(hba->host->host_lock, flags);
4049 ufshcd_schedule_eh(hba);
4050 mutex_unlock(&hba->uic_cmd_mutex);
4056 * ufshcd_uic_change_pwr_mode - Perform the UIC power mode chage
4057 * using DME_SET primitives.
4058 * @hba: per adapter instance
4059 * @mode: powr mode value
4061 * Returns 0 on success, non-zero value on failure
4063 static int ufshcd_uic_change_pwr_mode(struct ufs_hba *hba, u8 mode)
4065 struct uic_command uic_cmd = {0};
4068 if (hba->quirks & UFSHCD_QUIRK_BROKEN_PA_RXHSUNTERMCAP) {
4069 ret = ufshcd_dme_set(hba,
4070 UIC_ARG_MIB_SEL(PA_RXHSUNTERMCAP, 0), 1);
4072 dev_err(hba->dev, "%s: failed to enable PA_RXHSUNTERMCAP ret %d\n",
4078 uic_cmd.command = UIC_CMD_DME_SET;
4079 uic_cmd.argument1 = UIC_ARG_MIB(PA_PWRMODE);
4080 uic_cmd.argument3 = mode;
4081 ufshcd_hold(hba, false);
4082 ret = ufshcd_uic_pwr_ctrl(hba, &uic_cmd);
4083 ufshcd_release(hba);
4089 int ufshcd_link_recovery(struct ufs_hba *hba)
4092 unsigned long flags;
4094 spin_lock_irqsave(hba->host->host_lock, flags);
4095 hba->ufshcd_state = UFSHCD_STATE_RESET;
4096 ufshcd_set_eh_in_progress(hba);
4097 spin_unlock_irqrestore(hba->host->host_lock, flags);
4099 /* Reset the attached device */
4100 ufshcd_device_reset(hba);
4102 ret = ufshcd_host_reset_and_restore(hba);
4104 spin_lock_irqsave(hba->host->host_lock, flags);
4106 hba->ufshcd_state = UFSHCD_STATE_ERROR;
4107 ufshcd_clear_eh_in_progress(hba);
4108 spin_unlock_irqrestore(hba->host->host_lock, flags);
4111 dev_err(hba->dev, "%s: link recovery failed, err %d",
4116 EXPORT_SYMBOL_GPL(ufshcd_link_recovery);
4118 int ufshcd_uic_hibern8_enter(struct ufs_hba *hba)
4121 struct uic_command uic_cmd = {0};
4122 ktime_t start = ktime_get();
4124 ufshcd_vops_hibern8_notify(hba, UIC_CMD_DME_HIBER_ENTER, PRE_CHANGE);
4126 uic_cmd.command = UIC_CMD_DME_HIBER_ENTER;
4127 ret = ufshcd_uic_pwr_ctrl(hba, &uic_cmd);
4128 trace_ufshcd_profile_hibern8(dev_name(hba->dev), "enter",
4129 ktime_to_us(ktime_sub(ktime_get(), start)), ret);
4132 dev_err(hba->dev, "%s: hibern8 enter failed. ret = %d\n",
4135 ufshcd_vops_hibern8_notify(hba, UIC_CMD_DME_HIBER_ENTER,
4140 EXPORT_SYMBOL_GPL(ufshcd_uic_hibern8_enter);
4142 int ufshcd_uic_hibern8_exit(struct ufs_hba *hba)
4144 struct uic_command uic_cmd = {0};
4146 ktime_t start = ktime_get();
4148 ufshcd_vops_hibern8_notify(hba, UIC_CMD_DME_HIBER_EXIT, PRE_CHANGE);
4150 uic_cmd.command = UIC_CMD_DME_HIBER_EXIT;
4151 ret = ufshcd_uic_pwr_ctrl(hba, &uic_cmd);
4152 trace_ufshcd_profile_hibern8(dev_name(hba->dev), "exit",
4153 ktime_to_us(ktime_sub(ktime_get(), start)), ret);
4156 dev_err(hba->dev, "%s: hibern8 exit failed. ret = %d\n",
4159 ufshcd_vops_hibern8_notify(hba, UIC_CMD_DME_HIBER_EXIT,
4161 hba->ufs_stats.last_hibern8_exit_tstamp = ktime_get();
4162 hba->ufs_stats.hibern8_exit_cnt++;
4167 EXPORT_SYMBOL_GPL(ufshcd_uic_hibern8_exit);
4169 void ufshcd_auto_hibern8_update(struct ufs_hba *hba, u32 ahit)
4171 unsigned long flags;
4172 bool update = false;
4174 if (!ufshcd_is_auto_hibern8_supported(hba))
4177 spin_lock_irqsave(hba->host->host_lock, flags);
4178 if (hba->ahit != ahit) {
4182 spin_unlock_irqrestore(hba->host->host_lock, flags);
4185 !pm_runtime_suspended(&hba->sdev_ufs_device->sdev_gendev)) {
4186 ufshcd_rpm_get_sync(hba);
4187 ufshcd_hold(hba, false);
4188 ufshcd_auto_hibern8_enable(hba);
4189 ufshcd_release(hba);
4190 ufshcd_rpm_put_sync(hba);
4193 EXPORT_SYMBOL_GPL(ufshcd_auto_hibern8_update);
4195 void ufshcd_auto_hibern8_enable(struct ufs_hba *hba)
4197 unsigned long flags;
4199 if (!ufshcd_is_auto_hibern8_supported(hba))
4202 spin_lock_irqsave(hba->host->host_lock, flags);
4203 ufshcd_writel(hba, hba->ahit, REG_AUTO_HIBERNATE_IDLE_TIMER);
4204 spin_unlock_irqrestore(hba->host->host_lock, flags);
4208 * ufshcd_init_pwr_info - setting the POR (power on reset)
4209 * values in hba power info
4210 * @hba: per-adapter instance
4212 static void ufshcd_init_pwr_info(struct ufs_hba *hba)
4214 hba->pwr_info.gear_rx = UFS_PWM_G1;
4215 hba->pwr_info.gear_tx = UFS_PWM_G1;
4216 hba->pwr_info.lane_rx = 1;
4217 hba->pwr_info.lane_tx = 1;
4218 hba->pwr_info.pwr_rx = SLOWAUTO_MODE;
4219 hba->pwr_info.pwr_tx = SLOWAUTO_MODE;
4220 hba->pwr_info.hs_rate = 0;
4224 * ufshcd_get_max_pwr_mode - reads the max power mode negotiated with device
4225 * @hba: per-adapter instance
4227 static int ufshcd_get_max_pwr_mode(struct ufs_hba *hba)
4229 struct ufs_pa_layer_attr *pwr_info = &hba->max_pwr_info.info;
4231 if (hba->max_pwr_info.is_valid)
4234 pwr_info->pwr_tx = FAST_MODE;
4235 pwr_info->pwr_rx = FAST_MODE;
4236 pwr_info->hs_rate = PA_HS_MODE_B;
4238 /* Get the connected lane count */
4239 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_CONNECTEDRXDATALANES),
4240 &pwr_info->lane_rx);
4241 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_CONNECTEDTXDATALANES),
4242 &pwr_info->lane_tx);
4244 if (!pwr_info->lane_rx || !pwr_info->lane_tx) {
4245 dev_err(hba->dev, "%s: invalid connected lanes value. rx=%d, tx=%d\n",
4253 * First, get the maximum gears of HS speed.
4254 * If a zero value, it means there is no HSGEAR capability.
4255 * Then, get the maximum gears of PWM speed.
4257 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_MAXRXHSGEAR), &pwr_info->gear_rx);
4258 if (!pwr_info->gear_rx) {
4259 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_MAXRXPWMGEAR),
4260 &pwr_info->gear_rx);
4261 if (!pwr_info->gear_rx) {
4262 dev_err(hba->dev, "%s: invalid max pwm rx gear read = %d\n",
4263 __func__, pwr_info->gear_rx);
4266 pwr_info->pwr_rx = SLOW_MODE;
4269 ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_MAXRXHSGEAR),
4270 &pwr_info->gear_tx);
4271 if (!pwr_info->gear_tx) {
4272 ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_MAXRXPWMGEAR),
4273 &pwr_info->gear_tx);
4274 if (!pwr_info->gear_tx) {
4275 dev_err(hba->dev, "%s: invalid max pwm tx gear read = %d\n",
4276 __func__, pwr_info->gear_tx);
4279 pwr_info->pwr_tx = SLOW_MODE;
4282 hba->max_pwr_info.is_valid = true;
4286 static int ufshcd_change_power_mode(struct ufs_hba *hba,
4287 struct ufs_pa_layer_attr *pwr_mode)
4291 /* if already configured to the requested pwr_mode */
4292 if (!hba->force_pmc &&
4293 pwr_mode->gear_rx == hba->pwr_info.gear_rx &&
4294 pwr_mode->gear_tx == hba->pwr_info.gear_tx &&
4295 pwr_mode->lane_rx == hba->pwr_info.lane_rx &&
4296 pwr_mode->lane_tx == hba->pwr_info.lane_tx &&
4297 pwr_mode->pwr_rx == hba->pwr_info.pwr_rx &&
4298 pwr_mode->pwr_tx == hba->pwr_info.pwr_tx &&
4299 pwr_mode->hs_rate == hba->pwr_info.hs_rate) {
4300 dev_dbg(hba->dev, "%s: power already configured\n", __func__);
4305 * Configure attributes for power mode change with below.
4306 * - PA_RXGEAR, PA_ACTIVERXDATALANES, PA_RXTERMINATION,
4307 * - PA_TXGEAR, PA_ACTIVETXDATALANES, PA_TXTERMINATION,
4310 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_RXGEAR), pwr_mode->gear_rx);
4311 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_ACTIVERXDATALANES),
4313 if (pwr_mode->pwr_rx == FASTAUTO_MODE ||
4314 pwr_mode->pwr_rx == FAST_MODE)
4315 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_RXTERMINATION), TRUE);
4317 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_RXTERMINATION), FALSE);
4319 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TXGEAR), pwr_mode->gear_tx);
4320 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_ACTIVETXDATALANES),
4322 if (pwr_mode->pwr_tx == FASTAUTO_MODE ||
4323 pwr_mode->pwr_tx == FAST_MODE)
4324 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TXTERMINATION), TRUE);
4326 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TXTERMINATION), FALSE);
4328 if (pwr_mode->pwr_rx == FASTAUTO_MODE ||
4329 pwr_mode->pwr_tx == FASTAUTO_MODE ||
4330 pwr_mode->pwr_rx == FAST_MODE ||
4331 pwr_mode->pwr_tx == FAST_MODE)
4332 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_HSSERIES),
4335 if (!(hba->quirks & UFSHCD_QUIRK_SKIP_DEF_UNIPRO_TIMEOUT_SETTING)) {
4336 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_PWRMODEUSERDATA0),
4337 DL_FC0ProtectionTimeOutVal_Default);
4338 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_PWRMODEUSERDATA1),
4339 DL_TC0ReplayTimeOutVal_Default);
4340 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_PWRMODEUSERDATA2),
4341 DL_AFC0ReqTimeOutVal_Default);
4342 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_PWRMODEUSERDATA3),
4343 DL_FC1ProtectionTimeOutVal_Default);
4344 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_PWRMODEUSERDATA4),
4345 DL_TC1ReplayTimeOutVal_Default);
4346 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_PWRMODEUSERDATA5),
4347 DL_AFC1ReqTimeOutVal_Default);
4349 ufshcd_dme_set(hba, UIC_ARG_MIB(DME_LocalFC0ProtectionTimeOutVal),
4350 DL_FC0ProtectionTimeOutVal_Default);
4351 ufshcd_dme_set(hba, UIC_ARG_MIB(DME_LocalTC0ReplayTimeOutVal),
4352 DL_TC0ReplayTimeOutVal_Default);
4353 ufshcd_dme_set(hba, UIC_ARG_MIB(DME_LocalAFC0ReqTimeOutVal),
4354 DL_AFC0ReqTimeOutVal_Default);
4357 ret = ufshcd_uic_change_pwr_mode(hba, pwr_mode->pwr_rx << 4
4358 | pwr_mode->pwr_tx);
4362 "%s: power mode change failed %d\n", __func__, ret);
4364 ufshcd_vops_pwr_change_notify(hba, POST_CHANGE, NULL,
4367 memcpy(&hba->pwr_info, pwr_mode,
4368 sizeof(struct ufs_pa_layer_attr));
4375 * ufshcd_config_pwr_mode - configure a new power mode
4376 * @hba: per-adapter instance
4377 * @desired_pwr_mode: desired power configuration
4379 int ufshcd_config_pwr_mode(struct ufs_hba *hba,
4380 struct ufs_pa_layer_attr *desired_pwr_mode)
4382 struct ufs_pa_layer_attr final_params = { 0 };
4385 ret = ufshcd_vops_pwr_change_notify(hba, PRE_CHANGE,
4386 desired_pwr_mode, &final_params);
4389 memcpy(&final_params, desired_pwr_mode, sizeof(final_params));
4391 ret = ufshcd_change_power_mode(hba, &final_params);
4395 EXPORT_SYMBOL_GPL(ufshcd_config_pwr_mode);
4398 * ufshcd_complete_dev_init() - checks device readiness
4399 * @hba: per-adapter instance
4401 * Set fDeviceInit flag and poll until device toggles it.
4403 static int ufshcd_complete_dev_init(struct ufs_hba *hba)
4406 bool flag_res = true;
4409 err = ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_SET_FLAG,
4410 QUERY_FLAG_IDN_FDEVICEINIT, 0, NULL);
4413 "%s setting fDeviceInit flag failed with error %d\n",
4418 /* Poll fDeviceInit flag to be cleared */
4419 timeout = ktime_add_ms(ktime_get(), FDEVICEINIT_COMPL_TIMEOUT);
4421 err = ufshcd_query_flag(hba, UPIU_QUERY_OPCODE_READ_FLAG,
4422 QUERY_FLAG_IDN_FDEVICEINIT, 0, &flag_res);
4425 usleep_range(5000, 10000);
4426 } while (ktime_before(ktime_get(), timeout));
4430 "%s reading fDeviceInit flag failed with error %d\n",
4432 } else if (flag_res) {
4434 "%s fDeviceInit was not cleared by the device\n",
4443 * ufshcd_make_hba_operational - Make UFS controller operational
4444 * @hba: per adapter instance
4446 * To bring UFS host controller to operational state,
4447 * 1. Enable required interrupts
4448 * 2. Configure interrupt aggregation
4449 * 3. Program UTRL and UTMRL base address
4450 * 4. Configure run-stop-registers
4452 * Returns 0 on success, non-zero value on failure
4454 int ufshcd_make_hba_operational(struct ufs_hba *hba)
4459 /* Enable required interrupts */
4460 ufshcd_enable_intr(hba, UFSHCD_ENABLE_INTRS);
4462 /* Configure interrupt aggregation */
4463 if (ufshcd_is_intr_aggr_allowed(hba))
4464 ufshcd_config_intr_aggr(hba, hba->nutrs - 1, INT_AGGR_DEF_TO);
4466 ufshcd_disable_intr_aggr(hba);
4468 /* Configure UTRL and UTMRL base address registers */
4469 ufshcd_writel(hba, lower_32_bits(hba->utrdl_dma_addr),
4470 REG_UTP_TRANSFER_REQ_LIST_BASE_L);
4471 ufshcd_writel(hba, upper_32_bits(hba->utrdl_dma_addr),
4472 REG_UTP_TRANSFER_REQ_LIST_BASE_H);
4473 ufshcd_writel(hba, lower_32_bits(hba->utmrdl_dma_addr),
4474 REG_UTP_TASK_REQ_LIST_BASE_L);
4475 ufshcd_writel(hba, upper_32_bits(hba->utmrdl_dma_addr),
4476 REG_UTP_TASK_REQ_LIST_BASE_H);
4479 * Make sure base address and interrupt setup are updated before
4480 * enabling the run/stop registers below.
4485 * UCRDY, UTMRLDY and UTRLRDY bits must be 1
4487 reg = ufshcd_readl(hba, REG_CONTROLLER_STATUS);
4488 if (!(ufshcd_get_lists_status(reg))) {
4489 ufshcd_enable_run_stop_reg(hba);
4492 "Host controller not ready to process requests");
4498 EXPORT_SYMBOL_GPL(ufshcd_make_hba_operational);
4501 * ufshcd_hba_stop - Send controller to reset state
4502 * @hba: per adapter instance
4504 void ufshcd_hba_stop(struct ufs_hba *hba)
4506 unsigned long flags;
4510 * Obtain the host lock to prevent that the controller is disabled
4511 * while the UFS interrupt handler is active on another CPU.
4513 spin_lock_irqsave(hba->host->host_lock, flags);
4514 ufshcd_writel(hba, CONTROLLER_DISABLE, REG_CONTROLLER_ENABLE);
4515 spin_unlock_irqrestore(hba->host->host_lock, flags);
4517 err = ufshcd_wait_for_register(hba, REG_CONTROLLER_ENABLE,
4518 CONTROLLER_ENABLE, CONTROLLER_DISABLE,
4521 dev_err(hba->dev, "%s: Controller disable failed\n", __func__);
4523 EXPORT_SYMBOL_GPL(ufshcd_hba_stop);
4526 * ufshcd_hba_execute_hce - initialize the controller
4527 * @hba: per adapter instance
4529 * The controller resets itself and controller firmware initialization
4530 * sequence kicks off. When controller is ready it will set
4531 * the Host Controller Enable bit to 1.
4533 * Returns 0 on success, non-zero value on failure
4535 static int ufshcd_hba_execute_hce(struct ufs_hba *hba)
4537 int retry_outer = 3;
4541 if (!ufshcd_is_hba_active(hba))
4542 /* change controller state to "reset state" */
4543 ufshcd_hba_stop(hba);
4545 /* UniPro link is disabled at this point */
4546 ufshcd_set_link_off(hba);
4548 ufshcd_vops_hce_enable_notify(hba, PRE_CHANGE);
4550 /* start controller initialization sequence */
4551 ufshcd_hba_start(hba);
4554 * To initialize a UFS host controller HCE bit must be set to 1.
4555 * During initialization the HCE bit value changes from 1->0->1.
4556 * When the host controller completes initialization sequence
4557 * it sets the value of HCE bit to 1. The same HCE bit is read back
4558 * to check if the controller has completed initialization sequence.
4559 * So without this delay the value HCE = 1, set in the previous
4560 * instruction might be read back.
4561 * This delay can be changed based on the controller.
4563 ufshcd_delay_us(hba->vps->hba_enable_delay_us, 100);
4565 /* wait for the host controller to complete initialization */
4567 while (ufshcd_is_hba_active(hba)) {
4572 "Controller enable failed\n");
4579 usleep_range(1000, 1100);
4582 /* enable UIC related interrupts */
4583 ufshcd_enable_intr(hba, UFSHCD_UIC_MASK);
4585 ufshcd_vops_hce_enable_notify(hba, POST_CHANGE);
4590 int ufshcd_hba_enable(struct ufs_hba *hba)
4594 if (hba->quirks & UFSHCI_QUIRK_BROKEN_HCE) {
4595 ufshcd_set_link_off(hba);
4596 ufshcd_vops_hce_enable_notify(hba, PRE_CHANGE);
4598 /* enable UIC related interrupts */
4599 ufshcd_enable_intr(hba, UFSHCD_UIC_MASK);
4600 ret = ufshcd_dme_reset(hba);
4602 ret = ufshcd_dme_enable(hba);
4604 ufshcd_vops_hce_enable_notify(hba, POST_CHANGE);
4607 "Host controller enable failed with non-hce\n");
4610 ret = ufshcd_hba_execute_hce(hba);
4615 EXPORT_SYMBOL_GPL(ufshcd_hba_enable);
4617 static int ufshcd_disable_tx_lcc(struct ufs_hba *hba, bool peer)
4619 int tx_lanes = 0, i, err = 0;
4622 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_CONNECTEDTXDATALANES),
4625 ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_CONNECTEDTXDATALANES),
4627 for (i = 0; i < tx_lanes; i++) {
4629 err = ufshcd_dme_set(hba,
4630 UIC_ARG_MIB_SEL(TX_LCC_ENABLE,
4631 UIC_ARG_MPHY_TX_GEN_SEL_INDEX(i)),
4634 err = ufshcd_dme_peer_set(hba,
4635 UIC_ARG_MIB_SEL(TX_LCC_ENABLE,
4636 UIC_ARG_MPHY_TX_GEN_SEL_INDEX(i)),
4639 dev_err(hba->dev, "%s: TX LCC Disable failed, peer = %d, lane = %d, err = %d",
4640 __func__, peer, i, err);
4648 static inline int ufshcd_disable_device_tx_lcc(struct ufs_hba *hba)
4650 return ufshcd_disable_tx_lcc(hba, true);
4653 void ufshcd_update_evt_hist(struct ufs_hba *hba, u32 id, u32 val)
4655 struct ufs_event_hist *e;
4657 if (id >= UFS_EVT_CNT)
4660 e = &hba->ufs_stats.event[id];
4661 e->val[e->pos] = val;
4662 e->tstamp[e->pos] = ktime_get();
4664 e->pos = (e->pos + 1) % UFS_EVENT_HIST_LENGTH;
4666 ufshcd_vops_event_notify(hba, id, &val);
4668 EXPORT_SYMBOL_GPL(ufshcd_update_evt_hist);
4671 * ufshcd_link_startup - Initialize unipro link startup
4672 * @hba: per adapter instance
4674 * Returns 0 for success, non-zero in case of failure
4676 static int ufshcd_link_startup(struct ufs_hba *hba)
4679 int retries = DME_LINKSTARTUP_RETRIES;
4680 bool link_startup_again = false;
4683 * If UFS device isn't active then we will have to issue link startup
4684 * 2 times to make sure the device state move to active.
4686 if (!ufshcd_is_ufs_dev_active(hba))
4687 link_startup_again = true;
4691 ufshcd_vops_link_startup_notify(hba, PRE_CHANGE);
4693 ret = ufshcd_dme_link_startup(hba);
4695 /* check if device is detected by inter-connect layer */
4696 if (!ret && !ufshcd_is_device_present(hba)) {
4697 ufshcd_update_evt_hist(hba,
4698 UFS_EVT_LINK_STARTUP_FAIL,
4700 dev_err(hba->dev, "%s: Device not present\n", __func__);
4706 * DME link lost indication is only received when link is up,
4707 * but we can't be sure if the link is up until link startup
4708 * succeeds. So reset the local Uni-Pro and try again.
4710 if (ret && ufshcd_hba_enable(hba)) {
4711 ufshcd_update_evt_hist(hba,
4712 UFS_EVT_LINK_STARTUP_FAIL,
4716 } while (ret && retries--);
4719 /* failed to get the link up... retire */
4720 ufshcd_update_evt_hist(hba,
4721 UFS_EVT_LINK_STARTUP_FAIL,
4726 if (link_startup_again) {
4727 link_startup_again = false;
4728 retries = DME_LINKSTARTUP_RETRIES;
4732 /* Mark that link is up in PWM-G1, 1-lane, SLOW-AUTO mode */
4733 ufshcd_init_pwr_info(hba);
4734 ufshcd_print_pwr_info(hba);
4736 if (hba->quirks & UFSHCD_QUIRK_BROKEN_LCC) {
4737 ret = ufshcd_disable_device_tx_lcc(hba);
4742 /* Include any host controller configuration via UIC commands */
4743 ret = ufshcd_vops_link_startup_notify(hba, POST_CHANGE);
4747 /* Clear UECPA once due to LINERESET has happened during LINK_STARTUP */
4748 ufshcd_readl(hba, REG_UIC_ERROR_CODE_PHY_ADAPTER_LAYER);
4749 ret = ufshcd_make_hba_operational(hba);
4752 dev_err(hba->dev, "link startup failed %d\n", ret);
4753 ufshcd_print_host_state(hba);
4754 ufshcd_print_pwr_info(hba);
4755 ufshcd_print_evt_hist(hba);
4761 * ufshcd_verify_dev_init() - Verify device initialization
4762 * @hba: per-adapter instance
4764 * Send NOP OUT UPIU and wait for NOP IN response to check whether the
4765 * device Transport Protocol (UTP) layer is ready after a reset.
4766 * If the UTP layer at the device side is not initialized, it may
4767 * not respond with NOP IN UPIU within timeout of %NOP_OUT_TIMEOUT
4768 * and we retry sending NOP OUT for %NOP_OUT_RETRIES iterations.
4770 static int ufshcd_verify_dev_init(struct ufs_hba *hba)
4775 ufshcd_hold(hba, false);
4776 mutex_lock(&hba->dev_cmd.lock);
4777 for (retries = NOP_OUT_RETRIES; retries > 0; retries--) {
4778 err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_NOP,
4781 if (!err || err == -ETIMEDOUT)
4784 dev_dbg(hba->dev, "%s: error %d retrying\n", __func__, err);
4786 mutex_unlock(&hba->dev_cmd.lock);
4787 ufshcd_release(hba);
4790 dev_err(hba->dev, "%s: NOP OUT failed %d\n", __func__, err);
4795 * ufshcd_set_queue_depth - set lun queue depth
4796 * @sdev: pointer to SCSI device
4798 * Read bLUQueueDepth value and activate scsi tagged command
4799 * queueing. For WLUN, queue depth is set to 1. For best-effort
4800 * cases (bLUQueueDepth = 0) the queue depth is set to a maximum
4801 * value that host can queue.
4803 static void ufshcd_set_queue_depth(struct scsi_device *sdev)
4807 struct ufs_hba *hba;
4809 hba = shost_priv(sdev->host);
4811 lun_qdepth = hba->nutrs;
4812 ret = ufshcd_read_unit_desc_param(hba,
4813 ufshcd_scsi_to_upiu_lun(sdev->lun),
4814 UNIT_DESC_PARAM_LU_Q_DEPTH,
4816 sizeof(lun_qdepth));
4818 /* Some WLUN doesn't support unit descriptor */
4819 if (ret == -EOPNOTSUPP)
4821 else if (!lun_qdepth)
4822 /* eventually, we can figure out the real queue depth */
4823 lun_qdepth = hba->nutrs;
4825 lun_qdepth = min_t(int, lun_qdepth, hba->nutrs);
4827 dev_dbg(hba->dev, "%s: activate tcq with queue depth %d\n",
4828 __func__, lun_qdepth);
4829 scsi_change_queue_depth(sdev, lun_qdepth);
4833 * ufshcd_get_lu_wp - returns the "b_lu_write_protect" from UNIT DESCRIPTOR
4834 * @hba: per-adapter instance
4835 * @lun: UFS device lun id
4836 * @b_lu_write_protect: pointer to buffer to hold the LU's write protect info
4838 * Returns 0 in case of success and b_lu_write_protect status would be returned
4839 * @b_lu_write_protect parameter.
4840 * Returns -ENOTSUPP if reading b_lu_write_protect is not supported.
4841 * Returns -EINVAL in case of invalid parameters passed to this function.
4843 static int ufshcd_get_lu_wp(struct ufs_hba *hba,
4845 u8 *b_lu_write_protect)
4849 if (!b_lu_write_protect)
4852 * According to UFS device spec, RPMB LU can't be write
4853 * protected so skip reading bLUWriteProtect parameter for
4854 * it. For other W-LUs, UNIT DESCRIPTOR is not available.
4856 else if (lun >= hba->dev_info.max_lu_supported)
4859 ret = ufshcd_read_unit_desc_param(hba,
4861 UNIT_DESC_PARAM_LU_WR_PROTECT,
4863 sizeof(*b_lu_write_protect));
4868 * ufshcd_get_lu_power_on_wp_status - get LU's power on write protect
4870 * @hba: per-adapter instance
4871 * @sdev: pointer to SCSI device
4874 static inline void ufshcd_get_lu_power_on_wp_status(struct ufs_hba *hba,
4875 struct scsi_device *sdev)
4877 if (hba->dev_info.f_power_on_wp_en &&
4878 !hba->dev_info.is_lu_power_on_wp) {
4879 u8 b_lu_write_protect;
4881 if (!ufshcd_get_lu_wp(hba, ufshcd_scsi_to_upiu_lun(sdev->lun),
4882 &b_lu_write_protect) &&
4883 (b_lu_write_protect == UFS_LU_POWER_ON_WP))
4884 hba->dev_info.is_lu_power_on_wp = true;
4889 * ufshcd_setup_links - associate link b/w device wlun and other luns
4890 * @sdev: pointer to SCSI device
4891 * @hba: pointer to ufs hba
4893 static void ufshcd_setup_links(struct ufs_hba *hba, struct scsi_device *sdev)
4895 struct device_link *link;
4898 * Device wlun is the supplier & rest of the luns are consumers.
4899 * This ensures that device wlun suspends after all other luns.
4901 if (hba->sdev_ufs_device) {
4902 link = device_link_add(&sdev->sdev_gendev,
4903 &hba->sdev_ufs_device->sdev_gendev,
4904 DL_FLAG_PM_RUNTIME | DL_FLAG_RPM_ACTIVE);
4906 dev_err(&sdev->sdev_gendev, "Failed establishing link - %s\n",
4907 dev_name(&hba->sdev_ufs_device->sdev_gendev));
4911 /* Ignore REPORT_LUN wlun probing */
4912 if (hba->luns_avail == 1) {
4913 ufshcd_rpm_put(hba);
4918 * Device wlun is probed. The assumption is that WLUNs are
4919 * scanned before other LUNs.
4926 * ufshcd_slave_alloc - handle initial SCSI device configurations
4927 * @sdev: pointer to SCSI device
4931 static int ufshcd_slave_alloc(struct scsi_device *sdev)
4933 struct ufs_hba *hba;
4935 hba = shost_priv(sdev->host);
4937 /* Mode sense(6) is not supported by UFS, so use Mode sense(10) */
4938 sdev->use_10_for_ms = 1;
4940 /* DBD field should be set to 1 in mode sense(10) */
4941 sdev->set_dbd_for_ms = 1;
4943 /* allow SCSI layer to restart the device in case of errors */
4944 sdev->allow_restart = 1;
4946 /* REPORT SUPPORTED OPERATION CODES is not supported */
4947 sdev->no_report_opcodes = 1;
4949 /* WRITE_SAME command is not supported */
4950 sdev->no_write_same = 1;
4952 ufshcd_set_queue_depth(sdev);
4954 ufshcd_get_lu_power_on_wp_status(hba, sdev);
4956 ufshcd_setup_links(hba, sdev);
4962 * ufshcd_change_queue_depth - change queue depth
4963 * @sdev: pointer to SCSI device
4964 * @depth: required depth to set
4966 * Change queue depth and make sure the max. limits are not crossed.
4968 static int ufshcd_change_queue_depth(struct scsi_device *sdev, int depth)
4970 struct ufs_hba *hba = shost_priv(sdev->host);
4972 if (depth > hba->nutrs)
4974 return scsi_change_queue_depth(sdev, depth);
4977 static void ufshcd_hpb_destroy(struct ufs_hba *hba, struct scsi_device *sdev)
4979 /* skip well-known LU */
4980 if ((sdev->lun >= UFS_UPIU_MAX_UNIT_NUM_ID) ||
4981 !(hba->dev_info.hpb_enabled) || !ufshpb_is_allowed(hba))
4984 ufshpb_destroy_lu(hba, sdev);
4987 static void ufshcd_hpb_configure(struct ufs_hba *hba, struct scsi_device *sdev)
4989 /* skip well-known LU */
4990 if ((sdev->lun >= UFS_UPIU_MAX_UNIT_NUM_ID) ||
4991 !(hba->dev_info.hpb_enabled) || !ufshpb_is_allowed(hba))
4994 ufshpb_init_hpb_lu(hba, sdev);
4998 * ufshcd_slave_configure - adjust SCSI device configurations
4999 * @sdev: pointer to SCSI device
5001 static int ufshcd_slave_configure(struct scsi_device *sdev)
5003 struct ufs_hba *hba = shost_priv(sdev->host);
5004 struct request_queue *q = sdev->request_queue;
5006 ufshcd_hpb_configure(hba, sdev);
5008 blk_queue_update_dma_pad(q, PRDT_DATA_BYTE_COUNT_PAD - 1);
5009 if (hba->quirks & UFSHCD_QUIRK_ALIGN_SG_WITH_PAGE_SIZE)
5010 blk_queue_update_dma_alignment(q, PAGE_SIZE - 1);
5012 * Block runtime-pm until all consumers are added.
5013 * Refer ufshcd_setup_links().
5015 if (is_device_wlun(sdev))
5016 pm_runtime_get_noresume(&sdev->sdev_gendev);
5017 else if (ufshcd_is_rpm_autosuspend_allowed(hba))
5018 sdev->rpm_autosuspend = 1;
5020 ufshcd_crypto_setup_rq_keyslot_manager(hba, q);
5026 * ufshcd_slave_destroy - remove SCSI device configurations
5027 * @sdev: pointer to SCSI device
5029 static void ufshcd_slave_destroy(struct scsi_device *sdev)
5031 struct ufs_hba *hba;
5032 unsigned long flags;
5034 hba = shost_priv(sdev->host);
5036 ufshcd_hpb_destroy(hba, sdev);
5038 /* Drop the reference as it won't be needed anymore */
5039 if (ufshcd_scsi_to_upiu_lun(sdev->lun) == UFS_UPIU_UFS_DEVICE_WLUN) {
5040 spin_lock_irqsave(hba->host->host_lock, flags);
5041 hba->sdev_ufs_device = NULL;
5042 spin_unlock_irqrestore(hba->host->host_lock, flags);
5043 } else if (hba->sdev_ufs_device) {
5044 struct device *supplier = NULL;
5046 /* Ensure UFS Device WLUN exists and does not disappear */
5047 spin_lock_irqsave(hba->host->host_lock, flags);
5048 if (hba->sdev_ufs_device) {
5049 supplier = &hba->sdev_ufs_device->sdev_gendev;
5050 get_device(supplier);
5052 spin_unlock_irqrestore(hba->host->host_lock, flags);
5056 * If a LUN fails to probe (e.g. absent BOOT WLUN), the
5057 * device will not have been registered but can still
5058 * have a device link holding a reference to the device.
5060 device_link_remove(&sdev->sdev_gendev, supplier);
5061 put_device(supplier);
5067 * ufshcd_scsi_cmd_status - Update SCSI command result based on SCSI status
5068 * @lrbp: pointer to local reference block of completed command
5069 * @scsi_status: SCSI command status
5071 * Returns value base on SCSI command status
5074 ufshcd_scsi_cmd_status(struct ufshcd_lrb *lrbp, int scsi_status)
5078 switch (scsi_status) {
5079 case SAM_STAT_CHECK_CONDITION:
5080 ufshcd_copy_sense_data(lrbp);
5083 result |= DID_OK << 16 | scsi_status;
5085 case SAM_STAT_TASK_SET_FULL:
5087 case SAM_STAT_TASK_ABORTED:
5088 ufshcd_copy_sense_data(lrbp);
5089 result |= scsi_status;
5092 result |= DID_ERROR << 16;
5094 } /* end of switch */
5100 * ufshcd_transfer_rsp_status - Get overall status of the response
5101 * @hba: per adapter instance
5102 * @lrbp: pointer to local reference block of completed command
5104 * Returns result of the command to notify SCSI midlayer
5107 ufshcd_transfer_rsp_status(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
5113 /* overall command status of utrd */
5114 ocs = ufshcd_get_tr_ocs(lrbp);
5116 if (hba->quirks & UFSHCD_QUIRK_BROKEN_OCS_FATAL_ERROR) {
5117 if (be32_to_cpu(lrbp->ucd_rsp_ptr->header.dword_1) &
5118 MASK_RSP_UPIU_RESULT)
5124 result = ufshcd_get_req_rsp(lrbp->ucd_rsp_ptr);
5125 hba->ufs_stats.last_hibern8_exit_tstamp = ktime_set(0, 0);
5127 case UPIU_TRANSACTION_RESPONSE:
5129 * get the response UPIU result to extract
5130 * the SCSI command status
5132 result = ufshcd_get_rsp_upiu_result(lrbp->ucd_rsp_ptr);
5135 * get the result based on SCSI status response
5136 * to notify the SCSI midlayer of the command status
5138 scsi_status = result & MASK_SCSI_STATUS;
5139 result = ufshcd_scsi_cmd_status(lrbp, scsi_status);
5142 * Currently we are only supporting BKOPs exception
5143 * events hence we can ignore BKOPs exception event
5144 * during power management callbacks. BKOPs exception
5145 * event is not expected to be raised in runtime suspend
5146 * callback as it allows the urgent bkops.
5147 * During system suspend, we are anyway forcefully
5148 * disabling the bkops and if urgent bkops is needed
5149 * it will be enabled on system resume. Long term
5150 * solution could be to abort the system suspend if
5151 * UFS device needs urgent BKOPs.
5153 if (!hba->pm_op_in_progress &&
5154 !ufshcd_eh_in_progress(hba) &&
5155 ufshcd_is_exception_event(lrbp->ucd_rsp_ptr))
5156 /* Flushed in suspend */
5157 schedule_work(&hba->eeh_work);
5159 if (scsi_status == SAM_STAT_GOOD)
5160 ufshpb_rsp_upiu(hba, lrbp);
5162 case UPIU_TRANSACTION_REJECT_UPIU:
5163 /* TODO: handle Reject UPIU Response */
5164 result = DID_ERROR << 16;
5166 "Reject UPIU not fully implemented\n");
5170 "Unexpected request response code = %x\n",
5172 result = DID_ERROR << 16;
5177 result |= DID_ABORT << 16;
5179 case OCS_INVALID_COMMAND_STATUS:
5180 result |= DID_REQUEUE << 16;
5182 case OCS_INVALID_CMD_TABLE_ATTR:
5183 case OCS_INVALID_PRDT_ATTR:
5184 case OCS_MISMATCH_DATA_BUF_SIZE:
5185 case OCS_MISMATCH_RESP_UPIU_SIZE:
5186 case OCS_PEER_COMM_FAILURE:
5187 case OCS_FATAL_ERROR:
5188 case OCS_DEVICE_FATAL_ERROR:
5189 case OCS_INVALID_CRYPTO_CONFIG:
5190 case OCS_GENERAL_CRYPTO_ERROR:
5192 result |= DID_ERROR << 16;
5194 "OCS error from controller = %x for tag %d\n",
5195 ocs, lrbp->task_tag);
5196 ufshcd_print_evt_hist(hba);
5197 ufshcd_print_host_state(hba);
5199 } /* end of switch */
5201 if ((host_byte(result) != DID_OK) &&
5202 (host_byte(result) != DID_REQUEUE) && !hba->silence_err_logs)
5203 ufshcd_print_trs(hba, 1 << lrbp->task_tag, true);
5207 static bool ufshcd_is_auto_hibern8_error(struct ufs_hba *hba,
5210 if (!ufshcd_is_auto_hibern8_supported(hba) ||
5211 !ufshcd_is_auto_hibern8_enabled(hba))
5214 if (!(intr_mask & UFSHCD_UIC_HIBERN8_MASK))
5217 if (hba->active_uic_cmd &&
5218 (hba->active_uic_cmd->command == UIC_CMD_DME_HIBER_ENTER ||
5219 hba->active_uic_cmd->command == UIC_CMD_DME_HIBER_EXIT))
5226 * ufshcd_uic_cmd_compl - handle completion of uic command
5227 * @hba: per adapter instance
5228 * @intr_status: interrupt status generated by the controller
5231 * IRQ_HANDLED - If interrupt is valid
5232 * IRQ_NONE - If invalid interrupt
5234 static irqreturn_t ufshcd_uic_cmd_compl(struct ufs_hba *hba, u32 intr_status)
5236 irqreturn_t retval = IRQ_NONE;
5238 spin_lock(hba->host->host_lock);
5239 if (ufshcd_is_auto_hibern8_error(hba, intr_status))
5240 hba->errors |= (UFSHCD_UIC_HIBERN8_MASK & intr_status);
5242 if ((intr_status & UIC_COMMAND_COMPL) && hba->active_uic_cmd) {
5243 hba->active_uic_cmd->argument2 |=
5244 ufshcd_get_uic_cmd_result(hba);
5245 hba->active_uic_cmd->argument3 =
5246 ufshcd_get_dme_attr_val(hba);
5247 if (!hba->uic_async_done)
5248 hba->active_uic_cmd->cmd_active = 0;
5249 complete(&hba->active_uic_cmd->done);
5250 retval = IRQ_HANDLED;
5253 if ((intr_status & UFSHCD_UIC_PWR_MASK) && hba->uic_async_done) {
5254 hba->active_uic_cmd->cmd_active = 0;
5255 complete(hba->uic_async_done);
5256 retval = IRQ_HANDLED;
5259 if (retval == IRQ_HANDLED)
5260 ufshcd_add_uic_command_trace(hba, hba->active_uic_cmd,
5262 spin_unlock(hba->host->host_lock);
5267 * __ufshcd_transfer_req_compl - handle SCSI and query command completion
5268 * @hba: per adapter instance
5269 * @completed_reqs: bitmask that indicates which requests to complete
5270 * @retry_requests: whether to ask the SCSI core to retry completed requests
5272 static void __ufshcd_transfer_req_compl(struct ufs_hba *hba,
5273 unsigned long completed_reqs,
5274 bool retry_requests)
5276 struct ufshcd_lrb *lrbp;
5277 struct scsi_cmnd *cmd;
5280 bool update_scaling = false;
5282 for_each_set_bit(index, &completed_reqs, hba->nutrs) {
5283 lrbp = &hba->lrb[index];
5284 lrbp->compl_time_stamp = ktime_get();
5287 if (unlikely(ufshcd_should_inform_monitor(hba, lrbp)))
5288 ufshcd_update_monitor(hba, lrbp);
5289 ufshcd_add_command_trace(hba, index, UFS_CMD_COMP);
5290 result = retry_requests ? DID_BUS_BUSY << 16 :
5291 ufshcd_transfer_rsp_status(hba, lrbp);
5292 scsi_dma_unmap(cmd);
5293 cmd->result = result;
5294 /* Mark completed command as NULL in LRB */
5296 /* Do not touch lrbp after scsi done */
5297 cmd->scsi_done(cmd);
5298 ufshcd_release(hba);
5299 update_scaling = true;
5300 } else if (lrbp->command_type == UTP_CMD_TYPE_DEV_MANAGE ||
5301 lrbp->command_type == UTP_CMD_TYPE_UFS_STORAGE) {
5302 if (hba->dev_cmd.complete) {
5303 ufshcd_add_command_trace(hba, index,
5305 complete(hba->dev_cmd.complete);
5306 update_scaling = true;
5310 ufshcd_clk_scaling_update_busy(hba);
5315 * ufshcd_transfer_req_compl - handle SCSI and query command completion
5316 * @hba: per adapter instance
5317 * @retry_requests: whether or not to ask to retry requests
5320 * IRQ_HANDLED - If interrupt is valid
5321 * IRQ_NONE - If invalid interrupt
5323 static irqreturn_t ufshcd_transfer_req_compl(struct ufs_hba *hba,
5324 bool retry_requests)
5326 unsigned long completed_reqs, flags;
5329 /* Resetting interrupt aggregation counters first and reading the
5330 * DOOR_BELL afterward allows us to handle all the completed requests.
5331 * In order to prevent other interrupts starvation the DB is read once
5332 * after reset. The down side of this solution is the possibility of
5333 * false interrupt if device completes another request after resetting
5334 * aggregation and before reading the DB.
5336 if (ufshcd_is_intr_aggr_allowed(hba) &&
5337 !(hba->quirks & UFSHCI_QUIRK_SKIP_RESET_INTR_AGGR))
5338 ufshcd_reset_intr_aggr(hba);
5340 if (ufs_fail_completion())
5343 spin_lock_irqsave(&hba->outstanding_lock, flags);
5344 tr_doorbell = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
5345 completed_reqs = ~tr_doorbell & hba->outstanding_reqs;
5346 WARN_ONCE(completed_reqs & ~hba->outstanding_reqs,
5347 "completed: %#lx; outstanding: %#lx\n", completed_reqs,
5348 hba->outstanding_reqs);
5349 hba->outstanding_reqs &= ~completed_reqs;
5350 spin_unlock_irqrestore(&hba->outstanding_lock, flags);
5352 if (completed_reqs) {
5353 __ufshcd_transfer_req_compl(hba, completed_reqs,
5361 int __ufshcd_write_ee_control(struct ufs_hba *hba, u32 ee_ctrl_mask)
5363 return ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_WRITE_ATTR,
5364 QUERY_ATTR_IDN_EE_CONTROL, 0, 0,
5368 int ufshcd_write_ee_control(struct ufs_hba *hba)
5372 mutex_lock(&hba->ee_ctrl_mutex);
5373 err = __ufshcd_write_ee_control(hba, hba->ee_ctrl_mask);
5374 mutex_unlock(&hba->ee_ctrl_mutex);
5376 dev_err(hba->dev, "%s: failed to write ee control %d\n",
5381 int ufshcd_update_ee_control(struct ufs_hba *hba, u16 *mask, u16 *other_mask,
5384 u16 new_mask, ee_ctrl_mask;
5387 mutex_lock(&hba->ee_ctrl_mutex);
5388 new_mask = (*mask & ~clr) | set;
5389 ee_ctrl_mask = new_mask | *other_mask;
5390 if (ee_ctrl_mask != hba->ee_ctrl_mask)
5391 err = __ufshcd_write_ee_control(hba, ee_ctrl_mask);
5392 /* Still need to update 'mask' even if 'ee_ctrl_mask' was unchanged */
5394 hba->ee_ctrl_mask = ee_ctrl_mask;
5397 mutex_unlock(&hba->ee_ctrl_mutex);
5402 * ufshcd_disable_ee - disable exception event
5403 * @hba: per-adapter instance
5404 * @mask: exception event to disable
5406 * Disables exception event in the device so that the EVENT_ALERT
5409 * Returns zero on success, non-zero error value on failure.
5411 static inline int ufshcd_disable_ee(struct ufs_hba *hba, u16 mask)
5413 return ufshcd_update_ee_drv_mask(hba, 0, mask);
5417 * ufshcd_enable_ee - enable exception event
5418 * @hba: per-adapter instance
5419 * @mask: exception event to enable
5421 * Enable corresponding exception event in the device to allow
5422 * device to alert host in critical scenarios.
5424 * Returns zero on success, non-zero error value on failure.
5426 static inline int ufshcd_enable_ee(struct ufs_hba *hba, u16 mask)
5428 return ufshcd_update_ee_drv_mask(hba, mask, 0);
5432 * ufshcd_enable_auto_bkops - Allow device managed BKOPS
5433 * @hba: per-adapter instance
5435 * Allow device to manage background operations on its own. Enabling
5436 * this might lead to inconsistent latencies during normal data transfers
5437 * as the device is allowed to manage its own way of handling background
5440 * Returns zero on success, non-zero on failure.
5442 static int ufshcd_enable_auto_bkops(struct ufs_hba *hba)
5446 if (hba->auto_bkops_enabled)
5449 err = ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_SET_FLAG,
5450 QUERY_FLAG_IDN_BKOPS_EN, 0, NULL);
5452 dev_err(hba->dev, "%s: failed to enable bkops %d\n",
5457 hba->auto_bkops_enabled = true;
5458 trace_ufshcd_auto_bkops_state(dev_name(hba->dev), "Enabled");
5460 /* No need of URGENT_BKOPS exception from the device */
5461 err = ufshcd_disable_ee(hba, MASK_EE_URGENT_BKOPS);
5463 dev_err(hba->dev, "%s: failed to disable exception event %d\n",
5470 * ufshcd_disable_auto_bkops - block device in doing background operations
5471 * @hba: per-adapter instance
5473 * Disabling background operations improves command response latency but
5474 * has drawback of device moving into critical state where the device is
5475 * not-operable. Make sure to call ufshcd_enable_auto_bkops() whenever the
5476 * host is idle so that BKOPS are managed effectively without any negative
5479 * Returns zero on success, non-zero on failure.
5481 static int ufshcd_disable_auto_bkops(struct ufs_hba *hba)
5485 if (!hba->auto_bkops_enabled)
5489 * If host assisted BKOPs is to be enabled, make sure
5490 * urgent bkops exception is allowed.
5492 err = ufshcd_enable_ee(hba, MASK_EE_URGENT_BKOPS);
5494 dev_err(hba->dev, "%s: failed to enable exception event %d\n",
5499 err = ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_CLEAR_FLAG,
5500 QUERY_FLAG_IDN_BKOPS_EN, 0, NULL);
5502 dev_err(hba->dev, "%s: failed to disable bkops %d\n",
5504 ufshcd_disable_ee(hba, MASK_EE_URGENT_BKOPS);
5508 hba->auto_bkops_enabled = false;
5509 trace_ufshcd_auto_bkops_state(dev_name(hba->dev), "Disabled");
5510 hba->is_urgent_bkops_lvl_checked = false;
5516 * ufshcd_force_reset_auto_bkops - force reset auto bkops state
5517 * @hba: per adapter instance
5519 * After a device reset the device may toggle the BKOPS_EN flag
5520 * to default value. The s/w tracking variables should be updated
5521 * as well. This function would change the auto-bkops state based on
5522 * UFSHCD_CAP_KEEP_AUTO_BKOPS_ENABLED_EXCEPT_SUSPEND.
5524 static void ufshcd_force_reset_auto_bkops(struct ufs_hba *hba)
5526 if (ufshcd_keep_autobkops_enabled_except_suspend(hba)) {
5527 hba->auto_bkops_enabled = false;
5528 hba->ee_ctrl_mask |= MASK_EE_URGENT_BKOPS;
5529 ufshcd_enable_auto_bkops(hba);
5531 hba->auto_bkops_enabled = true;
5532 hba->ee_ctrl_mask &= ~MASK_EE_URGENT_BKOPS;
5533 ufshcd_disable_auto_bkops(hba);
5535 hba->urgent_bkops_lvl = BKOPS_STATUS_PERF_IMPACT;
5536 hba->is_urgent_bkops_lvl_checked = false;
5539 static inline int ufshcd_get_bkops_status(struct ufs_hba *hba, u32 *status)
5541 return ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
5542 QUERY_ATTR_IDN_BKOPS_STATUS, 0, 0, status);
5546 * ufshcd_bkops_ctrl - control the auto bkops based on current bkops status
5547 * @hba: per-adapter instance
5548 * @status: bkops_status value
5550 * Read the bkops_status from the UFS device and Enable fBackgroundOpsEn
5551 * flag in the device to permit background operations if the device
5552 * bkops_status is greater than or equal to "status" argument passed to
5553 * this function, disable otherwise.
5555 * Returns 0 for success, non-zero in case of failure.
5557 * NOTE: Caller of this function can check the "hba->auto_bkops_enabled" flag
5558 * to know whether auto bkops is enabled or disabled after this function
5559 * returns control to it.
5561 static int ufshcd_bkops_ctrl(struct ufs_hba *hba,
5562 enum bkops_status status)
5565 u32 curr_status = 0;
5567 err = ufshcd_get_bkops_status(hba, &curr_status);
5569 dev_err(hba->dev, "%s: failed to get BKOPS status %d\n",
5572 } else if (curr_status > BKOPS_STATUS_MAX) {
5573 dev_err(hba->dev, "%s: invalid BKOPS status %d\n",
5574 __func__, curr_status);
5579 if (curr_status >= status)
5580 err = ufshcd_enable_auto_bkops(hba);
5582 err = ufshcd_disable_auto_bkops(hba);
5588 * ufshcd_urgent_bkops - handle urgent bkops exception event
5589 * @hba: per-adapter instance
5591 * Enable fBackgroundOpsEn flag in the device to permit background
5594 * If BKOPs is enabled, this function returns 0, 1 if the bkops in not enabled
5595 * and negative error value for any other failure.
5597 static int ufshcd_urgent_bkops(struct ufs_hba *hba)
5599 return ufshcd_bkops_ctrl(hba, hba->urgent_bkops_lvl);
5602 static inline int ufshcd_get_ee_status(struct ufs_hba *hba, u32 *status)
5604 return ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
5605 QUERY_ATTR_IDN_EE_STATUS, 0, 0, status);
5608 static void ufshcd_bkops_exception_event_handler(struct ufs_hba *hba)
5611 u32 curr_status = 0;
5613 if (hba->is_urgent_bkops_lvl_checked)
5614 goto enable_auto_bkops;
5616 err = ufshcd_get_bkops_status(hba, &curr_status);
5618 dev_err(hba->dev, "%s: failed to get BKOPS status %d\n",
5624 * We are seeing that some devices are raising the urgent bkops
5625 * exception events even when BKOPS status doesn't indicate performace
5626 * impacted or critical. Handle these device by determining their urgent
5627 * bkops status at runtime.
5629 if (curr_status < BKOPS_STATUS_PERF_IMPACT) {
5630 dev_err(hba->dev, "%s: device raised urgent BKOPS exception for bkops status %d\n",
5631 __func__, curr_status);
5632 /* update the current status as the urgent bkops level */
5633 hba->urgent_bkops_lvl = curr_status;
5634 hba->is_urgent_bkops_lvl_checked = true;
5638 err = ufshcd_enable_auto_bkops(hba);
5641 dev_err(hba->dev, "%s: failed to handle urgent bkops %d\n",
5645 static void ufshcd_temp_exception_event_handler(struct ufs_hba *hba, u16 status)
5649 if (ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
5650 QUERY_ATTR_IDN_CASE_ROUGH_TEMP, 0, 0, &value))
5653 dev_info(hba->dev, "exception Tcase %d\n", value - 80);
5655 ufs_hwmon_notify_event(hba, status & MASK_EE_URGENT_TEMP);
5658 * A placeholder for the platform vendors to add whatever additional
5663 static int __ufshcd_wb_toggle(struct ufs_hba *hba, bool set, enum flag_idn idn)
5666 enum query_opcode opcode = set ? UPIU_QUERY_OPCODE_SET_FLAG :
5667 UPIU_QUERY_OPCODE_CLEAR_FLAG;
5669 index = ufshcd_wb_get_query_index(hba);
5670 return ufshcd_query_flag_retry(hba, opcode, idn, index, NULL);
5673 int ufshcd_wb_toggle(struct ufs_hba *hba, bool enable)
5677 if (!ufshcd_is_wb_allowed(hba))
5680 if (!(enable ^ hba->dev_info.wb_enabled))
5683 ret = __ufshcd_wb_toggle(hba, enable, QUERY_FLAG_IDN_WB_EN);
5685 dev_err(hba->dev, "%s Write Booster %s failed %d\n",
5686 __func__, enable ? "enable" : "disable", ret);
5690 hba->dev_info.wb_enabled = enable;
5691 dev_info(hba->dev, "%s Write Booster %s\n",
5692 __func__, enable ? "enabled" : "disabled");
5697 static void ufshcd_wb_toggle_flush_during_h8(struct ufs_hba *hba, bool set)
5701 ret = __ufshcd_wb_toggle(hba, set,
5702 QUERY_FLAG_IDN_WB_BUFF_FLUSH_DURING_HIBERN8);
5704 dev_err(hba->dev, "%s: WB-Buf Flush during H8 %s failed: %d\n",
5705 __func__, set ? "enable" : "disable", ret);
5708 dev_dbg(hba->dev, "%s WB-Buf Flush during H8 %s\n",
5709 __func__, set ? "enabled" : "disabled");
5712 static inline void ufshcd_wb_toggle_flush(struct ufs_hba *hba, bool enable)
5716 if (!ufshcd_is_wb_allowed(hba) ||
5717 hba->dev_info.wb_buf_flush_enabled == enable)
5720 ret = __ufshcd_wb_toggle(hba, enable, QUERY_FLAG_IDN_WB_BUFF_FLUSH_EN);
5722 dev_err(hba->dev, "%s WB-Buf Flush %s failed %d\n", __func__,
5723 enable ? "enable" : "disable", ret);
5727 hba->dev_info.wb_buf_flush_enabled = enable;
5729 dev_dbg(hba->dev, "%s WB-Buf Flush %s\n",
5730 __func__, enable ? "enabled" : "disabled");
5733 static bool ufshcd_wb_presrv_usrspc_keep_vcc_on(struct ufs_hba *hba,
5740 index = ufshcd_wb_get_query_index(hba);
5741 ret = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
5742 QUERY_ATTR_IDN_CURR_WB_BUFF_SIZE,
5743 index, 0, &cur_buf);
5745 dev_err(hba->dev, "%s dCurWriteBoosterBufferSize read failed %d\n",
5751 dev_info(hba->dev, "dCurWBBuf: %d WB disabled until free-space is available\n",
5755 /* Let it continue to flush when available buffer exceeds threshold */
5756 if (avail_buf < hba->vps->wb_flush_threshold)
5762 static bool ufshcd_wb_need_flush(struct ufs_hba *hba)
5768 if (!ufshcd_is_wb_allowed(hba))
5771 * The ufs device needs the vcc to be ON to flush.
5772 * With user-space reduction enabled, it's enough to enable flush
5773 * by checking only the available buffer. The threshold
5774 * defined here is > 90% full.
5775 * With user-space preserved enabled, the current-buffer
5776 * should be checked too because the wb buffer size can reduce
5777 * when disk tends to be full. This info is provided by current
5778 * buffer (dCurrentWriteBoosterBufferSize). There's no point in
5779 * keeping vcc on when current buffer is empty.
5781 index = ufshcd_wb_get_query_index(hba);
5782 ret = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
5783 QUERY_ATTR_IDN_AVAIL_WB_BUFF_SIZE,
5784 index, 0, &avail_buf);
5786 dev_warn(hba->dev, "%s dAvailableWriteBoosterBufferSize read failed %d\n",
5791 if (!hba->dev_info.b_presrv_uspc_en) {
5792 if (avail_buf <= UFS_WB_BUF_REMAIN_PERCENT(10))
5797 return ufshcd_wb_presrv_usrspc_keep_vcc_on(hba, avail_buf);
5800 static void ufshcd_rpm_dev_flush_recheck_work(struct work_struct *work)
5802 struct ufs_hba *hba = container_of(to_delayed_work(work),
5804 rpm_dev_flush_recheck_work);
5806 * To prevent unnecessary VCC power drain after device finishes
5807 * WriteBooster buffer flush or Auto BKOPs, force runtime resume
5808 * after a certain delay to recheck the threshold by next runtime
5811 ufshcd_rpm_get_sync(hba);
5812 ufshcd_rpm_put_sync(hba);
5816 * ufshcd_exception_event_handler - handle exceptions raised by device
5817 * @work: pointer to work data
5819 * Read bExceptionEventStatus attribute from the device and handle the
5820 * exception event accordingly.
5822 static void ufshcd_exception_event_handler(struct work_struct *work)
5824 struct ufs_hba *hba;
5827 hba = container_of(work, struct ufs_hba, eeh_work);
5829 ufshcd_scsi_block_requests(hba);
5830 err = ufshcd_get_ee_status(hba, &status);
5832 dev_err(hba->dev, "%s: failed to get exception status %d\n",
5837 trace_ufshcd_exception_event(dev_name(hba->dev), status);
5839 if (status & hba->ee_drv_mask & MASK_EE_URGENT_BKOPS)
5840 ufshcd_bkops_exception_event_handler(hba);
5842 if (status & hba->ee_drv_mask & MASK_EE_URGENT_TEMP)
5843 ufshcd_temp_exception_event_handler(hba, status);
5845 ufs_debugfs_exception_event(hba, status);
5847 ufshcd_scsi_unblock_requests(hba);
5850 /* Complete requests that have door-bell cleared */
5851 static void ufshcd_complete_requests(struct ufs_hba *hba)
5853 ufshcd_transfer_req_compl(hba, /*retry_requests=*/false);
5854 ufshcd_tmc_handler(hba);
5857 static void ufshcd_retry_aborted_requests(struct ufs_hba *hba)
5859 ufshcd_transfer_req_compl(hba, /*retry_requests=*/true);
5860 ufshcd_tmc_handler(hba);
5864 * ufshcd_quirk_dl_nac_errors - This function checks if error handling is
5865 * to recover from the DL NAC errors or not.
5866 * @hba: per-adapter instance
5868 * Returns true if error handling is required, false otherwise
5870 static bool ufshcd_quirk_dl_nac_errors(struct ufs_hba *hba)
5872 unsigned long flags;
5873 bool err_handling = true;
5875 spin_lock_irqsave(hba->host->host_lock, flags);
5877 * UFS_DEVICE_QUIRK_RECOVERY_FROM_DL_NAC_ERRORS only workaround the
5878 * device fatal error and/or DL NAC & REPLAY timeout errors.
5880 if (hba->saved_err & (CONTROLLER_FATAL_ERROR | SYSTEM_BUS_FATAL_ERROR))
5883 if ((hba->saved_err & DEVICE_FATAL_ERROR) ||
5884 ((hba->saved_err & UIC_ERROR) &&
5885 (hba->saved_uic_err & UFSHCD_UIC_DL_TCx_REPLAY_ERROR)))
5888 if ((hba->saved_err & UIC_ERROR) &&
5889 (hba->saved_uic_err & UFSHCD_UIC_DL_NAC_RECEIVED_ERROR)) {
5892 * wait for 50ms to see if we can get any other errors or not.
5894 spin_unlock_irqrestore(hba->host->host_lock, flags);
5896 spin_lock_irqsave(hba->host->host_lock, flags);
5899 * now check if we have got any other severe errors other than
5902 if ((hba->saved_err & INT_FATAL_ERRORS) ||
5903 ((hba->saved_err & UIC_ERROR) &&
5904 (hba->saved_uic_err & ~UFSHCD_UIC_DL_NAC_RECEIVED_ERROR)))
5908 * As DL NAC is the only error received so far, send out NOP
5909 * command to confirm if link is still active or not.
5910 * - If we don't get any response then do error recovery.
5911 * - If we get response then clear the DL NAC error bit.
5914 spin_unlock_irqrestore(hba->host->host_lock, flags);
5915 err = ufshcd_verify_dev_init(hba);
5916 spin_lock_irqsave(hba->host->host_lock, flags);
5921 /* Link seems to be alive hence ignore the DL NAC errors */
5922 if (hba->saved_uic_err == UFSHCD_UIC_DL_NAC_RECEIVED_ERROR)
5923 hba->saved_err &= ~UIC_ERROR;
5924 /* clear NAC error */
5925 hba->saved_uic_err &= ~UFSHCD_UIC_DL_NAC_RECEIVED_ERROR;
5926 if (!hba->saved_uic_err)
5927 err_handling = false;
5930 spin_unlock_irqrestore(hba->host->host_lock, flags);
5931 return err_handling;
5934 static void ufshcd_clk_scaling_allow(struct ufs_hba *hba, bool allow)
5936 down_write(&hba->clk_scaling_lock);
5937 hba->clk_scaling.is_allowed = allow;
5938 up_write(&hba->clk_scaling_lock);
5941 static void ufshcd_clk_scaling_suspend(struct ufs_hba *hba, bool suspend)
5944 if (hba->clk_scaling.is_enabled)
5945 ufshcd_suspend_clkscaling(hba);
5946 ufshcd_clk_scaling_allow(hba, false);
5948 ufshcd_clk_scaling_allow(hba, true);
5949 if (hba->clk_scaling.is_enabled)
5950 ufshcd_resume_clkscaling(hba);
5954 static void ufshcd_err_handling_prepare(struct ufs_hba *hba)
5956 ufshcd_rpm_get_sync(hba);
5957 if (pm_runtime_status_suspended(&hba->sdev_ufs_device->sdev_gendev) ||
5958 hba->is_sys_suspended) {
5959 enum ufs_pm_op pm_op;
5962 * Don't assume anything of resume, if
5963 * resume fails, irq and clocks can be OFF, and powers
5964 * can be OFF or in LPM.
5966 ufshcd_setup_hba_vreg(hba, true);
5967 ufshcd_enable_irq(hba);
5968 ufshcd_setup_vreg(hba, true);
5969 ufshcd_config_vreg_hpm(hba, hba->vreg_info.vccq);
5970 ufshcd_config_vreg_hpm(hba, hba->vreg_info.vccq2);
5971 ufshcd_hold(hba, false);
5972 if (!ufshcd_is_clkgating_allowed(hba))
5973 ufshcd_setup_clocks(hba, true);
5974 ufshcd_release(hba);
5975 pm_op = hba->is_sys_suspended ? UFS_SYSTEM_PM : UFS_RUNTIME_PM;
5976 ufshcd_vops_resume(hba, pm_op);
5978 ufshcd_hold(hba, false);
5979 if (ufshcd_is_clkscaling_supported(hba) &&
5980 hba->clk_scaling.is_enabled)
5981 ufshcd_suspend_clkscaling(hba);
5982 ufshcd_clk_scaling_allow(hba, false);
5984 ufshcd_scsi_block_requests(hba);
5985 /* Drain ufshcd_queuecommand() */
5986 down_write(&hba->clk_scaling_lock);
5987 up_write(&hba->clk_scaling_lock);
5988 cancel_work_sync(&hba->eeh_work);
5991 static void ufshcd_err_handling_unprepare(struct ufs_hba *hba)
5993 ufshcd_scsi_unblock_requests(hba);
5994 ufshcd_release(hba);
5995 if (ufshcd_is_clkscaling_supported(hba))
5996 ufshcd_clk_scaling_suspend(hba, false);
5997 ufshcd_rpm_put(hba);
6000 static inline bool ufshcd_err_handling_should_stop(struct ufs_hba *hba)
6002 return (!hba->is_powered || hba->shutting_down ||
6003 !hba->sdev_ufs_device ||
6004 hba->ufshcd_state == UFSHCD_STATE_ERROR ||
6005 (!(hba->saved_err || hba->saved_uic_err || hba->force_reset ||
6006 ufshcd_is_link_broken(hba))));
6010 static void ufshcd_recover_pm_error(struct ufs_hba *hba)
6012 struct Scsi_Host *shost = hba->host;
6013 struct scsi_device *sdev;
6014 struct request_queue *q;
6017 hba->is_sys_suspended = false;
6019 * Set RPM status of wlun device to RPM_ACTIVE,
6020 * this also clears its runtime error.
6022 ret = pm_runtime_set_active(&hba->sdev_ufs_device->sdev_gendev);
6024 /* hba device might have a runtime error otherwise */
6026 ret = pm_runtime_set_active(hba->dev);
6028 * If wlun device had runtime error, we also need to resume those
6029 * consumer scsi devices in case any of them has failed to be
6030 * resumed due to supplier runtime resume failure. This is to unblock
6031 * blk_queue_enter in case there are bios waiting inside it.
6034 shost_for_each_device(sdev, shost) {
6035 q = sdev->request_queue;
6036 if (q->dev && (q->rpm_status == RPM_SUSPENDED ||
6037 q->rpm_status == RPM_SUSPENDING))
6038 pm_request_resume(q->dev);
6043 static inline void ufshcd_recover_pm_error(struct ufs_hba *hba)
6048 static bool ufshcd_is_pwr_mode_restore_needed(struct ufs_hba *hba)
6050 struct ufs_pa_layer_attr *pwr_info = &hba->pwr_info;
6053 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_PWRMODE), &mode);
6055 if (pwr_info->pwr_rx != ((mode >> PWRMODE_RX_OFFSET) & PWRMODE_MASK))
6058 if (pwr_info->pwr_tx != (mode & PWRMODE_MASK))
6065 * ufshcd_err_handler - handle UFS errors that require s/w attention
6066 * @host: SCSI host pointer
6068 static void ufshcd_err_handler(struct Scsi_Host *host)
6070 struct ufs_hba *hba = shost_priv(host);
6071 int retries = MAX_ERR_HANDLER_RETRIES;
6072 unsigned long flags;
6080 down(&hba->host_sem);
6081 spin_lock_irqsave(hba->host->host_lock, flags);
6082 hba->host->host_eh_scheduled = 0;
6083 if (ufshcd_err_handling_should_stop(hba)) {
6084 if (hba->ufshcd_state != UFSHCD_STATE_ERROR)
6085 hba->ufshcd_state = UFSHCD_STATE_OPERATIONAL;
6086 spin_unlock_irqrestore(hba->host->host_lock, flags);
6090 ufshcd_set_eh_in_progress(hba);
6091 spin_unlock_irqrestore(hba->host->host_lock, flags);
6092 ufshcd_err_handling_prepare(hba);
6093 /* Complete requests that have door-bell cleared by h/w */
6094 ufshcd_complete_requests(hba);
6095 spin_lock_irqsave(hba->host->host_lock, flags);
6097 needs_restore = false;
6098 needs_reset = false;
6102 if (hba->ufshcd_state != UFSHCD_STATE_ERROR)
6103 hba->ufshcd_state = UFSHCD_STATE_RESET;
6105 * A full reset and restore might have happened after preparation
6106 * is finished, double check whether we should stop.
6108 if (ufshcd_err_handling_should_stop(hba))
6109 goto skip_err_handling;
6111 if (hba->dev_quirks & UFS_DEVICE_QUIRK_RECOVERY_FROM_DL_NAC_ERRORS) {
6114 spin_unlock_irqrestore(hba->host->host_lock, flags);
6115 /* release the lock as ufshcd_quirk_dl_nac_errors() may sleep */
6116 ret = ufshcd_quirk_dl_nac_errors(hba);
6117 spin_lock_irqsave(hba->host->host_lock, flags);
6118 if (!ret && ufshcd_err_handling_should_stop(hba))
6119 goto skip_err_handling;
6122 if ((hba->saved_err & (INT_FATAL_ERRORS | UFSHCD_UIC_HIBERN8_MASK)) ||
6123 (hba->saved_uic_err &&
6124 (hba->saved_uic_err != UFSHCD_UIC_PA_GENERIC_ERROR))) {
6125 bool pr_prdt = !!(hba->saved_err & SYSTEM_BUS_FATAL_ERROR);
6127 spin_unlock_irqrestore(hba->host->host_lock, flags);
6128 ufshcd_print_host_state(hba);
6129 ufshcd_print_pwr_info(hba);
6130 ufshcd_print_evt_hist(hba);
6131 ufshcd_print_tmrs(hba, hba->outstanding_tasks);
6132 ufshcd_print_trs(hba, hba->outstanding_reqs, pr_prdt);
6133 spin_lock_irqsave(hba->host->host_lock, flags);
6137 * if host reset is required then skip clearing the pending
6138 * transfers forcefully because they will get cleared during
6139 * host reset and restore
6141 if (hba->force_reset || ufshcd_is_link_broken(hba) ||
6142 ufshcd_is_saved_err_fatal(hba) ||
6143 ((hba->saved_err & UIC_ERROR) &&
6144 (hba->saved_uic_err & (UFSHCD_UIC_DL_NAC_RECEIVED_ERROR |
6145 UFSHCD_UIC_DL_TCx_REPLAY_ERROR)))) {
6151 * If LINERESET was caught, UFS might have been put to PWM mode,
6152 * check if power mode restore is needed.
6154 if (hba->saved_uic_err & UFSHCD_UIC_PA_GENERIC_ERROR) {
6155 hba->saved_uic_err &= ~UFSHCD_UIC_PA_GENERIC_ERROR;
6156 if (!hba->saved_uic_err)
6157 hba->saved_err &= ~UIC_ERROR;
6158 spin_unlock_irqrestore(hba->host->host_lock, flags);
6159 if (ufshcd_is_pwr_mode_restore_needed(hba))
6160 needs_restore = true;
6161 spin_lock_irqsave(hba->host->host_lock, flags);
6162 if (!hba->saved_err && !needs_restore)
6163 goto skip_err_handling;
6166 hba->silence_err_logs = true;
6167 /* release lock as clear command might sleep */
6168 spin_unlock_irqrestore(hba->host->host_lock, flags);
6169 /* Clear pending transfer requests */
6170 for_each_set_bit(tag, &hba->outstanding_reqs, hba->nutrs) {
6171 if (ufshcd_try_to_abort_task(hba, tag)) {
6173 goto lock_skip_pending_xfer_clear;
6177 /* Clear pending task management requests */
6178 for_each_set_bit(tag, &hba->outstanding_tasks, hba->nutmrs) {
6179 if (ufshcd_clear_tm_cmd(hba, tag)) {
6181 goto lock_skip_pending_xfer_clear;
6185 lock_skip_pending_xfer_clear:
6186 ufshcd_retry_aborted_requests(hba);
6188 spin_lock_irqsave(hba->host->host_lock, flags);
6189 hba->silence_err_logs = false;
6190 if (err_xfer || err_tm) {
6196 * After all reqs and tasks are cleared from doorbell,
6197 * now it is safe to retore power mode.
6199 if (needs_restore) {
6200 spin_unlock_irqrestore(hba->host->host_lock, flags);
6202 * Hold the scaling lock just in case dev cmds
6203 * are sent via bsg and/or sysfs.
6205 down_write(&hba->clk_scaling_lock);
6206 hba->force_pmc = true;
6207 pmc_err = ufshcd_config_pwr_mode(hba, &(hba->pwr_info));
6210 dev_err(hba->dev, "%s: Failed to restore power mode, err = %d\n",
6213 hba->force_pmc = false;
6214 ufshcd_print_pwr_info(hba);
6215 up_write(&hba->clk_scaling_lock);
6216 spin_lock_irqsave(hba->host->host_lock, flags);
6220 /* Fatal errors need reset */
6224 hba->force_reset = false;
6225 spin_unlock_irqrestore(hba->host->host_lock, flags);
6226 err = ufshcd_reset_and_restore(hba);
6228 dev_err(hba->dev, "%s: reset and restore failed with err %d\n",
6231 ufshcd_recover_pm_error(hba);
6232 spin_lock_irqsave(hba->host->host_lock, flags);
6237 if (hba->ufshcd_state == UFSHCD_STATE_RESET)
6238 hba->ufshcd_state = UFSHCD_STATE_OPERATIONAL;
6239 if (hba->saved_err || hba->saved_uic_err)
6240 dev_err_ratelimited(hba->dev, "%s: exit: saved_err 0x%x saved_uic_err 0x%x",
6241 __func__, hba->saved_err, hba->saved_uic_err);
6243 /* Exit in an operational state or dead */
6244 if (hba->ufshcd_state != UFSHCD_STATE_OPERATIONAL &&
6245 hba->ufshcd_state != UFSHCD_STATE_ERROR) {
6248 hba->ufshcd_state = UFSHCD_STATE_ERROR;
6250 ufshcd_clear_eh_in_progress(hba);
6251 spin_unlock_irqrestore(hba->host->host_lock, flags);
6252 ufshcd_err_handling_unprepare(hba);
6257 * ufshcd_update_uic_error - check and set fatal UIC error flags.
6258 * @hba: per-adapter instance
6261 * IRQ_HANDLED - If interrupt is valid
6262 * IRQ_NONE - If invalid interrupt
6264 static irqreturn_t ufshcd_update_uic_error(struct ufs_hba *hba)
6267 irqreturn_t retval = IRQ_NONE;
6269 /* PHY layer error */
6270 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_PHY_ADAPTER_LAYER);
6271 if ((reg & UIC_PHY_ADAPTER_LAYER_ERROR) &&
6272 (reg & UIC_PHY_ADAPTER_LAYER_ERROR_CODE_MASK)) {
6273 ufshcd_update_evt_hist(hba, UFS_EVT_PA_ERR, reg);
6275 * To know whether this error is fatal or not, DB timeout
6276 * must be checked but this error is handled separately.
6278 if (reg & UIC_PHY_ADAPTER_LAYER_LANE_ERR_MASK)
6279 dev_dbg(hba->dev, "%s: UIC Lane error reported\n",
6282 /* Got a LINERESET indication. */
6283 if (reg & UIC_PHY_ADAPTER_LAYER_GENERIC_ERROR) {
6284 struct uic_command *cmd = NULL;
6286 hba->uic_error |= UFSHCD_UIC_PA_GENERIC_ERROR;
6287 if (hba->uic_async_done && hba->active_uic_cmd)
6288 cmd = hba->active_uic_cmd;
6290 * Ignore the LINERESET during power mode change
6291 * operation via DME_SET command.
6293 if (cmd && (cmd->command == UIC_CMD_DME_SET))
6294 hba->uic_error &= ~UFSHCD_UIC_PA_GENERIC_ERROR;
6296 retval |= IRQ_HANDLED;
6299 /* PA_INIT_ERROR is fatal and needs UIC reset */
6300 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_DATA_LINK_LAYER);
6301 if ((reg & UIC_DATA_LINK_LAYER_ERROR) &&
6302 (reg & UIC_DATA_LINK_LAYER_ERROR_CODE_MASK)) {
6303 ufshcd_update_evt_hist(hba, UFS_EVT_DL_ERR, reg);
6305 if (reg & UIC_DATA_LINK_LAYER_ERROR_PA_INIT)
6306 hba->uic_error |= UFSHCD_UIC_DL_PA_INIT_ERROR;
6307 else if (hba->dev_quirks &
6308 UFS_DEVICE_QUIRK_RECOVERY_FROM_DL_NAC_ERRORS) {
6309 if (reg & UIC_DATA_LINK_LAYER_ERROR_NAC_RECEIVED)
6311 UFSHCD_UIC_DL_NAC_RECEIVED_ERROR;
6312 else if (reg & UIC_DATA_LINK_LAYER_ERROR_TCx_REPLAY_TIMEOUT)
6313 hba->uic_error |= UFSHCD_UIC_DL_TCx_REPLAY_ERROR;
6315 retval |= IRQ_HANDLED;
6318 /* UIC NL/TL/DME errors needs software retry */
6319 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_NETWORK_LAYER);
6320 if ((reg & UIC_NETWORK_LAYER_ERROR) &&
6321 (reg & UIC_NETWORK_LAYER_ERROR_CODE_MASK)) {
6322 ufshcd_update_evt_hist(hba, UFS_EVT_NL_ERR, reg);
6323 hba->uic_error |= UFSHCD_UIC_NL_ERROR;
6324 retval |= IRQ_HANDLED;
6327 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_TRANSPORT_LAYER);
6328 if ((reg & UIC_TRANSPORT_LAYER_ERROR) &&
6329 (reg & UIC_TRANSPORT_LAYER_ERROR_CODE_MASK)) {
6330 ufshcd_update_evt_hist(hba, UFS_EVT_TL_ERR, reg);
6331 hba->uic_error |= UFSHCD_UIC_TL_ERROR;
6332 retval |= IRQ_HANDLED;
6335 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_DME);
6336 if ((reg & UIC_DME_ERROR) &&
6337 (reg & UIC_DME_ERROR_CODE_MASK)) {
6338 ufshcd_update_evt_hist(hba, UFS_EVT_DME_ERR, reg);
6339 hba->uic_error |= UFSHCD_UIC_DME_ERROR;
6340 retval |= IRQ_HANDLED;
6343 dev_dbg(hba->dev, "%s: UIC error flags = 0x%08x\n",
6344 __func__, hba->uic_error);
6349 * ufshcd_check_errors - Check for errors that need s/w attention
6350 * @hba: per-adapter instance
6351 * @intr_status: interrupt status generated by the controller
6354 * IRQ_HANDLED - If interrupt is valid
6355 * IRQ_NONE - If invalid interrupt
6357 static irqreturn_t ufshcd_check_errors(struct ufs_hba *hba, u32 intr_status)
6359 bool queue_eh_work = false;
6360 irqreturn_t retval = IRQ_NONE;
6362 spin_lock(hba->host->host_lock);
6363 hba->errors |= UFSHCD_ERROR_MASK & intr_status;
6365 if (hba->errors & INT_FATAL_ERRORS) {
6366 ufshcd_update_evt_hist(hba, UFS_EVT_FATAL_ERR,
6368 queue_eh_work = true;
6371 if (hba->errors & UIC_ERROR) {
6373 retval = ufshcd_update_uic_error(hba);
6375 queue_eh_work = true;
6378 if (hba->errors & UFSHCD_UIC_HIBERN8_MASK) {
6380 "%s: Auto Hibern8 %s failed - status: 0x%08x, upmcrs: 0x%08x\n",
6381 __func__, (hba->errors & UIC_HIBERNATE_ENTER) ?
6383 hba->errors, ufshcd_get_upmcrs(hba));
6384 ufshcd_update_evt_hist(hba, UFS_EVT_AUTO_HIBERN8_ERR,
6386 ufshcd_set_link_broken(hba);
6387 queue_eh_work = true;
6390 if (queue_eh_work) {
6392 * update the transfer error masks to sticky bits, let's do this
6393 * irrespective of current ufshcd_state.
6395 hba->saved_err |= hba->errors;
6396 hba->saved_uic_err |= hba->uic_error;
6398 /* dump controller state before resetting */
6399 if ((hba->saved_err &
6400 (INT_FATAL_ERRORS | UFSHCD_UIC_HIBERN8_MASK)) ||
6401 (hba->saved_uic_err &&
6402 (hba->saved_uic_err != UFSHCD_UIC_PA_GENERIC_ERROR))) {
6403 dev_err(hba->dev, "%s: saved_err 0x%x saved_uic_err 0x%x\n",
6404 __func__, hba->saved_err,
6405 hba->saved_uic_err);
6406 ufshcd_dump_regs(hba, 0, UFSHCI_REG_SPACE_SIZE,
6408 ufshcd_print_pwr_info(hba);
6410 retval |= IRQ_HANDLED;
6413 * if (!queue_eh_work) -
6414 * Other errors are either non-fatal where host recovers
6415 * itself without s/w intervention or errors that will be
6416 * handled by the SCSI core layer.
6420 spin_unlock(hba->host->host_lock);
6423 ufshcd_schedule_eh(hba);
6429 struct ufs_hba *hba;
6430 unsigned long pending;
6434 static bool ufshcd_compl_tm(struct request *req, void *priv, bool reserved)
6436 struct ctm_info *const ci = priv;
6437 struct completion *c;
6439 WARN_ON_ONCE(reserved);
6440 if (test_bit(req->tag, &ci->pending))
6443 c = req->end_io_data;
6450 * ufshcd_tmc_handler - handle task management function completion
6451 * @hba: per adapter instance
6454 * IRQ_HANDLED - If interrupt is valid
6455 * IRQ_NONE - If invalid interrupt
6457 static irqreturn_t ufshcd_tmc_handler(struct ufs_hba *hba)
6459 unsigned long flags;
6460 struct request_queue *q = hba->tmf_queue;
6461 struct ctm_info ci = {
6465 spin_lock_irqsave(hba->host->host_lock, flags);
6466 ci.pending = ufshcd_readl(hba, REG_UTP_TASK_REQ_DOOR_BELL);
6467 blk_mq_tagset_busy_iter(q->tag_set, ufshcd_compl_tm, &ci);
6468 spin_unlock_irqrestore(hba->host->host_lock, flags);
6470 return ci.ncpl ? IRQ_HANDLED : IRQ_NONE;
6474 * ufshcd_sl_intr - Interrupt service routine
6475 * @hba: per adapter instance
6476 * @intr_status: contains interrupts generated by the controller
6479 * IRQ_HANDLED - If interrupt is valid
6480 * IRQ_NONE - If invalid interrupt
6482 static irqreturn_t ufshcd_sl_intr(struct ufs_hba *hba, u32 intr_status)
6484 irqreturn_t retval = IRQ_NONE;
6486 if (intr_status & UFSHCD_UIC_MASK)
6487 retval |= ufshcd_uic_cmd_compl(hba, intr_status);
6489 if (intr_status & UFSHCD_ERROR_MASK || hba->errors)
6490 retval |= ufshcd_check_errors(hba, intr_status);
6492 if (intr_status & UTP_TASK_REQ_COMPL)
6493 retval |= ufshcd_tmc_handler(hba);
6495 if (intr_status & UTP_TRANSFER_REQ_COMPL)
6496 retval |= ufshcd_transfer_req_compl(hba, /*retry_requests=*/false);
6502 * ufshcd_intr - Main interrupt service routine
6504 * @__hba: pointer to adapter instance
6507 * IRQ_HANDLED - If interrupt is valid
6508 * IRQ_NONE - If invalid interrupt
6510 static irqreturn_t ufshcd_intr(int irq, void *__hba)
6512 u32 intr_status, enabled_intr_status = 0;
6513 irqreturn_t retval = IRQ_NONE;
6514 struct ufs_hba *hba = __hba;
6515 int retries = hba->nutrs;
6517 intr_status = ufshcd_readl(hba, REG_INTERRUPT_STATUS);
6518 hba->ufs_stats.last_intr_status = intr_status;
6519 hba->ufs_stats.last_intr_ts = ktime_get();
6522 * There could be max of hba->nutrs reqs in flight and in worst case
6523 * if the reqs get finished 1 by 1 after the interrupt status is
6524 * read, make sure we handle them by checking the interrupt status
6525 * again in a loop until we process all of the reqs before returning.
6527 while (intr_status && retries--) {
6528 enabled_intr_status =
6529 intr_status & ufshcd_readl(hba, REG_INTERRUPT_ENABLE);
6530 ufshcd_writel(hba, intr_status, REG_INTERRUPT_STATUS);
6531 if (enabled_intr_status)
6532 retval |= ufshcd_sl_intr(hba, enabled_intr_status);
6534 intr_status = ufshcd_readl(hba, REG_INTERRUPT_STATUS);
6537 if (enabled_intr_status && retval == IRQ_NONE &&
6538 (!(enabled_intr_status & UTP_TRANSFER_REQ_COMPL) ||
6539 hba->outstanding_reqs) && !ufshcd_eh_in_progress(hba)) {
6540 dev_err(hba->dev, "%s: Unhandled interrupt 0x%08x (0x%08x, 0x%08x)\n",
6543 hba->ufs_stats.last_intr_status,
6544 enabled_intr_status);
6545 ufshcd_dump_regs(hba, 0, UFSHCI_REG_SPACE_SIZE, "host_regs: ");
6551 static int ufshcd_clear_tm_cmd(struct ufs_hba *hba, int tag)
6554 u32 mask = 1 << tag;
6555 unsigned long flags;
6557 if (!test_bit(tag, &hba->outstanding_tasks))
6560 spin_lock_irqsave(hba->host->host_lock, flags);
6561 ufshcd_utmrl_clear(hba, tag);
6562 spin_unlock_irqrestore(hba->host->host_lock, flags);
6564 /* poll for max. 1 sec to clear door bell register by h/w */
6565 err = ufshcd_wait_for_register(hba,
6566 REG_UTP_TASK_REQ_DOOR_BELL,
6567 mask, 0, 1000, 1000);
6572 static int __ufshcd_issue_tm_cmd(struct ufs_hba *hba,
6573 struct utp_task_req_desc *treq, u8 tm_function)
6575 struct request_queue *q = hba->tmf_queue;
6576 struct Scsi_Host *host = hba->host;
6577 DECLARE_COMPLETION_ONSTACK(wait);
6578 struct request *req;
6579 unsigned long flags;
6583 * blk_get_request() is used here only to get a free tag.
6585 req = blk_get_request(q, REQ_OP_DRV_OUT, 0);
6587 return PTR_ERR(req);
6589 req->end_io_data = &wait;
6590 ufshcd_hold(hba, false);
6592 spin_lock_irqsave(host->host_lock, flags);
6593 blk_mq_start_request(req);
6595 task_tag = req->tag;
6596 treq->upiu_req.req_header.dword_0 |= cpu_to_be32(task_tag);
6598 memcpy(hba->utmrdl_base_addr + task_tag, treq, sizeof(*treq));
6599 ufshcd_vops_setup_task_mgmt(hba, task_tag, tm_function);
6601 /* send command to the controller */
6602 __set_bit(task_tag, &hba->outstanding_tasks);
6604 ufshcd_writel(hba, 1 << task_tag, REG_UTP_TASK_REQ_DOOR_BELL);
6605 /* Make sure that doorbell is committed immediately */
6608 spin_unlock_irqrestore(host->host_lock, flags);
6610 ufshcd_add_tm_upiu_trace(hba, task_tag, UFS_TM_SEND);
6612 /* wait until the task management command is completed */
6613 err = wait_for_completion_io_timeout(&wait,
6614 msecs_to_jiffies(TM_CMD_TIMEOUT));
6617 * Make sure that ufshcd_compl_tm() does not trigger a
6620 req->end_io_data = NULL;
6621 ufshcd_add_tm_upiu_trace(hba, task_tag, UFS_TM_ERR);
6622 dev_err(hba->dev, "%s: task management cmd 0x%.2x timed-out\n",
6623 __func__, tm_function);
6624 if (ufshcd_clear_tm_cmd(hba, task_tag))
6625 dev_WARN(hba->dev, "%s: unable to clear tm cmd (slot %d) after timeout\n",
6626 __func__, task_tag);
6630 memcpy(treq, hba->utmrdl_base_addr + task_tag, sizeof(*treq));
6632 ufshcd_add_tm_upiu_trace(hba, task_tag, UFS_TM_COMP);
6635 spin_lock_irqsave(hba->host->host_lock, flags);
6636 __clear_bit(task_tag, &hba->outstanding_tasks);
6637 spin_unlock_irqrestore(hba->host->host_lock, flags);
6639 ufshcd_release(hba);
6640 blk_put_request(req);
6646 * ufshcd_issue_tm_cmd - issues task management commands to controller
6647 * @hba: per adapter instance
6648 * @lun_id: LUN ID to which TM command is sent
6649 * @task_id: task ID to which the TM command is applicable
6650 * @tm_function: task management function opcode
6651 * @tm_response: task management service response return value
6653 * Returns non-zero value on error, zero on success.
6655 static int ufshcd_issue_tm_cmd(struct ufs_hba *hba, int lun_id, int task_id,
6656 u8 tm_function, u8 *tm_response)
6658 struct utp_task_req_desc treq = { { 0 }, };
6661 /* Configure task request descriptor */
6662 treq.header.dword_0 = cpu_to_le32(UTP_REQ_DESC_INT_CMD);
6663 treq.header.dword_2 = cpu_to_le32(OCS_INVALID_COMMAND_STATUS);
6665 /* Configure task request UPIU */
6666 treq.upiu_req.req_header.dword_0 = cpu_to_be32(lun_id << 8) |
6667 cpu_to_be32(UPIU_TRANSACTION_TASK_REQ << 24);
6668 treq.upiu_req.req_header.dword_1 = cpu_to_be32(tm_function << 16);
6671 * The host shall provide the same value for LUN field in the basic
6672 * header and for Input Parameter.
6674 treq.upiu_req.input_param1 = cpu_to_be32(lun_id);
6675 treq.upiu_req.input_param2 = cpu_to_be32(task_id);
6677 err = __ufshcd_issue_tm_cmd(hba, &treq, tm_function);
6678 if (err == -ETIMEDOUT)
6681 ocs_value = le32_to_cpu(treq.header.dword_2) & MASK_OCS;
6682 if (ocs_value != OCS_SUCCESS)
6683 dev_err(hba->dev, "%s: failed, ocs = 0x%x\n",
6684 __func__, ocs_value);
6685 else if (tm_response)
6686 *tm_response = be32_to_cpu(treq.upiu_rsp.output_param1) &
6687 MASK_TM_SERVICE_RESP;
6692 * ufshcd_issue_devman_upiu_cmd - API for sending "utrd" type requests
6693 * @hba: per-adapter instance
6694 * @req_upiu: upiu request
6695 * @rsp_upiu: upiu reply
6696 * @desc_buff: pointer to descriptor buffer, NULL if NA
6697 * @buff_len: descriptor size, 0 if NA
6698 * @cmd_type: specifies the type (NOP, Query...)
6699 * @desc_op: descriptor operation
6701 * Those type of requests uses UTP Transfer Request Descriptor - utrd.
6702 * Therefore, it "rides" the device management infrastructure: uses its tag and
6703 * tasks work queues.
6705 * Since there is only one available tag for device management commands,
6706 * the caller is expected to hold the hba->dev_cmd.lock mutex.
6708 static int ufshcd_issue_devman_upiu_cmd(struct ufs_hba *hba,
6709 struct utp_upiu_req *req_upiu,
6710 struct utp_upiu_req *rsp_upiu,
6711 u8 *desc_buff, int *buff_len,
6712 enum dev_cmd_type cmd_type,
6713 enum query_opcode desc_op)
6715 struct request_queue *q = hba->cmd_queue;
6716 DECLARE_COMPLETION_ONSTACK(wait);
6717 struct request *req;
6718 struct ufshcd_lrb *lrbp;
6723 down_read(&hba->clk_scaling_lock);
6725 req = blk_get_request(q, REQ_OP_DRV_OUT, 0);
6731 WARN_ONCE(tag < 0, "Invalid tag %d\n", tag);
6733 if (unlikely(test_bit(tag, &hba->outstanding_reqs))) {
6738 lrbp = &hba->lrb[tag];
6741 lrbp->sense_bufflen = 0;
6742 lrbp->sense_buffer = NULL;
6743 lrbp->task_tag = tag;
6745 lrbp->intr_cmd = true;
6746 ufshcd_prepare_lrbp_crypto(NULL, lrbp);
6747 hba->dev_cmd.type = cmd_type;
6749 if (hba->ufs_version <= ufshci_version(1, 1))
6750 lrbp->command_type = UTP_CMD_TYPE_DEV_MANAGE;
6752 lrbp->command_type = UTP_CMD_TYPE_UFS_STORAGE;
6754 /* update the task tag in the request upiu */
6755 req_upiu->header.dword_0 |= cpu_to_be32(tag);
6757 ufshcd_prepare_req_desc_hdr(lrbp, &upiu_flags, DMA_NONE);
6759 /* just copy the upiu request as it is */
6760 memcpy(lrbp->ucd_req_ptr, req_upiu, sizeof(*lrbp->ucd_req_ptr));
6761 if (desc_buff && desc_op == UPIU_QUERY_OPCODE_WRITE_DESC) {
6762 /* The Data Segment Area is optional depending upon the query
6763 * function value. for WRITE DESCRIPTOR, the data segment
6764 * follows right after the tsf.
6766 memcpy(lrbp->ucd_req_ptr + 1, desc_buff, *buff_len);
6770 memset(lrbp->ucd_rsp_ptr, 0, sizeof(struct utp_upiu_rsp));
6772 hba->dev_cmd.complete = &wait;
6774 ufshcd_add_query_upiu_trace(hba, UFS_QUERY_SEND, lrbp->ucd_req_ptr);
6776 ufshcd_send_command(hba, tag);
6778 * ignore the returning value here - ufshcd_check_query_response is
6779 * bound to fail since dev_cmd.query and dev_cmd.type were left empty.
6780 * read the response directly ignoring all errors.
6782 ufshcd_wait_for_dev_cmd(hba, lrbp, QUERY_REQ_TIMEOUT);
6784 /* just copy the upiu response as it is */
6785 memcpy(rsp_upiu, lrbp->ucd_rsp_ptr, sizeof(*rsp_upiu));
6786 if (desc_buff && desc_op == UPIU_QUERY_OPCODE_READ_DESC) {
6787 u8 *descp = (u8 *)lrbp->ucd_rsp_ptr + sizeof(*rsp_upiu);
6788 u16 resp_len = be32_to_cpu(lrbp->ucd_rsp_ptr->header.dword_2) &
6789 MASK_QUERY_DATA_SEG_LEN;
6791 if (*buff_len >= resp_len) {
6792 memcpy(desc_buff, descp, resp_len);
6793 *buff_len = resp_len;
6796 "%s: rsp size %d is bigger than buffer size %d",
6797 __func__, resp_len, *buff_len);
6802 ufshcd_add_query_upiu_trace(hba, err ? UFS_QUERY_ERR : UFS_QUERY_COMP,
6803 (struct utp_upiu_req *)lrbp->ucd_rsp_ptr);
6806 blk_put_request(req);
6808 up_read(&hba->clk_scaling_lock);
6813 * ufshcd_exec_raw_upiu_cmd - API function for sending raw upiu commands
6814 * @hba: per-adapter instance
6815 * @req_upiu: upiu request
6816 * @rsp_upiu: upiu reply - only 8 DW as we do not support scsi commands
6817 * @msgcode: message code, one of UPIU Transaction Codes Initiator to Target
6818 * @desc_buff: pointer to descriptor buffer, NULL if NA
6819 * @buff_len: descriptor size, 0 if NA
6820 * @desc_op: descriptor operation
6822 * Supports UTP Transfer requests (nop and query), and UTP Task
6823 * Management requests.
6824 * It is up to the caller to fill the upiu conent properly, as it will
6825 * be copied without any further input validations.
6827 int ufshcd_exec_raw_upiu_cmd(struct ufs_hba *hba,
6828 struct utp_upiu_req *req_upiu,
6829 struct utp_upiu_req *rsp_upiu,
6831 u8 *desc_buff, int *buff_len,
6832 enum query_opcode desc_op)
6835 enum dev_cmd_type cmd_type = DEV_CMD_TYPE_QUERY;
6836 struct utp_task_req_desc treq = { { 0 }, };
6838 u8 tm_f = be32_to_cpu(req_upiu->header.dword_1) >> 16 & MASK_TM_FUNC;
6841 case UPIU_TRANSACTION_NOP_OUT:
6842 cmd_type = DEV_CMD_TYPE_NOP;
6844 case UPIU_TRANSACTION_QUERY_REQ:
6845 ufshcd_hold(hba, false);
6846 mutex_lock(&hba->dev_cmd.lock);
6847 err = ufshcd_issue_devman_upiu_cmd(hba, req_upiu, rsp_upiu,
6848 desc_buff, buff_len,
6850 mutex_unlock(&hba->dev_cmd.lock);
6851 ufshcd_release(hba);
6854 case UPIU_TRANSACTION_TASK_REQ:
6855 treq.header.dword_0 = cpu_to_le32(UTP_REQ_DESC_INT_CMD);
6856 treq.header.dword_2 = cpu_to_le32(OCS_INVALID_COMMAND_STATUS);
6858 memcpy(&treq.upiu_req, req_upiu, sizeof(*req_upiu));
6860 err = __ufshcd_issue_tm_cmd(hba, &treq, tm_f);
6861 if (err == -ETIMEDOUT)
6864 ocs_value = le32_to_cpu(treq.header.dword_2) & MASK_OCS;
6865 if (ocs_value != OCS_SUCCESS) {
6866 dev_err(hba->dev, "%s: failed, ocs = 0x%x\n", __func__,
6871 memcpy(rsp_upiu, &treq.upiu_rsp, sizeof(*rsp_upiu));
6884 * ufshcd_eh_device_reset_handler - device reset handler registered to
6886 * @cmd: SCSI command pointer
6888 * Returns SUCCESS/FAILED
6890 static int ufshcd_eh_device_reset_handler(struct scsi_cmnd *cmd)
6892 struct Scsi_Host *host;
6893 struct ufs_hba *hba;
6898 host = cmd->device->host;
6899 hba = shost_priv(host);
6901 lun = ufshcd_scsi_to_upiu_lun(cmd->device->lun);
6902 err = ufshcd_issue_tm_cmd(hba, lun, 0, UFS_LOGICAL_RESET, &resp);
6903 if (err || resp != UPIU_TASK_MANAGEMENT_FUNC_COMPL) {
6909 /* clear the commands that were pending for corresponding LUN */
6910 for_each_set_bit(pos, &hba->outstanding_reqs, hba->nutrs) {
6911 if (hba->lrb[pos].lun == lun) {
6912 err = ufshcd_clear_cmd(hba, pos);
6915 __ufshcd_transfer_req_compl(hba, pos, /*retry_requests=*/true);
6920 hba->req_abort_count = 0;
6921 ufshcd_update_evt_hist(hba, UFS_EVT_DEV_RESET, (u32)err);
6925 dev_err(hba->dev, "%s: failed with err %d\n", __func__, err);
6931 static void ufshcd_set_req_abort_skip(struct ufs_hba *hba, unsigned long bitmap)
6933 struct ufshcd_lrb *lrbp;
6936 for_each_set_bit(tag, &bitmap, hba->nutrs) {
6937 lrbp = &hba->lrb[tag];
6938 lrbp->req_abort_skip = true;
6943 * ufshcd_try_to_abort_task - abort a specific task
6944 * @hba: Pointer to adapter instance
6945 * @tag: Task tag/index to be aborted
6947 * Abort the pending command in device by sending UFS_ABORT_TASK task management
6948 * command, and in host controller by clearing the door-bell register. There can
6949 * be race between controller sending the command to the device while abort is
6950 * issued. To avoid that, first issue UFS_QUERY_TASK to check if the command is
6951 * really issued and then try to abort it.
6953 * Returns zero on success, non-zero on failure
6955 static int ufshcd_try_to_abort_task(struct ufs_hba *hba, int tag)
6957 struct ufshcd_lrb *lrbp = &hba->lrb[tag];
6963 for (poll_cnt = 100; poll_cnt; poll_cnt--) {
6964 err = ufshcd_issue_tm_cmd(hba, lrbp->lun, lrbp->task_tag,
6965 UFS_QUERY_TASK, &resp);
6966 if (!err && resp == UPIU_TASK_MANAGEMENT_FUNC_SUCCEEDED) {
6967 /* cmd pending in the device */
6968 dev_err(hba->dev, "%s: cmd pending in the device. tag = %d\n",
6971 } else if (!err && resp == UPIU_TASK_MANAGEMENT_FUNC_COMPL) {
6973 * cmd not pending in the device, check if it is
6976 dev_err(hba->dev, "%s: cmd at tag %d not pending in the device.\n",
6978 reg = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
6979 if (reg & (1 << tag)) {
6980 /* sleep for max. 200us to stabilize */
6981 usleep_range(100, 200);
6984 /* command completed already */
6985 dev_err(hba->dev, "%s: cmd at tag %d successfully cleared from DB.\n",
6990 "%s: no response from device. tag = %d, err %d\n",
6991 __func__, tag, err);
6993 err = resp; /* service response error */
7003 err = ufshcd_issue_tm_cmd(hba, lrbp->lun, lrbp->task_tag,
7004 UFS_ABORT_TASK, &resp);
7005 if (err || resp != UPIU_TASK_MANAGEMENT_FUNC_COMPL) {
7007 err = resp; /* service response error */
7008 dev_err(hba->dev, "%s: issued. tag = %d, err %d\n",
7009 __func__, tag, err);
7014 err = ufshcd_clear_cmd(hba, tag);
7016 dev_err(hba->dev, "%s: Failed clearing cmd at tag %d, err %d\n",
7017 __func__, tag, err);
7024 * ufshcd_abort - scsi host template eh_abort_handler callback
7025 * @cmd: SCSI command pointer
7027 * Returns SUCCESS/FAILED
7029 static int ufshcd_abort(struct scsi_cmnd *cmd)
7031 struct Scsi_Host *host = cmd->device->host;
7032 struct ufs_hba *hba = shost_priv(host);
7033 int tag = scsi_cmd_to_rq(cmd)->tag;
7034 struct ufshcd_lrb *lrbp = &hba->lrb[tag];
7035 unsigned long flags;
7039 WARN_ONCE(tag < 0, "Invalid tag %d\n", tag);
7041 ufshcd_hold(hba, false);
7042 reg = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
7043 /* If command is already aborted/completed, return FAILED. */
7044 if (!(test_bit(tag, &hba->outstanding_reqs))) {
7046 "%s: cmd at tag %d already completed, outstanding=0x%lx, doorbell=0x%x\n",
7047 __func__, tag, hba->outstanding_reqs, reg);
7051 /* Print Transfer Request of aborted task */
7052 dev_info(hba->dev, "%s: Device abort task at tag %d\n", __func__, tag);
7055 * Print detailed info about aborted request.
7056 * As more than one request might get aborted at the same time,
7057 * print full information only for the first aborted request in order
7058 * to reduce repeated printouts. For other aborted requests only print
7061 scsi_print_command(cmd);
7062 if (!hba->req_abort_count) {
7063 ufshcd_update_evt_hist(hba, UFS_EVT_ABORT, tag);
7064 ufshcd_print_evt_hist(hba);
7065 ufshcd_print_host_state(hba);
7066 ufshcd_print_pwr_info(hba);
7067 ufshcd_print_trs(hba, 1 << tag, true);
7069 ufshcd_print_trs(hba, 1 << tag, false);
7071 hba->req_abort_count++;
7073 if (!(reg & (1 << tag))) {
7075 "%s: cmd was completed, but without a notifying intr, tag = %d",
7077 __ufshcd_transfer_req_compl(hba, 1UL << tag, /*retry_requests=*/false);
7082 * Task abort to the device W-LUN is illegal. When this command
7083 * will fail, due to spec violation, scsi err handling next step
7084 * will be to send LU reset which, again, is a spec violation.
7085 * To avoid these unnecessary/illegal steps, first we clean up
7086 * the lrb taken by this cmd and re-set it in outstanding_reqs,
7087 * then queue the error handler and bail.
7089 if (lrbp->lun == UFS_UPIU_UFS_DEVICE_WLUN) {
7090 ufshcd_update_evt_hist(hba, UFS_EVT_ABORT, lrbp->lun);
7092 spin_lock_irqsave(host->host_lock, flags);
7093 hba->force_reset = true;
7094 spin_unlock_irqrestore(host->host_lock, flags);
7096 ufshcd_schedule_eh(hba);
7101 /* Skip task abort in case previous aborts failed and report failure */
7102 if (lrbp->req_abort_skip) {
7103 dev_err(hba->dev, "%s: skipping abort\n", __func__);
7104 ufshcd_set_req_abort_skip(hba, hba->outstanding_reqs);
7108 err = ufshcd_try_to_abort_task(hba, tag);
7110 dev_err(hba->dev, "%s: failed with err %d\n", __func__, err);
7111 ufshcd_set_req_abort_skip(hba, hba->outstanding_reqs);
7119 /* Matches the ufshcd_hold() call at the start of this function. */
7120 ufshcd_release(hba);
7125 * ufshcd_host_reset_and_restore - reset and restore host controller
7126 * @hba: per-adapter instance
7128 * Note that host controller reset may issue DME_RESET to
7129 * local and remote (device) Uni-Pro stack and the attributes
7130 * are reset to default state.
7132 * Returns zero on success, non-zero on failure
7134 static int ufshcd_host_reset_and_restore(struct ufs_hba *hba)
7139 * Stop the host controller and complete the requests
7142 ufshpb_reset_host(hba);
7143 ufshcd_hba_stop(hba);
7144 hba->silence_err_logs = true;
7145 ufshcd_retry_aborted_requests(hba);
7146 hba->silence_err_logs = false;
7148 /* scale up clocks to max frequency before full reinitialization */
7149 ufshcd_set_clk_freq(hba, true);
7151 err = ufshcd_hba_enable(hba);
7153 /* Establish the link again and restore the device */
7155 err = ufshcd_probe_hba(hba, false);
7158 dev_err(hba->dev, "%s: Host init failed %d\n", __func__, err);
7159 ufshcd_update_evt_hist(hba, UFS_EVT_HOST_RESET, (u32)err);
7164 * ufshcd_reset_and_restore - reset and re-initialize host/device
7165 * @hba: per-adapter instance
7167 * Reset and recover device, host and re-establish link. This
7168 * is helpful to recover the communication in fatal error conditions.
7170 * Returns zero on success, non-zero on failure
7172 static int ufshcd_reset_and_restore(struct ufs_hba *hba)
7175 u32 saved_uic_err = 0;
7177 unsigned long flags;
7178 int retries = MAX_HOST_RESET_RETRIES;
7180 spin_lock_irqsave(hba->host->host_lock, flags);
7183 * This is a fresh start, cache and clear saved error first,
7184 * in case new error generated during reset and restore.
7186 saved_err |= hba->saved_err;
7187 saved_uic_err |= hba->saved_uic_err;
7189 hba->saved_uic_err = 0;
7190 hba->force_reset = false;
7191 hba->ufshcd_state = UFSHCD_STATE_RESET;
7192 spin_unlock_irqrestore(hba->host->host_lock, flags);
7194 /* Reset the attached device */
7195 ufshcd_device_reset(hba);
7197 err = ufshcd_host_reset_and_restore(hba);
7199 spin_lock_irqsave(hba->host->host_lock, flags);
7202 /* Do not exit unless operational or dead */
7203 if (hba->ufshcd_state != UFSHCD_STATE_OPERATIONAL &&
7204 hba->ufshcd_state != UFSHCD_STATE_ERROR &&
7205 hba->ufshcd_state != UFSHCD_STATE_EH_SCHEDULED_NON_FATAL)
7207 } while (err && --retries);
7210 * Inform scsi mid-layer that we did reset and allow to handle
7211 * Unit Attention properly.
7213 scsi_report_bus_reset(hba->host, 0);
7215 hba->ufshcd_state = UFSHCD_STATE_ERROR;
7216 hba->saved_err |= saved_err;
7217 hba->saved_uic_err |= saved_uic_err;
7219 spin_unlock_irqrestore(hba->host->host_lock, flags);
7225 * ufshcd_eh_host_reset_handler - host reset handler registered to scsi layer
7226 * @cmd: SCSI command pointer
7228 * Returns SUCCESS/FAILED
7230 static int ufshcd_eh_host_reset_handler(struct scsi_cmnd *cmd)
7233 unsigned long flags;
7234 struct ufs_hba *hba;
7236 hba = shost_priv(cmd->device->host);
7238 spin_lock_irqsave(hba->host->host_lock, flags);
7239 hba->force_reset = true;
7240 dev_err(hba->dev, "%s: reset in progress - 1\n", __func__);
7241 spin_unlock_irqrestore(hba->host->host_lock, flags);
7243 ufshcd_err_handler(hba->host);
7245 spin_lock_irqsave(hba->host->host_lock, flags);
7246 if (hba->ufshcd_state == UFSHCD_STATE_ERROR)
7248 spin_unlock_irqrestore(hba->host->host_lock, flags);
7254 * ufshcd_get_max_icc_level - calculate the ICC level
7255 * @sup_curr_uA: max. current supported by the regulator
7256 * @start_scan: row at the desc table to start scan from
7257 * @buff: power descriptor buffer
7259 * Returns calculated max ICC level for specific regulator
7261 static u32 ufshcd_get_max_icc_level(int sup_curr_uA, u32 start_scan, char *buff)
7268 for (i = start_scan; i >= 0; i--) {
7269 data = be16_to_cpup((__be16 *)&buff[2 * i]);
7270 unit = (data & ATTR_ICC_LVL_UNIT_MASK) >>
7271 ATTR_ICC_LVL_UNIT_OFFSET;
7272 curr_uA = data & ATTR_ICC_LVL_VALUE_MASK;
7274 case UFSHCD_NANO_AMP:
7275 curr_uA = curr_uA / 1000;
7277 case UFSHCD_MILI_AMP:
7278 curr_uA = curr_uA * 1000;
7281 curr_uA = curr_uA * 1000 * 1000;
7283 case UFSHCD_MICRO_AMP:
7287 if (sup_curr_uA >= curr_uA)
7292 pr_err("%s: Couldn't find valid icc_level = %d", __func__, i);
7299 * ufshcd_find_max_sup_active_icc_level - calculate the max ICC level
7300 * In case regulators are not initialized we'll return 0
7301 * @hba: per-adapter instance
7302 * @desc_buf: power descriptor buffer to extract ICC levels from.
7303 * @len: length of desc_buff
7305 * Returns calculated ICC level
7307 static u32 ufshcd_find_max_sup_active_icc_level(struct ufs_hba *hba,
7308 u8 *desc_buf, int len)
7312 if (!hba->vreg_info.vcc || !hba->vreg_info.vccq ||
7313 !hba->vreg_info.vccq2) {
7315 "%s: Regulator capability was not set, actvIccLevel=%d",
7316 __func__, icc_level);
7320 if (hba->vreg_info.vcc->max_uA)
7321 icc_level = ufshcd_get_max_icc_level(
7322 hba->vreg_info.vcc->max_uA,
7323 POWER_DESC_MAX_ACTV_ICC_LVLS - 1,
7324 &desc_buf[PWR_DESC_ACTIVE_LVLS_VCC_0]);
7326 if (hba->vreg_info.vccq->max_uA)
7327 icc_level = ufshcd_get_max_icc_level(
7328 hba->vreg_info.vccq->max_uA,
7330 &desc_buf[PWR_DESC_ACTIVE_LVLS_VCCQ_0]);
7332 if (hba->vreg_info.vccq2->max_uA)
7333 icc_level = ufshcd_get_max_icc_level(
7334 hba->vreg_info.vccq2->max_uA,
7336 &desc_buf[PWR_DESC_ACTIVE_LVLS_VCCQ2_0]);
7341 static void ufshcd_set_active_icc_lvl(struct ufs_hba *hba)
7344 int buff_len = hba->desc_size[QUERY_DESC_IDN_POWER];
7348 desc_buf = kmalloc(buff_len, GFP_KERNEL);
7352 ret = ufshcd_read_desc_param(hba, QUERY_DESC_IDN_POWER, 0, 0,
7353 desc_buf, buff_len);
7356 "%s: Failed reading power descriptor.len = %d ret = %d",
7357 __func__, buff_len, ret);
7361 icc_level = ufshcd_find_max_sup_active_icc_level(hba, desc_buf,
7363 dev_dbg(hba->dev, "%s: setting icc_level 0x%x", __func__, icc_level);
7365 ret = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_WRITE_ATTR,
7366 QUERY_ATTR_IDN_ACTIVE_ICC_LVL, 0, 0, &icc_level);
7370 "%s: Failed configuring bActiveICCLevel = %d ret = %d",
7371 __func__, icc_level, ret);
7377 static inline void ufshcd_blk_pm_runtime_init(struct scsi_device *sdev)
7379 scsi_autopm_get_device(sdev);
7380 blk_pm_runtime_init(sdev->request_queue, &sdev->sdev_gendev);
7381 if (sdev->rpm_autosuspend)
7382 pm_runtime_set_autosuspend_delay(&sdev->sdev_gendev,
7383 RPM_AUTOSUSPEND_DELAY_MS);
7384 scsi_autopm_put_device(sdev);
7388 * ufshcd_scsi_add_wlus - Adds required W-LUs
7389 * @hba: per-adapter instance
7391 * UFS device specification requires the UFS devices to support 4 well known
7393 * "REPORT_LUNS" (address: 01h)
7394 * "UFS Device" (address: 50h)
7395 * "RPMB" (address: 44h)
7396 * "BOOT" (address: 30h)
7397 * UFS device's power management needs to be controlled by "POWER CONDITION"
7398 * field of SSU (START STOP UNIT) command. But this "power condition" field
7399 * will take effect only when its sent to "UFS device" well known logical unit
7400 * hence we require the scsi_device instance to represent this logical unit in
7401 * order for the UFS host driver to send the SSU command for power management.
7403 * We also require the scsi_device instance for "RPMB" (Replay Protected Memory
7404 * Block) LU so user space process can control this LU. User space may also
7405 * want to have access to BOOT LU.
7407 * This function adds scsi device instances for each of all well known LUs
7408 * (except "REPORT LUNS" LU).
7410 * Returns zero on success (all required W-LUs are added successfully),
7411 * non-zero error value on failure (if failed to add any of the required W-LU).
7413 static int ufshcd_scsi_add_wlus(struct ufs_hba *hba)
7416 struct scsi_device *sdev_boot;
7418 hba->sdev_ufs_device = __scsi_add_device(hba->host, 0, 0,
7419 ufshcd_upiu_wlun_to_scsi_wlun(UFS_UPIU_UFS_DEVICE_WLUN), NULL);
7420 if (IS_ERR(hba->sdev_ufs_device)) {
7421 ret = PTR_ERR(hba->sdev_ufs_device);
7422 hba->sdev_ufs_device = NULL;
7425 scsi_device_put(hba->sdev_ufs_device);
7427 hba->sdev_rpmb = __scsi_add_device(hba->host, 0, 0,
7428 ufshcd_upiu_wlun_to_scsi_wlun(UFS_UPIU_RPMB_WLUN), NULL);
7429 if (IS_ERR(hba->sdev_rpmb)) {
7430 ret = PTR_ERR(hba->sdev_rpmb);
7431 goto remove_sdev_ufs_device;
7433 ufshcd_blk_pm_runtime_init(hba->sdev_rpmb);
7434 scsi_device_put(hba->sdev_rpmb);
7436 sdev_boot = __scsi_add_device(hba->host, 0, 0,
7437 ufshcd_upiu_wlun_to_scsi_wlun(UFS_UPIU_BOOT_WLUN), NULL);
7438 if (IS_ERR(sdev_boot)) {
7439 dev_err(hba->dev, "%s: BOOT WLUN not found\n", __func__);
7441 ufshcd_blk_pm_runtime_init(sdev_boot);
7442 scsi_device_put(sdev_boot);
7446 remove_sdev_ufs_device:
7447 scsi_remove_device(hba->sdev_ufs_device);
7452 static void ufshcd_wb_probe(struct ufs_hba *hba, u8 *desc_buf)
7454 struct ufs_dev_info *dev_info = &hba->dev_info;
7456 u32 d_lu_wb_buf_alloc;
7457 u32 ext_ufs_feature;
7459 if (!ufshcd_is_wb_allowed(hba))
7462 * Probe WB only for UFS-2.2 and UFS-3.1 (and later) devices or
7463 * UFS devices with quirk UFS_DEVICE_QUIRK_SUPPORT_EXTENDED_FEATURES
7466 if (!(dev_info->wspecversion >= 0x310 ||
7467 dev_info->wspecversion == 0x220 ||
7468 (hba->dev_quirks & UFS_DEVICE_QUIRK_SUPPORT_EXTENDED_FEATURES)))
7471 if (hba->desc_size[QUERY_DESC_IDN_DEVICE] <
7472 DEVICE_DESC_PARAM_EXT_UFS_FEATURE_SUP + 4)
7475 ext_ufs_feature = get_unaligned_be32(desc_buf +
7476 DEVICE_DESC_PARAM_EXT_UFS_FEATURE_SUP);
7478 if (!(ext_ufs_feature & UFS_DEV_WRITE_BOOSTER_SUP))
7482 * WB may be supported but not configured while provisioning. The spec
7483 * says, in dedicated wb buffer mode, a max of 1 lun would have wb
7484 * buffer configured.
7486 dev_info->wb_buffer_type = desc_buf[DEVICE_DESC_PARAM_WB_TYPE];
7488 dev_info->b_presrv_uspc_en =
7489 desc_buf[DEVICE_DESC_PARAM_WB_PRESRV_USRSPC_EN];
7491 if (dev_info->wb_buffer_type == WB_BUF_MODE_SHARED) {
7492 if (!get_unaligned_be32(desc_buf +
7493 DEVICE_DESC_PARAM_WB_SHARED_ALLOC_UNITS))
7496 for (lun = 0; lun < UFS_UPIU_MAX_WB_LUN_ID; lun++) {
7497 d_lu_wb_buf_alloc = 0;
7498 ufshcd_read_unit_desc_param(hba,
7500 UNIT_DESC_PARAM_WB_BUF_ALLOC_UNITS,
7501 (u8 *)&d_lu_wb_buf_alloc,
7502 sizeof(d_lu_wb_buf_alloc));
7503 if (d_lu_wb_buf_alloc) {
7504 dev_info->wb_dedicated_lu = lun;
7509 if (!d_lu_wb_buf_alloc)
7515 hba->caps &= ~UFSHCD_CAP_WB_EN;
7518 static void ufshcd_temp_notif_probe(struct ufs_hba *hba, u8 *desc_buf)
7520 struct ufs_dev_info *dev_info = &hba->dev_info;
7521 u32 ext_ufs_feature;
7524 if (!(hba->caps & UFSHCD_CAP_TEMP_NOTIF) || dev_info->wspecversion < 0x300)
7527 ext_ufs_feature = get_unaligned_be32(desc_buf + DEVICE_DESC_PARAM_EXT_UFS_FEATURE_SUP);
7529 if (ext_ufs_feature & UFS_DEV_LOW_TEMP_NOTIF)
7530 mask |= MASK_EE_TOO_LOW_TEMP;
7532 if (ext_ufs_feature & UFS_DEV_HIGH_TEMP_NOTIF)
7533 mask |= MASK_EE_TOO_HIGH_TEMP;
7536 ufshcd_enable_ee(hba, mask);
7537 ufs_hwmon_probe(hba, mask);
7541 void ufshcd_fixup_dev_quirks(struct ufs_hba *hba, struct ufs_dev_fix *fixups)
7543 struct ufs_dev_fix *f;
7544 struct ufs_dev_info *dev_info = &hba->dev_info;
7549 for (f = fixups; f->quirk; f++) {
7550 if ((f->wmanufacturerid == dev_info->wmanufacturerid ||
7551 f->wmanufacturerid == UFS_ANY_VENDOR) &&
7552 ((dev_info->model &&
7553 STR_PRFX_EQUAL(f->model, dev_info->model)) ||
7554 !strcmp(f->model, UFS_ANY_MODEL)))
7555 hba->dev_quirks |= f->quirk;
7558 EXPORT_SYMBOL_GPL(ufshcd_fixup_dev_quirks);
7560 static void ufs_fixup_device_setup(struct ufs_hba *hba)
7562 /* fix by general quirk table */
7563 ufshcd_fixup_dev_quirks(hba, ufs_fixups);
7565 /* allow vendors to fix quirks */
7566 ufshcd_vops_fixup_dev_quirks(hba);
7569 static int ufs_get_device_desc(struct ufs_hba *hba)
7573 u8 b_ufs_feature_sup;
7575 struct ufs_dev_info *dev_info = &hba->dev_info;
7577 desc_buf = kmalloc(QUERY_DESC_MAX_SIZE, GFP_KERNEL);
7583 err = ufshcd_read_desc_param(hba, QUERY_DESC_IDN_DEVICE, 0, 0, desc_buf,
7584 hba->desc_size[QUERY_DESC_IDN_DEVICE]);
7586 dev_err(hba->dev, "%s: Failed reading Device Desc. err = %d\n",
7592 * getting vendor (manufacturerID) and Bank Index in big endian
7595 dev_info->wmanufacturerid = desc_buf[DEVICE_DESC_PARAM_MANF_ID] << 8 |
7596 desc_buf[DEVICE_DESC_PARAM_MANF_ID + 1];
7598 /* getting Specification Version in big endian format */
7599 dev_info->wspecversion = desc_buf[DEVICE_DESC_PARAM_SPEC_VER] << 8 |
7600 desc_buf[DEVICE_DESC_PARAM_SPEC_VER + 1];
7601 b_ufs_feature_sup = desc_buf[DEVICE_DESC_PARAM_UFS_FEAT];
7603 model_index = desc_buf[DEVICE_DESC_PARAM_PRDCT_NAME];
7605 if (dev_info->wspecversion >= UFS_DEV_HPB_SUPPORT_VERSION &&
7606 (b_ufs_feature_sup & UFS_DEV_HPB_SUPPORT)) {
7607 bool hpb_en = false;
7609 ufshpb_get_dev_info(hba, desc_buf);
7611 if (!ufshpb_is_legacy(hba))
7612 err = ufshcd_query_flag_retry(hba,
7613 UPIU_QUERY_OPCODE_READ_FLAG,
7614 QUERY_FLAG_IDN_HPB_EN, 0,
7617 if (ufshpb_is_legacy(hba) || (!err && hpb_en))
7618 dev_info->hpb_enabled = true;
7621 err = ufshcd_read_string_desc(hba, model_index,
7622 &dev_info->model, SD_ASCII_STD);
7624 dev_err(hba->dev, "%s: Failed reading Product Name. err = %d\n",
7629 hba->luns_avail = desc_buf[DEVICE_DESC_PARAM_NUM_LU] +
7630 desc_buf[DEVICE_DESC_PARAM_NUM_WLU];
7632 ufs_fixup_device_setup(hba);
7634 ufshcd_wb_probe(hba, desc_buf);
7636 ufshcd_temp_notif_probe(hba, desc_buf);
7639 * ufshcd_read_string_desc returns size of the string
7640 * reset the error value
7649 static void ufs_put_device_desc(struct ufs_hba *hba)
7651 struct ufs_dev_info *dev_info = &hba->dev_info;
7653 kfree(dev_info->model);
7654 dev_info->model = NULL;
7658 * ufshcd_tune_pa_tactivate - Tunes PA_TActivate of local UniPro
7659 * @hba: per-adapter instance
7661 * PA_TActivate parameter can be tuned manually if UniPro version is less than
7662 * 1.61. PA_TActivate needs to be greater than or equal to peerM-PHY's
7663 * RX_MIN_ACTIVATETIME_CAPABILITY attribute. This optimal value can help reduce
7664 * the hibern8 exit latency.
7666 * Returns zero on success, non-zero error value on failure.
7668 static int ufshcd_tune_pa_tactivate(struct ufs_hba *hba)
7671 u32 peer_rx_min_activatetime = 0, tuned_pa_tactivate;
7673 ret = ufshcd_dme_peer_get(hba,
7675 RX_MIN_ACTIVATETIME_CAPABILITY,
7676 UIC_ARG_MPHY_RX_GEN_SEL_INDEX(0)),
7677 &peer_rx_min_activatetime);
7681 /* make sure proper unit conversion is applied */
7682 tuned_pa_tactivate =
7683 ((peer_rx_min_activatetime * RX_MIN_ACTIVATETIME_UNIT_US)
7684 / PA_TACTIVATE_TIME_UNIT_US);
7685 ret = ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TACTIVATE),
7686 tuned_pa_tactivate);
7693 * ufshcd_tune_pa_hibern8time - Tunes PA_Hibern8Time of local UniPro
7694 * @hba: per-adapter instance
7696 * PA_Hibern8Time parameter can be tuned manually if UniPro version is less than
7697 * 1.61. PA_Hibern8Time needs to be maximum of local M-PHY's
7698 * TX_HIBERN8TIME_CAPABILITY & peer M-PHY's RX_HIBERN8TIME_CAPABILITY.
7699 * This optimal value can help reduce the hibern8 exit latency.
7701 * Returns zero on success, non-zero error value on failure.
7703 static int ufshcd_tune_pa_hibern8time(struct ufs_hba *hba)
7706 u32 local_tx_hibern8_time_cap = 0, peer_rx_hibern8_time_cap = 0;
7707 u32 max_hibern8_time, tuned_pa_hibern8time;
7709 ret = ufshcd_dme_get(hba,
7710 UIC_ARG_MIB_SEL(TX_HIBERN8TIME_CAPABILITY,
7711 UIC_ARG_MPHY_TX_GEN_SEL_INDEX(0)),
7712 &local_tx_hibern8_time_cap);
7716 ret = ufshcd_dme_peer_get(hba,
7717 UIC_ARG_MIB_SEL(RX_HIBERN8TIME_CAPABILITY,
7718 UIC_ARG_MPHY_RX_GEN_SEL_INDEX(0)),
7719 &peer_rx_hibern8_time_cap);
7723 max_hibern8_time = max(local_tx_hibern8_time_cap,
7724 peer_rx_hibern8_time_cap);
7725 /* make sure proper unit conversion is applied */
7726 tuned_pa_hibern8time = ((max_hibern8_time * HIBERN8TIME_UNIT_US)
7727 / PA_HIBERN8_TIME_UNIT_US);
7728 ret = ufshcd_dme_set(hba, UIC_ARG_MIB(PA_HIBERN8TIME),
7729 tuned_pa_hibern8time);
7735 * ufshcd_quirk_tune_host_pa_tactivate - Ensures that host PA_TACTIVATE is
7736 * less than device PA_TACTIVATE time.
7737 * @hba: per-adapter instance
7739 * Some UFS devices require host PA_TACTIVATE to be lower than device
7740 * PA_TACTIVATE, we need to enable UFS_DEVICE_QUIRK_HOST_PA_TACTIVATE quirk
7743 * Returns zero on success, non-zero error value on failure.
7745 static int ufshcd_quirk_tune_host_pa_tactivate(struct ufs_hba *hba)
7748 u32 granularity, peer_granularity;
7749 u32 pa_tactivate, peer_pa_tactivate;
7750 u32 pa_tactivate_us, peer_pa_tactivate_us;
7751 u8 gran_to_us_table[] = {1, 4, 8, 16, 32, 100};
7753 ret = ufshcd_dme_get(hba, UIC_ARG_MIB(PA_GRANULARITY),
7758 ret = ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_GRANULARITY),
7763 if ((granularity < PA_GRANULARITY_MIN_VAL) ||
7764 (granularity > PA_GRANULARITY_MAX_VAL)) {
7765 dev_err(hba->dev, "%s: invalid host PA_GRANULARITY %d",
7766 __func__, granularity);
7770 if ((peer_granularity < PA_GRANULARITY_MIN_VAL) ||
7771 (peer_granularity > PA_GRANULARITY_MAX_VAL)) {
7772 dev_err(hba->dev, "%s: invalid device PA_GRANULARITY %d",
7773 __func__, peer_granularity);
7777 ret = ufshcd_dme_get(hba, UIC_ARG_MIB(PA_TACTIVATE), &pa_tactivate);
7781 ret = ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_TACTIVATE),
7782 &peer_pa_tactivate);
7786 pa_tactivate_us = pa_tactivate * gran_to_us_table[granularity - 1];
7787 peer_pa_tactivate_us = peer_pa_tactivate *
7788 gran_to_us_table[peer_granularity - 1];
7790 if (pa_tactivate_us > peer_pa_tactivate_us) {
7791 u32 new_peer_pa_tactivate;
7793 new_peer_pa_tactivate = pa_tactivate_us /
7794 gran_to_us_table[peer_granularity - 1];
7795 new_peer_pa_tactivate++;
7796 ret = ufshcd_dme_peer_set(hba, UIC_ARG_MIB(PA_TACTIVATE),
7797 new_peer_pa_tactivate);
7804 static void ufshcd_tune_unipro_params(struct ufs_hba *hba)
7806 if (ufshcd_is_unipro_pa_params_tuning_req(hba)) {
7807 ufshcd_tune_pa_tactivate(hba);
7808 ufshcd_tune_pa_hibern8time(hba);
7811 ufshcd_vops_apply_dev_quirks(hba);
7813 if (hba->dev_quirks & UFS_DEVICE_QUIRK_PA_TACTIVATE)
7814 /* set 1ms timeout for PA_TACTIVATE */
7815 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TACTIVATE), 10);
7817 if (hba->dev_quirks & UFS_DEVICE_QUIRK_HOST_PA_TACTIVATE)
7818 ufshcd_quirk_tune_host_pa_tactivate(hba);
7821 static void ufshcd_clear_dbg_ufs_stats(struct ufs_hba *hba)
7823 hba->ufs_stats.hibern8_exit_cnt = 0;
7824 hba->ufs_stats.last_hibern8_exit_tstamp = ktime_set(0, 0);
7825 hba->req_abort_count = 0;
7828 static int ufshcd_device_geo_params_init(struct ufs_hba *hba)
7834 buff_len = hba->desc_size[QUERY_DESC_IDN_GEOMETRY];
7835 desc_buf = kmalloc(buff_len, GFP_KERNEL);
7841 err = ufshcd_read_desc_param(hba, QUERY_DESC_IDN_GEOMETRY, 0, 0,
7842 desc_buf, buff_len);
7844 dev_err(hba->dev, "%s: Failed reading Geometry Desc. err = %d\n",
7849 if (desc_buf[GEOMETRY_DESC_PARAM_MAX_NUM_LUN] == 1)
7850 hba->dev_info.max_lu_supported = 32;
7851 else if (desc_buf[GEOMETRY_DESC_PARAM_MAX_NUM_LUN] == 0)
7852 hba->dev_info.max_lu_supported = 8;
7854 if (hba->desc_size[QUERY_DESC_IDN_GEOMETRY] >=
7855 GEOMETRY_DESC_PARAM_HPB_MAX_ACTIVE_REGS)
7856 ufshpb_get_geo_info(hba, desc_buf);
7863 static struct ufs_ref_clk ufs_ref_clk_freqs[] = {
7864 {19200000, REF_CLK_FREQ_19_2_MHZ},
7865 {26000000, REF_CLK_FREQ_26_MHZ},
7866 {38400000, REF_CLK_FREQ_38_4_MHZ},
7867 {52000000, REF_CLK_FREQ_52_MHZ},
7868 {0, REF_CLK_FREQ_INVAL},
7871 static enum ufs_ref_clk_freq
7872 ufs_get_bref_clk_from_hz(unsigned long freq)
7876 for (i = 0; ufs_ref_clk_freqs[i].freq_hz; i++)
7877 if (ufs_ref_clk_freqs[i].freq_hz == freq)
7878 return ufs_ref_clk_freqs[i].val;
7880 return REF_CLK_FREQ_INVAL;
7883 void ufshcd_parse_dev_ref_clk_freq(struct ufs_hba *hba, struct clk *refclk)
7887 freq = clk_get_rate(refclk);
7889 hba->dev_ref_clk_freq =
7890 ufs_get_bref_clk_from_hz(freq);
7892 if (hba->dev_ref_clk_freq == REF_CLK_FREQ_INVAL)
7894 "invalid ref_clk setting = %ld\n", freq);
7897 static int ufshcd_set_dev_ref_clk(struct ufs_hba *hba)
7901 u32 freq = hba->dev_ref_clk_freq;
7903 err = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
7904 QUERY_ATTR_IDN_REF_CLK_FREQ, 0, 0, &ref_clk);
7907 dev_err(hba->dev, "failed reading bRefClkFreq. err = %d\n",
7912 if (ref_clk == freq)
7913 goto out; /* nothing to update */
7915 err = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_WRITE_ATTR,
7916 QUERY_ATTR_IDN_REF_CLK_FREQ, 0, 0, &freq);
7919 dev_err(hba->dev, "bRefClkFreq setting to %lu Hz failed\n",
7920 ufs_ref_clk_freqs[freq].freq_hz);
7924 dev_dbg(hba->dev, "bRefClkFreq setting to %lu Hz succeeded\n",
7925 ufs_ref_clk_freqs[freq].freq_hz);
7931 static int ufshcd_device_params_init(struct ufs_hba *hba)
7936 /* Init device descriptor sizes */
7937 for (i = 0; i < QUERY_DESC_IDN_MAX; i++)
7938 hba->desc_size[i] = QUERY_DESC_MAX_SIZE;
7940 /* Init UFS geometry descriptor related parameters */
7941 ret = ufshcd_device_geo_params_init(hba);
7945 /* Check and apply UFS device quirks */
7946 ret = ufs_get_device_desc(hba);
7948 dev_err(hba->dev, "%s: Failed getting device info. err = %d\n",
7953 ufshcd_get_ref_clk_gating_wait(hba);
7955 if (!ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_READ_FLAG,
7956 QUERY_FLAG_IDN_PWR_ON_WPE, 0, &flag))
7957 hba->dev_info.f_power_on_wp_en = flag;
7959 /* Probe maximum power mode co-supported by both UFS host and device */
7960 if (ufshcd_get_max_pwr_mode(hba))
7962 "%s: Failed getting max supported power mode\n",
7969 * ufshcd_add_lus - probe and add UFS logical units
7970 * @hba: per-adapter instance
7972 static int ufshcd_add_lus(struct ufs_hba *hba)
7976 /* Add required well known logical units to scsi mid layer */
7977 ret = ufshcd_scsi_add_wlus(hba);
7981 /* Initialize devfreq after UFS device is detected */
7982 if (ufshcd_is_clkscaling_supported(hba)) {
7983 memcpy(&hba->clk_scaling.saved_pwr_info.info,
7985 sizeof(struct ufs_pa_layer_attr));
7986 hba->clk_scaling.saved_pwr_info.is_valid = true;
7987 hba->clk_scaling.is_allowed = true;
7989 ret = ufshcd_devfreq_init(hba);
7993 hba->clk_scaling.is_enabled = true;
7994 ufshcd_init_clk_scaling_sysfs(hba);
7999 scsi_scan_host(hba->host);
8000 pm_runtime_put_sync(hba->dev);
8007 * ufshcd_probe_hba - probe hba to detect device and initialize it
8008 * @hba: per-adapter instance
8009 * @init_dev_params: whether or not to call ufshcd_device_params_init().
8011 * Execute link-startup and verify device initialization
8013 static int ufshcd_probe_hba(struct ufs_hba *hba, bool init_dev_params)
8016 unsigned long flags;
8017 ktime_t start = ktime_get();
8019 hba->ufshcd_state = UFSHCD_STATE_RESET;
8021 ret = ufshcd_link_startup(hba);
8025 /* Debug counters initialization */
8026 ufshcd_clear_dbg_ufs_stats(hba);
8028 /* UniPro link is active now */
8029 ufshcd_set_link_active(hba);
8031 /* Verify device initialization by sending NOP OUT UPIU */
8032 ret = ufshcd_verify_dev_init(hba);
8036 /* Initiate UFS initialization, and waiting until completion */
8037 ret = ufshcd_complete_dev_init(hba);
8042 * Initialize UFS device parameters used by driver, these
8043 * parameters are associated with UFS descriptors.
8045 if (init_dev_params) {
8046 ret = ufshcd_device_params_init(hba);
8051 ufshcd_tune_unipro_params(hba);
8053 /* UFS device is also active now */
8054 ufshcd_set_ufs_dev_active(hba);
8055 ufshcd_force_reset_auto_bkops(hba);
8057 /* Gear up to HS gear if supported */
8058 if (hba->max_pwr_info.is_valid) {
8060 * Set the right value to bRefClkFreq before attempting to
8061 * switch to HS gears.
8063 if (hba->dev_ref_clk_freq != REF_CLK_FREQ_INVAL)
8064 ufshcd_set_dev_ref_clk(hba);
8065 ret = ufshcd_config_pwr_mode(hba, &hba->max_pwr_info.info);
8067 dev_err(hba->dev, "%s: Failed setting power mode, err = %d\n",
8071 ufshcd_print_pwr_info(hba);
8075 * bActiveICCLevel is volatile for UFS device (as per latest v2.1 spec)
8076 * and for removable UFS card as well, hence always set the parameter.
8077 * Note: Error handler may issue the device reset hence resetting
8078 * bActiveICCLevel as well so it is always safe to set this here.
8080 ufshcd_set_active_icc_lvl(hba);
8082 ufshcd_wb_config(hba);
8083 if (hba->ee_usr_mask)
8084 ufshcd_write_ee_control(hba);
8085 /* Enable Auto-Hibernate if configured */
8086 ufshcd_auto_hibern8_enable(hba);
8090 spin_lock_irqsave(hba->host->host_lock, flags);
8092 hba->ufshcd_state = UFSHCD_STATE_ERROR;
8093 else if (hba->ufshcd_state == UFSHCD_STATE_RESET)
8094 hba->ufshcd_state = UFSHCD_STATE_OPERATIONAL;
8095 spin_unlock_irqrestore(hba->host->host_lock, flags);
8097 trace_ufshcd_init(dev_name(hba->dev), ret,
8098 ktime_to_us(ktime_sub(ktime_get(), start)),
8099 hba->curr_dev_pwr_mode, hba->uic_link_state);
8104 * ufshcd_async_scan - asynchronous execution for probing hba
8105 * @data: data pointer to pass to this function
8106 * @cookie: cookie data
8108 static void ufshcd_async_scan(void *data, async_cookie_t cookie)
8110 struct ufs_hba *hba = (struct ufs_hba *)data;
8113 down(&hba->host_sem);
8114 /* Initialize hba, detect and initialize UFS device */
8115 ret = ufshcd_probe_hba(hba, true);
8120 /* Probe and add UFS logical units */
8121 ret = ufshcd_add_lus(hba);
8124 * If we failed to initialize the device or the device is not
8125 * present, turn off the power/clocks etc.
8128 pm_runtime_put_sync(hba->dev);
8129 ufshcd_hba_exit(hba);
8133 static const struct attribute_group *ufshcd_driver_groups[] = {
8134 &ufs_sysfs_unit_descriptor_group,
8135 &ufs_sysfs_lun_attributes_group,
8136 #ifdef CONFIG_SCSI_UFS_HPB
8137 &ufs_sysfs_hpb_stat_group,
8138 &ufs_sysfs_hpb_param_group,
8143 static struct ufs_hba_variant_params ufs_hba_vps = {
8144 .hba_enable_delay_us = 1000,
8145 .wb_flush_threshold = UFS_WB_BUF_REMAIN_PERCENT(40),
8146 .devfreq_profile.polling_ms = 100,
8147 .devfreq_profile.target = ufshcd_devfreq_target,
8148 .devfreq_profile.get_dev_status = ufshcd_devfreq_get_dev_status,
8149 .ondemand_data.upthreshold = 70,
8150 .ondemand_data.downdifferential = 5,
8153 static struct scsi_host_template ufshcd_driver_template = {
8154 .module = THIS_MODULE,
8156 .proc_name = UFSHCD,
8157 .queuecommand = ufshcd_queuecommand,
8158 .slave_alloc = ufshcd_slave_alloc,
8159 .slave_configure = ufshcd_slave_configure,
8160 .slave_destroy = ufshcd_slave_destroy,
8161 .change_queue_depth = ufshcd_change_queue_depth,
8162 .eh_abort_handler = ufshcd_abort,
8163 .eh_device_reset_handler = ufshcd_eh_device_reset_handler,
8164 .eh_host_reset_handler = ufshcd_eh_host_reset_handler,
8166 .sg_tablesize = SG_ALL,
8167 .cmd_per_lun = UFSHCD_CMD_PER_LUN,
8168 .can_queue = UFSHCD_CAN_QUEUE,
8169 .max_segment_size = PRDT_DATA_BYTE_COUNT_MAX,
8170 .max_host_blocked = 1,
8171 .track_queue_depth = 1,
8172 .sdev_groups = ufshcd_driver_groups,
8173 .dma_boundary = PAGE_SIZE - 1,
8174 .rpm_autosuspend_delay = RPM_AUTOSUSPEND_DELAY_MS,
8177 static int ufshcd_config_vreg_load(struct device *dev, struct ufs_vreg *vreg,
8186 * "set_load" operation shall be required on those regulators
8187 * which specifically configured current limitation. Otherwise
8188 * zero max_uA may cause unexpected behavior when regulator is
8189 * enabled or set as high power mode.
8194 ret = regulator_set_load(vreg->reg, ua);
8196 dev_err(dev, "%s: %s set load (ua=%d) failed, err=%d\n",
8197 __func__, vreg->name, ua, ret);
8203 static inline int ufshcd_config_vreg_lpm(struct ufs_hba *hba,
8204 struct ufs_vreg *vreg)
8206 return ufshcd_config_vreg_load(hba->dev, vreg, UFS_VREG_LPM_LOAD_UA);
8209 static inline int ufshcd_config_vreg_hpm(struct ufs_hba *hba,
8210 struct ufs_vreg *vreg)
8215 return ufshcd_config_vreg_load(hba->dev, vreg, vreg->max_uA);
8218 static int ufshcd_config_vreg(struct device *dev,
8219 struct ufs_vreg *vreg, bool on)
8222 struct regulator *reg;
8224 int min_uV, uA_load;
8231 if (regulator_count_voltages(reg) > 0) {
8232 uA_load = on ? vreg->max_uA : 0;
8233 ret = ufshcd_config_vreg_load(dev, vreg, uA_load);
8237 if (vreg->min_uV && vreg->max_uV) {
8238 min_uV = on ? vreg->min_uV : 0;
8239 ret = regulator_set_voltage(reg, min_uV, vreg->max_uV);
8242 "%s: %s set voltage failed, err=%d\n",
8243 __func__, name, ret);
8250 static int ufshcd_enable_vreg(struct device *dev, struct ufs_vreg *vreg)
8254 if (!vreg || vreg->enabled)
8257 ret = ufshcd_config_vreg(dev, vreg, true);
8259 ret = regulator_enable(vreg->reg);
8262 vreg->enabled = true;
8264 dev_err(dev, "%s: %s enable failed, err=%d\n",
8265 __func__, vreg->name, ret);
8270 static int ufshcd_disable_vreg(struct device *dev, struct ufs_vreg *vreg)
8274 if (!vreg || !vreg->enabled || vreg->always_on)
8277 ret = regulator_disable(vreg->reg);
8280 /* ignore errors on applying disable config */
8281 ufshcd_config_vreg(dev, vreg, false);
8282 vreg->enabled = false;
8284 dev_err(dev, "%s: %s disable failed, err=%d\n",
8285 __func__, vreg->name, ret);
8291 static int ufshcd_setup_vreg(struct ufs_hba *hba, bool on)
8294 struct device *dev = hba->dev;
8295 struct ufs_vreg_info *info = &hba->vreg_info;
8297 ret = ufshcd_toggle_vreg(dev, info->vcc, on);
8301 ret = ufshcd_toggle_vreg(dev, info->vccq, on);
8305 ret = ufshcd_toggle_vreg(dev, info->vccq2, on);
8309 ufshcd_toggle_vreg(dev, info->vccq2, false);
8310 ufshcd_toggle_vreg(dev, info->vccq, false);
8311 ufshcd_toggle_vreg(dev, info->vcc, false);
8316 static int ufshcd_setup_hba_vreg(struct ufs_hba *hba, bool on)
8318 struct ufs_vreg_info *info = &hba->vreg_info;
8320 return ufshcd_toggle_vreg(hba->dev, info->vdd_hba, on);
8323 static int ufshcd_get_vreg(struct device *dev, struct ufs_vreg *vreg)
8330 vreg->reg = devm_regulator_get(dev, vreg->name);
8331 if (IS_ERR(vreg->reg)) {
8332 ret = PTR_ERR(vreg->reg);
8333 dev_err(dev, "%s: %s get failed, err=%d\n",
8334 __func__, vreg->name, ret);
8340 static int ufshcd_init_vreg(struct ufs_hba *hba)
8343 struct device *dev = hba->dev;
8344 struct ufs_vreg_info *info = &hba->vreg_info;
8346 ret = ufshcd_get_vreg(dev, info->vcc);
8350 ret = ufshcd_get_vreg(dev, info->vccq);
8352 ret = ufshcd_get_vreg(dev, info->vccq2);
8357 static int ufshcd_init_hba_vreg(struct ufs_hba *hba)
8359 struct ufs_vreg_info *info = &hba->vreg_info;
8362 return ufshcd_get_vreg(hba->dev, info->vdd_hba);
8367 static int ufshcd_setup_clocks(struct ufs_hba *hba, bool on)
8370 struct ufs_clk_info *clki;
8371 struct list_head *head = &hba->clk_list_head;
8372 unsigned long flags;
8373 ktime_t start = ktime_get();
8374 bool clk_state_changed = false;
8376 if (list_empty(head))
8379 ret = ufshcd_vops_setup_clocks(hba, on, PRE_CHANGE);
8383 list_for_each_entry(clki, head, list) {
8384 if (!IS_ERR_OR_NULL(clki->clk)) {
8386 * Don't disable clocks which are needed
8387 * to keep the link active.
8389 if (ufshcd_is_link_active(hba) &&
8390 clki->keep_link_active)
8393 clk_state_changed = on ^ clki->enabled;
8394 if (on && !clki->enabled) {
8395 ret = clk_prepare_enable(clki->clk);
8397 dev_err(hba->dev, "%s: %s prepare enable failed, %d\n",
8398 __func__, clki->name, ret);
8401 } else if (!on && clki->enabled) {
8402 clk_disable_unprepare(clki->clk);
8405 dev_dbg(hba->dev, "%s: clk: %s %sabled\n", __func__,
8406 clki->name, on ? "en" : "dis");
8410 ret = ufshcd_vops_setup_clocks(hba, on, POST_CHANGE);
8416 list_for_each_entry(clki, head, list) {
8417 if (!IS_ERR_OR_NULL(clki->clk) && clki->enabled)
8418 clk_disable_unprepare(clki->clk);
8420 } else if (!ret && on) {
8421 spin_lock_irqsave(hba->host->host_lock, flags);
8422 hba->clk_gating.state = CLKS_ON;
8423 trace_ufshcd_clk_gating(dev_name(hba->dev),
8424 hba->clk_gating.state);
8425 spin_unlock_irqrestore(hba->host->host_lock, flags);
8428 if (clk_state_changed)
8429 trace_ufshcd_profile_clk_gating(dev_name(hba->dev),
8430 (on ? "on" : "off"),
8431 ktime_to_us(ktime_sub(ktime_get(), start)), ret);
8435 static int ufshcd_init_clocks(struct ufs_hba *hba)
8438 struct ufs_clk_info *clki;
8439 struct device *dev = hba->dev;
8440 struct list_head *head = &hba->clk_list_head;
8442 if (list_empty(head))
8445 list_for_each_entry(clki, head, list) {
8449 clki->clk = devm_clk_get(dev, clki->name);
8450 if (IS_ERR(clki->clk)) {
8451 ret = PTR_ERR(clki->clk);
8452 dev_err(dev, "%s: %s clk get failed, %d\n",
8453 __func__, clki->name, ret);
8458 * Parse device ref clk freq as per device tree "ref_clk".
8459 * Default dev_ref_clk_freq is set to REF_CLK_FREQ_INVAL
8460 * in ufshcd_alloc_host().
8462 if (!strcmp(clki->name, "ref_clk"))
8463 ufshcd_parse_dev_ref_clk_freq(hba, clki->clk);
8465 if (clki->max_freq) {
8466 ret = clk_set_rate(clki->clk, clki->max_freq);
8468 dev_err(hba->dev, "%s: %s clk set rate(%dHz) failed, %d\n",
8469 __func__, clki->name,
8470 clki->max_freq, ret);
8473 clki->curr_freq = clki->max_freq;
8475 dev_dbg(dev, "%s: clk: %s, rate: %lu\n", __func__,
8476 clki->name, clk_get_rate(clki->clk));
8482 static int ufshcd_variant_hba_init(struct ufs_hba *hba)
8489 err = ufshcd_vops_init(hba);
8491 dev_err(hba->dev, "%s: variant %s init failed err %d\n",
8492 __func__, ufshcd_get_var_name(hba), err);
8497 static void ufshcd_variant_hba_exit(struct ufs_hba *hba)
8502 ufshcd_vops_exit(hba);
8505 static int ufshcd_hba_init(struct ufs_hba *hba)
8510 * Handle host controller power separately from the UFS device power
8511 * rails as it will help controlling the UFS host controller power
8512 * collapse easily which is different than UFS device power collapse.
8513 * Also, enable the host controller power before we go ahead with rest
8514 * of the initialization here.
8516 err = ufshcd_init_hba_vreg(hba);
8520 err = ufshcd_setup_hba_vreg(hba, true);
8524 err = ufshcd_init_clocks(hba);
8526 goto out_disable_hba_vreg;
8528 err = ufshcd_setup_clocks(hba, true);
8530 goto out_disable_hba_vreg;
8532 err = ufshcd_init_vreg(hba);
8534 goto out_disable_clks;
8536 err = ufshcd_setup_vreg(hba, true);
8538 goto out_disable_clks;
8540 err = ufshcd_variant_hba_init(hba);
8542 goto out_disable_vreg;
8544 ufs_debugfs_hba_init(hba);
8546 hba->is_powered = true;
8550 ufshcd_setup_vreg(hba, false);
8552 ufshcd_setup_clocks(hba, false);
8553 out_disable_hba_vreg:
8554 ufshcd_setup_hba_vreg(hba, false);
8559 static void ufshcd_hba_exit(struct ufs_hba *hba)
8561 if (hba->is_powered) {
8562 ufshcd_exit_clk_scaling(hba);
8563 ufshcd_exit_clk_gating(hba);
8564 ufs_debugfs_hba_exit(hba);
8565 ufshcd_variant_hba_exit(hba);
8566 ufshcd_setup_vreg(hba, false);
8567 ufshcd_setup_clocks(hba, false);
8568 ufshcd_setup_hba_vreg(hba, false);
8569 hba->is_powered = false;
8570 ufs_put_device_desc(hba);
8575 * ufshcd_set_dev_pwr_mode - sends START STOP UNIT command to set device
8577 * @hba: per adapter instance
8578 * @pwr_mode: device power mode to set
8580 * Returns 0 if requested power mode is set successfully
8581 * Returns non-zero if failed to set the requested power mode
8583 static int ufshcd_set_dev_pwr_mode(struct ufs_hba *hba,
8584 enum ufs_dev_pwr_mode pwr_mode)
8586 unsigned char cmd[6] = { START_STOP };
8587 struct scsi_sense_hdr sshdr;
8588 struct scsi_device *sdp;
8589 unsigned long flags;
8592 spin_lock_irqsave(hba->host->host_lock, flags);
8593 sdp = hba->sdev_ufs_device;
8595 ret = scsi_device_get(sdp);
8596 if (!ret && !scsi_device_online(sdp)) {
8598 scsi_device_put(sdp);
8603 spin_unlock_irqrestore(hba->host->host_lock, flags);
8609 * If scsi commands fail, the scsi mid-layer schedules scsi error-
8610 * handling, which would wait for host to be resumed. Since we know
8611 * we are functional while we are here, skip host resume in error
8614 hba->host->eh_noresume = 1;
8616 cmd[4] = pwr_mode << 4;
8619 * Current function would be generally called from the power management
8620 * callbacks hence set the RQF_PM flag so that it doesn't resume the
8621 * already suspended childs.
8623 for (retries = 3; retries > 0; --retries) {
8624 ret = scsi_execute(sdp, cmd, DMA_NONE, NULL, 0, NULL, &sshdr,
8625 START_STOP_TIMEOUT, 0, 0, RQF_PM, NULL);
8626 if (!scsi_status_is_check_condition(ret) ||
8627 !scsi_sense_valid(&sshdr) ||
8628 sshdr.sense_key != UNIT_ATTENTION)
8632 sdev_printk(KERN_WARNING, sdp,
8633 "START_STOP failed for power mode: %d, result %x\n",
8635 if (ret > 0 && scsi_sense_valid(&sshdr))
8636 scsi_print_sense_hdr(sdp, NULL, &sshdr);
8640 hba->curr_dev_pwr_mode = pwr_mode;
8642 scsi_device_put(sdp);
8643 hba->host->eh_noresume = 0;
8647 static int ufshcd_link_state_transition(struct ufs_hba *hba,
8648 enum uic_link_state req_link_state,
8649 int check_for_bkops)
8653 if (req_link_state == hba->uic_link_state)
8656 if (req_link_state == UIC_LINK_HIBERN8_STATE) {
8657 ret = ufshcd_uic_hibern8_enter(hba);
8659 ufshcd_set_link_hibern8(hba);
8661 dev_err(hba->dev, "%s: hibern8 enter failed %d\n",
8667 * If autobkops is enabled, link can't be turned off because
8668 * turning off the link would also turn off the device, except in the
8669 * case of DeepSleep where the device is expected to remain powered.
8671 else if ((req_link_state == UIC_LINK_OFF_STATE) &&
8672 (!check_for_bkops || !hba->auto_bkops_enabled)) {
8674 * Let's make sure that link is in low power mode, we are doing
8675 * this currently by putting the link in Hibern8. Otherway to
8676 * put the link in low power mode is to send the DME end point
8677 * to device and then send the DME reset command to local
8678 * unipro. But putting the link in hibern8 is much faster.
8680 * Note also that putting the link in Hibern8 is a requirement
8681 * for entering DeepSleep.
8683 ret = ufshcd_uic_hibern8_enter(hba);
8685 dev_err(hba->dev, "%s: hibern8 enter failed %d\n",
8690 * Change controller state to "reset state" which
8691 * should also put the link in off/reset state
8693 ufshcd_hba_stop(hba);
8695 * TODO: Check if we need any delay to make sure that
8696 * controller is reset
8698 ufshcd_set_link_off(hba);
8705 static void ufshcd_vreg_set_lpm(struct ufs_hba *hba)
8707 bool vcc_off = false;
8710 * It seems some UFS devices may keep drawing more than sleep current
8711 * (atleast for 500us) from UFS rails (especially from VCCQ rail).
8712 * To avoid this situation, add 2ms delay before putting these UFS
8713 * rails in LPM mode.
8715 if (!ufshcd_is_link_active(hba) &&
8716 hba->dev_quirks & UFS_DEVICE_QUIRK_DELAY_BEFORE_LPM)
8717 usleep_range(2000, 2100);
8720 * If UFS device is either in UFS_Sleep turn off VCC rail to save some
8723 * If UFS device and link is in OFF state, all power supplies (VCC,
8724 * VCCQ, VCCQ2) can be turned off if power on write protect is not
8725 * required. If UFS link is inactive (Hibern8 or OFF state) and device
8726 * is in sleep state, put VCCQ & VCCQ2 rails in LPM mode.
8728 * Ignore the error returned by ufshcd_toggle_vreg() as device is anyway
8729 * in low power state which would save some power.
8731 * If Write Booster is enabled and the device needs to flush the WB
8732 * buffer OR if bkops status is urgent for WB, keep Vcc on.
8734 if (ufshcd_is_ufs_dev_poweroff(hba) && ufshcd_is_link_off(hba) &&
8735 !hba->dev_info.is_lu_power_on_wp) {
8736 ufshcd_setup_vreg(hba, false);
8738 } else if (!ufshcd_is_ufs_dev_active(hba)) {
8739 ufshcd_toggle_vreg(hba->dev, hba->vreg_info.vcc, false);
8741 if (ufshcd_is_link_hibern8(hba) || ufshcd_is_link_off(hba)) {
8742 ufshcd_config_vreg_lpm(hba, hba->vreg_info.vccq);
8743 ufshcd_config_vreg_lpm(hba, hba->vreg_info.vccq2);
8748 * Some UFS devices require delay after VCC power rail is turned-off.
8750 if (vcc_off && hba->vreg_info.vcc &&
8751 hba->dev_quirks & UFS_DEVICE_QUIRK_DELAY_AFTER_LPM)
8752 usleep_range(5000, 5100);
8756 static int ufshcd_vreg_set_hpm(struct ufs_hba *hba)
8760 if (ufshcd_is_ufs_dev_poweroff(hba) && ufshcd_is_link_off(hba) &&
8761 !hba->dev_info.is_lu_power_on_wp) {
8762 ret = ufshcd_setup_vreg(hba, true);
8763 } else if (!ufshcd_is_ufs_dev_active(hba)) {
8764 if (!ufshcd_is_link_active(hba)) {
8765 ret = ufshcd_config_vreg_hpm(hba, hba->vreg_info.vccq);
8768 ret = ufshcd_config_vreg_hpm(hba, hba->vreg_info.vccq2);
8772 ret = ufshcd_toggle_vreg(hba->dev, hba->vreg_info.vcc, true);
8777 ufshcd_config_vreg_lpm(hba, hba->vreg_info.vccq);
8779 ufshcd_toggle_vreg(hba->dev, hba->vreg_info.vcc, false);
8783 #endif /* CONFIG_PM */
8785 static void ufshcd_hba_vreg_set_lpm(struct ufs_hba *hba)
8787 if (ufshcd_is_link_off(hba) || ufshcd_can_aggressive_pc(hba))
8788 ufshcd_setup_hba_vreg(hba, false);
8791 static void ufshcd_hba_vreg_set_hpm(struct ufs_hba *hba)
8793 if (ufshcd_is_link_off(hba) || ufshcd_can_aggressive_pc(hba))
8794 ufshcd_setup_hba_vreg(hba, true);
8797 static int __ufshcd_wl_suspend(struct ufs_hba *hba, enum ufs_pm_op pm_op)
8800 int check_for_bkops;
8801 enum ufs_pm_level pm_lvl;
8802 enum ufs_dev_pwr_mode req_dev_pwr_mode;
8803 enum uic_link_state req_link_state;
8805 hba->pm_op_in_progress = true;
8806 if (pm_op != UFS_SHUTDOWN_PM) {
8807 pm_lvl = pm_op == UFS_RUNTIME_PM ?
8808 hba->rpm_lvl : hba->spm_lvl;
8809 req_dev_pwr_mode = ufs_get_pm_lvl_to_dev_pwr_mode(pm_lvl);
8810 req_link_state = ufs_get_pm_lvl_to_link_pwr_state(pm_lvl);
8812 req_dev_pwr_mode = UFS_POWERDOWN_PWR_MODE;
8813 req_link_state = UIC_LINK_OFF_STATE;
8816 ufshpb_suspend(hba);
8819 * If we can't transition into any of the low power modes
8820 * just gate the clocks.
8822 ufshcd_hold(hba, false);
8823 hba->clk_gating.is_suspended = true;
8825 if (ufshcd_is_clkscaling_supported(hba))
8826 ufshcd_clk_scaling_suspend(hba, true);
8828 if (req_dev_pwr_mode == UFS_ACTIVE_PWR_MODE &&
8829 req_link_state == UIC_LINK_ACTIVE_STATE) {
8833 if ((req_dev_pwr_mode == hba->curr_dev_pwr_mode) &&
8834 (req_link_state == hba->uic_link_state))
8835 goto enable_scaling;
8837 /* UFS device & link must be active before we enter in this function */
8838 if (!ufshcd_is_ufs_dev_active(hba) || !ufshcd_is_link_active(hba)) {
8840 goto enable_scaling;
8843 if (pm_op == UFS_RUNTIME_PM) {
8844 if (ufshcd_can_autobkops_during_suspend(hba)) {
8846 * The device is idle with no requests in the queue,
8847 * allow background operations if bkops status shows
8848 * that performance might be impacted.
8850 ret = ufshcd_urgent_bkops(hba);
8852 goto enable_scaling;
8854 /* make sure that auto bkops is disabled */
8855 ufshcd_disable_auto_bkops(hba);
8858 * If device needs to do BKOP or WB buffer flush during
8859 * Hibern8, keep device power mode as "active power mode"
8862 hba->dev_info.b_rpm_dev_flush_capable =
8863 hba->auto_bkops_enabled ||
8864 (((req_link_state == UIC_LINK_HIBERN8_STATE) ||
8865 ((req_link_state == UIC_LINK_ACTIVE_STATE) &&
8866 ufshcd_is_auto_hibern8_enabled(hba))) &&
8867 ufshcd_wb_need_flush(hba));
8870 flush_work(&hba->eeh_work);
8872 if (req_dev_pwr_mode != hba->curr_dev_pwr_mode) {
8873 if (pm_op != UFS_RUNTIME_PM)
8874 /* ensure that bkops is disabled */
8875 ufshcd_disable_auto_bkops(hba);
8877 if (!hba->dev_info.b_rpm_dev_flush_capable) {
8878 ret = ufshcd_set_dev_pwr_mode(hba, req_dev_pwr_mode);
8880 goto enable_scaling;
8885 * In the case of DeepSleep, the device is expected to remain powered
8886 * with the link off, so do not check for bkops.
8888 check_for_bkops = !ufshcd_is_ufs_dev_deepsleep(hba);
8889 ret = ufshcd_link_state_transition(hba, req_link_state, check_for_bkops);
8891 goto set_dev_active;
8895 * Call vendor specific suspend callback. As these callbacks may access
8896 * vendor specific host controller register space call them before the
8897 * host clocks are ON.
8899 ret = ufshcd_vops_suspend(hba, pm_op);
8901 goto set_link_active;
8906 * Device hardware reset is required to exit DeepSleep. Also, for
8907 * DeepSleep, the link is off so host reset and restore will be done
8910 if (ufshcd_is_ufs_dev_deepsleep(hba)) {
8911 ufshcd_device_reset(hba);
8912 WARN_ON(!ufshcd_is_link_off(hba));
8914 if (ufshcd_is_link_hibern8(hba) && !ufshcd_uic_hibern8_exit(hba))
8915 ufshcd_set_link_active(hba);
8916 else if (ufshcd_is_link_off(hba))
8917 ufshcd_host_reset_and_restore(hba);
8919 /* Can also get here needing to exit DeepSleep */
8920 if (ufshcd_is_ufs_dev_deepsleep(hba)) {
8921 ufshcd_device_reset(hba);
8922 ufshcd_host_reset_and_restore(hba);
8924 if (!ufshcd_set_dev_pwr_mode(hba, UFS_ACTIVE_PWR_MODE))
8925 ufshcd_disable_auto_bkops(hba);
8927 if (ufshcd_is_clkscaling_supported(hba))
8928 ufshcd_clk_scaling_suspend(hba, false);
8930 hba->dev_info.b_rpm_dev_flush_capable = false;
8932 if (hba->dev_info.b_rpm_dev_flush_capable) {
8933 schedule_delayed_work(&hba->rpm_dev_flush_recheck_work,
8934 msecs_to_jiffies(RPM_DEV_FLUSH_RECHECK_WORK_DELAY_MS));
8938 ufshcd_update_evt_hist(hba, UFS_EVT_WL_SUSP_ERR, (u32)ret);
8939 hba->clk_gating.is_suspended = false;
8940 ufshcd_release(hba);
8943 hba->pm_op_in_progress = false;
8948 static int __ufshcd_wl_resume(struct ufs_hba *hba, enum ufs_pm_op pm_op)
8951 enum uic_link_state old_link_state = hba->uic_link_state;
8953 hba->pm_op_in_progress = true;
8956 * Call vendor specific resume callback. As these callbacks may access
8957 * vendor specific host controller register space call them when the
8958 * host clocks are ON.
8960 ret = ufshcd_vops_resume(hba, pm_op);
8964 /* For DeepSleep, the only supported option is to have the link off */
8965 WARN_ON(ufshcd_is_ufs_dev_deepsleep(hba) && !ufshcd_is_link_off(hba));
8967 if (ufshcd_is_link_hibern8(hba)) {
8968 ret = ufshcd_uic_hibern8_exit(hba);
8970 ufshcd_set_link_active(hba);
8972 dev_err(hba->dev, "%s: hibern8 exit failed %d\n",
8974 goto vendor_suspend;
8976 } else if (ufshcd_is_link_off(hba)) {
8978 * A full initialization of the host and the device is
8979 * required since the link was put to off during suspend.
8980 * Note, in the case of DeepSleep, the device will exit
8981 * DeepSleep due to device reset.
8983 ret = ufshcd_reset_and_restore(hba);
8985 * ufshcd_reset_and_restore() should have already
8986 * set the link state as active
8988 if (ret || !ufshcd_is_link_active(hba))
8989 goto vendor_suspend;
8992 if (!ufshcd_is_ufs_dev_active(hba)) {
8993 ret = ufshcd_set_dev_pwr_mode(hba, UFS_ACTIVE_PWR_MODE);
8995 goto set_old_link_state;
8998 if (ufshcd_keep_autobkops_enabled_except_suspend(hba))
8999 ufshcd_enable_auto_bkops(hba);
9002 * If BKOPs operations are urgently needed at this moment then
9003 * keep auto-bkops enabled or else disable it.
9005 ufshcd_urgent_bkops(hba);
9007 if (hba->ee_usr_mask)
9008 ufshcd_write_ee_control(hba);
9010 if (ufshcd_is_clkscaling_supported(hba))
9011 ufshcd_clk_scaling_suspend(hba, false);
9013 if (hba->dev_info.b_rpm_dev_flush_capable) {
9014 hba->dev_info.b_rpm_dev_flush_capable = false;
9015 cancel_delayed_work(&hba->rpm_dev_flush_recheck_work);
9018 /* Enable Auto-Hibernate if configured */
9019 ufshcd_auto_hibern8_enable(hba);
9025 ufshcd_link_state_transition(hba, old_link_state, 0);
9027 ufshcd_vops_suspend(hba, pm_op);
9030 ufshcd_update_evt_hist(hba, UFS_EVT_WL_RES_ERR, (u32)ret);
9031 hba->clk_gating.is_suspended = false;
9032 ufshcd_release(hba);
9033 hba->pm_op_in_progress = false;
9037 static int ufshcd_wl_runtime_suspend(struct device *dev)
9039 struct scsi_device *sdev = to_scsi_device(dev);
9040 struct ufs_hba *hba;
9042 ktime_t start = ktime_get();
9044 hba = shost_priv(sdev->host);
9046 ret = __ufshcd_wl_suspend(hba, UFS_RUNTIME_PM);
9048 dev_err(&sdev->sdev_gendev, "%s failed: %d\n", __func__, ret);
9050 trace_ufshcd_wl_runtime_suspend(dev_name(dev), ret,
9051 ktime_to_us(ktime_sub(ktime_get(), start)),
9052 hba->curr_dev_pwr_mode, hba->uic_link_state);
9057 static int ufshcd_wl_runtime_resume(struct device *dev)
9059 struct scsi_device *sdev = to_scsi_device(dev);
9060 struct ufs_hba *hba;
9062 ktime_t start = ktime_get();
9064 hba = shost_priv(sdev->host);
9066 ret = __ufshcd_wl_resume(hba, UFS_RUNTIME_PM);
9068 dev_err(&sdev->sdev_gendev, "%s failed: %d\n", __func__, ret);
9070 trace_ufshcd_wl_runtime_resume(dev_name(dev), ret,
9071 ktime_to_us(ktime_sub(ktime_get(), start)),
9072 hba->curr_dev_pwr_mode, hba->uic_link_state);
9078 #ifdef CONFIG_PM_SLEEP
9079 static int ufshcd_wl_suspend(struct device *dev)
9081 struct scsi_device *sdev = to_scsi_device(dev);
9082 struct ufs_hba *hba;
9084 ktime_t start = ktime_get();
9086 hba = shost_priv(sdev->host);
9087 down(&hba->host_sem);
9089 if (pm_runtime_suspended(dev))
9092 ret = __ufshcd_wl_suspend(hba, UFS_SYSTEM_PM);
9094 dev_err(&sdev->sdev_gendev, "%s failed: %d\n", __func__, ret);
9100 hba->is_sys_suspended = true;
9101 trace_ufshcd_wl_suspend(dev_name(dev), ret,
9102 ktime_to_us(ktime_sub(ktime_get(), start)),
9103 hba->curr_dev_pwr_mode, hba->uic_link_state);
9108 static int ufshcd_wl_resume(struct device *dev)
9110 struct scsi_device *sdev = to_scsi_device(dev);
9111 struct ufs_hba *hba;
9113 ktime_t start = ktime_get();
9115 hba = shost_priv(sdev->host);
9117 if (pm_runtime_suspended(dev))
9120 ret = __ufshcd_wl_resume(hba, UFS_SYSTEM_PM);
9122 dev_err(&sdev->sdev_gendev, "%s failed: %d\n", __func__, ret);
9124 trace_ufshcd_wl_resume(dev_name(dev), ret,
9125 ktime_to_us(ktime_sub(ktime_get(), start)),
9126 hba->curr_dev_pwr_mode, hba->uic_link_state);
9128 hba->is_sys_suspended = false;
9134 static void ufshcd_wl_shutdown(struct device *dev)
9136 struct scsi_device *sdev = to_scsi_device(dev);
9137 struct ufs_hba *hba;
9139 hba = shost_priv(sdev->host);
9141 down(&hba->host_sem);
9142 hba->shutting_down = true;
9145 /* Turn on everything while shutting down */
9146 ufshcd_rpm_get_sync(hba);
9147 scsi_device_quiesce(sdev);
9148 shost_for_each_device(sdev, hba->host) {
9149 if (sdev == hba->sdev_ufs_device)
9151 scsi_device_quiesce(sdev);
9153 __ufshcd_wl_suspend(hba, UFS_SHUTDOWN_PM);
9157 * ufshcd_suspend - helper function for suspend operations
9158 * @hba: per adapter instance
9160 * This function will put disable irqs, turn off clocks
9161 * and set vreg and hba-vreg in lpm mode.
9163 static int ufshcd_suspend(struct ufs_hba *hba)
9167 if (!hba->is_powered)
9170 * Disable the host irq as host controller as there won't be any
9171 * host controller transaction expected till resume.
9173 ufshcd_disable_irq(hba);
9174 ret = ufshcd_setup_clocks(hba, false);
9176 ufshcd_enable_irq(hba);
9179 if (ufshcd_is_clkgating_allowed(hba)) {
9180 hba->clk_gating.state = CLKS_OFF;
9181 trace_ufshcd_clk_gating(dev_name(hba->dev),
9182 hba->clk_gating.state);
9185 ufshcd_vreg_set_lpm(hba);
9186 /* Put the host controller in low power mode if possible */
9187 ufshcd_hba_vreg_set_lpm(hba);
9193 * ufshcd_resume - helper function for resume operations
9194 * @hba: per adapter instance
9196 * This function basically turns on the regulators, clocks and
9199 * Returns 0 for success and non-zero for failure
9201 static int ufshcd_resume(struct ufs_hba *hba)
9205 if (!hba->is_powered)
9208 ufshcd_hba_vreg_set_hpm(hba);
9209 ret = ufshcd_vreg_set_hpm(hba);
9213 /* Make sure clocks are enabled before accessing controller */
9214 ret = ufshcd_setup_clocks(hba, true);
9218 /* enable the host irq as host controller would be active soon */
9219 ufshcd_enable_irq(hba);
9223 ufshcd_vreg_set_lpm(hba);
9226 ufshcd_update_evt_hist(hba, UFS_EVT_RESUME_ERR, (u32)ret);
9229 #endif /* CONFIG_PM */
9231 #ifdef CONFIG_PM_SLEEP
9233 * ufshcd_system_suspend - system suspend callback
9234 * @dev: Device associated with the UFS controller.
9236 * Executed before putting the system into a sleep state in which the contents
9237 * of main memory are preserved.
9239 * Returns 0 for success and non-zero for failure
9241 int ufshcd_system_suspend(struct device *dev)
9243 struct ufs_hba *hba = dev_get_drvdata(dev);
9245 ktime_t start = ktime_get();
9247 if (pm_runtime_suspended(hba->dev))
9250 ret = ufshcd_suspend(hba);
9252 trace_ufshcd_system_suspend(dev_name(hba->dev), ret,
9253 ktime_to_us(ktime_sub(ktime_get(), start)),
9254 hba->curr_dev_pwr_mode, hba->uic_link_state);
9257 EXPORT_SYMBOL(ufshcd_system_suspend);
9260 * ufshcd_system_resume - system resume callback
9261 * @dev: Device associated with the UFS controller.
9263 * Executed after waking the system up from a sleep state in which the contents
9264 * of main memory were preserved.
9266 * Returns 0 for success and non-zero for failure
9268 int ufshcd_system_resume(struct device *dev)
9270 struct ufs_hba *hba = dev_get_drvdata(dev);
9271 ktime_t start = ktime_get();
9274 if (pm_runtime_suspended(hba->dev))
9277 ret = ufshcd_resume(hba);
9280 trace_ufshcd_system_resume(dev_name(hba->dev), ret,
9281 ktime_to_us(ktime_sub(ktime_get(), start)),
9282 hba->curr_dev_pwr_mode, hba->uic_link_state);
9286 EXPORT_SYMBOL(ufshcd_system_resume);
9287 #endif /* CONFIG_PM_SLEEP */
9291 * ufshcd_runtime_suspend - runtime suspend callback
9292 * @dev: Device associated with the UFS controller.
9294 * Check the description of ufshcd_suspend() function for more details.
9296 * Returns 0 for success and non-zero for failure
9298 int ufshcd_runtime_suspend(struct device *dev)
9300 struct ufs_hba *hba = dev_get_drvdata(dev);
9302 ktime_t start = ktime_get();
9304 ret = ufshcd_suspend(hba);
9306 trace_ufshcd_runtime_suspend(dev_name(hba->dev), ret,
9307 ktime_to_us(ktime_sub(ktime_get(), start)),
9308 hba->curr_dev_pwr_mode, hba->uic_link_state);
9311 EXPORT_SYMBOL(ufshcd_runtime_suspend);
9314 * ufshcd_runtime_resume - runtime resume routine
9315 * @dev: Device associated with the UFS controller.
9317 * This function basically brings controller
9318 * to active state. Following operations are done in this function:
9320 * 1. Turn on all the controller related clocks
9321 * 2. Turn ON VCC rail
9323 int ufshcd_runtime_resume(struct device *dev)
9325 struct ufs_hba *hba = dev_get_drvdata(dev);
9327 ktime_t start = ktime_get();
9329 ret = ufshcd_resume(hba);
9331 trace_ufshcd_runtime_resume(dev_name(hba->dev), ret,
9332 ktime_to_us(ktime_sub(ktime_get(), start)),
9333 hba->curr_dev_pwr_mode, hba->uic_link_state);
9336 EXPORT_SYMBOL(ufshcd_runtime_resume);
9337 #endif /* CONFIG_PM */
9340 * ufshcd_shutdown - shutdown routine
9341 * @hba: per adapter instance
9343 * This function would turn off both UFS device and UFS hba
9344 * regulators. It would also disable clocks.
9346 * Returns 0 always to allow force shutdown even in case of errors.
9348 int ufshcd_shutdown(struct ufs_hba *hba)
9350 if (ufshcd_is_ufs_dev_poweroff(hba) && ufshcd_is_link_off(hba))
9353 pm_runtime_get_sync(hba->dev);
9355 ufshcd_suspend(hba);
9357 hba->is_powered = false;
9358 /* allow force shutdown even in case of errors */
9361 EXPORT_SYMBOL(ufshcd_shutdown);
9364 * ufshcd_remove - de-allocate SCSI host and host memory space
9365 * data structure memory
9366 * @hba: per adapter instance
9368 void ufshcd_remove(struct ufs_hba *hba)
9370 if (hba->sdev_ufs_device)
9371 ufshcd_rpm_get_sync(hba);
9372 ufs_hwmon_remove(hba);
9373 ufs_bsg_remove(hba);
9375 ufs_sysfs_remove_nodes(hba->dev);
9376 blk_cleanup_queue(hba->tmf_queue);
9377 blk_mq_free_tag_set(&hba->tmf_tag_set);
9378 blk_cleanup_queue(hba->cmd_queue);
9379 scsi_remove_host(hba->host);
9380 /* disable interrupts */
9381 ufshcd_disable_intr(hba, hba->intr_mask);
9382 ufshcd_hba_stop(hba);
9383 ufshcd_hba_exit(hba);
9385 EXPORT_SYMBOL_GPL(ufshcd_remove);
9388 * ufshcd_dealloc_host - deallocate Host Bus Adapter (HBA)
9389 * @hba: pointer to Host Bus Adapter (HBA)
9391 void ufshcd_dealloc_host(struct ufs_hba *hba)
9393 scsi_host_put(hba->host);
9395 EXPORT_SYMBOL_GPL(ufshcd_dealloc_host);
9398 * ufshcd_set_dma_mask - Set dma mask based on the controller
9399 * addressing capability
9400 * @hba: per adapter instance
9402 * Returns 0 for success, non-zero for failure
9404 static int ufshcd_set_dma_mask(struct ufs_hba *hba)
9406 if (hba->capabilities & MASK_64_ADDRESSING_SUPPORT) {
9407 if (!dma_set_mask_and_coherent(hba->dev, DMA_BIT_MASK(64)))
9410 return dma_set_mask_and_coherent(hba->dev, DMA_BIT_MASK(32));
9413 static struct scsi_transport_template ufshcd_transport_template = {
9414 .eh_strategy_handler = ufshcd_err_handler,
9418 * ufshcd_alloc_host - allocate Host Bus Adapter (HBA)
9419 * @dev: pointer to device handle
9420 * @hba_handle: driver private handle
9421 * Returns 0 on success, non-zero value on failure
9423 int ufshcd_alloc_host(struct device *dev, struct ufs_hba **hba_handle)
9425 struct Scsi_Host *host;
9426 struct ufs_hba *hba;
9431 "Invalid memory reference for dev is NULL\n");
9436 host = scsi_host_alloc(&ufshcd_driver_template,
9437 sizeof(struct ufs_hba));
9439 dev_err(dev, "scsi_host_alloc failed\n");
9443 host->transportt = &ufshcd_transport_template;
9444 hba = shost_priv(host);
9447 hba->dev_ref_clk_freq = REF_CLK_FREQ_INVAL;
9448 INIT_LIST_HEAD(&hba->clk_list_head);
9449 spin_lock_init(&hba->outstanding_lock);
9456 EXPORT_SYMBOL(ufshcd_alloc_host);
9458 /* This function exists because blk_mq_alloc_tag_set() requires this. */
9459 static blk_status_t ufshcd_queue_tmf(struct blk_mq_hw_ctx *hctx,
9460 const struct blk_mq_queue_data *qd)
9463 return BLK_STS_NOTSUPP;
9466 static const struct blk_mq_ops ufshcd_tmf_ops = {
9467 .queue_rq = ufshcd_queue_tmf,
9471 * ufshcd_init - Driver initialization routine
9472 * @hba: per-adapter instance
9473 * @mmio_base: base register address
9474 * @irq: Interrupt line of device
9475 * Returns 0 on success, non-zero value on failure
9477 int ufshcd_init(struct ufs_hba *hba, void __iomem *mmio_base, unsigned int irq)
9480 struct Scsi_Host *host = hba->host;
9481 struct device *dev = hba->dev;
9485 "Invalid memory reference for mmio_base is NULL\n");
9490 hba->mmio_base = mmio_base;
9492 hba->vps = &ufs_hba_vps;
9494 err = ufshcd_hba_init(hba);
9498 /* Read capabilities registers */
9499 err = ufshcd_hba_capabilities(hba);
9503 /* Get UFS version supported by the controller */
9504 hba->ufs_version = ufshcd_get_ufs_version(hba);
9506 /* Get Interrupt bit mask per version */
9507 hba->intr_mask = ufshcd_get_intr_mask(hba);
9509 err = ufshcd_set_dma_mask(hba);
9511 dev_err(hba->dev, "set dma mask failed\n");
9515 /* Allocate memory for host memory space */
9516 err = ufshcd_memory_alloc(hba);
9518 dev_err(hba->dev, "Memory allocation failed\n");
9523 ufshcd_host_memory_configure(hba);
9525 host->can_queue = hba->nutrs;
9526 host->cmd_per_lun = hba->nutrs;
9527 host->max_id = UFSHCD_MAX_ID;
9528 host->max_lun = UFS_MAX_LUNS;
9529 host->max_channel = UFSHCD_MAX_CHANNEL;
9530 host->unique_id = host->host_no;
9531 host->max_cmd_len = UFS_CDB_SIZE;
9533 hba->max_pwr_info.is_valid = false;
9535 INIT_WORK(&hba->eeh_work, ufshcd_exception_event_handler);
9537 sema_init(&hba->host_sem, 1);
9539 /* Initialize UIC command mutex */
9540 mutex_init(&hba->uic_cmd_mutex);
9542 /* Initialize mutex for device management commands */
9543 mutex_init(&hba->dev_cmd.lock);
9545 /* Initialize mutex for exception event control */
9546 mutex_init(&hba->ee_ctrl_mutex);
9548 init_rwsem(&hba->clk_scaling_lock);
9550 ufshcd_init_clk_gating(hba);
9552 ufshcd_init_clk_scaling(hba);
9555 * In order to avoid any spurious interrupt immediately after
9556 * registering UFS controller interrupt handler, clear any pending UFS
9557 * interrupt status and disable all the UFS interrupts.
9559 ufshcd_writel(hba, ufshcd_readl(hba, REG_INTERRUPT_STATUS),
9560 REG_INTERRUPT_STATUS);
9561 ufshcd_writel(hba, 0, REG_INTERRUPT_ENABLE);
9563 * Make sure that UFS interrupts are disabled and any pending interrupt
9564 * status is cleared before registering UFS interrupt handler.
9568 /* IRQ registration */
9569 err = devm_request_irq(dev, irq, ufshcd_intr, IRQF_SHARED, UFSHCD, hba);
9571 dev_err(hba->dev, "request irq failed\n");
9574 hba->is_irq_enabled = true;
9577 err = scsi_add_host(host, hba->dev);
9579 dev_err(hba->dev, "scsi_add_host failed\n");
9583 hba->cmd_queue = blk_mq_init_queue(&hba->host->tag_set);
9584 if (IS_ERR(hba->cmd_queue)) {
9585 err = PTR_ERR(hba->cmd_queue);
9586 goto out_remove_scsi_host;
9589 hba->tmf_tag_set = (struct blk_mq_tag_set) {
9591 .queue_depth = hba->nutmrs,
9592 .ops = &ufshcd_tmf_ops,
9593 .flags = BLK_MQ_F_NO_SCHED,
9595 err = blk_mq_alloc_tag_set(&hba->tmf_tag_set);
9597 goto free_cmd_queue;
9598 hba->tmf_queue = blk_mq_init_queue(&hba->tmf_tag_set);
9599 if (IS_ERR(hba->tmf_queue)) {
9600 err = PTR_ERR(hba->tmf_queue);
9601 goto free_tmf_tag_set;
9604 /* Reset the attached device */
9605 ufshcd_device_reset(hba);
9607 ufshcd_init_crypto(hba);
9609 /* Host controller enable */
9610 err = ufshcd_hba_enable(hba);
9612 dev_err(hba->dev, "Host controller enable failed\n");
9613 ufshcd_print_evt_hist(hba);
9614 ufshcd_print_host_state(hba);
9615 goto free_tmf_queue;
9619 * Set the default power management level for runtime and system PM.
9620 * Default power saving mode is to keep UFS link in Hibern8 state
9621 * and UFS device in sleep state.
9623 hba->rpm_lvl = ufs_get_desired_pm_lvl_for_dev_link_state(
9625 UIC_LINK_HIBERN8_STATE);
9626 hba->spm_lvl = ufs_get_desired_pm_lvl_for_dev_link_state(
9628 UIC_LINK_HIBERN8_STATE);
9630 INIT_DELAYED_WORK(&hba->rpm_dev_flush_recheck_work,
9631 ufshcd_rpm_dev_flush_recheck_work);
9633 /* Set the default auto-hiberate idle timer value to 150 ms */
9634 if (ufshcd_is_auto_hibern8_supported(hba) && !hba->ahit) {
9635 hba->ahit = FIELD_PREP(UFSHCI_AHIBERN8_TIMER_MASK, 150) |
9636 FIELD_PREP(UFSHCI_AHIBERN8_SCALE_MASK, 3);
9639 /* Hold auto suspend until async scan completes */
9640 pm_runtime_get_sync(dev);
9641 atomic_set(&hba->scsi_block_reqs_cnt, 0);
9643 * We are assuming that device wasn't put in sleep/power-down
9644 * state exclusively during the boot stage before kernel.
9645 * This assumption helps avoid doing link startup twice during
9646 * ufshcd_probe_hba().
9648 ufshcd_set_ufs_dev_active(hba);
9650 async_schedule(ufshcd_async_scan, hba);
9651 ufs_sysfs_add_nodes(hba->dev);
9653 device_enable_async_suspend(dev);
9657 blk_cleanup_queue(hba->tmf_queue);
9659 blk_mq_free_tag_set(&hba->tmf_tag_set);
9661 blk_cleanup_queue(hba->cmd_queue);
9662 out_remove_scsi_host:
9663 scsi_remove_host(hba->host);
9665 hba->is_irq_enabled = false;
9666 ufshcd_hba_exit(hba);
9670 EXPORT_SYMBOL_GPL(ufshcd_init);
9672 void ufshcd_resume_complete(struct device *dev)
9674 struct ufs_hba *hba = dev_get_drvdata(dev);
9676 if (hba->complete_put) {
9677 ufshcd_rpm_put(hba);
9678 hba->complete_put = false;
9681 EXPORT_SYMBOL_GPL(ufshcd_resume_complete);
9683 int ufshcd_suspend_prepare(struct device *dev)
9685 struct ufs_hba *hba = dev_get_drvdata(dev);
9689 * SCSI assumes that runtime-pm and system-pm for scsi drivers
9690 * are same. And it doesn't wake up the device for system-suspend
9691 * if it's runtime suspended. But ufs doesn't follow that.
9692 * Refer ufshcd_resume_complete()
9694 if (hba->sdev_ufs_device) {
9695 ret = ufshcd_rpm_get_sync(hba);
9696 if (ret < 0 && ret != -EACCES) {
9697 ufshcd_rpm_put(hba);
9700 hba->complete_put = true;
9704 EXPORT_SYMBOL_GPL(ufshcd_suspend_prepare);
9706 #ifdef CONFIG_PM_SLEEP
9707 static int ufshcd_wl_poweroff(struct device *dev)
9709 struct scsi_device *sdev = to_scsi_device(dev);
9710 struct ufs_hba *hba = shost_priv(sdev->host);
9712 __ufshcd_wl_suspend(hba, UFS_SHUTDOWN_PM);
9717 static int ufshcd_wl_probe(struct device *dev)
9719 struct scsi_device *sdev = to_scsi_device(dev);
9721 if (!is_device_wlun(sdev))
9724 blk_pm_runtime_init(sdev->request_queue, dev);
9725 pm_runtime_set_autosuspend_delay(dev, 0);
9726 pm_runtime_allow(dev);
9731 static int ufshcd_wl_remove(struct device *dev)
9733 pm_runtime_forbid(dev);
9737 static const struct dev_pm_ops ufshcd_wl_pm_ops = {
9738 #ifdef CONFIG_PM_SLEEP
9739 .suspend = ufshcd_wl_suspend,
9740 .resume = ufshcd_wl_resume,
9741 .freeze = ufshcd_wl_suspend,
9742 .thaw = ufshcd_wl_resume,
9743 .poweroff = ufshcd_wl_poweroff,
9744 .restore = ufshcd_wl_resume,
9746 SET_RUNTIME_PM_OPS(ufshcd_wl_runtime_suspend, ufshcd_wl_runtime_resume, NULL)
9750 * ufs_dev_wlun_template - describes ufs device wlun
9751 * ufs-device wlun - used to send pm commands
9752 * All luns are consumers of ufs-device wlun.
9754 * Currently, no sd driver is present for wluns.
9755 * Hence the no specific pm operations are performed.
9756 * With ufs design, SSU should be sent to ufs-device wlun.
9757 * Hence register a scsi driver for ufs wluns only.
9759 static struct scsi_driver ufs_dev_wlun_template = {
9761 .name = "ufs_device_wlun",
9762 .owner = THIS_MODULE,
9763 .probe = ufshcd_wl_probe,
9764 .remove = ufshcd_wl_remove,
9765 .pm = &ufshcd_wl_pm_ops,
9766 .shutdown = ufshcd_wl_shutdown,
9770 static int __init ufshcd_core_init(void)
9776 ret = scsi_register_driver(&ufs_dev_wlun_template.gendrv);
9782 static void __exit ufshcd_core_exit(void)
9785 scsi_unregister_driver(&ufs_dev_wlun_template.gendrv);
9788 module_init(ufshcd_core_init);
9789 module_exit(ufshcd_core_exit);
9791 MODULE_AUTHOR("Santosh Yaragnavi <santosh.sy@samsung.com>");
9792 MODULE_AUTHOR("Vinayak Holikatti <h.vinayak@samsung.com>");
9793 MODULE_DESCRIPTION("Generic UFS host controller driver Core");
9794 MODULE_LICENSE("GPL");
9795 MODULE_VERSION(UFSHCD_DRIVER_VERSION);