2 * Universal Flash Storage Host controller driver Core
4 * This code is based on drivers/scsi/ufs/ufshcd.c
5 * Copyright (C) 2011-2013 Samsung India Software Operations
6 * Copyright (c) 2013-2016, The Linux Foundation. All rights reserved.
9 * Santosh Yaraganavi <santosh.sy@samsung.com>
10 * Vinayak Holikatti <h.vinayak@samsung.com>
12 * This program is free software; you can redistribute it and/or
13 * modify it under the terms of the GNU General Public License
14 * as published by the Free Software Foundation; either version 2
15 * of the License, or (at your option) any later version.
16 * See the COPYING file in the top-level directory or visit
17 * <http://www.gnu.org/licenses/gpl-2.0.html>
19 * This program is distributed in the hope that it will be useful,
20 * but WITHOUT ANY WARRANTY; without even the implied warranty of
21 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22 * GNU General Public License for more details.
24 * This program is provided "AS IS" and "WITH ALL FAULTS" and
25 * without warranty of any kind. You are solely responsible for
26 * determining the appropriateness of using and distributing
27 * the program and assume all risks associated with your exercise
28 * of rights with respect to the program, including but not limited
29 * to infringement of third party rights, the risks and costs of
30 * program errors, damage to or loss of data, programs or equipment,
31 * and unavailability or interruption of operations. Under no
32 * circumstances will the contributor of this Program be liable for
33 * any damages of any kind arising from your use or distribution of
36 * The Linux Foundation chooses to take subject only to the GPLv2
37 * license terms, and distributes only under these terms.
40 #include <linux/async.h>
41 #include <linux/devfreq.h>
42 #include <linux/nls.h>
44 #include <linux/bitfield.h>
46 #include "ufs_quirks.h"
48 #include "ufs-sysfs.h"
51 #define CREATE_TRACE_POINTS
52 #include <trace/events/ufs.h>
54 #define UFSHCD_ENABLE_INTRS (UTP_TRANSFER_REQ_COMPL |\
57 /* UIC command timeout, unit: ms */
58 #define UIC_CMD_TIMEOUT 500
60 /* NOP OUT retries waiting for NOP IN response */
61 #define NOP_OUT_RETRIES 10
62 /* Timeout after 30 msecs if NOP OUT hangs without response */
63 #define NOP_OUT_TIMEOUT 30 /* msecs */
65 /* Query request retries */
66 #define QUERY_REQ_RETRIES 3
67 /* Query request timeout */
68 #define QUERY_REQ_TIMEOUT 1500 /* 1.5 seconds */
70 /* Task management command timeout */
71 #define TM_CMD_TIMEOUT 100 /* msecs */
73 /* maximum number of retries for a general UIC command */
74 #define UFS_UIC_COMMAND_RETRIES 3
76 /* maximum number of link-startup retries */
77 #define DME_LINKSTARTUP_RETRIES 3
79 /* Maximum retries for Hibern8 enter */
80 #define UIC_HIBERN8_ENTER_RETRIES 3
82 /* maximum number of reset retries before giving up */
83 #define MAX_HOST_RESET_RETRIES 5
85 /* Expose the flag value from utp_upiu_query.value */
86 #define MASK_QUERY_UPIU_FLAG_LOC 0xFF
88 /* Interrupt aggregation default timeout, unit: 40us */
89 #define INT_AGGR_DEF_TO 0x02
91 #define ufshcd_toggle_vreg(_dev, _vreg, _on) \
95 _ret = ufshcd_enable_vreg(_dev, _vreg); \
97 _ret = ufshcd_disable_vreg(_dev, _vreg); \
101 #define ufshcd_hex_dump(prefix_str, buf, len) do { \
102 size_t __len = (len); \
103 print_hex_dump(KERN_ERR, prefix_str, \
104 __len > 4 ? DUMP_PREFIX_OFFSET : DUMP_PREFIX_NONE,\
105 16, 4, buf, __len, false); \
108 int ufshcd_dump_regs(struct ufs_hba *hba, size_t offset, size_t len,
114 if (offset % 4 != 0 || len % 4 != 0) /* keep readl happy */
117 regs = kzalloc(len, GFP_KERNEL);
121 for (pos = 0; pos < len; pos += 4)
122 regs[pos / 4] = ufshcd_readl(hba, offset + pos);
124 ufshcd_hex_dump(prefix, regs, len);
129 EXPORT_SYMBOL_GPL(ufshcd_dump_regs);
132 UFSHCD_MAX_CHANNEL = 0,
134 UFSHCD_CMD_PER_LUN = 32,
135 UFSHCD_CAN_QUEUE = 32,
142 UFSHCD_STATE_OPERATIONAL,
143 UFSHCD_STATE_EH_SCHEDULED,
146 /* UFSHCD error handling flags */
148 UFSHCD_EH_IN_PROGRESS = (1 << 0),
151 /* UFSHCD UIC layer error flags */
153 UFSHCD_UIC_DL_PA_INIT_ERROR = (1 << 0), /* Data link layer error */
154 UFSHCD_UIC_DL_NAC_RECEIVED_ERROR = (1 << 1), /* Data link layer error */
155 UFSHCD_UIC_DL_TCx_REPLAY_ERROR = (1 << 2), /* Data link layer error */
156 UFSHCD_UIC_NL_ERROR = (1 << 3), /* Network layer error */
157 UFSHCD_UIC_TL_ERROR = (1 << 4), /* Transport Layer error */
158 UFSHCD_UIC_DME_ERROR = (1 << 5), /* DME error */
161 #define ufshcd_set_eh_in_progress(h) \
162 ((h)->eh_flags |= UFSHCD_EH_IN_PROGRESS)
163 #define ufshcd_eh_in_progress(h) \
164 ((h)->eh_flags & UFSHCD_EH_IN_PROGRESS)
165 #define ufshcd_clear_eh_in_progress(h) \
166 ((h)->eh_flags &= ~UFSHCD_EH_IN_PROGRESS)
168 #define ufshcd_set_ufs_dev_active(h) \
169 ((h)->curr_dev_pwr_mode = UFS_ACTIVE_PWR_MODE)
170 #define ufshcd_set_ufs_dev_sleep(h) \
171 ((h)->curr_dev_pwr_mode = UFS_SLEEP_PWR_MODE)
172 #define ufshcd_set_ufs_dev_poweroff(h) \
173 ((h)->curr_dev_pwr_mode = UFS_POWERDOWN_PWR_MODE)
174 #define ufshcd_is_ufs_dev_active(h) \
175 ((h)->curr_dev_pwr_mode == UFS_ACTIVE_PWR_MODE)
176 #define ufshcd_is_ufs_dev_sleep(h) \
177 ((h)->curr_dev_pwr_mode == UFS_SLEEP_PWR_MODE)
178 #define ufshcd_is_ufs_dev_poweroff(h) \
179 ((h)->curr_dev_pwr_mode == UFS_POWERDOWN_PWR_MODE)
181 struct ufs_pm_lvl_states ufs_pm_lvl_states[] = {
182 {UFS_ACTIVE_PWR_MODE, UIC_LINK_ACTIVE_STATE},
183 {UFS_ACTIVE_PWR_MODE, UIC_LINK_HIBERN8_STATE},
184 {UFS_SLEEP_PWR_MODE, UIC_LINK_ACTIVE_STATE},
185 {UFS_SLEEP_PWR_MODE, UIC_LINK_HIBERN8_STATE},
186 {UFS_POWERDOWN_PWR_MODE, UIC_LINK_HIBERN8_STATE},
187 {UFS_POWERDOWN_PWR_MODE, UIC_LINK_OFF_STATE},
190 static inline enum ufs_dev_pwr_mode
191 ufs_get_pm_lvl_to_dev_pwr_mode(enum ufs_pm_level lvl)
193 return ufs_pm_lvl_states[lvl].dev_state;
196 static inline enum uic_link_state
197 ufs_get_pm_lvl_to_link_pwr_state(enum ufs_pm_level lvl)
199 return ufs_pm_lvl_states[lvl].link_state;
202 static inline enum ufs_pm_level
203 ufs_get_desired_pm_lvl_for_dev_link_state(enum ufs_dev_pwr_mode dev_state,
204 enum uic_link_state link_state)
206 enum ufs_pm_level lvl;
208 for (lvl = UFS_PM_LVL_0; lvl < UFS_PM_LVL_MAX; lvl++) {
209 if ((ufs_pm_lvl_states[lvl].dev_state == dev_state) &&
210 (ufs_pm_lvl_states[lvl].link_state == link_state))
214 /* if no match found, return the level 0 */
218 static struct ufs_dev_fix ufs_fixups[] = {
219 /* UFS cards deviations table */
220 UFS_FIX(UFS_VENDOR_SAMSUNG, UFS_ANY_MODEL,
221 UFS_DEVICE_QUIRK_DELAY_BEFORE_LPM),
222 UFS_FIX(UFS_VENDOR_SAMSUNG, UFS_ANY_MODEL,
223 UFS_DEVICE_QUIRK_RECOVERY_FROM_DL_NAC_ERRORS),
224 UFS_FIX(UFS_VENDOR_SAMSUNG, UFS_ANY_MODEL,
225 UFS_DEVICE_QUIRK_HOST_PA_TACTIVATE),
226 UFS_FIX(UFS_VENDOR_TOSHIBA, UFS_ANY_MODEL,
227 UFS_DEVICE_QUIRK_DELAY_BEFORE_LPM),
228 UFS_FIX(UFS_VENDOR_TOSHIBA, "THGLF2G9C8KBADG",
229 UFS_DEVICE_QUIRK_PA_TACTIVATE),
230 UFS_FIX(UFS_VENDOR_TOSHIBA, "THGLF2G9D8KBADG",
231 UFS_DEVICE_QUIRK_PA_TACTIVATE),
232 UFS_FIX(UFS_VENDOR_SKHYNIX, UFS_ANY_MODEL,
233 UFS_DEVICE_QUIRK_HOST_PA_SAVECONFIGTIME),
234 UFS_FIX(UFS_VENDOR_SKHYNIX, "hB8aL1" /*H28U62301AMR*/,
235 UFS_DEVICE_QUIRK_HOST_VS_DEBUGSAVECONFIGTIME),
240 static void ufshcd_tmc_handler(struct ufs_hba *hba);
241 static void ufshcd_async_scan(void *data, async_cookie_t cookie);
242 static int ufshcd_reset_and_restore(struct ufs_hba *hba);
243 static int ufshcd_eh_host_reset_handler(struct scsi_cmnd *cmd);
244 static int ufshcd_clear_tm_cmd(struct ufs_hba *hba, int tag);
245 static void ufshcd_hba_exit(struct ufs_hba *hba);
246 static int ufshcd_probe_hba(struct ufs_hba *hba);
247 static int __ufshcd_setup_clocks(struct ufs_hba *hba, bool on,
249 static int ufshcd_setup_clocks(struct ufs_hba *hba, bool on);
250 static int ufshcd_uic_hibern8_exit(struct ufs_hba *hba);
251 static int ufshcd_uic_hibern8_enter(struct ufs_hba *hba);
252 static inline void ufshcd_add_delay_before_dme_cmd(struct ufs_hba *hba);
253 static int ufshcd_host_reset_and_restore(struct ufs_hba *hba);
254 static void ufshcd_resume_clkscaling(struct ufs_hba *hba);
255 static void ufshcd_suspend_clkscaling(struct ufs_hba *hba);
256 static void __ufshcd_suspend_clkscaling(struct ufs_hba *hba);
257 static int ufshcd_scale_clks(struct ufs_hba *hba, bool scale_up);
258 static irqreturn_t ufshcd_intr(int irq, void *__hba);
259 static int ufshcd_change_power_mode(struct ufs_hba *hba,
260 struct ufs_pa_layer_attr *pwr_mode);
261 static inline bool ufshcd_valid_tag(struct ufs_hba *hba, int tag)
263 return tag >= 0 && tag < hba->nutrs;
266 static inline int ufshcd_enable_irq(struct ufs_hba *hba)
270 if (!hba->is_irq_enabled) {
271 ret = request_irq(hba->irq, ufshcd_intr, IRQF_SHARED, UFSHCD,
274 dev_err(hba->dev, "%s: request_irq failed, ret=%d\n",
276 hba->is_irq_enabled = true;
282 static inline void ufshcd_disable_irq(struct ufs_hba *hba)
284 if (hba->is_irq_enabled) {
285 free_irq(hba->irq, hba);
286 hba->is_irq_enabled = false;
290 static void ufshcd_scsi_unblock_requests(struct ufs_hba *hba)
292 if (atomic_dec_and_test(&hba->scsi_block_reqs_cnt))
293 scsi_unblock_requests(hba->host);
296 static void ufshcd_scsi_block_requests(struct ufs_hba *hba)
298 if (atomic_inc_return(&hba->scsi_block_reqs_cnt) == 1)
299 scsi_block_requests(hba->host);
302 /* replace non-printable or non-ASCII characters with spaces */
303 static inline void ufshcd_remove_non_printable(char *val)
308 if (*val < 0x20 || *val > 0x7e)
312 static void ufshcd_add_cmd_upiu_trace(struct ufs_hba *hba, unsigned int tag,
315 struct utp_upiu_req *rq = hba->lrb[tag].ucd_req_ptr;
317 trace_ufshcd_upiu(dev_name(hba->dev), str, &rq->header, &rq->sc.cdb);
320 static void ufshcd_add_query_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->qr);
328 static void ufshcd_add_tm_upiu_trace(struct ufs_hba *hba, unsigned int tag,
331 int off = (int)tag - hba->nutrs;
332 struct utp_task_req_desc *descp = &hba->utmrdl_base_addr[off];
334 trace_ufshcd_upiu(dev_name(hba->dev), str, &descp->req_header,
335 &descp->input_param1);
338 static void ufshcd_add_command_trace(struct ufs_hba *hba,
339 unsigned int tag, const char *str)
344 struct ufshcd_lrb *lrbp = &hba->lrb[tag];
345 int transfer_len = -1;
347 if (!trace_ufshcd_command_enabled()) {
348 /* trace UPIU W/O tracing command */
350 ufshcd_add_cmd_upiu_trace(hba, tag, str);
354 if (lrbp->cmd) { /* data phase exists */
355 /* trace UPIU also */
356 ufshcd_add_cmd_upiu_trace(hba, tag, str);
357 opcode = (u8)(*lrbp->cmd->cmnd);
358 if ((opcode == READ_10) || (opcode == WRITE_10)) {
360 * Currently we only fully trace read(10) and write(10)
363 if (lrbp->cmd->request && lrbp->cmd->request->bio)
365 lrbp->cmd->request->bio->bi_iter.bi_sector;
366 transfer_len = be32_to_cpu(
367 lrbp->ucd_req_ptr->sc.exp_data_transfer_len);
371 intr = ufshcd_readl(hba, REG_INTERRUPT_STATUS);
372 doorbell = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
373 trace_ufshcd_command(dev_name(hba->dev), str, tag,
374 doorbell, transfer_len, intr, lba, opcode);
377 static void ufshcd_print_clk_freqs(struct ufs_hba *hba)
379 struct ufs_clk_info *clki;
380 struct list_head *head = &hba->clk_list_head;
382 if (list_empty(head))
385 list_for_each_entry(clki, head, list) {
386 if (!IS_ERR_OR_NULL(clki->clk) && clki->min_freq &&
388 dev_err(hba->dev, "clk: %s, rate: %u\n",
389 clki->name, clki->curr_freq);
393 static void ufshcd_print_uic_err_hist(struct ufs_hba *hba,
394 struct ufs_uic_err_reg_hist *err_hist, char *err_name)
399 for (i = 0; i < UIC_ERR_REG_HIST_LENGTH; i++) {
400 int p = (i + err_hist->pos) % UIC_ERR_REG_HIST_LENGTH;
402 if (err_hist->reg[p] == 0)
404 dev_err(hba->dev, "%s[%d] = 0x%x at %lld us\n", err_name, i,
405 err_hist->reg[p], ktime_to_us(err_hist->tstamp[p]));
410 dev_err(hba->dev, "No record of %s uic errors\n", err_name);
413 static void ufshcd_print_host_regs(struct ufs_hba *hba)
415 ufshcd_dump_regs(hba, 0, UFSHCI_REG_SPACE_SIZE, "host_regs: ");
416 dev_err(hba->dev, "hba->ufs_version = 0x%x, hba->capabilities = 0x%x\n",
417 hba->ufs_version, hba->capabilities);
419 "hba->outstanding_reqs = 0x%x, hba->outstanding_tasks = 0x%x\n",
420 (u32)hba->outstanding_reqs, (u32)hba->outstanding_tasks);
422 "last_hibern8_exit_tstamp at %lld us, hibern8_exit_cnt = %d\n",
423 ktime_to_us(hba->ufs_stats.last_hibern8_exit_tstamp),
424 hba->ufs_stats.hibern8_exit_cnt);
426 ufshcd_print_uic_err_hist(hba, &hba->ufs_stats.pa_err, "pa_err");
427 ufshcd_print_uic_err_hist(hba, &hba->ufs_stats.dl_err, "dl_err");
428 ufshcd_print_uic_err_hist(hba, &hba->ufs_stats.nl_err, "nl_err");
429 ufshcd_print_uic_err_hist(hba, &hba->ufs_stats.tl_err, "tl_err");
430 ufshcd_print_uic_err_hist(hba, &hba->ufs_stats.dme_err, "dme_err");
432 ufshcd_print_clk_freqs(hba);
434 if (hba->vops && hba->vops->dbg_register_dump)
435 hba->vops->dbg_register_dump(hba);
439 void ufshcd_print_trs(struct ufs_hba *hba, unsigned long bitmap, bool pr_prdt)
441 struct ufshcd_lrb *lrbp;
445 for_each_set_bit(tag, &bitmap, hba->nutrs) {
446 lrbp = &hba->lrb[tag];
448 dev_err(hba->dev, "UPIU[%d] - issue time %lld us\n",
449 tag, ktime_to_us(lrbp->issue_time_stamp));
450 dev_err(hba->dev, "UPIU[%d] - complete time %lld us\n",
451 tag, ktime_to_us(lrbp->compl_time_stamp));
453 "UPIU[%d] - Transfer Request Descriptor phys@0x%llx\n",
454 tag, (u64)lrbp->utrd_dma_addr);
456 ufshcd_hex_dump("UPIU TRD: ", lrbp->utr_descriptor_ptr,
457 sizeof(struct utp_transfer_req_desc));
458 dev_err(hba->dev, "UPIU[%d] - Request UPIU phys@0x%llx\n", tag,
459 (u64)lrbp->ucd_req_dma_addr);
460 ufshcd_hex_dump("UPIU REQ: ", lrbp->ucd_req_ptr,
461 sizeof(struct utp_upiu_req));
462 dev_err(hba->dev, "UPIU[%d] - Response UPIU phys@0x%llx\n", tag,
463 (u64)lrbp->ucd_rsp_dma_addr);
464 ufshcd_hex_dump("UPIU RSP: ", lrbp->ucd_rsp_ptr,
465 sizeof(struct utp_upiu_rsp));
467 prdt_length = le16_to_cpu(
468 lrbp->utr_descriptor_ptr->prd_table_length);
470 "UPIU[%d] - PRDT - %d entries phys@0x%llx\n",
472 (u64)lrbp->ucd_prdt_dma_addr);
475 ufshcd_hex_dump("UPIU PRDT: ", lrbp->ucd_prdt_ptr,
476 sizeof(struct ufshcd_sg_entry) * prdt_length);
480 static void ufshcd_print_tmrs(struct ufs_hba *hba, unsigned long bitmap)
484 for_each_set_bit(tag, &bitmap, hba->nutmrs) {
485 struct utp_task_req_desc *tmrdp = &hba->utmrdl_base_addr[tag];
487 dev_err(hba->dev, "TM[%d] - Task Management Header\n", tag);
488 ufshcd_hex_dump("", tmrdp, sizeof(*tmrdp));
492 static void ufshcd_print_host_state(struct ufs_hba *hba)
494 dev_err(hba->dev, "UFS Host state=%d\n", hba->ufshcd_state);
495 dev_err(hba->dev, "lrb in use=0x%lx, outstanding reqs=0x%lx tasks=0x%lx\n",
496 hba->lrb_in_use, hba->outstanding_reqs, hba->outstanding_tasks);
497 dev_err(hba->dev, "saved_err=0x%x, saved_uic_err=0x%x\n",
498 hba->saved_err, hba->saved_uic_err);
499 dev_err(hba->dev, "Device power mode=%d, UIC link state=%d\n",
500 hba->curr_dev_pwr_mode, hba->uic_link_state);
501 dev_err(hba->dev, "PM in progress=%d, sys. suspended=%d\n",
502 hba->pm_op_in_progress, hba->is_sys_suspended);
503 dev_err(hba->dev, "Auto BKOPS=%d, Host self-block=%d\n",
504 hba->auto_bkops_enabled, hba->host->host_self_blocked);
505 dev_err(hba->dev, "Clk gate=%d\n", hba->clk_gating.state);
506 dev_err(hba->dev, "error handling flags=0x%x, req. abort count=%d\n",
507 hba->eh_flags, hba->req_abort_count);
508 dev_err(hba->dev, "Host capabilities=0x%x, caps=0x%x\n",
509 hba->capabilities, hba->caps);
510 dev_err(hba->dev, "quirks=0x%x, dev. quirks=0x%x\n", hba->quirks,
515 * ufshcd_print_pwr_info - print power params as saved in hba
517 * @hba: per-adapter instance
519 static void ufshcd_print_pwr_info(struct ufs_hba *hba)
521 static const char * const names[] = {
531 dev_err(hba->dev, "%s:[RX, TX]: gear=[%d, %d], lane[%d, %d], pwr[%s, %s], rate = %d\n",
533 hba->pwr_info.gear_rx, hba->pwr_info.gear_tx,
534 hba->pwr_info.lane_rx, hba->pwr_info.lane_tx,
535 names[hba->pwr_info.pwr_rx],
536 names[hba->pwr_info.pwr_tx],
537 hba->pwr_info.hs_rate);
541 * ufshcd_wait_for_register - wait for register value to change
542 * @hba - per-adapter interface
543 * @reg - mmio register offset
544 * @mask - mask to apply to read register value
545 * @val - wait condition
546 * @interval_us - polling interval in microsecs
547 * @timeout_ms - timeout in millisecs
548 * @can_sleep - perform sleep or just spin
550 * Returns -ETIMEDOUT on error, zero on success
552 int ufshcd_wait_for_register(struct ufs_hba *hba, u32 reg, u32 mask,
553 u32 val, unsigned long interval_us,
554 unsigned long timeout_ms, bool can_sleep)
557 unsigned long timeout = jiffies + msecs_to_jiffies(timeout_ms);
559 /* ignore bits that we don't intend to wait on */
562 while ((ufshcd_readl(hba, reg) & mask) != val) {
564 usleep_range(interval_us, interval_us + 50);
567 if (time_after(jiffies, timeout)) {
568 if ((ufshcd_readl(hba, reg) & mask) != val)
578 * ufshcd_get_intr_mask - Get the interrupt bit mask
579 * @hba: Pointer to adapter instance
581 * Returns interrupt bit mask per version
583 static inline u32 ufshcd_get_intr_mask(struct ufs_hba *hba)
587 switch (hba->ufs_version) {
588 case UFSHCI_VERSION_10:
589 intr_mask = INTERRUPT_MASK_ALL_VER_10;
591 case UFSHCI_VERSION_11:
592 case UFSHCI_VERSION_20:
593 intr_mask = INTERRUPT_MASK_ALL_VER_11;
595 case UFSHCI_VERSION_21:
597 intr_mask = INTERRUPT_MASK_ALL_VER_21;
605 * ufshcd_get_ufs_version - Get the UFS version supported by the HBA
606 * @hba: Pointer to adapter instance
608 * Returns UFSHCI version supported by the controller
610 static inline u32 ufshcd_get_ufs_version(struct ufs_hba *hba)
612 if (hba->quirks & UFSHCD_QUIRK_BROKEN_UFS_HCI_VERSION)
613 return ufshcd_vops_get_ufs_hci_version(hba);
615 return ufshcd_readl(hba, REG_UFS_VERSION);
619 * ufshcd_is_device_present - Check if any device connected to
620 * the host controller
621 * @hba: pointer to adapter instance
623 * Returns true if device present, false if no device detected
625 static inline bool ufshcd_is_device_present(struct ufs_hba *hba)
627 return (ufshcd_readl(hba, REG_CONTROLLER_STATUS) &
628 DEVICE_PRESENT) ? true : false;
632 * ufshcd_get_tr_ocs - Get the UTRD Overall Command Status
633 * @lrbp: pointer to local command reference block
635 * This function is used to get the OCS field from UTRD
636 * Returns the OCS field in the UTRD
638 static inline int ufshcd_get_tr_ocs(struct ufshcd_lrb *lrbp)
640 return le32_to_cpu(lrbp->utr_descriptor_ptr->header.dword_2) & MASK_OCS;
644 * ufshcd_get_tm_free_slot - get a free slot for task management request
645 * @hba: per adapter instance
646 * @free_slot: pointer to variable with available slot value
648 * Get a free tag and lock it until ufshcd_put_tm_slot() is called.
649 * Returns 0 if free slot is not available, else return 1 with tag value
652 static bool ufshcd_get_tm_free_slot(struct ufs_hba *hba, int *free_slot)
661 tag = find_first_zero_bit(&hba->tm_slots_in_use, hba->nutmrs);
662 if (tag >= hba->nutmrs)
664 } while (test_and_set_bit_lock(tag, &hba->tm_slots_in_use));
672 static inline void ufshcd_put_tm_slot(struct ufs_hba *hba, int slot)
674 clear_bit_unlock(slot, &hba->tm_slots_in_use);
678 * ufshcd_utrl_clear - Clear a bit in UTRLCLR register
679 * @hba: per adapter instance
680 * @pos: position of the bit to be cleared
682 static inline void ufshcd_utrl_clear(struct ufs_hba *hba, u32 pos)
684 if (hba->quirks & UFSHCI_QUIRK_BROKEN_REQ_LIST_CLR)
685 ufshcd_writel(hba, (1 << pos), REG_UTP_TRANSFER_REQ_LIST_CLEAR);
687 ufshcd_writel(hba, ~(1 << pos),
688 REG_UTP_TRANSFER_REQ_LIST_CLEAR);
692 * ufshcd_utmrl_clear - Clear a bit in UTRMLCLR register
693 * @hba: per adapter instance
694 * @pos: position of the bit to be cleared
696 static inline void ufshcd_utmrl_clear(struct ufs_hba *hba, u32 pos)
698 if (hba->quirks & UFSHCI_QUIRK_BROKEN_REQ_LIST_CLR)
699 ufshcd_writel(hba, (1 << pos), REG_UTP_TASK_REQ_LIST_CLEAR);
701 ufshcd_writel(hba, ~(1 << pos), REG_UTP_TASK_REQ_LIST_CLEAR);
705 * ufshcd_outstanding_req_clear - Clear a bit in outstanding request field
706 * @hba: per adapter instance
707 * @tag: position of the bit to be cleared
709 static inline void ufshcd_outstanding_req_clear(struct ufs_hba *hba, int tag)
711 __clear_bit(tag, &hba->outstanding_reqs);
715 * ufshcd_get_lists_status - Check UCRDY, UTRLRDY and UTMRLRDY
716 * @reg: Register value of host controller status
718 * Returns integer, 0 on Success and positive value if failed
720 static inline int ufshcd_get_lists_status(u32 reg)
722 return !((reg & UFSHCD_STATUS_READY) == UFSHCD_STATUS_READY);
726 * ufshcd_get_uic_cmd_result - Get the UIC command result
727 * @hba: Pointer to adapter instance
729 * This function gets the result of UIC command completion
730 * Returns 0 on success, non zero value on error
732 static inline int ufshcd_get_uic_cmd_result(struct ufs_hba *hba)
734 return ufshcd_readl(hba, REG_UIC_COMMAND_ARG_2) &
735 MASK_UIC_COMMAND_RESULT;
739 * ufshcd_get_dme_attr_val - Get the value of attribute returned by UIC command
740 * @hba: Pointer to adapter instance
742 * This function gets UIC command argument3
743 * Returns 0 on success, non zero value on error
745 static inline u32 ufshcd_get_dme_attr_val(struct ufs_hba *hba)
747 return ufshcd_readl(hba, REG_UIC_COMMAND_ARG_3);
751 * ufshcd_get_req_rsp - returns the TR response transaction type
752 * @ucd_rsp_ptr: pointer to response UPIU
755 ufshcd_get_req_rsp(struct utp_upiu_rsp *ucd_rsp_ptr)
757 return be32_to_cpu(ucd_rsp_ptr->header.dword_0) >> 24;
761 * ufshcd_get_rsp_upiu_result - Get the result from response UPIU
762 * @ucd_rsp_ptr: pointer to response UPIU
764 * This function gets the response status and scsi_status from response UPIU
765 * Returns the response result code.
768 ufshcd_get_rsp_upiu_result(struct utp_upiu_rsp *ucd_rsp_ptr)
770 return be32_to_cpu(ucd_rsp_ptr->header.dword_1) & MASK_RSP_UPIU_RESULT;
774 * ufshcd_get_rsp_upiu_data_seg_len - Get the data segment length
776 * @ucd_rsp_ptr: pointer to response UPIU
778 * Return the data segment length.
780 static inline unsigned int
781 ufshcd_get_rsp_upiu_data_seg_len(struct utp_upiu_rsp *ucd_rsp_ptr)
783 return be32_to_cpu(ucd_rsp_ptr->header.dword_2) &
784 MASK_RSP_UPIU_DATA_SEG_LEN;
788 * ufshcd_is_exception_event - Check if the device raised an exception event
789 * @ucd_rsp_ptr: pointer to response UPIU
791 * The function checks if the device raised an exception event indicated in
792 * the Device Information field of response UPIU.
794 * Returns true if exception is raised, false otherwise.
796 static inline bool ufshcd_is_exception_event(struct utp_upiu_rsp *ucd_rsp_ptr)
798 return be32_to_cpu(ucd_rsp_ptr->header.dword_2) &
799 MASK_RSP_EXCEPTION_EVENT ? true : false;
803 * ufshcd_reset_intr_aggr - Reset interrupt aggregation values.
804 * @hba: per adapter instance
807 ufshcd_reset_intr_aggr(struct ufs_hba *hba)
809 ufshcd_writel(hba, INT_AGGR_ENABLE |
810 INT_AGGR_COUNTER_AND_TIMER_RESET,
811 REG_UTP_TRANSFER_REQ_INT_AGG_CONTROL);
815 * ufshcd_config_intr_aggr - Configure interrupt aggregation values.
816 * @hba: per adapter instance
817 * @cnt: Interrupt aggregation counter threshold
818 * @tmout: Interrupt aggregation timeout value
821 ufshcd_config_intr_aggr(struct ufs_hba *hba, u8 cnt, u8 tmout)
823 ufshcd_writel(hba, INT_AGGR_ENABLE | INT_AGGR_PARAM_WRITE |
824 INT_AGGR_COUNTER_THLD_VAL(cnt) |
825 INT_AGGR_TIMEOUT_VAL(tmout),
826 REG_UTP_TRANSFER_REQ_INT_AGG_CONTROL);
830 * ufshcd_disable_intr_aggr - Disables interrupt aggregation.
831 * @hba: per adapter instance
833 static inline void ufshcd_disable_intr_aggr(struct ufs_hba *hba)
835 ufshcd_writel(hba, 0, REG_UTP_TRANSFER_REQ_INT_AGG_CONTROL);
839 * ufshcd_enable_run_stop_reg - Enable run-stop registers,
840 * When run-stop registers are set to 1, it indicates the
841 * host controller that it can process the requests
842 * @hba: per adapter instance
844 static void ufshcd_enable_run_stop_reg(struct ufs_hba *hba)
846 ufshcd_writel(hba, UTP_TASK_REQ_LIST_RUN_STOP_BIT,
847 REG_UTP_TASK_REQ_LIST_RUN_STOP);
848 ufshcd_writel(hba, UTP_TRANSFER_REQ_LIST_RUN_STOP_BIT,
849 REG_UTP_TRANSFER_REQ_LIST_RUN_STOP);
853 * ufshcd_hba_start - Start controller initialization sequence
854 * @hba: per adapter instance
856 static inline void ufshcd_hba_start(struct ufs_hba *hba)
858 ufshcd_writel(hba, CONTROLLER_ENABLE, REG_CONTROLLER_ENABLE);
862 * ufshcd_is_hba_active - Get controller state
863 * @hba: per adapter instance
865 * Returns false if controller is active, true otherwise
867 static inline bool ufshcd_is_hba_active(struct ufs_hba *hba)
869 return (ufshcd_readl(hba, REG_CONTROLLER_ENABLE) & CONTROLLER_ENABLE)
873 u32 ufshcd_get_local_unipro_ver(struct ufs_hba *hba)
875 /* HCI version 1.0 and 1.1 supports UniPro 1.41 */
876 if ((hba->ufs_version == UFSHCI_VERSION_10) ||
877 (hba->ufs_version == UFSHCI_VERSION_11))
878 return UFS_UNIPRO_VER_1_41;
880 return UFS_UNIPRO_VER_1_6;
882 EXPORT_SYMBOL(ufshcd_get_local_unipro_ver);
884 static bool ufshcd_is_unipro_pa_params_tuning_req(struct ufs_hba *hba)
887 * If both host and device support UniPro ver1.6 or later, PA layer
888 * parameters tuning happens during link startup itself.
890 * We can manually tune PA layer parameters if either host or device
891 * doesn't support UniPro ver 1.6 or later. But to keep manual tuning
892 * logic simple, we will only do manual tuning if local unipro version
893 * doesn't support ver1.6 or later.
895 if (ufshcd_get_local_unipro_ver(hba) < UFS_UNIPRO_VER_1_6)
901 static int ufshcd_scale_clks(struct ufs_hba *hba, bool scale_up)
904 struct ufs_clk_info *clki;
905 struct list_head *head = &hba->clk_list_head;
906 ktime_t start = ktime_get();
907 bool clk_state_changed = false;
909 if (list_empty(head))
912 ret = ufshcd_vops_clk_scale_notify(hba, scale_up, PRE_CHANGE);
916 list_for_each_entry(clki, head, list) {
917 if (!IS_ERR_OR_NULL(clki->clk)) {
918 if (scale_up && clki->max_freq) {
919 if (clki->curr_freq == clki->max_freq)
922 clk_state_changed = true;
923 ret = clk_set_rate(clki->clk, clki->max_freq);
925 dev_err(hba->dev, "%s: %s clk set rate(%dHz) failed, %d\n",
926 __func__, clki->name,
927 clki->max_freq, ret);
930 trace_ufshcd_clk_scaling(dev_name(hba->dev),
931 "scaled up", clki->name,
935 clki->curr_freq = clki->max_freq;
937 } else if (!scale_up && clki->min_freq) {
938 if (clki->curr_freq == clki->min_freq)
941 clk_state_changed = true;
942 ret = clk_set_rate(clki->clk, clki->min_freq);
944 dev_err(hba->dev, "%s: %s clk set rate(%dHz) failed, %d\n",
945 __func__, clki->name,
946 clki->min_freq, ret);
949 trace_ufshcd_clk_scaling(dev_name(hba->dev),
950 "scaled down", clki->name,
953 clki->curr_freq = clki->min_freq;
956 dev_dbg(hba->dev, "%s: clk: %s, rate: %lu\n", __func__,
957 clki->name, clk_get_rate(clki->clk));
960 ret = ufshcd_vops_clk_scale_notify(hba, scale_up, POST_CHANGE);
963 if (clk_state_changed)
964 trace_ufshcd_profile_clk_scaling(dev_name(hba->dev),
965 (scale_up ? "up" : "down"),
966 ktime_to_us(ktime_sub(ktime_get(), start)), ret);
971 * ufshcd_is_devfreq_scaling_required - check if scaling is required or not
972 * @hba: per adapter instance
973 * @scale_up: True if scaling up and false if scaling down
975 * Returns true if scaling is required, false otherwise.
977 static bool ufshcd_is_devfreq_scaling_required(struct ufs_hba *hba,
980 struct ufs_clk_info *clki;
981 struct list_head *head = &hba->clk_list_head;
983 if (list_empty(head))
986 list_for_each_entry(clki, head, list) {
987 if (!IS_ERR_OR_NULL(clki->clk)) {
988 if (scale_up && clki->max_freq) {
989 if (clki->curr_freq == clki->max_freq)
992 } else if (!scale_up && clki->min_freq) {
993 if (clki->curr_freq == clki->min_freq)
1003 static int ufshcd_wait_for_doorbell_clr(struct ufs_hba *hba,
1004 u64 wait_timeout_us)
1006 unsigned long flags;
1010 bool timeout = false, do_last_check = false;
1013 ufshcd_hold(hba, false);
1014 spin_lock_irqsave(hba->host->host_lock, flags);
1016 * Wait for all the outstanding tasks/transfer requests.
1017 * Verify by checking the doorbell registers are clear.
1019 start = ktime_get();
1021 if (hba->ufshcd_state != UFSHCD_STATE_OPERATIONAL) {
1026 tm_doorbell = ufshcd_readl(hba, REG_UTP_TASK_REQ_DOOR_BELL);
1027 tr_doorbell = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
1028 if (!tm_doorbell && !tr_doorbell) {
1031 } else if (do_last_check) {
1035 spin_unlock_irqrestore(hba->host->host_lock, flags);
1037 if (ktime_to_us(ktime_sub(ktime_get(), start)) >
1041 * We might have scheduled out for long time so make
1042 * sure to check if doorbells are cleared by this time
1045 do_last_check = true;
1047 spin_lock_irqsave(hba->host->host_lock, flags);
1048 } while (tm_doorbell || tr_doorbell);
1052 "%s: timedout waiting for doorbell to clear (tm=0x%x, tr=0x%x)\n",
1053 __func__, tm_doorbell, tr_doorbell);
1057 spin_unlock_irqrestore(hba->host->host_lock, flags);
1058 ufshcd_release(hba);
1063 * ufshcd_scale_gear - scale up/down UFS gear
1064 * @hba: per adapter instance
1065 * @scale_up: True for scaling up gear and false for scaling down
1067 * Returns 0 for success,
1068 * Returns -EBUSY if scaling can't happen at this time
1069 * Returns non-zero for any other errors
1071 static int ufshcd_scale_gear(struct ufs_hba *hba, bool scale_up)
1073 #define UFS_MIN_GEAR_TO_SCALE_DOWN UFS_HS_G1
1075 struct ufs_pa_layer_attr new_pwr_info;
1078 memcpy(&new_pwr_info, &hba->clk_scaling.saved_pwr_info.info,
1079 sizeof(struct ufs_pa_layer_attr));
1081 memcpy(&new_pwr_info, &hba->pwr_info,
1082 sizeof(struct ufs_pa_layer_attr));
1084 if (hba->pwr_info.gear_tx > UFS_MIN_GEAR_TO_SCALE_DOWN
1085 || hba->pwr_info.gear_rx > UFS_MIN_GEAR_TO_SCALE_DOWN) {
1086 /* save the current power mode */
1087 memcpy(&hba->clk_scaling.saved_pwr_info.info,
1089 sizeof(struct ufs_pa_layer_attr));
1091 /* scale down gear */
1092 new_pwr_info.gear_tx = UFS_MIN_GEAR_TO_SCALE_DOWN;
1093 new_pwr_info.gear_rx = UFS_MIN_GEAR_TO_SCALE_DOWN;
1097 /* check if the power mode needs to be changed or not? */
1098 ret = ufshcd_change_power_mode(hba, &new_pwr_info);
1101 dev_err(hba->dev, "%s: failed err %d, old gear: (tx %d rx %d), new gear: (tx %d rx %d)",
1103 hba->pwr_info.gear_tx, hba->pwr_info.gear_rx,
1104 new_pwr_info.gear_tx, new_pwr_info.gear_rx);
1109 static int ufshcd_clock_scaling_prepare(struct ufs_hba *hba)
1111 #define DOORBELL_CLR_TOUT_US (1000 * 1000) /* 1 sec */
1114 * make sure that there are no outstanding requests when
1115 * clock scaling is in progress
1117 ufshcd_scsi_block_requests(hba);
1118 down_write(&hba->clk_scaling_lock);
1119 if (ufshcd_wait_for_doorbell_clr(hba, DOORBELL_CLR_TOUT_US)) {
1121 up_write(&hba->clk_scaling_lock);
1122 ufshcd_scsi_unblock_requests(hba);
1128 static void ufshcd_clock_scaling_unprepare(struct ufs_hba *hba)
1130 up_write(&hba->clk_scaling_lock);
1131 ufshcd_scsi_unblock_requests(hba);
1135 * ufshcd_devfreq_scale - scale up/down UFS clocks and gear
1136 * @hba: per adapter instance
1137 * @scale_up: True for scaling up and false for scalin down
1139 * Returns 0 for success,
1140 * Returns -EBUSY if scaling can't happen at this time
1141 * Returns non-zero for any other errors
1143 static int ufshcd_devfreq_scale(struct ufs_hba *hba, bool scale_up)
1147 /* let's not get into low power until clock scaling is completed */
1148 ufshcd_hold(hba, false);
1150 ret = ufshcd_clock_scaling_prepare(hba);
1154 /* scale down the gear before scaling down clocks */
1156 ret = ufshcd_scale_gear(hba, false);
1161 ret = ufshcd_scale_clks(hba, scale_up);
1164 ufshcd_scale_gear(hba, true);
1168 /* scale up the gear after scaling up clocks */
1170 ret = ufshcd_scale_gear(hba, true);
1172 ufshcd_scale_clks(hba, false);
1177 ret = ufshcd_vops_clk_scale_notify(hba, scale_up, POST_CHANGE);
1180 ufshcd_clock_scaling_unprepare(hba);
1181 ufshcd_release(hba);
1185 static void ufshcd_clk_scaling_suspend_work(struct work_struct *work)
1187 struct ufs_hba *hba = container_of(work, struct ufs_hba,
1188 clk_scaling.suspend_work);
1189 unsigned long irq_flags;
1191 spin_lock_irqsave(hba->host->host_lock, irq_flags);
1192 if (hba->clk_scaling.active_reqs || hba->clk_scaling.is_suspended) {
1193 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1196 hba->clk_scaling.is_suspended = true;
1197 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1199 __ufshcd_suspend_clkscaling(hba);
1202 static void ufshcd_clk_scaling_resume_work(struct work_struct *work)
1204 struct ufs_hba *hba = container_of(work, struct ufs_hba,
1205 clk_scaling.resume_work);
1206 unsigned long irq_flags;
1208 spin_lock_irqsave(hba->host->host_lock, irq_flags);
1209 if (!hba->clk_scaling.is_suspended) {
1210 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1213 hba->clk_scaling.is_suspended = false;
1214 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1216 devfreq_resume_device(hba->devfreq);
1219 static int ufshcd_devfreq_target(struct device *dev,
1220 unsigned long *freq, u32 flags)
1223 struct ufs_hba *hba = dev_get_drvdata(dev);
1225 bool scale_up, sched_clk_scaling_suspend_work = false;
1226 struct list_head *clk_list = &hba->clk_list_head;
1227 struct ufs_clk_info *clki;
1228 unsigned long irq_flags;
1230 if (!ufshcd_is_clkscaling_supported(hba))
1233 spin_lock_irqsave(hba->host->host_lock, irq_flags);
1234 if (ufshcd_eh_in_progress(hba)) {
1235 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1239 if (!hba->clk_scaling.active_reqs)
1240 sched_clk_scaling_suspend_work = true;
1242 if (list_empty(clk_list)) {
1243 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1247 clki = list_first_entry(&hba->clk_list_head, struct ufs_clk_info, list);
1248 scale_up = (*freq == clki->max_freq) ? true : false;
1249 if (!ufshcd_is_devfreq_scaling_required(hba, scale_up)) {
1250 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1252 goto out; /* no state change required */
1254 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1256 start = ktime_get();
1257 ret = ufshcd_devfreq_scale(hba, scale_up);
1259 trace_ufshcd_profile_clk_scaling(dev_name(hba->dev),
1260 (scale_up ? "up" : "down"),
1261 ktime_to_us(ktime_sub(ktime_get(), start)), ret);
1264 if (sched_clk_scaling_suspend_work)
1265 queue_work(hba->clk_scaling.workq,
1266 &hba->clk_scaling.suspend_work);
1272 static int ufshcd_devfreq_get_dev_status(struct device *dev,
1273 struct devfreq_dev_status *stat)
1275 struct ufs_hba *hba = dev_get_drvdata(dev);
1276 struct ufs_clk_scaling *scaling = &hba->clk_scaling;
1277 unsigned long flags;
1279 if (!ufshcd_is_clkscaling_supported(hba))
1282 memset(stat, 0, sizeof(*stat));
1284 spin_lock_irqsave(hba->host->host_lock, flags);
1285 if (!scaling->window_start_t)
1288 if (scaling->is_busy_started)
1289 scaling->tot_busy_t += ktime_to_us(ktime_sub(ktime_get(),
1290 scaling->busy_start_t));
1292 stat->total_time = jiffies_to_usecs((long)jiffies -
1293 (long)scaling->window_start_t);
1294 stat->busy_time = scaling->tot_busy_t;
1296 scaling->window_start_t = jiffies;
1297 scaling->tot_busy_t = 0;
1299 if (hba->outstanding_reqs) {
1300 scaling->busy_start_t = ktime_get();
1301 scaling->is_busy_started = true;
1303 scaling->busy_start_t = 0;
1304 scaling->is_busy_started = false;
1306 spin_unlock_irqrestore(hba->host->host_lock, flags);
1310 static struct devfreq_dev_profile ufs_devfreq_profile = {
1312 .target = ufshcd_devfreq_target,
1313 .get_dev_status = ufshcd_devfreq_get_dev_status,
1316 static int ufshcd_devfreq_init(struct ufs_hba *hba)
1318 struct list_head *clk_list = &hba->clk_list_head;
1319 struct ufs_clk_info *clki;
1320 struct devfreq *devfreq;
1323 /* Skip devfreq if we don't have any clocks in the list */
1324 if (list_empty(clk_list))
1327 clki = list_first_entry(clk_list, struct ufs_clk_info, list);
1328 dev_pm_opp_add(hba->dev, clki->min_freq, 0);
1329 dev_pm_opp_add(hba->dev, clki->max_freq, 0);
1331 devfreq = devfreq_add_device(hba->dev,
1332 &ufs_devfreq_profile,
1333 DEVFREQ_GOV_SIMPLE_ONDEMAND,
1335 if (IS_ERR(devfreq)) {
1336 ret = PTR_ERR(devfreq);
1337 dev_err(hba->dev, "Unable to register with devfreq %d\n", ret);
1339 dev_pm_opp_remove(hba->dev, clki->min_freq);
1340 dev_pm_opp_remove(hba->dev, clki->max_freq);
1344 hba->devfreq = devfreq;
1349 static void ufshcd_devfreq_remove(struct ufs_hba *hba)
1351 struct list_head *clk_list = &hba->clk_list_head;
1352 struct ufs_clk_info *clki;
1357 devfreq_remove_device(hba->devfreq);
1358 hba->devfreq = NULL;
1360 clki = list_first_entry(clk_list, struct ufs_clk_info, list);
1361 dev_pm_opp_remove(hba->dev, clki->min_freq);
1362 dev_pm_opp_remove(hba->dev, clki->max_freq);
1365 static void __ufshcd_suspend_clkscaling(struct ufs_hba *hba)
1367 unsigned long flags;
1369 devfreq_suspend_device(hba->devfreq);
1370 spin_lock_irqsave(hba->host->host_lock, flags);
1371 hba->clk_scaling.window_start_t = 0;
1372 spin_unlock_irqrestore(hba->host->host_lock, flags);
1375 static void ufshcd_suspend_clkscaling(struct ufs_hba *hba)
1377 unsigned long flags;
1378 bool suspend = false;
1380 if (!ufshcd_is_clkscaling_supported(hba))
1383 spin_lock_irqsave(hba->host->host_lock, flags);
1384 if (!hba->clk_scaling.is_suspended) {
1386 hba->clk_scaling.is_suspended = true;
1388 spin_unlock_irqrestore(hba->host->host_lock, flags);
1391 __ufshcd_suspend_clkscaling(hba);
1394 static void ufshcd_resume_clkscaling(struct ufs_hba *hba)
1396 unsigned long flags;
1397 bool resume = false;
1399 if (!ufshcd_is_clkscaling_supported(hba))
1402 spin_lock_irqsave(hba->host->host_lock, flags);
1403 if (hba->clk_scaling.is_suspended) {
1405 hba->clk_scaling.is_suspended = false;
1407 spin_unlock_irqrestore(hba->host->host_lock, flags);
1410 devfreq_resume_device(hba->devfreq);
1413 static ssize_t ufshcd_clkscale_enable_show(struct device *dev,
1414 struct device_attribute *attr, char *buf)
1416 struct ufs_hba *hba = dev_get_drvdata(dev);
1418 return snprintf(buf, PAGE_SIZE, "%d\n", hba->clk_scaling.is_allowed);
1421 static ssize_t ufshcd_clkscale_enable_store(struct device *dev,
1422 struct device_attribute *attr, const char *buf, size_t count)
1424 struct ufs_hba *hba = dev_get_drvdata(dev);
1428 if (kstrtou32(buf, 0, &value))
1432 if (value == hba->clk_scaling.is_allowed)
1435 pm_runtime_get_sync(hba->dev);
1436 ufshcd_hold(hba, false);
1438 cancel_work_sync(&hba->clk_scaling.suspend_work);
1439 cancel_work_sync(&hba->clk_scaling.resume_work);
1441 hba->clk_scaling.is_allowed = value;
1444 ufshcd_resume_clkscaling(hba);
1446 ufshcd_suspend_clkscaling(hba);
1447 err = ufshcd_devfreq_scale(hba, true);
1449 dev_err(hba->dev, "%s: failed to scale clocks up %d\n",
1453 ufshcd_release(hba);
1454 pm_runtime_put_sync(hba->dev);
1459 static void ufshcd_clkscaling_init_sysfs(struct ufs_hba *hba)
1461 hba->clk_scaling.enable_attr.show = ufshcd_clkscale_enable_show;
1462 hba->clk_scaling.enable_attr.store = ufshcd_clkscale_enable_store;
1463 sysfs_attr_init(&hba->clk_scaling.enable_attr.attr);
1464 hba->clk_scaling.enable_attr.attr.name = "clkscale_enable";
1465 hba->clk_scaling.enable_attr.attr.mode = 0644;
1466 if (device_create_file(hba->dev, &hba->clk_scaling.enable_attr))
1467 dev_err(hba->dev, "Failed to create sysfs for clkscale_enable\n");
1470 static void ufshcd_ungate_work(struct work_struct *work)
1473 unsigned long flags;
1474 struct ufs_hba *hba = container_of(work, struct ufs_hba,
1475 clk_gating.ungate_work);
1477 cancel_delayed_work_sync(&hba->clk_gating.gate_work);
1479 spin_lock_irqsave(hba->host->host_lock, flags);
1480 if (hba->clk_gating.state == CLKS_ON) {
1481 spin_unlock_irqrestore(hba->host->host_lock, flags);
1485 spin_unlock_irqrestore(hba->host->host_lock, flags);
1486 ufshcd_setup_clocks(hba, true);
1488 /* Exit from hibern8 */
1489 if (ufshcd_can_hibern8_during_gating(hba)) {
1490 /* Prevent gating in this path */
1491 hba->clk_gating.is_suspended = true;
1492 if (ufshcd_is_link_hibern8(hba)) {
1493 ret = ufshcd_uic_hibern8_exit(hba);
1495 dev_err(hba->dev, "%s: hibern8 exit failed %d\n",
1498 ufshcd_set_link_active(hba);
1500 hba->clk_gating.is_suspended = false;
1503 ufshcd_scsi_unblock_requests(hba);
1507 * ufshcd_hold - Enable clocks that were gated earlier due to ufshcd_release.
1508 * Also, exit from hibern8 mode and set the link as active.
1509 * @hba: per adapter instance
1510 * @async: This indicates whether caller should ungate clocks asynchronously.
1512 int ufshcd_hold(struct ufs_hba *hba, bool async)
1515 unsigned long flags;
1517 if (!ufshcd_is_clkgating_allowed(hba))
1519 spin_lock_irqsave(hba->host->host_lock, flags);
1520 hba->clk_gating.active_reqs++;
1522 if (ufshcd_eh_in_progress(hba)) {
1523 spin_unlock_irqrestore(hba->host->host_lock, flags);
1528 switch (hba->clk_gating.state) {
1531 * Wait for the ungate work to complete if in progress.
1532 * Though the clocks may be in ON state, the link could
1533 * still be in hibner8 state if hibern8 is allowed
1534 * during clock gating.
1535 * Make sure we exit hibern8 state also in addition to
1538 if (ufshcd_can_hibern8_during_gating(hba) &&
1539 ufshcd_is_link_hibern8(hba)) {
1540 spin_unlock_irqrestore(hba->host->host_lock, flags);
1541 flush_work(&hba->clk_gating.ungate_work);
1542 spin_lock_irqsave(hba->host->host_lock, flags);
1547 if (cancel_delayed_work(&hba->clk_gating.gate_work)) {
1548 hba->clk_gating.state = CLKS_ON;
1549 trace_ufshcd_clk_gating(dev_name(hba->dev),
1550 hba->clk_gating.state);
1554 * If we are here, it means gating work is either done or
1555 * currently running. Hence, fall through to cancel gating
1556 * work and to enable clocks.
1560 ufshcd_scsi_block_requests(hba);
1561 hba->clk_gating.state = REQ_CLKS_ON;
1562 trace_ufshcd_clk_gating(dev_name(hba->dev),
1563 hba->clk_gating.state);
1564 queue_work(hba->clk_gating.clk_gating_workq,
1565 &hba->clk_gating.ungate_work);
1567 * fall through to check if we should wait for this
1568 * work to be done or not.
1574 hba->clk_gating.active_reqs--;
1578 spin_unlock_irqrestore(hba->host->host_lock, flags);
1579 flush_work(&hba->clk_gating.ungate_work);
1580 /* Make sure state is CLKS_ON before returning */
1581 spin_lock_irqsave(hba->host->host_lock, flags);
1584 dev_err(hba->dev, "%s: clk gating is in invalid state %d\n",
1585 __func__, hba->clk_gating.state);
1588 spin_unlock_irqrestore(hba->host->host_lock, flags);
1592 EXPORT_SYMBOL_GPL(ufshcd_hold);
1594 static void ufshcd_gate_work(struct work_struct *work)
1596 struct ufs_hba *hba = container_of(work, struct ufs_hba,
1597 clk_gating.gate_work.work);
1598 unsigned long flags;
1600 spin_lock_irqsave(hba->host->host_lock, flags);
1602 * In case you are here to cancel this work the gating state
1603 * would be marked as REQ_CLKS_ON. In this case save time by
1604 * skipping the gating work and exit after changing the clock
1607 if (hba->clk_gating.is_suspended ||
1608 (hba->clk_gating.state == REQ_CLKS_ON)) {
1609 hba->clk_gating.state = CLKS_ON;
1610 trace_ufshcd_clk_gating(dev_name(hba->dev),
1611 hba->clk_gating.state);
1615 if (hba->clk_gating.active_reqs
1616 || hba->ufshcd_state != UFSHCD_STATE_OPERATIONAL
1617 || hba->lrb_in_use || hba->outstanding_tasks
1618 || hba->active_uic_cmd || hba->uic_async_done)
1621 spin_unlock_irqrestore(hba->host->host_lock, flags);
1623 /* put the link into hibern8 mode before turning off clocks */
1624 if (ufshcd_can_hibern8_during_gating(hba)) {
1625 if (ufshcd_uic_hibern8_enter(hba)) {
1626 hba->clk_gating.state = CLKS_ON;
1627 trace_ufshcd_clk_gating(dev_name(hba->dev),
1628 hba->clk_gating.state);
1631 ufshcd_set_link_hibern8(hba);
1634 if (!ufshcd_is_link_active(hba))
1635 ufshcd_setup_clocks(hba, false);
1637 /* If link is active, device ref_clk can't be switched off */
1638 __ufshcd_setup_clocks(hba, false, true);
1641 * In case you are here to cancel this work the gating state
1642 * would be marked as REQ_CLKS_ON. In this case keep the state
1643 * as REQ_CLKS_ON which would anyway imply that clocks are off
1644 * and a request to turn them on is pending. By doing this way,
1645 * we keep the state machine in tact and this would ultimately
1646 * prevent from doing cancel work multiple times when there are
1647 * new requests arriving before the current cancel work is done.
1649 spin_lock_irqsave(hba->host->host_lock, flags);
1650 if (hba->clk_gating.state == REQ_CLKS_OFF) {
1651 hba->clk_gating.state = CLKS_OFF;
1652 trace_ufshcd_clk_gating(dev_name(hba->dev),
1653 hba->clk_gating.state);
1656 spin_unlock_irqrestore(hba->host->host_lock, flags);
1661 /* host lock must be held before calling this variant */
1662 static void __ufshcd_release(struct ufs_hba *hba)
1664 if (!ufshcd_is_clkgating_allowed(hba))
1667 hba->clk_gating.active_reqs--;
1669 if (hba->clk_gating.active_reqs || hba->clk_gating.is_suspended
1670 || hba->ufshcd_state != UFSHCD_STATE_OPERATIONAL
1671 || hba->lrb_in_use || hba->outstanding_tasks
1672 || hba->active_uic_cmd || hba->uic_async_done
1673 || ufshcd_eh_in_progress(hba))
1676 hba->clk_gating.state = REQ_CLKS_OFF;
1677 trace_ufshcd_clk_gating(dev_name(hba->dev), hba->clk_gating.state);
1678 queue_delayed_work(hba->clk_gating.clk_gating_workq,
1679 &hba->clk_gating.gate_work,
1680 msecs_to_jiffies(hba->clk_gating.delay_ms));
1683 void ufshcd_release(struct ufs_hba *hba)
1685 unsigned long flags;
1687 spin_lock_irqsave(hba->host->host_lock, flags);
1688 __ufshcd_release(hba);
1689 spin_unlock_irqrestore(hba->host->host_lock, flags);
1691 EXPORT_SYMBOL_GPL(ufshcd_release);
1693 static ssize_t ufshcd_clkgate_delay_show(struct device *dev,
1694 struct device_attribute *attr, char *buf)
1696 struct ufs_hba *hba = dev_get_drvdata(dev);
1698 return snprintf(buf, PAGE_SIZE, "%lu\n", hba->clk_gating.delay_ms);
1701 static ssize_t ufshcd_clkgate_delay_store(struct device *dev,
1702 struct device_attribute *attr, const char *buf, size_t count)
1704 struct ufs_hba *hba = dev_get_drvdata(dev);
1705 unsigned long flags, value;
1707 if (kstrtoul(buf, 0, &value))
1710 spin_lock_irqsave(hba->host->host_lock, flags);
1711 hba->clk_gating.delay_ms = value;
1712 spin_unlock_irqrestore(hba->host->host_lock, flags);
1716 static ssize_t ufshcd_clkgate_enable_show(struct device *dev,
1717 struct device_attribute *attr, char *buf)
1719 struct ufs_hba *hba = dev_get_drvdata(dev);
1721 return snprintf(buf, PAGE_SIZE, "%d\n", hba->clk_gating.is_enabled);
1724 static ssize_t ufshcd_clkgate_enable_store(struct device *dev,
1725 struct device_attribute *attr, const char *buf, size_t count)
1727 struct ufs_hba *hba = dev_get_drvdata(dev);
1728 unsigned long flags;
1731 if (kstrtou32(buf, 0, &value))
1735 if (value == hba->clk_gating.is_enabled)
1739 ufshcd_release(hba);
1741 spin_lock_irqsave(hba->host->host_lock, flags);
1742 hba->clk_gating.active_reqs++;
1743 spin_unlock_irqrestore(hba->host->host_lock, flags);
1746 hba->clk_gating.is_enabled = value;
1751 static void ufshcd_init_clk_scaling(struct ufs_hba *hba)
1753 char wq_name[sizeof("ufs_clkscaling_00")];
1755 if (!ufshcd_is_clkscaling_supported(hba))
1758 INIT_WORK(&hba->clk_scaling.suspend_work,
1759 ufshcd_clk_scaling_suspend_work);
1760 INIT_WORK(&hba->clk_scaling.resume_work,
1761 ufshcd_clk_scaling_resume_work);
1763 snprintf(wq_name, sizeof(wq_name), "ufs_clkscaling_%d",
1764 hba->host->host_no);
1765 hba->clk_scaling.workq = create_singlethread_workqueue(wq_name);
1767 ufshcd_clkscaling_init_sysfs(hba);
1770 static void ufshcd_exit_clk_scaling(struct ufs_hba *hba)
1772 if (!ufshcd_is_clkscaling_supported(hba))
1775 destroy_workqueue(hba->clk_scaling.workq);
1776 ufshcd_devfreq_remove(hba);
1779 static void ufshcd_init_clk_gating(struct ufs_hba *hba)
1781 char wq_name[sizeof("ufs_clk_gating_00")];
1783 if (!ufshcd_is_clkgating_allowed(hba))
1786 hba->clk_gating.delay_ms = 150;
1787 INIT_DELAYED_WORK(&hba->clk_gating.gate_work, ufshcd_gate_work);
1788 INIT_WORK(&hba->clk_gating.ungate_work, ufshcd_ungate_work);
1790 snprintf(wq_name, ARRAY_SIZE(wq_name), "ufs_clk_gating_%d",
1791 hba->host->host_no);
1792 hba->clk_gating.clk_gating_workq = alloc_ordered_workqueue(wq_name,
1795 hba->clk_gating.is_enabled = true;
1797 hba->clk_gating.delay_attr.show = ufshcd_clkgate_delay_show;
1798 hba->clk_gating.delay_attr.store = ufshcd_clkgate_delay_store;
1799 sysfs_attr_init(&hba->clk_gating.delay_attr.attr);
1800 hba->clk_gating.delay_attr.attr.name = "clkgate_delay_ms";
1801 hba->clk_gating.delay_attr.attr.mode = 0644;
1802 if (device_create_file(hba->dev, &hba->clk_gating.delay_attr))
1803 dev_err(hba->dev, "Failed to create sysfs for clkgate_delay\n");
1805 hba->clk_gating.enable_attr.show = ufshcd_clkgate_enable_show;
1806 hba->clk_gating.enable_attr.store = ufshcd_clkgate_enable_store;
1807 sysfs_attr_init(&hba->clk_gating.enable_attr.attr);
1808 hba->clk_gating.enable_attr.attr.name = "clkgate_enable";
1809 hba->clk_gating.enable_attr.attr.mode = 0644;
1810 if (device_create_file(hba->dev, &hba->clk_gating.enable_attr))
1811 dev_err(hba->dev, "Failed to create sysfs for clkgate_enable\n");
1814 static void ufshcd_exit_clk_gating(struct ufs_hba *hba)
1816 if (!ufshcd_is_clkgating_allowed(hba))
1818 device_remove_file(hba->dev, &hba->clk_gating.delay_attr);
1819 device_remove_file(hba->dev, &hba->clk_gating.enable_attr);
1820 cancel_work_sync(&hba->clk_gating.ungate_work);
1821 cancel_delayed_work_sync(&hba->clk_gating.gate_work);
1822 destroy_workqueue(hba->clk_gating.clk_gating_workq);
1825 /* Must be called with host lock acquired */
1826 static void ufshcd_clk_scaling_start_busy(struct ufs_hba *hba)
1828 bool queue_resume_work = false;
1830 if (!ufshcd_is_clkscaling_supported(hba))
1833 if (!hba->clk_scaling.active_reqs++)
1834 queue_resume_work = true;
1836 if (!hba->clk_scaling.is_allowed || hba->pm_op_in_progress)
1839 if (queue_resume_work)
1840 queue_work(hba->clk_scaling.workq,
1841 &hba->clk_scaling.resume_work);
1843 if (!hba->clk_scaling.window_start_t) {
1844 hba->clk_scaling.window_start_t = jiffies;
1845 hba->clk_scaling.tot_busy_t = 0;
1846 hba->clk_scaling.is_busy_started = false;
1849 if (!hba->clk_scaling.is_busy_started) {
1850 hba->clk_scaling.busy_start_t = ktime_get();
1851 hba->clk_scaling.is_busy_started = true;
1855 static void ufshcd_clk_scaling_update_busy(struct ufs_hba *hba)
1857 struct ufs_clk_scaling *scaling = &hba->clk_scaling;
1859 if (!ufshcd_is_clkscaling_supported(hba))
1862 if (!hba->outstanding_reqs && scaling->is_busy_started) {
1863 scaling->tot_busy_t += ktime_to_us(ktime_sub(ktime_get(),
1864 scaling->busy_start_t));
1865 scaling->busy_start_t = 0;
1866 scaling->is_busy_started = false;
1870 * ufshcd_send_command - Send SCSI or device management commands
1871 * @hba: per adapter instance
1872 * @task_tag: Task tag of the command
1875 void ufshcd_send_command(struct ufs_hba *hba, unsigned int task_tag)
1877 hba->lrb[task_tag].issue_time_stamp = ktime_get();
1878 hba->lrb[task_tag].compl_time_stamp = ktime_set(0, 0);
1879 ufshcd_clk_scaling_start_busy(hba);
1880 __set_bit(task_tag, &hba->outstanding_reqs);
1881 ufshcd_writel(hba, 1 << task_tag, REG_UTP_TRANSFER_REQ_DOOR_BELL);
1882 /* Make sure that doorbell is committed immediately */
1884 ufshcd_add_command_trace(hba, task_tag, "send");
1888 * ufshcd_copy_sense_data - Copy sense data in case of check condition
1889 * @lrbp: pointer to local reference block
1891 static inline void ufshcd_copy_sense_data(struct ufshcd_lrb *lrbp)
1894 if (lrbp->sense_buffer &&
1895 ufshcd_get_rsp_upiu_data_seg_len(lrbp->ucd_rsp_ptr)) {
1898 len = be16_to_cpu(lrbp->ucd_rsp_ptr->sr.sense_data_len);
1899 len_to_copy = min_t(int, UFS_SENSE_SIZE, len);
1901 memcpy(lrbp->sense_buffer, lrbp->ucd_rsp_ptr->sr.sense_data,
1907 * ufshcd_copy_query_response() - Copy the Query Response and the data
1909 * @hba: per adapter instance
1910 * @lrbp: pointer to local reference block
1913 int ufshcd_copy_query_response(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
1915 struct ufs_query_res *query_res = &hba->dev_cmd.query.response;
1917 memcpy(&query_res->upiu_res, &lrbp->ucd_rsp_ptr->qr, QUERY_OSF_SIZE);
1919 /* Get the descriptor */
1920 if (hba->dev_cmd.query.descriptor &&
1921 lrbp->ucd_rsp_ptr->qr.opcode == UPIU_QUERY_OPCODE_READ_DESC) {
1922 u8 *descp = (u8 *)lrbp->ucd_rsp_ptr +
1923 GENERAL_UPIU_REQUEST_SIZE;
1927 /* data segment length */
1928 resp_len = be32_to_cpu(lrbp->ucd_rsp_ptr->header.dword_2) &
1929 MASK_QUERY_DATA_SEG_LEN;
1930 buf_len = be16_to_cpu(
1931 hba->dev_cmd.query.request.upiu_req.length);
1932 if (likely(buf_len >= resp_len)) {
1933 memcpy(hba->dev_cmd.query.descriptor, descp, resp_len);
1936 "%s: Response size is bigger than buffer",
1946 * ufshcd_hba_capabilities - Read controller capabilities
1947 * @hba: per adapter instance
1949 static inline void ufshcd_hba_capabilities(struct ufs_hba *hba)
1951 hba->capabilities = ufshcd_readl(hba, REG_CONTROLLER_CAPABILITIES);
1953 /* nutrs and nutmrs are 0 based values */
1954 hba->nutrs = (hba->capabilities & MASK_TRANSFER_REQUESTS_SLOTS) + 1;
1956 ((hba->capabilities & MASK_TASK_MANAGEMENT_REQUEST_SLOTS) >> 16) + 1;
1960 * ufshcd_ready_for_uic_cmd - Check if controller is ready
1961 * to accept UIC commands
1962 * @hba: per adapter instance
1963 * Return true on success, else false
1965 static inline bool ufshcd_ready_for_uic_cmd(struct ufs_hba *hba)
1967 if (ufshcd_readl(hba, REG_CONTROLLER_STATUS) & UIC_COMMAND_READY)
1974 * ufshcd_get_upmcrs - Get the power mode change request status
1975 * @hba: Pointer to adapter instance
1977 * This function gets the UPMCRS field of HCS register
1978 * Returns value of UPMCRS field
1980 static inline u8 ufshcd_get_upmcrs(struct ufs_hba *hba)
1982 return (ufshcd_readl(hba, REG_CONTROLLER_STATUS) >> 8) & 0x7;
1986 * ufshcd_dispatch_uic_cmd - Dispatch UIC commands to unipro layers
1987 * @hba: per adapter instance
1988 * @uic_cmd: UIC command
1990 * Mutex must be held.
1993 ufshcd_dispatch_uic_cmd(struct ufs_hba *hba, struct uic_command *uic_cmd)
1995 WARN_ON(hba->active_uic_cmd);
1997 hba->active_uic_cmd = uic_cmd;
2000 ufshcd_writel(hba, uic_cmd->argument1, REG_UIC_COMMAND_ARG_1);
2001 ufshcd_writel(hba, uic_cmd->argument2, REG_UIC_COMMAND_ARG_2);
2002 ufshcd_writel(hba, uic_cmd->argument3, REG_UIC_COMMAND_ARG_3);
2005 ufshcd_writel(hba, uic_cmd->command & COMMAND_OPCODE_MASK,
2010 * ufshcd_wait_for_uic_cmd - Wait complectioin of UIC command
2011 * @hba: per adapter instance
2012 * @uic_cmd: UIC command
2014 * Must be called with mutex held.
2015 * Returns 0 only if success.
2018 ufshcd_wait_for_uic_cmd(struct ufs_hba *hba, struct uic_command *uic_cmd)
2021 unsigned long flags;
2023 if (wait_for_completion_timeout(&uic_cmd->done,
2024 msecs_to_jiffies(UIC_CMD_TIMEOUT)))
2025 ret = uic_cmd->argument2 & MASK_UIC_COMMAND_RESULT;
2029 spin_lock_irqsave(hba->host->host_lock, flags);
2030 hba->active_uic_cmd = NULL;
2031 spin_unlock_irqrestore(hba->host->host_lock, flags);
2037 * __ufshcd_send_uic_cmd - Send UIC commands and retrieve the result
2038 * @hba: per adapter instance
2039 * @uic_cmd: UIC command
2040 * @completion: initialize the completion only if this is set to true
2042 * Identical to ufshcd_send_uic_cmd() expect mutex. Must be called
2043 * with mutex held and host_lock locked.
2044 * Returns 0 only if success.
2047 __ufshcd_send_uic_cmd(struct ufs_hba *hba, struct uic_command *uic_cmd,
2050 if (!ufshcd_ready_for_uic_cmd(hba)) {
2052 "Controller not ready to accept UIC commands\n");
2057 init_completion(&uic_cmd->done);
2059 ufshcd_dispatch_uic_cmd(hba, uic_cmd);
2065 * ufshcd_send_uic_cmd - Send UIC commands and retrieve the result
2066 * @hba: per adapter instance
2067 * @uic_cmd: UIC command
2069 * Returns 0 only if success.
2071 int ufshcd_send_uic_cmd(struct ufs_hba *hba, struct uic_command *uic_cmd)
2074 unsigned long flags;
2076 ufshcd_hold(hba, false);
2077 mutex_lock(&hba->uic_cmd_mutex);
2078 ufshcd_add_delay_before_dme_cmd(hba);
2080 spin_lock_irqsave(hba->host->host_lock, flags);
2081 ret = __ufshcd_send_uic_cmd(hba, uic_cmd, true);
2082 spin_unlock_irqrestore(hba->host->host_lock, flags);
2084 ret = ufshcd_wait_for_uic_cmd(hba, uic_cmd);
2086 mutex_unlock(&hba->uic_cmd_mutex);
2088 ufshcd_release(hba);
2093 * ufshcd_map_sg - Map scatter-gather list to prdt
2094 * @hba: per adapter instance
2095 * @lrbp: pointer to local reference block
2097 * Returns 0 in case of success, non-zero value in case of failure
2099 static int ufshcd_map_sg(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
2101 struct ufshcd_sg_entry *prd_table;
2102 struct scatterlist *sg;
2103 struct scsi_cmnd *cmd;
2108 sg_segments = scsi_dma_map(cmd);
2109 if (sg_segments < 0)
2113 if (hba->quirks & UFSHCD_QUIRK_PRDT_BYTE_GRAN)
2114 lrbp->utr_descriptor_ptr->prd_table_length =
2115 cpu_to_le16((u16)(sg_segments *
2116 sizeof(struct ufshcd_sg_entry)));
2118 lrbp->utr_descriptor_ptr->prd_table_length =
2119 cpu_to_le16((u16) (sg_segments));
2121 prd_table = (struct ufshcd_sg_entry *)lrbp->ucd_prdt_ptr;
2123 scsi_for_each_sg(cmd, sg, sg_segments, i) {
2125 cpu_to_le32(((u32) sg_dma_len(sg))-1);
2126 prd_table[i].base_addr =
2127 cpu_to_le32(lower_32_bits(sg->dma_address));
2128 prd_table[i].upper_addr =
2129 cpu_to_le32(upper_32_bits(sg->dma_address));
2130 prd_table[i].reserved = 0;
2133 lrbp->utr_descriptor_ptr->prd_table_length = 0;
2140 * ufshcd_enable_intr - enable interrupts
2141 * @hba: per adapter instance
2142 * @intrs: interrupt bits
2144 static void ufshcd_enable_intr(struct ufs_hba *hba, u32 intrs)
2146 u32 set = ufshcd_readl(hba, REG_INTERRUPT_ENABLE);
2148 if (hba->ufs_version == UFSHCI_VERSION_10) {
2150 rw = set & INTERRUPT_MASK_RW_VER_10;
2151 set = rw | ((set ^ intrs) & intrs);
2156 ufshcd_writel(hba, set, REG_INTERRUPT_ENABLE);
2160 * ufshcd_disable_intr - disable interrupts
2161 * @hba: per adapter instance
2162 * @intrs: interrupt bits
2164 static void ufshcd_disable_intr(struct ufs_hba *hba, u32 intrs)
2166 u32 set = ufshcd_readl(hba, REG_INTERRUPT_ENABLE);
2168 if (hba->ufs_version == UFSHCI_VERSION_10) {
2170 rw = (set & INTERRUPT_MASK_RW_VER_10) &
2171 ~(intrs & INTERRUPT_MASK_RW_VER_10);
2172 set = rw | ((set & intrs) & ~INTERRUPT_MASK_RW_VER_10);
2178 ufshcd_writel(hba, set, REG_INTERRUPT_ENABLE);
2182 * ufshcd_prepare_req_desc_hdr() - Fills the requests header
2183 * descriptor according to request
2184 * @lrbp: pointer to local reference block
2185 * @upiu_flags: flags required in the header
2186 * @cmd_dir: requests data direction
2188 static void ufshcd_prepare_req_desc_hdr(struct ufshcd_lrb *lrbp,
2189 u32 *upiu_flags, enum dma_data_direction cmd_dir)
2191 struct utp_transfer_req_desc *req_desc = lrbp->utr_descriptor_ptr;
2195 if (cmd_dir == DMA_FROM_DEVICE) {
2196 data_direction = UTP_DEVICE_TO_HOST;
2197 *upiu_flags = UPIU_CMD_FLAGS_READ;
2198 } else if (cmd_dir == DMA_TO_DEVICE) {
2199 data_direction = UTP_HOST_TO_DEVICE;
2200 *upiu_flags = UPIU_CMD_FLAGS_WRITE;
2202 data_direction = UTP_NO_DATA_TRANSFER;
2203 *upiu_flags = UPIU_CMD_FLAGS_NONE;
2206 dword_0 = data_direction | (lrbp->command_type
2207 << UPIU_COMMAND_TYPE_OFFSET);
2209 dword_0 |= UTP_REQ_DESC_INT_CMD;
2211 /* Transfer request descriptor header fields */
2212 req_desc->header.dword_0 = cpu_to_le32(dword_0);
2213 /* dword_1 is reserved, hence it is set to 0 */
2214 req_desc->header.dword_1 = 0;
2216 * assigning invalid value for command status. Controller
2217 * updates OCS on command completion, with the command
2220 req_desc->header.dword_2 =
2221 cpu_to_le32(OCS_INVALID_COMMAND_STATUS);
2222 /* dword_3 is reserved, hence it is set to 0 */
2223 req_desc->header.dword_3 = 0;
2225 req_desc->prd_table_length = 0;
2229 * ufshcd_prepare_utp_scsi_cmd_upiu() - fills the utp_transfer_req_desc,
2231 * @lrbp: local reference block pointer
2232 * @upiu_flags: flags
2235 void ufshcd_prepare_utp_scsi_cmd_upiu(struct ufshcd_lrb *lrbp, u32 upiu_flags)
2237 struct utp_upiu_req *ucd_req_ptr = lrbp->ucd_req_ptr;
2238 unsigned short cdb_len;
2240 /* command descriptor fields */
2241 ucd_req_ptr->header.dword_0 = UPIU_HEADER_DWORD(
2242 UPIU_TRANSACTION_COMMAND, upiu_flags,
2243 lrbp->lun, lrbp->task_tag);
2244 ucd_req_ptr->header.dword_1 = UPIU_HEADER_DWORD(
2245 UPIU_COMMAND_SET_TYPE_SCSI, 0, 0, 0);
2247 /* Total EHS length and Data segment length will be zero */
2248 ucd_req_ptr->header.dword_2 = 0;
2250 ucd_req_ptr->sc.exp_data_transfer_len =
2251 cpu_to_be32(lrbp->cmd->sdb.length);
2253 cdb_len = min_t(unsigned short, lrbp->cmd->cmd_len, UFS_CDB_SIZE);
2254 memset(ucd_req_ptr->sc.cdb, 0, UFS_CDB_SIZE);
2255 memcpy(ucd_req_ptr->sc.cdb, lrbp->cmd->cmnd, cdb_len);
2257 memset(lrbp->ucd_rsp_ptr, 0, sizeof(struct utp_upiu_rsp));
2261 * ufshcd_prepare_utp_query_req_upiu() - fills the utp_transfer_req_desc,
2264 * @lrbp: local reference block pointer
2265 * @upiu_flags: flags
2267 static void ufshcd_prepare_utp_query_req_upiu(struct ufs_hba *hba,
2268 struct ufshcd_lrb *lrbp, u32 upiu_flags)
2270 struct utp_upiu_req *ucd_req_ptr = lrbp->ucd_req_ptr;
2271 struct ufs_query *query = &hba->dev_cmd.query;
2272 u16 len = be16_to_cpu(query->request.upiu_req.length);
2274 /* Query request header */
2275 ucd_req_ptr->header.dword_0 = UPIU_HEADER_DWORD(
2276 UPIU_TRANSACTION_QUERY_REQ, upiu_flags,
2277 lrbp->lun, lrbp->task_tag);
2278 ucd_req_ptr->header.dword_1 = UPIU_HEADER_DWORD(
2279 0, query->request.query_func, 0, 0);
2281 /* Data segment length only need for WRITE_DESC */
2282 if (query->request.upiu_req.opcode == UPIU_QUERY_OPCODE_WRITE_DESC)
2283 ucd_req_ptr->header.dword_2 =
2284 UPIU_HEADER_DWORD(0, 0, (len >> 8), (u8)len);
2286 ucd_req_ptr->header.dword_2 = 0;
2288 /* Copy the Query Request buffer as is */
2289 memcpy(&ucd_req_ptr->qr, &query->request.upiu_req,
2292 /* Copy the Descriptor */
2293 if (query->request.upiu_req.opcode == UPIU_QUERY_OPCODE_WRITE_DESC)
2294 memcpy(ucd_req_ptr + 1, query->descriptor, len);
2296 memset(lrbp->ucd_rsp_ptr, 0, sizeof(struct utp_upiu_rsp));
2299 static inline void ufshcd_prepare_utp_nop_upiu(struct ufshcd_lrb *lrbp)
2301 struct utp_upiu_req *ucd_req_ptr = lrbp->ucd_req_ptr;
2303 memset(ucd_req_ptr, 0, sizeof(struct utp_upiu_req));
2305 /* command descriptor fields */
2306 ucd_req_ptr->header.dword_0 =
2308 UPIU_TRANSACTION_NOP_OUT, 0, 0, lrbp->task_tag);
2309 /* clear rest of the fields of basic header */
2310 ucd_req_ptr->header.dword_1 = 0;
2311 ucd_req_ptr->header.dword_2 = 0;
2313 memset(lrbp->ucd_rsp_ptr, 0, sizeof(struct utp_upiu_rsp));
2317 * ufshcd_comp_devman_upiu - UFS Protocol Information Unit(UPIU)
2318 * for Device Management Purposes
2319 * @hba: per adapter instance
2320 * @lrbp: pointer to local reference block
2322 static int ufshcd_comp_devman_upiu(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
2327 if ((hba->ufs_version == UFSHCI_VERSION_10) ||
2328 (hba->ufs_version == UFSHCI_VERSION_11))
2329 lrbp->command_type = UTP_CMD_TYPE_DEV_MANAGE;
2331 lrbp->command_type = UTP_CMD_TYPE_UFS_STORAGE;
2333 ufshcd_prepare_req_desc_hdr(lrbp, &upiu_flags, DMA_NONE);
2334 if (hba->dev_cmd.type == DEV_CMD_TYPE_QUERY)
2335 ufshcd_prepare_utp_query_req_upiu(hba, lrbp, upiu_flags);
2336 else if (hba->dev_cmd.type == DEV_CMD_TYPE_NOP)
2337 ufshcd_prepare_utp_nop_upiu(lrbp);
2345 * ufshcd_comp_scsi_upiu - UFS Protocol Information Unit(UPIU)
2347 * @hba: per adapter instance
2348 * @lrbp: pointer to local reference block
2350 static int ufshcd_comp_scsi_upiu(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
2355 if ((hba->ufs_version == UFSHCI_VERSION_10) ||
2356 (hba->ufs_version == UFSHCI_VERSION_11))
2357 lrbp->command_type = UTP_CMD_TYPE_SCSI;
2359 lrbp->command_type = UTP_CMD_TYPE_UFS_STORAGE;
2361 if (likely(lrbp->cmd)) {
2362 ufshcd_prepare_req_desc_hdr(lrbp, &upiu_flags,
2363 lrbp->cmd->sc_data_direction);
2364 ufshcd_prepare_utp_scsi_cmd_upiu(lrbp, upiu_flags);
2373 * ufshcd_upiu_wlun_to_scsi_wlun - maps UPIU W-LUN id to SCSI W-LUN ID
2374 * @upiu_wlun_id: UPIU W-LUN id
2376 * Returns SCSI W-LUN id
2378 static inline u16 ufshcd_upiu_wlun_to_scsi_wlun(u8 upiu_wlun_id)
2380 return (upiu_wlun_id & ~UFS_UPIU_WLUN_ID) | SCSI_W_LUN_BASE;
2384 * ufshcd_queuecommand - main entry point for SCSI requests
2385 * @host: SCSI host pointer
2386 * @cmd: command from SCSI Midlayer
2388 * Returns 0 for success, non-zero in case of failure
2390 static int ufshcd_queuecommand(struct Scsi_Host *host, struct scsi_cmnd *cmd)
2392 struct ufshcd_lrb *lrbp;
2393 struct ufs_hba *hba;
2394 unsigned long flags;
2398 hba = shost_priv(host);
2400 tag = cmd->request->tag;
2401 if (!ufshcd_valid_tag(hba, tag)) {
2403 "%s: invalid command tag %d: cmd=0x%p, cmd->request=0x%p",
2404 __func__, tag, cmd, cmd->request);
2408 if (!down_read_trylock(&hba->clk_scaling_lock))
2409 return SCSI_MLQUEUE_HOST_BUSY;
2411 spin_lock_irqsave(hba->host->host_lock, flags);
2412 switch (hba->ufshcd_state) {
2413 case UFSHCD_STATE_OPERATIONAL:
2415 case UFSHCD_STATE_EH_SCHEDULED:
2416 case UFSHCD_STATE_RESET:
2417 err = SCSI_MLQUEUE_HOST_BUSY;
2419 case UFSHCD_STATE_ERROR:
2420 set_host_byte(cmd, DID_ERROR);
2421 cmd->scsi_done(cmd);
2424 dev_WARN_ONCE(hba->dev, 1, "%s: invalid state %d\n",
2425 __func__, hba->ufshcd_state);
2426 set_host_byte(cmd, DID_BAD_TARGET);
2427 cmd->scsi_done(cmd);
2431 /* if error handling is in progress, don't issue commands */
2432 if (ufshcd_eh_in_progress(hba)) {
2433 set_host_byte(cmd, DID_ERROR);
2434 cmd->scsi_done(cmd);
2437 spin_unlock_irqrestore(hba->host->host_lock, flags);
2439 hba->req_abort_count = 0;
2441 /* acquire the tag to make sure device cmds don't use it */
2442 if (test_and_set_bit_lock(tag, &hba->lrb_in_use)) {
2444 * Dev manage command in progress, requeue the command.
2445 * Requeuing the command helps in cases where the request *may*
2446 * find different tag instead of waiting for dev manage command
2449 err = SCSI_MLQUEUE_HOST_BUSY;
2453 err = ufshcd_hold(hba, true);
2455 err = SCSI_MLQUEUE_HOST_BUSY;
2456 clear_bit_unlock(tag, &hba->lrb_in_use);
2459 WARN_ON(hba->clk_gating.state != CLKS_ON);
2461 lrbp = &hba->lrb[tag];
2465 lrbp->sense_bufflen = UFS_SENSE_SIZE;
2466 lrbp->sense_buffer = cmd->sense_buffer;
2467 lrbp->task_tag = tag;
2468 lrbp->lun = ufshcd_scsi_to_upiu_lun(cmd->device->lun);
2469 lrbp->intr_cmd = !ufshcd_is_intr_aggr_allowed(hba) ? true : false;
2470 lrbp->req_abort_skip = false;
2472 ufshcd_comp_scsi_upiu(hba, lrbp);
2474 err = ufshcd_map_sg(hba, lrbp);
2477 clear_bit_unlock(tag, &hba->lrb_in_use);
2480 /* Make sure descriptors are ready before ringing the doorbell */
2483 /* issue command to the controller */
2484 spin_lock_irqsave(hba->host->host_lock, flags);
2485 ufshcd_vops_setup_xfer_req(hba, tag, (lrbp->cmd ? true : false));
2486 ufshcd_send_command(hba, tag);
2488 spin_unlock_irqrestore(hba->host->host_lock, flags);
2490 up_read(&hba->clk_scaling_lock);
2494 static int ufshcd_compose_dev_cmd(struct ufs_hba *hba,
2495 struct ufshcd_lrb *lrbp, enum dev_cmd_type cmd_type, int tag)
2498 lrbp->sense_bufflen = 0;
2499 lrbp->sense_buffer = NULL;
2500 lrbp->task_tag = tag;
2501 lrbp->lun = 0; /* device management cmd is not specific to any LUN */
2502 lrbp->intr_cmd = true; /* No interrupt aggregation */
2503 hba->dev_cmd.type = cmd_type;
2505 return ufshcd_comp_devman_upiu(hba, lrbp);
2509 ufshcd_clear_cmd(struct ufs_hba *hba, int tag)
2512 unsigned long flags;
2513 u32 mask = 1 << tag;
2515 /* clear outstanding transaction before retry */
2516 spin_lock_irqsave(hba->host->host_lock, flags);
2517 ufshcd_utrl_clear(hba, tag);
2518 spin_unlock_irqrestore(hba->host->host_lock, flags);
2521 * wait for for h/w to clear corresponding bit in door-bell.
2522 * max. wait is 1 sec.
2524 err = ufshcd_wait_for_register(hba,
2525 REG_UTP_TRANSFER_REQ_DOOR_BELL,
2526 mask, ~mask, 1000, 1000, true);
2532 ufshcd_check_query_response(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
2534 struct ufs_query_res *query_res = &hba->dev_cmd.query.response;
2536 /* Get the UPIU response */
2537 query_res->response = ufshcd_get_rsp_upiu_result(lrbp->ucd_rsp_ptr) >>
2538 UPIU_RSP_CODE_OFFSET;
2539 return query_res->response;
2543 * ufshcd_dev_cmd_completion() - handles device management command responses
2544 * @hba: per adapter instance
2545 * @lrbp: pointer to local reference block
2548 ufshcd_dev_cmd_completion(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
2553 hba->ufs_stats.last_hibern8_exit_tstamp = ktime_set(0, 0);
2554 resp = ufshcd_get_req_rsp(lrbp->ucd_rsp_ptr);
2557 case UPIU_TRANSACTION_NOP_IN:
2558 if (hba->dev_cmd.type != DEV_CMD_TYPE_NOP) {
2560 dev_err(hba->dev, "%s: unexpected response %x\n",
2564 case UPIU_TRANSACTION_QUERY_RSP:
2565 err = ufshcd_check_query_response(hba, lrbp);
2567 err = ufshcd_copy_query_response(hba, lrbp);
2569 case UPIU_TRANSACTION_REJECT_UPIU:
2570 /* TODO: handle Reject UPIU Response */
2572 dev_err(hba->dev, "%s: Reject UPIU not fully implemented\n",
2577 dev_err(hba->dev, "%s: Invalid device management cmd response: %x\n",
2585 static int ufshcd_wait_for_dev_cmd(struct ufs_hba *hba,
2586 struct ufshcd_lrb *lrbp, int max_timeout)
2589 unsigned long time_left;
2590 unsigned long flags;
2592 time_left = wait_for_completion_timeout(hba->dev_cmd.complete,
2593 msecs_to_jiffies(max_timeout));
2595 /* Make sure descriptors are ready before ringing the doorbell */
2597 spin_lock_irqsave(hba->host->host_lock, flags);
2598 hba->dev_cmd.complete = NULL;
2599 if (likely(time_left)) {
2600 err = ufshcd_get_tr_ocs(lrbp);
2602 err = ufshcd_dev_cmd_completion(hba, lrbp);
2604 spin_unlock_irqrestore(hba->host->host_lock, flags);
2608 dev_dbg(hba->dev, "%s: dev_cmd request timedout, tag %d\n",
2609 __func__, lrbp->task_tag);
2610 if (!ufshcd_clear_cmd(hba, lrbp->task_tag))
2611 /* successfully cleared the command, retry if needed */
2614 * in case of an error, after clearing the doorbell,
2615 * we also need to clear the outstanding_request
2618 ufshcd_outstanding_req_clear(hba, lrbp->task_tag);
2625 * ufshcd_get_dev_cmd_tag - Get device management command tag
2626 * @hba: per-adapter instance
2627 * @tag_out: pointer to variable with available slot value
2629 * Get a free slot and lock it until device management command
2632 * Returns false if free slot is unavailable for locking, else
2633 * return true with tag value in @tag.
2635 static bool ufshcd_get_dev_cmd_tag(struct ufs_hba *hba, int *tag_out)
2645 tmp = ~hba->lrb_in_use;
2646 tag = find_last_bit(&tmp, hba->nutrs);
2647 if (tag >= hba->nutrs)
2649 } while (test_and_set_bit_lock(tag, &hba->lrb_in_use));
2657 static inline void ufshcd_put_dev_cmd_tag(struct ufs_hba *hba, int tag)
2659 clear_bit_unlock(tag, &hba->lrb_in_use);
2663 * ufshcd_exec_dev_cmd - API for sending device management requests
2665 * @cmd_type: specifies the type (NOP, Query...)
2666 * @timeout: time in seconds
2668 * NOTE: Since there is only one available tag for device management commands,
2669 * it is expected you hold the hba->dev_cmd.lock mutex.
2671 static int ufshcd_exec_dev_cmd(struct ufs_hba *hba,
2672 enum dev_cmd_type cmd_type, int timeout)
2674 struct ufshcd_lrb *lrbp;
2677 struct completion wait;
2678 unsigned long flags;
2680 down_read(&hba->clk_scaling_lock);
2683 * Get free slot, sleep if slots are unavailable.
2684 * Even though we use wait_event() which sleeps indefinitely,
2685 * the maximum wait time is bounded by SCSI request timeout.
2687 wait_event(hba->dev_cmd.tag_wq, ufshcd_get_dev_cmd_tag(hba, &tag));
2689 init_completion(&wait);
2690 lrbp = &hba->lrb[tag];
2692 err = ufshcd_compose_dev_cmd(hba, lrbp, cmd_type, tag);
2696 hba->dev_cmd.complete = &wait;
2698 ufshcd_add_query_upiu_trace(hba, tag, "query_send");
2699 /* Make sure descriptors are ready before ringing the doorbell */
2701 spin_lock_irqsave(hba->host->host_lock, flags);
2702 ufshcd_vops_setup_xfer_req(hba, tag, (lrbp->cmd ? true : false));
2703 ufshcd_send_command(hba, tag);
2704 spin_unlock_irqrestore(hba->host->host_lock, flags);
2706 err = ufshcd_wait_for_dev_cmd(hba, lrbp, timeout);
2708 ufshcd_add_query_upiu_trace(hba, tag,
2709 err ? "query_complete_err" : "query_complete");
2712 ufshcd_put_dev_cmd_tag(hba, tag);
2713 wake_up(&hba->dev_cmd.tag_wq);
2714 up_read(&hba->clk_scaling_lock);
2719 * ufshcd_init_query() - init the query response and request parameters
2720 * @hba: per-adapter instance
2721 * @request: address of the request pointer to be initialized
2722 * @response: address of the response pointer to be initialized
2723 * @opcode: operation to perform
2724 * @idn: flag idn to access
2725 * @index: LU number to access
2726 * @selector: query/flag/descriptor further identification
2728 static inline void ufshcd_init_query(struct ufs_hba *hba,
2729 struct ufs_query_req **request, struct ufs_query_res **response,
2730 enum query_opcode opcode, u8 idn, u8 index, u8 selector)
2732 *request = &hba->dev_cmd.query.request;
2733 *response = &hba->dev_cmd.query.response;
2734 memset(*request, 0, sizeof(struct ufs_query_req));
2735 memset(*response, 0, sizeof(struct ufs_query_res));
2736 (*request)->upiu_req.opcode = opcode;
2737 (*request)->upiu_req.idn = idn;
2738 (*request)->upiu_req.index = index;
2739 (*request)->upiu_req.selector = selector;
2742 static int ufshcd_query_flag_retry(struct ufs_hba *hba,
2743 enum query_opcode opcode, enum flag_idn idn, bool *flag_res)
2748 for (retries = 0; retries < QUERY_REQ_RETRIES; retries++) {
2749 ret = ufshcd_query_flag(hba, opcode, idn, flag_res);
2752 "%s: failed with error %d, retries %d\n",
2753 __func__, ret, retries);
2760 "%s: query attribute, opcode %d, idn %d, failed with error %d after %d retires\n",
2761 __func__, opcode, idn, ret, retries);
2766 * ufshcd_query_flag() - API function for sending flag query requests
2767 * @hba: per-adapter instance
2768 * @opcode: flag query to perform
2769 * @idn: flag idn to access
2770 * @flag_res: the flag value after the query request completes
2772 * Returns 0 for success, non-zero in case of failure
2774 int ufshcd_query_flag(struct ufs_hba *hba, enum query_opcode opcode,
2775 enum flag_idn idn, bool *flag_res)
2777 struct ufs_query_req *request = NULL;
2778 struct ufs_query_res *response = NULL;
2779 int err, index = 0, selector = 0;
2780 int timeout = QUERY_REQ_TIMEOUT;
2784 ufshcd_hold(hba, false);
2785 mutex_lock(&hba->dev_cmd.lock);
2786 ufshcd_init_query(hba, &request, &response, opcode, idn, index,
2790 case UPIU_QUERY_OPCODE_SET_FLAG:
2791 case UPIU_QUERY_OPCODE_CLEAR_FLAG:
2792 case UPIU_QUERY_OPCODE_TOGGLE_FLAG:
2793 request->query_func = UPIU_QUERY_FUNC_STANDARD_WRITE_REQUEST;
2795 case UPIU_QUERY_OPCODE_READ_FLAG:
2796 request->query_func = UPIU_QUERY_FUNC_STANDARD_READ_REQUEST;
2798 /* No dummy reads */
2799 dev_err(hba->dev, "%s: Invalid argument for read request\n",
2807 "%s: Expected query flag opcode but got = %d\n",
2813 err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_QUERY, timeout);
2817 "%s: Sending flag query for idn %d failed, err = %d\n",
2818 __func__, idn, err);
2823 *flag_res = (be32_to_cpu(response->upiu_res.value) &
2824 MASK_QUERY_UPIU_FLAG_LOC) & 0x1;
2827 mutex_unlock(&hba->dev_cmd.lock);
2828 ufshcd_release(hba);
2833 * ufshcd_query_attr - API function for sending attribute requests
2834 * @hba: per-adapter instance
2835 * @opcode: attribute opcode
2836 * @idn: attribute idn to access
2837 * @index: index field
2838 * @selector: selector field
2839 * @attr_val: the attribute value after the query request completes
2841 * Returns 0 for success, non-zero in case of failure
2843 int ufshcd_query_attr(struct ufs_hba *hba, enum query_opcode opcode,
2844 enum attr_idn idn, u8 index, u8 selector, u32 *attr_val)
2846 struct ufs_query_req *request = NULL;
2847 struct ufs_query_res *response = NULL;
2852 ufshcd_hold(hba, false);
2854 dev_err(hba->dev, "%s: attribute value required for opcode 0x%x\n",
2860 mutex_lock(&hba->dev_cmd.lock);
2861 ufshcd_init_query(hba, &request, &response, opcode, idn, index,
2865 case UPIU_QUERY_OPCODE_WRITE_ATTR:
2866 request->query_func = UPIU_QUERY_FUNC_STANDARD_WRITE_REQUEST;
2867 request->upiu_req.value = cpu_to_be32(*attr_val);
2869 case UPIU_QUERY_OPCODE_READ_ATTR:
2870 request->query_func = UPIU_QUERY_FUNC_STANDARD_READ_REQUEST;
2873 dev_err(hba->dev, "%s: Expected query attr opcode but got = 0x%.2x\n",
2879 err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_QUERY, QUERY_REQ_TIMEOUT);
2882 dev_err(hba->dev, "%s: opcode 0x%.2x for idn %d failed, index %d, err = %d\n",
2883 __func__, opcode, idn, index, err);
2887 *attr_val = be32_to_cpu(response->upiu_res.value);
2890 mutex_unlock(&hba->dev_cmd.lock);
2892 ufshcd_release(hba);
2897 * ufshcd_query_attr_retry() - API function for sending query
2898 * attribute with retries
2899 * @hba: per-adapter instance
2900 * @opcode: attribute opcode
2901 * @idn: attribute idn to access
2902 * @index: index field
2903 * @selector: selector field
2904 * @attr_val: the attribute value after the query request
2907 * Returns 0 for success, non-zero in case of failure
2909 static int ufshcd_query_attr_retry(struct ufs_hba *hba,
2910 enum query_opcode opcode, enum attr_idn idn, u8 index, u8 selector,
2916 for (retries = QUERY_REQ_RETRIES; retries > 0; retries--) {
2917 ret = ufshcd_query_attr(hba, opcode, idn, index,
2918 selector, attr_val);
2920 dev_dbg(hba->dev, "%s: failed with error %d, retries %d\n",
2921 __func__, ret, retries);
2928 "%s: query attribute, idn %d, failed with error %d after %d retires\n",
2929 __func__, idn, ret, QUERY_REQ_RETRIES);
2933 static int __ufshcd_query_descriptor(struct ufs_hba *hba,
2934 enum query_opcode opcode, enum desc_idn idn, u8 index,
2935 u8 selector, u8 *desc_buf, int *buf_len)
2937 struct ufs_query_req *request = NULL;
2938 struct ufs_query_res *response = NULL;
2943 ufshcd_hold(hba, false);
2945 dev_err(hba->dev, "%s: descriptor buffer required for opcode 0x%x\n",
2951 if (*buf_len < QUERY_DESC_MIN_SIZE || *buf_len > QUERY_DESC_MAX_SIZE) {
2952 dev_err(hba->dev, "%s: descriptor buffer size (%d) is out of range\n",
2953 __func__, *buf_len);
2958 mutex_lock(&hba->dev_cmd.lock);
2959 ufshcd_init_query(hba, &request, &response, opcode, idn, index,
2961 hba->dev_cmd.query.descriptor = desc_buf;
2962 request->upiu_req.length = cpu_to_be16(*buf_len);
2965 case UPIU_QUERY_OPCODE_WRITE_DESC:
2966 request->query_func = UPIU_QUERY_FUNC_STANDARD_WRITE_REQUEST;
2968 case UPIU_QUERY_OPCODE_READ_DESC:
2969 request->query_func = UPIU_QUERY_FUNC_STANDARD_READ_REQUEST;
2973 "%s: Expected query descriptor opcode but got = 0x%.2x\n",
2979 err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_QUERY, QUERY_REQ_TIMEOUT);
2982 dev_err(hba->dev, "%s: opcode 0x%.2x for idn %d failed, index %d, err = %d\n",
2983 __func__, opcode, idn, index, err);
2987 hba->dev_cmd.query.descriptor = NULL;
2988 *buf_len = be16_to_cpu(response->upiu_res.length);
2991 mutex_unlock(&hba->dev_cmd.lock);
2993 ufshcd_release(hba);
2998 * ufshcd_query_descriptor_retry - API function for sending descriptor requests
2999 * @hba: per-adapter instance
3000 * @opcode: attribute opcode
3001 * @idn: attribute idn to access
3002 * @index: index field
3003 * @selector: selector field
3004 * @desc_buf: the buffer that contains the descriptor
3005 * @buf_len: length parameter passed to the device
3007 * Returns 0 for success, non-zero in case of failure.
3008 * The buf_len parameter will contain, on return, the length parameter
3009 * received on the response.
3011 int ufshcd_query_descriptor_retry(struct ufs_hba *hba,
3012 enum query_opcode opcode,
3013 enum desc_idn idn, u8 index,
3015 u8 *desc_buf, int *buf_len)
3020 for (retries = QUERY_REQ_RETRIES; retries > 0; retries--) {
3021 err = __ufshcd_query_descriptor(hba, opcode, idn, index,
3022 selector, desc_buf, buf_len);
3023 if (!err || err == -EINVAL)
3031 * ufshcd_read_desc_length - read the specified descriptor length from header
3032 * @hba: Pointer to adapter instance
3033 * @desc_id: descriptor idn value
3034 * @desc_index: descriptor index
3035 * @desc_length: pointer to variable to read the length of descriptor
3037 * Return 0 in case of success, non-zero otherwise
3039 static int ufshcd_read_desc_length(struct ufs_hba *hba,
3040 enum desc_idn desc_id,
3045 u8 header[QUERY_DESC_HDR_SIZE];
3046 int header_len = QUERY_DESC_HDR_SIZE;
3048 if (desc_id >= QUERY_DESC_IDN_MAX)
3051 ret = ufshcd_query_descriptor_retry(hba, UPIU_QUERY_OPCODE_READ_DESC,
3052 desc_id, desc_index, 0, header,
3056 dev_err(hba->dev, "%s: Failed to get descriptor header id %d",
3059 } else if (desc_id != header[QUERY_DESC_DESC_TYPE_OFFSET]) {
3060 dev_warn(hba->dev, "%s: descriptor header id %d and desc_id %d mismatch",
3061 __func__, header[QUERY_DESC_DESC_TYPE_OFFSET],
3066 *desc_length = header[QUERY_DESC_LENGTH_OFFSET];
3072 * ufshcd_map_desc_id_to_length - map descriptor IDN to its length
3073 * @hba: Pointer to adapter instance
3074 * @desc_id: descriptor idn value
3075 * @desc_len: mapped desc length (out)
3077 * Return 0 in case of success, non-zero otherwise
3079 int ufshcd_map_desc_id_to_length(struct ufs_hba *hba,
3080 enum desc_idn desc_id, int *desc_len)
3083 case QUERY_DESC_IDN_DEVICE:
3084 *desc_len = hba->desc_size.dev_desc;
3086 case QUERY_DESC_IDN_POWER:
3087 *desc_len = hba->desc_size.pwr_desc;
3089 case QUERY_DESC_IDN_GEOMETRY:
3090 *desc_len = hba->desc_size.geom_desc;
3092 case QUERY_DESC_IDN_CONFIGURATION:
3093 *desc_len = hba->desc_size.conf_desc;
3095 case QUERY_DESC_IDN_UNIT:
3096 *desc_len = hba->desc_size.unit_desc;
3098 case QUERY_DESC_IDN_INTERCONNECT:
3099 *desc_len = hba->desc_size.interc_desc;
3101 case QUERY_DESC_IDN_STRING:
3102 *desc_len = QUERY_DESC_MAX_SIZE;
3104 case QUERY_DESC_IDN_HEALTH:
3105 *desc_len = hba->desc_size.hlth_desc;
3107 case QUERY_DESC_IDN_RFU_0:
3108 case QUERY_DESC_IDN_RFU_1:
3117 EXPORT_SYMBOL(ufshcd_map_desc_id_to_length);
3120 * ufshcd_read_desc_param - read the specified descriptor parameter
3121 * @hba: Pointer to adapter instance
3122 * @desc_id: descriptor idn value
3123 * @desc_index: descriptor index
3124 * @param_offset: offset of the parameter to read
3125 * @param_read_buf: pointer to buffer where parameter would be read
3126 * @param_size: sizeof(param_read_buf)
3128 * Return 0 in case of success, non-zero otherwise
3130 int ufshcd_read_desc_param(struct ufs_hba *hba,
3131 enum desc_idn desc_id,
3140 bool is_kmalloc = true;
3143 if (desc_id >= QUERY_DESC_IDN_MAX || !param_size)
3146 /* Get the max length of descriptor from structure filled up at probe
3149 ret = ufshcd_map_desc_id_to_length(hba, desc_id, &buff_len);
3152 if (ret || !buff_len) {
3153 dev_err(hba->dev, "%s: Failed to get full descriptor length",
3158 /* Check whether we need temp memory */
3159 if (param_offset != 0 || param_size < buff_len) {
3160 desc_buf = kmalloc(buff_len, GFP_KERNEL);
3164 desc_buf = param_read_buf;
3168 /* Request for full descriptor */
3169 ret = ufshcd_query_descriptor_retry(hba, UPIU_QUERY_OPCODE_READ_DESC,
3170 desc_id, desc_index, 0,
3171 desc_buf, &buff_len);
3174 dev_err(hba->dev, "%s: Failed reading descriptor. desc_id %d, desc_index %d, param_offset %d, ret %d",
3175 __func__, desc_id, desc_index, param_offset, ret);
3180 if (desc_buf[QUERY_DESC_DESC_TYPE_OFFSET] != desc_id) {
3181 dev_err(hba->dev, "%s: invalid desc_id %d in descriptor header",
3182 __func__, desc_buf[QUERY_DESC_DESC_TYPE_OFFSET]);
3187 /* Check wherher we will not copy more data, than available */
3188 if (is_kmalloc && param_size > buff_len)
3189 param_size = buff_len;
3192 memcpy(param_read_buf, &desc_buf[param_offset], param_size);
3199 static inline int ufshcd_read_desc(struct ufs_hba *hba,
3200 enum desc_idn desc_id,
3205 return ufshcd_read_desc_param(hba, desc_id, desc_index, 0, buf, size);
3208 static inline int ufshcd_read_power_desc(struct ufs_hba *hba,
3212 return ufshcd_read_desc(hba, QUERY_DESC_IDN_POWER, 0, buf, size);
3215 static int ufshcd_read_device_desc(struct ufs_hba *hba, u8 *buf, u32 size)
3217 return ufshcd_read_desc(hba, QUERY_DESC_IDN_DEVICE, 0, buf, size);
3221 * ufshcd_read_string_desc - read string descriptor
3222 * @hba: pointer to adapter instance
3223 * @desc_index: descriptor index
3224 * @buf: pointer to buffer where descriptor would be read
3225 * @size: size of buf
3226 * @ascii: if true convert from unicode to ascii characters
3228 * Return 0 in case of success, non-zero otherwise
3230 int ufshcd_read_string_desc(struct ufs_hba *hba, int desc_index,
3231 u8 *buf, u32 size, bool ascii)
3235 err = ufshcd_read_desc(hba,
3236 QUERY_DESC_IDN_STRING, desc_index, buf, size);
3239 dev_err(hba->dev, "%s: reading String Desc failed after %d retries. err = %d\n",
3240 __func__, QUERY_REQ_RETRIES, err);
3251 /* remove header and divide by 2 to move from UTF16 to UTF8 */
3252 ascii_len = (desc_len - QUERY_DESC_HDR_SIZE) / 2 + 1;
3253 if (size < ascii_len + QUERY_DESC_HDR_SIZE) {
3254 dev_err(hba->dev, "%s: buffer allocated size is too small\n",
3260 buff_ascii = kmalloc(ascii_len, GFP_KERNEL);
3267 * the descriptor contains string in UTF16 format
3268 * we need to convert to utf-8 so it can be displayed
3270 utf16s_to_utf8s((wchar_t *)&buf[QUERY_DESC_HDR_SIZE],
3271 desc_len - QUERY_DESC_HDR_SIZE,
3272 UTF16_BIG_ENDIAN, buff_ascii, ascii_len);
3274 /* replace non-printable or non-ASCII characters with spaces */
3275 for (i = 0; i < ascii_len; i++)
3276 ufshcd_remove_non_printable(&buff_ascii[i]);
3278 memset(buf + QUERY_DESC_HDR_SIZE, 0,
3279 size - QUERY_DESC_HDR_SIZE);
3280 memcpy(buf + QUERY_DESC_HDR_SIZE, buff_ascii, ascii_len);
3281 buf[QUERY_DESC_LENGTH_OFFSET] = ascii_len + QUERY_DESC_HDR_SIZE;
3289 * ufshcd_read_unit_desc_param - read the specified unit descriptor parameter
3290 * @hba: Pointer to adapter instance
3292 * @param_offset: offset of the parameter to read
3293 * @param_read_buf: pointer to buffer where parameter would be read
3294 * @param_size: sizeof(param_read_buf)
3296 * Return 0 in case of success, non-zero otherwise
3298 static inline int ufshcd_read_unit_desc_param(struct ufs_hba *hba,
3300 enum unit_desc_param param_offset,
3305 * Unit descriptors are only available for general purpose LUs (LUN id
3306 * from 0 to 7) and RPMB Well known LU.
3308 if (!ufs_is_valid_unit_desc_lun(lun))
3311 return ufshcd_read_desc_param(hba, QUERY_DESC_IDN_UNIT, lun,
3312 param_offset, param_read_buf, param_size);
3316 * ufshcd_memory_alloc - allocate memory for host memory space data structures
3317 * @hba: per adapter instance
3319 * 1. Allocate DMA memory for Command Descriptor array
3320 * Each command descriptor consist of Command UPIU, Response UPIU and PRDT
3321 * 2. Allocate DMA memory for UTP Transfer Request Descriptor List (UTRDL).
3322 * 3. Allocate DMA memory for UTP Task Management Request Descriptor List
3324 * 4. Allocate memory for local reference block(lrb).
3326 * Returns 0 for success, non-zero in case of failure
3328 static int ufshcd_memory_alloc(struct ufs_hba *hba)
3330 size_t utmrdl_size, utrdl_size, ucdl_size;
3332 /* Allocate memory for UTP command descriptors */
3333 ucdl_size = (sizeof(struct utp_transfer_cmd_desc) * hba->nutrs);
3334 hba->ucdl_base_addr = dmam_alloc_coherent(hba->dev,
3336 &hba->ucdl_dma_addr,
3340 * UFSHCI requires UTP command descriptor to be 128 byte aligned.
3341 * make sure hba->ucdl_dma_addr is aligned to PAGE_SIZE
3342 * if hba->ucdl_dma_addr is aligned to PAGE_SIZE, then it will
3343 * be aligned to 128 bytes as well
3345 if (!hba->ucdl_base_addr ||
3346 WARN_ON(hba->ucdl_dma_addr & (PAGE_SIZE - 1))) {
3348 "Command Descriptor Memory allocation failed\n");
3353 * Allocate memory for UTP Transfer descriptors
3354 * UFSHCI requires 1024 byte alignment of UTRD
3356 utrdl_size = (sizeof(struct utp_transfer_req_desc) * hba->nutrs);
3357 hba->utrdl_base_addr = dmam_alloc_coherent(hba->dev,
3359 &hba->utrdl_dma_addr,
3361 if (!hba->utrdl_base_addr ||
3362 WARN_ON(hba->utrdl_dma_addr & (PAGE_SIZE - 1))) {
3364 "Transfer Descriptor Memory allocation failed\n");
3369 * Allocate memory for UTP Task Management descriptors
3370 * UFSHCI requires 1024 byte alignment of UTMRD
3372 utmrdl_size = sizeof(struct utp_task_req_desc) * hba->nutmrs;
3373 hba->utmrdl_base_addr = dmam_alloc_coherent(hba->dev,
3375 &hba->utmrdl_dma_addr,
3377 if (!hba->utmrdl_base_addr ||
3378 WARN_ON(hba->utmrdl_dma_addr & (PAGE_SIZE - 1))) {
3380 "Task Management Descriptor Memory allocation failed\n");
3384 /* Allocate memory for local reference block */
3385 hba->lrb = devm_kcalloc(hba->dev,
3386 hba->nutrs, sizeof(struct ufshcd_lrb),
3389 dev_err(hba->dev, "LRB Memory allocation failed\n");
3398 * ufshcd_host_memory_configure - configure local reference block with
3400 * @hba: per adapter instance
3402 * Configure Host memory space
3403 * 1. Update Corresponding UTRD.UCDBA and UTRD.UCDBAU with UCD DMA
3405 * 2. Update each UTRD with Response UPIU offset, Response UPIU length
3407 * 3. Save the corresponding addresses of UTRD, UCD.CMD, UCD.RSP and UCD.PRDT
3408 * into local reference block.
3410 static void ufshcd_host_memory_configure(struct ufs_hba *hba)
3412 struct utp_transfer_cmd_desc *cmd_descp;
3413 struct utp_transfer_req_desc *utrdlp;
3414 dma_addr_t cmd_desc_dma_addr;
3415 dma_addr_t cmd_desc_element_addr;
3416 u16 response_offset;
3421 utrdlp = hba->utrdl_base_addr;
3422 cmd_descp = hba->ucdl_base_addr;
3425 offsetof(struct utp_transfer_cmd_desc, response_upiu);
3427 offsetof(struct utp_transfer_cmd_desc, prd_table);
3429 cmd_desc_size = sizeof(struct utp_transfer_cmd_desc);
3430 cmd_desc_dma_addr = hba->ucdl_dma_addr;
3432 for (i = 0; i < hba->nutrs; i++) {
3433 /* Configure UTRD with command descriptor base address */
3434 cmd_desc_element_addr =
3435 (cmd_desc_dma_addr + (cmd_desc_size * i));
3436 utrdlp[i].command_desc_base_addr_lo =
3437 cpu_to_le32(lower_32_bits(cmd_desc_element_addr));
3438 utrdlp[i].command_desc_base_addr_hi =
3439 cpu_to_le32(upper_32_bits(cmd_desc_element_addr));
3441 /* Response upiu and prdt offset should be in double words */
3442 if (hba->quirks & UFSHCD_QUIRK_PRDT_BYTE_GRAN) {
3443 utrdlp[i].response_upiu_offset =
3444 cpu_to_le16(response_offset);
3445 utrdlp[i].prd_table_offset =
3446 cpu_to_le16(prdt_offset);
3447 utrdlp[i].response_upiu_length =
3448 cpu_to_le16(ALIGNED_UPIU_SIZE);
3450 utrdlp[i].response_upiu_offset =
3451 cpu_to_le16((response_offset >> 2));
3452 utrdlp[i].prd_table_offset =
3453 cpu_to_le16((prdt_offset >> 2));
3454 utrdlp[i].response_upiu_length =
3455 cpu_to_le16(ALIGNED_UPIU_SIZE >> 2);
3458 hba->lrb[i].utr_descriptor_ptr = (utrdlp + i);
3459 hba->lrb[i].utrd_dma_addr = hba->utrdl_dma_addr +
3460 (i * sizeof(struct utp_transfer_req_desc));
3461 hba->lrb[i].ucd_req_ptr =
3462 (struct utp_upiu_req *)(cmd_descp + i);
3463 hba->lrb[i].ucd_req_dma_addr = cmd_desc_element_addr;
3464 hba->lrb[i].ucd_rsp_ptr =
3465 (struct utp_upiu_rsp *)cmd_descp[i].response_upiu;
3466 hba->lrb[i].ucd_rsp_dma_addr = cmd_desc_element_addr +
3468 hba->lrb[i].ucd_prdt_ptr =
3469 (struct ufshcd_sg_entry *)cmd_descp[i].prd_table;
3470 hba->lrb[i].ucd_prdt_dma_addr = cmd_desc_element_addr +
3476 * ufshcd_dme_link_startup - Notify Unipro to perform link startup
3477 * @hba: per adapter instance
3479 * UIC_CMD_DME_LINK_STARTUP command must be issued to Unipro layer,
3480 * in order to initialize the Unipro link startup procedure.
3481 * Once the Unipro links are up, the device connected to the controller
3484 * Returns 0 on success, non-zero value on failure
3486 static int ufshcd_dme_link_startup(struct ufs_hba *hba)
3488 struct uic_command uic_cmd = {0};
3491 uic_cmd.command = UIC_CMD_DME_LINK_STARTUP;
3493 ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
3496 "dme-link-startup: error code %d\n", ret);
3500 * ufshcd_dme_reset - UIC command for DME_RESET
3501 * @hba: per adapter instance
3503 * DME_RESET command is issued in order to reset UniPro stack.
3504 * This function now deal with cold reset.
3506 * Returns 0 on success, non-zero value on failure
3508 static int ufshcd_dme_reset(struct ufs_hba *hba)
3510 struct uic_command uic_cmd = {0};
3513 uic_cmd.command = UIC_CMD_DME_RESET;
3515 ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
3518 "dme-reset: error code %d\n", ret);
3524 * ufshcd_dme_enable - UIC command for DME_ENABLE
3525 * @hba: per adapter instance
3527 * DME_ENABLE command is issued in order to enable UniPro stack.
3529 * Returns 0 on success, non-zero value on failure
3531 static int ufshcd_dme_enable(struct ufs_hba *hba)
3533 struct uic_command uic_cmd = {0};
3536 uic_cmd.command = UIC_CMD_DME_ENABLE;
3538 ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
3541 "dme-reset: error code %d\n", ret);
3546 static inline void ufshcd_add_delay_before_dme_cmd(struct ufs_hba *hba)
3548 #define MIN_DELAY_BEFORE_DME_CMDS_US 1000
3549 unsigned long min_sleep_time_us;
3551 if (!(hba->quirks & UFSHCD_QUIRK_DELAY_BEFORE_DME_CMDS))
3555 * last_dme_cmd_tstamp will be 0 only for 1st call to
3558 if (unlikely(!ktime_to_us(hba->last_dme_cmd_tstamp))) {
3559 min_sleep_time_us = MIN_DELAY_BEFORE_DME_CMDS_US;
3561 unsigned long delta =
3562 (unsigned long) ktime_to_us(
3563 ktime_sub(ktime_get(),
3564 hba->last_dme_cmd_tstamp));
3566 if (delta < MIN_DELAY_BEFORE_DME_CMDS_US)
3568 MIN_DELAY_BEFORE_DME_CMDS_US - delta;
3570 return; /* no more delay required */
3573 /* allow sleep for extra 50us if needed */
3574 usleep_range(min_sleep_time_us, min_sleep_time_us + 50);
3578 * ufshcd_dme_set_attr - UIC command for DME_SET, DME_PEER_SET
3579 * @hba: per adapter instance
3580 * @attr_sel: uic command argument1
3581 * @attr_set: attribute set type as uic command argument2
3582 * @mib_val: setting value as uic command argument3
3583 * @peer: indicate whether peer or local
3585 * Returns 0 on success, non-zero value on failure
3587 int ufshcd_dme_set_attr(struct ufs_hba *hba, u32 attr_sel,
3588 u8 attr_set, u32 mib_val, u8 peer)
3590 struct uic_command uic_cmd = {0};
3591 static const char *const action[] = {
3595 const char *set = action[!!peer];
3597 int retries = UFS_UIC_COMMAND_RETRIES;
3599 uic_cmd.command = peer ?
3600 UIC_CMD_DME_PEER_SET : UIC_CMD_DME_SET;
3601 uic_cmd.argument1 = attr_sel;
3602 uic_cmd.argument2 = UIC_ARG_ATTR_TYPE(attr_set);
3603 uic_cmd.argument3 = mib_val;
3606 /* for peer attributes we retry upon failure */
3607 ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
3609 dev_dbg(hba->dev, "%s: attr-id 0x%x val 0x%x error code %d\n",
3610 set, UIC_GET_ATTR_ID(attr_sel), mib_val, ret);
3611 } while (ret && peer && --retries);
3614 dev_err(hba->dev, "%s: attr-id 0x%x val 0x%x failed %d retries\n",
3615 set, UIC_GET_ATTR_ID(attr_sel), mib_val,
3616 UFS_UIC_COMMAND_RETRIES - retries);
3620 EXPORT_SYMBOL_GPL(ufshcd_dme_set_attr);
3623 * ufshcd_dme_get_attr - UIC command for DME_GET, DME_PEER_GET
3624 * @hba: per adapter instance
3625 * @attr_sel: uic command argument1
3626 * @mib_val: the value of the attribute as returned by the UIC command
3627 * @peer: indicate whether peer or local
3629 * Returns 0 on success, non-zero value on failure
3631 int ufshcd_dme_get_attr(struct ufs_hba *hba, u32 attr_sel,
3632 u32 *mib_val, u8 peer)
3634 struct uic_command uic_cmd = {0};
3635 static const char *const action[] = {
3639 const char *get = action[!!peer];
3641 int retries = UFS_UIC_COMMAND_RETRIES;
3642 struct ufs_pa_layer_attr orig_pwr_info;
3643 struct ufs_pa_layer_attr temp_pwr_info;
3644 bool pwr_mode_change = false;
3646 if (peer && (hba->quirks & UFSHCD_QUIRK_DME_PEER_ACCESS_AUTO_MODE)) {
3647 orig_pwr_info = hba->pwr_info;
3648 temp_pwr_info = orig_pwr_info;
3650 if (orig_pwr_info.pwr_tx == FAST_MODE ||
3651 orig_pwr_info.pwr_rx == FAST_MODE) {
3652 temp_pwr_info.pwr_tx = FASTAUTO_MODE;
3653 temp_pwr_info.pwr_rx = FASTAUTO_MODE;
3654 pwr_mode_change = true;
3655 } else if (orig_pwr_info.pwr_tx == SLOW_MODE ||
3656 orig_pwr_info.pwr_rx == SLOW_MODE) {
3657 temp_pwr_info.pwr_tx = SLOWAUTO_MODE;
3658 temp_pwr_info.pwr_rx = SLOWAUTO_MODE;
3659 pwr_mode_change = true;
3661 if (pwr_mode_change) {
3662 ret = ufshcd_change_power_mode(hba, &temp_pwr_info);
3668 uic_cmd.command = peer ?
3669 UIC_CMD_DME_PEER_GET : UIC_CMD_DME_GET;
3670 uic_cmd.argument1 = attr_sel;
3673 /* for peer attributes we retry upon failure */
3674 ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
3676 dev_dbg(hba->dev, "%s: attr-id 0x%x error code %d\n",
3677 get, UIC_GET_ATTR_ID(attr_sel), ret);
3678 } while (ret && peer && --retries);
3681 dev_err(hba->dev, "%s: attr-id 0x%x failed %d retries\n",
3682 get, UIC_GET_ATTR_ID(attr_sel),
3683 UFS_UIC_COMMAND_RETRIES - retries);
3685 if (mib_val && !ret)
3686 *mib_val = uic_cmd.argument3;
3688 if (peer && (hba->quirks & UFSHCD_QUIRK_DME_PEER_ACCESS_AUTO_MODE)
3690 ufshcd_change_power_mode(hba, &orig_pwr_info);
3694 EXPORT_SYMBOL_GPL(ufshcd_dme_get_attr);
3697 * ufshcd_uic_pwr_ctrl - executes UIC commands (which affects the link power
3698 * state) and waits for it to take effect.
3700 * @hba: per adapter instance
3701 * @cmd: UIC command to execute
3703 * DME operations like DME_SET(PA_PWRMODE), DME_HIBERNATE_ENTER &
3704 * DME_HIBERNATE_EXIT commands take some time to take its effect on both host
3705 * and device UniPro link and hence it's final completion would be indicated by
3706 * dedicated status bits in Interrupt Status register (UPMS, UHES, UHXS) in
3707 * addition to normal UIC command completion Status (UCCS). This function only
3708 * returns after the relevant status bits indicate the completion.
3710 * Returns 0 on success, non-zero value on failure
3712 static int ufshcd_uic_pwr_ctrl(struct ufs_hba *hba, struct uic_command *cmd)
3714 struct completion uic_async_done;
3715 unsigned long flags;
3718 bool reenable_intr = false;
3720 mutex_lock(&hba->uic_cmd_mutex);
3721 init_completion(&uic_async_done);
3722 ufshcd_add_delay_before_dme_cmd(hba);
3724 spin_lock_irqsave(hba->host->host_lock, flags);
3725 hba->uic_async_done = &uic_async_done;
3726 if (ufshcd_readl(hba, REG_INTERRUPT_ENABLE) & UIC_COMMAND_COMPL) {
3727 ufshcd_disable_intr(hba, UIC_COMMAND_COMPL);
3729 * Make sure UIC command completion interrupt is disabled before
3730 * issuing UIC command.
3733 reenable_intr = true;
3735 ret = __ufshcd_send_uic_cmd(hba, cmd, false);
3736 spin_unlock_irqrestore(hba->host->host_lock, flags);
3739 "pwr ctrl cmd 0x%x with mode 0x%x uic error %d\n",
3740 cmd->command, cmd->argument3, ret);
3744 if (!wait_for_completion_timeout(hba->uic_async_done,
3745 msecs_to_jiffies(UIC_CMD_TIMEOUT))) {
3747 "pwr ctrl cmd 0x%x with mode 0x%x completion timeout\n",
3748 cmd->command, cmd->argument3);
3753 status = ufshcd_get_upmcrs(hba);
3754 if (status != PWR_LOCAL) {
3756 "pwr ctrl cmd 0x%x failed, host upmcrs:0x%x\n",
3757 cmd->command, status);
3758 ret = (status != PWR_OK) ? status : -1;
3762 ufshcd_print_host_state(hba);
3763 ufshcd_print_pwr_info(hba);
3764 ufshcd_print_host_regs(hba);
3767 spin_lock_irqsave(hba->host->host_lock, flags);
3768 hba->active_uic_cmd = NULL;
3769 hba->uic_async_done = NULL;
3771 ufshcd_enable_intr(hba, UIC_COMMAND_COMPL);
3772 spin_unlock_irqrestore(hba->host->host_lock, flags);
3773 mutex_unlock(&hba->uic_cmd_mutex);
3779 * ufshcd_uic_change_pwr_mode - Perform the UIC power mode chage
3780 * using DME_SET primitives.
3781 * @hba: per adapter instance
3782 * @mode: powr mode value
3784 * Returns 0 on success, non-zero value on failure
3786 static int ufshcd_uic_change_pwr_mode(struct ufs_hba *hba, u8 mode)
3788 struct uic_command uic_cmd = {0};
3791 if (hba->quirks & UFSHCD_QUIRK_BROKEN_PA_RXHSUNTERMCAP) {
3792 ret = ufshcd_dme_set(hba,
3793 UIC_ARG_MIB_SEL(PA_RXHSUNTERMCAP, 0), 1);
3795 dev_err(hba->dev, "%s: failed to enable PA_RXHSUNTERMCAP ret %d\n",
3801 uic_cmd.command = UIC_CMD_DME_SET;
3802 uic_cmd.argument1 = UIC_ARG_MIB(PA_PWRMODE);
3803 uic_cmd.argument3 = mode;
3804 ufshcd_hold(hba, false);
3805 ret = ufshcd_uic_pwr_ctrl(hba, &uic_cmd);
3806 ufshcd_release(hba);
3812 static int ufshcd_link_recovery(struct ufs_hba *hba)
3815 unsigned long flags;
3817 spin_lock_irqsave(hba->host->host_lock, flags);
3818 hba->ufshcd_state = UFSHCD_STATE_RESET;
3819 ufshcd_set_eh_in_progress(hba);
3820 spin_unlock_irqrestore(hba->host->host_lock, flags);
3822 ret = ufshcd_host_reset_and_restore(hba);
3824 spin_lock_irqsave(hba->host->host_lock, flags);
3826 hba->ufshcd_state = UFSHCD_STATE_ERROR;
3827 ufshcd_clear_eh_in_progress(hba);
3828 spin_unlock_irqrestore(hba->host->host_lock, flags);
3831 dev_err(hba->dev, "%s: link recovery failed, err %d",
3837 static int __ufshcd_uic_hibern8_enter(struct ufs_hba *hba)
3840 struct uic_command uic_cmd = {0};
3841 ktime_t start = ktime_get();
3843 ufshcd_vops_hibern8_notify(hba, UIC_CMD_DME_HIBER_ENTER, PRE_CHANGE);
3845 uic_cmd.command = UIC_CMD_DME_HIBER_ENTER;
3846 ret = ufshcd_uic_pwr_ctrl(hba, &uic_cmd);
3847 trace_ufshcd_profile_hibern8(dev_name(hba->dev), "enter",
3848 ktime_to_us(ktime_sub(ktime_get(), start)), ret);
3851 dev_err(hba->dev, "%s: hibern8 enter failed. ret = %d\n",
3855 * If link recovery fails then return error so that caller
3856 * don't retry the hibern8 enter again.
3858 if (ufshcd_link_recovery(hba))
3861 ufshcd_vops_hibern8_notify(hba, UIC_CMD_DME_HIBER_ENTER,
3867 static int ufshcd_uic_hibern8_enter(struct ufs_hba *hba)
3869 int ret = 0, retries;
3871 for (retries = UIC_HIBERN8_ENTER_RETRIES; retries > 0; retries--) {
3872 ret = __ufshcd_uic_hibern8_enter(hba);
3873 if (!ret || ret == -ENOLINK)
3880 static int ufshcd_uic_hibern8_exit(struct ufs_hba *hba)
3882 struct uic_command uic_cmd = {0};
3884 ktime_t start = ktime_get();
3886 ufshcd_vops_hibern8_notify(hba, UIC_CMD_DME_HIBER_EXIT, PRE_CHANGE);
3888 uic_cmd.command = UIC_CMD_DME_HIBER_EXIT;
3889 ret = ufshcd_uic_pwr_ctrl(hba, &uic_cmd);
3890 trace_ufshcd_profile_hibern8(dev_name(hba->dev), "exit",
3891 ktime_to_us(ktime_sub(ktime_get(), start)), ret);
3894 dev_err(hba->dev, "%s: hibern8 exit failed. ret = %d\n",
3896 ret = ufshcd_link_recovery(hba);
3898 ufshcd_vops_hibern8_notify(hba, UIC_CMD_DME_HIBER_EXIT,
3900 hba->ufs_stats.last_hibern8_exit_tstamp = ktime_get();
3901 hba->ufs_stats.hibern8_exit_cnt++;
3907 static void ufshcd_auto_hibern8_enable(struct ufs_hba *hba)
3909 unsigned long flags;
3911 if (!ufshcd_is_auto_hibern8_supported(hba) || !hba->ahit)
3914 spin_lock_irqsave(hba->host->host_lock, flags);
3915 ufshcd_writel(hba, hba->ahit, REG_AUTO_HIBERNATE_IDLE_TIMER);
3916 spin_unlock_irqrestore(hba->host->host_lock, flags);
3920 * ufshcd_init_pwr_info - setting the POR (power on reset)
3921 * values in hba power info
3922 * @hba: per-adapter instance
3924 static void ufshcd_init_pwr_info(struct ufs_hba *hba)
3926 hba->pwr_info.gear_rx = UFS_PWM_G1;
3927 hba->pwr_info.gear_tx = UFS_PWM_G1;
3928 hba->pwr_info.lane_rx = 1;
3929 hba->pwr_info.lane_tx = 1;
3930 hba->pwr_info.pwr_rx = SLOWAUTO_MODE;
3931 hba->pwr_info.pwr_tx = SLOWAUTO_MODE;
3932 hba->pwr_info.hs_rate = 0;
3936 * ufshcd_get_max_pwr_mode - reads the max power mode negotiated with device
3937 * @hba: per-adapter instance
3939 static int ufshcd_get_max_pwr_mode(struct ufs_hba *hba)
3941 struct ufs_pa_layer_attr *pwr_info = &hba->max_pwr_info.info;
3943 if (hba->max_pwr_info.is_valid)
3946 pwr_info->pwr_tx = FAST_MODE;
3947 pwr_info->pwr_rx = FAST_MODE;
3948 pwr_info->hs_rate = PA_HS_MODE_B;
3950 /* Get the connected lane count */
3951 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_CONNECTEDRXDATALANES),
3952 &pwr_info->lane_rx);
3953 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_CONNECTEDTXDATALANES),
3954 &pwr_info->lane_tx);
3956 if (!pwr_info->lane_rx || !pwr_info->lane_tx) {
3957 dev_err(hba->dev, "%s: invalid connected lanes value. rx=%d, tx=%d\n",
3965 * First, get the maximum gears of HS speed.
3966 * If a zero value, it means there is no HSGEAR capability.
3967 * Then, get the maximum gears of PWM speed.
3969 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_MAXRXHSGEAR), &pwr_info->gear_rx);
3970 if (!pwr_info->gear_rx) {
3971 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_MAXRXPWMGEAR),
3972 &pwr_info->gear_rx);
3973 if (!pwr_info->gear_rx) {
3974 dev_err(hba->dev, "%s: invalid max pwm rx gear read = %d\n",
3975 __func__, pwr_info->gear_rx);
3978 pwr_info->pwr_rx = SLOW_MODE;
3981 ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_MAXRXHSGEAR),
3982 &pwr_info->gear_tx);
3983 if (!pwr_info->gear_tx) {
3984 ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_MAXRXPWMGEAR),
3985 &pwr_info->gear_tx);
3986 if (!pwr_info->gear_tx) {
3987 dev_err(hba->dev, "%s: invalid max pwm tx gear read = %d\n",
3988 __func__, pwr_info->gear_tx);
3991 pwr_info->pwr_tx = SLOW_MODE;
3994 hba->max_pwr_info.is_valid = true;
3998 static int ufshcd_change_power_mode(struct ufs_hba *hba,
3999 struct ufs_pa_layer_attr *pwr_mode)
4003 /* if already configured to the requested pwr_mode */
4004 if (pwr_mode->gear_rx == hba->pwr_info.gear_rx &&
4005 pwr_mode->gear_tx == hba->pwr_info.gear_tx &&
4006 pwr_mode->lane_rx == hba->pwr_info.lane_rx &&
4007 pwr_mode->lane_tx == hba->pwr_info.lane_tx &&
4008 pwr_mode->pwr_rx == hba->pwr_info.pwr_rx &&
4009 pwr_mode->pwr_tx == hba->pwr_info.pwr_tx &&
4010 pwr_mode->hs_rate == hba->pwr_info.hs_rate) {
4011 dev_dbg(hba->dev, "%s: power already configured\n", __func__);
4016 * Configure attributes for power mode change with below.
4017 * - PA_RXGEAR, PA_ACTIVERXDATALANES, PA_RXTERMINATION,
4018 * - PA_TXGEAR, PA_ACTIVETXDATALANES, PA_TXTERMINATION,
4021 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_RXGEAR), pwr_mode->gear_rx);
4022 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_ACTIVERXDATALANES),
4024 if (pwr_mode->pwr_rx == FASTAUTO_MODE ||
4025 pwr_mode->pwr_rx == FAST_MODE)
4026 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_RXTERMINATION), TRUE);
4028 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_RXTERMINATION), FALSE);
4030 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TXGEAR), pwr_mode->gear_tx);
4031 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_ACTIVETXDATALANES),
4033 if (pwr_mode->pwr_tx == FASTAUTO_MODE ||
4034 pwr_mode->pwr_tx == FAST_MODE)
4035 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TXTERMINATION), TRUE);
4037 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TXTERMINATION), FALSE);
4039 if (pwr_mode->pwr_rx == FASTAUTO_MODE ||
4040 pwr_mode->pwr_tx == FASTAUTO_MODE ||
4041 pwr_mode->pwr_rx == FAST_MODE ||
4042 pwr_mode->pwr_tx == FAST_MODE)
4043 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_HSSERIES),
4046 ret = ufshcd_uic_change_pwr_mode(hba, pwr_mode->pwr_rx << 4
4047 | pwr_mode->pwr_tx);
4051 "%s: power mode change failed %d\n", __func__, ret);
4053 ufshcd_vops_pwr_change_notify(hba, POST_CHANGE, NULL,
4056 memcpy(&hba->pwr_info, pwr_mode,
4057 sizeof(struct ufs_pa_layer_attr));
4064 * ufshcd_config_pwr_mode - configure a new power mode
4065 * @hba: per-adapter instance
4066 * @desired_pwr_mode: desired power configuration
4068 int ufshcd_config_pwr_mode(struct ufs_hba *hba,
4069 struct ufs_pa_layer_attr *desired_pwr_mode)
4071 struct ufs_pa_layer_attr final_params = { 0 };
4074 ret = ufshcd_vops_pwr_change_notify(hba, PRE_CHANGE,
4075 desired_pwr_mode, &final_params);
4078 memcpy(&final_params, desired_pwr_mode, sizeof(final_params));
4080 ret = ufshcd_change_power_mode(hba, &final_params);
4082 ufshcd_print_pwr_info(hba);
4086 EXPORT_SYMBOL_GPL(ufshcd_config_pwr_mode);
4089 * ufshcd_complete_dev_init() - checks device readiness
4090 * @hba: per-adapter instance
4092 * Set fDeviceInit flag and poll until device toggles it.
4094 static int ufshcd_complete_dev_init(struct ufs_hba *hba)
4100 err = ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_SET_FLAG,
4101 QUERY_FLAG_IDN_FDEVICEINIT, NULL);
4104 "%s setting fDeviceInit flag failed with error %d\n",
4109 /* poll for max. 1000 iterations for fDeviceInit flag to clear */
4110 for (i = 0; i < 1000 && !err && flag_res; i++)
4111 err = ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_READ_FLAG,
4112 QUERY_FLAG_IDN_FDEVICEINIT, &flag_res);
4116 "%s reading fDeviceInit flag failed with error %d\n",
4120 "%s fDeviceInit was not cleared by the device\n",
4128 * ufshcd_make_hba_operational - Make UFS controller operational
4129 * @hba: per adapter instance
4131 * To bring UFS host controller to operational state,
4132 * 1. Enable required interrupts
4133 * 2. Configure interrupt aggregation
4134 * 3. Program UTRL and UTMRL base address
4135 * 4. Configure run-stop-registers
4137 * Returns 0 on success, non-zero value on failure
4139 static int ufshcd_make_hba_operational(struct ufs_hba *hba)
4144 /* Enable required interrupts */
4145 ufshcd_enable_intr(hba, UFSHCD_ENABLE_INTRS);
4147 /* Configure interrupt aggregation */
4148 if (ufshcd_is_intr_aggr_allowed(hba))
4149 ufshcd_config_intr_aggr(hba, hba->nutrs - 1, INT_AGGR_DEF_TO);
4151 ufshcd_disable_intr_aggr(hba);
4153 /* Configure UTRL and UTMRL base address registers */
4154 ufshcd_writel(hba, lower_32_bits(hba->utrdl_dma_addr),
4155 REG_UTP_TRANSFER_REQ_LIST_BASE_L);
4156 ufshcd_writel(hba, upper_32_bits(hba->utrdl_dma_addr),
4157 REG_UTP_TRANSFER_REQ_LIST_BASE_H);
4158 ufshcd_writel(hba, lower_32_bits(hba->utmrdl_dma_addr),
4159 REG_UTP_TASK_REQ_LIST_BASE_L);
4160 ufshcd_writel(hba, upper_32_bits(hba->utmrdl_dma_addr),
4161 REG_UTP_TASK_REQ_LIST_BASE_H);
4164 * Make sure base address and interrupt setup are updated before
4165 * enabling the run/stop registers below.
4170 * UCRDY, UTMRLDY and UTRLRDY bits must be 1
4172 reg = ufshcd_readl(hba, REG_CONTROLLER_STATUS);
4173 if (!(ufshcd_get_lists_status(reg))) {
4174 ufshcd_enable_run_stop_reg(hba);
4177 "Host controller not ready to process requests");
4187 * ufshcd_hba_stop - Send controller to reset state
4188 * @hba: per adapter instance
4189 * @can_sleep: perform sleep or just spin
4191 static inline void ufshcd_hba_stop(struct ufs_hba *hba, bool can_sleep)
4195 ufshcd_writel(hba, CONTROLLER_DISABLE, REG_CONTROLLER_ENABLE);
4196 err = ufshcd_wait_for_register(hba, REG_CONTROLLER_ENABLE,
4197 CONTROLLER_ENABLE, CONTROLLER_DISABLE,
4200 dev_err(hba->dev, "%s: Controller disable failed\n", __func__);
4204 * ufshcd_hba_execute_hce - initialize the controller
4205 * @hba: per adapter instance
4207 * The controller resets itself and controller firmware initialization
4208 * sequence kicks off. When controller is ready it will set
4209 * the Host Controller Enable bit to 1.
4211 * Returns 0 on success, non-zero value on failure
4213 static int ufshcd_hba_execute_hce(struct ufs_hba *hba)
4218 * msleep of 1 and 5 used in this function might result in msleep(20),
4219 * but it was necessary to send the UFS FPGA to reset mode during
4220 * development and testing of this driver. msleep can be changed to
4221 * mdelay and retry count can be reduced based on the controller.
4223 if (!ufshcd_is_hba_active(hba))
4224 /* change controller state to "reset state" */
4225 ufshcd_hba_stop(hba, true);
4227 /* UniPro link is disabled at this point */
4228 ufshcd_set_link_off(hba);
4230 ufshcd_vops_hce_enable_notify(hba, PRE_CHANGE);
4232 /* start controller initialization sequence */
4233 ufshcd_hba_start(hba);
4236 * To initialize a UFS host controller HCE bit must be set to 1.
4237 * During initialization the HCE bit value changes from 1->0->1.
4238 * When the host controller completes initialization sequence
4239 * it sets the value of HCE bit to 1. The same HCE bit is read back
4240 * to check if the controller has completed initialization sequence.
4241 * So without this delay the value HCE = 1, set in the previous
4242 * instruction might be read back.
4243 * This delay can be changed based on the controller.
4247 /* wait for the host controller to complete initialization */
4249 while (ufshcd_is_hba_active(hba)) {
4254 "Controller enable failed\n");
4260 /* enable UIC related interrupts */
4261 ufshcd_enable_intr(hba, UFSHCD_UIC_MASK);
4263 ufshcd_vops_hce_enable_notify(hba, POST_CHANGE);
4268 static int ufshcd_hba_enable(struct ufs_hba *hba)
4272 if (hba->quirks & UFSHCI_QUIRK_BROKEN_HCE) {
4273 ufshcd_set_link_off(hba);
4274 ufshcd_vops_hce_enable_notify(hba, PRE_CHANGE);
4276 /* enable UIC related interrupts */
4277 ufshcd_enable_intr(hba, UFSHCD_UIC_MASK);
4278 ret = ufshcd_dme_reset(hba);
4280 ret = ufshcd_dme_enable(hba);
4282 ufshcd_vops_hce_enable_notify(hba, POST_CHANGE);
4285 "Host controller enable failed with non-hce\n");
4288 ret = ufshcd_hba_execute_hce(hba);
4293 static int ufshcd_disable_tx_lcc(struct ufs_hba *hba, bool peer)
4295 int tx_lanes, i, err = 0;
4298 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_CONNECTEDTXDATALANES),
4301 ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_CONNECTEDTXDATALANES),
4303 for (i = 0; i < tx_lanes; i++) {
4305 err = ufshcd_dme_set(hba,
4306 UIC_ARG_MIB_SEL(TX_LCC_ENABLE,
4307 UIC_ARG_MPHY_TX_GEN_SEL_INDEX(i)),
4310 err = ufshcd_dme_peer_set(hba,
4311 UIC_ARG_MIB_SEL(TX_LCC_ENABLE,
4312 UIC_ARG_MPHY_TX_GEN_SEL_INDEX(i)),
4315 dev_err(hba->dev, "%s: TX LCC Disable failed, peer = %d, lane = %d, err = %d",
4316 __func__, peer, i, err);
4324 static inline int ufshcd_disable_device_tx_lcc(struct ufs_hba *hba)
4326 return ufshcd_disable_tx_lcc(hba, true);
4330 * ufshcd_link_startup - Initialize unipro link startup
4331 * @hba: per adapter instance
4333 * Returns 0 for success, non-zero in case of failure
4335 static int ufshcd_link_startup(struct ufs_hba *hba)
4338 int retries = DME_LINKSTARTUP_RETRIES;
4339 bool link_startup_again = false;
4342 * If UFS device isn't active then we will have to issue link startup
4343 * 2 times to make sure the device state move to active.
4345 if (!ufshcd_is_ufs_dev_active(hba))
4346 link_startup_again = true;
4350 ufshcd_vops_link_startup_notify(hba, PRE_CHANGE);
4352 ret = ufshcd_dme_link_startup(hba);
4354 /* check if device is detected by inter-connect layer */
4355 if (!ret && !ufshcd_is_device_present(hba)) {
4356 dev_err(hba->dev, "%s: Device not present\n", __func__);
4362 * DME link lost indication is only received when link is up,
4363 * but we can't be sure if the link is up until link startup
4364 * succeeds. So reset the local Uni-Pro and try again.
4366 if (ret && ufshcd_hba_enable(hba))
4368 } while (ret && retries--);
4371 /* failed to get the link up... retire */
4374 if (link_startup_again) {
4375 link_startup_again = false;
4376 retries = DME_LINKSTARTUP_RETRIES;
4380 /* Mark that link is up in PWM-G1, 1-lane, SLOW-AUTO mode */
4381 ufshcd_init_pwr_info(hba);
4382 ufshcd_print_pwr_info(hba);
4384 if (hba->quirks & UFSHCD_QUIRK_BROKEN_LCC) {
4385 ret = ufshcd_disable_device_tx_lcc(hba);
4390 /* Include any host controller configuration via UIC commands */
4391 ret = ufshcd_vops_link_startup_notify(hba, POST_CHANGE);
4395 ret = ufshcd_make_hba_operational(hba);
4398 dev_err(hba->dev, "link startup failed %d\n", ret);
4399 ufshcd_print_host_state(hba);
4400 ufshcd_print_pwr_info(hba);
4401 ufshcd_print_host_regs(hba);
4407 * ufshcd_verify_dev_init() - Verify device initialization
4408 * @hba: per-adapter instance
4410 * Send NOP OUT UPIU and wait for NOP IN response to check whether the
4411 * device Transport Protocol (UTP) layer is ready after a reset.
4412 * If the UTP layer at the device side is not initialized, it may
4413 * not respond with NOP IN UPIU within timeout of %NOP_OUT_TIMEOUT
4414 * and we retry sending NOP OUT for %NOP_OUT_RETRIES iterations.
4416 static int ufshcd_verify_dev_init(struct ufs_hba *hba)
4421 ufshcd_hold(hba, false);
4422 mutex_lock(&hba->dev_cmd.lock);
4423 for (retries = NOP_OUT_RETRIES; retries > 0; retries--) {
4424 err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_NOP,
4427 if (!err || err == -ETIMEDOUT)
4430 dev_dbg(hba->dev, "%s: error %d retrying\n", __func__, err);
4432 mutex_unlock(&hba->dev_cmd.lock);
4433 ufshcd_release(hba);
4436 dev_err(hba->dev, "%s: NOP OUT failed %d\n", __func__, err);
4441 * ufshcd_set_queue_depth - set lun queue depth
4442 * @sdev: pointer to SCSI device
4444 * Read bLUQueueDepth value and activate scsi tagged command
4445 * queueing. For WLUN, queue depth is set to 1. For best-effort
4446 * cases (bLUQueueDepth = 0) the queue depth is set to a maximum
4447 * value that host can queue.
4449 static void ufshcd_set_queue_depth(struct scsi_device *sdev)
4453 struct ufs_hba *hba;
4455 hba = shost_priv(sdev->host);
4457 lun_qdepth = hba->nutrs;
4458 ret = ufshcd_read_unit_desc_param(hba,
4459 ufshcd_scsi_to_upiu_lun(sdev->lun),
4460 UNIT_DESC_PARAM_LU_Q_DEPTH,
4462 sizeof(lun_qdepth));
4464 /* Some WLUN doesn't support unit descriptor */
4465 if (ret == -EOPNOTSUPP)
4467 else if (!lun_qdepth)
4468 /* eventually, we can figure out the real queue depth */
4469 lun_qdepth = hba->nutrs;
4471 lun_qdepth = min_t(int, lun_qdepth, hba->nutrs);
4473 dev_dbg(hba->dev, "%s: activate tcq with queue depth %d\n",
4474 __func__, lun_qdepth);
4475 scsi_change_queue_depth(sdev, lun_qdepth);
4479 * ufshcd_get_lu_wp - returns the "b_lu_write_protect" from UNIT DESCRIPTOR
4480 * @hba: per-adapter instance
4481 * @lun: UFS device lun id
4482 * @b_lu_write_protect: pointer to buffer to hold the LU's write protect info
4484 * Returns 0 in case of success and b_lu_write_protect status would be returned
4485 * @b_lu_write_protect parameter.
4486 * Returns -ENOTSUPP if reading b_lu_write_protect is not supported.
4487 * Returns -EINVAL in case of invalid parameters passed to this function.
4489 static int ufshcd_get_lu_wp(struct ufs_hba *hba,
4491 u8 *b_lu_write_protect)
4495 if (!b_lu_write_protect)
4498 * According to UFS device spec, RPMB LU can't be write
4499 * protected so skip reading bLUWriteProtect parameter for
4500 * it. For other W-LUs, UNIT DESCRIPTOR is not available.
4502 else if (lun >= UFS_UPIU_MAX_GENERAL_LUN)
4505 ret = ufshcd_read_unit_desc_param(hba,
4507 UNIT_DESC_PARAM_LU_WR_PROTECT,
4509 sizeof(*b_lu_write_protect));
4514 * ufshcd_get_lu_power_on_wp_status - get LU's power on write protect
4516 * @hba: per-adapter instance
4517 * @sdev: pointer to SCSI device
4520 static inline void ufshcd_get_lu_power_on_wp_status(struct ufs_hba *hba,
4521 struct scsi_device *sdev)
4523 if (hba->dev_info.f_power_on_wp_en &&
4524 !hba->dev_info.is_lu_power_on_wp) {
4525 u8 b_lu_write_protect;
4527 if (!ufshcd_get_lu_wp(hba, ufshcd_scsi_to_upiu_lun(sdev->lun),
4528 &b_lu_write_protect) &&
4529 (b_lu_write_protect == UFS_LU_POWER_ON_WP))
4530 hba->dev_info.is_lu_power_on_wp = true;
4535 * ufshcd_slave_alloc - handle initial SCSI device configurations
4536 * @sdev: pointer to SCSI device
4540 static int ufshcd_slave_alloc(struct scsi_device *sdev)
4542 struct ufs_hba *hba;
4544 hba = shost_priv(sdev->host);
4546 /* Mode sense(6) is not supported by UFS, so use Mode sense(10) */
4547 sdev->use_10_for_ms = 1;
4549 /* allow SCSI layer to restart the device in case of errors */
4550 sdev->allow_restart = 1;
4552 /* REPORT SUPPORTED OPERATION CODES is not supported */
4553 sdev->no_report_opcodes = 1;
4555 /* WRITE_SAME command is not supported */
4556 sdev->no_write_same = 1;
4558 ufshcd_set_queue_depth(sdev);
4560 ufshcd_get_lu_power_on_wp_status(hba, sdev);
4566 * ufshcd_change_queue_depth - change queue depth
4567 * @sdev: pointer to SCSI device
4568 * @depth: required depth to set
4570 * Change queue depth and make sure the max. limits are not crossed.
4572 static int ufshcd_change_queue_depth(struct scsi_device *sdev, int depth)
4574 struct ufs_hba *hba = shost_priv(sdev->host);
4576 if (depth > hba->nutrs)
4578 return scsi_change_queue_depth(sdev, depth);
4582 * ufshcd_slave_configure - adjust SCSI device configurations
4583 * @sdev: pointer to SCSI device
4585 static int ufshcd_slave_configure(struct scsi_device *sdev)
4587 struct request_queue *q = sdev->request_queue;
4589 blk_queue_update_dma_pad(q, PRDT_DATA_BYTE_COUNT_PAD - 1);
4594 * ufshcd_slave_destroy - remove SCSI device configurations
4595 * @sdev: pointer to SCSI device
4597 static void ufshcd_slave_destroy(struct scsi_device *sdev)
4599 struct ufs_hba *hba;
4601 hba = shost_priv(sdev->host);
4602 /* Drop the reference as it won't be needed anymore */
4603 if (ufshcd_scsi_to_upiu_lun(sdev->lun) == UFS_UPIU_UFS_DEVICE_WLUN) {
4604 unsigned long flags;
4606 spin_lock_irqsave(hba->host->host_lock, flags);
4607 hba->sdev_ufs_device = NULL;
4608 spin_unlock_irqrestore(hba->host->host_lock, flags);
4613 * ufshcd_scsi_cmd_status - Update SCSI command result based on SCSI status
4614 * @lrbp: pointer to local reference block of completed command
4615 * @scsi_status: SCSI command status
4617 * Returns value base on SCSI command status
4620 ufshcd_scsi_cmd_status(struct ufshcd_lrb *lrbp, int scsi_status)
4624 switch (scsi_status) {
4625 case SAM_STAT_CHECK_CONDITION:
4626 ufshcd_copy_sense_data(lrbp);
4629 result |= DID_OK << 16 |
4630 COMMAND_COMPLETE << 8 |
4633 case SAM_STAT_TASK_SET_FULL:
4635 case SAM_STAT_TASK_ABORTED:
4636 ufshcd_copy_sense_data(lrbp);
4637 result |= scsi_status;
4640 result |= DID_ERROR << 16;
4642 } /* end of switch */
4648 * ufshcd_transfer_rsp_status - Get overall status of the response
4649 * @hba: per adapter instance
4650 * @lrbp: pointer to local reference block of completed command
4652 * Returns result of the command to notify SCSI midlayer
4655 ufshcd_transfer_rsp_status(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
4661 /* overall command status of utrd */
4662 ocs = ufshcd_get_tr_ocs(lrbp);
4666 result = ufshcd_get_req_rsp(lrbp->ucd_rsp_ptr);
4667 hba->ufs_stats.last_hibern8_exit_tstamp = ktime_set(0, 0);
4669 case UPIU_TRANSACTION_RESPONSE:
4671 * get the response UPIU result to extract
4672 * the SCSI command status
4674 result = ufshcd_get_rsp_upiu_result(lrbp->ucd_rsp_ptr);
4677 * get the result based on SCSI status response
4678 * to notify the SCSI midlayer of the command status
4680 scsi_status = result & MASK_SCSI_STATUS;
4681 result = ufshcd_scsi_cmd_status(lrbp, scsi_status);
4684 * Currently we are only supporting BKOPs exception
4685 * events hence we can ignore BKOPs exception event
4686 * during power management callbacks. BKOPs exception
4687 * event is not expected to be raised in runtime suspend
4688 * callback as it allows the urgent bkops.
4689 * During system suspend, we are anyway forcefully
4690 * disabling the bkops and if urgent bkops is needed
4691 * it will be enabled on system resume. Long term
4692 * solution could be to abort the system suspend if
4693 * UFS device needs urgent BKOPs.
4695 if (!hba->pm_op_in_progress &&
4696 ufshcd_is_exception_event(lrbp->ucd_rsp_ptr))
4697 schedule_work(&hba->eeh_work);
4699 case UPIU_TRANSACTION_REJECT_UPIU:
4700 /* TODO: handle Reject UPIU Response */
4701 result = DID_ERROR << 16;
4703 "Reject UPIU not fully implemented\n");
4707 "Unexpected request response code = %x\n",
4709 result = DID_ERROR << 16;
4714 result |= DID_ABORT << 16;
4716 case OCS_INVALID_COMMAND_STATUS:
4717 result |= DID_REQUEUE << 16;
4719 case OCS_INVALID_CMD_TABLE_ATTR:
4720 case OCS_INVALID_PRDT_ATTR:
4721 case OCS_MISMATCH_DATA_BUF_SIZE:
4722 case OCS_MISMATCH_RESP_UPIU_SIZE:
4723 case OCS_PEER_COMM_FAILURE:
4724 case OCS_FATAL_ERROR:
4726 result |= DID_ERROR << 16;
4728 "OCS error from controller = %x for tag %d\n",
4729 ocs, lrbp->task_tag);
4730 ufshcd_print_host_regs(hba);
4731 ufshcd_print_host_state(hba);
4733 } /* end of switch */
4735 if (host_byte(result) != DID_OK)
4736 ufshcd_print_trs(hba, 1 << lrbp->task_tag, true);
4741 * ufshcd_uic_cmd_compl - handle completion of uic command
4742 * @hba: per adapter instance
4743 * @intr_status: interrupt status generated by the controller
4745 static void ufshcd_uic_cmd_compl(struct ufs_hba *hba, u32 intr_status)
4747 if ((intr_status & UIC_COMMAND_COMPL) && hba->active_uic_cmd) {
4748 hba->active_uic_cmd->argument2 |=
4749 ufshcd_get_uic_cmd_result(hba);
4750 hba->active_uic_cmd->argument3 =
4751 ufshcd_get_dme_attr_val(hba);
4752 complete(&hba->active_uic_cmd->done);
4755 if ((intr_status & UFSHCD_UIC_PWR_MASK) && hba->uic_async_done)
4756 complete(hba->uic_async_done);
4760 * __ufshcd_transfer_req_compl - handle SCSI and query command completion
4761 * @hba: per adapter instance
4762 * @completed_reqs: requests to complete
4764 static void __ufshcd_transfer_req_compl(struct ufs_hba *hba,
4765 unsigned long completed_reqs)
4767 struct ufshcd_lrb *lrbp;
4768 struct scsi_cmnd *cmd;
4772 for_each_set_bit(index, &completed_reqs, hba->nutrs) {
4773 lrbp = &hba->lrb[index];
4776 ufshcd_add_command_trace(hba, index, "complete");
4777 result = ufshcd_transfer_rsp_status(hba, lrbp);
4778 scsi_dma_unmap(cmd);
4779 cmd->result = result;
4780 /* Mark completed command as NULL in LRB */
4782 clear_bit_unlock(index, &hba->lrb_in_use);
4783 /* Do not touch lrbp after scsi done */
4784 cmd->scsi_done(cmd);
4785 __ufshcd_release(hba);
4786 } else if (lrbp->command_type == UTP_CMD_TYPE_DEV_MANAGE ||
4787 lrbp->command_type == UTP_CMD_TYPE_UFS_STORAGE) {
4788 if (hba->dev_cmd.complete) {
4789 ufshcd_add_command_trace(hba, index,
4791 complete(hba->dev_cmd.complete);
4794 if (ufshcd_is_clkscaling_supported(hba))
4795 hba->clk_scaling.active_reqs--;
4797 lrbp->compl_time_stamp = ktime_get();
4800 /* clear corresponding bits of completed commands */
4801 hba->outstanding_reqs ^= completed_reqs;
4803 ufshcd_clk_scaling_update_busy(hba);
4805 /* we might have free'd some tags above */
4806 wake_up(&hba->dev_cmd.tag_wq);
4810 * ufshcd_transfer_req_compl - handle SCSI and query command completion
4811 * @hba: per adapter instance
4813 static void ufshcd_transfer_req_compl(struct ufs_hba *hba)
4815 unsigned long completed_reqs;
4818 /* Resetting interrupt aggregation counters first and reading the
4819 * DOOR_BELL afterward allows us to handle all the completed requests.
4820 * In order to prevent other interrupts starvation the DB is read once
4821 * after reset. The down side of this solution is the possibility of
4822 * false interrupt if device completes another request after resetting
4823 * aggregation and before reading the DB.
4825 if (ufshcd_is_intr_aggr_allowed(hba) &&
4826 !(hba->quirks & UFSHCI_QUIRK_SKIP_RESET_INTR_AGGR))
4827 ufshcd_reset_intr_aggr(hba);
4829 tr_doorbell = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
4830 completed_reqs = tr_doorbell ^ hba->outstanding_reqs;
4832 __ufshcd_transfer_req_compl(hba, completed_reqs);
4836 * ufshcd_disable_ee - disable exception event
4837 * @hba: per-adapter instance
4838 * @mask: exception event to disable
4840 * Disables exception event in the device so that the EVENT_ALERT
4843 * Returns zero on success, non-zero error value on failure.
4845 static int ufshcd_disable_ee(struct ufs_hba *hba, u16 mask)
4850 if (!(hba->ee_ctrl_mask & mask))
4853 val = hba->ee_ctrl_mask & ~mask;
4854 val &= MASK_EE_STATUS;
4855 err = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_WRITE_ATTR,
4856 QUERY_ATTR_IDN_EE_CONTROL, 0, 0, &val);
4858 hba->ee_ctrl_mask &= ~mask;
4864 * ufshcd_enable_ee - enable exception event
4865 * @hba: per-adapter instance
4866 * @mask: exception event to enable
4868 * Enable corresponding exception event in the device to allow
4869 * device to alert host in critical scenarios.
4871 * Returns zero on success, non-zero error value on failure.
4873 static int ufshcd_enable_ee(struct ufs_hba *hba, u16 mask)
4878 if (hba->ee_ctrl_mask & mask)
4881 val = hba->ee_ctrl_mask | mask;
4882 val &= MASK_EE_STATUS;
4883 err = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_WRITE_ATTR,
4884 QUERY_ATTR_IDN_EE_CONTROL, 0, 0, &val);
4886 hba->ee_ctrl_mask |= mask;
4892 * ufshcd_enable_auto_bkops - Allow device managed BKOPS
4893 * @hba: per-adapter instance
4895 * Allow device to manage background operations on its own. Enabling
4896 * this might lead to inconsistent latencies during normal data transfers
4897 * as the device is allowed to manage its own way of handling background
4900 * Returns zero on success, non-zero on failure.
4902 static int ufshcd_enable_auto_bkops(struct ufs_hba *hba)
4906 if (hba->auto_bkops_enabled)
4909 err = ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_SET_FLAG,
4910 QUERY_FLAG_IDN_BKOPS_EN, NULL);
4912 dev_err(hba->dev, "%s: failed to enable bkops %d\n",
4917 hba->auto_bkops_enabled = true;
4918 trace_ufshcd_auto_bkops_state(dev_name(hba->dev), "Enabled");
4920 /* No need of URGENT_BKOPS exception from the device */
4921 err = ufshcd_disable_ee(hba, MASK_EE_URGENT_BKOPS);
4923 dev_err(hba->dev, "%s: failed to disable exception event %d\n",
4930 * ufshcd_disable_auto_bkops - block device in doing background operations
4931 * @hba: per-adapter instance
4933 * Disabling background operations improves command response latency but
4934 * has drawback of device moving into critical state where the device is
4935 * not-operable. Make sure to call ufshcd_enable_auto_bkops() whenever the
4936 * host is idle so that BKOPS are managed effectively without any negative
4939 * Returns zero on success, non-zero on failure.
4941 static int ufshcd_disable_auto_bkops(struct ufs_hba *hba)
4945 if (!hba->auto_bkops_enabled)
4949 * If host assisted BKOPs is to be enabled, make sure
4950 * urgent bkops exception is allowed.
4952 err = ufshcd_enable_ee(hba, MASK_EE_URGENT_BKOPS);
4954 dev_err(hba->dev, "%s: failed to enable exception event %d\n",
4959 err = ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_CLEAR_FLAG,
4960 QUERY_FLAG_IDN_BKOPS_EN, NULL);
4962 dev_err(hba->dev, "%s: failed to disable bkops %d\n",
4964 ufshcd_disable_ee(hba, MASK_EE_URGENT_BKOPS);
4968 hba->auto_bkops_enabled = false;
4969 trace_ufshcd_auto_bkops_state(dev_name(hba->dev), "Disabled");
4975 * ufshcd_force_reset_auto_bkops - force reset auto bkops state
4976 * @hba: per adapter instance
4978 * After a device reset the device may toggle the BKOPS_EN flag
4979 * to default value. The s/w tracking variables should be updated
4980 * as well. This function would change the auto-bkops state based on
4981 * UFSHCD_CAP_KEEP_AUTO_BKOPS_ENABLED_EXCEPT_SUSPEND.
4983 static void ufshcd_force_reset_auto_bkops(struct ufs_hba *hba)
4985 if (ufshcd_keep_autobkops_enabled_except_suspend(hba)) {
4986 hba->auto_bkops_enabled = false;
4987 hba->ee_ctrl_mask |= MASK_EE_URGENT_BKOPS;
4988 ufshcd_enable_auto_bkops(hba);
4990 hba->auto_bkops_enabled = true;
4991 hba->ee_ctrl_mask &= ~MASK_EE_URGENT_BKOPS;
4992 ufshcd_disable_auto_bkops(hba);
4996 static inline int ufshcd_get_bkops_status(struct ufs_hba *hba, u32 *status)
4998 return ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
4999 QUERY_ATTR_IDN_BKOPS_STATUS, 0, 0, status);
5003 * ufshcd_bkops_ctrl - control the auto bkops based on current bkops status
5004 * @hba: per-adapter instance
5005 * @status: bkops_status value
5007 * Read the bkops_status from the UFS device and Enable fBackgroundOpsEn
5008 * flag in the device to permit background operations if the device
5009 * bkops_status is greater than or equal to "status" argument passed to
5010 * this function, disable otherwise.
5012 * Returns 0 for success, non-zero in case of failure.
5014 * NOTE: Caller of this function can check the "hba->auto_bkops_enabled" flag
5015 * to know whether auto bkops is enabled or disabled after this function
5016 * returns control to it.
5018 static int ufshcd_bkops_ctrl(struct ufs_hba *hba,
5019 enum bkops_status status)
5022 u32 curr_status = 0;
5024 err = ufshcd_get_bkops_status(hba, &curr_status);
5026 dev_err(hba->dev, "%s: failed to get BKOPS status %d\n",
5029 } else if (curr_status > BKOPS_STATUS_MAX) {
5030 dev_err(hba->dev, "%s: invalid BKOPS status %d\n",
5031 __func__, curr_status);
5036 if (curr_status >= status)
5037 err = ufshcd_enable_auto_bkops(hba);
5039 err = ufshcd_disable_auto_bkops(hba);
5045 * ufshcd_urgent_bkops - handle urgent bkops exception event
5046 * @hba: per-adapter instance
5048 * Enable fBackgroundOpsEn flag in the device to permit background
5051 * If BKOPs is enabled, this function returns 0, 1 if the bkops in not enabled
5052 * and negative error value for any other failure.
5054 static int ufshcd_urgent_bkops(struct ufs_hba *hba)
5056 return ufshcd_bkops_ctrl(hba, hba->urgent_bkops_lvl);
5059 static inline int ufshcd_get_ee_status(struct ufs_hba *hba, u32 *status)
5061 return ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
5062 QUERY_ATTR_IDN_EE_STATUS, 0, 0, status);
5065 static void ufshcd_bkops_exception_event_handler(struct ufs_hba *hba)
5068 u32 curr_status = 0;
5070 if (hba->is_urgent_bkops_lvl_checked)
5071 goto enable_auto_bkops;
5073 err = ufshcd_get_bkops_status(hba, &curr_status);
5075 dev_err(hba->dev, "%s: failed to get BKOPS status %d\n",
5081 * We are seeing that some devices are raising the urgent bkops
5082 * exception events even when BKOPS status doesn't indicate performace
5083 * impacted or critical. Handle these device by determining their urgent
5084 * bkops status at runtime.
5086 if (curr_status < BKOPS_STATUS_PERF_IMPACT) {
5087 dev_err(hba->dev, "%s: device raised urgent BKOPS exception for bkops status %d\n",
5088 __func__, curr_status);
5089 /* update the current status as the urgent bkops level */
5090 hba->urgent_bkops_lvl = curr_status;
5091 hba->is_urgent_bkops_lvl_checked = true;
5095 err = ufshcd_enable_auto_bkops(hba);
5098 dev_err(hba->dev, "%s: failed to handle urgent bkops %d\n",
5103 * ufshcd_exception_event_handler - handle exceptions raised by device
5104 * @work: pointer to work data
5106 * Read bExceptionEventStatus attribute from the device and handle the
5107 * exception event accordingly.
5109 static void ufshcd_exception_event_handler(struct work_struct *work)
5111 struct ufs_hba *hba;
5114 hba = container_of(work, struct ufs_hba, eeh_work);
5116 pm_runtime_get_sync(hba->dev);
5117 scsi_block_requests(hba->host);
5118 err = ufshcd_get_ee_status(hba, &status);
5120 dev_err(hba->dev, "%s: failed to get exception status %d\n",
5125 status &= hba->ee_ctrl_mask;
5127 if (status & MASK_EE_URGENT_BKOPS)
5128 ufshcd_bkops_exception_event_handler(hba);
5131 scsi_unblock_requests(hba->host);
5132 pm_runtime_put_sync(hba->dev);
5136 /* Complete requests that have door-bell cleared */
5137 static void ufshcd_complete_requests(struct ufs_hba *hba)
5139 ufshcd_transfer_req_compl(hba);
5140 ufshcd_tmc_handler(hba);
5144 * ufshcd_quirk_dl_nac_errors - This function checks if error handling is
5145 * to recover from the DL NAC errors or not.
5146 * @hba: per-adapter instance
5148 * Returns true if error handling is required, false otherwise
5150 static bool ufshcd_quirk_dl_nac_errors(struct ufs_hba *hba)
5152 unsigned long flags;
5153 bool err_handling = true;
5155 spin_lock_irqsave(hba->host->host_lock, flags);
5157 * UFS_DEVICE_QUIRK_RECOVERY_FROM_DL_NAC_ERRORS only workaround the
5158 * device fatal error and/or DL NAC & REPLAY timeout errors.
5160 if (hba->saved_err & (CONTROLLER_FATAL_ERROR | SYSTEM_BUS_FATAL_ERROR))
5163 if ((hba->saved_err & DEVICE_FATAL_ERROR) ||
5164 ((hba->saved_err & UIC_ERROR) &&
5165 (hba->saved_uic_err & UFSHCD_UIC_DL_TCx_REPLAY_ERROR)))
5168 if ((hba->saved_err & UIC_ERROR) &&
5169 (hba->saved_uic_err & UFSHCD_UIC_DL_NAC_RECEIVED_ERROR)) {
5172 * wait for 50ms to see if we can get any other errors or not.
5174 spin_unlock_irqrestore(hba->host->host_lock, flags);
5176 spin_lock_irqsave(hba->host->host_lock, flags);
5179 * now check if we have got any other severe errors other than
5182 if ((hba->saved_err & INT_FATAL_ERRORS) ||
5183 ((hba->saved_err & UIC_ERROR) &&
5184 (hba->saved_uic_err & ~UFSHCD_UIC_DL_NAC_RECEIVED_ERROR)))
5188 * As DL NAC is the only error received so far, send out NOP
5189 * command to confirm if link is still active or not.
5190 * - If we don't get any response then do error recovery.
5191 * - If we get response then clear the DL NAC error bit.
5194 spin_unlock_irqrestore(hba->host->host_lock, flags);
5195 err = ufshcd_verify_dev_init(hba);
5196 spin_lock_irqsave(hba->host->host_lock, flags);
5201 /* Link seems to be alive hence ignore the DL NAC errors */
5202 if (hba->saved_uic_err == UFSHCD_UIC_DL_NAC_RECEIVED_ERROR)
5203 hba->saved_err &= ~UIC_ERROR;
5204 /* clear NAC error */
5205 hba->saved_uic_err &= ~UFSHCD_UIC_DL_NAC_RECEIVED_ERROR;
5206 if (!hba->saved_uic_err) {
5207 err_handling = false;
5212 spin_unlock_irqrestore(hba->host->host_lock, flags);
5213 return err_handling;
5217 * ufshcd_err_handler - handle UFS errors that require s/w attention
5218 * @work: pointer to work structure
5220 static void ufshcd_err_handler(struct work_struct *work)
5222 struct ufs_hba *hba;
5223 unsigned long flags;
5228 bool needs_reset = false;
5230 hba = container_of(work, struct ufs_hba, eh_work);
5232 pm_runtime_get_sync(hba->dev);
5233 ufshcd_hold(hba, false);
5235 spin_lock_irqsave(hba->host->host_lock, flags);
5236 if (hba->ufshcd_state == UFSHCD_STATE_RESET)
5239 hba->ufshcd_state = UFSHCD_STATE_RESET;
5240 ufshcd_set_eh_in_progress(hba);
5242 /* Complete requests that have door-bell cleared by h/w */
5243 ufshcd_complete_requests(hba);
5245 if (hba->dev_quirks & UFS_DEVICE_QUIRK_RECOVERY_FROM_DL_NAC_ERRORS) {
5248 spin_unlock_irqrestore(hba->host->host_lock, flags);
5249 /* release the lock as ufshcd_quirk_dl_nac_errors() may sleep */
5250 ret = ufshcd_quirk_dl_nac_errors(hba);
5251 spin_lock_irqsave(hba->host->host_lock, flags);
5253 goto skip_err_handling;
5255 if ((hba->saved_err & INT_FATAL_ERRORS) ||
5256 (hba->saved_err & UFSHCD_UIC_HIBERN8_MASK) ||
5257 ((hba->saved_err & UIC_ERROR) &&
5258 (hba->saved_uic_err & (UFSHCD_UIC_DL_PA_INIT_ERROR |
5259 UFSHCD_UIC_DL_NAC_RECEIVED_ERROR |
5260 UFSHCD_UIC_DL_TCx_REPLAY_ERROR))))
5264 * if host reset is required then skip clearing the pending
5265 * transfers forcefully because they will automatically get
5266 * cleared after link startup.
5269 goto skip_pending_xfer_clear;
5271 /* release lock as clear command might sleep */
5272 spin_unlock_irqrestore(hba->host->host_lock, flags);
5273 /* Clear pending transfer requests */
5274 for_each_set_bit(tag, &hba->outstanding_reqs, hba->nutrs) {
5275 if (ufshcd_clear_cmd(hba, tag)) {
5277 goto lock_skip_pending_xfer_clear;
5281 /* Clear pending task management requests */
5282 for_each_set_bit(tag, &hba->outstanding_tasks, hba->nutmrs) {
5283 if (ufshcd_clear_tm_cmd(hba, tag)) {
5285 goto lock_skip_pending_xfer_clear;
5289 lock_skip_pending_xfer_clear:
5290 spin_lock_irqsave(hba->host->host_lock, flags);
5292 /* Complete the requests that are cleared by s/w */
5293 ufshcd_complete_requests(hba);
5295 if (err_xfer || err_tm)
5298 skip_pending_xfer_clear:
5299 /* Fatal errors need reset */
5301 unsigned long max_doorbells = (1UL << hba->nutrs) - 1;
5304 * ufshcd_reset_and_restore() does the link reinitialization
5305 * which will need atleast one empty doorbell slot to send the
5306 * device management commands (NOP and query commands).
5307 * If there is no slot empty at this moment then free up last
5310 if (hba->outstanding_reqs == max_doorbells)
5311 __ufshcd_transfer_req_compl(hba,
5312 (1UL << (hba->nutrs - 1)));
5314 spin_unlock_irqrestore(hba->host->host_lock, flags);
5315 err = ufshcd_reset_and_restore(hba);
5316 spin_lock_irqsave(hba->host->host_lock, flags);
5318 dev_err(hba->dev, "%s: reset and restore failed\n",
5320 hba->ufshcd_state = UFSHCD_STATE_ERROR;
5323 * Inform scsi mid-layer that we did reset and allow to handle
5324 * Unit Attention properly.
5326 scsi_report_bus_reset(hba->host, 0);
5328 hba->saved_uic_err = 0;
5333 hba->ufshcd_state = UFSHCD_STATE_OPERATIONAL;
5334 if (hba->saved_err || hba->saved_uic_err)
5335 dev_err_ratelimited(hba->dev, "%s: exit: saved_err 0x%x saved_uic_err 0x%x",
5336 __func__, hba->saved_err, hba->saved_uic_err);
5339 ufshcd_clear_eh_in_progress(hba);
5342 spin_unlock_irqrestore(hba->host->host_lock, flags);
5343 ufshcd_scsi_unblock_requests(hba);
5344 ufshcd_release(hba);
5345 pm_runtime_put_sync(hba->dev);
5348 static void ufshcd_update_uic_reg_hist(struct ufs_uic_err_reg_hist *reg_hist,
5351 reg_hist->reg[reg_hist->pos] = reg;
5352 reg_hist->tstamp[reg_hist->pos] = ktime_get();
5353 reg_hist->pos = (reg_hist->pos + 1) % UIC_ERR_REG_HIST_LENGTH;
5357 * ufshcd_update_uic_error - check and set fatal UIC error flags.
5358 * @hba: per-adapter instance
5360 static void ufshcd_update_uic_error(struct ufs_hba *hba)
5364 /* PHY layer lane error */
5365 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_PHY_ADAPTER_LAYER);
5366 /* Ignore LINERESET indication, as this is not an error */
5367 if ((reg & UIC_PHY_ADAPTER_LAYER_ERROR) &&
5368 (reg & UIC_PHY_ADAPTER_LAYER_LANE_ERR_MASK)) {
5370 * To know whether this error is fatal or not, DB timeout
5371 * must be checked but this error is handled separately.
5373 dev_dbg(hba->dev, "%s: UIC Lane error reported\n", __func__);
5374 ufshcd_update_uic_reg_hist(&hba->ufs_stats.pa_err, reg);
5377 /* PA_INIT_ERROR is fatal and needs UIC reset */
5378 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_DATA_LINK_LAYER);
5380 ufshcd_update_uic_reg_hist(&hba->ufs_stats.dl_err, reg);
5382 if (reg & UIC_DATA_LINK_LAYER_ERROR_PA_INIT)
5383 hba->uic_error |= UFSHCD_UIC_DL_PA_INIT_ERROR;
5384 else if (hba->dev_quirks &
5385 UFS_DEVICE_QUIRK_RECOVERY_FROM_DL_NAC_ERRORS) {
5386 if (reg & UIC_DATA_LINK_LAYER_ERROR_NAC_RECEIVED)
5388 UFSHCD_UIC_DL_NAC_RECEIVED_ERROR;
5389 else if (reg & UIC_DATA_LINK_LAYER_ERROR_TCx_REPLAY_TIMEOUT)
5390 hba->uic_error |= UFSHCD_UIC_DL_TCx_REPLAY_ERROR;
5393 /* UIC NL/TL/DME errors needs software retry */
5394 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_NETWORK_LAYER);
5396 ufshcd_update_uic_reg_hist(&hba->ufs_stats.nl_err, reg);
5397 hba->uic_error |= UFSHCD_UIC_NL_ERROR;
5400 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_TRANSPORT_LAYER);
5402 ufshcd_update_uic_reg_hist(&hba->ufs_stats.tl_err, reg);
5403 hba->uic_error |= UFSHCD_UIC_TL_ERROR;
5406 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_DME);
5408 ufshcd_update_uic_reg_hist(&hba->ufs_stats.dme_err, reg);
5409 hba->uic_error |= UFSHCD_UIC_DME_ERROR;
5412 dev_dbg(hba->dev, "%s: UIC error flags = 0x%08x\n",
5413 __func__, hba->uic_error);
5416 static bool ufshcd_is_auto_hibern8_error(struct ufs_hba *hba,
5419 if (!ufshcd_is_auto_hibern8_supported(hba))
5422 if (!(intr_mask & UFSHCD_UIC_HIBERN8_MASK))
5425 if (hba->active_uic_cmd &&
5426 (hba->active_uic_cmd->command == UIC_CMD_DME_HIBER_ENTER ||
5427 hba->active_uic_cmd->command == UIC_CMD_DME_HIBER_EXIT))
5434 * ufshcd_check_errors - Check for errors that need s/w attention
5435 * @hba: per-adapter instance
5437 static void ufshcd_check_errors(struct ufs_hba *hba)
5439 bool queue_eh_work = false;
5441 if (hba->errors & INT_FATAL_ERRORS)
5442 queue_eh_work = true;
5444 if (hba->errors & UIC_ERROR) {
5446 ufshcd_update_uic_error(hba);
5448 queue_eh_work = true;
5451 if (hba->errors & UFSHCD_UIC_HIBERN8_MASK) {
5453 "%s: Auto Hibern8 %s failed - status: 0x%08x, upmcrs: 0x%08x\n",
5454 __func__, (hba->errors & UIC_HIBERNATE_ENTER) ?
5456 hba->errors, ufshcd_get_upmcrs(hba));
5457 queue_eh_work = true;
5460 if (queue_eh_work) {
5462 * update the transfer error masks to sticky bits, let's do this
5463 * irrespective of current ufshcd_state.
5465 hba->saved_err |= hba->errors;
5466 hba->saved_uic_err |= hba->uic_error;
5468 /* handle fatal errors only when link is functional */
5469 if (hba->ufshcd_state == UFSHCD_STATE_OPERATIONAL) {
5470 /* block commands from scsi mid-layer */
5471 ufshcd_scsi_block_requests(hba);
5473 hba->ufshcd_state = UFSHCD_STATE_EH_SCHEDULED;
5475 /* dump controller state before resetting */
5476 if (hba->saved_err & (INT_FATAL_ERRORS | UIC_ERROR)) {
5477 bool pr_prdt = !!(hba->saved_err &
5478 SYSTEM_BUS_FATAL_ERROR);
5480 dev_err(hba->dev, "%s: saved_err 0x%x saved_uic_err 0x%x\n",
5481 __func__, hba->saved_err,
5482 hba->saved_uic_err);
5484 ufshcd_print_host_regs(hba);
5485 ufshcd_print_pwr_info(hba);
5486 ufshcd_print_tmrs(hba, hba->outstanding_tasks);
5487 ufshcd_print_trs(hba, hba->outstanding_reqs,
5490 schedule_work(&hba->eh_work);
5494 * if (!queue_eh_work) -
5495 * Other errors are either non-fatal where host recovers
5496 * itself without s/w intervention or errors that will be
5497 * handled by the SCSI core layer.
5502 * ufshcd_tmc_handler - handle task management function completion
5503 * @hba: per adapter instance
5505 static void ufshcd_tmc_handler(struct ufs_hba *hba)
5509 tm_doorbell = ufshcd_readl(hba, REG_UTP_TASK_REQ_DOOR_BELL);
5510 hba->tm_condition = tm_doorbell ^ hba->outstanding_tasks;
5511 wake_up(&hba->tm_wq);
5515 * ufshcd_sl_intr - Interrupt service routine
5516 * @hba: per adapter instance
5517 * @intr_status: contains interrupts generated by the controller
5519 static void ufshcd_sl_intr(struct ufs_hba *hba, u32 intr_status)
5521 hba->errors = UFSHCD_ERROR_MASK & intr_status;
5523 if (ufshcd_is_auto_hibern8_error(hba, intr_status))
5524 hba->errors |= (UFSHCD_UIC_HIBERN8_MASK & intr_status);
5527 ufshcd_check_errors(hba);
5529 if (intr_status & UFSHCD_UIC_MASK)
5530 ufshcd_uic_cmd_compl(hba, intr_status);
5532 if (intr_status & UTP_TASK_REQ_COMPL)
5533 ufshcd_tmc_handler(hba);
5535 if (intr_status & UTP_TRANSFER_REQ_COMPL)
5536 ufshcd_transfer_req_compl(hba);
5540 * ufshcd_intr - Main interrupt service routine
5542 * @__hba: pointer to adapter instance
5544 * Returns IRQ_HANDLED - If interrupt is valid
5545 * IRQ_NONE - If invalid interrupt
5547 static irqreturn_t ufshcd_intr(int irq, void *__hba)
5549 u32 intr_status, enabled_intr_status;
5550 irqreturn_t retval = IRQ_NONE;
5551 struct ufs_hba *hba = __hba;
5552 int retries = hba->nutrs;
5554 spin_lock(hba->host->host_lock);
5555 intr_status = ufshcd_readl(hba, REG_INTERRUPT_STATUS);
5558 * There could be max of hba->nutrs reqs in flight and in worst case
5559 * if the reqs get finished 1 by 1 after the interrupt status is
5560 * read, make sure we handle them by checking the interrupt status
5561 * again in a loop until we process all of the reqs before returning.
5564 enabled_intr_status =
5565 intr_status & ufshcd_readl(hba, REG_INTERRUPT_ENABLE);
5567 ufshcd_writel(hba, intr_status, REG_INTERRUPT_STATUS);
5568 if (enabled_intr_status) {
5569 ufshcd_sl_intr(hba, enabled_intr_status);
5570 retval = IRQ_HANDLED;
5573 intr_status = ufshcd_readl(hba, REG_INTERRUPT_STATUS);
5574 } while (intr_status && --retries);
5576 spin_unlock(hba->host->host_lock);
5580 static int ufshcd_clear_tm_cmd(struct ufs_hba *hba, int tag)
5583 u32 mask = 1 << tag;
5584 unsigned long flags;
5586 if (!test_bit(tag, &hba->outstanding_tasks))
5589 spin_lock_irqsave(hba->host->host_lock, flags);
5590 ufshcd_utmrl_clear(hba, tag);
5591 spin_unlock_irqrestore(hba->host->host_lock, flags);
5593 /* poll for max. 1 sec to clear door bell register by h/w */
5594 err = ufshcd_wait_for_register(hba,
5595 REG_UTP_TASK_REQ_DOOR_BELL,
5596 mask, 0, 1000, 1000, true);
5601 static int __ufshcd_issue_tm_cmd(struct ufs_hba *hba,
5602 struct utp_task_req_desc *treq, u8 tm_function)
5604 struct Scsi_Host *host = hba->host;
5605 unsigned long flags;
5606 int free_slot, task_tag, err;
5609 * Get free slot, sleep if slots are unavailable.
5610 * Even though we use wait_event() which sleeps indefinitely,
5611 * the maximum wait time is bounded by %TM_CMD_TIMEOUT.
5613 wait_event(hba->tm_tag_wq, ufshcd_get_tm_free_slot(hba, &free_slot));
5614 ufshcd_hold(hba, false);
5616 spin_lock_irqsave(host->host_lock, flags);
5617 task_tag = hba->nutrs + free_slot;
5619 treq->req_header.dword_0 |= cpu_to_be32(task_tag);
5621 memcpy(hba->utmrdl_base_addr + free_slot, treq, sizeof(*treq));
5622 ufshcd_vops_setup_task_mgmt(hba, free_slot, tm_function);
5624 /* send command to the controller */
5625 __set_bit(free_slot, &hba->outstanding_tasks);
5627 /* Make sure descriptors are ready before ringing the task doorbell */
5630 ufshcd_writel(hba, 1 << free_slot, REG_UTP_TASK_REQ_DOOR_BELL);
5631 /* Make sure that doorbell is committed immediately */
5634 spin_unlock_irqrestore(host->host_lock, flags);
5636 ufshcd_add_tm_upiu_trace(hba, task_tag, "tm_send");
5638 /* wait until the task management command is completed */
5639 err = wait_event_timeout(hba->tm_wq,
5640 test_bit(free_slot, &hba->tm_condition),
5641 msecs_to_jiffies(TM_CMD_TIMEOUT));
5643 ufshcd_add_tm_upiu_trace(hba, task_tag, "tm_complete_err");
5644 dev_err(hba->dev, "%s: task management cmd 0x%.2x timed-out\n",
5645 __func__, tm_function);
5646 if (ufshcd_clear_tm_cmd(hba, free_slot))
5647 dev_WARN(hba->dev, "%s: unable clear tm cmd (slot %d) after timeout\n",
5648 __func__, free_slot);
5652 memcpy(treq, hba->utmrdl_base_addr + free_slot, sizeof(*treq));
5654 ufshcd_add_tm_upiu_trace(hba, task_tag, "tm_complete");
5656 spin_lock_irqsave(hba->host->host_lock, flags);
5657 __clear_bit(free_slot, &hba->outstanding_tasks);
5658 spin_unlock_irqrestore(hba->host->host_lock, flags);
5662 clear_bit(free_slot, &hba->tm_condition);
5663 ufshcd_put_tm_slot(hba, free_slot);
5664 wake_up(&hba->tm_tag_wq);
5666 ufshcd_release(hba);
5671 * ufshcd_issue_tm_cmd - issues task management commands to controller
5672 * @hba: per adapter instance
5673 * @lun_id: LUN ID to which TM command is sent
5674 * @task_id: task ID to which the TM command is applicable
5675 * @tm_function: task management function opcode
5676 * @tm_response: task management service response return value
5678 * Returns non-zero value on error, zero on success.
5680 static int ufshcd_issue_tm_cmd(struct ufs_hba *hba, int lun_id, int task_id,
5681 u8 tm_function, u8 *tm_response)
5683 struct utp_task_req_desc treq = { { 0 }, };
5686 /* Configure task request descriptor */
5687 treq.header.dword_0 = cpu_to_le32(UTP_REQ_DESC_INT_CMD);
5688 treq.header.dword_2 = cpu_to_le32(OCS_INVALID_COMMAND_STATUS);
5690 /* Configure task request UPIU */
5691 treq.req_header.dword_0 = cpu_to_be32(lun_id << 8) |
5692 cpu_to_be32(UPIU_TRANSACTION_TASK_REQ << 24);
5693 treq.req_header.dword_1 = cpu_to_be32(tm_function << 16);
5696 * The host shall provide the same value for LUN field in the basic
5697 * header and for Input Parameter.
5699 treq.input_param1 = cpu_to_be32(lun_id);
5700 treq.input_param2 = cpu_to_be32(task_id);
5702 err = __ufshcd_issue_tm_cmd(hba, &treq, tm_function);
5703 if (err == -ETIMEDOUT)
5706 ocs_value = le32_to_cpu(treq.header.dword_2) & MASK_OCS;
5707 if (ocs_value != OCS_SUCCESS)
5708 dev_err(hba->dev, "%s: failed, ocs = 0x%x\n",
5709 __func__, ocs_value);
5710 else if (tm_response)
5711 *tm_response = be32_to_cpu(treq.output_param1) &
5712 MASK_TM_SERVICE_RESP;
5717 * ufshcd_issue_devman_upiu_cmd - API for sending "utrd" type requests
5718 * @hba: per-adapter instance
5719 * @req_upiu: upiu request
5720 * @rsp_upiu: upiu reply
5721 * @msgcode: message code, one of UPIU Transaction Codes Initiator to Target
5722 * @desc_buff: pointer to descriptor buffer, NULL if NA
5723 * @buff_len: descriptor size, 0 if NA
5724 * @desc_op: descriptor operation
5726 * Those type of requests uses UTP Transfer Request Descriptor - utrd.
5727 * Therefore, it "rides" the device management infrastructure: uses its tag and
5728 * tasks work queues.
5730 * Since there is only one available tag for device management commands,
5731 * the caller is expected to hold the hba->dev_cmd.lock mutex.
5733 static int ufshcd_issue_devman_upiu_cmd(struct ufs_hba *hba,
5734 struct utp_upiu_req *req_upiu,
5735 struct utp_upiu_req *rsp_upiu,
5736 u8 *desc_buff, int *buff_len,
5738 enum query_opcode desc_op)
5740 struct ufshcd_lrb *lrbp;
5743 struct completion wait;
5744 unsigned long flags;
5747 down_read(&hba->clk_scaling_lock);
5749 wait_event(hba->dev_cmd.tag_wq, ufshcd_get_dev_cmd_tag(hba, &tag));
5751 init_completion(&wait);
5752 lrbp = &hba->lrb[tag];
5756 lrbp->sense_bufflen = 0;
5757 lrbp->sense_buffer = NULL;
5758 lrbp->task_tag = tag;
5760 lrbp->intr_cmd = true;
5761 hba->dev_cmd.type = cmd_type;
5763 switch (hba->ufs_version) {
5764 case UFSHCI_VERSION_10:
5765 case UFSHCI_VERSION_11:
5766 lrbp->command_type = UTP_CMD_TYPE_DEV_MANAGE;
5769 lrbp->command_type = UTP_CMD_TYPE_UFS_STORAGE;
5773 /* update the task tag in the request upiu */
5774 req_upiu->header.dword_0 |= cpu_to_be32(tag);
5776 ufshcd_prepare_req_desc_hdr(lrbp, &upiu_flags, DMA_NONE);
5778 /* just copy the upiu request as it is */
5779 memcpy(lrbp->ucd_req_ptr, req_upiu, sizeof(*lrbp->ucd_req_ptr));
5780 if (desc_buff && desc_op == UPIU_QUERY_OPCODE_WRITE_DESC) {
5781 /* The Data Segment Area is optional depending upon the query
5782 * function value. for WRITE DESCRIPTOR, the data segment
5783 * follows right after the tsf.
5785 memcpy(lrbp->ucd_req_ptr + 1, desc_buff, *buff_len);
5789 memset(lrbp->ucd_rsp_ptr, 0, sizeof(struct utp_upiu_rsp));
5791 hba->dev_cmd.complete = &wait;
5793 /* Make sure descriptors are ready before ringing the doorbell */
5795 spin_lock_irqsave(hba->host->host_lock, flags);
5796 ufshcd_send_command(hba, tag);
5797 spin_unlock_irqrestore(hba->host->host_lock, flags);
5800 * ignore the returning value here - ufshcd_check_query_response is
5801 * bound to fail since dev_cmd.query and dev_cmd.type were left empty.
5802 * read the response directly ignoring all errors.
5804 ufshcd_wait_for_dev_cmd(hba, lrbp, QUERY_REQ_TIMEOUT);
5806 /* just copy the upiu response as it is */
5807 memcpy(rsp_upiu, lrbp->ucd_rsp_ptr, sizeof(*rsp_upiu));
5808 if (desc_buff && desc_op == UPIU_QUERY_OPCODE_READ_DESC) {
5809 u8 *descp = (u8 *)lrbp->ucd_rsp_ptr + sizeof(*rsp_upiu);
5810 u16 resp_len = be32_to_cpu(lrbp->ucd_rsp_ptr->header.dword_2) &
5811 MASK_QUERY_DATA_SEG_LEN;
5813 if (*buff_len >= resp_len) {
5814 memcpy(desc_buff, descp, resp_len);
5815 *buff_len = resp_len;
5817 dev_warn(hba->dev, "rsp size is bigger than buffer");
5823 ufshcd_put_dev_cmd_tag(hba, tag);
5824 wake_up(&hba->dev_cmd.tag_wq);
5825 up_read(&hba->clk_scaling_lock);
5830 * ufshcd_exec_raw_upiu_cmd - API function for sending raw upiu commands
5831 * @hba: per-adapter instance
5832 * @req_upiu: upiu request
5833 * @rsp_upiu: upiu reply - only 8 DW as we do not support scsi commands
5834 * @msgcode: message code, one of UPIU Transaction Codes Initiator to Target
5835 * @desc_buff: pointer to descriptor buffer, NULL if NA
5836 * @buff_len: descriptor size, 0 if NA
5837 * @desc_op: descriptor operation
5839 * Supports UTP Transfer requests (nop and query), and UTP Task
5840 * Management requests.
5841 * It is up to the caller to fill the upiu conent properly, as it will
5842 * be copied without any further input validations.
5844 int ufshcd_exec_raw_upiu_cmd(struct ufs_hba *hba,
5845 struct utp_upiu_req *req_upiu,
5846 struct utp_upiu_req *rsp_upiu,
5848 u8 *desc_buff, int *buff_len,
5849 enum query_opcode desc_op)
5852 int cmd_type = DEV_CMD_TYPE_QUERY;
5853 struct utp_task_req_desc treq = { { 0 }, };
5855 u8 tm_f = be32_to_cpu(req_upiu->header.dword_1) >> 16 & MASK_TM_FUNC;
5858 case UPIU_TRANSACTION_NOP_OUT:
5859 cmd_type = DEV_CMD_TYPE_NOP;
5861 case UPIU_TRANSACTION_QUERY_REQ:
5862 ufshcd_hold(hba, false);
5863 mutex_lock(&hba->dev_cmd.lock);
5864 err = ufshcd_issue_devman_upiu_cmd(hba, req_upiu, rsp_upiu,
5865 desc_buff, buff_len,
5867 mutex_unlock(&hba->dev_cmd.lock);
5868 ufshcd_release(hba);
5871 case UPIU_TRANSACTION_TASK_REQ:
5872 treq.header.dword_0 = cpu_to_le32(UTP_REQ_DESC_INT_CMD);
5873 treq.header.dword_2 = cpu_to_le32(OCS_INVALID_COMMAND_STATUS);
5875 memcpy(&treq.req_header, req_upiu, sizeof(*req_upiu));
5877 err = __ufshcd_issue_tm_cmd(hba, &treq, tm_f);
5878 if (err == -ETIMEDOUT)
5881 ocs_value = le32_to_cpu(treq.header.dword_2) & MASK_OCS;
5882 if (ocs_value != OCS_SUCCESS) {
5883 dev_err(hba->dev, "%s: failed, ocs = 0x%x\n", __func__,
5888 memcpy(rsp_upiu, &treq.rsp_header, sizeof(*rsp_upiu));
5901 * ufshcd_eh_device_reset_handler - device reset handler registered to
5903 * @cmd: SCSI command pointer
5905 * Returns SUCCESS/FAILED
5907 static int ufshcd_eh_device_reset_handler(struct scsi_cmnd *cmd)
5909 struct Scsi_Host *host;
5910 struct ufs_hba *hba;
5915 struct ufshcd_lrb *lrbp;
5916 unsigned long flags;
5918 host = cmd->device->host;
5919 hba = shost_priv(host);
5920 tag = cmd->request->tag;
5922 lrbp = &hba->lrb[tag];
5923 err = ufshcd_issue_tm_cmd(hba, lrbp->lun, 0, UFS_LOGICAL_RESET, &resp);
5924 if (err || resp != UPIU_TASK_MANAGEMENT_FUNC_COMPL) {
5930 /* clear the commands that were pending for corresponding LUN */
5931 for_each_set_bit(pos, &hba->outstanding_reqs, hba->nutrs) {
5932 if (hba->lrb[pos].lun == lrbp->lun) {
5933 err = ufshcd_clear_cmd(hba, pos);
5938 spin_lock_irqsave(host->host_lock, flags);
5939 ufshcd_transfer_req_compl(hba);
5940 spin_unlock_irqrestore(host->host_lock, flags);
5943 hba->req_abort_count = 0;
5947 dev_err(hba->dev, "%s: failed with err %d\n", __func__, err);
5953 static void ufshcd_set_req_abort_skip(struct ufs_hba *hba, unsigned long bitmap)
5955 struct ufshcd_lrb *lrbp;
5958 for_each_set_bit(tag, &bitmap, hba->nutrs) {
5959 lrbp = &hba->lrb[tag];
5960 lrbp->req_abort_skip = true;
5965 * ufshcd_abort - abort a specific command
5966 * @cmd: SCSI command pointer
5968 * Abort the pending command in device by sending UFS_ABORT_TASK task management
5969 * command, and in host controller by clearing the door-bell register. There can
5970 * be race between controller sending the command to the device while abort is
5971 * issued. To avoid that, first issue UFS_QUERY_TASK to check if the command is
5972 * really issued and then try to abort it.
5974 * Returns SUCCESS/FAILED
5976 static int ufshcd_abort(struct scsi_cmnd *cmd)
5978 struct Scsi_Host *host;
5979 struct ufs_hba *hba;
5980 unsigned long flags;
5985 struct ufshcd_lrb *lrbp;
5988 host = cmd->device->host;
5989 hba = shost_priv(host);
5990 tag = cmd->request->tag;
5991 lrbp = &hba->lrb[tag];
5992 if (!ufshcd_valid_tag(hba, tag)) {
5994 "%s: invalid command tag %d: cmd=0x%p, cmd->request=0x%p",
5995 __func__, tag, cmd, cmd->request);
6000 * Task abort to the device W-LUN is illegal. When this command
6001 * will fail, due to spec violation, scsi err handling next step
6002 * will be to send LU reset which, again, is a spec violation.
6003 * To avoid these unnecessary/illegal step we skip to the last error
6004 * handling stage: reset and restore.
6006 if (lrbp->lun == UFS_UPIU_UFS_DEVICE_WLUN)
6007 return ufshcd_eh_host_reset_handler(cmd);
6009 ufshcd_hold(hba, false);
6010 reg = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
6011 /* If command is already aborted/completed, return SUCCESS */
6012 if (!(test_bit(tag, &hba->outstanding_reqs))) {
6014 "%s: cmd at tag %d already completed, outstanding=0x%lx, doorbell=0x%x\n",
6015 __func__, tag, hba->outstanding_reqs, reg);
6019 if (!(reg & (1 << tag))) {
6021 "%s: cmd was completed, but without a notifying intr, tag = %d",
6025 /* Print Transfer Request of aborted task */
6026 dev_err(hba->dev, "%s: Device abort task at tag %d\n", __func__, tag);
6029 * Print detailed info about aborted request.
6030 * As more than one request might get aborted at the same time,
6031 * print full information only for the first aborted request in order
6032 * to reduce repeated printouts. For other aborted requests only print
6035 scsi_print_command(hba->lrb[tag].cmd);
6036 if (!hba->req_abort_count) {
6037 ufshcd_print_host_regs(hba);
6038 ufshcd_print_host_state(hba);
6039 ufshcd_print_pwr_info(hba);
6040 ufshcd_print_trs(hba, 1 << tag, true);
6042 ufshcd_print_trs(hba, 1 << tag, false);
6044 hba->req_abort_count++;
6046 /* Skip task abort in case previous aborts failed and report failure */
6047 if (lrbp->req_abort_skip) {
6052 for (poll_cnt = 100; poll_cnt; poll_cnt--) {
6053 err = ufshcd_issue_tm_cmd(hba, lrbp->lun, lrbp->task_tag,
6054 UFS_QUERY_TASK, &resp);
6055 if (!err && resp == UPIU_TASK_MANAGEMENT_FUNC_SUCCEEDED) {
6056 /* cmd pending in the device */
6057 dev_err(hba->dev, "%s: cmd pending in the device. tag = %d\n",
6060 } else if (!err && resp == UPIU_TASK_MANAGEMENT_FUNC_COMPL) {
6062 * cmd not pending in the device, check if it is
6065 dev_err(hba->dev, "%s: cmd at tag %d not pending in the device.\n",
6067 reg = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
6068 if (reg & (1 << tag)) {
6069 /* sleep for max. 200us to stabilize */
6070 usleep_range(100, 200);
6073 /* command completed already */
6074 dev_err(hba->dev, "%s: cmd at tag %d successfully cleared from DB.\n",
6079 "%s: no response from device. tag = %d, err %d\n",
6080 __func__, tag, err);
6082 err = resp; /* service response error */
6092 err = ufshcd_issue_tm_cmd(hba, lrbp->lun, lrbp->task_tag,
6093 UFS_ABORT_TASK, &resp);
6094 if (err || resp != UPIU_TASK_MANAGEMENT_FUNC_COMPL) {
6096 err = resp; /* service response error */
6097 dev_err(hba->dev, "%s: issued. tag = %d, err %d\n",
6098 __func__, tag, err);
6103 err = ufshcd_clear_cmd(hba, tag);
6105 dev_err(hba->dev, "%s: Failed clearing cmd at tag %d, err %d\n",
6106 __func__, tag, err);
6110 scsi_dma_unmap(cmd);
6112 spin_lock_irqsave(host->host_lock, flags);
6113 ufshcd_outstanding_req_clear(hba, tag);
6114 hba->lrb[tag].cmd = NULL;
6115 spin_unlock_irqrestore(host->host_lock, flags);
6117 clear_bit_unlock(tag, &hba->lrb_in_use);
6118 wake_up(&hba->dev_cmd.tag_wq);
6124 dev_err(hba->dev, "%s: failed with err %d\n", __func__, err);
6125 ufshcd_set_req_abort_skip(hba, hba->outstanding_reqs);
6130 * This ufshcd_release() corresponds to the original scsi cmd that got
6131 * aborted here (as we won't get any IRQ for it).
6133 ufshcd_release(hba);
6138 * ufshcd_host_reset_and_restore - reset and restore host controller
6139 * @hba: per-adapter instance
6141 * Note that host controller reset may issue DME_RESET to
6142 * local and remote (device) Uni-Pro stack and the attributes
6143 * are reset to default state.
6145 * Returns zero on success, non-zero on failure
6147 static int ufshcd_host_reset_and_restore(struct ufs_hba *hba)
6150 unsigned long flags;
6152 /* Reset the host controller */
6153 spin_lock_irqsave(hba->host->host_lock, flags);
6154 ufshcd_hba_stop(hba, false);
6155 spin_unlock_irqrestore(hba->host->host_lock, flags);
6157 /* scale up clocks to max frequency before full reinitialization */
6158 ufshcd_scale_clks(hba, true);
6160 err = ufshcd_hba_enable(hba);
6164 /* Establish the link again and restore the device */
6165 err = ufshcd_probe_hba(hba);
6167 if (!err && (hba->ufshcd_state != UFSHCD_STATE_OPERATIONAL))
6171 dev_err(hba->dev, "%s: Host init failed %d\n", __func__, err);
6177 * ufshcd_reset_and_restore - reset and re-initialize host/device
6178 * @hba: per-adapter instance
6180 * Reset and recover device, host and re-establish link. This
6181 * is helpful to recover the communication in fatal error conditions.
6183 * Returns zero on success, non-zero on failure
6185 static int ufshcd_reset_and_restore(struct ufs_hba *hba)
6188 unsigned long flags;
6189 int retries = MAX_HOST_RESET_RETRIES;
6192 err = ufshcd_host_reset_and_restore(hba);
6193 } while (err && --retries);
6196 * After reset the door-bell might be cleared, complete
6197 * outstanding requests in s/w here.
6199 spin_lock_irqsave(hba->host->host_lock, flags);
6200 ufshcd_transfer_req_compl(hba);
6201 ufshcd_tmc_handler(hba);
6202 spin_unlock_irqrestore(hba->host->host_lock, flags);
6208 * ufshcd_eh_host_reset_handler - host reset handler registered to scsi layer
6209 * @cmd: SCSI command pointer
6211 * Returns SUCCESS/FAILED
6213 static int ufshcd_eh_host_reset_handler(struct scsi_cmnd *cmd)
6216 unsigned long flags;
6217 struct ufs_hba *hba;
6219 hba = shost_priv(cmd->device->host);
6221 ufshcd_hold(hba, false);
6223 * Check if there is any race with fatal error handling.
6224 * If so, wait for it to complete. Even though fatal error
6225 * handling does reset and restore in some cases, don't assume
6226 * anything out of it. We are just avoiding race here.
6229 spin_lock_irqsave(hba->host->host_lock, flags);
6230 if (!(work_pending(&hba->eh_work) ||
6231 hba->ufshcd_state == UFSHCD_STATE_RESET ||
6232 hba->ufshcd_state == UFSHCD_STATE_EH_SCHEDULED))
6234 spin_unlock_irqrestore(hba->host->host_lock, flags);
6235 dev_dbg(hba->dev, "%s: reset in progress\n", __func__);
6236 flush_work(&hba->eh_work);
6239 hba->ufshcd_state = UFSHCD_STATE_RESET;
6240 ufshcd_set_eh_in_progress(hba);
6241 spin_unlock_irqrestore(hba->host->host_lock, flags);
6243 err = ufshcd_reset_and_restore(hba);
6245 spin_lock_irqsave(hba->host->host_lock, flags);
6248 hba->ufshcd_state = UFSHCD_STATE_OPERATIONAL;
6251 hba->ufshcd_state = UFSHCD_STATE_ERROR;
6253 ufshcd_clear_eh_in_progress(hba);
6254 spin_unlock_irqrestore(hba->host->host_lock, flags);
6256 ufshcd_release(hba);
6261 * ufshcd_get_max_icc_level - calculate the ICC level
6262 * @sup_curr_uA: max. current supported by the regulator
6263 * @start_scan: row at the desc table to start scan from
6264 * @buff: power descriptor buffer
6266 * Returns calculated max ICC level for specific regulator
6268 static u32 ufshcd_get_max_icc_level(int sup_curr_uA, u32 start_scan, char *buff)
6275 for (i = start_scan; i >= 0; i--) {
6276 data = be16_to_cpup((__be16 *)&buff[2 * i]);
6277 unit = (data & ATTR_ICC_LVL_UNIT_MASK) >>
6278 ATTR_ICC_LVL_UNIT_OFFSET;
6279 curr_uA = data & ATTR_ICC_LVL_VALUE_MASK;
6281 case UFSHCD_NANO_AMP:
6282 curr_uA = curr_uA / 1000;
6284 case UFSHCD_MILI_AMP:
6285 curr_uA = curr_uA * 1000;
6288 curr_uA = curr_uA * 1000 * 1000;
6290 case UFSHCD_MICRO_AMP:
6294 if (sup_curr_uA >= curr_uA)
6299 pr_err("%s: Couldn't find valid icc_level = %d", __func__, i);
6306 * ufshcd_calc_icc_level - calculate the max ICC level
6307 * In case regulators are not initialized we'll return 0
6308 * @hba: per-adapter instance
6309 * @desc_buf: power descriptor buffer to extract ICC levels from.
6310 * @len: length of desc_buff
6312 * Returns calculated ICC level
6314 static u32 ufshcd_find_max_sup_active_icc_level(struct ufs_hba *hba,
6315 u8 *desc_buf, int len)
6319 if (!hba->vreg_info.vcc || !hba->vreg_info.vccq ||
6320 !hba->vreg_info.vccq2) {
6322 "%s: Regulator capability was not set, actvIccLevel=%d",
6323 __func__, icc_level);
6327 if (hba->vreg_info.vcc && hba->vreg_info.vcc->max_uA)
6328 icc_level = ufshcd_get_max_icc_level(
6329 hba->vreg_info.vcc->max_uA,
6330 POWER_DESC_MAX_ACTV_ICC_LVLS - 1,
6331 &desc_buf[PWR_DESC_ACTIVE_LVLS_VCC_0]);
6333 if (hba->vreg_info.vccq && hba->vreg_info.vccq->max_uA)
6334 icc_level = ufshcd_get_max_icc_level(
6335 hba->vreg_info.vccq->max_uA,
6337 &desc_buf[PWR_DESC_ACTIVE_LVLS_VCCQ_0]);
6339 if (hba->vreg_info.vccq2 && hba->vreg_info.vccq2->max_uA)
6340 icc_level = ufshcd_get_max_icc_level(
6341 hba->vreg_info.vccq2->max_uA,
6343 &desc_buf[PWR_DESC_ACTIVE_LVLS_VCCQ2_0]);
6348 static void ufshcd_init_icc_levels(struct ufs_hba *hba)
6351 int buff_len = hba->desc_size.pwr_desc;
6354 desc_buf = kmalloc(buff_len, GFP_KERNEL);
6358 ret = ufshcd_read_power_desc(hba, desc_buf, buff_len);
6361 "%s: Failed reading power descriptor.len = %d ret = %d",
6362 __func__, buff_len, ret);
6366 hba->init_prefetch_data.icc_level =
6367 ufshcd_find_max_sup_active_icc_level(hba,
6368 desc_buf, buff_len);
6369 dev_dbg(hba->dev, "%s: setting icc_level 0x%x",
6370 __func__, hba->init_prefetch_data.icc_level);
6372 ret = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_WRITE_ATTR,
6373 QUERY_ATTR_IDN_ACTIVE_ICC_LVL, 0, 0,
6374 &hba->init_prefetch_data.icc_level);
6378 "%s: Failed configuring bActiveICCLevel = %d ret = %d",
6379 __func__, hba->init_prefetch_data.icc_level , ret);
6386 * ufshcd_scsi_add_wlus - Adds required W-LUs
6387 * @hba: per-adapter instance
6389 * UFS device specification requires the UFS devices to support 4 well known
6391 * "REPORT_LUNS" (address: 01h)
6392 * "UFS Device" (address: 50h)
6393 * "RPMB" (address: 44h)
6394 * "BOOT" (address: 30h)
6395 * UFS device's power management needs to be controlled by "POWER CONDITION"
6396 * field of SSU (START STOP UNIT) command. But this "power condition" field
6397 * will take effect only when its sent to "UFS device" well known logical unit
6398 * hence we require the scsi_device instance to represent this logical unit in
6399 * order for the UFS host driver to send the SSU command for power management.
6401 * We also require the scsi_device instance for "RPMB" (Replay Protected Memory
6402 * Block) LU so user space process can control this LU. User space may also
6403 * want to have access to BOOT LU.
6405 * This function adds scsi device instances for each of all well known LUs
6406 * (except "REPORT LUNS" LU).
6408 * Returns zero on success (all required W-LUs are added successfully),
6409 * non-zero error value on failure (if failed to add any of the required W-LU).
6411 static int ufshcd_scsi_add_wlus(struct ufs_hba *hba)
6414 struct scsi_device *sdev_rpmb;
6415 struct scsi_device *sdev_boot;
6417 hba->sdev_ufs_device = __scsi_add_device(hba->host, 0, 0,
6418 ufshcd_upiu_wlun_to_scsi_wlun(UFS_UPIU_UFS_DEVICE_WLUN), NULL);
6419 if (IS_ERR(hba->sdev_ufs_device)) {
6420 ret = PTR_ERR(hba->sdev_ufs_device);
6421 hba->sdev_ufs_device = NULL;
6424 scsi_device_put(hba->sdev_ufs_device);
6426 sdev_rpmb = __scsi_add_device(hba->host, 0, 0,
6427 ufshcd_upiu_wlun_to_scsi_wlun(UFS_UPIU_RPMB_WLUN), NULL);
6428 if (IS_ERR(sdev_rpmb)) {
6429 ret = PTR_ERR(sdev_rpmb);
6430 goto remove_sdev_ufs_device;
6432 scsi_device_put(sdev_rpmb);
6434 sdev_boot = __scsi_add_device(hba->host, 0, 0,
6435 ufshcd_upiu_wlun_to_scsi_wlun(UFS_UPIU_BOOT_WLUN), NULL);
6436 if (IS_ERR(sdev_boot))
6437 dev_err(hba->dev, "%s: BOOT WLUN not found\n", __func__);
6439 scsi_device_put(sdev_boot);
6442 remove_sdev_ufs_device:
6443 scsi_remove_device(hba->sdev_ufs_device);
6448 static int ufs_get_device_desc(struct ufs_hba *hba,
6449 struct ufs_dev_desc *dev_desc)
6456 buff_len = max_t(size_t, hba->desc_size.dev_desc,
6457 QUERY_DESC_MAX_SIZE + 1);
6458 desc_buf = kmalloc(buff_len, GFP_KERNEL);
6464 err = ufshcd_read_device_desc(hba, desc_buf, hba->desc_size.dev_desc);
6466 dev_err(hba->dev, "%s: Failed reading Device Desc. err = %d\n",
6472 * getting vendor (manufacturerID) and Bank Index in big endian
6475 dev_desc->wmanufacturerid = desc_buf[DEVICE_DESC_PARAM_MANF_ID] << 8 |
6476 desc_buf[DEVICE_DESC_PARAM_MANF_ID + 1];
6478 model_index = desc_buf[DEVICE_DESC_PARAM_PRDCT_NAME];
6480 /* Zero-pad entire buffer for string termination. */
6481 memset(desc_buf, 0, buff_len);
6483 err = ufshcd_read_string_desc(hba, model_index, desc_buf,
6484 QUERY_DESC_MAX_SIZE, true/*ASCII*/);
6486 dev_err(hba->dev, "%s: Failed reading Product Name. err = %d\n",
6491 desc_buf[QUERY_DESC_MAX_SIZE] = '\0';
6492 strlcpy(dev_desc->model, (desc_buf + QUERY_DESC_HDR_SIZE),
6493 min_t(u8, desc_buf[QUERY_DESC_LENGTH_OFFSET],
6496 /* Null terminate the model string */
6497 dev_desc->model[MAX_MODEL_LEN] = '\0';
6504 static void ufs_fixup_device_setup(struct ufs_hba *hba,
6505 struct ufs_dev_desc *dev_desc)
6507 struct ufs_dev_fix *f;
6509 for (f = ufs_fixups; f->quirk; f++) {
6510 if ((f->card.wmanufacturerid == dev_desc->wmanufacturerid ||
6511 f->card.wmanufacturerid == UFS_ANY_VENDOR) &&
6512 (STR_PRFX_EQUAL(f->card.model, dev_desc->model) ||
6513 !strcmp(f->card.model, UFS_ANY_MODEL)))
6514 hba->dev_quirks |= f->quirk;
6519 * ufshcd_tune_pa_tactivate - Tunes PA_TActivate of local UniPro
6520 * @hba: per-adapter instance
6522 * PA_TActivate parameter can be tuned manually if UniPro version is less than
6523 * 1.61. PA_TActivate needs to be greater than or equal to peerM-PHY's
6524 * RX_MIN_ACTIVATETIME_CAPABILITY attribute. This optimal value can help reduce
6525 * the hibern8 exit latency.
6527 * Returns zero on success, non-zero error value on failure.
6529 static int ufshcd_tune_pa_tactivate(struct ufs_hba *hba)
6532 u32 peer_rx_min_activatetime = 0, tuned_pa_tactivate;
6534 ret = ufshcd_dme_peer_get(hba,
6536 RX_MIN_ACTIVATETIME_CAPABILITY,
6537 UIC_ARG_MPHY_RX_GEN_SEL_INDEX(0)),
6538 &peer_rx_min_activatetime);
6542 /* make sure proper unit conversion is applied */
6543 tuned_pa_tactivate =
6544 ((peer_rx_min_activatetime * RX_MIN_ACTIVATETIME_UNIT_US)
6545 / PA_TACTIVATE_TIME_UNIT_US);
6546 ret = ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TACTIVATE),
6547 tuned_pa_tactivate);
6554 * ufshcd_tune_pa_hibern8time - Tunes PA_Hibern8Time of local UniPro
6555 * @hba: per-adapter instance
6557 * PA_Hibern8Time parameter can be tuned manually if UniPro version is less than
6558 * 1.61. PA_Hibern8Time needs to be maximum of local M-PHY's
6559 * TX_HIBERN8TIME_CAPABILITY & peer M-PHY's RX_HIBERN8TIME_CAPABILITY.
6560 * This optimal value can help reduce the hibern8 exit latency.
6562 * Returns zero on success, non-zero error value on failure.
6564 static int ufshcd_tune_pa_hibern8time(struct ufs_hba *hba)
6567 u32 local_tx_hibern8_time_cap = 0, peer_rx_hibern8_time_cap = 0;
6568 u32 max_hibern8_time, tuned_pa_hibern8time;
6570 ret = ufshcd_dme_get(hba,
6571 UIC_ARG_MIB_SEL(TX_HIBERN8TIME_CAPABILITY,
6572 UIC_ARG_MPHY_TX_GEN_SEL_INDEX(0)),
6573 &local_tx_hibern8_time_cap);
6577 ret = ufshcd_dme_peer_get(hba,
6578 UIC_ARG_MIB_SEL(RX_HIBERN8TIME_CAPABILITY,
6579 UIC_ARG_MPHY_RX_GEN_SEL_INDEX(0)),
6580 &peer_rx_hibern8_time_cap);
6584 max_hibern8_time = max(local_tx_hibern8_time_cap,
6585 peer_rx_hibern8_time_cap);
6586 /* make sure proper unit conversion is applied */
6587 tuned_pa_hibern8time = ((max_hibern8_time * HIBERN8TIME_UNIT_US)
6588 / PA_HIBERN8_TIME_UNIT_US);
6589 ret = ufshcd_dme_set(hba, UIC_ARG_MIB(PA_HIBERN8TIME),
6590 tuned_pa_hibern8time);
6596 * ufshcd_quirk_tune_host_pa_tactivate - Ensures that host PA_TACTIVATE is
6597 * less than device PA_TACTIVATE time.
6598 * @hba: per-adapter instance
6600 * Some UFS devices require host PA_TACTIVATE to be lower than device
6601 * PA_TACTIVATE, we need to enable UFS_DEVICE_QUIRK_HOST_PA_TACTIVATE quirk
6604 * Returns zero on success, non-zero error value on failure.
6606 static int ufshcd_quirk_tune_host_pa_tactivate(struct ufs_hba *hba)
6609 u32 granularity, peer_granularity;
6610 u32 pa_tactivate, peer_pa_tactivate;
6611 u32 pa_tactivate_us, peer_pa_tactivate_us;
6612 u8 gran_to_us_table[] = {1, 4, 8, 16, 32, 100};
6614 ret = ufshcd_dme_get(hba, UIC_ARG_MIB(PA_GRANULARITY),
6619 ret = ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_GRANULARITY),
6624 if ((granularity < PA_GRANULARITY_MIN_VAL) ||
6625 (granularity > PA_GRANULARITY_MAX_VAL)) {
6626 dev_err(hba->dev, "%s: invalid host PA_GRANULARITY %d",
6627 __func__, granularity);
6631 if ((peer_granularity < PA_GRANULARITY_MIN_VAL) ||
6632 (peer_granularity > PA_GRANULARITY_MAX_VAL)) {
6633 dev_err(hba->dev, "%s: invalid device PA_GRANULARITY %d",
6634 __func__, peer_granularity);
6638 ret = ufshcd_dme_get(hba, UIC_ARG_MIB(PA_TACTIVATE), &pa_tactivate);
6642 ret = ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_TACTIVATE),
6643 &peer_pa_tactivate);
6647 pa_tactivate_us = pa_tactivate * gran_to_us_table[granularity - 1];
6648 peer_pa_tactivate_us = peer_pa_tactivate *
6649 gran_to_us_table[peer_granularity - 1];
6651 if (pa_tactivate_us > peer_pa_tactivate_us) {
6652 u32 new_peer_pa_tactivate;
6654 new_peer_pa_tactivate = pa_tactivate_us /
6655 gran_to_us_table[peer_granularity - 1];
6656 new_peer_pa_tactivate++;
6657 ret = ufshcd_dme_peer_set(hba, UIC_ARG_MIB(PA_TACTIVATE),
6658 new_peer_pa_tactivate);
6665 static void ufshcd_tune_unipro_params(struct ufs_hba *hba)
6667 if (ufshcd_is_unipro_pa_params_tuning_req(hba)) {
6668 ufshcd_tune_pa_tactivate(hba);
6669 ufshcd_tune_pa_hibern8time(hba);
6672 if (hba->dev_quirks & UFS_DEVICE_QUIRK_PA_TACTIVATE)
6673 /* set 1ms timeout for PA_TACTIVATE */
6674 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TACTIVATE), 10);
6676 if (hba->dev_quirks & UFS_DEVICE_QUIRK_HOST_PA_TACTIVATE)
6677 ufshcd_quirk_tune_host_pa_tactivate(hba);
6679 ufshcd_vops_apply_dev_quirks(hba);
6682 static void ufshcd_clear_dbg_ufs_stats(struct ufs_hba *hba)
6684 int err_reg_hist_size = sizeof(struct ufs_uic_err_reg_hist);
6686 hba->ufs_stats.hibern8_exit_cnt = 0;
6687 hba->ufs_stats.last_hibern8_exit_tstamp = ktime_set(0, 0);
6689 memset(&hba->ufs_stats.pa_err, 0, err_reg_hist_size);
6690 memset(&hba->ufs_stats.dl_err, 0, err_reg_hist_size);
6691 memset(&hba->ufs_stats.nl_err, 0, err_reg_hist_size);
6692 memset(&hba->ufs_stats.tl_err, 0, err_reg_hist_size);
6693 memset(&hba->ufs_stats.dme_err, 0, err_reg_hist_size);
6695 hba->req_abort_count = 0;
6698 static void ufshcd_init_desc_sizes(struct ufs_hba *hba)
6702 err = ufshcd_read_desc_length(hba, QUERY_DESC_IDN_DEVICE, 0,
6703 &hba->desc_size.dev_desc);
6705 hba->desc_size.dev_desc = QUERY_DESC_DEVICE_DEF_SIZE;
6707 err = ufshcd_read_desc_length(hba, QUERY_DESC_IDN_POWER, 0,
6708 &hba->desc_size.pwr_desc);
6710 hba->desc_size.pwr_desc = QUERY_DESC_POWER_DEF_SIZE;
6712 err = ufshcd_read_desc_length(hba, QUERY_DESC_IDN_INTERCONNECT, 0,
6713 &hba->desc_size.interc_desc);
6715 hba->desc_size.interc_desc = QUERY_DESC_INTERCONNECT_DEF_SIZE;
6717 err = ufshcd_read_desc_length(hba, QUERY_DESC_IDN_CONFIGURATION, 0,
6718 &hba->desc_size.conf_desc);
6720 hba->desc_size.conf_desc = QUERY_DESC_CONFIGURATION_DEF_SIZE;
6722 err = ufshcd_read_desc_length(hba, QUERY_DESC_IDN_UNIT, 0,
6723 &hba->desc_size.unit_desc);
6725 hba->desc_size.unit_desc = QUERY_DESC_UNIT_DEF_SIZE;
6727 err = ufshcd_read_desc_length(hba, QUERY_DESC_IDN_GEOMETRY, 0,
6728 &hba->desc_size.geom_desc);
6730 hba->desc_size.geom_desc = QUERY_DESC_GEOMETRY_DEF_SIZE;
6731 err = ufshcd_read_desc_length(hba, QUERY_DESC_IDN_HEALTH, 0,
6732 &hba->desc_size.hlth_desc);
6734 hba->desc_size.hlth_desc = QUERY_DESC_HEALTH_DEF_SIZE;
6737 static void ufshcd_def_desc_sizes(struct ufs_hba *hba)
6739 hba->desc_size.dev_desc = QUERY_DESC_DEVICE_DEF_SIZE;
6740 hba->desc_size.pwr_desc = QUERY_DESC_POWER_DEF_SIZE;
6741 hba->desc_size.interc_desc = QUERY_DESC_INTERCONNECT_DEF_SIZE;
6742 hba->desc_size.conf_desc = QUERY_DESC_CONFIGURATION_DEF_SIZE;
6743 hba->desc_size.unit_desc = QUERY_DESC_UNIT_DEF_SIZE;
6744 hba->desc_size.geom_desc = QUERY_DESC_GEOMETRY_DEF_SIZE;
6745 hba->desc_size.hlth_desc = QUERY_DESC_HEALTH_DEF_SIZE;
6748 static struct ufs_ref_clk ufs_ref_clk_freqs[] = {
6749 {19200000, REF_CLK_FREQ_19_2_MHZ},
6750 {26000000, REF_CLK_FREQ_26_MHZ},
6751 {38400000, REF_CLK_FREQ_38_4_MHZ},
6752 {52000000, REF_CLK_FREQ_52_MHZ},
6753 {0, REF_CLK_FREQ_INVAL},
6756 static enum ufs_ref_clk_freq
6757 ufs_get_bref_clk_from_hz(unsigned long freq)
6761 for (i = 0; ufs_ref_clk_freqs[i].freq_hz; i++)
6762 if (ufs_ref_clk_freqs[i].freq_hz == freq)
6763 return ufs_ref_clk_freqs[i].val;
6765 return REF_CLK_FREQ_INVAL;
6768 void ufshcd_parse_dev_ref_clk_freq(struct ufs_hba *hba, struct clk *refclk)
6772 freq = clk_get_rate(refclk);
6774 hba->dev_ref_clk_freq =
6775 ufs_get_bref_clk_from_hz(freq);
6777 if (hba->dev_ref_clk_freq == REF_CLK_FREQ_INVAL)
6779 "invalid ref_clk setting = %ld\n", freq);
6782 static int ufshcd_set_dev_ref_clk(struct ufs_hba *hba)
6786 u32 freq = hba->dev_ref_clk_freq;
6788 err = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
6789 QUERY_ATTR_IDN_REF_CLK_FREQ, 0, 0, &ref_clk);
6792 dev_err(hba->dev, "failed reading bRefClkFreq. err = %d\n",
6797 if (ref_clk == freq)
6798 goto out; /* nothing to update */
6800 err = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_WRITE_ATTR,
6801 QUERY_ATTR_IDN_REF_CLK_FREQ, 0, 0, &freq);
6804 dev_err(hba->dev, "bRefClkFreq setting to %lu Hz failed\n",
6805 ufs_ref_clk_freqs[freq].freq_hz);
6809 dev_dbg(hba->dev, "bRefClkFreq setting to %lu Hz succeeded\n",
6810 ufs_ref_clk_freqs[freq].freq_hz);
6817 * ufshcd_probe_hba - probe hba to detect device and initialize
6818 * @hba: per-adapter instance
6820 * Execute link-startup and verify device initialization
6822 static int ufshcd_probe_hba(struct ufs_hba *hba)
6824 struct ufs_dev_desc card = {0};
6826 ktime_t start = ktime_get();
6828 ret = ufshcd_link_startup(hba);
6832 /* set the default level for urgent bkops */
6833 hba->urgent_bkops_lvl = BKOPS_STATUS_PERF_IMPACT;
6834 hba->is_urgent_bkops_lvl_checked = false;
6836 /* Debug counters initialization */
6837 ufshcd_clear_dbg_ufs_stats(hba);
6839 /* UniPro link is active now */
6840 ufshcd_set_link_active(hba);
6842 /* Enable Auto-Hibernate if configured */
6843 ufshcd_auto_hibern8_enable(hba);
6845 ret = ufshcd_verify_dev_init(hba);
6849 ret = ufshcd_complete_dev_init(hba);
6853 /* Init check for device descriptor sizes */
6854 ufshcd_init_desc_sizes(hba);
6856 ret = ufs_get_device_desc(hba, &card);
6858 dev_err(hba->dev, "%s: Failed getting device info. err = %d\n",
6863 ufs_fixup_device_setup(hba, &card);
6864 ufshcd_tune_unipro_params(hba);
6866 /* UFS device is also active now */
6867 ufshcd_set_ufs_dev_active(hba);
6868 ufshcd_force_reset_auto_bkops(hba);
6869 hba->wlun_dev_clr_ua = true;
6871 if (ufshcd_get_max_pwr_mode(hba)) {
6873 "%s: Failed getting max supported power mode\n",
6877 * Set the right value to bRefClkFreq before attempting to
6878 * switch to HS gears.
6880 if (hba->dev_ref_clk_freq != REF_CLK_FREQ_INVAL)
6881 ufshcd_set_dev_ref_clk(hba);
6882 ret = ufshcd_config_pwr_mode(hba, &hba->max_pwr_info.info);
6884 dev_err(hba->dev, "%s: Failed setting power mode, err = %d\n",
6890 /* set the state as operational after switching to desired gear */
6891 hba->ufshcd_state = UFSHCD_STATE_OPERATIONAL;
6894 * If we are in error handling context or in power management callbacks
6895 * context, no need to scan the host
6897 if (!ufshcd_eh_in_progress(hba) && !hba->pm_op_in_progress) {
6900 /* clear any previous UFS device information */
6901 memset(&hba->dev_info, 0, sizeof(hba->dev_info));
6902 if (!ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_READ_FLAG,
6903 QUERY_FLAG_IDN_PWR_ON_WPE, &flag))
6904 hba->dev_info.f_power_on_wp_en = flag;
6906 if (!hba->is_init_prefetch)
6907 ufshcd_init_icc_levels(hba);
6909 /* Add required well known logical units to scsi mid layer */
6910 if (ufshcd_scsi_add_wlus(hba))
6913 /* Initialize devfreq after UFS device is detected */
6914 if (ufshcd_is_clkscaling_supported(hba)) {
6915 memcpy(&hba->clk_scaling.saved_pwr_info.info,
6917 sizeof(struct ufs_pa_layer_attr));
6918 hba->clk_scaling.saved_pwr_info.is_valid = true;
6919 if (!hba->devfreq) {
6920 ret = ufshcd_devfreq_init(hba);
6924 hba->clk_scaling.is_allowed = true;
6929 scsi_scan_host(hba->host);
6930 pm_runtime_put_sync(hba->dev);
6933 if (!hba->is_init_prefetch)
6934 hba->is_init_prefetch = true;
6938 * If we failed to initialize the device or the device is not
6939 * present, turn off the power/clocks etc.
6941 if (ret && !ufshcd_eh_in_progress(hba) && !hba->pm_op_in_progress) {
6942 pm_runtime_put_sync(hba->dev);
6943 ufshcd_exit_clk_scaling(hba);
6944 ufshcd_hba_exit(hba);
6947 trace_ufshcd_init(dev_name(hba->dev), ret,
6948 ktime_to_us(ktime_sub(ktime_get(), start)),
6949 hba->curr_dev_pwr_mode, hba->uic_link_state);
6954 * ufshcd_async_scan - asynchronous execution for probing hba
6955 * @data: data pointer to pass to this function
6956 * @cookie: cookie data
6958 static void ufshcd_async_scan(void *data, async_cookie_t cookie)
6960 struct ufs_hba *hba = (struct ufs_hba *)data;
6962 ufshcd_probe_hba(hba);
6965 static enum blk_eh_timer_return ufshcd_eh_timed_out(struct scsi_cmnd *scmd)
6967 unsigned long flags;
6968 struct Scsi_Host *host;
6969 struct ufs_hba *hba;
6973 if (!scmd || !scmd->device || !scmd->device->host)
6976 host = scmd->device->host;
6977 hba = shost_priv(host);
6981 spin_lock_irqsave(host->host_lock, flags);
6983 for_each_set_bit(index, &hba->outstanding_reqs, hba->nutrs) {
6984 if (hba->lrb[index].cmd == scmd) {
6990 spin_unlock_irqrestore(host->host_lock, flags);
6993 * Bypass SCSI error handling and reset the block layer timer if this
6994 * SCSI command was not actually dispatched to UFS driver, otherwise
6995 * let SCSI layer handle the error as usual.
6997 return found ? BLK_EH_DONE : BLK_EH_RESET_TIMER;
7000 static const struct attribute_group *ufshcd_driver_groups[] = {
7001 &ufs_sysfs_unit_descriptor_group,
7002 &ufs_sysfs_lun_attributes_group,
7006 static struct scsi_host_template ufshcd_driver_template = {
7007 .module = THIS_MODULE,
7009 .proc_name = UFSHCD,
7010 .queuecommand = ufshcd_queuecommand,
7011 .slave_alloc = ufshcd_slave_alloc,
7012 .slave_configure = ufshcd_slave_configure,
7013 .slave_destroy = ufshcd_slave_destroy,
7014 .change_queue_depth = ufshcd_change_queue_depth,
7015 .eh_abort_handler = ufshcd_abort,
7016 .eh_device_reset_handler = ufshcd_eh_device_reset_handler,
7017 .eh_host_reset_handler = ufshcd_eh_host_reset_handler,
7018 .eh_timed_out = ufshcd_eh_timed_out,
7020 .sg_tablesize = SG_ALL,
7021 .cmd_per_lun = UFSHCD_CMD_PER_LUN,
7022 .can_queue = UFSHCD_CAN_QUEUE,
7023 .max_segment_size = PRDT_DATA_BYTE_COUNT_MAX,
7024 .max_host_blocked = 1,
7025 .track_queue_depth = 1,
7026 .sdev_groups = ufshcd_driver_groups,
7027 .dma_boundary = PAGE_SIZE - 1,
7030 static int ufshcd_config_vreg_load(struct device *dev, struct ufs_vreg *vreg,
7039 * "set_load" operation shall be required on those regulators
7040 * which specifically configured current limitation. Otherwise
7041 * zero max_uA may cause unexpected behavior when regulator is
7042 * enabled or set as high power mode.
7047 ret = regulator_set_load(vreg->reg, ua);
7049 dev_err(dev, "%s: %s set load (ua=%d) failed, err=%d\n",
7050 __func__, vreg->name, ua, ret);
7056 static inline int ufshcd_config_vreg_lpm(struct ufs_hba *hba,
7057 struct ufs_vreg *vreg)
7059 return ufshcd_config_vreg_load(hba->dev, vreg, UFS_VREG_LPM_LOAD_UA);
7062 static inline int ufshcd_config_vreg_hpm(struct ufs_hba *hba,
7063 struct ufs_vreg *vreg)
7065 return ufshcd_config_vreg_load(hba->dev, vreg, vreg->max_uA);
7068 static int ufshcd_config_vreg(struct device *dev,
7069 struct ufs_vreg *vreg, bool on)
7072 struct regulator *reg;
7074 int min_uV, uA_load;
7081 if (regulator_count_voltages(reg) > 0) {
7082 if (vreg->min_uV && vreg->max_uV) {
7083 min_uV = on ? vreg->min_uV : 0;
7084 ret = regulator_set_voltage(reg, min_uV, vreg->max_uV);
7087 "%s: %s set voltage failed, err=%d\n",
7088 __func__, name, ret);
7093 uA_load = on ? vreg->max_uA : 0;
7094 ret = ufshcd_config_vreg_load(dev, vreg, uA_load);
7102 static int ufshcd_enable_vreg(struct device *dev, struct ufs_vreg *vreg)
7106 if (!vreg || vreg->enabled)
7109 ret = ufshcd_config_vreg(dev, vreg, true);
7111 ret = regulator_enable(vreg->reg);
7114 vreg->enabled = true;
7116 dev_err(dev, "%s: %s enable failed, err=%d\n",
7117 __func__, vreg->name, ret);
7122 static int ufshcd_disable_vreg(struct device *dev, struct ufs_vreg *vreg)
7126 if (!vreg || !vreg->enabled)
7129 ret = regulator_disable(vreg->reg);
7132 /* ignore errors on applying disable config */
7133 ufshcd_config_vreg(dev, vreg, false);
7134 vreg->enabled = false;
7136 dev_err(dev, "%s: %s disable failed, err=%d\n",
7137 __func__, vreg->name, ret);
7143 static int ufshcd_setup_vreg(struct ufs_hba *hba, bool on)
7146 struct device *dev = hba->dev;
7147 struct ufs_vreg_info *info = &hba->vreg_info;
7149 ret = ufshcd_toggle_vreg(dev, info->vcc, on);
7153 ret = ufshcd_toggle_vreg(dev, info->vccq, on);
7157 ret = ufshcd_toggle_vreg(dev, info->vccq2, on);
7163 ufshcd_toggle_vreg(dev, info->vccq2, false);
7164 ufshcd_toggle_vreg(dev, info->vccq, false);
7165 ufshcd_toggle_vreg(dev, info->vcc, false);
7170 static int ufshcd_setup_hba_vreg(struct ufs_hba *hba, bool on)
7172 struct ufs_vreg_info *info = &hba->vreg_info;
7174 return ufshcd_toggle_vreg(hba->dev, info->vdd_hba, on);
7177 static int ufshcd_get_vreg(struct device *dev, struct ufs_vreg *vreg)
7184 vreg->reg = devm_regulator_get(dev, vreg->name);
7185 if (IS_ERR(vreg->reg)) {
7186 ret = PTR_ERR(vreg->reg);
7187 dev_err(dev, "%s: %s get failed, err=%d\n",
7188 __func__, vreg->name, ret);
7194 static int ufshcd_init_vreg(struct ufs_hba *hba)
7197 struct device *dev = hba->dev;
7198 struct ufs_vreg_info *info = &hba->vreg_info;
7200 ret = ufshcd_get_vreg(dev, info->vcc);
7204 ret = ufshcd_get_vreg(dev, info->vccq);
7208 ret = ufshcd_get_vreg(dev, info->vccq2);
7213 static int ufshcd_init_hba_vreg(struct ufs_hba *hba)
7215 struct ufs_vreg_info *info = &hba->vreg_info;
7218 return ufshcd_get_vreg(hba->dev, info->vdd_hba);
7223 static int __ufshcd_setup_clocks(struct ufs_hba *hba, bool on,
7227 struct ufs_clk_info *clki;
7228 struct list_head *head = &hba->clk_list_head;
7229 unsigned long flags;
7230 ktime_t start = ktime_get();
7231 bool clk_state_changed = false;
7233 if (list_empty(head))
7237 * vendor specific setup_clocks ops may depend on clocks managed by
7238 * this standard driver hence call the vendor specific setup_clocks
7239 * before disabling the clocks managed here.
7242 ret = ufshcd_vops_setup_clocks(hba, on, PRE_CHANGE);
7247 list_for_each_entry(clki, head, list) {
7248 if (!IS_ERR_OR_NULL(clki->clk)) {
7249 if (skip_ref_clk && !strcmp(clki->name, "ref_clk"))
7252 clk_state_changed = on ^ clki->enabled;
7253 if (on && !clki->enabled) {
7254 ret = clk_prepare_enable(clki->clk);
7256 dev_err(hba->dev, "%s: %s prepare enable failed, %d\n",
7257 __func__, clki->name, ret);
7260 } else if (!on && clki->enabled) {
7261 clk_disable_unprepare(clki->clk);
7264 dev_dbg(hba->dev, "%s: clk: %s %sabled\n", __func__,
7265 clki->name, on ? "en" : "dis");
7270 * vendor specific setup_clocks ops may depend on clocks managed by
7271 * this standard driver hence call the vendor specific setup_clocks
7272 * after enabling the clocks managed here.
7275 ret = ufshcd_vops_setup_clocks(hba, on, POST_CHANGE);
7282 list_for_each_entry(clki, head, list) {
7283 if (!IS_ERR_OR_NULL(clki->clk) && clki->enabled)
7284 clk_disable_unprepare(clki->clk);
7286 } else if (!ret && on) {
7287 spin_lock_irqsave(hba->host->host_lock, flags);
7288 hba->clk_gating.state = CLKS_ON;
7289 trace_ufshcd_clk_gating(dev_name(hba->dev),
7290 hba->clk_gating.state);
7291 spin_unlock_irqrestore(hba->host->host_lock, flags);
7294 if (clk_state_changed)
7295 trace_ufshcd_profile_clk_gating(dev_name(hba->dev),
7296 (on ? "on" : "off"),
7297 ktime_to_us(ktime_sub(ktime_get(), start)), ret);
7301 static int ufshcd_setup_clocks(struct ufs_hba *hba, bool on)
7303 return __ufshcd_setup_clocks(hba, on, false);
7306 static int ufshcd_init_clocks(struct ufs_hba *hba)
7309 struct ufs_clk_info *clki;
7310 struct device *dev = hba->dev;
7311 struct list_head *head = &hba->clk_list_head;
7313 if (list_empty(head))
7316 list_for_each_entry(clki, head, list) {
7320 clki->clk = devm_clk_get(dev, clki->name);
7321 if (IS_ERR(clki->clk)) {
7322 ret = PTR_ERR(clki->clk);
7323 dev_err(dev, "%s: %s clk get failed, %d\n",
7324 __func__, clki->name, ret);
7329 * Parse device ref clk freq as per device tree "ref_clk".
7330 * Default dev_ref_clk_freq is set to REF_CLK_FREQ_INVAL
7331 * in ufshcd_alloc_host().
7333 if (!strcmp(clki->name, "ref_clk"))
7334 ufshcd_parse_dev_ref_clk_freq(hba, clki->clk);
7336 if (clki->max_freq) {
7337 ret = clk_set_rate(clki->clk, clki->max_freq);
7339 dev_err(hba->dev, "%s: %s clk set rate(%dHz) failed, %d\n",
7340 __func__, clki->name,
7341 clki->max_freq, ret);
7344 clki->curr_freq = clki->max_freq;
7346 dev_dbg(dev, "%s: clk: %s, rate: %lu\n", __func__,
7347 clki->name, clk_get_rate(clki->clk));
7353 static int ufshcd_variant_hba_init(struct ufs_hba *hba)
7360 err = ufshcd_vops_init(hba);
7364 err = ufshcd_vops_setup_regulators(hba, true);
7371 ufshcd_vops_exit(hba);
7374 dev_err(hba->dev, "%s: variant %s init failed err %d\n",
7375 __func__, ufshcd_get_var_name(hba), err);
7379 static void ufshcd_variant_hba_exit(struct ufs_hba *hba)
7384 ufshcd_vops_setup_regulators(hba, false);
7386 ufshcd_vops_exit(hba);
7389 static int ufshcd_hba_init(struct ufs_hba *hba)
7394 * Handle host controller power separately from the UFS device power
7395 * rails as it will help controlling the UFS host controller power
7396 * collapse easily which is different than UFS device power collapse.
7397 * Also, enable the host controller power before we go ahead with rest
7398 * of the initialization here.
7400 err = ufshcd_init_hba_vreg(hba);
7404 err = ufshcd_setup_hba_vreg(hba, true);
7408 err = ufshcd_init_clocks(hba);
7410 goto out_disable_hba_vreg;
7412 err = ufshcd_setup_clocks(hba, true);
7414 goto out_disable_hba_vreg;
7416 err = ufshcd_init_vreg(hba);
7418 goto out_disable_clks;
7420 err = ufshcd_setup_vreg(hba, true);
7422 goto out_disable_clks;
7424 err = ufshcd_variant_hba_init(hba);
7426 goto out_disable_vreg;
7428 hba->is_powered = true;
7432 ufshcd_setup_vreg(hba, false);
7434 ufshcd_setup_clocks(hba, false);
7435 out_disable_hba_vreg:
7436 ufshcd_setup_hba_vreg(hba, false);
7441 static void ufshcd_hba_exit(struct ufs_hba *hba)
7443 if (hba->is_powered) {
7444 ufshcd_variant_hba_exit(hba);
7445 ufshcd_setup_vreg(hba, false);
7446 ufshcd_suspend_clkscaling(hba);
7447 if (ufshcd_is_clkscaling_supported(hba))
7449 ufshcd_suspend_clkscaling(hba);
7450 ufshcd_setup_clocks(hba, false);
7451 ufshcd_setup_hba_vreg(hba, false);
7452 hba->is_powered = false;
7457 ufshcd_send_request_sense(struct ufs_hba *hba, struct scsi_device *sdp)
7459 unsigned char cmd[6] = {REQUEST_SENSE,
7468 buffer = kzalloc(UFS_SENSE_SIZE, GFP_KERNEL);
7474 ret = scsi_execute(sdp, cmd, DMA_FROM_DEVICE, buffer,
7475 UFS_SENSE_SIZE, NULL, NULL,
7476 msecs_to_jiffies(1000), 3, 0, RQF_PM, NULL);
7478 pr_err("%s: failed with err %d\n", __func__, ret);
7486 * ufshcd_set_dev_pwr_mode - sends START STOP UNIT command to set device
7488 * @hba: per adapter instance
7489 * @pwr_mode: device power mode to set
7491 * Returns 0 if requested power mode is set successfully
7492 * Returns non-zero if failed to set the requested power mode
7494 static int ufshcd_set_dev_pwr_mode(struct ufs_hba *hba,
7495 enum ufs_dev_pwr_mode pwr_mode)
7497 unsigned char cmd[6] = { START_STOP };
7498 struct scsi_sense_hdr sshdr;
7499 struct scsi_device *sdp;
7500 unsigned long flags;
7503 spin_lock_irqsave(hba->host->host_lock, flags);
7504 sdp = hba->sdev_ufs_device;
7506 ret = scsi_device_get(sdp);
7507 if (!ret && !scsi_device_online(sdp)) {
7509 scsi_device_put(sdp);
7514 spin_unlock_irqrestore(hba->host->host_lock, flags);
7520 * If scsi commands fail, the scsi mid-layer schedules scsi error-
7521 * handling, which would wait for host to be resumed. Since we know
7522 * we are functional while we are here, skip host resume in error
7525 hba->host->eh_noresume = 1;
7526 if (hba->wlun_dev_clr_ua) {
7527 ret = ufshcd_send_request_sense(hba, sdp);
7530 /* Unit attention condition is cleared now */
7531 hba->wlun_dev_clr_ua = false;
7534 cmd[4] = pwr_mode << 4;
7537 * Current function would be generally called from the power management
7538 * callbacks hence set the RQF_PM flag so that it doesn't resume the
7539 * already suspended childs.
7541 ret = scsi_execute(sdp, cmd, DMA_NONE, NULL, 0, NULL, &sshdr,
7542 START_STOP_TIMEOUT, 0, 0, RQF_PM, NULL);
7544 sdev_printk(KERN_WARNING, sdp,
7545 "START_STOP failed for power mode: %d, result %x\n",
7547 if (driver_byte(ret) == DRIVER_SENSE)
7548 scsi_print_sense_hdr(sdp, NULL, &sshdr);
7552 hba->curr_dev_pwr_mode = pwr_mode;
7554 scsi_device_put(sdp);
7555 hba->host->eh_noresume = 0;
7559 static int ufshcd_link_state_transition(struct ufs_hba *hba,
7560 enum uic_link_state req_link_state,
7561 int check_for_bkops)
7565 if (req_link_state == hba->uic_link_state)
7568 if (req_link_state == UIC_LINK_HIBERN8_STATE) {
7569 ret = ufshcd_uic_hibern8_enter(hba);
7571 ufshcd_set_link_hibern8(hba);
7576 * If autobkops is enabled, link can't be turned off because
7577 * turning off the link would also turn off the device.
7579 else if ((req_link_state == UIC_LINK_OFF_STATE) &&
7580 (!check_for_bkops || (check_for_bkops &&
7581 !hba->auto_bkops_enabled))) {
7583 * Let's make sure that link is in low power mode, we are doing
7584 * this currently by putting the link in Hibern8. Otherway to
7585 * put the link in low power mode is to send the DME end point
7586 * to device and then send the DME reset command to local
7587 * unipro. But putting the link in hibern8 is much faster.
7589 ret = ufshcd_uic_hibern8_enter(hba);
7593 * Change controller state to "reset state" which
7594 * should also put the link in off/reset state
7596 ufshcd_hba_stop(hba, true);
7598 * TODO: Check if we need any delay to make sure that
7599 * controller is reset
7601 ufshcd_set_link_off(hba);
7608 static void ufshcd_vreg_set_lpm(struct ufs_hba *hba)
7611 * It seems some UFS devices may keep drawing more than sleep current
7612 * (atleast for 500us) from UFS rails (especially from VCCQ rail).
7613 * To avoid this situation, add 2ms delay before putting these UFS
7614 * rails in LPM mode.
7616 if (!ufshcd_is_link_active(hba) &&
7617 hba->dev_quirks & UFS_DEVICE_QUIRK_DELAY_BEFORE_LPM)
7618 usleep_range(2000, 2100);
7621 * If UFS device is either in UFS_Sleep turn off VCC rail to save some
7624 * If UFS device and link is in OFF state, all power supplies (VCC,
7625 * VCCQ, VCCQ2) can be turned off if power on write protect is not
7626 * required. If UFS link is inactive (Hibern8 or OFF state) and device
7627 * is in sleep state, put VCCQ & VCCQ2 rails in LPM mode.
7629 * Ignore the error returned by ufshcd_toggle_vreg() as device is anyway
7630 * in low power state which would save some power.
7632 if (ufshcd_is_ufs_dev_poweroff(hba) && ufshcd_is_link_off(hba) &&
7633 !hba->dev_info.is_lu_power_on_wp) {
7634 ufshcd_setup_vreg(hba, false);
7635 } else if (!ufshcd_is_ufs_dev_active(hba)) {
7636 ufshcd_toggle_vreg(hba->dev, hba->vreg_info.vcc, false);
7637 if (!ufshcd_is_link_active(hba)) {
7638 ufshcd_config_vreg_lpm(hba, hba->vreg_info.vccq);
7639 ufshcd_config_vreg_lpm(hba, hba->vreg_info.vccq2);
7644 static int ufshcd_vreg_set_hpm(struct ufs_hba *hba)
7648 if (ufshcd_is_ufs_dev_poweroff(hba) && ufshcd_is_link_off(hba) &&
7649 !hba->dev_info.is_lu_power_on_wp) {
7650 ret = ufshcd_setup_vreg(hba, true);
7651 } else if (!ufshcd_is_ufs_dev_active(hba)) {
7652 if (!ret && !ufshcd_is_link_active(hba)) {
7653 ret = ufshcd_config_vreg_hpm(hba, hba->vreg_info.vccq);
7656 ret = ufshcd_config_vreg_hpm(hba, hba->vreg_info.vccq2);
7660 ret = ufshcd_toggle_vreg(hba->dev, hba->vreg_info.vcc, true);
7665 ufshcd_config_vreg_lpm(hba, hba->vreg_info.vccq);
7667 ufshcd_toggle_vreg(hba->dev, hba->vreg_info.vcc, false);
7672 static void ufshcd_hba_vreg_set_lpm(struct ufs_hba *hba)
7674 if (ufshcd_is_link_off(hba))
7675 ufshcd_setup_hba_vreg(hba, false);
7678 static void ufshcd_hba_vreg_set_hpm(struct ufs_hba *hba)
7680 if (ufshcd_is_link_off(hba))
7681 ufshcd_setup_hba_vreg(hba, true);
7685 * ufshcd_suspend - helper function for suspend operations
7686 * @hba: per adapter instance
7687 * @pm_op: desired low power operation type
7689 * This function will try to put the UFS device and link into low power
7690 * mode based on the "rpm_lvl" (Runtime PM level) or "spm_lvl"
7691 * (System PM level).
7693 * If this function is called during shutdown, it will make sure that
7694 * both UFS device and UFS link is powered off.
7696 * NOTE: UFS device & link must be active before we enter in this function.
7698 * Returns 0 for success and non-zero for failure
7700 static int ufshcd_suspend(struct ufs_hba *hba, enum ufs_pm_op pm_op)
7703 enum ufs_pm_level pm_lvl;
7704 enum ufs_dev_pwr_mode req_dev_pwr_mode;
7705 enum uic_link_state req_link_state;
7707 hba->pm_op_in_progress = 1;
7708 if (!ufshcd_is_shutdown_pm(pm_op)) {
7709 pm_lvl = ufshcd_is_runtime_pm(pm_op) ?
7710 hba->rpm_lvl : hba->spm_lvl;
7711 req_dev_pwr_mode = ufs_get_pm_lvl_to_dev_pwr_mode(pm_lvl);
7712 req_link_state = ufs_get_pm_lvl_to_link_pwr_state(pm_lvl);
7714 req_dev_pwr_mode = UFS_POWERDOWN_PWR_MODE;
7715 req_link_state = UIC_LINK_OFF_STATE;
7719 * If we can't transition into any of the low power modes
7720 * just gate the clocks.
7722 ufshcd_hold(hba, false);
7723 hba->clk_gating.is_suspended = true;
7725 if (hba->clk_scaling.is_allowed) {
7726 cancel_work_sync(&hba->clk_scaling.suspend_work);
7727 cancel_work_sync(&hba->clk_scaling.resume_work);
7728 ufshcd_suspend_clkscaling(hba);
7731 if (req_dev_pwr_mode == UFS_ACTIVE_PWR_MODE &&
7732 req_link_state == UIC_LINK_ACTIVE_STATE) {
7736 if ((req_dev_pwr_mode == hba->curr_dev_pwr_mode) &&
7737 (req_link_state == hba->uic_link_state))
7740 /* UFS device & link must be active before we enter in this function */
7741 if (!ufshcd_is_ufs_dev_active(hba) || !ufshcd_is_link_active(hba)) {
7746 if (ufshcd_is_runtime_pm(pm_op)) {
7747 if (ufshcd_can_autobkops_during_suspend(hba)) {
7749 * The device is idle with no requests in the queue,
7750 * allow background operations if bkops status shows
7751 * that performance might be impacted.
7753 ret = ufshcd_urgent_bkops(hba);
7757 /* make sure that auto bkops is disabled */
7758 ufshcd_disable_auto_bkops(hba);
7762 if ((req_dev_pwr_mode != hba->curr_dev_pwr_mode) &&
7763 ((ufshcd_is_runtime_pm(pm_op) && !hba->auto_bkops_enabled) ||
7764 !ufshcd_is_runtime_pm(pm_op))) {
7765 /* ensure that bkops is disabled */
7766 ufshcd_disable_auto_bkops(hba);
7767 ret = ufshcd_set_dev_pwr_mode(hba, req_dev_pwr_mode);
7772 ret = ufshcd_link_state_transition(hba, req_link_state, 1);
7774 goto set_dev_active;
7776 ufshcd_vreg_set_lpm(hba);
7780 * Call vendor specific suspend callback. As these callbacks may access
7781 * vendor specific host controller register space call them before the
7782 * host clocks are ON.
7784 ret = ufshcd_vops_suspend(hba, pm_op);
7786 goto set_link_active;
7788 if (!ufshcd_is_link_active(hba))
7789 ufshcd_setup_clocks(hba, false);
7791 /* If link is active, device ref_clk can't be switched off */
7792 __ufshcd_setup_clocks(hba, false, true);
7794 hba->clk_gating.state = CLKS_OFF;
7795 trace_ufshcd_clk_gating(dev_name(hba->dev), hba->clk_gating.state);
7797 * Disable the host irq as host controller as there won't be any
7798 * host controller transaction expected till resume.
7800 ufshcd_disable_irq(hba);
7801 /* Put the host controller in low power mode if possible */
7802 ufshcd_hba_vreg_set_lpm(hba);
7806 if (hba->clk_scaling.is_allowed)
7807 ufshcd_resume_clkscaling(hba);
7808 ufshcd_vreg_set_hpm(hba);
7809 if (ufshcd_is_link_hibern8(hba) && !ufshcd_uic_hibern8_exit(hba))
7810 ufshcd_set_link_active(hba);
7811 else if (ufshcd_is_link_off(hba))
7812 ufshcd_host_reset_and_restore(hba);
7814 if (!ufshcd_set_dev_pwr_mode(hba, UFS_ACTIVE_PWR_MODE))
7815 ufshcd_disable_auto_bkops(hba);
7817 if (hba->clk_scaling.is_allowed)
7818 ufshcd_resume_clkscaling(hba);
7819 hba->clk_gating.is_suspended = false;
7820 ufshcd_release(hba);
7822 hba->pm_op_in_progress = 0;
7827 * ufshcd_resume - helper function for resume operations
7828 * @hba: per adapter instance
7829 * @pm_op: runtime PM or system PM
7831 * This function basically brings the UFS device, UniPro link and controller
7834 * Returns 0 for success and non-zero for failure
7836 static int ufshcd_resume(struct ufs_hba *hba, enum ufs_pm_op pm_op)
7839 enum uic_link_state old_link_state;
7841 hba->pm_op_in_progress = 1;
7842 old_link_state = hba->uic_link_state;
7844 ufshcd_hba_vreg_set_hpm(hba);
7845 /* Make sure clocks are enabled before accessing controller */
7846 ret = ufshcd_setup_clocks(hba, true);
7850 /* enable the host irq as host controller would be active soon */
7851 ret = ufshcd_enable_irq(hba);
7853 goto disable_irq_and_vops_clks;
7855 ret = ufshcd_vreg_set_hpm(hba);
7857 goto disable_irq_and_vops_clks;
7860 * Call vendor specific resume callback. As these callbacks may access
7861 * vendor specific host controller register space call them when the
7862 * host clocks are ON.
7864 ret = ufshcd_vops_resume(hba, pm_op);
7868 if (ufshcd_is_link_hibern8(hba)) {
7869 ret = ufshcd_uic_hibern8_exit(hba);
7871 ufshcd_set_link_active(hba);
7873 goto vendor_suspend;
7874 } else if (ufshcd_is_link_off(hba)) {
7875 ret = ufshcd_host_reset_and_restore(hba);
7877 * ufshcd_host_reset_and_restore() should have already
7878 * set the link state as active
7880 if (ret || !ufshcd_is_link_active(hba))
7881 goto vendor_suspend;
7884 if (!ufshcd_is_ufs_dev_active(hba)) {
7885 ret = ufshcd_set_dev_pwr_mode(hba, UFS_ACTIVE_PWR_MODE);
7887 goto set_old_link_state;
7890 if (ufshcd_keep_autobkops_enabled_except_suspend(hba))
7891 ufshcd_enable_auto_bkops(hba);
7894 * If BKOPs operations are urgently needed at this moment then
7895 * keep auto-bkops enabled or else disable it.
7897 ufshcd_urgent_bkops(hba);
7899 hba->clk_gating.is_suspended = false;
7901 if (hba->clk_scaling.is_allowed)
7902 ufshcd_resume_clkscaling(hba);
7904 /* Schedule clock gating in case of no access to UFS device yet */
7905 ufshcd_release(hba);
7907 /* Enable Auto-Hibernate if configured */
7908 ufshcd_auto_hibern8_enable(hba);
7913 ufshcd_link_state_transition(hba, old_link_state, 0);
7915 ufshcd_vops_suspend(hba, pm_op);
7917 ufshcd_vreg_set_lpm(hba);
7918 disable_irq_and_vops_clks:
7919 ufshcd_disable_irq(hba);
7920 if (hba->clk_scaling.is_allowed)
7921 ufshcd_suspend_clkscaling(hba);
7922 ufshcd_setup_clocks(hba, false);
7924 hba->pm_op_in_progress = 0;
7929 * ufshcd_system_suspend - system suspend routine
7930 * @hba: per adapter instance
7932 * Check the description of ufshcd_suspend() function for more details.
7934 * Returns 0 for success and non-zero for failure
7936 int ufshcd_system_suspend(struct ufs_hba *hba)
7939 ktime_t start = ktime_get();
7941 if (!hba || !hba->is_powered)
7944 if ((ufs_get_pm_lvl_to_dev_pwr_mode(hba->spm_lvl) ==
7945 hba->curr_dev_pwr_mode) &&
7946 (ufs_get_pm_lvl_to_link_pwr_state(hba->spm_lvl) ==
7947 hba->uic_link_state))
7950 if (pm_runtime_suspended(hba->dev)) {
7952 * UFS device and/or UFS link low power states during runtime
7953 * suspend seems to be different than what is expected during
7954 * system suspend. Hence runtime resume the devic & link and
7955 * let the system suspend low power states to take effect.
7956 * TODO: If resume takes longer time, we might have optimize
7957 * it in future by not resuming everything if possible.
7959 ret = ufshcd_runtime_resume(hba);
7964 ret = ufshcd_suspend(hba, UFS_SYSTEM_PM);
7966 trace_ufshcd_system_suspend(dev_name(hba->dev), ret,
7967 ktime_to_us(ktime_sub(ktime_get(), start)),
7968 hba->curr_dev_pwr_mode, hba->uic_link_state);
7970 hba->is_sys_suspended = true;
7973 EXPORT_SYMBOL(ufshcd_system_suspend);
7976 * ufshcd_system_resume - system resume routine
7977 * @hba: per adapter instance
7979 * Returns 0 for success and non-zero for failure
7982 int ufshcd_system_resume(struct ufs_hba *hba)
7985 ktime_t start = ktime_get();
7990 if (!hba->is_powered || pm_runtime_suspended(hba->dev))
7992 * Let the runtime resume take care of resuming
7993 * if runtime suspended.
7997 ret = ufshcd_resume(hba, UFS_SYSTEM_PM);
7999 trace_ufshcd_system_resume(dev_name(hba->dev), ret,
8000 ktime_to_us(ktime_sub(ktime_get(), start)),
8001 hba->curr_dev_pwr_mode, hba->uic_link_state);
8003 hba->is_sys_suspended = false;
8006 EXPORT_SYMBOL(ufshcd_system_resume);
8009 * ufshcd_runtime_suspend - runtime suspend routine
8010 * @hba: per adapter instance
8012 * Check the description of ufshcd_suspend() function for more details.
8014 * Returns 0 for success and non-zero for failure
8016 int ufshcd_runtime_suspend(struct ufs_hba *hba)
8019 ktime_t start = ktime_get();
8024 if (!hba->is_powered)
8027 ret = ufshcd_suspend(hba, UFS_RUNTIME_PM);
8029 trace_ufshcd_runtime_suspend(dev_name(hba->dev), ret,
8030 ktime_to_us(ktime_sub(ktime_get(), start)),
8031 hba->curr_dev_pwr_mode, hba->uic_link_state);
8034 EXPORT_SYMBOL(ufshcd_runtime_suspend);
8037 * ufshcd_runtime_resume - runtime resume routine
8038 * @hba: per adapter instance
8040 * This function basically brings the UFS device, UniPro link and controller
8041 * to active state. Following operations are done in this function:
8043 * 1. Turn on all the controller related clocks
8044 * 2. Bring the UniPro link out of Hibernate state
8045 * 3. If UFS device is in sleep state, turn ON VCC rail and bring the UFS device
8047 * 4. If auto-bkops is enabled on the device, disable it.
8049 * So following would be the possible power state after this function return
8051 * S1: UFS device in Active state with VCC rail ON
8052 * UniPro link in Active state
8053 * All the UFS/UniPro controller clocks are ON
8055 * Returns 0 for success and non-zero for failure
8057 int ufshcd_runtime_resume(struct ufs_hba *hba)
8060 ktime_t start = ktime_get();
8065 if (!hba->is_powered)
8068 ret = ufshcd_resume(hba, UFS_RUNTIME_PM);
8070 trace_ufshcd_runtime_resume(dev_name(hba->dev), ret,
8071 ktime_to_us(ktime_sub(ktime_get(), start)),
8072 hba->curr_dev_pwr_mode, hba->uic_link_state);
8075 EXPORT_SYMBOL(ufshcd_runtime_resume);
8077 int ufshcd_runtime_idle(struct ufs_hba *hba)
8081 EXPORT_SYMBOL(ufshcd_runtime_idle);
8084 * ufshcd_shutdown - shutdown routine
8085 * @hba: per adapter instance
8087 * This function would power off both UFS device and UFS link.
8089 * Returns 0 always to allow force shutdown even in case of errors.
8091 int ufshcd_shutdown(struct ufs_hba *hba)
8095 if (ufshcd_is_ufs_dev_poweroff(hba) && ufshcd_is_link_off(hba))
8098 if (pm_runtime_suspended(hba->dev)) {
8099 ret = ufshcd_runtime_resume(hba);
8104 ret = ufshcd_suspend(hba, UFS_SHUTDOWN_PM);
8107 dev_err(hba->dev, "%s failed, err %d\n", __func__, ret);
8108 /* allow force shutdown even in case of errors */
8111 EXPORT_SYMBOL(ufshcd_shutdown);
8114 * ufshcd_remove - de-allocate SCSI host and host memory space
8115 * data structure memory
8116 * @hba: per adapter instance
8118 void ufshcd_remove(struct ufs_hba *hba)
8120 ufs_bsg_remove(hba);
8121 ufs_sysfs_remove_nodes(hba->dev);
8122 scsi_remove_host(hba->host);
8123 /* disable interrupts */
8124 ufshcd_disable_intr(hba, hba->intr_mask);
8125 ufshcd_hba_stop(hba, true);
8127 ufshcd_exit_clk_scaling(hba);
8128 ufshcd_exit_clk_gating(hba);
8129 if (ufshcd_is_clkscaling_supported(hba))
8130 device_remove_file(hba->dev, &hba->clk_scaling.enable_attr);
8131 ufshcd_hba_exit(hba);
8133 EXPORT_SYMBOL_GPL(ufshcd_remove);
8136 * ufshcd_dealloc_host - deallocate Host Bus Adapter (HBA)
8137 * @hba: pointer to Host Bus Adapter (HBA)
8139 void ufshcd_dealloc_host(struct ufs_hba *hba)
8141 scsi_host_put(hba->host);
8143 EXPORT_SYMBOL_GPL(ufshcd_dealloc_host);
8146 * ufshcd_set_dma_mask - Set dma mask based on the controller
8147 * addressing capability
8148 * @hba: per adapter instance
8150 * Returns 0 for success, non-zero for failure
8152 static int ufshcd_set_dma_mask(struct ufs_hba *hba)
8154 if (hba->capabilities & MASK_64_ADDRESSING_SUPPORT) {
8155 if (!dma_set_mask_and_coherent(hba->dev, DMA_BIT_MASK(64)))
8158 return dma_set_mask_and_coherent(hba->dev, DMA_BIT_MASK(32));
8162 * ufshcd_alloc_host - allocate Host Bus Adapter (HBA)
8163 * @dev: pointer to device handle
8164 * @hba_handle: driver private handle
8165 * Returns 0 on success, non-zero value on failure
8167 int ufshcd_alloc_host(struct device *dev, struct ufs_hba **hba_handle)
8169 struct Scsi_Host *host;
8170 struct ufs_hba *hba;
8175 "Invalid memory reference for dev is NULL\n");
8180 host = scsi_host_alloc(&ufshcd_driver_template,
8181 sizeof(struct ufs_hba));
8183 dev_err(dev, "scsi_host_alloc failed\n");
8187 hba = shost_priv(host);
8191 hba->dev_ref_clk_freq = REF_CLK_FREQ_INVAL;
8193 INIT_LIST_HEAD(&hba->clk_list_head);
8198 EXPORT_SYMBOL(ufshcd_alloc_host);
8201 * ufshcd_init - Driver initialization routine
8202 * @hba: per-adapter instance
8203 * @mmio_base: base register address
8204 * @irq: Interrupt line of device
8205 * Returns 0 on success, non-zero value on failure
8207 int ufshcd_init(struct ufs_hba *hba, void __iomem *mmio_base, unsigned int irq)
8210 struct Scsi_Host *host = hba->host;
8211 struct device *dev = hba->dev;
8215 "Invalid memory reference for mmio_base is NULL\n");
8220 hba->mmio_base = mmio_base;
8223 /* Set descriptor lengths to specification defaults */
8224 ufshcd_def_desc_sizes(hba);
8226 err = ufshcd_hba_init(hba);
8230 /* Read capabilities registers */
8231 ufshcd_hba_capabilities(hba);
8233 /* Get UFS version supported by the controller */
8234 hba->ufs_version = ufshcd_get_ufs_version(hba);
8236 if ((hba->ufs_version != UFSHCI_VERSION_10) &&
8237 (hba->ufs_version != UFSHCI_VERSION_11) &&
8238 (hba->ufs_version != UFSHCI_VERSION_20) &&
8239 (hba->ufs_version != UFSHCI_VERSION_21))
8240 dev_err(hba->dev, "invalid UFS version 0x%x\n",
8243 /* Get Interrupt bit mask per version */
8244 hba->intr_mask = ufshcd_get_intr_mask(hba);
8246 err = ufshcd_set_dma_mask(hba);
8248 dev_err(hba->dev, "set dma mask failed\n");
8252 /* Allocate memory for host memory space */
8253 err = ufshcd_memory_alloc(hba);
8255 dev_err(hba->dev, "Memory allocation failed\n");
8260 ufshcd_host_memory_configure(hba);
8262 host->can_queue = hba->nutrs;
8263 host->cmd_per_lun = hba->nutrs;
8264 host->max_id = UFSHCD_MAX_ID;
8265 host->max_lun = UFS_MAX_LUNS;
8266 host->max_channel = UFSHCD_MAX_CHANNEL;
8267 host->unique_id = host->host_no;
8268 host->max_cmd_len = UFS_CDB_SIZE;
8270 hba->max_pwr_info.is_valid = false;
8272 /* Initailize wait queue for task management */
8273 init_waitqueue_head(&hba->tm_wq);
8274 init_waitqueue_head(&hba->tm_tag_wq);
8276 /* Initialize work queues */
8277 INIT_WORK(&hba->eh_work, ufshcd_err_handler);
8278 INIT_WORK(&hba->eeh_work, ufshcd_exception_event_handler);
8280 /* Initialize UIC command mutex */
8281 mutex_init(&hba->uic_cmd_mutex);
8283 /* Initialize mutex for device management commands */
8284 mutex_init(&hba->dev_cmd.lock);
8286 init_rwsem(&hba->clk_scaling_lock);
8288 /* Initialize device management tag acquire wait queue */
8289 init_waitqueue_head(&hba->dev_cmd.tag_wq);
8291 ufshcd_init_clk_gating(hba);
8293 ufshcd_init_clk_scaling(hba);
8296 * In order to avoid any spurious interrupt immediately after
8297 * registering UFS controller interrupt handler, clear any pending UFS
8298 * interrupt status and disable all the UFS interrupts.
8300 ufshcd_writel(hba, ufshcd_readl(hba, REG_INTERRUPT_STATUS),
8301 REG_INTERRUPT_STATUS);
8302 ufshcd_writel(hba, 0, REG_INTERRUPT_ENABLE);
8304 * Make sure that UFS interrupts are disabled and any pending interrupt
8305 * status is cleared before registering UFS interrupt handler.
8309 /* IRQ registration */
8310 err = devm_request_irq(dev, irq, ufshcd_intr, IRQF_SHARED, UFSHCD, hba);
8312 dev_err(hba->dev, "request irq failed\n");
8315 hba->is_irq_enabled = true;
8318 err = scsi_add_host(host, hba->dev);
8320 dev_err(hba->dev, "scsi_add_host failed\n");
8324 /* Host controller enable */
8325 err = ufshcd_hba_enable(hba);
8327 dev_err(hba->dev, "Host controller enable failed\n");
8328 ufshcd_print_host_regs(hba);
8329 ufshcd_print_host_state(hba);
8330 goto out_remove_scsi_host;
8334 * Set the default power management level for runtime and system PM.
8335 * Default power saving mode is to keep UFS link in Hibern8 state
8336 * and UFS device in sleep state.
8338 hba->rpm_lvl = ufs_get_desired_pm_lvl_for_dev_link_state(
8340 UIC_LINK_HIBERN8_STATE);
8341 hba->spm_lvl = ufs_get_desired_pm_lvl_for_dev_link_state(
8343 UIC_LINK_HIBERN8_STATE);
8345 /* Set the default auto-hiberate idle timer value to 150 ms */
8346 if (ufshcd_is_auto_hibern8_supported(hba) && !hba->ahit) {
8347 hba->ahit = FIELD_PREP(UFSHCI_AHIBERN8_TIMER_MASK, 150) |
8348 FIELD_PREP(UFSHCI_AHIBERN8_SCALE_MASK, 3);
8351 /* Hold auto suspend until async scan completes */
8352 pm_runtime_get_sync(dev);
8353 atomic_set(&hba->scsi_block_reqs_cnt, 0);
8355 * We are assuming that device wasn't put in sleep/power-down
8356 * state exclusively during the boot stage before kernel.
8357 * This assumption helps avoid doing link startup twice during
8358 * ufshcd_probe_hba().
8360 ufshcd_set_ufs_dev_active(hba);
8362 async_schedule(ufshcd_async_scan, hba);
8363 ufs_sysfs_add_nodes(hba->dev);
8367 out_remove_scsi_host:
8368 scsi_remove_host(hba->host);
8370 ufshcd_exit_clk_scaling(hba);
8371 ufshcd_exit_clk_gating(hba);
8373 hba->is_irq_enabled = false;
8374 ufshcd_hba_exit(hba);
8378 EXPORT_SYMBOL_GPL(ufshcd_init);
8380 MODULE_AUTHOR("Santosh Yaragnavi <santosh.sy@samsung.com>");
8381 MODULE_AUTHOR("Vinayak Holikatti <h.vinayak@samsung.com>");
8382 MODULE_DESCRIPTION("Generic UFS host controller driver Core");
8383 MODULE_LICENSE("GPL");
8384 MODULE_VERSION(UFSHCD_DRIVER_VERSION);