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"
50 #define CREATE_TRACE_POINTS
51 #include <trace/events/ufs.h>
53 #define UFSHCD_REQ_SENSE_SIZE 18
55 #define UFSHCD_ENABLE_INTRS (UTP_TRANSFER_REQ_COMPL |\
58 /* UIC command timeout, unit: ms */
59 #define UIC_CMD_TIMEOUT 500
61 /* NOP OUT retries waiting for NOP IN response */
62 #define NOP_OUT_RETRIES 10
63 /* Timeout after 30 msecs if NOP OUT hangs without response */
64 #define NOP_OUT_TIMEOUT 30 /* msecs */
66 /* Query request retries */
67 #define QUERY_REQ_RETRIES 3
68 /* Query request timeout */
69 #define QUERY_REQ_TIMEOUT 1500 /* 1.5 seconds */
71 /* Task management command timeout */
72 #define TM_CMD_TIMEOUT 100 /* msecs */
74 /* maximum number of retries for a general UIC command */
75 #define UFS_UIC_COMMAND_RETRIES 3
77 /* maximum number of link-startup retries */
78 #define DME_LINKSTARTUP_RETRIES 3
80 /* Maximum retries for Hibern8 enter */
81 #define UIC_HIBERN8_ENTER_RETRIES 3
83 /* maximum number of reset retries before giving up */
84 #define MAX_HOST_RESET_RETRIES 5
86 /* Expose the flag value from utp_upiu_query.value */
87 #define MASK_QUERY_UPIU_FLAG_LOC 0xFF
89 /* Interrupt aggregation default timeout, unit: 40us */
90 #define INT_AGGR_DEF_TO 0x02
92 #define ufshcd_toggle_vreg(_dev, _vreg, _on) \
96 _ret = ufshcd_enable_vreg(_dev, _vreg); \
98 _ret = ufshcd_disable_vreg(_dev, _vreg); \
102 #define ufshcd_hex_dump(prefix_str, buf, len) do { \
103 size_t __len = (len); \
104 print_hex_dump(KERN_ERR, prefix_str, \
105 __len > 4 ? DUMP_PREFIX_OFFSET : DUMP_PREFIX_NONE,\
106 16, 4, buf, __len, false); \
109 int ufshcd_dump_regs(struct ufs_hba *hba, size_t offset, size_t len,
115 if (offset % 4 != 0 || len % 4 != 0) /* keep readl happy */
118 regs = kzalloc(len, GFP_KERNEL);
122 for (pos = 0; pos < len; pos += 4)
123 regs[pos / 4] = ufshcd_readl(hba, offset + pos);
125 ufshcd_hex_dump(prefix, regs, len);
130 EXPORT_SYMBOL_GPL(ufshcd_dump_regs);
133 UFSHCD_MAX_CHANNEL = 0,
135 UFSHCD_CMD_PER_LUN = 32,
136 UFSHCD_CAN_QUEUE = 32,
143 UFSHCD_STATE_OPERATIONAL,
144 UFSHCD_STATE_EH_SCHEDULED,
147 /* UFSHCD error handling flags */
149 UFSHCD_EH_IN_PROGRESS = (1 << 0),
152 /* UFSHCD UIC layer error flags */
154 UFSHCD_UIC_DL_PA_INIT_ERROR = (1 << 0), /* Data link layer error */
155 UFSHCD_UIC_DL_NAC_RECEIVED_ERROR = (1 << 1), /* Data link layer error */
156 UFSHCD_UIC_DL_TCx_REPLAY_ERROR = (1 << 2), /* Data link layer error */
157 UFSHCD_UIC_NL_ERROR = (1 << 3), /* Network layer error */
158 UFSHCD_UIC_TL_ERROR = (1 << 4), /* Transport Layer error */
159 UFSHCD_UIC_DME_ERROR = (1 << 5), /* DME error */
162 #define ufshcd_set_eh_in_progress(h) \
163 ((h)->eh_flags |= UFSHCD_EH_IN_PROGRESS)
164 #define ufshcd_eh_in_progress(h) \
165 ((h)->eh_flags & UFSHCD_EH_IN_PROGRESS)
166 #define ufshcd_clear_eh_in_progress(h) \
167 ((h)->eh_flags &= ~UFSHCD_EH_IN_PROGRESS)
169 #define ufshcd_set_ufs_dev_active(h) \
170 ((h)->curr_dev_pwr_mode = UFS_ACTIVE_PWR_MODE)
171 #define ufshcd_set_ufs_dev_sleep(h) \
172 ((h)->curr_dev_pwr_mode = UFS_SLEEP_PWR_MODE)
173 #define ufshcd_set_ufs_dev_poweroff(h) \
174 ((h)->curr_dev_pwr_mode = UFS_POWERDOWN_PWR_MODE)
175 #define ufshcd_is_ufs_dev_active(h) \
176 ((h)->curr_dev_pwr_mode == UFS_ACTIVE_PWR_MODE)
177 #define ufshcd_is_ufs_dev_sleep(h) \
178 ((h)->curr_dev_pwr_mode == UFS_SLEEP_PWR_MODE)
179 #define ufshcd_is_ufs_dev_poweroff(h) \
180 ((h)->curr_dev_pwr_mode == UFS_POWERDOWN_PWR_MODE)
182 struct ufs_pm_lvl_states ufs_pm_lvl_states[] = {
183 {UFS_ACTIVE_PWR_MODE, UIC_LINK_ACTIVE_STATE},
184 {UFS_ACTIVE_PWR_MODE, UIC_LINK_HIBERN8_STATE},
185 {UFS_SLEEP_PWR_MODE, UIC_LINK_ACTIVE_STATE},
186 {UFS_SLEEP_PWR_MODE, UIC_LINK_HIBERN8_STATE},
187 {UFS_POWERDOWN_PWR_MODE, UIC_LINK_HIBERN8_STATE},
188 {UFS_POWERDOWN_PWR_MODE, UIC_LINK_OFF_STATE},
191 static inline enum ufs_dev_pwr_mode
192 ufs_get_pm_lvl_to_dev_pwr_mode(enum ufs_pm_level lvl)
194 return ufs_pm_lvl_states[lvl].dev_state;
197 static inline enum uic_link_state
198 ufs_get_pm_lvl_to_link_pwr_state(enum ufs_pm_level lvl)
200 return ufs_pm_lvl_states[lvl].link_state;
203 static inline enum ufs_pm_level
204 ufs_get_desired_pm_lvl_for_dev_link_state(enum ufs_dev_pwr_mode dev_state,
205 enum uic_link_state link_state)
207 enum ufs_pm_level lvl;
209 for (lvl = UFS_PM_LVL_0; lvl < UFS_PM_LVL_MAX; lvl++) {
210 if ((ufs_pm_lvl_states[lvl].dev_state == dev_state) &&
211 (ufs_pm_lvl_states[lvl].link_state == link_state))
215 /* if no match found, return the level 0 */
219 static struct ufs_dev_fix ufs_fixups[] = {
220 /* UFS cards deviations table */
221 UFS_FIX(UFS_VENDOR_MICRON, UFS_ANY_MODEL,
222 UFS_DEVICE_QUIRK_DELAY_BEFORE_LPM),
223 UFS_FIX(UFS_VENDOR_SAMSUNG, UFS_ANY_MODEL,
224 UFS_DEVICE_QUIRK_DELAY_BEFORE_LPM),
225 UFS_FIX(UFS_VENDOR_SAMSUNG, UFS_ANY_MODEL, UFS_DEVICE_NO_VCCQ),
226 UFS_FIX(UFS_VENDOR_SAMSUNG, UFS_ANY_MODEL,
227 UFS_DEVICE_QUIRK_RECOVERY_FROM_DL_NAC_ERRORS),
228 UFS_FIX(UFS_VENDOR_SAMSUNG, UFS_ANY_MODEL,
229 UFS_DEVICE_NO_FASTAUTO),
230 UFS_FIX(UFS_VENDOR_SAMSUNG, UFS_ANY_MODEL,
231 UFS_DEVICE_QUIRK_HOST_PA_TACTIVATE),
232 UFS_FIX(UFS_VENDOR_TOSHIBA, UFS_ANY_MODEL,
233 UFS_DEVICE_QUIRK_DELAY_BEFORE_LPM),
234 UFS_FIX(UFS_VENDOR_TOSHIBA, "THGLF2G9C8KBADG",
235 UFS_DEVICE_QUIRK_PA_TACTIVATE),
236 UFS_FIX(UFS_VENDOR_TOSHIBA, "THGLF2G9D8KBADG",
237 UFS_DEVICE_QUIRK_PA_TACTIVATE),
238 UFS_FIX(UFS_VENDOR_SKHYNIX, UFS_ANY_MODEL, UFS_DEVICE_NO_VCCQ),
239 UFS_FIX(UFS_VENDOR_SKHYNIX, UFS_ANY_MODEL,
240 UFS_DEVICE_QUIRK_HOST_PA_SAVECONFIGTIME),
241 UFS_FIX(UFS_VENDOR_SKHYNIX, "hB8aL1" /*H28U62301AMR*/,
242 UFS_DEVICE_QUIRK_HOST_VS_DEBUGSAVECONFIGTIME),
247 static void ufshcd_tmc_handler(struct ufs_hba *hba);
248 static void ufshcd_async_scan(void *data, async_cookie_t cookie);
249 static int ufshcd_reset_and_restore(struct ufs_hba *hba);
250 static int ufshcd_eh_host_reset_handler(struct scsi_cmnd *cmd);
251 static int ufshcd_clear_tm_cmd(struct ufs_hba *hba, int tag);
252 static void ufshcd_hba_exit(struct ufs_hba *hba);
253 static int ufshcd_probe_hba(struct ufs_hba *hba);
254 static int __ufshcd_setup_clocks(struct ufs_hba *hba, bool on,
256 static int ufshcd_setup_clocks(struct ufs_hba *hba, bool on);
257 static int ufshcd_set_vccq_rail_unused(struct ufs_hba *hba, bool unused);
258 static int ufshcd_uic_hibern8_exit(struct ufs_hba *hba);
259 static int ufshcd_uic_hibern8_enter(struct ufs_hba *hba);
260 static inline void ufshcd_add_delay_before_dme_cmd(struct ufs_hba *hba);
261 static int ufshcd_host_reset_and_restore(struct ufs_hba *hba);
262 static void ufshcd_resume_clkscaling(struct ufs_hba *hba);
263 static void ufshcd_suspend_clkscaling(struct ufs_hba *hba);
264 static void __ufshcd_suspend_clkscaling(struct ufs_hba *hba);
265 static int ufshcd_scale_clks(struct ufs_hba *hba, bool scale_up);
266 static irqreturn_t ufshcd_intr(int irq, void *__hba);
267 static int ufshcd_change_power_mode(struct ufs_hba *hba,
268 struct ufs_pa_layer_attr *pwr_mode);
269 static inline bool ufshcd_valid_tag(struct ufs_hba *hba, int tag)
271 return tag >= 0 && tag < hba->nutrs;
274 static inline int ufshcd_enable_irq(struct ufs_hba *hba)
278 if (!hba->is_irq_enabled) {
279 ret = request_irq(hba->irq, ufshcd_intr, IRQF_SHARED, UFSHCD,
282 dev_err(hba->dev, "%s: request_irq failed, ret=%d\n",
284 hba->is_irq_enabled = true;
290 static inline void ufshcd_disable_irq(struct ufs_hba *hba)
292 if (hba->is_irq_enabled) {
293 free_irq(hba->irq, hba);
294 hba->is_irq_enabled = false;
298 static void ufshcd_scsi_unblock_requests(struct ufs_hba *hba)
300 if (atomic_dec_and_test(&hba->scsi_block_reqs_cnt))
301 scsi_unblock_requests(hba->host);
304 static void ufshcd_scsi_block_requests(struct ufs_hba *hba)
306 if (atomic_inc_return(&hba->scsi_block_reqs_cnt) == 1)
307 scsi_block_requests(hba->host);
310 /* replace non-printable or non-ASCII characters with spaces */
311 static inline void ufshcd_remove_non_printable(char *val)
316 if (*val < 0x20 || *val > 0x7e)
320 static void ufshcd_add_cmd_upiu_trace(struct ufs_hba *hba, unsigned int tag,
323 struct utp_upiu_req *rq = hba->lrb[tag].ucd_req_ptr;
325 trace_ufshcd_upiu(dev_name(hba->dev), str, &rq->header, &rq->sc.cdb);
328 static void ufshcd_add_query_upiu_trace(struct ufs_hba *hba, unsigned int tag,
331 struct utp_upiu_req *rq = hba->lrb[tag].ucd_req_ptr;
333 trace_ufshcd_upiu(dev_name(hba->dev), str, &rq->header, &rq->qr);
336 static void ufshcd_add_tm_upiu_trace(struct ufs_hba *hba, unsigned int tag,
339 struct utp_task_req_desc *descp;
340 struct utp_upiu_task_req *task_req;
341 int off = (int)tag - hba->nutrs;
343 descp = &hba->utmrdl_base_addr[off];
344 task_req = (struct utp_upiu_task_req *)descp->task_req_upiu;
345 trace_ufshcd_upiu(dev_name(hba->dev), str, &task_req->header,
346 &task_req->input_param1);
349 static void ufshcd_add_command_trace(struct ufs_hba *hba,
350 unsigned int tag, const char *str)
355 struct ufshcd_lrb *lrbp = &hba->lrb[tag];
356 struct scsi_cmnd *cmd = lrbp->cmd;
357 int transfer_len = -1;
359 if (!trace_ufshcd_command_enabled()) {
360 /* trace UPIU W/O tracing command */
362 ufshcd_add_cmd_upiu_trace(hba, tag, str);
366 if (cmd) { /* data phase exists */
367 /* trace UPIU also */
368 ufshcd_add_cmd_upiu_trace(hba, tag, str);
369 opcode = cmd->cmnd[0];
370 if ((opcode == READ_10) || (opcode == WRITE_10)) {
372 * Currently we only fully trace read(10) and write(10)
375 if (cmd->request && cmd->request->bio)
376 lba = cmd->request->bio->bi_iter.bi_sector;
377 transfer_len = be32_to_cpu(
378 lrbp->ucd_req_ptr->sc.exp_data_transfer_len);
382 intr = ufshcd_readl(hba, REG_INTERRUPT_STATUS);
383 doorbell = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
384 trace_ufshcd_command(dev_name(hba->dev), str, tag,
385 doorbell, transfer_len, intr, lba, opcode);
388 static void ufshcd_print_clk_freqs(struct ufs_hba *hba)
390 struct ufs_clk_info *clki;
391 struct list_head *head = &hba->clk_list_head;
393 if (list_empty(head))
396 list_for_each_entry(clki, head, list) {
397 if (!IS_ERR_OR_NULL(clki->clk) && clki->min_freq &&
399 dev_err(hba->dev, "clk: %s, rate: %u\n",
400 clki->name, clki->curr_freq);
404 static void ufshcd_print_uic_err_hist(struct ufs_hba *hba,
405 struct ufs_uic_err_reg_hist *err_hist, char *err_name)
409 for (i = 0; i < UIC_ERR_REG_HIST_LENGTH; i++) {
410 int p = (i + err_hist->pos - 1) % UIC_ERR_REG_HIST_LENGTH;
412 if (err_hist->reg[p] == 0)
414 dev_err(hba->dev, "%s[%d] = 0x%x at %lld us\n", err_name, i,
415 err_hist->reg[p], ktime_to_us(err_hist->tstamp[p]));
419 static void ufshcd_print_host_regs(struct ufs_hba *hba)
421 ufshcd_dump_regs(hba, 0, UFSHCI_REG_SPACE_SIZE, "host_regs: ");
422 dev_err(hba->dev, "hba->ufs_version = 0x%x, hba->capabilities = 0x%x\n",
423 hba->ufs_version, hba->capabilities);
425 "hba->outstanding_reqs = 0x%x, hba->outstanding_tasks = 0x%x\n",
426 (u32)hba->outstanding_reqs, (u32)hba->outstanding_tasks);
428 "last_hibern8_exit_tstamp at %lld us, hibern8_exit_cnt = %d\n",
429 ktime_to_us(hba->ufs_stats.last_hibern8_exit_tstamp),
430 hba->ufs_stats.hibern8_exit_cnt);
432 ufshcd_print_uic_err_hist(hba, &hba->ufs_stats.pa_err, "pa_err");
433 ufshcd_print_uic_err_hist(hba, &hba->ufs_stats.dl_err, "dl_err");
434 ufshcd_print_uic_err_hist(hba, &hba->ufs_stats.nl_err, "nl_err");
435 ufshcd_print_uic_err_hist(hba, &hba->ufs_stats.tl_err, "tl_err");
436 ufshcd_print_uic_err_hist(hba, &hba->ufs_stats.dme_err, "dme_err");
438 ufshcd_print_clk_freqs(hba);
440 if (hba->vops && hba->vops->dbg_register_dump)
441 hba->vops->dbg_register_dump(hba);
445 void ufshcd_print_trs(struct ufs_hba *hba, unsigned long bitmap, bool pr_prdt)
447 struct ufshcd_lrb *lrbp;
451 for_each_set_bit(tag, &bitmap, hba->nutrs) {
452 lrbp = &hba->lrb[tag];
454 dev_err(hba->dev, "UPIU[%d] - issue time %lld us\n",
455 tag, ktime_to_us(lrbp->issue_time_stamp));
456 dev_err(hba->dev, "UPIU[%d] - complete time %lld us\n",
457 tag, ktime_to_us(lrbp->compl_time_stamp));
459 "UPIU[%d] - Transfer Request Descriptor phys@0x%llx\n",
460 tag, (u64)lrbp->utrd_dma_addr);
462 ufshcd_hex_dump("UPIU TRD: ", lrbp->utr_descriptor_ptr,
463 sizeof(struct utp_transfer_req_desc));
464 dev_err(hba->dev, "UPIU[%d] - Request UPIU phys@0x%llx\n", tag,
465 (u64)lrbp->ucd_req_dma_addr);
466 ufshcd_hex_dump("UPIU REQ: ", lrbp->ucd_req_ptr,
467 sizeof(struct utp_upiu_req));
468 dev_err(hba->dev, "UPIU[%d] - Response UPIU phys@0x%llx\n", tag,
469 (u64)lrbp->ucd_rsp_dma_addr);
470 ufshcd_hex_dump("UPIU RSP: ", lrbp->ucd_rsp_ptr,
471 sizeof(struct utp_upiu_rsp));
473 prdt_length = le16_to_cpu(
474 lrbp->utr_descriptor_ptr->prd_table_length);
476 "UPIU[%d] - PRDT - %d entries phys@0x%llx\n",
478 (u64)lrbp->ucd_prdt_dma_addr);
481 ufshcd_hex_dump("UPIU PRDT: ", lrbp->ucd_prdt_ptr,
482 sizeof(struct ufshcd_sg_entry) * prdt_length);
486 static void ufshcd_print_tmrs(struct ufs_hba *hba, unsigned long bitmap)
488 struct utp_task_req_desc *tmrdp;
491 for_each_set_bit(tag, &bitmap, hba->nutmrs) {
492 tmrdp = &hba->utmrdl_base_addr[tag];
493 dev_err(hba->dev, "TM[%d] - Task Management Header\n", tag);
494 ufshcd_hex_dump("TM TRD: ", &tmrdp->header,
495 sizeof(struct request_desc_header));
496 dev_err(hba->dev, "TM[%d] - Task Management Request UPIU\n",
498 ufshcd_hex_dump("TM REQ: ", tmrdp->task_req_upiu,
499 sizeof(struct utp_upiu_req));
500 dev_err(hba->dev, "TM[%d] - Task Management Response UPIU\n",
502 ufshcd_hex_dump("TM RSP: ", tmrdp->task_rsp_upiu,
503 sizeof(struct utp_task_req_desc));
507 static void ufshcd_print_host_state(struct ufs_hba *hba)
509 dev_err(hba->dev, "UFS Host state=%d\n", hba->ufshcd_state);
510 dev_err(hba->dev, "lrb in use=0x%lx, outstanding reqs=0x%lx tasks=0x%lx\n",
511 hba->lrb_in_use, hba->outstanding_reqs, hba->outstanding_tasks);
512 dev_err(hba->dev, "saved_err=0x%x, saved_uic_err=0x%x\n",
513 hba->saved_err, hba->saved_uic_err);
514 dev_err(hba->dev, "Device power mode=%d, UIC link state=%d\n",
515 hba->curr_dev_pwr_mode, hba->uic_link_state);
516 dev_err(hba->dev, "PM in progress=%d, sys. suspended=%d\n",
517 hba->pm_op_in_progress, hba->is_sys_suspended);
518 dev_err(hba->dev, "Auto BKOPS=%d, Host self-block=%d\n",
519 hba->auto_bkops_enabled, hba->host->host_self_blocked);
520 dev_err(hba->dev, "Clk gate=%d\n", hba->clk_gating.state);
521 dev_err(hba->dev, "error handling flags=0x%x, req. abort count=%d\n",
522 hba->eh_flags, hba->req_abort_count);
523 dev_err(hba->dev, "Host capabilities=0x%x, caps=0x%x\n",
524 hba->capabilities, hba->caps);
525 dev_err(hba->dev, "quirks=0x%x, dev. quirks=0x%x\n", hba->quirks,
530 * ufshcd_print_pwr_info - print power params as saved in hba
532 * @hba: per-adapter instance
534 static void ufshcd_print_pwr_info(struct ufs_hba *hba)
536 static const char * const names[] = {
546 dev_err(hba->dev, "%s:[RX, TX]: gear=[%d, %d], lane[%d, %d], pwr[%s, %s], rate = %d\n",
548 hba->pwr_info.gear_rx, hba->pwr_info.gear_tx,
549 hba->pwr_info.lane_rx, hba->pwr_info.lane_tx,
550 names[hba->pwr_info.pwr_rx],
551 names[hba->pwr_info.pwr_tx],
552 hba->pwr_info.hs_rate);
556 * ufshcd_wait_for_register - wait for register value to change
557 * @hba - per-adapter interface
558 * @reg - mmio register offset
559 * @mask - mask to apply to read register value
560 * @val - wait condition
561 * @interval_us - polling interval in microsecs
562 * @timeout_ms - timeout in millisecs
563 * @can_sleep - perform sleep or just spin
565 * Returns -ETIMEDOUT on error, zero on success
567 int ufshcd_wait_for_register(struct ufs_hba *hba, u32 reg, u32 mask,
568 u32 val, unsigned long interval_us,
569 unsigned long timeout_ms, bool can_sleep)
572 unsigned long timeout = jiffies + msecs_to_jiffies(timeout_ms);
574 /* ignore bits that we don't intend to wait on */
577 while ((ufshcd_readl(hba, reg) & mask) != val) {
579 usleep_range(interval_us, interval_us + 50);
582 if (time_after(jiffies, timeout)) {
583 if ((ufshcd_readl(hba, reg) & mask) != val)
593 * ufshcd_get_intr_mask - Get the interrupt bit mask
594 * @hba: Pointer to adapter instance
596 * Returns interrupt bit mask per version
598 static inline u32 ufshcd_get_intr_mask(struct ufs_hba *hba)
602 switch (hba->ufs_version) {
603 case UFSHCI_VERSION_10:
604 intr_mask = INTERRUPT_MASK_ALL_VER_10;
606 case UFSHCI_VERSION_11:
607 case UFSHCI_VERSION_20:
608 intr_mask = INTERRUPT_MASK_ALL_VER_11;
610 case UFSHCI_VERSION_21:
612 intr_mask = INTERRUPT_MASK_ALL_VER_21;
620 * ufshcd_get_ufs_version - Get the UFS version supported by the HBA
621 * @hba: Pointer to adapter instance
623 * Returns UFSHCI version supported by the controller
625 static inline u32 ufshcd_get_ufs_version(struct ufs_hba *hba)
627 if (hba->quirks & UFSHCD_QUIRK_BROKEN_UFS_HCI_VERSION)
628 return ufshcd_vops_get_ufs_hci_version(hba);
630 return ufshcd_readl(hba, REG_UFS_VERSION);
634 * ufshcd_is_device_present - Check if any device connected to
635 * the host controller
636 * @hba: pointer to adapter instance
638 * Returns true if device present, false if no device detected
640 static inline bool ufshcd_is_device_present(struct ufs_hba *hba)
642 return (ufshcd_readl(hba, REG_CONTROLLER_STATUS) &
643 DEVICE_PRESENT) ? true : false;
647 * ufshcd_get_tr_ocs - Get the UTRD Overall Command Status
648 * @lrbp: pointer to local command reference block
650 * This function is used to get the OCS field from UTRD
651 * Returns the OCS field in the UTRD
653 static inline int ufshcd_get_tr_ocs(struct ufshcd_lrb *lrbp)
655 return le32_to_cpu(lrbp->utr_descriptor_ptr->header.dword_2) & MASK_OCS;
659 * ufshcd_get_tmr_ocs - Get the UTMRD Overall Command Status
660 * @task_req_descp: pointer to utp_task_req_desc structure
662 * This function is used to get the OCS field from UTMRD
663 * Returns the OCS field in the UTMRD
666 ufshcd_get_tmr_ocs(struct utp_task_req_desc *task_req_descp)
668 return le32_to_cpu(task_req_descp->header.dword_2) & MASK_OCS;
672 * ufshcd_get_tm_free_slot - get a free slot for task management request
673 * @hba: per adapter instance
674 * @free_slot: pointer to variable with available slot value
676 * Get a free tag and lock it until ufshcd_put_tm_slot() is called.
677 * Returns 0 if free slot is not available, else return 1 with tag value
680 static bool ufshcd_get_tm_free_slot(struct ufs_hba *hba, int *free_slot)
689 tag = find_first_zero_bit(&hba->tm_slots_in_use, hba->nutmrs);
690 if (tag >= hba->nutmrs)
692 } while (test_and_set_bit_lock(tag, &hba->tm_slots_in_use));
700 static inline void ufshcd_put_tm_slot(struct ufs_hba *hba, int slot)
702 clear_bit_unlock(slot, &hba->tm_slots_in_use);
706 * ufshcd_utrl_clear - Clear a bit in UTRLCLR register
707 * @hba: per adapter instance
708 * @pos: position of the bit to be cleared
710 static inline void ufshcd_utrl_clear(struct ufs_hba *hba, u32 pos)
712 if (hba->quirks & UFSHCI_QUIRK_BROKEN_REQ_LIST_CLR)
713 ufshcd_writel(hba, (1 << pos), REG_UTP_TRANSFER_REQ_LIST_CLEAR);
715 ufshcd_writel(hba, ~(1 << pos),
716 REG_UTP_TRANSFER_REQ_LIST_CLEAR);
720 * ufshcd_utmrl_clear - Clear a bit in UTRMLCLR register
721 * @hba: per adapter instance
722 * @pos: position of the bit to be cleared
724 static inline void ufshcd_utmrl_clear(struct ufs_hba *hba, u32 pos)
726 if (hba->quirks & UFSHCI_QUIRK_BROKEN_REQ_LIST_CLR)
727 ufshcd_writel(hba, (1 << pos), REG_UTP_TASK_REQ_LIST_CLEAR);
729 ufshcd_writel(hba, ~(1 << pos), REG_UTP_TASK_REQ_LIST_CLEAR);
733 * ufshcd_outstanding_req_clear - Clear a bit in outstanding request field
734 * @hba: per adapter instance
735 * @tag: position of the bit to be cleared
737 static inline void ufshcd_outstanding_req_clear(struct ufs_hba *hba, int tag)
739 __clear_bit(tag, &hba->outstanding_reqs);
743 * ufshcd_get_lists_status - Check UCRDY, UTRLRDY and UTMRLRDY
744 * @reg: Register value of host controller status
746 * Returns integer, 0 on Success and positive value if failed
748 static inline int ufshcd_get_lists_status(u32 reg)
750 return !((reg & UFSHCD_STATUS_READY) == UFSHCD_STATUS_READY);
754 * ufshcd_get_uic_cmd_result - Get the UIC command result
755 * @hba: Pointer to adapter instance
757 * This function gets the result of UIC command completion
758 * Returns 0 on success, non zero value on error
760 static inline int ufshcd_get_uic_cmd_result(struct ufs_hba *hba)
762 return ufshcd_readl(hba, REG_UIC_COMMAND_ARG_2) &
763 MASK_UIC_COMMAND_RESULT;
767 * ufshcd_get_dme_attr_val - Get the value of attribute returned by UIC command
768 * @hba: Pointer to adapter instance
770 * This function gets UIC command argument3
771 * Returns 0 on success, non zero value on error
773 static inline u32 ufshcd_get_dme_attr_val(struct ufs_hba *hba)
775 return ufshcd_readl(hba, REG_UIC_COMMAND_ARG_3);
779 * ufshcd_get_req_rsp - returns the TR response transaction type
780 * @ucd_rsp_ptr: pointer to response UPIU
783 ufshcd_get_req_rsp(struct utp_upiu_rsp *ucd_rsp_ptr)
785 return be32_to_cpu(ucd_rsp_ptr->header.dword_0) >> 24;
789 * ufshcd_get_rsp_upiu_result - Get the result from response UPIU
790 * @ucd_rsp_ptr: pointer to response UPIU
792 * This function gets the response status and scsi_status from response UPIU
793 * Returns the response result code.
796 ufshcd_get_rsp_upiu_result(struct utp_upiu_rsp *ucd_rsp_ptr)
798 return be32_to_cpu(ucd_rsp_ptr->header.dword_1) & MASK_RSP_UPIU_RESULT;
802 * ufshcd_get_rsp_upiu_data_seg_len - Get the data segment length
804 * @ucd_rsp_ptr: pointer to response UPIU
806 * Return the data segment length.
808 static inline unsigned int
809 ufshcd_get_rsp_upiu_data_seg_len(struct utp_upiu_rsp *ucd_rsp_ptr)
811 return be32_to_cpu(ucd_rsp_ptr->header.dword_2) &
812 MASK_RSP_UPIU_DATA_SEG_LEN;
816 * ufshcd_is_exception_event - Check if the device raised an exception event
817 * @ucd_rsp_ptr: pointer to response UPIU
819 * The function checks if the device raised an exception event indicated in
820 * the Device Information field of response UPIU.
822 * Returns true if exception is raised, false otherwise.
824 static inline bool ufshcd_is_exception_event(struct utp_upiu_rsp *ucd_rsp_ptr)
826 return be32_to_cpu(ucd_rsp_ptr->header.dword_2) &
827 MASK_RSP_EXCEPTION_EVENT ? true : false;
831 * ufshcd_reset_intr_aggr - Reset interrupt aggregation values.
832 * @hba: per adapter instance
835 ufshcd_reset_intr_aggr(struct ufs_hba *hba)
837 ufshcd_writel(hba, INT_AGGR_ENABLE |
838 INT_AGGR_COUNTER_AND_TIMER_RESET,
839 REG_UTP_TRANSFER_REQ_INT_AGG_CONTROL);
843 * ufshcd_config_intr_aggr - Configure interrupt aggregation values.
844 * @hba: per adapter instance
845 * @cnt: Interrupt aggregation counter threshold
846 * @tmout: Interrupt aggregation timeout value
849 ufshcd_config_intr_aggr(struct ufs_hba *hba, u8 cnt, u8 tmout)
851 ufshcd_writel(hba, INT_AGGR_ENABLE | INT_AGGR_PARAM_WRITE |
852 INT_AGGR_COUNTER_THLD_VAL(cnt) |
853 INT_AGGR_TIMEOUT_VAL(tmout),
854 REG_UTP_TRANSFER_REQ_INT_AGG_CONTROL);
858 * ufshcd_disable_intr_aggr - Disables interrupt aggregation.
859 * @hba: per adapter instance
861 static inline void ufshcd_disable_intr_aggr(struct ufs_hba *hba)
863 ufshcd_writel(hba, 0, REG_UTP_TRANSFER_REQ_INT_AGG_CONTROL);
867 * ufshcd_enable_run_stop_reg - Enable run-stop registers,
868 * When run-stop registers are set to 1, it indicates the
869 * host controller that it can process the requests
870 * @hba: per adapter instance
872 static void ufshcd_enable_run_stop_reg(struct ufs_hba *hba)
874 ufshcd_writel(hba, UTP_TASK_REQ_LIST_RUN_STOP_BIT,
875 REG_UTP_TASK_REQ_LIST_RUN_STOP);
876 ufshcd_writel(hba, UTP_TRANSFER_REQ_LIST_RUN_STOP_BIT,
877 REG_UTP_TRANSFER_REQ_LIST_RUN_STOP);
881 * ufshcd_hba_start - Start controller initialization sequence
882 * @hba: per adapter instance
884 static inline void ufshcd_hba_start(struct ufs_hba *hba)
886 ufshcd_writel(hba, CONTROLLER_ENABLE, REG_CONTROLLER_ENABLE);
890 * ufshcd_is_hba_active - Get controller state
891 * @hba: per adapter instance
893 * Returns false if controller is active, true otherwise
895 static inline bool ufshcd_is_hba_active(struct ufs_hba *hba)
897 return (ufshcd_readl(hba, REG_CONTROLLER_ENABLE) & CONTROLLER_ENABLE)
901 u32 ufshcd_get_local_unipro_ver(struct ufs_hba *hba)
903 /* HCI version 1.0 and 1.1 supports UniPro 1.41 */
904 if ((hba->ufs_version == UFSHCI_VERSION_10) ||
905 (hba->ufs_version == UFSHCI_VERSION_11))
906 return UFS_UNIPRO_VER_1_41;
908 return UFS_UNIPRO_VER_1_6;
910 EXPORT_SYMBOL(ufshcd_get_local_unipro_ver);
912 static bool ufshcd_is_unipro_pa_params_tuning_req(struct ufs_hba *hba)
915 * If both host and device support UniPro ver1.6 or later, PA layer
916 * parameters tuning happens during link startup itself.
918 * We can manually tune PA layer parameters if either host or device
919 * doesn't support UniPro ver 1.6 or later. But to keep manual tuning
920 * logic simple, we will only do manual tuning if local unipro version
921 * doesn't support ver1.6 or later.
923 if (ufshcd_get_local_unipro_ver(hba) < UFS_UNIPRO_VER_1_6)
929 static int ufshcd_scale_clks(struct ufs_hba *hba, bool scale_up)
932 struct ufs_clk_info *clki;
933 struct list_head *head = &hba->clk_list_head;
934 ktime_t start = ktime_get();
935 bool clk_state_changed = false;
937 if (list_empty(head))
940 ret = ufshcd_vops_clk_scale_notify(hba, scale_up, PRE_CHANGE);
944 list_for_each_entry(clki, head, list) {
945 if (!IS_ERR_OR_NULL(clki->clk)) {
946 if (scale_up && clki->max_freq) {
947 if (clki->curr_freq == clki->max_freq)
950 clk_state_changed = true;
951 ret = clk_set_rate(clki->clk, clki->max_freq);
953 dev_err(hba->dev, "%s: %s clk set rate(%dHz) failed, %d\n",
954 __func__, clki->name,
955 clki->max_freq, ret);
958 trace_ufshcd_clk_scaling(dev_name(hba->dev),
959 "scaled up", clki->name,
963 clki->curr_freq = clki->max_freq;
965 } else if (!scale_up && clki->min_freq) {
966 if (clki->curr_freq == clki->min_freq)
969 clk_state_changed = true;
970 ret = clk_set_rate(clki->clk, clki->min_freq);
972 dev_err(hba->dev, "%s: %s clk set rate(%dHz) failed, %d\n",
973 __func__, clki->name,
974 clki->min_freq, ret);
977 trace_ufshcd_clk_scaling(dev_name(hba->dev),
978 "scaled down", clki->name,
981 clki->curr_freq = clki->min_freq;
984 dev_dbg(hba->dev, "%s: clk: %s, rate: %lu\n", __func__,
985 clki->name, clk_get_rate(clki->clk));
988 ret = ufshcd_vops_clk_scale_notify(hba, scale_up, POST_CHANGE);
991 if (clk_state_changed)
992 trace_ufshcd_profile_clk_scaling(dev_name(hba->dev),
993 (scale_up ? "up" : "down"),
994 ktime_to_us(ktime_sub(ktime_get(), start)), ret);
999 * ufshcd_is_devfreq_scaling_required - check if scaling is required or not
1000 * @hba: per adapter instance
1001 * @scale_up: True if scaling up and false if scaling down
1003 * Returns true if scaling is required, false otherwise.
1005 static bool ufshcd_is_devfreq_scaling_required(struct ufs_hba *hba,
1008 struct ufs_clk_info *clki;
1009 struct list_head *head = &hba->clk_list_head;
1011 if (list_empty(head))
1014 list_for_each_entry(clki, head, list) {
1015 if (!IS_ERR_OR_NULL(clki->clk)) {
1016 if (scale_up && clki->max_freq) {
1017 if (clki->curr_freq == clki->max_freq)
1020 } else if (!scale_up && clki->min_freq) {
1021 if (clki->curr_freq == clki->min_freq)
1031 static int ufshcd_wait_for_doorbell_clr(struct ufs_hba *hba,
1032 u64 wait_timeout_us)
1034 unsigned long flags;
1038 bool timeout = false, do_last_check = false;
1041 ufshcd_hold(hba, false);
1042 spin_lock_irqsave(hba->host->host_lock, flags);
1044 * Wait for all the outstanding tasks/transfer requests.
1045 * Verify by checking the doorbell registers are clear.
1047 start = ktime_get();
1049 if (hba->ufshcd_state != UFSHCD_STATE_OPERATIONAL) {
1054 tm_doorbell = ufshcd_readl(hba, REG_UTP_TASK_REQ_DOOR_BELL);
1055 tr_doorbell = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
1056 if (!tm_doorbell && !tr_doorbell) {
1059 } else if (do_last_check) {
1063 spin_unlock_irqrestore(hba->host->host_lock, flags);
1065 if (ktime_to_us(ktime_sub(ktime_get(), start)) >
1069 * We might have scheduled out for long time so make
1070 * sure to check if doorbells are cleared by this time
1073 do_last_check = true;
1075 spin_lock_irqsave(hba->host->host_lock, flags);
1076 } while (tm_doorbell || tr_doorbell);
1080 "%s: timedout waiting for doorbell to clear (tm=0x%x, tr=0x%x)\n",
1081 __func__, tm_doorbell, tr_doorbell);
1085 spin_unlock_irqrestore(hba->host->host_lock, flags);
1086 ufshcd_release(hba);
1091 * ufshcd_scale_gear - scale up/down UFS gear
1092 * @hba: per adapter instance
1093 * @scale_up: True for scaling up gear and false for scaling down
1095 * Returns 0 for success,
1096 * Returns -EBUSY if scaling can't happen at this time
1097 * Returns non-zero for any other errors
1099 static int ufshcd_scale_gear(struct ufs_hba *hba, bool scale_up)
1101 #define UFS_MIN_GEAR_TO_SCALE_DOWN UFS_HS_G1
1103 struct ufs_pa_layer_attr new_pwr_info;
1106 memcpy(&new_pwr_info, &hba->clk_scaling.saved_pwr_info.info,
1107 sizeof(struct ufs_pa_layer_attr));
1109 memcpy(&new_pwr_info, &hba->pwr_info,
1110 sizeof(struct ufs_pa_layer_attr));
1112 if (hba->pwr_info.gear_tx > UFS_MIN_GEAR_TO_SCALE_DOWN
1113 || hba->pwr_info.gear_rx > UFS_MIN_GEAR_TO_SCALE_DOWN) {
1114 /* save the current power mode */
1115 memcpy(&hba->clk_scaling.saved_pwr_info.info,
1117 sizeof(struct ufs_pa_layer_attr));
1119 /* scale down gear */
1120 new_pwr_info.gear_tx = UFS_MIN_GEAR_TO_SCALE_DOWN;
1121 new_pwr_info.gear_rx = UFS_MIN_GEAR_TO_SCALE_DOWN;
1125 /* check if the power mode needs to be changed or not? */
1126 ret = ufshcd_change_power_mode(hba, &new_pwr_info);
1129 dev_err(hba->dev, "%s: failed err %d, old gear: (tx %d rx %d), new gear: (tx %d rx %d)",
1131 hba->pwr_info.gear_tx, hba->pwr_info.gear_rx,
1132 new_pwr_info.gear_tx, new_pwr_info.gear_rx);
1137 static int ufshcd_clock_scaling_prepare(struct ufs_hba *hba)
1139 #define DOORBELL_CLR_TOUT_US (1000 * 1000) /* 1 sec */
1142 * make sure that there are no outstanding requests when
1143 * clock scaling is in progress
1145 ufshcd_scsi_block_requests(hba);
1146 down_write(&hba->clk_scaling_lock);
1147 if (ufshcd_wait_for_doorbell_clr(hba, DOORBELL_CLR_TOUT_US)) {
1149 up_write(&hba->clk_scaling_lock);
1150 ufshcd_scsi_unblock_requests(hba);
1156 static void ufshcd_clock_scaling_unprepare(struct ufs_hba *hba)
1158 up_write(&hba->clk_scaling_lock);
1159 ufshcd_scsi_unblock_requests(hba);
1163 * ufshcd_devfreq_scale - scale up/down UFS clocks and gear
1164 * @hba: per adapter instance
1165 * @scale_up: True for scaling up and false for scalin down
1167 * Returns 0 for success,
1168 * Returns -EBUSY if scaling can't happen at this time
1169 * Returns non-zero for any other errors
1171 static int ufshcd_devfreq_scale(struct ufs_hba *hba, bool scale_up)
1175 /* let's not get into low power until clock scaling is completed */
1176 ufshcd_hold(hba, false);
1178 ret = ufshcd_clock_scaling_prepare(hba);
1182 /* scale down the gear before scaling down clocks */
1184 ret = ufshcd_scale_gear(hba, false);
1189 ret = ufshcd_scale_clks(hba, scale_up);
1192 ufshcd_scale_gear(hba, true);
1196 /* scale up the gear after scaling up clocks */
1198 ret = ufshcd_scale_gear(hba, true);
1200 ufshcd_scale_clks(hba, false);
1205 ret = ufshcd_vops_clk_scale_notify(hba, scale_up, POST_CHANGE);
1208 ufshcd_clock_scaling_unprepare(hba);
1209 ufshcd_release(hba);
1213 static void ufshcd_clk_scaling_suspend_work(struct work_struct *work)
1215 struct ufs_hba *hba = container_of(work, struct ufs_hba,
1216 clk_scaling.suspend_work);
1217 unsigned long irq_flags;
1219 spin_lock_irqsave(hba->host->host_lock, irq_flags);
1220 if (hba->clk_scaling.active_reqs || hba->clk_scaling.is_suspended) {
1221 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1224 hba->clk_scaling.is_suspended = true;
1225 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1227 __ufshcd_suspend_clkscaling(hba);
1230 static void ufshcd_clk_scaling_resume_work(struct work_struct *work)
1232 struct ufs_hba *hba = container_of(work, struct ufs_hba,
1233 clk_scaling.resume_work);
1234 unsigned long irq_flags;
1236 spin_lock_irqsave(hba->host->host_lock, irq_flags);
1237 if (!hba->clk_scaling.is_suspended) {
1238 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1241 hba->clk_scaling.is_suspended = false;
1242 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1244 devfreq_resume_device(hba->devfreq);
1247 static int ufshcd_devfreq_target(struct device *dev,
1248 unsigned long *freq, u32 flags)
1251 struct ufs_hba *hba = dev_get_drvdata(dev);
1253 bool scale_up, sched_clk_scaling_suspend_work = false;
1254 struct list_head *clk_list = &hba->clk_list_head;
1255 struct ufs_clk_info *clki;
1256 unsigned long irq_flags;
1258 if (!ufshcd_is_clkscaling_supported(hba))
1261 spin_lock_irqsave(hba->host->host_lock, irq_flags);
1262 if (ufshcd_eh_in_progress(hba)) {
1263 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1267 if (!hba->clk_scaling.active_reqs)
1268 sched_clk_scaling_suspend_work = true;
1270 if (list_empty(clk_list)) {
1271 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1275 clki = list_first_entry(&hba->clk_list_head, struct ufs_clk_info, list);
1276 scale_up = (*freq == clki->max_freq) ? true : false;
1277 if (!ufshcd_is_devfreq_scaling_required(hba, scale_up)) {
1278 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1280 goto out; /* no state change required */
1282 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1284 pm_runtime_get_noresume(hba->dev);
1285 if (!pm_runtime_active(hba->dev)) {
1286 pm_runtime_put_noidle(hba->dev);
1290 start = ktime_get();
1291 ret = ufshcd_devfreq_scale(hba, scale_up);
1292 pm_runtime_put(hba->dev);
1294 trace_ufshcd_profile_clk_scaling(dev_name(hba->dev),
1295 (scale_up ? "up" : "down"),
1296 ktime_to_us(ktime_sub(ktime_get(), start)), ret);
1299 if (sched_clk_scaling_suspend_work)
1300 queue_work(hba->clk_scaling.workq,
1301 &hba->clk_scaling.suspend_work);
1307 static int ufshcd_devfreq_get_dev_status(struct device *dev,
1308 struct devfreq_dev_status *stat)
1310 struct ufs_hba *hba = dev_get_drvdata(dev);
1311 struct ufs_clk_scaling *scaling = &hba->clk_scaling;
1312 unsigned long flags;
1314 if (!ufshcd_is_clkscaling_supported(hba))
1317 memset(stat, 0, sizeof(*stat));
1319 spin_lock_irqsave(hba->host->host_lock, flags);
1320 if (!scaling->window_start_t)
1323 if (scaling->is_busy_started)
1324 scaling->tot_busy_t += ktime_to_us(ktime_sub(ktime_get(),
1325 scaling->busy_start_t));
1327 stat->total_time = jiffies_to_usecs((long)jiffies -
1328 (long)scaling->window_start_t);
1329 stat->busy_time = scaling->tot_busy_t;
1331 scaling->window_start_t = jiffies;
1332 scaling->tot_busy_t = 0;
1334 if (hba->outstanding_reqs) {
1335 scaling->busy_start_t = ktime_get();
1336 scaling->is_busy_started = true;
1338 scaling->busy_start_t = 0;
1339 scaling->is_busy_started = false;
1341 spin_unlock_irqrestore(hba->host->host_lock, flags);
1345 static struct devfreq_dev_profile ufs_devfreq_profile = {
1347 .target = ufshcd_devfreq_target,
1348 .get_dev_status = ufshcd_devfreq_get_dev_status,
1351 static int ufshcd_devfreq_init(struct ufs_hba *hba)
1353 struct list_head *clk_list = &hba->clk_list_head;
1354 struct ufs_clk_info *clki;
1355 struct devfreq *devfreq;
1358 /* Skip devfreq if we don't have any clocks in the list */
1359 if (list_empty(clk_list))
1362 clki = list_first_entry(clk_list, struct ufs_clk_info, list);
1363 dev_pm_opp_add(hba->dev, clki->min_freq, 0);
1364 dev_pm_opp_add(hba->dev, clki->max_freq, 0);
1366 devfreq = devfreq_add_device(hba->dev,
1367 &ufs_devfreq_profile,
1368 DEVFREQ_GOV_SIMPLE_ONDEMAND,
1370 if (IS_ERR(devfreq)) {
1371 ret = PTR_ERR(devfreq);
1372 dev_err(hba->dev, "Unable to register with devfreq %d\n", ret);
1374 dev_pm_opp_remove(hba->dev, clki->min_freq);
1375 dev_pm_opp_remove(hba->dev, clki->max_freq);
1379 hba->devfreq = devfreq;
1384 static void ufshcd_devfreq_remove(struct ufs_hba *hba)
1386 struct list_head *clk_list = &hba->clk_list_head;
1387 struct ufs_clk_info *clki;
1392 devfreq_remove_device(hba->devfreq);
1393 hba->devfreq = NULL;
1395 clki = list_first_entry(clk_list, struct ufs_clk_info, list);
1396 dev_pm_opp_remove(hba->dev, clki->min_freq);
1397 dev_pm_opp_remove(hba->dev, clki->max_freq);
1400 static void __ufshcd_suspend_clkscaling(struct ufs_hba *hba)
1402 unsigned long flags;
1404 devfreq_suspend_device(hba->devfreq);
1405 spin_lock_irqsave(hba->host->host_lock, flags);
1406 hba->clk_scaling.window_start_t = 0;
1407 spin_unlock_irqrestore(hba->host->host_lock, flags);
1410 static void ufshcd_suspend_clkscaling(struct ufs_hba *hba)
1412 unsigned long flags;
1413 bool suspend = false;
1415 if (!ufshcd_is_clkscaling_supported(hba))
1418 spin_lock_irqsave(hba->host->host_lock, flags);
1419 if (!hba->clk_scaling.is_suspended) {
1421 hba->clk_scaling.is_suspended = true;
1423 spin_unlock_irqrestore(hba->host->host_lock, flags);
1426 __ufshcd_suspend_clkscaling(hba);
1429 static void ufshcd_resume_clkscaling(struct ufs_hba *hba)
1431 unsigned long flags;
1432 bool resume = false;
1434 if (!ufshcd_is_clkscaling_supported(hba))
1437 spin_lock_irqsave(hba->host->host_lock, flags);
1438 if (hba->clk_scaling.is_suspended) {
1440 hba->clk_scaling.is_suspended = false;
1442 spin_unlock_irqrestore(hba->host->host_lock, flags);
1445 devfreq_resume_device(hba->devfreq);
1448 static ssize_t ufshcd_clkscale_enable_show(struct device *dev,
1449 struct device_attribute *attr, char *buf)
1451 struct ufs_hba *hba = dev_get_drvdata(dev);
1453 return snprintf(buf, PAGE_SIZE, "%d\n", hba->clk_scaling.is_allowed);
1456 static ssize_t ufshcd_clkscale_enable_store(struct device *dev,
1457 struct device_attribute *attr, const char *buf, size_t count)
1459 struct ufs_hba *hba = dev_get_drvdata(dev);
1463 if (kstrtou32(buf, 0, &value))
1467 if (value == hba->clk_scaling.is_allowed)
1470 pm_runtime_get_sync(hba->dev);
1471 ufshcd_hold(hba, false);
1473 cancel_work_sync(&hba->clk_scaling.suspend_work);
1474 cancel_work_sync(&hba->clk_scaling.resume_work);
1476 hba->clk_scaling.is_allowed = value;
1479 ufshcd_resume_clkscaling(hba);
1481 ufshcd_suspend_clkscaling(hba);
1482 err = ufshcd_devfreq_scale(hba, true);
1484 dev_err(hba->dev, "%s: failed to scale clocks up %d\n",
1488 ufshcd_release(hba);
1489 pm_runtime_put_sync(hba->dev);
1494 static void ufshcd_clkscaling_init_sysfs(struct ufs_hba *hba)
1496 hba->clk_scaling.enable_attr.show = ufshcd_clkscale_enable_show;
1497 hba->clk_scaling.enable_attr.store = ufshcd_clkscale_enable_store;
1498 sysfs_attr_init(&hba->clk_scaling.enable_attr.attr);
1499 hba->clk_scaling.enable_attr.attr.name = "clkscale_enable";
1500 hba->clk_scaling.enable_attr.attr.mode = 0644;
1501 if (device_create_file(hba->dev, &hba->clk_scaling.enable_attr))
1502 dev_err(hba->dev, "Failed to create sysfs for clkscale_enable\n");
1505 static void ufshcd_ungate_work(struct work_struct *work)
1508 unsigned long flags;
1509 struct ufs_hba *hba = container_of(work, struct ufs_hba,
1510 clk_gating.ungate_work);
1512 cancel_delayed_work_sync(&hba->clk_gating.gate_work);
1514 spin_lock_irqsave(hba->host->host_lock, flags);
1515 if (hba->clk_gating.state == CLKS_ON) {
1516 spin_unlock_irqrestore(hba->host->host_lock, flags);
1520 spin_unlock_irqrestore(hba->host->host_lock, flags);
1521 ufshcd_setup_clocks(hba, true);
1523 /* Exit from hibern8 */
1524 if (ufshcd_can_hibern8_during_gating(hba)) {
1525 /* Prevent gating in this path */
1526 hba->clk_gating.is_suspended = true;
1527 if (ufshcd_is_link_hibern8(hba)) {
1528 ret = ufshcd_uic_hibern8_exit(hba);
1530 dev_err(hba->dev, "%s: hibern8 exit failed %d\n",
1533 ufshcd_set_link_active(hba);
1535 hba->clk_gating.is_suspended = false;
1538 ufshcd_scsi_unblock_requests(hba);
1542 * ufshcd_hold - Enable clocks that were gated earlier due to ufshcd_release.
1543 * Also, exit from hibern8 mode and set the link as active.
1544 * @hba: per adapter instance
1545 * @async: This indicates whether caller should ungate clocks asynchronously.
1547 int ufshcd_hold(struct ufs_hba *hba, bool async)
1551 unsigned long flags;
1553 if (!ufshcd_is_clkgating_allowed(hba))
1555 spin_lock_irqsave(hba->host->host_lock, flags);
1556 hba->clk_gating.active_reqs++;
1558 if (ufshcd_eh_in_progress(hba)) {
1559 spin_unlock_irqrestore(hba->host->host_lock, flags);
1564 switch (hba->clk_gating.state) {
1567 * Wait for the ungate work to complete if in progress.
1568 * Though the clocks may be in ON state, the link could
1569 * still be in hibner8 state if hibern8 is allowed
1570 * during clock gating.
1571 * Make sure we exit hibern8 state also in addition to
1574 if (ufshcd_can_hibern8_during_gating(hba) &&
1575 ufshcd_is_link_hibern8(hba)) {
1578 hba->clk_gating.active_reqs--;
1581 spin_unlock_irqrestore(hba->host->host_lock, flags);
1582 flush_result = flush_work(&hba->clk_gating.ungate_work);
1583 if (hba->clk_gating.is_suspended && !flush_result)
1585 spin_lock_irqsave(hba->host->host_lock, flags);
1590 if (cancel_delayed_work(&hba->clk_gating.gate_work)) {
1591 hba->clk_gating.state = CLKS_ON;
1592 trace_ufshcd_clk_gating(dev_name(hba->dev),
1593 hba->clk_gating.state);
1597 * If we are here, it means gating work is either done or
1598 * currently running. Hence, fall through to cancel gating
1599 * work and to enable clocks.
1602 hba->clk_gating.state = REQ_CLKS_ON;
1603 trace_ufshcd_clk_gating(dev_name(hba->dev),
1604 hba->clk_gating.state);
1605 if (queue_work(hba->clk_gating.clk_gating_workq,
1606 &hba->clk_gating.ungate_work))
1607 ufshcd_scsi_block_requests(hba);
1609 * fall through to check if we should wait for this
1610 * work to be done or not.
1615 hba->clk_gating.active_reqs--;
1619 spin_unlock_irqrestore(hba->host->host_lock, flags);
1620 flush_work(&hba->clk_gating.ungate_work);
1621 /* Make sure state is CLKS_ON before returning */
1622 spin_lock_irqsave(hba->host->host_lock, flags);
1625 dev_err(hba->dev, "%s: clk gating is in invalid state %d\n",
1626 __func__, hba->clk_gating.state);
1629 spin_unlock_irqrestore(hba->host->host_lock, flags);
1633 EXPORT_SYMBOL_GPL(ufshcd_hold);
1635 static void ufshcd_gate_work(struct work_struct *work)
1637 struct ufs_hba *hba = container_of(work, struct ufs_hba,
1638 clk_gating.gate_work.work);
1639 unsigned long flags;
1641 spin_lock_irqsave(hba->host->host_lock, flags);
1643 * In case you are here to cancel this work the gating state
1644 * would be marked as REQ_CLKS_ON. In this case save time by
1645 * skipping the gating work and exit after changing the clock
1648 if (hba->clk_gating.is_suspended ||
1649 (hba->clk_gating.state == REQ_CLKS_ON)) {
1650 hba->clk_gating.state = CLKS_ON;
1651 trace_ufshcd_clk_gating(dev_name(hba->dev),
1652 hba->clk_gating.state);
1656 if (hba->clk_gating.active_reqs
1657 || hba->ufshcd_state != UFSHCD_STATE_OPERATIONAL
1658 || hba->lrb_in_use || hba->outstanding_tasks
1659 || hba->active_uic_cmd || hba->uic_async_done)
1662 spin_unlock_irqrestore(hba->host->host_lock, flags);
1664 /* put the link into hibern8 mode before turning off clocks */
1665 if (ufshcd_can_hibern8_during_gating(hba)) {
1666 if (ufshcd_uic_hibern8_enter(hba)) {
1667 hba->clk_gating.state = CLKS_ON;
1668 trace_ufshcd_clk_gating(dev_name(hba->dev),
1669 hba->clk_gating.state);
1672 ufshcd_set_link_hibern8(hba);
1675 if (!ufshcd_is_link_active(hba))
1676 ufshcd_setup_clocks(hba, false);
1678 /* If link is active, device ref_clk can't be switched off */
1679 __ufshcd_setup_clocks(hba, false, true);
1682 * In case you are here to cancel this work the gating state
1683 * would be marked as REQ_CLKS_ON. In this case keep the state
1684 * as REQ_CLKS_ON which would anyway imply that clocks are off
1685 * and a request to turn them on is pending. By doing this way,
1686 * we keep the state machine in tact and this would ultimately
1687 * prevent from doing cancel work multiple times when there are
1688 * new requests arriving before the current cancel work is done.
1690 spin_lock_irqsave(hba->host->host_lock, flags);
1691 if (hba->clk_gating.state == REQ_CLKS_OFF) {
1692 hba->clk_gating.state = CLKS_OFF;
1693 trace_ufshcd_clk_gating(dev_name(hba->dev),
1694 hba->clk_gating.state);
1697 spin_unlock_irqrestore(hba->host->host_lock, flags);
1702 /* host lock must be held before calling this variant */
1703 static void __ufshcd_release(struct ufs_hba *hba)
1705 if (!ufshcd_is_clkgating_allowed(hba))
1708 hba->clk_gating.active_reqs--;
1710 if (hba->clk_gating.active_reqs || hba->clk_gating.is_suspended
1711 || hba->ufshcd_state != UFSHCD_STATE_OPERATIONAL
1712 || hba->lrb_in_use || hba->outstanding_tasks
1713 || hba->active_uic_cmd || hba->uic_async_done
1714 || ufshcd_eh_in_progress(hba))
1717 hba->clk_gating.state = REQ_CLKS_OFF;
1718 trace_ufshcd_clk_gating(dev_name(hba->dev), hba->clk_gating.state);
1719 queue_delayed_work(hba->clk_gating.clk_gating_workq,
1720 &hba->clk_gating.gate_work,
1721 msecs_to_jiffies(hba->clk_gating.delay_ms));
1724 void ufshcd_release(struct ufs_hba *hba)
1726 unsigned long flags;
1728 spin_lock_irqsave(hba->host->host_lock, flags);
1729 __ufshcd_release(hba);
1730 spin_unlock_irqrestore(hba->host->host_lock, flags);
1732 EXPORT_SYMBOL_GPL(ufshcd_release);
1734 static ssize_t ufshcd_clkgate_delay_show(struct device *dev,
1735 struct device_attribute *attr, char *buf)
1737 struct ufs_hba *hba = dev_get_drvdata(dev);
1739 return snprintf(buf, PAGE_SIZE, "%lu\n", hba->clk_gating.delay_ms);
1742 static ssize_t ufshcd_clkgate_delay_store(struct device *dev,
1743 struct device_attribute *attr, const char *buf, size_t count)
1745 struct ufs_hba *hba = dev_get_drvdata(dev);
1746 unsigned long flags, value;
1748 if (kstrtoul(buf, 0, &value))
1751 spin_lock_irqsave(hba->host->host_lock, flags);
1752 hba->clk_gating.delay_ms = value;
1753 spin_unlock_irqrestore(hba->host->host_lock, flags);
1757 static ssize_t ufshcd_clkgate_enable_show(struct device *dev,
1758 struct device_attribute *attr, char *buf)
1760 struct ufs_hba *hba = dev_get_drvdata(dev);
1762 return snprintf(buf, PAGE_SIZE, "%d\n", hba->clk_gating.is_enabled);
1765 static ssize_t ufshcd_clkgate_enable_store(struct device *dev,
1766 struct device_attribute *attr, const char *buf, size_t count)
1768 struct ufs_hba *hba = dev_get_drvdata(dev);
1769 unsigned long flags;
1772 if (kstrtou32(buf, 0, &value))
1776 if (value == hba->clk_gating.is_enabled)
1780 ufshcd_release(hba);
1782 spin_lock_irqsave(hba->host->host_lock, flags);
1783 hba->clk_gating.active_reqs++;
1784 spin_unlock_irqrestore(hba->host->host_lock, flags);
1787 hba->clk_gating.is_enabled = value;
1792 static void ufshcd_init_clk_scaling(struct ufs_hba *hba)
1794 char wq_name[sizeof("ufs_clkscaling_00")];
1796 if (!ufshcd_is_clkscaling_supported(hba))
1799 INIT_WORK(&hba->clk_scaling.suspend_work,
1800 ufshcd_clk_scaling_suspend_work);
1801 INIT_WORK(&hba->clk_scaling.resume_work,
1802 ufshcd_clk_scaling_resume_work);
1804 snprintf(wq_name, sizeof(wq_name), "ufs_clkscaling_%d",
1805 hba->host->host_no);
1806 hba->clk_scaling.workq = create_singlethread_workqueue(wq_name);
1808 ufshcd_clkscaling_init_sysfs(hba);
1811 static void ufshcd_exit_clk_scaling(struct ufs_hba *hba)
1813 if (!ufshcd_is_clkscaling_supported(hba))
1816 destroy_workqueue(hba->clk_scaling.workq);
1817 ufshcd_devfreq_remove(hba);
1820 static void ufshcd_init_clk_gating(struct ufs_hba *hba)
1822 char wq_name[sizeof("ufs_clk_gating_00")];
1824 if (!ufshcd_is_clkgating_allowed(hba))
1827 hba->clk_gating.delay_ms = 150;
1828 INIT_DELAYED_WORK(&hba->clk_gating.gate_work, ufshcd_gate_work);
1829 INIT_WORK(&hba->clk_gating.ungate_work, ufshcd_ungate_work);
1831 snprintf(wq_name, ARRAY_SIZE(wq_name), "ufs_clk_gating_%d",
1832 hba->host->host_no);
1833 hba->clk_gating.clk_gating_workq = alloc_ordered_workqueue(wq_name,
1836 hba->clk_gating.is_enabled = true;
1838 hba->clk_gating.delay_attr.show = ufshcd_clkgate_delay_show;
1839 hba->clk_gating.delay_attr.store = ufshcd_clkgate_delay_store;
1840 sysfs_attr_init(&hba->clk_gating.delay_attr.attr);
1841 hba->clk_gating.delay_attr.attr.name = "clkgate_delay_ms";
1842 hba->clk_gating.delay_attr.attr.mode = 0644;
1843 if (device_create_file(hba->dev, &hba->clk_gating.delay_attr))
1844 dev_err(hba->dev, "Failed to create sysfs for clkgate_delay\n");
1846 hba->clk_gating.enable_attr.show = ufshcd_clkgate_enable_show;
1847 hba->clk_gating.enable_attr.store = ufshcd_clkgate_enable_store;
1848 sysfs_attr_init(&hba->clk_gating.enable_attr.attr);
1849 hba->clk_gating.enable_attr.attr.name = "clkgate_enable";
1850 hba->clk_gating.enable_attr.attr.mode = 0644;
1851 if (device_create_file(hba->dev, &hba->clk_gating.enable_attr))
1852 dev_err(hba->dev, "Failed to create sysfs for clkgate_enable\n");
1855 static void ufshcd_exit_clk_gating(struct ufs_hba *hba)
1857 if (!ufshcd_is_clkgating_allowed(hba))
1859 device_remove_file(hba->dev, &hba->clk_gating.delay_attr);
1860 device_remove_file(hba->dev, &hba->clk_gating.enable_attr);
1861 cancel_work_sync(&hba->clk_gating.ungate_work);
1862 cancel_delayed_work_sync(&hba->clk_gating.gate_work);
1863 destroy_workqueue(hba->clk_gating.clk_gating_workq);
1866 /* Must be called with host lock acquired */
1867 static void ufshcd_clk_scaling_start_busy(struct ufs_hba *hba)
1869 bool queue_resume_work = false;
1871 if (!ufshcd_is_clkscaling_supported(hba))
1874 if (!hba->clk_scaling.active_reqs++)
1875 queue_resume_work = true;
1877 if (!hba->clk_scaling.is_allowed || hba->pm_op_in_progress)
1880 if (queue_resume_work)
1881 queue_work(hba->clk_scaling.workq,
1882 &hba->clk_scaling.resume_work);
1884 if (!hba->clk_scaling.window_start_t) {
1885 hba->clk_scaling.window_start_t = jiffies;
1886 hba->clk_scaling.tot_busy_t = 0;
1887 hba->clk_scaling.is_busy_started = false;
1890 if (!hba->clk_scaling.is_busy_started) {
1891 hba->clk_scaling.busy_start_t = ktime_get();
1892 hba->clk_scaling.is_busy_started = true;
1896 static void ufshcd_clk_scaling_update_busy(struct ufs_hba *hba)
1898 struct ufs_clk_scaling *scaling = &hba->clk_scaling;
1900 if (!ufshcd_is_clkscaling_supported(hba))
1903 if (!hba->outstanding_reqs && scaling->is_busy_started) {
1904 scaling->tot_busy_t += ktime_to_us(ktime_sub(ktime_get(),
1905 scaling->busy_start_t));
1906 scaling->busy_start_t = 0;
1907 scaling->is_busy_started = false;
1911 * ufshcd_send_command - Send SCSI or device management commands
1912 * @hba: per adapter instance
1913 * @task_tag: Task tag of the command
1916 void ufshcd_send_command(struct ufs_hba *hba, unsigned int task_tag)
1918 hba->lrb[task_tag].issue_time_stamp = ktime_get();
1919 hba->lrb[task_tag].compl_time_stamp = ktime_set(0, 0);
1920 ufshcd_add_command_trace(hba, task_tag, "send");
1921 ufshcd_clk_scaling_start_busy(hba);
1922 __set_bit(task_tag, &hba->outstanding_reqs);
1923 ufshcd_writel(hba, 1 << task_tag, REG_UTP_TRANSFER_REQ_DOOR_BELL);
1924 /* Make sure that doorbell is committed immediately */
1929 * ufshcd_copy_sense_data - Copy sense data in case of check condition
1930 * @lrbp: pointer to local reference block
1932 static inline void ufshcd_copy_sense_data(struct ufshcd_lrb *lrbp)
1935 if (lrbp->sense_buffer &&
1936 ufshcd_get_rsp_upiu_data_seg_len(lrbp->ucd_rsp_ptr)) {
1939 len = be16_to_cpu(lrbp->ucd_rsp_ptr->sr.sense_data_len);
1940 len_to_copy = min_t(int, RESPONSE_UPIU_SENSE_DATA_LENGTH, len);
1942 memcpy(lrbp->sense_buffer,
1943 lrbp->ucd_rsp_ptr->sr.sense_data,
1944 min_t(int, len_to_copy, UFSHCD_REQ_SENSE_SIZE));
1949 * ufshcd_copy_query_response() - Copy the Query Response and the data
1951 * @hba: per adapter instance
1952 * @lrbp: pointer to local reference block
1955 int ufshcd_copy_query_response(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
1957 struct ufs_query_res *query_res = &hba->dev_cmd.query.response;
1959 memcpy(&query_res->upiu_res, &lrbp->ucd_rsp_ptr->qr, QUERY_OSF_SIZE);
1961 /* Get the descriptor */
1962 if (hba->dev_cmd.query.descriptor &&
1963 lrbp->ucd_rsp_ptr->qr.opcode == UPIU_QUERY_OPCODE_READ_DESC) {
1964 u8 *descp = (u8 *)lrbp->ucd_rsp_ptr +
1965 GENERAL_UPIU_REQUEST_SIZE;
1969 /* data segment length */
1970 resp_len = be32_to_cpu(lrbp->ucd_rsp_ptr->header.dword_2) &
1971 MASK_QUERY_DATA_SEG_LEN;
1972 buf_len = be16_to_cpu(
1973 hba->dev_cmd.query.request.upiu_req.length);
1974 if (likely(buf_len >= resp_len)) {
1975 memcpy(hba->dev_cmd.query.descriptor, descp, resp_len);
1978 "%s: Response size is bigger than buffer",
1988 * ufshcd_hba_capabilities - Read controller capabilities
1989 * @hba: per adapter instance
1991 static inline void ufshcd_hba_capabilities(struct ufs_hba *hba)
1993 hba->capabilities = ufshcd_readl(hba, REG_CONTROLLER_CAPABILITIES);
1995 /* nutrs and nutmrs are 0 based values */
1996 hba->nutrs = (hba->capabilities & MASK_TRANSFER_REQUESTS_SLOTS) + 1;
1998 ((hba->capabilities & MASK_TASK_MANAGEMENT_REQUEST_SLOTS) >> 16) + 1;
2002 * ufshcd_ready_for_uic_cmd - Check if controller is ready
2003 * to accept UIC commands
2004 * @hba: per adapter instance
2005 * Return true on success, else false
2007 static inline bool ufshcd_ready_for_uic_cmd(struct ufs_hba *hba)
2009 if (ufshcd_readl(hba, REG_CONTROLLER_STATUS) & UIC_COMMAND_READY)
2016 * ufshcd_get_upmcrs - Get the power mode change request status
2017 * @hba: Pointer to adapter instance
2019 * This function gets the UPMCRS field of HCS register
2020 * Returns value of UPMCRS field
2022 static inline u8 ufshcd_get_upmcrs(struct ufs_hba *hba)
2024 return (ufshcd_readl(hba, REG_CONTROLLER_STATUS) >> 8) & 0x7;
2028 * ufshcd_dispatch_uic_cmd - Dispatch UIC commands to unipro layers
2029 * @hba: per adapter instance
2030 * @uic_cmd: UIC command
2032 * Mutex must be held.
2035 ufshcd_dispatch_uic_cmd(struct ufs_hba *hba, struct uic_command *uic_cmd)
2037 WARN_ON(hba->active_uic_cmd);
2039 hba->active_uic_cmd = uic_cmd;
2042 ufshcd_writel(hba, uic_cmd->argument1, REG_UIC_COMMAND_ARG_1);
2043 ufshcd_writel(hba, uic_cmd->argument2, REG_UIC_COMMAND_ARG_2);
2044 ufshcd_writel(hba, uic_cmd->argument3, REG_UIC_COMMAND_ARG_3);
2047 ufshcd_writel(hba, uic_cmd->command & COMMAND_OPCODE_MASK,
2052 * ufshcd_wait_for_uic_cmd - Wait complectioin of UIC command
2053 * @hba: per adapter instance
2054 * @uic_cmd: UIC command
2056 * Must be called with mutex held.
2057 * Returns 0 only if success.
2060 ufshcd_wait_for_uic_cmd(struct ufs_hba *hba, struct uic_command *uic_cmd)
2063 unsigned long flags;
2065 if (wait_for_completion_timeout(&uic_cmd->done,
2066 msecs_to_jiffies(UIC_CMD_TIMEOUT)))
2067 ret = uic_cmd->argument2 & MASK_UIC_COMMAND_RESULT;
2071 spin_lock_irqsave(hba->host->host_lock, flags);
2072 hba->active_uic_cmd = NULL;
2073 spin_unlock_irqrestore(hba->host->host_lock, flags);
2079 * __ufshcd_send_uic_cmd - Send UIC commands and retrieve the result
2080 * @hba: per adapter instance
2081 * @uic_cmd: UIC command
2082 * @completion: initialize the completion only if this is set to true
2084 * Identical to ufshcd_send_uic_cmd() expect mutex. Must be called
2085 * with mutex held and host_lock locked.
2086 * Returns 0 only if success.
2089 __ufshcd_send_uic_cmd(struct ufs_hba *hba, struct uic_command *uic_cmd,
2092 if (!ufshcd_ready_for_uic_cmd(hba)) {
2094 "Controller not ready to accept UIC commands\n");
2099 init_completion(&uic_cmd->done);
2101 ufshcd_dispatch_uic_cmd(hba, uic_cmd);
2107 * ufshcd_send_uic_cmd - Send UIC commands and retrieve the result
2108 * @hba: per adapter instance
2109 * @uic_cmd: UIC command
2111 * Returns 0 only if success.
2114 ufshcd_send_uic_cmd(struct ufs_hba *hba, struct uic_command *uic_cmd)
2117 unsigned long flags;
2119 ufshcd_hold(hba, false);
2120 mutex_lock(&hba->uic_cmd_mutex);
2121 ufshcd_add_delay_before_dme_cmd(hba);
2123 spin_lock_irqsave(hba->host->host_lock, flags);
2124 ret = __ufshcd_send_uic_cmd(hba, uic_cmd, true);
2125 spin_unlock_irqrestore(hba->host->host_lock, flags);
2127 ret = ufshcd_wait_for_uic_cmd(hba, uic_cmd);
2129 mutex_unlock(&hba->uic_cmd_mutex);
2131 ufshcd_release(hba);
2136 * ufshcd_map_sg - Map scatter-gather list to prdt
2137 * @hba: per adapter instance
2138 * @lrbp: pointer to local reference block
2140 * Returns 0 in case of success, non-zero value in case of failure
2142 static int ufshcd_map_sg(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
2144 struct ufshcd_sg_entry *prd_table;
2145 struct scatterlist *sg;
2146 struct scsi_cmnd *cmd;
2151 sg_segments = scsi_dma_map(cmd);
2152 if (sg_segments < 0)
2156 if (hba->quirks & UFSHCD_QUIRK_PRDT_BYTE_GRAN)
2157 lrbp->utr_descriptor_ptr->prd_table_length =
2158 cpu_to_le16((u16)(sg_segments *
2159 sizeof(struct ufshcd_sg_entry)));
2161 lrbp->utr_descriptor_ptr->prd_table_length =
2162 cpu_to_le16((u16) (sg_segments));
2164 prd_table = (struct ufshcd_sg_entry *)lrbp->ucd_prdt_ptr;
2166 scsi_for_each_sg(cmd, sg, sg_segments, i) {
2168 cpu_to_le32(((u32) sg_dma_len(sg))-1);
2169 prd_table[i].base_addr =
2170 cpu_to_le32(lower_32_bits(sg->dma_address));
2171 prd_table[i].upper_addr =
2172 cpu_to_le32(upper_32_bits(sg->dma_address));
2173 prd_table[i].reserved = 0;
2176 lrbp->utr_descriptor_ptr->prd_table_length = 0;
2183 * ufshcd_enable_intr - enable interrupts
2184 * @hba: per adapter instance
2185 * @intrs: interrupt bits
2187 static void ufshcd_enable_intr(struct ufs_hba *hba, u32 intrs)
2189 u32 set = ufshcd_readl(hba, REG_INTERRUPT_ENABLE);
2191 if (hba->ufs_version == UFSHCI_VERSION_10) {
2193 rw = set & INTERRUPT_MASK_RW_VER_10;
2194 set = rw | ((set ^ intrs) & intrs);
2199 ufshcd_writel(hba, set, REG_INTERRUPT_ENABLE);
2203 * ufshcd_disable_intr - disable interrupts
2204 * @hba: per adapter instance
2205 * @intrs: interrupt bits
2207 static void ufshcd_disable_intr(struct ufs_hba *hba, u32 intrs)
2209 u32 set = ufshcd_readl(hba, REG_INTERRUPT_ENABLE);
2211 if (hba->ufs_version == UFSHCI_VERSION_10) {
2213 rw = (set & INTERRUPT_MASK_RW_VER_10) &
2214 ~(intrs & INTERRUPT_MASK_RW_VER_10);
2215 set = rw | ((set & intrs) & ~INTERRUPT_MASK_RW_VER_10);
2221 ufshcd_writel(hba, set, REG_INTERRUPT_ENABLE);
2225 * ufshcd_prepare_req_desc_hdr() - Fills the requests header
2226 * descriptor according to request
2227 * @lrbp: pointer to local reference block
2228 * @upiu_flags: flags required in the header
2229 * @cmd_dir: requests data direction
2231 static void ufshcd_prepare_req_desc_hdr(struct ufshcd_lrb *lrbp,
2232 u32 *upiu_flags, enum dma_data_direction cmd_dir)
2234 struct utp_transfer_req_desc *req_desc = lrbp->utr_descriptor_ptr;
2238 if (cmd_dir == DMA_FROM_DEVICE) {
2239 data_direction = UTP_DEVICE_TO_HOST;
2240 *upiu_flags = UPIU_CMD_FLAGS_READ;
2241 } else if (cmd_dir == DMA_TO_DEVICE) {
2242 data_direction = UTP_HOST_TO_DEVICE;
2243 *upiu_flags = UPIU_CMD_FLAGS_WRITE;
2245 data_direction = UTP_NO_DATA_TRANSFER;
2246 *upiu_flags = UPIU_CMD_FLAGS_NONE;
2249 dword_0 = data_direction | (lrbp->command_type
2250 << UPIU_COMMAND_TYPE_OFFSET);
2252 dword_0 |= UTP_REQ_DESC_INT_CMD;
2254 /* Transfer request descriptor header fields */
2255 req_desc->header.dword_0 = cpu_to_le32(dword_0);
2256 /* dword_1 is reserved, hence it is set to 0 */
2257 req_desc->header.dword_1 = 0;
2259 * assigning invalid value for command status. Controller
2260 * updates OCS on command completion, with the command
2263 req_desc->header.dword_2 =
2264 cpu_to_le32(OCS_INVALID_COMMAND_STATUS);
2265 /* dword_3 is reserved, hence it is set to 0 */
2266 req_desc->header.dword_3 = 0;
2268 req_desc->prd_table_length = 0;
2272 * ufshcd_prepare_utp_scsi_cmd_upiu() - fills the utp_transfer_req_desc,
2274 * @lrbp: local reference block pointer
2275 * @upiu_flags: flags
2278 void ufshcd_prepare_utp_scsi_cmd_upiu(struct ufshcd_lrb *lrbp, u32 upiu_flags)
2280 struct utp_upiu_req *ucd_req_ptr = lrbp->ucd_req_ptr;
2281 unsigned short cdb_len;
2283 /* command descriptor fields */
2284 ucd_req_ptr->header.dword_0 = UPIU_HEADER_DWORD(
2285 UPIU_TRANSACTION_COMMAND, upiu_flags,
2286 lrbp->lun, lrbp->task_tag);
2287 ucd_req_ptr->header.dword_1 = UPIU_HEADER_DWORD(
2288 UPIU_COMMAND_SET_TYPE_SCSI, 0, 0, 0);
2290 /* Total EHS length and Data segment length will be zero */
2291 ucd_req_ptr->header.dword_2 = 0;
2293 ucd_req_ptr->sc.exp_data_transfer_len =
2294 cpu_to_be32(lrbp->cmd->sdb.length);
2296 cdb_len = min_t(unsigned short, lrbp->cmd->cmd_len, MAX_CDB_SIZE);
2297 memset(ucd_req_ptr->sc.cdb, 0, MAX_CDB_SIZE);
2298 memcpy(ucd_req_ptr->sc.cdb, lrbp->cmd->cmnd, cdb_len);
2300 memset(lrbp->ucd_rsp_ptr, 0, sizeof(struct utp_upiu_rsp));
2304 * ufshcd_prepare_utp_query_req_upiu() - fills the utp_transfer_req_desc,
2307 * @lrbp: local reference block pointer
2308 * @upiu_flags: flags
2310 static void ufshcd_prepare_utp_query_req_upiu(struct ufs_hba *hba,
2311 struct ufshcd_lrb *lrbp, u32 upiu_flags)
2313 struct utp_upiu_req *ucd_req_ptr = lrbp->ucd_req_ptr;
2314 struct ufs_query *query = &hba->dev_cmd.query;
2315 u16 len = be16_to_cpu(query->request.upiu_req.length);
2316 u8 *descp = (u8 *)lrbp->ucd_req_ptr + GENERAL_UPIU_REQUEST_SIZE;
2318 /* Query request header */
2319 ucd_req_ptr->header.dword_0 = UPIU_HEADER_DWORD(
2320 UPIU_TRANSACTION_QUERY_REQ, upiu_flags,
2321 lrbp->lun, lrbp->task_tag);
2322 ucd_req_ptr->header.dword_1 = UPIU_HEADER_DWORD(
2323 0, query->request.query_func, 0, 0);
2325 /* Data segment length only need for WRITE_DESC */
2326 if (query->request.upiu_req.opcode == UPIU_QUERY_OPCODE_WRITE_DESC)
2327 ucd_req_ptr->header.dword_2 =
2328 UPIU_HEADER_DWORD(0, 0, (len >> 8), (u8)len);
2330 ucd_req_ptr->header.dword_2 = 0;
2332 /* Copy the Query Request buffer as is */
2333 memcpy(&ucd_req_ptr->qr, &query->request.upiu_req,
2336 /* Copy the Descriptor */
2337 if (query->request.upiu_req.opcode == UPIU_QUERY_OPCODE_WRITE_DESC)
2338 memcpy(descp, query->descriptor, len);
2340 memset(lrbp->ucd_rsp_ptr, 0, sizeof(struct utp_upiu_rsp));
2343 static inline void ufshcd_prepare_utp_nop_upiu(struct ufshcd_lrb *lrbp)
2345 struct utp_upiu_req *ucd_req_ptr = lrbp->ucd_req_ptr;
2347 memset(ucd_req_ptr, 0, sizeof(struct utp_upiu_req));
2349 /* command descriptor fields */
2350 ucd_req_ptr->header.dword_0 =
2352 UPIU_TRANSACTION_NOP_OUT, 0, 0, lrbp->task_tag);
2353 /* clear rest of the fields of basic header */
2354 ucd_req_ptr->header.dword_1 = 0;
2355 ucd_req_ptr->header.dword_2 = 0;
2357 memset(lrbp->ucd_rsp_ptr, 0, sizeof(struct utp_upiu_rsp));
2361 * ufshcd_comp_devman_upiu - UFS Protocol Information Unit(UPIU)
2362 * for Device Management Purposes
2363 * @hba: per adapter instance
2364 * @lrbp: pointer to local reference block
2366 static int ufshcd_comp_devman_upiu(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
2371 if ((hba->ufs_version == UFSHCI_VERSION_10) ||
2372 (hba->ufs_version == UFSHCI_VERSION_11))
2373 lrbp->command_type = UTP_CMD_TYPE_DEV_MANAGE;
2375 lrbp->command_type = UTP_CMD_TYPE_UFS_STORAGE;
2377 ufshcd_prepare_req_desc_hdr(lrbp, &upiu_flags, DMA_NONE);
2378 if (hba->dev_cmd.type == DEV_CMD_TYPE_QUERY)
2379 ufshcd_prepare_utp_query_req_upiu(hba, lrbp, upiu_flags);
2380 else if (hba->dev_cmd.type == DEV_CMD_TYPE_NOP)
2381 ufshcd_prepare_utp_nop_upiu(lrbp);
2389 * ufshcd_comp_scsi_upiu - UFS Protocol Information Unit(UPIU)
2391 * @hba: per adapter instance
2392 * @lrbp: pointer to local reference block
2394 static int ufshcd_comp_scsi_upiu(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
2399 if ((hba->ufs_version == UFSHCI_VERSION_10) ||
2400 (hba->ufs_version == UFSHCI_VERSION_11))
2401 lrbp->command_type = UTP_CMD_TYPE_SCSI;
2403 lrbp->command_type = UTP_CMD_TYPE_UFS_STORAGE;
2405 if (likely(lrbp->cmd)) {
2406 ufshcd_prepare_req_desc_hdr(lrbp, &upiu_flags,
2407 lrbp->cmd->sc_data_direction);
2408 ufshcd_prepare_utp_scsi_cmd_upiu(lrbp, upiu_flags);
2417 * ufshcd_upiu_wlun_to_scsi_wlun - maps UPIU W-LUN id to SCSI W-LUN ID
2418 * @upiu_wlun_id: UPIU W-LUN id
2420 * Returns SCSI W-LUN id
2422 static inline u16 ufshcd_upiu_wlun_to_scsi_wlun(u8 upiu_wlun_id)
2424 return (upiu_wlun_id & ~UFS_UPIU_WLUN_ID) | SCSI_W_LUN_BASE;
2428 * ufshcd_queuecommand - main entry point for SCSI requests
2429 * @host: SCSI host pointer
2430 * @cmd: command from SCSI Midlayer
2432 * Returns 0 for success, non-zero in case of failure
2434 static int ufshcd_queuecommand(struct Scsi_Host *host, struct scsi_cmnd *cmd)
2436 struct ufshcd_lrb *lrbp;
2437 struct ufs_hba *hba;
2438 unsigned long flags;
2442 hba = shost_priv(host);
2444 tag = cmd->request->tag;
2445 if (!ufshcd_valid_tag(hba, tag)) {
2447 "%s: invalid command tag %d: cmd=0x%p, cmd->request=0x%p",
2448 __func__, tag, cmd, cmd->request);
2452 if (!down_read_trylock(&hba->clk_scaling_lock))
2453 return SCSI_MLQUEUE_HOST_BUSY;
2455 spin_lock_irqsave(hba->host->host_lock, flags);
2456 switch (hba->ufshcd_state) {
2457 case UFSHCD_STATE_OPERATIONAL:
2459 case UFSHCD_STATE_EH_SCHEDULED:
2460 case UFSHCD_STATE_RESET:
2461 err = SCSI_MLQUEUE_HOST_BUSY;
2463 case UFSHCD_STATE_ERROR:
2464 set_host_byte(cmd, DID_ERROR);
2465 cmd->scsi_done(cmd);
2468 dev_WARN_ONCE(hba->dev, 1, "%s: invalid state %d\n",
2469 __func__, hba->ufshcd_state);
2470 set_host_byte(cmd, DID_BAD_TARGET);
2471 cmd->scsi_done(cmd);
2475 /* if error handling is in progress, don't issue commands */
2476 if (ufshcd_eh_in_progress(hba)) {
2477 set_host_byte(cmd, DID_ERROR);
2478 cmd->scsi_done(cmd);
2481 spin_unlock_irqrestore(hba->host->host_lock, flags);
2483 hba->req_abort_count = 0;
2485 /* acquire the tag to make sure device cmds don't use it */
2486 if (test_and_set_bit_lock(tag, &hba->lrb_in_use)) {
2488 * Dev manage command in progress, requeue the command.
2489 * Requeuing the command helps in cases where the request *may*
2490 * find different tag instead of waiting for dev manage command
2493 err = SCSI_MLQUEUE_HOST_BUSY;
2497 err = ufshcd_hold(hba, true);
2499 err = SCSI_MLQUEUE_HOST_BUSY;
2500 clear_bit_unlock(tag, &hba->lrb_in_use);
2503 WARN_ON(hba->clk_gating.state != CLKS_ON);
2505 lrbp = &hba->lrb[tag];
2509 lrbp->sense_bufflen = UFSHCD_REQ_SENSE_SIZE;
2510 lrbp->sense_buffer = cmd->sense_buffer;
2511 lrbp->task_tag = tag;
2512 lrbp->lun = ufshcd_scsi_to_upiu_lun(cmd->device->lun);
2513 lrbp->intr_cmd = !ufshcd_is_intr_aggr_allowed(hba) ? true : false;
2514 lrbp->req_abort_skip = false;
2516 ufshcd_comp_scsi_upiu(hba, lrbp);
2518 err = ufshcd_map_sg(hba, lrbp);
2520 ufshcd_release(hba);
2522 clear_bit_unlock(tag, &hba->lrb_in_use);
2525 /* Make sure descriptors are ready before ringing the doorbell */
2528 /* issue command to the controller */
2529 spin_lock_irqsave(hba->host->host_lock, flags);
2530 ufshcd_vops_setup_xfer_req(hba, tag, (lrbp->cmd ? true : false));
2531 ufshcd_send_command(hba, tag);
2533 spin_unlock_irqrestore(hba->host->host_lock, flags);
2535 up_read(&hba->clk_scaling_lock);
2539 static int ufshcd_compose_dev_cmd(struct ufs_hba *hba,
2540 struct ufshcd_lrb *lrbp, enum dev_cmd_type cmd_type, int tag)
2543 lrbp->sense_bufflen = 0;
2544 lrbp->sense_buffer = NULL;
2545 lrbp->task_tag = tag;
2546 lrbp->lun = 0; /* device management cmd is not specific to any LUN */
2547 lrbp->intr_cmd = true; /* No interrupt aggregation */
2548 hba->dev_cmd.type = cmd_type;
2550 return ufshcd_comp_devman_upiu(hba, lrbp);
2554 ufshcd_clear_cmd(struct ufs_hba *hba, int tag)
2557 unsigned long flags;
2558 u32 mask = 1 << tag;
2560 /* clear outstanding transaction before retry */
2561 spin_lock_irqsave(hba->host->host_lock, flags);
2562 ufshcd_utrl_clear(hba, tag);
2563 spin_unlock_irqrestore(hba->host->host_lock, flags);
2566 * wait for for h/w to clear corresponding bit in door-bell.
2567 * max. wait is 1 sec.
2569 err = ufshcd_wait_for_register(hba,
2570 REG_UTP_TRANSFER_REQ_DOOR_BELL,
2571 mask, ~mask, 1000, 1000, true);
2577 ufshcd_check_query_response(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
2579 struct ufs_query_res *query_res = &hba->dev_cmd.query.response;
2581 /* Get the UPIU response */
2582 query_res->response = ufshcd_get_rsp_upiu_result(lrbp->ucd_rsp_ptr) >>
2583 UPIU_RSP_CODE_OFFSET;
2584 return query_res->response;
2588 * ufshcd_dev_cmd_completion() - handles device management command responses
2589 * @hba: per adapter instance
2590 * @lrbp: pointer to local reference block
2593 ufshcd_dev_cmd_completion(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
2598 hba->ufs_stats.last_hibern8_exit_tstamp = ktime_set(0, 0);
2599 resp = ufshcd_get_req_rsp(lrbp->ucd_rsp_ptr);
2602 case UPIU_TRANSACTION_NOP_IN:
2603 if (hba->dev_cmd.type != DEV_CMD_TYPE_NOP) {
2605 dev_err(hba->dev, "%s: unexpected response %x\n",
2609 case UPIU_TRANSACTION_QUERY_RSP:
2610 err = ufshcd_check_query_response(hba, lrbp);
2612 err = ufshcd_copy_query_response(hba, lrbp);
2614 case UPIU_TRANSACTION_REJECT_UPIU:
2615 /* TODO: handle Reject UPIU Response */
2617 dev_err(hba->dev, "%s: Reject UPIU not fully implemented\n",
2622 dev_err(hba->dev, "%s: Invalid device management cmd response: %x\n",
2630 static int ufshcd_wait_for_dev_cmd(struct ufs_hba *hba,
2631 struct ufshcd_lrb *lrbp, int max_timeout)
2634 unsigned long time_left;
2635 unsigned long flags;
2637 time_left = wait_for_completion_timeout(hba->dev_cmd.complete,
2638 msecs_to_jiffies(max_timeout));
2640 /* Make sure descriptors are ready before ringing the doorbell */
2642 spin_lock_irqsave(hba->host->host_lock, flags);
2643 hba->dev_cmd.complete = NULL;
2644 if (likely(time_left)) {
2645 err = ufshcd_get_tr_ocs(lrbp);
2647 err = ufshcd_dev_cmd_completion(hba, lrbp);
2649 spin_unlock_irqrestore(hba->host->host_lock, flags);
2653 dev_dbg(hba->dev, "%s: dev_cmd request timedout, tag %d\n",
2654 __func__, lrbp->task_tag);
2655 if (!ufshcd_clear_cmd(hba, lrbp->task_tag))
2656 /* successfully cleared the command, retry if needed */
2659 * in case of an error, after clearing the doorbell,
2660 * we also need to clear the outstanding_request
2663 ufshcd_outstanding_req_clear(hba, lrbp->task_tag);
2670 * ufshcd_get_dev_cmd_tag - Get device management command tag
2671 * @hba: per-adapter instance
2672 * @tag_out: pointer to variable with available slot value
2674 * Get a free slot and lock it until device management command
2677 * Returns false if free slot is unavailable for locking, else
2678 * return true with tag value in @tag.
2680 static bool ufshcd_get_dev_cmd_tag(struct ufs_hba *hba, int *tag_out)
2690 tmp = ~hba->lrb_in_use;
2691 tag = find_last_bit(&tmp, hba->nutrs);
2692 if (tag >= hba->nutrs)
2694 } while (test_and_set_bit_lock(tag, &hba->lrb_in_use));
2702 static inline void ufshcd_put_dev_cmd_tag(struct ufs_hba *hba, int tag)
2704 clear_bit_unlock(tag, &hba->lrb_in_use);
2708 * ufshcd_exec_dev_cmd - API for sending device management requests
2710 * @cmd_type: specifies the type (NOP, Query...)
2711 * @timeout: time in seconds
2713 * NOTE: Since there is only one available tag for device management commands,
2714 * it is expected you hold the hba->dev_cmd.lock mutex.
2716 static int ufshcd_exec_dev_cmd(struct ufs_hba *hba,
2717 enum dev_cmd_type cmd_type, int timeout)
2719 struct ufshcd_lrb *lrbp;
2722 struct completion wait;
2723 unsigned long flags;
2725 down_read(&hba->clk_scaling_lock);
2728 * Get free slot, sleep if slots are unavailable.
2729 * Even though we use wait_event() which sleeps indefinitely,
2730 * the maximum wait time is bounded by SCSI request timeout.
2732 wait_event(hba->dev_cmd.tag_wq, ufshcd_get_dev_cmd_tag(hba, &tag));
2734 init_completion(&wait);
2735 lrbp = &hba->lrb[tag];
2737 err = ufshcd_compose_dev_cmd(hba, lrbp, cmd_type, tag);
2741 hba->dev_cmd.complete = &wait;
2743 ufshcd_add_query_upiu_trace(hba, tag, "query_send");
2744 /* Make sure descriptors are ready before ringing the doorbell */
2746 spin_lock_irqsave(hba->host->host_lock, flags);
2747 ufshcd_vops_setup_xfer_req(hba, tag, (lrbp->cmd ? true : false));
2748 ufshcd_send_command(hba, tag);
2749 spin_unlock_irqrestore(hba->host->host_lock, flags);
2751 err = ufshcd_wait_for_dev_cmd(hba, lrbp, timeout);
2753 ufshcd_add_query_upiu_trace(hba, tag,
2754 err ? "query_complete_err" : "query_complete");
2757 ufshcd_put_dev_cmd_tag(hba, tag);
2758 wake_up(&hba->dev_cmd.tag_wq);
2759 up_read(&hba->clk_scaling_lock);
2764 * ufshcd_init_query() - init the query response and request parameters
2765 * @hba: per-adapter instance
2766 * @request: address of the request pointer to be initialized
2767 * @response: address of the response pointer to be initialized
2768 * @opcode: operation to perform
2769 * @idn: flag idn to access
2770 * @index: LU number to access
2771 * @selector: query/flag/descriptor further identification
2773 static inline void ufshcd_init_query(struct ufs_hba *hba,
2774 struct ufs_query_req **request, struct ufs_query_res **response,
2775 enum query_opcode opcode, u8 idn, u8 index, u8 selector)
2777 *request = &hba->dev_cmd.query.request;
2778 *response = &hba->dev_cmd.query.response;
2779 memset(*request, 0, sizeof(struct ufs_query_req));
2780 memset(*response, 0, sizeof(struct ufs_query_res));
2781 (*request)->upiu_req.opcode = opcode;
2782 (*request)->upiu_req.idn = idn;
2783 (*request)->upiu_req.index = index;
2784 (*request)->upiu_req.selector = selector;
2787 static int ufshcd_query_flag_retry(struct ufs_hba *hba,
2788 enum query_opcode opcode, enum flag_idn idn, bool *flag_res)
2793 for (retries = 0; retries < QUERY_REQ_RETRIES; retries++) {
2794 ret = ufshcd_query_flag(hba, opcode, idn, flag_res);
2797 "%s: failed with error %d, retries %d\n",
2798 __func__, ret, retries);
2805 "%s: query attribute, opcode %d, idn %d, failed with error %d after %d retires\n",
2806 __func__, opcode, idn, ret, retries);
2811 * ufshcd_query_flag() - API function for sending flag query requests
2812 * @hba: per-adapter instance
2813 * @opcode: flag query to perform
2814 * @idn: flag idn to access
2815 * @flag_res: the flag value after the query request completes
2817 * Returns 0 for success, non-zero in case of failure
2819 int ufshcd_query_flag(struct ufs_hba *hba, enum query_opcode opcode,
2820 enum flag_idn idn, bool *flag_res)
2822 struct ufs_query_req *request = NULL;
2823 struct ufs_query_res *response = NULL;
2824 int err, index = 0, selector = 0;
2825 int timeout = QUERY_REQ_TIMEOUT;
2829 ufshcd_hold(hba, false);
2830 mutex_lock(&hba->dev_cmd.lock);
2831 ufshcd_init_query(hba, &request, &response, opcode, idn, index,
2835 case UPIU_QUERY_OPCODE_SET_FLAG:
2836 case UPIU_QUERY_OPCODE_CLEAR_FLAG:
2837 case UPIU_QUERY_OPCODE_TOGGLE_FLAG:
2838 request->query_func = UPIU_QUERY_FUNC_STANDARD_WRITE_REQUEST;
2840 case UPIU_QUERY_OPCODE_READ_FLAG:
2841 request->query_func = UPIU_QUERY_FUNC_STANDARD_READ_REQUEST;
2843 /* No dummy reads */
2844 dev_err(hba->dev, "%s: Invalid argument for read request\n",
2852 "%s: Expected query flag opcode but got = %d\n",
2858 err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_QUERY, timeout);
2862 "%s: Sending flag query for idn %d failed, err = %d\n",
2863 __func__, idn, err);
2868 *flag_res = (be32_to_cpu(response->upiu_res.value) &
2869 MASK_QUERY_UPIU_FLAG_LOC) & 0x1;
2872 mutex_unlock(&hba->dev_cmd.lock);
2873 ufshcd_release(hba);
2878 * ufshcd_query_attr - API function for sending attribute requests
2879 * @hba: per-adapter instance
2880 * @opcode: attribute opcode
2881 * @idn: attribute idn to access
2882 * @index: index field
2883 * @selector: selector field
2884 * @attr_val: the attribute value after the query request completes
2886 * Returns 0 for success, non-zero in case of failure
2888 int ufshcd_query_attr(struct ufs_hba *hba, enum query_opcode opcode,
2889 enum attr_idn idn, u8 index, u8 selector, u32 *attr_val)
2891 struct ufs_query_req *request = NULL;
2892 struct ufs_query_res *response = NULL;
2897 ufshcd_hold(hba, false);
2899 dev_err(hba->dev, "%s: attribute value required for opcode 0x%x\n",
2905 mutex_lock(&hba->dev_cmd.lock);
2906 ufshcd_init_query(hba, &request, &response, opcode, idn, index,
2910 case UPIU_QUERY_OPCODE_WRITE_ATTR:
2911 request->query_func = UPIU_QUERY_FUNC_STANDARD_WRITE_REQUEST;
2912 request->upiu_req.value = cpu_to_be32(*attr_val);
2914 case UPIU_QUERY_OPCODE_READ_ATTR:
2915 request->query_func = UPIU_QUERY_FUNC_STANDARD_READ_REQUEST;
2918 dev_err(hba->dev, "%s: Expected query attr opcode but got = 0x%.2x\n",
2924 err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_QUERY, QUERY_REQ_TIMEOUT);
2927 dev_err(hba->dev, "%s: opcode 0x%.2x for idn %d failed, index %d, err = %d\n",
2928 __func__, opcode, idn, index, err);
2932 *attr_val = be32_to_cpu(response->upiu_res.value);
2935 mutex_unlock(&hba->dev_cmd.lock);
2937 ufshcd_release(hba);
2942 * ufshcd_query_attr_retry() - API function for sending query
2943 * attribute with retries
2944 * @hba: per-adapter instance
2945 * @opcode: attribute opcode
2946 * @idn: attribute idn to access
2947 * @index: index field
2948 * @selector: selector field
2949 * @attr_val: the attribute value after the query request
2952 * Returns 0 for success, non-zero in case of failure
2954 static int ufshcd_query_attr_retry(struct ufs_hba *hba,
2955 enum query_opcode opcode, enum attr_idn idn, u8 index, u8 selector,
2961 for (retries = QUERY_REQ_RETRIES; retries > 0; retries--) {
2962 ret = ufshcd_query_attr(hba, opcode, idn, index,
2963 selector, attr_val);
2965 dev_dbg(hba->dev, "%s: failed with error %d, retries %d\n",
2966 __func__, ret, retries);
2973 "%s: query attribute, idn %d, failed with error %d after %d retires\n",
2974 __func__, idn, ret, QUERY_REQ_RETRIES);
2978 static int __ufshcd_query_descriptor(struct ufs_hba *hba,
2979 enum query_opcode opcode, enum desc_idn idn, u8 index,
2980 u8 selector, u8 *desc_buf, int *buf_len)
2982 struct ufs_query_req *request = NULL;
2983 struct ufs_query_res *response = NULL;
2988 ufshcd_hold(hba, false);
2990 dev_err(hba->dev, "%s: descriptor buffer required for opcode 0x%x\n",
2996 if (*buf_len < QUERY_DESC_MIN_SIZE || *buf_len > QUERY_DESC_MAX_SIZE) {
2997 dev_err(hba->dev, "%s: descriptor buffer size (%d) is out of range\n",
2998 __func__, *buf_len);
3003 mutex_lock(&hba->dev_cmd.lock);
3004 ufshcd_init_query(hba, &request, &response, opcode, idn, index,
3006 hba->dev_cmd.query.descriptor = desc_buf;
3007 request->upiu_req.length = cpu_to_be16(*buf_len);
3010 case UPIU_QUERY_OPCODE_WRITE_DESC:
3011 request->query_func = UPIU_QUERY_FUNC_STANDARD_WRITE_REQUEST;
3013 case UPIU_QUERY_OPCODE_READ_DESC:
3014 request->query_func = UPIU_QUERY_FUNC_STANDARD_READ_REQUEST;
3018 "%s: Expected query descriptor opcode but got = 0x%.2x\n",
3024 err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_QUERY, QUERY_REQ_TIMEOUT);
3027 dev_err(hba->dev, "%s: opcode 0x%.2x for idn %d failed, index %d, err = %d\n",
3028 __func__, opcode, idn, index, err);
3032 *buf_len = be16_to_cpu(response->upiu_res.length);
3035 hba->dev_cmd.query.descriptor = NULL;
3036 mutex_unlock(&hba->dev_cmd.lock);
3038 ufshcd_release(hba);
3043 * ufshcd_query_descriptor_retry - API function for sending descriptor requests
3044 * @hba: per-adapter instance
3045 * @opcode: attribute opcode
3046 * @idn: attribute idn to access
3047 * @index: index field
3048 * @selector: selector field
3049 * @desc_buf: the buffer that contains the descriptor
3050 * @buf_len: length parameter passed to the device
3052 * Returns 0 for success, non-zero in case of failure.
3053 * The buf_len parameter will contain, on return, the length parameter
3054 * received on the response.
3056 int ufshcd_query_descriptor_retry(struct ufs_hba *hba,
3057 enum query_opcode opcode,
3058 enum desc_idn idn, u8 index,
3060 u8 *desc_buf, int *buf_len)
3065 for (retries = QUERY_REQ_RETRIES; retries > 0; retries--) {
3066 err = __ufshcd_query_descriptor(hba, opcode, idn, index,
3067 selector, desc_buf, buf_len);
3068 if (!err || err == -EINVAL)
3076 * ufshcd_read_desc_length - read the specified descriptor length from header
3077 * @hba: Pointer to adapter instance
3078 * @desc_id: descriptor idn value
3079 * @desc_index: descriptor index
3080 * @desc_length: pointer to variable to read the length of descriptor
3082 * Return 0 in case of success, non-zero otherwise
3084 static int ufshcd_read_desc_length(struct ufs_hba *hba,
3085 enum desc_idn desc_id,
3090 u8 header[QUERY_DESC_HDR_SIZE];
3091 int header_len = QUERY_DESC_HDR_SIZE;
3093 if (desc_id >= QUERY_DESC_IDN_MAX)
3096 ret = ufshcd_query_descriptor_retry(hba, UPIU_QUERY_OPCODE_READ_DESC,
3097 desc_id, desc_index, 0, header,
3101 dev_err(hba->dev, "%s: Failed to get descriptor header id %d",
3104 } else if (desc_id != header[QUERY_DESC_DESC_TYPE_OFFSET]) {
3105 dev_warn(hba->dev, "%s: descriptor header id %d and desc_id %d mismatch",
3106 __func__, header[QUERY_DESC_DESC_TYPE_OFFSET],
3111 *desc_length = header[QUERY_DESC_LENGTH_OFFSET];
3117 * ufshcd_map_desc_id_to_length - map descriptor IDN to its length
3118 * @hba: Pointer to adapter instance
3119 * @desc_id: descriptor idn value
3120 * @desc_len: mapped desc length (out)
3122 * Return 0 in case of success, non-zero otherwise
3124 int ufshcd_map_desc_id_to_length(struct ufs_hba *hba,
3125 enum desc_idn desc_id, int *desc_len)
3128 case QUERY_DESC_IDN_DEVICE:
3129 *desc_len = hba->desc_size.dev_desc;
3131 case QUERY_DESC_IDN_POWER:
3132 *desc_len = hba->desc_size.pwr_desc;
3134 case QUERY_DESC_IDN_GEOMETRY:
3135 *desc_len = hba->desc_size.geom_desc;
3137 case QUERY_DESC_IDN_CONFIGURATION:
3138 *desc_len = hba->desc_size.conf_desc;
3140 case QUERY_DESC_IDN_UNIT:
3141 *desc_len = hba->desc_size.unit_desc;
3143 case QUERY_DESC_IDN_INTERCONNECT:
3144 *desc_len = hba->desc_size.interc_desc;
3146 case QUERY_DESC_IDN_STRING:
3147 *desc_len = QUERY_DESC_MAX_SIZE;
3149 case QUERY_DESC_IDN_HEALTH:
3150 *desc_len = hba->desc_size.hlth_desc;
3152 case QUERY_DESC_IDN_RFU_0:
3153 case QUERY_DESC_IDN_RFU_1:
3162 EXPORT_SYMBOL(ufshcd_map_desc_id_to_length);
3165 * ufshcd_read_desc_param - read the specified descriptor parameter
3166 * @hba: Pointer to adapter instance
3167 * @desc_id: descriptor idn value
3168 * @desc_index: descriptor index
3169 * @param_offset: offset of the parameter to read
3170 * @param_read_buf: pointer to buffer where parameter would be read
3171 * @param_size: sizeof(param_read_buf)
3173 * Return 0 in case of success, non-zero otherwise
3175 int ufshcd_read_desc_param(struct ufs_hba *hba,
3176 enum desc_idn desc_id,
3185 bool is_kmalloc = true;
3188 if (desc_id >= QUERY_DESC_IDN_MAX || !param_size)
3191 /* Get the max length of descriptor from structure filled up at probe
3194 ret = ufshcd_map_desc_id_to_length(hba, desc_id, &buff_len);
3197 if (ret || !buff_len) {
3198 dev_err(hba->dev, "%s: Failed to get full descriptor length",
3203 /* Check whether we need temp memory */
3204 if (param_offset != 0 || param_size < buff_len) {
3205 desc_buf = kmalloc(buff_len, GFP_KERNEL);
3209 desc_buf = param_read_buf;
3213 /* Request for full descriptor */
3214 ret = ufshcd_query_descriptor_retry(hba, UPIU_QUERY_OPCODE_READ_DESC,
3215 desc_id, desc_index, 0,
3216 desc_buf, &buff_len);
3219 dev_err(hba->dev, "%s: Failed reading descriptor. desc_id %d, desc_index %d, param_offset %d, ret %d",
3220 __func__, desc_id, desc_index, param_offset, ret);
3225 if (desc_buf[QUERY_DESC_DESC_TYPE_OFFSET] != desc_id) {
3226 dev_err(hba->dev, "%s: invalid desc_id %d in descriptor header",
3227 __func__, desc_buf[QUERY_DESC_DESC_TYPE_OFFSET]);
3232 /* Check wherher we will not copy more data, than available */
3233 if (is_kmalloc && param_size > buff_len)
3234 param_size = buff_len;
3237 memcpy(param_read_buf, &desc_buf[param_offset], param_size);
3244 static inline int ufshcd_read_desc(struct ufs_hba *hba,
3245 enum desc_idn desc_id,
3250 return ufshcd_read_desc_param(hba, desc_id, desc_index, 0, buf, size);
3253 static inline int ufshcd_read_power_desc(struct ufs_hba *hba,
3257 return ufshcd_read_desc(hba, QUERY_DESC_IDN_POWER, 0, buf, size);
3260 static int ufshcd_read_device_desc(struct ufs_hba *hba, u8 *buf, u32 size)
3262 return ufshcd_read_desc(hba, QUERY_DESC_IDN_DEVICE, 0, buf, size);
3266 * ufshcd_read_string_desc - read string descriptor
3267 * @hba: pointer to adapter instance
3268 * @desc_index: descriptor index
3269 * @buf: pointer to buffer where descriptor would be read
3270 * @size: size of buf
3271 * @ascii: if true convert from unicode to ascii characters
3273 * Return 0 in case of success, non-zero otherwise
3275 int ufshcd_read_string_desc(struct ufs_hba *hba, int desc_index,
3276 u8 *buf, u32 size, bool ascii)
3280 err = ufshcd_read_desc(hba,
3281 QUERY_DESC_IDN_STRING, desc_index, buf, size);
3284 dev_err(hba->dev, "%s: reading String Desc failed after %d retries. err = %d\n",
3285 __func__, QUERY_REQ_RETRIES, err);
3296 /* remove header and divide by 2 to move from UTF16 to UTF8 */
3297 ascii_len = (desc_len - QUERY_DESC_HDR_SIZE) / 2 + 1;
3298 if (size < ascii_len + QUERY_DESC_HDR_SIZE) {
3299 dev_err(hba->dev, "%s: buffer allocated size is too small\n",
3305 buff_ascii = kmalloc(ascii_len, GFP_KERNEL);
3312 * the descriptor contains string in UTF16 format
3313 * we need to convert to utf-8 so it can be displayed
3315 utf16s_to_utf8s((wchar_t *)&buf[QUERY_DESC_HDR_SIZE],
3316 desc_len - QUERY_DESC_HDR_SIZE,
3317 UTF16_BIG_ENDIAN, buff_ascii, ascii_len);
3319 /* replace non-printable or non-ASCII characters with spaces */
3320 for (i = 0; i < ascii_len; i++)
3321 ufshcd_remove_non_printable(&buff_ascii[i]);
3323 memset(buf + QUERY_DESC_HDR_SIZE, 0,
3324 size - QUERY_DESC_HDR_SIZE);
3325 memcpy(buf + QUERY_DESC_HDR_SIZE, buff_ascii, ascii_len);
3326 buf[QUERY_DESC_LENGTH_OFFSET] = ascii_len + QUERY_DESC_HDR_SIZE;
3334 * ufshcd_read_unit_desc_param - read the specified unit descriptor parameter
3335 * @hba: Pointer to adapter instance
3337 * @param_offset: offset of the parameter to read
3338 * @param_read_buf: pointer to buffer where parameter would be read
3339 * @param_size: sizeof(param_read_buf)
3341 * Return 0 in case of success, non-zero otherwise
3343 static inline int ufshcd_read_unit_desc_param(struct ufs_hba *hba,
3345 enum unit_desc_param param_offset,
3350 * Unit descriptors are only available for general purpose LUs (LUN id
3351 * from 0 to 7) and RPMB Well known LU.
3353 if (!ufs_is_valid_unit_desc_lun(lun))
3356 return ufshcd_read_desc_param(hba, QUERY_DESC_IDN_UNIT, lun,
3357 param_offset, param_read_buf, param_size);
3361 * ufshcd_memory_alloc - allocate memory for host memory space data structures
3362 * @hba: per adapter instance
3364 * 1. Allocate DMA memory for Command Descriptor array
3365 * Each command descriptor consist of Command UPIU, Response UPIU and PRDT
3366 * 2. Allocate DMA memory for UTP Transfer Request Descriptor List (UTRDL).
3367 * 3. Allocate DMA memory for UTP Task Management Request Descriptor List
3369 * 4. Allocate memory for local reference block(lrb).
3371 * Returns 0 for success, non-zero in case of failure
3373 static int ufshcd_memory_alloc(struct ufs_hba *hba)
3375 size_t utmrdl_size, utrdl_size, ucdl_size;
3377 /* Allocate memory for UTP command descriptors */
3378 ucdl_size = (sizeof(struct utp_transfer_cmd_desc) * hba->nutrs);
3379 hba->ucdl_base_addr = dmam_alloc_coherent(hba->dev,
3381 &hba->ucdl_dma_addr,
3385 * UFSHCI requires UTP command descriptor to be 128 byte aligned.
3386 * make sure hba->ucdl_dma_addr is aligned to PAGE_SIZE
3387 * if hba->ucdl_dma_addr is aligned to PAGE_SIZE, then it will
3388 * be aligned to 128 bytes as well
3390 if (!hba->ucdl_base_addr ||
3391 WARN_ON(hba->ucdl_dma_addr & (PAGE_SIZE - 1))) {
3393 "Command Descriptor Memory allocation failed\n");
3398 * Allocate memory for UTP Transfer descriptors
3399 * UFSHCI requires 1024 byte alignment of UTRD
3401 utrdl_size = (sizeof(struct utp_transfer_req_desc) * hba->nutrs);
3402 hba->utrdl_base_addr = dmam_alloc_coherent(hba->dev,
3404 &hba->utrdl_dma_addr,
3406 if (!hba->utrdl_base_addr ||
3407 WARN_ON(hba->utrdl_dma_addr & (PAGE_SIZE - 1))) {
3409 "Transfer Descriptor Memory allocation failed\n");
3414 * Allocate memory for UTP Task Management descriptors
3415 * UFSHCI requires 1024 byte alignment of UTMRD
3417 utmrdl_size = sizeof(struct utp_task_req_desc) * hba->nutmrs;
3418 hba->utmrdl_base_addr = dmam_alloc_coherent(hba->dev,
3420 &hba->utmrdl_dma_addr,
3422 if (!hba->utmrdl_base_addr ||
3423 WARN_ON(hba->utmrdl_dma_addr & (PAGE_SIZE - 1))) {
3425 "Task Management Descriptor Memory allocation failed\n");
3429 /* Allocate memory for local reference block */
3430 hba->lrb = devm_kcalloc(hba->dev,
3431 hba->nutrs, sizeof(struct ufshcd_lrb),
3434 dev_err(hba->dev, "LRB Memory allocation failed\n");
3443 * ufshcd_host_memory_configure - configure local reference block with
3445 * @hba: per adapter instance
3447 * Configure Host memory space
3448 * 1. Update Corresponding UTRD.UCDBA and UTRD.UCDBAU with UCD DMA
3450 * 2. Update each UTRD with Response UPIU offset, Response UPIU length
3452 * 3. Save the corresponding addresses of UTRD, UCD.CMD, UCD.RSP and UCD.PRDT
3453 * into local reference block.
3455 static void ufshcd_host_memory_configure(struct ufs_hba *hba)
3457 struct utp_transfer_cmd_desc *cmd_descp;
3458 struct utp_transfer_req_desc *utrdlp;
3459 dma_addr_t cmd_desc_dma_addr;
3460 dma_addr_t cmd_desc_element_addr;
3461 u16 response_offset;
3466 utrdlp = hba->utrdl_base_addr;
3467 cmd_descp = hba->ucdl_base_addr;
3470 offsetof(struct utp_transfer_cmd_desc, response_upiu);
3472 offsetof(struct utp_transfer_cmd_desc, prd_table);
3474 cmd_desc_size = sizeof(struct utp_transfer_cmd_desc);
3475 cmd_desc_dma_addr = hba->ucdl_dma_addr;
3477 for (i = 0; i < hba->nutrs; i++) {
3478 /* Configure UTRD with command descriptor base address */
3479 cmd_desc_element_addr =
3480 (cmd_desc_dma_addr + (cmd_desc_size * i));
3481 utrdlp[i].command_desc_base_addr_lo =
3482 cpu_to_le32(lower_32_bits(cmd_desc_element_addr));
3483 utrdlp[i].command_desc_base_addr_hi =
3484 cpu_to_le32(upper_32_bits(cmd_desc_element_addr));
3486 /* Response upiu and prdt offset should be in double words */
3487 if (hba->quirks & UFSHCD_QUIRK_PRDT_BYTE_GRAN) {
3488 utrdlp[i].response_upiu_offset =
3489 cpu_to_le16(response_offset);
3490 utrdlp[i].prd_table_offset =
3491 cpu_to_le16(prdt_offset);
3492 utrdlp[i].response_upiu_length =
3493 cpu_to_le16(ALIGNED_UPIU_SIZE);
3495 utrdlp[i].response_upiu_offset =
3496 cpu_to_le16((response_offset >> 2));
3497 utrdlp[i].prd_table_offset =
3498 cpu_to_le16((prdt_offset >> 2));
3499 utrdlp[i].response_upiu_length =
3500 cpu_to_le16(ALIGNED_UPIU_SIZE >> 2);
3503 hba->lrb[i].utr_descriptor_ptr = (utrdlp + i);
3504 hba->lrb[i].utrd_dma_addr = hba->utrdl_dma_addr +
3505 (i * sizeof(struct utp_transfer_req_desc));
3506 hba->lrb[i].ucd_req_ptr =
3507 (struct utp_upiu_req *)(cmd_descp + i);
3508 hba->lrb[i].ucd_req_dma_addr = cmd_desc_element_addr;
3509 hba->lrb[i].ucd_rsp_ptr =
3510 (struct utp_upiu_rsp *)cmd_descp[i].response_upiu;
3511 hba->lrb[i].ucd_rsp_dma_addr = cmd_desc_element_addr +
3513 hba->lrb[i].ucd_prdt_ptr =
3514 (struct ufshcd_sg_entry *)cmd_descp[i].prd_table;
3515 hba->lrb[i].ucd_prdt_dma_addr = cmd_desc_element_addr +
3521 * ufshcd_dme_link_startup - Notify Unipro to perform link startup
3522 * @hba: per adapter instance
3524 * UIC_CMD_DME_LINK_STARTUP command must be issued to Unipro layer,
3525 * in order to initialize the Unipro link startup procedure.
3526 * Once the Unipro links are up, the device connected to the controller
3529 * Returns 0 on success, non-zero value on failure
3531 static int ufshcd_dme_link_startup(struct ufs_hba *hba)
3533 struct uic_command uic_cmd = {0};
3536 uic_cmd.command = UIC_CMD_DME_LINK_STARTUP;
3538 ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
3541 "dme-link-startup: error code %d\n", ret);
3545 * ufshcd_dme_reset - UIC command for DME_RESET
3546 * @hba: per adapter instance
3548 * DME_RESET command is issued in order to reset UniPro stack.
3549 * This function now deal with cold reset.
3551 * Returns 0 on success, non-zero value on failure
3553 static int ufshcd_dme_reset(struct ufs_hba *hba)
3555 struct uic_command uic_cmd = {0};
3558 uic_cmd.command = UIC_CMD_DME_RESET;
3560 ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
3563 "dme-reset: error code %d\n", ret);
3569 * ufshcd_dme_enable - UIC command for DME_ENABLE
3570 * @hba: per adapter instance
3572 * DME_ENABLE command is issued in order to enable UniPro stack.
3574 * Returns 0 on success, non-zero value on failure
3576 static int ufshcd_dme_enable(struct ufs_hba *hba)
3578 struct uic_command uic_cmd = {0};
3581 uic_cmd.command = UIC_CMD_DME_ENABLE;
3583 ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
3586 "dme-enable: error code %d\n", ret);
3591 static inline void ufshcd_add_delay_before_dme_cmd(struct ufs_hba *hba)
3593 #define MIN_DELAY_BEFORE_DME_CMDS_US 1000
3594 unsigned long min_sleep_time_us;
3596 if (!(hba->quirks & UFSHCD_QUIRK_DELAY_BEFORE_DME_CMDS))
3600 * last_dme_cmd_tstamp will be 0 only for 1st call to
3603 if (unlikely(!ktime_to_us(hba->last_dme_cmd_tstamp))) {
3604 min_sleep_time_us = MIN_DELAY_BEFORE_DME_CMDS_US;
3606 unsigned long delta =
3607 (unsigned long) ktime_to_us(
3608 ktime_sub(ktime_get(),
3609 hba->last_dme_cmd_tstamp));
3611 if (delta < MIN_DELAY_BEFORE_DME_CMDS_US)
3613 MIN_DELAY_BEFORE_DME_CMDS_US - delta;
3615 return; /* no more delay required */
3618 /* allow sleep for extra 50us if needed */
3619 usleep_range(min_sleep_time_us, min_sleep_time_us + 50);
3623 * ufshcd_dme_set_attr - UIC command for DME_SET, DME_PEER_SET
3624 * @hba: per adapter instance
3625 * @attr_sel: uic command argument1
3626 * @attr_set: attribute set type as uic command argument2
3627 * @mib_val: setting value as uic command argument3
3628 * @peer: indicate whether peer or local
3630 * Returns 0 on success, non-zero value on failure
3632 int ufshcd_dme_set_attr(struct ufs_hba *hba, u32 attr_sel,
3633 u8 attr_set, u32 mib_val, u8 peer)
3635 struct uic_command uic_cmd = {0};
3636 static const char *const action[] = {
3640 const char *set = action[!!peer];
3642 int retries = UFS_UIC_COMMAND_RETRIES;
3644 uic_cmd.command = peer ?
3645 UIC_CMD_DME_PEER_SET : UIC_CMD_DME_SET;
3646 uic_cmd.argument1 = attr_sel;
3647 uic_cmd.argument2 = UIC_ARG_ATTR_TYPE(attr_set);
3648 uic_cmd.argument3 = mib_val;
3651 /* for peer attributes we retry upon failure */
3652 ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
3654 dev_dbg(hba->dev, "%s: attr-id 0x%x val 0x%x error code %d\n",
3655 set, UIC_GET_ATTR_ID(attr_sel), mib_val, ret);
3656 } while (ret && peer && --retries);
3659 dev_err(hba->dev, "%s: attr-id 0x%x val 0x%x failed %d retries\n",
3660 set, UIC_GET_ATTR_ID(attr_sel), mib_val,
3661 UFS_UIC_COMMAND_RETRIES - retries);
3665 EXPORT_SYMBOL_GPL(ufshcd_dme_set_attr);
3668 * ufshcd_dme_get_attr - UIC command for DME_GET, DME_PEER_GET
3669 * @hba: per adapter instance
3670 * @attr_sel: uic command argument1
3671 * @mib_val: the value of the attribute as returned by the UIC command
3672 * @peer: indicate whether peer or local
3674 * Returns 0 on success, non-zero value on failure
3676 int ufshcd_dme_get_attr(struct ufs_hba *hba, u32 attr_sel,
3677 u32 *mib_val, u8 peer)
3679 struct uic_command uic_cmd = {0};
3680 static const char *const action[] = {
3684 const char *get = action[!!peer];
3686 int retries = UFS_UIC_COMMAND_RETRIES;
3687 struct ufs_pa_layer_attr orig_pwr_info;
3688 struct ufs_pa_layer_attr temp_pwr_info;
3689 bool pwr_mode_change = false;
3691 if (peer && (hba->quirks & UFSHCD_QUIRK_DME_PEER_ACCESS_AUTO_MODE)) {
3692 orig_pwr_info = hba->pwr_info;
3693 temp_pwr_info = orig_pwr_info;
3695 if (orig_pwr_info.pwr_tx == FAST_MODE ||
3696 orig_pwr_info.pwr_rx == FAST_MODE) {
3697 temp_pwr_info.pwr_tx = FASTAUTO_MODE;
3698 temp_pwr_info.pwr_rx = FASTAUTO_MODE;
3699 pwr_mode_change = true;
3700 } else if (orig_pwr_info.pwr_tx == SLOW_MODE ||
3701 orig_pwr_info.pwr_rx == SLOW_MODE) {
3702 temp_pwr_info.pwr_tx = SLOWAUTO_MODE;
3703 temp_pwr_info.pwr_rx = SLOWAUTO_MODE;
3704 pwr_mode_change = true;
3706 if (pwr_mode_change) {
3707 ret = ufshcd_change_power_mode(hba, &temp_pwr_info);
3713 uic_cmd.command = peer ?
3714 UIC_CMD_DME_PEER_GET : UIC_CMD_DME_GET;
3715 uic_cmd.argument1 = attr_sel;
3718 /* for peer attributes we retry upon failure */
3719 ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
3721 dev_dbg(hba->dev, "%s: attr-id 0x%x error code %d\n",
3722 get, UIC_GET_ATTR_ID(attr_sel), ret);
3723 } while (ret && peer && --retries);
3726 dev_err(hba->dev, "%s: attr-id 0x%x failed %d retries\n",
3727 get, UIC_GET_ATTR_ID(attr_sel),
3728 UFS_UIC_COMMAND_RETRIES - retries);
3730 if (mib_val && !ret)
3731 *mib_val = uic_cmd.argument3;
3733 if (peer && (hba->quirks & UFSHCD_QUIRK_DME_PEER_ACCESS_AUTO_MODE)
3735 ufshcd_change_power_mode(hba, &orig_pwr_info);
3739 EXPORT_SYMBOL_GPL(ufshcd_dme_get_attr);
3742 * ufshcd_uic_pwr_ctrl - executes UIC commands (which affects the link power
3743 * state) and waits for it to take effect.
3745 * @hba: per adapter instance
3746 * @cmd: UIC command to execute
3748 * DME operations like DME_SET(PA_PWRMODE), DME_HIBERNATE_ENTER &
3749 * DME_HIBERNATE_EXIT commands take some time to take its effect on both host
3750 * and device UniPro link and hence it's final completion would be indicated by
3751 * dedicated status bits in Interrupt Status register (UPMS, UHES, UHXS) in
3752 * addition to normal UIC command completion Status (UCCS). This function only
3753 * returns after the relevant status bits indicate the completion.
3755 * Returns 0 on success, non-zero value on failure
3757 static int ufshcd_uic_pwr_ctrl(struct ufs_hba *hba, struct uic_command *cmd)
3759 struct completion uic_async_done;
3760 unsigned long flags;
3763 bool reenable_intr = false;
3765 mutex_lock(&hba->uic_cmd_mutex);
3766 init_completion(&uic_async_done);
3767 ufshcd_add_delay_before_dme_cmd(hba);
3769 spin_lock_irqsave(hba->host->host_lock, flags);
3770 hba->uic_async_done = &uic_async_done;
3771 if (ufshcd_readl(hba, REG_INTERRUPT_ENABLE) & UIC_COMMAND_COMPL) {
3772 ufshcd_disable_intr(hba, UIC_COMMAND_COMPL);
3774 * Make sure UIC command completion interrupt is disabled before
3775 * issuing UIC command.
3778 reenable_intr = true;
3780 ret = __ufshcd_send_uic_cmd(hba, cmd, false);
3781 spin_unlock_irqrestore(hba->host->host_lock, flags);
3784 "pwr ctrl cmd 0x%x with mode 0x%x uic error %d\n",
3785 cmd->command, cmd->argument3, ret);
3789 if (!wait_for_completion_timeout(hba->uic_async_done,
3790 msecs_to_jiffies(UIC_CMD_TIMEOUT))) {
3792 "pwr ctrl cmd 0x%x with mode 0x%x completion timeout\n",
3793 cmd->command, cmd->argument3);
3798 status = ufshcd_get_upmcrs(hba);
3799 if (status != PWR_LOCAL) {
3801 "pwr ctrl cmd 0x%x failed, host upmcrs:0x%x\n",
3802 cmd->command, status);
3803 ret = (status != PWR_OK) ? status : -1;
3807 ufshcd_print_host_state(hba);
3808 ufshcd_print_pwr_info(hba);
3809 ufshcd_print_host_regs(hba);
3812 spin_lock_irqsave(hba->host->host_lock, flags);
3813 hba->active_uic_cmd = NULL;
3814 hba->uic_async_done = NULL;
3816 ufshcd_enable_intr(hba, UIC_COMMAND_COMPL);
3817 spin_unlock_irqrestore(hba->host->host_lock, flags);
3818 mutex_unlock(&hba->uic_cmd_mutex);
3824 * ufshcd_uic_change_pwr_mode - Perform the UIC power mode chage
3825 * using DME_SET primitives.
3826 * @hba: per adapter instance
3827 * @mode: powr mode value
3829 * Returns 0 on success, non-zero value on failure
3831 static int ufshcd_uic_change_pwr_mode(struct ufs_hba *hba, u8 mode)
3833 struct uic_command uic_cmd = {0};
3836 if (hba->quirks & UFSHCD_QUIRK_BROKEN_PA_RXHSUNTERMCAP) {
3837 ret = ufshcd_dme_set(hba,
3838 UIC_ARG_MIB_SEL(PA_RXHSUNTERMCAP, 0), 1);
3840 dev_err(hba->dev, "%s: failed to enable PA_RXHSUNTERMCAP ret %d\n",
3846 uic_cmd.command = UIC_CMD_DME_SET;
3847 uic_cmd.argument1 = UIC_ARG_MIB(PA_PWRMODE);
3848 uic_cmd.argument3 = mode;
3849 ufshcd_hold(hba, false);
3850 ret = ufshcd_uic_pwr_ctrl(hba, &uic_cmd);
3851 ufshcd_release(hba);
3857 static int ufshcd_link_recovery(struct ufs_hba *hba)
3860 unsigned long flags;
3862 spin_lock_irqsave(hba->host->host_lock, flags);
3863 hba->ufshcd_state = UFSHCD_STATE_RESET;
3864 ufshcd_set_eh_in_progress(hba);
3865 spin_unlock_irqrestore(hba->host->host_lock, flags);
3867 ret = ufshcd_host_reset_and_restore(hba);
3869 spin_lock_irqsave(hba->host->host_lock, flags);
3871 hba->ufshcd_state = UFSHCD_STATE_ERROR;
3872 ufshcd_clear_eh_in_progress(hba);
3873 spin_unlock_irqrestore(hba->host->host_lock, flags);
3876 dev_err(hba->dev, "%s: link recovery failed, err %d",
3882 static int __ufshcd_uic_hibern8_enter(struct ufs_hba *hba)
3885 struct uic_command uic_cmd = {0};
3886 ktime_t start = ktime_get();
3888 ufshcd_vops_hibern8_notify(hba, UIC_CMD_DME_HIBER_ENTER, PRE_CHANGE);
3890 uic_cmd.command = UIC_CMD_DME_HIBER_ENTER;
3891 ret = ufshcd_uic_pwr_ctrl(hba, &uic_cmd);
3892 trace_ufshcd_profile_hibern8(dev_name(hba->dev), "enter",
3893 ktime_to_us(ktime_sub(ktime_get(), start)), ret);
3898 dev_err(hba->dev, "%s: hibern8 enter failed. ret = %d\n",
3902 * If link recovery fails then return error code returned from
3903 * ufshcd_link_recovery().
3904 * If link recovery succeeds then return -EAGAIN to attempt
3905 * hibern8 enter retry again.
3907 err = ufshcd_link_recovery(hba);
3909 dev_err(hba->dev, "%s: link recovery failed", __func__);
3915 ufshcd_vops_hibern8_notify(hba, UIC_CMD_DME_HIBER_ENTER,
3921 static int ufshcd_uic_hibern8_enter(struct ufs_hba *hba)
3923 int ret = 0, retries;
3925 for (retries = UIC_HIBERN8_ENTER_RETRIES; retries > 0; retries--) {
3926 ret = __ufshcd_uic_hibern8_enter(hba);
3934 static int ufshcd_uic_hibern8_exit(struct ufs_hba *hba)
3936 struct uic_command uic_cmd = {0};
3938 ktime_t start = ktime_get();
3940 ufshcd_vops_hibern8_notify(hba, UIC_CMD_DME_HIBER_EXIT, PRE_CHANGE);
3942 uic_cmd.command = UIC_CMD_DME_HIBER_EXIT;
3943 ret = ufshcd_uic_pwr_ctrl(hba, &uic_cmd);
3944 trace_ufshcd_profile_hibern8(dev_name(hba->dev), "exit",
3945 ktime_to_us(ktime_sub(ktime_get(), start)), ret);
3948 dev_err(hba->dev, "%s: hibern8 exit failed. ret = %d\n",
3950 ret = ufshcd_link_recovery(hba);
3952 ufshcd_vops_hibern8_notify(hba, UIC_CMD_DME_HIBER_EXIT,
3954 hba->ufs_stats.last_hibern8_exit_tstamp = ktime_get();
3955 hba->ufs_stats.hibern8_exit_cnt++;
3961 static void ufshcd_auto_hibern8_enable(struct ufs_hba *hba)
3963 unsigned long flags;
3965 if (!(hba->capabilities & MASK_AUTO_HIBERN8_SUPPORT) || !hba->ahit)
3968 spin_lock_irqsave(hba->host->host_lock, flags);
3969 ufshcd_writel(hba, hba->ahit, REG_AUTO_HIBERNATE_IDLE_TIMER);
3970 spin_unlock_irqrestore(hba->host->host_lock, flags);
3974 * ufshcd_init_pwr_info - setting the POR (power on reset)
3975 * values in hba power info
3976 * @hba: per-adapter instance
3978 static void ufshcd_init_pwr_info(struct ufs_hba *hba)
3980 hba->pwr_info.gear_rx = UFS_PWM_G1;
3981 hba->pwr_info.gear_tx = UFS_PWM_G1;
3982 hba->pwr_info.lane_rx = 1;
3983 hba->pwr_info.lane_tx = 1;
3984 hba->pwr_info.pwr_rx = SLOWAUTO_MODE;
3985 hba->pwr_info.pwr_tx = SLOWAUTO_MODE;
3986 hba->pwr_info.hs_rate = 0;
3990 * ufshcd_get_max_pwr_mode - reads the max power mode negotiated with device
3991 * @hba: per-adapter instance
3993 static int ufshcd_get_max_pwr_mode(struct ufs_hba *hba)
3995 struct ufs_pa_layer_attr *pwr_info = &hba->max_pwr_info.info;
3997 if (hba->max_pwr_info.is_valid)
4000 pwr_info->pwr_tx = FAST_MODE;
4001 pwr_info->pwr_rx = FAST_MODE;
4002 pwr_info->hs_rate = PA_HS_MODE_B;
4004 /* Get the connected lane count */
4005 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_CONNECTEDRXDATALANES),
4006 &pwr_info->lane_rx);
4007 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_CONNECTEDTXDATALANES),
4008 &pwr_info->lane_tx);
4010 if (!pwr_info->lane_rx || !pwr_info->lane_tx) {
4011 dev_err(hba->dev, "%s: invalid connected lanes value. rx=%d, tx=%d\n",
4019 * First, get the maximum gears of HS speed.
4020 * If a zero value, it means there is no HSGEAR capability.
4021 * Then, get the maximum gears of PWM speed.
4023 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_MAXRXHSGEAR), &pwr_info->gear_rx);
4024 if (!pwr_info->gear_rx) {
4025 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_MAXRXPWMGEAR),
4026 &pwr_info->gear_rx);
4027 if (!pwr_info->gear_rx) {
4028 dev_err(hba->dev, "%s: invalid max pwm rx gear read = %d\n",
4029 __func__, pwr_info->gear_rx);
4032 pwr_info->pwr_rx = SLOW_MODE;
4035 ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_MAXRXHSGEAR),
4036 &pwr_info->gear_tx);
4037 if (!pwr_info->gear_tx) {
4038 ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_MAXRXPWMGEAR),
4039 &pwr_info->gear_tx);
4040 if (!pwr_info->gear_tx) {
4041 dev_err(hba->dev, "%s: invalid max pwm tx gear read = %d\n",
4042 __func__, pwr_info->gear_tx);
4045 pwr_info->pwr_tx = SLOW_MODE;
4048 hba->max_pwr_info.is_valid = true;
4052 static int ufshcd_change_power_mode(struct ufs_hba *hba,
4053 struct ufs_pa_layer_attr *pwr_mode)
4057 /* if already configured to the requested pwr_mode */
4058 if (pwr_mode->gear_rx == hba->pwr_info.gear_rx &&
4059 pwr_mode->gear_tx == hba->pwr_info.gear_tx &&
4060 pwr_mode->lane_rx == hba->pwr_info.lane_rx &&
4061 pwr_mode->lane_tx == hba->pwr_info.lane_tx &&
4062 pwr_mode->pwr_rx == hba->pwr_info.pwr_rx &&
4063 pwr_mode->pwr_tx == hba->pwr_info.pwr_tx &&
4064 pwr_mode->hs_rate == hba->pwr_info.hs_rate) {
4065 dev_dbg(hba->dev, "%s: power already configured\n", __func__);
4070 * Configure attributes for power mode change with below.
4071 * - PA_RXGEAR, PA_ACTIVERXDATALANES, PA_RXTERMINATION,
4072 * - PA_TXGEAR, PA_ACTIVETXDATALANES, PA_TXTERMINATION,
4075 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_RXGEAR), pwr_mode->gear_rx);
4076 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_ACTIVERXDATALANES),
4078 if (pwr_mode->pwr_rx == FASTAUTO_MODE ||
4079 pwr_mode->pwr_rx == FAST_MODE)
4080 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_RXTERMINATION), TRUE);
4082 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_RXTERMINATION), FALSE);
4084 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TXGEAR), pwr_mode->gear_tx);
4085 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_ACTIVETXDATALANES),
4087 if (pwr_mode->pwr_tx == FASTAUTO_MODE ||
4088 pwr_mode->pwr_tx == FAST_MODE)
4089 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TXTERMINATION), TRUE);
4091 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TXTERMINATION), FALSE);
4093 if (pwr_mode->pwr_rx == FASTAUTO_MODE ||
4094 pwr_mode->pwr_tx == FASTAUTO_MODE ||
4095 pwr_mode->pwr_rx == FAST_MODE ||
4096 pwr_mode->pwr_tx == FAST_MODE)
4097 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_HSSERIES),
4100 ret = ufshcd_uic_change_pwr_mode(hba, pwr_mode->pwr_rx << 4
4101 | pwr_mode->pwr_tx);
4105 "%s: power mode change failed %d\n", __func__, ret);
4107 ufshcd_vops_pwr_change_notify(hba, POST_CHANGE, NULL,
4110 memcpy(&hba->pwr_info, pwr_mode,
4111 sizeof(struct ufs_pa_layer_attr));
4118 * ufshcd_config_pwr_mode - configure a new power mode
4119 * @hba: per-adapter instance
4120 * @desired_pwr_mode: desired power configuration
4122 int ufshcd_config_pwr_mode(struct ufs_hba *hba,
4123 struct ufs_pa_layer_attr *desired_pwr_mode)
4125 struct ufs_pa_layer_attr final_params = { 0 };
4128 ret = ufshcd_vops_pwr_change_notify(hba, PRE_CHANGE,
4129 desired_pwr_mode, &final_params);
4132 memcpy(&final_params, desired_pwr_mode, sizeof(final_params));
4134 ret = ufshcd_change_power_mode(hba, &final_params);
4136 ufshcd_print_pwr_info(hba);
4140 EXPORT_SYMBOL_GPL(ufshcd_config_pwr_mode);
4143 * ufshcd_complete_dev_init() - checks device readiness
4144 * @hba: per-adapter instance
4146 * Set fDeviceInit flag and poll until device toggles it.
4148 static int ufshcd_complete_dev_init(struct ufs_hba *hba)
4154 err = ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_SET_FLAG,
4155 QUERY_FLAG_IDN_FDEVICEINIT, NULL);
4158 "%s setting fDeviceInit flag failed with error %d\n",
4163 /* poll for max. 1000 iterations for fDeviceInit flag to clear */
4164 for (i = 0; i < 1000 && !err && flag_res; i++)
4165 err = ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_READ_FLAG,
4166 QUERY_FLAG_IDN_FDEVICEINIT, &flag_res);
4170 "%s reading fDeviceInit flag failed with error %d\n",
4174 "%s fDeviceInit was not cleared by the device\n",
4182 * ufshcd_make_hba_operational - Make UFS controller operational
4183 * @hba: per adapter instance
4185 * To bring UFS host controller to operational state,
4186 * 1. Enable required interrupts
4187 * 2. Configure interrupt aggregation
4188 * 3. Program UTRL and UTMRL base address
4189 * 4. Configure run-stop-registers
4191 * Returns 0 on success, non-zero value on failure
4193 static int ufshcd_make_hba_operational(struct ufs_hba *hba)
4198 /* Enable required interrupts */
4199 ufshcd_enable_intr(hba, UFSHCD_ENABLE_INTRS);
4201 /* Configure interrupt aggregation */
4202 if (ufshcd_is_intr_aggr_allowed(hba))
4203 ufshcd_config_intr_aggr(hba, hba->nutrs - 1, INT_AGGR_DEF_TO);
4205 ufshcd_disable_intr_aggr(hba);
4207 /* Configure UTRL and UTMRL base address registers */
4208 ufshcd_writel(hba, lower_32_bits(hba->utrdl_dma_addr),
4209 REG_UTP_TRANSFER_REQ_LIST_BASE_L);
4210 ufshcd_writel(hba, upper_32_bits(hba->utrdl_dma_addr),
4211 REG_UTP_TRANSFER_REQ_LIST_BASE_H);
4212 ufshcd_writel(hba, lower_32_bits(hba->utmrdl_dma_addr),
4213 REG_UTP_TASK_REQ_LIST_BASE_L);
4214 ufshcd_writel(hba, upper_32_bits(hba->utmrdl_dma_addr),
4215 REG_UTP_TASK_REQ_LIST_BASE_H);
4218 * Make sure base address and interrupt setup are updated before
4219 * enabling the run/stop registers below.
4224 * UCRDY, UTMRLDY and UTRLRDY bits must be 1
4226 reg = ufshcd_readl(hba, REG_CONTROLLER_STATUS);
4227 if (!(ufshcd_get_lists_status(reg))) {
4228 ufshcd_enable_run_stop_reg(hba);
4231 "Host controller not ready to process requests");
4241 * ufshcd_hba_stop - Send controller to reset state
4242 * @hba: per adapter instance
4243 * @can_sleep: perform sleep or just spin
4245 static inline void ufshcd_hba_stop(struct ufs_hba *hba, bool can_sleep)
4249 ufshcd_writel(hba, CONTROLLER_DISABLE, REG_CONTROLLER_ENABLE);
4250 err = ufshcd_wait_for_register(hba, REG_CONTROLLER_ENABLE,
4251 CONTROLLER_ENABLE, CONTROLLER_DISABLE,
4254 dev_err(hba->dev, "%s: Controller disable failed\n", __func__);
4258 * ufshcd_hba_execute_hce - initialize the controller
4259 * @hba: per adapter instance
4261 * The controller resets itself and controller firmware initialization
4262 * sequence kicks off. When controller is ready it will set
4263 * the Host Controller Enable bit to 1.
4265 * Returns 0 on success, non-zero value on failure
4267 static int ufshcd_hba_execute_hce(struct ufs_hba *hba)
4272 * msleep of 1 and 5 used in this function might result in msleep(20),
4273 * but it was necessary to send the UFS FPGA to reset mode during
4274 * development and testing of this driver. msleep can be changed to
4275 * mdelay and retry count can be reduced based on the controller.
4277 if (!ufshcd_is_hba_active(hba))
4278 /* change controller state to "reset state" */
4279 ufshcd_hba_stop(hba, true);
4281 /* UniPro link is disabled at this point */
4282 ufshcd_set_link_off(hba);
4284 ufshcd_vops_hce_enable_notify(hba, PRE_CHANGE);
4286 /* start controller initialization sequence */
4287 ufshcd_hba_start(hba);
4290 * To initialize a UFS host controller HCE bit must be set to 1.
4291 * During initialization the HCE bit value changes from 1->0->1.
4292 * When the host controller completes initialization sequence
4293 * it sets the value of HCE bit to 1. The same HCE bit is read back
4294 * to check if the controller has completed initialization sequence.
4295 * So without this delay the value HCE = 1, set in the previous
4296 * instruction might be read back.
4297 * This delay can be changed based on the controller.
4301 /* wait for the host controller to complete initialization */
4303 while (ufshcd_is_hba_active(hba)) {
4308 "Controller enable failed\n");
4314 /* enable UIC related interrupts */
4315 ufshcd_enable_intr(hba, UFSHCD_UIC_MASK);
4317 ufshcd_vops_hce_enable_notify(hba, POST_CHANGE);
4322 static int ufshcd_hba_enable(struct ufs_hba *hba)
4326 if (hba->quirks & UFSHCI_QUIRK_BROKEN_HCE) {
4327 ufshcd_set_link_off(hba);
4328 ufshcd_vops_hce_enable_notify(hba, PRE_CHANGE);
4330 /* enable UIC related interrupts */
4331 ufshcd_enable_intr(hba, UFSHCD_UIC_MASK);
4332 ret = ufshcd_dme_reset(hba);
4334 ret = ufshcd_dme_enable(hba);
4336 ufshcd_vops_hce_enable_notify(hba, POST_CHANGE);
4339 "Host controller enable failed with non-hce\n");
4342 ret = ufshcd_hba_execute_hce(hba);
4347 static int ufshcd_disable_tx_lcc(struct ufs_hba *hba, bool peer)
4349 int tx_lanes, i, err = 0;
4352 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_CONNECTEDTXDATALANES),
4355 ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_CONNECTEDTXDATALANES),
4357 for (i = 0; i < tx_lanes; i++) {
4359 err = ufshcd_dme_set(hba,
4360 UIC_ARG_MIB_SEL(TX_LCC_ENABLE,
4361 UIC_ARG_MPHY_TX_GEN_SEL_INDEX(i)),
4364 err = ufshcd_dme_peer_set(hba,
4365 UIC_ARG_MIB_SEL(TX_LCC_ENABLE,
4366 UIC_ARG_MPHY_TX_GEN_SEL_INDEX(i)),
4369 dev_err(hba->dev, "%s: TX LCC Disable failed, peer = %d, lane = %d, err = %d",
4370 __func__, peer, i, err);
4378 static inline int ufshcd_disable_device_tx_lcc(struct ufs_hba *hba)
4380 return ufshcd_disable_tx_lcc(hba, true);
4384 * ufshcd_link_startup - Initialize unipro link startup
4385 * @hba: per adapter instance
4387 * Returns 0 for success, non-zero in case of failure
4389 static int ufshcd_link_startup(struct ufs_hba *hba)
4392 int retries = DME_LINKSTARTUP_RETRIES;
4393 bool link_startup_again = false;
4396 * If UFS device isn't active then we will have to issue link startup
4397 * 2 times to make sure the device state move to active.
4399 if (!ufshcd_is_ufs_dev_active(hba))
4400 link_startup_again = true;
4404 ufshcd_vops_link_startup_notify(hba, PRE_CHANGE);
4406 ret = ufshcd_dme_link_startup(hba);
4408 /* check if device is detected by inter-connect layer */
4409 if (!ret && !ufshcd_is_device_present(hba)) {
4410 dev_err(hba->dev, "%s: Device not present\n", __func__);
4416 * DME link lost indication is only received when link is up,
4417 * but we can't be sure if the link is up until link startup
4418 * succeeds. So reset the local Uni-Pro and try again.
4420 if (ret && ufshcd_hba_enable(hba))
4422 } while (ret && retries--);
4425 /* failed to get the link up... retire */
4428 if (link_startup_again) {
4429 link_startup_again = false;
4430 retries = DME_LINKSTARTUP_RETRIES;
4434 /* Mark that link is up in PWM-G1, 1-lane, SLOW-AUTO mode */
4435 ufshcd_init_pwr_info(hba);
4436 ufshcd_print_pwr_info(hba);
4438 if (hba->quirks & UFSHCD_QUIRK_BROKEN_LCC) {
4439 ret = ufshcd_disable_device_tx_lcc(hba);
4444 /* Include any host controller configuration via UIC commands */
4445 ret = ufshcd_vops_link_startup_notify(hba, POST_CHANGE);
4449 ret = ufshcd_make_hba_operational(hba);
4452 dev_err(hba->dev, "link startup failed %d\n", ret);
4453 ufshcd_print_host_state(hba);
4454 ufshcd_print_pwr_info(hba);
4455 ufshcd_print_host_regs(hba);
4461 * ufshcd_verify_dev_init() - Verify device initialization
4462 * @hba: per-adapter instance
4464 * Send NOP OUT UPIU and wait for NOP IN response to check whether the
4465 * device Transport Protocol (UTP) layer is ready after a reset.
4466 * If the UTP layer at the device side is not initialized, it may
4467 * not respond with NOP IN UPIU within timeout of %NOP_OUT_TIMEOUT
4468 * and we retry sending NOP OUT for %NOP_OUT_RETRIES iterations.
4470 static int ufshcd_verify_dev_init(struct ufs_hba *hba)
4475 ufshcd_hold(hba, false);
4476 mutex_lock(&hba->dev_cmd.lock);
4477 for (retries = NOP_OUT_RETRIES; retries > 0; retries--) {
4478 err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_NOP,
4481 if (!err || err == -ETIMEDOUT)
4484 dev_dbg(hba->dev, "%s: error %d retrying\n", __func__, err);
4486 mutex_unlock(&hba->dev_cmd.lock);
4487 ufshcd_release(hba);
4490 dev_err(hba->dev, "%s: NOP OUT failed %d\n", __func__, err);
4495 * ufshcd_set_queue_depth - set lun queue depth
4496 * @sdev: pointer to SCSI device
4498 * Read bLUQueueDepth value and activate scsi tagged command
4499 * queueing. For WLUN, queue depth is set to 1. For best-effort
4500 * cases (bLUQueueDepth = 0) the queue depth is set to a maximum
4501 * value that host can queue.
4503 static void ufshcd_set_queue_depth(struct scsi_device *sdev)
4507 struct ufs_hba *hba;
4509 hba = shost_priv(sdev->host);
4511 lun_qdepth = hba->nutrs;
4512 ret = ufshcd_read_unit_desc_param(hba,
4513 ufshcd_scsi_to_upiu_lun(sdev->lun),
4514 UNIT_DESC_PARAM_LU_Q_DEPTH,
4516 sizeof(lun_qdepth));
4518 /* Some WLUN doesn't support unit descriptor */
4519 if (ret == -EOPNOTSUPP)
4521 else if (!lun_qdepth)
4522 /* eventually, we can figure out the real queue depth */
4523 lun_qdepth = hba->nutrs;
4525 lun_qdepth = min_t(int, lun_qdepth, hba->nutrs);
4527 dev_dbg(hba->dev, "%s: activate tcq with queue depth %d\n",
4528 __func__, lun_qdepth);
4529 scsi_change_queue_depth(sdev, lun_qdepth);
4533 * ufshcd_get_lu_wp - returns the "b_lu_write_protect" from UNIT DESCRIPTOR
4534 * @hba: per-adapter instance
4535 * @lun: UFS device lun id
4536 * @b_lu_write_protect: pointer to buffer to hold the LU's write protect info
4538 * Returns 0 in case of success and b_lu_write_protect status would be returned
4539 * @b_lu_write_protect parameter.
4540 * Returns -ENOTSUPP if reading b_lu_write_protect is not supported.
4541 * Returns -EINVAL in case of invalid parameters passed to this function.
4543 static int ufshcd_get_lu_wp(struct ufs_hba *hba,
4545 u8 *b_lu_write_protect)
4549 if (!b_lu_write_protect)
4552 * According to UFS device spec, RPMB LU can't be write
4553 * protected so skip reading bLUWriteProtect parameter for
4554 * it. For other W-LUs, UNIT DESCRIPTOR is not available.
4556 else if (lun >= UFS_UPIU_MAX_GENERAL_LUN)
4559 ret = ufshcd_read_unit_desc_param(hba,
4561 UNIT_DESC_PARAM_LU_WR_PROTECT,
4563 sizeof(*b_lu_write_protect));
4568 * ufshcd_get_lu_power_on_wp_status - get LU's power on write protect
4570 * @hba: per-adapter instance
4571 * @sdev: pointer to SCSI device
4574 static inline void ufshcd_get_lu_power_on_wp_status(struct ufs_hba *hba,
4575 struct scsi_device *sdev)
4577 if (hba->dev_info.f_power_on_wp_en &&
4578 !hba->dev_info.is_lu_power_on_wp) {
4579 u8 b_lu_write_protect;
4581 if (!ufshcd_get_lu_wp(hba, ufshcd_scsi_to_upiu_lun(sdev->lun),
4582 &b_lu_write_protect) &&
4583 (b_lu_write_protect == UFS_LU_POWER_ON_WP))
4584 hba->dev_info.is_lu_power_on_wp = true;
4589 * ufshcd_slave_alloc - handle initial SCSI device configurations
4590 * @sdev: pointer to SCSI device
4594 static int ufshcd_slave_alloc(struct scsi_device *sdev)
4596 struct ufs_hba *hba;
4598 hba = shost_priv(sdev->host);
4600 /* Mode sense(6) is not supported by UFS, so use Mode sense(10) */
4601 sdev->use_10_for_ms = 1;
4603 /* allow SCSI layer to restart the device in case of errors */
4604 sdev->allow_restart = 1;
4606 /* REPORT SUPPORTED OPERATION CODES is not supported */
4607 sdev->no_report_opcodes = 1;
4609 /* WRITE_SAME command is not supported */
4610 sdev->no_write_same = 1;
4612 ufshcd_set_queue_depth(sdev);
4614 ufshcd_get_lu_power_on_wp_status(hba, sdev);
4620 * ufshcd_change_queue_depth - change queue depth
4621 * @sdev: pointer to SCSI device
4622 * @depth: required depth to set
4624 * Change queue depth and make sure the max. limits are not crossed.
4626 static int ufshcd_change_queue_depth(struct scsi_device *sdev, int depth)
4628 struct ufs_hba *hba = shost_priv(sdev->host);
4630 if (depth > hba->nutrs)
4632 return scsi_change_queue_depth(sdev, depth);
4636 * ufshcd_slave_configure - adjust SCSI device configurations
4637 * @sdev: pointer to SCSI device
4639 static int ufshcd_slave_configure(struct scsi_device *sdev)
4641 struct request_queue *q = sdev->request_queue;
4643 blk_queue_update_dma_pad(q, PRDT_DATA_BYTE_COUNT_PAD - 1);
4644 blk_queue_max_segment_size(q, PRDT_DATA_BYTE_COUNT_MAX);
4650 * ufshcd_slave_destroy - remove SCSI device configurations
4651 * @sdev: pointer to SCSI device
4653 static void ufshcd_slave_destroy(struct scsi_device *sdev)
4655 struct ufs_hba *hba;
4657 hba = shost_priv(sdev->host);
4658 /* Drop the reference as it won't be needed anymore */
4659 if (ufshcd_scsi_to_upiu_lun(sdev->lun) == UFS_UPIU_UFS_DEVICE_WLUN) {
4660 unsigned long flags;
4662 spin_lock_irqsave(hba->host->host_lock, flags);
4663 hba->sdev_ufs_device = NULL;
4664 spin_unlock_irqrestore(hba->host->host_lock, flags);
4669 * ufshcd_task_req_compl - handle task management request completion
4670 * @hba: per adapter instance
4671 * @index: index of the completed request
4672 * @resp: task management service response
4674 * Returns non-zero value on error, zero on success
4676 static int ufshcd_task_req_compl(struct ufs_hba *hba, u32 index, u8 *resp)
4678 struct utp_task_req_desc *task_req_descp;
4679 struct utp_upiu_task_rsp *task_rsp_upiup;
4680 unsigned long flags;
4684 spin_lock_irqsave(hba->host->host_lock, flags);
4686 /* Clear completed tasks from outstanding_tasks */
4687 __clear_bit(index, &hba->outstanding_tasks);
4689 task_req_descp = hba->utmrdl_base_addr;
4690 ocs_value = ufshcd_get_tmr_ocs(&task_req_descp[index]);
4692 if (ocs_value == OCS_SUCCESS) {
4693 task_rsp_upiup = (struct utp_upiu_task_rsp *)
4694 task_req_descp[index].task_rsp_upiu;
4695 task_result = be32_to_cpu(task_rsp_upiup->output_param1);
4696 task_result = task_result & MASK_TM_SERVICE_RESP;
4698 *resp = (u8)task_result;
4700 dev_err(hba->dev, "%s: failed, ocs = 0x%x\n",
4701 __func__, ocs_value);
4703 spin_unlock_irqrestore(hba->host->host_lock, flags);
4709 * ufshcd_scsi_cmd_status - Update SCSI command result based on SCSI status
4710 * @lrbp: pointer to local reference block of completed command
4711 * @scsi_status: SCSI command status
4713 * Returns value base on SCSI command status
4716 ufshcd_scsi_cmd_status(struct ufshcd_lrb *lrbp, int scsi_status)
4720 switch (scsi_status) {
4721 case SAM_STAT_CHECK_CONDITION:
4722 ufshcd_copy_sense_data(lrbp);
4724 result |= DID_OK << 16 |
4725 COMMAND_COMPLETE << 8 |
4728 case SAM_STAT_TASK_SET_FULL:
4730 case SAM_STAT_TASK_ABORTED:
4731 ufshcd_copy_sense_data(lrbp);
4732 result |= scsi_status;
4735 result |= DID_ERROR << 16;
4737 } /* end of switch */
4743 * ufshcd_transfer_rsp_status - Get overall status of the response
4744 * @hba: per adapter instance
4745 * @lrbp: pointer to local reference block of completed command
4747 * Returns result of the command to notify SCSI midlayer
4750 ufshcd_transfer_rsp_status(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
4756 /* overall command status of utrd */
4757 ocs = ufshcd_get_tr_ocs(lrbp);
4761 result = ufshcd_get_req_rsp(lrbp->ucd_rsp_ptr);
4762 hba->ufs_stats.last_hibern8_exit_tstamp = ktime_set(0, 0);
4764 case UPIU_TRANSACTION_RESPONSE:
4766 * get the response UPIU result to extract
4767 * the SCSI command status
4769 result = ufshcd_get_rsp_upiu_result(lrbp->ucd_rsp_ptr);
4772 * get the result based on SCSI status response
4773 * to notify the SCSI midlayer of the command status
4775 scsi_status = result & MASK_SCSI_STATUS;
4776 result = ufshcd_scsi_cmd_status(lrbp, scsi_status);
4779 * Currently we are only supporting BKOPs exception
4780 * events hence we can ignore BKOPs exception event
4781 * during power management callbacks. BKOPs exception
4782 * event is not expected to be raised in runtime suspend
4783 * callback as it allows the urgent bkops.
4784 * During system suspend, we are anyway forcefully
4785 * disabling the bkops and if urgent bkops is needed
4786 * it will be enabled on system resume. Long term
4787 * solution could be to abort the system suspend if
4788 * UFS device needs urgent BKOPs.
4790 if (!hba->pm_op_in_progress &&
4791 ufshcd_is_exception_event(lrbp->ucd_rsp_ptr))
4792 schedule_work(&hba->eeh_work);
4794 case UPIU_TRANSACTION_REJECT_UPIU:
4795 /* TODO: handle Reject UPIU Response */
4796 result = DID_ERROR << 16;
4798 "Reject UPIU not fully implemented\n");
4801 result = DID_ERROR << 16;
4803 "Unexpected request response code = %x\n",
4809 result |= DID_ABORT << 16;
4811 case OCS_INVALID_COMMAND_STATUS:
4812 result |= DID_REQUEUE << 16;
4814 case OCS_INVALID_CMD_TABLE_ATTR:
4815 case OCS_INVALID_PRDT_ATTR:
4816 case OCS_MISMATCH_DATA_BUF_SIZE:
4817 case OCS_MISMATCH_RESP_UPIU_SIZE:
4818 case OCS_PEER_COMM_FAILURE:
4819 case OCS_FATAL_ERROR:
4821 result |= DID_ERROR << 16;
4823 "OCS error from controller = %x for tag %d\n",
4824 ocs, lrbp->task_tag);
4825 ufshcd_print_host_regs(hba);
4826 ufshcd_print_host_state(hba);
4828 } /* end of switch */
4830 if ((host_byte(result) != DID_OK) && !hba->silence_err_logs)
4831 ufshcd_print_trs(hba, 1 << lrbp->task_tag, true);
4836 * ufshcd_uic_cmd_compl - handle completion of uic command
4837 * @hba: per adapter instance
4838 * @intr_status: interrupt status generated by the controller
4840 static void ufshcd_uic_cmd_compl(struct ufs_hba *hba, u32 intr_status)
4842 if ((intr_status & UIC_COMMAND_COMPL) && hba->active_uic_cmd) {
4843 hba->active_uic_cmd->argument2 |=
4844 ufshcd_get_uic_cmd_result(hba);
4845 hba->active_uic_cmd->argument3 =
4846 ufshcd_get_dme_attr_val(hba);
4847 complete(&hba->active_uic_cmd->done);
4850 if ((intr_status & UFSHCD_UIC_PWR_MASK) && hba->uic_async_done)
4851 complete(hba->uic_async_done);
4855 * __ufshcd_transfer_req_compl - handle SCSI and query command completion
4856 * @hba: per adapter instance
4857 * @completed_reqs: requests to complete
4859 static void __ufshcd_transfer_req_compl(struct ufs_hba *hba,
4860 unsigned long completed_reqs)
4862 struct ufshcd_lrb *lrbp;
4863 struct scsi_cmnd *cmd;
4867 for_each_set_bit(index, &completed_reqs, hba->nutrs) {
4868 lrbp = &hba->lrb[index];
4871 ufshcd_add_command_trace(hba, index, "complete");
4872 result = ufshcd_transfer_rsp_status(hba, lrbp);
4873 scsi_dma_unmap(cmd);
4874 cmd->result = result;
4875 /* Mark completed command as NULL in LRB */
4877 clear_bit_unlock(index, &hba->lrb_in_use);
4878 /* Do not touch lrbp after scsi done */
4879 cmd->scsi_done(cmd);
4880 __ufshcd_release(hba);
4881 } else if (lrbp->command_type == UTP_CMD_TYPE_DEV_MANAGE ||
4882 lrbp->command_type == UTP_CMD_TYPE_UFS_STORAGE) {
4883 if (hba->dev_cmd.complete) {
4884 ufshcd_add_command_trace(hba, index,
4886 complete(hba->dev_cmd.complete);
4889 if (ufshcd_is_clkscaling_supported(hba))
4890 hba->clk_scaling.active_reqs--;
4892 lrbp->compl_time_stamp = ktime_get();
4895 /* clear corresponding bits of completed commands */
4896 hba->outstanding_reqs ^= completed_reqs;
4898 ufshcd_clk_scaling_update_busy(hba);
4900 /* we might have free'd some tags above */
4901 wake_up(&hba->dev_cmd.tag_wq);
4905 * ufshcd_transfer_req_compl - handle SCSI and query command completion
4906 * @hba: per adapter instance
4908 static void ufshcd_transfer_req_compl(struct ufs_hba *hba)
4910 unsigned long completed_reqs;
4913 /* Resetting interrupt aggregation counters first and reading the
4914 * DOOR_BELL afterward allows us to handle all the completed requests.
4915 * In order to prevent other interrupts starvation the DB is read once
4916 * after reset. The down side of this solution is the possibility of
4917 * false interrupt if device completes another request after resetting
4918 * aggregation and before reading the DB.
4920 if (ufshcd_is_intr_aggr_allowed(hba) &&
4921 !(hba->quirks & UFSHCI_QUIRK_SKIP_RESET_INTR_AGGR))
4922 ufshcd_reset_intr_aggr(hba);
4924 tr_doorbell = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
4925 completed_reqs = tr_doorbell ^ hba->outstanding_reqs;
4927 __ufshcd_transfer_req_compl(hba, completed_reqs);
4931 * ufshcd_disable_ee - disable exception event
4932 * @hba: per-adapter instance
4933 * @mask: exception event to disable
4935 * Disables exception event in the device so that the EVENT_ALERT
4938 * Returns zero on success, non-zero error value on failure.
4940 static int ufshcd_disable_ee(struct ufs_hba *hba, u16 mask)
4945 if (!(hba->ee_ctrl_mask & mask))
4948 val = hba->ee_ctrl_mask & ~mask;
4949 val &= MASK_EE_STATUS;
4950 err = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_WRITE_ATTR,
4951 QUERY_ATTR_IDN_EE_CONTROL, 0, 0, &val);
4953 hba->ee_ctrl_mask &= ~mask;
4959 * ufshcd_enable_ee - enable exception event
4960 * @hba: per-adapter instance
4961 * @mask: exception event to enable
4963 * Enable corresponding exception event in the device to allow
4964 * device to alert host in critical scenarios.
4966 * Returns zero on success, non-zero error value on failure.
4968 static int ufshcd_enable_ee(struct ufs_hba *hba, u16 mask)
4973 if (hba->ee_ctrl_mask & mask)
4976 val = hba->ee_ctrl_mask | mask;
4977 val &= MASK_EE_STATUS;
4978 err = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_WRITE_ATTR,
4979 QUERY_ATTR_IDN_EE_CONTROL, 0, 0, &val);
4981 hba->ee_ctrl_mask |= mask;
4987 * ufshcd_enable_auto_bkops - Allow device managed BKOPS
4988 * @hba: per-adapter instance
4990 * Allow device to manage background operations on its own. Enabling
4991 * this might lead to inconsistent latencies during normal data transfers
4992 * as the device is allowed to manage its own way of handling background
4995 * Returns zero on success, non-zero on failure.
4997 static int ufshcd_enable_auto_bkops(struct ufs_hba *hba)
5001 if (hba->auto_bkops_enabled)
5004 err = ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_SET_FLAG,
5005 QUERY_FLAG_IDN_BKOPS_EN, NULL);
5007 dev_err(hba->dev, "%s: failed to enable bkops %d\n",
5012 hba->auto_bkops_enabled = true;
5013 trace_ufshcd_auto_bkops_state(dev_name(hba->dev), "Enabled");
5015 /* No need of URGENT_BKOPS exception from the device */
5016 err = ufshcd_disable_ee(hba, MASK_EE_URGENT_BKOPS);
5018 dev_err(hba->dev, "%s: failed to disable exception event %d\n",
5025 * ufshcd_disable_auto_bkops - block device in doing background operations
5026 * @hba: per-adapter instance
5028 * Disabling background operations improves command response latency but
5029 * has drawback of device moving into critical state where the device is
5030 * not-operable. Make sure to call ufshcd_enable_auto_bkops() whenever the
5031 * host is idle so that BKOPS are managed effectively without any negative
5034 * Returns zero on success, non-zero on failure.
5036 static int ufshcd_disable_auto_bkops(struct ufs_hba *hba)
5040 if (!hba->auto_bkops_enabled)
5044 * If host assisted BKOPs is to be enabled, make sure
5045 * urgent bkops exception is allowed.
5047 err = ufshcd_enable_ee(hba, MASK_EE_URGENT_BKOPS);
5049 dev_err(hba->dev, "%s: failed to enable exception event %d\n",
5054 err = ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_CLEAR_FLAG,
5055 QUERY_FLAG_IDN_BKOPS_EN, NULL);
5057 dev_err(hba->dev, "%s: failed to disable bkops %d\n",
5059 ufshcd_disable_ee(hba, MASK_EE_URGENT_BKOPS);
5063 hba->auto_bkops_enabled = false;
5064 trace_ufshcd_auto_bkops_state(dev_name(hba->dev), "Disabled");
5065 hba->is_urgent_bkops_lvl_checked = false;
5071 * ufshcd_force_reset_auto_bkops - force reset auto bkops state
5072 * @hba: per adapter instance
5074 * After a device reset the device may toggle the BKOPS_EN flag
5075 * to default value. The s/w tracking variables should be updated
5076 * as well. This function would change the auto-bkops state based on
5077 * UFSHCD_CAP_KEEP_AUTO_BKOPS_ENABLED_EXCEPT_SUSPEND.
5079 static void ufshcd_force_reset_auto_bkops(struct ufs_hba *hba)
5081 if (ufshcd_keep_autobkops_enabled_except_suspend(hba)) {
5082 hba->auto_bkops_enabled = false;
5083 hba->ee_ctrl_mask |= MASK_EE_URGENT_BKOPS;
5084 ufshcd_enable_auto_bkops(hba);
5086 hba->auto_bkops_enabled = true;
5087 hba->ee_ctrl_mask &= ~MASK_EE_URGENT_BKOPS;
5088 ufshcd_disable_auto_bkops(hba);
5090 hba->is_urgent_bkops_lvl_checked = false;
5093 static inline int ufshcd_get_bkops_status(struct ufs_hba *hba, u32 *status)
5095 return ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
5096 QUERY_ATTR_IDN_BKOPS_STATUS, 0, 0, status);
5100 * ufshcd_bkops_ctrl - control the auto bkops based on current bkops status
5101 * @hba: per-adapter instance
5102 * @status: bkops_status value
5104 * Read the bkops_status from the UFS device and Enable fBackgroundOpsEn
5105 * flag in the device to permit background operations if the device
5106 * bkops_status is greater than or equal to "status" argument passed to
5107 * this function, disable otherwise.
5109 * Returns 0 for success, non-zero in case of failure.
5111 * NOTE: Caller of this function can check the "hba->auto_bkops_enabled" flag
5112 * to know whether auto bkops is enabled or disabled after this function
5113 * returns control to it.
5115 static int ufshcd_bkops_ctrl(struct ufs_hba *hba,
5116 enum bkops_status status)
5119 u32 curr_status = 0;
5121 err = ufshcd_get_bkops_status(hba, &curr_status);
5123 dev_err(hba->dev, "%s: failed to get BKOPS status %d\n",
5126 } else if (curr_status > BKOPS_STATUS_MAX) {
5127 dev_err(hba->dev, "%s: invalid BKOPS status %d\n",
5128 __func__, curr_status);
5133 if (curr_status >= status)
5134 err = ufshcd_enable_auto_bkops(hba);
5136 err = ufshcd_disable_auto_bkops(hba);
5142 * ufshcd_urgent_bkops - handle urgent bkops exception event
5143 * @hba: per-adapter instance
5145 * Enable fBackgroundOpsEn flag in the device to permit background
5148 * If BKOPs is enabled, this function returns 0, 1 if the bkops in not enabled
5149 * and negative error value for any other failure.
5151 static int ufshcd_urgent_bkops(struct ufs_hba *hba)
5153 return ufshcd_bkops_ctrl(hba, hba->urgent_bkops_lvl);
5156 static inline int ufshcd_get_ee_status(struct ufs_hba *hba, u32 *status)
5158 return ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
5159 QUERY_ATTR_IDN_EE_STATUS, 0, 0, status);
5162 static void ufshcd_bkops_exception_event_handler(struct ufs_hba *hba)
5165 u32 curr_status = 0;
5167 if (hba->is_urgent_bkops_lvl_checked)
5168 goto enable_auto_bkops;
5170 err = ufshcd_get_bkops_status(hba, &curr_status);
5172 dev_err(hba->dev, "%s: failed to get BKOPS status %d\n",
5178 * We are seeing that some devices are raising the urgent bkops
5179 * exception events even when BKOPS status doesn't indicate performace
5180 * impacted or critical. Handle these device by determining their urgent
5181 * bkops status at runtime.
5183 if (curr_status < BKOPS_STATUS_PERF_IMPACT) {
5184 dev_err(hba->dev, "%s: device raised urgent BKOPS exception for bkops status %d\n",
5185 __func__, curr_status);
5186 /* update the current status as the urgent bkops level */
5187 hba->urgent_bkops_lvl = curr_status;
5188 hba->is_urgent_bkops_lvl_checked = true;
5192 err = ufshcd_enable_auto_bkops(hba);
5195 dev_err(hba->dev, "%s: failed to handle urgent bkops %d\n",
5200 * ufshcd_exception_event_handler - handle exceptions raised by device
5201 * @work: pointer to work data
5203 * Read bExceptionEventStatus attribute from the device and handle the
5204 * exception event accordingly.
5206 static void ufshcd_exception_event_handler(struct work_struct *work)
5208 struct ufs_hba *hba;
5211 hba = container_of(work, struct ufs_hba, eeh_work);
5213 pm_runtime_get_sync(hba->dev);
5214 scsi_block_requests(hba->host);
5215 err = ufshcd_get_ee_status(hba, &status);
5217 dev_err(hba->dev, "%s: failed to get exception status %d\n",
5222 status &= hba->ee_ctrl_mask;
5224 if (status & MASK_EE_URGENT_BKOPS)
5225 ufshcd_bkops_exception_event_handler(hba);
5228 scsi_unblock_requests(hba->host);
5229 pm_runtime_put_sync(hba->dev);
5233 /* Complete requests that have door-bell cleared */
5234 static void ufshcd_complete_requests(struct ufs_hba *hba)
5236 ufshcd_transfer_req_compl(hba);
5237 ufshcd_tmc_handler(hba);
5241 * ufshcd_quirk_dl_nac_errors - This function checks if error handling is
5242 * to recover from the DL NAC errors or not.
5243 * @hba: per-adapter instance
5245 * Returns true if error handling is required, false otherwise
5247 static bool ufshcd_quirk_dl_nac_errors(struct ufs_hba *hba)
5249 unsigned long flags;
5250 bool err_handling = true;
5252 spin_lock_irqsave(hba->host->host_lock, flags);
5254 * UFS_DEVICE_QUIRK_RECOVERY_FROM_DL_NAC_ERRORS only workaround the
5255 * device fatal error and/or DL NAC & REPLAY timeout errors.
5257 if (hba->saved_err & (CONTROLLER_FATAL_ERROR | SYSTEM_BUS_FATAL_ERROR))
5260 if ((hba->saved_err & DEVICE_FATAL_ERROR) ||
5261 ((hba->saved_err & UIC_ERROR) &&
5262 (hba->saved_uic_err & UFSHCD_UIC_DL_TCx_REPLAY_ERROR)))
5265 if ((hba->saved_err & UIC_ERROR) &&
5266 (hba->saved_uic_err & UFSHCD_UIC_DL_NAC_RECEIVED_ERROR)) {
5269 * wait for 50ms to see if we can get any other errors or not.
5271 spin_unlock_irqrestore(hba->host->host_lock, flags);
5273 spin_lock_irqsave(hba->host->host_lock, flags);
5276 * now check if we have got any other severe errors other than
5279 if ((hba->saved_err & INT_FATAL_ERRORS) ||
5280 ((hba->saved_err & UIC_ERROR) &&
5281 (hba->saved_uic_err & ~UFSHCD_UIC_DL_NAC_RECEIVED_ERROR)))
5285 * As DL NAC is the only error received so far, send out NOP
5286 * command to confirm if link is still active or not.
5287 * - If we don't get any response then do error recovery.
5288 * - If we get response then clear the DL NAC error bit.
5291 spin_unlock_irqrestore(hba->host->host_lock, flags);
5292 err = ufshcd_verify_dev_init(hba);
5293 spin_lock_irqsave(hba->host->host_lock, flags);
5298 /* Link seems to be alive hence ignore the DL NAC errors */
5299 if (hba->saved_uic_err == UFSHCD_UIC_DL_NAC_RECEIVED_ERROR)
5300 hba->saved_err &= ~UIC_ERROR;
5301 /* clear NAC error */
5302 hba->saved_uic_err &= ~UFSHCD_UIC_DL_NAC_RECEIVED_ERROR;
5303 if (!hba->saved_uic_err) {
5304 err_handling = false;
5309 spin_unlock_irqrestore(hba->host->host_lock, flags);
5310 return err_handling;
5314 * ufshcd_err_handler - handle UFS errors that require s/w attention
5315 * @work: pointer to work structure
5317 static void ufshcd_err_handler(struct work_struct *work)
5319 struct ufs_hba *hba;
5320 unsigned long flags;
5325 bool needs_reset = false;
5327 hba = container_of(work, struct ufs_hba, eh_work);
5329 pm_runtime_get_sync(hba->dev);
5330 ufshcd_hold(hba, false);
5332 spin_lock_irqsave(hba->host->host_lock, flags);
5333 if (hba->ufshcd_state == UFSHCD_STATE_RESET)
5336 hba->ufshcd_state = UFSHCD_STATE_RESET;
5337 ufshcd_set_eh_in_progress(hba);
5339 /* Complete requests that have door-bell cleared by h/w */
5340 ufshcd_complete_requests(hba);
5342 if (hba->dev_quirks & UFS_DEVICE_QUIRK_RECOVERY_FROM_DL_NAC_ERRORS) {
5345 spin_unlock_irqrestore(hba->host->host_lock, flags);
5346 /* release the lock as ufshcd_quirk_dl_nac_errors() may sleep */
5347 ret = ufshcd_quirk_dl_nac_errors(hba);
5348 spin_lock_irqsave(hba->host->host_lock, flags);
5350 goto skip_err_handling;
5352 if ((hba->saved_err & INT_FATAL_ERRORS) ||
5353 ((hba->saved_err & UIC_ERROR) &&
5354 (hba->saved_uic_err & (UFSHCD_UIC_DL_PA_INIT_ERROR |
5355 UFSHCD_UIC_DL_NAC_RECEIVED_ERROR |
5356 UFSHCD_UIC_DL_TCx_REPLAY_ERROR))))
5360 * if host reset is required then skip clearing the pending
5361 * transfers forcefully because they will get cleared during
5362 * host reset and restore
5365 goto skip_pending_xfer_clear;
5367 /* release lock as clear command might sleep */
5368 spin_unlock_irqrestore(hba->host->host_lock, flags);
5369 /* Clear pending transfer requests */
5370 for_each_set_bit(tag, &hba->outstanding_reqs, hba->nutrs) {
5371 if (ufshcd_clear_cmd(hba, tag)) {
5373 goto lock_skip_pending_xfer_clear;
5377 /* Clear pending task management requests */
5378 for_each_set_bit(tag, &hba->outstanding_tasks, hba->nutmrs) {
5379 if (ufshcd_clear_tm_cmd(hba, tag)) {
5381 goto lock_skip_pending_xfer_clear;
5385 lock_skip_pending_xfer_clear:
5386 spin_lock_irqsave(hba->host->host_lock, flags);
5388 /* Complete the requests that are cleared by s/w */
5389 ufshcd_complete_requests(hba);
5391 if (err_xfer || err_tm)
5394 skip_pending_xfer_clear:
5395 /* Fatal errors need reset */
5397 unsigned long max_doorbells = (1UL << hba->nutrs) - 1;
5400 * ufshcd_reset_and_restore() does the link reinitialization
5401 * which will need atleast one empty doorbell slot to send the
5402 * device management commands (NOP and query commands).
5403 * If there is no slot empty at this moment then free up last
5406 if (hba->outstanding_reqs == max_doorbells)
5407 __ufshcd_transfer_req_compl(hba,
5408 (1UL << (hba->nutrs - 1)));
5410 spin_unlock_irqrestore(hba->host->host_lock, flags);
5411 err = ufshcd_reset_and_restore(hba);
5412 spin_lock_irqsave(hba->host->host_lock, flags);
5414 dev_err(hba->dev, "%s: reset and restore failed\n",
5416 hba->ufshcd_state = UFSHCD_STATE_ERROR;
5419 * Inform scsi mid-layer that we did reset and allow to handle
5420 * Unit Attention properly.
5422 scsi_report_bus_reset(hba->host, 0);
5424 hba->saved_uic_err = 0;
5429 hba->ufshcd_state = UFSHCD_STATE_OPERATIONAL;
5430 if (hba->saved_err || hba->saved_uic_err)
5431 dev_err_ratelimited(hba->dev, "%s: exit: saved_err 0x%x saved_uic_err 0x%x",
5432 __func__, hba->saved_err, hba->saved_uic_err);
5435 ufshcd_clear_eh_in_progress(hba);
5438 spin_unlock_irqrestore(hba->host->host_lock, flags);
5439 ufshcd_scsi_unblock_requests(hba);
5440 ufshcd_release(hba);
5441 pm_runtime_put_sync(hba->dev);
5444 static void ufshcd_update_uic_reg_hist(struct ufs_uic_err_reg_hist *reg_hist,
5447 reg_hist->reg[reg_hist->pos] = reg;
5448 reg_hist->tstamp[reg_hist->pos] = ktime_get();
5449 reg_hist->pos = (reg_hist->pos + 1) % UIC_ERR_REG_HIST_LENGTH;
5453 * ufshcd_update_uic_error - check and set fatal UIC error flags.
5454 * @hba: per-adapter instance
5456 static void ufshcd_update_uic_error(struct ufs_hba *hba)
5460 /* PHY layer lane error */
5461 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_PHY_ADAPTER_LAYER);
5462 /* Ignore LINERESET indication, as this is not an error */
5463 if ((reg & UIC_PHY_ADAPTER_LAYER_ERROR) &&
5464 (reg & UIC_PHY_ADAPTER_LAYER_LANE_ERR_MASK)) {
5466 * To know whether this error is fatal or not, DB timeout
5467 * must be checked but this error is handled separately.
5469 dev_dbg(hba->dev, "%s: UIC Lane error reported\n", __func__);
5470 ufshcd_update_uic_reg_hist(&hba->ufs_stats.pa_err, reg);
5473 /* PA_INIT_ERROR is fatal and needs UIC reset */
5474 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_DATA_LINK_LAYER);
5476 ufshcd_update_uic_reg_hist(&hba->ufs_stats.dl_err, reg);
5478 if (reg & UIC_DATA_LINK_LAYER_ERROR_PA_INIT)
5479 hba->uic_error |= UFSHCD_UIC_DL_PA_INIT_ERROR;
5480 else if (hba->dev_quirks &
5481 UFS_DEVICE_QUIRK_RECOVERY_FROM_DL_NAC_ERRORS) {
5482 if (reg & UIC_DATA_LINK_LAYER_ERROR_NAC_RECEIVED)
5484 UFSHCD_UIC_DL_NAC_RECEIVED_ERROR;
5485 else if (reg & UIC_DATA_LINK_LAYER_ERROR_TCx_REPLAY_TIMEOUT)
5486 hba->uic_error |= UFSHCD_UIC_DL_TCx_REPLAY_ERROR;
5489 /* UIC NL/TL/DME errors needs software retry */
5490 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_NETWORK_LAYER);
5492 ufshcd_update_uic_reg_hist(&hba->ufs_stats.nl_err, reg);
5493 hba->uic_error |= UFSHCD_UIC_NL_ERROR;
5496 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_TRANSPORT_LAYER);
5498 ufshcd_update_uic_reg_hist(&hba->ufs_stats.tl_err, reg);
5499 hba->uic_error |= UFSHCD_UIC_TL_ERROR;
5502 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_DME);
5504 ufshcd_update_uic_reg_hist(&hba->ufs_stats.dme_err, reg);
5505 hba->uic_error |= UFSHCD_UIC_DME_ERROR;
5508 dev_dbg(hba->dev, "%s: UIC error flags = 0x%08x\n",
5509 __func__, hba->uic_error);
5513 * ufshcd_check_errors - Check for errors that need s/w attention
5514 * @hba: per-adapter instance
5516 static void ufshcd_check_errors(struct ufs_hba *hba)
5518 bool queue_eh_work = false;
5520 if (hba->errors & INT_FATAL_ERRORS)
5521 queue_eh_work = true;
5523 if (hba->errors & UIC_ERROR) {
5525 ufshcd_update_uic_error(hba);
5527 queue_eh_work = true;
5530 if (queue_eh_work) {
5532 * update the transfer error masks to sticky bits, let's do this
5533 * irrespective of current ufshcd_state.
5535 hba->saved_err |= hba->errors;
5536 hba->saved_uic_err |= hba->uic_error;
5538 /* handle fatal errors only when link is functional */
5539 if (hba->ufshcd_state == UFSHCD_STATE_OPERATIONAL) {
5540 /* block commands from scsi mid-layer */
5541 ufshcd_scsi_block_requests(hba);
5543 hba->ufshcd_state = UFSHCD_STATE_EH_SCHEDULED;
5545 /* dump controller state before resetting */
5546 if (hba->saved_err & (INT_FATAL_ERRORS | UIC_ERROR)) {
5547 bool pr_prdt = !!(hba->saved_err &
5548 SYSTEM_BUS_FATAL_ERROR);
5550 dev_err(hba->dev, "%s: saved_err 0x%x saved_uic_err 0x%x\n",
5551 __func__, hba->saved_err,
5552 hba->saved_uic_err);
5554 ufshcd_print_host_regs(hba);
5555 ufshcd_print_pwr_info(hba);
5556 ufshcd_print_tmrs(hba, hba->outstanding_tasks);
5557 ufshcd_print_trs(hba, hba->outstanding_reqs,
5560 schedule_work(&hba->eh_work);
5564 * if (!queue_eh_work) -
5565 * Other errors are either non-fatal where host recovers
5566 * itself without s/w intervention or errors that will be
5567 * handled by the SCSI core layer.
5572 * ufshcd_tmc_handler - handle task management function completion
5573 * @hba: per adapter instance
5575 static void ufshcd_tmc_handler(struct ufs_hba *hba)
5579 tm_doorbell = ufshcd_readl(hba, REG_UTP_TASK_REQ_DOOR_BELL);
5580 hba->tm_condition = tm_doorbell ^ hba->outstanding_tasks;
5581 wake_up(&hba->tm_wq);
5585 * ufshcd_sl_intr - Interrupt service routine
5586 * @hba: per adapter instance
5587 * @intr_status: contains interrupts generated by the controller
5589 static void ufshcd_sl_intr(struct ufs_hba *hba, u32 intr_status)
5591 hba->errors = UFSHCD_ERROR_MASK & intr_status;
5593 ufshcd_check_errors(hba);
5595 if (intr_status & UFSHCD_UIC_MASK)
5596 ufshcd_uic_cmd_compl(hba, intr_status);
5598 if (intr_status & UTP_TASK_REQ_COMPL)
5599 ufshcd_tmc_handler(hba);
5601 if (intr_status & UTP_TRANSFER_REQ_COMPL)
5602 ufshcd_transfer_req_compl(hba);
5606 * ufshcd_intr - Main interrupt service routine
5608 * @__hba: pointer to adapter instance
5610 * Returns IRQ_HANDLED - If interrupt is valid
5611 * IRQ_NONE - If invalid interrupt
5613 static irqreturn_t ufshcd_intr(int irq, void *__hba)
5615 u32 intr_status, enabled_intr_status = 0;
5616 irqreturn_t retval = IRQ_NONE;
5617 struct ufs_hba *hba = __hba;
5618 int retries = hba->nutrs;
5620 spin_lock(hba->host->host_lock);
5621 intr_status = ufshcd_readl(hba, REG_INTERRUPT_STATUS);
5624 * There could be max of hba->nutrs reqs in flight and in worst case
5625 * if the reqs get finished 1 by 1 after the interrupt status is
5626 * read, make sure we handle them by checking the interrupt status
5627 * again in a loop until we process all of the reqs before returning.
5629 while (intr_status && retries--) {
5630 enabled_intr_status =
5631 intr_status & ufshcd_readl(hba, REG_INTERRUPT_ENABLE);
5633 ufshcd_writel(hba, intr_status, REG_INTERRUPT_STATUS);
5634 if (enabled_intr_status) {
5635 ufshcd_sl_intr(hba, enabled_intr_status);
5636 retval = IRQ_HANDLED;
5639 intr_status = ufshcd_readl(hba, REG_INTERRUPT_STATUS);
5642 spin_unlock(hba->host->host_lock);
5646 static int ufshcd_clear_tm_cmd(struct ufs_hba *hba, int tag)
5649 u32 mask = 1 << tag;
5650 unsigned long flags;
5652 if (!test_bit(tag, &hba->outstanding_tasks))
5655 spin_lock_irqsave(hba->host->host_lock, flags);
5656 ufshcd_utmrl_clear(hba, tag);
5657 spin_unlock_irqrestore(hba->host->host_lock, flags);
5659 /* poll for max. 1 sec to clear door bell register by h/w */
5660 err = ufshcd_wait_for_register(hba,
5661 REG_UTP_TASK_REQ_DOOR_BELL,
5662 mask, 0, 1000, 1000, true);
5668 * ufshcd_issue_tm_cmd - issues task management commands to controller
5669 * @hba: per adapter instance
5670 * @lun_id: LUN ID to which TM command is sent
5671 * @task_id: task ID to which the TM command is applicable
5672 * @tm_function: task management function opcode
5673 * @tm_response: task management service response return value
5675 * Returns non-zero value on error, zero on success.
5677 static int ufshcd_issue_tm_cmd(struct ufs_hba *hba, int lun_id, int task_id,
5678 u8 tm_function, u8 *tm_response)
5680 struct utp_task_req_desc *task_req_descp;
5681 struct utp_upiu_task_req *task_req_upiup;
5682 struct Scsi_Host *host;
5683 unsigned long flags;
5691 * Get free slot, sleep if slots are unavailable.
5692 * Even though we use wait_event() which sleeps indefinitely,
5693 * the maximum wait time is bounded by %TM_CMD_TIMEOUT.
5695 wait_event(hba->tm_tag_wq, ufshcd_get_tm_free_slot(hba, &free_slot));
5696 ufshcd_hold(hba, false);
5698 spin_lock_irqsave(host->host_lock, flags);
5699 task_req_descp = hba->utmrdl_base_addr;
5700 task_req_descp += free_slot;
5702 /* Configure task request descriptor */
5703 task_req_descp->header.dword_0 = cpu_to_le32(UTP_REQ_DESC_INT_CMD);
5704 task_req_descp->header.dword_2 =
5705 cpu_to_le32(OCS_INVALID_COMMAND_STATUS);
5707 /* Configure task request UPIU */
5709 (struct utp_upiu_task_req *) task_req_descp->task_req_upiu;
5710 task_tag = hba->nutrs + free_slot;
5711 task_req_upiup->header.dword_0 =
5712 UPIU_HEADER_DWORD(UPIU_TRANSACTION_TASK_REQ, 0,
5714 task_req_upiup->header.dword_1 =
5715 UPIU_HEADER_DWORD(0, tm_function, 0, 0);
5717 * The host shall provide the same value for LUN field in the basic
5718 * header and for Input Parameter.
5720 task_req_upiup->input_param1 = cpu_to_be32(lun_id);
5721 task_req_upiup->input_param2 = cpu_to_be32(task_id);
5723 ufshcd_vops_setup_task_mgmt(hba, free_slot, tm_function);
5725 /* send command to the controller */
5726 __set_bit(free_slot, &hba->outstanding_tasks);
5728 /* Make sure descriptors are ready before ringing the task doorbell */
5731 ufshcd_writel(hba, 1 << free_slot, REG_UTP_TASK_REQ_DOOR_BELL);
5732 /* Make sure that doorbell is committed immediately */
5735 spin_unlock_irqrestore(host->host_lock, flags);
5737 ufshcd_add_tm_upiu_trace(hba, task_tag, "tm_send");
5739 /* wait until the task management command is completed */
5740 err = wait_event_timeout(hba->tm_wq,
5741 test_bit(free_slot, &hba->tm_condition),
5742 msecs_to_jiffies(TM_CMD_TIMEOUT));
5744 ufshcd_add_tm_upiu_trace(hba, task_tag, "tm_complete_err");
5745 dev_err(hba->dev, "%s: task management cmd 0x%.2x timed-out\n",
5746 __func__, tm_function);
5747 if (ufshcd_clear_tm_cmd(hba, free_slot))
5748 dev_WARN(hba->dev, "%s: unable clear tm cmd (slot %d) after timeout\n",
5749 __func__, free_slot);
5752 err = ufshcd_task_req_compl(hba, free_slot, tm_response);
5753 ufshcd_add_tm_upiu_trace(hba, task_tag, "tm_complete");
5756 clear_bit(free_slot, &hba->tm_condition);
5757 ufshcd_put_tm_slot(hba, free_slot);
5758 wake_up(&hba->tm_tag_wq);
5760 ufshcd_release(hba);
5765 * ufshcd_eh_device_reset_handler - device reset handler registered to
5767 * @cmd: SCSI command pointer
5769 * Returns SUCCESS/FAILED
5771 static int ufshcd_eh_device_reset_handler(struct scsi_cmnd *cmd)
5773 struct Scsi_Host *host;
5774 struct ufs_hba *hba;
5778 unsigned long flags;
5780 host = cmd->device->host;
5781 hba = shost_priv(host);
5783 lun = ufshcd_scsi_to_upiu_lun(cmd->device->lun);
5784 err = ufshcd_issue_tm_cmd(hba, lun, 0, UFS_LOGICAL_RESET, &resp);
5785 if (err || resp != UPIU_TASK_MANAGEMENT_FUNC_COMPL) {
5791 /* clear the commands that were pending for corresponding LUN */
5792 for_each_set_bit(pos, &hba->outstanding_reqs, hba->nutrs) {
5793 if (hba->lrb[pos].lun == lun) {
5794 err = ufshcd_clear_cmd(hba, pos);
5799 spin_lock_irqsave(host->host_lock, flags);
5800 ufshcd_transfer_req_compl(hba);
5801 spin_unlock_irqrestore(host->host_lock, flags);
5804 hba->req_abort_count = 0;
5808 dev_err(hba->dev, "%s: failed with err %d\n", __func__, err);
5814 static void ufshcd_set_req_abort_skip(struct ufs_hba *hba, unsigned long bitmap)
5816 struct ufshcd_lrb *lrbp;
5819 for_each_set_bit(tag, &bitmap, hba->nutrs) {
5820 lrbp = &hba->lrb[tag];
5821 lrbp->req_abort_skip = true;
5826 * ufshcd_abort - abort a specific command
5827 * @cmd: SCSI command pointer
5829 * Abort the pending command in device by sending UFS_ABORT_TASK task management
5830 * command, and in host controller by clearing the door-bell register. There can
5831 * be race between controller sending the command to the device while abort is
5832 * issued. To avoid that, first issue UFS_QUERY_TASK to check if the command is
5833 * really issued and then try to abort it.
5835 * Returns SUCCESS/FAILED
5837 static int ufshcd_abort(struct scsi_cmnd *cmd)
5839 struct Scsi_Host *host;
5840 struct ufs_hba *hba;
5841 unsigned long flags;
5846 struct ufshcd_lrb *lrbp;
5849 host = cmd->device->host;
5850 hba = shost_priv(host);
5851 tag = cmd->request->tag;
5852 lrbp = &hba->lrb[tag];
5853 if (!ufshcd_valid_tag(hba, tag)) {
5855 "%s: invalid command tag %d: cmd=0x%p, cmd->request=0x%p",
5856 __func__, tag, cmd, cmd->request);
5861 * Task abort to the device W-LUN is illegal. When this command
5862 * will fail, due to spec violation, scsi err handling next step
5863 * will be to send LU reset which, again, is a spec violation.
5864 * To avoid these unnecessary/illegal step we skip to the last error
5865 * handling stage: reset and restore.
5867 if (lrbp->lun == UFS_UPIU_UFS_DEVICE_WLUN)
5868 return ufshcd_eh_host_reset_handler(cmd);
5870 ufshcd_hold(hba, false);
5871 reg = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
5872 /* If command is already aborted/completed, return SUCCESS */
5873 if (!(test_bit(tag, &hba->outstanding_reqs))) {
5875 "%s: cmd at tag %d already completed, outstanding=0x%lx, doorbell=0x%x\n",
5876 __func__, tag, hba->outstanding_reqs, reg);
5880 if (!(reg & (1 << tag))) {
5882 "%s: cmd was completed, but without a notifying intr, tag = %d",
5886 /* Print Transfer Request of aborted task */
5887 dev_err(hba->dev, "%s: Device abort task at tag %d\n", __func__, tag);
5890 * Print detailed info about aborted request.
5891 * As more than one request might get aborted at the same time,
5892 * print full information only for the first aborted request in order
5893 * to reduce repeated printouts. For other aborted requests only print
5896 scsi_print_command(hba->lrb[tag].cmd);
5897 if (!hba->req_abort_count) {
5898 ufshcd_print_host_regs(hba);
5899 ufshcd_print_host_state(hba);
5900 ufshcd_print_pwr_info(hba);
5901 ufshcd_print_trs(hba, 1 << tag, true);
5903 ufshcd_print_trs(hba, 1 << tag, false);
5905 hba->req_abort_count++;
5907 /* Skip task abort in case previous aborts failed and report failure */
5908 if (lrbp->req_abort_skip) {
5913 for (poll_cnt = 100; poll_cnt; poll_cnt--) {
5914 err = ufshcd_issue_tm_cmd(hba, lrbp->lun, lrbp->task_tag,
5915 UFS_QUERY_TASK, &resp);
5916 if (!err && resp == UPIU_TASK_MANAGEMENT_FUNC_SUCCEEDED) {
5917 /* cmd pending in the device */
5918 dev_err(hba->dev, "%s: cmd pending in the device. tag = %d\n",
5921 } else if (!err && resp == UPIU_TASK_MANAGEMENT_FUNC_COMPL) {
5923 * cmd not pending in the device, check if it is
5926 dev_err(hba->dev, "%s: cmd at tag %d not pending in the device.\n",
5928 reg = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
5929 if (reg & (1 << tag)) {
5930 /* sleep for max. 200us to stabilize */
5931 usleep_range(100, 200);
5934 /* command completed already */
5935 dev_err(hba->dev, "%s: cmd at tag %d successfully cleared from DB.\n",
5940 "%s: no response from device. tag = %d, err %d\n",
5941 __func__, tag, err);
5943 err = resp; /* service response error */
5953 err = ufshcd_issue_tm_cmd(hba, lrbp->lun, lrbp->task_tag,
5954 UFS_ABORT_TASK, &resp);
5955 if (err || resp != UPIU_TASK_MANAGEMENT_FUNC_COMPL) {
5957 err = resp; /* service response error */
5958 dev_err(hba->dev, "%s: issued. tag = %d, err %d\n",
5959 __func__, tag, err);
5964 err = ufshcd_clear_cmd(hba, tag);
5966 dev_err(hba->dev, "%s: Failed clearing cmd at tag %d, err %d\n",
5967 __func__, tag, err);
5972 scsi_dma_unmap(cmd);
5974 spin_lock_irqsave(host->host_lock, flags);
5975 ufshcd_outstanding_req_clear(hba, tag);
5976 hba->lrb[tag].cmd = NULL;
5977 spin_unlock_irqrestore(host->host_lock, flags);
5979 clear_bit_unlock(tag, &hba->lrb_in_use);
5980 wake_up(&hba->dev_cmd.tag_wq);
5986 dev_err(hba->dev, "%s: failed with err %d\n", __func__, err);
5987 ufshcd_set_req_abort_skip(hba, hba->outstanding_reqs);
5992 * This ufshcd_release() corresponds to the original scsi cmd that got
5993 * aborted here (as we won't get any IRQ for it).
5995 ufshcd_release(hba);
6000 * ufshcd_host_reset_and_restore - reset and restore host controller
6001 * @hba: per-adapter instance
6003 * Note that host controller reset may issue DME_RESET to
6004 * local and remote (device) Uni-Pro stack and the attributes
6005 * are reset to default state.
6007 * Returns zero on success, non-zero on failure
6009 static int ufshcd_host_reset_and_restore(struct ufs_hba *hba)
6012 unsigned long flags;
6015 * Stop the host controller and complete the requests
6018 spin_lock_irqsave(hba->host->host_lock, flags);
6019 ufshcd_hba_stop(hba, false);
6020 hba->silence_err_logs = true;
6021 ufshcd_complete_requests(hba);
6022 hba->silence_err_logs = false;
6023 spin_unlock_irqrestore(hba->host->host_lock, flags);
6025 /* scale up clocks to max frequency before full reinitialization */
6026 ufshcd_scale_clks(hba, true);
6028 err = ufshcd_hba_enable(hba);
6032 /* Establish the link again and restore the device */
6033 err = ufshcd_probe_hba(hba);
6035 if (!err && (hba->ufshcd_state != UFSHCD_STATE_OPERATIONAL))
6039 dev_err(hba->dev, "%s: Host init failed %d\n", __func__, err);
6045 * ufshcd_reset_and_restore - reset and re-initialize host/device
6046 * @hba: per-adapter instance
6048 * Reset and recover device, host and re-establish link. This
6049 * is helpful to recover the communication in fatal error conditions.
6051 * Returns zero on success, non-zero on failure
6053 static int ufshcd_reset_and_restore(struct ufs_hba *hba)
6056 int retries = MAX_HOST_RESET_RETRIES;
6059 err = ufshcd_host_reset_and_restore(hba);
6060 } while (err && --retries);
6066 * ufshcd_eh_host_reset_handler - host reset handler registered to scsi layer
6067 * @cmd: SCSI command pointer
6069 * Returns SUCCESS/FAILED
6071 static int ufshcd_eh_host_reset_handler(struct scsi_cmnd *cmd)
6074 unsigned long flags;
6075 struct ufs_hba *hba;
6077 hba = shost_priv(cmd->device->host);
6079 ufshcd_hold(hba, false);
6081 * Check if there is any race with fatal error handling.
6082 * If so, wait for it to complete. Even though fatal error
6083 * handling does reset and restore in some cases, don't assume
6084 * anything out of it. We are just avoiding race here.
6087 spin_lock_irqsave(hba->host->host_lock, flags);
6088 if (!(work_pending(&hba->eh_work) ||
6089 hba->ufshcd_state == UFSHCD_STATE_RESET ||
6090 hba->ufshcd_state == UFSHCD_STATE_EH_SCHEDULED))
6092 spin_unlock_irqrestore(hba->host->host_lock, flags);
6093 dev_dbg(hba->dev, "%s: reset in progress\n", __func__);
6094 flush_work(&hba->eh_work);
6097 hba->ufshcd_state = UFSHCD_STATE_RESET;
6098 ufshcd_set_eh_in_progress(hba);
6099 spin_unlock_irqrestore(hba->host->host_lock, flags);
6101 err = ufshcd_reset_and_restore(hba);
6103 spin_lock_irqsave(hba->host->host_lock, flags);
6106 hba->ufshcd_state = UFSHCD_STATE_OPERATIONAL;
6109 hba->ufshcd_state = UFSHCD_STATE_ERROR;
6111 ufshcd_clear_eh_in_progress(hba);
6112 spin_unlock_irqrestore(hba->host->host_lock, flags);
6114 ufshcd_release(hba);
6119 * ufshcd_get_max_icc_level - calculate the ICC level
6120 * @sup_curr_uA: max. current supported by the regulator
6121 * @start_scan: row at the desc table to start scan from
6122 * @buff: power descriptor buffer
6124 * Returns calculated max ICC level for specific regulator
6126 static u32 ufshcd_get_max_icc_level(int sup_curr_uA, u32 start_scan, char *buff)
6133 for (i = start_scan; i >= 0; i--) {
6134 data = be16_to_cpup((__be16 *)&buff[2 * i]);
6135 unit = (data & ATTR_ICC_LVL_UNIT_MASK) >>
6136 ATTR_ICC_LVL_UNIT_OFFSET;
6137 curr_uA = data & ATTR_ICC_LVL_VALUE_MASK;
6139 case UFSHCD_NANO_AMP:
6140 curr_uA = curr_uA / 1000;
6142 case UFSHCD_MILI_AMP:
6143 curr_uA = curr_uA * 1000;
6146 curr_uA = curr_uA * 1000 * 1000;
6148 case UFSHCD_MICRO_AMP:
6152 if (sup_curr_uA >= curr_uA)
6157 pr_err("%s: Couldn't find valid icc_level = %d", __func__, i);
6164 * ufshcd_calc_icc_level - calculate the max ICC level
6165 * In case regulators are not initialized we'll return 0
6166 * @hba: per-adapter instance
6167 * @desc_buf: power descriptor buffer to extract ICC levels from.
6168 * @len: length of desc_buff
6170 * Returns calculated ICC level
6172 static u32 ufshcd_find_max_sup_active_icc_level(struct ufs_hba *hba,
6173 u8 *desc_buf, int len)
6177 if (!hba->vreg_info.vcc || !hba->vreg_info.vccq ||
6178 !hba->vreg_info.vccq2) {
6180 "%s: Regulator capability was not set, actvIccLevel=%d",
6181 __func__, icc_level);
6185 if (hba->vreg_info.vcc && hba->vreg_info.vcc->max_uA)
6186 icc_level = ufshcd_get_max_icc_level(
6187 hba->vreg_info.vcc->max_uA,
6188 POWER_DESC_MAX_ACTV_ICC_LVLS - 1,
6189 &desc_buf[PWR_DESC_ACTIVE_LVLS_VCC_0]);
6191 if (hba->vreg_info.vccq && hba->vreg_info.vccq->max_uA)
6192 icc_level = ufshcd_get_max_icc_level(
6193 hba->vreg_info.vccq->max_uA,
6195 &desc_buf[PWR_DESC_ACTIVE_LVLS_VCCQ_0]);
6197 if (hba->vreg_info.vccq2 && hba->vreg_info.vccq2->max_uA)
6198 icc_level = ufshcd_get_max_icc_level(
6199 hba->vreg_info.vccq2->max_uA,
6201 &desc_buf[PWR_DESC_ACTIVE_LVLS_VCCQ2_0]);
6206 static void ufshcd_init_icc_levels(struct ufs_hba *hba)
6209 int buff_len = hba->desc_size.pwr_desc;
6212 desc_buf = kmalloc(buff_len, GFP_KERNEL);
6216 ret = ufshcd_read_power_desc(hba, desc_buf, buff_len);
6219 "%s: Failed reading power descriptor.len = %d ret = %d",
6220 __func__, buff_len, ret);
6224 hba->init_prefetch_data.icc_level =
6225 ufshcd_find_max_sup_active_icc_level(hba,
6226 desc_buf, buff_len);
6227 dev_dbg(hba->dev, "%s: setting icc_level 0x%x",
6228 __func__, hba->init_prefetch_data.icc_level);
6230 ret = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_WRITE_ATTR,
6231 QUERY_ATTR_IDN_ACTIVE_ICC_LVL, 0, 0,
6232 &hba->init_prefetch_data.icc_level);
6236 "%s: Failed configuring bActiveICCLevel = %d ret = %d",
6237 __func__, hba->init_prefetch_data.icc_level , ret);
6244 * ufshcd_scsi_add_wlus - Adds required W-LUs
6245 * @hba: per-adapter instance
6247 * UFS device specification requires the UFS devices to support 4 well known
6249 * "REPORT_LUNS" (address: 01h)
6250 * "UFS Device" (address: 50h)
6251 * "RPMB" (address: 44h)
6252 * "BOOT" (address: 30h)
6253 * UFS device's power management needs to be controlled by "POWER CONDITION"
6254 * field of SSU (START STOP UNIT) command. But this "power condition" field
6255 * will take effect only when its sent to "UFS device" well known logical unit
6256 * hence we require the scsi_device instance to represent this logical unit in
6257 * order for the UFS host driver to send the SSU command for power management.
6259 * We also require the scsi_device instance for "RPMB" (Replay Protected Memory
6260 * Block) LU so user space process can control this LU. User space may also
6261 * want to have access to BOOT LU.
6263 * This function adds scsi device instances for each of all well known LUs
6264 * (except "REPORT LUNS" LU).
6266 * Returns zero on success (all required W-LUs are added successfully),
6267 * non-zero error value on failure (if failed to add any of the required W-LU).
6269 static int ufshcd_scsi_add_wlus(struct ufs_hba *hba)
6272 struct scsi_device *sdev_rpmb;
6273 struct scsi_device *sdev_boot;
6275 hba->sdev_ufs_device = __scsi_add_device(hba->host, 0, 0,
6276 ufshcd_upiu_wlun_to_scsi_wlun(UFS_UPIU_UFS_DEVICE_WLUN), NULL);
6277 if (IS_ERR(hba->sdev_ufs_device)) {
6278 ret = PTR_ERR(hba->sdev_ufs_device);
6279 hba->sdev_ufs_device = NULL;
6282 scsi_device_put(hba->sdev_ufs_device);
6284 sdev_rpmb = __scsi_add_device(hba->host, 0, 0,
6285 ufshcd_upiu_wlun_to_scsi_wlun(UFS_UPIU_RPMB_WLUN), NULL);
6286 if (IS_ERR(sdev_rpmb)) {
6287 ret = PTR_ERR(sdev_rpmb);
6288 goto remove_sdev_ufs_device;
6290 scsi_device_put(sdev_rpmb);
6292 sdev_boot = __scsi_add_device(hba->host, 0, 0,
6293 ufshcd_upiu_wlun_to_scsi_wlun(UFS_UPIU_BOOT_WLUN), NULL);
6294 if (IS_ERR(sdev_boot))
6295 dev_err(hba->dev, "%s: BOOT WLUN not found\n", __func__);
6297 scsi_device_put(sdev_boot);
6300 remove_sdev_ufs_device:
6301 scsi_remove_device(hba->sdev_ufs_device);
6306 static int ufs_get_device_desc(struct ufs_hba *hba,
6307 struct ufs_dev_desc *dev_desc)
6314 buff_len = max_t(size_t, hba->desc_size.dev_desc,
6315 QUERY_DESC_MAX_SIZE + 1);
6316 desc_buf = kmalloc(buff_len, GFP_KERNEL);
6322 err = ufshcd_read_device_desc(hba, desc_buf, hba->desc_size.dev_desc);
6324 dev_err(hba->dev, "%s: Failed reading Device Desc. err = %d\n",
6330 * getting vendor (manufacturerID) and Bank Index in big endian
6333 dev_desc->wmanufacturerid = desc_buf[DEVICE_DESC_PARAM_MANF_ID] << 8 |
6334 desc_buf[DEVICE_DESC_PARAM_MANF_ID + 1];
6336 model_index = desc_buf[DEVICE_DESC_PARAM_PRDCT_NAME];
6338 /* Zero-pad entire buffer for string termination. */
6339 memset(desc_buf, 0, buff_len);
6341 err = ufshcd_read_string_desc(hba, model_index, desc_buf,
6342 QUERY_DESC_MAX_SIZE, true/*ASCII*/);
6344 dev_err(hba->dev, "%s: Failed reading Product Name. err = %d\n",
6349 desc_buf[QUERY_DESC_MAX_SIZE] = '\0';
6350 strlcpy(dev_desc->model, (desc_buf + QUERY_DESC_HDR_SIZE),
6351 min_t(u8, desc_buf[QUERY_DESC_LENGTH_OFFSET],
6354 /* Null terminate the model string */
6355 dev_desc->model[MAX_MODEL_LEN] = '\0';
6362 static void ufs_fixup_device_setup(struct ufs_hba *hba,
6363 struct ufs_dev_desc *dev_desc)
6365 struct ufs_dev_fix *f;
6367 for (f = ufs_fixups; f->quirk; f++) {
6368 if ((f->card.wmanufacturerid == dev_desc->wmanufacturerid ||
6369 f->card.wmanufacturerid == UFS_ANY_VENDOR) &&
6370 (STR_PRFX_EQUAL(f->card.model, dev_desc->model) ||
6371 !strcmp(f->card.model, UFS_ANY_MODEL)))
6372 hba->dev_quirks |= f->quirk;
6377 * ufshcd_tune_pa_tactivate - Tunes PA_TActivate of local UniPro
6378 * @hba: per-adapter instance
6380 * PA_TActivate parameter can be tuned manually if UniPro version is less than
6381 * 1.61. PA_TActivate needs to be greater than or equal to peerM-PHY's
6382 * RX_MIN_ACTIVATETIME_CAPABILITY attribute. This optimal value can help reduce
6383 * the hibern8 exit latency.
6385 * Returns zero on success, non-zero error value on failure.
6387 static int ufshcd_tune_pa_tactivate(struct ufs_hba *hba)
6390 u32 peer_rx_min_activatetime = 0, tuned_pa_tactivate;
6392 ret = ufshcd_dme_peer_get(hba,
6394 RX_MIN_ACTIVATETIME_CAPABILITY,
6395 UIC_ARG_MPHY_RX_GEN_SEL_INDEX(0)),
6396 &peer_rx_min_activatetime);
6400 /* make sure proper unit conversion is applied */
6401 tuned_pa_tactivate =
6402 ((peer_rx_min_activatetime * RX_MIN_ACTIVATETIME_UNIT_US)
6403 / PA_TACTIVATE_TIME_UNIT_US);
6404 ret = ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TACTIVATE),
6405 tuned_pa_tactivate);
6412 * ufshcd_tune_pa_hibern8time - Tunes PA_Hibern8Time of local UniPro
6413 * @hba: per-adapter instance
6415 * PA_Hibern8Time parameter can be tuned manually if UniPro version is less than
6416 * 1.61. PA_Hibern8Time needs to be maximum of local M-PHY's
6417 * TX_HIBERN8TIME_CAPABILITY & peer M-PHY's RX_HIBERN8TIME_CAPABILITY.
6418 * This optimal value can help reduce the hibern8 exit latency.
6420 * Returns zero on success, non-zero error value on failure.
6422 static int ufshcd_tune_pa_hibern8time(struct ufs_hba *hba)
6425 u32 local_tx_hibern8_time_cap = 0, peer_rx_hibern8_time_cap = 0;
6426 u32 max_hibern8_time, tuned_pa_hibern8time;
6428 ret = ufshcd_dme_get(hba,
6429 UIC_ARG_MIB_SEL(TX_HIBERN8TIME_CAPABILITY,
6430 UIC_ARG_MPHY_TX_GEN_SEL_INDEX(0)),
6431 &local_tx_hibern8_time_cap);
6435 ret = ufshcd_dme_peer_get(hba,
6436 UIC_ARG_MIB_SEL(RX_HIBERN8TIME_CAPABILITY,
6437 UIC_ARG_MPHY_RX_GEN_SEL_INDEX(0)),
6438 &peer_rx_hibern8_time_cap);
6442 max_hibern8_time = max(local_tx_hibern8_time_cap,
6443 peer_rx_hibern8_time_cap);
6444 /* make sure proper unit conversion is applied */
6445 tuned_pa_hibern8time = ((max_hibern8_time * HIBERN8TIME_UNIT_US)
6446 / PA_HIBERN8_TIME_UNIT_US);
6447 ret = ufshcd_dme_set(hba, UIC_ARG_MIB(PA_HIBERN8TIME),
6448 tuned_pa_hibern8time);
6454 * ufshcd_quirk_tune_host_pa_tactivate - Ensures that host PA_TACTIVATE is
6455 * less than device PA_TACTIVATE time.
6456 * @hba: per-adapter instance
6458 * Some UFS devices require host PA_TACTIVATE to be lower than device
6459 * PA_TACTIVATE, we need to enable UFS_DEVICE_QUIRK_HOST_PA_TACTIVATE quirk
6462 * Returns zero on success, non-zero error value on failure.
6464 static int ufshcd_quirk_tune_host_pa_tactivate(struct ufs_hba *hba)
6467 u32 granularity, peer_granularity;
6468 u32 pa_tactivate, peer_pa_tactivate;
6469 u32 pa_tactivate_us, peer_pa_tactivate_us;
6470 u8 gran_to_us_table[] = {1, 4, 8, 16, 32, 100};
6472 ret = ufshcd_dme_get(hba, UIC_ARG_MIB(PA_GRANULARITY),
6477 ret = ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_GRANULARITY),
6482 if ((granularity < PA_GRANULARITY_MIN_VAL) ||
6483 (granularity > PA_GRANULARITY_MAX_VAL)) {
6484 dev_err(hba->dev, "%s: invalid host PA_GRANULARITY %d",
6485 __func__, granularity);
6489 if ((peer_granularity < PA_GRANULARITY_MIN_VAL) ||
6490 (peer_granularity > PA_GRANULARITY_MAX_VAL)) {
6491 dev_err(hba->dev, "%s: invalid device PA_GRANULARITY %d",
6492 __func__, peer_granularity);
6496 ret = ufshcd_dme_get(hba, UIC_ARG_MIB(PA_TACTIVATE), &pa_tactivate);
6500 ret = ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_TACTIVATE),
6501 &peer_pa_tactivate);
6505 pa_tactivate_us = pa_tactivate * gran_to_us_table[granularity - 1];
6506 peer_pa_tactivate_us = peer_pa_tactivate *
6507 gran_to_us_table[peer_granularity - 1];
6509 if (pa_tactivate_us > peer_pa_tactivate_us) {
6510 u32 new_peer_pa_tactivate;
6512 new_peer_pa_tactivate = pa_tactivate_us /
6513 gran_to_us_table[peer_granularity - 1];
6514 new_peer_pa_tactivate++;
6515 ret = ufshcd_dme_peer_set(hba, UIC_ARG_MIB(PA_TACTIVATE),
6516 new_peer_pa_tactivate);
6523 static void ufshcd_tune_unipro_params(struct ufs_hba *hba)
6525 if (ufshcd_is_unipro_pa_params_tuning_req(hba)) {
6526 ufshcd_tune_pa_tactivate(hba);
6527 ufshcd_tune_pa_hibern8time(hba);
6530 if (hba->dev_quirks & UFS_DEVICE_QUIRK_PA_TACTIVATE)
6531 /* set 1ms timeout for PA_TACTIVATE */
6532 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TACTIVATE), 10);
6534 if (hba->dev_quirks & UFS_DEVICE_QUIRK_HOST_PA_TACTIVATE)
6535 ufshcd_quirk_tune_host_pa_tactivate(hba);
6537 ufshcd_vops_apply_dev_quirks(hba);
6540 static void ufshcd_clear_dbg_ufs_stats(struct ufs_hba *hba)
6542 int err_reg_hist_size = sizeof(struct ufs_uic_err_reg_hist);
6544 hba->ufs_stats.hibern8_exit_cnt = 0;
6545 hba->ufs_stats.last_hibern8_exit_tstamp = ktime_set(0, 0);
6547 memset(&hba->ufs_stats.pa_err, 0, err_reg_hist_size);
6548 memset(&hba->ufs_stats.dl_err, 0, err_reg_hist_size);
6549 memset(&hba->ufs_stats.nl_err, 0, err_reg_hist_size);
6550 memset(&hba->ufs_stats.tl_err, 0, err_reg_hist_size);
6551 memset(&hba->ufs_stats.dme_err, 0, err_reg_hist_size);
6553 hba->req_abort_count = 0;
6556 static void ufshcd_init_desc_sizes(struct ufs_hba *hba)
6560 err = ufshcd_read_desc_length(hba, QUERY_DESC_IDN_DEVICE, 0,
6561 &hba->desc_size.dev_desc);
6563 hba->desc_size.dev_desc = QUERY_DESC_DEVICE_DEF_SIZE;
6565 err = ufshcd_read_desc_length(hba, QUERY_DESC_IDN_POWER, 0,
6566 &hba->desc_size.pwr_desc);
6568 hba->desc_size.pwr_desc = QUERY_DESC_POWER_DEF_SIZE;
6570 err = ufshcd_read_desc_length(hba, QUERY_DESC_IDN_INTERCONNECT, 0,
6571 &hba->desc_size.interc_desc);
6573 hba->desc_size.interc_desc = QUERY_DESC_INTERCONNECT_DEF_SIZE;
6575 err = ufshcd_read_desc_length(hba, QUERY_DESC_IDN_CONFIGURATION, 0,
6576 &hba->desc_size.conf_desc);
6578 hba->desc_size.conf_desc = QUERY_DESC_CONFIGURATION_DEF_SIZE;
6580 err = ufshcd_read_desc_length(hba, QUERY_DESC_IDN_UNIT, 0,
6581 &hba->desc_size.unit_desc);
6583 hba->desc_size.unit_desc = QUERY_DESC_UNIT_DEF_SIZE;
6585 err = ufshcd_read_desc_length(hba, QUERY_DESC_IDN_GEOMETRY, 0,
6586 &hba->desc_size.geom_desc);
6588 hba->desc_size.geom_desc = QUERY_DESC_GEOMETRY_DEF_SIZE;
6589 err = ufshcd_read_desc_length(hba, QUERY_DESC_IDN_HEALTH, 0,
6590 &hba->desc_size.hlth_desc);
6592 hba->desc_size.hlth_desc = QUERY_DESC_HEALTH_DEF_SIZE;
6595 static void ufshcd_def_desc_sizes(struct ufs_hba *hba)
6597 hba->desc_size.dev_desc = QUERY_DESC_DEVICE_DEF_SIZE;
6598 hba->desc_size.pwr_desc = QUERY_DESC_POWER_DEF_SIZE;
6599 hba->desc_size.interc_desc = QUERY_DESC_INTERCONNECT_DEF_SIZE;
6600 hba->desc_size.conf_desc = QUERY_DESC_CONFIGURATION_DEF_SIZE;
6601 hba->desc_size.unit_desc = QUERY_DESC_UNIT_DEF_SIZE;
6602 hba->desc_size.geom_desc = QUERY_DESC_GEOMETRY_DEF_SIZE;
6603 hba->desc_size.hlth_desc = QUERY_DESC_HEALTH_DEF_SIZE;
6607 * ufshcd_probe_hba - probe hba to detect device and initialize
6608 * @hba: per-adapter instance
6610 * Execute link-startup and verify device initialization
6612 static int ufshcd_probe_hba(struct ufs_hba *hba)
6614 struct ufs_dev_desc card = {0};
6616 ktime_t start = ktime_get();
6618 ret = ufshcd_link_startup(hba);
6622 /* set the default level for urgent bkops */
6623 hba->urgent_bkops_lvl = BKOPS_STATUS_PERF_IMPACT;
6624 hba->is_urgent_bkops_lvl_checked = false;
6626 /* Debug counters initialization */
6627 ufshcd_clear_dbg_ufs_stats(hba);
6629 /* UniPro link is active now */
6630 ufshcd_set_link_active(hba);
6632 /* Enable Auto-Hibernate if configured */
6633 ufshcd_auto_hibern8_enable(hba);
6635 ret = ufshcd_verify_dev_init(hba);
6639 ret = ufshcd_complete_dev_init(hba);
6643 /* Init check for device descriptor sizes */
6644 ufshcd_init_desc_sizes(hba);
6646 ret = ufs_get_device_desc(hba, &card);
6648 dev_err(hba->dev, "%s: Failed getting device info. err = %d\n",
6653 ufs_fixup_device_setup(hba, &card);
6654 ufshcd_tune_unipro_params(hba);
6656 ret = ufshcd_set_vccq_rail_unused(hba,
6657 (hba->dev_quirks & UFS_DEVICE_NO_VCCQ) ? true : false);
6661 /* UFS device is also active now */
6662 ufshcd_set_ufs_dev_active(hba);
6663 ufshcd_force_reset_auto_bkops(hba);
6664 hba->wlun_dev_clr_ua = true;
6666 if (ufshcd_get_max_pwr_mode(hba)) {
6668 "%s: Failed getting max supported power mode\n",
6671 ret = ufshcd_config_pwr_mode(hba, &hba->max_pwr_info.info);
6673 dev_err(hba->dev, "%s: Failed setting power mode, err = %d\n",
6679 /* set the state as operational after switching to desired gear */
6680 hba->ufshcd_state = UFSHCD_STATE_OPERATIONAL;
6683 * If we are in error handling context or in power management callbacks
6684 * context, no need to scan the host
6686 if (!ufshcd_eh_in_progress(hba) && !hba->pm_op_in_progress) {
6689 /* clear any previous UFS device information */
6690 memset(&hba->dev_info, 0, sizeof(hba->dev_info));
6691 if (!ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_READ_FLAG,
6692 QUERY_FLAG_IDN_PWR_ON_WPE, &flag))
6693 hba->dev_info.f_power_on_wp_en = flag;
6695 if (!hba->is_init_prefetch)
6696 ufshcd_init_icc_levels(hba);
6698 /* Add required well known logical units to scsi mid layer */
6699 ret = ufshcd_scsi_add_wlus(hba);
6703 /* Initialize devfreq after UFS device is detected */
6704 if (ufshcd_is_clkscaling_supported(hba)) {
6705 memcpy(&hba->clk_scaling.saved_pwr_info.info,
6707 sizeof(struct ufs_pa_layer_attr));
6708 hba->clk_scaling.saved_pwr_info.is_valid = true;
6709 if (!hba->devfreq) {
6710 ret = ufshcd_devfreq_init(hba);
6714 hba->clk_scaling.is_allowed = true;
6717 scsi_scan_host(hba->host);
6718 pm_runtime_put_sync(hba->dev);
6721 if (!hba->is_init_prefetch)
6722 hba->is_init_prefetch = true;
6726 * If we failed to initialize the device or the device is not
6727 * present, turn off the power/clocks etc.
6729 if (ret && !ufshcd_eh_in_progress(hba) && !hba->pm_op_in_progress) {
6730 pm_runtime_put_sync(hba->dev);
6731 ufshcd_exit_clk_scaling(hba);
6732 ufshcd_hba_exit(hba);
6735 trace_ufshcd_init(dev_name(hba->dev), ret,
6736 ktime_to_us(ktime_sub(ktime_get(), start)),
6737 hba->curr_dev_pwr_mode, hba->uic_link_state);
6742 * ufshcd_async_scan - asynchronous execution for probing hba
6743 * @data: data pointer to pass to this function
6744 * @cookie: cookie data
6746 static void ufshcd_async_scan(void *data, async_cookie_t cookie)
6748 struct ufs_hba *hba = (struct ufs_hba *)data;
6750 ufshcd_probe_hba(hba);
6753 static enum blk_eh_timer_return ufshcd_eh_timed_out(struct scsi_cmnd *scmd)
6755 unsigned long flags;
6756 struct Scsi_Host *host;
6757 struct ufs_hba *hba;
6761 if (!scmd || !scmd->device || !scmd->device->host)
6764 host = scmd->device->host;
6765 hba = shost_priv(host);
6769 spin_lock_irqsave(host->host_lock, flags);
6771 for_each_set_bit(index, &hba->outstanding_reqs, hba->nutrs) {
6772 if (hba->lrb[index].cmd == scmd) {
6778 spin_unlock_irqrestore(host->host_lock, flags);
6781 * Bypass SCSI error handling and reset the block layer timer if this
6782 * SCSI command was not actually dispatched to UFS driver, otherwise
6783 * let SCSI layer handle the error as usual.
6785 return found ? BLK_EH_DONE : BLK_EH_RESET_TIMER;
6788 static const struct attribute_group *ufshcd_driver_groups[] = {
6789 &ufs_sysfs_unit_descriptor_group,
6790 &ufs_sysfs_lun_attributes_group,
6794 static struct scsi_host_template ufshcd_driver_template = {
6795 .module = THIS_MODULE,
6797 .proc_name = UFSHCD,
6798 .queuecommand = ufshcd_queuecommand,
6799 .slave_alloc = ufshcd_slave_alloc,
6800 .slave_configure = ufshcd_slave_configure,
6801 .slave_destroy = ufshcd_slave_destroy,
6802 .change_queue_depth = ufshcd_change_queue_depth,
6803 .eh_abort_handler = ufshcd_abort,
6804 .eh_device_reset_handler = ufshcd_eh_device_reset_handler,
6805 .eh_host_reset_handler = ufshcd_eh_host_reset_handler,
6806 .eh_timed_out = ufshcd_eh_timed_out,
6808 .sg_tablesize = SG_ALL,
6809 .cmd_per_lun = UFSHCD_CMD_PER_LUN,
6810 .can_queue = UFSHCD_CAN_QUEUE,
6811 .max_host_blocked = 1,
6812 .track_queue_depth = 1,
6813 .sdev_groups = ufshcd_driver_groups,
6816 static int ufshcd_config_vreg_load(struct device *dev, struct ufs_vreg *vreg,
6825 * "set_load" operation shall be required on those regulators
6826 * which specifically configured current limitation. Otherwise
6827 * zero max_uA may cause unexpected behavior when regulator is
6828 * enabled or set as high power mode.
6833 ret = regulator_set_load(vreg->reg, ua);
6835 dev_err(dev, "%s: %s set load (ua=%d) failed, err=%d\n",
6836 __func__, vreg->name, ua, ret);
6842 static inline int ufshcd_config_vreg_lpm(struct ufs_hba *hba,
6843 struct ufs_vreg *vreg)
6847 else if (vreg->unused)
6850 return ufshcd_config_vreg_load(hba->dev, vreg,
6851 UFS_VREG_LPM_LOAD_UA);
6854 static inline int ufshcd_config_vreg_hpm(struct ufs_hba *hba,
6855 struct ufs_vreg *vreg)
6859 else if (vreg->unused)
6862 return ufshcd_config_vreg_load(hba->dev, vreg, vreg->max_uA);
6865 static int ufshcd_config_vreg(struct device *dev,
6866 struct ufs_vreg *vreg, bool on)
6869 struct regulator *reg;
6871 int min_uV, uA_load;
6878 if (regulator_count_voltages(reg) > 0) {
6879 if (vreg->min_uV && vreg->max_uV) {
6880 min_uV = on ? vreg->min_uV : 0;
6881 ret = regulator_set_voltage(reg, min_uV, vreg->max_uV);
6884 "%s: %s set voltage failed, err=%d\n",
6885 __func__, name, ret);
6890 uA_load = on ? vreg->max_uA : 0;
6891 ret = ufshcd_config_vreg_load(dev, vreg, uA_load);
6899 static int ufshcd_enable_vreg(struct device *dev, struct ufs_vreg *vreg)
6905 else if (vreg->enabled || vreg->unused)
6908 ret = ufshcd_config_vreg(dev, vreg, true);
6910 ret = regulator_enable(vreg->reg);
6913 vreg->enabled = true;
6915 dev_err(dev, "%s: %s enable failed, err=%d\n",
6916 __func__, vreg->name, ret);
6921 static int ufshcd_disable_vreg(struct device *dev, struct ufs_vreg *vreg)
6927 else if (!vreg->enabled || vreg->unused)
6930 ret = regulator_disable(vreg->reg);
6933 /* ignore errors on applying disable config */
6934 ufshcd_config_vreg(dev, vreg, false);
6935 vreg->enabled = false;
6937 dev_err(dev, "%s: %s disable failed, err=%d\n",
6938 __func__, vreg->name, ret);
6944 static int ufshcd_setup_vreg(struct ufs_hba *hba, bool on)
6947 struct device *dev = hba->dev;
6948 struct ufs_vreg_info *info = &hba->vreg_info;
6953 ret = ufshcd_toggle_vreg(dev, info->vcc, on);
6957 ret = ufshcd_toggle_vreg(dev, info->vccq, on);
6961 ret = ufshcd_toggle_vreg(dev, info->vccq2, on);
6967 ufshcd_toggle_vreg(dev, info->vccq2, false);
6968 ufshcd_toggle_vreg(dev, info->vccq, false);
6969 ufshcd_toggle_vreg(dev, info->vcc, false);
6974 static int ufshcd_setup_hba_vreg(struct ufs_hba *hba, bool on)
6976 struct ufs_vreg_info *info = &hba->vreg_info;
6979 return ufshcd_toggle_vreg(hba->dev, info->vdd_hba, on);
6984 static int ufshcd_get_vreg(struct device *dev, struct ufs_vreg *vreg)
6991 vreg->reg = devm_regulator_get(dev, vreg->name);
6992 if (IS_ERR(vreg->reg)) {
6993 ret = PTR_ERR(vreg->reg);
6994 dev_err(dev, "%s: %s get failed, err=%d\n",
6995 __func__, vreg->name, ret);
7001 static int ufshcd_init_vreg(struct ufs_hba *hba)
7004 struct device *dev = hba->dev;
7005 struct ufs_vreg_info *info = &hba->vreg_info;
7010 ret = ufshcd_get_vreg(dev, info->vcc);
7014 ret = ufshcd_get_vreg(dev, info->vccq);
7018 ret = ufshcd_get_vreg(dev, info->vccq2);
7023 static int ufshcd_init_hba_vreg(struct ufs_hba *hba)
7025 struct ufs_vreg_info *info = &hba->vreg_info;
7028 return ufshcd_get_vreg(hba->dev, info->vdd_hba);
7033 static int ufshcd_set_vccq_rail_unused(struct ufs_hba *hba, bool unused)
7036 struct ufs_vreg_info *info = &hba->vreg_info;
7040 else if (!info->vccq)
7044 /* shut off the rail here */
7045 ret = ufshcd_toggle_vreg(hba->dev, info->vccq, false);
7047 * Mark this rail as no longer used, so it doesn't get enabled
7051 info->vccq->unused = true;
7054 * rail should have been already enabled hence just make sure
7055 * that unused flag is cleared.
7057 info->vccq->unused = false;
7063 static int __ufshcd_setup_clocks(struct ufs_hba *hba, bool on,
7067 struct ufs_clk_info *clki;
7068 struct list_head *head = &hba->clk_list_head;
7069 unsigned long flags;
7070 ktime_t start = ktime_get();
7071 bool clk_state_changed = false;
7073 if (list_empty(head))
7077 * vendor specific setup_clocks ops may depend on clocks managed by
7078 * this standard driver hence call the vendor specific setup_clocks
7079 * before disabling the clocks managed here.
7082 ret = ufshcd_vops_setup_clocks(hba, on, PRE_CHANGE);
7087 list_for_each_entry(clki, head, list) {
7088 if (!IS_ERR_OR_NULL(clki->clk)) {
7089 if (skip_ref_clk && !strcmp(clki->name, "ref_clk"))
7092 clk_state_changed = on ^ clki->enabled;
7093 if (on && !clki->enabled) {
7094 ret = clk_prepare_enable(clki->clk);
7096 dev_err(hba->dev, "%s: %s prepare enable failed, %d\n",
7097 __func__, clki->name, ret);
7100 } else if (!on && clki->enabled) {
7101 clk_disable_unprepare(clki->clk);
7104 dev_dbg(hba->dev, "%s: clk: %s %sabled\n", __func__,
7105 clki->name, on ? "en" : "dis");
7110 * vendor specific setup_clocks ops may depend on clocks managed by
7111 * this standard driver hence call the vendor specific setup_clocks
7112 * after enabling the clocks managed here.
7115 ret = ufshcd_vops_setup_clocks(hba, on, POST_CHANGE);
7122 list_for_each_entry(clki, head, list) {
7123 if (!IS_ERR_OR_NULL(clki->clk) && clki->enabled)
7124 clk_disable_unprepare(clki->clk);
7126 } else if (!ret && on) {
7127 spin_lock_irqsave(hba->host->host_lock, flags);
7128 hba->clk_gating.state = CLKS_ON;
7129 trace_ufshcd_clk_gating(dev_name(hba->dev),
7130 hba->clk_gating.state);
7131 spin_unlock_irqrestore(hba->host->host_lock, flags);
7134 if (clk_state_changed)
7135 trace_ufshcd_profile_clk_gating(dev_name(hba->dev),
7136 (on ? "on" : "off"),
7137 ktime_to_us(ktime_sub(ktime_get(), start)), ret);
7141 static int ufshcd_setup_clocks(struct ufs_hba *hba, bool on)
7143 return __ufshcd_setup_clocks(hba, on, false);
7146 static int ufshcd_init_clocks(struct ufs_hba *hba)
7149 struct ufs_clk_info *clki;
7150 struct device *dev = hba->dev;
7151 struct list_head *head = &hba->clk_list_head;
7153 if (list_empty(head))
7156 list_for_each_entry(clki, head, list) {
7160 clki->clk = devm_clk_get(dev, clki->name);
7161 if (IS_ERR(clki->clk)) {
7162 ret = PTR_ERR(clki->clk);
7163 dev_err(dev, "%s: %s clk get failed, %d\n",
7164 __func__, clki->name, ret);
7168 if (clki->max_freq) {
7169 ret = clk_set_rate(clki->clk, clki->max_freq);
7171 dev_err(hba->dev, "%s: %s clk set rate(%dHz) failed, %d\n",
7172 __func__, clki->name,
7173 clki->max_freq, ret);
7176 clki->curr_freq = clki->max_freq;
7178 dev_dbg(dev, "%s: clk: %s, rate: %lu\n", __func__,
7179 clki->name, clk_get_rate(clki->clk));
7185 static int ufshcd_variant_hba_init(struct ufs_hba *hba)
7192 err = ufshcd_vops_init(hba);
7196 err = ufshcd_vops_setup_regulators(hba, true);
7203 ufshcd_vops_exit(hba);
7206 dev_err(hba->dev, "%s: variant %s init failed err %d\n",
7207 __func__, ufshcd_get_var_name(hba), err);
7211 static void ufshcd_variant_hba_exit(struct ufs_hba *hba)
7216 ufshcd_vops_setup_regulators(hba, false);
7218 ufshcd_vops_exit(hba);
7221 static int ufshcd_hba_init(struct ufs_hba *hba)
7226 * Handle host controller power separately from the UFS device power
7227 * rails as it will help controlling the UFS host controller power
7228 * collapse easily which is different than UFS device power collapse.
7229 * Also, enable the host controller power before we go ahead with rest
7230 * of the initialization here.
7232 err = ufshcd_init_hba_vreg(hba);
7236 err = ufshcd_setup_hba_vreg(hba, true);
7240 err = ufshcd_init_clocks(hba);
7242 goto out_disable_hba_vreg;
7244 err = ufshcd_setup_clocks(hba, true);
7246 goto out_disable_hba_vreg;
7248 err = ufshcd_init_vreg(hba);
7250 goto out_disable_clks;
7252 err = ufshcd_setup_vreg(hba, true);
7254 goto out_disable_clks;
7256 err = ufshcd_variant_hba_init(hba);
7258 goto out_disable_vreg;
7260 hba->is_powered = true;
7264 ufshcd_setup_vreg(hba, false);
7266 ufshcd_setup_clocks(hba, false);
7267 out_disable_hba_vreg:
7268 ufshcd_setup_hba_vreg(hba, false);
7273 static void ufshcd_hba_exit(struct ufs_hba *hba)
7275 if (hba->is_powered) {
7276 ufshcd_variant_hba_exit(hba);
7277 ufshcd_setup_vreg(hba, false);
7278 ufshcd_suspend_clkscaling(hba);
7279 if (ufshcd_is_clkscaling_supported(hba))
7281 ufshcd_suspend_clkscaling(hba);
7282 ufshcd_setup_clocks(hba, false);
7283 ufshcd_setup_hba_vreg(hba, false);
7284 hba->is_powered = false;
7289 ufshcd_send_request_sense(struct ufs_hba *hba, struct scsi_device *sdp)
7291 unsigned char cmd[6] = {REQUEST_SENSE,
7295 UFSHCD_REQ_SENSE_SIZE,
7300 buffer = kzalloc(UFSHCD_REQ_SENSE_SIZE, GFP_KERNEL);
7306 ret = scsi_execute(sdp, cmd, DMA_FROM_DEVICE, buffer,
7307 UFSHCD_REQ_SENSE_SIZE, NULL, NULL,
7308 msecs_to_jiffies(1000), 3, 0, RQF_PM, NULL);
7310 pr_err("%s: failed with err %d\n", __func__, ret);
7318 * ufshcd_set_dev_pwr_mode - sends START STOP UNIT command to set device
7320 * @hba: per adapter instance
7321 * @pwr_mode: device power mode to set
7323 * Returns 0 if requested power mode is set successfully
7324 * Returns non-zero if failed to set the requested power mode
7326 static int ufshcd_set_dev_pwr_mode(struct ufs_hba *hba,
7327 enum ufs_dev_pwr_mode pwr_mode)
7329 unsigned char cmd[6] = { START_STOP };
7330 struct scsi_sense_hdr sshdr;
7331 struct scsi_device *sdp;
7332 unsigned long flags;
7335 spin_lock_irqsave(hba->host->host_lock, flags);
7336 sdp = hba->sdev_ufs_device;
7338 ret = scsi_device_get(sdp);
7339 if (!ret && !scsi_device_online(sdp)) {
7341 scsi_device_put(sdp);
7346 spin_unlock_irqrestore(hba->host->host_lock, flags);
7352 * If scsi commands fail, the scsi mid-layer schedules scsi error-
7353 * handling, which would wait for host to be resumed. Since we know
7354 * we are functional while we are here, skip host resume in error
7357 hba->host->eh_noresume = 1;
7358 if (hba->wlun_dev_clr_ua) {
7359 ret = ufshcd_send_request_sense(hba, sdp);
7362 /* Unit attention condition is cleared now */
7363 hba->wlun_dev_clr_ua = false;
7366 cmd[4] = pwr_mode << 4;
7369 * Current function would be generally called from the power management
7370 * callbacks hence set the RQF_PM flag so that it doesn't resume the
7371 * already suspended childs.
7373 ret = scsi_execute(sdp, cmd, DMA_NONE, NULL, 0, NULL, &sshdr,
7374 START_STOP_TIMEOUT, 0, 0, RQF_PM, NULL);
7376 sdev_printk(KERN_WARNING, sdp,
7377 "START_STOP failed for power mode: %d, result %x\n",
7379 if (driver_byte(ret) == DRIVER_SENSE)
7380 scsi_print_sense_hdr(sdp, NULL, &sshdr);
7384 hba->curr_dev_pwr_mode = pwr_mode;
7386 scsi_device_put(sdp);
7387 hba->host->eh_noresume = 0;
7391 static int ufshcd_link_state_transition(struct ufs_hba *hba,
7392 enum uic_link_state req_link_state,
7393 int check_for_bkops)
7397 if (req_link_state == hba->uic_link_state)
7400 if (req_link_state == UIC_LINK_HIBERN8_STATE) {
7401 ret = ufshcd_uic_hibern8_enter(hba);
7403 ufshcd_set_link_hibern8(hba);
7408 * If autobkops is enabled, link can't be turned off because
7409 * turning off the link would also turn off the device.
7411 else if ((req_link_state == UIC_LINK_OFF_STATE) &&
7412 (!check_for_bkops || (check_for_bkops &&
7413 !hba->auto_bkops_enabled))) {
7415 * Let's make sure that link is in low power mode, we are doing
7416 * this currently by putting the link in Hibern8. Otherway to
7417 * put the link in low power mode is to send the DME end point
7418 * to device and then send the DME reset command to local
7419 * unipro. But putting the link in hibern8 is much faster.
7421 ret = ufshcd_uic_hibern8_enter(hba);
7425 * Change controller state to "reset state" which
7426 * should also put the link in off/reset state
7428 ufshcd_hba_stop(hba, true);
7430 * TODO: Check if we need any delay to make sure that
7431 * controller is reset
7433 ufshcd_set_link_off(hba);
7440 static void ufshcd_vreg_set_lpm(struct ufs_hba *hba)
7443 * It seems some UFS devices may keep drawing more than sleep current
7444 * (atleast for 500us) from UFS rails (especially from VCCQ rail).
7445 * To avoid this situation, add 2ms delay before putting these UFS
7446 * rails in LPM mode.
7448 if (!ufshcd_is_link_active(hba) &&
7449 hba->dev_quirks & UFS_DEVICE_QUIRK_DELAY_BEFORE_LPM)
7450 usleep_range(2000, 2100);
7453 * If UFS device is either in UFS_Sleep turn off VCC rail to save some
7456 * If UFS device and link is in OFF state, all power supplies (VCC,
7457 * VCCQ, VCCQ2) can be turned off if power on write protect is not
7458 * required. If UFS link is inactive (Hibern8 or OFF state) and device
7459 * is in sleep state, put VCCQ & VCCQ2 rails in LPM mode.
7461 * Ignore the error returned by ufshcd_toggle_vreg() as device is anyway
7462 * in low power state which would save some power.
7464 if (ufshcd_is_ufs_dev_poweroff(hba) && ufshcd_is_link_off(hba) &&
7465 !hba->dev_info.is_lu_power_on_wp) {
7466 ufshcd_setup_vreg(hba, false);
7467 } else if (!ufshcd_is_ufs_dev_active(hba)) {
7468 ufshcd_toggle_vreg(hba->dev, hba->vreg_info.vcc, false);
7469 if (!ufshcd_is_link_active(hba)) {
7470 ufshcd_config_vreg_lpm(hba, hba->vreg_info.vccq);
7471 ufshcd_config_vreg_lpm(hba, hba->vreg_info.vccq2);
7476 static int ufshcd_vreg_set_hpm(struct ufs_hba *hba)
7480 if (ufshcd_is_ufs_dev_poweroff(hba) && ufshcd_is_link_off(hba) &&
7481 !hba->dev_info.is_lu_power_on_wp) {
7482 ret = ufshcd_setup_vreg(hba, true);
7483 } else if (!ufshcd_is_ufs_dev_active(hba)) {
7484 if (!ret && !ufshcd_is_link_active(hba)) {
7485 ret = ufshcd_config_vreg_hpm(hba, hba->vreg_info.vccq);
7488 ret = ufshcd_config_vreg_hpm(hba, hba->vreg_info.vccq2);
7492 ret = ufshcd_toggle_vreg(hba->dev, hba->vreg_info.vcc, true);
7497 ufshcd_config_vreg_lpm(hba, hba->vreg_info.vccq);
7499 ufshcd_toggle_vreg(hba->dev, hba->vreg_info.vcc, false);
7504 static void ufshcd_hba_vreg_set_lpm(struct ufs_hba *hba)
7506 if (ufshcd_is_link_off(hba))
7507 ufshcd_setup_hba_vreg(hba, false);
7510 static void ufshcd_hba_vreg_set_hpm(struct ufs_hba *hba)
7512 if (ufshcd_is_link_off(hba))
7513 ufshcd_setup_hba_vreg(hba, true);
7517 * ufshcd_suspend - helper function for suspend operations
7518 * @hba: per adapter instance
7519 * @pm_op: desired low power operation type
7521 * This function will try to put the UFS device and link into low power
7522 * mode based on the "rpm_lvl" (Runtime PM level) or "spm_lvl"
7523 * (System PM level).
7525 * If this function is called during shutdown, it will make sure that
7526 * both UFS device and UFS link is powered off.
7528 * NOTE: UFS device & link must be active before we enter in this function.
7530 * Returns 0 for success and non-zero for failure
7532 static int ufshcd_suspend(struct ufs_hba *hba, enum ufs_pm_op pm_op)
7535 enum ufs_pm_level pm_lvl;
7536 enum ufs_dev_pwr_mode req_dev_pwr_mode;
7537 enum uic_link_state req_link_state;
7539 hba->pm_op_in_progress = 1;
7540 if (!ufshcd_is_shutdown_pm(pm_op)) {
7541 pm_lvl = ufshcd_is_runtime_pm(pm_op) ?
7542 hba->rpm_lvl : hba->spm_lvl;
7543 req_dev_pwr_mode = ufs_get_pm_lvl_to_dev_pwr_mode(pm_lvl);
7544 req_link_state = ufs_get_pm_lvl_to_link_pwr_state(pm_lvl);
7546 req_dev_pwr_mode = UFS_POWERDOWN_PWR_MODE;
7547 req_link_state = UIC_LINK_OFF_STATE;
7551 * If we can't transition into any of the low power modes
7552 * just gate the clocks.
7554 ufshcd_hold(hba, false);
7555 hba->clk_gating.is_suspended = true;
7557 if (hba->clk_scaling.is_allowed) {
7558 cancel_work_sync(&hba->clk_scaling.suspend_work);
7559 cancel_work_sync(&hba->clk_scaling.resume_work);
7560 ufshcd_suspend_clkscaling(hba);
7563 if (req_dev_pwr_mode == UFS_ACTIVE_PWR_MODE &&
7564 req_link_state == UIC_LINK_ACTIVE_STATE) {
7568 if ((req_dev_pwr_mode == hba->curr_dev_pwr_mode) &&
7569 (req_link_state == hba->uic_link_state))
7572 /* UFS device & link must be active before we enter in this function */
7573 if (!ufshcd_is_ufs_dev_active(hba) || !ufshcd_is_link_active(hba)) {
7578 if (ufshcd_is_runtime_pm(pm_op)) {
7579 if (ufshcd_can_autobkops_during_suspend(hba)) {
7581 * The device is idle with no requests in the queue,
7582 * allow background operations if bkops status shows
7583 * that performance might be impacted.
7585 ret = ufshcd_urgent_bkops(hba);
7589 /* make sure that auto bkops is disabled */
7590 ufshcd_disable_auto_bkops(hba);
7594 if ((req_dev_pwr_mode != hba->curr_dev_pwr_mode) &&
7595 ((ufshcd_is_runtime_pm(pm_op) && !hba->auto_bkops_enabled) ||
7596 !ufshcd_is_runtime_pm(pm_op))) {
7597 /* ensure that bkops is disabled */
7598 ufshcd_disable_auto_bkops(hba);
7599 ret = ufshcd_set_dev_pwr_mode(hba, req_dev_pwr_mode);
7604 ret = ufshcd_link_state_transition(hba, req_link_state, 1);
7606 goto set_dev_active;
7608 ufshcd_vreg_set_lpm(hba);
7612 * Call vendor specific suspend callback. As these callbacks may access
7613 * vendor specific host controller register space call them before the
7614 * host clocks are ON.
7616 ret = ufshcd_vops_suspend(hba, pm_op);
7618 goto set_link_active;
7620 if (!ufshcd_is_link_active(hba))
7621 ufshcd_setup_clocks(hba, false);
7623 /* If link is active, device ref_clk can't be switched off */
7624 __ufshcd_setup_clocks(hba, false, true);
7626 hba->clk_gating.state = CLKS_OFF;
7627 trace_ufshcd_clk_gating(dev_name(hba->dev), hba->clk_gating.state);
7629 * Disable the host irq as host controller as there won't be any
7630 * host controller transaction expected till resume.
7632 ufshcd_disable_irq(hba);
7633 /* Put the host controller in low power mode if possible */
7634 ufshcd_hba_vreg_set_lpm(hba);
7638 if (hba->clk_scaling.is_allowed)
7639 ufshcd_resume_clkscaling(hba);
7640 ufshcd_vreg_set_hpm(hba);
7641 if (ufshcd_is_link_hibern8(hba) && !ufshcd_uic_hibern8_exit(hba))
7642 ufshcd_set_link_active(hba);
7643 else if (ufshcd_is_link_off(hba))
7644 ufshcd_host_reset_and_restore(hba);
7646 if (!ufshcd_set_dev_pwr_mode(hba, UFS_ACTIVE_PWR_MODE))
7647 ufshcd_disable_auto_bkops(hba);
7649 if (hba->clk_scaling.is_allowed)
7650 ufshcd_resume_clkscaling(hba);
7651 hba->clk_gating.is_suspended = false;
7652 ufshcd_release(hba);
7654 hba->pm_op_in_progress = 0;
7659 * ufshcd_resume - helper function for resume operations
7660 * @hba: per adapter instance
7661 * @pm_op: runtime PM or system PM
7663 * This function basically brings the UFS device, UniPro link and controller
7666 * Returns 0 for success and non-zero for failure
7668 static int ufshcd_resume(struct ufs_hba *hba, enum ufs_pm_op pm_op)
7671 enum uic_link_state old_link_state;
7673 hba->pm_op_in_progress = 1;
7674 old_link_state = hba->uic_link_state;
7676 ufshcd_hba_vreg_set_hpm(hba);
7677 /* Make sure clocks are enabled before accessing controller */
7678 ret = ufshcd_setup_clocks(hba, true);
7682 /* enable the host irq as host controller would be active soon */
7683 ret = ufshcd_enable_irq(hba);
7685 goto disable_irq_and_vops_clks;
7687 ret = ufshcd_vreg_set_hpm(hba);
7689 goto disable_irq_and_vops_clks;
7692 * Call vendor specific resume callback. As these callbacks may access
7693 * vendor specific host controller register space call them when the
7694 * host clocks are ON.
7696 ret = ufshcd_vops_resume(hba, pm_op);
7700 if (ufshcd_is_link_hibern8(hba)) {
7701 ret = ufshcd_uic_hibern8_exit(hba);
7703 ufshcd_set_link_active(hba);
7705 goto vendor_suspend;
7706 } else if (ufshcd_is_link_off(hba)) {
7707 ret = ufshcd_host_reset_and_restore(hba);
7709 * ufshcd_host_reset_and_restore() should have already
7710 * set the link state as active
7712 if (ret || !ufshcd_is_link_active(hba))
7713 goto vendor_suspend;
7716 if (!ufshcd_is_ufs_dev_active(hba)) {
7717 ret = ufshcd_set_dev_pwr_mode(hba, UFS_ACTIVE_PWR_MODE);
7719 goto set_old_link_state;
7722 if (ufshcd_keep_autobkops_enabled_except_suspend(hba))
7723 ufshcd_enable_auto_bkops(hba);
7726 * If BKOPs operations are urgently needed at this moment then
7727 * keep auto-bkops enabled or else disable it.
7729 ufshcd_urgent_bkops(hba);
7731 hba->clk_gating.is_suspended = false;
7733 if (hba->clk_scaling.is_allowed)
7734 ufshcd_resume_clkscaling(hba);
7736 /* Schedule clock gating in case of no access to UFS device yet */
7737 ufshcd_release(hba);
7739 /* Enable Auto-Hibernate if configured */
7740 ufshcd_auto_hibern8_enable(hba);
7745 ufshcd_link_state_transition(hba, old_link_state, 0);
7747 ufshcd_vops_suspend(hba, pm_op);
7749 ufshcd_vreg_set_lpm(hba);
7750 disable_irq_and_vops_clks:
7751 ufshcd_disable_irq(hba);
7752 if (hba->clk_scaling.is_allowed)
7753 ufshcd_suspend_clkscaling(hba);
7754 ufshcd_setup_clocks(hba, false);
7756 hba->pm_op_in_progress = 0;
7761 * ufshcd_system_suspend - system suspend routine
7762 * @hba: per adapter instance
7764 * Check the description of ufshcd_suspend() function for more details.
7766 * Returns 0 for success and non-zero for failure
7768 int ufshcd_system_suspend(struct ufs_hba *hba)
7771 ktime_t start = ktime_get();
7773 if (!hba || !hba->is_powered)
7776 if ((ufs_get_pm_lvl_to_dev_pwr_mode(hba->spm_lvl) ==
7777 hba->curr_dev_pwr_mode) &&
7778 (ufs_get_pm_lvl_to_link_pwr_state(hba->spm_lvl) ==
7779 hba->uic_link_state))
7782 if (pm_runtime_suspended(hba->dev)) {
7784 * UFS device and/or UFS link low power states during runtime
7785 * suspend seems to be different than what is expected during
7786 * system suspend. Hence runtime resume the devic & link and
7787 * let the system suspend low power states to take effect.
7788 * TODO: If resume takes longer time, we might have optimize
7789 * it in future by not resuming everything if possible.
7791 ret = ufshcd_runtime_resume(hba);
7796 ret = ufshcd_suspend(hba, UFS_SYSTEM_PM);
7798 trace_ufshcd_system_suspend(dev_name(hba->dev), ret,
7799 ktime_to_us(ktime_sub(ktime_get(), start)),
7800 hba->curr_dev_pwr_mode, hba->uic_link_state);
7802 hba->is_sys_suspended = true;
7805 EXPORT_SYMBOL(ufshcd_system_suspend);
7808 * ufshcd_system_resume - system resume routine
7809 * @hba: per adapter instance
7811 * Returns 0 for success and non-zero for failure
7814 int ufshcd_system_resume(struct ufs_hba *hba)
7817 ktime_t start = ktime_get();
7822 if (!hba->is_powered || pm_runtime_suspended(hba->dev))
7824 * Let the runtime resume take care of resuming
7825 * if runtime suspended.
7829 ret = ufshcd_resume(hba, UFS_SYSTEM_PM);
7831 trace_ufshcd_system_resume(dev_name(hba->dev), ret,
7832 ktime_to_us(ktime_sub(ktime_get(), start)),
7833 hba->curr_dev_pwr_mode, hba->uic_link_state);
7835 hba->is_sys_suspended = false;
7838 EXPORT_SYMBOL(ufshcd_system_resume);
7841 * ufshcd_runtime_suspend - runtime suspend routine
7842 * @hba: per adapter instance
7844 * Check the description of ufshcd_suspend() function for more details.
7846 * Returns 0 for success and non-zero for failure
7848 int ufshcd_runtime_suspend(struct ufs_hba *hba)
7851 ktime_t start = ktime_get();
7856 if (!hba->is_powered)
7859 ret = ufshcd_suspend(hba, UFS_RUNTIME_PM);
7861 trace_ufshcd_runtime_suspend(dev_name(hba->dev), ret,
7862 ktime_to_us(ktime_sub(ktime_get(), start)),
7863 hba->curr_dev_pwr_mode, hba->uic_link_state);
7866 EXPORT_SYMBOL(ufshcd_runtime_suspend);
7869 * ufshcd_runtime_resume - runtime resume routine
7870 * @hba: per adapter instance
7872 * This function basically brings the UFS device, UniPro link and controller
7873 * to active state. Following operations are done in this function:
7875 * 1. Turn on all the controller related clocks
7876 * 2. Bring the UniPro link out of Hibernate state
7877 * 3. If UFS device is in sleep state, turn ON VCC rail and bring the UFS device
7879 * 4. If auto-bkops is enabled on the device, disable it.
7881 * So following would be the possible power state after this function return
7883 * S1: UFS device in Active state with VCC rail ON
7884 * UniPro link in Active state
7885 * All the UFS/UniPro controller clocks are ON
7887 * Returns 0 for success and non-zero for failure
7889 int ufshcd_runtime_resume(struct ufs_hba *hba)
7892 ktime_t start = ktime_get();
7897 if (!hba->is_powered)
7900 ret = ufshcd_resume(hba, UFS_RUNTIME_PM);
7902 trace_ufshcd_runtime_resume(dev_name(hba->dev), ret,
7903 ktime_to_us(ktime_sub(ktime_get(), start)),
7904 hba->curr_dev_pwr_mode, hba->uic_link_state);
7907 EXPORT_SYMBOL(ufshcd_runtime_resume);
7909 int ufshcd_runtime_idle(struct ufs_hba *hba)
7913 EXPORT_SYMBOL(ufshcd_runtime_idle);
7916 * ufshcd_shutdown - shutdown routine
7917 * @hba: per adapter instance
7919 * This function would power off both UFS device and UFS link.
7921 * Returns 0 always to allow force shutdown even in case of errors.
7923 int ufshcd_shutdown(struct ufs_hba *hba)
7927 if (!hba->is_powered)
7930 if (ufshcd_is_ufs_dev_poweroff(hba) && ufshcd_is_link_off(hba))
7933 pm_runtime_get_sync(hba->dev);
7935 ret = ufshcd_suspend(hba, UFS_SHUTDOWN_PM);
7938 dev_err(hba->dev, "%s failed, err %d\n", __func__, ret);
7939 /* allow force shutdown even in case of errors */
7942 EXPORT_SYMBOL(ufshcd_shutdown);
7945 * ufshcd_remove - de-allocate SCSI host and host memory space
7946 * data structure memory
7947 * @hba: per adapter instance
7949 void ufshcd_remove(struct ufs_hba *hba)
7951 ufs_sysfs_remove_nodes(hba->dev);
7952 scsi_remove_host(hba->host);
7953 /* disable interrupts */
7954 ufshcd_disable_intr(hba, hba->intr_mask);
7955 ufshcd_hba_stop(hba, true);
7957 ufshcd_exit_clk_scaling(hba);
7958 ufshcd_exit_clk_gating(hba);
7959 if (ufshcd_is_clkscaling_supported(hba))
7960 device_remove_file(hba->dev, &hba->clk_scaling.enable_attr);
7961 ufshcd_hba_exit(hba);
7963 EXPORT_SYMBOL_GPL(ufshcd_remove);
7966 * ufshcd_dealloc_host - deallocate Host Bus Adapter (HBA)
7967 * @hba: pointer to Host Bus Adapter (HBA)
7969 void ufshcd_dealloc_host(struct ufs_hba *hba)
7971 scsi_host_put(hba->host);
7973 EXPORT_SYMBOL_GPL(ufshcd_dealloc_host);
7976 * ufshcd_set_dma_mask - Set dma mask based on the controller
7977 * addressing capability
7978 * @hba: per adapter instance
7980 * Returns 0 for success, non-zero for failure
7982 static int ufshcd_set_dma_mask(struct ufs_hba *hba)
7984 if (hba->capabilities & MASK_64_ADDRESSING_SUPPORT) {
7985 if (!dma_set_mask_and_coherent(hba->dev, DMA_BIT_MASK(64)))
7988 return dma_set_mask_and_coherent(hba->dev, DMA_BIT_MASK(32));
7992 * ufshcd_alloc_host - allocate Host Bus Adapter (HBA)
7993 * @dev: pointer to device handle
7994 * @hba_handle: driver private handle
7995 * Returns 0 on success, non-zero value on failure
7997 int ufshcd_alloc_host(struct device *dev, struct ufs_hba **hba_handle)
7999 struct Scsi_Host *host;
8000 struct ufs_hba *hba;
8005 "Invalid memory reference for dev is NULL\n");
8010 host = scsi_host_alloc(&ufshcd_driver_template,
8011 sizeof(struct ufs_hba));
8013 dev_err(dev, "scsi_host_alloc failed\n");
8019 * Do not use blk-mq at this time because blk-mq does not support
8022 host->use_blk_mq = false;
8024 hba = shost_priv(host);
8029 INIT_LIST_HEAD(&hba->clk_list_head);
8034 EXPORT_SYMBOL(ufshcd_alloc_host);
8037 * ufshcd_init - Driver initialization routine
8038 * @hba: per-adapter instance
8039 * @mmio_base: base register address
8040 * @irq: Interrupt line of device
8041 * Returns 0 on success, non-zero value on failure
8043 int ufshcd_init(struct ufs_hba *hba, void __iomem *mmio_base, unsigned int irq)
8046 struct Scsi_Host *host = hba->host;
8047 struct device *dev = hba->dev;
8051 "Invalid memory reference for mmio_base is NULL\n");
8056 hba->mmio_base = mmio_base;
8059 /* Set descriptor lengths to specification defaults */
8060 ufshcd_def_desc_sizes(hba);
8062 err = ufshcd_hba_init(hba);
8066 /* Read capabilities registers */
8067 ufshcd_hba_capabilities(hba);
8069 /* Get UFS version supported by the controller */
8070 hba->ufs_version = ufshcd_get_ufs_version(hba);
8072 if ((hba->ufs_version != UFSHCI_VERSION_10) &&
8073 (hba->ufs_version != UFSHCI_VERSION_11) &&
8074 (hba->ufs_version != UFSHCI_VERSION_20) &&
8075 (hba->ufs_version != UFSHCI_VERSION_21))
8076 dev_err(hba->dev, "invalid UFS version 0x%x\n",
8079 /* Get Interrupt bit mask per version */
8080 hba->intr_mask = ufshcd_get_intr_mask(hba);
8082 err = ufshcd_set_dma_mask(hba);
8084 dev_err(hba->dev, "set dma mask failed\n");
8088 /* Allocate memory for host memory space */
8089 err = ufshcd_memory_alloc(hba);
8091 dev_err(hba->dev, "Memory allocation failed\n");
8096 ufshcd_host_memory_configure(hba);
8098 host->can_queue = hba->nutrs;
8099 host->cmd_per_lun = hba->nutrs;
8100 host->max_id = UFSHCD_MAX_ID;
8101 host->max_lun = UFS_MAX_LUNS;
8102 host->max_channel = UFSHCD_MAX_CHANNEL;
8103 host->unique_id = host->host_no;
8104 host->max_cmd_len = MAX_CDB_SIZE;
8106 hba->max_pwr_info.is_valid = false;
8108 /* Initailize wait queue for task management */
8109 init_waitqueue_head(&hba->tm_wq);
8110 init_waitqueue_head(&hba->tm_tag_wq);
8112 /* Initialize work queues */
8113 INIT_WORK(&hba->eh_work, ufshcd_err_handler);
8114 INIT_WORK(&hba->eeh_work, ufshcd_exception_event_handler);
8116 /* Initialize UIC command mutex */
8117 mutex_init(&hba->uic_cmd_mutex);
8119 /* Initialize mutex for device management commands */
8120 mutex_init(&hba->dev_cmd.lock);
8122 init_rwsem(&hba->clk_scaling_lock);
8124 /* Initialize device management tag acquire wait queue */
8125 init_waitqueue_head(&hba->dev_cmd.tag_wq);
8127 ufshcd_init_clk_gating(hba);
8129 ufshcd_init_clk_scaling(hba);
8132 * In order to avoid any spurious interrupt immediately after
8133 * registering UFS controller interrupt handler, clear any pending UFS
8134 * interrupt status and disable all the UFS interrupts.
8136 ufshcd_writel(hba, ufshcd_readl(hba, REG_INTERRUPT_STATUS),
8137 REG_INTERRUPT_STATUS);
8138 ufshcd_writel(hba, 0, REG_INTERRUPT_ENABLE);
8140 * Make sure that UFS interrupts are disabled and any pending interrupt
8141 * status is cleared before registering UFS interrupt handler.
8145 /* IRQ registration */
8146 err = devm_request_irq(dev, irq, ufshcd_intr, IRQF_SHARED, UFSHCD, hba);
8148 dev_err(hba->dev, "request irq failed\n");
8151 hba->is_irq_enabled = true;
8154 err = scsi_add_host(host, hba->dev);
8156 dev_err(hba->dev, "scsi_add_host failed\n");
8160 /* Host controller enable */
8161 err = ufshcd_hba_enable(hba);
8163 dev_err(hba->dev, "Host controller enable failed\n");
8164 ufshcd_print_host_regs(hba);
8165 ufshcd_print_host_state(hba);
8166 goto out_remove_scsi_host;
8170 * Set the default power management level for runtime and system PM.
8171 * Default power saving mode is to keep UFS link in Hibern8 state
8172 * and UFS device in sleep state.
8174 hba->rpm_lvl = ufs_get_desired_pm_lvl_for_dev_link_state(
8176 UIC_LINK_HIBERN8_STATE);
8177 hba->spm_lvl = ufs_get_desired_pm_lvl_for_dev_link_state(
8179 UIC_LINK_HIBERN8_STATE);
8181 /* Set the default auto-hiberate idle timer value to 150 ms */
8182 if (hba->capabilities & MASK_AUTO_HIBERN8_SUPPORT) {
8183 hba->ahit = FIELD_PREP(UFSHCI_AHIBERN8_TIMER_MASK, 150) |
8184 FIELD_PREP(UFSHCI_AHIBERN8_SCALE_MASK, 3);
8187 /* Hold auto suspend until async scan completes */
8188 pm_runtime_get_sync(dev);
8189 atomic_set(&hba->scsi_block_reqs_cnt, 0);
8191 * We are assuming that device wasn't put in sleep/power-down
8192 * state exclusively during the boot stage before kernel.
8193 * This assumption helps avoid doing link startup twice during
8194 * ufshcd_probe_hba().
8196 ufshcd_set_ufs_dev_active(hba);
8198 async_schedule(ufshcd_async_scan, hba);
8199 ufs_sysfs_add_nodes(hba->dev);
8203 out_remove_scsi_host:
8204 scsi_remove_host(hba->host);
8206 ufshcd_exit_clk_scaling(hba);
8207 ufshcd_exit_clk_gating(hba);
8209 hba->is_irq_enabled = false;
8210 ufshcd_hba_exit(hba);
8214 EXPORT_SYMBOL_GPL(ufshcd_init);
8216 MODULE_AUTHOR("Santosh Yaragnavi <santosh.sy@samsung.com>");
8217 MODULE_AUTHOR("Vinayak Holikatti <h.vinayak@samsung.com>");
8218 MODULE_DESCRIPTION("Generic UFS host controller driver Core");
8219 MODULE_LICENSE("GPL");
8220 MODULE_VERSION(UFSHCD_DRIVER_VERSION);