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-2016, 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 <linux/devfreq.h>
42 #include <linux/nls.h>
44 #include <linux/bitfield.h>
46 #include "ufs_quirks.h"
48 #include "ufs-sysfs.h"
51 #define CREATE_TRACE_POINTS
52 #include <trace/events/ufs.h>
54 #define UFSHCD_ENABLE_INTRS (UTP_TRANSFER_REQ_COMPL |\
57 /* UIC command timeout, unit: ms */
58 #define UIC_CMD_TIMEOUT 500
60 /* NOP OUT retries waiting for NOP IN response */
61 #define NOP_OUT_RETRIES 10
62 /* Timeout after 30 msecs if NOP OUT hangs without response */
63 #define NOP_OUT_TIMEOUT 30 /* msecs */
65 /* Query request retries */
66 #define QUERY_REQ_RETRIES 3
67 /* Query request timeout */
68 #define QUERY_REQ_TIMEOUT 1500 /* 1.5 seconds */
70 /* Task management command timeout */
71 #define TM_CMD_TIMEOUT 100 /* msecs */
73 /* maximum number of retries for a general UIC command */
74 #define UFS_UIC_COMMAND_RETRIES 3
76 /* maximum number of link-startup retries */
77 #define DME_LINKSTARTUP_RETRIES 3
79 /* Maximum retries for Hibern8 enter */
80 #define UIC_HIBERN8_ENTER_RETRIES 3
82 /* maximum number of reset retries before giving up */
83 #define MAX_HOST_RESET_RETRIES 5
85 /* Expose the flag value from utp_upiu_query.value */
86 #define MASK_QUERY_UPIU_FLAG_LOC 0xFF
88 /* Interrupt aggregation default timeout, unit: 40us */
89 #define INT_AGGR_DEF_TO 0x02
91 #define ufshcd_toggle_vreg(_dev, _vreg, _on) \
95 _ret = ufshcd_enable_vreg(_dev, _vreg); \
97 _ret = ufshcd_disable_vreg(_dev, _vreg); \
101 #define ufshcd_hex_dump(prefix_str, buf, len) do { \
102 size_t __len = (len); \
103 print_hex_dump(KERN_ERR, prefix_str, \
104 __len > 4 ? DUMP_PREFIX_OFFSET : DUMP_PREFIX_NONE,\
105 16, 4, buf, __len, false); \
108 int ufshcd_dump_regs(struct ufs_hba *hba, size_t offset, size_t len,
114 if (offset % 4 != 0 || len % 4 != 0) /* keep readl happy */
117 regs = kzalloc(len, GFP_KERNEL);
121 for (pos = 0; pos < len; pos += 4)
122 regs[pos / 4] = ufshcd_readl(hba, offset + pos);
124 ufshcd_hex_dump(prefix, regs, len);
129 EXPORT_SYMBOL_GPL(ufshcd_dump_regs);
132 UFSHCD_MAX_CHANNEL = 0,
134 UFSHCD_CMD_PER_LUN = 32,
135 UFSHCD_CAN_QUEUE = 32,
142 UFSHCD_STATE_OPERATIONAL,
143 UFSHCD_STATE_EH_SCHEDULED,
146 /* UFSHCD error handling flags */
148 UFSHCD_EH_IN_PROGRESS = (1 << 0),
151 /* UFSHCD UIC layer error flags */
153 UFSHCD_UIC_DL_PA_INIT_ERROR = (1 << 0), /* Data link layer error */
154 UFSHCD_UIC_DL_NAC_RECEIVED_ERROR = (1 << 1), /* Data link layer error */
155 UFSHCD_UIC_DL_TCx_REPLAY_ERROR = (1 << 2), /* Data link layer error */
156 UFSHCD_UIC_NL_ERROR = (1 << 3), /* Network layer error */
157 UFSHCD_UIC_TL_ERROR = (1 << 4), /* Transport Layer error */
158 UFSHCD_UIC_DME_ERROR = (1 << 5), /* DME error */
161 #define ufshcd_set_eh_in_progress(h) \
162 ((h)->eh_flags |= UFSHCD_EH_IN_PROGRESS)
163 #define ufshcd_eh_in_progress(h) \
164 ((h)->eh_flags & UFSHCD_EH_IN_PROGRESS)
165 #define ufshcd_clear_eh_in_progress(h) \
166 ((h)->eh_flags &= ~UFSHCD_EH_IN_PROGRESS)
168 #define ufshcd_set_ufs_dev_active(h) \
169 ((h)->curr_dev_pwr_mode = UFS_ACTIVE_PWR_MODE)
170 #define ufshcd_set_ufs_dev_sleep(h) \
171 ((h)->curr_dev_pwr_mode = UFS_SLEEP_PWR_MODE)
172 #define ufshcd_set_ufs_dev_poweroff(h) \
173 ((h)->curr_dev_pwr_mode = UFS_POWERDOWN_PWR_MODE)
174 #define ufshcd_is_ufs_dev_active(h) \
175 ((h)->curr_dev_pwr_mode == UFS_ACTIVE_PWR_MODE)
176 #define ufshcd_is_ufs_dev_sleep(h) \
177 ((h)->curr_dev_pwr_mode == UFS_SLEEP_PWR_MODE)
178 #define ufshcd_is_ufs_dev_poweroff(h) \
179 ((h)->curr_dev_pwr_mode == UFS_POWERDOWN_PWR_MODE)
181 struct ufs_pm_lvl_states ufs_pm_lvl_states[] = {
182 {UFS_ACTIVE_PWR_MODE, UIC_LINK_ACTIVE_STATE},
183 {UFS_ACTIVE_PWR_MODE, UIC_LINK_HIBERN8_STATE},
184 {UFS_SLEEP_PWR_MODE, UIC_LINK_ACTIVE_STATE},
185 {UFS_SLEEP_PWR_MODE, UIC_LINK_HIBERN8_STATE},
186 {UFS_POWERDOWN_PWR_MODE, UIC_LINK_HIBERN8_STATE},
187 {UFS_POWERDOWN_PWR_MODE, UIC_LINK_OFF_STATE},
190 static inline enum ufs_dev_pwr_mode
191 ufs_get_pm_lvl_to_dev_pwr_mode(enum ufs_pm_level lvl)
193 return ufs_pm_lvl_states[lvl].dev_state;
196 static inline enum uic_link_state
197 ufs_get_pm_lvl_to_link_pwr_state(enum ufs_pm_level lvl)
199 return ufs_pm_lvl_states[lvl].link_state;
202 static inline enum ufs_pm_level
203 ufs_get_desired_pm_lvl_for_dev_link_state(enum ufs_dev_pwr_mode dev_state,
204 enum uic_link_state link_state)
206 enum ufs_pm_level lvl;
208 for (lvl = UFS_PM_LVL_0; lvl < UFS_PM_LVL_MAX; lvl++) {
209 if ((ufs_pm_lvl_states[lvl].dev_state == dev_state) &&
210 (ufs_pm_lvl_states[lvl].link_state == link_state))
214 /* if no match found, return the level 0 */
218 static struct ufs_dev_fix ufs_fixups[] = {
219 /* UFS cards deviations table */
220 UFS_FIX(UFS_VENDOR_SAMSUNG, UFS_ANY_MODEL,
221 UFS_DEVICE_QUIRK_DELAY_BEFORE_LPM),
222 UFS_FIX(UFS_VENDOR_SAMSUNG, UFS_ANY_MODEL,
223 UFS_DEVICE_QUIRK_RECOVERY_FROM_DL_NAC_ERRORS),
224 UFS_FIX(UFS_VENDOR_SAMSUNG, UFS_ANY_MODEL,
225 UFS_DEVICE_QUIRK_HOST_PA_TACTIVATE),
226 UFS_FIX(UFS_VENDOR_TOSHIBA, UFS_ANY_MODEL,
227 UFS_DEVICE_QUIRK_DELAY_BEFORE_LPM),
228 UFS_FIX(UFS_VENDOR_TOSHIBA, "THGLF2G9C8KBADG",
229 UFS_DEVICE_QUIRK_PA_TACTIVATE),
230 UFS_FIX(UFS_VENDOR_TOSHIBA, "THGLF2G9D8KBADG",
231 UFS_DEVICE_QUIRK_PA_TACTIVATE),
232 UFS_FIX(UFS_VENDOR_SKHYNIX, UFS_ANY_MODEL,
233 UFS_DEVICE_QUIRK_HOST_PA_SAVECONFIGTIME),
234 UFS_FIX(UFS_VENDOR_SKHYNIX, "hB8aL1" /*H28U62301AMR*/,
235 UFS_DEVICE_QUIRK_HOST_VS_DEBUGSAVECONFIGTIME),
240 static void ufshcd_tmc_handler(struct ufs_hba *hba);
241 static void ufshcd_async_scan(void *data, async_cookie_t cookie);
242 static int ufshcd_reset_and_restore(struct ufs_hba *hba);
243 static int ufshcd_eh_host_reset_handler(struct scsi_cmnd *cmd);
244 static int ufshcd_clear_tm_cmd(struct ufs_hba *hba, int tag);
245 static void ufshcd_hba_exit(struct ufs_hba *hba);
246 static int ufshcd_probe_hba(struct ufs_hba *hba);
247 static int __ufshcd_setup_clocks(struct ufs_hba *hba, bool on,
249 static int ufshcd_setup_clocks(struct ufs_hba *hba, bool on);
250 static int ufshcd_uic_hibern8_exit(struct ufs_hba *hba);
251 static int ufshcd_uic_hibern8_enter(struct ufs_hba *hba);
252 static inline void ufshcd_add_delay_before_dme_cmd(struct ufs_hba *hba);
253 static int ufshcd_host_reset_and_restore(struct ufs_hba *hba);
254 static void ufshcd_resume_clkscaling(struct ufs_hba *hba);
255 static void ufshcd_suspend_clkscaling(struct ufs_hba *hba);
256 static void __ufshcd_suspend_clkscaling(struct ufs_hba *hba);
257 static int ufshcd_scale_clks(struct ufs_hba *hba, bool scale_up);
258 static irqreturn_t ufshcd_intr(int irq, void *__hba);
259 static int ufshcd_change_power_mode(struct ufs_hba *hba,
260 struct ufs_pa_layer_attr *pwr_mode);
261 static inline bool ufshcd_valid_tag(struct ufs_hba *hba, int tag)
263 return tag >= 0 && tag < hba->nutrs;
266 static inline int ufshcd_enable_irq(struct ufs_hba *hba)
270 if (!hba->is_irq_enabled) {
271 ret = request_irq(hba->irq, ufshcd_intr, IRQF_SHARED, UFSHCD,
274 dev_err(hba->dev, "%s: request_irq failed, ret=%d\n",
276 hba->is_irq_enabled = true;
282 static inline void ufshcd_disable_irq(struct ufs_hba *hba)
284 if (hba->is_irq_enabled) {
285 free_irq(hba->irq, hba);
286 hba->is_irq_enabled = false;
290 static void ufshcd_scsi_unblock_requests(struct ufs_hba *hba)
292 if (atomic_dec_and_test(&hba->scsi_block_reqs_cnt))
293 scsi_unblock_requests(hba->host);
296 static void ufshcd_scsi_block_requests(struct ufs_hba *hba)
298 if (atomic_inc_return(&hba->scsi_block_reqs_cnt) == 1)
299 scsi_block_requests(hba->host);
302 static void ufshcd_add_cmd_upiu_trace(struct ufs_hba *hba, unsigned int tag,
305 struct utp_upiu_req *rq = hba->lrb[tag].ucd_req_ptr;
307 trace_ufshcd_upiu(dev_name(hba->dev), str, &rq->header, &rq->sc.cdb);
310 static void ufshcd_add_query_upiu_trace(struct ufs_hba *hba, unsigned int tag,
313 struct utp_upiu_req *rq = hba->lrb[tag].ucd_req_ptr;
315 trace_ufshcd_upiu(dev_name(hba->dev), str, &rq->header, &rq->qr);
318 static void ufshcd_add_tm_upiu_trace(struct ufs_hba *hba, unsigned int tag,
321 int off = (int)tag - hba->nutrs;
322 struct utp_task_req_desc *descp = &hba->utmrdl_base_addr[off];
324 trace_ufshcd_upiu(dev_name(hba->dev), str, &descp->req_header,
325 &descp->input_param1);
328 static void ufshcd_add_command_trace(struct ufs_hba *hba,
329 unsigned int tag, const char *str)
334 struct ufshcd_lrb *lrbp = &hba->lrb[tag];
335 int transfer_len = -1;
337 if (!trace_ufshcd_command_enabled()) {
338 /* trace UPIU W/O tracing command */
340 ufshcd_add_cmd_upiu_trace(hba, tag, str);
344 if (lrbp->cmd) { /* data phase exists */
345 /* trace UPIU also */
346 ufshcd_add_cmd_upiu_trace(hba, tag, str);
347 opcode = (u8)(*lrbp->cmd->cmnd);
348 if ((opcode == READ_10) || (opcode == WRITE_10)) {
350 * Currently we only fully trace read(10) and write(10)
353 if (lrbp->cmd->request && lrbp->cmd->request->bio)
355 lrbp->cmd->request->bio->bi_iter.bi_sector;
356 transfer_len = be32_to_cpu(
357 lrbp->ucd_req_ptr->sc.exp_data_transfer_len);
361 intr = ufshcd_readl(hba, REG_INTERRUPT_STATUS);
362 doorbell = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
363 trace_ufshcd_command(dev_name(hba->dev), str, tag,
364 doorbell, transfer_len, intr, lba, opcode);
367 static void ufshcd_print_clk_freqs(struct ufs_hba *hba)
369 struct ufs_clk_info *clki;
370 struct list_head *head = &hba->clk_list_head;
372 if (list_empty(head))
375 list_for_each_entry(clki, head, list) {
376 if (!IS_ERR_OR_NULL(clki->clk) && clki->min_freq &&
378 dev_err(hba->dev, "clk: %s, rate: %u\n",
379 clki->name, clki->curr_freq);
383 static void ufshcd_print_err_hist(struct ufs_hba *hba,
384 struct ufs_err_reg_hist *err_hist,
390 for (i = 0; i < UFS_ERR_REG_HIST_LENGTH; i++) {
391 int p = (i + err_hist->pos) % UFS_ERR_REG_HIST_LENGTH;
393 if (err_hist->reg[p] == 0)
395 dev_err(hba->dev, "%s[%d] = 0x%x at %lld us\n", err_name, p,
396 err_hist->reg[p], ktime_to_us(err_hist->tstamp[p]));
401 dev_err(hba->dev, "No record of %s errors\n", err_name);
404 static void ufshcd_print_host_regs(struct ufs_hba *hba)
406 ufshcd_dump_regs(hba, 0, UFSHCI_REG_SPACE_SIZE, "host_regs: ");
407 dev_err(hba->dev, "hba->ufs_version = 0x%x, hba->capabilities = 0x%x\n",
408 hba->ufs_version, hba->capabilities);
410 "hba->outstanding_reqs = 0x%x, hba->outstanding_tasks = 0x%x\n",
411 (u32)hba->outstanding_reqs, (u32)hba->outstanding_tasks);
413 "last_hibern8_exit_tstamp at %lld us, hibern8_exit_cnt = %d\n",
414 ktime_to_us(hba->ufs_stats.last_hibern8_exit_tstamp),
415 hba->ufs_stats.hibern8_exit_cnt);
417 ufshcd_print_err_hist(hba, &hba->ufs_stats.pa_err, "pa_err");
418 ufshcd_print_err_hist(hba, &hba->ufs_stats.dl_err, "dl_err");
419 ufshcd_print_err_hist(hba, &hba->ufs_stats.nl_err, "nl_err");
420 ufshcd_print_err_hist(hba, &hba->ufs_stats.tl_err, "tl_err");
421 ufshcd_print_err_hist(hba, &hba->ufs_stats.dme_err, "dme_err");
422 ufshcd_print_err_hist(hba, &hba->ufs_stats.auto_hibern8_err,
424 ufshcd_print_err_hist(hba, &hba->ufs_stats.fatal_err, "fatal_err");
425 ufshcd_print_err_hist(hba, &hba->ufs_stats.link_startup_err,
426 "link_startup_fail");
427 ufshcd_print_err_hist(hba, &hba->ufs_stats.resume_err, "resume_fail");
428 ufshcd_print_err_hist(hba, &hba->ufs_stats.suspend_err,
430 ufshcd_print_err_hist(hba, &hba->ufs_stats.dev_reset, "dev_reset");
431 ufshcd_print_err_hist(hba, &hba->ufs_stats.host_reset, "host_reset");
432 ufshcd_print_err_hist(hba, &hba->ufs_stats.task_abort, "task_abort");
434 ufshcd_print_clk_freqs(hba);
436 if (hba->vops && hba->vops->dbg_register_dump)
437 hba->vops->dbg_register_dump(hba);
441 void ufshcd_print_trs(struct ufs_hba *hba, unsigned long bitmap, bool pr_prdt)
443 struct ufshcd_lrb *lrbp;
447 for_each_set_bit(tag, &bitmap, hba->nutrs) {
448 lrbp = &hba->lrb[tag];
450 dev_err(hba->dev, "UPIU[%d] - issue time %lld us\n",
451 tag, ktime_to_us(lrbp->issue_time_stamp));
452 dev_err(hba->dev, "UPIU[%d] - complete time %lld us\n",
453 tag, ktime_to_us(lrbp->compl_time_stamp));
455 "UPIU[%d] - Transfer Request Descriptor phys@0x%llx\n",
456 tag, (u64)lrbp->utrd_dma_addr);
458 ufshcd_hex_dump("UPIU TRD: ", lrbp->utr_descriptor_ptr,
459 sizeof(struct utp_transfer_req_desc));
460 dev_err(hba->dev, "UPIU[%d] - Request UPIU phys@0x%llx\n", tag,
461 (u64)lrbp->ucd_req_dma_addr);
462 ufshcd_hex_dump("UPIU REQ: ", lrbp->ucd_req_ptr,
463 sizeof(struct utp_upiu_req));
464 dev_err(hba->dev, "UPIU[%d] - Response UPIU phys@0x%llx\n", tag,
465 (u64)lrbp->ucd_rsp_dma_addr);
466 ufshcd_hex_dump("UPIU RSP: ", lrbp->ucd_rsp_ptr,
467 sizeof(struct utp_upiu_rsp));
469 prdt_length = le16_to_cpu(
470 lrbp->utr_descriptor_ptr->prd_table_length);
472 "UPIU[%d] - PRDT - %d entries phys@0x%llx\n",
474 (u64)lrbp->ucd_prdt_dma_addr);
477 ufshcd_hex_dump("UPIU PRDT: ", lrbp->ucd_prdt_ptr,
478 sizeof(struct ufshcd_sg_entry) * prdt_length);
482 static void ufshcd_print_tmrs(struct ufs_hba *hba, unsigned long bitmap)
486 for_each_set_bit(tag, &bitmap, hba->nutmrs) {
487 struct utp_task_req_desc *tmrdp = &hba->utmrdl_base_addr[tag];
489 dev_err(hba->dev, "TM[%d] - Task Management Header\n", tag);
490 ufshcd_hex_dump("", tmrdp, sizeof(*tmrdp));
494 static void ufshcd_print_host_state(struct ufs_hba *hba)
496 dev_err(hba->dev, "UFS Host state=%d\n", hba->ufshcd_state);
497 dev_err(hba->dev, "lrb in use=0x%lx, outstanding reqs=0x%lx tasks=0x%lx\n",
498 hba->lrb_in_use, hba->outstanding_reqs, hba->outstanding_tasks);
499 dev_err(hba->dev, "saved_err=0x%x, saved_uic_err=0x%x\n",
500 hba->saved_err, hba->saved_uic_err);
501 dev_err(hba->dev, "Device power mode=%d, UIC link state=%d\n",
502 hba->curr_dev_pwr_mode, hba->uic_link_state);
503 dev_err(hba->dev, "PM in progress=%d, sys. suspended=%d\n",
504 hba->pm_op_in_progress, hba->is_sys_suspended);
505 dev_err(hba->dev, "Auto BKOPS=%d, Host self-block=%d\n",
506 hba->auto_bkops_enabled, hba->host->host_self_blocked);
507 dev_err(hba->dev, "Clk gate=%d\n", hba->clk_gating.state);
508 dev_err(hba->dev, "error handling flags=0x%x, req. abort count=%d\n",
509 hba->eh_flags, hba->req_abort_count);
510 dev_err(hba->dev, "Host capabilities=0x%x, caps=0x%x\n",
511 hba->capabilities, hba->caps);
512 dev_err(hba->dev, "quirks=0x%x, dev. quirks=0x%x\n", hba->quirks,
517 * ufshcd_print_pwr_info - print power params as saved in hba
519 * @hba: per-adapter instance
521 static void ufshcd_print_pwr_info(struct ufs_hba *hba)
523 static const char * const names[] = {
533 dev_err(hba->dev, "%s:[RX, TX]: gear=[%d, %d], lane[%d, %d], pwr[%s, %s], rate = %d\n",
535 hba->pwr_info.gear_rx, hba->pwr_info.gear_tx,
536 hba->pwr_info.lane_rx, hba->pwr_info.lane_tx,
537 names[hba->pwr_info.pwr_rx],
538 names[hba->pwr_info.pwr_tx],
539 hba->pwr_info.hs_rate);
543 * ufshcd_wait_for_register - wait for register value to change
544 * @hba - per-adapter interface
545 * @reg - mmio register offset
546 * @mask - mask to apply to read register value
547 * @val - wait condition
548 * @interval_us - polling interval in microsecs
549 * @timeout_ms - timeout in millisecs
550 * @can_sleep - perform sleep or just spin
552 * Returns -ETIMEDOUT on error, zero on success
554 int ufshcd_wait_for_register(struct ufs_hba *hba, u32 reg, u32 mask,
555 u32 val, unsigned long interval_us,
556 unsigned long timeout_ms, bool can_sleep)
559 unsigned long timeout = jiffies + msecs_to_jiffies(timeout_ms);
561 /* ignore bits that we don't intend to wait on */
564 while ((ufshcd_readl(hba, reg) & mask) != val) {
566 usleep_range(interval_us, interval_us + 50);
569 if (time_after(jiffies, timeout)) {
570 if ((ufshcd_readl(hba, reg) & mask) != val)
580 * ufshcd_get_intr_mask - Get the interrupt bit mask
581 * @hba: Pointer to adapter instance
583 * Returns interrupt bit mask per version
585 static inline u32 ufshcd_get_intr_mask(struct ufs_hba *hba)
589 switch (hba->ufs_version) {
590 case UFSHCI_VERSION_10:
591 intr_mask = INTERRUPT_MASK_ALL_VER_10;
593 case UFSHCI_VERSION_11:
594 case UFSHCI_VERSION_20:
595 intr_mask = INTERRUPT_MASK_ALL_VER_11;
597 case UFSHCI_VERSION_21:
599 intr_mask = INTERRUPT_MASK_ALL_VER_21;
607 * ufshcd_get_ufs_version - Get the UFS version supported by the HBA
608 * @hba: Pointer to adapter instance
610 * Returns UFSHCI version supported by the controller
612 static inline u32 ufshcd_get_ufs_version(struct ufs_hba *hba)
614 if (hba->quirks & UFSHCD_QUIRK_BROKEN_UFS_HCI_VERSION)
615 return ufshcd_vops_get_ufs_hci_version(hba);
617 return ufshcd_readl(hba, REG_UFS_VERSION);
621 * ufshcd_is_device_present - Check if any device connected to
622 * the host controller
623 * @hba: pointer to adapter instance
625 * Returns true if device present, false if no device detected
627 static inline bool ufshcd_is_device_present(struct ufs_hba *hba)
629 return (ufshcd_readl(hba, REG_CONTROLLER_STATUS) &
630 DEVICE_PRESENT) ? true : false;
634 * ufshcd_get_tr_ocs - Get the UTRD Overall Command Status
635 * @lrbp: pointer to local command reference block
637 * This function is used to get the OCS field from UTRD
638 * Returns the OCS field in the UTRD
640 static inline int ufshcd_get_tr_ocs(struct ufshcd_lrb *lrbp)
642 return le32_to_cpu(lrbp->utr_descriptor_ptr->header.dword_2) & MASK_OCS;
646 * ufshcd_get_tm_free_slot - get a free slot for task management request
647 * @hba: per adapter instance
648 * @free_slot: pointer to variable with available slot value
650 * Get a free tag and lock it until ufshcd_put_tm_slot() is called.
651 * Returns 0 if free slot is not available, else return 1 with tag value
654 static bool ufshcd_get_tm_free_slot(struct ufs_hba *hba, int *free_slot)
663 tag = find_first_zero_bit(&hba->tm_slots_in_use, hba->nutmrs);
664 if (tag >= hba->nutmrs)
666 } while (test_and_set_bit_lock(tag, &hba->tm_slots_in_use));
674 static inline void ufshcd_put_tm_slot(struct ufs_hba *hba, int slot)
676 clear_bit_unlock(slot, &hba->tm_slots_in_use);
680 * ufshcd_utrl_clear - Clear a bit in UTRLCLR register
681 * @hba: per adapter instance
682 * @pos: position of the bit to be cleared
684 static inline void ufshcd_utrl_clear(struct ufs_hba *hba, u32 pos)
686 if (hba->quirks & UFSHCI_QUIRK_BROKEN_REQ_LIST_CLR)
687 ufshcd_writel(hba, (1 << pos), REG_UTP_TRANSFER_REQ_LIST_CLEAR);
689 ufshcd_writel(hba, ~(1 << pos),
690 REG_UTP_TRANSFER_REQ_LIST_CLEAR);
694 * ufshcd_utmrl_clear - Clear a bit in UTRMLCLR register
695 * @hba: per adapter instance
696 * @pos: position of the bit to be cleared
698 static inline void ufshcd_utmrl_clear(struct ufs_hba *hba, u32 pos)
700 if (hba->quirks & UFSHCI_QUIRK_BROKEN_REQ_LIST_CLR)
701 ufshcd_writel(hba, (1 << pos), REG_UTP_TASK_REQ_LIST_CLEAR);
703 ufshcd_writel(hba, ~(1 << pos), REG_UTP_TASK_REQ_LIST_CLEAR);
707 * ufshcd_outstanding_req_clear - Clear a bit in outstanding request field
708 * @hba: per adapter instance
709 * @tag: position of the bit to be cleared
711 static inline void ufshcd_outstanding_req_clear(struct ufs_hba *hba, int tag)
713 __clear_bit(tag, &hba->outstanding_reqs);
717 * ufshcd_get_lists_status - Check UCRDY, UTRLRDY and UTMRLRDY
718 * @reg: Register value of host controller status
720 * Returns integer, 0 on Success and positive value if failed
722 static inline int ufshcd_get_lists_status(u32 reg)
724 return !((reg & UFSHCD_STATUS_READY) == UFSHCD_STATUS_READY);
728 * ufshcd_get_uic_cmd_result - Get the UIC command result
729 * @hba: Pointer to adapter instance
731 * This function gets the result of UIC command completion
732 * Returns 0 on success, non zero value on error
734 static inline int ufshcd_get_uic_cmd_result(struct ufs_hba *hba)
736 return ufshcd_readl(hba, REG_UIC_COMMAND_ARG_2) &
737 MASK_UIC_COMMAND_RESULT;
741 * ufshcd_get_dme_attr_val - Get the value of attribute returned by UIC command
742 * @hba: Pointer to adapter instance
744 * This function gets UIC command argument3
745 * Returns 0 on success, non zero value on error
747 static inline u32 ufshcd_get_dme_attr_val(struct ufs_hba *hba)
749 return ufshcd_readl(hba, REG_UIC_COMMAND_ARG_3);
753 * ufshcd_get_req_rsp - returns the TR response transaction type
754 * @ucd_rsp_ptr: pointer to response UPIU
757 ufshcd_get_req_rsp(struct utp_upiu_rsp *ucd_rsp_ptr)
759 return be32_to_cpu(ucd_rsp_ptr->header.dword_0) >> 24;
763 * ufshcd_get_rsp_upiu_result - Get the result from response UPIU
764 * @ucd_rsp_ptr: pointer to response UPIU
766 * This function gets the response status and scsi_status from response UPIU
767 * Returns the response result code.
770 ufshcd_get_rsp_upiu_result(struct utp_upiu_rsp *ucd_rsp_ptr)
772 return be32_to_cpu(ucd_rsp_ptr->header.dword_1) & MASK_RSP_UPIU_RESULT;
776 * ufshcd_get_rsp_upiu_data_seg_len - Get the data segment length
778 * @ucd_rsp_ptr: pointer to response UPIU
780 * Return the data segment length.
782 static inline unsigned int
783 ufshcd_get_rsp_upiu_data_seg_len(struct utp_upiu_rsp *ucd_rsp_ptr)
785 return be32_to_cpu(ucd_rsp_ptr->header.dword_2) &
786 MASK_RSP_UPIU_DATA_SEG_LEN;
790 * ufshcd_is_exception_event - Check if the device raised an exception event
791 * @ucd_rsp_ptr: pointer to response UPIU
793 * The function checks if the device raised an exception event indicated in
794 * the Device Information field of response UPIU.
796 * Returns true if exception is raised, false otherwise.
798 static inline bool ufshcd_is_exception_event(struct utp_upiu_rsp *ucd_rsp_ptr)
800 return be32_to_cpu(ucd_rsp_ptr->header.dword_2) &
801 MASK_RSP_EXCEPTION_EVENT ? true : false;
805 * ufshcd_reset_intr_aggr - Reset interrupt aggregation values.
806 * @hba: per adapter instance
809 ufshcd_reset_intr_aggr(struct ufs_hba *hba)
811 ufshcd_writel(hba, INT_AGGR_ENABLE |
812 INT_AGGR_COUNTER_AND_TIMER_RESET,
813 REG_UTP_TRANSFER_REQ_INT_AGG_CONTROL);
817 * ufshcd_config_intr_aggr - Configure interrupt aggregation values.
818 * @hba: per adapter instance
819 * @cnt: Interrupt aggregation counter threshold
820 * @tmout: Interrupt aggregation timeout value
823 ufshcd_config_intr_aggr(struct ufs_hba *hba, u8 cnt, u8 tmout)
825 ufshcd_writel(hba, INT_AGGR_ENABLE | INT_AGGR_PARAM_WRITE |
826 INT_AGGR_COUNTER_THLD_VAL(cnt) |
827 INT_AGGR_TIMEOUT_VAL(tmout),
828 REG_UTP_TRANSFER_REQ_INT_AGG_CONTROL);
832 * ufshcd_disable_intr_aggr - Disables interrupt aggregation.
833 * @hba: per adapter instance
835 static inline void ufshcd_disable_intr_aggr(struct ufs_hba *hba)
837 ufshcd_writel(hba, 0, REG_UTP_TRANSFER_REQ_INT_AGG_CONTROL);
841 * ufshcd_enable_run_stop_reg - Enable run-stop registers,
842 * When run-stop registers are set to 1, it indicates the
843 * host controller that it can process the requests
844 * @hba: per adapter instance
846 static void ufshcd_enable_run_stop_reg(struct ufs_hba *hba)
848 ufshcd_writel(hba, UTP_TASK_REQ_LIST_RUN_STOP_BIT,
849 REG_UTP_TASK_REQ_LIST_RUN_STOP);
850 ufshcd_writel(hba, UTP_TRANSFER_REQ_LIST_RUN_STOP_BIT,
851 REG_UTP_TRANSFER_REQ_LIST_RUN_STOP);
855 * ufshcd_hba_start - Start controller initialization sequence
856 * @hba: per adapter instance
858 static inline void ufshcd_hba_start(struct ufs_hba *hba)
860 ufshcd_writel(hba, CONTROLLER_ENABLE, REG_CONTROLLER_ENABLE);
864 * ufshcd_is_hba_active - Get controller state
865 * @hba: per adapter instance
867 * Returns false if controller is active, true otherwise
869 static inline bool ufshcd_is_hba_active(struct ufs_hba *hba)
871 return (ufshcd_readl(hba, REG_CONTROLLER_ENABLE) & CONTROLLER_ENABLE)
875 u32 ufshcd_get_local_unipro_ver(struct ufs_hba *hba)
877 /* HCI version 1.0 and 1.1 supports UniPro 1.41 */
878 if ((hba->ufs_version == UFSHCI_VERSION_10) ||
879 (hba->ufs_version == UFSHCI_VERSION_11))
880 return UFS_UNIPRO_VER_1_41;
882 return UFS_UNIPRO_VER_1_6;
884 EXPORT_SYMBOL(ufshcd_get_local_unipro_ver);
886 static bool ufshcd_is_unipro_pa_params_tuning_req(struct ufs_hba *hba)
889 * If both host and device support UniPro ver1.6 or later, PA layer
890 * parameters tuning happens during link startup itself.
892 * We can manually tune PA layer parameters if either host or device
893 * doesn't support UniPro ver 1.6 or later. But to keep manual tuning
894 * logic simple, we will only do manual tuning if local unipro version
895 * doesn't support ver1.6 or later.
897 if (ufshcd_get_local_unipro_ver(hba) < UFS_UNIPRO_VER_1_6)
903 static int ufshcd_scale_clks(struct ufs_hba *hba, bool scale_up)
906 struct ufs_clk_info *clki;
907 struct list_head *head = &hba->clk_list_head;
908 ktime_t start = ktime_get();
909 bool clk_state_changed = false;
911 if (list_empty(head))
914 ret = ufshcd_vops_clk_scale_notify(hba, scale_up, PRE_CHANGE);
918 list_for_each_entry(clki, head, list) {
919 if (!IS_ERR_OR_NULL(clki->clk)) {
920 if (scale_up && clki->max_freq) {
921 if (clki->curr_freq == clki->max_freq)
924 clk_state_changed = true;
925 ret = clk_set_rate(clki->clk, clki->max_freq);
927 dev_err(hba->dev, "%s: %s clk set rate(%dHz) failed, %d\n",
928 __func__, clki->name,
929 clki->max_freq, ret);
932 trace_ufshcd_clk_scaling(dev_name(hba->dev),
933 "scaled up", clki->name,
937 clki->curr_freq = clki->max_freq;
939 } else if (!scale_up && clki->min_freq) {
940 if (clki->curr_freq == clki->min_freq)
943 clk_state_changed = true;
944 ret = clk_set_rate(clki->clk, clki->min_freq);
946 dev_err(hba->dev, "%s: %s clk set rate(%dHz) failed, %d\n",
947 __func__, clki->name,
948 clki->min_freq, ret);
951 trace_ufshcd_clk_scaling(dev_name(hba->dev),
952 "scaled down", clki->name,
955 clki->curr_freq = clki->min_freq;
958 dev_dbg(hba->dev, "%s: clk: %s, rate: %lu\n", __func__,
959 clki->name, clk_get_rate(clki->clk));
962 ret = ufshcd_vops_clk_scale_notify(hba, scale_up, POST_CHANGE);
965 if (clk_state_changed)
966 trace_ufshcd_profile_clk_scaling(dev_name(hba->dev),
967 (scale_up ? "up" : "down"),
968 ktime_to_us(ktime_sub(ktime_get(), start)), ret);
973 * ufshcd_is_devfreq_scaling_required - check if scaling is required or not
974 * @hba: per adapter instance
975 * @scale_up: True if scaling up and false if scaling down
977 * Returns true if scaling is required, false otherwise.
979 static bool ufshcd_is_devfreq_scaling_required(struct ufs_hba *hba,
982 struct ufs_clk_info *clki;
983 struct list_head *head = &hba->clk_list_head;
985 if (list_empty(head))
988 list_for_each_entry(clki, head, list) {
989 if (!IS_ERR_OR_NULL(clki->clk)) {
990 if (scale_up && clki->max_freq) {
991 if (clki->curr_freq == clki->max_freq)
994 } else if (!scale_up && clki->min_freq) {
995 if (clki->curr_freq == clki->min_freq)
1005 static int ufshcd_wait_for_doorbell_clr(struct ufs_hba *hba,
1006 u64 wait_timeout_us)
1008 unsigned long flags;
1012 bool timeout = false, do_last_check = false;
1015 ufshcd_hold(hba, false);
1016 spin_lock_irqsave(hba->host->host_lock, flags);
1018 * Wait for all the outstanding tasks/transfer requests.
1019 * Verify by checking the doorbell registers are clear.
1021 start = ktime_get();
1023 if (hba->ufshcd_state != UFSHCD_STATE_OPERATIONAL) {
1028 tm_doorbell = ufshcd_readl(hba, REG_UTP_TASK_REQ_DOOR_BELL);
1029 tr_doorbell = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
1030 if (!tm_doorbell && !tr_doorbell) {
1033 } else if (do_last_check) {
1037 spin_unlock_irqrestore(hba->host->host_lock, flags);
1039 if (ktime_to_us(ktime_sub(ktime_get(), start)) >
1043 * We might have scheduled out for long time so make
1044 * sure to check if doorbells are cleared by this time
1047 do_last_check = true;
1049 spin_lock_irqsave(hba->host->host_lock, flags);
1050 } while (tm_doorbell || tr_doorbell);
1054 "%s: timedout waiting for doorbell to clear (tm=0x%x, tr=0x%x)\n",
1055 __func__, tm_doorbell, tr_doorbell);
1059 spin_unlock_irqrestore(hba->host->host_lock, flags);
1060 ufshcd_release(hba);
1065 * ufshcd_scale_gear - scale up/down UFS gear
1066 * @hba: per adapter instance
1067 * @scale_up: True for scaling up gear and false for scaling down
1069 * Returns 0 for success,
1070 * Returns -EBUSY if scaling can't happen at this time
1071 * Returns non-zero for any other errors
1073 static int ufshcd_scale_gear(struct ufs_hba *hba, bool scale_up)
1075 #define UFS_MIN_GEAR_TO_SCALE_DOWN UFS_HS_G1
1077 struct ufs_pa_layer_attr new_pwr_info;
1080 memcpy(&new_pwr_info, &hba->clk_scaling.saved_pwr_info.info,
1081 sizeof(struct ufs_pa_layer_attr));
1083 memcpy(&new_pwr_info, &hba->pwr_info,
1084 sizeof(struct ufs_pa_layer_attr));
1086 if (hba->pwr_info.gear_tx > UFS_MIN_GEAR_TO_SCALE_DOWN
1087 || hba->pwr_info.gear_rx > UFS_MIN_GEAR_TO_SCALE_DOWN) {
1088 /* save the current power mode */
1089 memcpy(&hba->clk_scaling.saved_pwr_info.info,
1091 sizeof(struct ufs_pa_layer_attr));
1093 /* scale down gear */
1094 new_pwr_info.gear_tx = UFS_MIN_GEAR_TO_SCALE_DOWN;
1095 new_pwr_info.gear_rx = UFS_MIN_GEAR_TO_SCALE_DOWN;
1099 /* check if the power mode needs to be changed or not? */
1100 ret = ufshcd_change_power_mode(hba, &new_pwr_info);
1103 dev_err(hba->dev, "%s: failed err %d, old gear: (tx %d rx %d), new gear: (tx %d rx %d)",
1105 hba->pwr_info.gear_tx, hba->pwr_info.gear_rx,
1106 new_pwr_info.gear_tx, new_pwr_info.gear_rx);
1111 static int ufshcd_clock_scaling_prepare(struct ufs_hba *hba)
1113 #define DOORBELL_CLR_TOUT_US (1000 * 1000) /* 1 sec */
1116 * make sure that there are no outstanding requests when
1117 * clock scaling is in progress
1119 ufshcd_scsi_block_requests(hba);
1120 down_write(&hba->clk_scaling_lock);
1121 if (ufshcd_wait_for_doorbell_clr(hba, DOORBELL_CLR_TOUT_US)) {
1123 up_write(&hba->clk_scaling_lock);
1124 ufshcd_scsi_unblock_requests(hba);
1130 static void ufshcd_clock_scaling_unprepare(struct ufs_hba *hba)
1132 up_write(&hba->clk_scaling_lock);
1133 ufshcd_scsi_unblock_requests(hba);
1137 * ufshcd_devfreq_scale - scale up/down UFS clocks and gear
1138 * @hba: per adapter instance
1139 * @scale_up: True for scaling up and false for scalin down
1141 * Returns 0 for success,
1142 * Returns -EBUSY if scaling can't happen at this time
1143 * Returns non-zero for any other errors
1145 static int ufshcd_devfreq_scale(struct ufs_hba *hba, bool scale_up)
1149 /* let's not get into low power until clock scaling is completed */
1150 ufshcd_hold(hba, false);
1152 ret = ufshcd_clock_scaling_prepare(hba);
1156 /* scale down the gear before scaling down clocks */
1158 ret = ufshcd_scale_gear(hba, false);
1163 ret = ufshcd_scale_clks(hba, scale_up);
1166 ufshcd_scale_gear(hba, true);
1170 /* scale up the gear after scaling up clocks */
1172 ret = ufshcd_scale_gear(hba, true);
1174 ufshcd_scale_clks(hba, false);
1179 ret = ufshcd_vops_clk_scale_notify(hba, scale_up, POST_CHANGE);
1182 ufshcd_clock_scaling_unprepare(hba);
1183 ufshcd_release(hba);
1187 static void ufshcd_clk_scaling_suspend_work(struct work_struct *work)
1189 struct ufs_hba *hba = container_of(work, struct ufs_hba,
1190 clk_scaling.suspend_work);
1191 unsigned long irq_flags;
1193 spin_lock_irqsave(hba->host->host_lock, irq_flags);
1194 if (hba->clk_scaling.active_reqs || hba->clk_scaling.is_suspended) {
1195 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1198 hba->clk_scaling.is_suspended = true;
1199 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1201 __ufshcd_suspend_clkscaling(hba);
1204 static void ufshcd_clk_scaling_resume_work(struct work_struct *work)
1206 struct ufs_hba *hba = container_of(work, struct ufs_hba,
1207 clk_scaling.resume_work);
1208 unsigned long irq_flags;
1210 spin_lock_irqsave(hba->host->host_lock, irq_flags);
1211 if (!hba->clk_scaling.is_suspended) {
1212 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1215 hba->clk_scaling.is_suspended = false;
1216 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1218 devfreq_resume_device(hba->devfreq);
1221 static int ufshcd_devfreq_target(struct device *dev,
1222 unsigned long *freq, u32 flags)
1225 struct ufs_hba *hba = dev_get_drvdata(dev);
1227 bool scale_up, sched_clk_scaling_suspend_work = false;
1228 struct list_head *clk_list = &hba->clk_list_head;
1229 struct ufs_clk_info *clki;
1230 unsigned long irq_flags;
1232 if (!ufshcd_is_clkscaling_supported(hba))
1235 spin_lock_irqsave(hba->host->host_lock, irq_flags);
1236 if (ufshcd_eh_in_progress(hba)) {
1237 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1241 if (!hba->clk_scaling.active_reqs)
1242 sched_clk_scaling_suspend_work = true;
1244 if (list_empty(clk_list)) {
1245 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1249 clki = list_first_entry(&hba->clk_list_head, struct ufs_clk_info, list);
1250 scale_up = (*freq == clki->max_freq) ? true : false;
1251 if (!ufshcd_is_devfreq_scaling_required(hba, scale_up)) {
1252 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1254 goto out; /* no state change required */
1256 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1258 start = ktime_get();
1259 ret = ufshcd_devfreq_scale(hba, scale_up);
1261 trace_ufshcd_profile_clk_scaling(dev_name(hba->dev),
1262 (scale_up ? "up" : "down"),
1263 ktime_to_us(ktime_sub(ktime_get(), start)), ret);
1266 if (sched_clk_scaling_suspend_work)
1267 queue_work(hba->clk_scaling.workq,
1268 &hba->clk_scaling.suspend_work);
1274 static int ufshcd_devfreq_get_dev_status(struct device *dev,
1275 struct devfreq_dev_status *stat)
1277 struct ufs_hba *hba = dev_get_drvdata(dev);
1278 struct ufs_clk_scaling *scaling = &hba->clk_scaling;
1279 unsigned long flags;
1281 if (!ufshcd_is_clkscaling_supported(hba))
1284 memset(stat, 0, sizeof(*stat));
1286 spin_lock_irqsave(hba->host->host_lock, flags);
1287 if (!scaling->window_start_t)
1290 if (scaling->is_busy_started)
1291 scaling->tot_busy_t += ktime_to_us(ktime_sub(ktime_get(),
1292 scaling->busy_start_t));
1294 stat->total_time = jiffies_to_usecs((long)jiffies -
1295 (long)scaling->window_start_t);
1296 stat->busy_time = scaling->tot_busy_t;
1298 scaling->window_start_t = jiffies;
1299 scaling->tot_busy_t = 0;
1301 if (hba->outstanding_reqs) {
1302 scaling->busy_start_t = ktime_get();
1303 scaling->is_busy_started = true;
1305 scaling->busy_start_t = 0;
1306 scaling->is_busy_started = false;
1308 spin_unlock_irqrestore(hba->host->host_lock, flags);
1312 static struct devfreq_dev_profile ufs_devfreq_profile = {
1314 .target = ufshcd_devfreq_target,
1315 .get_dev_status = ufshcd_devfreq_get_dev_status,
1318 static int ufshcd_devfreq_init(struct ufs_hba *hba)
1320 struct list_head *clk_list = &hba->clk_list_head;
1321 struct ufs_clk_info *clki;
1322 struct devfreq *devfreq;
1325 /* Skip devfreq if we don't have any clocks in the list */
1326 if (list_empty(clk_list))
1329 clki = list_first_entry(clk_list, struct ufs_clk_info, list);
1330 dev_pm_opp_add(hba->dev, clki->min_freq, 0);
1331 dev_pm_opp_add(hba->dev, clki->max_freq, 0);
1333 devfreq = devfreq_add_device(hba->dev,
1334 &ufs_devfreq_profile,
1335 DEVFREQ_GOV_SIMPLE_ONDEMAND,
1337 if (IS_ERR(devfreq)) {
1338 ret = PTR_ERR(devfreq);
1339 dev_err(hba->dev, "Unable to register with devfreq %d\n", ret);
1341 dev_pm_opp_remove(hba->dev, clki->min_freq);
1342 dev_pm_opp_remove(hba->dev, clki->max_freq);
1346 hba->devfreq = devfreq;
1351 static void ufshcd_devfreq_remove(struct ufs_hba *hba)
1353 struct list_head *clk_list = &hba->clk_list_head;
1354 struct ufs_clk_info *clki;
1359 devfreq_remove_device(hba->devfreq);
1360 hba->devfreq = NULL;
1362 clki = list_first_entry(clk_list, struct ufs_clk_info, list);
1363 dev_pm_opp_remove(hba->dev, clki->min_freq);
1364 dev_pm_opp_remove(hba->dev, clki->max_freq);
1367 static void __ufshcd_suspend_clkscaling(struct ufs_hba *hba)
1369 unsigned long flags;
1371 devfreq_suspend_device(hba->devfreq);
1372 spin_lock_irqsave(hba->host->host_lock, flags);
1373 hba->clk_scaling.window_start_t = 0;
1374 spin_unlock_irqrestore(hba->host->host_lock, flags);
1377 static void ufshcd_suspend_clkscaling(struct ufs_hba *hba)
1379 unsigned long flags;
1380 bool suspend = false;
1382 if (!ufshcd_is_clkscaling_supported(hba))
1385 spin_lock_irqsave(hba->host->host_lock, flags);
1386 if (!hba->clk_scaling.is_suspended) {
1388 hba->clk_scaling.is_suspended = true;
1390 spin_unlock_irqrestore(hba->host->host_lock, flags);
1393 __ufshcd_suspend_clkscaling(hba);
1396 static void ufshcd_resume_clkscaling(struct ufs_hba *hba)
1398 unsigned long flags;
1399 bool resume = false;
1401 if (!ufshcd_is_clkscaling_supported(hba))
1404 spin_lock_irqsave(hba->host->host_lock, flags);
1405 if (hba->clk_scaling.is_suspended) {
1407 hba->clk_scaling.is_suspended = false;
1409 spin_unlock_irqrestore(hba->host->host_lock, flags);
1412 devfreq_resume_device(hba->devfreq);
1415 static ssize_t ufshcd_clkscale_enable_show(struct device *dev,
1416 struct device_attribute *attr, char *buf)
1418 struct ufs_hba *hba = dev_get_drvdata(dev);
1420 return snprintf(buf, PAGE_SIZE, "%d\n", hba->clk_scaling.is_allowed);
1423 static ssize_t ufshcd_clkscale_enable_store(struct device *dev,
1424 struct device_attribute *attr, const char *buf, size_t count)
1426 struct ufs_hba *hba = dev_get_drvdata(dev);
1430 if (kstrtou32(buf, 0, &value))
1434 if (value == hba->clk_scaling.is_allowed)
1437 pm_runtime_get_sync(hba->dev);
1438 ufshcd_hold(hba, false);
1440 cancel_work_sync(&hba->clk_scaling.suspend_work);
1441 cancel_work_sync(&hba->clk_scaling.resume_work);
1443 hba->clk_scaling.is_allowed = value;
1446 ufshcd_resume_clkscaling(hba);
1448 ufshcd_suspend_clkscaling(hba);
1449 err = ufshcd_devfreq_scale(hba, true);
1451 dev_err(hba->dev, "%s: failed to scale clocks up %d\n",
1455 ufshcd_release(hba);
1456 pm_runtime_put_sync(hba->dev);
1461 static void ufshcd_clkscaling_init_sysfs(struct ufs_hba *hba)
1463 hba->clk_scaling.enable_attr.show = ufshcd_clkscale_enable_show;
1464 hba->clk_scaling.enable_attr.store = ufshcd_clkscale_enable_store;
1465 sysfs_attr_init(&hba->clk_scaling.enable_attr.attr);
1466 hba->clk_scaling.enable_attr.attr.name = "clkscale_enable";
1467 hba->clk_scaling.enable_attr.attr.mode = 0644;
1468 if (device_create_file(hba->dev, &hba->clk_scaling.enable_attr))
1469 dev_err(hba->dev, "Failed to create sysfs for clkscale_enable\n");
1472 static void ufshcd_ungate_work(struct work_struct *work)
1475 unsigned long flags;
1476 struct ufs_hba *hba = container_of(work, struct ufs_hba,
1477 clk_gating.ungate_work);
1479 cancel_delayed_work_sync(&hba->clk_gating.gate_work);
1481 spin_lock_irqsave(hba->host->host_lock, flags);
1482 if (hba->clk_gating.state == CLKS_ON) {
1483 spin_unlock_irqrestore(hba->host->host_lock, flags);
1487 spin_unlock_irqrestore(hba->host->host_lock, flags);
1488 ufshcd_setup_clocks(hba, true);
1490 /* Exit from hibern8 */
1491 if (ufshcd_can_hibern8_during_gating(hba)) {
1492 /* Prevent gating in this path */
1493 hba->clk_gating.is_suspended = true;
1494 if (ufshcd_is_link_hibern8(hba)) {
1495 ret = ufshcd_uic_hibern8_exit(hba);
1497 dev_err(hba->dev, "%s: hibern8 exit failed %d\n",
1500 ufshcd_set_link_active(hba);
1502 hba->clk_gating.is_suspended = false;
1505 ufshcd_scsi_unblock_requests(hba);
1509 * ufshcd_hold - Enable clocks that were gated earlier due to ufshcd_release.
1510 * Also, exit from hibern8 mode and set the link as active.
1511 * @hba: per adapter instance
1512 * @async: This indicates whether caller should ungate clocks asynchronously.
1514 int ufshcd_hold(struct ufs_hba *hba, bool async)
1517 unsigned long flags;
1519 if (!ufshcd_is_clkgating_allowed(hba))
1521 spin_lock_irqsave(hba->host->host_lock, flags);
1522 hba->clk_gating.active_reqs++;
1524 if (ufshcd_eh_in_progress(hba)) {
1525 spin_unlock_irqrestore(hba->host->host_lock, flags);
1530 switch (hba->clk_gating.state) {
1533 * Wait for the ungate work to complete if in progress.
1534 * Though the clocks may be in ON state, the link could
1535 * still be in hibner8 state if hibern8 is allowed
1536 * during clock gating.
1537 * Make sure we exit hibern8 state also in addition to
1540 if (ufshcd_can_hibern8_during_gating(hba) &&
1541 ufshcd_is_link_hibern8(hba)) {
1542 spin_unlock_irqrestore(hba->host->host_lock, flags);
1543 flush_work(&hba->clk_gating.ungate_work);
1544 spin_lock_irqsave(hba->host->host_lock, flags);
1549 if (cancel_delayed_work(&hba->clk_gating.gate_work)) {
1550 hba->clk_gating.state = CLKS_ON;
1551 trace_ufshcd_clk_gating(dev_name(hba->dev),
1552 hba->clk_gating.state);
1556 * If we are here, it means gating work is either done or
1557 * currently running. Hence, fall through to cancel gating
1558 * work and to enable clocks.
1562 ufshcd_scsi_block_requests(hba);
1563 hba->clk_gating.state = REQ_CLKS_ON;
1564 trace_ufshcd_clk_gating(dev_name(hba->dev),
1565 hba->clk_gating.state);
1566 queue_work(hba->clk_gating.clk_gating_workq,
1567 &hba->clk_gating.ungate_work);
1569 * fall through to check if we should wait for this
1570 * work to be done or not.
1576 hba->clk_gating.active_reqs--;
1580 spin_unlock_irqrestore(hba->host->host_lock, flags);
1581 flush_work(&hba->clk_gating.ungate_work);
1582 /* Make sure state is CLKS_ON before returning */
1583 spin_lock_irqsave(hba->host->host_lock, flags);
1586 dev_err(hba->dev, "%s: clk gating is in invalid state %d\n",
1587 __func__, hba->clk_gating.state);
1590 spin_unlock_irqrestore(hba->host->host_lock, flags);
1594 EXPORT_SYMBOL_GPL(ufshcd_hold);
1596 static void ufshcd_gate_work(struct work_struct *work)
1598 struct ufs_hba *hba = container_of(work, struct ufs_hba,
1599 clk_gating.gate_work.work);
1600 unsigned long flags;
1602 spin_lock_irqsave(hba->host->host_lock, flags);
1604 * In case you are here to cancel this work the gating state
1605 * would be marked as REQ_CLKS_ON. In this case save time by
1606 * skipping the gating work and exit after changing the clock
1609 if (hba->clk_gating.is_suspended ||
1610 (hba->clk_gating.state == REQ_CLKS_ON)) {
1611 hba->clk_gating.state = CLKS_ON;
1612 trace_ufshcd_clk_gating(dev_name(hba->dev),
1613 hba->clk_gating.state);
1617 if (hba->clk_gating.active_reqs
1618 || hba->ufshcd_state != UFSHCD_STATE_OPERATIONAL
1619 || hba->lrb_in_use || hba->outstanding_tasks
1620 || hba->active_uic_cmd || hba->uic_async_done)
1623 spin_unlock_irqrestore(hba->host->host_lock, flags);
1625 /* put the link into hibern8 mode before turning off clocks */
1626 if (ufshcd_can_hibern8_during_gating(hba)) {
1627 if (ufshcd_uic_hibern8_enter(hba)) {
1628 hba->clk_gating.state = CLKS_ON;
1629 trace_ufshcd_clk_gating(dev_name(hba->dev),
1630 hba->clk_gating.state);
1633 ufshcd_set_link_hibern8(hba);
1636 if (!ufshcd_is_link_active(hba))
1637 ufshcd_setup_clocks(hba, false);
1639 /* If link is active, device ref_clk can't be switched off */
1640 __ufshcd_setup_clocks(hba, false, true);
1643 * In case you are here to cancel this work the gating state
1644 * would be marked as REQ_CLKS_ON. In this case keep the state
1645 * as REQ_CLKS_ON which would anyway imply that clocks are off
1646 * and a request to turn them on is pending. By doing this way,
1647 * we keep the state machine in tact and this would ultimately
1648 * prevent from doing cancel work multiple times when there are
1649 * new requests arriving before the current cancel work is done.
1651 spin_lock_irqsave(hba->host->host_lock, flags);
1652 if (hba->clk_gating.state == REQ_CLKS_OFF) {
1653 hba->clk_gating.state = CLKS_OFF;
1654 trace_ufshcd_clk_gating(dev_name(hba->dev),
1655 hba->clk_gating.state);
1658 spin_unlock_irqrestore(hba->host->host_lock, flags);
1663 /* host lock must be held before calling this variant */
1664 static void __ufshcd_release(struct ufs_hba *hba)
1666 if (!ufshcd_is_clkgating_allowed(hba))
1669 hba->clk_gating.active_reqs--;
1671 if (hba->clk_gating.active_reqs || hba->clk_gating.is_suspended
1672 || hba->ufshcd_state != UFSHCD_STATE_OPERATIONAL
1673 || hba->lrb_in_use || hba->outstanding_tasks
1674 || hba->active_uic_cmd || hba->uic_async_done
1675 || ufshcd_eh_in_progress(hba))
1678 hba->clk_gating.state = REQ_CLKS_OFF;
1679 trace_ufshcd_clk_gating(dev_name(hba->dev), hba->clk_gating.state);
1680 queue_delayed_work(hba->clk_gating.clk_gating_workq,
1681 &hba->clk_gating.gate_work,
1682 msecs_to_jiffies(hba->clk_gating.delay_ms));
1685 void ufshcd_release(struct ufs_hba *hba)
1687 unsigned long flags;
1689 spin_lock_irqsave(hba->host->host_lock, flags);
1690 __ufshcd_release(hba);
1691 spin_unlock_irqrestore(hba->host->host_lock, flags);
1693 EXPORT_SYMBOL_GPL(ufshcd_release);
1695 static ssize_t ufshcd_clkgate_delay_show(struct device *dev,
1696 struct device_attribute *attr, char *buf)
1698 struct ufs_hba *hba = dev_get_drvdata(dev);
1700 return snprintf(buf, PAGE_SIZE, "%lu\n", hba->clk_gating.delay_ms);
1703 static ssize_t ufshcd_clkgate_delay_store(struct device *dev,
1704 struct device_attribute *attr, const char *buf, size_t count)
1706 struct ufs_hba *hba = dev_get_drvdata(dev);
1707 unsigned long flags, value;
1709 if (kstrtoul(buf, 0, &value))
1712 spin_lock_irqsave(hba->host->host_lock, flags);
1713 hba->clk_gating.delay_ms = value;
1714 spin_unlock_irqrestore(hba->host->host_lock, flags);
1718 static ssize_t ufshcd_clkgate_enable_show(struct device *dev,
1719 struct device_attribute *attr, char *buf)
1721 struct ufs_hba *hba = dev_get_drvdata(dev);
1723 return snprintf(buf, PAGE_SIZE, "%d\n", hba->clk_gating.is_enabled);
1726 static ssize_t ufshcd_clkgate_enable_store(struct device *dev,
1727 struct device_attribute *attr, const char *buf, size_t count)
1729 struct ufs_hba *hba = dev_get_drvdata(dev);
1730 unsigned long flags;
1733 if (kstrtou32(buf, 0, &value))
1737 if (value == hba->clk_gating.is_enabled)
1741 ufshcd_release(hba);
1743 spin_lock_irqsave(hba->host->host_lock, flags);
1744 hba->clk_gating.active_reqs++;
1745 spin_unlock_irqrestore(hba->host->host_lock, flags);
1748 hba->clk_gating.is_enabled = value;
1753 static void ufshcd_init_clk_scaling(struct ufs_hba *hba)
1755 char wq_name[sizeof("ufs_clkscaling_00")];
1757 if (!ufshcd_is_clkscaling_supported(hba))
1760 INIT_WORK(&hba->clk_scaling.suspend_work,
1761 ufshcd_clk_scaling_suspend_work);
1762 INIT_WORK(&hba->clk_scaling.resume_work,
1763 ufshcd_clk_scaling_resume_work);
1765 snprintf(wq_name, sizeof(wq_name), "ufs_clkscaling_%d",
1766 hba->host->host_no);
1767 hba->clk_scaling.workq = create_singlethread_workqueue(wq_name);
1769 ufshcd_clkscaling_init_sysfs(hba);
1772 static void ufshcd_exit_clk_scaling(struct ufs_hba *hba)
1774 if (!ufshcd_is_clkscaling_supported(hba))
1777 destroy_workqueue(hba->clk_scaling.workq);
1778 ufshcd_devfreq_remove(hba);
1781 static void ufshcd_init_clk_gating(struct ufs_hba *hba)
1783 char wq_name[sizeof("ufs_clk_gating_00")];
1785 if (!ufshcd_is_clkgating_allowed(hba))
1788 hba->clk_gating.delay_ms = 150;
1789 INIT_DELAYED_WORK(&hba->clk_gating.gate_work, ufshcd_gate_work);
1790 INIT_WORK(&hba->clk_gating.ungate_work, ufshcd_ungate_work);
1792 snprintf(wq_name, ARRAY_SIZE(wq_name), "ufs_clk_gating_%d",
1793 hba->host->host_no);
1794 hba->clk_gating.clk_gating_workq = alloc_ordered_workqueue(wq_name,
1797 hba->clk_gating.is_enabled = true;
1799 hba->clk_gating.delay_attr.show = ufshcd_clkgate_delay_show;
1800 hba->clk_gating.delay_attr.store = ufshcd_clkgate_delay_store;
1801 sysfs_attr_init(&hba->clk_gating.delay_attr.attr);
1802 hba->clk_gating.delay_attr.attr.name = "clkgate_delay_ms";
1803 hba->clk_gating.delay_attr.attr.mode = 0644;
1804 if (device_create_file(hba->dev, &hba->clk_gating.delay_attr))
1805 dev_err(hba->dev, "Failed to create sysfs for clkgate_delay\n");
1807 hba->clk_gating.enable_attr.show = ufshcd_clkgate_enable_show;
1808 hba->clk_gating.enable_attr.store = ufshcd_clkgate_enable_store;
1809 sysfs_attr_init(&hba->clk_gating.enable_attr.attr);
1810 hba->clk_gating.enable_attr.attr.name = "clkgate_enable";
1811 hba->clk_gating.enable_attr.attr.mode = 0644;
1812 if (device_create_file(hba->dev, &hba->clk_gating.enable_attr))
1813 dev_err(hba->dev, "Failed to create sysfs for clkgate_enable\n");
1816 static void ufshcd_exit_clk_gating(struct ufs_hba *hba)
1818 if (!ufshcd_is_clkgating_allowed(hba))
1820 device_remove_file(hba->dev, &hba->clk_gating.delay_attr);
1821 device_remove_file(hba->dev, &hba->clk_gating.enable_attr);
1822 cancel_work_sync(&hba->clk_gating.ungate_work);
1823 cancel_delayed_work_sync(&hba->clk_gating.gate_work);
1824 destroy_workqueue(hba->clk_gating.clk_gating_workq);
1827 /* Must be called with host lock acquired */
1828 static void ufshcd_clk_scaling_start_busy(struct ufs_hba *hba)
1830 bool queue_resume_work = false;
1832 if (!ufshcd_is_clkscaling_supported(hba))
1835 if (!hba->clk_scaling.active_reqs++)
1836 queue_resume_work = true;
1838 if (!hba->clk_scaling.is_allowed || hba->pm_op_in_progress)
1841 if (queue_resume_work)
1842 queue_work(hba->clk_scaling.workq,
1843 &hba->clk_scaling.resume_work);
1845 if (!hba->clk_scaling.window_start_t) {
1846 hba->clk_scaling.window_start_t = jiffies;
1847 hba->clk_scaling.tot_busy_t = 0;
1848 hba->clk_scaling.is_busy_started = false;
1851 if (!hba->clk_scaling.is_busy_started) {
1852 hba->clk_scaling.busy_start_t = ktime_get();
1853 hba->clk_scaling.is_busy_started = true;
1857 static void ufshcd_clk_scaling_update_busy(struct ufs_hba *hba)
1859 struct ufs_clk_scaling *scaling = &hba->clk_scaling;
1861 if (!ufshcd_is_clkscaling_supported(hba))
1864 if (!hba->outstanding_reqs && scaling->is_busy_started) {
1865 scaling->tot_busy_t += ktime_to_us(ktime_sub(ktime_get(),
1866 scaling->busy_start_t));
1867 scaling->busy_start_t = 0;
1868 scaling->is_busy_started = false;
1872 * ufshcd_send_command - Send SCSI or device management commands
1873 * @hba: per adapter instance
1874 * @task_tag: Task tag of the command
1877 void ufshcd_send_command(struct ufs_hba *hba, unsigned int task_tag)
1879 hba->lrb[task_tag].issue_time_stamp = ktime_get();
1880 hba->lrb[task_tag].compl_time_stamp = ktime_set(0, 0);
1881 ufshcd_clk_scaling_start_busy(hba);
1882 __set_bit(task_tag, &hba->outstanding_reqs);
1883 ufshcd_writel(hba, 1 << task_tag, REG_UTP_TRANSFER_REQ_DOOR_BELL);
1884 /* Make sure that doorbell is committed immediately */
1886 ufshcd_add_command_trace(hba, task_tag, "send");
1890 * ufshcd_copy_sense_data - Copy sense data in case of check condition
1891 * @lrbp: pointer to local reference block
1893 static inline void ufshcd_copy_sense_data(struct ufshcd_lrb *lrbp)
1896 if (lrbp->sense_buffer &&
1897 ufshcd_get_rsp_upiu_data_seg_len(lrbp->ucd_rsp_ptr)) {
1900 len = be16_to_cpu(lrbp->ucd_rsp_ptr->sr.sense_data_len);
1901 len_to_copy = min_t(int, UFS_SENSE_SIZE, len);
1903 memcpy(lrbp->sense_buffer, lrbp->ucd_rsp_ptr->sr.sense_data,
1909 * ufshcd_copy_query_response() - Copy the Query Response and the data
1911 * @hba: per adapter instance
1912 * @lrbp: pointer to local reference block
1915 int ufshcd_copy_query_response(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
1917 struct ufs_query_res *query_res = &hba->dev_cmd.query.response;
1919 memcpy(&query_res->upiu_res, &lrbp->ucd_rsp_ptr->qr, QUERY_OSF_SIZE);
1921 /* Get the descriptor */
1922 if (hba->dev_cmd.query.descriptor &&
1923 lrbp->ucd_rsp_ptr->qr.opcode == UPIU_QUERY_OPCODE_READ_DESC) {
1924 u8 *descp = (u8 *)lrbp->ucd_rsp_ptr +
1925 GENERAL_UPIU_REQUEST_SIZE;
1929 /* data segment length */
1930 resp_len = be32_to_cpu(lrbp->ucd_rsp_ptr->header.dword_2) &
1931 MASK_QUERY_DATA_SEG_LEN;
1932 buf_len = be16_to_cpu(
1933 hba->dev_cmd.query.request.upiu_req.length);
1934 if (likely(buf_len >= resp_len)) {
1935 memcpy(hba->dev_cmd.query.descriptor, descp, resp_len);
1938 "%s: Response size is bigger than buffer",
1948 * ufshcd_hba_capabilities - Read controller capabilities
1949 * @hba: per adapter instance
1951 static inline void ufshcd_hba_capabilities(struct ufs_hba *hba)
1953 hba->capabilities = ufshcd_readl(hba, REG_CONTROLLER_CAPABILITIES);
1955 /* nutrs and nutmrs are 0 based values */
1956 hba->nutrs = (hba->capabilities & MASK_TRANSFER_REQUESTS_SLOTS) + 1;
1958 ((hba->capabilities & MASK_TASK_MANAGEMENT_REQUEST_SLOTS) >> 16) + 1;
1962 * ufshcd_ready_for_uic_cmd - Check if controller is ready
1963 * to accept UIC commands
1964 * @hba: per adapter instance
1965 * Return true on success, else false
1967 static inline bool ufshcd_ready_for_uic_cmd(struct ufs_hba *hba)
1969 if (ufshcd_readl(hba, REG_CONTROLLER_STATUS) & UIC_COMMAND_READY)
1976 * ufshcd_get_upmcrs - Get the power mode change request status
1977 * @hba: Pointer to adapter instance
1979 * This function gets the UPMCRS field of HCS register
1980 * Returns value of UPMCRS field
1982 static inline u8 ufshcd_get_upmcrs(struct ufs_hba *hba)
1984 return (ufshcd_readl(hba, REG_CONTROLLER_STATUS) >> 8) & 0x7;
1988 * ufshcd_dispatch_uic_cmd - Dispatch UIC commands to unipro layers
1989 * @hba: per adapter instance
1990 * @uic_cmd: UIC command
1992 * Mutex must be held.
1995 ufshcd_dispatch_uic_cmd(struct ufs_hba *hba, struct uic_command *uic_cmd)
1997 WARN_ON(hba->active_uic_cmd);
1999 hba->active_uic_cmd = uic_cmd;
2002 ufshcd_writel(hba, uic_cmd->argument1, REG_UIC_COMMAND_ARG_1);
2003 ufshcd_writel(hba, uic_cmd->argument2, REG_UIC_COMMAND_ARG_2);
2004 ufshcd_writel(hba, uic_cmd->argument3, REG_UIC_COMMAND_ARG_3);
2007 ufshcd_writel(hba, uic_cmd->command & COMMAND_OPCODE_MASK,
2012 * ufshcd_wait_for_uic_cmd - Wait complectioin of UIC command
2013 * @hba: per adapter instance
2014 * @uic_cmd: UIC command
2016 * Must be called with mutex held.
2017 * Returns 0 only if success.
2020 ufshcd_wait_for_uic_cmd(struct ufs_hba *hba, struct uic_command *uic_cmd)
2023 unsigned long flags;
2025 if (wait_for_completion_timeout(&uic_cmd->done,
2026 msecs_to_jiffies(UIC_CMD_TIMEOUT)))
2027 ret = uic_cmd->argument2 & MASK_UIC_COMMAND_RESULT;
2031 spin_lock_irqsave(hba->host->host_lock, flags);
2032 hba->active_uic_cmd = NULL;
2033 spin_unlock_irqrestore(hba->host->host_lock, flags);
2039 * __ufshcd_send_uic_cmd - Send UIC commands and retrieve the result
2040 * @hba: per adapter instance
2041 * @uic_cmd: UIC command
2042 * @completion: initialize the completion only if this is set to true
2044 * Identical to ufshcd_send_uic_cmd() expect mutex. Must be called
2045 * with mutex held and host_lock locked.
2046 * Returns 0 only if success.
2049 __ufshcd_send_uic_cmd(struct ufs_hba *hba, struct uic_command *uic_cmd,
2052 if (!ufshcd_ready_for_uic_cmd(hba)) {
2054 "Controller not ready to accept UIC commands\n");
2059 init_completion(&uic_cmd->done);
2061 ufshcd_dispatch_uic_cmd(hba, uic_cmd);
2067 * ufshcd_send_uic_cmd - Send UIC commands and retrieve the result
2068 * @hba: per adapter instance
2069 * @uic_cmd: UIC command
2071 * Returns 0 only if success.
2073 int ufshcd_send_uic_cmd(struct ufs_hba *hba, struct uic_command *uic_cmd)
2076 unsigned long flags;
2078 ufshcd_hold(hba, false);
2079 mutex_lock(&hba->uic_cmd_mutex);
2080 ufshcd_add_delay_before_dme_cmd(hba);
2082 spin_lock_irqsave(hba->host->host_lock, flags);
2083 ret = __ufshcd_send_uic_cmd(hba, uic_cmd, true);
2084 spin_unlock_irqrestore(hba->host->host_lock, flags);
2086 ret = ufshcd_wait_for_uic_cmd(hba, uic_cmd);
2088 mutex_unlock(&hba->uic_cmd_mutex);
2090 ufshcd_release(hba);
2095 * ufshcd_map_sg - Map scatter-gather list to prdt
2096 * @hba: per adapter instance
2097 * @lrbp: pointer to local reference block
2099 * Returns 0 in case of success, non-zero value in case of failure
2101 static int ufshcd_map_sg(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
2103 struct ufshcd_sg_entry *prd_table;
2104 struct scatterlist *sg;
2105 struct scsi_cmnd *cmd;
2110 sg_segments = scsi_dma_map(cmd);
2111 if (sg_segments < 0)
2115 if (hba->quirks & UFSHCD_QUIRK_PRDT_BYTE_GRAN)
2116 lrbp->utr_descriptor_ptr->prd_table_length =
2117 cpu_to_le16((u16)(sg_segments *
2118 sizeof(struct ufshcd_sg_entry)));
2120 lrbp->utr_descriptor_ptr->prd_table_length =
2121 cpu_to_le16((u16) (sg_segments));
2123 prd_table = (struct ufshcd_sg_entry *)lrbp->ucd_prdt_ptr;
2125 scsi_for_each_sg(cmd, sg, sg_segments, i) {
2127 cpu_to_le32(((u32) sg_dma_len(sg))-1);
2128 prd_table[i].base_addr =
2129 cpu_to_le32(lower_32_bits(sg->dma_address));
2130 prd_table[i].upper_addr =
2131 cpu_to_le32(upper_32_bits(sg->dma_address));
2132 prd_table[i].reserved = 0;
2135 lrbp->utr_descriptor_ptr->prd_table_length = 0;
2142 * ufshcd_enable_intr - enable interrupts
2143 * @hba: per adapter instance
2144 * @intrs: interrupt bits
2146 static void ufshcd_enable_intr(struct ufs_hba *hba, u32 intrs)
2148 u32 set = ufshcd_readl(hba, REG_INTERRUPT_ENABLE);
2150 if (hba->ufs_version == UFSHCI_VERSION_10) {
2152 rw = set & INTERRUPT_MASK_RW_VER_10;
2153 set = rw | ((set ^ intrs) & intrs);
2158 ufshcd_writel(hba, set, REG_INTERRUPT_ENABLE);
2162 * ufshcd_disable_intr - disable interrupts
2163 * @hba: per adapter instance
2164 * @intrs: interrupt bits
2166 static void ufshcd_disable_intr(struct ufs_hba *hba, u32 intrs)
2168 u32 set = ufshcd_readl(hba, REG_INTERRUPT_ENABLE);
2170 if (hba->ufs_version == UFSHCI_VERSION_10) {
2172 rw = (set & INTERRUPT_MASK_RW_VER_10) &
2173 ~(intrs & INTERRUPT_MASK_RW_VER_10);
2174 set = rw | ((set & intrs) & ~INTERRUPT_MASK_RW_VER_10);
2180 ufshcd_writel(hba, set, REG_INTERRUPT_ENABLE);
2184 * ufshcd_prepare_req_desc_hdr() - Fills the requests header
2185 * descriptor according to request
2186 * @lrbp: pointer to local reference block
2187 * @upiu_flags: flags required in the header
2188 * @cmd_dir: requests data direction
2190 static void ufshcd_prepare_req_desc_hdr(struct ufshcd_lrb *lrbp,
2191 u32 *upiu_flags, enum dma_data_direction cmd_dir)
2193 struct utp_transfer_req_desc *req_desc = lrbp->utr_descriptor_ptr;
2197 if (cmd_dir == DMA_FROM_DEVICE) {
2198 data_direction = UTP_DEVICE_TO_HOST;
2199 *upiu_flags = UPIU_CMD_FLAGS_READ;
2200 } else if (cmd_dir == DMA_TO_DEVICE) {
2201 data_direction = UTP_HOST_TO_DEVICE;
2202 *upiu_flags = UPIU_CMD_FLAGS_WRITE;
2204 data_direction = UTP_NO_DATA_TRANSFER;
2205 *upiu_flags = UPIU_CMD_FLAGS_NONE;
2208 dword_0 = data_direction | (lrbp->command_type
2209 << UPIU_COMMAND_TYPE_OFFSET);
2211 dword_0 |= UTP_REQ_DESC_INT_CMD;
2213 /* Transfer request descriptor header fields */
2214 req_desc->header.dword_0 = cpu_to_le32(dword_0);
2215 /* dword_1 is reserved, hence it is set to 0 */
2216 req_desc->header.dword_1 = 0;
2218 * assigning invalid value for command status. Controller
2219 * updates OCS on command completion, with the command
2222 req_desc->header.dword_2 =
2223 cpu_to_le32(OCS_INVALID_COMMAND_STATUS);
2224 /* dword_3 is reserved, hence it is set to 0 */
2225 req_desc->header.dword_3 = 0;
2227 req_desc->prd_table_length = 0;
2231 * ufshcd_prepare_utp_scsi_cmd_upiu() - fills the utp_transfer_req_desc,
2233 * @lrbp: local reference block pointer
2234 * @upiu_flags: flags
2237 void ufshcd_prepare_utp_scsi_cmd_upiu(struct ufshcd_lrb *lrbp, u32 upiu_flags)
2239 struct utp_upiu_req *ucd_req_ptr = lrbp->ucd_req_ptr;
2240 unsigned short cdb_len;
2242 /* command descriptor fields */
2243 ucd_req_ptr->header.dword_0 = UPIU_HEADER_DWORD(
2244 UPIU_TRANSACTION_COMMAND, upiu_flags,
2245 lrbp->lun, lrbp->task_tag);
2246 ucd_req_ptr->header.dword_1 = UPIU_HEADER_DWORD(
2247 UPIU_COMMAND_SET_TYPE_SCSI, 0, 0, 0);
2249 /* Total EHS length and Data segment length will be zero */
2250 ucd_req_ptr->header.dword_2 = 0;
2252 ucd_req_ptr->sc.exp_data_transfer_len =
2253 cpu_to_be32(lrbp->cmd->sdb.length);
2255 cdb_len = min_t(unsigned short, lrbp->cmd->cmd_len, UFS_CDB_SIZE);
2256 memset(ucd_req_ptr->sc.cdb, 0, UFS_CDB_SIZE);
2257 memcpy(ucd_req_ptr->sc.cdb, lrbp->cmd->cmnd, cdb_len);
2259 memset(lrbp->ucd_rsp_ptr, 0, sizeof(struct utp_upiu_rsp));
2263 * ufshcd_prepare_utp_query_req_upiu() - fills the utp_transfer_req_desc,
2266 * @lrbp: local reference block pointer
2267 * @upiu_flags: flags
2269 static void ufshcd_prepare_utp_query_req_upiu(struct ufs_hba *hba,
2270 struct ufshcd_lrb *lrbp, u32 upiu_flags)
2272 struct utp_upiu_req *ucd_req_ptr = lrbp->ucd_req_ptr;
2273 struct ufs_query *query = &hba->dev_cmd.query;
2274 u16 len = be16_to_cpu(query->request.upiu_req.length);
2276 /* Query request header */
2277 ucd_req_ptr->header.dword_0 = UPIU_HEADER_DWORD(
2278 UPIU_TRANSACTION_QUERY_REQ, upiu_flags,
2279 lrbp->lun, lrbp->task_tag);
2280 ucd_req_ptr->header.dword_1 = UPIU_HEADER_DWORD(
2281 0, query->request.query_func, 0, 0);
2283 /* Data segment length only need for WRITE_DESC */
2284 if (query->request.upiu_req.opcode == UPIU_QUERY_OPCODE_WRITE_DESC)
2285 ucd_req_ptr->header.dword_2 =
2286 UPIU_HEADER_DWORD(0, 0, (len >> 8), (u8)len);
2288 ucd_req_ptr->header.dword_2 = 0;
2290 /* Copy the Query Request buffer as is */
2291 memcpy(&ucd_req_ptr->qr, &query->request.upiu_req,
2294 /* Copy the Descriptor */
2295 if (query->request.upiu_req.opcode == UPIU_QUERY_OPCODE_WRITE_DESC)
2296 memcpy(ucd_req_ptr + 1, query->descriptor, len);
2298 memset(lrbp->ucd_rsp_ptr, 0, sizeof(struct utp_upiu_rsp));
2301 static inline void ufshcd_prepare_utp_nop_upiu(struct ufshcd_lrb *lrbp)
2303 struct utp_upiu_req *ucd_req_ptr = lrbp->ucd_req_ptr;
2305 memset(ucd_req_ptr, 0, sizeof(struct utp_upiu_req));
2307 /* command descriptor fields */
2308 ucd_req_ptr->header.dword_0 =
2310 UPIU_TRANSACTION_NOP_OUT, 0, 0, lrbp->task_tag);
2311 /* clear rest of the fields of basic header */
2312 ucd_req_ptr->header.dword_1 = 0;
2313 ucd_req_ptr->header.dword_2 = 0;
2315 memset(lrbp->ucd_rsp_ptr, 0, sizeof(struct utp_upiu_rsp));
2319 * ufshcd_comp_devman_upiu - UFS Protocol Information Unit(UPIU)
2320 * for Device Management Purposes
2321 * @hba: per adapter instance
2322 * @lrbp: pointer to local reference block
2324 static int ufshcd_comp_devman_upiu(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
2329 if ((hba->ufs_version == UFSHCI_VERSION_10) ||
2330 (hba->ufs_version == UFSHCI_VERSION_11))
2331 lrbp->command_type = UTP_CMD_TYPE_DEV_MANAGE;
2333 lrbp->command_type = UTP_CMD_TYPE_UFS_STORAGE;
2335 ufshcd_prepare_req_desc_hdr(lrbp, &upiu_flags, DMA_NONE);
2336 if (hba->dev_cmd.type == DEV_CMD_TYPE_QUERY)
2337 ufshcd_prepare_utp_query_req_upiu(hba, lrbp, upiu_flags);
2338 else if (hba->dev_cmd.type == DEV_CMD_TYPE_NOP)
2339 ufshcd_prepare_utp_nop_upiu(lrbp);
2347 * ufshcd_comp_scsi_upiu - UFS Protocol Information Unit(UPIU)
2349 * @hba: per adapter instance
2350 * @lrbp: pointer to local reference block
2352 static int ufshcd_comp_scsi_upiu(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
2357 if ((hba->ufs_version == UFSHCI_VERSION_10) ||
2358 (hba->ufs_version == UFSHCI_VERSION_11))
2359 lrbp->command_type = UTP_CMD_TYPE_SCSI;
2361 lrbp->command_type = UTP_CMD_TYPE_UFS_STORAGE;
2363 if (likely(lrbp->cmd)) {
2364 ufshcd_prepare_req_desc_hdr(lrbp, &upiu_flags,
2365 lrbp->cmd->sc_data_direction);
2366 ufshcd_prepare_utp_scsi_cmd_upiu(lrbp, upiu_flags);
2375 * ufshcd_upiu_wlun_to_scsi_wlun - maps UPIU W-LUN id to SCSI W-LUN ID
2376 * @upiu_wlun_id: UPIU W-LUN id
2378 * Returns SCSI W-LUN id
2380 static inline u16 ufshcd_upiu_wlun_to_scsi_wlun(u8 upiu_wlun_id)
2382 return (upiu_wlun_id & ~UFS_UPIU_WLUN_ID) | SCSI_W_LUN_BASE;
2386 * ufshcd_queuecommand - main entry point for SCSI requests
2387 * @host: SCSI host pointer
2388 * @cmd: command from SCSI Midlayer
2390 * Returns 0 for success, non-zero in case of failure
2392 static int ufshcd_queuecommand(struct Scsi_Host *host, struct scsi_cmnd *cmd)
2394 struct ufshcd_lrb *lrbp;
2395 struct ufs_hba *hba;
2396 unsigned long flags;
2400 hba = shost_priv(host);
2402 tag = cmd->request->tag;
2403 if (!ufshcd_valid_tag(hba, tag)) {
2405 "%s: invalid command tag %d: cmd=0x%p, cmd->request=0x%p",
2406 __func__, tag, cmd, cmd->request);
2410 if (!down_read_trylock(&hba->clk_scaling_lock))
2411 return SCSI_MLQUEUE_HOST_BUSY;
2413 spin_lock_irqsave(hba->host->host_lock, flags);
2414 switch (hba->ufshcd_state) {
2415 case UFSHCD_STATE_OPERATIONAL:
2417 case UFSHCD_STATE_EH_SCHEDULED:
2418 case UFSHCD_STATE_RESET:
2419 err = SCSI_MLQUEUE_HOST_BUSY;
2421 case UFSHCD_STATE_ERROR:
2422 set_host_byte(cmd, DID_ERROR);
2423 cmd->scsi_done(cmd);
2426 dev_WARN_ONCE(hba->dev, 1, "%s: invalid state %d\n",
2427 __func__, hba->ufshcd_state);
2428 set_host_byte(cmd, DID_BAD_TARGET);
2429 cmd->scsi_done(cmd);
2433 /* if error handling is in progress, don't issue commands */
2434 if (ufshcd_eh_in_progress(hba)) {
2435 set_host_byte(cmd, DID_ERROR);
2436 cmd->scsi_done(cmd);
2439 spin_unlock_irqrestore(hba->host->host_lock, flags);
2441 hba->req_abort_count = 0;
2443 /* acquire the tag to make sure device cmds don't use it */
2444 if (test_and_set_bit_lock(tag, &hba->lrb_in_use)) {
2446 * Dev manage command in progress, requeue the command.
2447 * Requeuing the command helps in cases where the request *may*
2448 * find different tag instead of waiting for dev manage command
2451 err = SCSI_MLQUEUE_HOST_BUSY;
2455 err = ufshcd_hold(hba, true);
2457 err = SCSI_MLQUEUE_HOST_BUSY;
2458 clear_bit_unlock(tag, &hba->lrb_in_use);
2461 WARN_ON(hba->clk_gating.state != CLKS_ON);
2463 lrbp = &hba->lrb[tag];
2467 lrbp->sense_bufflen = UFS_SENSE_SIZE;
2468 lrbp->sense_buffer = cmd->sense_buffer;
2469 lrbp->task_tag = tag;
2470 lrbp->lun = ufshcd_scsi_to_upiu_lun(cmd->device->lun);
2471 lrbp->intr_cmd = !ufshcd_is_intr_aggr_allowed(hba) ? true : false;
2472 lrbp->req_abort_skip = false;
2474 ufshcd_comp_scsi_upiu(hba, lrbp);
2476 err = ufshcd_map_sg(hba, lrbp);
2479 clear_bit_unlock(tag, &hba->lrb_in_use);
2482 /* Make sure descriptors are ready before ringing the doorbell */
2485 /* issue command to the controller */
2486 spin_lock_irqsave(hba->host->host_lock, flags);
2487 ufshcd_vops_setup_xfer_req(hba, tag, (lrbp->cmd ? true : false));
2488 ufshcd_send_command(hba, tag);
2490 spin_unlock_irqrestore(hba->host->host_lock, flags);
2492 up_read(&hba->clk_scaling_lock);
2496 static int ufshcd_compose_dev_cmd(struct ufs_hba *hba,
2497 struct ufshcd_lrb *lrbp, enum dev_cmd_type cmd_type, int tag)
2500 lrbp->sense_bufflen = 0;
2501 lrbp->sense_buffer = NULL;
2502 lrbp->task_tag = tag;
2503 lrbp->lun = 0; /* device management cmd is not specific to any LUN */
2504 lrbp->intr_cmd = true; /* No interrupt aggregation */
2505 hba->dev_cmd.type = cmd_type;
2507 return ufshcd_comp_devman_upiu(hba, lrbp);
2511 ufshcd_clear_cmd(struct ufs_hba *hba, int tag)
2514 unsigned long flags;
2515 u32 mask = 1 << tag;
2517 /* clear outstanding transaction before retry */
2518 spin_lock_irqsave(hba->host->host_lock, flags);
2519 ufshcd_utrl_clear(hba, tag);
2520 spin_unlock_irqrestore(hba->host->host_lock, flags);
2523 * wait for for h/w to clear corresponding bit in door-bell.
2524 * max. wait is 1 sec.
2526 err = ufshcd_wait_for_register(hba,
2527 REG_UTP_TRANSFER_REQ_DOOR_BELL,
2528 mask, ~mask, 1000, 1000, true);
2534 ufshcd_check_query_response(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
2536 struct ufs_query_res *query_res = &hba->dev_cmd.query.response;
2538 /* Get the UPIU response */
2539 query_res->response = ufshcd_get_rsp_upiu_result(lrbp->ucd_rsp_ptr) >>
2540 UPIU_RSP_CODE_OFFSET;
2541 return query_res->response;
2545 * ufshcd_dev_cmd_completion() - handles device management command responses
2546 * @hba: per adapter instance
2547 * @lrbp: pointer to local reference block
2550 ufshcd_dev_cmd_completion(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
2555 hba->ufs_stats.last_hibern8_exit_tstamp = ktime_set(0, 0);
2556 resp = ufshcd_get_req_rsp(lrbp->ucd_rsp_ptr);
2559 case UPIU_TRANSACTION_NOP_IN:
2560 if (hba->dev_cmd.type != DEV_CMD_TYPE_NOP) {
2562 dev_err(hba->dev, "%s: unexpected response %x\n",
2566 case UPIU_TRANSACTION_QUERY_RSP:
2567 err = ufshcd_check_query_response(hba, lrbp);
2569 err = ufshcd_copy_query_response(hba, lrbp);
2571 case UPIU_TRANSACTION_REJECT_UPIU:
2572 /* TODO: handle Reject UPIU Response */
2574 dev_err(hba->dev, "%s: Reject UPIU not fully implemented\n",
2579 dev_err(hba->dev, "%s: Invalid device management cmd response: %x\n",
2587 static int ufshcd_wait_for_dev_cmd(struct ufs_hba *hba,
2588 struct ufshcd_lrb *lrbp, int max_timeout)
2591 unsigned long time_left;
2592 unsigned long flags;
2594 time_left = wait_for_completion_timeout(hba->dev_cmd.complete,
2595 msecs_to_jiffies(max_timeout));
2597 /* Make sure descriptors are ready before ringing the doorbell */
2599 spin_lock_irqsave(hba->host->host_lock, flags);
2600 hba->dev_cmd.complete = NULL;
2601 if (likely(time_left)) {
2602 err = ufshcd_get_tr_ocs(lrbp);
2604 err = ufshcd_dev_cmd_completion(hba, lrbp);
2606 spin_unlock_irqrestore(hba->host->host_lock, flags);
2610 dev_dbg(hba->dev, "%s: dev_cmd request timedout, tag %d\n",
2611 __func__, lrbp->task_tag);
2612 if (!ufshcd_clear_cmd(hba, lrbp->task_tag))
2613 /* successfully cleared the command, retry if needed */
2616 * in case of an error, after clearing the doorbell,
2617 * we also need to clear the outstanding_request
2620 ufshcd_outstanding_req_clear(hba, lrbp->task_tag);
2627 * ufshcd_get_dev_cmd_tag - Get device management command tag
2628 * @hba: per-adapter instance
2629 * @tag_out: pointer to variable with available slot value
2631 * Get a free slot and lock it until device management command
2634 * Returns false if free slot is unavailable for locking, else
2635 * return true with tag value in @tag.
2637 static bool ufshcd_get_dev_cmd_tag(struct ufs_hba *hba, int *tag_out)
2647 tmp = ~hba->lrb_in_use;
2648 tag = find_last_bit(&tmp, hba->nutrs);
2649 if (tag >= hba->nutrs)
2651 } while (test_and_set_bit_lock(tag, &hba->lrb_in_use));
2659 static inline void ufshcd_put_dev_cmd_tag(struct ufs_hba *hba, int tag)
2661 clear_bit_unlock(tag, &hba->lrb_in_use);
2665 * ufshcd_exec_dev_cmd - API for sending device management requests
2667 * @cmd_type: specifies the type (NOP, Query...)
2668 * @timeout: time in seconds
2670 * NOTE: Since there is only one available tag for device management commands,
2671 * it is expected you hold the hba->dev_cmd.lock mutex.
2673 static int ufshcd_exec_dev_cmd(struct ufs_hba *hba,
2674 enum dev_cmd_type cmd_type, int timeout)
2676 struct ufshcd_lrb *lrbp;
2679 struct completion wait;
2680 unsigned long flags;
2682 down_read(&hba->clk_scaling_lock);
2685 * Get free slot, sleep if slots are unavailable.
2686 * Even though we use wait_event() which sleeps indefinitely,
2687 * the maximum wait time is bounded by SCSI request timeout.
2689 wait_event(hba->dev_cmd.tag_wq, ufshcd_get_dev_cmd_tag(hba, &tag));
2691 init_completion(&wait);
2692 lrbp = &hba->lrb[tag];
2694 err = ufshcd_compose_dev_cmd(hba, lrbp, cmd_type, tag);
2698 hba->dev_cmd.complete = &wait;
2700 ufshcd_add_query_upiu_trace(hba, tag, "query_send");
2701 /* Make sure descriptors are ready before ringing the doorbell */
2703 spin_lock_irqsave(hba->host->host_lock, flags);
2704 ufshcd_vops_setup_xfer_req(hba, tag, (lrbp->cmd ? true : false));
2705 ufshcd_send_command(hba, tag);
2706 spin_unlock_irqrestore(hba->host->host_lock, flags);
2708 err = ufshcd_wait_for_dev_cmd(hba, lrbp, timeout);
2710 ufshcd_add_query_upiu_trace(hba, tag,
2711 err ? "query_complete_err" : "query_complete");
2714 ufshcd_put_dev_cmd_tag(hba, tag);
2715 wake_up(&hba->dev_cmd.tag_wq);
2716 up_read(&hba->clk_scaling_lock);
2721 * ufshcd_init_query() - init the query response and request parameters
2722 * @hba: per-adapter instance
2723 * @request: address of the request pointer to be initialized
2724 * @response: address of the response pointer to be initialized
2725 * @opcode: operation to perform
2726 * @idn: flag idn to access
2727 * @index: LU number to access
2728 * @selector: query/flag/descriptor further identification
2730 static inline void ufshcd_init_query(struct ufs_hba *hba,
2731 struct ufs_query_req **request, struct ufs_query_res **response,
2732 enum query_opcode opcode, u8 idn, u8 index, u8 selector)
2734 *request = &hba->dev_cmd.query.request;
2735 *response = &hba->dev_cmd.query.response;
2736 memset(*request, 0, sizeof(struct ufs_query_req));
2737 memset(*response, 0, sizeof(struct ufs_query_res));
2738 (*request)->upiu_req.opcode = opcode;
2739 (*request)->upiu_req.idn = idn;
2740 (*request)->upiu_req.index = index;
2741 (*request)->upiu_req.selector = selector;
2744 static int ufshcd_query_flag_retry(struct ufs_hba *hba,
2745 enum query_opcode opcode, enum flag_idn idn, bool *flag_res)
2750 for (retries = 0; retries < QUERY_REQ_RETRIES; retries++) {
2751 ret = ufshcd_query_flag(hba, opcode, idn, flag_res);
2754 "%s: failed with error %d, retries %d\n",
2755 __func__, ret, retries);
2762 "%s: query attribute, opcode %d, idn %d, failed with error %d after %d retires\n",
2763 __func__, opcode, idn, ret, retries);
2768 * ufshcd_query_flag() - API function for sending flag query requests
2769 * @hba: per-adapter instance
2770 * @opcode: flag query to perform
2771 * @idn: flag idn to access
2772 * @flag_res: the flag value after the query request completes
2774 * Returns 0 for success, non-zero in case of failure
2776 int ufshcd_query_flag(struct ufs_hba *hba, enum query_opcode opcode,
2777 enum flag_idn idn, bool *flag_res)
2779 struct ufs_query_req *request = NULL;
2780 struct ufs_query_res *response = NULL;
2781 int err, index = 0, selector = 0;
2782 int timeout = QUERY_REQ_TIMEOUT;
2786 ufshcd_hold(hba, false);
2787 mutex_lock(&hba->dev_cmd.lock);
2788 ufshcd_init_query(hba, &request, &response, opcode, idn, index,
2792 case UPIU_QUERY_OPCODE_SET_FLAG:
2793 case UPIU_QUERY_OPCODE_CLEAR_FLAG:
2794 case UPIU_QUERY_OPCODE_TOGGLE_FLAG:
2795 request->query_func = UPIU_QUERY_FUNC_STANDARD_WRITE_REQUEST;
2797 case UPIU_QUERY_OPCODE_READ_FLAG:
2798 request->query_func = UPIU_QUERY_FUNC_STANDARD_READ_REQUEST;
2800 /* No dummy reads */
2801 dev_err(hba->dev, "%s: Invalid argument for read request\n",
2809 "%s: Expected query flag opcode but got = %d\n",
2815 err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_QUERY, timeout);
2819 "%s: Sending flag query for idn %d failed, err = %d\n",
2820 __func__, idn, err);
2825 *flag_res = (be32_to_cpu(response->upiu_res.value) &
2826 MASK_QUERY_UPIU_FLAG_LOC) & 0x1;
2829 mutex_unlock(&hba->dev_cmd.lock);
2830 ufshcd_release(hba);
2835 * ufshcd_query_attr - API function for sending attribute requests
2836 * @hba: per-adapter instance
2837 * @opcode: attribute opcode
2838 * @idn: attribute idn to access
2839 * @index: index field
2840 * @selector: selector field
2841 * @attr_val: the attribute value after the query request completes
2843 * Returns 0 for success, non-zero in case of failure
2845 int ufshcd_query_attr(struct ufs_hba *hba, enum query_opcode opcode,
2846 enum attr_idn idn, u8 index, u8 selector, u32 *attr_val)
2848 struct ufs_query_req *request = NULL;
2849 struct ufs_query_res *response = NULL;
2854 ufshcd_hold(hba, false);
2856 dev_err(hba->dev, "%s: attribute value required for opcode 0x%x\n",
2862 mutex_lock(&hba->dev_cmd.lock);
2863 ufshcd_init_query(hba, &request, &response, opcode, idn, index,
2867 case UPIU_QUERY_OPCODE_WRITE_ATTR:
2868 request->query_func = UPIU_QUERY_FUNC_STANDARD_WRITE_REQUEST;
2869 request->upiu_req.value = cpu_to_be32(*attr_val);
2871 case UPIU_QUERY_OPCODE_READ_ATTR:
2872 request->query_func = UPIU_QUERY_FUNC_STANDARD_READ_REQUEST;
2875 dev_err(hba->dev, "%s: Expected query attr opcode but got = 0x%.2x\n",
2881 err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_QUERY, QUERY_REQ_TIMEOUT);
2884 dev_err(hba->dev, "%s: opcode 0x%.2x for idn %d failed, index %d, err = %d\n",
2885 __func__, opcode, idn, index, err);
2889 *attr_val = be32_to_cpu(response->upiu_res.value);
2892 mutex_unlock(&hba->dev_cmd.lock);
2894 ufshcd_release(hba);
2899 * ufshcd_query_attr_retry() - API function for sending query
2900 * attribute with retries
2901 * @hba: per-adapter instance
2902 * @opcode: attribute opcode
2903 * @idn: attribute idn to access
2904 * @index: index field
2905 * @selector: selector field
2906 * @attr_val: the attribute value after the query request
2909 * Returns 0 for success, non-zero in case of failure
2911 static int ufshcd_query_attr_retry(struct ufs_hba *hba,
2912 enum query_opcode opcode, enum attr_idn idn, u8 index, u8 selector,
2918 for (retries = QUERY_REQ_RETRIES; retries > 0; retries--) {
2919 ret = ufshcd_query_attr(hba, opcode, idn, index,
2920 selector, attr_val);
2922 dev_dbg(hba->dev, "%s: failed with error %d, retries %d\n",
2923 __func__, ret, retries);
2930 "%s: query attribute, idn %d, failed with error %d after %d retires\n",
2931 __func__, idn, ret, QUERY_REQ_RETRIES);
2935 static int __ufshcd_query_descriptor(struct ufs_hba *hba,
2936 enum query_opcode opcode, enum desc_idn idn, u8 index,
2937 u8 selector, u8 *desc_buf, int *buf_len)
2939 struct ufs_query_req *request = NULL;
2940 struct ufs_query_res *response = NULL;
2945 ufshcd_hold(hba, false);
2947 dev_err(hba->dev, "%s: descriptor buffer required for opcode 0x%x\n",
2953 if (*buf_len < QUERY_DESC_MIN_SIZE || *buf_len > QUERY_DESC_MAX_SIZE) {
2954 dev_err(hba->dev, "%s: descriptor buffer size (%d) is out of range\n",
2955 __func__, *buf_len);
2960 mutex_lock(&hba->dev_cmd.lock);
2961 ufshcd_init_query(hba, &request, &response, opcode, idn, index,
2963 hba->dev_cmd.query.descriptor = desc_buf;
2964 request->upiu_req.length = cpu_to_be16(*buf_len);
2967 case UPIU_QUERY_OPCODE_WRITE_DESC:
2968 request->query_func = UPIU_QUERY_FUNC_STANDARD_WRITE_REQUEST;
2970 case UPIU_QUERY_OPCODE_READ_DESC:
2971 request->query_func = UPIU_QUERY_FUNC_STANDARD_READ_REQUEST;
2975 "%s: Expected query descriptor opcode but got = 0x%.2x\n",
2981 err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_QUERY, QUERY_REQ_TIMEOUT);
2984 dev_err(hba->dev, "%s: opcode 0x%.2x for idn %d failed, index %d, err = %d\n",
2985 __func__, opcode, idn, index, err);
2989 hba->dev_cmd.query.descriptor = NULL;
2990 *buf_len = be16_to_cpu(response->upiu_res.length);
2993 mutex_unlock(&hba->dev_cmd.lock);
2995 ufshcd_release(hba);
3000 * ufshcd_query_descriptor_retry - API function for sending descriptor requests
3001 * @hba: per-adapter instance
3002 * @opcode: attribute opcode
3003 * @idn: attribute idn to access
3004 * @index: index field
3005 * @selector: selector field
3006 * @desc_buf: the buffer that contains the descriptor
3007 * @buf_len: length parameter passed to the device
3009 * Returns 0 for success, non-zero in case of failure.
3010 * The buf_len parameter will contain, on return, the length parameter
3011 * received on the response.
3013 int ufshcd_query_descriptor_retry(struct ufs_hba *hba,
3014 enum query_opcode opcode,
3015 enum desc_idn idn, u8 index,
3017 u8 *desc_buf, int *buf_len)
3022 for (retries = QUERY_REQ_RETRIES; retries > 0; retries--) {
3023 err = __ufshcd_query_descriptor(hba, opcode, idn, index,
3024 selector, desc_buf, buf_len);
3025 if (!err || err == -EINVAL)
3033 * ufshcd_read_desc_length - read the specified descriptor length from header
3034 * @hba: Pointer to adapter instance
3035 * @desc_id: descriptor idn value
3036 * @desc_index: descriptor index
3037 * @desc_length: pointer to variable to read the length of descriptor
3039 * Return 0 in case of success, non-zero otherwise
3041 static int ufshcd_read_desc_length(struct ufs_hba *hba,
3042 enum desc_idn desc_id,
3047 u8 header[QUERY_DESC_HDR_SIZE];
3048 int header_len = QUERY_DESC_HDR_SIZE;
3050 if (desc_id >= QUERY_DESC_IDN_MAX)
3053 ret = ufshcd_query_descriptor_retry(hba, UPIU_QUERY_OPCODE_READ_DESC,
3054 desc_id, desc_index, 0, header,
3058 dev_err(hba->dev, "%s: Failed to get descriptor header id %d",
3061 } else if (desc_id != header[QUERY_DESC_DESC_TYPE_OFFSET]) {
3062 dev_warn(hba->dev, "%s: descriptor header id %d and desc_id %d mismatch",
3063 __func__, header[QUERY_DESC_DESC_TYPE_OFFSET],
3068 *desc_length = header[QUERY_DESC_LENGTH_OFFSET];
3074 * ufshcd_map_desc_id_to_length - map descriptor IDN to its length
3075 * @hba: Pointer to adapter instance
3076 * @desc_id: descriptor idn value
3077 * @desc_len: mapped desc length (out)
3079 * Return 0 in case of success, non-zero otherwise
3081 int ufshcd_map_desc_id_to_length(struct ufs_hba *hba,
3082 enum desc_idn desc_id, int *desc_len)
3085 case QUERY_DESC_IDN_DEVICE:
3086 *desc_len = hba->desc_size.dev_desc;
3088 case QUERY_DESC_IDN_POWER:
3089 *desc_len = hba->desc_size.pwr_desc;
3091 case QUERY_DESC_IDN_GEOMETRY:
3092 *desc_len = hba->desc_size.geom_desc;
3094 case QUERY_DESC_IDN_CONFIGURATION:
3095 *desc_len = hba->desc_size.conf_desc;
3097 case QUERY_DESC_IDN_UNIT:
3098 *desc_len = hba->desc_size.unit_desc;
3100 case QUERY_DESC_IDN_INTERCONNECT:
3101 *desc_len = hba->desc_size.interc_desc;
3103 case QUERY_DESC_IDN_STRING:
3104 *desc_len = QUERY_DESC_MAX_SIZE;
3106 case QUERY_DESC_IDN_HEALTH:
3107 *desc_len = hba->desc_size.hlth_desc;
3109 case QUERY_DESC_IDN_RFU_0:
3110 case QUERY_DESC_IDN_RFU_1:
3119 EXPORT_SYMBOL(ufshcd_map_desc_id_to_length);
3122 * ufshcd_read_desc_param - read the specified descriptor parameter
3123 * @hba: Pointer to adapter instance
3124 * @desc_id: descriptor idn value
3125 * @desc_index: descriptor index
3126 * @param_offset: offset of the parameter to read
3127 * @param_read_buf: pointer to buffer where parameter would be read
3128 * @param_size: sizeof(param_read_buf)
3130 * Return 0 in case of success, non-zero otherwise
3132 int ufshcd_read_desc_param(struct ufs_hba *hba,
3133 enum desc_idn desc_id,
3142 bool is_kmalloc = true;
3145 if (desc_id >= QUERY_DESC_IDN_MAX || !param_size)
3148 /* Get the max length of descriptor from structure filled up at probe
3151 ret = ufshcd_map_desc_id_to_length(hba, desc_id, &buff_len);
3154 if (ret || !buff_len) {
3155 dev_err(hba->dev, "%s: Failed to get full descriptor length",
3160 /* Check whether we need temp memory */
3161 if (param_offset != 0 || param_size < buff_len) {
3162 desc_buf = kmalloc(buff_len, GFP_KERNEL);
3166 desc_buf = param_read_buf;
3170 /* Request for full descriptor */
3171 ret = ufshcd_query_descriptor_retry(hba, UPIU_QUERY_OPCODE_READ_DESC,
3172 desc_id, desc_index, 0,
3173 desc_buf, &buff_len);
3176 dev_err(hba->dev, "%s: Failed reading descriptor. desc_id %d, desc_index %d, param_offset %d, ret %d",
3177 __func__, desc_id, desc_index, param_offset, ret);
3182 if (desc_buf[QUERY_DESC_DESC_TYPE_OFFSET] != desc_id) {
3183 dev_err(hba->dev, "%s: invalid desc_id %d in descriptor header",
3184 __func__, desc_buf[QUERY_DESC_DESC_TYPE_OFFSET]);
3189 /* Check wherher we will not copy more data, than available */
3190 if (is_kmalloc && param_size > buff_len)
3191 param_size = buff_len;
3194 memcpy(param_read_buf, &desc_buf[param_offset], param_size);
3201 static inline int ufshcd_read_desc(struct ufs_hba *hba,
3202 enum desc_idn desc_id,
3207 return ufshcd_read_desc_param(hba, desc_id, desc_index, 0, buf, size);
3210 static inline int ufshcd_read_power_desc(struct ufs_hba *hba,
3214 return ufshcd_read_desc(hba, QUERY_DESC_IDN_POWER, 0, buf, size);
3217 static int ufshcd_read_device_desc(struct ufs_hba *hba, u8 *buf, u32 size)
3219 return ufshcd_read_desc(hba, QUERY_DESC_IDN_DEVICE, 0, buf, size);
3223 * struct uc_string_id - unicode string
3225 * @len: size of this descriptor inclusive
3226 * @type: descriptor type
3227 * @uc: unicode string character
3229 struct uc_string_id {
3235 /* replace non-printable or non-ASCII characters with spaces */
3236 static inline char ufshcd_remove_non_printable(u8 ch)
3238 return (ch >= 0x20 && ch <= 0x7e) ? ch : ' ';
3242 * ufshcd_read_string_desc - read string descriptor
3243 * @hba: pointer to adapter instance
3244 * @desc_index: descriptor index
3245 * @buf: pointer to buffer where descriptor would be read,
3246 * the caller should free the memory.
3247 * @ascii: if true convert from unicode to ascii characters
3248 * null terminated string.
3251 * * string size on success.
3252 * * -ENOMEM: on allocation failure
3253 * * -EINVAL: on a wrong parameter
3255 int ufshcd_read_string_desc(struct ufs_hba *hba, u8 desc_index,
3256 u8 **buf, bool ascii)
3258 struct uc_string_id *uc_str;
3265 uc_str = kzalloc(QUERY_DESC_MAX_SIZE, GFP_KERNEL);
3269 ret = ufshcd_read_desc(hba, QUERY_DESC_IDN_STRING,
3271 QUERY_DESC_MAX_SIZE);
3273 dev_err(hba->dev, "Reading String Desc failed after %d retries. err = %d\n",
3274 QUERY_REQ_RETRIES, ret);
3279 if (uc_str->len <= QUERY_DESC_HDR_SIZE) {
3280 dev_dbg(hba->dev, "String Desc is of zero length\n");
3289 /* remove header and divide by 2 to move from UTF16 to UTF8 */
3290 ascii_len = (uc_str->len - QUERY_DESC_HDR_SIZE) / 2 + 1;
3291 str = kzalloc(ascii_len, GFP_KERNEL);
3298 * the descriptor contains string in UTF16 format
3299 * we need to convert to utf-8 so it can be displayed
3301 ret = utf16s_to_utf8s(uc_str->uc,
3302 uc_str->len - QUERY_DESC_HDR_SIZE,
3303 UTF16_BIG_ENDIAN, str, ascii_len);
3305 /* replace non-printable or non-ASCII characters with spaces */
3306 for (i = 0; i < ret; i++)
3307 str[i] = ufshcd_remove_non_printable(str[i]);
3312 str = kmemdup(uc_str, uc_str->len, GFP_KERNEL);
3326 * ufshcd_read_unit_desc_param - read the specified unit descriptor parameter
3327 * @hba: Pointer to adapter instance
3329 * @param_offset: offset of the parameter to read
3330 * @param_read_buf: pointer to buffer where parameter would be read
3331 * @param_size: sizeof(param_read_buf)
3333 * Return 0 in case of success, non-zero otherwise
3335 static inline int ufshcd_read_unit_desc_param(struct ufs_hba *hba,
3337 enum unit_desc_param param_offset,
3342 * Unit descriptors are only available for general purpose LUs (LUN id
3343 * from 0 to 7) and RPMB Well known LU.
3345 if (!ufs_is_valid_unit_desc_lun(lun))
3348 return ufshcd_read_desc_param(hba, QUERY_DESC_IDN_UNIT, lun,
3349 param_offset, param_read_buf, param_size);
3353 * ufshcd_memory_alloc - allocate memory for host memory space data structures
3354 * @hba: per adapter instance
3356 * 1. Allocate DMA memory for Command Descriptor array
3357 * Each command descriptor consist of Command UPIU, Response UPIU and PRDT
3358 * 2. Allocate DMA memory for UTP Transfer Request Descriptor List (UTRDL).
3359 * 3. Allocate DMA memory for UTP Task Management Request Descriptor List
3361 * 4. Allocate memory for local reference block(lrb).
3363 * Returns 0 for success, non-zero in case of failure
3365 static int ufshcd_memory_alloc(struct ufs_hba *hba)
3367 size_t utmrdl_size, utrdl_size, ucdl_size;
3369 /* Allocate memory for UTP command descriptors */
3370 ucdl_size = (sizeof(struct utp_transfer_cmd_desc) * hba->nutrs);
3371 hba->ucdl_base_addr = dmam_alloc_coherent(hba->dev,
3373 &hba->ucdl_dma_addr,
3377 * UFSHCI requires UTP command descriptor to be 128 byte aligned.
3378 * make sure hba->ucdl_dma_addr is aligned to PAGE_SIZE
3379 * if hba->ucdl_dma_addr is aligned to PAGE_SIZE, then it will
3380 * be aligned to 128 bytes as well
3382 if (!hba->ucdl_base_addr ||
3383 WARN_ON(hba->ucdl_dma_addr & (PAGE_SIZE - 1))) {
3385 "Command Descriptor Memory allocation failed\n");
3390 * Allocate memory for UTP Transfer descriptors
3391 * UFSHCI requires 1024 byte alignment of UTRD
3393 utrdl_size = (sizeof(struct utp_transfer_req_desc) * hba->nutrs);
3394 hba->utrdl_base_addr = dmam_alloc_coherent(hba->dev,
3396 &hba->utrdl_dma_addr,
3398 if (!hba->utrdl_base_addr ||
3399 WARN_ON(hba->utrdl_dma_addr & (PAGE_SIZE - 1))) {
3401 "Transfer Descriptor Memory allocation failed\n");
3406 * Allocate memory for UTP Task Management descriptors
3407 * UFSHCI requires 1024 byte alignment of UTMRD
3409 utmrdl_size = sizeof(struct utp_task_req_desc) * hba->nutmrs;
3410 hba->utmrdl_base_addr = dmam_alloc_coherent(hba->dev,
3412 &hba->utmrdl_dma_addr,
3414 if (!hba->utmrdl_base_addr ||
3415 WARN_ON(hba->utmrdl_dma_addr & (PAGE_SIZE - 1))) {
3417 "Task Management Descriptor Memory allocation failed\n");
3421 /* Allocate memory for local reference block */
3422 hba->lrb = devm_kcalloc(hba->dev,
3423 hba->nutrs, sizeof(struct ufshcd_lrb),
3426 dev_err(hba->dev, "LRB Memory allocation failed\n");
3435 * ufshcd_host_memory_configure - configure local reference block with
3437 * @hba: per adapter instance
3439 * Configure Host memory space
3440 * 1. Update Corresponding UTRD.UCDBA and UTRD.UCDBAU with UCD DMA
3442 * 2. Update each UTRD with Response UPIU offset, Response UPIU length
3444 * 3. Save the corresponding addresses of UTRD, UCD.CMD, UCD.RSP and UCD.PRDT
3445 * into local reference block.
3447 static void ufshcd_host_memory_configure(struct ufs_hba *hba)
3449 struct utp_transfer_cmd_desc *cmd_descp;
3450 struct utp_transfer_req_desc *utrdlp;
3451 dma_addr_t cmd_desc_dma_addr;
3452 dma_addr_t cmd_desc_element_addr;
3453 u16 response_offset;
3458 utrdlp = hba->utrdl_base_addr;
3459 cmd_descp = hba->ucdl_base_addr;
3462 offsetof(struct utp_transfer_cmd_desc, response_upiu);
3464 offsetof(struct utp_transfer_cmd_desc, prd_table);
3466 cmd_desc_size = sizeof(struct utp_transfer_cmd_desc);
3467 cmd_desc_dma_addr = hba->ucdl_dma_addr;
3469 for (i = 0; i < hba->nutrs; i++) {
3470 /* Configure UTRD with command descriptor base address */
3471 cmd_desc_element_addr =
3472 (cmd_desc_dma_addr + (cmd_desc_size * i));
3473 utrdlp[i].command_desc_base_addr_lo =
3474 cpu_to_le32(lower_32_bits(cmd_desc_element_addr));
3475 utrdlp[i].command_desc_base_addr_hi =
3476 cpu_to_le32(upper_32_bits(cmd_desc_element_addr));
3478 /* Response upiu and prdt offset should be in double words */
3479 if (hba->quirks & UFSHCD_QUIRK_PRDT_BYTE_GRAN) {
3480 utrdlp[i].response_upiu_offset =
3481 cpu_to_le16(response_offset);
3482 utrdlp[i].prd_table_offset =
3483 cpu_to_le16(prdt_offset);
3484 utrdlp[i].response_upiu_length =
3485 cpu_to_le16(ALIGNED_UPIU_SIZE);
3487 utrdlp[i].response_upiu_offset =
3488 cpu_to_le16((response_offset >> 2));
3489 utrdlp[i].prd_table_offset =
3490 cpu_to_le16((prdt_offset >> 2));
3491 utrdlp[i].response_upiu_length =
3492 cpu_to_le16(ALIGNED_UPIU_SIZE >> 2);
3495 hba->lrb[i].utr_descriptor_ptr = (utrdlp + i);
3496 hba->lrb[i].utrd_dma_addr = hba->utrdl_dma_addr +
3497 (i * sizeof(struct utp_transfer_req_desc));
3498 hba->lrb[i].ucd_req_ptr =
3499 (struct utp_upiu_req *)(cmd_descp + i);
3500 hba->lrb[i].ucd_req_dma_addr = cmd_desc_element_addr;
3501 hba->lrb[i].ucd_rsp_ptr =
3502 (struct utp_upiu_rsp *)cmd_descp[i].response_upiu;
3503 hba->lrb[i].ucd_rsp_dma_addr = cmd_desc_element_addr +
3505 hba->lrb[i].ucd_prdt_ptr =
3506 (struct ufshcd_sg_entry *)cmd_descp[i].prd_table;
3507 hba->lrb[i].ucd_prdt_dma_addr = cmd_desc_element_addr +
3513 * ufshcd_dme_link_startup - Notify Unipro to perform link startup
3514 * @hba: per adapter instance
3516 * UIC_CMD_DME_LINK_STARTUP command must be issued to Unipro layer,
3517 * in order to initialize the Unipro link startup procedure.
3518 * Once the Unipro links are up, the device connected to the controller
3521 * Returns 0 on success, non-zero value on failure
3523 static int ufshcd_dme_link_startup(struct ufs_hba *hba)
3525 struct uic_command uic_cmd = {0};
3528 uic_cmd.command = UIC_CMD_DME_LINK_STARTUP;
3530 ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
3533 "dme-link-startup: error code %d\n", ret);
3537 * ufshcd_dme_reset - UIC command for DME_RESET
3538 * @hba: per adapter instance
3540 * DME_RESET command is issued in order to reset UniPro stack.
3541 * This function now deal with cold reset.
3543 * Returns 0 on success, non-zero value on failure
3545 static int ufshcd_dme_reset(struct ufs_hba *hba)
3547 struct uic_command uic_cmd = {0};
3550 uic_cmd.command = UIC_CMD_DME_RESET;
3552 ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
3555 "dme-reset: error code %d\n", ret);
3561 * ufshcd_dme_enable - UIC command for DME_ENABLE
3562 * @hba: per adapter instance
3564 * DME_ENABLE command is issued in order to enable UniPro stack.
3566 * Returns 0 on success, non-zero value on failure
3568 static int ufshcd_dme_enable(struct ufs_hba *hba)
3570 struct uic_command uic_cmd = {0};
3573 uic_cmd.command = UIC_CMD_DME_ENABLE;
3575 ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
3578 "dme-reset: error code %d\n", ret);
3583 static inline void ufshcd_add_delay_before_dme_cmd(struct ufs_hba *hba)
3585 #define MIN_DELAY_BEFORE_DME_CMDS_US 1000
3586 unsigned long min_sleep_time_us;
3588 if (!(hba->quirks & UFSHCD_QUIRK_DELAY_BEFORE_DME_CMDS))
3592 * last_dme_cmd_tstamp will be 0 only for 1st call to
3595 if (unlikely(!ktime_to_us(hba->last_dme_cmd_tstamp))) {
3596 min_sleep_time_us = MIN_DELAY_BEFORE_DME_CMDS_US;
3598 unsigned long delta =
3599 (unsigned long) ktime_to_us(
3600 ktime_sub(ktime_get(),
3601 hba->last_dme_cmd_tstamp));
3603 if (delta < MIN_DELAY_BEFORE_DME_CMDS_US)
3605 MIN_DELAY_BEFORE_DME_CMDS_US - delta;
3607 return; /* no more delay required */
3610 /* allow sleep for extra 50us if needed */
3611 usleep_range(min_sleep_time_us, min_sleep_time_us + 50);
3615 * ufshcd_dme_set_attr - UIC command for DME_SET, DME_PEER_SET
3616 * @hba: per adapter instance
3617 * @attr_sel: uic command argument1
3618 * @attr_set: attribute set type as uic command argument2
3619 * @mib_val: setting value as uic command argument3
3620 * @peer: indicate whether peer or local
3622 * Returns 0 on success, non-zero value on failure
3624 int ufshcd_dme_set_attr(struct ufs_hba *hba, u32 attr_sel,
3625 u8 attr_set, u32 mib_val, u8 peer)
3627 struct uic_command uic_cmd = {0};
3628 static const char *const action[] = {
3632 const char *set = action[!!peer];
3634 int retries = UFS_UIC_COMMAND_RETRIES;
3636 uic_cmd.command = peer ?
3637 UIC_CMD_DME_PEER_SET : UIC_CMD_DME_SET;
3638 uic_cmd.argument1 = attr_sel;
3639 uic_cmd.argument2 = UIC_ARG_ATTR_TYPE(attr_set);
3640 uic_cmd.argument3 = mib_val;
3643 /* for peer attributes we retry upon failure */
3644 ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
3646 dev_dbg(hba->dev, "%s: attr-id 0x%x val 0x%x error code %d\n",
3647 set, UIC_GET_ATTR_ID(attr_sel), mib_val, ret);
3648 } while (ret && peer && --retries);
3651 dev_err(hba->dev, "%s: attr-id 0x%x val 0x%x failed %d retries\n",
3652 set, UIC_GET_ATTR_ID(attr_sel), mib_val,
3653 UFS_UIC_COMMAND_RETRIES - retries);
3657 EXPORT_SYMBOL_GPL(ufshcd_dme_set_attr);
3660 * ufshcd_dme_get_attr - UIC command for DME_GET, DME_PEER_GET
3661 * @hba: per adapter instance
3662 * @attr_sel: uic command argument1
3663 * @mib_val: the value of the attribute as returned by the UIC command
3664 * @peer: indicate whether peer or local
3666 * Returns 0 on success, non-zero value on failure
3668 int ufshcd_dme_get_attr(struct ufs_hba *hba, u32 attr_sel,
3669 u32 *mib_val, u8 peer)
3671 struct uic_command uic_cmd = {0};
3672 static const char *const action[] = {
3676 const char *get = action[!!peer];
3678 int retries = UFS_UIC_COMMAND_RETRIES;
3679 struct ufs_pa_layer_attr orig_pwr_info;
3680 struct ufs_pa_layer_attr temp_pwr_info;
3681 bool pwr_mode_change = false;
3683 if (peer && (hba->quirks & UFSHCD_QUIRK_DME_PEER_ACCESS_AUTO_MODE)) {
3684 orig_pwr_info = hba->pwr_info;
3685 temp_pwr_info = orig_pwr_info;
3687 if (orig_pwr_info.pwr_tx == FAST_MODE ||
3688 orig_pwr_info.pwr_rx == FAST_MODE) {
3689 temp_pwr_info.pwr_tx = FASTAUTO_MODE;
3690 temp_pwr_info.pwr_rx = FASTAUTO_MODE;
3691 pwr_mode_change = true;
3692 } else if (orig_pwr_info.pwr_tx == SLOW_MODE ||
3693 orig_pwr_info.pwr_rx == SLOW_MODE) {
3694 temp_pwr_info.pwr_tx = SLOWAUTO_MODE;
3695 temp_pwr_info.pwr_rx = SLOWAUTO_MODE;
3696 pwr_mode_change = true;
3698 if (pwr_mode_change) {
3699 ret = ufshcd_change_power_mode(hba, &temp_pwr_info);
3705 uic_cmd.command = peer ?
3706 UIC_CMD_DME_PEER_GET : UIC_CMD_DME_GET;
3707 uic_cmd.argument1 = attr_sel;
3710 /* for peer attributes we retry upon failure */
3711 ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
3713 dev_dbg(hba->dev, "%s: attr-id 0x%x error code %d\n",
3714 get, UIC_GET_ATTR_ID(attr_sel), ret);
3715 } while (ret && peer && --retries);
3718 dev_err(hba->dev, "%s: attr-id 0x%x failed %d retries\n",
3719 get, UIC_GET_ATTR_ID(attr_sel),
3720 UFS_UIC_COMMAND_RETRIES - retries);
3722 if (mib_val && !ret)
3723 *mib_val = uic_cmd.argument3;
3725 if (peer && (hba->quirks & UFSHCD_QUIRK_DME_PEER_ACCESS_AUTO_MODE)
3727 ufshcd_change_power_mode(hba, &orig_pwr_info);
3731 EXPORT_SYMBOL_GPL(ufshcd_dme_get_attr);
3734 * ufshcd_uic_pwr_ctrl - executes UIC commands (which affects the link power
3735 * state) and waits for it to take effect.
3737 * @hba: per adapter instance
3738 * @cmd: UIC command to execute
3740 * DME operations like DME_SET(PA_PWRMODE), DME_HIBERNATE_ENTER &
3741 * DME_HIBERNATE_EXIT commands take some time to take its effect on both host
3742 * and device UniPro link and hence it's final completion would be indicated by
3743 * dedicated status bits in Interrupt Status register (UPMS, UHES, UHXS) in
3744 * addition to normal UIC command completion Status (UCCS). This function only
3745 * returns after the relevant status bits indicate the completion.
3747 * Returns 0 on success, non-zero value on failure
3749 static int ufshcd_uic_pwr_ctrl(struct ufs_hba *hba, struct uic_command *cmd)
3751 struct completion uic_async_done;
3752 unsigned long flags;
3755 bool reenable_intr = false;
3757 mutex_lock(&hba->uic_cmd_mutex);
3758 init_completion(&uic_async_done);
3759 ufshcd_add_delay_before_dme_cmd(hba);
3761 spin_lock_irqsave(hba->host->host_lock, flags);
3762 hba->uic_async_done = &uic_async_done;
3763 if (ufshcd_readl(hba, REG_INTERRUPT_ENABLE) & UIC_COMMAND_COMPL) {
3764 ufshcd_disable_intr(hba, UIC_COMMAND_COMPL);
3766 * Make sure UIC command completion interrupt is disabled before
3767 * issuing UIC command.
3770 reenable_intr = true;
3772 ret = __ufshcd_send_uic_cmd(hba, cmd, false);
3773 spin_unlock_irqrestore(hba->host->host_lock, flags);
3776 "pwr ctrl cmd 0x%x with mode 0x%x uic error %d\n",
3777 cmd->command, cmd->argument3, ret);
3781 if (!wait_for_completion_timeout(hba->uic_async_done,
3782 msecs_to_jiffies(UIC_CMD_TIMEOUT))) {
3784 "pwr ctrl cmd 0x%x with mode 0x%x completion timeout\n",
3785 cmd->command, cmd->argument3);
3790 status = ufshcd_get_upmcrs(hba);
3791 if (status != PWR_LOCAL) {
3793 "pwr ctrl cmd 0x%x failed, host upmcrs:0x%x\n",
3794 cmd->command, status);
3795 ret = (status != PWR_OK) ? status : -1;
3799 ufshcd_print_host_state(hba);
3800 ufshcd_print_pwr_info(hba);
3801 ufshcd_print_host_regs(hba);
3804 spin_lock_irqsave(hba->host->host_lock, flags);
3805 hba->active_uic_cmd = NULL;
3806 hba->uic_async_done = NULL;
3808 ufshcd_enable_intr(hba, UIC_COMMAND_COMPL);
3809 spin_unlock_irqrestore(hba->host->host_lock, flags);
3810 mutex_unlock(&hba->uic_cmd_mutex);
3816 * ufshcd_uic_change_pwr_mode - Perform the UIC power mode chage
3817 * using DME_SET primitives.
3818 * @hba: per adapter instance
3819 * @mode: powr mode value
3821 * Returns 0 on success, non-zero value on failure
3823 static int ufshcd_uic_change_pwr_mode(struct ufs_hba *hba, u8 mode)
3825 struct uic_command uic_cmd = {0};
3828 if (hba->quirks & UFSHCD_QUIRK_BROKEN_PA_RXHSUNTERMCAP) {
3829 ret = ufshcd_dme_set(hba,
3830 UIC_ARG_MIB_SEL(PA_RXHSUNTERMCAP, 0), 1);
3832 dev_err(hba->dev, "%s: failed to enable PA_RXHSUNTERMCAP ret %d\n",
3838 uic_cmd.command = UIC_CMD_DME_SET;
3839 uic_cmd.argument1 = UIC_ARG_MIB(PA_PWRMODE);
3840 uic_cmd.argument3 = mode;
3841 ufshcd_hold(hba, false);
3842 ret = ufshcd_uic_pwr_ctrl(hba, &uic_cmd);
3843 ufshcd_release(hba);
3849 static int ufshcd_link_recovery(struct ufs_hba *hba)
3852 unsigned long flags;
3854 spin_lock_irqsave(hba->host->host_lock, flags);
3855 hba->ufshcd_state = UFSHCD_STATE_RESET;
3856 ufshcd_set_eh_in_progress(hba);
3857 spin_unlock_irqrestore(hba->host->host_lock, flags);
3859 ret = ufshcd_host_reset_and_restore(hba);
3861 spin_lock_irqsave(hba->host->host_lock, flags);
3863 hba->ufshcd_state = UFSHCD_STATE_ERROR;
3864 ufshcd_clear_eh_in_progress(hba);
3865 spin_unlock_irqrestore(hba->host->host_lock, flags);
3868 dev_err(hba->dev, "%s: link recovery failed, err %d",
3874 static int __ufshcd_uic_hibern8_enter(struct ufs_hba *hba)
3877 struct uic_command uic_cmd = {0};
3878 ktime_t start = ktime_get();
3880 ufshcd_vops_hibern8_notify(hba, UIC_CMD_DME_HIBER_ENTER, PRE_CHANGE);
3882 uic_cmd.command = UIC_CMD_DME_HIBER_ENTER;
3883 ret = ufshcd_uic_pwr_ctrl(hba, &uic_cmd);
3884 trace_ufshcd_profile_hibern8(dev_name(hba->dev), "enter",
3885 ktime_to_us(ktime_sub(ktime_get(), start)), ret);
3888 dev_err(hba->dev, "%s: hibern8 enter failed. ret = %d\n",
3892 * If link recovery fails then return error so that caller
3893 * don't retry the hibern8 enter again.
3895 if (ufshcd_link_recovery(hba))
3898 ufshcd_vops_hibern8_notify(hba, UIC_CMD_DME_HIBER_ENTER,
3904 static int ufshcd_uic_hibern8_enter(struct ufs_hba *hba)
3906 int ret = 0, retries;
3908 for (retries = UIC_HIBERN8_ENTER_RETRIES; retries > 0; retries--) {
3909 ret = __ufshcd_uic_hibern8_enter(hba);
3910 if (!ret || ret == -ENOLINK)
3917 static int ufshcd_uic_hibern8_exit(struct ufs_hba *hba)
3919 struct uic_command uic_cmd = {0};
3921 ktime_t start = ktime_get();
3923 ufshcd_vops_hibern8_notify(hba, UIC_CMD_DME_HIBER_EXIT, PRE_CHANGE);
3925 uic_cmd.command = UIC_CMD_DME_HIBER_EXIT;
3926 ret = ufshcd_uic_pwr_ctrl(hba, &uic_cmd);
3927 trace_ufshcd_profile_hibern8(dev_name(hba->dev), "exit",
3928 ktime_to_us(ktime_sub(ktime_get(), start)), ret);
3931 dev_err(hba->dev, "%s: hibern8 exit failed. ret = %d\n",
3933 ret = ufshcd_link_recovery(hba);
3935 ufshcd_vops_hibern8_notify(hba, UIC_CMD_DME_HIBER_EXIT,
3937 hba->ufs_stats.last_hibern8_exit_tstamp = ktime_get();
3938 hba->ufs_stats.hibern8_exit_cnt++;
3944 static void ufshcd_auto_hibern8_enable(struct ufs_hba *hba)
3946 unsigned long flags;
3948 if (!ufshcd_is_auto_hibern8_supported(hba) || !hba->ahit)
3951 spin_lock_irqsave(hba->host->host_lock, flags);
3952 ufshcd_writel(hba, hba->ahit, REG_AUTO_HIBERNATE_IDLE_TIMER);
3953 spin_unlock_irqrestore(hba->host->host_lock, flags);
3957 * ufshcd_init_pwr_info - setting the POR (power on reset)
3958 * values in hba power info
3959 * @hba: per-adapter instance
3961 static void ufshcd_init_pwr_info(struct ufs_hba *hba)
3963 hba->pwr_info.gear_rx = UFS_PWM_G1;
3964 hba->pwr_info.gear_tx = UFS_PWM_G1;
3965 hba->pwr_info.lane_rx = 1;
3966 hba->pwr_info.lane_tx = 1;
3967 hba->pwr_info.pwr_rx = SLOWAUTO_MODE;
3968 hba->pwr_info.pwr_tx = SLOWAUTO_MODE;
3969 hba->pwr_info.hs_rate = 0;
3973 * ufshcd_get_max_pwr_mode - reads the max power mode negotiated with device
3974 * @hba: per-adapter instance
3976 static int ufshcd_get_max_pwr_mode(struct ufs_hba *hba)
3978 struct ufs_pa_layer_attr *pwr_info = &hba->max_pwr_info.info;
3980 if (hba->max_pwr_info.is_valid)
3983 pwr_info->pwr_tx = FAST_MODE;
3984 pwr_info->pwr_rx = FAST_MODE;
3985 pwr_info->hs_rate = PA_HS_MODE_B;
3987 /* Get the connected lane count */
3988 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_CONNECTEDRXDATALANES),
3989 &pwr_info->lane_rx);
3990 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_CONNECTEDTXDATALANES),
3991 &pwr_info->lane_tx);
3993 if (!pwr_info->lane_rx || !pwr_info->lane_tx) {
3994 dev_err(hba->dev, "%s: invalid connected lanes value. rx=%d, tx=%d\n",
4002 * First, get the maximum gears of HS speed.
4003 * If a zero value, it means there is no HSGEAR capability.
4004 * Then, get the maximum gears of PWM speed.
4006 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_MAXRXHSGEAR), &pwr_info->gear_rx);
4007 if (!pwr_info->gear_rx) {
4008 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_MAXRXPWMGEAR),
4009 &pwr_info->gear_rx);
4010 if (!pwr_info->gear_rx) {
4011 dev_err(hba->dev, "%s: invalid max pwm rx gear read = %d\n",
4012 __func__, pwr_info->gear_rx);
4015 pwr_info->pwr_rx = SLOW_MODE;
4018 ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_MAXRXHSGEAR),
4019 &pwr_info->gear_tx);
4020 if (!pwr_info->gear_tx) {
4021 ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_MAXRXPWMGEAR),
4022 &pwr_info->gear_tx);
4023 if (!pwr_info->gear_tx) {
4024 dev_err(hba->dev, "%s: invalid max pwm tx gear read = %d\n",
4025 __func__, pwr_info->gear_tx);
4028 pwr_info->pwr_tx = SLOW_MODE;
4031 hba->max_pwr_info.is_valid = true;
4035 static int ufshcd_change_power_mode(struct ufs_hba *hba,
4036 struct ufs_pa_layer_attr *pwr_mode)
4040 /* if already configured to the requested pwr_mode */
4041 if (pwr_mode->gear_rx == hba->pwr_info.gear_rx &&
4042 pwr_mode->gear_tx == hba->pwr_info.gear_tx &&
4043 pwr_mode->lane_rx == hba->pwr_info.lane_rx &&
4044 pwr_mode->lane_tx == hba->pwr_info.lane_tx &&
4045 pwr_mode->pwr_rx == hba->pwr_info.pwr_rx &&
4046 pwr_mode->pwr_tx == hba->pwr_info.pwr_tx &&
4047 pwr_mode->hs_rate == hba->pwr_info.hs_rate) {
4048 dev_dbg(hba->dev, "%s: power already configured\n", __func__);
4053 * Configure attributes for power mode change with below.
4054 * - PA_RXGEAR, PA_ACTIVERXDATALANES, PA_RXTERMINATION,
4055 * - PA_TXGEAR, PA_ACTIVETXDATALANES, PA_TXTERMINATION,
4058 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_RXGEAR), pwr_mode->gear_rx);
4059 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_ACTIVERXDATALANES),
4061 if (pwr_mode->pwr_rx == FASTAUTO_MODE ||
4062 pwr_mode->pwr_rx == FAST_MODE)
4063 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_RXTERMINATION), TRUE);
4065 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_RXTERMINATION), FALSE);
4067 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TXGEAR), pwr_mode->gear_tx);
4068 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_ACTIVETXDATALANES),
4070 if (pwr_mode->pwr_tx == FASTAUTO_MODE ||
4071 pwr_mode->pwr_tx == FAST_MODE)
4072 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TXTERMINATION), TRUE);
4074 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TXTERMINATION), FALSE);
4076 if (pwr_mode->pwr_rx == FASTAUTO_MODE ||
4077 pwr_mode->pwr_tx == FASTAUTO_MODE ||
4078 pwr_mode->pwr_rx == FAST_MODE ||
4079 pwr_mode->pwr_tx == FAST_MODE)
4080 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_HSSERIES),
4083 ret = ufshcd_uic_change_pwr_mode(hba, pwr_mode->pwr_rx << 4
4084 | pwr_mode->pwr_tx);
4088 "%s: power mode change failed %d\n", __func__, ret);
4090 ufshcd_vops_pwr_change_notify(hba, POST_CHANGE, NULL,
4093 memcpy(&hba->pwr_info, pwr_mode,
4094 sizeof(struct ufs_pa_layer_attr));
4101 * ufshcd_config_pwr_mode - configure a new power mode
4102 * @hba: per-adapter instance
4103 * @desired_pwr_mode: desired power configuration
4105 int ufshcd_config_pwr_mode(struct ufs_hba *hba,
4106 struct ufs_pa_layer_attr *desired_pwr_mode)
4108 struct ufs_pa_layer_attr final_params = { 0 };
4111 ret = ufshcd_vops_pwr_change_notify(hba, PRE_CHANGE,
4112 desired_pwr_mode, &final_params);
4115 memcpy(&final_params, desired_pwr_mode, sizeof(final_params));
4117 ret = ufshcd_change_power_mode(hba, &final_params);
4119 ufshcd_print_pwr_info(hba);
4123 EXPORT_SYMBOL_GPL(ufshcd_config_pwr_mode);
4126 * ufshcd_complete_dev_init() - checks device readiness
4127 * @hba: per-adapter instance
4129 * Set fDeviceInit flag and poll until device toggles it.
4131 static int ufshcd_complete_dev_init(struct ufs_hba *hba)
4137 err = ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_SET_FLAG,
4138 QUERY_FLAG_IDN_FDEVICEINIT, NULL);
4141 "%s setting fDeviceInit flag failed with error %d\n",
4146 /* poll for max. 1000 iterations for fDeviceInit flag to clear */
4147 for (i = 0; i < 1000 && !err && flag_res; i++)
4148 err = ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_READ_FLAG,
4149 QUERY_FLAG_IDN_FDEVICEINIT, &flag_res);
4153 "%s reading fDeviceInit flag failed with error %d\n",
4157 "%s fDeviceInit was not cleared by the device\n",
4165 * ufshcd_make_hba_operational - Make UFS controller operational
4166 * @hba: per adapter instance
4168 * To bring UFS host controller to operational state,
4169 * 1. Enable required interrupts
4170 * 2. Configure interrupt aggregation
4171 * 3. Program UTRL and UTMRL base address
4172 * 4. Configure run-stop-registers
4174 * Returns 0 on success, non-zero value on failure
4176 static int ufshcd_make_hba_operational(struct ufs_hba *hba)
4181 /* Enable required interrupts */
4182 ufshcd_enable_intr(hba, UFSHCD_ENABLE_INTRS);
4184 /* Configure interrupt aggregation */
4185 if (ufshcd_is_intr_aggr_allowed(hba))
4186 ufshcd_config_intr_aggr(hba, hba->nutrs - 1, INT_AGGR_DEF_TO);
4188 ufshcd_disable_intr_aggr(hba);
4190 /* Configure UTRL and UTMRL base address registers */
4191 ufshcd_writel(hba, lower_32_bits(hba->utrdl_dma_addr),
4192 REG_UTP_TRANSFER_REQ_LIST_BASE_L);
4193 ufshcd_writel(hba, upper_32_bits(hba->utrdl_dma_addr),
4194 REG_UTP_TRANSFER_REQ_LIST_BASE_H);
4195 ufshcd_writel(hba, lower_32_bits(hba->utmrdl_dma_addr),
4196 REG_UTP_TASK_REQ_LIST_BASE_L);
4197 ufshcd_writel(hba, upper_32_bits(hba->utmrdl_dma_addr),
4198 REG_UTP_TASK_REQ_LIST_BASE_H);
4201 * Make sure base address and interrupt setup are updated before
4202 * enabling the run/stop registers below.
4207 * UCRDY, UTMRLDY and UTRLRDY bits must be 1
4209 reg = ufshcd_readl(hba, REG_CONTROLLER_STATUS);
4210 if (!(ufshcd_get_lists_status(reg))) {
4211 ufshcd_enable_run_stop_reg(hba);
4214 "Host controller not ready to process requests");
4224 * ufshcd_hba_stop - Send controller to reset state
4225 * @hba: per adapter instance
4226 * @can_sleep: perform sleep or just spin
4228 static inline void ufshcd_hba_stop(struct ufs_hba *hba, bool can_sleep)
4232 ufshcd_writel(hba, CONTROLLER_DISABLE, REG_CONTROLLER_ENABLE);
4233 err = ufshcd_wait_for_register(hba, REG_CONTROLLER_ENABLE,
4234 CONTROLLER_ENABLE, CONTROLLER_DISABLE,
4237 dev_err(hba->dev, "%s: Controller disable failed\n", __func__);
4241 * ufshcd_hba_execute_hce - initialize the controller
4242 * @hba: per adapter instance
4244 * The controller resets itself and controller firmware initialization
4245 * sequence kicks off. When controller is ready it will set
4246 * the Host Controller Enable bit to 1.
4248 * Returns 0 on success, non-zero value on failure
4250 static int ufshcd_hba_execute_hce(struct ufs_hba *hba)
4254 if (!ufshcd_is_hba_active(hba))
4255 /* change controller state to "reset state" */
4256 ufshcd_hba_stop(hba, true);
4258 /* UniPro link is disabled at this point */
4259 ufshcd_set_link_off(hba);
4261 ufshcd_vops_hce_enable_notify(hba, PRE_CHANGE);
4263 /* start controller initialization sequence */
4264 ufshcd_hba_start(hba);
4267 * To initialize a UFS host controller HCE bit must be set to 1.
4268 * During initialization the HCE bit value changes from 1->0->1.
4269 * When the host controller completes initialization sequence
4270 * it sets the value of HCE bit to 1. The same HCE bit is read back
4271 * to check if the controller has completed initialization sequence.
4272 * So without this delay the value HCE = 1, set in the previous
4273 * instruction might be read back.
4274 * This delay can be changed based on the controller.
4276 usleep_range(1000, 1100);
4278 /* wait for the host controller to complete initialization */
4280 while (ufshcd_is_hba_active(hba)) {
4285 "Controller enable failed\n");
4288 usleep_range(5000, 5100);
4291 /* enable UIC related interrupts */
4292 ufshcd_enable_intr(hba, UFSHCD_UIC_MASK);
4294 ufshcd_vops_hce_enable_notify(hba, POST_CHANGE);
4299 static int ufshcd_hba_enable(struct ufs_hba *hba)
4303 if (hba->quirks & UFSHCI_QUIRK_BROKEN_HCE) {
4304 ufshcd_set_link_off(hba);
4305 ufshcd_vops_hce_enable_notify(hba, PRE_CHANGE);
4307 /* enable UIC related interrupts */
4308 ufshcd_enable_intr(hba, UFSHCD_UIC_MASK);
4309 ret = ufshcd_dme_reset(hba);
4311 ret = ufshcd_dme_enable(hba);
4313 ufshcd_vops_hce_enable_notify(hba, POST_CHANGE);
4316 "Host controller enable failed with non-hce\n");
4319 ret = ufshcd_hba_execute_hce(hba);
4324 static int ufshcd_disable_tx_lcc(struct ufs_hba *hba, bool peer)
4326 int tx_lanes, i, err = 0;
4329 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_CONNECTEDTXDATALANES),
4332 ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_CONNECTEDTXDATALANES),
4334 for (i = 0; i < tx_lanes; i++) {
4336 err = ufshcd_dme_set(hba,
4337 UIC_ARG_MIB_SEL(TX_LCC_ENABLE,
4338 UIC_ARG_MPHY_TX_GEN_SEL_INDEX(i)),
4341 err = ufshcd_dme_peer_set(hba,
4342 UIC_ARG_MIB_SEL(TX_LCC_ENABLE,
4343 UIC_ARG_MPHY_TX_GEN_SEL_INDEX(i)),
4346 dev_err(hba->dev, "%s: TX LCC Disable failed, peer = %d, lane = %d, err = %d",
4347 __func__, peer, i, err);
4355 static inline int ufshcd_disable_device_tx_lcc(struct ufs_hba *hba)
4357 return ufshcd_disable_tx_lcc(hba, true);
4360 static void ufshcd_update_reg_hist(struct ufs_err_reg_hist *reg_hist,
4363 reg_hist->reg[reg_hist->pos] = reg;
4364 reg_hist->tstamp[reg_hist->pos] = ktime_get();
4365 reg_hist->pos = (reg_hist->pos + 1) % UFS_ERR_REG_HIST_LENGTH;
4369 * ufshcd_link_startup - Initialize unipro link startup
4370 * @hba: per adapter instance
4372 * Returns 0 for success, non-zero in case of failure
4374 static int ufshcd_link_startup(struct ufs_hba *hba)
4377 int retries = DME_LINKSTARTUP_RETRIES;
4378 bool link_startup_again = false;
4381 * If UFS device isn't active then we will have to issue link startup
4382 * 2 times to make sure the device state move to active.
4384 if (!ufshcd_is_ufs_dev_active(hba))
4385 link_startup_again = true;
4389 ufshcd_vops_link_startup_notify(hba, PRE_CHANGE);
4391 ret = ufshcd_dme_link_startup(hba);
4393 /* check if device is detected by inter-connect layer */
4394 if (!ret && !ufshcd_is_device_present(hba)) {
4395 ufshcd_update_reg_hist(&hba->ufs_stats.link_startup_err,
4397 dev_err(hba->dev, "%s: Device not present\n", __func__);
4403 * DME link lost indication is only received when link is up,
4404 * but we can't be sure if the link is up until link startup
4405 * succeeds. So reset the local Uni-Pro and try again.
4407 if (ret && ufshcd_hba_enable(hba)) {
4408 ufshcd_update_reg_hist(&hba->ufs_stats.link_startup_err,
4412 } while (ret && retries--);
4415 /* failed to get the link up... retire */
4416 ufshcd_update_reg_hist(&hba->ufs_stats.link_startup_err,
4421 if (link_startup_again) {
4422 link_startup_again = false;
4423 retries = DME_LINKSTARTUP_RETRIES;
4427 /* Mark that link is up in PWM-G1, 1-lane, SLOW-AUTO mode */
4428 ufshcd_init_pwr_info(hba);
4429 ufshcd_print_pwr_info(hba);
4431 if (hba->quirks & UFSHCD_QUIRK_BROKEN_LCC) {
4432 ret = ufshcd_disable_device_tx_lcc(hba);
4437 /* Include any host controller configuration via UIC commands */
4438 ret = ufshcd_vops_link_startup_notify(hba, POST_CHANGE);
4442 ret = ufshcd_make_hba_operational(hba);
4445 dev_err(hba->dev, "link startup failed %d\n", ret);
4446 ufshcd_print_host_state(hba);
4447 ufshcd_print_pwr_info(hba);
4448 ufshcd_print_host_regs(hba);
4454 * ufshcd_verify_dev_init() - Verify device initialization
4455 * @hba: per-adapter instance
4457 * Send NOP OUT UPIU and wait for NOP IN response to check whether the
4458 * device Transport Protocol (UTP) layer is ready after a reset.
4459 * If the UTP layer at the device side is not initialized, it may
4460 * not respond with NOP IN UPIU within timeout of %NOP_OUT_TIMEOUT
4461 * and we retry sending NOP OUT for %NOP_OUT_RETRIES iterations.
4463 static int ufshcd_verify_dev_init(struct ufs_hba *hba)
4468 ufshcd_hold(hba, false);
4469 mutex_lock(&hba->dev_cmd.lock);
4470 for (retries = NOP_OUT_RETRIES; retries > 0; retries--) {
4471 err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_NOP,
4474 if (!err || err == -ETIMEDOUT)
4477 dev_dbg(hba->dev, "%s: error %d retrying\n", __func__, err);
4479 mutex_unlock(&hba->dev_cmd.lock);
4480 ufshcd_release(hba);
4483 dev_err(hba->dev, "%s: NOP OUT failed %d\n", __func__, err);
4488 * ufshcd_set_queue_depth - set lun queue depth
4489 * @sdev: pointer to SCSI device
4491 * Read bLUQueueDepth value and activate scsi tagged command
4492 * queueing. For WLUN, queue depth is set to 1. For best-effort
4493 * cases (bLUQueueDepth = 0) the queue depth is set to a maximum
4494 * value that host can queue.
4496 static void ufshcd_set_queue_depth(struct scsi_device *sdev)
4500 struct ufs_hba *hba;
4502 hba = shost_priv(sdev->host);
4504 lun_qdepth = hba->nutrs;
4505 ret = ufshcd_read_unit_desc_param(hba,
4506 ufshcd_scsi_to_upiu_lun(sdev->lun),
4507 UNIT_DESC_PARAM_LU_Q_DEPTH,
4509 sizeof(lun_qdepth));
4511 /* Some WLUN doesn't support unit descriptor */
4512 if (ret == -EOPNOTSUPP)
4514 else if (!lun_qdepth)
4515 /* eventually, we can figure out the real queue depth */
4516 lun_qdepth = hba->nutrs;
4518 lun_qdepth = min_t(int, lun_qdepth, hba->nutrs);
4520 dev_dbg(hba->dev, "%s: activate tcq with queue depth %d\n",
4521 __func__, lun_qdepth);
4522 scsi_change_queue_depth(sdev, lun_qdepth);
4526 * ufshcd_get_lu_wp - returns the "b_lu_write_protect" from UNIT DESCRIPTOR
4527 * @hba: per-adapter instance
4528 * @lun: UFS device lun id
4529 * @b_lu_write_protect: pointer to buffer to hold the LU's write protect info
4531 * Returns 0 in case of success and b_lu_write_protect status would be returned
4532 * @b_lu_write_protect parameter.
4533 * Returns -ENOTSUPP if reading b_lu_write_protect is not supported.
4534 * Returns -EINVAL in case of invalid parameters passed to this function.
4536 static int ufshcd_get_lu_wp(struct ufs_hba *hba,
4538 u8 *b_lu_write_protect)
4542 if (!b_lu_write_protect)
4545 * According to UFS device spec, RPMB LU can't be write
4546 * protected so skip reading bLUWriteProtect parameter for
4547 * it. For other W-LUs, UNIT DESCRIPTOR is not available.
4549 else if (lun >= UFS_UPIU_MAX_GENERAL_LUN)
4552 ret = ufshcd_read_unit_desc_param(hba,
4554 UNIT_DESC_PARAM_LU_WR_PROTECT,
4556 sizeof(*b_lu_write_protect));
4561 * ufshcd_get_lu_power_on_wp_status - get LU's power on write protect
4563 * @hba: per-adapter instance
4564 * @sdev: pointer to SCSI device
4567 static inline void ufshcd_get_lu_power_on_wp_status(struct ufs_hba *hba,
4568 struct scsi_device *sdev)
4570 if (hba->dev_info.f_power_on_wp_en &&
4571 !hba->dev_info.is_lu_power_on_wp) {
4572 u8 b_lu_write_protect;
4574 if (!ufshcd_get_lu_wp(hba, ufshcd_scsi_to_upiu_lun(sdev->lun),
4575 &b_lu_write_protect) &&
4576 (b_lu_write_protect == UFS_LU_POWER_ON_WP))
4577 hba->dev_info.is_lu_power_on_wp = true;
4582 * ufshcd_slave_alloc - handle initial SCSI device configurations
4583 * @sdev: pointer to SCSI device
4587 static int ufshcd_slave_alloc(struct scsi_device *sdev)
4589 struct ufs_hba *hba;
4591 hba = shost_priv(sdev->host);
4593 /* Mode sense(6) is not supported by UFS, so use Mode sense(10) */
4594 sdev->use_10_for_ms = 1;
4596 /* allow SCSI layer to restart the device in case of errors */
4597 sdev->allow_restart = 1;
4599 /* REPORT SUPPORTED OPERATION CODES is not supported */
4600 sdev->no_report_opcodes = 1;
4602 /* WRITE_SAME command is not supported */
4603 sdev->no_write_same = 1;
4605 ufshcd_set_queue_depth(sdev);
4607 ufshcd_get_lu_power_on_wp_status(hba, sdev);
4613 * ufshcd_change_queue_depth - change queue depth
4614 * @sdev: pointer to SCSI device
4615 * @depth: required depth to set
4617 * Change queue depth and make sure the max. limits are not crossed.
4619 static int ufshcd_change_queue_depth(struct scsi_device *sdev, int depth)
4621 struct ufs_hba *hba = shost_priv(sdev->host);
4623 if (depth > hba->nutrs)
4625 return scsi_change_queue_depth(sdev, depth);
4629 * ufshcd_slave_configure - adjust SCSI device configurations
4630 * @sdev: pointer to SCSI device
4632 static int ufshcd_slave_configure(struct scsi_device *sdev)
4634 struct request_queue *q = sdev->request_queue;
4636 blk_queue_update_dma_pad(q, PRDT_DATA_BYTE_COUNT_PAD - 1);
4641 * ufshcd_slave_destroy - remove SCSI device configurations
4642 * @sdev: pointer to SCSI device
4644 static void ufshcd_slave_destroy(struct scsi_device *sdev)
4646 struct ufs_hba *hba;
4648 hba = shost_priv(sdev->host);
4649 /* Drop the reference as it won't be needed anymore */
4650 if (ufshcd_scsi_to_upiu_lun(sdev->lun) == UFS_UPIU_UFS_DEVICE_WLUN) {
4651 unsigned long flags;
4653 spin_lock_irqsave(hba->host->host_lock, flags);
4654 hba->sdev_ufs_device = NULL;
4655 spin_unlock_irqrestore(hba->host->host_lock, flags);
4660 * ufshcd_scsi_cmd_status - Update SCSI command result based on SCSI status
4661 * @lrbp: pointer to local reference block of completed command
4662 * @scsi_status: SCSI command status
4664 * Returns value base on SCSI command status
4667 ufshcd_scsi_cmd_status(struct ufshcd_lrb *lrbp, int scsi_status)
4671 switch (scsi_status) {
4672 case SAM_STAT_CHECK_CONDITION:
4673 ufshcd_copy_sense_data(lrbp);
4676 result |= DID_OK << 16 |
4677 COMMAND_COMPLETE << 8 |
4680 case SAM_STAT_TASK_SET_FULL:
4682 case SAM_STAT_TASK_ABORTED:
4683 ufshcd_copy_sense_data(lrbp);
4684 result |= scsi_status;
4687 result |= DID_ERROR << 16;
4689 } /* end of switch */
4695 * ufshcd_transfer_rsp_status - Get overall status of the response
4696 * @hba: per adapter instance
4697 * @lrbp: pointer to local reference block of completed command
4699 * Returns result of the command to notify SCSI midlayer
4702 ufshcd_transfer_rsp_status(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
4708 /* overall command status of utrd */
4709 ocs = ufshcd_get_tr_ocs(lrbp);
4713 result = ufshcd_get_req_rsp(lrbp->ucd_rsp_ptr);
4714 hba->ufs_stats.last_hibern8_exit_tstamp = ktime_set(0, 0);
4716 case UPIU_TRANSACTION_RESPONSE:
4718 * get the response UPIU result to extract
4719 * the SCSI command status
4721 result = ufshcd_get_rsp_upiu_result(lrbp->ucd_rsp_ptr);
4724 * get the result based on SCSI status response
4725 * to notify the SCSI midlayer of the command status
4727 scsi_status = result & MASK_SCSI_STATUS;
4728 result = ufshcd_scsi_cmd_status(lrbp, scsi_status);
4731 * Currently we are only supporting BKOPs exception
4732 * events hence we can ignore BKOPs exception event
4733 * during power management callbacks. BKOPs exception
4734 * event is not expected to be raised in runtime suspend
4735 * callback as it allows the urgent bkops.
4736 * During system suspend, we are anyway forcefully
4737 * disabling the bkops and if urgent bkops is needed
4738 * it will be enabled on system resume. Long term
4739 * solution could be to abort the system suspend if
4740 * UFS device needs urgent BKOPs.
4742 if (!hba->pm_op_in_progress &&
4743 ufshcd_is_exception_event(lrbp->ucd_rsp_ptr))
4744 schedule_work(&hba->eeh_work);
4746 case UPIU_TRANSACTION_REJECT_UPIU:
4747 /* TODO: handle Reject UPIU Response */
4748 result = DID_ERROR << 16;
4750 "Reject UPIU not fully implemented\n");
4754 "Unexpected request response code = %x\n",
4756 result = DID_ERROR << 16;
4761 result |= DID_ABORT << 16;
4763 case OCS_INVALID_COMMAND_STATUS:
4764 result |= DID_REQUEUE << 16;
4766 case OCS_INVALID_CMD_TABLE_ATTR:
4767 case OCS_INVALID_PRDT_ATTR:
4768 case OCS_MISMATCH_DATA_BUF_SIZE:
4769 case OCS_MISMATCH_RESP_UPIU_SIZE:
4770 case OCS_PEER_COMM_FAILURE:
4771 case OCS_FATAL_ERROR:
4773 result |= DID_ERROR << 16;
4775 "OCS error from controller = %x for tag %d\n",
4776 ocs, lrbp->task_tag);
4777 ufshcd_print_host_regs(hba);
4778 ufshcd_print_host_state(hba);
4780 } /* end of switch */
4782 if (host_byte(result) != DID_OK)
4783 ufshcd_print_trs(hba, 1 << lrbp->task_tag, true);
4788 * ufshcd_uic_cmd_compl - handle completion of uic command
4789 * @hba: per adapter instance
4790 * @intr_status: interrupt status generated by the controller
4792 static void ufshcd_uic_cmd_compl(struct ufs_hba *hba, u32 intr_status)
4794 if ((intr_status & UIC_COMMAND_COMPL) && hba->active_uic_cmd) {
4795 hba->active_uic_cmd->argument2 |=
4796 ufshcd_get_uic_cmd_result(hba);
4797 hba->active_uic_cmd->argument3 =
4798 ufshcd_get_dme_attr_val(hba);
4799 complete(&hba->active_uic_cmd->done);
4802 if ((intr_status & UFSHCD_UIC_PWR_MASK) && hba->uic_async_done)
4803 complete(hba->uic_async_done);
4807 * __ufshcd_transfer_req_compl - handle SCSI and query command completion
4808 * @hba: per adapter instance
4809 * @completed_reqs: requests to complete
4811 static void __ufshcd_transfer_req_compl(struct ufs_hba *hba,
4812 unsigned long completed_reqs)
4814 struct ufshcd_lrb *lrbp;
4815 struct scsi_cmnd *cmd;
4819 for_each_set_bit(index, &completed_reqs, hba->nutrs) {
4820 lrbp = &hba->lrb[index];
4823 ufshcd_add_command_trace(hba, index, "complete");
4824 result = ufshcd_transfer_rsp_status(hba, lrbp);
4825 scsi_dma_unmap(cmd);
4826 cmd->result = result;
4827 /* Mark completed command as NULL in LRB */
4829 clear_bit_unlock(index, &hba->lrb_in_use);
4830 /* Do not touch lrbp after scsi done */
4831 cmd->scsi_done(cmd);
4832 __ufshcd_release(hba);
4833 } else if (lrbp->command_type == UTP_CMD_TYPE_DEV_MANAGE ||
4834 lrbp->command_type == UTP_CMD_TYPE_UFS_STORAGE) {
4835 if (hba->dev_cmd.complete) {
4836 ufshcd_add_command_trace(hba, index,
4838 complete(hba->dev_cmd.complete);
4841 if (ufshcd_is_clkscaling_supported(hba))
4842 hba->clk_scaling.active_reqs--;
4844 lrbp->compl_time_stamp = ktime_get();
4847 /* clear corresponding bits of completed commands */
4848 hba->outstanding_reqs ^= completed_reqs;
4850 ufshcd_clk_scaling_update_busy(hba);
4852 /* we might have free'd some tags above */
4853 wake_up(&hba->dev_cmd.tag_wq);
4857 * ufshcd_transfer_req_compl - handle SCSI and query command completion
4858 * @hba: per adapter instance
4860 static void ufshcd_transfer_req_compl(struct ufs_hba *hba)
4862 unsigned long completed_reqs;
4865 /* Resetting interrupt aggregation counters first and reading the
4866 * DOOR_BELL afterward allows us to handle all the completed requests.
4867 * In order to prevent other interrupts starvation the DB is read once
4868 * after reset. The down side of this solution is the possibility of
4869 * false interrupt if device completes another request after resetting
4870 * aggregation and before reading the DB.
4872 if (ufshcd_is_intr_aggr_allowed(hba) &&
4873 !(hba->quirks & UFSHCI_QUIRK_SKIP_RESET_INTR_AGGR))
4874 ufshcd_reset_intr_aggr(hba);
4876 tr_doorbell = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
4877 completed_reqs = tr_doorbell ^ hba->outstanding_reqs;
4879 __ufshcd_transfer_req_compl(hba, completed_reqs);
4883 * ufshcd_disable_ee - disable exception event
4884 * @hba: per-adapter instance
4885 * @mask: exception event to disable
4887 * Disables exception event in the device so that the EVENT_ALERT
4890 * Returns zero on success, non-zero error value on failure.
4892 static int ufshcd_disable_ee(struct ufs_hba *hba, u16 mask)
4897 if (!(hba->ee_ctrl_mask & mask))
4900 val = hba->ee_ctrl_mask & ~mask;
4901 val &= MASK_EE_STATUS;
4902 err = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_WRITE_ATTR,
4903 QUERY_ATTR_IDN_EE_CONTROL, 0, 0, &val);
4905 hba->ee_ctrl_mask &= ~mask;
4911 * ufshcd_enable_ee - enable exception event
4912 * @hba: per-adapter instance
4913 * @mask: exception event to enable
4915 * Enable corresponding exception event in the device to allow
4916 * device to alert host in critical scenarios.
4918 * Returns zero on success, non-zero error value on failure.
4920 static int ufshcd_enable_ee(struct ufs_hba *hba, u16 mask)
4925 if (hba->ee_ctrl_mask & mask)
4928 val = hba->ee_ctrl_mask | mask;
4929 val &= MASK_EE_STATUS;
4930 err = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_WRITE_ATTR,
4931 QUERY_ATTR_IDN_EE_CONTROL, 0, 0, &val);
4933 hba->ee_ctrl_mask |= mask;
4939 * ufshcd_enable_auto_bkops - Allow device managed BKOPS
4940 * @hba: per-adapter instance
4942 * Allow device to manage background operations on its own. Enabling
4943 * this might lead to inconsistent latencies during normal data transfers
4944 * as the device is allowed to manage its own way of handling background
4947 * Returns zero on success, non-zero on failure.
4949 static int ufshcd_enable_auto_bkops(struct ufs_hba *hba)
4953 if (hba->auto_bkops_enabled)
4956 err = ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_SET_FLAG,
4957 QUERY_FLAG_IDN_BKOPS_EN, NULL);
4959 dev_err(hba->dev, "%s: failed to enable bkops %d\n",
4964 hba->auto_bkops_enabled = true;
4965 trace_ufshcd_auto_bkops_state(dev_name(hba->dev), "Enabled");
4967 /* No need of URGENT_BKOPS exception from the device */
4968 err = ufshcd_disable_ee(hba, MASK_EE_URGENT_BKOPS);
4970 dev_err(hba->dev, "%s: failed to disable exception event %d\n",
4977 * ufshcd_disable_auto_bkops - block device in doing background operations
4978 * @hba: per-adapter instance
4980 * Disabling background operations improves command response latency but
4981 * has drawback of device moving into critical state where the device is
4982 * not-operable. Make sure to call ufshcd_enable_auto_bkops() whenever the
4983 * host is idle so that BKOPS are managed effectively without any negative
4986 * Returns zero on success, non-zero on failure.
4988 static int ufshcd_disable_auto_bkops(struct ufs_hba *hba)
4992 if (!hba->auto_bkops_enabled)
4996 * If host assisted BKOPs is to be enabled, make sure
4997 * urgent bkops exception is allowed.
4999 err = ufshcd_enable_ee(hba, MASK_EE_URGENT_BKOPS);
5001 dev_err(hba->dev, "%s: failed to enable exception event %d\n",
5006 err = ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_CLEAR_FLAG,
5007 QUERY_FLAG_IDN_BKOPS_EN, NULL);
5009 dev_err(hba->dev, "%s: failed to disable bkops %d\n",
5011 ufshcd_disable_ee(hba, MASK_EE_URGENT_BKOPS);
5015 hba->auto_bkops_enabled = false;
5016 trace_ufshcd_auto_bkops_state(dev_name(hba->dev), "Disabled");
5022 * ufshcd_force_reset_auto_bkops - force reset auto bkops state
5023 * @hba: per adapter instance
5025 * After a device reset the device may toggle the BKOPS_EN flag
5026 * to default value. The s/w tracking variables should be updated
5027 * as well. This function would change the auto-bkops state based on
5028 * UFSHCD_CAP_KEEP_AUTO_BKOPS_ENABLED_EXCEPT_SUSPEND.
5030 static void ufshcd_force_reset_auto_bkops(struct ufs_hba *hba)
5032 if (ufshcd_keep_autobkops_enabled_except_suspend(hba)) {
5033 hba->auto_bkops_enabled = false;
5034 hba->ee_ctrl_mask |= MASK_EE_URGENT_BKOPS;
5035 ufshcd_enable_auto_bkops(hba);
5037 hba->auto_bkops_enabled = true;
5038 hba->ee_ctrl_mask &= ~MASK_EE_URGENT_BKOPS;
5039 ufshcd_disable_auto_bkops(hba);
5043 static inline int ufshcd_get_bkops_status(struct ufs_hba *hba, u32 *status)
5045 return ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
5046 QUERY_ATTR_IDN_BKOPS_STATUS, 0, 0, status);
5050 * ufshcd_bkops_ctrl - control the auto bkops based on current bkops status
5051 * @hba: per-adapter instance
5052 * @status: bkops_status value
5054 * Read the bkops_status from the UFS device and Enable fBackgroundOpsEn
5055 * flag in the device to permit background operations if the device
5056 * bkops_status is greater than or equal to "status" argument passed to
5057 * this function, disable otherwise.
5059 * Returns 0 for success, non-zero in case of failure.
5061 * NOTE: Caller of this function can check the "hba->auto_bkops_enabled" flag
5062 * to know whether auto bkops is enabled or disabled after this function
5063 * returns control to it.
5065 static int ufshcd_bkops_ctrl(struct ufs_hba *hba,
5066 enum bkops_status status)
5069 u32 curr_status = 0;
5071 err = ufshcd_get_bkops_status(hba, &curr_status);
5073 dev_err(hba->dev, "%s: failed to get BKOPS status %d\n",
5076 } else if (curr_status > BKOPS_STATUS_MAX) {
5077 dev_err(hba->dev, "%s: invalid BKOPS status %d\n",
5078 __func__, curr_status);
5083 if (curr_status >= status)
5084 err = ufshcd_enable_auto_bkops(hba);
5086 err = ufshcd_disable_auto_bkops(hba);
5092 * ufshcd_urgent_bkops - handle urgent bkops exception event
5093 * @hba: per-adapter instance
5095 * Enable fBackgroundOpsEn flag in the device to permit background
5098 * If BKOPs is enabled, this function returns 0, 1 if the bkops in not enabled
5099 * and negative error value for any other failure.
5101 static int ufshcd_urgent_bkops(struct ufs_hba *hba)
5103 return ufshcd_bkops_ctrl(hba, hba->urgent_bkops_lvl);
5106 static inline int ufshcd_get_ee_status(struct ufs_hba *hba, u32 *status)
5108 return ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
5109 QUERY_ATTR_IDN_EE_STATUS, 0, 0, status);
5112 static void ufshcd_bkops_exception_event_handler(struct ufs_hba *hba)
5115 u32 curr_status = 0;
5117 if (hba->is_urgent_bkops_lvl_checked)
5118 goto enable_auto_bkops;
5120 err = ufshcd_get_bkops_status(hba, &curr_status);
5122 dev_err(hba->dev, "%s: failed to get BKOPS status %d\n",
5128 * We are seeing that some devices are raising the urgent bkops
5129 * exception events even when BKOPS status doesn't indicate performace
5130 * impacted or critical. Handle these device by determining their urgent
5131 * bkops status at runtime.
5133 if (curr_status < BKOPS_STATUS_PERF_IMPACT) {
5134 dev_err(hba->dev, "%s: device raised urgent BKOPS exception for bkops status %d\n",
5135 __func__, curr_status);
5136 /* update the current status as the urgent bkops level */
5137 hba->urgent_bkops_lvl = curr_status;
5138 hba->is_urgent_bkops_lvl_checked = true;
5142 err = ufshcd_enable_auto_bkops(hba);
5145 dev_err(hba->dev, "%s: failed to handle urgent bkops %d\n",
5150 * ufshcd_exception_event_handler - handle exceptions raised by device
5151 * @work: pointer to work data
5153 * Read bExceptionEventStatus attribute from the device and handle the
5154 * exception event accordingly.
5156 static void ufshcd_exception_event_handler(struct work_struct *work)
5158 struct ufs_hba *hba;
5161 hba = container_of(work, struct ufs_hba, eeh_work);
5163 pm_runtime_get_sync(hba->dev);
5164 scsi_block_requests(hba->host);
5165 err = ufshcd_get_ee_status(hba, &status);
5167 dev_err(hba->dev, "%s: failed to get exception status %d\n",
5172 status &= hba->ee_ctrl_mask;
5174 if (status & MASK_EE_URGENT_BKOPS)
5175 ufshcd_bkops_exception_event_handler(hba);
5178 scsi_unblock_requests(hba->host);
5179 pm_runtime_put_sync(hba->dev);
5183 /* Complete requests that have door-bell cleared */
5184 static void ufshcd_complete_requests(struct ufs_hba *hba)
5186 ufshcd_transfer_req_compl(hba);
5187 ufshcd_tmc_handler(hba);
5191 * ufshcd_quirk_dl_nac_errors - This function checks if error handling is
5192 * to recover from the DL NAC errors or not.
5193 * @hba: per-adapter instance
5195 * Returns true if error handling is required, false otherwise
5197 static bool ufshcd_quirk_dl_nac_errors(struct ufs_hba *hba)
5199 unsigned long flags;
5200 bool err_handling = true;
5202 spin_lock_irqsave(hba->host->host_lock, flags);
5204 * UFS_DEVICE_QUIRK_RECOVERY_FROM_DL_NAC_ERRORS only workaround the
5205 * device fatal error and/or DL NAC & REPLAY timeout errors.
5207 if (hba->saved_err & (CONTROLLER_FATAL_ERROR | SYSTEM_BUS_FATAL_ERROR))
5210 if ((hba->saved_err & DEVICE_FATAL_ERROR) ||
5211 ((hba->saved_err & UIC_ERROR) &&
5212 (hba->saved_uic_err & UFSHCD_UIC_DL_TCx_REPLAY_ERROR)))
5215 if ((hba->saved_err & UIC_ERROR) &&
5216 (hba->saved_uic_err & UFSHCD_UIC_DL_NAC_RECEIVED_ERROR)) {
5219 * wait for 50ms to see if we can get any other errors or not.
5221 spin_unlock_irqrestore(hba->host->host_lock, flags);
5223 spin_lock_irqsave(hba->host->host_lock, flags);
5226 * now check if we have got any other severe errors other than
5229 if ((hba->saved_err & INT_FATAL_ERRORS) ||
5230 ((hba->saved_err & UIC_ERROR) &&
5231 (hba->saved_uic_err & ~UFSHCD_UIC_DL_NAC_RECEIVED_ERROR)))
5235 * As DL NAC is the only error received so far, send out NOP
5236 * command to confirm if link is still active or not.
5237 * - If we don't get any response then do error recovery.
5238 * - If we get response then clear the DL NAC error bit.
5241 spin_unlock_irqrestore(hba->host->host_lock, flags);
5242 err = ufshcd_verify_dev_init(hba);
5243 spin_lock_irqsave(hba->host->host_lock, flags);
5248 /* Link seems to be alive hence ignore the DL NAC errors */
5249 if (hba->saved_uic_err == UFSHCD_UIC_DL_NAC_RECEIVED_ERROR)
5250 hba->saved_err &= ~UIC_ERROR;
5251 /* clear NAC error */
5252 hba->saved_uic_err &= ~UFSHCD_UIC_DL_NAC_RECEIVED_ERROR;
5253 if (!hba->saved_uic_err) {
5254 err_handling = false;
5259 spin_unlock_irqrestore(hba->host->host_lock, flags);
5260 return err_handling;
5264 * ufshcd_err_handler - handle UFS errors that require s/w attention
5265 * @work: pointer to work structure
5267 static void ufshcd_err_handler(struct work_struct *work)
5269 struct ufs_hba *hba;
5270 unsigned long flags;
5275 bool needs_reset = false;
5277 hba = container_of(work, struct ufs_hba, eh_work);
5279 pm_runtime_get_sync(hba->dev);
5280 ufshcd_hold(hba, false);
5282 spin_lock_irqsave(hba->host->host_lock, flags);
5283 if (hba->ufshcd_state == UFSHCD_STATE_RESET)
5286 hba->ufshcd_state = UFSHCD_STATE_RESET;
5287 ufshcd_set_eh_in_progress(hba);
5289 /* Complete requests that have door-bell cleared by h/w */
5290 ufshcd_complete_requests(hba);
5292 if (hba->dev_quirks & UFS_DEVICE_QUIRK_RECOVERY_FROM_DL_NAC_ERRORS) {
5295 spin_unlock_irqrestore(hba->host->host_lock, flags);
5296 /* release the lock as ufshcd_quirk_dl_nac_errors() may sleep */
5297 ret = ufshcd_quirk_dl_nac_errors(hba);
5298 spin_lock_irqsave(hba->host->host_lock, flags);
5300 goto skip_err_handling;
5302 if ((hba->saved_err & INT_FATAL_ERRORS) ||
5303 (hba->saved_err & UFSHCD_UIC_HIBERN8_MASK) ||
5304 ((hba->saved_err & UIC_ERROR) &&
5305 (hba->saved_uic_err & (UFSHCD_UIC_DL_PA_INIT_ERROR |
5306 UFSHCD_UIC_DL_NAC_RECEIVED_ERROR |
5307 UFSHCD_UIC_DL_TCx_REPLAY_ERROR))))
5311 * if host reset is required then skip clearing the pending
5312 * transfers forcefully because they will automatically get
5313 * cleared after link startup.
5316 goto skip_pending_xfer_clear;
5318 /* release lock as clear command might sleep */
5319 spin_unlock_irqrestore(hba->host->host_lock, flags);
5320 /* Clear pending transfer requests */
5321 for_each_set_bit(tag, &hba->outstanding_reqs, hba->nutrs) {
5322 if (ufshcd_clear_cmd(hba, tag)) {
5324 goto lock_skip_pending_xfer_clear;
5328 /* Clear pending task management requests */
5329 for_each_set_bit(tag, &hba->outstanding_tasks, hba->nutmrs) {
5330 if (ufshcd_clear_tm_cmd(hba, tag)) {
5332 goto lock_skip_pending_xfer_clear;
5336 lock_skip_pending_xfer_clear:
5337 spin_lock_irqsave(hba->host->host_lock, flags);
5339 /* Complete the requests that are cleared by s/w */
5340 ufshcd_complete_requests(hba);
5342 if (err_xfer || err_tm)
5345 skip_pending_xfer_clear:
5346 /* Fatal errors need reset */
5348 unsigned long max_doorbells = (1UL << hba->nutrs) - 1;
5351 * ufshcd_reset_and_restore() does the link reinitialization
5352 * which will need atleast one empty doorbell slot to send the
5353 * device management commands (NOP and query commands).
5354 * If there is no slot empty at this moment then free up last
5357 if (hba->outstanding_reqs == max_doorbells)
5358 __ufshcd_transfer_req_compl(hba,
5359 (1UL << (hba->nutrs - 1)));
5361 spin_unlock_irqrestore(hba->host->host_lock, flags);
5362 err = ufshcd_reset_and_restore(hba);
5363 spin_lock_irqsave(hba->host->host_lock, flags);
5365 dev_err(hba->dev, "%s: reset and restore failed\n",
5367 hba->ufshcd_state = UFSHCD_STATE_ERROR;
5370 * Inform scsi mid-layer that we did reset and allow to handle
5371 * Unit Attention properly.
5373 scsi_report_bus_reset(hba->host, 0);
5375 hba->saved_uic_err = 0;
5380 hba->ufshcd_state = UFSHCD_STATE_OPERATIONAL;
5381 if (hba->saved_err || hba->saved_uic_err)
5382 dev_err_ratelimited(hba->dev, "%s: exit: saved_err 0x%x saved_uic_err 0x%x",
5383 __func__, hba->saved_err, hba->saved_uic_err);
5386 ufshcd_clear_eh_in_progress(hba);
5389 spin_unlock_irqrestore(hba->host->host_lock, flags);
5390 ufshcd_scsi_unblock_requests(hba);
5391 ufshcd_release(hba);
5392 pm_runtime_put_sync(hba->dev);
5396 * ufshcd_update_uic_error - check and set fatal UIC error flags.
5397 * @hba: per-adapter instance
5399 static void ufshcd_update_uic_error(struct ufs_hba *hba)
5403 /* PHY layer lane error */
5404 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_PHY_ADAPTER_LAYER);
5405 /* Ignore LINERESET indication, as this is not an error */
5406 if ((reg & UIC_PHY_ADAPTER_LAYER_ERROR) &&
5407 (reg & UIC_PHY_ADAPTER_LAYER_LANE_ERR_MASK)) {
5409 * To know whether this error is fatal or not, DB timeout
5410 * must be checked but this error is handled separately.
5412 dev_dbg(hba->dev, "%s: UIC Lane error reported\n", __func__);
5413 ufshcd_update_reg_hist(&hba->ufs_stats.pa_err, reg);
5416 /* PA_INIT_ERROR is fatal and needs UIC reset */
5417 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_DATA_LINK_LAYER);
5419 ufshcd_update_reg_hist(&hba->ufs_stats.dl_err, reg);
5421 if (reg & UIC_DATA_LINK_LAYER_ERROR_PA_INIT)
5422 hba->uic_error |= UFSHCD_UIC_DL_PA_INIT_ERROR;
5423 else if (hba->dev_quirks &
5424 UFS_DEVICE_QUIRK_RECOVERY_FROM_DL_NAC_ERRORS) {
5425 if (reg & UIC_DATA_LINK_LAYER_ERROR_NAC_RECEIVED)
5427 UFSHCD_UIC_DL_NAC_RECEIVED_ERROR;
5428 else if (reg & UIC_DATA_LINK_LAYER_ERROR_TCx_REPLAY_TIMEOUT)
5429 hba->uic_error |= UFSHCD_UIC_DL_TCx_REPLAY_ERROR;
5432 /* UIC NL/TL/DME errors needs software retry */
5433 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_NETWORK_LAYER);
5435 ufshcd_update_reg_hist(&hba->ufs_stats.nl_err, reg);
5436 hba->uic_error |= UFSHCD_UIC_NL_ERROR;
5439 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_TRANSPORT_LAYER);
5441 ufshcd_update_reg_hist(&hba->ufs_stats.tl_err, reg);
5442 hba->uic_error |= UFSHCD_UIC_TL_ERROR;
5445 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_DME);
5447 ufshcd_update_reg_hist(&hba->ufs_stats.dme_err, reg);
5448 hba->uic_error |= UFSHCD_UIC_DME_ERROR;
5451 dev_dbg(hba->dev, "%s: UIC error flags = 0x%08x\n",
5452 __func__, hba->uic_error);
5455 static bool ufshcd_is_auto_hibern8_error(struct ufs_hba *hba,
5458 if (!ufshcd_is_auto_hibern8_supported(hba))
5461 if (!(intr_mask & UFSHCD_UIC_HIBERN8_MASK))
5464 if (hba->active_uic_cmd &&
5465 (hba->active_uic_cmd->command == UIC_CMD_DME_HIBER_ENTER ||
5466 hba->active_uic_cmd->command == UIC_CMD_DME_HIBER_EXIT))
5473 * ufshcd_check_errors - Check for errors that need s/w attention
5474 * @hba: per-adapter instance
5476 static void ufshcd_check_errors(struct ufs_hba *hba)
5478 bool queue_eh_work = false;
5480 if (hba->errors & INT_FATAL_ERRORS) {
5481 ufshcd_update_reg_hist(&hba->ufs_stats.fatal_err, hba->errors);
5482 queue_eh_work = true;
5485 if (hba->errors & UIC_ERROR) {
5487 ufshcd_update_uic_error(hba);
5489 queue_eh_work = true;
5492 if (hba->errors & UFSHCD_UIC_HIBERN8_MASK) {
5494 "%s: Auto Hibern8 %s failed - status: 0x%08x, upmcrs: 0x%08x\n",
5495 __func__, (hba->errors & UIC_HIBERNATE_ENTER) ?
5497 hba->errors, ufshcd_get_upmcrs(hba));
5498 ufshcd_update_reg_hist(&hba->ufs_stats.auto_hibern8_err,
5500 queue_eh_work = true;
5503 if (queue_eh_work) {
5505 * update the transfer error masks to sticky bits, let's do this
5506 * irrespective of current ufshcd_state.
5508 hba->saved_err |= hba->errors;
5509 hba->saved_uic_err |= hba->uic_error;
5511 /* handle fatal errors only when link is functional */
5512 if (hba->ufshcd_state == UFSHCD_STATE_OPERATIONAL) {
5513 /* block commands from scsi mid-layer */
5514 ufshcd_scsi_block_requests(hba);
5516 hba->ufshcd_state = UFSHCD_STATE_EH_SCHEDULED;
5518 /* dump controller state before resetting */
5519 if (hba->saved_err & (INT_FATAL_ERRORS | UIC_ERROR)) {
5520 bool pr_prdt = !!(hba->saved_err &
5521 SYSTEM_BUS_FATAL_ERROR);
5523 dev_err(hba->dev, "%s: saved_err 0x%x saved_uic_err 0x%x\n",
5524 __func__, hba->saved_err,
5525 hba->saved_uic_err);
5527 ufshcd_print_host_regs(hba);
5528 ufshcd_print_pwr_info(hba);
5529 ufshcd_print_tmrs(hba, hba->outstanding_tasks);
5530 ufshcd_print_trs(hba, hba->outstanding_reqs,
5533 schedule_work(&hba->eh_work);
5537 * if (!queue_eh_work) -
5538 * Other errors are either non-fatal where host recovers
5539 * itself without s/w intervention or errors that will be
5540 * handled by the SCSI core layer.
5545 * ufshcd_tmc_handler - handle task management function completion
5546 * @hba: per adapter instance
5548 static void ufshcd_tmc_handler(struct ufs_hba *hba)
5552 tm_doorbell = ufshcd_readl(hba, REG_UTP_TASK_REQ_DOOR_BELL);
5553 hba->tm_condition = tm_doorbell ^ hba->outstanding_tasks;
5554 wake_up(&hba->tm_wq);
5558 * ufshcd_sl_intr - Interrupt service routine
5559 * @hba: per adapter instance
5560 * @intr_status: contains interrupts generated by the controller
5562 static void ufshcd_sl_intr(struct ufs_hba *hba, u32 intr_status)
5564 hba->errors = UFSHCD_ERROR_MASK & intr_status;
5566 if (ufshcd_is_auto_hibern8_error(hba, intr_status))
5567 hba->errors |= (UFSHCD_UIC_HIBERN8_MASK & intr_status);
5570 ufshcd_check_errors(hba);
5572 if (intr_status & UFSHCD_UIC_MASK)
5573 ufshcd_uic_cmd_compl(hba, intr_status);
5575 if (intr_status & UTP_TASK_REQ_COMPL)
5576 ufshcd_tmc_handler(hba);
5578 if (intr_status & UTP_TRANSFER_REQ_COMPL)
5579 ufshcd_transfer_req_compl(hba);
5583 * ufshcd_intr - Main interrupt service routine
5585 * @__hba: pointer to adapter instance
5587 * Returns IRQ_HANDLED - If interrupt is valid
5588 * IRQ_NONE - If invalid interrupt
5590 static irqreturn_t ufshcd_intr(int irq, void *__hba)
5592 u32 intr_status, enabled_intr_status;
5593 irqreturn_t retval = IRQ_NONE;
5594 struct ufs_hba *hba = __hba;
5595 int retries = hba->nutrs;
5597 spin_lock(hba->host->host_lock);
5598 intr_status = ufshcd_readl(hba, REG_INTERRUPT_STATUS);
5601 * There could be max of hba->nutrs reqs in flight and in worst case
5602 * if the reqs get finished 1 by 1 after the interrupt status is
5603 * read, make sure we handle them by checking the interrupt status
5604 * again in a loop until we process all of the reqs before returning.
5607 enabled_intr_status =
5608 intr_status & ufshcd_readl(hba, REG_INTERRUPT_ENABLE);
5610 ufshcd_writel(hba, intr_status, REG_INTERRUPT_STATUS);
5611 if (enabled_intr_status) {
5612 ufshcd_sl_intr(hba, enabled_intr_status);
5613 retval = IRQ_HANDLED;
5616 intr_status = ufshcd_readl(hba, REG_INTERRUPT_STATUS);
5617 } while (intr_status && --retries);
5619 spin_unlock(hba->host->host_lock);
5623 static int ufshcd_clear_tm_cmd(struct ufs_hba *hba, int tag)
5626 u32 mask = 1 << tag;
5627 unsigned long flags;
5629 if (!test_bit(tag, &hba->outstanding_tasks))
5632 spin_lock_irqsave(hba->host->host_lock, flags);
5633 ufshcd_utmrl_clear(hba, tag);
5634 spin_unlock_irqrestore(hba->host->host_lock, flags);
5636 /* poll for max. 1 sec to clear door bell register by h/w */
5637 err = ufshcd_wait_for_register(hba,
5638 REG_UTP_TASK_REQ_DOOR_BELL,
5639 mask, 0, 1000, 1000, true);
5644 static int __ufshcd_issue_tm_cmd(struct ufs_hba *hba,
5645 struct utp_task_req_desc *treq, u8 tm_function)
5647 struct Scsi_Host *host = hba->host;
5648 unsigned long flags;
5649 int free_slot, task_tag, err;
5652 * Get free slot, sleep if slots are unavailable.
5653 * Even though we use wait_event() which sleeps indefinitely,
5654 * the maximum wait time is bounded by %TM_CMD_TIMEOUT.
5656 wait_event(hba->tm_tag_wq, ufshcd_get_tm_free_slot(hba, &free_slot));
5657 ufshcd_hold(hba, false);
5659 spin_lock_irqsave(host->host_lock, flags);
5660 task_tag = hba->nutrs + free_slot;
5662 treq->req_header.dword_0 |= cpu_to_be32(task_tag);
5664 memcpy(hba->utmrdl_base_addr + free_slot, treq, sizeof(*treq));
5665 ufshcd_vops_setup_task_mgmt(hba, free_slot, tm_function);
5667 /* send command to the controller */
5668 __set_bit(free_slot, &hba->outstanding_tasks);
5670 /* Make sure descriptors are ready before ringing the task doorbell */
5673 ufshcd_writel(hba, 1 << free_slot, REG_UTP_TASK_REQ_DOOR_BELL);
5674 /* Make sure that doorbell is committed immediately */
5677 spin_unlock_irqrestore(host->host_lock, flags);
5679 ufshcd_add_tm_upiu_trace(hba, task_tag, "tm_send");
5681 /* wait until the task management command is completed */
5682 err = wait_event_timeout(hba->tm_wq,
5683 test_bit(free_slot, &hba->tm_condition),
5684 msecs_to_jiffies(TM_CMD_TIMEOUT));
5686 ufshcd_add_tm_upiu_trace(hba, task_tag, "tm_complete_err");
5687 dev_err(hba->dev, "%s: task management cmd 0x%.2x timed-out\n",
5688 __func__, tm_function);
5689 if (ufshcd_clear_tm_cmd(hba, free_slot))
5690 dev_WARN(hba->dev, "%s: unable clear tm cmd (slot %d) after timeout\n",
5691 __func__, free_slot);
5695 memcpy(treq, hba->utmrdl_base_addr + free_slot, sizeof(*treq));
5697 ufshcd_add_tm_upiu_trace(hba, task_tag, "tm_complete");
5700 spin_lock_irqsave(hba->host->host_lock, flags);
5701 __clear_bit(free_slot, &hba->outstanding_tasks);
5702 spin_unlock_irqrestore(hba->host->host_lock, flags);
5704 clear_bit(free_slot, &hba->tm_condition);
5705 ufshcd_put_tm_slot(hba, free_slot);
5706 wake_up(&hba->tm_tag_wq);
5708 ufshcd_release(hba);
5713 * ufshcd_issue_tm_cmd - issues task management commands to controller
5714 * @hba: per adapter instance
5715 * @lun_id: LUN ID to which TM command is sent
5716 * @task_id: task ID to which the TM command is applicable
5717 * @tm_function: task management function opcode
5718 * @tm_response: task management service response return value
5720 * Returns non-zero value on error, zero on success.
5722 static int ufshcd_issue_tm_cmd(struct ufs_hba *hba, int lun_id, int task_id,
5723 u8 tm_function, u8 *tm_response)
5725 struct utp_task_req_desc treq = { { 0 }, };
5728 /* Configure task request descriptor */
5729 treq.header.dword_0 = cpu_to_le32(UTP_REQ_DESC_INT_CMD);
5730 treq.header.dword_2 = cpu_to_le32(OCS_INVALID_COMMAND_STATUS);
5732 /* Configure task request UPIU */
5733 treq.req_header.dword_0 = cpu_to_be32(lun_id << 8) |
5734 cpu_to_be32(UPIU_TRANSACTION_TASK_REQ << 24);
5735 treq.req_header.dword_1 = cpu_to_be32(tm_function << 16);
5738 * The host shall provide the same value for LUN field in the basic
5739 * header and for Input Parameter.
5741 treq.input_param1 = cpu_to_be32(lun_id);
5742 treq.input_param2 = cpu_to_be32(task_id);
5744 err = __ufshcd_issue_tm_cmd(hba, &treq, tm_function);
5745 if (err == -ETIMEDOUT)
5748 ocs_value = le32_to_cpu(treq.header.dword_2) & MASK_OCS;
5749 if (ocs_value != OCS_SUCCESS)
5750 dev_err(hba->dev, "%s: failed, ocs = 0x%x\n",
5751 __func__, ocs_value);
5752 else if (tm_response)
5753 *tm_response = be32_to_cpu(treq.output_param1) &
5754 MASK_TM_SERVICE_RESP;
5759 * ufshcd_issue_devman_upiu_cmd - API for sending "utrd" type requests
5760 * @hba: per-adapter instance
5761 * @req_upiu: upiu request
5762 * @rsp_upiu: upiu reply
5763 * @msgcode: message code, one of UPIU Transaction Codes Initiator to Target
5764 * @desc_buff: pointer to descriptor buffer, NULL if NA
5765 * @buff_len: descriptor size, 0 if NA
5766 * @desc_op: descriptor operation
5768 * Those type of requests uses UTP Transfer Request Descriptor - utrd.
5769 * Therefore, it "rides" the device management infrastructure: uses its tag and
5770 * tasks work queues.
5772 * Since there is only one available tag for device management commands,
5773 * the caller is expected to hold the hba->dev_cmd.lock mutex.
5775 static int ufshcd_issue_devman_upiu_cmd(struct ufs_hba *hba,
5776 struct utp_upiu_req *req_upiu,
5777 struct utp_upiu_req *rsp_upiu,
5778 u8 *desc_buff, int *buff_len,
5780 enum query_opcode desc_op)
5782 struct ufshcd_lrb *lrbp;
5785 struct completion wait;
5786 unsigned long flags;
5789 down_read(&hba->clk_scaling_lock);
5791 wait_event(hba->dev_cmd.tag_wq, ufshcd_get_dev_cmd_tag(hba, &tag));
5793 init_completion(&wait);
5794 lrbp = &hba->lrb[tag];
5798 lrbp->sense_bufflen = 0;
5799 lrbp->sense_buffer = NULL;
5800 lrbp->task_tag = tag;
5802 lrbp->intr_cmd = true;
5803 hba->dev_cmd.type = cmd_type;
5805 switch (hba->ufs_version) {
5806 case UFSHCI_VERSION_10:
5807 case UFSHCI_VERSION_11:
5808 lrbp->command_type = UTP_CMD_TYPE_DEV_MANAGE;
5811 lrbp->command_type = UTP_CMD_TYPE_UFS_STORAGE;
5815 /* update the task tag in the request upiu */
5816 req_upiu->header.dword_0 |= cpu_to_be32(tag);
5818 ufshcd_prepare_req_desc_hdr(lrbp, &upiu_flags, DMA_NONE);
5820 /* just copy the upiu request as it is */
5821 memcpy(lrbp->ucd_req_ptr, req_upiu, sizeof(*lrbp->ucd_req_ptr));
5822 if (desc_buff && desc_op == UPIU_QUERY_OPCODE_WRITE_DESC) {
5823 /* The Data Segment Area is optional depending upon the query
5824 * function value. for WRITE DESCRIPTOR, the data segment
5825 * follows right after the tsf.
5827 memcpy(lrbp->ucd_req_ptr + 1, desc_buff, *buff_len);
5831 memset(lrbp->ucd_rsp_ptr, 0, sizeof(struct utp_upiu_rsp));
5833 hba->dev_cmd.complete = &wait;
5835 /* Make sure descriptors are ready before ringing the doorbell */
5837 spin_lock_irqsave(hba->host->host_lock, flags);
5838 ufshcd_send_command(hba, tag);
5839 spin_unlock_irqrestore(hba->host->host_lock, flags);
5842 * ignore the returning value here - ufshcd_check_query_response is
5843 * bound to fail since dev_cmd.query and dev_cmd.type were left empty.
5844 * read the response directly ignoring all errors.
5846 ufshcd_wait_for_dev_cmd(hba, lrbp, QUERY_REQ_TIMEOUT);
5848 /* just copy the upiu response as it is */
5849 memcpy(rsp_upiu, lrbp->ucd_rsp_ptr, sizeof(*rsp_upiu));
5850 if (desc_buff && desc_op == UPIU_QUERY_OPCODE_READ_DESC) {
5851 u8 *descp = (u8 *)lrbp->ucd_rsp_ptr + sizeof(*rsp_upiu);
5852 u16 resp_len = be32_to_cpu(lrbp->ucd_rsp_ptr->header.dword_2) &
5853 MASK_QUERY_DATA_SEG_LEN;
5855 if (*buff_len >= resp_len) {
5856 memcpy(desc_buff, descp, resp_len);
5857 *buff_len = resp_len;
5859 dev_warn(hba->dev, "rsp size is bigger than buffer");
5865 ufshcd_put_dev_cmd_tag(hba, tag);
5866 wake_up(&hba->dev_cmd.tag_wq);
5867 up_read(&hba->clk_scaling_lock);
5872 * ufshcd_exec_raw_upiu_cmd - API function for sending raw upiu commands
5873 * @hba: per-adapter instance
5874 * @req_upiu: upiu request
5875 * @rsp_upiu: upiu reply - only 8 DW as we do not support scsi commands
5876 * @msgcode: message code, one of UPIU Transaction Codes Initiator to Target
5877 * @desc_buff: pointer to descriptor buffer, NULL if NA
5878 * @buff_len: descriptor size, 0 if NA
5879 * @desc_op: descriptor operation
5881 * Supports UTP Transfer requests (nop and query), and UTP Task
5882 * Management requests.
5883 * It is up to the caller to fill the upiu conent properly, as it will
5884 * be copied without any further input validations.
5886 int ufshcd_exec_raw_upiu_cmd(struct ufs_hba *hba,
5887 struct utp_upiu_req *req_upiu,
5888 struct utp_upiu_req *rsp_upiu,
5890 u8 *desc_buff, int *buff_len,
5891 enum query_opcode desc_op)
5894 int cmd_type = DEV_CMD_TYPE_QUERY;
5895 struct utp_task_req_desc treq = { { 0 }, };
5897 u8 tm_f = be32_to_cpu(req_upiu->header.dword_1) >> 16 & MASK_TM_FUNC;
5900 case UPIU_TRANSACTION_NOP_OUT:
5901 cmd_type = DEV_CMD_TYPE_NOP;
5903 case UPIU_TRANSACTION_QUERY_REQ:
5904 ufshcd_hold(hba, false);
5905 mutex_lock(&hba->dev_cmd.lock);
5906 err = ufshcd_issue_devman_upiu_cmd(hba, req_upiu, rsp_upiu,
5907 desc_buff, buff_len,
5909 mutex_unlock(&hba->dev_cmd.lock);
5910 ufshcd_release(hba);
5913 case UPIU_TRANSACTION_TASK_REQ:
5914 treq.header.dword_0 = cpu_to_le32(UTP_REQ_DESC_INT_CMD);
5915 treq.header.dword_2 = cpu_to_le32(OCS_INVALID_COMMAND_STATUS);
5917 memcpy(&treq.req_header, req_upiu, sizeof(*req_upiu));
5919 err = __ufshcd_issue_tm_cmd(hba, &treq, tm_f);
5920 if (err == -ETIMEDOUT)
5923 ocs_value = le32_to_cpu(treq.header.dword_2) & MASK_OCS;
5924 if (ocs_value != OCS_SUCCESS) {
5925 dev_err(hba->dev, "%s: failed, ocs = 0x%x\n", __func__,
5930 memcpy(rsp_upiu, &treq.rsp_header, sizeof(*rsp_upiu));
5943 * ufshcd_eh_device_reset_handler - device reset handler registered to
5945 * @cmd: SCSI command pointer
5947 * Returns SUCCESS/FAILED
5949 static int ufshcd_eh_device_reset_handler(struct scsi_cmnd *cmd)
5951 struct Scsi_Host *host;
5952 struct ufs_hba *hba;
5957 struct ufshcd_lrb *lrbp;
5958 unsigned long flags;
5960 host = cmd->device->host;
5961 hba = shost_priv(host);
5962 tag = cmd->request->tag;
5964 lrbp = &hba->lrb[tag];
5965 err = ufshcd_issue_tm_cmd(hba, lrbp->lun, 0, UFS_LOGICAL_RESET, &resp);
5966 if (err || resp != UPIU_TASK_MANAGEMENT_FUNC_COMPL) {
5972 /* clear the commands that were pending for corresponding LUN */
5973 for_each_set_bit(pos, &hba->outstanding_reqs, hba->nutrs) {
5974 if (hba->lrb[pos].lun == lrbp->lun) {
5975 err = ufshcd_clear_cmd(hba, pos);
5980 spin_lock_irqsave(host->host_lock, flags);
5981 ufshcd_transfer_req_compl(hba);
5982 spin_unlock_irqrestore(host->host_lock, flags);
5985 hba->req_abort_count = 0;
5986 ufshcd_update_reg_hist(&hba->ufs_stats.dev_reset, (u32)err);
5990 dev_err(hba->dev, "%s: failed with err %d\n", __func__, err);
5996 static void ufshcd_set_req_abort_skip(struct ufs_hba *hba, unsigned long bitmap)
5998 struct ufshcd_lrb *lrbp;
6001 for_each_set_bit(tag, &bitmap, hba->nutrs) {
6002 lrbp = &hba->lrb[tag];
6003 lrbp->req_abort_skip = true;
6008 * ufshcd_abort - abort a specific command
6009 * @cmd: SCSI command pointer
6011 * Abort the pending command in device by sending UFS_ABORT_TASK task management
6012 * command, and in host controller by clearing the door-bell register. There can
6013 * be race between controller sending the command to the device while abort is
6014 * issued. To avoid that, first issue UFS_QUERY_TASK to check if the command is
6015 * really issued and then try to abort it.
6017 * Returns SUCCESS/FAILED
6019 static int ufshcd_abort(struct scsi_cmnd *cmd)
6021 struct Scsi_Host *host;
6022 struct ufs_hba *hba;
6023 unsigned long flags;
6028 struct ufshcd_lrb *lrbp;
6031 host = cmd->device->host;
6032 hba = shost_priv(host);
6033 tag = cmd->request->tag;
6034 lrbp = &hba->lrb[tag];
6035 if (!ufshcd_valid_tag(hba, tag)) {
6037 "%s: invalid command tag %d: cmd=0x%p, cmd->request=0x%p",
6038 __func__, tag, cmd, cmd->request);
6043 * Task abort to the device W-LUN is illegal. When this command
6044 * will fail, due to spec violation, scsi err handling next step
6045 * will be to send LU reset which, again, is a spec violation.
6046 * To avoid these unnecessary/illegal step we skip to the last error
6047 * handling stage: reset and restore.
6049 if (lrbp->lun == UFS_UPIU_UFS_DEVICE_WLUN)
6050 return ufshcd_eh_host_reset_handler(cmd);
6052 ufshcd_hold(hba, false);
6053 reg = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
6054 /* If command is already aborted/completed, return SUCCESS */
6055 if (!(test_bit(tag, &hba->outstanding_reqs))) {
6057 "%s: cmd at tag %d already completed, outstanding=0x%lx, doorbell=0x%x\n",
6058 __func__, tag, hba->outstanding_reqs, reg);
6062 if (!(reg & (1 << tag))) {
6064 "%s: cmd was completed, but without a notifying intr, tag = %d",
6068 /* Print Transfer Request of aborted task */
6069 dev_err(hba->dev, "%s: Device abort task at tag %d\n", __func__, tag);
6072 * Print detailed info about aborted request.
6073 * As more than one request might get aborted at the same time,
6074 * print full information only for the first aborted request in order
6075 * to reduce repeated printouts. For other aborted requests only print
6078 scsi_print_command(hba->lrb[tag].cmd);
6079 if (!hba->req_abort_count) {
6080 ufshcd_update_reg_hist(&hba->ufs_stats.task_abort, 0);
6081 ufshcd_print_host_regs(hba);
6082 ufshcd_print_host_state(hba);
6083 ufshcd_print_pwr_info(hba);
6084 ufshcd_print_trs(hba, 1 << tag, true);
6086 ufshcd_print_trs(hba, 1 << tag, false);
6088 hba->req_abort_count++;
6090 /* Skip task abort in case previous aborts failed and report failure */
6091 if (lrbp->req_abort_skip) {
6096 for (poll_cnt = 100; poll_cnt; poll_cnt--) {
6097 err = ufshcd_issue_tm_cmd(hba, lrbp->lun, lrbp->task_tag,
6098 UFS_QUERY_TASK, &resp);
6099 if (!err && resp == UPIU_TASK_MANAGEMENT_FUNC_SUCCEEDED) {
6100 /* cmd pending in the device */
6101 dev_err(hba->dev, "%s: cmd pending in the device. tag = %d\n",
6104 } else if (!err && resp == UPIU_TASK_MANAGEMENT_FUNC_COMPL) {
6106 * cmd not pending in the device, check if it is
6109 dev_err(hba->dev, "%s: cmd at tag %d not pending in the device.\n",
6111 reg = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
6112 if (reg & (1 << tag)) {
6113 /* sleep for max. 200us to stabilize */
6114 usleep_range(100, 200);
6117 /* command completed already */
6118 dev_err(hba->dev, "%s: cmd at tag %d successfully cleared from DB.\n",
6123 "%s: no response from device. tag = %d, err %d\n",
6124 __func__, tag, err);
6126 err = resp; /* service response error */
6136 err = ufshcd_issue_tm_cmd(hba, lrbp->lun, lrbp->task_tag,
6137 UFS_ABORT_TASK, &resp);
6138 if (err || resp != UPIU_TASK_MANAGEMENT_FUNC_COMPL) {
6140 err = resp; /* service response error */
6141 dev_err(hba->dev, "%s: issued. tag = %d, err %d\n",
6142 __func__, tag, err);
6147 err = ufshcd_clear_cmd(hba, tag);
6149 dev_err(hba->dev, "%s: Failed clearing cmd at tag %d, err %d\n",
6150 __func__, tag, err);
6154 scsi_dma_unmap(cmd);
6156 spin_lock_irqsave(host->host_lock, flags);
6157 ufshcd_outstanding_req_clear(hba, tag);
6158 hba->lrb[tag].cmd = NULL;
6159 spin_unlock_irqrestore(host->host_lock, flags);
6161 clear_bit_unlock(tag, &hba->lrb_in_use);
6162 wake_up(&hba->dev_cmd.tag_wq);
6168 dev_err(hba->dev, "%s: failed with err %d\n", __func__, err);
6169 ufshcd_set_req_abort_skip(hba, hba->outstanding_reqs);
6174 * This ufshcd_release() corresponds to the original scsi cmd that got
6175 * aborted here (as we won't get any IRQ for it).
6177 ufshcd_release(hba);
6182 * ufshcd_host_reset_and_restore - reset and restore host controller
6183 * @hba: per-adapter instance
6185 * Note that host controller reset may issue DME_RESET to
6186 * local and remote (device) Uni-Pro stack and the attributes
6187 * are reset to default state.
6189 * Returns zero on success, non-zero on failure
6191 static int ufshcd_host_reset_and_restore(struct ufs_hba *hba)
6194 unsigned long flags;
6196 /* Reset the host controller */
6197 spin_lock_irqsave(hba->host->host_lock, flags);
6198 ufshcd_hba_stop(hba, false);
6199 spin_unlock_irqrestore(hba->host->host_lock, flags);
6201 /* scale up clocks to max frequency before full reinitialization */
6202 ufshcd_scale_clks(hba, true);
6204 err = ufshcd_hba_enable(hba);
6208 /* Establish the link again and restore the device */
6209 err = ufshcd_probe_hba(hba);
6211 if (!err && (hba->ufshcd_state != UFSHCD_STATE_OPERATIONAL))
6215 dev_err(hba->dev, "%s: Host init failed %d\n", __func__, err);
6216 ufshcd_update_reg_hist(&hba->ufs_stats.host_reset, (u32)err);
6221 * ufshcd_reset_and_restore - reset and re-initialize host/device
6222 * @hba: per-adapter instance
6224 * Reset and recover device, host and re-establish link. This
6225 * is helpful to recover the communication in fatal error conditions.
6227 * Returns zero on success, non-zero on failure
6229 static int ufshcd_reset_and_restore(struct ufs_hba *hba)
6232 unsigned long flags;
6233 int retries = MAX_HOST_RESET_RETRIES;
6236 /* Reset the attached device */
6237 ufshcd_vops_device_reset(hba);
6239 err = ufshcd_host_reset_and_restore(hba);
6240 } while (err && --retries);
6243 * After reset the door-bell might be cleared, complete
6244 * outstanding requests in s/w here.
6246 spin_lock_irqsave(hba->host->host_lock, flags);
6247 ufshcd_transfer_req_compl(hba);
6248 ufshcd_tmc_handler(hba);
6249 spin_unlock_irqrestore(hba->host->host_lock, flags);
6255 * ufshcd_eh_host_reset_handler - host reset handler registered to scsi layer
6256 * @cmd: SCSI command pointer
6258 * Returns SUCCESS/FAILED
6260 static int ufshcd_eh_host_reset_handler(struct scsi_cmnd *cmd)
6263 unsigned long flags;
6264 struct ufs_hba *hba;
6266 hba = shost_priv(cmd->device->host);
6268 ufshcd_hold(hba, false);
6270 * Check if there is any race with fatal error handling.
6271 * If so, wait for it to complete. Even though fatal error
6272 * handling does reset and restore in some cases, don't assume
6273 * anything out of it. We are just avoiding race here.
6276 spin_lock_irqsave(hba->host->host_lock, flags);
6277 if (!(work_pending(&hba->eh_work) ||
6278 hba->ufshcd_state == UFSHCD_STATE_RESET ||
6279 hba->ufshcd_state == UFSHCD_STATE_EH_SCHEDULED))
6281 spin_unlock_irqrestore(hba->host->host_lock, flags);
6282 dev_dbg(hba->dev, "%s: reset in progress\n", __func__);
6283 flush_work(&hba->eh_work);
6286 hba->ufshcd_state = UFSHCD_STATE_RESET;
6287 ufshcd_set_eh_in_progress(hba);
6288 spin_unlock_irqrestore(hba->host->host_lock, flags);
6290 err = ufshcd_reset_and_restore(hba);
6292 spin_lock_irqsave(hba->host->host_lock, flags);
6295 hba->ufshcd_state = UFSHCD_STATE_OPERATIONAL;
6298 hba->ufshcd_state = UFSHCD_STATE_ERROR;
6300 ufshcd_clear_eh_in_progress(hba);
6301 spin_unlock_irqrestore(hba->host->host_lock, flags);
6303 ufshcd_release(hba);
6308 * ufshcd_get_max_icc_level - calculate the ICC level
6309 * @sup_curr_uA: max. current supported by the regulator
6310 * @start_scan: row at the desc table to start scan from
6311 * @buff: power descriptor buffer
6313 * Returns calculated max ICC level for specific regulator
6315 static u32 ufshcd_get_max_icc_level(int sup_curr_uA, u32 start_scan, char *buff)
6322 for (i = start_scan; i >= 0; i--) {
6323 data = be16_to_cpup((__be16 *)&buff[2 * i]);
6324 unit = (data & ATTR_ICC_LVL_UNIT_MASK) >>
6325 ATTR_ICC_LVL_UNIT_OFFSET;
6326 curr_uA = data & ATTR_ICC_LVL_VALUE_MASK;
6328 case UFSHCD_NANO_AMP:
6329 curr_uA = curr_uA / 1000;
6331 case UFSHCD_MILI_AMP:
6332 curr_uA = curr_uA * 1000;
6335 curr_uA = curr_uA * 1000 * 1000;
6337 case UFSHCD_MICRO_AMP:
6341 if (sup_curr_uA >= curr_uA)
6346 pr_err("%s: Couldn't find valid icc_level = %d", __func__, i);
6353 * ufshcd_calc_icc_level - calculate the max ICC level
6354 * In case regulators are not initialized we'll return 0
6355 * @hba: per-adapter instance
6356 * @desc_buf: power descriptor buffer to extract ICC levels from.
6357 * @len: length of desc_buff
6359 * Returns calculated ICC level
6361 static u32 ufshcd_find_max_sup_active_icc_level(struct ufs_hba *hba,
6362 u8 *desc_buf, int len)
6366 if (!hba->vreg_info.vcc || !hba->vreg_info.vccq ||
6367 !hba->vreg_info.vccq2) {
6369 "%s: Regulator capability was not set, actvIccLevel=%d",
6370 __func__, icc_level);
6374 if (hba->vreg_info.vcc && hba->vreg_info.vcc->max_uA)
6375 icc_level = ufshcd_get_max_icc_level(
6376 hba->vreg_info.vcc->max_uA,
6377 POWER_DESC_MAX_ACTV_ICC_LVLS - 1,
6378 &desc_buf[PWR_DESC_ACTIVE_LVLS_VCC_0]);
6380 if (hba->vreg_info.vccq && hba->vreg_info.vccq->max_uA)
6381 icc_level = ufshcd_get_max_icc_level(
6382 hba->vreg_info.vccq->max_uA,
6384 &desc_buf[PWR_DESC_ACTIVE_LVLS_VCCQ_0]);
6386 if (hba->vreg_info.vccq2 && hba->vreg_info.vccq2->max_uA)
6387 icc_level = ufshcd_get_max_icc_level(
6388 hba->vreg_info.vccq2->max_uA,
6390 &desc_buf[PWR_DESC_ACTIVE_LVLS_VCCQ2_0]);
6395 static void ufshcd_init_icc_levels(struct ufs_hba *hba)
6398 int buff_len = hba->desc_size.pwr_desc;
6401 desc_buf = kmalloc(buff_len, GFP_KERNEL);
6405 ret = ufshcd_read_power_desc(hba, desc_buf, buff_len);
6408 "%s: Failed reading power descriptor.len = %d ret = %d",
6409 __func__, buff_len, ret);
6413 hba->init_prefetch_data.icc_level =
6414 ufshcd_find_max_sup_active_icc_level(hba,
6415 desc_buf, buff_len);
6416 dev_dbg(hba->dev, "%s: setting icc_level 0x%x",
6417 __func__, hba->init_prefetch_data.icc_level);
6419 ret = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_WRITE_ATTR,
6420 QUERY_ATTR_IDN_ACTIVE_ICC_LVL, 0, 0,
6421 &hba->init_prefetch_data.icc_level);
6425 "%s: Failed configuring bActiveICCLevel = %d ret = %d",
6426 __func__, hba->init_prefetch_data.icc_level , ret);
6433 * ufshcd_scsi_add_wlus - Adds required W-LUs
6434 * @hba: per-adapter instance
6436 * UFS device specification requires the UFS devices to support 4 well known
6438 * "REPORT_LUNS" (address: 01h)
6439 * "UFS Device" (address: 50h)
6440 * "RPMB" (address: 44h)
6441 * "BOOT" (address: 30h)
6442 * UFS device's power management needs to be controlled by "POWER CONDITION"
6443 * field of SSU (START STOP UNIT) command. But this "power condition" field
6444 * will take effect only when its sent to "UFS device" well known logical unit
6445 * hence we require the scsi_device instance to represent this logical unit in
6446 * order for the UFS host driver to send the SSU command for power management.
6448 * We also require the scsi_device instance for "RPMB" (Replay Protected Memory
6449 * Block) LU so user space process can control this LU. User space may also
6450 * want to have access to BOOT LU.
6452 * This function adds scsi device instances for each of all well known LUs
6453 * (except "REPORT LUNS" LU).
6455 * Returns zero on success (all required W-LUs are added successfully),
6456 * non-zero error value on failure (if failed to add any of the required W-LU).
6458 static int ufshcd_scsi_add_wlus(struct ufs_hba *hba)
6461 struct scsi_device *sdev_rpmb;
6462 struct scsi_device *sdev_boot;
6464 hba->sdev_ufs_device = __scsi_add_device(hba->host, 0, 0,
6465 ufshcd_upiu_wlun_to_scsi_wlun(UFS_UPIU_UFS_DEVICE_WLUN), NULL);
6466 if (IS_ERR(hba->sdev_ufs_device)) {
6467 ret = PTR_ERR(hba->sdev_ufs_device);
6468 hba->sdev_ufs_device = NULL;
6471 scsi_device_put(hba->sdev_ufs_device);
6473 sdev_rpmb = __scsi_add_device(hba->host, 0, 0,
6474 ufshcd_upiu_wlun_to_scsi_wlun(UFS_UPIU_RPMB_WLUN), NULL);
6475 if (IS_ERR(sdev_rpmb)) {
6476 ret = PTR_ERR(sdev_rpmb);
6477 goto remove_sdev_ufs_device;
6479 scsi_device_put(sdev_rpmb);
6481 sdev_boot = __scsi_add_device(hba->host, 0, 0,
6482 ufshcd_upiu_wlun_to_scsi_wlun(UFS_UPIU_BOOT_WLUN), NULL);
6483 if (IS_ERR(sdev_boot))
6484 dev_err(hba->dev, "%s: BOOT WLUN not found\n", __func__);
6486 scsi_device_put(sdev_boot);
6489 remove_sdev_ufs_device:
6490 scsi_remove_device(hba->sdev_ufs_device);
6495 static int ufs_get_device_desc(struct ufs_hba *hba,
6496 struct ufs_dev_desc *dev_desc)
6506 buff_len = max_t(size_t, hba->desc_size.dev_desc,
6507 QUERY_DESC_MAX_SIZE + 1);
6508 desc_buf = kmalloc(buff_len, GFP_KERNEL);
6514 err = ufshcd_read_device_desc(hba, desc_buf, hba->desc_size.dev_desc);
6516 dev_err(hba->dev, "%s: Failed reading Device Desc. err = %d\n",
6522 * getting vendor (manufacturerID) and Bank Index in big endian
6525 dev_desc->wmanufacturerid = desc_buf[DEVICE_DESC_PARAM_MANF_ID] << 8 |
6526 desc_buf[DEVICE_DESC_PARAM_MANF_ID + 1];
6528 model_index = desc_buf[DEVICE_DESC_PARAM_PRDCT_NAME];
6529 err = ufshcd_read_string_desc(hba, model_index,
6530 &dev_desc->model, SD_ASCII_STD);
6532 dev_err(hba->dev, "%s: Failed reading Product Name. err = %d\n",
6538 * ufshcd_read_string_desc returns size of the string
6539 * reset the error value
6548 static void ufs_put_device_desc(struct ufs_dev_desc *dev_desc)
6550 kfree(dev_desc->model);
6551 dev_desc->model = NULL;
6554 static void ufs_fixup_device_setup(struct ufs_hba *hba,
6555 struct ufs_dev_desc *dev_desc)
6557 struct ufs_dev_fix *f;
6559 for (f = ufs_fixups; f->quirk; f++) {
6560 if ((f->card.wmanufacturerid == dev_desc->wmanufacturerid ||
6561 f->card.wmanufacturerid == UFS_ANY_VENDOR) &&
6562 ((dev_desc->model &&
6563 STR_PRFX_EQUAL(f->card.model, dev_desc->model)) ||
6564 !strcmp(f->card.model, UFS_ANY_MODEL)))
6565 hba->dev_quirks |= f->quirk;
6570 * ufshcd_tune_pa_tactivate - Tunes PA_TActivate of local UniPro
6571 * @hba: per-adapter instance
6573 * PA_TActivate parameter can be tuned manually if UniPro version is less than
6574 * 1.61. PA_TActivate needs to be greater than or equal to peerM-PHY's
6575 * RX_MIN_ACTIVATETIME_CAPABILITY attribute. This optimal value can help reduce
6576 * the hibern8 exit latency.
6578 * Returns zero on success, non-zero error value on failure.
6580 static int ufshcd_tune_pa_tactivate(struct ufs_hba *hba)
6583 u32 peer_rx_min_activatetime = 0, tuned_pa_tactivate;
6585 ret = ufshcd_dme_peer_get(hba,
6587 RX_MIN_ACTIVATETIME_CAPABILITY,
6588 UIC_ARG_MPHY_RX_GEN_SEL_INDEX(0)),
6589 &peer_rx_min_activatetime);
6593 /* make sure proper unit conversion is applied */
6594 tuned_pa_tactivate =
6595 ((peer_rx_min_activatetime * RX_MIN_ACTIVATETIME_UNIT_US)
6596 / PA_TACTIVATE_TIME_UNIT_US);
6597 ret = ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TACTIVATE),
6598 tuned_pa_tactivate);
6605 * ufshcd_tune_pa_hibern8time - Tunes PA_Hibern8Time of local UniPro
6606 * @hba: per-adapter instance
6608 * PA_Hibern8Time parameter can be tuned manually if UniPro version is less than
6609 * 1.61. PA_Hibern8Time needs to be maximum of local M-PHY's
6610 * TX_HIBERN8TIME_CAPABILITY & peer M-PHY's RX_HIBERN8TIME_CAPABILITY.
6611 * This optimal value can help reduce the hibern8 exit latency.
6613 * Returns zero on success, non-zero error value on failure.
6615 static int ufshcd_tune_pa_hibern8time(struct ufs_hba *hba)
6618 u32 local_tx_hibern8_time_cap = 0, peer_rx_hibern8_time_cap = 0;
6619 u32 max_hibern8_time, tuned_pa_hibern8time;
6621 ret = ufshcd_dme_get(hba,
6622 UIC_ARG_MIB_SEL(TX_HIBERN8TIME_CAPABILITY,
6623 UIC_ARG_MPHY_TX_GEN_SEL_INDEX(0)),
6624 &local_tx_hibern8_time_cap);
6628 ret = ufshcd_dme_peer_get(hba,
6629 UIC_ARG_MIB_SEL(RX_HIBERN8TIME_CAPABILITY,
6630 UIC_ARG_MPHY_RX_GEN_SEL_INDEX(0)),
6631 &peer_rx_hibern8_time_cap);
6635 max_hibern8_time = max(local_tx_hibern8_time_cap,
6636 peer_rx_hibern8_time_cap);
6637 /* make sure proper unit conversion is applied */
6638 tuned_pa_hibern8time = ((max_hibern8_time * HIBERN8TIME_UNIT_US)
6639 / PA_HIBERN8_TIME_UNIT_US);
6640 ret = ufshcd_dme_set(hba, UIC_ARG_MIB(PA_HIBERN8TIME),
6641 tuned_pa_hibern8time);
6647 * ufshcd_quirk_tune_host_pa_tactivate - Ensures that host PA_TACTIVATE is
6648 * less than device PA_TACTIVATE time.
6649 * @hba: per-adapter instance
6651 * Some UFS devices require host PA_TACTIVATE to be lower than device
6652 * PA_TACTIVATE, we need to enable UFS_DEVICE_QUIRK_HOST_PA_TACTIVATE quirk
6655 * Returns zero on success, non-zero error value on failure.
6657 static int ufshcd_quirk_tune_host_pa_tactivate(struct ufs_hba *hba)
6660 u32 granularity, peer_granularity;
6661 u32 pa_tactivate, peer_pa_tactivate;
6662 u32 pa_tactivate_us, peer_pa_tactivate_us;
6663 u8 gran_to_us_table[] = {1, 4, 8, 16, 32, 100};
6665 ret = ufshcd_dme_get(hba, UIC_ARG_MIB(PA_GRANULARITY),
6670 ret = ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_GRANULARITY),
6675 if ((granularity < PA_GRANULARITY_MIN_VAL) ||
6676 (granularity > PA_GRANULARITY_MAX_VAL)) {
6677 dev_err(hba->dev, "%s: invalid host PA_GRANULARITY %d",
6678 __func__, granularity);
6682 if ((peer_granularity < PA_GRANULARITY_MIN_VAL) ||
6683 (peer_granularity > PA_GRANULARITY_MAX_VAL)) {
6684 dev_err(hba->dev, "%s: invalid device PA_GRANULARITY %d",
6685 __func__, peer_granularity);
6689 ret = ufshcd_dme_get(hba, UIC_ARG_MIB(PA_TACTIVATE), &pa_tactivate);
6693 ret = ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_TACTIVATE),
6694 &peer_pa_tactivate);
6698 pa_tactivate_us = pa_tactivate * gran_to_us_table[granularity - 1];
6699 peer_pa_tactivate_us = peer_pa_tactivate *
6700 gran_to_us_table[peer_granularity - 1];
6702 if (pa_tactivate_us > peer_pa_tactivate_us) {
6703 u32 new_peer_pa_tactivate;
6705 new_peer_pa_tactivate = pa_tactivate_us /
6706 gran_to_us_table[peer_granularity - 1];
6707 new_peer_pa_tactivate++;
6708 ret = ufshcd_dme_peer_set(hba, UIC_ARG_MIB(PA_TACTIVATE),
6709 new_peer_pa_tactivate);
6716 static void ufshcd_tune_unipro_params(struct ufs_hba *hba)
6718 if (ufshcd_is_unipro_pa_params_tuning_req(hba)) {
6719 ufshcd_tune_pa_tactivate(hba);
6720 ufshcd_tune_pa_hibern8time(hba);
6723 if (hba->dev_quirks & UFS_DEVICE_QUIRK_PA_TACTIVATE)
6724 /* set 1ms timeout for PA_TACTIVATE */
6725 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TACTIVATE), 10);
6727 if (hba->dev_quirks & UFS_DEVICE_QUIRK_HOST_PA_TACTIVATE)
6728 ufshcd_quirk_tune_host_pa_tactivate(hba);
6730 ufshcd_vops_apply_dev_quirks(hba);
6733 static void ufshcd_clear_dbg_ufs_stats(struct ufs_hba *hba)
6735 hba->ufs_stats.hibern8_exit_cnt = 0;
6736 hba->ufs_stats.last_hibern8_exit_tstamp = ktime_set(0, 0);
6737 hba->req_abort_count = 0;
6740 static void ufshcd_init_desc_sizes(struct ufs_hba *hba)
6744 err = ufshcd_read_desc_length(hba, QUERY_DESC_IDN_DEVICE, 0,
6745 &hba->desc_size.dev_desc);
6747 hba->desc_size.dev_desc = QUERY_DESC_DEVICE_DEF_SIZE;
6749 err = ufshcd_read_desc_length(hba, QUERY_DESC_IDN_POWER, 0,
6750 &hba->desc_size.pwr_desc);
6752 hba->desc_size.pwr_desc = QUERY_DESC_POWER_DEF_SIZE;
6754 err = ufshcd_read_desc_length(hba, QUERY_DESC_IDN_INTERCONNECT, 0,
6755 &hba->desc_size.interc_desc);
6757 hba->desc_size.interc_desc = QUERY_DESC_INTERCONNECT_DEF_SIZE;
6759 err = ufshcd_read_desc_length(hba, QUERY_DESC_IDN_CONFIGURATION, 0,
6760 &hba->desc_size.conf_desc);
6762 hba->desc_size.conf_desc = QUERY_DESC_CONFIGURATION_DEF_SIZE;
6764 err = ufshcd_read_desc_length(hba, QUERY_DESC_IDN_UNIT, 0,
6765 &hba->desc_size.unit_desc);
6767 hba->desc_size.unit_desc = QUERY_DESC_UNIT_DEF_SIZE;
6769 err = ufshcd_read_desc_length(hba, QUERY_DESC_IDN_GEOMETRY, 0,
6770 &hba->desc_size.geom_desc);
6772 hba->desc_size.geom_desc = QUERY_DESC_GEOMETRY_DEF_SIZE;
6773 err = ufshcd_read_desc_length(hba, QUERY_DESC_IDN_HEALTH, 0,
6774 &hba->desc_size.hlth_desc);
6776 hba->desc_size.hlth_desc = QUERY_DESC_HEALTH_DEF_SIZE;
6779 static void ufshcd_def_desc_sizes(struct ufs_hba *hba)
6781 hba->desc_size.dev_desc = QUERY_DESC_DEVICE_DEF_SIZE;
6782 hba->desc_size.pwr_desc = QUERY_DESC_POWER_DEF_SIZE;
6783 hba->desc_size.interc_desc = QUERY_DESC_INTERCONNECT_DEF_SIZE;
6784 hba->desc_size.conf_desc = QUERY_DESC_CONFIGURATION_DEF_SIZE;
6785 hba->desc_size.unit_desc = QUERY_DESC_UNIT_DEF_SIZE;
6786 hba->desc_size.geom_desc = QUERY_DESC_GEOMETRY_DEF_SIZE;
6787 hba->desc_size.hlth_desc = QUERY_DESC_HEALTH_DEF_SIZE;
6790 static struct ufs_ref_clk ufs_ref_clk_freqs[] = {
6791 {19200000, REF_CLK_FREQ_19_2_MHZ},
6792 {26000000, REF_CLK_FREQ_26_MHZ},
6793 {38400000, REF_CLK_FREQ_38_4_MHZ},
6794 {52000000, REF_CLK_FREQ_52_MHZ},
6795 {0, REF_CLK_FREQ_INVAL},
6798 static enum ufs_ref_clk_freq
6799 ufs_get_bref_clk_from_hz(unsigned long freq)
6803 for (i = 0; ufs_ref_clk_freqs[i].freq_hz; i++)
6804 if (ufs_ref_clk_freqs[i].freq_hz == freq)
6805 return ufs_ref_clk_freqs[i].val;
6807 return REF_CLK_FREQ_INVAL;
6810 void ufshcd_parse_dev_ref_clk_freq(struct ufs_hba *hba, struct clk *refclk)
6814 freq = clk_get_rate(refclk);
6816 hba->dev_ref_clk_freq =
6817 ufs_get_bref_clk_from_hz(freq);
6819 if (hba->dev_ref_clk_freq == REF_CLK_FREQ_INVAL)
6821 "invalid ref_clk setting = %ld\n", freq);
6824 static int ufshcd_set_dev_ref_clk(struct ufs_hba *hba)
6828 u32 freq = hba->dev_ref_clk_freq;
6830 err = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
6831 QUERY_ATTR_IDN_REF_CLK_FREQ, 0, 0, &ref_clk);
6834 dev_err(hba->dev, "failed reading bRefClkFreq. err = %d\n",
6839 if (ref_clk == freq)
6840 goto out; /* nothing to update */
6842 err = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_WRITE_ATTR,
6843 QUERY_ATTR_IDN_REF_CLK_FREQ, 0, 0, &freq);
6846 dev_err(hba->dev, "bRefClkFreq setting to %lu Hz failed\n",
6847 ufs_ref_clk_freqs[freq].freq_hz);
6851 dev_dbg(hba->dev, "bRefClkFreq setting to %lu Hz succeeded\n",
6852 ufs_ref_clk_freqs[freq].freq_hz);
6859 * ufshcd_probe_hba - probe hba to detect device and initialize
6860 * @hba: per-adapter instance
6862 * Execute link-startup and verify device initialization
6864 static int ufshcd_probe_hba(struct ufs_hba *hba)
6866 struct ufs_dev_desc card = {0};
6868 ktime_t start = ktime_get();
6870 ret = ufshcd_link_startup(hba);
6874 /* set the default level for urgent bkops */
6875 hba->urgent_bkops_lvl = BKOPS_STATUS_PERF_IMPACT;
6876 hba->is_urgent_bkops_lvl_checked = false;
6878 /* Debug counters initialization */
6879 ufshcd_clear_dbg_ufs_stats(hba);
6881 /* UniPro link is active now */
6882 ufshcd_set_link_active(hba);
6884 /* Enable Auto-Hibernate if configured */
6885 ufshcd_auto_hibern8_enable(hba);
6887 ret = ufshcd_verify_dev_init(hba);
6891 ret = ufshcd_complete_dev_init(hba);
6895 /* Init check for device descriptor sizes */
6896 ufshcd_init_desc_sizes(hba);
6898 ret = ufs_get_device_desc(hba, &card);
6900 dev_err(hba->dev, "%s: Failed getting device info. err = %d\n",
6905 ufs_fixup_device_setup(hba, &card);
6906 ufs_put_device_desc(&card);
6908 ufshcd_tune_unipro_params(hba);
6910 /* UFS device is also active now */
6911 ufshcd_set_ufs_dev_active(hba);
6912 ufshcd_force_reset_auto_bkops(hba);
6913 hba->wlun_dev_clr_ua = true;
6915 if (ufshcd_get_max_pwr_mode(hba)) {
6917 "%s: Failed getting max supported power mode\n",
6921 * Set the right value to bRefClkFreq before attempting to
6922 * switch to HS gears.
6924 if (hba->dev_ref_clk_freq != REF_CLK_FREQ_INVAL)
6925 ufshcd_set_dev_ref_clk(hba);
6926 ret = ufshcd_config_pwr_mode(hba, &hba->max_pwr_info.info);
6928 dev_err(hba->dev, "%s: Failed setting power mode, err = %d\n",
6934 /* set the state as operational after switching to desired gear */
6935 hba->ufshcd_state = UFSHCD_STATE_OPERATIONAL;
6938 * If we are in error handling context or in power management callbacks
6939 * context, no need to scan the host
6941 if (!ufshcd_eh_in_progress(hba) && !hba->pm_op_in_progress) {
6944 /* clear any previous UFS device information */
6945 memset(&hba->dev_info, 0, sizeof(hba->dev_info));
6946 if (!ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_READ_FLAG,
6947 QUERY_FLAG_IDN_PWR_ON_WPE, &flag))
6948 hba->dev_info.f_power_on_wp_en = flag;
6950 if (!hba->is_init_prefetch)
6951 ufshcd_init_icc_levels(hba);
6953 /* Add required well known logical units to scsi mid layer */
6954 if (ufshcd_scsi_add_wlus(hba))
6957 /* Initialize devfreq after UFS device is detected */
6958 if (ufshcd_is_clkscaling_supported(hba)) {
6959 memcpy(&hba->clk_scaling.saved_pwr_info.info,
6961 sizeof(struct ufs_pa_layer_attr));
6962 hba->clk_scaling.saved_pwr_info.is_valid = true;
6963 if (!hba->devfreq) {
6964 ret = ufshcd_devfreq_init(hba);
6968 hba->clk_scaling.is_allowed = true;
6973 scsi_scan_host(hba->host);
6974 pm_runtime_put_sync(hba->dev);
6977 if (!hba->is_init_prefetch)
6978 hba->is_init_prefetch = true;
6982 * If we failed to initialize the device or the device is not
6983 * present, turn off the power/clocks etc.
6985 if (ret && !ufshcd_eh_in_progress(hba) && !hba->pm_op_in_progress) {
6986 pm_runtime_put_sync(hba->dev);
6987 ufshcd_exit_clk_scaling(hba);
6988 ufshcd_hba_exit(hba);
6991 trace_ufshcd_init(dev_name(hba->dev), ret,
6992 ktime_to_us(ktime_sub(ktime_get(), start)),
6993 hba->curr_dev_pwr_mode, hba->uic_link_state);
6998 * ufshcd_async_scan - asynchronous execution for probing hba
6999 * @data: data pointer to pass to this function
7000 * @cookie: cookie data
7002 static void ufshcd_async_scan(void *data, async_cookie_t cookie)
7004 struct ufs_hba *hba = (struct ufs_hba *)data;
7006 ufshcd_probe_hba(hba);
7009 static enum blk_eh_timer_return ufshcd_eh_timed_out(struct scsi_cmnd *scmd)
7011 unsigned long flags;
7012 struct Scsi_Host *host;
7013 struct ufs_hba *hba;
7017 if (!scmd || !scmd->device || !scmd->device->host)
7020 host = scmd->device->host;
7021 hba = shost_priv(host);
7025 spin_lock_irqsave(host->host_lock, flags);
7027 for_each_set_bit(index, &hba->outstanding_reqs, hba->nutrs) {
7028 if (hba->lrb[index].cmd == scmd) {
7034 spin_unlock_irqrestore(host->host_lock, flags);
7037 * Bypass SCSI error handling and reset the block layer timer if this
7038 * SCSI command was not actually dispatched to UFS driver, otherwise
7039 * let SCSI layer handle the error as usual.
7041 return found ? BLK_EH_DONE : BLK_EH_RESET_TIMER;
7044 static const struct attribute_group *ufshcd_driver_groups[] = {
7045 &ufs_sysfs_unit_descriptor_group,
7046 &ufs_sysfs_lun_attributes_group,
7050 static struct scsi_host_template ufshcd_driver_template = {
7051 .module = THIS_MODULE,
7053 .proc_name = UFSHCD,
7054 .queuecommand = ufshcd_queuecommand,
7055 .slave_alloc = ufshcd_slave_alloc,
7056 .slave_configure = ufshcd_slave_configure,
7057 .slave_destroy = ufshcd_slave_destroy,
7058 .change_queue_depth = ufshcd_change_queue_depth,
7059 .eh_abort_handler = ufshcd_abort,
7060 .eh_device_reset_handler = ufshcd_eh_device_reset_handler,
7061 .eh_host_reset_handler = ufshcd_eh_host_reset_handler,
7062 .eh_timed_out = ufshcd_eh_timed_out,
7064 .sg_tablesize = SG_ALL,
7065 .cmd_per_lun = UFSHCD_CMD_PER_LUN,
7066 .can_queue = UFSHCD_CAN_QUEUE,
7067 .max_segment_size = PRDT_DATA_BYTE_COUNT_MAX,
7068 .max_host_blocked = 1,
7069 .track_queue_depth = 1,
7070 .sdev_groups = ufshcd_driver_groups,
7071 .dma_boundary = PAGE_SIZE - 1,
7074 static int ufshcd_config_vreg_load(struct device *dev, struct ufs_vreg *vreg,
7083 * "set_load" operation shall be required on those regulators
7084 * which specifically configured current limitation. Otherwise
7085 * zero max_uA may cause unexpected behavior when regulator is
7086 * enabled or set as high power mode.
7091 ret = regulator_set_load(vreg->reg, ua);
7093 dev_err(dev, "%s: %s set load (ua=%d) failed, err=%d\n",
7094 __func__, vreg->name, ua, ret);
7100 static inline int ufshcd_config_vreg_lpm(struct ufs_hba *hba,
7101 struct ufs_vreg *vreg)
7103 return ufshcd_config_vreg_load(hba->dev, vreg, UFS_VREG_LPM_LOAD_UA);
7106 static inline int ufshcd_config_vreg_hpm(struct ufs_hba *hba,
7107 struct ufs_vreg *vreg)
7112 return ufshcd_config_vreg_load(hba->dev, vreg, vreg->max_uA);
7115 static int ufshcd_config_vreg(struct device *dev,
7116 struct ufs_vreg *vreg, bool on)
7119 struct regulator *reg;
7121 int min_uV, uA_load;
7128 if (regulator_count_voltages(reg) > 0) {
7129 if (vreg->min_uV && vreg->max_uV) {
7130 min_uV = on ? vreg->min_uV : 0;
7131 ret = regulator_set_voltage(reg, min_uV, vreg->max_uV);
7134 "%s: %s set voltage failed, err=%d\n",
7135 __func__, name, ret);
7140 uA_load = on ? vreg->max_uA : 0;
7141 ret = ufshcd_config_vreg_load(dev, vreg, uA_load);
7149 static int ufshcd_enable_vreg(struct device *dev, struct ufs_vreg *vreg)
7153 if (!vreg || vreg->enabled)
7156 ret = ufshcd_config_vreg(dev, vreg, true);
7158 ret = regulator_enable(vreg->reg);
7161 vreg->enabled = true;
7163 dev_err(dev, "%s: %s enable failed, err=%d\n",
7164 __func__, vreg->name, ret);
7169 static int ufshcd_disable_vreg(struct device *dev, struct ufs_vreg *vreg)
7173 if (!vreg || !vreg->enabled)
7176 ret = regulator_disable(vreg->reg);
7179 /* ignore errors on applying disable config */
7180 ufshcd_config_vreg(dev, vreg, false);
7181 vreg->enabled = false;
7183 dev_err(dev, "%s: %s disable failed, err=%d\n",
7184 __func__, vreg->name, ret);
7190 static int ufshcd_setup_vreg(struct ufs_hba *hba, bool on)
7193 struct device *dev = hba->dev;
7194 struct ufs_vreg_info *info = &hba->vreg_info;
7196 ret = ufshcd_toggle_vreg(dev, info->vcc, on);
7200 ret = ufshcd_toggle_vreg(dev, info->vccq, on);
7204 ret = ufshcd_toggle_vreg(dev, info->vccq2, on);
7210 ufshcd_toggle_vreg(dev, info->vccq2, false);
7211 ufshcd_toggle_vreg(dev, info->vccq, false);
7212 ufshcd_toggle_vreg(dev, info->vcc, false);
7217 static int ufshcd_setup_hba_vreg(struct ufs_hba *hba, bool on)
7219 struct ufs_vreg_info *info = &hba->vreg_info;
7221 return ufshcd_toggle_vreg(hba->dev, info->vdd_hba, on);
7224 static int ufshcd_get_vreg(struct device *dev, struct ufs_vreg *vreg)
7231 vreg->reg = devm_regulator_get(dev, vreg->name);
7232 if (IS_ERR(vreg->reg)) {
7233 ret = PTR_ERR(vreg->reg);
7234 dev_err(dev, "%s: %s get failed, err=%d\n",
7235 __func__, vreg->name, ret);
7241 static int ufshcd_init_vreg(struct ufs_hba *hba)
7244 struct device *dev = hba->dev;
7245 struct ufs_vreg_info *info = &hba->vreg_info;
7247 ret = ufshcd_get_vreg(dev, info->vcc);
7251 ret = ufshcd_get_vreg(dev, info->vccq);
7255 ret = ufshcd_get_vreg(dev, info->vccq2);
7260 static int ufshcd_init_hba_vreg(struct ufs_hba *hba)
7262 struct ufs_vreg_info *info = &hba->vreg_info;
7265 return ufshcd_get_vreg(hba->dev, info->vdd_hba);
7270 static int __ufshcd_setup_clocks(struct ufs_hba *hba, bool on,
7274 struct ufs_clk_info *clki;
7275 struct list_head *head = &hba->clk_list_head;
7276 unsigned long flags;
7277 ktime_t start = ktime_get();
7278 bool clk_state_changed = false;
7280 if (list_empty(head))
7284 * vendor specific setup_clocks ops may depend on clocks managed by
7285 * this standard driver hence call the vendor specific setup_clocks
7286 * before disabling the clocks managed here.
7289 ret = ufshcd_vops_setup_clocks(hba, on, PRE_CHANGE);
7294 list_for_each_entry(clki, head, list) {
7295 if (!IS_ERR_OR_NULL(clki->clk)) {
7296 if (skip_ref_clk && !strcmp(clki->name, "ref_clk"))
7299 clk_state_changed = on ^ clki->enabled;
7300 if (on && !clki->enabled) {
7301 ret = clk_prepare_enable(clki->clk);
7303 dev_err(hba->dev, "%s: %s prepare enable failed, %d\n",
7304 __func__, clki->name, ret);
7307 } else if (!on && clki->enabled) {
7308 clk_disable_unprepare(clki->clk);
7311 dev_dbg(hba->dev, "%s: clk: %s %sabled\n", __func__,
7312 clki->name, on ? "en" : "dis");
7317 * vendor specific setup_clocks ops may depend on clocks managed by
7318 * this standard driver hence call the vendor specific setup_clocks
7319 * after enabling the clocks managed here.
7322 ret = ufshcd_vops_setup_clocks(hba, on, POST_CHANGE);
7329 list_for_each_entry(clki, head, list) {
7330 if (!IS_ERR_OR_NULL(clki->clk) && clki->enabled)
7331 clk_disable_unprepare(clki->clk);
7333 } else if (!ret && on) {
7334 spin_lock_irqsave(hba->host->host_lock, flags);
7335 hba->clk_gating.state = CLKS_ON;
7336 trace_ufshcd_clk_gating(dev_name(hba->dev),
7337 hba->clk_gating.state);
7338 spin_unlock_irqrestore(hba->host->host_lock, flags);
7341 if (clk_state_changed)
7342 trace_ufshcd_profile_clk_gating(dev_name(hba->dev),
7343 (on ? "on" : "off"),
7344 ktime_to_us(ktime_sub(ktime_get(), start)), ret);
7348 static int ufshcd_setup_clocks(struct ufs_hba *hba, bool on)
7350 return __ufshcd_setup_clocks(hba, on, false);
7353 static int ufshcd_init_clocks(struct ufs_hba *hba)
7356 struct ufs_clk_info *clki;
7357 struct device *dev = hba->dev;
7358 struct list_head *head = &hba->clk_list_head;
7360 if (list_empty(head))
7363 list_for_each_entry(clki, head, list) {
7367 clki->clk = devm_clk_get(dev, clki->name);
7368 if (IS_ERR(clki->clk)) {
7369 ret = PTR_ERR(clki->clk);
7370 dev_err(dev, "%s: %s clk get failed, %d\n",
7371 __func__, clki->name, ret);
7376 * Parse device ref clk freq as per device tree "ref_clk".
7377 * Default dev_ref_clk_freq is set to REF_CLK_FREQ_INVAL
7378 * in ufshcd_alloc_host().
7380 if (!strcmp(clki->name, "ref_clk"))
7381 ufshcd_parse_dev_ref_clk_freq(hba, clki->clk);
7383 if (clki->max_freq) {
7384 ret = clk_set_rate(clki->clk, clki->max_freq);
7386 dev_err(hba->dev, "%s: %s clk set rate(%dHz) failed, %d\n",
7387 __func__, clki->name,
7388 clki->max_freq, ret);
7391 clki->curr_freq = clki->max_freq;
7393 dev_dbg(dev, "%s: clk: %s, rate: %lu\n", __func__,
7394 clki->name, clk_get_rate(clki->clk));
7400 static int ufshcd_variant_hba_init(struct ufs_hba *hba)
7407 err = ufshcd_vops_init(hba);
7411 err = ufshcd_vops_setup_regulators(hba, true);
7418 ufshcd_vops_exit(hba);
7421 dev_err(hba->dev, "%s: variant %s init failed err %d\n",
7422 __func__, ufshcd_get_var_name(hba), err);
7426 static void ufshcd_variant_hba_exit(struct ufs_hba *hba)
7431 ufshcd_vops_setup_regulators(hba, false);
7433 ufshcd_vops_exit(hba);
7436 static int ufshcd_hba_init(struct ufs_hba *hba)
7441 * Handle host controller power separately from the UFS device power
7442 * rails as it will help controlling the UFS host controller power
7443 * collapse easily which is different than UFS device power collapse.
7444 * Also, enable the host controller power before we go ahead with rest
7445 * of the initialization here.
7447 err = ufshcd_init_hba_vreg(hba);
7451 err = ufshcd_setup_hba_vreg(hba, true);
7455 err = ufshcd_init_clocks(hba);
7457 goto out_disable_hba_vreg;
7459 err = ufshcd_setup_clocks(hba, true);
7461 goto out_disable_hba_vreg;
7463 err = ufshcd_init_vreg(hba);
7465 goto out_disable_clks;
7467 err = ufshcd_setup_vreg(hba, true);
7469 goto out_disable_clks;
7471 err = ufshcd_variant_hba_init(hba);
7473 goto out_disable_vreg;
7475 hba->is_powered = true;
7479 ufshcd_setup_vreg(hba, false);
7481 ufshcd_setup_clocks(hba, false);
7482 out_disable_hba_vreg:
7483 ufshcd_setup_hba_vreg(hba, false);
7488 static void ufshcd_hba_exit(struct ufs_hba *hba)
7490 if (hba->is_powered) {
7491 ufshcd_variant_hba_exit(hba);
7492 ufshcd_setup_vreg(hba, false);
7493 ufshcd_suspend_clkscaling(hba);
7494 if (ufshcd_is_clkscaling_supported(hba))
7496 ufshcd_suspend_clkscaling(hba);
7497 ufshcd_setup_clocks(hba, false);
7498 ufshcd_setup_hba_vreg(hba, false);
7499 hba->is_powered = false;
7504 ufshcd_send_request_sense(struct ufs_hba *hba, struct scsi_device *sdp)
7506 unsigned char cmd[6] = {REQUEST_SENSE,
7515 buffer = kzalloc(UFS_SENSE_SIZE, GFP_KERNEL);
7521 ret = scsi_execute(sdp, cmd, DMA_FROM_DEVICE, buffer,
7522 UFS_SENSE_SIZE, NULL, NULL,
7523 msecs_to_jiffies(1000), 3, 0, RQF_PM, NULL);
7525 pr_err("%s: failed with err %d\n", __func__, ret);
7533 * ufshcd_set_dev_pwr_mode - sends START STOP UNIT command to set device
7535 * @hba: per adapter instance
7536 * @pwr_mode: device power mode to set
7538 * Returns 0 if requested power mode is set successfully
7539 * Returns non-zero if failed to set the requested power mode
7541 static int ufshcd_set_dev_pwr_mode(struct ufs_hba *hba,
7542 enum ufs_dev_pwr_mode pwr_mode)
7544 unsigned char cmd[6] = { START_STOP };
7545 struct scsi_sense_hdr sshdr;
7546 struct scsi_device *sdp;
7547 unsigned long flags;
7550 spin_lock_irqsave(hba->host->host_lock, flags);
7551 sdp = hba->sdev_ufs_device;
7553 ret = scsi_device_get(sdp);
7554 if (!ret && !scsi_device_online(sdp)) {
7556 scsi_device_put(sdp);
7561 spin_unlock_irqrestore(hba->host->host_lock, flags);
7567 * If scsi commands fail, the scsi mid-layer schedules scsi error-
7568 * handling, which would wait for host to be resumed. Since we know
7569 * we are functional while we are here, skip host resume in error
7572 hba->host->eh_noresume = 1;
7573 if (hba->wlun_dev_clr_ua) {
7574 ret = ufshcd_send_request_sense(hba, sdp);
7577 /* Unit attention condition is cleared now */
7578 hba->wlun_dev_clr_ua = false;
7581 cmd[4] = pwr_mode << 4;
7584 * Current function would be generally called from the power management
7585 * callbacks hence set the RQF_PM flag so that it doesn't resume the
7586 * already suspended childs.
7588 ret = scsi_execute(sdp, cmd, DMA_NONE, NULL, 0, NULL, &sshdr,
7589 START_STOP_TIMEOUT, 0, 0, RQF_PM, NULL);
7591 sdev_printk(KERN_WARNING, sdp,
7592 "START_STOP failed for power mode: %d, result %x\n",
7594 if (driver_byte(ret) == DRIVER_SENSE)
7595 scsi_print_sense_hdr(sdp, NULL, &sshdr);
7599 hba->curr_dev_pwr_mode = pwr_mode;
7601 scsi_device_put(sdp);
7602 hba->host->eh_noresume = 0;
7606 static int ufshcd_link_state_transition(struct ufs_hba *hba,
7607 enum uic_link_state req_link_state,
7608 int check_for_bkops)
7612 if (req_link_state == hba->uic_link_state)
7615 if (req_link_state == UIC_LINK_HIBERN8_STATE) {
7616 ret = ufshcd_uic_hibern8_enter(hba);
7618 ufshcd_set_link_hibern8(hba);
7623 * If autobkops is enabled, link can't be turned off because
7624 * turning off the link would also turn off the device.
7626 else if ((req_link_state == UIC_LINK_OFF_STATE) &&
7627 (!check_for_bkops || (check_for_bkops &&
7628 !hba->auto_bkops_enabled))) {
7630 * Let's make sure that link is in low power mode, we are doing
7631 * this currently by putting the link in Hibern8. Otherway to
7632 * put the link in low power mode is to send the DME end point
7633 * to device and then send the DME reset command to local
7634 * unipro. But putting the link in hibern8 is much faster.
7636 ret = ufshcd_uic_hibern8_enter(hba);
7640 * Change controller state to "reset state" which
7641 * should also put the link in off/reset state
7643 ufshcd_hba_stop(hba, true);
7645 * TODO: Check if we need any delay to make sure that
7646 * controller is reset
7648 ufshcd_set_link_off(hba);
7655 static void ufshcd_vreg_set_lpm(struct ufs_hba *hba)
7658 * It seems some UFS devices may keep drawing more than sleep current
7659 * (atleast for 500us) from UFS rails (especially from VCCQ rail).
7660 * To avoid this situation, add 2ms delay before putting these UFS
7661 * rails in LPM mode.
7663 if (!ufshcd_is_link_active(hba) &&
7664 hba->dev_quirks & UFS_DEVICE_QUIRK_DELAY_BEFORE_LPM)
7665 usleep_range(2000, 2100);
7668 * If UFS device is either in UFS_Sleep turn off VCC rail to save some
7671 * If UFS device and link is in OFF state, all power supplies (VCC,
7672 * VCCQ, VCCQ2) can be turned off if power on write protect is not
7673 * required. If UFS link is inactive (Hibern8 or OFF state) and device
7674 * is in sleep state, put VCCQ & VCCQ2 rails in LPM mode.
7676 * Ignore the error returned by ufshcd_toggle_vreg() as device is anyway
7677 * in low power state which would save some power.
7679 if (ufshcd_is_ufs_dev_poweroff(hba) && ufshcd_is_link_off(hba) &&
7680 !hba->dev_info.is_lu_power_on_wp) {
7681 ufshcd_setup_vreg(hba, false);
7682 } else if (!ufshcd_is_ufs_dev_active(hba)) {
7683 ufshcd_toggle_vreg(hba->dev, hba->vreg_info.vcc, false);
7684 if (!ufshcd_is_link_active(hba)) {
7685 ufshcd_config_vreg_lpm(hba, hba->vreg_info.vccq);
7686 ufshcd_config_vreg_lpm(hba, hba->vreg_info.vccq2);
7691 static int ufshcd_vreg_set_hpm(struct ufs_hba *hba)
7695 if (ufshcd_is_ufs_dev_poweroff(hba) && ufshcd_is_link_off(hba) &&
7696 !hba->dev_info.is_lu_power_on_wp) {
7697 ret = ufshcd_setup_vreg(hba, true);
7698 } else if (!ufshcd_is_ufs_dev_active(hba)) {
7699 if (!ret && !ufshcd_is_link_active(hba)) {
7700 ret = ufshcd_config_vreg_hpm(hba, hba->vreg_info.vccq);
7703 ret = ufshcd_config_vreg_hpm(hba, hba->vreg_info.vccq2);
7707 ret = ufshcd_toggle_vreg(hba->dev, hba->vreg_info.vcc, true);
7712 ufshcd_config_vreg_lpm(hba, hba->vreg_info.vccq);
7714 ufshcd_toggle_vreg(hba->dev, hba->vreg_info.vcc, false);
7719 static void ufshcd_hba_vreg_set_lpm(struct ufs_hba *hba)
7721 if (ufshcd_is_link_off(hba))
7722 ufshcd_setup_hba_vreg(hba, false);
7725 static void ufshcd_hba_vreg_set_hpm(struct ufs_hba *hba)
7727 if (ufshcd_is_link_off(hba))
7728 ufshcd_setup_hba_vreg(hba, true);
7732 * ufshcd_suspend - helper function for suspend operations
7733 * @hba: per adapter instance
7734 * @pm_op: desired low power operation type
7736 * This function will try to put the UFS device and link into low power
7737 * mode based on the "rpm_lvl" (Runtime PM level) or "spm_lvl"
7738 * (System PM level).
7740 * If this function is called during shutdown, it will make sure that
7741 * both UFS device and UFS link is powered off.
7743 * NOTE: UFS device & link must be active before we enter in this function.
7745 * Returns 0 for success and non-zero for failure
7747 static int ufshcd_suspend(struct ufs_hba *hba, enum ufs_pm_op pm_op)
7750 enum ufs_pm_level pm_lvl;
7751 enum ufs_dev_pwr_mode req_dev_pwr_mode;
7752 enum uic_link_state req_link_state;
7754 hba->pm_op_in_progress = 1;
7755 if (!ufshcd_is_shutdown_pm(pm_op)) {
7756 pm_lvl = ufshcd_is_runtime_pm(pm_op) ?
7757 hba->rpm_lvl : hba->spm_lvl;
7758 req_dev_pwr_mode = ufs_get_pm_lvl_to_dev_pwr_mode(pm_lvl);
7759 req_link_state = ufs_get_pm_lvl_to_link_pwr_state(pm_lvl);
7761 req_dev_pwr_mode = UFS_POWERDOWN_PWR_MODE;
7762 req_link_state = UIC_LINK_OFF_STATE;
7766 * If we can't transition into any of the low power modes
7767 * just gate the clocks.
7769 ufshcd_hold(hba, false);
7770 hba->clk_gating.is_suspended = true;
7772 if (hba->clk_scaling.is_allowed) {
7773 cancel_work_sync(&hba->clk_scaling.suspend_work);
7774 cancel_work_sync(&hba->clk_scaling.resume_work);
7775 ufshcd_suspend_clkscaling(hba);
7778 if (req_dev_pwr_mode == UFS_ACTIVE_PWR_MODE &&
7779 req_link_state == UIC_LINK_ACTIVE_STATE) {
7783 if ((req_dev_pwr_mode == hba->curr_dev_pwr_mode) &&
7784 (req_link_state == hba->uic_link_state))
7787 /* UFS device & link must be active before we enter in this function */
7788 if (!ufshcd_is_ufs_dev_active(hba) || !ufshcd_is_link_active(hba)) {
7793 if (ufshcd_is_runtime_pm(pm_op)) {
7794 if (ufshcd_can_autobkops_during_suspend(hba)) {
7796 * The device is idle with no requests in the queue,
7797 * allow background operations if bkops status shows
7798 * that performance might be impacted.
7800 ret = ufshcd_urgent_bkops(hba);
7804 /* make sure that auto bkops is disabled */
7805 ufshcd_disable_auto_bkops(hba);
7809 if ((req_dev_pwr_mode != hba->curr_dev_pwr_mode) &&
7810 ((ufshcd_is_runtime_pm(pm_op) && !hba->auto_bkops_enabled) ||
7811 !ufshcd_is_runtime_pm(pm_op))) {
7812 /* ensure that bkops is disabled */
7813 ufshcd_disable_auto_bkops(hba);
7814 ret = ufshcd_set_dev_pwr_mode(hba, req_dev_pwr_mode);
7819 ret = ufshcd_link_state_transition(hba, req_link_state, 1);
7821 goto set_dev_active;
7823 ufshcd_vreg_set_lpm(hba);
7827 * Call vendor specific suspend callback. As these callbacks may access
7828 * vendor specific host controller register space call them before the
7829 * host clocks are ON.
7831 ret = ufshcd_vops_suspend(hba, pm_op);
7833 goto set_link_active;
7835 if (!ufshcd_is_link_active(hba))
7836 ufshcd_setup_clocks(hba, false);
7838 /* If link is active, device ref_clk can't be switched off */
7839 __ufshcd_setup_clocks(hba, false, true);
7841 hba->clk_gating.state = CLKS_OFF;
7842 trace_ufshcd_clk_gating(dev_name(hba->dev), hba->clk_gating.state);
7844 * Disable the host irq as host controller as there won't be any
7845 * host controller transaction expected till resume.
7847 ufshcd_disable_irq(hba);
7848 /* Put the host controller in low power mode if possible */
7849 ufshcd_hba_vreg_set_lpm(hba);
7853 if (hba->clk_scaling.is_allowed)
7854 ufshcd_resume_clkscaling(hba);
7855 ufshcd_vreg_set_hpm(hba);
7856 if (ufshcd_is_link_hibern8(hba) && !ufshcd_uic_hibern8_exit(hba))
7857 ufshcd_set_link_active(hba);
7858 else if (ufshcd_is_link_off(hba))
7859 ufshcd_host_reset_and_restore(hba);
7861 if (!ufshcd_set_dev_pwr_mode(hba, UFS_ACTIVE_PWR_MODE))
7862 ufshcd_disable_auto_bkops(hba);
7864 if (hba->clk_scaling.is_allowed)
7865 ufshcd_resume_clkscaling(hba);
7866 hba->clk_gating.is_suspended = false;
7867 ufshcd_release(hba);
7869 hba->pm_op_in_progress = 0;
7871 ufshcd_update_reg_hist(&hba->ufs_stats.suspend_err, (u32)ret);
7876 * ufshcd_resume - helper function for resume operations
7877 * @hba: per adapter instance
7878 * @pm_op: runtime PM or system PM
7880 * This function basically brings the UFS device, UniPro link and controller
7883 * Returns 0 for success and non-zero for failure
7885 static int ufshcd_resume(struct ufs_hba *hba, enum ufs_pm_op pm_op)
7888 enum uic_link_state old_link_state;
7890 hba->pm_op_in_progress = 1;
7891 old_link_state = hba->uic_link_state;
7893 ufshcd_hba_vreg_set_hpm(hba);
7894 /* Make sure clocks are enabled before accessing controller */
7895 ret = ufshcd_setup_clocks(hba, true);
7899 /* enable the host irq as host controller would be active soon */
7900 ret = ufshcd_enable_irq(hba);
7902 goto disable_irq_and_vops_clks;
7904 ret = ufshcd_vreg_set_hpm(hba);
7906 goto disable_irq_and_vops_clks;
7909 * Call vendor specific resume callback. As these callbacks may access
7910 * vendor specific host controller register space call them when the
7911 * host clocks are ON.
7913 ret = ufshcd_vops_resume(hba, pm_op);
7917 if (ufshcd_is_link_hibern8(hba)) {
7918 ret = ufshcd_uic_hibern8_exit(hba);
7920 ufshcd_set_link_active(hba);
7922 goto vendor_suspend;
7923 } else if (ufshcd_is_link_off(hba)) {
7924 ret = ufshcd_host_reset_and_restore(hba);
7926 * ufshcd_host_reset_and_restore() should have already
7927 * set the link state as active
7929 if (ret || !ufshcd_is_link_active(hba))
7930 goto vendor_suspend;
7933 if (!ufshcd_is_ufs_dev_active(hba)) {
7934 ret = ufshcd_set_dev_pwr_mode(hba, UFS_ACTIVE_PWR_MODE);
7936 goto set_old_link_state;
7939 if (ufshcd_keep_autobkops_enabled_except_suspend(hba))
7940 ufshcd_enable_auto_bkops(hba);
7943 * If BKOPs operations are urgently needed at this moment then
7944 * keep auto-bkops enabled or else disable it.
7946 ufshcd_urgent_bkops(hba);
7948 hba->clk_gating.is_suspended = false;
7950 if (hba->clk_scaling.is_allowed)
7951 ufshcd_resume_clkscaling(hba);
7953 /* Schedule clock gating in case of no access to UFS device yet */
7954 ufshcd_release(hba);
7956 /* Enable Auto-Hibernate if configured */
7957 ufshcd_auto_hibern8_enable(hba);
7962 ufshcd_link_state_transition(hba, old_link_state, 0);
7964 ufshcd_vops_suspend(hba, pm_op);
7966 ufshcd_vreg_set_lpm(hba);
7967 disable_irq_and_vops_clks:
7968 ufshcd_disable_irq(hba);
7969 if (hba->clk_scaling.is_allowed)
7970 ufshcd_suspend_clkscaling(hba);
7971 ufshcd_setup_clocks(hba, false);
7973 hba->pm_op_in_progress = 0;
7975 ufshcd_update_reg_hist(&hba->ufs_stats.resume_err, (u32)ret);
7980 * ufshcd_system_suspend - system suspend routine
7981 * @hba: per adapter instance
7983 * Check the description of ufshcd_suspend() function for more details.
7985 * Returns 0 for success and non-zero for failure
7987 int ufshcd_system_suspend(struct ufs_hba *hba)
7990 ktime_t start = ktime_get();
7992 if (!hba || !hba->is_powered)
7995 if ((ufs_get_pm_lvl_to_dev_pwr_mode(hba->spm_lvl) ==
7996 hba->curr_dev_pwr_mode) &&
7997 (ufs_get_pm_lvl_to_link_pwr_state(hba->spm_lvl) ==
7998 hba->uic_link_state))
8001 if (pm_runtime_suspended(hba->dev)) {
8003 * UFS device and/or UFS link low power states during runtime
8004 * suspend seems to be different than what is expected during
8005 * system suspend. Hence runtime resume the devic & link and
8006 * let the system suspend low power states to take effect.
8007 * TODO: If resume takes longer time, we might have optimize
8008 * it in future by not resuming everything if possible.
8010 ret = ufshcd_runtime_resume(hba);
8015 ret = ufshcd_suspend(hba, UFS_SYSTEM_PM);
8017 trace_ufshcd_system_suspend(dev_name(hba->dev), ret,
8018 ktime_to_us(ktime_sub(ktime_get(), start)),
8019 hba->curr_dev_pwr_mode, hba->uic_link_state);
8021 hba->is_sys_suspended = true;
8024 EXPORT_SYMBOL(ufshcd_system_suspend);
8027 * ufshcd_system_resume - system resume routine
8028 * @hba: per adapter instance
8030 * Returns 0 for success and non-zero for failure
8033 int ufshcd_system_resume(struct ufs_hba *hba)
8036 ktime_t start = ktime_get();
8041 if (!hba->is_powered || pm_runtime_suspended(hba->dev))
8043 * Let the runtime resume take care of resuming
8044 * if runtime suspended.
8048 ret = ufshcd_resume(hba, UFS_SYSTEM_PM);
8050 trace_ufshcd_system_resume(dev_name(hba->dev), ret,
8051 ktime_to_us(ktime_sub(ktime_get(), start)),
8052 hba->curr_dev_pwr_mode, hba->uic_link_state);
8054 hba->is_sys_suspended = false;
8057 EXPORT_SYMBOL(ufshcd_system_resume);
8060 * ufshcd_runtime_suspend - runtime suspend routine
8061 * @hba: per adapter instance
8063 * Check the description of ufshcd_suspend() function for more details.
8065 * Returns 0 for success and non-zero for failure
8067 int ufshcd_runtime_suspend(struct ufs_hba *hba)
8070 ktime_t start = ktime_get();
8075 if (!hba->is_powered)
8078 ret = ufshcd_suspend(hba, UFS_RUNTIME_PM);
8080 trace_ufshcd_runtime_suspend(dev_name(hba->dev), ret,
8081 ktime_to_us(ktime_sub(ktime_get(), start)),
8082 hba->curr_dev_pwr_mode, hba->uic_link_state);
8085 EXPORT_SYMBOL(ufshcd_runtime_suspend);
8088 * ufshcd_runtime_resume - runtime resume routine
8089 * @hba: per adapter instance
8091 * This function basically brings the UFS device, UniPro link and controller
8092 * to active state. Following operations are done in this function:
8094 * 1. Turn on all the controller related clocks
8095 * 2. Bring the UniPro link out of Hibernate state
8096 * 3. If UFS device is in sleep state, turn ON VCC rail and bring the UFS device
8098 * 4. If auto-bkops is enabled on the device, disable it.
8100 * So following would be the possible power state after this function return
8102 * S1: UFS device in Active state with VCC rail ON
8103 * UniPro link in Active state
8104 * All the UFS/UniPro controller clocks are ON
8106 * Returns 0 for success and non-zero for failure
8108 int ufshcd_runtime_resume(struct ufs_hba *hba)
8111 ktime_t start = ktime_get();
8116 if (!hba->is_powered)
8119 ret = ufshcd_resume(hba, UFS_RUNTIME_PM);
8121 trace_ufshcd_runtime_resume(dev_name(hba->dev), ret,
8122 ktime_to_us(ktime_sub(ktime_get(), start)),
8123 hba->curr_dev_pwr_mode, hba->uic_link_state);
8126 EXPORT_SYMBOL(ufshcd_runtime_resume);
8128 int ufshcd_runtime_idle(struct ufs_hba *hba)
8132 EXPORT_SYMBOL(ufshcd_runtime_idle);
8135 * ufshcd_shutdown - shutdown routine
8136 * @hba: per adapter instance
8138 * This function would power off both UFS device and UFS link.
8140 * Returns 0 always to allow force shutdown even in case of errors.
8142 int ufshcd_shutdown(struct ufs_hba *hba)
8146 if (ufshcd_is_ufs_dev_poweroff(hba) && ufshcd_is_link_off(hba))
8149 if (pm_runtime_suspended(hba->dev)) {
8150 ret = ufshcd_runtime_resume(hba);
8155 ret = ufshcd_suspend(hba, UFS_SHUTDOWN_PM);
8158 dev_err(hba->dev, "%s failed, err %d\n", __func__, ret);
8159 /* allow force shutdown even in case of errors */
8162 EXPORT_SYMBOL(ufshcd_shutdown);
8165 * ufshcd_remove - de-allocate SCSI host and host memory space
8166 * data structure memory
8167 * @hba: per adapter instance
8169 void ufshcd_remove(struct ufs_hba *hba)
8171 ufs_bsg_remove(hba);
8172 ufs_sysfs_remove_nodes(hba->dev);
8173 scsi_remove_host(hba->host);
8174 /* disable interrupts */
8175 ufshcd_disable_intr(hba, hba->intr_mask);
8176 ufshcd_hba_stop(hba, true);
8178 ufshcd_exit_clk_scaling(hba);
8179 ufshcd_exit_clk_gating(hba);
8180 if (ufshcd_is_clkscaling_supported(hba))
8181 device_remove_file(hba->dev, &hba->clk_scaling.enable_attr);
8182 ufshcd_hba_exit(hba);
8184 EXPORT_SYMBOL_GPL(ufshcd_remove);
8187 * ufshcd_dealloc_host - deallocate Host Bus Adapter (HBA)
8188 * @hba: pointer to Host Bus Adapter (HBA)
8190 void ufshcd_dealloc_host(struct ufs_hba *hba)
8192 scsi_host_put(hba->host);
8194 EXPORT_SYMBOL_GPL(ufshcd_dealloc_host);
8197 * ufshcd_set_dma_mask - Set dma mask based on the controller
8198 * addressing capability
8199 * @hba: per adapter instance
8201 * Returns 0 for success, non-zero for failure
8203 static int ufshcd_set_dma_mask(struct ufs_hba *hba)
8205 if (hba->capabilities & MASK_64_ADDRESSING_SUPPORT) {
8206 if (!dma_set_mask_and_coherent(hba->dev, DMA_BIT_MASK(64)))
8209 return dma_set_mask_and_coherent(hba->dev, DMA_BIT_MASK(32));
8213 * ufshcd_alloc_host - allocate Host Bus Adapter (HBA)
8214 * @dev: pointer to device handle
8215 * @hba_handle: driver private handle
8216 * Returns 0 on success, non-zero value on failure
8218 int ufshcd_alloc_host(struct device *dev, struct ufs_hba **hba_handle)
8220 struct Scsi_Host *host;
8221 struct ufs_hba *hba;
8226 "Invalid memory reference for dev is NULL\n");
8231 host = scsi_host_alloc(&ufshcd_driver_template,
8232 sizeof(struct ufs_hba));
8234 dev_err(dev, "scsi_host_alloc failed\n");
8238 hba = shost_priv(host);
8242 hba->dev_ref_clk_freq = REF_CLK_FREQ_INVAL;
8244 INIT_LIST_HEAD(&hba->clk_list_head);
8249 EXPORT_SYMBOL(ufshcd_alloc_host);
8252 * ufshcd_init - Driver initialization routine
8253 * @hba: per-adapter instance
8254 * @mmio_base: base register address
8255 * @irq: Interrupt line of device
8256 * Returns 0 on success, non-zero value on failure
8258 int ufshcd_init(struct ufs_hba *hba, void __iomem *mmio_base, unsigned int irq)
8261 struct Scsi_Host *host = hba->host;
8262 struct device *dev = hba->dev;
8266 "Invalid memory reference for mmio_base is NULL\n");
8271 hba->mmio_base = mmio_base;
8274 /* Set descriptor lengths to specification defaults */
8275 ufshcd_def_desc_sizes(hba);
8277 err = ufshcd_hba_init(hba);
8281 /* Read capabilities registers */
8282 ufshcd_hba_capabilities(hba);
8284 /* Get UFS version supported by the controller */
8285 hba->ufs_version = ufshcd_get_ufs_version(hba);
8287 if ((hba->ufs_version != UFSHCI_VERSION_10) &&
8288 (hba->ufs_version != UFSHCI_VERSION_11) &&
8289 (hba->ufs_version != UFSHCI_VERSION_20) &&
8290 (hba->ufs_version != UFSHCI_VERSION_21))
8291 dev_err(hba->dev, "invalid UFS version 0x%x\n",
8294 /* Get Interrupt bit mask per version */
8295 hba->intr_mask = ufshcd_get_intr_mask(hba);
8297 err = ufshcd_set_dma_mask(hba);
8299 dev_err(hba->dev, "set dma mask failed\n");
8303 /* Allocate memory for host memory space */
8304 err = ufshcd_memory_alloc(hba);
8306 dev_err(hba->dev, "Memory allocation failed\n");
8311 ufshcd_host_memory_configure(hba);
8313 host->can_queue = hba->nutrs;
8314 host->cmd_per_lun = hba->nutrs;
8315 host->max_id = UFSHCD_MAX_ID;
8316 host->max_lun = UFS_MAX_LUNS;
8317 host->max_channel = UFSHCD_MAX_CHANNEL;
8318 host->unique_id = host->host_no;
8319 host->max_cmd_len = UFS_CDB_SIZE;
8321 hba->max_pwr_info.is_valid = false;
8323 /* Initailize wait queue for task management */
8324 init_waitqueue_head(&hba->tm_wq);
8325 init_waitqueue_head(&hba->tm_tag_wq);
8327 /* Initialize work queues */
8328 INIT_WORK(&hba->eh_work, ufshcd_err_handler);
8329 INIT_WORK(&hba->eeh_work, ufshcd_exception_event_handler);
8331 /* Initialize UIC command mutex */
8332 mutex_init(&hba->uic_cmd_mutex);
8334 /* Initialize mutex for device management commands */
8335 mutex_init(&hba->dev_cmd.lock);
8337 init_rwsem(&hba->clk_scaling_lock);
8339 /* Initialize device management tag acquire wait queue */
8340 init_waitqueue_head(&hba->dev_cmd.tag_wq);
8342 ufshcd_init_clk_gating(hba);
8344 ufshcd_init_clk_scaling(hba);
8347 * In order to avoid any spurious interrupt immediately after
8348 * registering UFS controller interrupt handler, clear any pending UFS
8349 * interrupt status and disable all the UFS interrupts.
8351 ufshcd_writel(hba, ufshcd_readl(hba, REG_INTERRUPT_STATUS),
8352 REG_INTERRUPT_STATUS);
8353 ufshcd_writel(hba, 0, REG_INTERRUPT_ENABLE);
8355 * Make sure that UFS interrupts are disabled and any pending interrupt
8356 * status is cleared before registering UFS interrupt handler.
8360 /* IRQ registration */
8361 err = devm_request_irq(dev, irq, ufshcd_intr, IRQF_SHARED, UFSHCD, hba);
8363 dev_err(hba->dev, "request irq failed\n");
8366 hba->is_irq_enabled = true;
8369 err = scsi_add_host(host, hba->dev);
8371 dev_err(hba->dev, "scsi_add_host failed\n");
8375 /* Reset the attached device */
8376 ufshcd_vops_device_reset(hba);
8378 /* Host controller enable */
8379 err = ufshcd_hba_enable(hba);
8381 dev_err(hba->dev, "Host controller enable failed\n");
8382 ufshcd_print_host_regs(hba);
8383 ufshcd_print_host_state(hba);
8384 goto out_remove_scsi_host;
8388 * Set the default power management level for runtime and system PM.
8389 * Default power saving mode is to keep UFS link in Hibern8 state
8390 * and UFS device in sleep state.
8392 hba->rpm_lvl = ufs_get_desired_pm_lvl_for_dev_link_state(
8394 UIC_LINK_HIBERN8_STATE);
8395 hba->spm_lvl = ufs_get_desired_pm_lvl_for_dev_link_state(
8397 UIC_LINK_HIBERN8_STATE);
8399 /* Set the default auto-hiberate idle timer value to 150 ms */
8400 if (ufshcd_is_auto_hibern8_supported(hba) && !hba->ahit) {
8401 hba->ahit = FIELD_PREP(UFSHCI_AHIBERN8_TIMER_MASK, 150) |
8402 FIELD_PREP(UFSHCI_AHIBERN8_SCALE_MASK, 3);
8405 /* Hold auto suspend until async scan completes */
8406 pm_runtime_get_sync(dev);
8407 atomic_set(&hba->scsi_block_reqs_cnt, 0);
8409 * We are assuming that device wasn't put in sleep/power-down
8410 * state exclusively during the boot stage before kernel.
8411 * This assumption helps avoid doing link startup twice during
8412 * ufshcd_probe_hba().
8414 ufshcd_set_ufs_dev_active(hba);
8416 async_schedule(ufshcd_async_scan, hba);
8417 ufs_sysfs_add_nodes(hba->dev);
8421 out_remove_scsi_host:
8422 scsi_remove_host(hba->host);
8424 ufshcd_exit_clk_scaling(hba);
8425 ufshcd_exit_clk_gating(hba);
8427 hba->is_irq_enabled = false;
8428 ufshcd_hba_exit(hba);
8432 EXPORT_SYMBOL_GPL(ufshcd_init);
8434 MODULE_AUTHOR("Santosh Yaragnavi <santosh.sy@samsung.com>");
8435 MODULE_AUTHOR("Vinayak Holikatti <h.vinayak@samsung.com>");
8436 MODULE_DESCRIPTION("Generic UFS host controller driver Core");
8437 MODULE_LICENSE("GPL");
8438 MODULE_VERSION(UFSHCD_DRIVER_VERSION);