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-2019, 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);
5616 /* Update IO svc time latency histogram */
5617 if (req->lat_hist_enabled) {
5621 completion = ktime_get();
5622 delta_us = ktime_us_delta(completion,
5623 req->lat_hist_io_start);
5624 blk_update_latency_hist(
5625 (rq_data_dir(req) == READ) ?
5627 &hba->io_lat_write, delta_us);
5630 /* Do not touch lrbp after scsi done */
5631 cmd->scsi_done(cmd);
5632 } else if (lrbp->command_type == UTP_CMD_TYPE_DEV_MANAGE) {
5633 if (hba->dev_cmd.complete) {
5634 ufshcd_cond_add_cmd_trace(hba, index,
5636 complete(hba->dev_cmd.complete);
5639 if (ufshcd_is_clkscaling_supported(hba))
5640 hba->clk_scaling.active_reqs--;
5643 /* clear corresponding bits of completed commands */
5644 hba->outstanding_reqs ^= completed_reqs;
5646 ufshcd_clk_scaling_update_busy(hba);
5648 /* we might have free'd some tags above */
5649 wake_up(&hba->dev_cmd.tag_wq);
5653 * ufshcd_transfer_req_compl - handle SCSI and query command completion
5654 * @hba: per adapter instance
5657 * IRQ_HANDLED - If interrupt is valid
5658 * IRQ_NONE - If invalid interrupt
5660 static irqreturn_t ufshcd_transfer_req_compl(struct ufs_hba *hba)
5662 unsigned long completed_reqs;
5665 /* Resetting interrupt aggregation counters first and reading the
5666 * DOOR_BELL afterward allows us to handle all the completed requests.
5667 * In order to prevent other interrupts starvation the DB is read once
5668 * after reset. The down side of this solution is the possibility of
5669 * false interrupt if device completes another request after resetting
5670 * aggregation and before reading the DB.
5672 if (ufshcd_is_intr_aggr_allowed(hba))
5673 ufshcd_reset_intr_aggr(hba);
5675 tr_doorbell = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
5676 completed_reqs = tr_doorbell ^ hba->outstanding_reqs;
5678 if (completed_reqs) {
5679 __ufshcd_transfer_req_compl(hba, completed_reqs);
5687 * ufshcd_disable_ee - disable exception event
5688 * @hba: per-adapter instance
5689 * @mask: exception event to disable
5691 * Disables exception event in the device so that the EVENT_ALERT
5694 * Returns zero on success, non-zero error value on failure.
5696 static int ufshcd_disable_ee(struct ufs_hba *hba, u16 mask)
5701 if (!(hba->ee_ctrl_mask & mask))
5704 val = hba->ee_ctrl_mask & ~mask;
5705 val &= 0xFFFF; /* 2 bytes */
5706 err = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_WRITE_ATTR,
5707 QUERY_ATTR_IDN_EE_CONTROL, 0, 0, &val);
5709 hba->ee_ctrl_mask &= ~mask;
5715 * ufshcd_enable_ee - enable exception event
5716 * @hba: per-adapter instance
5717 * @mask: exception event to enable
5719 * Enable corresponding exception event in the device to allow
5720 * device to alert host in critical scenarios.
5722 * Returns zero on success, non-zero error value on failure.
5724 static int ufshcd_enable_ee(struct ufs_hba *hba, u16 mask)
5729 if (hba->ee_ctrl_mask & mask)
5732 val = hba->ee_ctrl_mask | mask;
5733 val &= 0xFFFF; /* 2 bytes */
5734 err = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_WRITE_ATTR,
5735 QUERY_ATTR_IDN_EE_CONTROL, 0, 0, &val);
5737 hba->ee_ctrl_mask |= mask;
5743 * ufshcd_enable_auto_bkops - Allow device managed BKOPS
5744 * @hba: per-adapter instance
5746 * Allow device to manage background operations on its own. Enabling
5747 * this might lead to inconsistent latencies during normal data transfers
5748 * as the device is allowed to manage its own way of handling background
5751 * Returns zero on success, non-zero on failure.
5753 static int ufshcd_enable_auto_bkops(struct ufs_hba *hba)
5757 if (hba->auto_bkops_enabled)
5760 err = ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_SET_FLAG,
5761 QUERY_FLAG_IDN_BKOPS_EN, NULL);
5763 dev_err(hba->dev, "%s: failed to enable bkops %d\n",
5768 hba->auto_bkops_enabled = true;
5769 trace_ufshcd_auto_bkops_state(dev_name(hba->dev), 1);
5771 /* No need of URGENT_BKOPS exception from the device */
5772 err = ufshcd_disable_ee(hba, MASK_EE_URGENT_BKOPS);
5774 dev_err(hba->dev, "%s: failed to disable exception event %d\n",
5781 * ufshcd_disable_auto_bkops - block device in doing background operations
5782 * @hba: per-adapter instance
5784 * Disabling background operations improves command response latency but
5785 * has drawback of device moving into critical state where the device is
5786 * not-operable. Make sure to call ufshcd_enable_auto_bkops() whenever the
5787 * host is idle so that BKOPS are managed effectively without any negative
5790 * Returns zero on success, non-zero on failure.
5792 static int ufshcd_disable_auto_bkops(struct ufs_hba *hba)
5796 if (!hba->auto_bkops_enabled)
5800 * If host assisted BKOPs is to be enabled, make sure
5801 * urgent bkops exception is allowed.
5803 err = ufshcd_enable_ee(hba, MASK_EE_URGENT_BKOPS);
5805 dev_err(hba->dev, "%s: failed to enable exception event %d\n",
5810 err = ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_CLEAR_FLAG,
5811 QUERY_FLAG_IDN_BKOPS_EN, NULL);
5813 dev_err(hba->dev, "%s: failed to disable bkops %d\n",
5815 ufshcd_disable_ee(hba, MASK_EE_URGENT_BKOPS);
5819 hba->auto_bkops_enabled = false;
5820 trace_ufshcd_auto_bkops_state(dev_name(hba->dev), 0);
5826 * ufshcd_force_reset_auto_bkops - force reset auto bkops state
5827 * @hba: per adapter instance
5829 * After a device reset the device may toggle the BKOPS_EN flag
5830 * to default value. The s/w tracking variables should be updated
5831 * as well. This function would change the auto-bkops state based on
5832 * UFSHCD_CAP_KEEP_AUTO_BKOPS_ENABLED_EXCEPT_SUSPEND.
5834 static void ufshcd_force_reset_auto_bkops(struct ufs_hba *hba)
5836 if (ufshcd_keep_autobkops_enabled_except_suspend(hba)) {
5837 hba->auto_bkops_enabled = false;
5838 hba->ee_ctrl_mask |= MASK_EE_URGENT_BKOPS;
5839 ufshcd_enable_auto_bkops(hba);
5841 hba->auto_bkops_enabled = true;
5842 hba->ee_ctrl_mask &= ~MASK_EE_URGENT_BKOPS;
5843 ufshcd_disable_auto_bkops(hba);
5847 static inline int ufshcd_get_bkops_status(struct ufs_hba *hba, u32 *status)
5849 return ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
5850 QUERY_ATTR_IDN_BKOPS_STATUS, 0, 0, status);
5854 * ufshcd_bkops_ctrl - control the auto bkops based on current bkops status
5855 * @hba: per-adapter instance
5856 * @status: bkops_status value
5858 * Read the bkops_status from the UFS device and Enable fBackgroundOpsEn
5859 * flag in the device to permit background operations if the device
5860 * bkops_status is greater than or equal to "status" argument passed to
5861 * this function, disable otherwise.
5863 * Returns 0 for success, non-zero in case of failure.
5865 * NOTE: Caller of this function can check the "hba->auto_bkops_enabled" flag
5866 * to know whether auto bkops is enabled or disabled after this function
5867 * returns control to it.
5869 static int ufshcd_bkops_ctrl(struct ufs_hba *hba,
5870 enum bkops_status status)
5873 u32 curr_status = 0;
5875 err = ufshcd_get_bkops_status(hba, &curr_status);
5877 dev_err(hba->dev, "%s: failed to get BKOPS status %d\n",
5880 } else if (curr_status > BKOPS_STATUS_MAX) {
5881 dev_err(hba->dev, "%s: invalid BKOPS status %d\n",
5882 __func__, curr_status);
5887 if (curr_status >= status)
5888 err = ufshcd_enable_auto_bkops(hba);
5890 err = ufshcd_disable_auto_bkops(hba);
5896 * ufshcd_urgent_bkops - handle urgent bkops exception event
5897 * @hba: per-adapter instance
5899 * Enable fBackgroundOpsEn flag in the device to permit background
5902 * If BKOPs is enabled, this function returns 0, 1 if the bkops in not enabled
5903 * and negative error value for any other failure.
5905 static int ufshcd_urgent_bkops(struct ufs_hba *hba)
5907 return ufshcd_bkops_ctrl(hba, hba->urgent_bkops_lvl);
5910 static inline int ufshcd_get_ee_status(struct ufs_hba *hba, u32 *status)
5912 return ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
5913 QUERY_ATTR_IDN_EE_STATUS, 0, 0, status);
5916 static void ufshcd_bkops_exception_event_handler(struct ufs_hba *hba)
5919 u32 curr_status = 0;
5921 if (hba->is_urgent_bkops_lvl_checked)
5922 goto enable_auto_bkops;
5924 err = ufshcd_get_bkops_status(hba, &curr_status);
5926 dev_err(hba->dev, "%s: failed to get BKOPS status %d\n",
5932 * We are seeing that some devices are raising the urgent bkops
5933 * exception events even when BKOPS status doesn't indicate performace
5934 * impacted or critical. Handle these device by determining their urgent
5935 * bkops status at runtime.
5937 if (curr_status < BKOPS_STATUS_PERF_IMPACT) {
5938 dev_err(hba->dev, "%s: device raised urgent BKOPS exception for bkops status %d\n",
5939 __func__, curr_status);
5940 /* update the current status as the urgent bkops level */
5941 hba->urgent_bkops_lvl = curr_status;
5942 hba->is_urgent_bkops_lvl_checked = true;
5946 err = ufshcd_enable_auto_bkops(hba);
5949 dev_err(hba->dev, "%s: failed to handle urgent bkops %d\n",
5954 * ufshcd_exception_event_handler - handle exceptions raised by device
5955 * @work: pointer to work data
5957 * Read bExceptionEventStatus attribute from the device and handle the
5958 * exception event accordingly.
5960 static void ufshcd_exception_event_handler(struct work_struct *work)
5962 struct ufs_hba *hba;
5965 hba = container_of(work, struct ufs_hba, eeh_work);
5967 pm_runtime_get_sync(hba->dev);
5968 ufshcd_scsi_block_requests(hba);
5969 err = ufshcd_get_ee_status(hba, &status);
5971 dev_err(hba->dev, "%s: failed to get exception status %d\n",
5976 status &= hba->ee_ctrl_mask;
5978 if (status & MASK_EE_URGENT_BKOPS)
5979 ufshcd_bkops_exception_event_handler(hba);
5982 ufshcd_scsi_unblock_requests(hba);
5983 pm_runtime_put(hba->dev);
5987 /* Complete requests that have door-bell cleared */
5988 static void ufshcd_complete_requests(struct ufs_hba *hba)
5990 ufshcd_transfer_req_compl(hba);
5991 ufshcd_tmc_handler(hba);
5995 * ufshcd_quirk_dl_nac_errors - This function checks if error handling is
5996 * to recover from the DL NAC errors or not.
5997 * @hba: per-adapter instance
5999 * Returns true if error handling is required, false otherwise
6001 static bool ufshcd_quirk_dl_nac_errors(struct ufs_hba *hba)
6003 unsigned long flags;
6004 bool err_handling = true;
6006 spin_lock_irqsave(hba->host->host_lock, flags);
6008 * UFS_DEVICE_QUIRK_RECOVERY_FROM_DL_NAC_ERRORS only workaround the
6009 * device fatal error and/or DL NAC & REPLAY timeout errors.
6011 if (hba->saved_err & (CONTROLLER_FATAL_ERROR | SYSTEM_BUS_FATAL_ERROR))
6014 if ((hba->saved_err & DEVICE_FATAL_ERROR) ||
6015 ((hba->saved_err & UIC_ERROR) &&
6016 (hba->saved_uic_err & UFSHCD_UIC_DL_TCx_REPLAY_ERROR))) {
6018 * we have to do error recovery but atleast silence the error
6021 hba->silence_err_logs = true;
6025 if ((hba->saved_err & UIC_ERROR) &&
6026 (hba->saved_uic_err & UFSHCD_UIC_DL_NAC_RECEIVED_ERROR)) {
6029 * wait for 50ms to see if we can get any other errors or not.
6031 spin_unlock_irqrestore(hba->host->host_lock, flags);
6033 spin_lock_irqsave(hba->host->host_lock, flags);
6036 * now check if we have got any other severe errors other than
6039 if ((hba->saved_err & INT_FATAL_ERRORS) ||
6040 ((hba->saved_err & UIC_ERROR) &&
6041 (hba->saved_uic_err & ~UFSHCD_UIC_DL_NAC_RECEIVED_ERROR))) {
6042 if (((hba->saved_err & INT_FATAL_ERRORS) ==
6043 DEVICE_FATAL_ERROR) || (hba->saved_uic_err &
6044 ~UFSHCD_UIC_DL_NAC_RECEIVED_ERROR))
6045 hba->silence_err_logs = true;
6050 * As DL NAC is the only error received so far, send out NOP
6051 * command to confirm if link is still active or not.
6052 * - If we don't get any response then do error recovery.
6053 * - If we get response then clear the DL NAC error bit.
6056 /* silence the error logs from NOP command */
6057 hba->silence_err_logs = true;
6058 spin_unlock_irqrestore(hba->host->host_lock, flags);
6059 err = ufshcd_verify_dev_init(hba);
6060 spin_lock_irqsave(hba->host->host_lock, flags);
6061 hba->silence_err_logs = false;
6064 hba->silence_err_logs = true;
6068 /* Link seems to be alive hence ignore the DL NAC errors */
6069 if (hba->saved_uic_err == UFSHCD_UIC_DL_NAC_RECEIVED_ERROR)
6070 hba->saved_err &= ~UIC_ERROR;
6071 /* clear NAC error */
6072 hba->saved_uic_err &= ~UFSHCD_UIC_DL_NAC_RECEIVED_ERROR;
6073 if (!hba->saved_uic_err) {
6074 err_handling = false;
6078 * there seems to be some errors other than NAC, so do error
6081 hba->silence_err_logs = true;
6084 spin_unlock_irqrestore(hba->host->host_lock, flags);
6085 return err_handling;
6089 * ufshcd_err_handler - handle UFS errors that require s/w attention
6090 * @work: pointer to work structure
6092 static void ufshcd_err_handler(struct work_struct *work)
6094 struct ufs_hba *hba;
6095 unsigned long flags;
6096 bool err_xfer = false, err_tm = false;
6099 bool needs_reset = false;
6100 bool clks_enabled = false;
6102 hba = container_of(work, struct ufs_hba, eh_work);
6104 spin_lock_irqsave(hba->host->host_lock, flags);
6105 ufsdbg_set_err_state(hba);
6107 if (hba->ufshcd_state == UFSHCD_STATE_RESET)
6111 * Make sure the clocks are ON before we proceed with err
6112 * handling. For the majority of cases err handler would be
6113 * run with clocks ON. There is a possibility that the err
6114 * handler was scheduled due to auto hibern8 error interrupt,
6115 * in which case the clocks could be gated or be in the
6116 * process of gating when the err handler runs.
6118 if (unlikely((hba->clk_gating.state != CLKS_ON) &&
6119 ufshcd_is_auto_hibern8_supported(hba))) {
6120 spin_unlock_irqrestore(hba->host->host_lock, flags);
6121 hba->ufs_stats.clk_hold.ctx = ERR_HNDLR_WORK;
6122 ufshcd_hold(hba, false);
6123 spin_lock_irqsave(hba->host->host_lock, flags);
6124 clks_enabled = true;
6127 hba->ufshcd_state = UFSHCD_STATE_RESET;
6128 ufshcd_set_eh_in_progress(hba);
6130 /* Complete requests that have door-bell cleared by h/w */
6131 ufshcd_complete_requests(hba);
6133 if (hba->dev_quirks & UFS_DEVICE_QUIRK_RECOVERY_FROM_DL_NAC_ERRORS) {
6136 spin_unlock_irqrestore(hba->host->host_lock, flags);
6137 /* release the lock as ufshcd_quirk_dl_nac_errors() may sleep */
6138 ret = ufshcd_quirk_dl_nac_errors(hba);
6139 spin_lock_irqsave(hba->host->host_lock, flags);
6141 goto skip_err_handling;
6145 * Dump controller state before resetting. Transfer requests state
6146 * will be dump as part of the request completion.
6148 if (hba->saved_err & (INT_FATAL_ERRORS | UIC_ERROR)) {
6149 dev_err(hba->dev, "%s: saved_err 0x%x saved_uic_err 0x%x",
6150 __func__, hba->saved_err, hba->saved_uic_err);
6151 if (!hba->silence_err_logs) {
6152 /* release lock as print host regs sleeps */
6153 spin_unlock_irqrestore(hba->host->host_lock, flags);
6154 ufshcd_print_host_regs(hba);
6155 ufshcd_print_host_state(hba);
6156 ufshcd_print_pwr_info(hba);
6157 ufshcd_print_tmrs(hba, hba->outstanding_tasks);
6158 ufshcd_print_cmd_log(hba);
6159 spin_lock_irqsave(hba->host->host_lock, flags);
6163 if ((hba->saved_err & INT_FATAL_ERRORS)
6164 || hba->saved_ce_err || hba->force_host_reset ||
6165 ((hba->saved_err & UIC_ERROR) &&
6166 (hba->saved_uic_err & (UFSHCD_UIC_DL_PA_INIT_ERROR |
6167 UFSHCD_UIC_DL_NAC_RECEIVED_ERROR |
6168 UFSHCD_UIC_DL_TCx_REPLAY_ERROR))))
6172 * if host reset is required then skip clearing the pending
6173 * transfers forcefully because they will automatically get
6174 * cleared after link startup.
6177 goto skip_pending_xfer_clear;
6179 /* release lock as clear command might sleep */
6180 spin_unlock_irqrestore(hba->host->host_lock, flags);
6181 /* Clear pending transfer requests */
6182 for_each_set_bit(tag, &hba->outstanding_reqs, hba->nutrs) {
6183 if (ufshcd_clear_cmd(hba, tag)) {
6185 goto lock_skip_pending_xfer_clear;
6189 /* Clear pending task management requests */
6190 for_each_set_bit(tag, &hba->outstanding_tasks, hba->nutmrs) {
6191 if (ufshcd_clear_tm_cmd(hba, tag)) {
6193 goto lock_skip_pending_xfer_clear;
6197 lock_skip_pending_xfer_clear:
6198 spin_lock_irqsave(hba->host->host_lock, flags);
6200 /* Complete the requests that are cleared by s/w */
6201 ufshcd_complete_requests(hba);
6203 if (err_xfer || err_tm)
6206 skip_pending_xfer_clear:
6207 /* Fatal errors need reset */
6209 unsigned long max_doorbells = (1UL << hba->nutrs) - 1;
6211 if (hba->saved_err & INT_FATAL_ERRORS)
6212 ufshcd_update_error_stats(hba,
6213 UFS_ERR_INT_FATAL_ERRORS);
6214 if (hba->saved_ce_err)
6215 ufshcd_update_error_stats(hba, UFS_ERR_CRYPTO_ENGINE);
6217 if (hba->saved_err & UIC_ERROR)
6218 ufshcd_update_error_stats(hba,
6219 UFS_ERR_INT_UIC_ERROR);
6221 if (err_xfer || err_tm)
6222 ufshcd_update_error_stats(hba,
6223 UFS_ERR_CLEAR_PEND_XFER_TM);
6226 * ufshcd_reset_and_restore() does the link reinitialization
6227 * which will need atleast one empty doorbell slot to send the
6228 * device management commands (NOP and query commands).
6229 * If there is no slot empty at this moment then free up last
6232 if (hba->outstanding_reqs == max_doorbells)
6233 __ufshcd_transfer_req_compl(hba,
6234 (1UL << (hba->nutrs - 1)));
6236 spin_unlock_irqrestore(hba->host->host_lock, flags);
6237 err = ufshcd_reset_and_restore(hba);
6238 spin_lock_irqsave(hba->host->host_lock, flags);
6240 dev_err(hba->dev, "%s: reset and restore failed\n",
6242 hba->ufshcd_state = UFSHCD_STATE_ERROR;
6245 * Inform scsi mid-layer that we did reset and allow to handle
6246 * Unit Attention properly.
6248 scsi_report_bus_reset(hba->host, 0);
6250 hba->saved_uic_err = 0;
6251 hba->saved_ce_err = 0;
6252 hba->force_host_reset = false;
6257 hba->ufshcd_state = UFSHCD_STATE_OPERATIONAL;
6258 if (hba->saved_err || hba->saved_uic_err)
6259 dev_err_ratelimited(hba->dev, "%s: exit: saved_err 0x%x saved_uic_err 0x%x",
6260 __func__, hba->saved_err, hba->saved_uic_err);
6263 hba->silence_err_logs = false;
6266 __ufshcd_release(hba, false);
6267 hba->ufs_stats.clk_rel.ctx = ERR_HNDLR_WORK;
6270 ufshcd_clear_eh_in_progress(hba);
6271 spin_unlock_irqrestore(hba->host->host_lock, flags);
6274 static void ufshcd_update_uic_reg_hist(struct ufs_uic_err_reg_hist *reg_hist,
6277 reg_hist->reg[reg_hist->pos] = reg;
6278 reg_hist->tstamp[reg_hist->pos] = ktime_get();
6279 reg_hist->pos = (reg_hist->pos + 1) % UIC_ERR_REG_HIST_LENGTH;
6282 static void ufshcd_rls_handler(struct work_struct *work)
6284 struct ufs_hba *hba;
6288 hba = container_of(work, struct ufs_hba, rls_work);
6289 ufshcd_scsi_block_requests(hba);
6290 pm_runtime_get_sync(hba->dev);
6291 ret = ufshcd_wait_for_doorbell_clr(hba, U64_MAX);
6294 "Timed out (%d) waiting for DB to clear\n",
6299 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_PWRMODE), &mode);
6300 if (hba->pwr_info.pwr_rx != ((mode >> PWR_RX_OFFSET) & PWR_INFO_MASK))
6301 hba->restore_needed = true;
6303 if (hba->pwr_info.pwr_tx != (mode & PWR_INFO_MASK))
6304 hba->restore_needed = true;
6306 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_RXGEAR), &mode);
6307 if (hba->pwr_info.gear_rx != mode)
6308 hba->restore_needed = true;
6310 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_TXGEAR), &mode);
6311 if (hba->pwr_info.gear_tx != mode)
6312 hba->restore_needed = true;
6314 if (hba->restore_needed)
6315 ret = ufshcd_config_pwr_mode(hba, &(hba->pwr_info));
6318 dev_err(hba->dev, "%s: Failed setting power mode, err = %d\n",
6321 hba->restore_needed = false;
6324 ufshcd_scsi_unblock_requests(hba);
6325 pm_runtime_put_sync(hba->dev);
6329 * ufshcd_update_uic_error - check and set fatal UIC error flags.
6330 * @hba: per-adapter instance
6333 * IRQ_HANDLED - If interrupt is valid
6334 * IRQ_NONE - If invalid interrupt
6336 static irqreturn_t ufshcd_update_uic_error(struct ufs_hba *hba)
6339 irqreturn_t retval = IRQ_NONE;
6341 /* PHY layer lane error */
6342 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_PHY_ADAPTER_LAYER);
6343 if ((reg & UIC_PHY_ADAPTER_LAYER_ERROR) &&
6344 (reg & UIC_PHY_ADAPTER_LAYER_ERROR_CODE_MASK)) {
6346 * To know whether this error is fatal or not, DB timeout
6347 * must be checked but this error is handled separately.
6349 dev_dbg(hba->dev, "%s: UIC Lane error reported, reg 0x%x\n",
6351 ufshcd_update_uic_reg_hist(&hba->ufs_stats.pa_err, reg);
6354 * Don't ignore LINERESET indication during hibern8
6357 if (reg & UIC_PHY_ADAPTER_LAYER_GENERIC_ERROR) {
6358 struct uic_command *cmd = hba->active_uic_cmd;
6361 if (cmd->command == UIC_CMD_DME_HIBER_ENTER) {
6362 dev_err(hba->dev, "%s: LINERESET during hibern8 enter, reg 0x%x\n",
6364 hba->full_init_linereset = true;
6367 if (!hba->full_init_linereset)
6368 schedule_work(&hba->rls_work);
6370 retval |= IRQ_HANDLED;
6373 /* PA_INIT_ERROR is fatal and needs UIC reset */
6374 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_DATA_LINK_LAYER);
6375 if ((reg & UIC_DATA_LINK_LAYER_ERROR) &&
6376 (reg & UIC_DATA_LINK_LAYER_ERROR_CODE_MASK)) {
6377 ufshcd_update_uic_reg_hist(&hba->ufs_stats.dl_err, reg);
6379 if (reg & UIC_DATA_LINK_LAYER_ERROR_PA_INIT) {
6380 hba->uic_error |= UFSHCD_UIC_DL_PA_INIT_ERROR;
6381 } else if (hba->dev_quirks &
6382 UFS_DEVICE_QUIRK_RECOVERY_FROM_DL_NAC_ERRORS) {
6383 if (reg & UIC_DATA_LINK_LAYER_ERROR_NAC_RECEIVED)
6385 UFSHCD_UIC_DL_NAC_RECEIVED_ERROR;
6387 UIC_DATA_LINK_LAYER_ERROR_TCx_REPLAY_TIMEOUT)
6389 UFSHCD_UIC_DL_TCx_REPLAY_ERROR;
6391 retval |= IRQ_HANDLED;
6394 /* UIC NL/TL/DME errors needs software retry */
6395 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_NETWORK_LAYER);
6396 if ((reg & UIC_NETWORK_LAYER_ERROR) &&
6397 (reg & UIC_NETWORK_LAYER_ERROR_CODE_MASK)) {
6398 ufshcd_update_uic_reg_hist(&hba->ufs_stats.nl_err, reg);
6399 hba->uic_error |= UFSHCD_UIC_NL_ERROR;
6400 retval |= IRQ_HANDLED;
6403 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_TRANSPORT_LAYER);
6404 if ((reg & UIC_TRANSPORT_LAYER_ERROR) &&
6405 (reg & UIC_TRANSPORT_LAYER_ERROR_CODE_MASK)) {
6406 ufshcd_update_uic_reg_hist(&hba->ufs_stats.tl_err, reg);
6407 hba->uic_error |= UFSHCD_UIC_TL_ERROR;
6408 retval |= IRQ_HANDLED;
6411 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_DME);
6412 if ((reg & UIC_DME_ERROR) &&
6413 (reg & UIC_DME_ERROR_CODE_MASK)) {
6414 ufshcd_update_uic_reg_hist(&hba->ufs_stats.dme_err, reg);
6415 hba->uic_error |= UFSHCD_UIC_DME_ERROR;
6416 retval |= IRQ_HANDLED;
6419 dev_dbg(hba->dev, "%s: UIC error flags = 0x%08x\n",
6420 __func__, hba->uic_error);
6425 * ufshcd_check_errors - Check for errors that need s/w attention
6426 * @hba: per-adapter instance
6429 * IRQ_HANDLED - If interrupt is valid
6430 * IRQ_NONE - If invalid interrupt
6432 static irqreturn_t ufshcd_check_errors(struct ufs_hba *hba)
6434 bool queue_eh_work = false;
6435 irqreturn_t retval = IRQ_NONE;
6437 if (hba->errors & INT_FATAL_ERRORS || hba->ce_error)
6438 queue_eh_work = true;
6440 if (hba->errors & UIC_ERROR) {
6442 retval = ufshcd_update_uic_error(hba);
6444 queue_eh_work = true;
6447 if (queue_eh_work) {
6449 * update the transfer error masks to sticky bits, let's do this
6450 * irrespective of current ufshcd_state.
6452 hba->saved_err |= hba->errors;
6453 hba->saved_uic_err |= hba->uic_error;
6454 hba->saved_ce_err |= hba->ce_error;
6456 /* handle fatal errors only when link is functional */
6457 if (hba->ufshcd_state == UFSHCD_STATE_OPERATIONAL) {
6459 * Set error handling in progress flag early so that we
6460 * don't issue new requests any more.
6462 ufshcd_set_eh_in_progress(hba);
6464 hba->ufshcd_state = UFSHCD_STATE_ERROR;
6465 schedule_work(&hba->eh_work);
6467 retval |= IRQ_HANDLED;
6470 * if (!queue_eh_work) -
6471 * Other errors are either non-fatal where host recovers
6472 * itself without s/w intervention or errors that will be
6473 * handled by the SCSI core layer.
6479 * ufshcd_tmc_handler - handle task management function completion
6480 * @hba: per adapter instance
6483 * IRQ_HANDLED - If interrupt is valid
6484 * IRQ_NONE - If invalid interrupt
6486 static irqreturn_t ufshcd_tmc_handler(struct ufs_hba *hba)
6490 tm_doorbell = ufshcd_readl(hba, REG_UTP_TASK_REQ_DOOR_BELL);
6491 hba->tm_condition = tm_doorbell ^ hba->outstanding_tasks;
6492 if (hba->tm_condition) {
6493 wake_up(&hba->tm_wq);
6501 * ufshcd_sl_intr - Interrupt service routine
6502 * @hba: per adapter instance
6503 * @intr_status: contains interrupts generated by the controller
6506 * IRQ_HANDLED - If interrupt is valid
6507 * IRQ_NONE - If invalid interrupt
6509 static irqreturn_t ufshcd_sl_intr(struct ufs_hba *hba, u32 intr_status)
6511 irqreturn_t retval = IRQ_NONE;
6513 ufsdbg_error_inject_dispatcher(hba,
6514 ERR_INJECT_INTR, intr_status, &intr_status);
6516 ufshcd_vops_crypto_engine_get_status(hba, &hba->ce_error);
6518 hba->errors = UFSHCD_ERROR_MASK & intr_status;
6519 if (hba->errors || hba->ce_error)
6520 retval |= ufshcd_check_errors(hba);
6522 if (intr_status & UFSHCD_UIC_MASK)
6523 retval |= ufshcd_uic_cmd_compl(hba, intr_status);
6525 if (intr_status & UTP_TASK_REQ_COMPL)
6526 retval |= ufshcd_tmc_handler(hba);
6528 if (intr_status & UTP_TRANSFER_REQ_COMPL)
6529 retval |= ufshcd_transfer_req_compl(hba);
6535 * ufshcd_intr - Main interrupt service routine
6537 * @__hba: pointer to adapter instance
6540 * IRQ_HANDLED - If interrupt is valid
6541 * IRQ_NONE - If invalid interrupt
6543 static irqreturn_t ufshcd_intr(int irq, void *__hba)
6545 u32 intr_status, enabled_intr_status;
6546 irqreturn_t retval = IRQ_NONE;
6547 struct ufs_hba *hba = __hba;
6548 int retries = hba->nutrs;
6550 spin_lock(hba->host->host_lock);
6551 intr_status = ufshcd_readl(hba, REG_INTERRUPT_STATUS);
6552 hba->ufs_stats.last_intr_status = intr_status;
6553 hba->ufs_stats.last_intr_ts = ktime_get();
6555 * There could be max of hba->nutrs reqs in flight and in worst case
6556 * if the reqs get finished 1 by 1 after the interrupt status is
6557 * read, make sure we handle them by checking the interrupt status
6558 * again in a loop until we process all of the reqs before returning.
6561 enabled_intr_status =
6562 intr_status & ufshcd_readl(hba, REG_INTERRUPT_ENABLE);
6564 ufshcd_writel(hba, intr_status, REG_INTERRUPT_STATUS);
6565 if (enabled_intr_status)
6566 retval |= ufshcd_sl_intr(hba, enabled_intr_status);
6568 intr_status = ufshcd_readl(hba, REG_INTERRUPT_STATUS);
6569 } while (intr_status && --retries);
6571 if (retval == IRQ_NONE) {
6572 dev_err(hba->dev, "%s: Unhandled interrupt 0x%08x\n",
6573 __func__, intr_status);
6574 ufshcd_hex_dump("host regs: ", hba->mmio_base,
6575 UFSHCI_REG_SPACE_SIZE);
6578 spin_unlock(hba->host->host_lock);
6582 static int ufshcd_clear_tm_cmd(struct ufs_hba *hba, int tag)
6585 u32 mask = 1 << tag;
6586 unsigned long flags;
6588 if (!test_bit(tag, &hba->outstanding_tasks))
6591 spin_lock_irqsave(hba->host->host_lock, flags);
6592 ufshcd_writel(hba, ~(1 << tag), REG_UTP_TASK_REQ_LIST_CLEAR);
6593 spin_unlock_irqrestore(hba->host->host_lock, flags);
6595 /* poll for max. 1 sec to clear door bell register by h/w */
6596 err = ufshcd_wait_for_register(hba,
6597 REG_UTP_TASK_REQ_DOOR_BELL,
6598 mask, 0, 1000, 1000, true);
6604 * ufshcd_issue_tm_cmd - issues task management commands to controller
6605 * @hba: per adapter instance
6606 * @lun_id: LUN ID to which TM command is sent
6607 * @task_id: task ID to which the TM command is applicable
6608 * @tm_function: task management function opcode
6609 * @tm_response: task management service response return value
6611 * Returns non-zero value on error, zero on success.
6613 static int ufshcd_issue_tm_cmd(struct ufs_hba *hba, int lun_id, int task_id,
6614 u8 tm_function, u8 *tm_response)
6616 struct utp_task_req_desc *task_req_descp;
6617 struct utp_upiu_task_req *task_req_upiup;
6618 struct Scsi_Host *host;
6619 unsigned long flags;
6627 * Get free slot, sleep if slots are unavailable.
6628 * Even though we use wait_event() which sleeps indefinitely,
6629 * the maximum wait time is bounded by %TM_CMD_TIMEOUT.
6631 wait_event(hba->tm_tag_wq, ufshcd_get_tm_free_slot(hba, &free_slot));
6632 hba->ufs_stats.clk_hold.ctx = TM_CMD_SEND;
6633 ufshcd_hold_all(hba);
6635 spin_lock_irqsave(host->host_lock, flags);
6636 task_req_descp = hba->utmrdl_base_addr;
6637 task_req_descp += free_slot;
6639 /* Configure task request descriptor */
6640 task_req_descp->header.dword_0 = cpu_to_le32(UTP_REQ_DESC_INT_CMD);
6641 task_req_descp->header.dword_2 =
6642 cpu_to_le32(OCS_INVALID_COMMAND_STATUS);
6644 /* Configure task request UPIU */
6646 (struct utp_upiu_task_req *) task_req_descp->task_req_upiu;
6647 task_tag = hba->nutrs + free_slot;
6648 task_req_upiup->header.dword_0 =
6649 UPIU_HEADER_DWORD(UPIU_TRANSACTION_TASK_REQ, 0,
6651 task_req_upiup->header.dword_1 =
6652 UPIU_HEADER_DWORD(0, tm_function, 0, 0);
6654 * The host shall provide the same value for LUN field in the basic
6655 * header and for Input Parameter.
6657 task_req_upiup->input_param1 = cpu_to_be32(lun_id);
6658 task_req_upiup->input_param2 = cpu_to_be32(task_id);
6660 /* send command to the controller */
6661 __set_bit(free_slot, &hba->outstanding_tasks);
6663 /* Make sure descriptors are ready before ringing the task doorbell */
6666 ufshcd_writel(hba, 1 << free_slot, REG_UTP_TASK_REQ_DOOR_BELL);
6667 /* Make sure that doorbell is committed immediately */
6670 spin_unlock_irqrestore(host->host_lock, flags);
6672 /* wait until the task management command is completed */
6673 err = wait_event_timeout(hba->tm_wq,
6674 test_bit(free_slot, &hba->tm_condition),
6675 msecs_to_jiffies(TM_CMD_TIMEOUT));
6677 dev_err(hba->dev, "%s: task management cmd 0x%.2x timed-out\n",
6678 __func__, tm_function);
6679 if (ufshcd_clear_tm_cmd(hba, free_slot))
6680 dev_WARN(hba->dev, "%s: unable clear tm cmd (slot %d) after timeout\n",
6681 __func__, free_slot);
6684 err = ufshcd_task_req_compl(hba, free_slot, tm_response);
6687 clear_bit(free_slot, &hba->tm_condition);
6688 ufshcd_put_tm_slot(hba, free_slot);
6689 wake_up(&hba->tm_tag_wq);
6690 hba->ufs_stats.clk_rel.ctx = TM_CMD_SEND;
6692 ufshcd_release_all(hba);
6697 * ufshcd_eh_device_reset_handler - device reset handler registered to
6699 * @cmd: SCSI command pointer
6701 * Returns SUCCESS/FAILED
6703 static int ufshcd_eh_device_reset_handler(struct scsi_cmnd *cmd)
6705 struct Scsi_Host *host;
6706 struct ufs_hba *hba;
6711 struct ufshcd_lrb *lrbp;
6712 unsigned long flags;
6714 host = cmd->device->host;
6715 hba = shost_priv(host);
6716 tag = cmd->request->tag;
6718 ufshcd_print_cmd_log(hba);
6719 lrbp = &hba->lrb[tag];
6720 err = ufshcd_issue_tm_cmd(hba, lrbp->lun, 0, UFS_LOGICAL_RESET, &resp);
6721 if (err || resp != UPIU_TASK_MANAGEMENT_FUNC_COMPL) {
6727 /* clear the commands that were pending for corresponding LUN */
6728 for_each_set_bit(pos, &hba->outstanding_reqs, hba->nutrs) {
6729 if (hba->lrb[pos].lun == lrbp->lun) {
6730 err = ufshcd_clear_cmd(hba, pos);
6735 spin_lock_irqsave(host->host_lock, flags);
6736 ufshcd_transfer_req_compl(hba);
6737 spin_unlock_irqrestore(host->host_lock, flags);
6740 hba->req_abort_count = 0;
6744 dev_err(hba->dev, "%s: failed with err %d\n", __func__, err);
6750 static void ufshcd_set_req_abort_skip(struct ufs_hba *hba, unsigned long bitmap)
6752 struct ufshcd_lrb *lrbp;
6755 for_each_set_bit(tag, &bitmap, hba->nutrs) {
6756 lrbp = &hba->lrb[tag];
6757 lrbp->req_abort_skip = true;
6762 * ufshcd_abort - abort a specific command
6763 * @cmd: SCSI command pointer
6765 * Abort the pending command in device by sending UFS_ABORT_TASK task management
6766 * command, and in host controller by clearing the door-bell register. There can
6767 * be race between controller sending the command to the device while abort is
6768 * issued. To avoid that, first issue UFS_QUERY_TASK to check if the command is
6769 * really issued and then try to abort it.
6771 * Returns SUCCESS/FAILED
6773 static int ufshcd_abort(struct scsi_cmnd *cmd)
6775 struct Scsi_Host *host;
6776 struct ufs_hba *hba;
6777 unsigned long flags;
6782 struct ufshcd_lrb *lrbp;
6785 host = cmd->device->host;
6786 hba = shost_priv(host);
6787 tag = cmd->request->tag;
6788 if (!ufshcd_valid_tag(hba, tag)) {
6790 "%s: invalid command tag %d: cmd=0x%p, cmd->request=0x%p",
6791 __func__, tag, cmd, cmd->request);
6795 lrbp = &hba->lrb[tag];
6797 ufshcd_update_error_stats(hba, UFS_ERR_TASK_ABORT);
6800 * Task abort to the device W-LUN is illegal. When this command
6801 * will fail, due to spec violation, scsi err handling next step
6802 * will be to send LU reset which, again, is a spec violation.
6803 * To avoid these unnecessary/illegal step we skip to the last error
6804 * handling stage: reset and restore.
6806 if (lrbp->lun == UFS_UPIU_UFS_DEVICE_WLUN)
6807 return ufshcd_eh_host_reset_handler(cmd);
6809 ufshcd_hold_all(hba);
6810 reg = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
6811 /* If command is already aborted/completed, return SUCCESS */
6812 if (!(test_bit(tag, &hba->outstanding_reqs))) {
6814 "%s: cmd at tag %d already completed, outstanding=0x%lx, doorbell=0x%x\n",
6815 __func__, tag, hba->outstanding_reqs, reg);
6819 if (!(reg & (1 << tag))) {
6821 "%s: cmd was completed, but without a notifying intr, tag = %d",
6825 /* Print Transfer Request of aborted task */
6826 dev_err(hba->dev, "%s: Device abort task at tag %d", __func__, tag);
6829 * Print detailed info about aborted request.
6830 * As more than one request might get aborted at the same time,
6831 * print full information only for the first aborted request in order
6832 * to reduce repeated printouts. For other aborted requests only print
6835 scsi_print_command(cmd);
6836 if (!hba->req_abort_count) {
6837 ufshcd_print_fsm_state(hba);
6838 ufshcd_print_host_regs(hba);
6839 ufshcd_print_host_state(hba);
6840 ufshcd_print_pwr_info(hba);
6841 ufshcd_print_trs(hba, 1 << tag, true);
6843 ufshcd_print_trs(hba, 1 << tag, false);
6845 hba->req_abort_count++;
6848 /* Skip task abort in case previous aborts failed and report failure */
6849 if (lrbp->req_abort_skip) {
6854 for (poll_cnt = 100; poll_cnt; poll_cnt--) {
6855 err = ufshcd_issue_tm_cmd(hba, lrbp->lun, lrbp->task_tag,
6856 UFS_QUERY_TASK, &resp);
6857 if (!err && resp == UPIU_TASK_MANAGEMENT_FUNC_SUCCEEDED) {
6858 /* cmd pending in the device */
6859 dev_err(hba->dev, "%s: cmd pending in the device. tag = %d",
6862 } else if (!err && resp == UPIU_TASK_MANAGEMENT_FUNC_COMPL) {
6864 * cmd not pending in the device, check if it is
6867 dev_err(hba->dev, "%s: cmd at tag %d not pending in the device.",
6869 reg = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
6870 if (reg & (1 << tag)) {
6871 /* sleep for max. 200us to stabilize */
6872 usleep_range(100, 200);
6875 /* command completed already */
6876 dev_err(hba->dev, "%s: cmd at tag %d successfully cleared from DB.",
6881 "%s: no response from device. tag = %d, err %d",
6882 __func__, tag, err);
6884 err = resp; /* service response error */
6894 err = ufshcd_issue_tm_cmd(hba, lrbp->lun, lrbp->task_tag,
6895 UFS_ABORT_TASK, &resp);
6896 if (err || resp != UPIU_TASK_MANAGEMENT_FUNC_COMPL) {
6898 err = resp; /* service response error */
6899 dev_err(hba->dev, "%s: issued. tag = %d, err %d",
6900 __func__, tag, err);
6905 err = ufshcd_clear_cmd(hba, tag);
6907 dev_err(hba->dev, "%s: Failed clearing cmd at tag %d, err %d",
6908 __func__, tag, err);
6912 scsi_dma_unmap(cmd);
6914 spin_lock_irqsave(host->host_lock, flags);
6915 ufshcd_outstanding_req_clear(hba, tag);
6916 hba->lrb[tag].cmd = NULL;
6917 spin_unlock_irqrestore(host->host_lock, flags);
6919 clear_bit_unlock(tag, &hba->lrb_in_use);
6920 wake_up(&hba->dev_cmd.tag_wq);
6926 dev_err(hba->dev, "%s: failed with err %d\n", __func__, err);
6927 ufshcd_set_req_abort_skip(hba, hba->outstanding_reqs);
6932 * This ufshcd_release_all() corresponds to the original scsi cmd that
6933 * got aborted here (as we won't get any IRQ for it).
6935 ufshcd_release_all(hba);
6940 * ufshcd_host_reset_and_restore - reset and restore host controller
6941 * @hba: per-adapter instance
6943 * Note that host controller reset may issue DME_RESET to
6944 * local and remote (device) Uni-Pro stack and the attributes
6945 * are reset to default state.
6947 * Returns zero on success, non-zero on failure
6949 static int ufshcd_host_reset_and_restore(struct ufs_hba *hba)
6952 unsigned long flags;
6954 /* Reset the host controller */
6955 spin_lock_irqsave(hba->host->host_lock, flags);
6956 ufshcd_hba_stop(hba, false);
6957 spin_unlock_irqrestore(hba->host->host_lock, flags);
6959 /* scale up clocks to max frequency before full reinitialization */
6960 ufshcd_set_clk_freq(hba, true);
6962 err = ufshcd_hba_enable(hba);
6966 /* Establish the link again and restore the device */
6967 err = ufshcd_probe_hba(hba);
6969 if (!err && (hba->ufshcd_state != UFSHCD_STATE_OPERATIONAL)) {
6975 err = ufshcd_vops_crypto_engine_reset(hba);
6978 "%s: failed to reset crypto engine %d\n",
6986 dev_err(hba->dev, "%s: Host init failed %d\n", __func__, err);
6992 * ufshcd_reset_and_restore - reset and re-initialize host/device
6993 * @hba: per-adapter instance
6995 * Reset and recover device, host and re-establish link. This
6996 * is helpful to recover the communication in fatal error conditions.
6998 * Returns zero on success, non-zero on failure
7000 static int ufshcd_reset_and_restore(struct ufs_hba *hba)
7003 unsigned long flags;
7004 int retries = MAX_HOST_RESET_RETRIES;
7007 err = ufshcd_vops_full_reset(hba);
7009 dev_warn(hba->dev, "%s: full reset returned %d\n",
7012 err = ufshcd_reset_device(hba);
7014 dev_warn(hba->dev, "%s: device reset failed. err %d\n",
7017 err = ufshcd_host_reset_and_restore(hba);
7018 } while (err && --retries);
7021 * There is no point proceeding even after failing
7022 * to recover after multiple retries.
7027 * After reset the door-bell might be cleared, complete
7028 * outstanding requests in s/w here.
7030 spin_lock_irqsave(hba->host->host_lock, flags);
7031 ufshcd_transfer_req_compl(hba);
7032 ufshcd_tmc_handler(hba);
7033 spin_unlock_irqrestore(hba->host->host_lock, flags);
7039 * ufshcd_eh_host_reset_handler - host reset handler registered to scsi layer
7040 * @cmd - SCSI command pointer
7042 * Returns SUCCESS/FAILED
7044 static int ufshcd_eh_host_reset_handler(struct scsi_cmnd *cmd)
7047 unsigned long flags;
7048 struct ufs_hba *hba;
7050 hba = shost_priv(cmd->device->host);
7053 * Check if there is any race with fatal error handling.
7054 * If so, wait for it to complete. Even though fatal error
7055 * handling does reset and restore in some cases, don't assume
7056 * anything out of it. We are just avoiding race here.
7059 spin_lock_irqsave(hba->host->host_lock, flags);
7060 if (!(work_pending(&hba->eh_work) ||
7061 hba->ufshcd_state == UFSHCD_STATE_RESET))
7063 spin_unlock_irqrestore(hba->host->host_lock, flags);
7064 dev_err(hba->dev, "%s: reset in progress - 1\n", __func__);
7065 flush_work(&hba->eh_work);
7069 * we don't know if previous reset had really reset the host controller
7070 * or not. So let's force reset here to be sure.
7072 hba->ufshcd_state = UFSHCD_STATE_ERROR;
7073 hba->force_host_reset = true;
7074 schedule_work(&hba->eh_work);
7076 /* wait for the reset work to finish */
7078 if (!(work_pending(&hba->eh_work) ||
7079 hba->ufshcd_state == UFSHCD_STATE_RESET))
7081 spin_unlock_irqrestore(hba->host->host_lock, flags);
7082 dev_err(hba->dev, "%s: reset in progress - 2\n", __func__);
7083 flush_work(&hba->eh_work);
7084 spin_lock_irqsave(hba->host->host_lock, flags);
7087 if (!((hba->ufshcd_state == UFSHCD_STATE_OPERATIONAL) &&
7088 ufshcd_is_link_active(hba))) {
7090 hba->ufshcd_state = UFSHCD_STATE_ERROR;
7093 spin_unlock_irqrestore(hba->host->host_lock, flags);
7099 * ufshcd_get_max_icc_level - calculate the ICC level
7100 * @sup_curr_uA: max. current supported by the regulator
7101 * @start_scan: row at the desc table to start scan from
7102 * @buff: power descriptor buffer
7104 * Returns calculated max ICC level for specific regulator
7106 static u32 ufshcd_get_max_icc_level(int sup_curr_uA, u32 start_scan, char *buff)
7113 for (i = start_scan; i >= 0; i--) {
7114 data = be16_to_cpu(*((u16 *)(buff + 2*i)));
7115 unit = (data & ATTR_ICC_LVL_UNIT_MASK) >>
7116 ATTR_ICC_LVL_UNIT_OFFSET;
7117 curr_uA = data & ATTR_ICC_LVL_VALUE_MASK;
7119 case UFSHCD_NANO_AMP:
7120 curr_uA = curr_uA / 1000;
7122 case UFSHCD_MILI_AMP:
7123 curr_uA = curr_uA * 1000;
7126 curr_uA = curr_uA * 1000 * 1000;
7128 case UFSHCD_MICRO_AMP:
7132 if (sup_curr_uA >= curr_uA)
7137 pr_err("%s: Couldn't find valid icc_level = %d", __func__, i);
7144 * ufshcd_calc_icc_level - calculate the max ICC level
7145 * In case regulators are not initialized we'll return 0
7146 * @hba: per-adapter instance
7147 * @desc_buf: power descriptor buffer to extract ICC levels from.
7148 * @len: length of desc_buff
7150 * Returns calculated ICC level
7152 static u32 ufshcd_find_max_sup_active_icc_level(struct ufs_hba *hba,
7153 u8 *desc_buf, int len)
7157 if (!hba->vreg_info.vcc || !hba->vreg_info.vccq ||
7158 !hba->vreg_info.vccq2) {
7160 "%s: Regulator capability was not set, actvIccLevel=%d",
7161 __func__, icc_level);
7165 if (hba->vreg_info.vcc && hba->vreg_info.vcc->max_uA)
7166 icc_level = ufshcd_get_max_icc_level(
7167 hba->vreg_info.vcc->max_uA,
7168 POWER_DESC_MAX_ACTV_ICC_LVLS - 1,
7169 &desc_buf[PWR_DESC_ACTIVE_LVLS_VCC_0]);
7171 if (hba->vreg_info.vccq && hba->vreg_info.vccq->max_uA)
7172 icc_level = ufshcd_get_max_icc_level(
7173 hba->vreg_info.vccq->max_uA,
7175 &desc_buf[PWR_DESC_ACTIVE_LVLS_VCCQ_0]);
7177 if (hba->vreg_info.vccq2 && hba->vreg_info.vccq2->max_uA)
7178 icc_level = ufshcd_get_max_icc_level(
7179 hba->vreg_info.vccq2->max_uA,
7181 &desc_buf[PWR_DESC_ACTIVE_LVLS_VCCQ2_0]);
7186 static void ufshcd_init_icc_levels(struct ufs_hba *hba)
7189 int buff_len = QUERY_DESC_POWER_MAX_SIZE;
7190 u8 desc_buf[QUERY_DESC_POWER_MAX_SIZE];
7192 ret = ufshcd_read_power_desc(hba, desc_buf, buff_len);
7195 "%s: Failed reading power descriptor.len = %d ret = %d",
7196 __func__, buff_len, ret);
7200 hba->init_prefetch_data.icc_level =
7201 ufshcd_find_max_sup_active_icc_level(hba,
7202 desc_buf, buff_len);
7203 dev_dbg(hba->dev, "%s: setting icc_level 0x%x",
7204 __func__, hba->init_prefetch_data.icc_level);
7206 ret = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_WRITE_ATTR,
7207 QUERY_ATTR_IDN_ACTIVE_ICC_LVL, 0, 0,
7208 &hba->init_prefetch_data.icc_level);
7212 "%s: Failed configuring bActiveICCLevel = %d ret = %d",
7213 __func__, hba->init_prefetch_data.icc_level , ret);
7218 * ufshcd_scsi_add_wlus - Adds required W-LUs
7219 * @hba: per-adapter instance
7221 * UFS device specification requires the UFS devices to support 4 well known
7223 * "REPORT_LUNS" (address: 01h)
7224 * "UFS Device" (address: 50h)
7225 * "RPMB" (address: 44h)
7226 * "BOOT" (address: 30h)
7227 * UFS device's power management needs to be controlled by "POWER CONDITION"
7228 * field of SSU (START STOP UNIT) command. But this "power condition" field
7229 * will take effect only when its sent to "UFS device" well known logical unit
7230 * hence we require the scsi_device instance to represent this logical unit in
7231 * order for the UFS host driver to send the SSU command for power management.
7233 * We also require the scsi_device instance for "RPMB" (Replay Protected Memory
7234 * Block) LU so user space process can control this LU. User space may also
7235 * want to have access to BOOT LU.
7237 * This function adds scsi device instances for each of all well known LUs
7238 * (except "REPORT LUNS" LU).
7240 * Returns zero on success (all required W-LUs are added successfully),
7241 * non-zero error value on failure (if failed to add any of the required W-LU).
7243 static int ufshcd_scsi_add_wlus(struct ufs_hba *hba)
7246 struct scsi_device *sdev_rpmb;
7247 struct scsi_device *sdev_boot;
7249 hba->sdev_ufs_device = __scsi_add_device(hba->host, 0, 0,
7250 ufshcd_upiu_wlun_to_scsi_wlun(UFS_UPIU_UFS_DEVICE_WLUN), NULL);
7251 if (IS_ERR(hba->sdev_ufs_device)) {
7252 ret = PTR_ERR(hba->sdev_ufs_device);
7253 hba->sdev_ufs_device = NULL;
7256 scsi_device_put(hba->sdev_ufs_device);
7258 sdev_boot = __scsi_add_device(hba->host, 0, 0,
7259 ufshcd_upiu_wlun_to_scsi_wlun(UFS_UPIU_BOOT_WLUN), NULL);
7260 if (IS_ERR(sdev_boot)) {
7261 ret = PTR_ERR(sdev_boot);
7262 goto remove_sdev_ufs_device;
7264 scsi_device_put(sdev_boot);
7266 sdev_rpmb = __scsi_add_device(hba->host, 0, 0,
7267 ufshcd_upiu_wlun_to_scsi_wlun(UFS_UPIU_RPMB_WLUN), NULL);
7268 if (IS_ERR(sdev_rpmb)) {
7269 ret = PTR_ERR(sdev_rpmb);
7270 goto remove_sdev_boot;
7272 scsi_device_put(sdev_rpmb);
7276 scsi_remove_device(sdev_boot);
7277 remove_sdev_ufs_device:
7278 scsi_remove_device(hba->sdev_ufs_device);
7284 * ufshcd_tune_pa_tactivate - Tunes PA_TActivate of local UniPro
7285 * @hba: per-adapter instance
7287 * PA_TActivate parameter can be tuned manually if UniPro version is less than
7288 * 1.61. PA_TActivate needs to be greater than or equal to peerM-PHY's
7289 * RX_MIN_ACTIVATETIME_CAPABILITY attribute. This optimal value can help reduce
7290 * the hibern8 exit latency.
7292 * Returns zero on success, non-zero error value on failure.
7294 static int ufshcd_tune_pa_tactivate(struct ufs_hba *hba)
7297 u32 peer_rx_min_activatetime = 0, tuned_pa_tactivate;
7299 if (!ufshcd_is_unipro_pa_params_tuning_req(hba))
7302 ret = ufshcd_dme_peer_get(hba,
7304 RX_MIN_ACTIVATETIME_CAPABILITY,
7305 UIC_ARG_MPHY_RX_GEN_SEL_INDEX(0)),
7306 &peer_rx_min_activatetime);
7310 /* make sure proper unit conversion is applied */
7311 tuned_pa_tactivate =
7312 ((peer_rx_min_activatetime * RX_MIN_ACTIVATETIME_UNIT_US)
7313 / PA_TACTIVATE_TIME_UNIT_US);
7314 ret = ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TACTIVATE),
7315 tuned_pa_tactivate);
7322 * ufshcd_tune_pa_hibern8time - Tunes PA_Hibern8Time of local UniPro
7323 * @hba: per-adapter instance
7325 * PA_Hibern8Time parameter can be tuned manually if UniPro version is less than
7326 * 1.61. PA_Hibern8Time needs to be maximum of local M-PHY's
7327 * TX_HIBERN8TIME_CAPABILITY & peer M-PHY's RX_HIBERN8TIME_CAPABILITY.
7328 * This optimal value can help reduce the hibern8 exit latency.
7330 * Returns zero on success, non-zero error value on failure.
7332 static int ufshcd_tune_pa_hibern8time(struct ufs_hba *hba)
7335 u32 local_tx_hibern8_time_cap = 0, peer_rx_hibern8_time_cap = 0;
7336 u32 max_hibern8_time, tuned_pa_hibern8time;
7338 ret = ufshcd_dme_get(hba,
7339 UIC_ARG_MIB_SEL(TX_HIBERN8TIME_CAPABILITY,
7340 UIC_ARG_MPHY_TX_GEN_SEL_INDEX(0)),
7341 &local_tx_hibern8_time_cap);
7345 ret = ufshcd_dme_peer_get(hba,
7346 UIC_ARG_MIB_SEL(RX_HIBERN8TIME_CAPABILITY,
7347 UIC_ARG_MPHY_RX_GEN_SEL_INDEX(0)),
7348 &peer_rx_hibern8_time_cap);
7352 max_hibern8_time = max(local_tx_hibern8_time_cap,
7353 peer_rx_hibern8_time_cap);
7354 /* make sure proper unit conversion is applied */
7355 tuned_pa_hibern8time = ((max_hibern8_time * HIBERN8TIME_UNIT_US)
7356 / PA_HIBERN8_TIME_UNIT_US);
7357 ret = ufshcd_dme_set(hba, UIC_ARG_MIB(PA_HIBERN8TIME),
7358 tuned_pa_hibern8time);
7364 * ufshcd_quirk_tune_host_pa_tactivate - Ensures that host PA_TACTIVATE is
7365 * less than device PA_TACTIVATE time.
7366 * @hba: per-adapter instance
7368 * Some UFS devices require host PA_TACTIVATE to be lower than device
7369 * PA_TACTIVATE, we need to enable UFS_DEVICE_QUIRK_HOST_PA_TACTIVATE quirk
7372 * Returns zero on success, non-zero error value on failure.
7374 static int ufshcd_quirk_tune_host_pa_tactivate(struct ufs_hba *hba)
7377 u32 granularity, peer_granularity;
7378 u32 pa_tactivate, peer_pa_tactivate;
7379 u32 pa_tactivate_us, peer_pa_tactivate_us;
7380 u8 gran_to_us_table[] = {1, 4, 8, 16, 32, 100};
7382 ret = ufshcd_dme_get(hba, UIC_ARG_MIB(PA_GRANULARITY),
7387 ret = ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_GRANULARITY),
7392 if ((granularity < PA_GRANULARITY_MIN_VAL) ||
7393 (granularity > PA_GRANULARITY_MAX_VAL)) {
7394 dev_err(hba->dev, "%s: invalid host PA_GRANULARITY %d",
7395 __func__, granularity);
7399 if ((peer_granularity < PA_GRANULARITY_MIN_VAL) ||
7400 (peer_granularity > PA_GRANULARITY_MAX_VAL)) {
7401 dev_err(hba->dev, "%s: invalid device PA_GRANULARITY %d",
7402 __func__, peer_granularity);
7406 ret = ufshcd_dme_get(hba, UIC_ARG_MIB(PA_TACTIVATE), &pa_tactivate);
7410 ret = ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_TACTIVATE),
7411 &peer_pa_tactivate);
7415 pa_tactivate_us = pa_tactivate * gran_to_us_table[granularity - 1];
7416 peer_pa_tactivate_us = peer_pa_tactivate *
7417 gran_to_us_table[peer_granularity - 1];
7419 if (pa_tactivate_us > peer_pa_tactivate_us) {
7420 u32 new_peer_pa_tactivate;
7422 new_peer_pa_tactivate = pa_tactivate_us /
7423 gran_to_us_table[peer_granularity - 1];
7424 new_peer_pa_tactivate++;
7425 ret = ufshcd_dme_peer_set(hba, UIC_ARG_MIB(PA_TACTIVATE),
7426 new_peer_pa_tactivate);
7433 static void ufshcd_tune_unipro_params(struct ufs_hba *hba)
7435 if (ufshcd_is_unipro_pa_params_tuning_req(hba)) {
7436 ufshcd_tune_pa_tactivate(hba);
7437 ufshcd_tune_pa_hibern8time(hba);
7440 if (hba->dev_quirks & UFS_DEVICE_QUIRK_PA_TACTIVATE)
7441 /* set 1ms timeout for PA_TACTIVATE */
7442 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TACTIVATE), 10);
7444 if (hba->dev_quirks & UFS_DEVICE_QUIRK_HOST_PA_TACTIVATE)
7445 ufshcd_quirk_tune_host_pa_tactivate(hba);
7447 ufshcd_vops_apply_dev_quirks(hba);
7450 static void ufshcd_clear_dbg_ufs_stats(struct ufs_hba *hba)
7452 int err_reg_hist_size = sizeof(struct ufs_uic_err_reg_hist);
7454 memset(&hba->ufs_stats.pa_err, 0, err_reg_hist_size);
7455 memset(&hba->ufs_stats.dl_err, 0, err_reg_hist_size);
7456 memset(&hba->ufs_stats.nl_err, 0, err_reg_hist_size);
7457 memset(&hba->ufs_stats.tl_err, 0, err_reg_hist_size);
7458 memset(&hba->ufs_stats.dme_err, 0, err_reg_hist_size);
7460 hba->req_abort_count = 0;
7463 static void ufshcd_apply_pm_quirks(struct ufs_hba *hba)
7465 if (hba->dev_quirks & UFS_DEVICE_QUIRK_NO_LINK_OFF) {
7466 if (ufs_get_pm_lvl_to_link_pwr_state(hba->rpm_lvl) ==
7467 UIC_LINK_OFF_STATE) {
7469 ufs_get_desired_pm_lvl_for_dev_link_state(
7471 UIC_LINK_HIBERN8_STATE);
7472 dev_info(hba->dev, "UFS_DEVICE_QUIRK_NO_LINK_OFF enabled, changed rpm_lvl to %d\n",
7475 if (ufs_get_pm_lvl_to_link_pwr_state(hba->spm_lvl) ==
7476 UIC_LINK_OFF_STATE) {
7478 ufs_get_desired_pm_lvl_for_dev_link_state(
7480 UIC_LINK_HIBERN8_STATE);
7481 dev_info(hba->dev, "UFS_DEVICE_QUIRK_NO_LINK_OFF enabled, changed spm_lvl to %d\n",
7488 * ufshcd_probe_hba - probe hba to detect device and initialize
7489 * @hba: per-adapter instance
7491 * Execute link-startup and verify device initialization
7493 static int ufshcd_probe_hba(struct ufs_hba *hba)
7496 ktime_t start = ktime_get();
7498 ret = ufshcd_link_startup(hba);
7502 /* Debug counters initialization */
7503 ufshcd_clear_dbg_ufs_stats(hba);
7504 /* set the default level for urgent bkops */
7505 hba->urgent_bkops_lvl = BKOPS_STATUS_PERF_IMPACT;
7506 hba->is_urgent_bkops_lvl_checked = false;
7508 /* UniPro link is active now */
7509 ufshcd_set_link_active(hba);
7511 ret = ufshcd_verify_dev_init(hba);
7515 ret = ufshcd_complete_dev_init(hba);
7519 ufs_advertise_fixup_device(hba);
7520 ufshcd_tune_unipro_params(hba);
7522 ufshcd_apply_pm_quirks(hba);
7523 ret = ufshcd_set_vccq_rail_unused(hba,
7524 (hba->dev_quirks & UFS_DEVICE_NO_VCCQ) ? true : false);
7528 /* UFS device is also active now */
7529 ufshcd_set_ufs_dev_active(hba);
7530 ufshcd_force_reset_auto_bkops(hba);
7531 hba->wlun_dev_clr_ua = true;
7533 if (ufshcd_get_max_pwr_mode(hba)) {
7535 "%s: Failed getting max supported power mode\n",
7538 ret = ufshcd_config_pwr_mode(hba, &hba->max_pwr_info.info);
7540 dev_err(hba->dev, "%s: Failed setting power mode, err = %d\n",
7546 /* set the state as operational after switching to desired gear */
7547 hba->ufshcd_state = UFSHCD_STATE_OPERATIONAL;
7549 * If we are in error handling context or in power management callbacks
7550 * context, no need to scan the host
7552 if (!ufshcd_eh_in_progress(hba) && !hba->pm_op_in_progress) {
7555 /* clear any previous UFS device information */
7556 memset(&hba->dev_info, 0, sizeof(hba->dev_info));
7557 if (!ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_READ_FLAG,
7558 QUERY_FLAG_IDN_PWR_ON_WPE, &flag))
7559 hba->dev_info.f_power_on_wp_en = flag;
7561 if (!hba->is_init_prefetch)
7562 ufshcd_init_icc_levels(hba);
7564 /* Add required well known logical units to scsi mid layer */
7565 if (ufshcd_scsi_add_wlus(hba))
7568 /* Initialize devfreq after UFS device is detected */
7569 if (ufshcd_is_clkscaling_supported(hba)) {
7570 memcpy(&hba->clk_scaling.saved_pwr_info.info,
7571 &hba->pwr_info, sizeof(struct ufs_pa_layer_attr));
7572 hba->clk_scaling.saved_pwr_info.is_valid = true;
7573 hba->clk_scaling.is_scaled_up = true;
7574 if (!hba->devfreq) {
7575 hba->devfreq = devfreq_add_device(hba->dev,
7576 &ufs_devfreq_profile,
7579 if (IS_ERR(hba->devfreq)) {
7580 ret = PTR_ERR(hba->devfreq);
7581 dev_err(hba->dev, "Unable to register with devfreq %d\n",
7586 hba->clk_scaling.is_allowed = true;
7589 scsi_scan_host(hba->host);
7590 pm_runtime_put_sync(hba->dev);
7593 if (!hba->is_init_prefetch)
7594 hba->is_init_prefetch = true;
7597 * Enable auto hibern8 if supported, after full host and
7598 * device initialization.
7600 if (ufshcd_is_auto_hibern8_supported(hba))
7601 ufshcd_set_auto_hibern8_timer(hba,
7602 hba->hibern8_on_idle.delay_ms);
7605 * If we failed to initialize the device or the device is not
7606 * present, turn off the power/clocks etc.
7608 if (ret && !ufshcd_eh_in_progress(hba) && !hba->pm_op_in_progress) {
7609 pm_runtime_put_sync(hba->dev);
7610 ufshcd_hba_exit(hba);
7613 trace_ufshcd_init(dev_name(hba->dev), ret,
7614 ktime_to_us(ktime_sub(ktime_get(), start)),
7615 hba->curr_dev_pwr_mode, hba->uic_link_state);
7620 * ufshcd_async_scan - asynchronous execution for probing hba
7621 * @data: data pointer to pass to this function
7622 * @cookie: cookie data
7624 static void ufshcd_async_scan(void *data, async_cookie_t cookie)
7626 struct ufs_hba *hba = (struct ufs_hba *)data;
7629 * Don't allow clock gating and hibern8 enter for faster device
7632 ufshcd_hold_all(hba);
7633 ufshcd_probe_hba(hba);
7634 ufshcd_release_all(hba);
7638 * ufshcd_query_ioctl - perform user read queries
7639 * @hba: per-adapter instance
7640 * @lun: used for lun specific queries
7641 * @buffer: user space buffer for reading and submitting query data and params
7642 * @return: 0 for success negative error code otherwise
7644 * Expected/Submitted buffer structure is struct ufs_ioctl_query_data.
7645 * It will read the opcode, idn and buf_length parameters, and, put the
7646 * response in the buffer field while updating the used size in buf_length.
7648 static int ufshcd_query_ioctl(struct ufs_hba *hba, u8 lun, void __user *buffer)
7650 struct ufs_ioctl_query_data *ioctl_data;
7659 ioctl_data = kzalloc(sizeof(struct ufs_ioctl_query_data), GFP_KERNEL);
7661 dev_err(hba->dev, "%s: Failed allocating %zu bytes\n", __func__,
7662 sizeof(struct ufs_ioctl_query_data));
7667 /* extract params from user buffer */
7668 err = copy_from_user(ioctl_data, buffer,
7669 sizeof(struct ufs_ioctl_query_data));
7672 "%s: Failed copying buffer from user, err %d\n",
7674 goto out_release_mem;
7677 /* verify legal parameters & send query */
7678 switch (ioctl_data->opcode) {
7679 case UPIU_QUERY_OPCODE_READ_DESC:
7680 switch (ioctl_data->idn) {
7681 case QUERY_DESC_IDN_DEVICE:
7682 case QUERY_DESC_IDN_CONFIGURAION:
7683 case QUERY_DESC_IDN_INTERCONNECT:
7684 case QUERY_DESC_IDN_GEOMETRY:
7685 case QUERY_DESC_IDN_POWER:
7688 case QUERY_DESC_IDN_UNIT:
7689 if (!ufs_is_valid_unit_desc_lun(lun)) {
7691 "%s: No unit descriptor for lun 0x%x\n",
7694 goto out_release_mem;
7701 length = min_t(int, QUERY_DESC_MAX_SIZE,
7702 ioctl_data->buf_size);
7703 desc = kzalloc(length, GFP_KERNEL);
7705 dev_err(hba->dev, "%s: Failed allocating %d bytes\n",
7708 goto out_release_mem;
7710 err = ufshcd_query_descriptor(hba, ioctl_data->opcode,
7711 ioctl_data->idn, index, 0, desc, &length);
7713 case UPIU_QUERY_OPCODE_READ_ATTR:
7714 switch (ioctl_data->idn) {
7715 case QUERY_ATTR_IDN_BOOT_LU_EN:
7716 case QUERY_ATTR_IDN_POWER_MODE:
7717 case QUERY_ATTR_IDN_ACTIVE_ICC_LVL:
7718 case QUERY_ATTR_IDN_OOO_DATA_EN:
7719 case QUERY_ATTR_IDN_BKOPS_STATUS:
7720 case QUERY_ATTR_IDN_PURGE_STATUS:
7721 case QUERY_ATTR_IDN_MAX_DATA_IN:
7722 case QUERY_ATTR_IDN_MAX_DATA_OUT:
7723 case QUERY_ATTR_IDN_REF_CLK_FREQ:
7724 case QUERY_ATTR_IDN_CONF_DESC_LOCK:
7725 case QUERY_ATTR_IDN_MAX_NUM_OF_RTT:
7726 case QUERY_ATTR_IDN_EE_CONTROL:
7727 case QUERY_ATTR_IDN_EE_STATUS:
7728 case QUERY_ATTR_IDN_SECONDS_PASSED:
7731 case QUERY_ATTR_IDN_DYN_CAP_NEEDED:
7732 case QUERY_ATTR_IDN_CORR_PRG_BLK_NUM:
7738 err = ufshcd_query_attr(hba, ioctl_data->opcode, ioctl_data->idn,
7742 case UPIU_QUERY_OPCODE_WRITE_ATTR:
7743 err = copy_from_user(&att,
7744 buffer + sizeof(struct ufs_ioctl_query_data),
7748 "%s: Failed copying buffer from user, err %d\n",
7750 goto out_release_mem;
7753 switch (ioctl_data->idn) {
7754 case QUERY_ATTR_IDN_BOOT_LU_EN:
7756 if (att > QUERY_ATTR_IDN_BOOT_LU_EN_MAX) {
7758 "%s: Illegal ufs query ioctl data, opcode 0x%x, idn 0x%x, att 0x%x\n",
7759 __func__, ioctl_data->opcode,
7760 (unsigned int)ioctl_data->idn, att);
7762 goto out_release_mem;
7768 err = ufshcd_query_attr(hba, ioctl_data->opcode,
7769 ioctl_data->idn, index, 0, &att);
7772 case UPIU_QUERY_OPCODE_READ_FLAG:
7773 switch (ioctl_data->idn) {
7774 case QUERY_FLAG_IDN_FDEVICEINIT:
7775 case QUERY_FLAG_IDN_PERMANENT_WPE:
7776 case QUERY_FLAG_IDN_PWR_ON_WPE:
7777 case QUERY_FLAG_IDN_BKOPS_EN:
7778 case QUERY_FLAG_IDN_PURGE_ENABLE:
7779 case QUERY_FLAG_IDN_FPHYRESOURCEREMOVAL:
7780 case QUERY_FLAG_IDN_BUSY_RTC:
7785 err = ufshcd_query_flag_retry(hba, ioctl_data->opcode,
7786 ioctl_data->idn, &flag);
7793 dev_err(hba->dev, "%s: Query for idn %d failed\n", __func__,
7795 goto out_release_mem;
7799 * copy response data
7800 * As we might end up reading less data then what is specified in
7801 * "ioctl_data->buf_size". So we are updating "ioctl_data->
7802 * buf_size" to what exactly we have read.
7804 switch (ioctl_data->opcode) {
7805 case UPIU_QUERY_OPCODE_READ_DESC:
7806 ioctl_data->buf_size = min_t(int, ioctl_data->buf_size, length);
7809 case UPIU_QUERY_OPCODE_READ_ATTR:
7810 ioctl_data->buf_size = sizeof(u32);
7813 case UPIU_QUERY_OPCODE_READ_FLAG:
7814 ioctl_data->buf_size = 1;
7817 case UPIU_QUERY_OPCODE_WRITE_ATTR:
7818 goto out_release_mem;
7824 err = copy_to_user(buffer, ioctl_data,
7825 sizeof(struct ufs_ioctl_query_data));
7827 dev_err(hba->dev, "%s: Failed copying back to user.\n",
7829 err = copy_to_user(buffer + sizeof(struct ufs_ioctl_query_data),
7830 data_ptr, ioctl_data->buf_size);
7832 dev_err(hba->dev, "%s: err %d copying back to user.\n",
7834 goto out_release_mem;
7838 "%s: illegal ufs query ioctl data, opcode 0x%x, idn 0x%x\n",
7839 __func__, ioctl_data->opcode, (unsigned int)ioctl_data->idn);
7849 * ufshcd_ioctl - ufs ioctl callback registered in scsi_host
7850 * @dev: scsi device required for per LUN queries
7851 * @cmd: command opcode
7852 * @buffer: user space buffer for transferring data
7854 * Supported commands:
7857 static int ufshcd_ioctl(struct scsi_device *dev, int cmd, void __user *buffer)
7859 struct ufs_hba *hba = shost_priv(dev->host);
7864 dev_err(hba->dev, "%s: User buffer is NULL!\n", __func__);
7869 case UFS_IOCTL_QUERY:
7870 pm_runtime_get_sync(hba->dev);
7871 err = ufshcd_query_ioctl(hba, ufshcd_scsi_to_upiu_lun(dev->lun),
7873 pm_runtime_put_sync(hba->dev);
7877 dev_dbg(hba->dev, "%s: Unsupported ioctl cmd %d\n", __func__,
7885 static enum blk_eh_timer_return ufshcd_eh_timed_out(struct scsi_cmnd *scmd)
7887 unsigned long flags;
7888 struct Scsi_Host *host;
7889 struct ufs_hba *hba;
7893 if (!scmd || !scmd->device || !scmd->device->host)
7894 return BLK_EH_NOT_HANDLED;
7896 host = scmd->device->host;
7897 hba = shost_priv(host);
7899 return BLK_EH_NOT_HANDLED;
7901 spin_lock_irqsave(host->host_lock, flags);
7903 for_each_set_bit(index, &hba->outstanding_reqs, hba->nutrs) {
7904 if (hba->lrb[index].cmd == scmd) {
7910 spin_unlock_irqrestore(host->host_lock, flags);
7913 * Bypass SCSI error handling and reset the block layer timer if this
7914 * SCSI command was not actually dispatched to UFS driver, otherwise
7915 * let SCSI layer handle the error as usual.
7917 return found ? BLK_EH_NOT_HANDLED : BLK_EH_RESET_TIMER;
7920 static struct scsi_host_template ufshcd_driver_template = {
7921 .module = THIS_MODULE,
7923 .proc_name = UFSHCD,
7924 .queuecommand = ufshcd_queuecommand,
7925 .slave_alloc = ufshcd_slave_alloc,
7926 .slave_configure = ufshcd_slave_configure,
7927 .slave_destroy = ufshcd_slave_destroy,
7928 .change_queue_depth = ufshcd_change_queue_depth,
7929 .eh_abort_handler = ufshcd_abort,
7930 .eh_device_reset_handler = ufshcd_eh_device_reset_handler,
7931 .eh_host_reset_handler = ufshcd_eh_host_reset_handler,
7932 .eh_timed_out = ufshcd_eh_timed_out,
7933 .ioctl = ufshcd_ioctl,
7934 #ifdef CONFIG_COMPAT
7935 .compat_ioctl = ufshcd_ioctl,
7938 .sg_tablesize = SG_ALL,
7939 .cmd_per_lun = UFSHCD_CMD_PER_LUN,
7940 .can_queue = UFSHCD_CAN_QUEUE,
7941 .max_host_blocked = 1,
7942 .track_queue_depth = 1,
7945 static int ufshcd_config_vreg_load(struct device *dev, struct ufs_vreg *vreg,
7954 * "set_load" operation shall be required on those regulators
7955 * which specifically configured current limitation. Otherwise
7956 * zero max_uA may cause unexpected behavior when regulator is
7957 * enabled or set as high power mode.
7962 ret = regulator_set_load(vreg->reg, ua);
7964 dev_err(dev, "%s: %s set load (ua=%d) failed, err=%d\n",
7965 __func__, vreg->name, ua, ret);
7971 static inline int ufshcd_config_vreg_lpm(struct ufs_hba *hba,
7972 struct ufs_vreg *vreg)
7976 else if (vreg->unused)
7979 return ufshcd_config_vreg_load(hba->dev, vreg,
7980 UFS_VREG_LPM_LOAD_UA);
7983 static inline int ufshcd_config_vreg_hpm(struct ufs_hba *hba,
7984 struct ufs_vreg *vreg)
7988 else if (vreg->unused)
7991 return ufshcd_config_vreg_load(hba->dev, vreg, vreg->max_uA);
7994 static int ufshcd_config_vreg(struct device *dev,
7995 struct ufs_vreg *vreg, bool on)
7998 struct regulator *reg;
8000 int min_uV, uA_load;
8007 if (regulator_count_voltages(reg) > 0) {
8008 uA_load = on ? vreg->max_uA : 0;
8009 ret = ufshcd_config_vreg_load(dev, vreg, uA_load);
8013 if (vreg->min_uV && vreg->max_uV) {
8014 min_uV = on ? vreg->min_uV : 0;
8015 ret = regulator_set_voltage(reg, min_uV, vreg->max_uV);
8018 "%s: %s set voltage failed, err=%d\n",
8019 __func__, name, ret);
8028 static int ufshcd_enable_vreg(struct device *dev, struct ufs_vreg *vreg)
8034 else if (vreg->enabled || vreg->unused)
8037 ret = ufshcd_config_vreg(dev, vreg, true);
8039 ret = regulator_enable(vreg->reg);
8042 vreg->enabled = true;
8044 dev_err(dev, "%s: %s enable failed, err=%d\n",
8045 __func__, vreg->name, ret);
8050 static int ufshcd_disable_vreg(struct device *dev, struct ufs_vreg *vreg)
8056 else if (!vreg->enabled || vreg->unused)
8059 ret = regulator_disable(vreg->reg);
8062 /* ignore errors on applying disable config */
8063 ufshcd_config_vreg(dev, vreg, false);
8064 vreg->enabled = false;
8066 dev_err(dev, "%s: %s disable failed, err=%d\n",
8067 __func__, vreg->name, ret);
8073 static int ufshcd_setup_vreg(struct ufs_hba *hba, bool on)
8076 struct device *dev = hba->dev;
8077 struct ufs_vreg_info *info = &hba->vreg_info;
8082 ret = ufshcd_toggle_vreg(dev, info->vcc, on);
8086 ret = ufshcd_toggle_vreg(dev, info->vccq, on);
8090 ret = ufshcd_toggle_vreg(dev, info->vccq2, on);
8096 ufshcd_toggle_vreg(dev, info->vccq2, false);
8097 ufshcd_toggle_vreg(dev, info->vccq, false);
8098 ufshcd_toggle_vreg(dev, info->vcc, false);
8103 static int ufshcd_setup_hba_vreg(struct ufs_hba *hba, bool on)
8105 struct ufs_vreg_info *info = &hba->vreg_info;
8108 if (info->vdd_hba) {
8109 ret = ufshcd_toggle_vreg(hba->dev, info->vdd_hba, on);
8112 ufshcd_vops_update_sec_cfg(hba, on);
8118 static int ufshcd_get_vreg(struct device *dev, struct ufs_vreg *vreg)
8125 vreg->reg = devm_regulator_get(dev, vreg->name);
8126 if (IS_ERR(vreg->reg)) {
8127 ret = PTR_ERR(vreg->reg);
8128 dev_err(dev, "%s: %s get failed, err=%d\n",
8129 __func__, vreg->name, ret);
8135 static int ufshcd_init_vreg(struct ufs_hba *hba)
8138 struct device *dev = hba->dev;
8139 struct ufs_vreg_info *info = &hba->vreg_info;
8144 ret = ufshcd_get_vreg(dev, info->vcc);
8148 ret = ufshcd_get_vreg(dev, info->vccq);
8152 ret = ufshcd_get_vreg(dev, info->vccq2);
8157 static int ufshcd_init_hba_vreg(struct ufs_hba *hba)
8159 struct ufs_vreg_info *info = &hba->vreg_info;
8162 return ufshcd_get_vreg(hba->dev, info->vdd_hba);
8167 static int ufshcd_set_vccq_rail_unused(struct ufs_hba *hba, bool unused)
8170 struct ufs_vreg_info *info = &hba->vreg_info;
8174 else if (!info->vccq)
8178 /* shut off the rail here */
8179 ret = ufshcd_toggle_vreg(hba->dev, info->vccq, false);
8181 * Mark this rail as no longer used, so it doesn't get enabled
8185 info->vccq->unused = true;
8188 * rail should have been already enabled hence just make sure
8189 * that unused flag is cleared.
8191 info->vccq->unused = false;
8197 static int ufshcd_setup_clocks(struct ufs_hba *hba, bool on,
8198 bool skip_ref_clk, bool is_gating_context)
8201 struct ufs_clk_info *clki;
8202 struct list_head *head = &hba->clk_list_head;
8203 unsigned long flags;
8204 ktime_t start = ktime_get();
8205 bool clk_state_changed = false;
8207 if (!head || list_empty(head))
8210 /* call vendor specific bus vote before enabling the clocks */
8212 ret = ufshcd_vops_set_bus_vote(hba, on);
8218 * vendor specific setup_clocks ops may depend on clocks managed by
8219 * this standard driver hence call the vendor specific setup_clocks
8220 * before disabling the clocks managed here.
8223 ret = ufshcd_vops_setup_clocks(hba, on, is_gating_context);
8228 list_for_each_entry(clki, head, list) {
8229 if (!IS_ERR_OR_NULL(clki->clk)) {
8230 if (skip_ref_clk && !strcmp(clki->name, "ref_clk"))
8233 clk_state_changed = on ^ clki->enabled;
8234 if (on && !clki->enabled) {
8235 ret = clk_prepare_enable(clki->clk);
8237 dev_err(hba->dev, "%s: %s prepare enable failed, %d\n",
8238 __func__, clki->name, ret);
8241 } else if (!on && clki->enabled) {
8242 clk_disable_unprepare(clki->clk);
8245 dev_dbg(hba->dev, "%s: clk: %s %sabled\n", __func__,
8246 clki->name, on ? "en" : "dis");
8251 * vendor specific setup_clocks ops may depend on clocks managed by
8252 * this standard driver hence call the vendor specific setup_clocks
8253 * after enabling the clocks managed here.
8256 ret = ufshcd_vops_setup_clocks(hba, on, is_gating_context);
8262 * call vendor specific bus vote to remove the vote after
8263 * disabling the clocks.
8266 ret = ufshcd_vops_set_bus_vote(hba, on);
8271 /* Can't do much if this fails */
8272 (void) ufshcd_vops_set_bus_vote(hba, false);
8273 list_for_each_entry(clki, head, list) {
8274 if (!IS_ERR_OR_NULL(clki->clk) && clki->enabled)
8275 clk_disable_unprepare(clki->clk);
8277 } else if (!ret && on) {
8278 spin_lock_irqsave(hba->host->host_lock, flags);
8279 hba->clk_gating.state = CLKS_ON;
8280 trace_ufshcd_clk_gating(dev_name(hba->dev),
8281 hba->clk_gating.state);
8282 spin_unlock_irqrestore(hba->host->host_lock, flags);
8283 /* restore the secure configuration as clocks are enabled */
8284 ufshcd_vops_update_sec_cfg(hba, true);
8287 if (clk_state_changed)
8288 trace_ufshcd_profile_clk_gating(dev_name(hba->dev),
8289 (on ? "on" : "off"),
8290 ktime_to_us(ktime_sub(ktime_get(), start)), ret);
8294 static int ufshcd_enable_clocks(struct ufs_hba *hba)
8296 return ufshcd_setup_clocks(hba, true, false, false);
8299 static int ufshcd_disable_clocks(struct ufs_hba *hba,
8300 bool is_gating_context)
8302 return ufshcd_setup_clocks(hba, false, false, is_gating_context);
8305 static int ufshcd_disable_clocks_skip_ref_clk(struct ufs_hba *hba,
8306 bool is_gating_context)
8308 return ufshcd_setup_clocks(hba, false, true, is_gating_context);
8311 static int ufshcd_init_clocks(struct ufs_hba *hba)
8314 struct ufs_clk_info *clki;
8315 struct device *dev = hba->dev;
8316 struct list_head *head = &hba->clk_list_head;
8318 if (!head || list_empty(head))
8321 list_for_each_entry(clki, head, list) {
8325 clki->clk = devm_clk_get(dev, clki->name);
8326 if (IS_ERR(clki->clk)) {
8327 ret = PTR_ERR(clki->clk);
8328 dev_err(dev, "%s: %s clk get failed, %d\n",
8329 __func__, clki->name, ret);
8333 if (clki->max_freq) {
8334 ret = clk_set_rate(clki->clk, clki->max_freq);
8336 dev_err(hba->dev, "%s: %s clk set rate(%dHz) failed, %d\n",
8337 __func__, clki->name,
8338 clki->max_freq, ret);
8341 clki->curr_freq = clki->max_freq;
8343 dev_dbg(dev, "%s: clk: %s, rate: %lu\n", __func__,
8344 clki->name, clk_get_rate(clki->clk));
8350 static int ufshcd_variant_hba_init(struct ufs_hba *hba)
8354 if (!hba->var || !hba->var->vops)
8357 err = ufshcd_vops_init(hba);
8361 err = ufshcd_vops_setup_regulators(hba, true);
8368 ufshcd_vops_exit(hba);
8371 dev_err(hba->dev, "%s: variant %s init failed err %d\n",
8372 __func__, ufshcd_get_var_name(hba), err);
8376 static void ufshcd_variant_hba_exit(struct ufs_hba *hba)
8378 if (!hba->var || !hba->var->vops)
8381 ufshcd_vops_setup_regulators(hba, false);
8383 ufshcd_vops_exit(hba);
8386 static int ufshcd_hba_init(struct ufs_hba *hba)
8391 * Handle host controller power separately from the UFS device power
8392 * rails as it will help controlling the UFS host controller power
8393 * collapse easily which is different than UFS device power collapse.
8394 * Also, enable the host controller power before we go ahead with rest
8395 * of the initialization here.
8397 err = ufshcd_init_hba_vreg(hba);
8401 err = ufshcd_setup_hba_vreg(hba, true);
8405 err = ufshcd_init_clocks(hba);
8407 goto out_disable_hba_vreg;
8409 err = ufshcd_enable_clocks(hba);
8411 goto out_disable_hba_vreg;
8413 err = ufshcd_init_vreg(hba);
8415 goto out_disable_clks;
8417 err = ufshcd_setup_vreg(hba, true);
8419 goto out_disable_clks;
8421 err = ufshcd_variant_hba_init(hba);
8423 goto out_disable_vreg;
8425 hba->is_powered = true;
8429 ufshcd_setup_vreg(hba, false);
8431 ufshcd_disable_clocks(hba, false);
8432 out_disable_hba_vreg:
8433 ufshcd_setup_hba_vreg(hba, false);
8438 static void ufshcd_hba_exit(struct ufs_hba *hba)
8440 if (hba->is_powered) {
8441 ufshcd_variant_hba_exit(hba);
8442 ufshcd_setup_vreg(hba, false);
8443 if (ufshcd_is_clkscaling_supported(hba)) {
8445 ufshcd_suspend_clkscaling(hba);
8446 if (hba->clk_scaling.workq)
8447 destroy_workqueue(hba->clk_scaling.workq);
8449 ufshcd_disable_clocks(hba, false);
8450 ufshcd_setup_hba_vreg(hba, false);
8451 hba->is_powered = false;
8456 ufshcd_send_request_sense(struct ufs_hba *hba, struct scsi_device *sdp)
8458 unsigned char cmd[6] = {REQUEST_SENSE,
8462 UFSHCD_REQ_SENSE_SIZE,
8467 buffer = kzalloc(UFSHCD_REQ_SENSE_SIZE, GFP_KERNEL);
8473 ret = scsi_execute_req_flags(sdp, cmd, DMA_FROM_DEVICE, buffer,
8474 UFSHCD_REQ_SENSE_SIZE, NULL,
8475 msecs_to_jiffies(1000), 3, NULL, REQ_PM);
8477 pr_err("%s: failed with err %d\n", __func__, ret);
8485 * ufshcd_set_dev_pwr_mode - sends START STOP UNIT command to set device
8487 * @hba: per adapter instance
8488 * @pwr_mode: device power mode to set
8490 * Returns 0 if requested power mode is set successfully
8491 * Returns non-zero if failed to set the requested power mode
8493 static int ufshcd_set_dev_pwr_mode(struct ufs_hba *hba,
8494 enum ufs_dev_pwr_mode pwr_mode)
8496 unsigned char cmd[6] = { START_STOP };
8497 struct scsi_sense_hdr sshdr;
8498 struct scsi_device *sdp;
8499 unsigned long flags;
8502 spin_lock_irqsave(hba->host->host_lock, flags);
8503 sdp = hba->sdev_ufs_device;
8505 ret = scsi_device_get(sdp);
8506 if (!ret && !scsi_device_online(sdp)) {
8508 scsi_device_put(sdp);
8513 spin_unlock_irqrestore(hba->host->host_lock, flags);
8519 * If scsi commands fail, the scsi mid-layer schedules scsi error-
8520 * handling, which would wait for host to be resumed. Since we know
8521 * we are functional while we are here, skip host resume in error
8524 hba->host->eh_noresume = 1;
8525 if (hba->wlun_dev_clr_ua) {
8526 ret = ufshcd_send_request_sense(hba, sdp);
8529 /* Unit attention condition is cleared now */
8530 hba->wlun_dev_clr_ua = false;
8533 cmd[4] = pwr_mode << 4;
8536 * Current function would be generally called from the power management
8537 * callbacks hence set the REQ_PM flag so that it doesn't resume the
8538 * already suspended childs.
8540 ret = scsi_execute_req_flags(sdp, cmd, DMA_NONE, NULL, 0, &sshdr,
8541 START_STOP_TIMEOUT, 0, NULL, REQ_PM);
8543 sdev_printk(KERN_WARNING, sdp,
8544 "START_STOP failed for power mode: %d, result %x\n",
8546 if (driver_byte(ret) & DRIVER_SENSE)
8547 scsi_print_sense_hdr(sdp, NULL, &sshdr);
8551 hba->curr_dev_pwr_mode = pwr_mode;
8553 scsi_device_put(sdp);
8554 hba->host->eh_noresume = 0;
8558 static int ufshcd_link_state_transition(struct ufs_hba *hba,
8559 enum uic_link_state req_link_state,
8560 int check_for_bkops)
8564 if (req_link_state == hba->uic_link_state)
8567 if (req_link_state == UIC_LINK_HIBERN8_STATE) {
8568 ret = ufshcd_uic_hibern8_enter(hba);
8570 ufshcd_set_link_hibern8(hba);
8575 * If autobkops is enabled, link can't be turned off because
8576 * turning off the link would also turn off the device.
8578 else if ((req_link_state == UIC_LINK_OFF_STATE) &&
8579 (!check_for_bkops || (check_for_bkops &&
8580 !hba->auto_bkops_enabled))) {
8582 * Let's make sure that link is in low power mode, we are doing
8583 * this currently by putting the link in Hibern8. Otherway to
8584 * put the link in low power mode is to send the DME end point
8585 * to device and then send the DME reset command to local
8586 * unipro. But putting the link in hibern8 is much faster.
8588 ret = ufshcd_uic_hibern8_enter(hba);
8592 * Change controller state to "reset state" which
8593 * should also put the link in off/reset state
8595 ufshcd_hba_stop(hba, true);
8597 * TODO: Check if we need any delay to make sure that
8598 * controller is reset
8600 ufshcd_set_link_off(hba);
8607 static void ufshcd_vreg_set_lpm(struct ufs_hba *hba)
8610 * It seems some UFS devices may keep drawing more than sleep current
8611 * (atleast for 500us) from UFS rails (especially from VCCQ rail).
8612 * To avoid this situation, add 2ms delay before putting these UFS
8613 * rails in LPM mode.
8615 if (!ufshcd_is_link_active(hba))
8616 usleep_range(2000, 2100);
8619 * If UFS device is either in UFS_Sleep turn off VCC rail to save some
8622 * If UFS device and link is in OFF state, all power supplies (VCC,
8623 * VCCQ, VCCQ2) can be turned off if power on write protect is not
8624 * required. If UFS link is inactive (Hibern8 or OFF state) and device
8625 * is in sleep state, put VCCQ & VCCQ2 rails in LPM mode.
8627 * Ignore the error returned by ufshcd_toggle_vreg() as device is anyway
8628 * in low power state which would save some power.
8630 if (ufshcd_is_ufs_dev_poweroff(hba) && ufshcd_is_link_off(hba) &&
8631 !hba->dev_info.is_lu_power_on_wp) {
8632 ufshcd_setup_vreg(hba, false);
8633 } else if (!ufshcd_is_ufs_dev_active(hba)) {
8634 ufshcd_toggle_vreg(hba->dev, hba->vreg_info.vcc, false);
8635 if (!ufshcd_is_link_active(hba)) {
8636 ufshcd_config_vreg_lpm(hba, hba->vreg_info.vccq);
8637 ufshcd_config_vreg_lpm(hba, hba->vreg_info.vccq2);
8642 static int ufshcd_vreg_set_hpm(struct ufs_hba *hba)
8646 if (ufshcd_is_ufs_dev_poweroff(hba) && ufshcd_is_link_off(hba) &&
8647 !hba->dev_info.is_lu_power_on_wp) {
8648 ret = ufshcd_setup_vreg(hba, true);
8649 } else if (!ufshcd_is_ufs_dev_active(hba)) {
8650 if (!ret && !ufshcd_is_link_active(hba)) {
8651 ret = ufshcd_config_vreg_hpm(hba, hba->vreg_info.vccq);
8654 ret = ufshcd_config_vreg_hpm(hba, hba->vreg_info.vccq2);
8658 ret = ufshcd_toggle_vreg(hba->dev, hba->vreg_info.vcc, true);
8663 ufshcd_config_vreg_lpm(hba, hba->vreg_info.vccq);
8665 ufshcd_toggle_vreg(hba->dev, hba->vreg_info.vcc, false);
8670 static void ufshcd_hba_vreg_set_lpm(struct ufs_hba *hba)
8672 if (ufshcd_is_link_off(hba) ||
8673 (ufshcd_is_link_hibern8(hba)
8674 && ufshcd_is_power_collapse_during_hibern8_allowed(hba)))
8675 ufshcd_setup_hba_vreg(hba, false);
8678 static void ufshcd_hba_vreg_set_hpm(struct ufs_hba *hba)
8680 if (ufshcd_is_link_off(hba) ||
8681 (ufshcd_is_link_hibern8(hba)
8682 && ufshcd_is_power_collapse_during_hibern8_allowed(hba)))
8683 ufshcd_setup_hba_vreg(hba, true);
8687 * ufshcd_suspend - helper function for suspend operations
8688 * @hba: per adapter instance
8689 * @pm_op: desired low power operation type
8691 * This function will try to put the UFS device and link into low power
8692 * mode based on the "rpm_lvl" (Runtime PM level) or "spm_lvl"
8693 * (System PM level).
8695 * If this function is called during shutdown, it will make sure that
8696 * both UFS device and UFS link is powered off.
8698 * NOTE: UFS device & link must be active before we enter in this function.
8700 * Returns 0 for success and non-zero for failure
8702 static int ufshcd_suspend(struct ufs_hba *hba, enum ufs_pm_op pm_op)
8705 enum ufs_pm_level pm_lvl;
8706 enum ufs_dev_pwr_mode req_dev_pwr_mode;
8707 enum uic_link_state req_link_state;
8709 hba->pm_op_in_progress = 1;
8710 if (!ufshcd_is_shutdown_pm(pm_op)) {
8711 pm_lvl = ufshcd_is_runtime_pm(pm_op) ?
8712 hba->rpm_lvl : hba->spm_lvl;
8713 req_dev_pwr_mode = ufs_get_pm_lvl_to_dev_pwr_mode(pm_lvl);
8714 req_link_state = ufs_get_pm_lvl_to_link_pwr_state(pm_lvl);
8716 req_dev_pwr_mode = UFS_POWERDOWN_PWR_MODE;
8717 req_link_state = UIC_LINK_OFF_STATE;
8721 * If we can't transition into any of the low power modes
8722 * just gate the clocks.
8724 WARN_ON(hba->hibern8_on_idle.is_enabled &&
8725 hba->hibern8_on_idle.active_reqs);
8726 ufshcd_hold_all(hba);
8727 hba->clk_gating.is_suspended = true;
8728 hba->hibern8_on_idle.is_suspended = true;
8730 if (hba->clk_scaling.is_allowed) {
8731 cancel_work_sync(&hba->clk_scaling.suspend_work);
8732 cancel_work_sync(&hba->clk_scaling.resume_work);
8733 ufshcd_suspend_clkscaling(hba);
8736 if (req_dev_pwr_mode == UFS_ACTIVE_PWR_MODE &&
8737 req_link_state == UIC_LINK_ACTIVE_STATE) {
8741 if ((req_dev_pwr_mode == hba->curr_dev_pwr_mode) &&
8742 (req_link_state == hba->uic_link_state))
8745 /* UFS device & link must be active before we enter in this function */
8746 if (!ufshcd_is_ufs_dev_active(hba) || !ufshcd_is_link_active(hba)) {
8751 if (ufshcd_is_runtime_pm(pm_op)) {
8752 if (ufshcd_can_autobkops_during_suspend(hba)) {
8754 * The device is idle with no requests in the queue,
8755 * allow background operations if bkops status shows
8756 * that performance might be impacted.
8758 ret = ufshcd_urgent_bkops(hba);
8762 /* make sure that auto bkops is disabled */
8763 ufshcd_disable_auto_bkops(hba);
8767 if ((req_dev_pwr_mode != hba->curr_dev_pwr_mode) &&
8768 ((ufshcd_is_runtime_pm(pm_op) && !hba->auto_bkops_enabled) ||
8769 !ufshcd_is_runtime_pm(pm_op))) {
8770 /* ensure that bkops is disabled */
8771 ufshcd_disable_auto_bkops(hba);
8772 ret = ufshcd_set_dev_pwr_mode(hba, req_dev_pwr_mode);
8777 ret = ufshcd_link_state_transition(hba, req_link_state, 1);
8779 goto set_dev_active;
8781 if (ufshcd_is_link_hibern8(hba) &&
8782 ufshcd_is_hibern8_on_idle_allowed(hba))
8783 hba->hibern8_on_idle.state = HIBERN8_ENTERED;
8785 ufshcd_vreg_set_lpm(hba);
8789 * Call vendor specific suspend callback. As these callbacks may access
8790 * vendor specific host controller register space call them before the
8791 * host clocks are ON.
8793 ret = ufshcd_vops_suspend(hba, pm_op);
8795 goto set_link_active;
8797 if (!ufshcd_is_link_active(hba))
8798 ret = ufshcd_disable_clocks(hba, false);
8800 /* If link is active, device ref_clk can't be switched off */
8801 ret = ufshcd_disable_clocks_skip_ref_clk(hba, false);
8803 goto set_link_active;
8805 if (ufshcd_is_clkgating_allowed(hba)) {
8806 hba->clk_gating.state = CLKS_OFF;
8807 trace_ufshcd_clk_gating(dev_name(hba->dev),
8808 hba->clk_gating.state);
8811 * Disable the host irq as host controller as there won't be any
8812 * host controller transaction expected till resume.
8814 ufshcd_disable_irq(hba);
8815 /* Put the host controller in low power mode if possible */
8816 ufshcd_hba_vreg_set_lpm(hba);
8820 if (hba->clk_scaling.is_allowed)
8821 ufshcd_resume_clkscaling(hba);
8822 ufshcd_vreg_set_hpm(hba);
8823 if (ufshcd_is_link_hibern8(hba) && !ufshcd_uic_hibern8_exit(hba)) {
8824 ufshcd_set_link_active(hba);
8825 } else if (ufshcd_is_link_off(hba)) {
8826 ufshcd_update_error_stats(hba, UFS_ERR_VOPS_SUSPEND);
8827 ufshcd_host_reset_and_restore(hba);
8830 if (!ufshcd_set_dev_pwr_mode(hba, UFS_ACTIVE_PWR_MODE))
8831 ufshcd_disable_auto_bkops(hba);
8833 if (hba->clk_scaling.is_allowed)
8834 ufshcd_resume_clkscaling(hba);
8835 hba->hibern8_on_idle.is_suspended = false;
8836 hba->clk_gating.is_suspended = false;
8837 ufshcd_release_all(hba);
8839 hba->pm_op_in_progress = 0;
8842 ufshcd_update_error_stats(hba, UFS_ERR_SUSPEND);
8848 * ufshcd_resume - helper function for resume operations
8849 * @hba: per adapter instance
8850 * @pm_op: runtime PM or system PM
8852 * This function basically brings the UFS device, UniPro link and controller
8855 * Returns 0 for success and non-zero for failure
8857 static int ufshcd_resume(struct ufs_hba *hba, enum ufs_pm_op pm_op)
8860 enum uic_link_state old_link_state;
8862 hba->pm_op_in_progress = 1;
8863 old_link_state = hba->uic_link_state;
8865 ufshcd_hba_vreg_set_hpm(hba);
8866 /* Make sure clocks are enabled before accessing controller */
8867 ret = ufshcd_enable_clocks(hba);
8871 /* enable the host irq as host controller would be active soon */
8872 ufshcd_enable_irq(hba);
8874 ret = ufshcd_vreg_set_hpm(hba);
8876 goto disable_irq_and_vops_clks;
8879 * Call vendor specific resume callback. As these callbacks may access
8880 * vendor specific host controller register space call them when the
8881 * host clocks are ON.
8883 ret = ufshcd_vops_resume(hba, pm_op);
8887 if (ufshcd_is_link_hibern8(hba)) {
8888 ret = ufshcd_uic_hibern8_exit(hba);
8890 ufshcd_set_link_active(hba);
8891 if (ufshcd_is_hibern8_on_idle_allowed(hba))
8892 hba->hibern8_on_idle.state = HIBERN8_EXITED;
8894 goto vendor_suspend;
8896 } else if (ufshcd_is_link_off(hba)) {
8898 * A full initialization of the host and the device is required
8899 * since the link was put to off during suspend.
8901 ret = ufshcd_reset_and_restore(hba);
8903 * ufshcd_reset_and_restore() should have already
8904 * set the link state as active
8906 if (ret || !ufshcd_is_link_active(hba))
8907 goto vendor_suspend;
8908 /* mark link state as hibern8 exited */
8909 if (ufshcd_is_hibern8_on_idle_allowed(hba))
8910 hba->hibern8_on_idle.state = HIBERN8_EXITED;
8913 if (!ufshcd_is_ufs_dev_active(hba)) {
8914 ret = ufshcd_set_dev_pwr_mode(hba, UFS_ACTIVE_PWR_MODE);
8916 goto set_old_link_state;
8919 if (ufshcd_keep_autobkops_enabled_except_suspend(hba))
8920 ufshcd_enable_auto_bkops(hba);
8923 * If BKOPs operations are urgently needed at this moment then
8924 * keep auto-bkops enabled or else disable it.
8926 ufshcd_urgent_bkops(hba);
8928 hba->clk_gating.is_suspended = false;
8929 hba->hibern8_on_idle.is_suspended = false;
8931 if (hba->clk_scaling.is_allowed)
8932 ufshcd_resume_clkscaling(hba);
8934 /* Schedule clock gating in case of no access to UFS device yet */
8935 ufshcd_release_all(hba);
8939 ufshcd_link_state_transition(hba, old_link_state, 0);
8940 if (ufshcd_is_link_hibern8(hba) &&
8941 ufshcd_is_hibern8_on_idle_allowed(hba))
8942 hba->hibern8_on_idle.state = HIBERN8_ENTERED;
8944 ufshcd_vops_suspend(hba, pm_op);
8946 ufshcd_vreg_set_lpm(hba);
8947 disable_irq_and_vops_clks:
8948 ufshcd_disable_irq(hba);
8949 if (hba->clk_scaling.is_allowed)
8950 ufshcd_suspend_clkscaling(hba);
8951 ufshcd_disable_clocks(hba, false);
8952 if (ufshcd_is_clkgating_allowed(hba))
8953 hba->clk_gating.state = CLKS_OFF;
8955 hba->pm_op_in_progress = 0;
8958 ufshcd_update_error_stats(hba, UFS_ERR_RESUME);
8964 * ufshcd_system_suspend - system suspend routine
8965 * @hba: per adapter instance
8966 * @pm_op: runtime PM or system PM
8968 * Check the description of ufshcd_suspend() function for more details.
8970 * Returns 0 for success and non-zero for failure
8972 int ufshcd_system_suspend(struct ufs_hba *hba)
8975 ktime_t start = ktime_get();
8977 if (!hba || !hba->is_powered)
8980 if ((ufs_get_pm_lvl_to_dev_pwr_mode(hba->spm_lvl) ==
8981 hba->curr_dev_pwr_mode) &&
8982 (ufs_get_pm_lvl_to_link_pwr_state(hba->spm_lvl) ==
8983 hba->uic_link_state))
8986 if (pm_runtime_suspended(hba->dev)) {
8988 * UFS device and/or UFS link low power states during runtime
8989 * suspend seems to be different than what is expected during
8990 * system suspend. Hence runtime resume the devic & link and
8991 * let the system suspend low power states to take effect.
8992 * TODO: If resume takes longer time, we might have optimize
8993 * it in future by not resuming everything if possible.
8995 ret = ufshcd_runtime_resume(hba);
9000 ret = ufshcd_suspend(hba, UFS_SYSTEM_PM);
9002 trace_ufshcd_system_suspend(dev_name(hba->dev), ret,
9003 ktime_to_us(ktime_sub(ktime_get(), start)),
9004 hba->curr_dev_pwr_mode, hba->uic_link_state);
9006 hba->is_sys_suspended = true;
9009 EXPORT_SYMBOL(ufshcd_system_suspend);
9012 * ufshcd_system_resume - system resume routine
9013 * @hba: per adapter instance
9015 * Returns 0 for success and non-zero for failure
9018 int ufshcd_system_resume(struct ufs_hba *hba)
9021 ktime_t start = ktime_get();
9026 if (!hba->is_powered || pm_runtime_suspended(hba->dev))
9028 * Let the runtime resume take care of resuming
9029 * if runtime suspended.
9033 ret = ufshcd_resume(hba, UFS_SYSTEM_PM);
9035 trace_ufshcd_system_resume(dev_name(hba->dev), ret,
9036 ktime_to_us(ktime_sub(ktime_get(), start)),
9037 hba->curr_dev_pwr_mode, hba->uic_link_state);
9040 EXPORT_SYMBOL(ufshcd_system_resume);
9043 * ufshcd_runtime_suspend - runtime suspend routine
9044 * @hba: per adapter instance
9046 * Check the description of ufshcd_suspend() function for more details.
9048 * Returns 0 for success and non-zero for failure
9050 int ufshcd_runtime_suspend(struct ufs_hba *hba)
9053 ktime_t start = ktime_get();
9058 if (!hba->is_powered)
9061 ret = ufshcd_suspend(hba, UFS_RUNTIME_PM);
9063 trace_ufshcd_runtime_suspend(dev_name(hba->dev), ret,
9064 ktime_to_us(ktime_sub(ktime_get(), start)),
9065 hba->curr_dev_pwr_mode,
9066 hba->uic_link_state);
9070 EXPORT_SYMBOL(ufshcd_runtime_suspend);
9073 * ufshcd_runtime_resume - runtime resume routine
9074 * @hba: per adapter instance
9076 * This function basically brings the UFS device, UniPro link and controller
9077 * to active state. Following operations are done in this function:
9079 * 1. Turn on all the controller related clocks
9080 * 2. Bring the UniPro link out of Hibernate state
9081 * 3. If UFS device is in sleep state, turn ON VCC rail and bring the UFS device
9083 * 4. If auto-bkops is enabled on the device, disable it.
9085 * So following would be the possible power state after this function return
9087 * S1: UFS device in Active state with VCC rail ON
9088 * UniPro link in Active state
9089 * All the UFS/UniPro controller clocks are ON
9091 * Returns 0 for success and non-zero for failure
9093 int ufshcd_runtime_resume(struct ufs_hba *hba)
9096 ktime_t start = ktime_get();
9101 if (!hba->is_powered)
9104 ret = ufshcd_resume(hba, UFS_RUNTIME_PM);
9106 trace_ufshcd_runtime_resume(dev_name(hba->dev), ret,
9107 ktime_to_us(ktime_sub(ktime_get(), start)),
9108 hba->curr_dev_pwr_mode,
9109 hba->uic_link_state);
9112 EXPORT_SYMBOL(ufshcd_runtime_resume);
9114 int ufshcd_runtime_idle(struct ufs_hba *hba)
9118 EXPORT_SYMBOL(ufshcd_runtime_idle);
9120 static inline ssize_t ufshcd_pm_lvl_store(struct device *dev,
9121 struct device_attribute *attr,
9122 const char *buf, size_t count,
9125 struct ufs_hba *hba = dev_get_drvdata(dev);
9126 unsigned long flags, value;
9128 if (kstrtoul(buf, 0, &value))
9131 if (value >= UFS_PM_LVL_MAX)
9134 spin_lock_irqsave(hba->host->host_lock, flags);
9136 hba->rpm_lvl = value;
9138 hba->spm_lvl = value;
9139 ufshcd_apply_pm_quirks(hba);
9140 spin_unlock_irqrestore(hba->host->host_lock, flags);
9144 static ssize_t ufshcd_rpm_lvl_show(struct device *dev,
9145 struct device_attribute *attr, char *buf)
9147 struct ufs_hba *hba = dev_get_drvdata(dev);
9151 curr_len = snprintf(buf, PAGE_SIZE,
9152 "\nCurrent Runtime PM level [%d] => dev_state [%s] link_state [%s]\n",
9154 ufschd_ufs_dev_pwr_mode_to_string(
9155 ufs_pm_lvl_states[hba->rpm_lvl].dev_state),
9156 ufschd_uic_link_state_to_string(
9157 ufs_pm_lvl_states[hba->rpm_lvl].link_state));
9159 curr_len += snprintf((buf + curr_len), (PAGE_SIZE - curr_len),
9160 "\nAll available Runtime PM levels info:\n");
9161 for (lvl = UFS_PM_LVL_0; lvl < UFS_PM_LVL_MAX; lvl++)
9162 curr_len += snprintf((buf + curr_len), (PAGE_SIZE - curr_len),
9163 "\tRuntime PM level [%d] => dev_state [%s] link_state [%s]\n",
9165 ufschd_ufs_dev_pwr_mode_to_string(
9166 ufs_pm_lvl_states[lvl].dev_state),
9167 ufschd_uic_link_state_to_string(
9168 ufs_pm_lvl_states[lvl].link_state));
9173 static ssize_t ufshcd_rpm_lvl_store(struct device *dev,
9174 struct device_attribute *attr, const char *buf, size_t count)
9176 return ufshcd_pm_lvl_store(dev, attr, buf, count, true);
9179 static void ufshcd_add_rpm_lvl_sysfs_nodes(struct ufs_hba *hba)
9181 hba->rpm_lvl_attr.show = ufshcd_rpm_lvl_show;
9182 hba->rpm_lvl_attr.store = ufshcd_rpm_lvl_store;
9183 sysfs_attr_init(&hba->rpm_lvl_attr.attr);
9184 hba->rpm_lvl_attr.attr.name = "rpm_lvl";
9185 hba->rpm_lvl_attr.attr.mode = S_IRUGO | S_IWUSR;
9186 if (device_create_file(hba->dev, &hba->rpm_lvl_attr))
9187 dev_err(hba->dev, "Failed to create sysfs for rpm_lvl\n");
9190 static ssize_t ufshcd_spm_lvl_show(struct device *dev,
9191 struct device_attribute *attr, char *buf)
9193 struct ufs_hba *hba = dev_get_drvdata(dev);
9197 curr_len = snprintf(buf, PAGE_SIZE,
9198 "\nCurrent System PM level [%d] => dev_state [%s] link_state [%s]\n",
9200 ufschd_ufs_dev_pwr_mode_to_string(
9201 ufs_pm_lvl_states[hba->spm_lvl].dev_state),
9202 ufschd_uic_link_state_to_string(
9203 ufs_pm_lvl_states[hba->spm_lvl].link_state));
9205 curr_len += snprintf((buf + curr_len), (PAGE_SIZE - curr_len),
9206 "\nAll available System PM levels info:\n");
9207 for (lvl = UFS_PM_LVL_0; lvl < UFS_PM_LVL_MAX; lvl++)
9208 curr_len += snprintf((buf + curr_len), (PAGE_SIZE - curr_len),
9209 "\tSystem PM level [%d] => dev_state [%s] link_state [%s]\n",
9211 ufschd_ufs_dev_pwr_mode_to_string(
9212 ufs_pm_lvl_states[lvl].dev_state),
9213 ufschd_uic_link_state_to_string(
9214 ufs_pm_lvl_states[lvl].link_state));
9219 static ssize_t ufshcd_spm_lvl_store(struct device *dev,
9220 struct device_attribute *attr, const char *buf, size_t count)
9222 return ufshcd_pm_lvl_store(dev, attr, buf, count, false);
9225 static void ufshcd_add_spm_lvl_sysfs_nodes(struct ufs_hba *hba)
9227 hba->spm_lvl_attr.show = ufshcd_spm_lvl_show;
9228 hba->spm_lvl_attr.store = ufshcd_spm_lvl_store;
9229 sysfs_attr_init(&hba->spm_lvl_attr.attr);
9230 hba->spm_lvl_attr.attr.name = "spm_lvl";
9231 hba->spm_lvl_attr.attr.mode = S_IRUGO | S_IWUSR;
9232 if (device_create_file(hba->dev, &hba->spm_lvl_attr))
9233 dev_err(hba->dev, "Failed to create sysfs for spm_lvl\n");
9236 static inline void ufshcd_add_sysfs_nodes(struct ufs_hba *hba)
9238 ufshcd_add_rpm_lvl_sysfs_nodes(hba);
9239 ufshcd_add_spm_lvl_sysfs_nodes(hba);
9242 static void ufshcd_shutdown_clkscaling(struct ufs_hba *hba)
9244 bool suspend = false;
9245 unsigned long flags;
9247 spin_lock_irqsave(hba->host->host_lock, flags);
9248 if (hba->clk_scaling.is_allowed) {
9249 hba->clk_scaling.is_allowed = false;
9252 spin_unlock_irqrestore(hba->host->host_lock, flags);
9255 * Scaling may be scheduled before, hence make sure it
9256 * doesn't race with shutdown
9258 if (ufshcd_is_clkscaling_supported(hba)) {
9259 device_remove_file(hba->dev, &hba->clk_scaling.enable_attr);
9260 cancel_work_sync(&hba->clk_scaling.suspend_work);
9261 cancel_work_sync(&hba->clk_scaling.resume_work);
9263 ufshcd_suspend_clkscaling(hba);
9266 /* Unregister so that devfreq_monitor can't race with shutdown */
9268 devfreq_remove_device(hba->devfreq);
9272 * ufshcd_shutdown - shutdown routine
9273 * @hba: per adapter instance
9275 * This function would power off both UFS device and UFS link.
9277 * Returns 0 always to allow force shutdown even in case of errors.
9279 int ufshcd_shutdown(struct ufs_hba *hba)
9283 if (ufshcd_is_ufs_dev_poweroff(hba) && ufshcd_is_link_off(hba))
9286 pm_runtime_get_sync(hba->dev);
9287 ufshcd_hold_all(hba);
9288 ufshcd_mark_shutdown_ongoing(hba);
9289 ufshcd_shutdown_clkscaling(hba);
9291 * (1) Acquire the lock to stop any more requests
9292 * (2) Wait for all issued requests to complete
9294 ufshcd_get_write_lock(hba);
9295 ufshcd_scsi_block_requests(hba);
9296 ret = ufshcd_wait_for_doorbell_clr(hba, U64_MAX);
9298 dev_err(hba->dev, "%s: waiting for DB clear: failed: %d\n",
9300 /* Requests may have errored out above, let it be handled */
9301 flush_work(&hba->eh_work);
9302 /* reqs issued from contexts other than shutdown will fail from now */
9303 ufshcd_scsi_unblock_requests(hba);
9304 ufshcd_release_all(hba);
9305 ret = ufshcd_suspend(hba, UFS_SHUTDOWN_PM);
9308 dev_err(hba->dev, "%s failed, err %d\n", __func__, ret);
9309 /* allow force shutdown even in case of errors */
9312 EXPORT_SYMBOL(ufshcd_shutdown);
9315 * Values permitted 0, 1, 2.
9316 * 0 -> Disable IO latency histograms (default)
9317 * 1 -> Enable IO latency histograms
9318 * 2 -> Zero out IO latency histograms
9321 latency_hist_store(struct device *dev, struct device_attribute *attr,
9322 const char *buf, size_t count)
9324 struct ufs_hba *hba = dev_get_drvdata(dev);
9327 if (kstrtol(buf, 0, &value))
9329 if (value == BLK_IO_LAT_HIST_ZERO) {
9330 memset(&hba->io_lat_read, 0, sizeof(hba->io_lat_read));
9331 memset(&hba->io_lat_write, 0, sizeof(hba->io_lat_write));
9332 } else if (value == BLK_IO_LAT_HIST_ENABLE ||
9333 value == BLK_IO_LAT_HIST_DISABLE)
9334 hba->latency_hist_enabled = value;
9339 latency_hist_show(struct device *dev, struct device_attribute *attr,
9342 struct ufs_hba *hba = dev_get_drvdata(dev);
9343 size_t written_bytes;
9345 written_bytes = blk_latency_hist_show("Read", &hba->io_lat_read,
9347 written_bytes += blk_latency_hist_show("Write", &hba->io_lat_write,
9348 buf + written_bytes, PAGE_SIZE - written_bytes);
9350 return written_bytes;
9353 static DEVICE_ATTR(latency_hist, S_IRUGO | S_IWUSR,
9354 latency_hist_show, latency_hist_store);
9357 ufshcd_init_latency_hist(struct ufs_hba *hba)
9359 if (device_create_file(hba->dev, &dev_attr_latency_hist))
9360 dev_err(hba->dev, "Failed to create latency_hist sysfs entry\n");
9364 ufshcd_exit_latency_hist(struct ufs_hba *hba)
9366 device_create_file(hba->dev, &dev_attr_latency_hist);
9370 * ufshcd_remove - de-allocate SCSI host and host memory space
9371 * data structure memory
9372 * @hba - per adapter instance
9374 void ufshcd_remove(struct ufs_hba *hba)
9376 scsi_remove_host(hba->host);
9377 /* disable interrupts */
9378 ufshcd_disable_intr(hba, hba->intr_mask);
9379 ufshcd_hba_stop(hba, true);
9381 ufshcd_exit_clk_gating(hba);
9382 ufshcd_exit_hibern8_on_idle(hba);
9383 if (ufshcd_is_clkscaling_supported(hba)) {
9384 device_remove_file(hba->dev, &hba->clk_scaling.enable_attr);
9385 ufshcd_exit_latency_hist(hba);
9386 devfreq_remove_device(hba->devfreq);
9388 ufshcd_hba_exit(hba);
9389 ufsdbg_remove_debugfs(hba);
9391 EXPORT_SYMBOL_GPL(ufshcd_remove);
9394 * ufshcd_dealloc_host - deallocate Host Bus Adapter (HBA)
9395 * @hba: pointer to Host Bus Adapter (HBA)
9397 void ufshcd_dealloc_host(struct ufs_hba *hba)
9399 scsi_host_put(hba->host);
9401 EXPORT_SYMBOL_GPL(ufshcd_dealloc_host);
9404 * ufshcd_set_dma_mask - Set dma mask based on the controller
9405 * addressing capability
9406 * @hba: per adapter instance
9408 * Returns 0 for success, non-zero for failure
9410 static int ufshcd_set_dma_mask(struct ufs_hba *hba)
9412 if (hba->capabilities & MASK_64_ADDRESSING_SUPPORT) {
9413 if (!dma_set_mask_and_coherent(hba->dev, DMA_BIT_MASK(64)))
9416 return dma_set_mask_and_coherent(hba->dev, DMA_BIT_MASK(32));
9420 * ufshcd_alloc_host - allocate Host Bus Adapter (HBA)
9421 * @dev: pointer to device handle
9422 * @hba_handle: driver private handle
9423 * Returns 0 on success, non-zero value on failure
9425 int ufshcd_alloc_host(struct device *dev, struct ufs_hba **hba_handle)
9427 struct Scsi_Host *host;
9428 struct ufs_hba *hba;
9433 "Invalid memory reference for dev is NULL\n");
9438 host = scsi_host_alloc(&ufshcd_driver_template,
9439 sizeof(struct ufs_hba));
9441 dev_err(dev, "scsi_host_alloc failed\n");
9445 hba = shost_priv(host);
9453 EXPORT_SYMBOL(ufshcd_alloc_host);
9456 * ufshcd_is_devfreq_scaling_required - check if scaling is required or not
9457 * @hba: per adapter instance
9458 * @scale_up: True if scaling up and false if scaling down
9460 * Returns true if scaling is required, false otherwise.
9462 static bool ufshcd_is_devfreq_scaling_required(struct ufs_hba *hba,
9465 struct ufs_clk_info *clki;
9466 struct list_head *head = &hba->clk_list_head;
9468 if (!head || list_empty(head))
9471 list_for_each_entry(clki, head, list) {
9472 if (!IS_ERR_OR_NULL(clki->clk)) {
9473 if (scale_up && clki->max_freq) {
9474 if (clki->curr_freq == clki->max_freq)
9477 } else if (!scale_up && clki->min_freq) {
9478 if (clki->curr_freq == clki->min_freq)
9489 * ufshcd_scale_gear - scale up/down UFS gear
9490 * @hba: per adapter instance
9491 * @scale_up: True for scaling up gear and false for scaling down
9493 * Returns 0 for success,
9494 * Returns -EBUSY if scaling can't happen at this time
9495 * Returns non-zero for any other errors
9497 static int ufshcd_scale_gear(struct ufs_hba *hba, bool scale_up)
9500 struct ufs_pa_layer_attr new_pwr_info;
9501 u32 scale_down_gear = ufshcd_vops_get_scale_down_gear(hba);
9503 BUG_ON(!hba->clk_scaling.saved_pwr_info.is_valid);
9506 memcpy(&new_pwr_info, &hba->clk_scaling.saved_pwr_info.info,
9507 sizeof(struct ufs_pa_layer_attr));
9509 * Some UFS devices may stop responding after switching from
9510 * HS-G1 to HS-G3. Also, it is found that these devices work
9511 * fine if we do 2 steps switch: HS-G1 to HS-G2 followed by
9512 * HS-G2 to HS-G3. If UFS_DEVICE_QUIRK_HS_G1_TO_HS_G3_SWITCH
9513 * quirk is enabled for such devices, this 2 steps gear switch
9514 * workaround will be applied.
9516 if ((hba->dev_quirks & UFS_DEVICE_QUIRK_HS_G1_TO_HS_G3_SWITCH)
9517 && (hba->pwr_info.gear_tx == UFS_HS_G1)
9518 && (new_pwr_info.gear_tx == UFS_HS_G3)) {
9519 /* scale up to G2 first */
9520 new_pwr_info.gear_tx = UFS_HS_G2;
9521 new_pwr_info.gear_rx = UFS_HS_G2;
9522 ret = ufshcd_change_power_mode(hba, &new_pwr_info);
9526 /* scale up to G3 now */
9527 new_pwr_info.gear_tx = UFS_HS_G3;
9528 new_pwr_info.gear_rx = UFS_HS_G3;
9529 /* now, fall through to set the HS-G3 */
9531 ret = ufshcd_change_power_mode(hba, &new_pwr_info);
9535 memcpy(&new_pwr_info, &hba->pwr_info,
9536 sizeof(struct ufs_pa_layer_attr));
9538 if (hba->pwr_info.gear_tx > scale_down_gear
9539 || hba->pwr_info.gear_rx > scale_down_gear) {
9540 /* save the current power mode */
9541 memcpy(&hba->clk_scaling.saved_pwr_info.info,
9543 sizeof(struct ufs_pa_layer_attr));
9545 /* scale down gear */
9546 new_pwr_info.gear_tx = scale_down_gear;
9547 new_pwr_info.gear_rx = scale_down_gear;
9548 if (!(hba->dev_quirks & UFS_DEVICE_NO_FASTAUTO)) {
9549 new_pwr_info.pwr_tx = FASTAUTO_MODE;
9550 new_pwr_info.pwr_rx = FASTAUTO_MODE;
9553 ret = ufshcd_change_power_mode(hba, &new_pwr_info);
9558 dev_err(hba->dev, "%s: failed err %d, old gear: (tx %d rx %d), new gear: (tx %d rx %d), scale_up = %d",
9560 hba->pwr_info.gear_tx, hba->pwr_info.gear_rx,
9561 new_pwr_info.gear_tx, new_pwr_info.gear_rx,
9567 static int ufshcd_clock_scaling_prepare(struct ufs_hba *hba)
9569 #define DOORBELL_CLR_TOUT_US (1000 * 1000) /* 1 sec */
9572 * make sure that there are no outstanding requests when
9573 * clock scaling is in progress
9575 ufshcd_scsi_block_requests(hba);
9576 down_write(&hba->lock);
9577 if (ufshcd_wait_for_doorbell_clr(hba, DOORBELL_CLR_TOUT_US)) {
9579 up_write(&hba->lock);
9580 ufshcd_scsi_unblock_requests(hba);
9586 static void ufshcd_clock_scaling_unprepare(struct ufs_hba *hba)
9588 up_write(&hba->lock);
9589 ufshcd_scsi_unblock_requests(hba);
9593 * ufshcd_devfreq_scale - scale up/down UFS clocks and gear
9594 * @hba: per adapter instance
9595 * @scale_up: True for scaling up and false for scalin down
9597 * Returns 0 for success,
9598 * Returns -EBUSY if scaling can't happen at this time
9599 * Returns non-zero for any other errors
9601 static int ufshcd_devfreq_scale(struct ufs_hba *hba, bool scale_up)
9605 /* let's not get into low power until clock scaling is completed */
9606 hba->ufs_stats.clk_hold.ctx = CLK_SCALE_WORK;
9607 ufshcd_hold_all(hba);
9609 ret = ufshcd_clock_scaling_prepare(hba);
9613 /* scale down the gear before scaling down clocks */
9615 ret = ufshcd_scale_gear(hba, false);
9617 goto clk_scaling_unprepare;
9621 * If auto hibern8 is supported then put the link in
9622 * hibern8 manually, this is to avoid auto hibern8
9623 * racing during clock frequency scaling sequence.
9625 if (ufshcd_is_auto_hibern8_supported(hba)) {
9626 ret = ufshcd_uic_hibern8_enter(hba);
9628 /* link will be bad state so no need to scale_up_gear */
9632 ret = ufshcd_scale_clks(hba, scale_up);
9636 if (ufshcd_is_auto_hibern8_supported(hba)) {
9637 ret = ufshcd_uic_hibern8_exit(hba);
9639 /* link will be bad state so no need to scale_up_gear */
9643 /* scale up the gear after scaling up clocks */
9645 ret = ufshcd_scale_gear(hba, true);
9647 ufshcd_scale_clks(hba, false);
9648 goto clk_scaling_unprepare;
9653 hba->clk_scaling.is_scaled_up = scale_up;
9655 hba->clk_gating.delay_ms =
9656 hba->clk_gating.delay_ms_perf;
9658 hba->clk_gating.delay_ms =
9659 hba->clk_gating.delay_ms_pwr_save;
9662 goto clk_scaling_unprepare;
9666 ufshcd_scale_gear(hba, true);
9667 clk_scaling_unprepare:
9668 ufshcd_clock_scaling_unprepare(hba);
9670 hba->ufs_stats.clk_rel.ctx = CLK_SCALE_WORK;
9671 ufshcd_release_all(hba);
9675 static void __ufshcd_suspend_clkscaling(struct ufs_hba *hba)
9677 unsigned long flags;
9679 devfreq_suspend_device(hba->devfreq);
9680 spin_lock_irqsave(hba->host->host_lock, flags);
9681 hba->clk_scaling.window_start_t = 0;
9682 spin_unlock_irqrestore(hba->host->host_lock, flags);
9685 static void ufshcd_suspend_clkscaling(struct ufs_hba *hba)
9687 unsigned long flags;
9688 bool suspend = false;
9690 if (!ufshcd_is_clkscaling_supported(hba))
9693 spin_lock_irqsave(hba->host->host_lock, flags);
9694 if (!hba->clk_scaling.is_suspended) {
9696 hba->clk_scaling.is_suspended = true;
9698 spin_unlock_irqrestore(hba->host->host_lock, flags);
9701 __ufshcd_suspend_clkscaling(hba);
9704 static void ufshcd_resume_clkscaling(struct ufs_hba *hba)
9706 unsigned long flags;
9707 bool resume = false;
9709 if (!ufshcd_is_clkscaling_supported(hba))
9712 spin_lock_irqsave(hba->host->host_lock, flags);
9713 if (hba->clk_scaling.is_suspended) {
9715 hba->clk_scaling.is_suspended = false;
9717 spin_unlock_irqrestore(hba->host->host_lock, flags);
9720 devfreq_resume_device(hba->devfreq);
9723 static ssize_t ufshcd_clkscale_enable_show(struct device *dev,
9724 struct device_attribute *attr, char *buf)
9726 struct ufs_hba *hba = dev_get_drvdata(dev);
9728 return snprintf(buf, PAGE_SIZE, "%d\n", hba->clk_scaling.is_allowed);
9731 static ssize_t ufshcd_clkscale_enable_store(struct device *dev,
9732 struct device_attribute *attr, const char *buf, size_t count)
9734 struct ufs_hba *hba = dev_get_drvdata(dev);
9738 if (kstrtou32(buf, 0, &value))
9742 if (value == hba->clk_scaling.is_allowed)
9745 pm_runtime_get_sync(hba->dev);
9746 ufshcd_hold(hba, false);
9748 cancel_work_sync(&hba->clk_scaling.suspend_work);
9749 cancel_work_sync(&hba->clk_scaling.resume_work);
9751 hba->clk_scaling.is_allowed = value;
9754 ufshcd_resume_clkscaling(hba);
9756 ufshcd_suspend_clkscaling(hba);
9757 err = ufshcd_devfreq_scale(hba, true);
9759 dev_err(hba->dev, "%s: failed to scale clocks up %d\n",
9763 ufshcd_release(hba, false);
9764 pm_runtime_put_sync(hba->dev);
9769 static void ufshcd_clk_scaling_suspend_work(struct work_struct *work)
9771 struct ufs_hba *hba = container_of(work, struct ufs_hba,
9772 clk_scaling.suspend_work);
9773 unsigned long irq_flags;
9775 spin_lock_irqsave(hba->host->host_lock, irq_flags);
9776 if (hba->clk_scaling.active_reqs || hba->clk_scaling.is_suspended) {
9777 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
9780 hba->clk_scaling.is_suspended = true;
9781 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
9783 __ufshcd_suspend_clkscaling(hba);
9786 static void ufshcd_clk_scaling_resume_work(struct work_struct *work)
9788 struct ufs_hba *hba = container_of(work, struct ufs_hba,
9789 clk_scaling.resume_work);
9790 unsigned long irq_flags;
9792 spin_lock_irqsave(hba->host->host_lock, irq_flags);
9793 if (!hba->clk_scaling.is_suspended) {
9794 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
9797 hba->clk_scaling.is_suspended = false;
9798 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
9800 devfreq_resume_device(hba->devfreq);
9803 static int ufshcd_devfreq_target(struct device *dev,
9804 unsigned long *freq, u32 flags)
9807 struct ufs_hba *hba = dev_get_drvdata(dev);
9808 unsigned long irq_flags;
9810 bool scale_up, sched_clk_scaling_suspend_work = false;
9812 if (!ufshcd_is_clkscaling_supported(hba))
9815 if ((*freq > 0) && (*freq < UINT_MAX)) {
9816 dev_err(hba->dev, "%s: invalid freq = %lu\n", __func__, *freq);
9820 spin_lock_irqsave(hba->host->host_lock, irq_flags);
9821 if (ufshcd_eh_in_progress(hba)) {
9822 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
9826 if (!hba->clk_scaling.active_reqs)
9827 sched_clk_scaling_suspend_work = true;
9829 scale_up = (*freq == UINT_MAX) ? true : false;
9830 if (!ufshcd_is_devfreq_scaling_required(hba, scale_up)) {
9831 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
9833 goto out; /* no state change required */
9835 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
9837 start = ktime_get();
9838 ret = ufshcd_devfreq_scale(hba, scale_up);
9839 trace_ufshcd_profile_clk_scaling(dev_name(hba->dev),
9840 (scale_up ? "up" : "down"),
9841 ktime_to_us(ktime_sub(ktime_get(), start)), ret);
9844 if (sched_clk_scaling_suspend_work)
9845 queue_work(hba->clk_scaling.workq,
9846 &hba->clk_scaling.suspend_work);
9851 static int ufshcd_devfreq_get_dev_status(struct device *dev,
9852 struct devfreq_dev_status *stat)
9854 struct ufs_hba *hba = dev_get_drvdata(dev);
9855 struct ufs_clk_scaling *scaling = &hba->clk_scaling;
9856 unsigned long flags;
9858 if (!ufshcd_is_clkscaling_supported(hba))
9861 memset(stat, 0, sizeof(*stat));
9863 spin_lock_irqsave(hba->host->host_lock, flags);
9864 if (!scaling->window_start_t)
9867 if (scaling->is_busy_started)
9868 scaling->tot_busy_t += ktime_to_us(ktime_sub(ktime_get(),
9869 scaling->busy_start_t));
9871 stat->total_time = jiffies_to_usecs((long)jiffies -
9872 (long)scaling->window_start_t);
9873 stat->busy_time = scaling->tot_busy_t;
9875 scaling->window_start_t = jiffies;
9876 scaling->tot_busy_t = 0;
9878 if (hba->outstanding_reqs) {
9879 scaling->busy_start_t = ktime_get();
9880 scaling->is_busy_started = true;
9882 scaling->busy_start_t = ktime_set(0, 0);
9883 scaling->is_busy_started = false;
9885 spin_unlock_irqrestore(hba->host->host_lock, flags);
9889 static void ufshcd_clkscaling_init_sysfs(struct ufs_hba *hba)
9891 hba->clk_scaling.enable_attr.show = ufshcd_clkscale_enable_show;
9892 hba->clk_scaling.enable_attr.store = ufshcd_clkscale_enable_store;
9893 sysfs_attr_init(&hba->clk_scaling.enable_attr.attr);
9894 hba->clk_scaling.enable_attr.attr.name = "clkscale_enable";
9895 hba->clk_scaling.enable_attr.attr.mode = S_IRUGO | S_IWUSR;
9896 if (device_create_file(hba->dev, &hba->clk_scaling.enable_attr))
9897 dev_err(hba->dev, "Failed to create sysfs for clkscale_enable\n");
9900 static void ufshcd_init_lanes_per_dir(struct ufs_hba *hba)
9902 struct device *dev = hba->dev;
9905 ret = of_property_read_u32(dev->of_node, "lanes-per-direction",
9906 &hba->lanes_per_direction);
9909 "%s: failed to read lanes-per-direction, ret=%d\n",
9911 hba->lanes_per_direction = UFSHCD_DEFAULT_LANES_PER_DIRECTION;
9915 * ufshcd_init - Driver initialization routine
9916 * @hba: per-adapter instance
9917 * @mmio_base: base register address
9918 * @irq: Interrupt line of device
9919 * Returns 0 on success, non-zero value on failure
9921 int ufshcd_init(struct ufs_hba *hba, void __iomem *mmio_base, unsigned int irq)
9924 struct Scsi_Host *host = hba->host;
9925 struct device *dev = hba->dev;
9929 "Invalid memory reference for mmio_base is NULL\n");
9934 hba->mmio_base = mmio_base;
9937 ufshcd_init_lanes_per_dir(hba);
9939 err = ufshcd_hba_init(hba);
9943 /* Read capabilities registers */
9944 ufshcd_hba_capabilities(hba);
9946 /* Get UFS version supported by the controller */
9947 hba->ufs_version = ufshcd_get_ufs_version(hba);
9949 /* print error message if ufs_version is not valid */
9950 if ((hba->ufs_version != UFSHCI_VERSION_10) &&
9951 (hba->ufs_version != UFSHCI_VERSION_11) &&
9952 (hba->ufs_version != UFSHCI_VERSION_20) &&
9953 (hba->ufs_version != UFSHCI_VERSION_21))
9954 dev_err(hba->dev, "invalid UFS version 0x%x\n",
9957 /* Get Interrupt bit mask per version */
9958 hba->intr_mask = ufshcd_get_intr_mask(hba);
9960 /* Enable debug prints */
9961 hba->ufshcd_dbg_print = DEFAULT_UFSHCD_DBG_PRINT_EN;
9963 err = ufshcd_set_dma_mask(hba);
9965 dev_err(hba->dev, "set dma mask failed\n");
9969 /* Allocate memory for host memory space */
9970 err = ufshcd_memory_alloc(hba);
9972 dev_err(hba->dev, "Memory allocation failed\n");
9977 ufshcd_host_memory_configure(hba);
9979 host->can_queue = hba->nutrs;
9980 host->cmd_per_lun = hba->nutrs;
9981 host->max_id = UFSHCD_MAX_ID;
9982 host->max_lun = UFS_MAX_LUNS;
9983 host->max_channel = UFSHCD_MAX_CHANNEL;
9984 host->unique_id = host->host_no;
9985 host->max_cmd_len = MAX_CDB_SIZE;
9986 host->set_dbd_for_caching = 1;
9988 hba->max_pwr_info.is_valid = false;
9990 /* Initailize wait queue for task management */
9991 init_waitqueue_head(&hba->tm_wq);
9992 init_waitqueue_head(&hba->tm_tag_wq);
9994 /* Initialize work queues */
9995 INIT_WORK(&hba->eh_work, ufshcd_err_handler);
9996 INIT_WORK(&hba->eeh_work, ufshcd_exception_event_handler);
9997 INIT_WORK(&hba->rls_work, ufshcd_rls_handler);
9999 /* Initialize UIC command mutex */
10000 mutex_init(&hba->uic_cmd_mutex);
10002 /* Initialize mutex for device management commands */
10003 mutex_init(&hba->dev_cmd.lock);
10005 init_rwsem(&hba->lock);
10007 /* Initialize device management tag acquire wait queue */
10008 init_waitqueue_head(&hba->dev_cmd.tag_wq);
10010 ufshcd_init_clk_gating(hba);
10011 ufshcd_init_hibern8_on_idle(hba);
10014 * In order to avoid any spurious interrupt immediately after
10015 * registering UFS controller interrupt handler, clear any pending UFS
10016 * interrupt status and disable all the UFS interrupts.
10018 ufshcd_writel(hba, ufshcd_readl(hba, REG_INTERRUPT_STATUS),
10019 REG_INTERRUPT_STATUS);
10020 ufshcd_writel(hba, 0, REG_INTERRUPT_ENABLE);
10022 * Make sure that UFS interrupts are disabled and any pending interrupt
10023 * status is cleared before registering UFS interrupt handler.
10027 /* IRQ registration */
10028 err = devm_request_irq(dev, irq, ufshcd_intr, IRQF_SHARED, UFSHCD, hba);
10030 dev_err(hba->dev, "request irq failed\n");
10033 hba->is_irq_enabled = true;
10036 err = scsi_add_host(host, hba->dev);
10038 dev_err(hba->dev, "scsi_add_host failed\n");
10042 /* Reset controller to power on reset (POR) state */
10043 ufshcd_vops_full_reset(hba);
10045 /* reset connected UFS device */
10046 err = ufshcd_reset_device(hba);
10048 dev_warn(hba->dev, "%s: device reset failed. err %d\n",
10051 /* Host controller enable */
10052 err = ufshcd_hba_enable(hba);
10054 dev_err(hba->dev, "Host controller enable failed\n");
10055 ufshcd_print_host_regs(hba);
10056 ufshcd_print_host_state(hba);
10057 goto out_remove_scsi_host;
10060 if (ufshcd_is_clkscaling_supported(hba)) {
10061 char wq_name[sizeof("ufs_clkscaling_00")];
10063 INIT_WORK(&hba->clk_scaling.suspend_work,
10064 ufshcd_clk_scaling_suspend_work);
10065 INIT_WORK(&hba->clk_scaling.resume_work,
10066 ufshcd_clk_scaling_resume_work);
10068 snprintf(wq_name, ARRAY_SIZE(wq_name), "ufs_clkscaling_%d",
10070 hba->clk_scaling.workq = create_singlethread_workqueue(wq_name);
10072 ufshcd_clkscaling_init_sysfs(hba);
10076 * If rpm_lvl and and spm_lvl are not already set to valid levels,
10077 * set the default power management level for UFS runtime and system
10078 * suspend. Default power saving mode selected is keeping UFS link in
10079 * Hibern8 state and UFS device in sleep.
10081 if (!ufshcd_is_valid_pm_lvl(hba->rpm_lvl))
10082 hba->rpm_lvl = ufs_get_desired_pm_lvl_for_dev_link_state(
10083 UFS_SLEEP_PWR_MODE,
10084 UIC_LINK_HIBERN8_STATE);
10085 if (!ufshcd_is_valid_pm_lvl(hba->spm_lvl))
10086 hba->spm_lvl = ufs_get_desired_pm_lvl_for_dev_link_state(
10087 UFS_SLEEP_PWR_MODE,
10088 UIC_LINK_HIBERN8_STATE);
10090 /* Hold auto suspend until async scan completes */
10091 pm_runtime_get_sync(dev);
10093 ufshcd_init_latency_hist(hba);
10096 * We are assuming that device wasn't put in sleep/power-down
10097 * state exclusively during the boot stage before kernel.
10098 * This assumption helps avoid doing link startup twice during
10099 * ufshcd_probe_hba().
10101 ufshcd_set_ufs_dev_active(hba);
10103 ufshcd_cmd_log_init(hba);
10105 async_schedule(ufshcd_async_scan, hba);
10107 ufsdbg_add_debugfs(hba);
10109 ufshcd_add_sysfs_nodes(hba);
10113 out_remove_scsi_host:
10114 scsi_remove_host(hba->host);
10116 ufshcd_exit_clk_gating(hba);
10117 ufshcd_exit_latency_hist(hba);
10119 hba->is_irq_enabled = false;
10120 ufshcd_hba_exit(hba);
10124 EXPORT_SYMBOL_GPL(ufshcd_init);
10126 MODULE_AUTHOR("Santosh Yaragnavi <santosh.sy@samsung.com>");
10127 MODULE_AUTHOR("Vinayak Holikatti <h.vinayak@samsung.com>");
10128 MODULE_DESCRIPTION("Generic UFS host controller driver Core");
10129 MODULE_LICENSE("GPL");
10130 MODULE_VERSION(UFSHCD_DRIVER_VERSION);