2 * Universal Flash Storage Host controller driver Core
4 * This code is based on drivers/scsi/ufs/ufshcd.c
5 * Copyright (C) 2011-2013 Samsung India Software Operations
6 * Copyright (c) 2013-2018, The Linux Foundation. All rights reserved.
9 * Santosh Yaraganavi <santosh.sy@samsung.com>
10 * Vinayak Holikatti <h.vinayak@samsung.com>
12 * This program is free software; you can redistribute it and/or
13 * modify it under the terms of the GNU General Public License
14 * as published by the Free Software Foundation; either version 2
15 * of the License, or (at your option) any later version.
16 * See the COPYING file in the top-level directory or visit
17 * <http://www.gnu.org/licenses/gpl-2.0.html>
19 * This program is distributed in the hope that it will be useful,
20 * but WITHOUT ANY WARRANTY; without even the implied warranty of
21 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22 * GNU General Public License for more details.
24 * This program is provided "AS IS" and "WITH ALL FAULTS" and
25 * without warranty of any kind. You are solely responsible for
26 * determining the appropriateness of using and distributing
27 * the program and assume all risks associated with your exercise
28 * of rights with respect to the program, including but not limited
29 * to infringement of third party rights, the risks and costs of
30 * program errors, damage to or loss of data, programs or equipment,
31 * and unavailability or interruption of operations. Under no
32 * circumstances will the contributor of this Program be liable for
33 * any damages of any kind arising from your use or distribution of
36 * The Linux Foundation chooses to take subject only to the GPLv2
37 * license terms, and distributes only under these terms.
40 #include <linux/async.h>
41 #include <scsi/ufs/ioctl.h>
42 #include <linux/devfreq.h>
43 #include <linux/nls.h>
45 #include <linux/blkdev.h>
49 #include "ufs_quirks.h"
50 #include "ufs-debugfs.h"
53 #define CREATE_TRACE_POINTS
54 #include <trace/events/ufs.h>
56 #ifdef CONFIG_DEBUG_FS
58 static int ufshcd_tag_req_type(struct request *rq)
60 int rq_type = TS_WRITE;
62 if (!rq || !(rq->cmd_type & REQ_TYPE_FS))
63 rq_type = TS_NOT_SUPPORTED;
64 else if (rq->cmd_flags & REQ_FLUSH)
66 else if (rq_data_dir(rq) == READ)
67 rq_type = (rq->cmd_flags & REQ_URGENT) ?
68 TS_URGENT_READ : TS_READ;
69 else if (rq->cmd_flags & REQ_URGENT)
70 rq_type = TS_URGENT_WRITE;
75 static void ufshcd_update_error_stats(struct ufs_hba *hba, int type)
77 ufsdbg_set_err_state(hba);
78 if (type < UFS_ERR_MAX)
79 hba->ufs_stats.err_stats[type]++;
82 static void ufshcd_update_tag_stats(struct ufs_hba *hba, int tag)
85 hba->lrb[tag].cmd ? hba->lrb[tag].cmd->request : NULL;
86 u64 **tag_stats = hba->ufs_stats.tag_stats;
89 if (!hba->ufs_stats.enabled)
92 tag_stats[tag][TS_TAG]++;
93 if (!rq || !(rq->cmd_type & REQ_TYPE_FS))
96 WARN_ON(hba->ufs_stats.q_depth > hba->nutrs);
97 rq_type = ufshcd_tag_req_type(rq);
98 if (!(rq_type < 0 || rq_type > TS_NUM_STATS))
99 tag_stats[hba->ufs_stats.q_depth++][rq_type]++;
102 static void ufshcd_update_tag_stats_completion(struct ufs_hba *hba,
103 struct scsi_cmnd *cmd)
105 struct request *rq = cmd ? cmd->request : NULL;
107 if (rq && rq->cmd_type & REQ_TYPE_FS)
108 hba->ufs_stats.q_depth--;
111 static void update_req_stats(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
114 struct request *rq = lrbp->cmd ? lrbp->cmd->request : NULL;
115 s64 delta = ktime_us_delta(lrbp->complete_time_stamp,
116 lrbp->issue_time_stamp);
118 /* update general request statistics */
119 if (hba->ufs_stats.req_stats[TS_TAG].count == 0)
120 hba->ufs_stats.req_stats[TS_TAG].min = delta;
121 hba->ufs_stats.req_stats[TS_TAG].count++;
122 hba->ufs_stats.req_stats[TS_TAG].sum += delta;
123 if (delta > hba->ufs_stats.req_stats[TS_TAG].max)
124 hba->ufs_stats.req_stats[TS_TAG].max = delta;
125 if (delta < hba->ufs_stats.req_stats[TS_TAG].min)
126 hba->ufs_stats.req_stats[TS_TAG].min = delta;
128 rq_type = ufshcd_tag_req_type(rq);
129 if (rq_type == TS_NOT_SUPPORTED)
132 /* update request type specific statistics */
133 if (hba->ufs_stats.req_stats[rq_type].count == 0)
134 hba->ufs_stats.req_stats[rq_type].min = delta;
135 hba->ufs_stats.req_stats[rq_type].count++;
136 hba->ufs_stats.req_stats[rq_type].sum += delta;
137 if (delta > hba->ufs_stats.req_stats[rq_type].max)
138 hba->ufs_stats.req_stats[rq_type].max = delta;
139 if (delta < hba->ufs_stats.req_stats[rq_type].min)
140 hba->ufs_stats.req_stats[rq_type].min = delta;
144 ufshcd_update_query_stats(struct ufs_hba *hba, enum query_opcode opcode, u8 idn)
146 if (opcode < UPIU_QUERY_OPCODE_MAX && idn < MAX_QUERY_IDN)
147 hba->ufs_stats.query_stats_arr[opcode][idn]++;
151 static inline void ufshcd_update_tag_stats(struct ufs_hba *hba, int tag)
155 static inline void ufshcd_update_tag_stats_completion(struct ufs_hba *hba,
156 struct scsi_cmnd *cmd)
160 static inline void ufshcd_update_error_stats(struct ufs_hba *hba, int type)
165 void update_req_stats(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
170 void ufshcd_update_query_stats(struct ufs_hba *hba,
171 enum query_opcode opcode, u8 idn)
176 #define PWR_INFO_MASK 0xF
177 #define PWR_RX_OFFSET 4
179 #define UFSHCD_REQ_SENSE_SIZE 18
181 #define UFSHCD_ENABLE_INTRS (UTP_TRANSFER_REQ_COMPL |\
182 UTP_TASK_REQ_COMPL |\
184 /* UIC command timeout, unit: ms */
185 #define UIC_CMD_TIMEOUT 500
187 /* NOP OUT retries waiting for NOP IN response */
188 #define NOP_OUT_RETRIES 10
189 /* Timeout after 30 msecs if NOP OUT hangs without response */
190 #define NOP_OUT_TIMEOUT 30 /* msecs */
192 /* Query request retries */
193 #define QUERY_REQ_RETRIES 3
194 /* Query request timeout */
195 #define QUERY_REQ_TIMEOUT 1500 /* 1.5 seconds */
197 /* Task management command timeout */
198 #define TM_CMD_TIMEOUT 100 /* msecs */
200 /* maximum number of retries for a general UIC command */
201 #define UFS_UIC_COMMAND_RETRIES 3
203 /* maximum number of link-startup retries */
204 #define DME_LINKSTARTUP_RETRIES 3
206 /* Maximum retries for Hibern8 enter */
207 #define UIC_HIBERN8_ENTER_RETRIES 3
209 /* maximum number of reset retries before giving up */
210 #define MAX_HOST_RESET_RETRIES 5
212 /* Expose the flag value from utp_upiu_query.value */
213 #define MASK_QUERY_UPIU_FLAG_LOC 0xFF
215 /* Interrupt aggregation default timeout, unit: 40us */
216 #define INT_AGGR_DEF_TO 0x02
218 /* default value of auto suspend is 3 seconds */
219 #define UFSHCD_AUTO_SUSPEND_DELAY_MS 3000 /* millisecs */
221 #define UFSHCD_CLK_GATING_DELAY_MS_PWR_SAVE 10
222 #define UFSHCD_CLK_GATING_DELAY_MS_PERF 50
224 /* IOCTL opcode for command - ufs set device read only */
225 #define UFS_IOCTL_BLKROSET BLKROSET
227 #define UFSHCD_DEFAULT_LANES_PER_DIRECTION 2
229 #define ufshcd_toggle_vreg(_dev, _vreg, _on) \
233 _ret = ufshcd_enable_vreg(_dev, _vreg); \
235 _ret = ufshcd_disable_vreg(_dev, _vreg); \
239 #define ufshcd_hex_dump(prefix_str, buf, len) \
240 print_hex_dump(KERN_ERR, prefix_str, DUMP_PREFIX_OFFSET, 16, 4, buf, len, false)
242 static u32 ufs_query_desc_max_size[] = {
243 QUERY_DESC_DEVICE_MAX_SIZE,
244 QUERY_DESC_CONFIGURAION_MAX_SIZE,
245 QUERY_DESC_UNIT_MAX_SIZE,
246 QUERY_DESC_RFU_MAX_SIZE,
247 QUERY_DESC_INTERCONNECT_MAX_SIZE,
248 QUERY_DESC_STRING_MAX_SIZE,
249 QUERY_DESC_RFU_MAX_SIZE,
250 QUERY_DESC_GEOMETRY_MAZ_SIZE,
251 QUERY_DESC_POWER_MAX_SIZE,
252 QUERY_DESC_RFU_MAX_SIZE,
256 UFSHCD_MAX_CHANNEL = 0,
258 UFSHCD_CMD_PER_LUN = 32,
259 UFSHCD_CAN_QUEUE = 32,
266 UFSHCD_STATE_OPERATIONAL,
269 /* UFSHCD error handling flags */
271 UFSHCD_EH_IN_PROGRESS = (1 << 0),
274 /* UFSHCD UIC layer error flags */
276 UFSHCD_UIC_DL_PA_INIT_ERROR = (1 << 0), /* Data link layer error */
277 UFSHCD_UIC_DL_NAC_RECEIVED_ERROR = (1 << 1), /* Data link layer error */
278 UFSHCD_UIC_DL_TCx_REPLAY_ERROR = (1 << 2), /* Data link layer error */
279 UFSHCD_UIC_NL_ERROR = (1 << 3), /* Network layer error */
280 UFSHCD_UIC_TL_ERROR = (1 << 4), /* Transport Layer error */
281 UFSHCD_UIC_DME_ERROR = (1 << 5), /* DME error */
284 /* Interrupt configuration options */
291 #define DEFAULT_UFSHCD_DBG_PRINT_EN UFSHCD_DBG_PRINT_ALL
293 #define ufshcd_set_eh_in_progress(h) \
294 (h->eh_flags |= UFSHCD_EH_IN_PROGRESS)
295 #define ufshcd_eh_in_progress(h) \
296 (h->eh_flags & UFSHCD_EH_IN_PROGRESS)
297 #define ufshcd_clear_eh_in_progress(h) \
298 (h->eh_flags &= ~UFSHCD_EH_IN_PROGRESS)
300 #define ufshcd_set_ufs_dev_active(h) \
301 ((h)->curr_dev_pwr_mode = UFS_ACTIVE_PWR_MODE)
302 #define ufshcd_set_ufs_dev_sleep(h) \
303 ((h)->curr_dev_pwr_mode = UFS_SLEEP_PWR_MODE)
304 #define ufshcd_set_ufs_dev_poweroff(h) \
305 ((h)->curr_dev_pwr_mode = UFS_POWERDOWN_PWR_MODE)
306 #define ufshcd_is_ufs_dev_active(h) \
307 ((h)->curr_dev_pwr_mode == UFS_ACTIVE_PWR_MODE)
308 #define ufshcd_is_ufs_dev_sleep(h) \
309 ((h)->curr_dev_pwr_mode == UFS_SLEEP_PWR_MODE)
310 #define ufshcd_is_ufs_dev_poweroff(h) \
311 ((h)->curr_dev_pwr_mode == UFS_POWERDOWN_PWR_MODE)
313 static struct ufs_pm_lvl_states ufs_pm_lvl_states[] = {
314 {UFS_ACTIVE_PWR_MODE, UIC_LINK_ACTIVE_STATE},
315 {UFS_ACTIVE_PWR_MODE, UIC_LINK_HIBERN8_STATE},
316 {UFS_SLEEP_PWR_MODE, UIC_LINK_ACTIVE_STATE},
317 {UFS_SLEEP_PWR_MODE, UIC_LINK_HIBERN8_STATE},
318 {UFS_POWERDOWN_PWR_MODE, UIC_LINK_HIBERN8_STATE},
319 {UFS_POWERDOWN_PWR_MODE, UIC_LINK_OFF_STATE},
322 static inline enum ufs_dev_pwr_mode
323 ufs_get_pm_lvl_to_dev_pwr_mode(enum ufs_pm_level lvl)
325 return ufs_pm_lvl_states[lvl].dev_state;
328 static inline enum uic_link_state
329 ufs_get_pm_lvl_to_link_pwr_state(enum ufs_pm_level lvl)
331 return ufs_pm_lvl_states[lvl].link_state;
334 static inline enum ufs_pm_level
335 ufs_get_desired_pm_lvl_for_dev_link_state(enum ufs_dev_pwr_mode dev_state,
336 enum uic_link_state link_state)
338 enum ufs_pm_level lvl;
340 for (lvl = UFS_PM_LVL_0; lvl < UFS_PM_LVL_MAX; lvl++) {
341 if ((ufs_pm_lvl_states[lvl].dev_state == dev_state) &&
342 (ufs_pm_lvl_states[lvl].link_state == link_state))
346 /* if no match found, return the level 0 */
350 static inline bool ufshcd_is_valid_pm_lvl(int lvl)
352 if (lvl >= 0 && lvl < ARRAY_SIZE(ufs_pm_lvl_states))
358 static irqreturn_t ufshcd_intr(int irq, void *__hba);
359 static irqreturn_t ufshcd_tmc_handler(struct ufs_hba *hba);
360 static void ufshcd_async_scan(void *data, async_cookie_t cookie);
361 static int ufshcd_reset_and_restore(struct ufs_hba *hba);
362 static int ufshcd_eh_host_reset_handler(struct scsi_cmnd *cmd);
363 static int ufshcd_clear_tm_cmd(struct ufs_hba *hba, int tag);
364 static void ufshcd_hba_exit(struct ufs_hba *hba);
365 static int ufshcd_probe_hba(struct ufs_hba *hba);
366 static int ufshcd_enable_clocks(struct ufs_hba *hba);
367 static int ufshcd_disable_clocks(struct ufs_hba *hba,
368 bool is_gating_context);
369 static int ufshcd_disable_clocks_skip_ref_clk(struct ufs_hba *hba,
370 bool is_gating_context);
371 static void ufshcd_hold_all(struct ufs_hba *hba);
372 static void ufshcd_release_all(struct ufs_hba *hba);
373 static int ufshcd_set_vccq_rail_unused(struct ufs_hba *hba, bool unused);
374 static inline void ufshcd_add_delay_before_dme_cmd(struct ufs_hba *hba);
375 static inline void ufshcd_save_tstamp_of_last_dme_cmd(struct ufs_hba *hba);
376 static int ufshcd_host_reset_and_restore(struct ufs_hba *hba);
377 static void ufshcd_resume_clkscaling(struct ufs_hba *hba);
378 static void ufshcd_suspend_clkscaling(struct ufs_hba *hba);
379 static void __ufshcd_suspend_clkscaling(struct ufs_hba *hba);
380 static void ufshcd_release_all(struct ufs_hba *hba);
381 static void ufshcd_hba_vreg_set_lpm(struct ufs_hba *hba);
382 static void ufshcd_hba_vreg_set_hpm(struct ufs_hba *hba);
383 static int ufshcd_devfreq_target(struct device *dev,
384 unsigned long *freq, u32 flags);
385 static int ufshcd_devfreq_get_dev_status(struct device *dev,
386 struct devfreq_dev_status *stat);
388 #if IS_ENABLED(CONFIG_DEVFREQ_GOV_SIMPLE_ONDEMAND)
389 static struct devfreq_simple_ondemand_data ufshcd_ondemand_data = {
391 .downdifferential = 30,
395 static void *gov_data = &ufshcd_ondemand_data;
397 static void *gov_data;
400 static struct devfreq_dev_profile ufs_devfreq_profile = {
402 .target = ufshcd_devfreq_target,
403 .get_dev_status = ufshcd_devfreq_get_dev_status,
406 static inline bool ufshcd_valid_tag(struct ufs_hba *hba, int tag)
408 return tag >= 0 && tag < hba->nutrs;
411 static inline void ufshcd_enable_irq(struct ufs_hba *hba)
413 if (!hba->is_irq_enabled) {
414 enable_irq(hba->irq);
415 hba->is_irq_enabled = true;
419 static inline void ufshcd_disable_irq(struct ufs_hba *hba)
421 if (hba->is_irq_enabled) {
422 disable_irq(hba->irq);
423 hba->is_irq_enabled = false;
427 void ufshcd_scsi_unblock_requests(struct ufs_hba *hba)
430 bool unblock = false;
432 spin_lock_irqsave(hba->host->host_lock, flags);
433 hba->scsi_block_reqs_cnt--;
434 unblock = !hba->scsi_block_reqs_cnt;
435 spin_unlock_irqrestore(hba->host->host_lock, flags);
437 scsi_unblock_requests(hba->host);
439 EXPORT_SYMBOL(ufshcd_scsi_unblock_requests);
441 static inline void __ufshcd_scsi_block_requests(struct ufs_hba *hba)
443 if (!hba->scsi_block_reqs_cnt++)
444 scsi_block_requests(hba->host);
447 void ufshcd_scsi_block_requests(struct ufs_hba *hba)
451 spin_lock_irqsave(hba->host->host_lock, flags);
452 __ufshcd_scsi_block_requests(hba);
453 spin_unlock_irqrestore(hba->host->host_lock, flags);
455 EXPORT_SYMBOL(ufshcd_scsi_block_requests);
457 static int ufshcd_device_reset_ctrl(struct ufs_hba *hba, bool ctrl)
464 /* Assert reset if ctrl == true */
466 ret = pinctrl_select_state(hba->pctrl,
467 pinctrl_lookup_state(hba->pctrl, "dev-reset-assert"));
469 ret = pinctrl_select_state(hba->pctrl,
470 pinctrl_lookup_state(hba->pctrl, "dev-reset-deassert"));
473 dev_err(hba->dev, "%s: %s failed with err %d\n",
474 __func__, ctrl ? "Assert" : "Deassert", ret);
479 static inline int ufshcd_assert_device_reset(struct ufs_hba *hba)
481 return ufshcd_device_reset_ctrl(hba, true);
484 static inline int ufshcd_deassert_device_reset(struct ufs_hba *hba)
486 return ufshcd_device_reset_ctrl(hba, false);
489 static int ufshcd_reset_device(struct ufs_hba *hba)
493 /* reset the connected UFS device */
494 ret = ufshcd_assert_device_reset(hba);
498 * The reset signal is active low.
499 * The UFS device shall detect more than or equal to 1us of positive
500 * or negative RST_n pulse width.
501 * To be on safe side, keep the reset low for atleast 10us.
503 usleep_range(10, 15);
505 ret = ufshcd_deassert_device_reset(hba);
508 /* same as assert, wait for atleast 10us after deassert */
509 usleep_range(10, 15);
514 /* replace non-printable or non-ASCII characters with spaces */
515 static inline void ufshcd_remove_non_printable(char *val)
520 if (*val < 0x20 || *val > 0x7e)
524 #define UFSHCD_MAX_CMD_LOGGING 200
526 #ifdef CONFIG_TRACEPOINTS
527 static inline void ufshcd_add_command_trace(struct ufs_hba *hba,
528 struct ufshcd_cmd_log_entry *entry, u8 opcode)
530 if (trace_ufshcd_command_enabled()) {
531 u32 intr = ufshcd_readl(hba, REG_INTERRUPT_STATUS);
533 trace_ufshcd_command(dev_name(hba->dev), entry->str, entry->tag,
534 entry->doorbell, entry->transfer_len, intr,
539 static inline void ufshcd_add_command_trace(struct ufs_hba *hba,
540 struct ufshcd_cmd_log_entry *entry, u8 opcode)
545 #ifdef CONFIG_SCSI_UFSHCD_CMD_LOGGING
546 static void ufshcd_cmd_log_init(struct ufs_hba *hba)
548 /* Allocate log entries */
549 if (!hba->cmd_log.entries) {
550 hba->cmd_log.entries = kzalloc(UFSHCD_MAX_CMD_LOGGING *
551 sizeof(struct ufshcd_cmd_log_entry), GFP_KERNEL);
552 if (!hba->cmd_log.entries)
554 dev_dbg(hba->dev, "%s: cmd_log.entries initialized\n",
559 static void __ufshcd_cmd_log(struct ufs_hba *hba, char *str, char *cmd_type,
560 unsigned int tag, u8 cmd_id, u8 idn, u8 lun,
561 sector_t lba, int transfer_len, u8 opcode)
563 struct ufshcd_cmd_log_entry *entry;
565 if (!hba->cmd_log.entries)
568 entry = &hba->cmd_log.entries[hba->cmd_log.pos];
571 entry->cmd_type = cmd_type;
572 entry->cmd_id = cmd_id;
574 entry->transfer_len = transfer_len;
576 entry->doorbell = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
578 entry->tstamp = ktime_get();
579 entry->outstanding_reqs = hba->outstanding_reqs;
580 entry->seq_num = hba->cmd_log.seq_num;
581 hba->cmd_log.seq_num++;
583 (hba->cmd_log.pos + 1) % UFSHCD_MAX_CMD_LOGGING;
585 ufshcd_add_command_trace(hba, entry, opcode);
588 static void ufshcd_cmd_log(struct ufs_hba *hba, char *str, char *cmd_type,
589 unsigned int tag, u8 cmd_id, u8 idn)
591 __ufshcd_cmd_log(hba, str, cmd_type, tag, cmd_id, idn,
592 0xff, (sector_t)-1, -1, -1);
595 static void ufshcd_dme_cmd_log(struct ufs_hba *hba, char *str, u8 cmd_id)
597 ufshcd_cmd_log(hba, str, "dme", 0xff, cmd_id, 0xff);
600 static void ufshcd_print_cmd_log(struct ufs_hba *hba)
604 struct ufshcd_cmd_log_entry *p;
606 if (!hba->cmd_log.entries)
609 pos = hba->cmd_log.pos;
610 for (i = 0; i < UFSHCD_MAX_CMD_LOGGING; i++) {
611 p = &hba->cmd_log.entries[pos];
612 pos = (pos + 1) % UFSHCD_MAX_CMD_LOGGING;
614 if (ktime_to_us(p->tstamp)) {
615 pr_err("%s: %s: seq_no=%u lun=0x%x cmd_id=0x%02x lba=0x%llx txfer_len=%d tag=%u, doorbell=0x%x outstanding=0x%x idn=%d time=%lld us\n",
616 p->cmd_type, p->str, p->seq_num,
617 p->lun, p->cmd_id, (unsigned long long)p->lba,
618 p->transfer_len, p->tag, p->doorbell,
619 p->outstanding_reqs, p->idn,
620 ktime_to_us(p->tstamp));
621 usleep_range(1000, 1100);
626 static void ufshcd_cmd_log_init(struct ufs_hba *hba)
630 static void __ufshcd_cmd_log(struct ufs_hba *hba, char *str, char *cmd_type,
631 unsigned int tag, u8 cmd_id, u8 idn, u8 lun,
632 sector_t lba, int transfer_len, u8 opcode)
634 struct ufshcd_cmd_log_entry entry;
638 entry.cmd_id = cmd_id;
639 entry.transfer_len = transfer_len;
640 entry.doorbell = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
643 ufshcd_add_command_trace(hba, &entry, opcode);
646 static void ufshcd_dme_cmd_log(struct ufs_hba *hba, char *str, u8 cmd_id)
650 static void ufshcd_print_cmd_log(struct ufs_hba *hba)
655 #ifdef CONFIG_TRACEPOINTS
656 static inline void ufshcd_cond_add_cmd_trace(struct ufs_hba *hba,
657 unsigned int tag, const char *str)
659 struct ufshcd_lrb *lrbp;
660 char *cmd_type = NULL;
662 u8 cmd_id = 0, idn = 0;
664 int transfer_len = -1;
666 lrbp = &hba->lrb[tag];
668 if (lrbp->cmd) { /* data phase exists */
669 opcode = (u8)(*lrbp->cmd->cmnd);
670 if ((opcode == READ_10) || (opcode == WRITE_10)) {
672 * Currently we only fully trace read(10) and write(10)
675 if (lrbp->cmd->request && lrbp->cmd->request->bio)
677 lrbp->cmd->request->bio->bi_iter.bi_sector;
678 transfer_len = be32_to_cpu(
679 lrbp->ucd_req_ptr->sc.exp_data_transfer_len);
683 if (lrbp->cmd && (lrbp->command_type == UTP_CMD_TYPE_SCSI)) {
685 cmd_id = (u8)(*lrbp->cmd->cmnd);
686 } else if (lrbp->command_type == UTP_CMD_TYPE_DEV_MANAGE) {
687 if (hba->dev_cmd.type == DEV_CMD_TYPE_NOP) {
690 } else if (hba->dev_cmd.type == DEV_CMD_TYPE_QUERY) {
692 cmd_id = hba->dev_cmd.query.request.upiu_req.opcode;
693 idn = hba->dev_cmd.query.request.upiu_req.idn;
697 __ufshcd_cmd_log(hba, (char *) str, cmd_type, tag, cmd_id, idn,
698 lrbp->lun, lba, transfer_len, opcode);
701 static inline void ufshcd_cond_add_cmd_trace(struct ufs_hba *hba,
702 unsigned int tag, const char *str)
707 static void ufshcd_print_clk_freqs(struct ufs_hba *hba)
709 struct ufs_clk_info *clki;
710 struct list_head *head = &hba->clk_list_head;
712 if (!(hba->ufshcd_dbg_print & UFSHCD_DBG_PRINT_CLK_FREQ_EN))
715 if (!head || list_empty(head))
718 list_for_each_entry(clki, head, list) {
719 if (!IS_ERR_OR_NULL(clki->clk) && clki->min_freq &&
721 dev_err(hba->dev, "clk: %s, rate: %u\n",
722 clki->name, clki->curr_freq);
726 static void ufshcd_print_uic_err_hist(struct ufs_hba *hba,
727 struct ufs_uic_err_reg_hist *err_hist, char *err_name)
731 if (!(hba->ufshcd_dbg_print & UFSHCD_DBG_PRINT_UIC_ERR_HIST_EN))
734 for (i = 0; i < UIC_ERR_REG_HIST_LENGTH; i++) {
735 int p = (i + err_hist->pos - 1) % UIC_ERR_REG_HIST_LENGTH;
737 if (err_hist->reg[p] == 0)
739 dev_err(hba->dev, "%s[%d] = 0x%x at %lld us", err_name, i,
740 err_hist->reg[p], ktime_to_us(err_hist->tstamp[p]));
744 static inline void __ufshcd_print_host_regs(struct ufs_hba *hba, bool no_sleep)
746 if (!(hba->ufshcd_dbg_print & UFSHCD_DBG_PRINT_HOST_REGS_EN))
750 * hex_dump reads its data without the readl macro. This might
751 * cause inconsistency issues on some platform, as the printed
752 * values may be from cache and not the most recent value.
753 * To know whether you are looking at an un-cached version verify
754 * that IORESOURCE_MEM flag is on when xxx_get_resource() is invoked
755 * during platform/pci probe function.
757 ufshcd_hex_dump("host regs: ", hba->mmio_base, UFSHCI_REG_SPACE_SIZE);
758 dev_err(hba->dev, "hba->ufs_version = 0x%x, hba->capabilities = 0x%x",
759 hba->ufs_version, hba->capabilities);
761 "hba->outstanding_reqs = 0x%x, hba->outstanding_tasks = 0x%x",
762 (u32)hba->outstanding_reqs, (u32)hba->outstanding_tasks);
764 "last_hibern8_exit_tstamp at %lld us, hibern8_exit_cnt = %d",
765 ktime_to_us(hba->ufs_stats.last_hibern8_exit_tstamp),
766 hba->ufs_stats.hibern8_exit_cnt);
768 ufshcd_print_uic_err_hist(hba, &hba->ufs_stats.pa_err, "pa_err");
769 ufshcd_print_uic_err_hist(hba, &hba->ufs_stats.dl_err, "dl_err");
770 ufshcd_print_uic_err_hist(hba, &hba->ufs_stats.nl_err, "nl_err");
771 ufshcd_print_uic_err_hist(hba, &hba->ufs_stats.tl_err, "tl_err");
772 ufshcd_print_uic_err_hist(hba, &hba->ufs_stats.dme_err, "dme_err");
774 ufshcd_print_clk_freqs(hba);
776 ufshcd_vops_dbg_register_dump(hba, no_sleep);
779 static void ufshcd_print_host_regs(struct ufs_hba *hba)
781 __ufshcd_print_host_regs(hba, false);
785 void ufshcd_print_trs(struct ufs_hba *hba, unsigned long bitmap, bool pr_prdt)
787 struct ufshcd_lrb *lrbp;
791 if (!(hba->ufshcd_dbg_print & UFSHCD_DBG_PRINT_TRS_EN))
794 for_each_set_bit(tag, &bitmap, hba->nutrs) {
795 lrbp = &hba->lrb[tag];
797 dev_err(hba->dev, "UPIU[%d] - issue time %lld us",
798 tag, ktime_to_us(lrbp->issue_time_stamp));
800 "UPIU[%d] - Transfer Request Descriptor phys@0x%llx",
801 tag, (u64)lrbp->utrd_dma_addr);
802 ufshcd_hex_dump("UPIU TRD: ", lrbp->utr_descriptor_ptr,
803 sizeof(struct utp_transfer_req_desc));
804 dev_err(hba->dev, "UPIU[%d] - Request UPIU phys@0x%llx", tag,
805 (u64)lrbp->ucd_req_dma_addr);
806 ufshcd_hex_dump("UPIU REQ: ", lrbp->ucd_req_ptr,
807 sizeof(struct utp_upiu_req));
808 dev_err(hba->dev, "UPIU[%d] - Response UPIU phys@0x%llx", tag,
809 (u64)lrbp->ucd_rsp_dma_addr);
810 ufshcd_hex_dump("UPIU RSP: ", lrbp->ucd_rsp_ptr,
811 sizeof(struct utp_upiu_rsp));
813 le16_to_cpu(lrbp->utr_descriptor_ptr->prd_table_length);
814 dev_err(hba->dev, "UPIU[%d] - PRDT - %d entries phys@0x%llx",
815 tag, prdt_length, (u64)lrbp->ucd_prdt_dma_addr);
817 ufshcd_hex_dump("UPIU PRDT: ", lrbp->ucd_prdt_ptr,
818 sizeof(struct ufshcd_sg_entry) * prdt_length);
822 static void ufshcd_print_tmrs(struct ufs_hba *hba, unsigned long bitmap)
824 struct utp_task_req_desc *tmrdp;
827 if (!(hba->ufshcd_dbg_print & UFSHCD_DBG_PRINT_TMRS_EN))
830 for_each_set_bit(tag, &bitmap, hba->nutmrs) {
831 tmrdp = &hba->utmrdl_base_addr[tag];
832 dev_err(hba->dev, "TM[%d] - Task Management Header", tag);
833 ufshcd_hex_dump("TM TRD: ", &tmrdp->header,
834 sizeof(struct request_desc_header));
835 dev_err(hba->dev, "TM[%d] - Task Management Request UPIU",
837 ufshcd_hex_dump("TM REQ: ", tmrdp->task_req_upiu,
838 sizeof(struct utp_upiu_req));
839 dev_err(hba->dev, "TM[%d] - Task Management Response UPIU",
841 ufshcd_hex_dump("TM RSP: ", tmrdp->task_rsp_upiu,
842 sizeof(struct utp_task_req_desc));
846 static void ufshcd_print_fsm_state(struct ufs_hba *hba)
848 int err = 0, tx_fsm_val = 0, rx_fsm_val = 0;
850 err = ufshcd_dme_get(hba,
851 UIC_ARG_MIB_SEL(MPHY_TX_FSM_STATE,
852 UIC_ARG_MPHY_TX_GEN_SEL_INDEX(0)),
854 dev_err(hba->dev, "%s: TX_FSM_STATE = %u, err = %d\n", __func__,
856 err = ufshcd_dme_get(hba,
857 UIC_ARG_MIB_SEL(MPHY_RX_FSM_STATE,
858 UIC_ARG_MPHY_RX_GEN_SEL_INDEX(0)),
860 dev_err(hba->dev, "%s: RX_FSM_STATE = %u, err = %d\n", __func__,
864 static void ufshcd_print_host_state(struct ufs_hba *hba)
866 if (!(hba->ufshcd_dbg_print & UFSHCD_DBG_PRINT_HOST_STATE_EN))
869 dev_err(hba->dev, "UFS Host state=%d\n", hba->ufshcd_state);
870 dev_err(hba->dev, "lrb in use=0x%lx, outstanding reqs=0x%lx tasks=0x%lx\n",
871 hba->lrb_in_use, hba->outstanding_tasks, hba->outstanding_reqs);
872 dev_err(hba->dev, "saved_err=0x%x, saved_uic_err=0x%x, saved_ce_err=0x%x\n",
873 hba->saved_err, hba->saved_uic_err, hba->saved_ce_err);
874 dev_err(hba->dev, "Device power mode=%d, UIC link state=%d\n",
875 hba->curr_dev_pwr_mode, hba->uic_link_state);
876 dev_err(hba->dev, "PM in progress=%d, sys. suspended=%d\n",
877 hba->pm_op_in_progress, hba->is_sys_suspended);
878 dev_err(hba->dev, "Auto BKOPS=%d, Host self-block=%d\n",
879 hba->auto_bkops_enabled, hba->host->host_self_blocked);
880 dev_err(hba->dev, "Clk gate=%d, hibern8 on idle=%d\n",
881 hba->clk_gating.state, hba->hibern8_on_idle.state);
882 dev_err(hba->dev, "error handling flags=0x%x, req. abort count=%d\n",
883 hba->eh_flags, hba->req_abort_count);
884 dev_err(hba->dev, "Host capabilities=0x%x, caps=0x%x\n",
885 hba->capabilities, hba->caps);
886 dev_err(hba->dev, "quirks=0x%x, dev. quirks=0x%x\n", hba->quirks,
891 * ufshcd_print_pwr_info - print power params as saved in hba
893 * @hba: per-adapter instance
895 static void ufshcd_print_pwr_info(struct ufs_hba *hba)
907 if (!(hba->ufshcd_dbg_print & UFSHCD_DBG_PRINT_PWR_EN))
910 dev_err(hba->dev, "%s:[RX, TX]: gear=[%d, %d], lane[%d, %d], pwr[%s, %s], rate = %d\n",
912 hba->pwr_info.gear_rx, hba->pwr_info.gear_tx,
913 hba->pwr_info.lane_rx, hba->pwr_info.lane_tx,
914 names[hba->pwr_info.pwr_rx],
915 names[hba->pwr_info.pwr_tx],
916 hba->pwr_info.hs_rate);
920 * ufshcd_wait_for_register - wait for register value to change
921 * @hba - per-adapter interface
922 * @reg - mmio register offset
923 * @mask - mask to apply to read register value
924 * @val - wait condition
925 * @interval_us - polling interval in microsecs
926 * @timeout_ms - timeout in millisecs
927 * @can_sleep - perform sleep or just spin
928 * Returns -ETIMEDOUT on error, zero on success
930 int ufshcd_wait_for_register(struct ufs_hba *hba, u32 reg, u32 mask,
931 u32 val, unsigned long interval_us,
932 unsigned long timeout_ms, bool can_sleep)
935 unsigned long timeout = jiffies + msecs_to_jiffies(timeout_ms);
937 /* ignore bits that we don't intend to wait on */
940 while ((ufshcd_readl(hba, reg) & mask) != val) {
942 usleep_range(interval_us, interval_us + 50);
945 if (time_after(jiffies, timeout)) {
946 if ((ufshcd_readl(hba, reg) & mask) != val)
956 * ufshcd_get_intr_mask - Get the interrupt bit mask
957 * @hba - Pointer to adapter instance
959 * Returns interrupt bit mask per version
961 static inline u32 ufshcd_get_intr_mask(struct ufs_hba *hba)
965 switch (hba->ufs_version) {
966 case UFSHCI_VERSION_10:
967 intr_mask = INTERRUPT_MASK_ALL_VER_10;
969 /* allow fall through */
970 case UFSHCI_VERSION_11:
971 case UFSHCI_VERSION_20:
972 intr_mask = INTERRUPT_MASK_ALL_VER_11;
974 /* allow fall through */
975 case UFSHCI_VERSION_21:
977 intr_mask = INTERRUPT_MASK_ALL_VER_21;
980 if (!ufshcd_is_crypto_supported(hba))
981 intr_mask &= ~CRYPTO_ENGINE_FATAL_ERROR;
987 * ufshcd_get_ufs_version - Get the UFS version supported by the HBA
988 * @hba - Pointer to adapter instance
990 * Returns UFSHCI version supported by the controller
992 static inline u32 ufshcd_get_ufs_version(struct ufs_hba *hba)
994 if (hba->quirks & UFSHCD_QUIRK_BROKEN_UFS_HCI_VERSION)
995 return ufshcd_vops_get_ufs_hci_version(hba);
997 return ufshcd_readl(hba, REG_UFS_VERSION);
1001 * ufshcd_is_device_present - Check if any device connected to
1002 * the host controller
1003 * @hba: pointer to adapter instance
1005 * Returns 1 if device present, 0 if no device detected
1007 static inline int ufshcd_is_device_present(struct ufs_hba *hba)
1009 return (ufshcd_readl(hba, REG_CONTROLLER_STATUS) &
1010 DEVICE_PRESENT) ? 1 : 0;
1014 * ufshcd_get_tr_ocs - Get the UTRD Overall Command Status
1015 * @lrb: pointer to local command reference block
1017 * This function is used to get the OCS field from UTRD
1018 * Returns the OCS field in the UTRD
1020 static inline int ufshcd_get_tr_ocs(struct ufshcd_lrb *lrbp)
1022 return le32_to_cpu(lrbp->utr_descriptor_ptr->header.dword_2) & MASK_OCS;
1026 * ufshcd_get_tmr_ocs - Get the UTMRD Overall Command Status
1027 * @task_req_descp: pointer to utp_task_req_desc structure
1029 * This function is used to get the OCS field from UTMRD
1030 * Returns the OCS field in the UTMRD
1033 ufshcd_get_tmr_ocs(struct utp_task_req_desc *task_req_descp)
1035 return le32_to_cpu(task_req_descp->header.dword_2) & MASK_OCS;
1039 * ufshcd_get_tm_free_slot - get a free slot for task management request
1040 * @hba: per adapter instance
1041 * @free_slot: pointer to variable with available slot value
1043 * Get a free tag and lock it until ufshcd_put_tm_slot() is called.
1044 * Returns 0 if free slot is not available, else return 1 with tag value
1047 static bool ufshcd_get_tm_free_slot(struct ufs_hba *hba, int *free_slot)
1056 tag = find_first_zero_bit(&hba->tm_slots_in_use, hba->nutmrs);
1057 if (tag >= hba->nutmrs)
1059 } while (test_and_set_bit_lock(tag, &hba->tm_slots_in_use));
1067 static inline void ufshcd_put_tm_slot(struct ufs_hba *hba, int slot)
1069 clear_bit_unlock(slot, &hba->tm_slots_in_use);
1073 * ufshcd_utrl_clear - Clear a bit in UTRLCLR register
1074 * @hba: per adapter instance
1075 * @pos: position of the bit to be cleared
1077 static inline void ufshcd_utrl_clear(struct ufs_hba *hba, u32 pos)
1079 ufshcd_writel(hba, ~(1 << pos), REG_UTP_TRANSFER_REQ_LIST_CLEAR);
1083 * ufshcd_outstanding_req_clear - Clear a bit in outstanding request field
1084 * @hba: per adapter instance
1085 * @tag: position of the bit to be cleared
1087 static inline void ufshcd_outstanding_req_clear(struct ufs_hba *hba, int tag)
1089 __clear_bit(tag, &hba->outstanding_reqs);
1093 * ufshcd_get_lists_status - Check UCRDY, UTRLRDY and UTMRLRDY
1094 * @reg: Register value of host controller status
1096 * Returns integer, 0 on Success and positive value if failed
1098 static inline int ufshcd_get_lists_status(u32 reg)
1101 * The mask 0xFF is for the following HCS register bits
1109 return ((reg & 0xFF) >> 1) ^ 0x07;
1113 * ufshcd_get_uic_cmd_result - Get the UIC command result
1114 * @hba: Pointer to adapter instance
1116 * This function gets the result of UIC command completion
1117 * Returns 0 on success, non zero value on error
1119 static inline int ufshcd_get_uic_cmd_result(struct ufs_hba *hba)
1121 return ufshcd_readl(hba, REG_UIC_COMMAND_ARG_2) &
1122 MASK_UIC_COMMAND_RESULT;
1126 * ufshcd_get_dme_attr_val - Get the value of attribute returned by UIC command
1127 * @hba: Pointer to adapter instance
1129 * This function gets UIC command argument3
1130 * Returns 0 on success, non zero value on error
1132 static inline u32 ufshcd_get_dme_attr_val(struct ufs_hba *hba)
1134 return ufshcd_readl(hba, REG_UIC_COMMAND_ARG_3);
1138 * ufshcd_get_req_rsp - returns the TR response transaction type
1139 * @ucd_rsp_ptr: pointer to response UPIU
1142 ufshcd_get_req_rsp(struct utp_upiu_rsp *ucd_rsp_ptr)
1144 return be32_to_cpu(ucd_rsp_ptr->header.dword_0) >> 24;
1148 * ufshcd_get_rsp_upiu_result - Get the result from response UPIU
1149 * @ucd_rsp_ptr: pointer to response UPIU
1151 * This function gets the response status and scsi_status from response UPIU
1152 * Returns the response result code.
1155 ufshcd_get_rsp_upiu_result(struct utp_upiu_rsp *ucd_rsp_ptr)
1157 return be32_to_cpu(ucd_rsp_ptr->header.dword_1) & MASK_RSP_UPIU_RESULT;
1161 * ufshcd_get_rsp_upiu_data_seg_len - Get the data segment length
1162 * from response UPIU
1163 * @ucd_rsp_ptr: pointer to response UPIU
1165 * Return the data segment length.
1167 static inline unsigned int
1168 ufshcd_get_rsp_upiu_data_seg_len(struct utp_upiu_rsp *ucd_rsp_ptr)
1170 return be32_to_cpu(ucd_rsp_ptr->header.dword_2) &
1171 MASK_RSP_UPIU_DATA_SEG_LEN;
1175 * ufshcd_is_exception_event - Check if the device raised an exception event
1176 * @ucd_rsp_ptr: pointer to response UPIU
1178 * The function checks if the device raised an exception event indicated in
1179 * the Device Information field of response UPIU.
1181 * Returns true if exception is raised, false otherwise.
1183 static inline bool ufshcd_is_exception_event(struct utp_upiu_rsp *ucd_rsp_ptr)
1185 return be32_to_cpu(ucd_rsp_ptr->header.dword_2) &
1186 MASK_RSP_EXCEPTION_EVENT ? true : false;
1190 * ufshcd_reset_intr_aggr - Reset interrupt aggregation values.
1191 * @hba: per adapter instance
1194 ufshcd_reset_intr_aggr(struct ufs_hba *hba)
1196 ufshcd_writel(hba, INT_AGGR_ENABLE |
1197 INT_AGGR_COUNTER_AND_TIMER_RESET,
1198 REG_UTP_TRANSFER_REQ_INT_AGG_CONTROL);
1202 * ufshcd_config_intr_aggr - Configure interrupt aggregation values.
1203 * @hba: per adapter instance
1204 * @cnt: Interrupt aggregation counter threshold
1205 * @tmout: Interrupt aggregation timeout value
1208 ufshcd_config_intr_aggr(struct ufs_hba *hba, u8 cnt, u8 tmout)
1210 ufshcd_writel(hba, INT_AGGR_ENABLE | INT_AGGR_PARAM_WRITE |
1211 INT_AGGR_COUNTER_THLD_VAL(cnt) |
1212 INT_AGGR_TIMEOUT_VAL(tmout),
1213 REG_UTP_TRANSFER_REQ_INT_AGG_CONTROL);
1217 * ufshcd_disable_intr_aggr - Disables interrupt aggregation.
1218 * @hba: per adapter instance
1220 static inline void ufshcd_disable_intr_aggr(struct ufs_hba *hba)
1222 ufshcd_writel(hba, 0, REG_UTP_TRANSFER_REQ_INT_AGG_CONTROL);
1226 * ufshcd_enable_run_stop_reg - Enable run-stop registers,
1227 * When run-stop registers are set to 1, it indicates the
1228 * host controller that it can process the requests
1229 * @hba: per adapter instance
1231 static void ufshcd_enable_run_stop_reg(struct ufs_hba *hba)
1233 ufshcd_writel(hba, UTP_TASK_REQ_LIST_RUN_STOP_BIT,
1234 REG_UTP_TASK_REQ_LIST_RUN_STOP);
1235 ufshcd_writel(hba, UTP_TRANSFER_REQ_LIST_RUN_STOP_BIT,
1236 REG_UTP_TRANSFER_REQ_LIST_RUN_STOP);
1240 * ufshcd_hba_start - Start controller initialization sequence
1241 * @hba: per adapter instance
1243 static inline void ufshcd_hba_start(struct ufs_hba *hba)
1245 u32 val = CONTROLLER_ENABLE;
1247 if (ufshcd_is_crypto_supported(hba))
1248 val |= CRYPTO_GENERAL_ENABLE;
1249 ufshcd_writel(hba, val, REG_CONTROLLER_ENABLE);
1253 * ufshcd_is_hba_active - Get controller state
1254 * @hba: per adapter instance
1256 * Returns zero if controller is active, 1 otherwise
1258 static inline int ufshcd_is_hba_active(struct ufs_hba *hba)
1260 return (ufshcd_readl(hba, REG_CONTROLLER_ENABLE) & 0x1) ? 0 : 1;
1263 static const char *ufschd_uic_link_state_to_string(
1264 enum uic_link_state state)
1267 case UIC_LINK_OFF_STATE: return "OFF";
1268 case UIC_LINK_ACTIVE_STATE: return "ACTIVE";
1269 case UIC_LINK_HIBERN8_STATE: return "HIBERN8";
1270 default: return "UNKNOWN";
1274 static const char *ufschd_ufs_dev_pwr_mode_to_string(
1275 enum ufs_dev_pwr_mode state)
1278 case UFS_ACTIVE_PWR_MODE: return "ACTIVE";
1279 case UFS_SLEEP_PWR_MODE: return "SLEEP";
1280 case UFS_POWERDOWN_PWR_MODE: return "POWERDOWN";
1281 default: return "UNKNOWN";
1285 u32 ufshcd_get_local_unipro_ver(struct ufs_hba *hba)
1287 /* HCI version 1.0 and 1.1 supports UniPro 1.41 */
1288 if ((hba->ufs_version == UFSHCI_VERSION_10) ||
1289 (hba->ufs_version == UFSHCI_VERSION_11))
1290 return UFS_UNIPRO_VER_1_41;
1292 return UFS_UNIPRO_VER_1_6;
1294 EXPORT_SYMBOL(ufshcd_get_local_unipro_ver);
1296 static bool ufshcd_is_unipro_pa_params_tuning_req(struct ufs_hba *hba)
1299 * If both host and device support UniPro ver1.6 or later, PA layer
1300 * parameters tuning happens during link startup itself.
1302 * We can manually tune PA layer parameters if either host or device
1303 * doesn't support UniPro ver 1.6 or later. But to keep manual tuning
1304 * logic simple, we will only do manual tuning if local unipro version
1305 * doesn't support ver1.6 or later.
1307 if (ufshcd_get_local_unipro_ver(hba) < UFS_UNIPRO_VER_1_6)
1314 * ufshcd_set_clk_freq - set UFS controller clock frequencies
1315 * @hba: per adapter instance
1316 * @scale_up: If True, set max possible frequency othewise set low frequency
1318 * Returns 0 if successful
1319 * Returns < 0 for any other errors
1321 static int ufshcd_set_clk_freq(struct ufs_hba *hba, bool scale_up)
1324 struct ufs_clk_info *clki;
1325 struct list_head *head = &hba->clk_list_head;
1327 if (!head || list_empty(head))
1330 list_for_each_entry(clki, head, list) {
1331 if (!IS_ERR_OR_NULL(clki->clk)) {
1332 if (scale_up && clki->max_freq) {
1333 if (clki->curr_freq == clki->max_freq)
1336 ret = clk_set_rate(clki->clk, clki->max_freq);
1338 dev_err(hba->dev, "%s: %s clk set rate(%dHz) failed, %d\n",
1339 __func__, clki->name,
1340 clki->max_freq, ret);
1343 trace_ufshcd_clk_scaling(dev_name(hba->dev),
1344 "scaled up", clki->name,
1347 clki->curr_freq = clki->max_freq;
1349 } else if (!scale_up && clki->min_freq) {
1350 if (clki->curr_freq == clki->min_freq)
1353 ret = clk_set_rate(clki->clk, clki->min_freq);
1355 dev_err(hba->dev, "%s: %s clk set rate(%dHz) failed, %d\n",
1356 __func__, clki->name,
1357 clki->min_freq, ret);
1360 trace_ufshcd_clk_scaling(dev_name(hba->dev),
1361 "scaled down", clki->name,
1364 clki->curr_freq = clki->min_freq;
1367 dev_dbg(hba->dev, "%s: clk: %s, rate: %lu\n", __func__,
1368 clki->name, clk_get_rate(clki->clk));
1376 * ufshcd_scale_clks - scale up or scale down UFS controller clocks
1377 * @hba: per adapter instance
1378 * @scale_up: True if scaling up and false if scaling down
1380 * Returns 0 if successful
1381 * Returns < 0 for any other errors
1383 static int ufshcd_scale_clks(struct ufs_hba *hba, bool scale_up)
1387 ret = ufshcd_vops_clk_scale_notify(hba, scale_up, PRE_CHANGE);
1391 ret = ufshcd_set_clk_freq(hba, scale_up);
1395 ret = ufshcd_vops_clk_scale_notify(hba, scale_up, POST_CHANGE);
1397 ufshcd_set_clk_freq(hba, !scale_up);
1404 static inline void ufshcd_cancel_gate_work(struct ufs_hba *hba)
1406 hrtimer_cancel(&hba->clk_gating.gate_hrtimer);
1407 cancel_work_sync(&hba->clk_gating.gate_work);
1410 static void ufshcd_ungate_work(struct work_struct *work)
1413 unsigned long flags;
1414 struct ufs_hba *hba = container_of(work, struct ufs_hba,
1415 clk_gating.ungate_work);
1417 ufshcd_cancel_gate_work(hba);
1419 spin_lock_irqsave(hba->host->host_lock, flags);
1420 if (hba->clk_gating.state == CLKS_ON) {
1421 spin_unlock_irqrestore(hba->host->host_lock, flags);
1425 spin_unlock_irqrestore(hba->host->host_lock, flags);
1426 ufshcd_hba_vreg_set_hpm(hba);
1427 ufshcd_enable_clocks(hba);
1429 /* Exit from hibern8 */
1430 if (ufshcd_can_hibern8_during_gating(hba)) {
1431 /* Prevent gating in this path */
1432 hba->clk_gating.is_suspended = true;
1433 if (ufshcd_is_link_hibern8(hba)) {
1434 ret = ufshcd_uic_hibern8_exit(hba);
1436 dev_err(hba->dev, "%s: hibern8 exit failed %d\n",
1439 ufshcd_set_link_active(hba);
1441 hba->clk_gating.is_suspended = false;
1444 ufshcd_scsi_unblock_requests(hba);
1448 * ufshcd_hold - Enable clocks that were gated earlier due to ufshcd_release.
1449 * Also, exit from hibern8 mode and set the link as active.
1450 * @hba: per adapter instance
1451 * @async: This indicates whether caller should ungate clocks asynchronously.
1453 int ufshcd_hold(struct ufs_hba *hba, bool async)
1456 unsigned long flags;
1458 if (!ufshcd_is_clkgating_allowed(hba))
1460 spin_lock_irqsave(hba->host->host_lock, flags);
1461 hba->clk_gating.active_reqs++;
1463 if (ufshcd_eh_in_progress(hba)) {
1464 spin_unlock_irqrestore(hba->host->host_lock, flags);
1469 switch (hba->clk_gating.state) {
1472 * Wait for the ungate work to complete if in progress.
1473 * Though the clocks may be in ON state, the link could
1474 * still be in hibner8 state if hibern8 is allowed
1475 * during clock gating.
1476 * Make sure we exit hibern8 state also in addition to
1479 if (ufshcd_can_hibern8_during_gating(hba) &&
1480 ufshcd_is_link_hibern8(hba)) {
1481 spin_unlock_irqrestore(hba->host->host_lock, flags);
1482 flush_work(&hba->clk_gating.ungate_work);
1483 spin_lock_irqsave(hba->host->host_lock, flags);
1489 * If the timer was active but the callback was not running
1490 * we have nothing to do, just change state and return.
1492 if (hrtimer_try_to_cancel(&hba->clk_gating.gate_hrtimer) == 1) {
1493 hba->clk_gating.state = CLKS_ON;
1494 trace_ufshcd_clk_gating(dev_name(hba->dev),
1495 hba->clk_gating.state);
1499 * If we are here, it means gating work is either done or
1500 * currently running. Hence, fall through to cancel gating
1501 * work and to enable clocks.
1504 __ufshcd_scsi_block_requests(hba);
1505 hba->clk_gating.state = REQ_CLKS_ON;
1506 trace_ufshcd_clk_gating(dev_name(hba->dev),
1507 hba->clk_gating.state);
1508 queue_work(hba->clk_gating.clk_gating_workq,
1509 &hba->clk_gating.ungate_work);
1511 * fall through to check if we should wait for this
1512 * work to be done or not.
1517 hba->clk_gating.active_reqs--;
1521 spin_unlock_irqrestore(hba->host->host_lock, flags);
1522 flush_work(&hba->clk_gating.ungate_work);
1523 /* Make sure state is CLKS_ON before returning */
1524 spin_lock_irqsave(hba->host->host_lock, flags);
1527 dev_err(hba->dev, "%s: clk gating is in invalid state %d\n",
1528 __func__, hba->clk_gating.state);
1531 spin_unlock_irqrestore(hba->host->host_lock, flags);
1533 hba->ufs_stats.clk_hold.ts = ktime_get();
1536 EXPORT_SYMBOL_GPL(ufshcd_hold);
1538 static void ufshcd_gate_work(struct work_struct *work)
1540 struct ufs_hba *hba = container_of(work, struct ufs_hba,
1541 clk_gating.gate_work);
1542 unsigned long flags;
1544 spin_lock_irqsave(hba->host->host_lock, flags);
1546 * In case you are here to cancel this work the gating state
1547 * would be marked as REQ_CLKS_ON. In this case save time by
1548 * skipping the gating work and exit after changing the clock
1551 if (hba->clk_gating.is_suspended ||
1552 (hba->clk_gating.state != REQ_CLKS_OFF)) {
1553 hba->clk_gating.state = CLKS_ON;
1554 trace_ufshcd_clk_gating(dev_name(hba->dev),
1555 hba->clk_gating.state);
1559 if (hba->clk_gating.active_reqs
1560 || hba->ufshcd_state != UFSHCD_STATE_OPERATIONAL
1561 || hba->lrb_in_use || hba->outstanding_tasks
1562 || hba->active_uic_cmd || hba->uic_async_done)
1565 spin_unlock_irqrestore(hba->host->host_lock, flags);
1567 if (ufshcd_is_hibern8_on_idle_allowed(hba) &&
1568 hba->hibern8_on_idle.is_enabled)
1570 * Hibern8 enter work (on Idle) needs clocks to be ON hence
1571 * make sure that it is flushed before turning off the clocks.
1573 flush_delayed_work(&hba->hibern8_on_idle.enter_work);
1575 /* put the link into hibern8 mode before turning off clocks */
1576 if (ufshcd_can_hibern8_during_gating(hba)) {
1577 if (ufshcd_uic_hibern8_enter(hba)) {
1578 hba->clk_gating.state = CLKS_ON;
1579 trace_ufshcd_clk_gating(dev_name(hba->dev),
1580 hba->clk_gating.state);
1583 ufshcd_set_link_hibern8(hba);
1587 * If auto hibern8 is supported then the link will already
1588 * be in hibern8 state and the ref clock can be gated.
1590 if ((ufshcd_is_auto_hibern8_supported(hba) ||
1591 !ufshcd_is_link_active(hba)) && !hba->no_ref_clk_gating)
1592 ufshcd_disable_clocks(hba, true);
1594 /* If link is active, device ref_clk can't be switched off */
1595 ufshcd_disable_clocks_skip_ref_clk(hba, true);
1597 /* Put the host controller in low power mode if possible */
1598 ufshcd_hba_vreg_set_lpm(hba);
1601 * In case you are here to cancel this work the gating state
1602 * would be marked as REQ_CLKS_ON. In this case keep the state
1603 * as REQ_CLKS_ON which would anyway imply that clocks are off
1604 * and a request to turn them on is pending. By doing this way,
1605 * we keep the state machine in tact and this would ultimately
1606 * prevent from doing cancel work multiple times when there are
1607 * new requests arriving before the current cancel work is done.
1609 spin_lock_irqsave(hba->host->host_lock, flags);
1610 if (hba->clk_gating.state == REQ_CLKS_OFF) {
1611 hba->clk_gating.state = CLKS_OFF;
1612 trace_ufshcd_clk_gating(dev_name(hba->dev),
1613 hba->clk_gating.state);
1616 spin_unlock_irqrestore(hba->host->host_lock, flags);
1621 /* host lock must be held before calling this variant */
1622 static void __ufshcd_release(struct ufs_hba *hba, bool no_sched)
1624 if (!ufshcd_is_clkgating_allowed(hba))
1627 hba->clk_gating.active_reqs--;
1629 if (hba->clk_gating.active_reqs || hba->clk_gating.is_suspended
1630 || hba->ufshcd_state != UFSHCD_STATE_OPERATIONAL
1631 || hba->lrb_in_use || hba->outstanding_tasks
1632 || hba->active_uic_cmd || hba->uic_async_done
1633 || ufshcd_eh_in_progress(hba) || no_sched)
1636 hba->clk_gating.state = REQ_CLKS_OFF;
1637 trace_ufshcd_clk_gating(dev_name(hba->dev), hba->clk_gating.state);
1638 hba->ufs_stats.clk_rel.ts = ktime_get();
1640 hrtimer_start(&hba->clk_gating.gate_hrtimer,
1641 ms_to_ktime(hba->clk_gating.delay_ms),
1645 void ufshcd_release(struct ufs_hba *hba, bool no_sched)
1647 unsigned long flags;
1649 spin_lock_irqsave(hba->host->host_lock, flags);
1650 __ufshcd_release(hba, no_sched);
1651 spin_unlock_irqrestore(hba->host->host_lock, flags);
1653 EXPORT_SYMBOL_GPL(ufshcd_release);
1655 static ssize_t ufshcd_clkgate_delay_show(struct device *dev,
1656 struct device_attribute *attr, char *buf)
1658 struct ufs_hba *hba = dev_get_drvdata(dev);
1660 return snprintf(buf, PAGE_SIZE, "%lu\n", hba->clk_gating.delay_ms);
1663 static ssize_t ufshcd_clkgate_delay_store(struct device *dev,
1664 struct device_attribute *attr, const char *buf, size_t count)
1666 struct ufs_hba *hba = dev_get_drvdata(dev);
1667 unsigned long flags, value;
1669 if (kstrtoul(buf, 0, &value))
1672 spin_lock_irqsave(hba->host->host_lock, flags);
1673 hba->clk_gating.delay_ms = value;
1674 spin_unlock_irqrestore(hba->host->host_lock, flags);
1678 static ssize_t ufshcd_clkgate_delay_pwr_save_show(struct device *dev,
1679 struct device_attribute *attr, char *buf)
1681 struct ufs_hba *hba = dev_get_drvdata(dev);
1683 return snprintf(buf, PAGE_SIZE, "%lu\n",
1684 hba->clk_gating.delay_ms_pwr_save);
1687 static ssize_t ufshcd_clkgate_delay_pwr_save_store(struct device *dev,
1688 struct device_attribute *attr, const char *buf, size_t count)
1690 struct ufs_hba *hba = dev_get_drvdata(dev);
1691 unsigned long flags, value;
1693 if (kstrtoul(buf, 0, &value))
1696 spin_lock_irqsave(hba->host->host_lock, flags);
1698 hba->clk_gating.delay_ms_pwr_save = value;
1699 if (ufshcd_is_clkscaling_supported(hba) &&
1700 !hba->clk_scaling.is_scaled_up)
1701 hba->clk_gating.delay_ms = hba->clk_gating.delay_ms_pwr_save;
1703 spin_unlock_irqrestore(hba->host->host_lock, flags);
1707 static ssize_t ufshcd_clkgate_delay_perf_show(struct device *dev,
1708 struct device_attribute *attr, char *buf)
1710 struct ufs_hba *hba = dev_get_drvdata(dev);
1712 return snprintf(buf, PAGE_SIZE, "%lu\n", hba->clk_gating.delay_ms_perf);
1715 static ssize_t ufshcd_clkgate_delay_perf_store(struct device *dev,
1716 struct device_attribute *attr, const char *buf, size_t count)
1718 struct ufs_hba *hba = dev_get_drvdata(dev);
1719 unsigned long flags, value;
1721 if (kstrtoul(buf, 0, &value))
1724 spin_lock_irqsave(hba->host->host_lock, flags);
1726 hba->clk_gating.delay_ms_perf = value;
1727 if (ufshcd_is_clkscaling_supported(hba) &&
1728 hba->clk_scaling.is_scaled_up)
1729 hba->clk_gating.delay_ms = hba->clk_gating.delay_ms_perf;
1731 spin_unlock_irqrestore(hba->host->host_lock, flags);
1735 static ssize_t ufshcd_clkgate_enable_show(struct device *dev,
1736 struct device_attribute *attr, char *buf)
1738 struct ufs_hba *hba = dev_get_drvdata(dev);
1740 return snprintf(buf, PAGE_SIZE, "%d\n", hba->clk_gating.is_enabled);
1743 static ssize_t ufshcd_clkgate_enable_store(struct device *dev,
1744 struct device_attribute *attr, const char *buf, size_t count)
1746 struct ufs_hba *hba = dev_get_drvdata(dev);
1747 unsigned long flags;
1750 if (kstrtou32(buf, 0, &value))
1754 if (value == hba->clk_gating.is_enabled)
1758 ufshcd_release(hba, false);
1760 spin_lock_irqsave(hba->host->host_lock, flags);
1761 hba->clk_gating.active_reqs++;
1762 spin_unlock_irqrestore(hba->host->host_lock, flags);
1765 hba->clk_gating.is_enabled = value;
1770 static enum hrtimer_restart ufshcd_clkgate_hrtimer_handler(
1771 struct hrtimer *timer)
1773 struct ufs_hba *hba = container_of(timer, struct ufs_hba,
1774 clk_gating.gate_hrtimer);
1776 queue_work(hba->clk_gating.clk_gating_workq,
1777 &hba->clk_gating.gate_work);
1779 return HRTIMER_NORESTART;
1782 static void ufshcd_init_clk_gating(struct ufs_hba *hba)
1784 struct ufs_clk_gating *gating = &hba->clk_gating;
1785 char wq_name[sizeof("ufs_clk_gating_00")];
1787 hba->clk_gating.state = CLKS_ON;
1789 if (!ufshcd_is_clkgating_allowed(hba))
1793 * Disable hibern8 during clk gating if
1794 * auto hibern8 is supported
1796 if (ufshcd_is_auto_hibern8_supported(hba))
1797 hba->caps &= ~UFSHCD_CAP_HIBERN8_WITH_CLK_GATING;
1799 INIT_WORK(&gating->gate_work, ufshcd_gate_work);
1800 INIT_WORK(&gating->ungate_work, ufshcd_ungate_work);
1802 * Clock gating work must be executed only after auto hibern8
1803 * timeout has expired in the hardware or after aggressive
1804 * hibern8 on idle software timeout. Using jiffy based low
1805 * resolution delayed work is not reliable to guarantee this,
1806 * hence use a high resolution timer to make sure we schedule
1807 * the gate work precisely more than hibern8 timeout.
1809 * Always make sure gating->delay_ms > hibern8_on_idle->delay_ms
1811 hrtimer_init(&gating->gate_hrtimer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
1812 gating->gate_hrtimer.function = ufshcd_clkgate_hrtimer_handler;
1814 snprintf(wq_name, ARRAY_SIZE(wq_name), "ufs_clk_gating_%d",
1815 hba->host->host_no);
1816 hba->clk_gating.clk_gating_workq =
1817 create_singlethread_workqueue(wq_name);
1819 gating->is_enabled = true;
1821 gating->delay_ms_pwr_save = UFSHCD_CLK_GATING_DELAY_MS_PWR_SAVE;
1822 gating->delay_ms_perf = UFSHCD_CLK_GATING_DELAY_MS_PERF;
1824 /* start with performance mode */
1825 gating->delay_ms = gating->delay_ms_perf;
1827 if (!ufshcd_is_clkscaling_supported(hba))
1828 goto scaling_not_supported;
1830 gating->delay_pwr_save_attr.show = ufshcd_clkgate_delay_pwr_save_show;
1831 gating->delay_pwr_save_attr.store = ufshcd_clkgate_delay_pwr_save_store;
1832 sysfs_attr_init(&gating->delay_pwr_save_attr.attr);
1833 gating->delay_pwr_save_attr.attr.name = "clkgate_delay_ms_pwr_save";
1834 gating->delay_pwr_save_attr.attr.mode = S_IRUGO | S_IWUSR;
1835 if (device_create_file(hba->dev, &gating->delay_pwr_save_attr))
1836 dev_err(hba->dev, "Failed to create sysfs for clkgate_delay_ms_pwr_save\n");
1838 gating->delay_perf_attr.show = ufshcd_clkgate_delay_perf_show;
1839 gating->delay_perf_attr.store = ufshcd_clkgate_delay_perf_store;
1840 sysfs_attr_init(&gating->delay_perf_attr.attr);
1841 gating->delay_perf_attr.attr.name = "clkgate_delay_ms_perf";
1842 gating->delay_perf_attr.attr.mode = S_IRUGO | S_IWUSR;
1843 if (device_create_file(hba->dev, &gating->delay_perf_attr))
1844 dev_err(hba->dev, "Failed to create sysfs for clkgate_delay_ms_perf\n");
1846 goto add_clkgate_enable;
1848 scaling_not_supported:
1849 hba->clk_gating.delay_attr.show = ufshcd_clkgate_delay_show;
1850 hba->clk_gating.delay_attr.store = ufshcd_clkgate_delay_store;
1851 sysfs_attr_init(&hba->clk_gating.delay_attr.attr);
1852 hba->clk_gating.delay_attr.attr.name = "clkgate_delay_ms";
1853 hba->clk_gating.delay_attr.attr.mode = S_IRUGO | S_IWUSR;
1854 if (device_create_file(hba->dev, &hba->clk_gating.delay_attr))
1855 dev_err(hba->dev, "Failed to create sysfs for clkgate_delay\n");
1858 gating->enable_attr.show = ufshcd_clkgate_enable_show;
1859 gating->enable_attr.store = ufshcd_clkgate_enable_store;
1860 sysfs_attr_init(&gating->enable_attr.attr);
1861 gating->enable_attr.attr.name = "clkgate_enable";
1862 gating->enable_attr.attr.mode = S_IRUGO | S_IWUSR;
1863 if (device_create_file(hba->dev, &gating->enable_attr))
1864 dev_err(hba->dev, "Failed to create sysfs for clkgate_enable\n");
1867 static void ufshcd_exit_clk_gating(struct ufs_hba *hba)
1869 if (!ufshcd_is_clkgating_allowed(hba))
1871 if (ufshcd_is_clkscaling_supported(hba)) {
1872 device_remove_file(hba->dev,
1873 &hba->clk_gating.delay_pwr_save_attr);
1874 device_remove_file(hba->dev, &hba->clk_gating.delay_perf_attr);
1876 device_remove_file(hba->dev, &hba->clk_gating.delay_attr);
1878 device_remove_file(hba->dev, &hba->clk_gating.enable_attr);
1879 ufshcd_cancel_gate_work(hba);
1880 cancel_work_sync(&hba->clk_gating.ungate_work);
1881 destroy_workqueue(hba->clk_gating.clk_gating_workq);
1884 static void ufshcd_set_auto_hibern8_timer(struct ufs_hba *hba, u32 delay)
1886 ufshcd_rmwl(hba, AUTO_HIBERN8_TIMER_SCALE_MASK |
1887 AUTO_HIBERN8_IDLE_TIMER_MASK,
1888 AUTO_HIBERN8_TIMER_SCALE_1_MS | delay,
1889 REG_AUTO_HIBERN8_IDLE_TIMER);
1890 /* Make sure the timer gets applied before further operations */
1895 * ufshcd_hibern8_hold - Make sure that link is not in hibern8.
1897 * @hba: per adapter instance
1898 * @async: This indicates whether caller wants to exit hibern8 asynchronously.
1900 * Exit from hibern8 mode and set the link as active.
1902 * Return 0 on success, non-zero on failure.
1904 static int ufshcd_hibern8_hold(struct ufs_hba *hba, bool async)
1907 unsigned long flags;
1909 if (!ufshcd_is_hibern8_on_idle_allowed(hba))
1912 spin_lock_irqsave(hba->host->host_lock, flags);
1913 hba->hibern8_on_idle.active_reqs++;
1915 if (ufshcd_eh_in_progress(hba)) {
1916 spin_unlock_irqrestore(hba->host->host_lock, flags);
1921 switch (hba->hibern8_on_idle.state) {
1922 case HIBERN8_EXITED:
1924 case REQ_HIBERN8_ENTER:
1925 if (cancel_delayed_work(&hba->hibern8_on_idle.enter_work)) {
1926 hba->hibern8_on_idle.state = HIBERN8_EXITED;
1927 trace_ufshcd_hibern8_on_idle(dev_name(hba->dev),
1928 hba->hibern8_on_idle.state);
1932 * If we here, it means Hibern8 enter work is either done or
1933 * currently running. Hence, fall through to cancel hibern8
1934 * work and exit hibern8.
1936 case HIBERN8_ENTERED:
1937 __ufshcd_scsi_block_requests(hba);
1938 hba->hibern8_on_idle.state = REQ_HIBERN8_EXIT;
1939 trace_ufshcd_hibern8_on_idle(dev_name(hba->dev),
1940 hba->hibern8_on_idle.state);
1941 schedule_work(&hba->hibern8_on_idle.exit_work);
1943 * fall through to check if we should wait for this
1944 * work to be done or not.
1946 case REQ_HIBERN8_EXIT:
1949 hba->hibern8_on_idle.active_reqs--;
1952 spin_unlock_irqrestore(hba->host->host_lock, flags);
1953 flush_work(&hba->hibern8_on_idle.exit_work);
1954 /* Make sure state is HIBERN8_EXITED before returning */
1955 spin_lock_irqsave(hba->host->host_lock, flags);
1959 dev_err(hba->dev, "%s: H8 is in invalid state %d\n",
1960 __func__, hba->hibern8_on_idle.state);
1963 spin_unlock_irqrestore(hba->host->host_lock, flags);
1968 /* host lock must be held before calling this variant */
1969 static void __ufshcd_hibern8_release(struct ufs_hba *hba, bool no_sched)
1971 unsigned long delay_in_jiffies;
1973 if (!ufshcd_is_hibern8_on_idle_allowed(hba))
1976 hba->hibern8_on_idle.active_reqs--;
1977 BUG_ON(hba->hibern8_on_idle.active_reqs < 0);
1979 if (hba->hibern8_on_idle.active_reqs
1980 || hba->hibern8_on_idle.is_suspended
1981 || hba->ufshcd_state != UFSHCD_STATE_OPERATIONAL
1982 || hba->lrb_in_use || hba->outstanding_tasks
1983 || hba->active_uic_cmd || hba->uic_async_done
1984 || ufshcd_eh_in_progress(hba) || no_sched)
1987 hba->hibern8_on_idle.state = REQ_HIBERN8_ENTER;
1988 trace_ufshcd_hibern8_on_idle(dev_name(hba->dev),
1989 hba->hibern8_on_idle.state);
1991 * Scheduling the delayed work after 1 jiffies will make the work to
1992 * get schedule any time from 0ms to 1000/HZ ms which is not desirable
1993 * for hibern8 enter work as it may impact the performance if it gets
1994 * scheduled almost immediately. Hence make sure that hibern8 enter
1995 * work gets scheduled atleast after 2 jiffies (any time between
1996 * 1000/HZ ms to 2000/HZ ms).
1998 delay_in_jiffies = msecs_to_jiffies(hba->hibern8_on_idle.delay_ms);
1999 if (delay_in_jiffies == 1)
2002 schedule_delayed_work(&hba->hibern8_on_idle.enter_work,
2006 static void ufshcd_hibern8_release(struct ufs_hba *hba, bool no_sched)
2008 unsigned long flags;
2010 spin_lock_irqsave(hba->host->host_lock, flags);
2011 __ufshcd_hibern8_release(hba, no_sched);
2012 spin_unlock_irqrestore(hba->host->host_lock, flags);
2015 static void ufshcd_hibern8_enter_work(struct work_struct *work)
2017 struct ufs_hba *hba = container_of(work, struct ufs_hba,
2018 hibern8_on_idle.enter_work.work);
2019 unsigned long flags;
2021 spin_lock_irqsave(hba->host->host_lock, flags);
2022 if (hba->hibern8_on_idle.is_suspended) {
2023 hba->hibern8_on_idle.state = HIBERN8_EXITED;
2024 trace_ufshcd_hibern8_on_idle(dev_name(hba->dev),
2025 hba->hibern8_on_idle.state);
2029 if (hba->hibern8_on_idle.active_reqs
2030 || hba->ufshcd_state != UFSHCD_STATE_OPERATIONAL
2031 || hba->lrb_in_use || hba->outstanding_tasks
2032 || hba->active_uic_cmd || hba->uic_async_done)
2035 spin_unlock_irqrestore(hba->host->host_lock, flags);
2037 if (ufshcd_is_link_active(hba) && ufshcd_uic_hibern8_enter(hba)) {
2039 hba->hibern8_on_idle.state = HIBERN8_EXITED;
2040 trace_ufshcd_hibern8_on_idle(dev_name(hba->dev),
2041 hba->hibern8_on_idle.state);
2044 ufshcd_set_link_hibern8(hba);
2047 * In case you are here to cancel this work the hibern8_on_idle.state
2048 * would be marked as REQ_HIBERN8_EXIT. In this case keep the state
2049 * as REQ_HIBERN8_EXIT which would anyway imply that we are in hibern8
2050 * and a request to exit from it is pending. By doing this way,
2051 * we keep the state machine in tact and this would ultimately
2052 * prevent from doing cancel work multiple times when there are
2053 * new requests arriving before the current cancel work is done.
2055 spin_lock_irqsave(hba->host->host_lock, flags);
2056 if (hba->hibern8_on_idle.state == REQ_HIBERN8_ENTER) {
2057 hba->hibern8_on_idle.state = HIBERN8_ENTERED;
2058 trace_ufshcd_hibern8_on_idle(dev_name(hba->dev),
2059 hba->hibern8_on_idle.state);
2062 spin_unlock_irqrestore(hba->host->host_lock, flags);
2067 static void __ufshcd_set_auto_hibern8_timer(struct ufs_hba *hba,
2068 unsigned long delay_ms)
2070 pm_runtime_get_sync(hba->dev);
2071 ufshcd_hold_all(hba);
2072 ufshcd_scsi_block_requests(hba);
2073 down_write(&hba->lock);
2074 /* wait for all the outstanding requests to finish */
2075 ufshcd_wait_for_doorbell_clr(hba, U64_MAX);
2076 ufshcd_set_auto_hibern8_timer(hba, delay_ms);
2077 up_write(&hba->lock);
2078 ufshcd_scsi_unblock_requests(hba);
2079 ufshcd_release_all(hba);
2080 pm_runtime_put_sync(hba->dev);
2083 static void ufshcd_hibern8_exit_work(struct work_struct *work)
2086 unsigned long flags;
2087 struct ufs_hba *hba = container_of(work, struct ufs_hba,
2088 hibern8_on_idle.exit_work);
2090 cancel_delayed_work_sync(&hba->hibern8_on_idle.enter_work);
2092 spin_lock_irqsave(hba->host->host_lock, flags);
2093 if ((hba->hibern8_on_idle.state == HIBERN8_EXITED)
2094 || ufshcd_is_link_active(hba)) {
2095 hba->hibern8_on_idle.state = HIBERN8_EXITED;
2096 spin_unlock_irqrestore(hba->host->host_lock, flags);
2099 spin_unlock_irqrestore(hba->host->host_lock, flags);
2101 /* Exit from hibern8 */
2102 if (ufshcd_is_link_hibern8(hba)) {
2103 hba->ufs_stats.clk_hold.ctx = H8_EXIT_WORK;
2104 ufshcd_hold(hba, false);
2105 ret = ufshcd_uic_hibern8_exit(hba);
2106 hba->ufs_stats.clk_rel.ctx = H8_EXIT_WORK;
2107 ufshcd_release(hba, false);
2109 spin_lock_irqsave(hba->host->host_lock, flags);
2110 ufshcd_set_link_active(hba);
2111 hba->hibern8_on_idle.state = HIBERN8_EXITED;
2112 trace_ufshcd_hibern8_on_idle(dev_name(hba->dev),
2113 hba->hibern8_on_idle.state);
2114 spin_unlock_irqrestore(hba->host->host_lock, flags);
2118 ufshcd_scsi_unblock_requests(hba);
2121 static ssize_t ufshcd_hibern8_on_idle_delay_show(struct device *dev,
2122 struct device_attribute *attr, char *buf)
2124 struct ufs_hba *hba = dev_get_drvdata(dev);
2126 return snprintf(buf, PAGE_SIZE, "%lu\n", hba->hibern8_on_idle.delay_ms);
2129 static ssize_t ufshcd_hibern8_on_idle_delay_store(struct device *dev,
2130 struct device_attribute *attr, const char *buf, size_t count)
2132 struct ufs_hba *hba = dev_get_drvdata(dev);
2133 unsigned long flags, value;
2136 if (kstrtoul(buf, 0, &value))
2139 spin_lock_irqsave(hba->host->host_lock, flags);
2140 if (hba->hibern8_on_idle.delay_ms == value)
2143 if (value >= hba->clk_gating.delay_ms_pwr_save ||
2144 value >= hba->clk_gating.delay_ms_perf) {
2145 dev_err(hba->dev, "hibern8_on_idle_delay (%lu) can not be >= to clkgate_delay_ms_pwr_save (%lu) and clkgate_delay_ms_perf (%lu)\n",
2146 value, hba->clk_gating.delay_ms_pwr_save,
2147 hba->clk_gating.delay_ms_perf);
2148 spin_unlock_irqrestore(hba->host->host_lock, flags);
2152 hba->hibern8_on_idle.delay_ms = value;
2153 spin_unlock_irqrestore(hba->host->host_lock, flags);
2155 /* Update auto hibern8 timer value if supported */
2156 if (change && ufshcd_is_auto_hibern8_supported(hba) &&
2157 hba->hibern8_on_idle.is_enabled)
2158 __ufshcd_set_auto_hibern8_timer(hba,
2159 hba->hibern8_on_idle.delay_ms);
2164 static ssize_t ufshcd_hibern8_on_idle_enable_show(struct device *dev,
2165 struct device_attribute *attr, char *buf)
2167 struct ufs_hba *hba = dev_get_drvdata(dev);
2169 return snprintf(buf, PAGE_SIZE, "%d\n",
2170 hba->hibern8_on_idle.is_enabled);
2173 static ssize_t ufshcd_hibern8_on_idle_enable_store(struct device *dev,
2174 struct device_attribute *attr, const char *buf, size_t count)
2176 struct ufs_hba *hba = dev_get_drvdata(dev);
2177 unsigned long flags;
2180 if (kstrtou32(buf, 0, &value))
2184 if (value == hba->hibern8_on_idle.is_enabled)
2187 /* Update auto hibern8 timer value if supported */
2188 if (ufshcd_is_auto_hibern8_supported(hba)) {
2189 __ufshcd_set_auto_hibern8_timer(hba,
2190 value ? hba->hibern8_on_idle.delay_ms : value);
2196 * As clock gating work would wait for the hibern8 enter work
2197 * to finish, clocks would remain on during hibern8 enter work.
2199 ufshcd_hold(hba, false);
2200 ufshcd_release_all(hba);
2202 spin_lock_irqsave(hba->host->host_lock, flags);
2203 hba->hibern8_on_idle.active_reqs++;
2204 spin_unlock_irqrestore(hba->host->host_lock, flags);
2208 hba->hibern8_on_idle.is_enabled = value;
2213 static void ufshcd_init_hibern8_on_idle(struct ufs_hba *hba)
2215 /* initialize the state variable here */
2216 hba->hibern8_on_idle.state = HIBERN8_EXITED;
2218 if (!ufshcd_is_hibern8_on_idle_allowed(hba) &&
2219 !ufshcd_is_auto_hibern8_supported(hba))
2222 if (ufshcd_is_auto_hibern8_supported(hba)) {
2223 hba->hibern8_on_idle.delay_ms = 1;
2224 hba->hibern8_on_idle.state = AUTO_HIBERN8;
2226 * Disable SW hibern8 enter on idle in case
2227 * auto hibern8 is supported
2229 hba->caps &= ~UFSHCD_CAP_HIBERN8_ENTER_ON_IDLE;
2231 hba->hibern8_on_idle.delay_ms = 10;
2232 INIT_DELAYED_WORK(&hba->hibern8_on_idle.enter_work,
2233 ufshcd_hibern8_enter_work);
2234 INIT_WORK(&hba->hibern8_on_idle.exit_work,
2235 ufshcd_hibern8_exit_work);
2238 hba->hibern8_on_idle.is_enabled = true;
2240 hba->hibern8_on_idle.delay_attr.show =
2241 ufshcd_hibern8_on_idle_delay_show;
2242 hba->hibern8_on_idle.delay_attr.store =
2243 ufshcd_hibern8_on_idle_delay_store;
2244 sysfs_attr_init(&hba->hibern8_on_idle.delay_attr.attr);
2245 hba->hibern8_on_idle.delay_attr.attr.name = "hibern8_on_idle_delay_ms";
2246 hba->hibern8_on_idle.delay_attr.attr.mode = S_IRUGO | S_IWUSR;
2247 if (device_create_file(hba->dev, &hba->hibern8_on_idle.delay_attr))
2248 dev_err(hba->dev, "Failed to create sysfs for hibern8_on_idle_delay\n");
2250 hba->hibern8_on_idle.enable_attr.show =
2251 ufshcd_hibern8_on_idle_enable_show;
2252 hba->hibern8_on_idle.enable_attr.store =
2253 ufshcd_hibern8_on_idle_enable_store;
2254 sysfs_attr_init(&hba->hibern8_on_idle.enable_attr.attr);
2255 hba->hibern8_on_idle.enable_attr.attr.name = "hibern8_on_idle_enable";
2256 hba->hibern8_on_idle.enable_attr.attr.mode = S_IRUGO | S_IWUSR;
2257 if (device_create_file(hba->dev, &hba->hibern8_on_idle.enable_attr))
2258 dev_err(hba->dev, "Failed to create sysfs for hibern8_on_idle_enable\n");
2261 static void ufshcd_exit_hibern8_on_idle(struct ufs_hba *hba)
2263 if (!ufshcd_is_hibern8_on_idle_allowed(hba) &&
2264 !ufshcd_is_auto_hibern8_supported(hba))
2266 device_remove_file(hba->dev, &hba->hibern8_on_idle.delay_attr);
2267 device_remove_file(hba->dev, &hba->hibern8_on_idle.enable_attr);
2270 static void ufshcd_hold_all(struct ufs_hba *hba)
2272 ufshcd_hold(hba, false);
2273 ufshcd_hibern8_hold(hba, false);
2276 static void ufshcd_release_all(struct ufs_hba *hba)
2278 ufshcd_hibern8_release(hba, false);
2279 ufshcd_release(hba, false);
2282 /* Must be called with host lock acquired */
2283 static void ufshcd_clk_scaling_start_busy(struct ufs_hba *hba)
2285 bool queue_resume_work = false;
2287 if (!ufshcd_is_clkscaling_supported(hba))
2290 if (!hba->clk_scaling.active_reqs++)
2291 queue_resume_work = true;
2293 if (!hba->clk_scaling.is_allowed || hba->pm_op_in_progress)
2296 if (queue_resume_work)
2297 queue_work(hba->clk_scaling.workq,
2298 &hba->clk_scaling.resume_work);
2300 if (!hba->clk_scaling.window_start_t) {
2301 hba->clk_scaling.window_start_t = jiffies;
2302 hba->clk_scaling.tot_busy_t = 0;
2303 hba->clk_scaling.is_busy_started = false;
2306 if (!hba->clk_scaling.is_busy_started) {
2307 hba->clk_scaling.busy_start_t = ktime_get();
2308 hba->clk_scaling.is_busy_started = true;
2312 static void ufshcd_clk_scaling_update_busy(struct ufs_hba *hba)
2314 struct ufs_clk_scaling *scaling = &hba->clk_scaling;
2316 if (!ufshcd_is_clkscaling_supported(hba))
2319 if (!hba->outstanding_reqs && scaling->is_busy_started) {
2320 scaling->tot_busy_t += ktime_to_us(ktime_sub(ktime_get(),
2321 scaling->busy_start_t));
2322 scaling->busy_start_t = ktime_set(0, 0);
2323 scaling->is_busy_started = false;
2328 * ufshcd_send_command - Send SCSI or device management commands
2329 * @hba: per adapter instance
2330 * @task_tag: Task tag of the command
2333 int ufshcd_send_command(struct ufs_hba *hba, unsigned int task_tag)
2337 hba->lrb[task_tag].issue_time_stamp = ktime_get();
2338 hba->lrb[task_tag].complete_time_stamp = ktime_set(0, 0);
2339 ufshcd_clk_scaling_start_busy(hba);
2340 __set_bit(task_tag, &hba->outstanding_reqs);
2341 ufshcd_writel(hba, 1 << task_tag, REG_UTP_TRANSFER_REQ_DOOR_BELL);
2342 /* Make sure that doorbell is committed immediately */
2344 ufshcd_cond_add_cmd_trace(hba, task_tag, "send");
2345 ufshcd_update_tag_stats(hba, task_tag);
2350 * ufshcd_copy_sense_data - Copy sense data in case of check condition
2351 * @lrb - pointer to local reference block
2353 static inline void ufshcd_copy_sense_data(struct ufshcd_lrb *lrbp)
2356 if (lrbp->sense_buffer &&
2357 ufshcd_get_rsp_upiu_data_seg_len(lrbp->ucd_rsp_ptr)) {
2360 len = be16_to_cpu(lrbp->ucd_rsp_ptr->sr.sense_data_len);
2361 len_to_copy = min_t(int, RESPONSE_UPIU_SENSE_DATA_LENGTH, len);
2363 memcpy(lrbp->sense_buffer,
2364 lrbp->ucd_rsp_ptr->sr.sense_data,
2365 min_t(int, len_to_copy, UFSHCD_REQ_SENSE_SIZE));
2370 * ufshcd_copy_query_response() - Copy the Query Response and the data
2372 * @hba: per adapter instance
2373 * @lrb - pointer to local reference block
2376 int ufshcd_copy_query_response(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
2378 struct ufs_query_res *query_res = &hba->dev_cmd.query.response;
2380 memcpy(&query_res->upiu_res, &lrbp->ucd_rsp_ptr->qr, QUERY_OSF_SIZE);
2382 /* Get the descriptor */
2383 if (lrbp->ucd_rsp_ptr->qr.opcode == UPIU_QUERY_OPCODE_READ_DESC) {
2384 u8 *descp = (u8 *)lrbp->ucd_rsp_ptr +
2385 GENERAL_UPIU_REQUEST_SIZE;
2389 /* data segment length */
2390 resp_len = be32_to_cpu(lrbp->ucd_rsp_ptr->header.dword_2) &
2391 MASK_QUERY_DATA_SEG_LEN;
2392 buf_len = be16_to_cpu(
2393 hba->dev_cmd.query.request.upiu_req.length);
2394 if (likely(buf_len >= resp_len)) {
2395 memcpy(hba->dev_cmd.query.descriptor, descp, resp_len);
2398 "%s: Response size is bigger than buffer",
2408 * ufshcd_hba_capabilities - Read controller capabilities
2409 * @hba: per adapter instance
2411 static inline void ufshcd_hba_capabilities(struct ufs_hba *hba)
2413 hba->capabilities = ufshcd_readl(hba, REG_CONTROLLER_CAPABILITIES);
2415 /* nutrs and nutmrs are 0 based values */
2416 hba->nutrs = (hba->capabilities & MASK_TRANSFER_REQUESTS_SLOTS) + 1;
2418 ((hba->capabilities & MASK_TASK_MANAGEMENT_REQUEST_SLOTS) >> 16) + 1;
2422 * ufshcd_ready_for_uic_cmd - Check if controller is ready
2423 * to accept UIC commands
2424 * @hba: per adapter instance
2425 * Return true on success, else false
2427 static inline bool ufshcd_ready_for_uic_cmd(struct ufs_hba *hba)
2429 if (ufshcd_readl(hba, REG_CONTROLLER_STATUS) & UIC_COMMAND_READY)
2436 * ufshcd_get_upmcrs - Get the power mode change request status
2437 * @hba: Pointer to adapter instance
2439 * This function gets the UPMCRS field of HCS register
2440 * Returns value of UPMCRS field
2442 static inline u8 ufshcd_get_upmcrs(struct ufs_hba *hba)
2444 return (ufshcd_readl(hba, REG_CONTROLLER_STATUS) >> 8) & 0x7;
2448 * ufshcd_dispatch_uic_cmd - Dispatch UIC commands to unipro layers
2449 * @hba: per adapter instance
2450 * @uic_cmd: UIC command
2452 * Mutex must be held.
2455 ufshcd_dispatch_uic_cmd(struct ufs_hba *hba, struct uic_command *uic_cmd)
2457 WARN_ON(hba->active_uic_cmd);
2459 hba->active_uic_cmd = uic_cmd;
2461 ufshcd_dme_cmd_log(hba, "send", hba->active_uic_cmd->command);
2463 ufshcd_writel(hba, uic_cmd->argument1, REG_UIC_COMMAND_ARG_1);
2464 ufshcd_writel(hba, uic_cmd->argument2, REG_UIC_COMMAND_ARG_2);
2465 ufshcd_writel(hba, uic_cmd->argument3, REG_UIC_COMMAND_ARG_3);
2468 ufshcd_writel(hba, uic_cmd->command & COMMAND_OPCODE_MASK,
2473 * ufshcd_wait_for_uic_cmd - Wait complectioin of UIC command
2474 * @hba: per adapter instance
2475 * @uic_command: UIC command
2477 * Must be called with mutex held.
2478 * Returns 0 only if success.
2481 ufshcd_wait_for_uic_cmd(struct ufs_hba *hba, struct uic_command *uic_cmd)
2484 unsigned long flags;
2486 if (wait_for_completion_timeout(&uic_cmd->done,
2487 msecs_to_jiffies(UIC_CMD_TIMEOUT)))
2488 ret = uic_cmd->argument2 & MASK_UIC_COMMAND_RESULT;
2493 ufsdbg_set_err_state(hba);
2495 ufshcd_dme_cmd_log(hba, "cmp1", hba->active_uic_cmd->command);
2497 spin_lock_irqsave(hba->host->host_lock, flags);
2498 hba->active_uic_cmd = NULL;
2499 spin_unlock_irqrestore(hba->host->host_lock, flags);
2505 * __ufshcd_send_uic_cmd - Send UIC commands and retrieve the result
2506 * @hba: per adapter instance
2507 * @uic_cmd: UIC command
2508 * @completion: initialize the completion only if this is set to true
2510 * Identical to ufshcd_send_uic_cmd() expect mutex. Must be called
2511 * with mutex held and host_lock locked.
2512 * Returns 0 only if success.
2515 __ufshcd_send_uic_cmd(struct ufs_hba *hba, struct uic_command *uic_cmd,
2518 if (!ufshcd_ready_for_uic_cmd(hba)) {
2520 "Controller not ready to accept UIC commands\n");
2525 init_completion(&uic_cmd->done);
2527 ufshcd_dispatch_uic_cmd(hba, uic_cmd);
2533 * ufshcd_send_uic_cmd - Send UIC commands and retrieve the result
2534 * @hba: per adapter instance
2535 * @uic_cmd: UIC command
2537 * Returns 0 only if success.
2540 ufshcd_send_uic_cmd(struct ufs_hba *hba, struct uic_command *uic_cmd)
2543 unsigned long flags;
2545 hba->ufs_stats.clk_hold.ctx = UIC_CMD_SEND;
2546 ufshcd_hold_all(hba);
2547 mutex_lock(&hba->uic_cmd_mutex);
2548 ufshcd_add_delay_before_dme_cmd(hba);
2550 spin_lock_irqsave(hba->host->host_lock, flags);
2551 ret = __ufshcd_send_uic_cmd(hba, uic_cmd, true);
2552 spin_unlock_irqrestore(hba->host->host_lock, flags);
2554 ret = ufshcd_wait_for_uic_cmd(hba, uic_cmd);
2556 ufshcd_save_tstamp_of_last_dme_cmd(hba);
2557 mutex_unlock(&hba->uic_cmd_mutex);
2558 ufshcd_release_all(hba);
2559 hba->ufs_stats.clk_rel.ctx = UIC_CMD_SEND;
2561 ufsdbg_error_inject_dispatcher(hba,
2562 ERR_INJECT_UIC, 0, &ret);
2568 * ufshcd_map_sg - Map scatter-gather list to prdt
2569 * @lrbp - pointer to local reference block
2571 * Returns 0 in case of success, non-zero value in case of failure
2573 static int ufshcd_map_sg(struct ufshcd_lrb *lrbp)
2575 struct ufshcd_sg_entry *prd_table;
2576 struct scatterlist *sg;
2577 struct scsi_cmnd *cmd;
2582 sg_segments = scsi_dma_map(cmd);
2583 if (sg_segments < 0)
2587 lrbp->utr_descriptor_ptr->prd_table_length =
2588 cpu_to_le16((u16) (sg_segments));
2590 prd_table = (struct ufshcd_sg_entry *)lrbp->ucd_prdt_ptr;
2592 scsi_for_each_sg(cmd, sg, sg_segments, i) {
2594 cpu_to_le32(((u32) sg_dma_len(sg))-1);
2595 prd_table[i].base_addr =
2596 cpu_to_le32(lower_32_bits(sg->dma_address));
2597 prd_table[i].upper_addr =
2598 cpu_to_le32(upper_32_bits(sg->dma_address));
2599 prd_table[i].reserved = 0;
2602 lrbp->utr_descriptor_ptr->prd_table_length = 0;
2609 * ufshcd_enable_intr - enable interrupts
2610 * @hba: per adapter instance
2611 * @intrs: interrupt bits
2613 static void ufshcd_enable_intr(struct ufs_hba *hba, u32 intrs)
2615 u32 set = ufshcd_readl(hba, REG_INTERRUPT_ENABLE);
2617 if (hba->ufs_version == UFSHCI_VERSION_10) {
2619 rw = set & INTERRUPT_MASK_RW_VER_10;
2620 set = rw | ((set ^ intrs) & intrs);
2625 ufshcd_writel(hba, set, REG_INTERRUPT_ENABLE);
2629 * ufshcd_disable_intr - disable interrupts
2630 * @hba: per adapter instance
2631 * @intrs: interrupt bits
2633 static void ufshcd_disable_intr(struct ufs_hba *hba, u32 intrs)
2635 u32 set = ufshcd_readl(hba, REG_INTERRUPT_ENABLE);
2637 if (hba->ufs_version == UFSHCI_VERSION_10) {
2639 rw = (set & INTERRUPT_MASK_RW_VER_10) &
2640 ~(intrs & INTERRUPT_MASK_RW_VER_10);
2641 set = rw | ((set & intrs) & ~INTERRUPT_MASK_RW_VER_10);
2647 ufshcd_writel(hba, set, REG_INTERRUPT_ENABLE);
2650 static int ufshcd_prepare_crypto_utrd(struct ufs_hba *hba,
2651 struct ufshcd_lrb *lrbp)
2653 struct utp_transfer_req_desc *req_desc = lrbp->utr_descriptor_ptr;
2655 bool enable = false;
2660 * Call vendor specific code to get crypto info for this request:
2661 * enable, crypto config. index, DUN.
2662 * If bypass is set, don't bother setting the other fields.
2664 ret = ufshcd_vops_crypto_req_setup(hba, lrbp, &cc_index, &enable, &dun);
2666 if (ret != -EAGAIN) {
2668 "%s: failed to setup crypto request (%d)\n",
2678 req_desc->header.dword_0 |= cc_index | UTRD_CRYPTO_ENABLE;
2679 req_desc->header.dword_1 = (u32)(dun & 0xFFFFFFFF);
2680 req_desc->header.dword_3 = (u32)((dun >> 32) & 0xFFFFFFFF);
2686 * ufshcd_prepare_req_desc_hdr() - Fills the requests header
2687 * descriptor according to request
2688 * @hba: per adapter instance
2689 * @lrbp: pointer to local reference block
2690 * @upiu_flags: flags required in the header
2691 * @cmd_dir: requests data direction
2693 static int ufshcd_prepare_req_desc_hdr(struct ufs_hba *hba,
2694 struct ufshcd_lrb *lrbp, u32 *upiu_flags,
2695 enum dma_data_direction cmd_dir)
2697 struct utp_transfer_req_desc *req_desc = lrbp->utr_descriptor_ptr;
2701 if (cmd_dir == DMA_FROM_DEVICE) {
2702 data_direction = UTP_DEVICE_TO_HOST;
2703 *upiu_flags = UPIU_CMD_FLAGS_READ;
2704 } else if (cmd_dir == DMA_TO_DEVICE) {
2705 data_direction = UTP_HOST_TO_DEVICE;
2706 *upiu_flags = UPIU_CMD_FLAGS_WRITE;
2708 data_direction = UTP_NO_DATA_TRANSFER;
2709 *upiu_flags = UPIU_CMD_FLAGS_NONE;
2712 dword_0 = data_direction | (lrbp->command_type
2713 << UPIU_COMMAND_TYPE_OFFSET);
2715 dword_0 |= UTP_REQ_DESC_INT_CMD;
2717 /* Transfer request descriptor header fields */
2718 req_desc->header.dword_0 = cpu_to_le32(dword_0);
2719 /* dword_1 is reserved, hence it is set to 0 */
2720 req_desc->header.dword_1 = 0;
2722 * assigning invalid value for command status. Controller
2723 * updates OCS on command completion, with the command
2726 req_desc->header.dword_2 =
2727 cpu_to_le32(OCS_INVALID_COMMAND_STATUS);
2728 /* dword_3 is reserved, hence it is set to 0 */
2729 req_desc->header.dword_3 = 0;
2731 req_desc->prd_table_length = 0;
2733 if (ufshcd_is_crypto_supported(hba))
2734 return ufshcd_prepare_crypto_utrd(hba, lrbp);
2740 * ufshcd_prepare_utp_scsi_cmd_upiu() - fills the utp_transfer_req_desc,
2742 * @lrbp - local reference block pointer
2743 * @upiu_flags - flags
2746 void ufshcd_prepare_utp_scsi_cmd_upiu(struct ufshcd_lrb *lrbp, u32 upiu_flags)
2748 struct utp_upiu_req *ucd_req_ptr = lrbp->ucd_req_ptr;
2749 unsigned short cdb_len;
2751 /* command descriptor fields */
2752 ucd_req_ptr->header.dword_0 = UPIU_HEADER_DWORD(
2753 UPIU_TRANSACTION_COMMAND, upiu_flags,
2754 lrbp->lun, lrbp->task_tag);
2755 ucd_req_ptr->header.dword_1 = UPIU_HEADER_DWORD(
2756 UPIU_COMMAND_SET_TYPE_SCSI, 0, 0, 0);
2758 /* Total EHS length and Data segment length will be zero */
2759 ucd_req_ptr->header.dword_2 = 0;
2761 ucd_req_ptr->sc.exp_data_transfer_len =
2762 cpu_to_be32(lrbp->cmd->sdb.length);
2764 cdb_len = min_t(unsigned short, lrbp->cmd->cmd_len, MAX_CDB_SIZE);
2765 memcpy(ucd_req_ptr->sc.cdb, lrbp->cmd->cmnd, cdb_len);
2766 if (cdb_len < MAX_CDB_SIZE)
2767 memset(ucd_req_ptr->sc.cdb + cdb_len, 0,
2768 (MAX_CDB_SIZE - cdb_len));
2769 memset(lrbp->ucd_rsp_ptr, 0, sizeof(struct utp_upiu_rsp));
2773 * ufshcd_prepare_utp_query_req_upiu() - fills the utp_transfer_req_desc,
2776 * @lrbp: local reference block pointer
2777 * @upiu_flags: flags
2779 static void ufshcd_prepare_utp_query_req_upiu(struct ufs_hba *hba,
2780 struct ufshcd_lrb *lrbp, u32 upiu_flags)
2782 struct utp_upiu_req *ucd_req_ptr = lrbp->ucd_req_ptr;
2783 struct ufs_query *query = &hba->dev_cmd.query;
2784 u16 len = be16_to_cpu(query->request.upiu_req.length);
2785 u8 *descp = (u8 *)lrbp->ucd_req_ptr + GENERAL_UPIU_REQUEST_SIZE;
2787 /* Query request header */
2788 ucd_req_ptr->header.dword_0 = UPIU_HEADER_DWORD(
2789 UPIU_TRANSACTION_QUERY_REQ, upiu_flags,
2790 lrbp->lun, lrbp->task_tag);
2791 ucd_req_ptr->header.dword_1 = UPIU_HEADER_DWORD(
2792 0, query->request.query_func, 0, 0);
2794 /* Data segment length */
2795 ucd_req_ptr->header.dword_2 = UPIU_HEADER_DWORD(
2796 0, 0, len >> 8, (u8)len);
2798 /* Copy the Query Request buffer as is */
2799 memcpy(&ucd_req_ptr->qr, &query->request.upiu_req,
2802 /* Copy the Descriptor */
2803 if (query->request.upiu_req.opcode == UPIU_QUERY_OPCODE_WRITE_DESC)
2804 memcpy(descp, query->descriptor, len);
2806 memset(lrbp->ucd_rsp_ptr, 0, sizeof(struct utp_upiu_rsp));
2809 static inline void ufshcd_prepare_utp_nop_upiu(struct ufshcd_lrb *lrbp)
2811 struct utp_upiu_req *ucd_req_ptr = lrbp->ucd_req_ptr;
2813 memset(ucd_req_ptr, 0, sizeof(struct utp_upiu_req));
2815 /* command descriptor fields */
2816 ucd_req_ptr->header.dword_0 =
2818 UPIU_TRANSACTION_NOP_OUT, 0, 0, lrbp->task_tag);
2819 /* clear rest of the fields of basic header */
2820 ucd_req_ptr->header.dword_1 = 0;
2821 ucd_req_ptr->header.dword_2 = 0;
2823 memset(lrbp->ucd_rsp_ptr, 0, sizeof(struct utp_upiu_rsp));
2827 * ufshcd_compose_upiu - form UFS Protocol Information Unit(UPIU)
2828 * @hba - per adapter instance
2829 * @lrb - pointer to local reference block
2831 static int ufshcd_compose_upiu(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
2836 switch (lrbp->command_type) {
2837 case UTP_CMD_TYPE_SCSI:
2838 if (likely(lrbp->cmd)) {
2839 ret = ufshcd_prepare_req_desc_hdr(hba, lrbp,
2840 &upiu_flags, lrbp->cmd->sc_data_direction);
2841 ufshcd_prepare_utp_scsi_cmd_upiu(lrbp, upiu_flags);
2846 case UTP_CMD_TYPE_DEV_MANAGE:
2847 ret = ufshcd_prepare_req_desc_hdr(hba, lrbp, &upiu_flags,
2849 if (hba->dev_cmd.type == DEV_CMD_TYPE_QUERY)
2850 ufshcd_prepare_utp_query_req_upiu(
2851 hba, lrbp, upiu_flags);
2852 else if (hba->dev_cmd.type == DEV_CMD_TYPE_NOP)
2853 ufshcd_prepare_utp_nop_upiu(lrbp);
2857 case UTP_CMD_TYPE_UFS:
2858 /* For UFS native command implementation */
2860 dev_err(hba->dev, "%s: UFS native command are not supported\n",
2865 dev_err(hba->dev, "%s: unknown command type: 0x%x\n",
2866 __func__, lrbp->command_type);
2868 } /* end of switch */
2874 * ufshcd_scsi_to_upiu_lun - maps scsi LUN to UPIU LUN
2875 * @scsi_lun: scsi LUN id
2877 * Returns UPIU LUN id
2879 static inline u8 ufshcd_scsi_to_upiu_lun(unsigned int scsi_lun)
2881 if (scsi_is_wlun(scsi_lun))
2882 return (scsi_lun & UFS_UPIU_MAX_UNIT_NUM_ID)
2885 return scsi_lun & UFS_UPIU_MAX_UNIT_NUM_ID;
2889 * ufshcd_upiu_wlun_to_scsi_wlun - maps UPIU W-LUN id to SCSI W-LUN ID
2890 * @scsi_lun: UPIU W-LUN id
2892 * Returns SCSI W-LUN id
2894 static inline u16 ufshcd_upiu_wlun_to_scsi_wlun(u8 upiu_wlun_id)
2896 return (upiu_wlun_id & ~UFS_UPIU_WLUN_ID) | SCSI_W_LUN_BASE;
2900 * ufshcd_get_write_lock - synchronize between shutdown, scaling &
2901 * arrival of requests
2904 * Lock is predominantly held by shutdown context thus, ensuring
2905 * that no requests from any other context may sneak through.
2907 static inline void ufshcd_get_write_lock(struct ufs_hba *hba)
2909 down_write(&hba->lock);
2913 * ufshcd_get_read_lock - synchronize between shutdown, scaling &
2914 * arrival of requests
2917 * Returns 1 if acquired, < 0 on contention
2919 * After shutdown's initiated, allow requests only directed to the
2920 * well known device lun. The sync between scaling & issue is maintained
2921 * as is and this restructuring syncs shutdown with these too.
2923 static int ufshcd_get_read_lock(struct ufs_hba *hba, u64 lun)
2927 err = down_read_trylock(&hba->lock);
2930 /* let requests for well known device lun to go through */
2931 if (ufshcd_scsi_to_upiu_lun(lun) == UFS_UPIU_UFS_DEVICE_WLUN)
2933 else if (!ufshcd_is_shutdown_ongoing(hba))
2943 * ufshcd_put_read_lock - synchronize between shutdown, scaling &
2944 * arrival of requests
2949 static inline void ufshcd_put_read_lock(struct ufs_hba *hba)
2951 up_read(&hba->lock);
2955 * ufshcd_queuecommand - main entry point for SCSI requests
2956 * @cmd: command from SCSI Midlayer
2957 * @done: call back function
2959 * Returns 0 for success, non-zero in case of failure
2961 static int ufshcd_queuecommand(struct Scsi_Host *host, struct scsi_cmnd *cmd)
2963 struct ufshcd_lrb *lrbp;
2964 struct ufs_hba *hba;
2965 unsigned long flags;
2968 bool has_read_lock = false;
2970 hba = shost_priv(host);
2972 if (!cmd || !cmd->request || !hba)
2975 tag = cmd->request->tag;
2976 if (!ufshcd_valid_tag(hba, tag)) {
2978 "%s: invalid command tag %d: cmd=0x%p, cmd->request=0x%p",
2979 __func__, tag, cmd, cmd->request);
2983 err = ufshcd_get_read_lock(hba, cmd->device->lun);
2984 if (unlikely(err < 0)) {
2985 if (err == -EPERM) {
2986 set_host_byte(cmd, DID_ERROR);
2987 cmd->scsi_done(cmd);
2991 return SCSI_MLQUEUE_HOST_BUSY;
2992 } else if (err == 1) {
2993 has_read_lock = true;
2996 spin_lock_irqsave(hba->host->host_lock, flags);
2998 /* if error handling is in progress, return host busy */
2999 if (ufshcd_eh_in_progress(hba)) {
3000 err = SCSI_MLQUEUE_HOST_BUSY;
3004 switch (hba->ufshcd_state) {
3005 case UFSHCD_STATE_OPERATIONAL:
3007 case UFSHCD_STATE_RESET:
3008 err = SCSI_MLQUEUE_HOST_BUSY;
3010 case UFSHCD_STATE_ERROR:
3011 set_host_byte(cmd, DID_ERROR);
3012 cmd->scsi_done(cmd);
3015 dev_WARN_ONCE(hba->dev, 1, "%s: invalid state %d\n",
3016 __func__, hba->ufshcd_state);
3017 set_host_byte(cmd, DID_BAD_TARGET);
3018 cmd->scsi_done(cmd);
3021 spin_unlock_irqrestore(hba->host->host_lock, flags);
3023 hba->req_abort_count = 0;
3025 /* acquire the tag to make sure device cmds don't use it */
3026 if (test_and_set_bit_lock(tag, &hba->lrb_in_use)) {
3028 * Dev manage command in progress, requeue the command.
3029 * Requeuing the command helps in cases where the request *may*
3030 * find different tag instead of waiting for dev manage command
3033 err = SCSI_MLQUEUE_HOST_BUSY;
3037 hba->ufs_stats.clk_hold.ctx = QUEUE_CMD;
3038 err = ufshcd_hold(hba, true);
3040 err = SCSI_MLQUEUE_HOST_BUSY;
3041 clear_bit_unlock(tag, &hba->lrb_in_use);
3044 if (ufshcd_is_clkgating_allowed(hba))
3045 WARN_ON(hba->clk_gating.state != CLKS_ON);
3047 err = ufshcd_hibern8_hold(hba, true);
3049 clear_bit_unlock(tag, &hba->lrb_in_use);
3050 err = SCSI_MLQUEUE_HOST_BUSY;
3051 hba->ufs_stats.clk_rel.ctx = QUEUE_CMD;
3052 ufshcd_release(hba, true);
3055 if (ufshcd_is_hibern8_on_idle_allowed(hba))
3056 WARN_ON(hba->hibern8_on_idle.state != HIBERN8_EXITED);
3058 /* Vote PM QoS for the request */
3059 ufshcd_vops_pm_qos_req_start(hba, cmd->request);
3061 /* IO svc time latency histogram */
3062 if (hba->latency_hist_enabled &&
3063 (cmd->request->cmd_type == REQ_TYPE_FS)) {
3064 cmd->request->lat_hist_io_start = ktime_get();
3065 cmd->request->lat_hist_enabled = 1;
3067 cmd->request->lat_hist_enabled = 0;
3070 WARN_ON(hba->clk_gating.state != CLKS_ON);
3072 lrbp = &hba->lrb[tag];
3076 lrbp->sense_bufflen = UFSHCD_REQ_SENSE_SIZE;
3077 lrbp->sense_buffer = cmd->sense_buffer;
3078 lrbp->task_tag = tag;
3079 lrbp->lun = ufshcd_scsi_to_upiu_lun(cmd->device->lun);
3080 lrbp->intr_cmd = !ufshcd_is_intr_aggr_allowed(hba) ? true : false;
3081 lrbp->command_type = UTP_CMD_TYPE_SCSI;
3082 lrbp->req_abort_skip = false;
3084 /* form UPIU before issuing the command */
3085 err = ufshcd_compose_upiu(hba, lrbp);
3089 "%s: failed to compose upiu %d\n",
3093 clear_bit_unlock(tag, &hba->lrb_in_use);
3094 ufshcd_release_all(hba);
3095 ufshcd_vops_pm_qos_req_end(hba, cmd->request, true);
3099 err = ufshcd_map_sg(lrbp);
3102 clear_bit_unlock(tag, &hba->lrb_in_use);
3103 ufshcd_release_all(hba);
3104 ufshcd_vops_pm_qos_req_end(hba, cmd->request, true);
3108 err = ufshcd_vops_crypto_engine_cfg_start(hba, tag);
3112 "%s: failed to configure crypto engine %d\n",
3115 scsi_dma_unmap(lrbp->cmd);
3117 clear_bit_unlock(tag, &hba->lrb_in_use);
3118 ufshcd_release_all(hba);
3119 ufshcd_vops_pm_qos_req_end(hba, cmd->request, true);
3124 /* Make sure descriptors are ready before ringing the doorbell */
3126 /* issue command to the controller */
3127 spin_lock_irqsave(hba->host->host_lock, flags);
3129 err = ufshcd_send_command(hba, tag);
3131 spin_unlock_irqrestore(hba->host->host_lock, flags);
3132 scsi_dma_unmap(lrbp->cmd);
3134 clear_bit_unlock(tag, &hba->lrb_in_use);
3135 ufshcd_release_all(hba);
3136 ufshcd_vops_pm_qos_req_end(hba, cmd->request, true);
3137 ufshcd_vops_crypto_engine_cfg_end(hba, lrbp, cmd->request);
3138 dev_err(hba->dev, "%s: failed sending command, %d\n",
3145 spin_unlock_irqrestore(hba->host->host_lock, flags);
3148 ufshcd_put_read_lock(hba);
3152 static int ufshcd_compose_dev_cmd(struct ufs_hba *hba,
3153 struct ufshcd_lrb *lrbp, enum dev_cmd_type cmd_type, int tag)
3156 lrbp->sense_bufflen = 0;
3157 lrbp->sense_buffer = NULL;
3158 lrbp->task_tag = tag;
3159 lrbp->lun = 0; /* device management cmd is not specific to any LUN */
3160 lrbp->command_type = UTP_CMD_TYPE_DEV_MANAGE;
3161 lrbp->intr_cmd = true; /* No interrupt aggregation */
3162 hba->dev_cmd.type = cmd_type;
3164 return ufshcd_compose_upiu(hba, lrbp);
3168 ufshcd_clear_cmd(struct ufs_hba *hba, int tag)
3171 unsigned long flags;
3172 u32 mask = 1 << tag;
3174 /* clear outstanding transaction before retry */
3175 spin_lock_irqsave(hba->host->host_lock, flags);
3176 ufshcd_utrl_clear(hba, tag);
3177 spin_unlock_irqrestore(hba->host->host_lock, flags);
3180 * wait for for h/w to clear corresponding bit in door-bell.
3181 * max. wait is 1 sec.
3183 err = ufshcd_wait_for_register(hba,
3184 REG_UTP_TRANSFER_REQ_DOOR_BELL,
3185 mask, ~mask, 1000, 1000, true);
3191 ufshcd_check_query_response(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
3193 struct ufs_query_res *query_res = &hba->dev_cmd.query.response;
3195 /* Get the UPIU response */
3196 query_res->response = ufshcd_get_rsp_upiu_result(lrbp->ucd_rsp_ptr) >>
3197 UPIU_RSP_CODE_OFFSET;
3198 return query_res->response;
3202 * ufshcd_dev_cmd_completion() - handles device management command responses
3203 * @hba: per adapter instance
3204 * @lrbp: pointer to local reference block
3207 ufshcd_dev_cmd_completion(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
3212 hba->ufs_stats.last_hibern8_exit_tstamp = ktime_set(0, 0);
3213 resp = ufshcd_get_req_rsp(lrbp->ucd_rsp_ptr);
3216 case UPIU_TRANSACTION_NOP_IN:
3217 if (hba->dev_cmd.type != DEV_CMD_TYPE_NOP) {
3219 dev_err(hba->dev, "%s: unexpected response %x\n",
3223 case UPIU_TRANSACTION_QUERY_RSP:
3224 err = ufshcd_check_query_response(hba, lrbp);
3226 err = ufshcd_copy_query_response(hba, lrbp);
3228 case UPIU_TRANSACTION_REJECT_UPIU:
3229 /* TODO: handle Reject UPIU Response */
3231 dev_err(hba->dev, "%s: Reject UPIU not fully implemented\n",
3236 dev_err(hba->dev, "%s: Invalid device management cmd response: %x\n",
3244 static int ufshcd_wait_for_dev_cmd(struct ufs_hba *hba,
3245 struct ufshcd_lrb *lrbp, int max_timeout)
3248 unsigned long time_left;
3249 unsigned long flags;
3251 time_left = wait_for_completion_timeout(hba->dev_cmd.complete,
3252 msecs_to_jiffies(max_timeout));
3254 spin_lock_irqsave(hba->host->host_lock, flags);
3255 hba->dev_cmd.complete = NULL;
3256 if (likely(time_left)) {
3257 err = ufshcd_get_tr_ocs(lrbp);
3259 err = ufshcd_dev_cmd_completion(hba, lrbp);
3261 spin_unlock_irqrestore(hba->host->host_lock, flags);
3265 dev_dbg(hba->dev, "%s: dev_cmd request timedout, tag %d\n",
3266 __func__, lrbp->task_tag);
3267 if (!ufshcd_clear_cmd(hba, lrbp->task_tag))
3268 /* successfully cleared the command, retry if needed */
3271 * in case of an error, after clearing the doorbell,
3272 * we also need to clear the outstanding_request
3275 ufshcd_outstanding_req_clear(hba, lrbp->task_tag);
3279 ufsdbg_set_err_state(hba);
3285 * ufshcd_get_dev_cmd_tag - Get device management command tag
3286 * @hba: per-adapter instance
3287 * @tag: pointer to variable with available slot value
3289 * Get a free slot and lock it until device management command
3292 * Returns false if free slot is unavailable for locking, else
3293 * return true with tag value in @tag.
3295 static bool ufshcd_get_dev_cmd_tag(struct ufs_hba *hba, int *tag_out)
3305 tmp = ~hba->lrb_in_use;
3306 tag = find_last_bit(&tmp, hba->nutrs);
3307 if (tag >= hba->nutrs)
3309 } while (test_and_set_bit_lock(tag, &hba->lrb_in_use));
3317 static inline void ufshcd_put_dev_cmd_tag(struct ufs_hba *hba, int tag)
3319 clear_bit_unlock(tag, &hba->lrb_in_use);
3323 * ufshcd_exec_dev_cmd - API for sending device management requests
3325 * @cmd_type - specifies the type (NOP, Query...)
3326 * @timeout - time in seconds
3328 * NOTE: Since there is only one available tag for device management commands,
3329 * it is expected you hold the hba->dev_cmd.lock mutex.
3331 static int ufshcd_exec_dev_cmd(struct ufs_hba *hba,
3332 enum dev_cmd_type cmd_type, int timeout)
3334 struct ufshcd_lrb *lrbp;
3337 struct completion wait;
3338 unsigned long flags;
3341 * May get invoked from shutdown and IOCTL contexts.
3342 * In shutdown context, it comes in with lock acquired.
3343 * In error recovery context, it may come with lock acquired.
3346 if (!ufshcd_is_shutdown_ongoing(hba) && !ufshcd_eh_in_progress(hba))
3347 down_read(&hba->lock);
3350 * Get free slot, sleep if slots are unavailable.
3351 * Even though we use wait_event() which sleeps indefinitely,
3352 * the maximum wait time is bounded by SCSI request timeout.
3354 wait_event(hba->dev_cmd.tag_wq, ufshcd_get_dev_cmd_tag(hba, &tag));
3356 init_completion(&wait);
3357 lrbp = &hba->lrb[tag];
3359 err = ufshcd_compose_dev_cmd(hba, lrbp, cmd_type, tag);
3363 hba->dev_cmd.complete = &wait;
3365 /* Make sure descriptors are ready before ringing the doorbell */
3367 spin_lock_irqsave(hba->host->host_lock, flags);
3368 err = ufshcd_send_command(hba, tag);
3369 spin_unlock_irqrestore(hba->host->host_lock, flags);
3371 dev_err(hba->dev, "%s: failed sending command, %d\n",
3375 err = ufshcd_wait_for_dev_cmd(hba, lrbp, timeout);
3378 ufshcd_put_dev_cmd_tag(hba, tag);
3379 wake_up(&hba->dev_cmd.tag_wq);
3380 if (!ufshcd_is_shutdown_ongoing(hba) && !ufshcd_eh_in_progress(hba))
3381 up_read(&hba->lock);
3386 * ufshcd_init_query() - init the query response and request parameters
3387 * @hba: per-adapter instance
3388 * @request: address of the request pointer to be initialized
3389 * @response: address of the response pointer to be initialized
3390 * @opcode: operation to perform
3391 * @idn: flag idn to access
3392 * @index: LU number to access
3393 * @selector: query/flag/descriptor further identification
3395 static inline void ufshcd_init_query(struct ufs_hba *hba,
3396 struct ufs_query_req **request, struct ufs_query_res **response,
3397 enum query_opcode opcode, u8 idn, u8 index, u8 selector)
3399 int idn_t = (int)idn;
3401 ufsdbg_error_inject_dispatcher(hba,
3402 ERR_INJECT_QUERY, idn_t, (int *)&idn_t);
3405 *request = &hba->dev_cmd.query.request;
3406 *response = &hba->dev_cmd.query.response;
3407 memset(*request, 0, sizeof(struct ufs_query_req));
3408 memset(*response, 0, sizeof(struct ufs_query_res));
3409 (*request)->upiu_req.opcode = opcode;
3410 (*request)->upiu_req.idn = idn;
3411 (*request)->upiu_req.index = index;
3412 (*request)->upiu_req.selector = selector;
3414 ufshcd_update_query_stats(hba, opcode, idn);
3417 static int ufshcd_query_flag_retry(struct ufs_hba *hba,
3418 enum query_opcode opcode, enum flag_idn idn, bool *flag_res)
3423 for (retries = 0; retries < QUERY_REQ_RETRIES; retries++) {
3424 ret = ufshcd_query_flag(hba, opcode, idn, flag_res);
3427 "%s: failed with error %d, retries %d\n",
3428 __func__, ret, retries);
3435 "%s: query attribute, opcode %d, idn %d, failed with error %d after %d retires\n",
3436 __func__, opcode, idn, ret, retries);
3441 * ufshcd_query_flag() - API function for sending flag query requests
3442 * hba: per-adapter instance
3443 * query_opcode: flag query to perform
3444 * idn: flag idn to access
3445 * flag_res: the flag value after the query request completes
3447 * Returns 0 for success, non-zero in case of failure
3449 int ufshcd_query_flag(struct ufs_hba *hba, enum query_opcode opcode,
3450 enum flag_idn idn, bool *flag_res)
3452 struct ufs_query_req *request = NULL;
3453 struct ufs_query_res *response = NULL;
3454 int err, index = 0, selector = 0;
3455 int timeout = QUERY_REQ_TIMEOUT;
3459 ufshcd_hold_all(hba);
3460 mutex_lock(&hba->dev_cmd.lock);
3461 ufshcd_init_query(hba, &request, &response, opcode, idn, index,
3465 case UPIU_QUERY_OPCODE_SET_FLAG:
3466 case UPIU_QUERY_OPCODE_CLEAR_FLAG:
3467 case UPIU_QUERY_OPCODE_TOGGLE_FLAG:
3468 request->query_func = UPIU_QUERY_FUNC_STANDARD_WRITE_REQUEST;
3470 case UPIU_QUERY_OPCODE_READ_FLAG:
3471 request->query_func = UPIU_QUERY_FUNC_STANDARD_READ_REQUEST;
3473 /* No dummy reads */
3474 dev_err(hba->dev, "%s: Invalid argument for read request\n",
3482 "%s: Expected query flag opcode but got = %d\n",
3488 err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_QUERY, timeout);
3492 "%s: Sending flag query for idn %d failed, err = %d\n",
3493 __func__, request->upiu_req.idn, err);
3498 *flag_res = (be32_to_cpu(response->upiu_res.value) &
3499 MASK_QUERY_UPIU_FLAG_LOC) & 0x1;
3502 mutex_unlock(&hba->dev_cmd.lock);
3503 ufshcd_release_all(hba);
3506 EXPORT_SYMBOL(ufshcd_query_flag);
3509 * ufshcd_query_attr - API function for sending attribute requests
3510 * hba: per-adapter instance
3511 * opcode: attribute opcode
3512 * idn: attribute idn to access
3513 * index: index field
3514 * selector: selector field
3515 * attr_val: the attribute value after the query request completes
3517 * Returns 0 for success, non-zero in case of failure
3519 int ufshcd_query_attr(struct ufs_hba *hba, enum query_opcode opcode,
3520 enum attr_idn idn, u8 index, u8 selector, u32 *attr_val)
3522 struct ufs_query_req *request = NULL;
3523 struct ufs_query_res *response = NULL;
3528 ufshcd_hold_all(hba);
3530 dev_err(hba->dev, "%s: attribute value required for opcode 0x%x\n",
3536 mutex_lock(&hba->dev_cmd.lock);
3537 ufshcd_init_query(hba, &request, &response, opcode, idn, index,
3541 case UPIU_QUERY_OPCODE_WRITE_ATTR:
3542 request->query_func = UPIU_QUERY_FUNC_STANDARD_WRITE_REQUEST;
3543 request->upiu_req.value = cpu_to_be32(*attr_val);
3545 case UPIU_QUERY_OPCODE_READ_ATTR:
3546 request->query_func = UPIU_QUERY_FUNC_STANDARD_READ_REQUEST;
3549 dev_err(hba->dev, "%s: Expected query attr opcode but got = 0x%.2x\n",
3555 err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_QUERY, QUERY_REQ_TIMEOUT);
3558 dev_err(hba->dev, "%s: opcode 0x%.2x for idn %d failed, index %d, err = %d\n",
3560 request->upiu_req.idn, index, err);
3564 *attr_val = be32_to_cpu(response->upiu_res.value);
3567 mutex_unlock(&hba->dev_cmd.lock);
3569 ufshcd_release_all(hba);
3572 EXPORT_SYMBOL(ufshcd_query_attr);
3575 * ufshcd_query_attr_retry() - API function for sending query
3576 * attribute with retries
3577 * @hba: per-adapter instance
3578 * @opcode: attribute opcode
3579 * @idn: attribute idn to access
3580 * @index: index field
3581 * @selector: selector field
3582 * @attr_val: the attribute value after the query request
3585 * Returns 0 for success, non-zero in case of failure
3587 static int ufshcd_query_attr_retry(struct ufs_hba *hba,
3588 enum query_opcode opcode, enum attr_idn idn, u8 index, u8 selector,
3594 for (retries = QUERY_REQ_RETRIES; retries > 0; retries--) {
3595 ret = ufshcd_query_attr(hba, opcode, idn, index,
3596 selector, attr_val);
3598 dev_dbg(hba->dev, "%s: failed with error %d, retries %d\n",
3599 __func__, ret, retries);
3606 "%s: query attribute, idn %d, failed with error %d after %d retires\n",
3607 __func__, idn, ret, retries);
3611 static int __ufshcd_query_descriptor(struct ufs_hba *hba,
3612 enum query_opcode opcode, enum desc_idn idn, u8 index,
3613 u8 selector, u8 *desc_buf, int *buf_len)
3615 struct ufs_query_req *request = NULL;
3616 struct ufs_query_res *response = NULL;
3621 ufshcd_hold_all(hba);
3623 dev_err(hba->dev, "%s: descriptor buffer required for opcode 0x%x\n",
3629 if (*buf_len <= QUERY_DESC_MIN_SIZE || *buf_len > QUERY_DESC_MAX_SIZE) {
3630 dev_err(hba->dev, "%s: descriptor buffer size (%d) is out of range\n",
3631 __func__, *buf_len);
3636 mutex_lock(&hba->dev_cmd.lock);
3637 ufshcd_init_query(hba, &request, &response, opcode, idn, index,
3639 hba->dev_cmd.query.descriptor = desc_buf;
3640 request->upiu_req.length = cpu_to_be16(*buf_len);
3643 case UPIU_QUERY_OPCODE_WRITE_DESC:
3644 request->query_func = UPIU_QUERY_FUNC_STANDARD_WRITE_REQUEST;
3646 case UPIU_QUERY_OPCODE_READ_DESC:
3647 request->query_func = UPIU_QUERY_FUNC_STANDARD_READ_REQUEST;
3651 "%s: Expected query descriptor opcode but got = 0x%.2x\n",
3657 err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_QUERY, QUERY_REQ_TIMEOUT);
3660 dev_err(hba->dev, "%s: opcode 0x%.2x for idn %d failed, index %d, err = %d\n",
3662 request->upiu_req.idn, index, err);
3666 hba->dev_cmd.query.descriptor = NULL;
3667 *buf_len = be16_to_cpu(response->upiu_res.length);
3670 mutex_unlock(&hba->dev_cmd.lock);
3672 ufshcd_release_all(hba);
3677 * ufshcd_query_descriptor - API function for sending descriptor requests
3678 * hba: per-adapter instance
3679 * opcode: attribute opcode
3680 * idn: attribute idn to access
3681 * index: index field
3682 * selector: selector field
3683 * desc_buf: the buffer that contains the descriptor
3684 * buf_len: length parameter passed to the device
3686 * Returns 0 for success, non-zero in case of failure.
3687 * The buf_len parameter will contain, on return, the length parameter
3688 * received on the response.
3690 int ufshcd_query_descriptor(struct ufs_hba *hba,
3691 enum query_opcode opcode, enum desc_idn idn, u8 index,
3692 u8 selector, u8 *desc_buf, int *buf_len)
3697 for (retries = QUERY_REQ_RETRIES; retries > 0; retries--) {
3698 err = __ufshcd_query_descriptor(hba, opcode, idn, index,
3699 selector, desc_buf, buf_len);
3700 if (!err || err == -EINVAL)
3706 EXPORT_SYMBOL(ufshcd_query_descriptor);
3709 * ufshcd_read_desc_param - read the specified descriptor parameter
3710 * @hba: Pointer to adapter instance
3711 * @desc_id: descriptor idn value
3712 * @desc_index: descriptor index
3713 * @param_offset: offset of the parameter to read
3714 * @param_read_buf: pointer to buffer where parameter would be read
3715 * @param_size: sizeof(param_read_buf)
3717 * Return 0 in case of success, non-zero otherwise
3719 static int ufshcd_read_desc_param(struct ufs_hba *hba,
3720 enum desc_idn desc_id,
3729 bool is_kmalloc = true;
3732 if (desc_id >= QUERY_DESC_IDN_MAX)
3735 buff_len = ufs_query_desc_max_size[desc_id];
3736 if ((param_offset + param_size) > buff_len)
3739 if (!param_offset && (param_size == buff_len)) {
3740 /* memory space already available to hold full descriptor */
3741 desc_buf = param_read_buf;
3744 /* allocate memory to hold full descriptor */
3745 desc_buf = kmalloc(buff_len, GFP_KERNEL);
3750 ret = ufshcd_query_descriptor(hba, UPIU_QUERY_OPCODE_READ_DESC,
3751 desc_id, desc_index, 0, desc_buf,
3755 dev_err(hba->dev, "%s: Failed reading descriptor. desc_id %d, desc_index %d, param_offset %d, ret %d",
3756 __func__, desc_id, desc_index, param_offset, ret);
3762 if (desc_buf[QUERY_DESC_DESC_TYPE_OFFSET] != desc_id) {
3763 dev_err(hba->dev, "%s: invalid desc_id %d in descriptor header",
3764 __func__, desc_buf[QUERY_DESC_DESC_TYPE_OFFSET]);
3770 * While reading variable size descriptors (like string descriptor),
3771 * some UFS devices may report the "LENGTH" (field in "Transaction
3772 * Specific fields" of Query Response UPIU) same as what was requested
3773 * in Query Request UPIU instead of reporting the actual size of the
3774 * variable size descriptor.
3775 * Although it's safe to ignore the "LENGTH" field for variable size
3776 * descriptors as we can always derive the length of the descriptor from
3777 * the descriptor header fields. Hence this change impose the length
3778 * match check only for fixed size descriptors (for which we always
3779 * request the correct size as part of Query Request UPIU).
3781 if ((desc_id != QUERY_DESC_IDN_STRING) &&
3782 (buff_len != desc_buf[QUERY_DESC_LENGTH_OFFSET])) {
3783 dev_err(hba->dev, "%s: desc_buf length mismatch: buff_len %d, buff_len(desc_header) %d",
3784 __func__, buff_len, desc_buf[QUERY_DESC_LENGTH_OFFSET]);
3790 memcpy(param_read_buf, &desc_buf[param_offset], param_size);
3797 static inline int ufshcd_read_desc(struct ufs_hba *hba,
3798 enum desc_idn desc_id,
3803 return ufshcd_read_desc_param(hba, desc_id, desc_index, 0, buf, size);
3806 static inline int ufshcd_read_power_desc(struct ufs_hba *hba,
3810 return ufshcd_read_desc(hba, QUERY_DESC_IDN_POWER, 0, buf, size);
3813 int ufshcd_read_device_desc(struct ufs_hba *hba, u8 *buf, u32 size)
3815 return ufshcd_read_desc(hba, QUERY_DESC_IDN_DEVICE, 0, buf, size);
3819 * ufshcd_read_string_desc - read string descriptor
3820 * @hba: pointer to adapter instance
3821 * @desc_index: descriptor index
3822 * @buf: pointer to buffer where descriptor would be read
3823 * @size: size of buf
3824 * @ascii: if true convert from unicode to ascii characters
3826 * Return 0 in case of success, non-zero otherwise
3828 int ufshcd_read_string_desc(struct ufs_hba *hba, int desc_index, u8 *buf,
3829 u32 size, bool ascii)
3833 err = ufshcd_read_desc(hba,
3834 QUERY_DESC_IDN_STRING, desc_index, buf, size);
3837 dev_err(hba->dev, "%s: reading String Desc failed after %d retries. err = %d\n",
3838 __func__, QUERY_REQ_RETRIES, err);
3849 /* remove header and divide by 2 to move from UTF16 to UTF8 */
3850 ascii_len = (desc_len - QUERY_DESC_HDR_SIZE) / 2 + 1;
3851 if (size < ascii_len + QUERY_DESC_HDR_SIZE) {
3852 dev_err(hba->dev, "%s: buffer allocated size is too small\n",
3858 buff_ascii = kzalloc(ascii_len, GFP_KERNEL);
3860 dev_err(hba->dev, "%s: Failed allocating %d bytes\n",
3861 __func__, ascii_len);
3867 * the descriptor contains string in UTF16 format
3868 * we need to convert to utf-8 so it can be displayed
3870 utf16s_to_utf8s((wchar_t *)&buf[QUERY_DESC_HDR_SIZE],
3871 desc_len - QUERY_DESC_HDR_SIZE,
3872 UTF16_BIG_ENDIAN, buff_ascii, ascii_len);
3874 /* replace non-printable or non-ASCII characters with spaces */
3875 for (i = 0; i < ascii_len; i++)
3876 ufshcd_remove_non_printable(&buff_ascii[i]);
3878 memset(buf + QUERY_DESC_HDR_SIZE, 0,
3879 size - QUERY_DESC_HDR_SIZE);
3880 memcpy(buf + QUERY_DESC_HDR_SIZE, buff_ascii, ascii_len);
3881 buf[QUERY_DESC_LENGTH_OFFSET] = ascii_len + QUERY_DESC_HDR_SIZE;
3890 * ufshcd_read_unit_desc_param - read the specified unit descriptor parameter
3891 * @hba: Pointer to adapter instance
3893 * @param_offset: offset of the parameter to read
3894 * @param_read_buf: pointer to buffer where parameter would be read
3895 * @param_size: sizeof(param_read_buf)
3897 * Return 0 in case of success, non-zero otherwise
3899 static inline int ufshcd_read_unit_desc_param(struct ufs_hba *hba,
3901 enum unit_desc_param param_offset,
3906 * Unit descriptors are only available for general purpose LUs (LUN id
3907 * from 0 to 7) and RPMB Well known LU.
3909 if (!ufs_is_valid_unit_desc_lun(lun))
3912 return ufshcd_read_desc_param(hba, QUERY_DESC_IDN_UNIT, lun,
3913 param_offset, param_read_buf, param_size);
3917 * ufshcd_memory_alloc - allocate memory for host memory space data structures
3918 * @hba: per adapter instance
3920 * 1. Allocate DMA memory for Command Descriptor array
3921 * Each command descriptor consist of Command UPIU, Response UPIU and PRDT
3922 * 2. Allocate DMA memory for UTP Transfer Request Descriptor List (UTRDL).
3923 * 3. Allocate DMA memory for UTP Task Management Request Descriptor List
3925 * 4. Allocate memory for local reference block(lrb).
3927 * Returns 0 for success, non-zero in case of failure
3929 static int ufshcd_memory_alloc(struct ufs_hba *hba)
3931 size_t utmrdl_size, utrdl_size, ucdl_size;
3933 /* Allocate memory for UTP command descriptors */
3934 ucdl_size = (sizeof(struct utp_transfer_cmd_desc) * hba->nutrs);
3935 hba->ucdl_base_addr = dmam_alloc_coherent(hba->dev,
3937 &hba->ucdl_dma_addr,
3941 * UFSHCI requires UTP command descriptor to be 128 byte aligned.
3942 * make sure hba->ucdl_dma_addr is aligned to PAGE_SIZE
3943 * if hba->ucdl_dma_addr is aligned to PAGE_SIZE, then it will
3944 * be aligned to 128 bytes as well
3946 if (!hba->ucdl_base_addr ||
3947 WARN_ON(hba->ucdl_dma_addr & (PAGE_SIZE - 1))) {
3949 "Command Descriptor Memory allocation failed\n");
3954 * Allocate memory for UTP Transfer descriptors
3955 * UFSHCI requires 1024 byte alignment of UTRD
3957 utrdl_size = (sizeof(struct utp_transfer_req_desc) * hba->nutrs);
3958 hba->utrdl_base_addr = dmam_alloc_coherent(hba->dev,
3960 &hba->utrdl_dma_addr,
3962 if (!hba->utrdl_base_addr ||
3963 WARN_ON(hba->utrdl_dma_addr & (PAGE_SIZE - 1))) {
3965 "Transfer Descriptor Memory allocation failed\n");
3970 * Allocate memory for UTP Task Management descriptors
3971 * UFSHCI requires 1024 byte alignment of UTMRD
3973 utmrdl_size = sizeof(struct utp_task_req_desc) * hba->nutmrs;
3974 hba->utmrdl_base_addr = dmam_alloc_coherent(hba->dev,
3976 &hba->utmrdl_dma_addr,
3978 if (!hba->utmrdl_base_addr ||
3979 WARN_ON(hba->utmrdl_dma_addr & (PAGE_SIZE - 1))) {
3981 "Task Management Descriptor Memory allocation failed\n");
3985 /* Allocate memory for local reference block */
3986 hba->lrb = devm_kzalloc(hba->dev,
3987 hba->nutrs * sizeof(struct ufshcd_lrb),
3990 dev_err(hba->dev, "LRB Memory allocation failed\n");
3999 * ufshcd_host_memory_configure - configure local reference block with
4001 * @hba: per adapter instance
4003 * Configure Host memory space
4004 * 1. Update Corresponding UTRD.UCDBA and UTRD.UCDBAU with UCD DMA
4006 * 2. Update each UTRD with Response UPIU offset, Response UPIU length
4008 * 3. Save the corresponding addresses of UTRD, UCD.CMD, UCD.RSP and UCD.PRDT
4009 * into local reference block.
4011 static void ufshcd_host_memory_configure(struct ufs_hba *hba)
4013 struct utp_transfer_cmd_desc *cmd_descp;
4014 struct utp_transfer_req_desc *utrdlp;
4015 dma_addr_t cmd_desc_dma_addr;
4016 dma_addr_t cmd_desc_element_addr;
4017 u16 response_offset;
4022 utrdlp = hba->utrdl_base_addr;
4023 cmd_descp = hba->ucdl_base_addr;
4026 offsetof(struct utp_transfer_cmd_desc, response_upiu);
4028 offsetof(struct utp_transfer_cmd_desc, prd_table);
4030 cmd_desc_size = sizeof(struct utp_transfer_cmd_desc);
4031 cmd_desc_dma_addr = hba->ucdl_dma_addr;
4033 for (i = 0; i < hba->nutrs; i++) {
4034 /* Configure UTRD with command descriptor base address */
4035 cmd_desc_element_addr =
4036 (cmd_desc_dma_addr + (cmd_desc_size * i));
4037 utrdlp[i].command_desc_base_addr_lo =
4038 cpu_to_le32(lower_32_bits(cmd_desc_element_addr));
4039 utrdlp[i].command_desc_base_addr_hi =
4040 cpu_to_le32(upper_32_bits(cmd_desc_element_addr));
4042 /* Response upiu and prdt offset should be in double words */
4043 utrdlp[i].response_upiu_offset =
4044 cpu_to_le16((response_offset >> 2));
4045 utrdlp[i].prd_table_offset =
4046 cpu_to_le16((prdt_offset >> 2));
4047 utrdlp[i].response_upiu_length =
4048 cpu_to_le16(ALIGNED_UPIU_SIZE >> 2);
4050 hba->lrb[i].utr_descriptor_ptr = (utrdlp + i);
4051 hba->lrb[i].utrd_dma_addr = hba->utrdl_dma_addr +
4052 (i * sizeof(struct utp_transfer_req_desc));
4053 hba->lrb[i].ucd_req_ptr =
4054 (struct utp_upiu_req *)(cmd_descp + i);
4055 hba->lrb[i].ucd_req_dma_addr = cmd_desc_element_addr;
4056 hba->lrb[i].ucd_rsp_ptr =
4057 (struct utp_upiu_rsp *)cmd_descp[i].response_upiu;
4058 hba->lrb[i].ucd_rsp_dma_addr = cmd_desc_element_addr +
4060 hba->lrb[i].ucd_prdt_ptr =
4061 (struct ufshcd_sg_entry *)cmd_descp[i].prd_table;
4062 hba->lrb[i].ucd_prdt_dma_addr = cmd_desc_element_addr +
4068 * ufshcd_dme_link_startup - Notify Unipro to perform link startup
4069 * @hba: per adapter instance
4071 * UIC_CMD_DME_LINK_STARTUP command must be issued to Unipro layer,
4072 * in order to initialize the Unipro link startup procedure.
4073 * Once the Unipro links are up, the device connected to the controller
4076 * Returns 0 on success, non-zero value on failure
4078 static int ufshcd_dme_link_startup(struct ufs_hba *hba)
4080 struct uic_command uic_cmd = {0};
4083 uic_cmd.command = UIC_CMD_DME_LINK_STARTUP;
4085 ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
4088 "dme-link-startup: error code %d\n", ret);
4092 static inline void ufshcd_add_delay_before_dme_cmd(struct ufs_hba *hba)
4094 #define MIN_DELAY_BEFORE_DME_CMDS_US 1000
4095 unsigned long min_sleep_time_us;
4097 if (!(hba->quirks & UFSHCD_QUIRK_DELAY_BEFORE_DME_CMDS))
4101 * last_dme_cmd_tstamp will be 0 only for 1st call to
4104 if (unlikely(!ktime_to_us(hba->last_dme_cmd_tstamp))) {
4105 min_sleep_time_us = MIN_DELAY_BEFORE_DME_CMDS_US;
4107 unsigned long delta =
4108 (unsigned long) ktime_to_us(
4109 ktime_sub(ktime_get(),
4110 hba->last_dme_cmd_tstamp));
4112 if (delta < MIN_DELAY_BEFORE_DME_CMDS_US)
4114 MIN_DELAY_BEFORE_DME_CMDS_US - delta;
4116 return; /* no more delay required */
4119 /* allow sleep for extra 50us if needed */
4120 usleep_range(min_sleep_time_us, min_sleep_time_us + 50);
4123 static inline void ufshcd_save_tstamp_of_last_dme_cmd(
4124 struct ufs_hba *hba)
4126 if (hba->quirks & UFSHCD_QUIRK_DELAY_BEFORE_DME_CMDS)
4127 hba->last_dme_cmd_tstamp = ktime_get();
4131 * ufshcd_dme_set_attr - UIC command for DME_SET, DME_PEER_SET
4132 * @hba: per adapter instance
4133 * @attr_sel: uic command argument1
4134 * @attr_set: attribute set type as uic command argument2
4135 * @mib_val: setting value as uic command argument3
4136 * @peer: indicate whether peer or local
4138 * Returns 0 on success, non-zero value on failure
4140 int ufshcd_dme_set_attr(struct ufs_hba *hba, u32 attr_sel,
4141 u8 attr_set, u32 mib_val, u8 peer)
4143 struct uic_command uic_cmd = {0};
4144 static const char *const action[] = {
4148 const char *set = action[!!peer];
4150 int retries = UFS_UIC_COMMAND_RETRIES;
4152 ufsdbg_error_inject_dispatcher(hba,
4153 ERR_INJECT_DME_ATTR, attr_sel, &attr_sel);
4155 uic_cmd.command = peer ?
4156 UIC_CMD_DME_PEER_SET : UIC_CMD_DME_SET;
4157 uic_cmd.argument1 = attr_sel;
4158 uic_cmd.argument2 = UIC_ARG_ATTR_TYPE(attr_set);
4159 uic_cmd.argument3 = mib_val;
4162 /* for peer attributes we retry upon failure */
4163 ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
4165 dev_dbg(hba->dev, "%s: attr-id 0x%x val 0x%x error code %d\n",
4166 set, UIC_GET_ATTR_ID(attr_sel), mib_val, ret);
4167 } while (ret && peer && --retries);
4170 dev_err(hba->dev, "%s: attr-id 0x%x val 0x%x failed %d retries\n",
4171 set, UIC_GET_ATTR_ID(attr_sel), mib_val,
4172 UFS_UIC_COMMAND_RETRIES - retries);
4176 EXPORT_SYMBOL_GPL(ufshcd_dme_set_attr);
4179 * ufshcd_dme_get_attr - UIC command for DME_GET, DME_PEER_GET
4180 * @hba: per adapter instance
4181 * @attr_sel: uic command argument1
4182 * @mib_val: the value of the attribute as returned by the UIC command
4183 * @peer: indicate whether peer or local
4185 * Returns 0 on success, non-zero value on failure
4187 int ufshcd_dme_get_attr(struct ufs_hba *hba, u32 attr_sel,
4188 u32 *mib_val, u8 peer)
4190 struct uic_command uic_cmd = {0};
4191 static const char *const action[] = {
4195 const char *get = action[!!peer];
4197 int retries = UFS_UIC_COMMAND_RETRIES;
4198 struct ufs_pa_layer_attr orig_pwr_info;
4199 struct ufs_pa_layer_attr temp_pwr_info;
4200 bool pwr_mode_change = false;
4202 if (peer && (hba->quirks & UFSHCD_QUIRK_DME_PEER_ACCESS_AUTO_MODE)) {
4203 orig_pwr_info = hba->pwr_info;
4204 temp_pwr_info = orig_pwr_info;
4206 if (orig_pwr_info.pwr_tx == FAST_MODE ||
4207 orig_pwr_info.pwr_rx == FAST_MODE) {
4208 temp_pwr_info.pwr_tx = FASTAUTO_MODE;
4209 temp_pwr_info.pwr_rx = FASTAUTO_MODE;
4210 pwr_mode_change = true;
4211 } else if (orig_pwr_info.pwr_tx == SLOW_MODE ||
4212 orig_pwr_info.pwr_rx == SLOW_MODE) {
4213 temp_pwr_info.pwr_tx = SLOWAUTO_MODE;
4214 temp_pwr_info.pwr_rx = SLOWAUTO_MODE;
4215 pwr_mode_change = true;
4217 if (pwr_mode_change) {
4218 ret = ufshcd_change_power_mode(hba, &temp_pwr_info);
4224 uic_cmd.command = peer ?
4225 UIC_CMD_DME_PEER_GET : UIC_CMD_DME_GET;
4227 ufsdbg_error_inject_dispatcher(hba,
4228 ERR_INJECT_DME_ATTR, attr_sel, &attr_sel);
4230 uic_cmd.argument1 = attr_sel;
4233 /* for peer attributes we retry upon failure */
4234 ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
4236 dev_dbg(hba->dev, "%s: attr-id 0x%x error code %d\n",
4237 get, UIC_GET_ATTR_ID(attr_sel), ret);
4238 } while (ret && peer && --retries);
4241 dev_err(hba->dev, "%s: attr-id 0x%x failed %d retries\n",
4242 get, UIC_GET_ATTR_ID(attr_sel),
4243 UFS_UIC_COMMAND_RETRIES - retries);
4245 if (mib_val && !ret)
4246 *mib_val = uic_cmd.argument3;
4248 if (peer && (hba->quirks & UFSHCD_QUIRK_DME_PEER_ACCESS_AUTO_MODE)
4250 ufshcd_change_power_mode(hba, &orig_pwr_info);
4254 EXPORT_SYMBOL_GPL(ufshcd_dme_get_attr);
4257 * ufshcd_uic_pwr_ctrl - executes UIC commands (which affects the link power
4258 * state) and waits for it to take effect.
4260 * @hba: per adapter instance
4261 * @cmd: UIC command to execute
4263 * DME operations like DME_SET(PA_PWRMODE), DME_HIBERNATE_ENTER &
4264 * DME_HIBERNATE_EXIT commands take some time to take its effect on both host
4265 * and device UniPro link and hence it's final completion would be indicated by
4266 * dedicated status bits in Interrupt Status register (UPMS, UHES, UHXS) in
4267 * addition to normal UIC command completion Status (UCCS). This function only
4268 * returns after the relevant status bits indicate the completion.
4270 * Returns 0 on success, non-zero value on failure
4272 static int ufshcd_uic_pwr_ctrl(struct ufs_hba *hba, struct uic_command *cmd)
4274 struct completion uic_async_done;
4275 unsigned long flags;
4278 bool reenable_intr = false;
4280 mutex_lock(&hba->uic_cmd_mutex);
4281 init_completion(&uic_async_done);
4282 ufshcd_add_delay_before_dme_cmd(hba);
4284 spin_lock_irqsave(hba->host->host_lock, flags);
4285 hba->uic_async_done = &uic_async_done;
4286 if (ufshcd_readl(hba, REG_INTERRUPT_ENABLE) & UIC_COMMAND_COMPL) {
4287 ufshcd_disable_intr(hba, UIC_COMMAND_COMPL);
4289 * Make sure UIC command completion interrupt is disabled before
4290 * issuing UIC command.
4293 reenable_intr = true;
4295 ret = __ufshcd_send_uic_cmd(hba, cmd, false);
4296 spin_unlock_irqrestore(hba->host->host_lock, flags);
4299 "pwr ctrl cmd 0x%x with mode 0x%x uic error %d\n",
4300 cmd->command, cmd->argument3, ret);
4304 if (!wait_for_completion_timeout(hba->uic_async_done,
4305 msecs_to_jiffies(UIC_CMD_TIMEOUT))) {
4307 "pwr ctrl cmd 0x%x with mode 0x%x completion timeout\n",
4308 cmd->command, cmd->argument3);
4313 status = ufshcd_get_upmcrs(hba);
4314 if (status != PWR_LOCAL) {
4316 "pwr ctrl cmd 0x%0x failed, host umpcrs:0x%x\n",
4317 cmd->command, status);
4318 ret = (status != PWR_OK) ? status : -1;
4320 ufshcd_dme_cmd_log(hba, "cmp2", hba->active_uic_cmd->command);
4324 ufsdbg_set_err_state(hba);
4325 ufshcd_print_host_state(hba);
4326 ufshcd_print_pwr_info(hba);
4327 ufshcd_print_host_regs(hba);
4328 ufshcd_print_cmd_log(hba);
4331 ufshcd_save_tstamp_of_last_dme_cmd(hba);
4332 spin_lock_irqsave(hba->host->host_lock, flags);
4333 hba->active_uic_cmd = NULL;
4334 hba->uic_async_done = NULL;
4336 ufshcd_enable_intr(hba, UIC_COMMAND_COMPL);
4337 spin_unlock_irqrestore(hba->host->host_lock, flags);
4338 mutex_unlock(&hba->uic_cmd_mutex);
4342 int ufshcd_wait_for_doorbell_clr(struct ufs_hba *hba, u64 wait_timeout_us)
4344 unsigned long flags;
4348 bool timeout = false, do_last_check = false;
4351 ufshcd_hold_all(hba);
4352 spin_lock_irqsave(hba->host->host_lock, flags);
4354 * Wait for all the outstanding tasks/transfer requests.
4355 * Verify by checking the doorbell registers are clear.
4357 start = ktime_get();
4359 if (hba->ufshcd_state != UFSHCD_STATE_OPERATIONAL) {
4364 tm_doorbell = ufshcd_readl(hba, REG_UTP_TASK_REQ_DOOR_BELL);
4365 tr_doorbell = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
4366 if (!tm_doorbell && !tr_doorbell) {
4369 } else if (do_last_check) {
4373 spin_unlock_irqrestore(hba->host->host_lock, flags);
4375 if (ktime_to_us(ktime_sub(ktime_get(), start)) >
4379 * We might have scheduled out for long time so make
4380 * sure to check if doorbells are cleared by this time
4383 do_last_check = true;
4385 spin_lock_irqsave(hba->host->host_lock, flags);
4386 } while (tm_doorbell || tr_doorbell);
4390 "%s: timedout waiting for doorbell to clear (tm=0x%x, tr=0x%x)\n",
4391 __func__, tm_doorbell, tr_doorbell);
4395 spin_unlock_irqrestore(hba->host->host_lock, flags);
4396 ufshcd_release_all(hba);
4401 * ufshcd_uic_change_pwr_mode - Perform the UIC power mode chage
4402 * using DME_SET primitives.
4403 * @hba: per adapter instance
4404 * @mode: powr mode value
4406 * Returns 0 on success, non-zero value on failure
4408 static int ufshcd_uic_change_pwr_mode(struct ufs_hba *hba, u8 mode)
4410 struct uic_command uic_cmd = {0};
4413 if (hba->quirks & UFSHCD_QUIRK_BROKEN_PA_RXHSUNTERMCAP) {
4414 ret = ufshcd_dme_set(hba,
4415 UIC_ARG_MIB_SEL(PA_RXHSUNTERMCAP, 0), 1);
4417 dev_err(hba->dev, "%s: failed to enable PA_RXHSUNTERMCAP ret %d\n",
4423 uic_cmd.command = UIC_CMD_DME_SET;
4424 uic_cmd.argument1 = UIC_ARG_MIB(PA_PWRMODE);
4425 uic_cmd.argument3 = mode;
4426 hba->ufs_stats.clk_hold.ctx = PWRCTL_CMD_SEND;
4427 ufshcd_hold_all(hba);
4428 ret = ufshcd_uic_pwr_ctrl(hba, &uic_cmd);
4429 hba->ufs_stats.clk_rel.ctx = PWRCTL_CMD_SEND;
4430 ufshcd_release_all(hba);
4435 static int ufshcd_link_recovery(struct ufs_hba *hba)
4438 unsigned long flags;
4441 * Check if there is any race with fatal error handling.
4442 * If so, wait for it to complete. Even though fatal error
4443 * handling does reset and restore in some cases, don't assume
4444 * anything out of it. We are just avoiding race here.
4447 spin_lock_irqsave(hba->host->host_lock, flags);
4448 if (!(work_pending(&hba->eh_work) ||
4449 hba->ufshcd_state == UFSHCD_STATE_RESET))
4451 spin_unlock_irqrestore(hba->host->host_lock, flags);
4452 dev_dbg(hba->dev, "%s: reset in progress\n", __func__);
4453 flush_work(&hba->eh_work);
4458 * we don't know if previous reset had really reset the host controller
4459 * or not. So let's force reset here to be sure.
4461 hba->ufshcd_state = UFSHCD_STATE_ERROR;
4462 hba->force_host_reset = true;
4463 schedule_work(&hba->eh_work);
4465 /* wait for the reset work to finish */
4467 if (!(work_pending(&hba->eh_work) ||
4468 hba->ufshcd_state == UFSHCD_STATE_RESET))
4470 spin_unlock_irqrestore(hba->host->host_lock, flags);
4471 dev_dbg(hba->dev, "%s: reset in progress\n", __func__);
4472 flush_work(&hba->eh_work);
4473 spin_lock_irqsave(hba->host->host_lock, flags);
4476 if (!((hba->ufshcd_state == UFSHCD_STATE_OPERATIONAL) &&
4477 ufshcd_is_link_active(hba)))
4479 spin_unlock_irqrestore(hba->host->host_lock, flags);
4484 static int __ufshcd_uic_hibern8_enter(struct ufs_hba *hba)
4487 struct uic_command uic_cmd = {0};
4488 ktime_t start = ktime_get();
4490 uic_cmd.command = UIC_CMD_DME_HIBER_ENTER;
4491 ret = ufshcd_uic_pwr_ctrl(hba, &uic_cmd);
4492 trace_ufshcd_profile_hibern8(dev_name(hba->dev), "enter",
4493 ktime_to_us(ktime_sub(ktime_get(), start)), ret);
4496 * Do full reinit if enter failed or if LINERESET was detected during
4497 * Hibern8 operation. After LINERESET, link moves to default PWM-G1
4498 * mode hence full reinit is required to move link to HS speeds.
4500 if (ret || hba->full_init_linereset) {
4503 hba->full_init_linereset = false;
4504 ufshcd_update_error_stats(hba, UFS_ERR_HIBERN8_ENTER);
4505 dev_err(hba->dev, "%s: hibern8 enter failed. ret = %d",
4508 * If link recovery fails then return error code (-ENOLINK)
4509 * returned ufshcd_link_recovery().
4510 * If link recovery succeeds then return -EAGAIN to attempt
4511 * hibern8 enter retry again.
4513 err = ufshcd_link_recovery(hba);
4515 dev_err(hba->dev, "%s: link recovery failed", __func__);
4521 dev_dbg(hba->dev, "%s: Hibern8 Enter at %lld us", __func__,
4522 ktime_to_us(ktime_get()));
4528 int ufshcd_uic_hibern8_enter(struct ufs_hba *hba)
4530 int ret = 0, retries;
4532 for (retries = UIC_HIBERN8_ENTER_RETRIES; retries > 0; retries--) {
4533 ret = __ufshcd_uic_hibern8_enter(hba);
4536 else if (ret != -EAGAIN)
4537 /* Unable to recover the link, so no point proceeding */
4544 int ufshcd_uic_hibern8_exit(struct ufs_hba *hba)
4546 struct uic_command uic_cmd = {0};
4548 ktime_t start = ktime_get();
4550 uic_cmd.command = UIC_CMD_DME_HIBER_EXIT;
4551 ret = ufshcd_uic_pwr_ctrl(hba, &uic_cmd);
4552 trace_ufshcd_profile_hibern8(dev_name(hba->dev), "exit",
4553 ktime_to_us(ktime_sub(ktime_get(), start)), ret);
4555 /* Do full reinit if exit failed */
4557 ufshcd_update_error_stats(hba, UFS_ERR_HIBERN8_EXIT);
4558 dev_err(hba->dev, "%s: hibern8 exit failed. ret = %d",
4560 ret = ufshcd_link_recovery(hba);
4561 /* Unable to recover the link, so no point proceeding */
4565 dev_dbg(hba->dev, "%s: Hibern8 Exit at %lld us", __func__,
4566 ktime_to_us(ktime_get()));
4567 hba->ufs_stats.last_hibern8_exit_tstamp = ktime_get();
4568 hba->ufs_stats.hibern8_exit_cnt++;
4575 * ufshcd_init_pwr_info - setting the POR (power on reset)
4576 * values in hba power info
4577 * @hba: per-adapter instance
4579 static void ufshcd_init_pwr_info(struct ufs_hba *hba)
4581 hba->pwr_info.gear_rx = UFS_PWM_G1;
4582 hba->pwr_info.gear_tx = UFS_PWM_G1;
4583 hba->pwr_info.lane_rx = 1;
4584 hba->pwr_info.lane_tx = 1;
4585 hba->pwr_info.pwr_rx = SLOWAUTO_MODE;
4586 hba->pwr_info.pwr_tx = SLOWAUTO_MODE;
4587 hba->pwr_info.hs_rate = 0;
4591 * ufshcd_get_max_pwr_mode - reads the max power mode negotiated with device
4592 * @hba: per-adapter instance
4594 static int ufshcd_get_max_pwr_mode(struct ufs_hba *hba)
4596 struct ufs_pa_layer_attr *pwr_info = &hba->max_pwr_info.info;
4598 if (hba->max_pwr_info.is_valid)
4601 pwr_info->pwr_tx = FAST_MODE;
4602 pwr_info->pwr_rx = FAST_MODE;
4603 pwr_info->hs_rate = PA_HS_MODE_B;
4605 /* Get the connected lane count */
4606 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_CONNECTEDRXDATALANES),
4607 &pwr_info->lane_rx);
4608 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_CONNECTEDTXDATALANES),
4609 &pwr_info->lane_tx);
4611 if (!pwr_info->lane_rx || !pwr_info->lane_tx) {
4612 dev_err(hba->dev, "%s: invalid connected lanes value. rx=%d, tx=%d\n",
4620 * First, get the maximum gears of HS speed.
4621 * If a zero value, it means there is no HSGEAR capability.
4622 * Then, get the maximum gears of PWM speed.
4624 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_MAXRXHSGEAR), &pwr_info->gear_rx);
4625 if (!pwr_info->gear_rx) {
4626 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_MAXRXPWMGEAR),
4627 &pwr_info->gear_rx);
4628 if (!pwr_info->gear_rx) {
4629 dev_err(hba->dev, "%s: invalid max pwm rx gear read = %d\n",
4630 __func__, pwr_info->gear_rx);
4633 pwr_info->pwr_rx = SLOW_MODE;
4636 ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_MAXRXHSGEAR),
4637 &pwr_info->gear_tx);
4638 if (!pwr_info->gear_tx) {
4639 ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_MAXRXPWMGEAR),
4640 &pwr_info->gear_tx);
4641 if (!pwr_info->gear_tx) {
4642 dev_err(hba->dev, "%s: invalid max pwm tx gear read = %d\n",
4643 __func__, pwr_info->gear_tx);
4646 pwr_info->pwr_tx = SLOW_MODE;
4649 hba->max_pwr_info.is_valid = true;
4653 int ufshcd_change_power_mode(struct ufs_hba *hba,
4654 struct ufs_pa_layer_attr *pwr_mode)
4658 /* if already configured to the requested pwr_mode */
4659 if (!hba->restore_needed &&
4660 pwr_mode->gear_rx == hba->pwr_info.gear_rx &&
4661 pwr_mode->gear_tx == hba->pwr_info.gear_tx &&
4662 pwr_mode->lane_rx == hba->pwr_info.lane_rx &&
4663 pwr_mode->lane_tx == hba->pwr_info.lane_tx &&
4664 pwr_mode->pwr_rx == hba->pwr_info.pwr_rx &&
4665 pwr_mode->pwr_tx == hba->pwr_info.pwr_tx &&
4666 pwr_mode->hs_rate == hba->pwr_info.hs_rate) {
4667 dev_dbg(hba->dev, "%s: power already configured\n", __func__);
4671 ufsdbg_error_inject_dispatcher(hba, ERR_INJECT_PWR_CHANGE, 0, &ret);
4676 * Configure attributes for power mode change with below.
4677 * - PA_RXGEAR, PA_ACTIVERXDATALANES, PA_RXTERMINATION,
4678 * - PA_TXGEAR, PA_ACTIVETXDATALANES, PA_TXTERMINATION,
4681 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_RXGEAR), pwr_mode->gear_rx);
4682 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_ACTIVERXDATALANES),
4684 if (pwr_mode->pwr_rx == FASTAUTO_MODE ||
4685 pwr_mode->pwr_rx == FAST_MODE)
4686 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_RXTERMINATION), TRUE);
4688 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_RXTERMINATION), FALSE);
4690 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TXGEAR), pwr_mode->gear_tx);
4691 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_ACTIVETXDATALANES),
4693 if (pwr_mode->pwr_tx == FASTAUTO_MODE ||
4694 pwr_mode->pwr_tx == FAST_MODE)
4695 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TXTERMINATION), TRUE);
4697 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TXTERMINATION), FALSE);
4699 if (pwr_mode->pwr_rx == FASTAUTO_MODE ||
4700 pwr_mode->pwr_tx == FASTAUTO_MODE ||
4701 pwr_mode->pwr_rx == FAST_MODE ||
4702 pwr_mode->pwr_tx == FAST_MODE)
4703 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_HSSERIES),
4706 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_PWRMODEUSERDATA0),
4707 DL_FC0ProtectionTimeOutVal_Default);
4708 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_PWRMODEUSERDATA1),
4709 DL_TC0ReplayTimeOutVal_Default);
4710 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_PWRMODEUSERDATA2),
4711 DL_AFC0ReqTimeOutVal_Default);
4713 ufshcd_dme_set(hba, UIC_ARG_MIB(DME_LocalFC0ProtectionTimeOutVal),
4714 DL_FC0ProtectionTimeOutVal_Default);
4715 ufshcd_dme_set(hba, UIC_ARG_MIB(DME_LocalTC0ReplayTimeOutVal),
4716 DL_TC0ReplayTimeOutVal_Default);
4717 ufshcd_dme_set(hba, UIC_ARG_MIB(DME_LocalAFC0ReqTimeOutVal),
4718 DL_AFC0ReqTimeOutVal_Default);
4720 ret = ufshcd_uic_change_pwr_mode(hba, pwr_mode->pwr_rx << 4
4721 | pwr_mode->pwr_tx);
4724 ufshcd_update_error_stats(hba, UFS_ERR_POWER_MODE_CHANGE);
4726 "%s: power mode change failed %d\n", __func__, ret);
4728 ufshcd_vops_pwr_change_notify(hba, POST_CHANGE, NULL,
4731 memcpy(&hba->pwr_info, pwr_mode,
4732 sizeof(struct ufs_pa_layer_attr));
4733 hba->ufs_stats.power_mode_change_cnt++;
4740 * ufshcd_config_pwr_mode - configure a new power mode
4741 * @hba: per-adapter instance
4742 * @desired_pwr_mode: desired power configuration
4744 static int ufshcd_config_pwr_mode(struct ufs_hba *hba,
4745 struct ufs_pa_layer_attr *desired_pwr_mode)
4747 struct ufs_pa_layer_attr final_params = { 0 };
4750 ret = ufshcd_vops_pwr_change_notify(hba, PRE_CHANGE,
4751 desired_pwr_mode, &final_params);
4754 memcpy(&final_params, desired_pwr_mode, sizeof(final_params));
4756 ret = ufshcd_change_power_mode(hba, &final_params);
4758 ufshcd_print_pwr_info(hba);
4764 * ufshcd_complete_dev_init() - checks device readiness
4765 * hba: per-adapter instance
4767 * Set fDeviceInit flag and poll until device toggles it.
4769 static int ufshcd_complete_dev_init(struct ufs_hba *hba)
4775 err = ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_SET_FLAG,
4776 QUERY_FLAG_IDN_FDEVICEINIT, NULL);
4779 "%s setting fDeviceInit flag failed with error %d\n",
4784 /* poll for max. 1000 iterations for fDeviceInit flag to clear */
4785 for (i = 0; i < 1000 && !err && flag_res; i++)
4786 err = ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_READ_FLAG,
4787 QUERY_FLAG_IDN_FDEVICEINIT, &flag_res);
4791 "%s reading fDeviceInit flag failed with error %d\n",
4795 "%s fDeviceInit was not cleared by the device\n",
4803 * ufshcd_make_hba_operational - Make UFS controller operational
4804 * @hba: per adapter instance
4806 * To bring UFS host controller to operational state,
4807 * 1. Enable required interrupts
4808 * 2. Configure interrupt aggregation
4809 * 3. Program UTRL and UTMRL base address
4810 * 4. Configure run-stop-registers
4812 * Returns 0 on success, non-zero value on failure
4814 static int ufshcd_make_hba_operational(struct ufs_hba *hba)
4819 /* Enable required interrupts */
4820 ufshcd_enable_intr(hba, UFSHCD_ENABLE_INTRS);
4822 /* Configure interrupt aggregation */
4823 if (ufshcd_is_intr_aggr_allowed(hba))
4824 ufshcd_config_intr_aggr(hba, hba->nutrs - 1, INT_AGGR_DEF_TO);
4826 ufshcd_disable_intr_aggr(hba);
4828 /* Configure UTRL and UTMRL base address registers */
4829 ufshcd_writel(hba, lower_32_bits(hba->utrdl_dma_addr),
4830 REG_UTP_TRANSFER_REQ_LIST_BASE_L);
4831 ufshcd_writel(hba, upper_32_bits(hba->utrdl_dma_addr),
4832 REG_UTP_TRANSFER_REQ_LIST_BASE_H);
4833 ufshcd_writel(hba, lower_32_bits(hba->utmrdl_dma_addr),
4834 REG_UTP_TASK_REQ_LIST_BASE_L);
4835 ufshcd_writel(hba, upper_32_bits(hba->utmrdl_dma_addr),
4836 REG_UTP_TASK_REQ_LIST_BASE_H);
4839 * Make sure base address and interrupt setup are updated before
4840 * enabling the run/stop registers below.
4845 * UCRDY, UTMRLDY and UTRLRDY bits must be 1
4847 reg = ufshcd_readl(hba, REG_CONTROLLER_STATUS);
4848 if (!(ufshcd_get_lists_status(reg))) {
4849 ufshcd_enable_run_stop_reg(hba);
4852 "Host controller not ready to process requests");
4862 * ufshcd_hba_stop - Send controller to reset state
4863 * @hba: per adapter instance
4864 * @can_sleep: perform sleep or just spin
4866 static inline void ufshcd_hba_stop(struct ufs_hba *hba, bool can_sleep)
4870 ufshcd_writel(hba, CONTROLLER_DISABLE, REG_CONTROLLER_ENABLE);
4871 err = ufshcd_wait_for_register(hba, REG_CONTROLLER_ENABLE,
4872 CONTROLLER_ENABLE, CONTROLLER_DISABLE,
4875 dev_err(hba->dev, "%s: Controller disable failed\n", __func__);
4879 * ufshcd_hba_enable - initialize the controller
4880 * @hba: per adapter instance
4882 * The controller resets itself and controller firmware initialization
4883 * sequence kicks off. When controller is ready it will set
4884 * the Host Controller Enable bit to 1.
4886 * Returns 0 on success, non-zero value on failure
4888 static int ufshcd_hba_enable(struct ufs_hba *hba)
4893 * msleep of 1 and 5 used in this function might result in msleep(20),
4894 * but it was necessary to send the UFS FPGA to reset mode during
4895 * development and testing of this driver. msleep can be changed to
4896 * mdelay and retry count can be reduced based on the controller.
4898 if (!ufshcd_is_hba_active(hba))
4899 /* change controller state to "reset state" */
4900 ufshcd_hba_stop(hba, true);
4902 /* UniPro link is disabled at this point */
4903 ufshcd_set_link_off(hba);
4905 ufshcd_vops_hce_enable_notify(hba, PRE_CHANGE);
4907 /* start controller initialization sequence */
4908 ufshcd_hba_start(hba);
4911 * To initialize a UFS host controller HCE bit must be set to 1.
4912 * During initialization the HCE bit value changes from 1->0->1.
4913 * When the host controller completes initialization sequence
4914 * it sets the value of HCE bit to 1. The same HCE bit is read back
4915 * to check if the controller has completed initialization sequence.
4916 * So without this delay the value HCE = 1, set in the previous
4917 * instruction might be read back.
4918 * This delay can be changed based on the controller.
4922 /* wait for the host controller to complete initialization */
4924 while (ufshcd_is_hba_active(hba)) {
4929 "Controller enable failed\n");
4935 /* enable UIC related interrupts */
4936 ufshcd_enable_intr(hba, UFSHCD_UIC_MASK);
4938 ufshcd_vops_hce_enable_notify(hba, POST_CHANGE);
4943 static int ufshcd_disable_tx_lcc(struct ufs_hba *hba, bool peer)
4945 int tx_lanes, i, err = 0;
4948 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_CONNECTEDTXDATALANES),
4951 ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_CONNECTEDTXDATALANES),
4953 for (i = 0; i < tx_lanes; i++) {
4955 err = ufshcd_dme_set(hba,
4956 UIC_ARG_MIB_SEL(TX_LCC_ENABLE,
4957 UIC_ARG_MPHY_TX_GEN_SEL_INDEX(i)),
4960 err = ufshcd_dme_peer_set(hba,
4961 UIC_ARG_MIB_SEL(TX_LCC_ENABLE,
4962 UIC_ARG_MPHY_TX_GEN_SEL_INDEX(i)),
4965 dev_err(hba->dev, "%s: TX LCC Disable failed, peer = %d, lane = %d, err = %d",
4966 __func__, peer, i, err);
4974 static inline int ufshcd_disable_host_tx_lcc(struct ufs_hba *hba)
4976 return ufshcd_disable_tx_lcc(hba, false);
4979 static inline int ufshcd_disable_device_tx_lcc(struct ufs_hba *hba)
4981 return ufshcd_disable_tx_lcc(hba, true);
4985 * ufshcd_link_startup - Initialize unipro link startup
4986 * @hba: per adapter instance
4988 * Returns 0 for success, non-zero in case of failure
4990 static int ufshcd_link_startup(struct ufs_hba *hba)
4993 int retries = DME_LINKSTARTUP_RETRIES;
4994 bool link_startup_again = false;
4997 * If UFS device isn't active then we will have to issue link startup
4998 * 2 times to make sure the device state move to active.
5000 if (!ufshcd_is_ufs_dev_active(hba))
5001 link_startup_again = true;
5005 ufshcd_vops_link_startup_notify(hba, PRE_CHANGE);
5007 ret = ufshcd_dme_link_startup(hba);
5009 ufshcd_update_error_stats(hba, UFS_ERR_LINKSTARTUP);
5011 /* check if device is detected by inter-connect layer */
5012 if (!ret && !ufshcd_is_device_present(hba)) {
5013 ufshcd_update_error_stats(hba, UFS_ERR_LINKSTARTUP);
5014 dev_err(hba->dev, "%s: Device not present\n", __func__);
5020 * DME link lost indication is only received when link is up,
5021 * but we can't be sure if the link is up until link startup
5022 * succeeds. So reset the local Uni-Pro and try again.
5024 if (ret && ufshcd_hba_enable(hba))
5026 } while (ret && retries--);
5029 /* failed to get the link up... retire */
5032 if (link_startup_again) {
5033 link_startup_again = false;
5034 retries = DME_LINKSTARTUP_RETRIES;
5038 /* Mark that link is up in PWM-G1, 1-lane, SLOW-AUTO mode */
5039 ufshcd_init_pwr_info(hba);
5040 ufshcd_print_pwr_info(hba);
5042 if (hba->quirks & UFSHCD_QUIRK_BROKEN_LCC) {
5043 ret = ufshcd_disable_device_tx_lcc(hba);
5048 if (hba->dev_quirks & UFS_DEVICE_QUIRK_BROKEN_LCC) {
5049 ret = ufshcd_disable_host_tx_lcc(hba);
5054 /* Include any host controller configuration via UIC commands */
5055 ret = ufshcd_vops_link_startup_notify(hba, POST_CHANGE);
5059 ret = ufshcd_make_hba_operational(hba);
5062 dev_err(hba->dev, "link startup failed %d\n", ret);
5063 ufshcd_print_host_state(hba);
5064 ufshcd_print_pwr_info(hba);
5065 ufshcd_print_host_regs(hba);
5071 * ufshcd_verify_dev_init() - Verify device initialization
5072 * @hba: per-adapter instance
5074 * Send NOP OUT UPIU and wait for NOP IN response to check whether the
5075 * device Transport Protocol (UTP) layer is ready after a reset.
5076 * If the UTP layer at the device side is not initialized, it may
5077 * not respond with NOP IN UPIU within timeout of %NOP_OUT_TIMEOUT
5078 * and we retry sending NOP OUT for %NOP_OUT_RETRIES iterations.
5080 static int ufshcd_verify_dev_init(struct ufs_hba *hba)
5085 ufshcd_hold_all(hba);
5086 mutex_lock(&hba->dev_cmd.lock);
5087 for (retries = NOP_OUT_RETRIES; retries > 0; retries--) {
5088 err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_NOP,
5091 if (!err || err == -ETIMEDOUT)
5094 dev_dbg(hba->dev, "%s: error %d retrying\n", __func__, err);
5096 mutex_unlock(&hba->dev_cmd.lock);
5097 ufshcd_release_all(hba);
5100 dev_err(hba->dev, "%s: NOP OUT failed %d\n", __func__, err);
5105 * ufshcd_set_queue_depth - set lun queue depth
5106 * @sdev: pointer to SCSI device
5108 * Read bLUQueueDepth value and activate scsi tagged command
5109 * queueing. For WLUN, queue depth is set to 1. For best-effort
5110 * cases (bLUQueueDepth = 0) the queue depth is set to a maximum
5111 * value that host can queue.
5113 static void ufshcd_set_queue_depth(struct scsi_device *sdev)
5117 struct ufs_hba *hba;
5119 hba = shost_priv(sdev->host);
5121 lun_qdepth = hba->nutrs;
5122 ret = ufshcd_read_unit_desc_param(hba,
5123 ufshcd_scsi_to_upiu_lun(sdev->lun),
5124 UNIT_DESC_PARAM_LU_Q_DEPTH,
5126 sizeof(lun_qdepth));
5128 /* Some WLUN doesn't support unit descriptor */
5129 if (ret == -EOPNOTSUPP)
5131 else if (!lun_qdepth)
5132 /* eventually, we can figure out the real queue depth */
5133 lun_qdepth = hba->nutrs;
5135 lun_qdepth = min_t(int, lun_qdepth, hba->nutrs);
5137 dev_dbg(hba->dev, "%s: activate tcq with queue depth %d\n",
5138 __func__, lun_qdepth);
5139 scsi_change_queue_depth(sdev, lun_qdepth);
5143 * ufshcd_get_lu_wp - returns the "b_lu_write_protect" from UNIT DESCRIPTOR
5144 * @hba: per-adapter instance
5145 * @lun: UFS device lun id
5146 * @b_lu_write_protect: pointer to buffer to hold the LU's write protect info
5148 * Returns 0 in case of success and b_lu_write_protect status would be returned
5149 * @b_lu_write_protect parameter.
5150 * Returns -ENOTSUPP if reading b_lu_write_protect is not supported.
5151 * Returns -EINVAL in case of invalid parameters passed to this function.
5153 static int ufshcd_get_lu_wp(struct ufs_hba *hba,
5155 u8 *b_lu_write_protect)
5159 if (!b_lu_write_protect)
5162 * According to UFS device spec, RPMB LU can't be write
5163 * protected so skip reading bLUWriteProtect parameter for
5164 * it. For other W-LUs, UNIT DESCRIPTOR is not available.
5166 else if (lun >= UFS_UPIU_MAX_GENERAL_LUN)
5169 ret = ufshcd_read_unit_desc_param(hba,
5171 UNIT_DESC_PARAM_LU_WR_PROTECT,
5173 sizeof(*b_lu_write_protect));
5178 * ufshcd_get_lu_power_on_wp_status - get LU's power on write protect
5180 * @hba: per-adapter instance
5181 * @sdev: pointer to SCSI device
5184 static inline void ufshcd_get_lu_power_on_wp_status(struct ufs_hba *hba,
5185 struct scsi_device *sdev)
5187 if (hba->dev_info.f_power_on_wp_en &&
5188 !hba->dev_info.is_lu_power_on_wp) {
5189 u8 b_lu_write_protect;
5191 if (!ufshcd_get_lu_wp(hba, ufshcd_scsi_to_upiu_lun(sdev->lun),
5192 &b_lu_write_protect) &&
5193 (b_lu_write_protect == UFS_LU_POWER_ON_WP))
5194 hba->dev_info.is_lu_power_on_wp = true;
5199 * ufshcd_slave_alloc - handle initial SCSI device configurations
5200 * @sdev: pointer to SCSI device
5204 static int ufshcd_slave_alloc(struct scsi_device *sdev)
5206 struct ufs_hba *hba;
5208 hba = shost_priv(sdev->host);
5210 /* Mode sense(6) is not supported by UFS, so use Mode sense(10) */
5211 sdev->use_10_for_ms = 1;
5213 /* allow SCSI layer to restart the device in case of errors */
5214 sdev->allow_restart = 1;
5216 /* REPORT SUPPORTED OPERATION CODES is not supported */
5217 sdev->no_report_opcodes = 1;
5219 /* WRITE_SAME command is not supported */
5220 sdev->no_write_same = 1;
5222 ufshcd_set_queue_depth(sdev);
5224 ufshcd_get_lu_power_on_wp_status(hba, sdev);
5230 * ufshcd_change_queue_depth - change queue depth
5231 * @sdev: pointer to SCSI device
5232 * @depth: required depth to set
5234 * Change queue depth and make sure the max. limits are not crossed.
5236 static int ufshcd_change_queue_depth(struct scsi_device *sdev, int depth)
5238 struct ufs_hba *hba = shost_priv(sdev->host);
5240 if (depth > hba->nutrs)
5242 return scsi_change_queue_depth(sdev, depth);
5246 * ufshcd_slave_configure - adjust SCSI device configurations
5247 * @sdev: pointer to SCSI device
5249 static int ufshcd_slave_configure(struct scsi_device *sdev)
5251 struct request_queue *q = sdev->request_queue;
5253 blk_queue_update_dma_pad(q, PRDT_DATA_BYTE_COUNT_PAD - 1);
5254 blk_queue_max_segment_size(q, PRDT_DATA_BYTE_COUNT_MAX);
5256 sdev->autosuspend_delay = UFSHCD_AUTO_SUSPEND_DELAY_MS;
5257 sdev->use_rpm_auto = 1;
5263 * ufshcd_slave_destroy - remove SCSI device configurations
5264 * @sdev: pointer to SCSI device
5266 static void ufshcd_slave_destroy(struct scsi_device *sdev)
5268 struct ufs_hba *hba;
5270 hba = shost_priv(sdev->host);
5271 /* Drop the reference as it won't be needed anymore */
5272 if (ufshcd_scsi_to_upiu_lun(sdev->lun) == UFS_UPIU_UFS_DEVICE_WLUN) {
5273 unsigned long flags;
5275 spin_lock_irqsave(hba->host->host_lock, flags);
5276 hba->sdev_ufs_device = NULL;
5277 spin_unlock_irqrestore(hba->host->host_lock, flags);
5282 * ufshcd_task_req_compl - handle task management request completion
5283 * @hba: per adapter instance
5284 * @index: index of the completed request
5285 * @resp: task management service response
5287 * Returns non-zero value on error, zero on success
5289 static int ufshcd_task_req_compl(struct ufs_hba *hba, u32 index, u8 *resp)
5291 struct utp_task_req_desc *task_req_descp;
5292 struct utp_upiu_task_rsp *task_rsp_upiup;
5293 unsigned long flags;
5297 spin_lock_irqsave(hba->host->host_lock, flags);
5299 /* Clear completed tasks from outstanding_tasks */
5300 __clear_bit(index, &hba->outstanding_tasks);
5302 task_req_descp = hba->utmrdl_base_addr;
5303 ocs_value = ufshcd_get_tmr_ocs(&task_req_descp[index]);
5305 if (ocs_value == OCS_SUCCESS) {
5306 task_rsp_upiup = (struct utp_upiu_task_rsp *)
5307 task_req_descp[index].task_rsp_upiu;
5308 task_result = be32_to_cpu(task_rsp_upiup->header.dword_1);
5309 task_result = ((task_result & MASK_TASK_RESPONSE) >> 8);
5311 *resp = (u8)task_result;
5313 dev_err(hba->dev, "%s: failed, ocs = 0x%x\n",
5314 __func__, ocs_value);
5316 spin_unlock_irqrestore(hba->host->host_lock, flags);
5322 * ufshcd_scsi_cmd_status - Update SCSI command result based on SCSI status
5323 * @lrb: pointer to local reference block of completed command
5324 * @scsi_status: SCSI command status
5326 * Returns value base on SCSI command status
5329 ufshcd_scsi_cmd_status(struct ufshcd_lrb *lrbp, int scsi_status)
5333 switch (scsi_status) {
5334 case SAM_STAT_CHECK_CONDITION:
5335 ufshcd_copy_sense_data(lrbp);
5337 result |= DID_OK << 16 |
5338 COMMAND_COMPLETE << 8 |
5341 case SAM_STAT_TASK_SET_FULL:
5343 case SAM_STAT_TASK_ABORTED:
5344 ufshcd_copy_sense_data(lrbp);
5345 result |= scsi_status;
5348 result |= DID_ERROR << 16;
5350 } /* end of switch */
5356 * ufshcd_transfer_rsp_status - Get overall status of the response
5357 * @hba: per adapter instance
5358 * @lrb: pointer to local reference block of completed command
5360 * Returns result of the command to notify SCSI midlayer
5363 ufshcd_transfer_rsp_status(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
5370 /* overall command status of utrd */
5371 ocs = ufshcd_get_tr_ocs(lrbp);
5375 result = ufshcd_get_req_rsp(lrbp->ucd_rsp_ptr);
5376 hba->ufs_stats.last_hibern8_exit_tstamp = ktime_set(0, 0);
5378 case UPIU_TRANSACTION_RESPONSE:
5380 * get the response UPIU result to extract
5381 * the SCSI command status
5383 result = ufshcd_get_rsp_upiu_result(lrbp->ucd_rsp_ptr);
5386 * get the result based on SCSI status response
5387 * to notify the SCSI midlayer of the command status
5389 scsi_status = result & MASK_SCSI_STATUS;
5390 result = ufshcd_scsi_cmd_status(lrbp, scsi_status);
5393 * Currently we are only supporting BKOPs exception
5394 * events hence we can ignore BKOPs exception event
5395 * during power management callbacks. BKOPs exception
5396 * event is not expected to be raised in runtime suspend
5397 * callback as it allows the urgent bkops.
5398 * During system suspend, we are anyway forcefully
5399 * disabling the bkops and if urgent bkops is needed
5400 * it will be enabled on system resume. Long term
5401 * solution could be to abort the system suspend if
5402 * UFS device needs urgent BKOPs.
5404 if (!hba->pm_op_in_progress &&
5405 ufshcd_is_exception_event(lrbp->ucd_rsp_ptr))
5406 schedule_work(&hba->eeh_work);
5408 case UPIU_TRANSACTION_REJECT_UPIU:
5409 /* TODO: handle Reject UPIU Response */
5410 result = DID_ERROR << 16;
5412 "Reject UPIU not fully implemented\n");
5415 result = DID_ERROR << 16;
5417 "Unexpected request response code = %x\n",
5423 result |= DID_ABORT << 16;
5425 case OCS_INVALID_COMMAND_STATUS:
5426 result |= DID_REQUEUE << 16;
5428 case OCS_INVALID_CMD_TABLE_ATTR:
5429 case OCS_INVALID_PRDT_ATTR:
5430 case OCS_MISMATCH_DATA_BUF_SIZE:
5431 case OCS_MISMATCH_RESP_UPIU_SIZE:
5432 case OCS_PEER_COMM_FAILURE:
5433 case OCS_FATAL_ERROR:
5434 case OCS_DEVICE_FATAL_ERROR:
5435 case OCS_INVALID_CRYPTO_CONFIG:
5436 case OCS_GENERAL_CRYPTO_ERROR:
5438 result |= DID_ERROR << 16;
5440 "OCS error from controller = %x for tag %d\n",
5441 ocs, lrbp->task_tag);
5443 * This is called in interrupt context, hence avoid sleep
5444 * while printing debug registers. Also print only the minimum
5445 * debug registers needed to debug OCS failure.
5447 __ufshcd_print_host_regs(hba, true);
5448 ufshcd_print_host_state(hba);
5450 } /* end of switch */
5452 if ((host_byte(result) != DID_OK) && !hba->silence_err_logs) {
5453 print_prdt = (ocs == OCS_INVALID_PRDT_ATTR ||
5454 ocs == OCS_MISMATCH_DATA_BUF_SIZE);
5455 ufshcd_print_trs(hba, 1 << lrbp->task_tag, print_prdt);
5458 if ((host_byte(result) == DID_ERROR) ||
5459 (host_byte(result) == DID_ABORT))
5460 ufsdbg_set_err_state(hba);
5466 * ufshcd_uic_cmd_compl - handle completion of uic command
5467 * @hba: per adapter instance
5468 * @intr_status: interrupt status generated by the controller
5471 * IRQ_HANDLED - If interrupt is valid
5472 * IRQ_NONE - If invalid interrupt
5474 static irqreturn_t ufshcd_uic_cmd_compl(struct ufs_hba *hba, u32 intr_status)
5476 irqreturn_t retval = IRQ_NONE;
5478 if ((intr_status & UIC_COMMAND_COMPL) && hba->active_uic_cmd) {
5479 hba->active_uic_cmd->argument2 |=
5480 ufshcd_get_uic_cmd_result(hba);
5481 hba->active_uic_cmd->argument3 =
5482 ufshcd_get_dme_attr_val(hba);
5483 complete(&hba->active_uic_cmd->done);
5484 retval = IRQ_HANDLED;
5487 if (intr_status & UFSHCD_UIC_PWR_MASK) {
5488 if (hba->uic_async_done) {
5489 complete(hba->uic_async_done);
5490 retval = IRQ_HANDLED;
5491 } else if (ufshcd_is_auto_hibern8_supported(hba)) {
5493 * If uic_async_done flag is not set then this
5494 * is an Auto hibern8 err interrupt.
5495 * Perform a host reset followed by a full
5498 hba->ufshcd_state = UFSHCD_STATE_ERROR;
5499 hba->force_host_reset = true;
5500 dev_err(hba->dev, "%s: Auto Hibern8 %s failed - status: 0x%08x, upmcrs: 0x%08x\n",
5501 __func__, (intr_status & UIC_HIBERNATE_ENTER) ?
5503 intr_status, ufshcd_get_upmcrs(hba));
5504 __ufshcd_print_host_regs(hba, true);
5505 ufshcd_print_host_state(hba);
5506 schedule_work(&hba->eh_work);
5507 retval = IRQ_HANDLED;
5514 * ufshcd_abort_outstanding_requests - abort all outstanding transfer requests.
5515 * @hba: per adapter instance
5516 * @result: error result to inform scsi layer about
5518 void ufshcd_abort_outstanding_transfer_requests(struct ufs_hba *hba, int result)
5521 struct ufshcd_lrb *lrbp;
5522 struct scsi_cmnd *cmd;
5524 if (!hba->outstanding_reqs)
5527 for_each_set_bit(index, &hba->outstanding_reqs, hba->nutrs) {
5528 lrbp = &hba->lrb[index];
5531 ufshcd_cond_add_cmd_trace(hba, index, "failed");
5532 ufshcd_update_error_stats(hba,
5533 UFS_ERR_INT_FATAL_ERRORS);
5534 scsi_dma_unmap(cmd);
5535 cmd->result = result;
5536 /* Clear pending transfer requests */
5537 ufshcd_clear_cmd(hba, index);
5538 ufshcd_outstanding_req_clear(hba, index);
5539 clear_bit_unlock(index, &hba->lrb_in_use);
5540 lrbp->complete_time_stamp = ktime_get();
5541 update_req_stats(hba, lrbp);
5542 /* Mark completed command as NULL in LRB */
5544 ufshcd_release_all(hba);
5547 * As we are accessing the "request" structure,
5548 * this must be called before calling
5549 * ->scsi_done() callback.
5551 ufshcd_vops_pm_qos_req_end(hba, cmd->request,
5553 ufshcd_vops_crypto_engine_cfg_end(hba,
5554 lrbp, cmd->request);
5556 /* Do not touch lrbp after scsi done */
5557 cmd->scsi_done(cmd);
5558 } else if (lrbp->command_type == UTP_CMD_TYPE_DEV_MANAGE) {
5559 if (hba->dev_cmd.complete) {
5560 ufshcd_cond_add_cmd_trace(hba, index,
5562 ufshcd_outstanding_req_clear(hba, index);
5563 complete(hba->dev_cmd.complete);
5566 if (ufshcd_is_clkscaling_supported(hba))
5567 hba->clk_scaling.active_reqs--;
5572 * __ufshcd_transfer_req_compl - handle SCSI and query command completion
5573 * @hba: per adapter instance
5574 * @completed_reqs: requests to complete
5576 static void __ufshcd_transfer_req_compl(struct ufs_hba *hba,
5577 unsigned long completed_reqs)
5579 struct ufshcd_lrb *lrbp;
5580 struct scsi_cmnd *cmd;
5583 struct request *req;
5585 for_each_set_bit(index, &completed_reqs, hba->nutrs) {
5586 lrbp = &hba->lrb[index];
5589 ufshcd_cond_add_cmd_trace(hba, index, "complete");
5590 ufshcd_update_tag_stats_completion(hba, cmd);
5591 result = ufshcd_transfer_rsp_status(hba, lrbp);
5592 scsi_dma_unmap(cmd);
5593 cmd->result = result;
5594 clear_bit_unlock(index, &hba->lrb_in_use);
5595 lrbp->complete_time_stamp = ktime_get();
5596 update_req_stats(hba, lrbp);
5597 /* Mark completed command as NULL in LRB */
5599 hba->ufs_stats.clk_rel.ctx = XFR_REQ_COMPL;
5600 __ufshcd_release(hba, false);
5601 __ufshcd_hibern8_release(hba, false);
5604 * As we are accessing the "request" structure,
5605 * this must be called before calling
5606 * ->scsi_done() callback.
5608 ufshcd_vops_pm_qos_req_end(hba, cmd->request,
5610 ufshcd_vops_crypto_engine_cfg_end(hba,
5611 lrbp, cmd->request);
5614 clear_bit_unlock(index, &hba->lrb_in_use);
5617 /* Update IO svc time latency histogram */
5618 if (req->lat_hist_enabled) {
5622 completion = ktime_get();
5623 delta_us = ktime_us_delta(completion,
5624 req->lat_hist_io_start);
5625 blk_update_latency_hist(
5626 (rq_data_dir(req) == READ) ?
5628 &hba->io_lat_write, delta_us);
5631 /* Do not touch lrbp after scsi done */
5632 cmd->scsi_done(cmd);
5633 } else if (lrbp->command_type == UTP_CMD_TYPE_DEV_MANAGE) {
5634 if (hba->dev_cmd.complete) {
5635 ufshcd_cond_add_cmd_trace(hba, index,
5637 complete(hba->dev_cmd.complete);
5640 if (ufshcd_is_clkscaling_supported(hba))
5641 hba->clk_scaling.active_reqs--;
5644 /* clear corresponding bits of completed commands */
5645 hba->outstanding_reqs ^= completed_reqs;
5647 ufshcd_clk_scaling_update_busy(hba);
5649 /* we might have free'd some tags above */
5650 wake_up(&hba->dev_cmd.tag_wq);
5654 * ufshcd_transfer_req_compl - handle SCSI and query command completion
5655 * @hba: per adapter instance
5658 * IRQ_HANDLED - If interrupt is valid
5659 * IRQ_NONE - If invalid interrupt
5661 static irqreturn_t ufshcd_transfer_req_compl(struct ufs_hba *hba)
5663 unsigned long completed_reqs;
5666 /* Resetting interrupt aggregation counters first and reading the
5667 * DOOR_BELL afterward allows us to handle all the completed requests.
5668 * In order to prevent other interrupts starvation the DB is read once
5669 * after reset. The down side of this solution is the possibility of
5670 * false interrupt if device completes another request after resetting
5671 * aggregation and before reading the DB.
5673 if (ufshcd_is_intr_aggr_allowed(hba))
5674 ufshcd_reset_intr_aggr(hba);
5676 tr_doorbell = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
5677 completed_reqs = tr_doorbell ^ hba->outstanding_reqs;
5679 if (completed_reqs) {
5680 __ufshcd_transfer_req_compl(hba, completed_reqs);
5688 * ufshcd_disable_ee - disable exception event
5689 * @hba: per-adapter instance
5690 * @mask: exception event to disable
5692 * Disables exception event in the device so that the EVENT_ALERT
5695 * Returns zero on success, non-zero error value on failure.
5697 static int ufshcd_disable_ee(struct ufs_hba *hba, u16 mask)
5702 if (!(hba->ee_ctrl_mask & mask))
5705 val = hba->ee_ctrl_mask & ~mask;
5706 val &= 0xFFFF; /* 2 bytes */
5707 err = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_WRITE_ATTR,
5708 QUERY_ATTR_IDN_EE_CONTROL, 0, 0, &val);
5710 hba->ee_ctrl_mask &= ~mask;
5716 * ufshcd_enable_ee - enable exception event
5717 * @hba: per-adapter instance
5718 * @mask: exception event to enable
5720 * Enable corresponding exception event in the device to allow
5721 * device to alert host in critical scenarios.
5723 * Returns zero on success, non-zero error value on failure.
5725 static int ufshcd_enable_ee(struct ufs_hba *hba, u16 mask)
5730 if (hba->ee_ctrl_mask & mask)
5733 val = hba->ee_ctrl_mask | mask;
5734 val &= 0xFFFF; /* 2 bytes */
5735 err = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_WRITE_ATTR,
5736 QUERY_ATTR_IDN_EE_CONTROL, 0, 0, &val);
5738 hba->ee_ctrl_mask |= mask;
5744 * ufshcd_enable_auto_bkops - Allow device managed BKOPS
5745 * @hba: per-adapter instance
5747 * Allow device to manage background operations on its own. Enabling
5748 * this might lead to inconsistent latencies during normal data transfers
5749 * as the device is allowed to manage its own way of handling background
5752 * Returns zero on success, non-zero on failure.
5754 static int ufshcd_enable_auto_bkops(struct ufs_hba *hba)
5758 if (hba->auto_bkops_enabled)
5761 err = ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_SET_FLAG,
5762 QUERY_FLAG_IDN_BKOPS_EN, NULL);
5764 dev_err(hba->dev, "%s: failed to enable bkops %d\n",
5769 hba->auto_bkops_enabled = true;
5770 trace_ufshcd_auto_bkops_state(dev_name(hba->dev), 1);
5772 /* No need of URGENT_BKOPS exception from the device */
5773 err = ufshcd_disable_ee(hba, MASK_EE_URGENT_BKOPS);
5775 dev_err(hba->dev, "%s: failed to disable exception event %d\n",
5782 * ufshcd_disable_auto_bkops - block device in doing background operations
5783 * @hba: per-adapter instance
5785 * Disabling background operations improves command response latency but
5786 * has drawback of device moving into critical state where the device is
5787 * not-operable. Make sure to call ufshcd_enable_auto_bkops() whenever the
5788 * host is idle so that BKOPS are managed effectively without any negative
5791 * Returns zero on success, non-zero on failure.
5793 static int ufshcd_disable_auto_bkops(struct ufs_hba *hba)
5797 if (!hba->auto_bkops_enabled)
5801 * If host assisted BKOPs is to be enabled, make sure
5802 * urgent bkops exception is allowed.
5804 err = ufshcd_enable_ee(hba, MASK_EE_URGENT_BKOPS);
5806 dev_err(hba->dev, "%s: failed to enable exception event %d\n",
5811 err = ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_CLEAR_FLAG,
5812 QUERY_FLAG_IDN_BKOPS_EN, NULL);
5814 dev_err(hba->dev, "%s: failed to disable bkops %d\n",
5816 ufshcd_disable_ee(hba, MASK_EE_URGENT_BKOPS);
5820 hba->auto_bkops_enabled = false;
5821 trace_ufshcd_auto_bkops_state(dev_name(hba->dev), 0);
5827 * ufshcd_force_reset_auto_bkops - force reset auto bkops state
5828 * @hba: per adapter instance
5830 * After a device reset the device may toggle the BKOPS_EN flag
5831 * to default value. The s/w tracking variables should be updated
5832 * as well. This function would change the auto-bkops state based on
5833 * UFSHCD_CAP_KEEP_AUTO_BKOPS_ENABLED_EXCEPT_SUSPEND.
5835 static void ufshcd_force_reset_auto_bkops(struct ufs_hba *hba)
5837 if (ufshcd_keep_autobkops_enabled_except_suspend(hba)) {
5838 hba->auto_bkops_enabled = false;
5839 hba->ee_ctrl_mask |= MASK_EE_URGENT_BKOPS;
5840 ufshcd_enable_auto_bkops(hba);
5842 hba->auto_bkops_enabled = true;
5843 hba->ee_ctrl_mask &= ~MASK_EE_URGENT_BKOPS;
5844 ufshcd_disable_auto_bkops(hba);
5848 static inline int ufshcd_get_bkops_status(struct ufs_hba *hba, u32 *status)
5850 return ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
5851 QUERY_ATTR_IDN_BKOPS_STATUS, 0, 0, status);
5855 * ufshcd_bkops_ctrl - control the auto bkops based on current bkops status
5856 * @hba: per-adapter instance
5857 * @status: bkops_status value
5859 * Read the bkops_status from the UFS device and Enable fBackgroundOpsEn
5860 * flag in the device to permit background operations if the device
5861 * bkops_status is greater than or equal to "status" argument passed to
5862 * this function, disable otherwise.
5864 * Returns 0 for success, non-zero in case of failure.
5866 * NOTE: Caller of this function can check the "hba->auto_bkops_enabled" flag
5867 * to know whether auto bkops is enabled or disabled after this function
5868 * returns control to it.
5870 static int ufshcd_bkops_ctrl(struct ufs_hba *hba,
5871 enum bkops_status status)
5874 u32 curr_status = 0;
5876 err = ufshcd_get_bkops_status(hba, &curr_status);
5878 dev_err(hba->dev, "%s: failed to get BKOPS status %d\n",
5881 } else if (curr_status > BKOPS_STATUS_MAX) {
5882 dev_err(hba->dev, "%s: invalid BKOPS status %d\n",
5883 __func__, curr_status);
5888 if (curr_status >= status)
5889 err = ufshcd_enable_auto_bkops(hba);
5891 err = ufshcd_disable_auto_bkops(hba);
5897 * ufshcd_urgent_bkops - handle urgent bkops exception event
5898 * @hba: per-adapter instance
5900 * Enable fBackgroundOpsEn flag in the device to permit background
5903 * If BKOPs is enabled, this function returns 0, 1 if the bkops in not enabled
5904 * and negative error value for any other failure.
5906 static int ufshcd_urgent_bkops(struct ufs_hba *hba)
5908 return ufshcd_bkops_ctrl(hba, hba->urgent_bkops_lvl);
5911 static inline int ufshcd_get_ee_status(struct ufs_hba *hba, u32 *status)
5913 return ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
5914 QUERY_ATTR_IDN_EE_STATUS, 0, 0, status);
5917 static void ufshcd_bkops_exception_event_handler(struct ufs_hba *hba)
5920 u32 curr_status = 0;
5922 if (hba->is_urgent_bkops_lvl_checked)
5923 goto enable_auto_bkops;
5925 err = ufshcd_get_bkops_status(hba, &curr_status);
5927 dev_err(hba->dev, "%s: failed to get BKOPS status %d\n",
5933 * We are seeing that some devices are raising the urgent bkops
5934 * exception events even when BKOPS status doesn't indicate performace
5935 * impacted or critical. Handle these device by determining their urgent
5936 * bkops status at runtime.
5938 if (curr_status < BKOPS_STATUS_PERF_IMPACT) {
5939 dev_err(hba->dev, "%s: device raised urgent BKOPS exception for bkops status %d\n",
5940 __func__, curr_status);
5941 /* update the current status as the urgent bkops level */
5942 hba->urgent_bkops_lvl = curr_status;
5943 hba->is_urgent_bkops_lvl_checked = true;
5947 err = ufshcd_enable_auto_bkops(hba);
5950 dev_err(hba->dev, "%s: failed to handle urgent bkops %d\n",
5955 * ufshcd_exception_event_handler - handle exceptions raised by device
5956 * @work: pointer to work data
5958 * Read bExceptionEventStatus attribute from the device and handle the
5959 * exception event accordingly.
5961 static void ufshcd_exception_event_handler(struct work_struct *work)
5963 struct ufs_hba *hba;
5966 hba = container_of(work, struct ufs_hba, eeh_work);
5968 pm_runtime_get_sync(hba->dev);
5969 ufshcd_scsi_block_requests(hba);
5970 err = ufshcd_get_ee_status(hba, &status);
5972 dev_err(hba->dev, "%s: failed to get exception status %d\n",
5977 status &= hba->ee_ctrl_mask;
5979 if (status & MASK_EE_URGENT_BKOPS)
5980 ufshcd_bkops_exception_event_handler(hba);
5983 ufshcd_scsi_unblock_requests(hba);
5984 pm_runtime_put(hba->dev);
5988 /* Complete requests that have door-bell cleared */
5989 static void ufshcd_complete_requests(struct ufs_hba *hba)
5991 ufshcd_transfer_req_compl(hba);
5992 ufshcd_tmc_handler(hba);
5996 * ufshcd_quirk_dl_nac_errors - This function checks if error handling is
5997 * to recover from the DL NAC errors or not.
5998 * @hba: per-adapter instance
6000 * Returns true if error handling is required, false otherwise
6002 static bool ufshcd_quirk_dl_nac_errors(struct ufs_hba *hba)
6004 unsigned long flags;
6005 bool err_handling = true;
6007 spin_lock_irqsave(hba->host->host_lock, flags);
6009 * UFS_DEVICE_QUIRK_RECOVERY_FROM_DL_NAC_ERRORS only workaround the
6010 * device fatal error and/or DL NAC & REPLAY timeout errors.
6012 if (hba->saved_err & (CONTROLLER_FATAL_ERROR | SYSTEM_BUS_FATAL_ERROR))
6015 if ((hba->saved_err & DEVICE_FATAL_ERROR) ||
6016 ((hba->saved_err & UIC_ERROR) &&
6017 (hba->saved_uic_err & UFSHCD_UIC_DL_TCx_REPLAY_ERROR))) {
6019 * we have to do error recovery but atleast silence the error
6022 hba->silence_err_logs = true;
6026 if ((hba->saved_err & UIC_ERROR) &&
6027 (hba->saved_uic_err & UFSHCD_UIC_DL_NAC_RECEIVED_ERROR)) {
6030 * wait for 50ms to see if we can get any other errors or not.
6032 spin_unlock_irqrestore(hba->host->host_lock, flags);
6034 spin_lock_irqsave(hba->host->host_lock, flags);
6037 * now check if we have got any other severe errors other than
6040 if ((hba->saved_err & INT_FATAL_ERRORS) ||
6041 ((hba->saved_err & UIC_ERROR) &&
6042 (hba->saved_uic_err & ~UFSHCD_UIC_DL_NAC_RECEIVED_ERROR))) {
6043 if (((hba->saved_err & INT_FATAL_ERRORS) ==
6044 DEVICE_FATAL_ERROR) || (hba->saved_uic_err &
6045 ~UFSHCD_UIC_DL_NAC_RECEIVED_ERROR))
6046 hba->silence_err_logs = true;
6051 * As DL NAC is the only error received so far, send out NOP
6052 * command to confirm if link is still active or not.
6053 * - If we don't get any response then do error recovery.
6054 * - If we get response then clear the DL NAC error bit.
6057 /* silence the error logs from NOP command */
6058 hba->silence_err_logs = true;
6059 spin_unlock_irqrestore(hba->host->host_lock, flags);
6060 err = ufshcd_verify_dev_init(hba);
6061 spin_lock_irqsave(hba->host->host_lock, flags);
6062 hba->silence_err_logs = false;
6065 hba->silence_err_logs = true;
6069 /* Link seems to be alive hence ignore the DL NAC errors */
6070 if (hba->saved_uic_err == UFSHCD_UIC_DL_NAC_RECEIVED_ERROR)
6071 hba->saved_err &= ~UIC_ERROR;
6072 /* clear NAC error */
6073 hba->saved_uic_err &= ~UFSHCD_UIC_DL_NAC_RECEIVED_ERROR;
6074 if (!hba->saved_uic_err) {
6075 err_handling = false;
6079 * there seems to be some errors other than NAC, so do error
6082 hba->silence_err_logs = true;
6085 spin_unlock_irqrestore(hba->host->host_lock, flags);
6086 return err_handling;
6090 * ufshcd_err_handler - handle UFS errors that require s/w attention
6091 * @work: pointer to work structure
6093 static void ufshcd_err_handler(struct work_struct *work)
6095 struct ufs_hba *hba;
6096 unsigned long flags;
6097 bool err_xfer = false, err_tm = false;
6100 bool needs_reset = false;
6101 bool clks_enabled = false;
6103 hba = container_of(work, struct ufs_hba, eh_work);
6105 spin_lock_irqsave(hba->host->host_lock, flags);
6106 ufsdbg_set_err_state(hba);
6108 if (hba->ufshcd_state == UFSHCD_STATE_RESET)
6112 * Make sure the clocks are ON before we proceed with err
6113 * handling. For the majority of cases err handler would be
6114 * run with clocks ON. There is a possibility that the err
6115 * handler was scheduled due to auto hibern8 error interrupt,
6116 * in which case the clocks could be gated or be in the
6117 * process of gating when the err handler runs.
6119 if (unlikely((hba->clk_gating.state != CLKS_ON) &&
6120 ufshcd_is_auto_hibern8_supported(hba))) {
6121 spin_unlock_irqrestore(hba->host->host_lock, flags);
6122 hba->ufs_stats.clk_hold.ctx = ERR_HNDLR_WORK;
6123 ufshcd_hold(hba, false);
6124 spin_lock_irqsave(hba->host->host_lock, flags);
6125 clks_enabled = true;
6128 hba->ufshcd_state = UFSHCD_STATE_RESET;
6129 ufshcd_set_eh_in_progress(hba);
6131 /* Complete requests that have door-bell cleared by h/w */
6132 ufshcd_complete_requests(hba);
6134 if (hba->dev_quirks & UFS_DEVICE_QUIRK_RECOVERY_FROM_DL_NAC_ERRORS) {
6137 spin_unlock_irqrestore(hba->host->host_lock, flags);
6138 /* release the lock as ufshcd_quirk_dl_nac_errors() may sleep */
6139 ret = ufshcd_quirk_dl_nac_errors(hba);
6140 spin_lock_irqsave(hba->host->host_lock, flags);
6142 goto skip_err_handling;
6146 * Dump controller state before resetting. Transfer requests state
6147 * will be dump as part of the request completion.
6149 if (hba->saved_err & (INT_FATAL_ERRORS | UIC_ERROR)) {
6150 dev_err(hba->dev, "%s: saved_err 0x%x saved_uic_err 0x%x",
6151 __func__, hba->saved_err, hba->saved_uic_err);
6152 if (!hba->silence_err_logs) {
6153 /* release lock as print host regs sleeps */
6154 spin_unlock_irqrestore(hba->host->host_lock, flags);
6155 ufshcd_print_host_regs(hba);
6156 ufshcd_print_host_state(hba);
6157 ufshcd_print_pwr_info(hba);
6158 ufshcd_print_tmrs(hba, hba->outstanding_tasks);
6159 ufshcd_print_cmd_log(hba);
6160 spin_lock_irqsave(hba->host->host_lock, flags);
6164 if ((hba->saved_err & INT_FATAL_ERRORS)
6165 || hba->saved_ce_err || hba->force_host_reset ||
6166 ((hba->saved_err & UIC_ERROR) &&
6167 (hba->saved_uic_err & (UFSHCD_UIC_DL_PA_INIT_ERROR |
6168 UFSHCD_UIC_DL_NAC_RECEIVED_ERROR |
6169 UFSHCD_UIC_DL_TCx_REPLAY_ERROR))))
6173 * if host reset is required then skip clearing the pending
6174 * transfers forcefully because they will automatically get
6175 * cleared after link startup.
6178 goto skip_pending_xfer_clear;
6180 /* release lock as clear command might sleep */
6181 spin_unlock_irqrestore(hba->host->host_lock, flags);
6182 /* Clear pending transfer requests */
6183 for_each_set_bit(tag, &hba->outstanding_reqs, hba->nutrs) {
6184 if (ufshcd_clear_cmd(hba, tag)) {
6186 goto lock_skip_pending_xfer_clear;
6190 /* Clear pending task management requests */
6191 for_each_set_bit(tag, &hba->outstanding_tasks, hba->nutmrs) {
6192 if (ufshcd_clear_tm_cmd(hba, tag)) {
6194 goto lock_skip_pending_xfer_clear;
6198 lock_skip_pending_xfer_clear:
6199 spin_lock_irqsave(hba->host->host_lock, flags);
6201 /* Complete the requests that are cleared by s/w */
6202 ufshcd_complete_requests(hba);
6204 if (err_xfer || err_tm)
6207 skip_pending_xfer_clear:
6208 /* Fatal errors need reset */
6210 unsigned long max_doorbells = (1UL << hba->nutrs) - 1;
6212 if (hba->saved_err & INT_FATAL_ERRORS)
6213 ufshcd_update_error_stats(hba,
6214 UFS_ERR_INT_FATAL_ERRORS);
6215 if (hba->saved_ce_err)
6216 ufshcd_update_error_stats(hba, UFS_ERR_CRYPTO_ENGINE);
6218 if (hba->saved_err & UIC_ERROR)
6219 ufshcd_update_error_stats(hba,
6220 UFS_ERR_INT_UIC_ERROR);
6222 if (err_xfer || err_tm)
6223 ufshcd_update_error_stats(hba,
6224 UFS_ERR_CLEAR_PEND_XFER_TM);
6227 * ufshcd_reset_and_restore() does the link reinitialization
6228 * which will need atleast one empty doorbell slot to send the
6229 * device management commands (NOP and query commands).
6230 * If there is no slot empty at this moment then free up last
6233 if (hba->outstanding_reqs == max_doorbells)
6234 __ufshcd_transfer_req_compl(hba,
6235 (1UL << (hba->nutrs - 1)));
6237 spin_unlock_irqrestore(hba->host->host_lock, flags);
6238 err = ufshcd_reset_and_restore(hba);
6239 spin_lock_irqsave(hba->host->host_lock, flags);
6241 dev_err(hba->dev, "%s: reset and restore failed\n",
6243 hba->ufshcd_state = UFSHCD_STATE_ERROR;
6246 * Inform scsi mid-layer that we did reset and allow to handle
6247 * Unit Attention properly.
6249 scsi_report_bus_reset(hba->host, 0);
6251 hba->saved_uic_err = 0;
6252 hba->saved_ce_err = 0;
6253 hba->force_host_reset = false;
6258 hba->ufshcd_state = UFSHCD_STATE_OPERATIONAL;
6259 if (hba->saved_err || hba->saved_uic_err)
6260 dev_err_ratelimited(hba->dev, "%s: exit: saved_err 0x%x saved_uic_err 0x%x",
6261 __func__, hba->saved_err, hba->saved_uic_err);
6264 hba->silence_err_logs = false;
6267 __ufshcd_release(hba, false);
6268 hba->ufs_stats.clk_rel.ctx = ERR_HNDLR_WORK;
6271 ufshcd_clear_eh_in_progress(hba);
6272 spin_unlock_irqrestore(hba->host->host_lock, flags);
6275 static void ufshcd_update_uic_reg_hist(struct ufs_uic_err_reg_hist *reg_hist,
6278 reg_hist->reg[reg_hist->pos] = reg;
6279 reg_hist->tstamp[reg_hist->pos] = ktime_get();
6280 reg_hist->pos = (reg_hist->pos + 1) % UIC_ERR_REG_HIST_LENGTH;
6283 static void ufshcd_rls_handler(struct work_struct *work)
6285 struct ufs_hba *hba;
6289 hba = container_of(work, struct ufs_hba, rls_work);
6290 ufshcd_scsi_block_requests(hba);
6291 pm_runtime_get_sync(hba->dev);
6292 ret = ufshcd_wait_for_doorbell_clr(hba, U64_MAX);
6295 "Timed out (%d) waiting for DB to clear\n",
6300 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_PWRMODE), &mode);
6301 if (hba->pwr_info.pwr_rx != ((mode >> PWR_RX_OFFSET) & PWR_INFO_MASK))
6302 hba->restore_needed = true;
6304 if (hba->pwr_info.pwr_tx != (mode & PWR_INFO_MASK))
6305 hba->restore_needed = true;
6307 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_RXGEAR), &mode);
6308 if (hba->pwr_info.gear_rx != mode)
6309 hba->restore_needed = true;
6311 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_TXGEAR), &mode);
6312 if (hba->pwr_info.gear_tx != mode)
6313 hba->restore_needed = true;
6315 if (hba->restore_needed)
6316 ret = ufshcd_config_pwr_mode(hba, &(hba->pwr_info));
6319 dev_err(hba->dev, "%s: Failed setting power mode, err = %d\n",
6322 hba->restore_needed = false;
6325 ufshcd_scsi_unblock_requests(hba);
6326 pm_runtime_put_sync(hba->dev);
6330 * ufshcd_update_uic_error - check and set fatal UIC error flags.
6331 * @hba: per-adapter instance
6334 * IRQ_HANDLED - If interrupt is valid
6335 * IRQ_NONE - If invalid interrupt
6337 static irqreturn_t ufshcd_update_uic_error(struct ufs_hba *hba)
6340 irqreturn_t retval = IRQ_NONE;
6342 /* PHY layer lane error */
6343 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_PHY_ADAPTER_LAYER);
6344 if ((reg & UIC_PHY_ADAPTER_LAYER_ERROR) &&
6345 (reg & UIC_PHY_ADAPTER_LAYER_ERROR_CODE_MASK)) {
6347 * To know whether this error is fatal or not, DB timeout
6348 * must be checked but this error is handled separately.
6350 dev_dbg(hba->dev, "%s: UIC Lane error reported, reg 0x%x\n",
6352 ufshcd_update_uic_reg_hist(&hba->ufs_stats.pa_err, reg);
6355 * Don't ignore LINERESET indication during hibern8
6358 if (reg & UIC_PHY_ADAPTER_LAYER_GENERIC_ERROR) {
6359 struct uic_command *cmd = hba->active_uic_cmd;
6362 if (cmd->command == UIC_CMD_DME_HIBER_ENTER) {
6363 dev_err(hba->dev, "%s: LINERESET during hibern8 enter, reg 0x%x\n",
6365 hba->full_init_linereset = true;
6368 if (!hba->full_init_linereset)
6369 schedule_work(&hba->rls_work);
6371 retval |= IRQ_HANDLED;
6374 /* PA_INIT_ERROR is fatal and needs UIC reset */
6375 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_DATA_LINK_LAYER);
6376 if ((reg & UIC_DATA_LINK_LAYER_ERROR) &&
6377 (reg & UIC_DATA_LINK_LAYER_ERROR_CODE_MASK)) {
6378 ufshcd_update_uic_reg_hist(&hba->ufs_stats.dl_err, reg);
6380 if (reg & UIC_DATA_LINK_LAYER_ERROR_PA_INIT) {
6381 hba->uic_error |= UFSHCD_UIC_DL_PA_INIT_ERROR;
6382 } else if (hba->dev_quirks &
6383 UFS_DEVICE_QUIRK_RECOVERY_FROM_DL_NAC_ERRORS) {
6384 if (reg & UIC_DATA_LINK_LAYER_ERROR_NAC_RECEIVED)
6386 UFSHCD_UIC_DL_NAC_RECEIVED_ERROR;
6388 UIC_DATA_LINK_LAYER_ERROR_TCx_REPLAY_TIMEOUT)
6390 UFSHCD_UIC_DL_TCx_REPLAY_ERROR;
6392 retval |= IRQ_HANDLED;
6395 /* UIC NL/TL/DME errors needs software retry */
6396 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_NETWORK_LAYER);
6397 if ((reg & UIC_NETWORK_LAYER_ERROR) &&
6398 (reg & UIC_NETWORK_LAYER_ERROR_CODE_MASK)) {
6399 ufshcd_update_uic_reg_hist(&hba->ufs_stats.nl_err, reg);
6400 hba->uic_error |= UFSHCD_UIC_NL_ERROR;
6401 retval |= IRQ_HANDLED;
6404 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_TRANSPORT_LAYER);
6405 if ((reg & UIC_TRANSPORT_LAYER_ERROR) &&
6406 (reg & UIC_TRANSPORT_LAYER_ERROR_CODE_MASK)) {
6407 ufshcd_update_uic_reg_hist(&hba->ufs_stats.tl_err, reg);
6408 hba->uic_error |= UFSHCD_UIC_TL_ERROR;
6409 retval |= IRQ_HANDLED;
6412 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_DME);
6413 if ((reg & UIC_DME_ERROR) &&
6414 (reg & UIC_DME_ERROR_CODE_MASK)) {
6415 ufshcd_update_uic_reg_hist(&hba->ufs_stats.dme_err, reg);
6416 hba->uic_error |= UFSHCD_UIC_DME_ERROR;
6417 retval |= IRQ_HANDLED;
6420 dev_dbg(hba->dev, "%s: UIC error flags = 0x%08x\n",
6421 __func__, hba->uic_error);
6426 * ufshcd_check_errors - Check for errors that need s/w attention
6427 * @hba: per-adapter instance
6430 * IRQ_HANDLED - If interrupt is valid
6431 * IRQ_NONE - If invalid interrupt
6433 static irqreturn_t ufshcd_check_errors(struct ufs_hba *hba)
6435 bool queue_eh_work = false;
6436 irqreturn_t retval = IRQ_NONE;
6438 if (hba->errors & INT_FATAL_ERRORS || hba->ce_error)
6439 queue_eh_work = true;
6441 if (hba->errors & UIC_ERROR) {
6443 retval = ufshcd_update_uic_error(hba);
6445 queue_eh_work = true;
6448 if (queue_eh_work) {
6450 * update the transfer error masks to sticky bits, let's do this
6451 * irrespective of current ufshcd_state.
6453 hba->saved_err |= hba->errors;
6454 hba->saved_uic_err |= hba->uic_error;
6455 hba->saved_ce_err |= hba->ce_error;
6457 /* handle fatal errors only when link is functional */
6458 if (hba->ufshcd_state == UFSHCD_STATE_OPERATIONAL) {
6460 * Set error handling in progress flag early so that we
6461 * don't issue new requests any more.
6463 ufshcd_set_eh_in_progress(hba);
6465 hba->ufshcd_state = UFSHCD_STATE_ERROR;
6466 schedule_work(&hba->eh_work);
6468 retval |= IRQ_HANDLED;
6471 * if (!queue_eh_work) -
6472 * Other errors are either non-fatal where host recovers
6473 * itself without s/w intervention or errors that will be
6474 * handled by the SCSI core layer.
6480 * ufshcd_tmc_handler - handle task management function completion
6481 * @hba: per adapter instance
6484 * IRQ_HANDLED - If interrupt is valid
6485 * IRQ_NONE - If invalid interrupt
6487 static irqreturn_t ufshcd_tmc_handler(struct ufs_hba *hba)
6491 tm_doorbell = ufshcd_readl(hba, REG_UTP_TASK_REQ_DOOR_BELL);
6492 hba->tm_condition = tm_doorbell ^ hba->outstanding_tasks;
6493 if (hba->tm_condition) {
6494 wake_up(&hba->tm_wq);
6502 * ufshcd_sl_intr - Interrupt service routine
6503 * @hba: per adapter instance
6504 * @intr_status: contains interrupts generated by the controller
6507 * IRQ_HANDLED - If interrupt is valid
6508 * IRQ_NONE - If invalid interrupt
6510 static irqreturn_t ufshcd_sl_intr(struct ufs_hba *hba, u32 intr_status)
6512 irqreturn_t retval = IRQ_NONE;
6514 ufsdbg_error_inject_dispatcher(hba,
6515 ERR_INJECT_INTR, intr_status, &intr_status);
6517 ufshcd_vops_crypto_engine_get_status(hba, &hba->ce_error);
6519 hba->errors = UFSHCD_ERROR_MASK & intr_status;
6520 if (hba->errors || hba->ce_error)
6521 retval |= ufshcd_check_errors(hba);
6523 if (intr_status & UFSHCD_UIC_MASK)
6524 retval |= ufshcd_uic_cmd_compl(hba, intr_status);
6526 if (intr_status & UTP_TASK_REQ_COMPL)
6527 retval |= ufshcd_tmc_handler(hba);
6529 if (intr_status & UTP_TRANSFER_REQ_COMPL)
6530 retval |= ufshcd_transfer_req_compl(hba);
6536 * ufshcd_intr - Main interrupt service routine
6538 * @__hba: pointer to adapter instance
6541 * IRQ_HANDLED - If interrupt is valid
6542 * IRQ_NONE - If invalid interrupt
6544 static irqreturn_t ufshcd_intr(int irq, void *__hba)
6546 u32 intr_status, enabled_intr_status;
6547 irqreturn_t retval = IRQ_NONE;
6548 struct ufs_hba *hba = __hba;
6549 int retries = hba->nutrs;
6551 spin_lock(hba->host->host_lock);
6552 intr_status = ufshcd_readl(hba, REG_INTERRUPT_STATUS);
6553 hba->ufs_stats.last_intr_status = intr_status;
6554 hba->ufs_stats.last_intr_ts = ktime_get();
6556 * There could be max of hba->nutrs reqs in flight and in worst case
6557 * if the reqs get finished 1 by 1 after the interrupt status is
6558 * read, make sure we handle them by checking the interrupt status
6559 * again in a loop until we process all of the reqs before returning.
6562 enabled_intr_status =
6563 intr_status & ufshcd_readl(hba, REG_INTERRUPT_ENABLE);
6565 ufshcd_writel(hba, intr_status, REG_INTERRUPT_STATUS);
6566 if (enabled_intr_status)
6567 retval |= ufshcd_sl_intr(hba, enabled_intr_status);
6569 intr_status = ufshcd_readl(hba, REG_INTERRUPT_STATUS);
6570 } while (intr_status && --retries);
6572 if (retval == IRQ_NONE) {
6573 dev_err(hba->dev, "%s: Unhandled interrupt 0x%08x\n",
6574 __func__, intr_status);
6575 ufshcd_hex_dump("host regs: ", hba->mmio_base,
6576 UFSHCI_REG_SPACE_SIZE);
6579 spin_unlock(hba->host->host_lock);
6583 static int ufshcd_clear_tm_cmd(struct ufs_hba *hba, int tag)
6586 u32 mask = 1 << tag;
6587 unsigned long flags;
6589 if (!test_bit(tag, &hba->outstanding_tasks))
6592 spin_lock_irqsave(hba->host->host_lock, flags);
6593 ufshcd_writel(hba, ~(1 << tag), REG_UTP_TASK_REQ_LIST_CLEAR);
6594 spin_unlock_irqrestore(hba->host->host_lock, flags);
6596 /* poll for max. 1 sec to clear door bell register by h/w */
6597 err = ufshcd_wait_for_register(hba,
6598 REG_UTP_TASK_REQ_DOOR_BELL,
6599 mask, 0, 1000, 1000, true);
6605 * ufshcd_issue_tm_cmd - issues task management commands to controller
6606 * @hba: per adapter instance
6607 * @lun_id: LUN ID to which TM command is sent
6608 * @task_id: task ID to which the TM command is applicable
6609 * @tm_function: task management function opcode
6610 * @tm_response: task management service response return value
6612 * Returns non-zero value on error, zero on success.
6614 static int ufshcd_issue_tm_cmd(struct ufs_hba *hba, int lun_id, int task_id,
6615 u8 tm_function, u8 *tm_response)
6617 struct utp_task_req_desc *task_req_descp;
6618 struct utp_upiu_task_req *task_req_upiup;
6619 struct Scsi_Host *host;
6620 unsigned long flags;
6628 * Get free slot, sleep if slots are unavailable.
6629 * Even though we use wait_event() which sleeps indefinitely,
6630 * the maximum wait time is bounded by %TM_CMD_TIMEOUT.
6632 wait_event(hba->tm_tag_wq, ufshcd_get_tm_free_slot(hba, &free_slot));
6633 hba->ufs_stats.clk_hold.ctx = TM_CMD_SEND;
6634 ufshcd_hold_all(hba);
6636 spin_lock_irqsave(host->host_lock, flags);
6637 task_req_descp = hba->utmrdl_base_addr;
6638 task_req_descp += free_slot;
6640 /* Configure task request descriptor */
6641 task_req_descp->header.dword_0 = cpu_to_le32(UTP_REQ_DESC_INT_CMD);
6642 task_req_descp->header.dword_2 =
6643 cpu_to_le32(OCS_INVALID_COMMAND_STATUS);
6645 /* Configure task request UPIU */
6647 (struct utp_upiu_task_req *) task_req_descp->task_req_upiu;
6648 task_tag = hba->nutrs + free_slot;
6649 task_req_upiup->header.dword_0 =
6650 UPIU_HEADER_DWORD(UPIU_TRANSACTION_TASK_REQ, 0,
6652 task_req_upiup->header.dword_1 =
6653 UPIU_HEADER_DWORD(0, tm_function, 0, 0);
6655 * The host shall provide the same value for LUN field in the basic
6656 * header and for Input Parameter.
6658 task_req_upiup->input_param1 = cpu_to_be32(lun_id);
6659 task_req_upiup->input_param2 = cpu_to_be32(task_id);
6661 /* send command to the controller */
6662 __set_bit(free_slot, &hba->outstanding_tasks);
6664 /* Make sure descriptors are ready before ringing the task doorbell */
6667 ufshcd_writel(hba, 1 << free_slot, REG_UTP_TASK_REQ_DOOR_BELL);
6668 /* Make sure that doorbell is committed immediately */
6671 spin_unlock_irqrestore(host->host_lock, flags);
6673 /* wait until the task management command is completed */
6674 err = wait_event_timeout(hba->tm_wq,
6675 test_bit(free_slot, &hba->tm_condition),
6676 msecs_to_jiffies(TM_CMD_TIMEOUT));
6678 dev_err(hba->dev, "%s: task management cmd 0x%.2x timed-out\n",
6679 __func__, tm_function);
6680 if (ufshcd_clear_tm_cmd(hba, free_slot))
6681 dev_WARN(hba->dev, "%s: unable clear tm cmd (slot %d) after timeout\n",
6682 __func__, free_slot);
6685 err = ufshcd_task_req_compl(hba, free_slot, tm_response);
6688 clear_bit(free_slot, &hba->tm_condition);
6689 ufshcd_put_tm_slot(hba, free_slot);
6690 wake_up(&hba->tm_tag_wq);
6691 hba->ufs_stats.clk_rel.ctx = TM_CMD_SEND;
6693 ufshcd_release_all(hba);
6698 * ufshcd_eh_device_reset_handler - device reset handler registered to
6700 * @cmd: SCSI command pointer
6702 * Returns SUCCESS/FAILED
6704 static int ufshcd_eh_device_reset_handler(struct scsi_cmnd *cmd)
6706 struct Scsi_Host *host;
6707 struct ufs_hba *hba;
6712 struct ufshcd_lrb *lrbp;
6713 unsigned long flags;
6715 host = cmd->device->host;
6716 hba = shost_priv(host);
6717 tag = cmd->request->tag;
6719 ufshcd_print_cmd_log(hba);
6720 lrbp = &hba->lrb[tag];
6721 err = ufshcd_issue_tm_cmd(hba, lrbp->lun, 0, UFS_LOGICAL_RESET, &resp);
6722 if (err || resp != UPIU_TASK_MANAGEMENT_FUNC_COMPL) {
6728 /* clear the commands that were pending for corresponding LUN */
6729 for_each_set_bit(pos, &hba->outstanding_reqs, hba->nutrs) {
6730 if (hba->lrb[pos].lun == lrbp->lun) {
6731 err = ufshcd_clear_cmd(hba, pos);
6736 spin_lock_irqsave(host->host_lock, flags);
6737 ufshcd_transfer_req_compl(hba);
6738 spin_unlock_irqrestore(host->host_lock, flags);
6741 hba->req_abort_count = 0;
6745 dev_err(hba->dev, "%s: failed with err %d\n", __func__, err);
6751 static void ufshcd_set_req_abort_skip(struct ufs_hba *hba, unsigned long bitmap)
6753 struct ufshcd_lrb *lrbp;
6756 for_each_set_bit(tag, &bitmap, hba->nutrs) {
6757 lrbp = &hba->lrb[tag];
6758 lrbp->req_abort_skip = true;
6763 * ufshcd_abort - abort a specific command
6764 * @cmd: SCSI command pointer
6766 * Abort the pending command in device by sending UFS_ABORT_TASK task management
6767 * command, and in host controller by clearing the door-bell register. There can
6768 * be race between controller sending the command to the device while abort is
6769 * issued. To avoid that, first issue UFS_QUERY_TASK to check if the command is
6770 * really issued and then try to abort it.
6772 * Returns SUCCESS/FAILED
6774 static int ufshcd_abort(struct scsi_cmnd *cmd)
6776 struct Scsi_Host *host;
6777 struct ufs_hba *hba;
6778 unsigned long flags;
6783 struct ufshcd_lrb *lrbp;
6786 host = cmd->device->host;
6787 hba = shost_priv(host);
6788 tag = cmd->request->tag;
6789 if (!ufshcd_valid_tag(hba, tag)) {
6791 "%s: invalid command tag %d: cmd=0x%p, cmd->request=0x%p",
6792 __func__, tag, cmd, cmd->request);
6796 lrbp = &hba->lrb[tag];
6798 ufshcd_update_error_stats(hba, UFS_ERR_TASK_ABORT);
6801 * Task abort to the device W-LUN is illegal. When this command
6802 * will fail, due to spec violation, scsi err handling next step
6803 * will be to send LU reset which, again, is a spec violation.
6804 * To avoid these unnecessary/illegal step we skip to the last error
6805 * handling stage: reset and restore.
6807 if (lrbp->lun == UFS_UPIU_UFS_DEVICE_WLUN)
6808 return ufshcd_eh_host_reset_handler(cmd);
6810 ufshcd_hold_all(hba);
6811 reg = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
6812 /* If command is already aborted/completed, return SUCCESS */
6813 if (!(test_bit(tag, &hba->outstanding_reqs))) {
6815 "%s: cmd at tag %d already completed, outstanding=0x%lx, doorbell=0x%x\n",
6816 __func__, tag, hba->outstanding_reqs, reg);
6820 if (!(reg & (1 << tag))) {
6822 "%s: cmd was completed, but without a notifying intr, tag = %d",
6826 /* Print Transfer Request of aborted task */
6827 dev_err(hba->dev, "%s: Device abort task at tag %d", __func__, tag);
6830 * Print detailed info about aborted request.
6831 * As more than one request might get aborted at the same time,
6832 * print full information only for the first aborted request in order
6833 * to reduce repeated printouts. For other aborted requests only print
6836 scsi_print_command(cmd);
6837 if (!hba->req_abort_count) {
6838 ufshcd_print_fsm_state(hba);
6839 ufshcd_print_host_regs(hba);
6840 ufshcd_print_host_state(hba);
6841 ufshcd_print_pwr_info(hba);
6842 ufshcd_print_trs(hba, 1 << tag, true);
6844 ufshcd_print_trs(hba, 1 << tag, false);
6846 hba->req_abort_count++;
6849 /* Skip task abort in case previous aborts failed and report failure */
6850 if (lrbp->req_abort_skip) {
6855 for (poll_cnt = 100; poll_cnt; poll_cnt--) {
6856 err = ufshcd_issue_tm_cmd(hba, lrbp->lun, lrbp->task_tag,
6857 UFS_QUERY_TASK, &resp);
6858 if (!err && resp == UPIU_TASK_MANAGEMENT_FUNC_SUCCEEDED) {
6859 /* cmd pending in the device */
6860 dev_err(hba->dev, "%s: cmd pending in the device. tag = %d",
6863 } else if (!err && resp == UPIU_TASK_MANAGEMENT_FUNC_COMPL) {
6865 * cmd not pending in the device, check if it is
6868 dev_err(hba->dev, "%s: cmd at tag %d not pending in the device.",
6870 reg = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
6871 if (reg & (1 << tag)) {
6872 /* sleep for max. 200us to stabilize */
6873 usleep_range(100, 200);
6876 /* command completed already */
6877 dev_err(hba->dev, "%s: cmd at tag %d successfully cleared from DB.",
6882 "%s: no response from device. tag = %d, err %d",
6883 __func__, tag, err);
6885 err = resp; /* service response error */
6895 err = ufshcd_issue_tm_cmd(hba, lrbp->lun, lrbp->task_tag,
6896 UFS_ABORT_TASK, &resp);
6897 if (err || resp != UPIU_TASK_MANAGEMENT_FUNC_COMPL) {
6899 err = resp; /* service response error */
6900 dev_err(hba->dev, "%s: issued. tag = %d, err %d",
6901 __func__, tag, err);
6906 err = ufshcd_clear_cmd(hba, tag);
6908 dev_err(hba->dev, "%s: Failed clearing cmd at tag %d, err %d",
6909 __func__, tag, err);
6913 scsi_dma_unmap(cmd);
6915 spin_lock_irqsave(host->host_lock, flags);
6916 ufshcd_outstanding_req_clear(hba, tag);
6917 hba->lrb[tag].cmd = NULL;
6918 spin_unlock_irqrestore(host->host_lock, flags);
6920 clear_bit_unlock(tag, &hba->lrb_in_use);
6921 wake_up(&hba->dev_cmd.tag_wq);
6927 dev_err(hba->dev, "%s: failed with err %d\n", __func__, err);
6928 ufshcd_set_req_abort_skip(hba, hba->outstanding_reqs);
6933 * This ufshcd_release_all() corresponds to the original scsi cmd that
6934 * got aborted here (as we won't get any IRQ for it).
6936 ufshcd_release_all(hba);
6941 * ufshcd_host_reset_and_restore - reset and restore host controller
6942 * @hba: per-adapter instance
6944 * Note that host controller reset may issue DME_RESET to
6945 * local and remote (device) Uni-Pro stack and the attributes
6946 * are reset to default state.
6948 * Returns zero on success, non-zero on failure
6950 static int ufshcd_host_reset_and_restore(struct ufs_hba *hba)
6953 unsigned long flags;
6955 /* Reset the host controller */
6956 spin_lock_irqsave(hba->host->host_lock, flags);
6957 ufshcd_hba_stop(hba, false);
6958 spin_unlock_irqrestore(hba->host->host_lock, flags);
6960 /* scale up clocks to max frequency before full reinitialization */
6961 ufshcd_set_clk_freq(hba, true);
6963 err = ufshcd_hba_enable(hba);
6967 /* Establish the link again and restore the device */
6968 err = ufshcd_probe_hba(hba);
6970 if (!err && (hba->ufshcd_state != UFSHCD_STATE_OPERATIONAL)) {
6976 err = ufshcd_vops_crypto_engine_reset(hba);
6979 "%s: failed to reset crypto engine %d\n",
6987 dev_err(hba->dev, "%s: Host init failed %d\n", __func__, err);
6993 * ufshcd_reset_and_restore - reset and re-initialize host/device
6994 * @hba: per-adapter instance
6996 * Reset and recover device, host and re-establish link. This
6997 * is helpful to recover the communication in fatal error conditions.
6999 * Returns zero on success, non-zero on failure
7001 static int ufshcd_reset_and_restore(struct ufs_hba *hba)
7004 unsigned long flags;
7005 int retries = MAX_HOST_RESET_RETRIES;
7008 err = ufshcd_vops_full_reset(hba);
7010 dev_warn(hba->dev, "%s: full reset returned %d\n",
7013 err = ufshcd_reset_device(hba);
7015 dev_warn(hba->dev, "%s: device reset failed. err %d\n",
7018 err = ufshcd_host_reset_and_restore(hba);
7019 } while (err && --retries);
7022 * There is no point proceeding even after failing
7023 * to recover after multiple retries.
7028 * After reset the door-bell might be cleared, complete
7029 * outstanding requests in s/w here.
7031 spin_lock_irqsave(hba->host->host_lock, flags);
7032 ufshcd_transfer_req_compl(hba);
7033 ufshcd_tmc_handler(hba);
7034 spin_unlock_irqrestore(hba->host->host_lock, flags);
7040 * ufshcd_eh_host_reset_handler - host reset handler registered to scsi layer
7041 * @cmd - SCSI command pointer
7043 * Returns SUCCESS/FAILED
7045 static int ufshcd_eh_host_reset_handler(struct scsi_cmnd *cmd)
7048 unsigned long flags;
7049 struct ufs_hba *hba;
7051 hba = shost_priv(cmd->device->host);
7054 * Check if there is any race with fatal error handling.
7055 * If so, wait for it to complete. Even though fatal error
7056 * handling does reset and restore in some cases, don't assume
7057 * anything out of it. We are just avoiding race here.
7060 spin_lock_irqsave(hba->host->host_lock, flags);
7061 if (!(work_pending(&hba->eh_work) ||
7062 hba->ufshcd_state == UFSHCD_STATE_RESET))
7064 spin_unlock_irqrestore(hba->host->host_lock, flags);
7065 dev_err(hba->dev, "%s: reset in progress - 1\n", __func__);
7066 flush_work(&hba->eh_work);
7070 * we don't know if previous reset had really reset the host controller
7071 * or not. So let's force reset here to be sure.
7073 hba->ufshcd_state = UFSHCD_STATE_ERROR;
7074 hba->force_host_reset = true;
7075 schedule_work(&hba->eh_work);
7077 /* wait for the reset work to finish */
7079 if (!(work_pending(&hba->eh_work) ||
7080 hba->ufshcd_state == UFSHCD_STATE_RESET))
7082 spin_unlock_irqrestore(hba->host->host_lock, flags);
7083 dev_err(hba->dev, "%s: reset in progress - 2\n", __func__);
7084 flush_work(&hba->eh_work);
7085 spin_lock_irqsave(hba->host->host_lock, flags);
7088 if (!((hba->ufshcd_state == UFSHCD_STATE_OPERATIONAL) &&
7089 ufshcd_is_link_active(hba))) {
7091 hba->ufshcd_state = UFSHCD_STATE_ERROR;
7094 spin_unlock_irqrestore(hba->host->host_lock, flags);
7100 * ufshcd_get_max_icc_level - calculate the ICC level
7101 * @sup_curr_uA: max. current supported by the regulator
7102 * @start_scan: row at the desc table to start scan from
7103 * @buff: power descriptor buffer
7105 * Returns calculated max ICC level for specific regulator
7107 static u32 ufshcd_get_max_icc_level(int sup_curr_uA, u32 start_scan, char *buff)
7114 for (i = start_scan; i >= 0; i--) {
7115 data = be16_to_cpu(*((u16 *)(buff + 2*i)));
7116 unit = (data & ATTR_ICC_LVL_UNIT_MASK) >>
7117 ATTR_ICC_LVL_UNIT_OFFSET;
7118 curr_uA = data & ATTR_ICC_LVL_VALUE_MASK;
7120 case UFSHCD_NANO_AMP:
7121 curr_uA = curr_uA / 1000;
7123 case UFSHCD_MILI_AMP:
7124 curr_uA = curr_uA * 1000;
7127 curr_uA = curr_uA * 1000 * 1000;
7129 case UFSHCD_MICRO_AMP:
7133 if (sup_curr_uA >= curr_uA)
7138 pr_err("%s: Couldn't find valid icc_level = %d", __func__, i);
7145 * ufshcd_calc_icc_level - calculate the max ICC level
7146 * In case regulators are not initialized we'll return 0
7147 * @hba: per-adapter instance
7148 * @desc_buf: power descriptor buffer to extract ICC levels from.
7149 * @len: length of desc_buff
7151 * Returns calculated ICC level
7153 static u32 ufshcd_find_max_sup_active_icc_level(struct ufs_hba *hba,
7154 u8 *desc_buf, int len)
7158 if (!hba->vreg_info.vcc || !hba->vreg_info.vccq ||
7159 !hba->vreg_info.vccq2) {
7161 "%s: Regulator capability was not set, actvIccLevel=%d",
7162 __func__, icc_level);
7166 if (hba->vreg_info.vcc)
7167 icc_level = ufshcd_get_max_icc_level(
7168 hba->vreg_info.vcc->max_uA,
7169 POWER_DESC_MAX_ACTV_ICC_LVLS - 1,
7170 &desc_buf[PWR_DESC_ACTIVE_LVLS_VCC_0]);
7172 if (hba->vreg_info.vccq)
7173 icc_level = ufshcd_get_max_icc_level(
7174 hba->vreg_info.vccq->max_uA,
7176 &desc_buf[PWR_DESC_ACTIVE_LVLS_VCCQ_0]);
7178 if (hba->vreg_info.vccq2)
7179 icc_level = ufshcd_get_max_icc_level(
7180 hba->vreg_info.vccq2->max_uA,
7182 &desc_buf[PWR_DESC_ACTIVE_LVLS_VCCQ2_0]);
7187 static void ufshcd_init_icc_levels(struct ufs_hba *hba)
7190 int buff_len = QUERY_DESC_POWER_MAX_SIZE;
7191 u8 desc_buf[QUERY_DESC_POWER_MAX_SIZE];
7193 ret = ufshcd_read_power_desc(hba, desc_buf, buff_len);
7196 "%s: Failed reading power descriptor.len = %d ret = %d",
7197 __func__, buff_len, ret);
7201 hba->init_prefetch_data.icc_level =
7202 ufshcd_find_max_sup_active_icc_level(hba,
7203 desc_buf, buff_len);
7204 dev_dbg(hba->dev, "%s: setting icc_level 0x%x",
7205 __func__, hba->init_prefetch_data.icc_level);
7207 ret = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_WRITE_ATTR,
7208 QUERY_ATTR_IDN_ACTIVE_ICC_LVL, 0, 0,
7209 &hba->init_prefetch_data.icc_level);
7213 "%s: Failed configuring bActiveICCLevel = %d ret = %d",
7214 __func__, hba->init_prefetch_data.icc_level , ret);
7219 * ufshcd_scsi_add_wlus - Adds required W-LUs
7220 * @hba: per-adapter instance
7222 * UFS device specification requires the UFS devices to support 4 well known
7224 * "REPORT_LUNS" (address: 01h)
7225 * "UFS Device" (address: 50h)
7226 * "RPMB" (address: 44h)
7227 * "BOOT" (address: 30h)
7228 * UFS device's power management needs to be controlled by "POWER CONDITION"
7229 * field of SSU (START STOP UNIT) command. But this "power condition" field
7230 * will take effect only when its sent to "UFS device" well known logical unit
7231 * hence we require the scsi_device instance to represent this logical unit in
7232 * order for the UFS host driver to send the SSU command for power management.
7234 * We also require the scsi_device instance for "RPMB" (Replay Protected Memory
7235 * Block) LU so user space process can control this LU. User space may also
7236 * want to have access to BOOT LU.
7238 * This function adds scsi device instances for each of all well known LUs
7239 * (except "REPORT LUNS" LU).
7241 * Returns zero on success (all required W-LUs are added successfully),
7242 * non-zero error value on failure (if failed to add any of the required W-LU).
7244 static int ufshcd_scsi_add_wlus(struct ufs_hba *hba)
7247 struct scsi_device *sdev_rpmb;
7248 struct scsi_device *sdev_boot;
7250 hba->sdev_ufs_device = __scsi_add_device(hba->host, 0, 0,
7251 ufshcd_upiu_wlun_to_scsi_wlun(UFS_UPIU_UFS_DEVICE_WLUN), NULL);
7252 if (IS_ERR(hba->sdev_ufs_device)) {
7253 ret = PTR_ERR(hba->sdev_ufs_device);
7254 hba->sdev_ufs_device = NULL;
7257 scsi_device_put(hba->sdev_ufs_device);
7259 sdev_boot = __scsi_add_device(hba->host, 0, 0,
7260 ufshcd_upiu_wlun_to_scsi_wlun(UFS_UPIU_BOOT_WLUN), NULL);
7261 if (IS_ERR(sdev_boot)) {
7262 ret = PTR_ERR(sdev_boot);
7263 goto remove_sdev_ufs_device;
7265 scsi_device_put(sdev_boot);
7267 sdev_rpmb = __scsi_add_device(hba->host, 0, 0,
7268 ufshcd_upiu_wlun_to_scsi_wlun(UFS_UPIU_RPMB_WLUN), NULL);
7269 if (IS_ERR(sdev_rpmb)) {
7270 ret = PTR_ERR(sdev_rpmb);
7271 goto remove_sdev_boot;
7273 scsi_device_put(sdev_rpmb);
7277 scsi_remove_device(sdev_boot);
7278 remove_sdev_ufs_device:
7279 scsi_remove_device(hba->sdev_ufs_device);
7285 * ufshcd_tune_pa_tactivate - Tunes PA_TActivate of local UniPro
7286 * @hba: per-adapter instance
7288 * PA_TActivate parameter can be tuned manually if UniPro version is less than
7289 * 1.61. PA_TActivate needs to be greater than or equal to peerM-PHY's
7290 * RX_MIN_ACTIVATETIME_CAPABILITY attribute. This optimal value can help reduce
7291 * the hibern8 exit latency.
7293 * Returns zero on success, non-zero error value on failure.
7295 static int ufshcd_tune_pa_tactivate(struct ufs_hba *hba)
7298 u32 peer_rx_min_activatetime = 0, tuned_pa_tactivate;
7300 if (!ufshcd_is_unipro_pa_params_tuning_req(hba))
7303 ret = ufshcd_dme_peer_get(hba,
7305 RX_MIN_ACTIVATETIME_CAPABILITY,
7306 UIC_ARG_MPHY_RX_GEN_SEL_INDEX(0)),
7307 &peer_rx_min_activatetime);
7311 /* make sure proper unit conversion is applied */
7312 tuned_pa_tactivate =
7313 ((peer_rx_min_activatetime * RX_MIN_ACTIVATETIME_UNIT_US)
7314 / PA_TACTIVATE_TIME_UNIT_US);
7315 ret = ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TACTIVATE),
7316 tuned_pa_tactivate);
7323 * ufshcd_tune_pa_hibern8time - Tunes PA_Hibern8Time of local UniPro
7324 * @hba: per-adapter instance
7326 * PA_Hibern8Time parameter can be tuned manually if UniPro version is less than
7327 * 1.61. PA_Hibern8Time needs to be maximum of local M-PHY's
7328 * TX_HIBERN8TIME_CAPABILITY & peer M-PHY's RX_HIBERN8TIME_CAPABILITY.
7329 * This optimal value can help reduce the hibern8 exit latency.
7331 * Returns zero on success, non-zero error value on failure.
7333 static int ufshcd_tune_pa_hibern8time(struct ufs_hba *hba)
7336 u32 local_tx_hibern8_time_cap = 0, peer_rx_hibern8_time_cap = 0;
7337 u32 max_hibern8_time, tuned_pa_hibern8time;
7339 ret = ufshcd_dme_get(hba,
7340 UIC_ARG_MIB_SEL(TX_HIBERN8TIME_CAPABILITY,
7341 UIC_ARG_MPHY_TX_GEN_SEL_INDEX(0)),
7342 &local_tx_hibern8_time_cap);
7346 ret = ufshcd_dme_peer_get(hba,
7347 UIC_ARG_MIB_SEL(RX_HIBERN8TIME_CAPABILITY,
7348 UIC_ARG_MPHY_RX_GEN_SEL_INDEX(0)),
7349 &peer_rx_hibern8_time_cap);
7353 max_hibern8_time = max(local_tx_hibern8_time_cap,
7354 peer_rx_hibern8_time_cap);
7355 /* make sure proper unit conversion is applied */
7356 tuned_pa_hibern8time = ((max_hibern8_time * HIBERN8TIME_UNIT_US)
7357 / PA_HIBERN8_TIME_UNIT_US);
7358 ret = ufshcd_dme_set(hba, UIC_ARG_MIB(PA_HIBERN8TIME),
7359 tuned_pa_hibern8time);
7365 * ufshcd_quirk_tune_host_pa_tactivate - Ensures that host PA_TACTIVATE is
7366 * less than device PA_TACTIVATE time.
7367 * @hba: per-adapter instance
7369 * Some UFS devices require host PA_TACTIVATE to be lower than device
7370 * PA_TACTIVATE, we need to enable UFS_DEVICE_QUIRK_HOST_PA_TACTIVATE quirk
7373 * Returns zero on success, non-zero error value on failure.
7375 static int ufshcd_quirk_tune_host_pa_tactivate(struct ufs_hba *hba)
7378 u32 granularity, peer_granularity;
7379 u32 pa_tactivate, peer_pa_tactivate;
7380 u32 pa_tactivate_us, peer_pa_tactivate_us;
7381 u8 gran_to_us_table[] = {1, 4, 8, 16, 32, 100};
7383 ret = ufshcd_dme_get(hba, UIC_ARG_MIB(PA_GRANULARITY),
7388 ret = ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_GRANULARITY),
7393 if ((granularity < PA_GRANULARITY_MIN_VAL) ||
7394 (granularity > PA_GRANULARITY_MAX_VAL)) {
7395 dev_err(hba->dev, "%s: invalid host PA_GRANULARITY %d",
7396 __func__, granularity);
7400 if ((peer_granularity < PA_GRANULARITY_MIN_VAL) ||
7401 (peer_granularity > PA_GRANULARITY_MAX_VAL)) {
7402 dev_err(hba->dev, "%s: invalid device PA_GRANULARITY %d",
7403 __func__, peer_granularity);
7407 ret = ufshcd_dme_get(hba, UIC_ARG_MIB(PA_TACTIVATE), &pa_tactivate);
7411 ret = ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_TACTIVATE),
7412 &peer_pa_tactivate);
7416 pa_tactivate_us = pa_tactivate * gran_to_us_table[granularity - 1];
7417 peer_pa_tactivate_us = peer_pa_tactivate *
7418 gran_to_us_table[peer_granularity - 1];
7420 if (pa_tactivate_us > peer_pa_tactivate_us) {
7421 u32 new_peer_pa_tactivate;
7423 new_peer_pa_tactivate = pa_tactivate_us /
7424 gran_to_us_table[peer_granularity - 1];
7425 new_peer_pa_tactivate++;
7426 ret = ufshcd_dme_peer_set(hba, UIC_ARG_MIB(PA_TACTIVATE),
7427 new_peer_pa_tactivate);
7434 static void ufshcd_tune_unipro_params(struct ufs_hba *hba)
7436 if (ufshcd_is_unipro_pa_params_tuning_req(hba)) {
7437 ufshcd_tune_pa_tactivate(hba);
7438 ufshcd_tune_pa_hibern8time(hba);
7441 if (hba->dev_quirks & UFS_DEVICE_QUIRK_PA_TACTIVATE)
7442 /* set 1ms timeout for PA_TACTIVATE */
7443 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TACTIVATE), 10);
7445 if (hba->dev_quirks & UFS_DEVICE_QUIRK_HOST_PA_TACTIVATE)
7446 ufshcd_quirk_tune_host_pa_tactivate(hba);
7448 ufshcd_vops_apply_dev_quirks(hba);
7451 static void ufshcd_clear_dbg_ufs_stats(struct ufs_hba *hba)
7453 int err_reg_hist_size = sizeof(struct ufs_uic_err_reg_hist);
7455 memset(&hba->ufs_stats.pa_err, 0, err_reg_hist_size);
7456 memset(&hba->ufs_stats.dl_err, 0, err_reg_hist_size);
7457 memset(&hba->ufs_stats.nl_err, 0, err_reg_hist_size);
7458 memset(&hba->ufs_stats.tl_err, 0, err_reg_hist_size);
7459 memset(&hba->ufs_stats.dme_err, 0, err_reg_hist_size);
7461 hba->req_abort_count = 0;
7464 static void ufshcd_apply_pm_quirks(struct ufs_hba *hba)
7466 if (hba->dev_quirks & UFS_DEVICE_QUIRK_NO_LINK_OFF) {
7467 if (ufs_get_pm_lvl_to_link_pwr_state(hba->rpm_lvl) ==
7468 UIC_LINK_OFF_STATE) {
7470 ufs_get_desired_pm_lvl_for_dev_link_state(
7472 UIC_LINK_HIBERN8_STATE);
7473 dev_info(hba->dev, "UFS_DEVICE_QUIRK_NO_LINK_OFF enabled, changed rpm_lvl to %d\n",
7476 if (ufs_get_pm_lvl_to_link_pwr_state(hba->spm_lvl) ==
7477 UIC_LINK_OFF_STATE) {
7479 ufs_get_desired_pm_lvl_for_dev_link_state(
7481 UIC_LINK_HIBERN8_STATE);
7482 dev_info(hba->dev, "UFS_DEVICE_QUIRK_NO_LINK_OFF enabled, changed spm_lvl to %d\n",
7489 * ufshcd_probe_hba - probe hba to detect device and initialize
7490 * @hba: per-adapter instance
7492 * Execute link-startup and verify device initialization
7494 static int ufshcd_probe_hba(struct ufs_hba *hba)
7497 ktime_t start = ktime_get();
7499 ret = ufshcd_link_startup(hba);
7503 /* Debug counters initialization */
7504 ufshcd_clear_dbg_ufs_stats(hba);
7505 /* set the default level for urgent bkops */
7506 hba->urgent_bkops_lvl = BKOPS_STATUS_PERF_IMPACT;
7507 hba->is_urgent_bkops_lvl_checked = false;
7509 /* UniPro link is active now */
7510 ufshcd_set_link_active(hba);
7512 ret = ufshcd_verify_dev_init(hba);
7516 ret = ufshcd_complete_dev_init(hba);
7520 ufs_advertise_fixup_device(hba);
7521 ufshcd_tune_unipro_params(hba);
7523 ufshcd_apply_pm_quirks(hba);
7524 ret = ufshcd_set_vccq_rail_unused(hba,
7525 (hba->dev_quirks & UFS_DEVICE_NO_VCCQ) ? true : false);
7529 /* UFS device is also active now */
7530 ufshcd_set_ufs_dev_active(hba);
7531 ufshcd_force_reset_auto_bkops(hba);
7532 hba->wlun_dev_clr_ua = true;
7534 if (ufshcd_get_max_pwr_mode(hba)) {
7536 "%s: Failed getting max supported power mode\n",
7539 ret = ufshcd_config_pwr_mode(hba, &hba->max_pwr_info.info);
7541 dev_err(hba->dev, "%s: Failed setting power mode, err = %d\n",
7547 /* set the state as operational after switching to desired gear */
7548 hba->ufshcd_state = UFSHCD_STATE_OPERATIONAL;
7550 * If we are in error handling context or in power management callbacks
7551 * context, no need to scan the host
7553 if (!ufshcd_eh_in_progress(hba) && !hba->pm_op_in_progress) {
7556 /* clear any previous UFS device information */
7557 memset(&hba->dev_info, 0, sizeof(hba->dev_info));
7558 if (!ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_READ_FLAG,
7559 QUERY_FLAG_IDN_PWR_ON_WPE, &flag))
7560 hba->dev_info.f_power_on_wp_en = flag;
7562 if (!hba->is_init_prefetch)
7563 ufshcd_init_icc_levels(hba);
7565 /* Add required well known logical units to scsi mid layer */
7566 if (ufshcd_scsi_add_wlus(hba))
7569 /* Initialize devfreq after UFS device is detected */
7570 if (ufshcd_is_clkscaling_supported(hba)) {
7571 memcpy(&hba->clk_scaling.saved_pwr_info.info,
7572 &hba->pwr_info, sizeof(struct ufs_pa_layer_attr));
7573 hba->clk_scaling.saved_pwr_info.is_valid = true;
7574 hba->clk_scaling.is_scaled_up = true;
7575 if (!hba->devfreq) {
7576 hba->devfreq = devfreq_add_device(hba->dev,
7577 &ufs_devfreq_profile,
7580 if (IS_ERR(hba->devfreq)) {
7581 ret = PTR_ERR(hba->devfreq);
7582 dev_err(hba->dev, "Unable to register with devfreq %d\n",
7587 hba->clk_scaling.is_allowed = true;
7590 scsi_scan_host(hba->host);
7591 pm_runtime_put_sync(hba->dev);
7594 if (!hba->is_init_prefetch)
7595 hba->is_init_prefetch = true;
7598 * Enable auto hibern8 if supported, after full host and
7599 * device initialization.
7601 if (ufshcd_is_auto_hibern8_supported(hba))
7602 ufshcd_set_auto_hibern8_timer(hba,
7603 hba->hibern8_on_idle.delay_ms);
7606 * If we failed to initialize the device or the device is not
7607 * present, turn off the power/clocks etc.
7609 if (ret && !ufshcd_eh_in_progress(hba) && !hba->pm_op_in_progress) {
7610 pm_runtime_put_sync(hba->dev);
7611 ufshcd_hba_exit(hba);
7614 trace_ufshcd_init(dev_name(hba->dev), ret,
7615 ktime_to_us(ktime_sub(ktime_get(), start)),
7616 hba->curr_dev_pwr_mode, hba->uic_link_state);
7621 * ufshcd_async_scan - asynchronous execution for probing hba
7622 * @data: data pointer to pass to this function
7623 * @cookie: cookie data
7625 static void ufshcd_async_scan(void *data, async_cookie_t cookie)
7627 struct ufs_hba *hba = (struct ufs_hba *)data;
7630 * Don't allow clock gating and hibern8 enter for faster device
7633 ufshcd_hold_all(hba);
7634 ufshcd_probe_hba(hba);
7635 ufshcd_release_all(hba);
7639 * ufshcd_query_ioctl - perform user read queries
7640 * @hba: per-adapter instance
7641 * @lun: used for lun specific queries
7642 * @buffer: user space buffer for reading and submitting query data and params
7643 * @return: 0 for success negative error code otherwise
7645 * Expected/Submitted buffer structure is struct ufs_ioctl_query_data.
7646 * It will read the opcode, idn and buf_length parameters, and, put the
7647 * response in the buffer field while updating the used size in buf_length.
7649 static int ufshcd_query_ioctl(struct ufs_hba *hba, u8 lun, void __user *buffer)
7651 struct ufs_ioctl_query_data *ioctl_data;
7660 ioctl_data = kzalloc(sizeof(struct ufs_ioctl_query_data), GFP_KERNEL);
7662 dev_err(hba->dev, "%s: Failed allocating %zu bytes\n", __func__,
7663 sizeof(struct ufs_ioctl_query_data));
7668 /* extract params from user buffer */
7669 err = copy_from_user(ioctl_data, buffer,
7670 sizeof(struct ufs_ioctl_query_data));
7673 "%s: Failed copying buffer from user, err %d\n",
7675 goto out_release_mem;
7678 /* verify legal parameters & send query */
7679 switch (ioctl_data->opcode) {
7680 case UPIU_QUERY_OPCODE_READ_DESC:
7681 switch (ioctl_data->idn) {
7682 case QUERY_DESC_IDN_DEVICE:
7683 case QUERY_DESC_IDN_CONFIGURAION:
7684 case QUERY_DESC_IDN_INTERCONNECT:
7685 case QUERY_DESC_IDN_GEOMETRY:
7686 case QUERY_DESC_IDN_POWER:
7689 case QUERY_DESC_IDN_UNIT:
7690 if (!ufs_is_valid_unit_desc_lun(lun)) {
7692 "%s: No unit descriptor for lun 0x%x\n",
7695 goto out_release_mem;
7702 length = min_t(int, QUERY_DESC_MAX_SIZE,
7703 ioctl_data->buf_size);
7704 desc = kzalloc(length, GFP_KERNEL);
7706 dev_err(hba->dev, "%s: Failed allocating %d bytes\n",
7709 goto out_release_mem;
7711 err = ufshcd_query_descriptor(hba, ioctl_data->opcode,
7712 ioctl_data->idn, index, 0, desc, &length);
7714 case UPIU_QUERY_OPCODE_READ_ATTR:
7715 switch (ioctl_data->idn) {
7716 case QUERY_ATTR_IDN_BOOT_LU_EN:
7717 case QUERY_ATTR_IDN_POWER_MODE:
7718 case QUERY_ATTR_IDN_ACTIVE_ICC_LVL:
7719 case QUERY_ATTR_IDN_OOO_DATA_EN:
7720 case QUERY_ATTR_IDN_BKOPS_STATUS:
7721 case QUERY_ATTR_IDN_PURGE_STATUS:
7722 case QUERY_ATTR_IDN_MAX_DATA_IN:
7723 case QUERY_ATTR_IDN_MAX_DATA_OUT:
7724 case QUERY_ATTR_IDN_REF_CLK_FREQ:
7725 case QUERY_ATTR_IDN_CONF_DESC_LOCK:
7726 case QUERY_ATTR_IDN_MAX_NUM_OF_RTT:
7727 case QUERY_ATTR_IDN_EE_CONTROL:
7728 case QUERY_ATTR_IDN_EE_STATUS:
7729 case QUERY_ATTR_IDN_SECONDS_PASSED:
7732 case QUERY_ATTR_IDN_DYN_CAP_NEEDED:
7733 case QUERY_ATTR_IDN_CORR_PRG_BLK_NUM:
7739 err = ufshcd_query_attr(hba, ioctl_data->opcode, ioctl_data->idn,
7743 case UPIU_QUERY_OPCODE_WRITE_ATTR:
7744 err = copy_from_user(&att,
7745 buffer + sizeof(struct ufs_ioctl_query_data),
7749 "%s: Failed copying buffer from user, err %d\n",
7751 goto out_release_mem;
7754 switch (ioctl_data->idn) {
7755 case QUERY_ATTR_IDN_BOOT_LU_EN:
7757 if (att > QUERY_ATTR_IDN_BOOT_LU_EN_MAX) {
7759 "%s: Illegal ufs query ioctl data, opcode 0x%x, idn 0x%x, att 0x%x\n",
7760 __func__, ioctl_data->opcode,
7761 (unsigned int)ioctl_data->idn, att);
7763 goto out_release_mem;
7769 err = ufshcd_query_attr(hba, ioctl_data->opcode,
7770 ioctl_data->idn, index, 0, &att);
7773 case UPIU_QUERY_OPCODE_READ_FLAG:
7774 switch (ioctl_data->idn) {
7775 case QUERY_FLAG_IDN_FDEVICEINIT:
7776 case QUERY_FLAG_IDN_PERMANENT_WPE:
7777 case QUERY_FLAG_IDN_PWR_ON_WPE:
7778 case QUERY_FLAG_IDN_BKOPS_EN:
7779 case QUERY_FLAG_IDN_PURGE_ENABLE:
7780 case QUERY_FLAG_IDN_FPHYRESOURCEREMOVAL:
7781 case QUERY_FLAG_IDN_BUSY_RTC:
7786 err = ufshcd_query_flag_retry(hba, ioctl_data->opcode,
7787 ioctl_data->idn, &flag);
7794 dev_err(hba->dev, "%s: Query for idn %d failed\n", __func__,
7796 goto out_release_mem;
7800 * copy response data
7801 * As we might end up reading less data then what is specified in
7802 * "ioctl_data->buf_size". So we are updating "ioctl_data->
7803 * buf_size" to what exactly we have read.
7805 switch (ioctl_data->opcode) {
7806 case UPIU_QUERY_OPCODE_READ_DESC:
7807 ioctl_data->buf_size = min_t(int, ioctl_data->buf_size, length);
7810 case UPIU_QUERY_OPCODE_READ_ATTR:
7811 ioctl_data->buf_size = sizeof(u32);
7814 case UPIU_QUERY_OPCODE_READ_FLAG:
7815 ioctl_data->buf_size = 1;
7818 case UPIU_QUERY_OPCODE_WRITE_ATTR:
7819 goto out_release_mem;
7825 err = copy_to_user(buffer, ioctl_data,
7826 sizeof(struct ufs_ioctl_query_data));
7828 dev_err(hba->dev, "%s: Failed copying back to user.\n",
7830 err = copy_to_user(buffer + sizeof(struct ufs_ioctl_query_data),
7831 data_ptr, ioctl_data->buf_size);
7833 dev_err(hba->dev, "%s: err %d copying back to user.\n",
7835 goto out_release_mem;
7839 "%s: illegal ufs query ioctl data, opcode 0x%x, idn 0x%x\n",
7840 __func__, ioctl_data->opcode, (unsigned int)ioctl_data->idn);
7850 * ufshcd_ioctl - ufs ioctl callback registered in scsi_host
7851 * @dev: scsi device required for per LUN queries
7852 * @cmd: command opcode
7853 * @buffer: user space buffer for transferring data
7855 * Supported commands:
7858 static int ufshcd_ioctl(struct scsi_device *dev, int cmd, void __user *buffer)
7860 struct ufs_hba *hba = shost_priv(dev->host);
7865 dev_err(hba->dev, "%s: User buffer is NULL!\n", __func__);
7870 case UFS_IOCTL_QUERY:
7871 pm_runtime_get_sync(hba->dev);
7872 err = ufshcd_query_ioctl(hba, ufshcd_scsi_to_upiu_lun(dev->lun),
7874 pm_runtime_put_sync(hba->dev);
7878 dev_dbg(hba->dev, "%s: Unsupported ioctl cmd %d\n", __func__,
7886 static enum blk_eh_timer_return ufshcd_eh_timed_out(struct scsi_cmnd *scmd)
7888 unsigned long flags;
7889 struct Scsi_Host *host;
7890 struct ufs_hba *hba;
7894 if (!scmd || !scmd->device || !scmd->device->host)
7895 return BLK_EH_NOT_HANDLED;
7897 host = scmd->device->host;
7898 hba = shost_priv(host);
7900 return BLK_EH_NOT_HANDLED;
7902 spin_lock_irqsave(host->host_lock, flags);
7904 for_each_set_bit(index, &hba->outstanding_reqs, hba->nutrs) {
7905 if (hba->lrb[index].cmd == scmd) {
7911 spin_unlock_irqrestore(host->host_lock, flags);
7914 * Bypass SCSI error handling and reset the block layer timer if this
7915 * SCSI command was not actually dispatched to UFS driver, otherwise
7916 * let SCSI layer handle the error as usual.
7918 return found ? BLK_EH_NOT_HANDLED : BLK_EH_RESET_TIMER;
7921 static struct scsi_host_template ufshcd_driver_template = {
7922 .module = THIS_MODULE,
7924 .proc_name = UFSHCD,
7925 .queuecommand = ufshcd_queuecommand,
7926 .slave_alloc = ufshcd_slave_alloc,
7927 .slave_configure = ufshcd_slave_configure,
7928 .slave_destroy = ufshcd_slave_destroy,
7929 .change_queue_depth = ufshcd_change_queue_depth,
7930 .eh_abort_handler = ufshcd_abort,
7931 .eh_device_reset_handler = ufshcd_eh_device_reset_handler,
7932 .eh_host_reset_handler = ufshcd_eh_host_reset_handler,
7933 .eh_timed_out = ufshcd_eh_timed_out,
7934 .ioctl = ufshcd_ioctl,
7935 #ifdef CONFIG_COMPAT
7936 .compat_ioctl = ufshcd_ioctl,
7939 .sg_tablesize = SG_ALL,
7940 .cmd_per_lun = UFSHCD_CMD_PER_LUN,
7941 .can_queue = UFSHCD_CAN_QUEUE,
7942 .max_host_blocked = 1,
7943 .track_queue_depth = 1,
7946 static int ufshcd_config_vreg_load(struct device *dev, struct ufs_vreg *vreg,
7954 ret = regulator_set_load(vreg->reg, ua);
7956 dev_err(dev, "%s: %s set load (ua=%d) failed, err=%d\n",
7957 __func__, vreg->name, ua, ret);
7963 static inline int ufshcd_config_vreg_lpm(struct ufs_hba *hba,
7964 struct ufs_vreg *vreg)
7968 else if (vreg->unused)
7971 return ufshcd_config_vreg_load(hba->dev, vreg,
7972 UFS_VREG_LPM_LOAD_UA);
7975 static inline int ufshcd_config_vreg_hpm(struct ufs_hba *hba,
7976 struct ufs_vreg *vreg)
7980 else if (vreg->unused)
7983 return ufshcd_config_vreg_load(hba->dev, vreg, vreg->max_uA);
7986 static int ufshcd_config_vreg(struct device *dev,
7987 struct ufs_vreg *vreg, bool on)
7990 struct regulator *reg;
7992 int min_uV, uA_load;
7999 if (regulator_count_voltages(reg) > 0) {
8000 uA_load = on ? vreg->max_uA : 0;
8001 ret = ufshcd_config_vreg_load(dev, vreg, uA_load);
8005 min_uV = on ? vreg->min_uV : 0;
8006 ret = regulator_set_voltage(reg, min_uV, vreg->max_uV);
8008 dev_err(dev, "%s: %s set voltage failed, err=%d\n",
8009 __func__, name, ret);
8017 static int ufshcd_enable_vreg(struct device *dev, struct ufs_vreg *vreg)
8023 else if (vreg->enabled || vreg->unused)
8026 ret = ufshcd_config_vreg(dev, vreg, true);
8028 ret = regulator_enable(vreg->reg);
8031 vreg->enabled = true;
8033 dev_err(dev, "%s: %s enable failed, err=%d\n",
8034 __func__, vreg->name, ret);
8039 static int ufshcd_disable_vreg(struct device *dev, struct ufs_vreg *vreg)
8045 else if (!vreg->enabled || vreg->unused)
8048 ret = regulator_disable(vreg->reg);
8051 /* ignore errors on applying disable config */
8052 ufshcd_config_vreg(dev, vreg, false);
8053 vreg->enabled = false;
8055 dev_err(dev, "%s: %s disable failed, err=%d\n",
8056 __func__, vreg->name, ret);
8062 static int ufshcd_setup_vreg(struct ufs_hba *hba, bool on)
8065 struct device *dev = hba->dev;
8066 struct ufs_vreg_info *info = &hba->vreg_info;
8071 ret = ufshcd_toggle_vreg(dev, info->vcc, on);
8075 ret = ufshcd_toggle_vreg(dev, info->vccq, on);
8079 ret = ufshcd_toggle_vreg(dev, info->vccq2, on);
8085 ufshcd_toggle_vreg(dev, info->vccq2, false);
8086 ufshcd_toggle_vreg(dev, info->vccq, false);
8087 ufshcd_toggle_vreg(dev, info->vcc, false);
8092 static int ufshcd_setup_hba_vreg(struct ufs_hba *hba, bool on)
8094 struct ufs_vreg_info *info = &hba->vreg_info;
8097 if (info->vdd_hba) {
8098 ret = ufshcd_toggle_vreg(hba->dev, info->vdd_hba, on);
8101 ufshcd_vops_update_sec_cfg(hba, on);
8107 static int ufshcd_get_vreg(struct device *dev, struct ufs_vreg *vreg)
8114 vreg->reg = devm_regulator_get(dev, vreg->name);
8115 if (IS_ERR(vreg->reg)) {
8116 ret = PTR_ERR(vreg->reg);
8117 dev_err(dev, "%s: %s get failed, err=%d\n",
8118 __func__, vreg->name, ret);
8124 static int ufshcd_init_vreg(struct ufs_hba *hba)
8127 struct device *dev = hba->dev;
8128 struct ufs_vreg_info *info = &hba->vreg_info;
8133 ret = ufshcd_get_vreg(dev, info->vcc);
8137 ret = ufshcd_get_vreg(dev, info->vccq);
8141 ret = ufshcd_get_vreg(dev, info->vccq2);
8146 static int ufshcd_init_hba_vreg(struct ufs_hba *hba)
8148 struct ufs_vreg_info *info = &hba->vreg_info;
8151 return ufshcd_get_vreg(hba->dev, info->vdd_hba);
8156 static int ufshcd_set_vccq_rail_unused(struct ufs_hba *hba, bool unused)
8159 struct ufs_vreg_info *info = &hba->vreg_info;
8163 else if (!info->vccq)
8167 /* shut off the rail here */
8168 ret = ufshcd_toggle_vreg(hba->dev, info->vccq, false);
8170 * Mark this rail as no longer used, so it doesn't get enabled
8174 info->vccq->unused = true;
8177 * rail should have been already enabled hence just make sure
8178 * that unused flag is cleared.
8180 info->vccq->unused = false;
8186 static int ufshcd_setup_clocks(struct ufs_hba *hba, bool on,
8187 bool skip_ref_clk, bool is_gating_context)
8190 struct ufs_clk_info *clki;
8191 struct list_head *head = &hba->clk_list_head;
8192 unsigned long flags;
8193 ktime_t start = ktime_get();
8194 bool clk_state_changed = false;
8196 if (!head || list_empty(head))
8199 /* call vendor specific bus vote before enabling the clocks */
8201 ret = ufshcd_vops_set_bus_vote(hba, on);
8207 * vendor specific setup_clocks ops may depend on clocks managed by
8208 * this standard driver hence call the vendor specific setup_clocks
8209 * before disabling the clocks managed here.
8212 ret = ufshcd_vops_setup_clocks(hba, on, is_gating_context);
8217 list_for_each_entry(clki, head, list) {
8218 if (!IS_ERR_OR_NULL(clki->clk)) {
8219 if (skip_ref_clk && !strcmp(clki->name, "ref_clk"))
8222 clk_state_changed = on ^ clki->enabled;
8223 if (on && !clki->enabled) {
8224 ret = clk_prepare_enable(clki->clk);
8226 dev_err(hba->dev, "%s: %s prepare enable failed, %d\n",
8227 __func__, clki->name, ret);
8230 } else if (!on && clki->enabled) {
8231 clk_disable_unprepare(clki->clk);
8234 dev_dbg(hba->dev, "%s: clk: %s %sabled\n", __func__,
8235 clki->name, on ? "en" : "dis");
8240 * vendor specific setup_clocks ops may depend on clocks managed by
8241 * this standard driver hence call the vendor specific setup_clocks
8242 * after enabling the clocks managed here.
8245 ret = ufshcd_vops_setup_clocks(hba, on, is_gating_context);
8251 * call vendor specific bus vote to remove the vote after
8252 * disabling the clocks.
8255 ret = ufshcd_vops_set_bus_vote(hba, on);
8260 /* Can't do much if this fails */
8261 (void) ufshcd_vops_set_bus_vote(hba, false);
8262 list_for_each_entry(clki, head, list) {
8263 if (!IS_ERR_OR_NULL(clki->clk) && clki->enabled)
8264 clk_disable_unprepare(clki->clk);
8266 } else if (!ret && on) {
8267 spin_lock_irqsave(hba->host->host_lock, flags);
8268 hba->clk_gating.state = CLKS_ON;
8269 trace_ufshcd_clk_gating(dev_name(hba->dev),
8270 hba->clk_gating.state);
8271 spin_unlock_irqrestore(hba->host->host_lock, flags);
8272 /* restore the secure configuration as clocks are enabled */
8273 ufshcd_vops_update_sec_cfg(hba, true);
8276 if (clk_state_changed)
8277 trace_ufshcd_profile_clk_gating(dev_name(hba->dev),
8278 (on ? "on" : "off"),
8279 ktime_to_us(ktime_sub(ktime_get(), start)), ret);
8283 static int ufshcd_enable_clocks(struct ufs_hba *hba)
8285 return ufshcd_setup_clocks(hba, true, false, false);
8288 static int ufshcd_disable_clocks(struct ufs_hba *hba,
8289 bool is_gating_context)
8291 return ufshcd_setup_clocks(hba, false, false, is_gating_context);
8294 static int ufshcd_disable_clocks_skip_ref_clk(struct ufs_hba *hba,
8295 bool is_gating_context)
8297 return ufshcd_setup_clocks(hba, false, true, is_gating_context);
8300 static int ufshcd_init_clocks(struct ufs_hba *hba)
8303 struct ufs_clk_info *clki;
8304 struct device *dev = hba->dev;
8305 struct list_head *head = &hba->clk_list_head;
8307 if (!head || list_empty(head))
8310 list_for_each_entry(clki, head, list) {
8314 clki->clk = devm_clk_get(dev, clki->name);
8315 if (IS_ERR(clki->clk)) {
8316 ret = PTR_ERR(clki->clk);
8317 dev_err(dev, "%s: %s clk get failed, %d\n",
8318 __func__, clki->name, ret);
8322 if (clki->max_freq) {
8323 ret = clk_set_rate(clki->clk, clki->max_freq);
8325 dev_err(hba->dev, "%s: %s clk set rate(%dHz) failed, %d\n",
8326 __func__, clki->name,
8327 clki->max_freq, ret);
8330 clki->curr_freq = clki->max_freq;
8332 dev_dbg(dev, "%s: clk: %s, rate: %lu\n", __func__,
8333 clki->name, clk_get_rate(clki->clk));
8339 static int ufshcd_variant_hba_init(struct ufs_hba *hba)
8343 if (!hba->var || !hba->var->vops)
8346 err = ufshcd_vops_init(hba);
8350 err = ufshcd_vops_setup_regulators(hba, true);
8357 ufshcd_vops_exit(hba);
8360 dev_err(hba->dev, "%s: variant %s init failed err %d\n",
8361 __func__, ufshcd_get_var_name(hba), err);
8365 static void ufshcd_variant_hba_exit(struct ufs_hba *hba)
8367 if (!hba->var || !hba->var->vops)
8370 ufshcd_vops_setup_regulators(hba, false);
8372 ufshcd_vops_exit(hba);
8375 static int ufshcd_hba_init(struct ufs_hba *hba)
8380 * Handle host controller power separately from the UFS device power
8381 * rails as it will help controlling the UFS host controller power
8382 * collapse easily which is different than UFS device power collapse.
8383 * Also, enable the host controller power before we go ahead with rest
8384 * of the initialization here.
8386 err = ufshcd_init_hba_vreg(hba);
8390 err = ufshcd_setup_hba_vreg(hba, true);
8394 err = ufshcd_init_clocks(hba);
8396 goto out_disable_hba_vreg;
8398 err = ufshcd_enable_clocks(hba);
8400 goto out_disable_hba_vreg;
8402 err = ufshcd_init_vreg(hba);
8404 goto out_disable_clks;
8406 err = ufshcd_setup_vreg(hba, true);
8408 goto out_disable_clks;
8410 err = ufshcd_variant_hba_init(hba);
8412 goto out_disable_vreg;
8414 hba->is_powered = true;
8418 ufshcd_setup_vreg(hba, false);
8420 ufshcd_disable_clocks(hba, false);
8421 out_disable_hba_vreg:
8422 ufshcd_setup_hba_vreg(hba, false);
8427 static void ufshcd_hba_exit(struct ufs_hba *hba)
8429 if (hba->is_powered) {
8430 ufshcd_variant_hba_exit(hba);
8431 ufshcd_setup_vreg(hba, false);
8432 if (ufshcd_is_clkscaling_supported(hba)) {
8434 ufshcd_suspend_clkscaling(hba);
8435 if (hba->clk_scaling.workq)
8436 destroy_workqueue(hba->clk_scaling.workq);
8438 ufshcd_disable_clocks(hba, false);
8439 ufshcd_setup_hba_vreg(hba, false);
8440 hba->is_powered = false;
8445 ufshcd_send_request_sense(struct ufs_hba *hba, struct scsi_device *sdp)
8447 unsigned char cmd[6] = {REQUEST_SENSE,
8451 UFSHCD_REQ_SENSE_SIZE,
8456 buffer = kzalloc(UFSHCD_REQ_SENSE_SIZE, GFP_KERNEL);
8462 ret = scsi_execute_req_flags(sdp, cmd, DMA_FROM_DEVICE, buffer,
8463 UFSHCD_REQ_SENSE_SIZE, NULL,
8464 msecs_to_jiffies(1000), 3, NULL, REQ_PM);
8466 pr_err("%s: failed with err %d\n", __func__, ret);
8474 * ufshcd_set_dev_pwr_mode - sends START STOP UNIT command to set device
8476 * @hba: per adapter instance
8477 * @pwr_mode: device power mode to set
8479 * Returns 0 if requested power mode is set successfully
8480 * Returns non-zero if failed to set the requested power mode
8482 static int ufshcd_set_dev_pwr_mode(struct ufs_hba *hba,
8483 enum ufs_dev_pwr_mode pwr_mode)
8485 unsigned char cmd[6] = { START_STOP };
8486 struct scsi_sense_hdr sshdr;
8487 struct scsi_device *sdp;
8488 unsigned long flags;
8491 spin_lock_irqsave(hba->host->host_lock, flags);
8492 sdp = hba->sdev_ufs_device;
8494 ret = scsi_device_get(sdp);
8495 if (!ret && !scsi_device_online(sdp)) {
8497 scsi_device_put(sdp);
8502 spin_unlock_irqrestore(hba->host->host_lock, flags);
8508 * If scsi commands fail, the scsi mid-layer schedules scsi error-
8509 * handling, which would wait for host to be resumed. Since we know
8510 * we are functional while we are here, skip host resume in error
8513 hba->host->eh_noresume = 1;
8514 if (hba->wlun_dev_clr_ua) {
8515 ret = ufshcd_send_request_sense(hba, sdp);
8518 /* Unit attention condition is cleared now */
8519 hba->wlun_dev_clr_ua = false;
8522 cmd[4] = pwr_mode << 4;
8525 * Current function would be generally called from the power management
8526 * callbacks hence set the REQ_PM flag so that it doesn't resume the
8527 * already suspended childs.
8529 ret = scsi_execute_req_flags(sdp, cmd, DMA_NONE, NULL, 0, &sshdr,
8530 START_STOP_TIMEOUT, 0, NULL, REQ_PM);
8532 sdev_printk(KERN_WARNING, sdp,
8533 "START_STOP failed for power mode: %d, result %x\n",
8535 if (driver_byte(ret) & DRIVER_SENSE)
8536 scsi_print_sense_hdr(sdp, NULL, &sshdr);
8540 hba->curr_dev_pwr_mode = pwr_mode;
8542 scsi_device_put(sdp);
8543 hba->host->eh_noresume = 0;
8547 static int ufshcd_link_state_transition(struct ufs_hba *hba,
8548 enum uic_link_state req_link_state,
8549 int check_for_bkops)
8553 if (req_link_state == hba->uic_link_state)
8556 if (req_link_state == UIC_LINK_HIBERN8_STATE) {
8557 ret = ufshcd_uic_hibern8_enter(hba);
8559 ufshcd_set_link_hibern8(hba);
8564 * If autobkops is enabled, link can't be turned off because
8565 * turning off the link would also turn off the device.
8567 else if ((req_link_state == UIC_LINK_OFF_STATE) &&
8568 (!check_for_bkops || (check_for_bkops &&
8569 !hba->auto_bkops_enabled))) {
8571 * Let's make sure that link is in low power mode, we are doing
8572 * this currently by putting the link in Hibern8. Otherway to
8573 * put the link in low power mode is to send the DME end point
8574 * to device and then send the DME reset command to local
8575 * unipro. But putting the link in hibern8 is much faster.
8577 ret = ufshcd_uic_hibern8_enter(hba);
8581 * Change controller state to "reset state" which
8582 * should also put the link in off/reset state
8584 ufshcd_hba_stop(hba, true);
8586 * TODO: Check if we need any delay to make sure that
8587 * controller is reset
8589 ufshcd_set_link_off(hba);
8596 static void ufshcd_vreg_set_lpm(struct ufs_hba *hba)
8599 * It seems some UFS devices may keep drawing more than sleep current
8600 * (atleast for 500us) from UFS rails (especially from VCCQ rail).
8601 * To avoid this situation, add 2ms delay before putting these UFS
8602 * rails in LPM mode.
8604 if (!ufshcd_is_link_active(hba))
8605 usleep_range(2000, 2100);
8608 * If UFS device is either in UFS_Sleep turn off VCC rail to save some
8611 * If UFS device and link is in OFF state, all power supplies (VCC,
8612 * VCCQ, VCCQ2) can be turned off if power on write protect is not
8613 * required. If UFS link is inactive (Hibern8 or OFF state) and device
8614 * is in sleep state, put VCCQ & VCCQ2 rails in LPM mode.
8616 * Ignore the error returned by ufshcd_toggle_vreg() as device is anyway
8617 * in low power state which would save some power.
8619 if (ufshcd_is_ufs_dev_poweroff(hba) && ufshcd_is_link_off(hba) &&
8620 !hba->dev_info.is_lu_power_on_wp) {
8621 ufshcd_setup_vreg(hba, false);
8622 } else if (!ufshcd_is_ufs_dev_active(hba)) {
8623 ufshcd_toggle_vreg(hba->dev, hba->vreg_info.vcc, false);
8624 if (!ufshcd_is_link_active(hba)) {
8625 ufshcd_config_vreg_lpm(hba, hba->vreg_info.vccq);
8626 ufshcd_config_vreg_lpm(hba, hba->vreg_info.vccq2);
8631 static int ufshcd_vreg_set_hpm(struct ufs_hba *hba)
8635 if (ufshcd_is_ufs_dev_poweroff(hba) && ufshcd_is_link_off(hba) &&
8636 !hba->dev_info.is_lu_power_on_wp) {
8637 ret = ufshcd_setup_vreg(hba, true);
8638 } else if (!ufshcd_is_ufs_dev_active(hba)) {
8639 if (!ret && !ufshcd_is_link_active(hba)) {
8640 ret = ufshcd_config_vreg_hpm(hba, hba->vreg_info.vccq);
8643 ret = ufshcd_config_vreg_hpm(hba, hba->vreg_info.vccq2);
8647 ret = ufshcd_toggle_vreg(hba->dev, hba->vreg_info.vcc, true);
8652 ufshcd_config_vreg_lpm(hba, hba->vreg_info.vccq);
8654 ufshcd_toggle_vreg(hba->dev, hba->vreg_info.vcc, false);
8659 static void ufshcd_hba_vreg_set_lpm(struct ufs_hba *hba)
8661 if (ufshcd_is_link_off(hba) ||
8662 (ufshcd_is_link_hibern8(hba)
8663 && ufshcd_is_power_collapse_during_hibern8_allowed(hba)))
8664 ufshcd_setup_hba_vreg(hba, false);
8667 static void ufshcd_hba_vreg_set_hpm(struct ufs_hba *hba)
8669 if (ufshcd_is_link_off(hba) ||
8670 (ufshcd_is_link_hibern8(hba)
8671 && ufshcd_is_power_collapse_during_hibern8_allowed(hba)))
8672 ufshcd_setup_hba_vreg(hba, true);
8676 * ufshcd_suspend - helper function for suspend operations
8677 * @hba: per adapter instance
8678 * @pm_op: desired low power operation type
8680 * This function will try to put the UFS device and link into low power
8681 * mode based on the "rpm_lvl" (Runtime PM level) or "spm_lvl"
8682 * (System PM level).
8684 * If this function is called during shutdown, it will make sure that
8685 * both UFS device and UFS link is powered off.
8687 * NOTE: UFS device & link must be active before we enter in this function.
8689 * Returns 0 for success and non-zero for failure
8691 static int ufshcd_suspend(struct ufs_hba *hba, enum ufs_pm_op pm_op)
8694 enum ufs_pm_level pm_lvl;
8695 enum ufs_dev_pwr_mode req_dev_pwr_mode;
8696 enum uic_link_state req_link_state;
8698 hba->pm_op_in_progress = 1;
8699 if (!ufshcd_is_shutdown_pm(pm_op)) {
8700 pm_lvl = ufshcd_is_runtime_pm(pm_op) ?
8701 hba->rpm_lvl : hba->spm_lvl;
8702 req_dev_pwr_mode = ufs_get_pm_lvl_to_dev_pwr_mode(pm_lvl);
8703 req_link_state = ufs_get_pm_lvl_to_link_pwr_state(pm_lvl);
8705 req_dev_pwr_mode = UFS_POWERDOWN_PWR_MODE;
8706 req_link_state = UIC_LINK_OFF_STATE;
8710 * If we can't transition into any of the low power modes
8711 * just gate the clocks.
8713 WARN_ON(hba->hibern8_on_idle.is_enabled &&
8714 hba->hibern8_on_idle.active_reqs);
8715 ufshcd_hold_all(hba);
8716 hba->clk_gating.is_suspended = true;
8717 hba->hibern8_on_idle.is_suspended = true;
8719 if (hba->clk_scaling.is_allowed) {
8720 cancel_work_sync(&hba->clk_scaling.suspend_work);
8721 cancel_work_sync(&hba->clk_scaling.resume_work);
8722 ufshcd_suspend_clkscaling(hba);
8725 if (req_dev_pwr_mode == UFS_ACTIVE_PWR_MODE &&
8726 req_link_state == UIC_LINK_ACTIVE_STATE) {
8730 if ((req_dev_pwr_mode == hba->curr_dev_pwr_mode) &&
8731 (req_link_state == hba->uic_link_state))
8734 /* UFS device & link must be active before we enter in this function */
8735 if (!ufshcd_is_ufs_dev_active(hba) || !ufshcd_is_link_active(hba)) {
8740 if (ufshcd_is_runtime_pm(pm_op)) {
8741 if (ufshcd_can_autobkops_during_suspend(hba)) {
8743 * The device is idle with no requests in the queue,
8744 * allow background operations if bkops status shows
8745 * that performance might be impacted.
8747 ret = ufshcd_urgent_bkops(hba);
8751 /* make sure that auto bkops is disabled */
8752 ufshcd_disable_auto_bkops(hba);
8756 if ((req_dev_pwr_mode != hba->curr_dev_pwr_mode) &&
8757 ((ufshcd_is_runtime_pm(pm_op) && !hba->auto_bkops_enabled) ||
8758 !ufshcd_is_runtime_pm(pm_op))) {
8759 /* ensure that bkops is disabled */
8760 ufshcd_disable_auto_bkops(hba);
8761 ret = ufshcd_set_dev_pwr_mode(hba, req_dev_pwr_mode);
8766 ret = ufshcd_link_state_transition(hba, req_link_state, 1);
8768 goto set_dev_active;
8770 if (ufshcd_is_link_hibern8(hba) &&
8771 ufshcd_is_hibern8_on_idle_allowed(hba))
8772 hba->hibern8_on_idle.state = HIBERN8_ENTERED;
8774 ufshcd_vreg_set_lpm(hba);
8778 * Call vendor specific suspend callback. As these callbacks may access
8779 * vendor specific host controller register space call them before the
8780 * host clocks are ON.
8782 ret = ufshcd_vops_suspend(hba, pm_op);
8784 goto set_link_active;
8786 if (!ufshcd_is_link_active(hba))
8787 ret = ufshcd_disable_clocks(hba, false);
8789 /* If link is active, device ref_clk can't be switched off */
8790 ret = ufshcd_disable_clocks_skip_ref_clk(hba, false);
8792 goto set_link_active;
8794 if (ufshcd_is_clkgating_allowed(hba)) {
8795 hba->clk_gating.state = CLKS_OFF;
8796 trace_ufshcd_clk_gating(dev_name(hba->dev),
8797 hba->clk_gating.state);
8800 * Disable the host irq as host controller as there won't be any
8801 * host controller transaction expected till resume.
8803 ufshcd_disable_irq(hba);
8804 /* Put the host controller in low power mode if possible */
8805 ufshcd_hba_vreg_set_lpm(hba);
8809 if (hba->clk_scaling.is_allowed)
8810 ufshcd_resume_clkscaling(hba);
8811 ufshcd_vreg_set_hpm(hba);
8812 if (ufshcd_is_link_hibern8(hba) && !ufshcd_uic_hibern8_exit(hba)) {
8813 ufshcd_set_link_active(hba);
8814 } else if (ufshcd_is_link_off(hba)) {
8815 ufshcd_update_error_stats(hba, UFS_ERR_VOPS_SUSPEND);
8816 ufshcd_host_reset_and_restore(hba);
8819 if (!ufshcd_set_dev_pwr_mode(hba, UFS_ACTIVE_PWR_MODE))
8820 ufshcd_disable_auto_bkops(hba);
8822 if (hba->clk_scaling.is_allowed)
8823 ufshcd_resume_clkscaling(hba);
8824 hba->hibern8_on_idle.is_suspended = false;
8825 hba->clk_gating.is_suspended = false;
8826 ufshcd_release_all(hba);
8828 hba->pm_op_in_progress = 0;
8831 ufshcd_update_error_stats(hba, UFS_ERR_SUSPEND);
8837 * ufshcd_resume - helper function for resume operations
8838 * @hba: per adapter instance
8839 * @pm_op: runtime PM or system PM
8841 * This function basically brings the UFS device, UniPro link and controller
8844 * Returns 0 for success and non-zero for failure
8846 static int ufshcd_resume(struct ufs_hba *hba, enum ufs_pm_op pm_op)
8849 enum uic_link_state old_link_state;
8851 hba->pm_op_in_progress = 1;
8852 old_link_state = hba->uic_link_state;
8854 ufshcd_hba_vreg_set_hpm(hba);
8855 /* Make sure clocks are enabled before accessing controller */
8856 ret = ufshcd_enable_clocks(hba);
8860 /* enable the host irq as host controller would be active soon */
8861 ufshcd_enable_irq(hba);
8863 ret = ufshcd_vreg_set_hpm(hba);
8865 goto disable_irq_and_vops_clks;
8868 * Call vendor specific resume callback. As these callbacks may access
8869 * vendor specific host controller register space call them when the
8870 * host clocks are ON.
8872 ret = ufshcd_vops_resume(hba, pm_op);
8876 if (ufshcd_is_link_hibern8(hba)) {
8877 ret = ufshcd_uic_hibern8_exit(hba);
8879 ufshcd_set_link_active(hba);
8880 if (ufshcd_is_hibern8_on_idle_allowed(hba))
8881 hba->hibern8_on_idle.state = HIBERN8_EXITED;
8883 goto vendor_suspend;
8885 } else if (ufshcd_is_link_off(hba)) {
8887 * A full initialization of the host and the device is required
8888 * since the link was put to off during suspend.
8890 ret = ufshcd_reset_and_restore(hba);
8892 * ufshcd_reset_and_restore() should have already
8893 * set the link state as active
8895 if (ret || !ufshcd_is_link_active(hba))
8896 goto vendor_suspend;
8897 /* mark link state as hibern8 exited */
8898 if (ufshcd_is_hibern8_on_idle_allowed(hba))
8899 hba->hibern8_on_idle.state = HIBERN8_EXITED;
8902 if (!ufshcd_is_ufs_dev_active(hba)) {
8903 ret = ufshcd_set_dev_pwr_mode(hba, UFS_ACTIVE_PWR_MODE);
8905 goto set_old_link_state;
8908 if (ufshcd_keep_autobkops_enabled_except_suspend(hba))
8909 ufshcd_enable_auto_bkops(hba);
8912 * If BKOPs operations are urgently needed at this moment then
8913 * keep auto-bkops enabled or else disable it.
8915 ufshcd_urgent_bkops(hba);
8917 hba->clk_gating.is_suspended = false;
8918 hba->hibern8_on_idle.is_suspended = false;
8920 if (hba->clk_scaling.is_allowed)
8921 ufshcd_resume_clkscaling(hba);
8923 /* Schedule clock gating in case of no access to UFS device yet */
8924 ufshcd_release_all(hba);
8928 ufshcd_link_state_transition(hba, old_link_state, 0);
8929 if (ufshcd_is_link_hibern8(hba) &&
8930 ufshcd_is_hibern8_on_idle_allowed(hba))
8931 hba->hibern8_on_idle.state = HIBERN8_ENTERED;
8933 ufshcd_vops_suspend(hba, pm_op);
8935 ufshcd_vreg_set_lpm(hba);
8936 disable_irq_and_vops_clks:
8937 ufshcd_disable_irq(hba);
8938 if (hba->clk_scaling.is_allowed)
8939 ufshcd_suspend_clkscaling(hba);
8940 ufshcd_disable_clocks(hba, false);
8941 if (ufshcd_is_clkgating_allowed(hba))
8942 hba->clk_gating.state = CLKS_OFF;
8944 hba->pm_op_in_progress = 0;
8947 ufshcd_update_error_stats(hba, UFS_ERR_RESUME);
8953 * ufshcd_system_suspend - system suspend routine
8954 * @hba: per adapter instance
8955 * @pm_op: runtime PM or system PM
8957 * Check the description of ufshcd_suspend() function for more details.
8959 * Returns 0 for success and non-zero for failure
8961 int ufshcd_system_suspend(struct ufs_hba *hba)
8964 ktime_t start = ktime_get();
8966 if (!hba || !hba->is_powered)
8969 if ((ufs_get_pm_lvl_to_dev_pwr_mode(hba->spm_lvl) ==
8970 hba->curr_dev_pwr_mode) &&
8971 (ufs_get_pm_lvl_to_link_pwr_state(hba->spm_lvl) ==
8972 hba->uic_link_state))
8975 if (pm_runtime_suspended(hba->dev)) {
8977 * UFS device and/or UFS link low power states during runtime
8978 * suspend seems to be different than what is expected during
8979 * system suspend. Hence runtime resume the devic & link and
8980 * let the system suspend low power states to take effect.
8981 * TODO: If resume takes longer time, we might have optimize
8982 * it in future by not resuming everything if possible.
8984 ret = ufshcd_runtime_resume(hba);
8989 ret = ufshcd_suspend(hba, UFS_SYSTEM_PM);
8991 trace_ufshcd_system_suspend(dev_name(hba->dev), ret,
8992 ktime_to_us(ktime_sub(ktime_get(), start)),
8993 hba->curr_dev_pwr_mode, hba->uic_link_state);
8995 hba->is_sys_suspended = true;
8998 EXPORT_SYMBOL(ufshcd_system_suspend);
9001 * ufshcd_system_resume - system resume routine
9002 * @hba: per adapter instance
9004 * Returns 0 for success and non-zero for failure
9007 int ufshcd_system_resume(struct ufs_hba *hba)
9010 ktime_t start = ktime_get();
9015 if (!hba->is_powered || pm_runtime_suspended(hba->dev))
9017 * Let the runtime resume take care of resuming
9018 * if runtime suspended.
9022 ret = ufshcd_resume(hba, UFS_SYSTEM_PM);
9024 trace_ufshcd_system_resume(dev_name(hba->dev), ret,
9025 ktime_to_us(ktime_sub(ktime_get(), start)),
9026 hba->curr_dev_pwr_mode, hba->uic_link_state);
9029 EXPORT_SYMBOL(ufshcd_system_resume);
9032 * ufshcd_runtime_suspend - runtime suspend routine
9033 * @hba: per adapter instance
9035 * Check the description of ufshcd_suspend() function for more details.
9037 * Returns 0 for success and non-zero for failure
9039 int ufshcd_runtime_suspend(struct ufs_hba *hba)
9042 ktime_t start = ktime_get();
9047 if (!hba->is_powered)
9050 ret = ufshcd_suspend(hba, UFS_RUNTIME_PM);
9052 trace_ufshcd_runtime_suspend(dev_name(hba->dev), ret,
9053 ktime_to_us(ktime_sub(ktime_get(), start)),
9054 hba->curr_dev_pwr_mode,
9055 hba->uic_link_state);
9059 EXPORT_SYMBOL(ufshcd_runtime_suspend);
9062 * ufshcd_runtime_resume - runtime resume routine
9063 * @hba: per adapter instance
9065 * This function basically brings the UFS device, UniPro link and controller
9066 * to active state. Following operations are done in this function:
9068 * 1. Turn on all the controller related clocks
9069 * 2. Bring the UniPro link out of Hibernate state
9070 * 3. If UFS device is in sleep state, turn ON VCC rail and bring the UFS device
9072 * 4. If auto-bkops is enabled on the device, disable it.
9074 * So following would be the possible power state after this function return
9076 * S1: UFS device in Active state with VCC rail ON
9077 * UniPro link in Active state
9078 * All the UFS/UniPro controller clocks are ON
9080 * Returns 0 for success and non-zero for failure
9082 int ufshcd_runtime_resume(struct ufs_hba *hba)
9085 ktime_t start = ktime_get();
9090 if (!hba->is_powered)
9093 ret = ufshcd_resume(hba, UFS_RUNTIME_PM);
9095 trace_ufshcd_runtime_resume(dev_name(hba->dev), ret,
9096 ktime_to_us(ktime_sub(ktime_get(), start)),
9097 hba->curr_dev_pwr_mode,
9098 hba->uic_link_state);
9101 EXPORT_SYMBOL(ufshcd_runtime_resume);
9103 int ufshcd_runtime_idle(struct ufs_hba *hba)
9107 EXPORT_SYMBOL(ufshcd_runtime_idle);
9109 static inline ssize_t ufshcd_pm_lvl_store(struct device *dev,
9110 struct device_attribute *attr,
9111 const char *buf, size_t count,
9114 struct ufs_hba *hba = dev_get_drvdata(dev);
9115 unsigned long flags, value;
9117 if (kstrtoul(buf, 0, &value))
9120 if (value >= UFS_PM_LVL_MAX)
9123 spin_lock_irqsave(hba->host->host_lock, flags);
9125 hba->rpm_lvl = value;
9127 hba->spm_lvl = value;
9128 ufshcd_apply_pm_quirks(hba);
9129 spin_unlock_irqrestore(hba->host->host_lock, flags);
9133 static ssize_t ufshcd_rpm_lvl_show(struct device *dev,
9134 struct device_attribute *attr, char *buf)
9136 struct ufs_hba *hba = dev_get_drvdata(dev);
9140 curr_len = snprintf(buf, PAGE_SIZE,
9141 "\nCurrent Runtime PM level [%d] => dev_state [%s] link_state [%s]\n",
9143 ufschd_ufs_dev_pwr_mode_to_string(
9144 ufs_pm_lvl_states[hba->rpm_lvl].dev_state),
9145 ufschd_uic_link_state_to_string(
9146 ufs_pm_lvl_states[hba->rpm_lvl].link_state));
9148 curr_len += snprintf((buf + curr_len), (PAGE_SIZE - curr_len),
9149 "\nAll available Runtime PM levels info:\n");
9150 for (lvl = UFS_PM_LVL_0; lvl < UFS_PM_LVL_MAX; lvl++)
9151 curr_len += snprintf((buf + curr_len), (PAGE_SIZE - curr_len),
9152 "\tRuntime PM level [%d] => dev_state [%s] link_state [%s]\n",
9154 ufschd_ufs_dev_pwr_mode_to_string(
9155 ufs_pm_lvl_states[lvl].dev_state),
9156 ufschd_uic_link_state_to_string(
9157 ufs_pm_lvl_states[lvl].link_state));
9162 static ssize_t ufshcd_rpm_lvl_store(struct device *dev,
9163 struct device_attribute *attr, const char *buf, size_t count)
9165 return ufshcd_pm_lvl_store(dev, attr, buf, count, true);
9168 static void ufshcd_add_rpm_lvl_sysfs_nodes(struct ufs_hba *hba)
9170 hba->rpm_lvl_attr.show = ufshcd_rpm_lvl_show;
9171 hba->rpm_lvl_attr.store = ufshcd_rpm_lvl_store;
9172 sysfs_attr_init(&hba->rpm_lvl_attr.attr);
9173 hba->rpm_lvl_attr.attr.name = "rpm_lvl";
9174 hba->rpm_lvl_attr.attr.mode = S_IRUGO | S_IWUSR;
9175 if (device_create_file(hba->dev, &hba->rpm_lvl_attr))
9176 dev_err(hba->dev, "Failed to create sysfs for rpm_lvl\n");
9179 static ssize_t ufshcd_spm_lvl_show(struct device *dev,
9180 struct device_attribute *attr, char *buf)
9182 struct ufs_hba *hba = dev_get_drvdata(dev);
9186 curr_len = snprintf(buf, PAGE_SIZE,
9187 "\nCurrent System PM level [%d] => dev_state [%s] link_state [%s]\n",
9189 ufschd_ufs_dev_pwr_mode_to_string(
9190 ufs_pm_lvl_states[hba->spm_lvl].dev_state),
9191 ufschd_uic_link_state_to_string(
9192 ufs_pm_lvl_states[hba->spm_lvl].link_state));
9194 curr_len += snprintf((buf + curr_len), (PAGE_SIZE - curr_len),
9195 "\nAll available System PM levels info:\n");
9196 for (lvl = UFS_PM_LVL_0; lvl < UFS_PM_LVL_MAX; lvl++)
9197 curr_len += snprintf((buf + curr_len), (PAGE_SIZE - curr_len),
9198 "\tSystem PM level [%d] => dev_state [%s] link_state [%s]\n",
9200 ufschd_ufs_dev_pwr_mode_to_string(
9201 ufs_pm_lvl_states[lvl].dev_state),
9202 ufschd_uic_link_state_to_string(
9203 ufs_pm_lvl_states[lvl].link_state));
9208 static ssize_t ufshcd_spm_lvl_store(struct device *dev,
9209 struct device_attribute *attr, const char *buf, size_t count)
9211 return ufshcd_pm_lvl_store(dev, attr, buf, count, false);
9214 static void ufshcd_add_spm_lvl_sysfs_nodes(struct ufs_hba *hba)
9216 hba->spm_lvl_attr.show = ufshcd_spm_lvl_show;
9217 hba->spm_lvl_attr.store = ufshcd_spm_lvl_store;
9218 sysfs_attr_init(&hba->spm_lvl_attr.attr);
9219 hba->spm_lvl_attr.attr.name = "spm_lvl";
9220 hba->spm_lvl_attr.attr.mode = S_IRUGO | S_IWUSR;
9221 if (device_create_file(hba->dev, &hba->spm_lvl_attr))
9222 dev_err(hba->dev, "Failed to create sysfs for spm_lvl\n");
9225 static inline void ufshcd_add_sysfs_nodes(struct ufs_hba *hba)
9227 ufshcd_add_rpm_lvl_sysfs_nodes(hba);
9228 ufshcd_add_spm_lvl_sysfs_nodes(hba);
9231 static void ufshcd_shutdown_clkscaling(struct ufs_hba *hba)
9233 bool suspend = false;
9234 unsigned long flags;
9236 spin_lock_irqsave(hba->host->host_lock, flags);
9237 if (hba->clk_scaling.is_allowed) {
9238 hba->clk_scaling.is_allowed = false;
9241 spin_unlock_irqrestore(hba->host->host_lock, flags);
9244 * Scaling may be scheduled before, hence make sure it
9245 * doesn't race with shutdown
9247 if (ufshcd_is_clkscaling_supported(hba)) {
9248 device_remove_file(hba->dev, &hba->clk_scaling.enable_attr);
9249 cancel_work_sync(&hba->clk_scaling.suspend_work);
9250 cancel_work_sync(&hba->clk_scaling.resume_work);
9252 ufshcd_suspend_clkscaling(hba);
9255 /* Unregister so that devfreq_monitor can't race with shutdown */
9257 devfreq_remove_device(hba->devfreq);
9261 * ufshcd_shutdown - shutdown routine
9262 * @hba: per adapter instance
9264 * This function would power off both UFS device and UFS link.
9266 * Returns 0 always to allow force shutdown even in case of errors.
9268 int ufshcd_shutdown(struct ufs_hba *hba)
9272 if (ufshcd_is_ufs_dev_poweroff(hba) && ufshcd_is_link_off(hba))
9275 pm_runtime_get_sync(hba->dev);
9276 ufshcd_hold_all(hba);
9277 ufshcd_mark_shutdown_ongoing(hba);
9278 ufshcd_shutdown_clkscaling(hba);
9280 * (1) Acquire the lock to stop any more requests
9281 * (2) Wait for all issued requests to complete
9283 ufshcd_get_write_lock(hba);
9284 ufshcd_scsi_block_requests(hba);
9285 ret = ufshcd_wait_for_doorbell_clr(hba, U64_MAX);
9287 dev_err(hba->dev, "%s: waiting for DB clear: failed: %d\n",
9289 /* Requests may have errored out above, let it be handled */
9290 flush_work(&hba->eh_work);
9291 /* reqs issued from contexts other than shutdown will fail from now */
9292 ufshcd_scsi_unblock_requests(hba);
9293 ufshcd_release_all(hba);
9294 ret = ufshcd_suspend(hba, UFS_SHUTDOWN_PM);
9297 dev_err(hba->dev, "%s failed, err %d\n", __func__, ret);
9298 /* allow force shutdown even in case of errors */
9301 EXPORT_SYMBOL(ufshcd_shutdown);
9304 * Values permitted 0, 1, 2.
9305 * 0 -> Disable IO latency histograms (default)
9306 * 1 -> Enable IO latency histograms
9307 * 2 -> Zero out IO latency histograms
9310 latency_hist_store(struct device *dev, struct device_attribute *attr,
9311 const char *buf, size_t count)
9313 struct ufs_hba *hba = dev_get_drvdata(dev);
9316 if (kstrtol(buf, 0, &value))
9318 if (value == BLK_IO_LAT_HIST_ZERO) {
9319 memset(&hba->io_lat_read, 0, sizeof(hba->io_lat_read));
9320 memset(&hba->io_lat_write, 0, sizeof(hba->io_lat_write));
9321 } else if (value == BLK_IO_LAT_HIST_ENABLE ||
9322 value == BLK_IO_LAT_HIST_DISABLE)
9323 hba->latency_hist_enabled = value;
9328 latency_hist_show(struct device *dev, struct device_attribute *attr,
9331 struct ufs_hba *hba = dev_get_drvdata(dev);
9332 size_t written_bytes;
9334 written_bytes = blk_latency_hist_show("Read", &hba->io_lat_read,
9336 written_bytes += blk_latency_hist_show("Write", &hba->io_lat_write,
9337 buf + written_bytes, PAGE_SIZE - written_bytes);
9339 return written_bytes;
9342 static DEVICE_ATTR(latency_hist, S_IRUGO | S_IWUSR,
9343 latency_hist_show, latency_hist_store);
9346 ufshcd_init_latency_hist(struct ufs_hba *hba)
9348 if (device_create_file(hba->dev, &dev_attr_latency_hist))
9349 dev_err(hba->dev, "Failed to create latency_hist sysfs entry\n");
9353 ufshcd_exit_latency_hist(struct ufs_hba *hba)
9355 device_create_file(hba->dev, &dev_attr_latency_hist);
9359 * ufshcd_remove - de-allocate SCSI host and host memory space
9360 * data structure memory
9361 * @hba - per adapter instance
9363 void ufshcd_remove(struct ufs_hba *hba)
9365 scsi_remove_host(hba->host);
9366 /* disable interrupts */
9367 ufshcd_disable_intr(hba, hba->intr_mask);
9368 ufshcd_hba_stop(hba, true);
9370 ufshcd_exit_clk_gating(hba);
9371 ufshcd_exit_hibern8_on_idle(hba);
9372 if (ufshcd_is_clkscaling_supported(hba)) {
9373 device_remove_file(hba->dev, &hba->clk_scaling.enable_attr);
9374 ufshcd_exit_latency_hist(hba);
9375 devfreq_remove_device(hba->devfreq);
9377 ufshcd_hba_exit(hba);
9378 ufsdbg_remove_debugfs(hba);
9380 EXPORT_SYMBOL_GPL(ufshcd_remove);
9383 * ufshcd_dealloc_host - deallocate Host Bus Adapter (HBA)
9384 * @hba: pointer to Host Bus Adapter (HBA)
9386 void ufshcd_dealloc_host(struct ufs_hba *hba)
9388 scsi_host_put(hba->host);
9390 EXPORT_SYMBOL_GPL(ufshcd_dealloc_host);
9393 * ufshcd_set_dma_mask - Set dma mask based on the controller
9394 * addressing capability
9395 * @hba: per adapter instance
9397 * Returns 0 for success, non-zero for failure
9399 static int ufshcd_set_dma_mask(struct ufs_hba *hba)
9401 if (hba->capabilities & MASK_64_ADDRESSING_SUPPORT) {
9402 if (!dma_set_mask_and_coherent(hba->dev, DMA_BIT_MASK(64)))
9405 return dma_set_mask_and_coherent(hba->dev, DMA_BIT_MASK(32));
9409 * ufshcd_alloc_host - allocate Host Bus Adapter (HBA)
9410 * @dev: pointer to device handle
9411 * @hba_handle: driver private handle
9412 * Returns 0 on success, non-zero value on failure
9414 int ufshcd_alloc_host(struct device *dev, struct ufs_hba **hba_handle)
9416 struct Scsi_Host *host;
9417 struct ufs_hba *hba;
9422 "Invalid memory reference for dev is NULL\n");
9427 host = scsi_host_alloc(&ufshcd_driver_template,
9428 sizeof(struct ufs_hba));
9430 dev_err(dev, "scsi_host_alloc failed\n");
9434 hba = shost_priv(host);
9442 EXPORT_SYMBOL(ufshcd_alloc_host);
9445 * ufshcd_is_devfreq_scaling_required - check if scaling is required or not
9446 * @hba: per adapter instance
9447 * @scale_up: True if scaling up and false if scaling down
9449 * Returns true if scaling is required, false otherwise.
9451 static bool ufshcd_is_devfreq_scaling_required(struct ufs_hba *hba,
9454 struct ufs_clk_info *clki;
9455 struct list_head *head = &hba->clk_list_head;
9457 if (!head || list_empty(head))
9460 list_for_each_entry(clki, head, list) {
9461 if (!IS_ERR_OR_NULL(clki->clk)) {
9462 if (scale_up && clki->max_freq) {
9463 if (clki->curr_freq == clki->max_freq)
9466 } else if (!scale_up && clki->min_freq) {
9467 if (clki->curr_freq == clki->min_freq)
9478 * ufshcd_scale_gear - scale up/down UFS gear
9479 * @hba: per adapter instance
9480 * @scale_up: True for scaling up gear and false for scaling down
9482 * Returns 0 for success,
9483 * Returns -EBUSY if scaling can't happen at this time
9484 * Returns non-zero for any other errors
9486 static int ufshcd_scale_gear(struct ufs_hba *hba, bool scale_up)
9489 struct ufs_pa_layer_attr new_pwr_info;
9490 u32 scale_down_gear = ufshcd_vops_get_scale_down_gear(hba);
9492 BUG_ON(!hba->clk_scaling.saved_pwr_info.is_valid);
9495 memcpy(&new_pwr_info, &hba->clk_scaling.saved_pwr_info.info,
9496 sizeof(struct ufs_pa_layer_attr));
9498 * Some UFS devices may stop responding after switching from
9499 * HS-G1 to HS-G3. Also, it is found that these devices work
9500 * fine if we do 2 steps switch: HS-G1 to HS-G2 followed by
9501 * HS-G2 to HS-G3. If UFS_DEVICE_QUIRK_HS_G1_TO_HS_G3_SWITCH
9502 * quirk is enabled for such devices, this 2 steps gear switch
9503 * workaround will be applied.
9505 if ((hba->dev_quirks & UFS_DEVICE_QUIRK_HS_G1_TO_HS_G3_SWITCH)
9506 && (hba->pwr_info.gear_tx == UFS_HS_G1)
9507 && (new_pwr_info.gear_tx == UFS_HS_G3)) {
9508 /* scale up to G2 first */
9509 new_pwr_info.gear_tx = UFS_HS_G2;
9510 new_pwr_info.gear_rx = UFS_HS_G2;
9511 ret = ufshcd_change_power_mode(hba, &new_pwr_info);
9515 /* scale up to G3 now */
9516 new_pwr_info.gear_tx = UFS_HS_G3;
9517 new_pwr_info.gear_rx = UFS_HS_G3;
9518 /* now, fall through to set the HS-G3 */
9520 ret = ufshcd_change_power_mode(hba, &new_pwr_info);
9524 memcpy(&new_pwr_info, &hba->pwr_info,
9525 sizeof(struct ufs_pa_layer_attr));
9527 if (hba->pwr_info.gear_tx > scale_down_gear
9528 || hba->pwr_info.gear_rx > scale_down_gear) {
9529 /* save the current power mode */
9530 memcpy(&hba->clk_scaling.saved_pwr_info.info,
9532 sizeof(struct ufs_pa_layer_attr));
9534 /* scale down gear */
9535 new_pwr_info.gear_tx = scale_down_gear;
9536 new_pwr_info.gear_rx = scale_down_gear;
9537 if (!(hba->dev_quirks & UFS_DEVICE_NO_FASTAUTO)) {
9538 new_pwr_info.pwr_tx = FASTAUTO_MODE;
9539 new_pwr_info.pwr_rx = FASTAUTO_MODE;
9542 ret = ufshcd_change_power_mode(hba, &new_pwr_info);
9547 dev_err(hba->dev, "%s: failed err %d, old gear: (tx %d rx %d), new gear: (tx %d rx %d), scale_up = %d",
9549 hba->pwr_info.gear_tx, hba->pwr_info.gear_rx,
9550 new_pwr_info.gear_tx, new_pwr_info.gear_rx,
9556 static int ufshcd_clock_scaling_prepare(struct ufs_hba *hba)
9558 #define DOORBELL_CLR_TOUT_US (1000 * 1000) /* 1 sec */
9561 * make sure that there are no outstanding requests when
9562 * clock scaling is in progress
9564 ufshcd_scsi_block_requests(hba);
9565 down_write(&hba->lock);
9566 if (ufshcd_wait_for_doorbell_clr(hba, DOORBELL_CLR_TOUT_US)) {
9568 up_write(&hba->lock);
9569 ufshcd_scsi_unblock_requests(hba);
9575 static void ufshcd_clock_scaling_unprepare(struct ufs_hba *hba)
9577 up_write(&hba->lock);
9578 ufshcd_scsi_unblock_requests(hba);
9582 * ufshcd_devfreq_scale - scale up/down UFS clocks and gear
9583 * @hba: per adapter instance
9584 * @scale_up: True for scaling up and false for scalin down
9586 * Returns 0 for success,
9587 * Returns -EBUSY if scaling can't happen at this time
9588 * Returns non-zero for any other errors
9590 static int ufshcd_devfreq_scale(struct ufs_hba *hba, bool scale_up)
9594 /* let's not get into low power until clock scaling is completed */
9595 hba->ufs_stats.clk_hold.ctx = CLK_SCALE_WORK;
9596 ufshcd_hold_all(hba);
9598 ret = ufshcd_clock_scaling_prepare(hba);
9602 /* scale down the gear before scaling down clocks */
9604 ret = ufshcd_scale_gear(hba, false);
9606 goto clk_scaling_unprepare;
9610 * If auto hibern8 is supported then put the link in
9611 * hibern8 manually, this is to avoid auto hibern8
9612 * racing during clock frequency scaling sequence.
9614 if (ufshcd_is_auto_hibern8_supported(hba)) {
9615 ret = ufshcd_uic_hibern8_enter(hba);
9617 /* link will be bad state so no need to scale_up_gear */
9621 ret = ufshcd_scale_clks(hba, scale_up);
9625 if (ufshcd_is_auto_hibern8_supported(hba)) {
9626 ret = ufshcd_uic_hibern8_exit(hba);
9628 /* link will be bad state so no need to scale_up_gear */
9632 /* scale up the gear after scaling up clocks */
9634 ret = ufshcd_scale_gear(hba, true);
9636 ufshcd_scale_clks(hba, false);
9637 goto clk_scaling_unprepare;
9642 hba->clk_scaling.is_scaled_up = scale_up;
9644 hba->clk_gating.delay_ms =
9645 hba->clk_gating.delay_ms_perf;
9647 hba->clk_gating.delay_ms =
9648 hba->clk_gating.delay_ms_pwr_save;
9651 goto clk_scaling_unprepare;
9655 ufshcd_scale_gear(hba, true);
9656 clk_scaling_unprepare:
9657 ufshcd_clock_scaling_unprepare(hba);
9659 hba->ufs_stats.clk_rel.ctx = CLK_SCALE_WORK;
9660 ufshcd_release_all(hba);
9664 static void __ufshcd_suspend_clkscaling(struct ufs_hba *hba)
9666 unsigned long flags;
9668 devfreq_suspend_device(hba->devfreq);
9669 spin_lock_irqsave(hba->host->host_lock, flags);
9670 hba->clk_scaling.window_start_t = 0;
9671 spin_unlock_irqrestore(hba->host->host_lock, flags);
9674 static void ufshcd_suspend_clkscaling(struct ufs_hba *hba)
9676 unsigned long flags;
9677 bool suspend = false;
9679 if (!ufshcd_is_clkscaling_supported(hba))
9682 spin_lock_irqsave(hba->host->host_lock, flags);
9683 if (!hba->clk_scaling.is_suspended) {
9685 hba->clk_scaling.is_suspended = true;
9687 spin_unlock_irqrestore(hba->host->host_lock, flags);
9690 __ufshcd_suspend_clkscaling(hba);
9693 static void ufshcd_resume_clkscaling(struct ufs_hba *hba)
9695 unsigned long flags;
9696 bool resume = false;
9698 if (!ufshcd_is_clkscaling_supported(hba))
9701 spin_lock_irqsave(hba->host->host_lock, flags);
9702 if (hba->clk_scaling.is_suspended) {
9704 hba->clk_scaling.is_suspended = false;
9706 spin_unlock_irqrestore(hba->host->host_lock, flags);
9709 devfreq_resume_device(hba->devfreq);
9712 static ssize_t ufshcd_clkscale_enable_show(struct device *dev,
9713 struct device_attribute *attr, char *buf)
9715 struct ufs_hba *hba = dev_get_drvdata(dev);
9717 return snprintf(buf, PAGE_SIZE, "%d\n", hba->clk_scaling.is_allowed);
9720 static ssize_t ufshcd_clkscale_enable_store(struct device *dev,
9721 struct device_attribute *attr, const char *buf, size_t count)
9723 struct ufs_hba *hba = dev_get_drvdata(dev);
9727 if (kstrtou32(buf, 0, &value))
9731 if (value == hba->clk_scaling.is_allowed)
9734 pm_runtime_get_sync(hba->dev);
9735 ufshcd_hold(hba, false);
9737 cancel_work_sync(&hba->clk_scaling.suspend_work);
9738 cancel_work_sync(&hba->clk_scaling.resume_work);
9740 hba->clk_scaling.is_allowed = value;
9743 ufshcd_resume_clkscaling(hba);
9745 ufshcd_suspend_clkscaling(hba);
9746 err = ufshcd_devfreq_scale(hba, true);
9748 dev_err(hba->dev, "%s: failed to scale clocks up %d\n",
9752 ufshcd_release(hba, false);
9753 pm_runtime_put_sync(hba->dev);
9758 static void ufshcd_clk_scaling_suspend_work(struct work_struct *work)
9760 struct ufs_hba *hba = container_of(work, struct ufs_hba,
9761 clk_scaling.suspend_work);
9762 unsigned long irq_flags;
9764 spin_lock_irqsave(hba->host->host_lock, irq_flags);
9765 if (hba->clk_scaling.active_reqs || hba->clk_scaling.is_suspended) {
9766 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
9769 hba->clk_scaling.is_suspended = true;
9770 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
9772 __ufshcd_suspend_clkscaling(hba);
9775 static void ufshcd_clk_scaling_resume_work(struct work_struct *work)
9777 struct ufs_hba *hba = container_of(work, struct ufs_hba,
9778 clk_scaling.resume_work);
9779 unsigned long irq_flags;
9781 spin_lock_irqsave(hba->host->host_lock, irq_flags);
9782 if (!hba->clk_scaling.is_suspended) {
9783 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
9786 hba->clk_scaling.is_suspended = false;
9787 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
9789 devfreq_resume_device(hba->devfreq);
9792 static int ufshcd_devfreq_target(struct device *dev,
9793 unsigned long *freq, u32 flags)
9796 struct ufs_hba *hba = dev_get_drvdata(dev);
9797 unsigned long irq_flags;
9799 bool scale_up, sched_clk_scaling_suspend_work = false;
9801 if (!ufshcd_is_clkscaling_supported(hba))
9804 if ((*freq > 0) && (*freq < UINT_MAX)) {
9805 dev_err(hba->dev, "%s: invalid freq = %lu\n", __func__, *freq);
9809 spin_lock_irqsave(hba->host->host_lock, irq_flags);
9810 if (ufshcd_eh_in_progress(hba)) {
9811 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
9815 if (!hba->clk_scaling.active_reqs)
9816 sched_clk_scaling_suspend_work = true;
9818 scale_up = (*freq == UINT_MAX) ? true : false;
9819 if (!ufshcd_is_devfreq_scaling_required(hba, scale_up)) {
9820 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
9822 goto out; /* no state change required */
9824 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
9826 start = ktime_get();
9827 ret = ufshcd_devfreq_scale(hba, scale_up);
9828 trace_ufshcd_profile_clk_scaling(dev_name(hba->dev),
9829 (scale_up ? "up" : "down"),
9830 ktime_to_us(ktime_sub(ktime_get(), start)), ret);
9833 if (sched_clk_scaling_suspend_work)
9834 queue_work(hba->clk_scaling.workq,
9835 &hba->clk_scaling.suspend_work);
9840 static int ufshcd_devfreq_get_dev_status(struct device *dev,
9841 struct devfreq_dev_status *stat)
9843 struct ufs_hba *hba = dev_get_drvdata(dev);
9844 struct ufs_clk_scaling *scaling = &hba->clk_scaling;
9845 unsigned long flags;
9847 if (!ufshcd_is_clkscaling_supported(hba))
9850 memset(stat, 0, sizeof(*stat));
9852 spin_lock_irqsave(hba->host->host_lock, flags);
9853 if (!scaling->window_start_t)
9856 if (scaling->is_busy_started)
9857 scaling->tot_busy_t += ktime_to_us(ktime_sub(ktime_get(),
9858 scaling->busy_start_t));
9860 stat->total_time = jiffies_to_usecs((long)jiffies -
9861 (long)scaling->window_start_t);
9862 stat->busy_time = scaling->tot_busy_t;
9864 scaling->window_start_t = jiffies;
9865 scaling->tot_busy_t = 0;
9867 if (hba->outstanding_reqs) {
9868 scaling->busy_start_t = ktime_get();
9869 scaling->is_busy_started = true;
9871 scaling->busy_start_t = ktime_set(0, 0);
9872 scaling->is_busy_started = false;
9874 spin_unlock_irqrestore(hba->host->host_lock, flags);
9878 static void ufshcd_clkscaling_init_sysfs(struct ufs_hba *hba)
9880 hba->clk_scaling.enable_attr.show = ufshcd_clkscale_enable_show;
9881 hba->clk_scaling.enable_attr.store = ufshcd_clkscale_enable_store;
9882 sysfs_attr_init(&hba->clk_scaling.enable_attr.attr);
9883 hba->clk_scaling.enable_attr.attr.name = "clkscale_enable";
9884 hba->clk_scaling.enable_attr.attr.mode = S_IRUGO | S_IWUSR;
9885 if (device_create_file(hba->dev, &hba->clk_scaling.enable_attr))
9886 dev_err(hba->dev, "Failed to create sysfs for clkscale_enable\n");
9889 static void ufshcd_init_lanes_per_dir(struct ufs_hba *hba)
9891 struct device *dev = hba->dev;
9894 ret = of_property_read_u32(dev->of_node, "lanes-per-direction",
9895 &hba->lanes_per_direction);
9898 "%s: failed to read lanes-per-direction, ret=%d\n",
9900 hba->lanes_per_direction = UFSHCD_DEFAULT_LANES_PER_DIRECTION;
9904 * ufshcd_init - Driver initialization routine
9905 * @hba: per-adapter instance
9906 * @mmio_base: base register address
9907 * @irq: Interrupt line of device
9908 * Returns 0 on success, non-zero value on failure
9910 int ufshcd_init(struct ufs_hba *hba, void __iomem *mmio_base, unsigned int irq)
9913 struct Scsi_Host *host = hba->host;
9914 struct device *dev = hba->dev;
9918 "Invalid memory reference for mmio_base is NULL\n");
9923 hba->mmio_base = mmio_base;
9926 ufshcd_init_lanes_per_dir(hba);
9928 err = ufshcd_hba_init(hba);
9932 /* Read capabilities registers */
9933 ufshcd_hba_capabilities(hba);
9935 /* Get UFS version supported by the controller */
9936 hba->ufs_version = ufshcd_get_ufs_version(hba);
9938 /* print error message if ufs_version is not valid */
9939 if ((hba->ufs_version != UFSHCI_VERSION_10) &&
9940 (hba->ufs_version != UFSHCI_VERSION_11) &&
9941 (hba->ufs_version != UFSHCI_VERSION_20) &&
9942 (hba->ufs_version != UFSHCI_VERSION_21))
9943 dev_err(hba->dev, "invalid UFS version 0x%x\n",
9946 /* Get Interrupt bit mask per version */
9947 hba->intr_mask = ufshcd_get_intr_mask(hba);
9949 /* Enable debug prints */
9950 hba->ufshcd_dbg_print = DEFAULT_UFSHCD_DBG_PRINT_EN;
9952 err = ufshcd_set_dma_mask(hba);
9954 dev_err(hba->dev, "set dma mask failed\n");
9958 /* Allocate memory for host memory space */
9959 err = ufshcd_memory_alloc(hba);
9961 dev_err(hba->dev, "Memory allocation failed\n");
9966 ufshcd_host_memory_configure(hba);
9968 host->can_queue = hba->nutrs;
9969 host->cmd_per_lun = hba->nutrs;
9970 host->max_id = UFSHCD_MAX_ID;
9971 host->max_lun = UFS_MAX_LUNS;
9972 host->max_channel = UFSHCD_MAX_CHANNEL;
9973 host->unique_id = host->host_no;
9974 host->max_cmd_len = MAX_CDB_SIZE;
9975 host->set_dbd_for_caching = 1;
9977 hba->max_pwr_info.is_valid = false;
9979 /* Initailize wait queue for task management */
9980 init_waitqueue_head(&hba->tm_wq);
9981 init_waitqueue_head(&hba->tm_tag_wq);
9983 /* Initialize work queues */
9984 INIT_WORK(&hba->eh_work, ufshcd_err_handler);
9985 INIT_WORK(&hba->eeh_work, ufshcd_exception_event_handler);
9986 INIT_WORK(&hba->rls_work, ufshcd_rls_handler);
9988 /* Initialize UIC command mutex */
9989 mutex_init(&hba->uic_cmd_mutex);
9991 /* Initialize mutex for device management commands */
9992 mutex_init(&hba->dev_cmd.lock);
9994 init_rwsem(&hba->lock);
9996 /* Initialize device management tag acquire wait queue */
9997 init_waitqueue_head(&hba->dev_cmd.tag_wq);
9999 ufshcd_init_clk_gating(hba);
10000 ufshcd_init_hibern8_on_idle(hba);
10003 * In order to avoid any spurious interrupt immediately after
10004 * registering UFS controller interrupt handler, clear any pending UFS
10005 * interrupt status and disable all the UFS interrupts.
10007 ufshcd_writel(hba, ufshcd_readl(hba, REG_INTERRUPT_STATUS),
10008 REG_INTERRUPT_STATUS);
10009 ufshcd_writel(hba, 0, REG_INTERRUPT_ENABLE);
10011 * Make sure that UFS interrupts are disabled and any pending interrupt
10012 * status is cleared before registering UFS interrupt handler.
10016 /* IRQ registration */
10017 err = devm_request_irq(dev, irq, ufshcd_intr, IRQF_SHARED, UFSHCD, hba);
10019 dev_err(hba->dev, "request irq failed\n");
10022 hba->is_irq_enabled = true;
10025 err = scsi_add_host(host, hba->dev);
10027 dev_err(hba->dev, "scsi_add_host failed\n");
10031 /* Reset controller to power on reset (POR) state */
10032 ufshcd_vops_full_reset(hba);
10034 /* reset connected UFS device */
10035 err = ufshcd_reset_device(hba);
10037 dev_warn(hba->dev, "%s: device reset failed. err %d\n",
10040 /* Host controller enable */
10041 err = ufshcd_hba_enable(hba);
10043 dev_err(hba->dev, "Host controller enable failed\n");
10044 ufshcd_print_host_regs(hba);
10045 ufshcd_print_host_state(hba);
10046 goto out_remove_scsi_host;
10049 if (ufshcd_is_clkscaling_supported(hba)) {
10050 char wq_name[sizeof("ufs_clkscaling_00")];
10052 INIT_WORK(&hba->clk_scaling.suspend_work,
10053 ufshcd_clk_scaling_suspend_work);
10054 INIT_WORK(&hba->clk_scaling.resume_work,
10055 ufshcd_clk_scaling_resume_work);
10057 snprintf(wq_name, ARRAY_SIZE(wq_name), "ufs_clkscaling_%d",
10059 hba->clk_scaling.workq = create_singlethread_workqueue(wq_name);
10061 ufshcd_clkscaling_init_sysfs(hba);
10065 * If rpm_lvl and and spm_lvl are not already set to valid levels,
10066 * set the default power management level for UFS runtime and system
10067 * suspend. Default power saving mode selected is keeping UFS link in
10068 * Hibern8 state and UFS device in sleep.
10070 if (!ufshcd_is_valid_pm_lvl(hba->rpm_lvl))
10071 hba->rpm_lvl = ufs_get_desired_pm_lvl_for_dev_link_state(
10072 UFS_SLEEP_PWR_MODE,
10073 UIC_LINK_HIBERN8_STATE);
10074 if (!ufshcd_is_valid_pm_lvl(hba->spm_lvl))
10075 hba->spm_lvl = ufs_get_desired_pm_lvl_for_dev_link_state(
10076 UFS_SLEEP_PWR_MODE,
10077 UIC_LINK_HIBERN8_STATE);
10079 /* Hold auto suspend until async scan completes */
10080 pm_runtime_get_sync(dev);
10082 ufshcd_init_latency_hist(hba);
10085 * We are assuming that device wasn't put in sleep/power-down
10086 * state exclusively during the boot stage before kernel.
10087 * This assumption helps avoid doing link startup twice during
10088 * ufshcd_probe_hba().
10090 ufshcd_set_ufs_dev_active(hba);
10092 ufshcd_cmd_log_init(hba);
10094 async_schedule(ufshcd_async_scan, hba);
10096 ufsdbg_add_debugfs(hba);
10098 ufshcd_add_sysfs_nodes(hba);
10102 out_remove_scsi_host:
10103 scsi_remove_host(hba->host);
10105 ufshcd_exit_clk_gating(hba);
10106 ufshcd_exit_latency_hist(hba);
10108 hba->is_irq_enabled = false;
10109 ufshcd_hba_exit(hba);
10113 EXPORT_SYMBOL_GPL(ufshcd_init);
10115 MODULE_AUTHOR("Santosh Yaragnavi <santosh.sy@samsung.com>");
10116 MODULE_AUTHOR("Vinayak Holikatti <h.vinayak@samsung.com>");
10117 MODULE_DESCRIPTION("Generic UFS host controller driver Core");
10118 MODULE_LICENSE("GPL");
10119 MODULE_VERSION(UFSHCD_DRIVER_VERSION);