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>
45 #include "ufs_quirks.h"
48 #define CREATE_TRACE_POINTS
49 #include <trace/events/ufs.h>
51 #define UFSHCD_REQ_SENSE_SIZE 18
53 #define UFSHCD_ENABLE_INTRS (UTP_TRANSFER_REQ_COMPL |\
56 /* UIC command timeout, unit: ms */
57 #define UIC_CMD_TIMEOUT 500
59 /* NOP OUT retries waiting for NOP IN response */
60 #define NOP_OUT_RETRIES 10
61 /* Timeout after 30 msecs if NOP OUT hangs without response */
62 #define NOP_OUT_TIMEOUT 30 /* msecs */
64 /* Query request retries */
65 #define QUERY_REQ_RETRIES 3
66 /* Query request timeout */
67 #define QUERY_REQ_TIMEOUT 1500 /* 1.5 seconds */
69 /* Task management command timeout */
70 #define TM_CMD_TIMEOUT 100 /* msecs */
72 /* maximum number of retries for a general UIC command */
73 #define UFS_UIC_COMMAND_RETRIES 3
75 /* maximum number of link-startup retries */
76 #define DME_LINKSTARTUP_RETRIES 3
78 /* Maximum retries for Hibern8 enter */
79 #define UIC_HIBERN8_ENTER_RETRIES 3
81 /* maximum number of reset retries before giving up */
82 #define MAX_HOST_RESET_RETRIES 5
84 /* Expose the flag value from utp_upiu_query.value */
85 #define MASK_QUERY_UPIU_FLAG_LOC 0xFF
87 /* Interrupt aggregation default timeout, unit: 40us */
88 #define INT_AGGR_DEF_TO 0x02
90 #define ufshcd_toggle_vreg(_dev, _vreg, _on) \
94 _ret = ufshcd_enable_vreg(_dev, _vreg); \
96 _ret = ufshcd_disable_vreg(_dev, _vreg); \
100 #define ufshcd_hex_dump(prefix_str, buf, len) \
101 print_hex_dump(KERN_ERR, prefix_str, DUMP_PREFIX_OFFSET, 16, 4, buf, len, false)
103 static u32 ufs_query_desc_max_size[] = {
104 QUERY_DESC_DEVICE_MAX_SIZE,
105 QUERY_DESC_CONFIGURAION_MAX_SIZE,
106 QUERY_DESC_UNIT_MAX_SIZE,
107 QUERY_DESC_RFU_MAX_SIZE,
108 QUERY_DESC_INTERCONNECT_MAX_SIZE,
109 QUERY_DESC_STRING_MAX_SIZE,
110 QUERY_DESC_RFU_MAX_SIZE,
111 QUERY_DESC_GEOMETRY_MAX_SIZE,
112 QUERY_DESC_POWER_MAX_SIZE,
113 QUERY_DESC_RFU_MAX_SIZE,
117 UFSHCD_MAX_CHANNEL = 0,
119 UFSHCD_CMD_PER_LUN = 32,
120 UFSHCD_CAN_QUEUE = 32,
127 UFSHCD_STATE_OPERATIONAL,
128 UFSHCD_STATE_EH_SCHEDULED,
131 /* UFSHCD error handling flags */
133 UFSHCD_EH_IN_PROGRESS = (1 << 0),
136 /* UFSHCD UIC layer error flags */
138 UFSHCD_UIC_DL_PA_INIT_ERROR = (1 << 0), /* Data link layer error */
139 UFSHCD_UIC_DL_NAC_RECEIVED_ERROR = (1 << 1), /* Data link layer error */
140 UFSHCD_UIC_DL_TCx_REPLAY_ERROR = (1 << 2), /* Data link layer error */
141 UFSHCD_UIC_NL_ERROR = (1 << 3), /* Network layer error */
142 UFSHCD_UIC_TL_ERROR = (1 << 4), /* Transport Layer error */
143 UFSHCD_UIC_DME_ERROR = (1 << 5), /* DME error */
146 #define ufshcd_set_eh_in_progress(h) \
147 ((h)->eh_flags |= UFSHCD_EH_IN_PROGRESS)
148 #define ufshcd_eh_in_progress(h) \
149 ((h)->eh_flags & UFSHCD_EH_IN_PROGRESS)
150 #define ufshcd_clear_eh_in_progress(h) \
151 ((h)->eh_flags &= ~UFSHCD_EH_IN_PROGRESS)
153 #define ufshcd_set_ufs_dev_active(h) \
154 ((h)->curr_dev_pwr_mode = UFS_ACTIVE_PWR_MODE)
155 #define ufshcd_set_ufs_dev_sleep(h) \
156 ((h)->curr_dev_pwr_mode = UFS_SLEEP_PWR_MODE)
157 #define ufshcd_set_ufs_dev_poweroff(h) \
158 ((h)->curr_dev_pwr_mode = UFS_POWERDOWN_PWR_MODE)
159 #define ufshcd_is_ufs_dev_active(h) \
160 ((h)->curr_dev_pwr_mode == UFS_ACTIVE_PWR_MODE)
161 #define ufshcd_is_ufs_dev_sleep(h) \
162 ((h)->curr_dev_pwr_mode == UFS_SLEEP_PWR_MODE)
163 #define ufshcd_is_ufs_dev_poweroff(h) \
164 ((h)->curr_dev_pwr_mode == UFS_POWERDOWN_PWR_MODE)
166 static struct ufs_pm_lvl_states ufs_pm_lvl_states[] = {
167 {UFS_ACTIVE_PWR_MODE, UIC_LINK_ACTIVE_STATE},
168 {UFS_ACTIVE_PWR_MODE, UIC_LINK_HIBERN8_STATE},
169 {UFS_SLEEP_PWR_MODE, UIC_LINK_ACTIVE_STATE},
170 {UFS_SLEEP_PWR_MODE, UIC_LINK_HIBERN8_STATE},
171 {UFS_POWERDOWN_PWR_MODE, UIC_LINK_HIBERN8_STATE},
172 {UFS_POWERDOWN_PWR_MODE, UIC_LINK_OFF_STATE},
175 static inline enum ufs_dev_pwr_mode
176 ufs_get_pm_lvl_to_dev_pwr_mode(enum ufs_pm_level lvl)
178 return ufs_pm_lvl_states[lvl].dev_state;
181 static inline enum uic_link_state
182 ufs_get_pm_lvl_to_link_pwr_state(enum ufs_pm_level lvl)
184 return ufs_pm_lvl_states[lvl].link_state;
187 static inline enum ufs_pm_level
188 ufs_get_desired_pm_lvl_for_dev_link_state(enum ufs_dev_pwr_mode dev_state,
189 enum uic_link_state link_state)
191 enum ufs_pm_level lvl;
193 for (lvl = UFS_PM_LVL_0; lvl < UFS_PM_LVL_MAX; lvl++) {
194 if ((ufs_pm_lvl_states[lvl].dev_state == dev_state) &&
195 (ufs_pm_lvl_states[lvl].link_state == link_state))
199 /* if no match found, return the level 0 */
203 static struct ufs_dev_fix ufs_fixups[] = {
204 /* UFS cards deviations table */
205 UFS_FIX(UFS_VENDOR_SAMSUNG, UFS_ANY_MODEL,
206 UFS_DEVICE_QUIRK_DELAY_BEFORE_LPM),
207 UFS_FIX(UFS_VENDOR_SAMSUNG, UFS_ANY_MODEL, UFS_DEVICE_NO_VCCQ),
208 UFS_FIX(UFS_VENDOR_SAMSUNG, UFS_ANY_MODEL,
209 UFS_DEVICE_QUIRK_RECOVERY_FROM_DL_NAC_ERRORS),
210 UFS_FIX(UFS_VENDOR_SAMSUNG, UFS_ANY_MODEL,
211 UFS_DEVICE_NO_FASTAUTO),
212 UFS_FIX(UFS_VENDOR_SAMSUNG, UFS_ANY_MODEL,
213 UFS_DEVICE_QUIRK_HOST_PA_TACTIVATE),
214 UFS_FIX(UFS_VENDOR_TOSHIBA, UFS_ANY_MODEL,
215 UFS_DEVICE_QUIRK_DELAY_BEFORE_LPM),
216 UFS_FIX(UFS_VENDOR_TOSHIBA, "THGLF2G9C8KBADG",
217 UFS_DEVICE_QUIRK_PA_TACTIVATE),
218 UFS_FIX(UFS_VENDOR_TOSHIBA, "THGLF2G9D8KBADG",
219 UFS_DEVICE_QUIRK_PA_TACTIVATE),
220 UFS_FIX(UFS_VENDOR_SKHYNIX, UFS_ANY_MODEL, UFS_DEVICE_NO_VCCQ),
221 UFS_FIX(UFS_VENDOR_SKHYNIX, UFS_ANY_MODEL,
222 UFS_DEVICE_QUIRK_HOST_PA_SAVECONFIGTIME),
227 static void ufshcd_tmc_handler(struct ufs_hba *hba);
228 static void ufshcd_async_scan(void *data, async_cookie_t cookie);
229 static int ufshcd_reset_and_restore(struct ufs_hba *hba);
230 static int ufshcd_eh_host_reset_handler(struct scsi_cmnd *cmd);
231 static int ufshcd_clear_tm_cmd(struct ufs_hba *hba, int tag);
232 static void ufshcd_hba_exit(struct ufs_hba *hba);
233 static int ufshcd_probe_hba(struct ufs_hba *hba);
234 static int __ufshcd_setup_clocks(struct ufs_hba *hba, bool on,
236 static int ufshcd_setup_clocks(struct ufs_hba *hba, bool on);
237 static int ufshcd_set_vccq_rail_unused(struct ufs_hba *hba, bool unused);
238 static int ufshcd_uic_hibern8_exit(struct ufs_hba *hba);
239 static int ufshcd_uic_hibern8_enter(struct ufs_hba *hba);
240 static inline void ufshcd_add_delay_before_dme_cmd(struct ufs_hba *hba);
241 static int ufshcd_host_reset_and_restore(struct ufs_hba *hba);
242 static void ufshcd_resume_clkscaling(struct ufs_hba *hba);
243 static void ufshcd_suspend_clkscaling(struct ufs_hba *hba);
244 static void __ufshcd_suspend_clkscaling(struct ufs_hba *hba);
245 static int ufshcd_scale_clks(struct ufs_hba *hba, bool scale_up);
246 static irqreturn_t ufshcd_intr(int irq, void *__hba);
247 static int ufshcd_config_pwr_mode(struct ufs_hba *hba,
248 struct ufs_pa_layer_attr *desired_pwr_mode);
249 static int ufshcd_change_power_mode(struct ufs_hba *hba,
250 struct ufs_pa_layer_attr *pwr_mode);
251 static inline bool ufshcd_valid_tag(struct ufs_hba *hba, int tag)
253 return tag >= 0 && tag < hba->nutrs;
256 static inline int ufshcd_enable_irq(struct ufs_hba *hba)
260 if (!hba->is_irq_enabled) {
261 ret = request_irq(hba->irq, ufshcd_intr, IRQF_SHARED, UFSHCD,
264 dev_err(hba->dev, "%s: request_irq failed, ret=%d\n",
266 hba->is_irq_enabled = true;
272 static inline void ufshcd_disable_irq(struct ufs_hba *hba)
274 if (hba->is_irq_enabled) {
275 free_irq(hba->irq, hba);
276 hba->is_irq_enabled = false;
280 /* replace non-printable or non-ASCII characters with spaces */
281 static inline void ufshcd_remove_non_printable(char *val)
286 if (*val < 0x20 || *val > 0x7e)
290 static void ufshcd_add_command_trace(struct ufs_hba *hba,
291 unsigned int tag, const char *str)
296 struct ufshcd_lrb *lrbp;
297 int transfer_len = -1;
299 if (!trace_ufshcd_command_enabled())
302 lrbp = &hba->lrb[tag];
304 if (lrbp->cmd) { /* data phase exists */
305 opcode = (u8)(*lrbp->cmd->cmnd);
306 if ((opcode == READ_10) || (opcode == WRITE_10)) {
308 * Currently we only fully trace read(10) and write(10)
311 if (lrbp->cmd->request && lrbp->cmd->request->bio)
313 lrbp->cmd->request->bio->bi_iter.bi_sector;
314 transfer_len = be32_to_cpu(
315 lrbp->ucd_req_ptr->sc.exp_data_transfer_len);
319 intr = ufshcd_readl(hba, REG_INTERRUPT_STATUS);
320 doorbell = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
321 trace_ufshcd_command(dev_name(hba->dev), str, tag,
322 doorbell, transfer_len, intr, lba, opcode);
325 static void ufshcd_print_clk_freqs(struct ufs_hba *hba)
327 struct ufs_clk_info *clki;
328 struct list_head *head = &hba->clk_list_head;
330 if (!head || list_empty(head))
333 list_for_each_entry(clki, head, list) {
334 if (!IS_ERR_OR_NULL(clki->clk) && clki->min_freq &&
336 dev_err(hba->dev, "clk: %s, rate: %u\n",
337 clki->name, clki->curr_freq);
341 static void ufshcd_print_uic_err_hist(struct ufs_hba *hba,
342 struct ufs_uic_err_reg_hist *err_hist, char *err_name)
346 for (i = 0; i < UIC_ERR_REG_HIST_LENGTH; i++) {
347 int p = (i + err_hist->pos - 1) % UIC_ERR_REG_HIST_LENGTH;
349 if (err_hist->reg[p] == 0)
351 dev_err(hba->dev, "%s[%d] = 0x%x at %lld us\n", err_name, i,
352 err_hist->reg[p], ktime_to_us(err_hist->tstamp[p]));
356 static void ufshcd_print_host_regs(struct ufs_hba *hba)
359 * hex_dump reads its data without the readl macro. This might
360 * cause inconsistency issues on some platform, as the printed
361 * values may be from cache and not the most recent value.
362 * To know whether you are looking at an un-cached version verify
363 * that IORESOURCE_MEM flag is on when xxx_get_resource() is invoked
364 * during platform/pci probe function.
366 ufshcd_hex_dump("host regs: ", hba->mmio_base, UFSHCI_REG_SPACE_SIZE);
367 dev_err(hba->dev, "hba->ufs_version = 0x%x, hba->capabilities = 0x%x\n",
368 hba->ufs_version, hba->capabilities);
370 "hba->outstanding_reqs = 0x%x, hba->outstanding_tasks = 0x%x\n",
371 (u32)hba->outstanding_reqs, (u32)hba->outstanding_tasks);
373 "last_hibern8_exit_tstamp at %lld us, hibern8_exit_cnt = %d\n",
374 ktime_to_us(hba->ufs_stats.last_hibern8_exit_tstamp),
375 hba->ufs_stats.hibern8_exit_cnt);
377 ufshcd_print_uic_err_hist(hba, &hba->ufs_stats.pa_err, "pa_err");
378 ufshcd_print_uic_err_hist(hba, &hba->ufs_stats.dl_err, "dl_err");
379 ufshcd_print_uic_err_hist(hba, &hba->ufs_stats.nl_err, "nl_err");
380 ufshcd_print_uic_err_hist(hba, &hba->ufs_stats.tl_err, "tl_err");
381 ufshcd_print_uic_err_hist(hba, &hba->ufs_stats.dme_err, "dme_err");
383 ufshcd_print_clk_freqs(hba);
385 if (hba->vops && hba->vops->dbg_register_dump)
386 hba->vops->dbg_register_dump(hba);
390 void ufshcd_print_trs(struct ufs_hba *hba, unsigned long bitmap, bool pr_prdt)
392 struct ufshcd_lrb *lrbp;
396 for_each_set_bit(tag, &bitmap, hba->nutrs) {
397 lrbp = &hba->lrb[tag];
399 dev_err(hba->dev, "UPIU[%d] - issue time %lld us\n",
400 tag, ktime_to_us(lrbp->issue_time_stamp));
402 "UPIU[%d] - Transfer Request Descriptor phys@0x%llx\n",
403 tag, (u64)lrbp->utrd_dma_addr);
405 ufshcd_hex_dump("UPIU TRD: ", lrbp->utr_descriptor_ptr,
406 sizeof(struct utp_transfer_req_desc));
407 dev_err(hba->dev, "UPIU[%d] - Request UPIU phys@0x%llx\n", tag,
408 (u64)lrbp->ucd_req_dma_addr);
409 ufshcd_hex_dump("UPIU REQ: ", lrbp->ucd_req_ptr,
410 sizeof(struct utp_upiu_req));
411 dev_err(hba->dev, "UPIU[%d] - Response UPIU phys@0x%llx\n", tag,
412 (u64)lrbp->ucd_rsp_dma_addr);
413 ufshcd_hex_dump("UPIU RSP: ", lrbp->ucd_rsp_ptr,
414 sizeof(struct utp_upiu_rsp));
416 prdt_length = le16_to_cpu(
417 lrbp->utr_descriptor_ptr->prd_table_length);
419 "UPIU[%d] - PRDT - %d entries phys@0x%llx\n",
421 (u64)lrbp->ucd_prdt_dma_addr);
424 ufshcd_hex_dump("UPIU PRDT: ", lrbp->ucd_prdt_ptr,
425 sizeof(struct ufshcd_sg_entry) * prdt_length);
429 static void ufshcd_print_tmrs(struct ufs_hba *hba, unsigned long bitmap)
431 struct utp_task_req_desc *tmrdp;
434 for_each_set_bit(tag, &bitmap, hba->nutmrs) {
435 tmrdp = &hba->utmrdl_base_addr[tag];
436 dev_err(hba->dev, "TM[%d] - Task Management Header\n", tag);
437 ufshcd_hex_dump("TM TRD: ", &tmrdp->header,
438 sizeof(struct request_desc_header));
439 dev_err(hba->dev, "TM[%d] - Task Management Request UPIU\n",
441 ufshcd_hex_dump("TM REQ: ", tmrdp->task_req_upiu,
442 sizeof(struct utp_upiu_req));
443 dev_err(hba->dev, "TM[%d] - Task Management Response UPIU\n",
445 ufshcd_hex_dump("TM RSP: ", tmrdp->task_rsp_upiu,
446 sizeof(struct utp_task_req_desc));
450 static void ufshcd_print_host_state(struct ufs_hba *hba)
452 dev_err(hba->dev, "UFS Host state=%d\n", hba->ufshcd_state);
453 dev_err(hba->dev, "lrb in use=0x%lx, outstanding reqs=0x%lx tasks=0x%lx\n",
454 hba->lrb_in_use, hba->outstanding_tasks, hba->outstanding_reqs);
455 dev_err(hba->dev, "saved_err=0x%x, saved_uic_err=0x%x\n",
456 hba->saved_err, hba->saved_uic_err);
457 dev_err(hba->dev, "Device power mode=%d, UIC link state=%d\n",
458 hba->curr_dev_pwr_mode, hba->uic_link_state);
459 dev_err(hba->dev, "PM in progress=%d, sys. suspended=%d\n",
460 hba->pm_op_in_progress, hba->is_sys_suspended);
461 dev_err(hba->dev, "Auto BKOPS=%d, Host self-block=%d\n",
462 hba->auto_bkops_enabled, hba->host->host_self_blocked);
463 dev_err(hba->dev, "Clk gate=%d\n", hba->clk_gating.state);
464 dev_err(hba->dev, "error handling flags=0x%x, req. abort count=%d\n",
465 hba->eh_flags, hba->req_abort_count);
466 dev_err(hba->dev, "Host capabilities=0x%x, caps=0x%x\n",
467 hba->capabilities, hba->caps);
468 dev_err(hba->dev, "quirks=0x%x, dev. quirks=0x%x\n", hba->quirks,
473 * ufshcd_print_pwr_info - print power params as saved in hba
475 * @hba: per-adapter instance
477 static void ufshcd_print_pwr_info(struct ufs_hba *hba)
479 static const char * const names[] = {
489 dev_err(hba->dev, "%s:[RX, TX]: gear=[%d, %d], lane[%d, %d], pwr[%s, %s], rate = %d\n",
491 hba->pwr_info.gear_rx, hba->pwr_info.gear_tx,
492 hba->pwr_info.lane_rx, hba->pwr_info.lane_tx,
493 names[hba->pwr_info.pwr_rx],
494 names[hba->pwr_info.pwr_tx],
495 hba->pwr_info.hs_rate);
499 * ufshcd_wait_for_register - wait for register value to change
500 * @hba - per-adapter interface
501 * @reg - mmio register offset
502 * @mask - mask to apply to read register value
503 * @val - wait condition
504 * @interval_us - polling interval in microsecs
505 * @timeout_ms - timeout in millisecs
506 * @can_sleep - perform sleep or just spin
508 * Returns -ETIMEDOUT on error, zero on success
510 int ufshcd_wait_for_register(struct ufs_hba *hba, u32 reg, u32 mask,
511 u32 val, unsigned long interval_us,
512 unsigned long timeout_ms, bool can_sleep)
515 unsigned long timeout = jiffies + msecs_to_jiffies(timeout_ms);
517 /* ignore bits that we don't intend to wait on */
520 while ((ufshcd_readl(hba, reg) & mask) != val) {
522 usleep_range(interval_us, interval_us + 50);
525 if (time_after(jiffies, timeout)) {
526 if ((ufshcd_readl(hba, reg) & mask) != val)
536 * ufshcd_get_intr_mask - Get the interrupt bit mask
537 * @hba - Pointer to adapter instance
539 * Returns interrupt bit mask per version
541 static inline u32 ufshcd_get_intr_mask(struct ufs_hba *hba)
545 switch (hba->ufs_version) {
546 case UFSHCI_VERSION_10:
547 intr_mask = INTERRUPT_MASK_ALL_VER_10;
549 case UFSHCI_VERSION_11:
550 case UFSHCI_VERSION_20:
551 intr_mask = INTERRUPT_MASK_ALL_VER_11;
553 case UFSHCI_VERSION_21:
555 intr_mask = INTERRUPT_MASK_ALL_VER_21;
563 * ufshcd_get_ufs_version - Get the UFS version supported by the HBA
564 * @hba - Pointer to adapter instance
566 * Returns UFSHCI version supported by the controller
568 static inline u32 ufshcd_get_ufs_version(struct ufs_hba *hba)
570 if (hba->quirks & UFSHCD_QUIRK_BROKEN_UFS_HCI_VERSION)
571 return ufshcd_vops_get_ufs_hci_version(hba);
573 return ufshcd_readl(hba, REG_UFS_VERSION);
577 * ufshcd_is_device_present - Check if any device connected to
578 * the host controller
579 * @hba: pointer to adapter instance
581 * Returns true if device present, false if no device detected
583 static inline bool ufshcd_is_device_present(struct ufs_hba *hba)
585 return (ufshcd_readl(hba, REG_CONTROLLER_STATUS) &
586 DEVICE_PRESENT) ? true : false;
590 * ufshcd_get_tr_ocs - Get the UTRD Overall Command Status
591 * @lrb: pointer to local command reference block
593 * This function is used to get the OCS field from UTRD
594 * Returns the OCS field in the UTRD
596 static inline int ufshcd_get_tr_ocs(struct ufshcd_lrb *lrbp)
598 return le32_to_cpu(lrbp->utr_descriptor_ptr->header.dword_2) & MASK_OCS;
602 * ufshcd_get_tmr_ocs - Get the UTMRD Overall Command Status
603 * @task_req_descp: pointer to utp_task_req_desc structure
605 * This function is used to get the OCS field from UTMRD
606 * Returns the OCS field in the UTMRD
609 ufshcd_get_tmr_ocs(struct utp_task_req_desc *task_req_descp)
611 return le32_to_cpu(task_req_descp->header.dword_2) & MASK_OCS;
615 * ufshcd_get_tm_free_slot - get a free slot for task management request
616 * @hba: per adapter instance
617 * @free_slot: pointer to variable with available slot value
619 * Get a free tag and lock it until ufshcd_put_tm_slot() is called.
620 * Returns 0 if free slot is not available, else return 1 with tag value
623 static bool ufshcd_get_tm_free_slot(struct ufs_hba *hba, int *free_slot)
632 tag = find_first_zero_bit(&hba->tm_slots_in_use, hba->nutmrs);
633 if (tag >= hba->nutmrs)
635 } while (test_and_set_bit_lock(tag, &hba->tm_slots_in_use));
643 static inline void ufshcd_put_tm_slot(struct ufs_hba *hba, int slot)
645 clear_bit_unlock(slot, &hba->tm_slots_in_use);
649 * ufshcd_utrl_clear - Clear a bit in UTRLCLR register
650 * @hba: per adapter instance
651 * @pos: position of the bit to be cleared
653 static inline void ufshcd_utrl_clear(struct ufs_hba *hba, u32 pos)
655 ufshcd_writel(hba, ~(1 << pos), REG_UTP_TRANSFER_REQ_LIST_CLEAR);
659 * ufshcd_outstanding_req_clear - Clear a bit in outstanding request field
660 * @hba: per adapter instance
661 * @tag: position of the bit to be cleared
663 static inline void ufshcd_outstanding_req_clear(struct ufs_hba *hba, int tag)
665 __clear_bit(tag, &hba->outstanding_reqs);
669 * ufshcd_get_lists_status - Check UCRDY, UTRLRDY and UTMRLRDY
670 * @reg: Register value of host controller status
672 * Returns integer, 0 on Success and positive value if failed
674 static inline int ufshcd_get_lists_status(u32 reg)
677 * The mask 0xFF is for the following HCS register bits
685 return ((reg & 0xFF) >> 1) ^ 0x07;
689 * ufshcd_get_uic_cmd_result - Get the UIC command result
690 * @hba: Pointer to adapter instance
692 * This function gets the result of UIC command completion
693 * Returns 0 on success, non zero value on error
695 static inline int ufshcd_get_uic_cmd_result(struct ufs_hba *hba)
697 return ufshcd_readl(hba, REG_UIC_COMMAND_ARG_2) &
698 MASK_UIC_COMMAND_RESULT;
702 * ufshcd_get_dme_attr_val - Get the value of attribute returned by UIC command
703 * @hba: Pointer to adapter instance
705 * This function gets UIC command argument3
706 * Returns 0 on success, non zero value on error
708 static inline u32 ufshcd_get_dme_attr_val(struct ufs_hba *hba)
710 return ufshcd_readl(hba, REG_UIC_COMMAND_ARG_3);
714 * ufshcd_get_req_rsp - returns the TR response transaction type
715 * @ucd_rsp_ptr: pointer to response UPIU
718 ufshcd_get_req_rsp(struct utp_upiu_rsp *ucd_rsp_ptr)
720 return be32_to_cpu(ucd_rsp_ptr->header.dword_0) >> 24;
724 * ufshcd_get_rsp_upiu_result - Get the result from response UPIU
725 * @ucd_rsp_ptr: pointer to response UPIU
727 * This function gets the response status and scsi_status from response UPIU
728 * Returns the response result code.
731 ufshcd_get_rsp_upiu_result(struct utp_upiu_rsp *ucd_rsp_ptr)
733 return be32_to_cpu(ucd_rsp_ptr->header.dword_1) & MASK_RSP_UPIU_RESULT;
737 * ufshcd_get_rsp_upiu_data_seg_len - Get the data segment length
739 * @ucd_rsp_ptr: pointer to response UPIU
741 * Return the data segment length.
743 static inline unsigned int
744 ufshcd_get_rsp_upiu_data_seg_len(struct utp_upiu_rsp *ucd_rsp_ptr)
746 return be32_to_cpu(ucd_rsp_ptr->header.dword_2) &
747 MASK_RSP_UPIU_DATA_SEG_LEN;
751 * ufshcd_is_exception_event - Check if the device raised an exception event
752 * @ucd_rsp_ptr: pointer to response UPIU
754 * The function checks if the device raised an exception event indicated in
755 * the Device Information field of response UPIU.
757 * Returns true if exception is raised, false otherwise.
759 static inline bool ufshcd_is_exception_event(struct utp_upiu_rsp *ucd_rsp_ptr)
761 return be32_to_cpu(ucd_rsp_ptr->header.dword_2) &
762 MASK_RSP_EXCEPTION_EVENT ? true : false;
766 * ufshcd_reset_intr_aggr - Reset interrupt aggregation values.
767 * @hba: per adapter instance
770 ufshcd_reset_intr_aggr(struct ufs_hba *hba)
772 ufshcd_writel(hba, INT_AGGR_ENABLE |
773 INT_AGGR_COUNTER_AND_TIMER_RESET,
774 REG_UTP_TRANSFER_REQ_INT_AGG_CONTROL);
778 * ufshcd_config_intr_aggr - Configure interrupt aggregation values.
779 * @hba: per adapter instance
780 * @cnt: Interrupt aggregation counter threshold
781 * @tmout: Interrupt aggregation timeout value
784 ufshcd_config_intr_aggr(struct ufs_hba *hba, u8 cnt, u8 tmout)
786 ufshcd_writel(hba, INT_AGGR_ENABLE | INT_AGGR_PARAM_WRITE |
787 INT_AGGR_COUNTER_THLD_VAL(cnt) |
788 INT_AGGR_TIMEOUT_VAL(tmout),
789 REG_UTP_TRANSFER_REQ_INT_AGG_CONTROL);
793 * ufshcd_disable_intr_aggr - Disables interrupt aggregation.
794 * @hba: per adapter instance
796 static inline void ufshcd_disable_intr_aggr(struct ufs_hba *hba)
798 ufshcd_writel(hba, 0, REG_UTP_TRANSFER_REQ_INT_AGG_CONTROL);
802 * ufshcd_enable_run_stop_reg - Enable run-stop registers,
803 * When run-stop registers are set to 1, it indicates the
804 * host controller that it can process the requests
805 * @hba: per adapter instance
807 static void ufshcd_enable_run_stop_reg(struct ufs_hba *hba)
809 ufshcd_writel(hba, UTP_TASK_REQ_LIST_RUN_STOP_BIT,
810 REG_UTP_TASK_REQ_LIST_RUN_STOP);
811 ufshcd_writel(hba, UTP_TRANSFER_REQ_LIST_RUN_STOP_BIT,
812 REG_UTP_TRANSFER_REQ_LIST_RUN_STOP);
816 * ufshcd_hba_start - Start controller initialization sequence
817 * @hba: per adapter instance
819 static inline void ufshcd_hba_start(struct ufs_hba *hba)
821 ufshcd_writel(hba, CONTROLLER_ENABLE, REG_CONTROLLER_ENABLE);
825 * ufshcd_is_hba_active - Get controller state
826 * @hba: per adapter instance
828 * Returns false if controller is active, true otherwise
830 static inline bool ufshcd_is_hba_active(struct ufs_hba *hba)
832 return (ufshcd_readl(hba, REG_CONTROLLER_ENABLE) & CONTROLLER_ENABLE)
836 static const char *ufschd_uic_link_state_to_string(
837 enum uic_link_state state)
840 case UIC_LINK_OFF_STATE: return "OFF";
841 case UIC_LINK_ACTIVE_STATE: return "ACTIVE";
842 case UIC_LINK_HIBERN8_STATE: return "HIBERN8";
843 default: return "UNKNOWN";
847 static const char *ufschd_ufs_dev_pwr_mode_to_string(
848 enum ufs_dev_pwr_mode state)
851 case UFS_ACTIVE_PWR_MODE: return "ACTIVE";
852 case UFS_SLEEP_PWR_MODE: return "SLEEP";
853 case UFS_POWERDOWN_PWR_MODE: return "POWERDOWN";
854 default: return "UNKNOWN";
858 u32 ufshcd_get_local_unipro_ver(struct ufs_hba *hba)
860 /* HCI version 1.0 and 1.1 supports UniPro 1.41 */
861 if ((hba->ufs_version == UFSHCI_VERSION_10) ||
862 (hba->ufs_version == UFSHCI_VERSION_11))
863 return UFS_UNIPRO_VER_1_41;
865 return UFS_UNIPRO_VER_1_6;
867 EXPORT_SYMBOL(ufshcd_get_local_unipro_ver);
869 static bool ufshcd_is_unipro_pa_params_tuning_req(struct ufs_hba *hba)
872 * If both host and device support UniPro ver1.6 or later, PA layer
873 * parameters tuning happens during link startup itself.
875 * We can manually tune PA layer parameters if either host or device
876 * doesn't support UniPro ver 1.6 or later. But to keep manual tuning
877 * logic simple, we will only do manual tuning if local unipro version
878 * doesn't support ver1.6 or later.
880 if (ufshcd_get_local_unipro_ver(hba) < UFS_UNIPRO_VER_1_6)
886 static int ufshcd_scale_clks(struct ufs_hba *hba, bool scale_up)
889 struct ufs_clk_info *clki;
890 struct list_head *head = &hba->clk_list_head;
891 ktime_t start = ktime_get();
892 bool clk_state_changed = false;
894 if (!head || list_empty(head))
897 ret = ufshcd_vops_clk_scale_notify(hba, scale_up, PRE_CHANGE);
901 list_for_each_entry(clki, head, list) {
902 if (!IS_ERR_OR_NULL(clki->clk)) {
903 if (scale_up && clki->max_freq) {
904 if (clki->curr_freq == clki->max_freq)
907 clk_state_changed = true;
908 ret = clk_set_rate(clki->clk, clki->max_freq);
910 dev_err(hba->dev, "%s: %s clk set rate(%dHz) failed, %d\n",
911 __func__, clki->name,
912 clki->max_freq, ret);
915 trace_ufshcd_clk_scaling(dev_name(hba->dev),
916 "scaled up", clki->name,
920 clki->curr_freq = clki->max_freq;
922 } else if (!scale_up && clki->min_freq) {
923 if (clki->curr_freq == clki->min_freq)
926 clk_state_changed = true;
927 ret = clk_set_rate(clki->clk, clki->min_freq);
929 dev_err(hba->dev, "%s: %s clk set rate(%dHz) failed, %d\n",
930 __func__, clki->name,
931 clki->min_freq, ret);
934 trace_ufshcd_clk_scaling(dev_name(hba->dev),
935 "scaled down", clki->name,
938 clki->curr_freq = clki->min_freq;
941 dev_dbg(hba->dev, "%s: clk: %s, rate: %lu\n", __func__,
942 clki->name, clk_get_rate(clki->clk));
945 ret = ufshcd_vops_clk_scale_notify(hba, scale_up, POST_CHANGE);
948 if (clk_state_changed)
949 trace_ufshcd_profile_clk_scaling(dev_name(hba->dev),
950 (scale_up ? "up" : "down"),
951 ktime_to_us(ktime_sub(ktime_get(), start)), ret);
956 * ufshcd_is_devfreq_scaling_required - check if scaling is required or not
957 * @hba: per adapter instance
958 * @scale_up: True if scaling up and false if scaling down
960 * Returns true if scaling is required, false otherwise.
962 static bool ufshcd_is_devfreq_scaling_required(struct ufs_hba *hba,
965 struct ufs_clk_info *clki;
966 struct list_head *head = &hba->clk_list_head;
968 if (!head || list_empty(head))
971 list_for_each_entry(clki, head, list) {
972 if (!IS_ERR_OR_NULL(clki->clk)) {
973 if (scale_up && clki->max_freq) {
974 if (clki->curr_freq == clki->max_freq)
977 } else if (!scale_up && clki->min_freq) {
978 if (clki->curr_freq == clki->min_freq)
988 static int ufshcd_wait_for_doorbell_clr(struct ufs_hba *hba,
995 bool timeout = false, do_last_check = false;
998 ufshcd_hold(hba, false);
999 spin_lock_irqsave(hba->host->host_lock, flags);
1001 * Wait for all the outstanding tasks/transfer requests.
1002 * Verify by checking the doorbell registers are clear.
1004 start = ktime_get();
1006 if (hba->ufshcd_state != UFSHCD_STATE_OPERATIONAL) {
1011 tm_doorbell = ufshcd_readl(hba, REG_UTP_TASK_REQ_DOOR_BELL);
1012 tr_doorbell = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
1013 if (!tm_doorbell && !tr_doorbell) {
1016 } else if (do_last_check) {
1020 spin_unlock_irqrestore(hba->host->host_lock, flags);
1022 if (ktime_to_us(ktime_sub(ktime_get(), start)) >
1026 * We might have scheduled out for long time so make
1027 * sure to check if doorbells are cleared by this time
1030 do_last_check = true;
1032 spin_lock_irqsave(hba->host->host_lock, flags);
1033 } while (tm_doorbell || tr_doorbell);
1037 "%s: timedout waiting for doorbell to clear (tm=0x%x, tr=0x%x)\n",
1038 __func__, tm_doorbell, tr_doorbell);
1042 spin_unlock_irqrestore(hba->host->host_lock, flags);
1043 ufshcd_release(hba);
1048 * ufshcd_scale_gear - scale up/down UFS gear
1049 * @hba: per adapter instance
1050 * @scale_up: True for scaling up gear and false for scaling down
1052 * Returns 0 for success,
1053 * Returns -EBUSY if scaling can't happen at this time
1054 * Returns non-zero for any other errors
1056 static int ufshcd_scale_gear(struct ufs_hba *hba, bool scale_up)
1058 #define UFS_MIN_GEAR_TO_SCALE_DOWN UFS_HS_G1
1060 struct ufs_pa_layer_attr new_pwr_info;
1063 memcpy(&new_pwr_info, &hba->clk_scaling.saved_pwr_info.info,
1064 sizeof(struct ufs_pa_layer_attr));
1066 memcpy(&new_pwr_info, &hba->pwr_info,
1067 sizeof(struct ufs_pa_layer_attr));
1069 if (hba->pwr_info.gear_tx > UFS_MIN_GEAR_TO_SCALE_DOWN
1070 || hba->pwr_info.gear_rx > UFS_MIN_GEAR_TO_SCALE_DOWN) {
1071 /* save the current power mode */
1072 memcpy(&hba->clk_scaling.saved_pwr_info.info,
1074 sizeof(struct ufs_pa_layer_attr));
1076 /* scale down gear */
1077 new_pwr_info.gear_tx = UFS_MIN_GEAR_TO_SCALE_DOWN;
1078 new_pwr_info.gear_rx = UFS_MIN_GEAR_TO_SCALE_DOWN;
1082 /* check if the power mode needs to be changed or not? */
1083 ret = ufshcd_change_power_mode(hba, &new_pwr_info);
1086 dev_err(hba->dev, "%s: failed err %d, old gear: (tx %d rx %d), new gear: (tx %d rx %d)",
1088 hba->pwr_info.gear_tx, hba->pwr_info.gear_rx,
1089 new_pwr_info.gear_tx, new_pwr_info.gear_rx);
1094 static int ufshcd_clock_scaling_prepare(struct ufs_hba *hba)
1096 #define DOORBELL_CLR_TOUT_US (1000 * 1000) /* 1 sec */
1099 * make sure that there are no outstanding requests when
1100 * clock scaling is in progress
1102 scsi_block_requests(hba->host);
1103 down_write(&hba->clk_scaling_lock);
1104 if (ufshcd_wait_for_doorbell_clr(hba, DOORBELL_CLR_TOUT_US)) {
1106 up_write(&hba->clk_scaling_lock);
1107 scsi_unblock_requests(hba->host);
1113 static void ufshcd_clock_scaling_unprepare(struct ufs_hba *hba)
1115 up_write(&hba->clk_scaling_lock);
1116 scsi_unblock_requests(hba->host);
1120 * ufshcd_devfreq_scale - scale up/down UFS clocks and gear
1121 * @hba: per adapter instance
1122 * @scale_up: True for scaling up and false for scalin down
1124 * Returns 0 for success,
1125 * Returns -EBUSY if scaling can't happen at this time
1126 * Returns non-zero for any other errors
1128 static int ufshcd_devfreq_scale(struct ufs_hba *hba, bool scale_up)
1132 /* let's not get into low power until clock scaling is completed */
1133 ufshcd_hold(hba, false);
1135 ret = ufshcd_clock_scaling_prepare(hba);
1139 /* scale down the gear before scaling down clocks */
1141 ret = ufshcd_scale_gear(hba, false);
1146 ret = ufshcd_scale_clks(hba, scale_up);
1149 ufshcd_scale_gear(hba, true);
1153 /* scale up the gear after scaling up clocks */
1155 ret = ufshcd_scale_gear(hba, true);
1157 ufshcd_scale_clks(hba, false);
1162 ret = ufshcd_vops_clk_scale_notify(hba, scale_up, POST_CHANGE);
1165 ufshcd_clock_scaling_unprepare(hba);
1166 ufshcd_release(hba);
1170 static void ufshcd_clk_scaling_suspend_work(struct work_struct *work)
1172 struct ufs_hba *hba = container_of(work, struct ufs_hba,
1173 clk_scaling.suspend_work);
1174 unsigned long irq_flags;
1176 spin_lock_irqsave(hba->host->host_lock, irq_flags);
1177 if (hba->clk_scaling.active_reqs || hba->clk_scaling.is_suspended) {
1178 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1181 hba->clk_scaling.is_suspended = true;
1182 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1184 __ufshcd_suspend_clkscaling(hba);
1187 static void ufshcd_clk_scaling_resume_work(struct work_struct *work)
1189 struct ufs_hba *hba = container_of(work, struct ufs_hba,
1190 clk_scaling.resume_work);
1191 unsigned long irq_flags;
1193 spin_lock_irqsave(hba->host->host_lock, irq_flags);
1194 if (!hba->clk_scaling.is_suspended) {
1195 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1198 hba->clk_scaling.is_suspended = false;
1199 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1201 devfreq_resume_device(hba->devfreq);
1204 static int ufshcd_devfreq_target(struct device *dev,
1205 unsigned long *freq, u32 flags)
1208 struct ufs_hba *hba = dev_get_drvdata(dev);
1210 bool scale_up, sched_clk_scaling_suspend_work = false;
1211 unsigned long irq_flags;
1213 if (!ufshcd_is_clkscaling_supported(hba))
1216 if ((*freq > 0) && (*freq < UINT_MAX)) {
1217 dev_err(hba->dev, "%s: invalid freq = %lu\n", __func__, *freq);
1221 spin_lock_irqsave(hba->host->host_lock, irq_flags);
1222 if (ufshcd_eh_in_progress(hba)) {
1223 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1227 if (!hba->clk_scaling.active_reqs)
1228 sched_clk_scaling_suspend_work = true;
1230 scale_up = (*freq == UINT_MAX) ? true : false;
1231 if (!ufshcd_is_devfreq_scaling_required(hba, scale_up)) {
1232 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1234 goto out; /* no state change required */
1236 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1238 start = ktime_get();
1239 ret = ufshcd_devfreq_scale(hba, scale_up);
1241 trace_ufshcd_profile_clk_scaling(dev_name(hba->dev),
1242 (scale_up ? "up" : "down"),
1243 ktime_to_us(ktime_sub(ktime_get(), start)), ret);
1246 if (sched_clk_scaling_suspend_work)
1247 queue_work(hba->clk_scaling.workq,
1248 &hba->clk_scaling.suspend_work);
1254 static int ufshcd_devfreq_get_dev_status(struct device *dev,
1255 struct devfreq_dev_status *stat)
1257 struct ufs_hba *hba = dev_get_drvdata(dev);
1258 struct ufs_clk_scaling *scaling = &hba->clk_scaling;
1259 unsigned long flags;
1261 if (!ufshcd_is_clkscaling_supported(hba))
1264 memset(stat, 0, sizeof(*stat));
1266 spin_lock_irqsave(hba->host->host_lock, flags);
1267 if (!scaling->window_start_t)
1270 if (scaling->is_busy_started)
1271 scaling->tot_busy_t += ktime_to_us(ktime_sub(ktime_get(),
1272 scaling->busy_start_t));
1274 stat->total_time = jiffies_to_usecs((long)jiffies -
1275 (long)scaling->window_start_t);
1276 stat->busy_time = scaling->tot_busy_t;
1278 scaling->window_start_t = jiffies;
1279 scaling->tot_busy_t = 0;
1281 if (hba->outstanding_reqs) {
1282 scaling->busy_start_t = ktime_get();
1283 scaling->is_busy_started = true;
1285 scaling->busy_start_t = 0;
1286 scaling->is_busy_started = false;
1288 spin_unlock_irqrestore(hba->host->host_lock, flags);
1292 static struct devfreq_dev_profile ufs_devfreq_profile = {
1294 .target = ufshcd_devfreq_target,
1295 .get_dev_status = ufshcd_devfreq_get_dev_status,
1298 static void __ufshcd_suspend_clkscaling(struct ufs_hba *hba)
1300 unsigned long flags;
1302 devfreq_suspend_device(hba->devfreq);
1303 spin_lock_irqsave(hba->host->host_lock, flags);
1304 hba->clk_scaling.window_start_t = 0;
1305 spin_unlock_irqrestore(hba->host->host_lock, flags);
1308 static void ufshcd_suspend_clkscaling(struct ufs_hba *hba)
1310 unsigned long flags;
1311 bool suspend = false;
1313 if (!ufshcd_is_clkscaling_supported(hba))
1316 spin_lock_irqsave(hba->host->host_lock, flags);
1317 if (!hba->clk_scaling.is_suspended) {
1319 hba->clk_scaling.is_suspended = true;
1321 spin_unlock_irqrestore(hba->host->host_lock, flags);
1324 __ufshcd_suspend_clkscaling(hba);
1327 static void ufshcd_resume_clkscaling(struct ufs_hba *hba)
1329 unsigned long flags;
1330 bool resume = false;
1332 if (!ufshcd_is_clkscaling_supported(hba))
1335 spin_lock_irqsave(hba->host->host_lock, flags);
1336 if (hba->clk_scaling.is_suspended) {
1338 hba->clk_scaling.is_suspended = false;
1340 spin_unlock_irqrestore(hba->host->host_lock, flags);
1343 devfreq_resume_device(hba->devfreq);
1346 static ssize_t ufshcd_clkscale_enable_show(struct device *dev,
1347 struct device_attribute *attr, char *buf)
1349 struct ufs_hba *hba = dev_get_drvdata(dev);
1351 return snprintf(buf, PAGE_SIZE, "%d\n", hba->clk_scaling.is_allowed);
1354 static ssize_t ufshcd_clkscale_enable_store(struct device *dev,
1355 struct device_attribute *attr, const char *buf, size_t count)
1357 struct ufs_hba *hba = dev_get_drvdata(dev);
1361 if (kstrtou32(buf, 0, &value))
1365 if (value == hba->clk_scaling.is_allowed)
1368 pm_runtime_get_sync(hba->dev);
1369 ufshcd_hold(hba, false);
1371 cancel_work_sync(&hba->clk_scaling.suspend_work);
1372 cancel_work_sync(&hba->clk_scaling.resume_work);
1374 hba->clk_scaling.is_allowed = value;
1377 ufshcd_resume_clkscaling(hba);
1379 ufshcd_suspend_clkscaling(hba);
1380 err = ufshcd_devfreq_scale(hba, true);
1382 dev_err(hba->dev, "%s: failed to scale clocks up %d\n",
1386 ufshcd_release(hba);
1387 pm_runtime_put_sync(hba->dev);
1392 static void ufshcd_clkscaling_init_sysfs(struct ufs_hba *hba)
1394 hba->clk_scaling.enable_attr.show = ufshcd_clkscale_enable_show;
1395 hba->clk_scaling.enable_attr.store = ufshcd_clkscale_enable_store;
1396 sysfs_attr_init(&hba->clk_scaling.enable_attr.attr);
1397 hba->clk_scaling.enable_attr.attr.name = "clkscale_enable";
1398 hba->clk_scaling.enable_attr.attr.mode = 0644;
1399 if (device_create_file(hba->dev, &hba->clk_scaling.enable_attr))
1400 dev_err(hba->dev, "Failed to create sysfs for clkscale_enable\n");
1403 static void ufshcd_ungate_work(struct work_struct *work)
1406 unsigned long flags;
1407 struct ufs_hba *hba = container_of(work, struct ufs_hba,
1408 clk_gating.ungate_work);
1410 cancel_delayed_work_sync(&hba->clk_gating.gate_work);
1412 spin_lock_irqsave(hba->host->host_lock, flags);
1413 if (hba->clk_gating.state == CLKS_ON) {
1414 spin_unlock_irqrestore(hba->host->host_lock, flags);
1418 spin_unlock_irqrestore(hba->host->host_lock, flags);
1419 ufshcd_setup_clocks(hba, true);
1421 /* Exit from hibern8 */
1422 if (ufshcd_can_hibern8_during_gating(hba)) {
1423 /* Prevent gating in this path */
1424 hba->clk_gating.is_suspended = true;
1425 if (ufshcd_is_link_hibern8(hba)) {
1426 ret = ufshcd_uic_hibern8_exit(hba);
1428 dev_err(hba->dev, "%s: hibern8 exit failed %d\n",
1431 ufshcd_set_link_active(hba);
1433 hba->clk_gating.is_suspended = false;
1436 scsi_unblock_requests(hba->host);
1440 * ufshcd_hold - Enable clocks that were gated earlier due to ufshcd_release.
1441 * Also, exit from hibern8 mode and set the link as active.
1442 * @hba: per adapter instance
1443 * @async: This indicates whether caller should ungate clocks asynchronously.
1445 int ufshcd_hold(struct ufs_hba *hba, bool async)
1448 unsigned long flags;
1450 if (!ufshcd_is_clkgating_allowed(hba))
1452 spin_lock_irqsave(hba->host->host_lock, flags);
1453 hba->clk_gating.active_reqs++;
1455 if (ufshcd_eh_in_progress(hba)) {
1456 spin_unlock_irqrestore(hba->host->host_lock, flags);
1461 switch (hba->clk_gating.state) {
1464 * Wait for the ungate work to complete if in progress.
1465 * Though the clocks may be in ON state, the link could
1466 * still be in hibner8 state if hibern8 is allowed
1467 * during clock gating.
1468 * Make sure we exit hibern8 state also in addition to
1471 if (ufshcd_can_hibern8_during_gating(hba) &&
1472 ufshcd_is_link_hibern8(hba)) {
1473 spin_unlock_irqrestore(hba->host->host_lock, flags);
1474 flush_work(&hba->clk_gating.ungate_work);
1475 spin_lock_irqsave(hba->host->host_lock, flags);
1480 if (cancel_delayed_work(&hba->clk_gating.gate_work)) {
1481 hba->clk_gating.state = CLKS_ON;
1482 trace_ufshcd_clk_gating(dev_name(hba->dev),
1483 hba->clk_gating.state);
1487 * If we are here, it means gating work is either done or
1488 * currently running. Hence, fall through to cancel gating
1489 * work and to enable clocks.
1492 scsi_block_requests(hba->host);
1493 hba->clk_gating.state = REQ_CLKS_ON;
1494 trace_ufshcd_clk_gating(dev_name(hba->dev),
1495 hba->clk_gating.state);
1496 schedule_work(&hba->clk_gating.ungate_work);
1498 * fall through to check if we should wait for this
1499 * work to be done or not.
1504 hba->clk_gating.active_reqs--;
1508 spin_unlock_irqrestore(hba->host->host_lock, flags);
1509 flush_work(&hba->clk_gating.ungate_work);
1510 /* Make sure state is CLKS_ON before returning */
1511 spin_lock_irqsave(hba->host->host_lock, flags);
1514 dev_err(hba->dev, "%s: clk gating is in invalid state %d\n",
1515 __func__, hba->clk_gating.state);
1518 spin_unlock_irqrestore(hba->host->host_lock, flags);
1522 EXPORT_SYMBOL_GPL(ufshcd_hold);
1524 static void ufshcd_gate_work(struct work_struct *work)
1526 struct ufs_hba *hba = container_of(work, struct ufs_hba,
1527 clk_gating.gate_work.work);
1528 unsigned long flags;
1530 spin_lock_irqsave(hba->host->host_lock, flags);
1532 * In case you are here to cancel this work the gating state
1533 * would be marked as REQ_CLKS_ON. In this case save time by
1534 * skipping the gating work and exit after changing the clock
1537 if (hba->clk_gating.is_suspended ||
1538 (hba->clk_gating.state == REQ_CLKS_ON)) {
1539 hba->clk_gating.state = CLKS_ON;
1540 trace_ufshcd_clk_gating(dev_name(hba->dev),
1541 hba->clk_gating.state);
1545 if (hba->clk_gating.active_reqs
1546 || hba->ufshcd_state != UFSHCD_STATE_OPERATIONAL
1547 || hba->lrb_in_use || hba->outstanding_tasks
1548 || hba->active_uic_cmd || hba->uic_async_done)
1551 spin_unlock_irqrestore(hba->host->host_lock, flags);
1553 /* put the link into hibern8 mode before turning off clocks */
1554 if (ufshcd_can_hibern8_during_gating(hba)) {
1555 if (ufshcd_uic_hibern8_enter(hba)) {
1556 hba->clk_gating.state = CLKS_ON;
1557 trace_ufshcd_clk_gating(dev_name(hba->dev),
1558 hba->clk_gating.state);
1561 ufshcd_set_link_hibern8(hba);
1564 if (!ufshcd_is_link_active(hba))
1565 ufshcd_setup_clocks(hba, false);
1567 /* If link is active, device ref_clk can't be switched off */
1568 __ufshcd_setup_clocks(hba, false, true);
1571 * In case you are here to cancel this work the gating state
1572 * would be marked as REQ_CLKS_ON. In this case keep the state
1573 * as REQ_CLKS_ON which would anyway imply that clocks are off
1574 * and a request to turn them on is pending. By doing this way,
1575 * we keep the state machine in tact and this would ultimately
1576 * prevent from doing cancel work multiple times when there are
1577 * new requests arriving before the current cancel work is done.
1579 spin_lock_irqsave(hba->host->host_lock, flags);
1580 if (hba->clk_gating.state == REQ_CLKS_OFF) {
1581 hba->clk_gating.state = CLKS_OFF;
1582 trace_ufshcd_clk_gating(dev_name(hba->dev),
1583 hba->clk_gating.state);
1586 spin_unlock_irqrestore(hba->host->host_lock, flags);
1591 /* host lock must be held before calling this variant */
1592 static void __ufshcd_release(struct ufs_hba *hba)
1594 if (!ufshcd_is_clkgating_allowed(hba))
1597 hba->clk_gating.active_reqs--;
1599 if (hba->clk_gating.active_reqs || hba->clk_gating.is_suspended
1600 || hba->ufshcd_state != UFSHCD_STATE_OPERATIONAL
1601 || hba->lrb_in_use || hba->outstanding_tasks
1602 || hba->active_uic_cmd || hba->uic_async_done
1603 || ufshcd_eh_in_progress(hba))
1606 hba->clk_gating.state = REQ_CLKS_OFF;
1607 trace_ufshcd_clk_gating(dev_name(hba->dev), hba->clk_gating.state);
1608 schedule_delayed_work(&hba->clk_gating.gate_work,
1609 msecs_to_jiffies(hba->clk_gating.delay_ms));
1612 void ufshcd_release(struct ufs_hba *hba)
1614 unsigned long flags;
1616 spin_lock_irqsave(hba->host->host_lock, flags);
1617 __ufshcd_release(hba);
1618 spin_unlock_irqrestore(hba->host->host_lock, flags);
1620 EXPORT_SYMBOL_GPL(ufshcd_release);
1622 static ssize_t ufshcd_clkgate_delay_show(struct device *dev,
1623 struct device_attribute *attr, char *buf)
1625 struct ufs_hba *hba = dev_get_drvdata(dev);
1627 return snprintf(buf, PAGE_SIZE, "%lu\n", hba->clk_gating.delay_ms);
1630 static ssize_t ufshcd_clkgate_delay_store(struct device *dev,
1631 struct device_attribute *attr, const char *buf, size_t count)
1633 struct ufs_hba *hba = dev_get_drvdata(dev);
1634 unsigned long flags, value;
1636 if (kstrtoul(buf, 0, &value))
1639 spin_lock_irqsave(hba->host->host_lock, flags);
1640 hba->clk_gating.delay_ms = value;
1641 spin_unlock_irqrestore(hba->host->host_lock, flags);
1645 static ssize_t ufshcd_clkgate_enable_show(struct device *dev,
1646 struct device_attribute *attr, char *buf)
1648 struct ufs_hba *hba = dev_get_drvdata(dev);
1650 return snprintf(buf, PAGE_SIZE, "%d\n", hba->clk_gating.is_enabled);
1653 static ssize_t ufshcd_clkgate_enable_store(struct device *dev,
1654 struct device_attribute *attr, const char *buf, size_t count)
1656 struct ufs_hba *hba = dev_get_drvdata(dev);
1657 unsigned long flags;
1660 if (kstrtou32(buf, 0, &value))
1664 if (value == hba->clk_gating.is_enabled)
1668 ufshcd_release(hba);
1670 spin_lock_irqsave(hba->host->host_lock, flags);
1671 hba->clk_gating.active_reqs++;
1672 spin_unlock_irqrestore(hba->host->host_lock, flags);
1675 hba->clk_gating.is_enabled = value;
1680 static void ufshcd_init_clk_gating(struct ufs_hba *hba)
1682 if (!ufshcd_is_clkgating_allowed(hba))
1685 hba->clk_gating.delay_ms = 150;
1686 INIT_DELAYED_WORK(&hba->clk_gating.gate_work, ufshcd_gate_work);
1687 INIT_WORK(&hba->clk_gating.ungate_work, ufshcd_ungate_work);
1689 hba->clk_gating.is_enabled = true;
1691 hba->clk_gating.delay_attr.show = ufshcd_clkgate_delay_show;
1692 hba->clk_gating.delay_attr.store = ufshcd_clkgate_delay_store;
1693 sysfs_attr_init(&hba->clk_gating.delay_attr.attr);
1694 hba->clk_gating.delay_attr.attr.name = "clkgate_delay_ms";
1695 hba->clk_gating.delay_attr.attr.mode = 0644;
1696 if (device_create_file(hba->dev, &hba->clk_gating.delay_attr))
1697 dev_err(hba->dev, "Failed to create sysfs for clkgate_delay\n");
1699 hba->clk_gating.enable_attr.show = ufshcd_clkgate_enable_show;
1700 hba->clk_gating.enable_attr.store = ufshcd_clkgate_enable_store;
1701 sysfs_attr_init(&hba->clk_gating.enable_attr.attr);
1702 hba->clk_gating.enable_attr.attr.name = "clkgate_enable";
1703 hba->clk_gating.enable_attr.attr.mode = 0644;
1704 if (device_create_file(hba->dev, &hba->clk_gating.enable_attr))
1705 dev_err(hba->dev, "Failed to create sysfs for clkgate_enable\n");
1708 static void ufshcd_exit_clk_gating(struct ufs_hba *hba)
1710 if (!ufshcd_is_clkgating_allowed(hba))
1712 device_remove_file(hba->dev, &hba->clk_gating.delay_attr);
1713 device_remove_file(hba->dev, &hba->clk_gating.enable_attr);
1714 cancel_work_sync(&hba->clk_gating.ungate_work);
1715 cancel_delayed_work_sync(&hba->clk_gating.gate_work);
1718 /* Must be called with host lock acquired */
1719 static void ufshcd_clk_scaling_start_busy(struct ufs_hba *hba)
1721 bool queue_resume_work = false;
1723 if (!ufshcd_is_clkscaling_supported(hba))
1726 if (!hba->clk_scaling.active_reqs++)
1727 queue_resume_work = true;
1729 if (!hba->clk_scaling.is_allowed || hba->pm_op_in_progress)
1732 if (queue_resume_work)
1733 queue_work(hba->clk_scaling.workq,
1734 &hba->clk_scaling.resume_work);
1736 if (!hba->clk_scaling.window_start_t) {
1737 hba->clk_scaling.window_start_t = jiffies;
1738 hba->clk_scaling.tot_busy_t = 0;
1739 hba->clk_scaling.is_busy_started = false;
1742 if (!hba->clk_scaling.is_busy_started) {
1743 hba->clk_scaling.busy_start_t = ktime_get();
1744 hba->clk_scaling.is_busy_started = true;
1748 static void ufshcd_clk_scaling_update_busy(struct ufs_hba *hba)
1750 struct ufs_clk_scaling *scaling = &hba->clk_scaling;
1752 if (!ufshcd_is_clkscaling_supported(hba))
1755 if (!hba->outstanding_reqs && scaling->is_busy_started) {
1756 scaling->tot_busy_t += ktime_to_us(ktime_sub(ktime_get(),
1757 scaling->busy_start_t));
1758 scaling->busy_start_t = 0;
1759 scaling->is_busy_started = false;
1763 * ufshcd_send_command - Send SCSI or device management commands
1764 * @hba: per adapter instance
1765 * @task_tag: Task tag of the command
1768 void ufshcd_send_command(struct ufs_hba *hba, unsigned int task_tag)
1770 hba->lrb[task_tag].issue_time_stamp = ktime_get();
1771 ufshcd_clk_scaling_start_busy(hba);
1772 __set_bit(task_tag, &hba->outstanding_reqs);
1773 ufshcd_writel(hba, 1 << task_tag, REG_UTP_TRANSFER_REQ_DOOR_BELL);
1774 /* Make sure that doorbell is committed immediately */
1776 ufshcd_add_command_trace(hba, task_tag, "send");
1780 * ufshcd_copy_sense_data - Copy sense data in case of check condition
1781 * @lrb - pointer to local reference block
1783 static inline void ufshcd_copy_sense_data(struct ufshcd_lrb *lrbp)
1786 if (lrbp->sense_buffer &&
1787 ufshcd_get_rsp_upiu_data_seg_len(lrbp->ucd_rsp_ptr)) {
1790 len = be16_to_cpu(lrbp->ucd_rsp_ptr->sr.sense_data_len);
1791 len_to_copy = min_t(int, RESPONSE_UPIU_SENSE_DATA_LENGTH, len);
1793 memcpy(lrbp->sense_buffer,
1794 lrbp->ucd_rsp_ptr->sr.sense_data,
1795 min_t(int, len_to_copy, UFSHCD_REQ_SENSE_SIZE));
1800 * ufshcd_copy_query_response() - Copy the Query Response and the data
1802 * @hba: per adapter instance
1803 * @lrb - pointer to local reference block
1806 int ufshcd_copy_query_response(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
1808 struct ufs_query_res *query_res = &hba->dev_cmd.query.response;
1810 memcpy(&query_res->upiu_res, &lrbp->ucd_rsp_ptr->qr, QUERY_OSF_SIZE);
1812 /* Get the descriptor */
1813 if (lrbp->ucd_rsp_ptr->qr.opcode == UPIU_QUERY_OPCODE_READ_DESC) {
1814 u8 *descp = (u8 *)lrbp->ucd_rsp_ptr +
1815 GENERAL_UPIU_REQUEST_SIZE;
1819 /* data segment length */
1820 resp_len = be32_to_cpu(lrbp->ucd_rsp_ptr->header.dword_2) &
1821 MASK_QUERY_DATA_SEG_LEN;
1822 buf_len = be16_to_cpu(
1823 hba->dev_cmd.query.request.upiu_req.length);
1824 if (likely(buf_len >= resp_len)) {
1825 memcpy(hba->dev_cmd.query.descriptor, descp, resp_len);
1828 "%s: Response size is bigger than buffer",
1838 * ufshcd_hba_capabilities - Read controller capabilities
1839 * @hba: per adapter instance
1841 static inline void ufshcd_hba_capabilities(struct ufs_hba *hba)
1843 hba->capabilities = ufshcd_readl(hba, REG_CONTROLLER_CAPABILITIES);
1845 /* nutrs and nutmrs are 0 based values */
1846 hba->nutrs = (hba->capabilities & MASK_TRANSFER_REQUESTS_SLOTS) + 1;
1848 ((hba->capabilities & MASK_TASK_MANAGEMENT_REQUEST_SLOTS) >> 16) + 1;
1852 * ufshcd_ready_for_uic_cmd - Check if controller is ready
1853 * to accept UIC commands
1854 * @hba: per adapter instance
1855 * Return true on success, else false
1857 static inline bool ufshcd_ready_for_uic_cmd(struct ufs_hba *hba)
1859 if (ufshcd_readl(hba, REG_CONTROLLER_STATUS) & UIC_COMMAND_READY)
1866 * ufshcd_get_upmcrs - Get the power mode change request status
1867 * @hba: Pointer to adapter instance
1869 * This function gets the UPMCRS field of HCS register
1870 * Returns value of UPMCRS field
1872 static inline u8 ufshcd_get_upmcrs(struct ufs_hba *hba)
1874 return (ufshcd_readl(hba, REG_CONTROLLER_STATUS) >> 8) & 0x7;
1878 * ufshcd_dispatch_uic_cmd - Dispatch UIC commands to unipro layers
1879 * @hba: per adapter instance
1880 * @uic_cmd: UIC command
1882 * Mutex must be held.
1885 ufshcd_dispatch_uic_cmd(struct ufs_hba *hba, struct uic_command *uic_cmd)
1887 WARN_ON(hba->active_uic_cmd);
1889 hba->active_uic_cmd = uic_cmd;
1892 ufshcd_writel(hba, uic_cmd->argument1, REG_UIC_COMMAND_ARG_1);
1893 ufshcd_writel(hba, uic_cmd->argument2, REG_UIC_COMMAND_ARG_2);
1894 ufshcd_writel(hba, uic_cmd->argument3, REG_UIC_COMMAND_ARG_3);
1897 ufshcd_writel(hba, uic_cmd->command & COMMAND_OPCODE_MASK,
1902 * ufshcd_wait_for_uic_cmd - Wait complectioin of UIC command
1903 * @hba: per adapter instance
1904 * @uic_command: UIC command
1906 * Must be called with mutex held.
1907 * Returns 0 only if success.
1910 ufshcd_wait_for_uic_cmd(struct ufs_hba *hba, struct uic_command *uic_cmd)
1913 unsigned long flags;
1915 if (wait_for_completion_timeout(&uic_cmd->done,
1916 msecs_to_jiffies(UIC_CMD_TIMEOUT)))
1917 ret = uic_cmd->argument2 & MASK_UIC_COMMAND_RESULT;
1921 spin_lock_irqsave(hba->host->host_lock, flags);
1922 hba->active_uic_cmd = NULL;
1923 spin_unlock_irqrestore(hba->host->host_lock, flags);
1929 * __ufshcd_send_uic_cmd - Send UIC commands and retrieve the result
1930 * @hba: per adapter instance
1931 * @uic_cmd: UIC command
1932 * @completion: initialize the completion only if this is set to true
1934 * Identical to ufshcd_send_uic_cmd() expect mutex. Must be called
1935 * with mutex held and host_lock locked.
1936 * Returns 0 only if success.
1939 __ufshcd_send_uic_cmd(struct ufs_hba *hba, struct uic_command *uic_cmd,
1942 if (!ufshcd_ready_for_uic_cmd(hba)) {
1944 "Controller not ready to accept UIC commands\n");
1949 init_completion(&uic_cmd->done);
1951 ufshcd_dispatch_uic_cmd(hba, uic_cmd);
1957 * ufshcd_send_uic_cmd - Send UIC commands and retrieve the result
1958 * @hba: per adapter instance
1959 * @uic_cmd: UIC command
1961 * Returns 0 only if success.
1964 ufshcd_send_uic_cmd(struct ufs_hba *hba, struct uic_command *uic_cmd)
1967 unsigned long flags;
1969 ufshcd_hold(hba, false);
1970 mutex_lock(&hba->uic_cmd_mutex);
1971 ufshcd_add_delay_before_dme_cmd(hba);
1973 spin_lock_irqsave(hba->host->host_lock, flags);
1974 ret = __ufshcd_send_uic_cmd(hba, uic_cmd, true);
1975 spin_unlock_irqrestore(hba->host->host_lock, flags);
1977 ret = ufshcd_wait_for_uic_cmd(hba, uic_cmd);
1979 mutex_unlock(&hba->uic_cmd_mutex);
1981 ufshcd_release(hba);
1986 * ufshcd_map_sg - Map scatter-gather list to prdt
1987 * @lrbp - pointer to local reference block
1989 * Returns 0 in case of success, non-zero value in case of failure
1991 static int ufshcd_map_sg(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
1993 struct ufshcd_sg_entry *prd_table;
1994 struct scatterlist *sg;
1995 struct scsi_cmnd *cmd;
2000 sg_segments = scsi_dma_map(cmd);
2001 if (sg_segments < 0)
2005 if (hba->quirks & UFSHCD_QUIRK_PRDT_BYTE_GRAN)
2006 lrbp->utr_descriptor_ptr->prd_table_length =
2007 cpu_to_le16((u16)(sg_segments *
2008 sizeof(struct ufshcd_sg_entry)));
2010 lrbp->utr_descriptor_ptr->prd_table_length =
2011 cpu_to_le16((u16) (sg_segments));
2013 prd_table = (struct ufshcd_sg_entry *)lrbp->ucd_prdt_ptr;
2015 scsi_for_each_sg(cmd, sg, sg_segments, i) {
2017 cpu_to_le32(((u32) sg_dma_len(sg))-1);
2018 prd_table[i].base_addr =
2019 cpu_to_le32(lower_32_bits(sg->dma_address));
2020 prd_table[i].upper_addr =
2021 cpu_to_le32(upper_32_bits(sg->dma_address));
2022 prd_table[i].reserved = 0;
2025 lrbp->utr_descriptor_ptr->prd_table_length = 0;
2032 * ufshcd_enable_intr - enable interrupts
2033 * @hba: per adapter instance
2034 * @intrs: interrupt bits
2036 static void ufshcd_enable_intr(struct ufs_hba *hba, u32 intrs)
2038 u32 set = ufshcd_readl(hba, REG_INTERRUPT_ENABLE);
2040 if (hba->ufs_version == UFSHCI_VERSION_10) {
2042 rw = set & INTERRUPT_MASK_RW_VER_10;
2043 set = rw | ((set ^ intrs) & intrs);
2048 ufshcd_writel(hba, set, REG_INTERRUPT_ENABLE);
2052 * ufshcd_disable_intr - disable interrupts
2053 * @hba: per adapter instance
2054 * @intrs: interrupt bits
2056 static void ufshcd_disable_intr(struct ufs_hba *hba, u32 intrs)
2058 u32 set = ufshcd_readl(hba, REG_INTERRUPT_ENABLE);
2060 if (hba->ufs_version == UFSHCI_VERSION_10) {
2062 rw = (set & INTERRUPT_MASK_RW_VER_10) &
2063 ~(intrs & INTERRUPT_MASK_RW_VER_10);
2064 set = rw | ((set & intrs) & ~INTERRUPT_MASK_RW_VER_10);
2070 ufshcd_writel(hba, set, REG_INTERRUPT_ENABLE);
2074 * ufshcd_prepare_req_desc_hdr() - Fills the requests header
2075 * descriptor according to request
2076 * @lrbp: pointer to local reference block
2077 * @upiu_flags: flags required in the header
2078 * @cmd_dir: requests data direction
2080 static void ufshcd_prepare_req_desc_hdr(struct ufshcd_lrb *lrbp,
2081 u32 *upiu_flags, enum dma_data_direction cmd_dir)
2083 struct utp_transfer_req_desc *req_desc = lrbp->utr_descriptor_ptr;
2087 if (cmd_dir == DMA_FROM_DEVICE) {
2088 data_direction = UTP_DEVICE_TO_HOST;
2089 *upiu_flags = UPIU_CMD_FLAGS_READ;
2090 } else if (cmd_dir == DMA_TO_DEVICE) {
2091 data_direction = UTP_HOST_TO_DEVICE;
2092 *upiu_flags = UPIU_CMD_FLAGS_WRITE;
2094 data_direction = UTP_NO_DATA_TRANSFER;
2095 *upiu_flags = UPIU_CMD_FLAGS_NONE;
2098 dword_0 = data_direction | (lrbp->command_type
2099 << UPIU_COMMAND_TYPE_OFFSET);
2101 dword_0 |= UTP_REQ_DESC_INT_CMD;
2103 /* Transfer request descriptor header fields */
2104 req_desc->header.dword_0 = cpu_to_le32(dword_0);
2105 /* dword_1 is reserved, hence it is set to 0 */
2106 req_desc->header.dword_1 = 0;
2108 * assigning invalid value for command status. Controller
2109 * updates OCS on command completion, with the command
2112 req_desc->header.dword_2 =
2113 cpu_to_le32(OCS_INVALID_COMMAND_STATUS);
2114 /* dword_3 is reserved, hence it is set to 0 */
2115 req_desc->header.dword_3 = 0;
2117 req_desc->prd_table_length = 0;
2121 * ufshcd_prepare_utp_scsi_cmd_upiu() - fills the utp_transfer_req_desc,
2123 * @lrbp - local reference block pointer
2124 * @upiu_flags - flags
2127 void ufshcd_prepare_utp_scsi_cmd_upiu(struct ufshcd_lrb *lrbp, u32 upiu_flags)
2129 struct utp_upiu_req *ucd_req_ptr = lrbp->ucd_req_ptr;
2130 unsigned short cdb_len;
2132 /* command descriptor fields */
2133 ucd_req_ptr->header.dword_0 = UPIU_HEADER_DWORD(
2134 UPIU_TRANSACTION_COMMAND, upiu_flags,
2135 lrbp->lun, lrbp->task_tag);
2136 ucd_req_ptr->header.dword_1 = UPIU_HEADER_DWORD(
2137 UPIU_COMMAND_SET_TYPE_SCSI, 0, 0, 0);
2139 /* Total EHS length and Data segment length will be zero */
2140 ucd_req_ptr->header.dword_2 = 0;
2142 ucd_req_ptr->sc.exp_data_transfer_len =
2143 cpu_to_be32(lrbp->cmd->sdb.length);
2145 cdb_len = min_t(unsigned short, lrbp->cmd->cmd_len, MAX_CDB_SIZE);
2146 memset(ucd_req_ptr->sc.cdb, 0, MAX_CDB_SIZE);
2147 memcpy(ucd_req_ptr->sc.cdb, lrbp->cmd->cmnd, cdb_len);
2149 memset(lrbp->ucd_rsp_ptr, 0, sizeof(struct utp_upiu_rsp));
2153 * ufshcd_prepare_utp_query_req_upiu() - fills the utp_transfer_req_desc,
2156 * @lrbp: local reference block pointer
2157 * @upiu_flags: flags
2159 static void ufshcd_prepare_utp_query_req_upiu(struct ufs_hba *hba,
2160 struct ufshcd_lrb *lrbp, u32 upiu_flags)
2162 struct utp_upiu_req *ucd_req_ptr = lrbp->ucd_req_ptr;
2163 struct ufs_query *query = &hba->dev_cmd.query;
2164 u16 len = be16_to_cpu(query->request.upiu_req.length);
2165 u8 *descp = (u8 *)lrbp->ucd_req_ptr + GENERAL_UPIU_REQUEST_SIZE;
2167 /* Query request header */
2168 ucd_req_ptr->header.dword_0 = UPIU_HEADER_DWORD(
2169 UPIU_TRANSACTION_QUERY_REQ, upiu_flags,
2170 lrbp->lun, lrbp->task_tag);
2171 ucd_req_ptr->header.dword_1 = UPIU_HEADER_DWORD(
2172 0, query->request.query_func, 0, 0);
2174 /* Data segment length only need for WRITE_DESC */
2175 if (query->request.upiu_req.opcode == UPIU_QUERY_OPCODE_WRITE_DESC)
2176 ucd_req_ptr->header.dword_2 =
2177 UPIU_HEADER_DWORD(0, 0, (len >> 8), (u8)len);
2179 ucd_req_ptr->header.dword_2 = 0;
2181 /* Copy the Query Request buffer as is */
2182 memcpy(&ucd_req_ptr->qr, &query->request.upiu_req,
2185 /* Copy the Descriptor */
2186 if (query->request.upiu_req.opcode == UPIU_QUERY_OPCODE_WRITE_DESC)
2187 memcpy(descp, query->descriptor, len);
2189 memset(lrbp->ucd_rsp_ptr, 0, sizeof(struct utp_upiu_rsp));
2192 static inline void ufshcd_prepare_utp_nop_upiu(struct ufshcd_lrb *lrbp)
2194 struct utp_upiu_req *ucd_req_ptr = lrbp->ucd_req_ptr;
2196 memset(ucd_req_ptr, 0, sizeof(struct utp_upiu_req));
2198 /* command descriptor fields */
2199 ucd_req_ptr->header.dword_0 =
2201 UPIU_TRANSACTION_NOP_OUT, 0, 0, lrbp->task_tag);
2202 /* clear rest of the fields of basic header */
2203 ucd_req_ptr->header.dword_1 = 0;
2204 ucd_req_ptr->header.dword_2 = 0;
2206 memset(lrbp->ucd_rsp_ptr, 0, sizeof(struct utp_upiu_rsp));
2210 * ufshcd_comp_devman_upiu - UFS Protocol Information Unit(UPIU)
2211 * for Device Management Purposes
2212 * @hba - per adapter instance
2213 * @lrb - pointer to local reference block
2215 static int ufshcd_comp_devman_upiu(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
2220 if (hba->ufs_version == UFSHCI_VERSION_20)
2221 lrbp->command_type = UTP_CMD_TYPE_UFS_STORAGE;
2223 lrbp->command_type = UTP_CMD_TYPE_DEV_MANAGE;
2225 ufshcd_prepare_req_desc_hdr(lrbp, &upiu_flags, DMA_NONE);
2226 if (hba->dev_cmd.type == DEV_CMD_TYPE_QUERY)
2227 ufshcd_prepare_utp_query_req_upiu(hba, lrbp, upiu_flags);
2228 else if (hba->dev_cmd.type == DEV_CMD_TYPE_NOP)
2229 ufshcd_prepare_utp_nop_upiu(lrbp);
2237 * ufshcd_comp_scsi_upiu - UFS Protocol Information Unit(UPIU)
2239 * @hba - per adapter instance
2240 * @lrb - pointer to local reference block
2242 static int ufshcd_comp_scsi_upiu(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
2247 if (hba->ufs_version == UFSHCI_VERSION_20)
2248 lrbp->command_type = UTP_CMD_TYPE_UFS_STORAGE;
2250 lrbp->command_type = UTP_CMD_TYPE_SCSI;
2252 if (likely(lrbp->cmd)) {
2253 ufshcd_prepare_req_desc_hdr(lrbp, &upiu_flags,
2254 lrbp->cmd->sc_data_direction);
2255 ufshcd_prepare_utp_scsi_cmd_upiu(lrbp, upiu_flags);
2264 * ufshcd_scsi_to_upiu_lun - maps scsi LUN to UPIU LUN
2265 * @scsi_lun: scsi LUN id
2267 * Returns UPIU LUN id
2269 static inline u8 ufshcd_scsi_to_upiu_lun(unsigned int scsi_lun)
2271 if (scsi_is_wlun(scsi_lun))
2272 return (scsi_lun & UFS_UPIU_MAX_UNIT_NUM_ID)
2275 return scsi_lun & UFS_UPIU_MAX_UNIT_NUM_ID;
2279 * ufshcd_upiu_wlun_to_scsi_wlun - maps UPIU W-LUN id to SCSI W-LUN ID
2280 * @scsi_lun: UPIU W-LUN id
2282 * Returns SCSI W-LUN id
2284 static inline u16 ufshcd_upiu_wlun_to_scsi_wlun(u8 upiu_wlun_id)
2286 return (upiu_wlun_id & ~UFS_UPIU_WLUN_ID) | SCSI_W_LUN_BASE;
2290 * ufshcd_queuecommand - main entry point for SCSI requests
2291 * @cmd: command from SCSI Midlayer
2292 * @done: call back function
2294 * Returns 0 for success, non-zero in case of failure
2296 static int ufshcd_queuecommand(struct Scsi_Host *host, struct scsi_cmnd *cmd)
2298 struct ufshcd_lrb *lrbp;
2299 struct ufs_hba *hba;
2300 unsigned long flags;
2304 hba = shost_priv(host);
2306 tag = cmd->request->tag;
2307 if (!ufshcd_valid_tag(hba, tag)) {
2309 "%s: invalid command tag %d: cmd=0x%p, cmd->request=0x%p",
2310 __func__, tag, cmd, cmd->request);
2314 if (!down_read_trylock(&hba->clk_scaling_lock))
2315 return SCSI_MLQUEUE_HOST_BUSY;
2317 spin_lock_irqsave(hba->host->host_lock, flags);
2318 switch (hba->ufshcd_state) {
2319 case UFSHCD_STATE_OPERATIONAL:
2321 case UFSHCD_STATE_EH_SCHEDULED:
2322 case UFSHCD_STATE_RESET:
2323 err = SCSI_MLQUEUE_HOST_BUSY;
2325 case UFSHCD_STATE_ERROR:
2326 set_host_byte(cmd, DID_ERROR);
2327 cmd->scsi_done(cmd);
2330 dev_WARN_ONCE(hba->dev, 1, "%s: invalid state %d\n",
2331 __func__, hba->ufshcd_state);
2332 set_host_byte(cmd, DID_BAD_TARGET);
2333 cmd->scsi_done(cmd);
2337 /* if error handling is in progress, don't issue commands */
2338 if (ufshcd_eh_in_progress(hba)) {
2339 set_host_byte(cmd, DID_ERROR);
2340 cmd->scsi_done(cmd);
2343 spin_unlock_irqrestore(hba->host->host_lock, flags);
2345 hba->req_abort_count = 0;
2347 /* acquire the tag to make sure device cmds don't use it */
2348 if (test_and_set_bit_lock(tag, &hba->lrb_in_use)) {
2350 * Dev manage command in progress, requeue the command.
2351 * Requeuing the command helps in cases where the request *may*
2352 * find different tag instead of waiting for dev manage command
2355 err = SCSI_MLQUEUE_HOST_BUSY;
2359 err = ufshcd_hold(hba, true);
2361 err = SCSI_MLQUEUE_HOST_BUSY;
2362 clear_bit_unlock(tag, &hba->lrb_in_use);
2365 WARN_ON(hba->clk_gating.state != CLKS_ON);
2367 lrbp = &hba->lrb[tag];
2371 lrbp->sense_bufflen = UFSHCD_REQ_SENSE_SIZE;
2372 lrbp->sense_buffer = cmd->sense_buffer;
2373 lrbp->task_tag = tag;
2374 lrbp->lun = ufshcd_scsi_to_upiu_lun(cmd->device->lun);
2375 lrbp->intr_cmd = !ufshcd_is_intr_aggr_allowed(hba) ? true : false;
2376 lrbp->req_abort_skip = false;
2378 ufshcd_comp_scsi_upiu(hba, lrbp);
2380 err = ufshcd_map_sg(hba, lrbp);
2383 clear_bit_unlock(tag, &hba->lrb_in_use);
2386 /* Make sure descriptors are ready before ringing the doorbell */
2389 /* issue command to the controller */
2390 spin_lock_irqsave(hba->host->host_lock, flags);
2391 ufshcd_vops_setup_xfer_req(hba, tag, (lrbp->cmd ? true : false));
2392 ufshcd_send_command(hba, tag);
2394 spin_unlock_irqrestore(hba->host->host_lock, flags);
2396 up_read(&hba->clk_scaling_lock);
2400 static int ufshcd_compose_dev_cmd(struct ufs_hba *hba,
2401 struct ufshcd_lrb *lrbp, enum dev_cmd_type cmd_type, int tag)
2404 lrbp->sense_bufflen = 0;
2405 lrbp->sense_buffer = NULL;
2406 lrbp->task_tag = tag;
2407 lrbp->lun = 0; /* device management cmd is not specific to any LUN */
2408 lrbp->intr_cmd = true; /* No interrupt aggregation */
2409 hba->dev_cmd.type = cmd_type;
2411 return ufshcd_comp_devman_upiu(hba, lrbp);
2415 ufshcd_clear_cmd(struct ufs_hba *hba, int tag)
2418 unsigned long flags;
2419 u32 mask = 1 << tag;
2421 /* clear outstanding transaction before retry */
2422 spin_lock_irqsave(hba->host->host_lock, flags);
2423 ufshcd_utrl_clear(hba, tag);
2424 spin_unlock_irqrestore(hba->host->host_lock, flags);
2427 * wait for for h/w to clear corresponding bit in door-bell.
2428 * max. wait is 1 sec.
2430 err = ufshcd_wait_for_register(hba,
2431 REG_UTP_TRANSFER_REQ_DOOR_BELL,
2432 mask, ~mask, 1000, 1000, true);
2438 ufshcd_check_query_response(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
2440 struct ufs_query_res *query_res = &hba->dev_cmd.query.response;
2442 /* Get the UPIU response */
2443 query_res->response = ufshcd_get_rsp_upiu_result(lrbp->ucd_rsp_ptr) >>
2444 UPIU_RSP_CODE_OFFSET;
2445 return query_res->response;
2449 * ufshcd_dev_cmd_completion() - handles device management command responses
2450 * @hba: per adapter instance
2451 * @lrbp: pointer to local reference block
2454 ufshcd_dev_cmd_completion(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
2459 hba->ufs_stats.last_hibern8_exit_tstamp = ktime_set(0, 0);
2460 resp = ufshcd_get_req_rsp(lrbp->ucd_rsp_ptr);
2463 case UPIU_TRANSACTION_NOP_IN:
2464 if (hba->dev_cmd.type != DEV_CMD_TYPE_NOP) {
2466 dev_err(hba->dev, "%s: unexpected response %x\n",
2470 case UPIU_TRANSACTION_QUERY_RSP:
2471 err = ufshcd_check_query_response(hba, lrbp);
2473 err = ufshcd_copy_query_response(hba, lrbp);
2475 case UPIU_TRANSACTION_REJECT_UPIU:
2476 /* TODO: handle Reject UPIU Response */
2478 dev_err(hba->dev, "%s: Reject UPIU not fully implemented\n",
2483 dev_err(hba->dev, "%s: Invalid device management cmd response: %x\n",
2491 static int ufshcd_wait_for_dev_cmd(struct ufs_hba *hba,
2492 struct ufshcd_lrb *lrbp, int max_timeout)
2495 unsigned long time_left;
2496 unsigned long flags;
2498 time_left = wait_for_completion_timeout(hba->dev_cmd.complete,
2499 msecs_to_jiffies(max_timeout));
2501 /* Make sure descriptors are ready before ringing the doorbell */
2503 spin_lock_irqsave(hba->host->host_lock, flags);
2504 hba->dev_cmd.complete = NULL;
2505 if (likely(time_left)) {
2506 err = ufshcd_get_tr_ocs(lrbp);
2508 err = ufshcd_dev_cmd_completion(hba, lrbp);
2510 spin_unlock_irqrestore(hba->host->host_lock, flags);
2514 dev_dbg(hba->dev, "%s: dev_cmd request timedout, tag %d\n",
2515 __func__, lrbp->task_tag);
2516 if (!ufshcd_clear_cmd(hba, lrbp->task_tag))
2517 /* successfully cleared the command, retry if needed */
2520 * in case of an error, after clearing the doorbell,
2521 * we also need to clear the outstanding_request
2524 ufshcd_outstanding_req_clear(hba, lrbp->task_tag);
2531 * ufshcd_get_dev_cmd_tag - Get device management command tag
2532 * @hba: per-adapter instance
2533 * @tag: pointer to variable with available slot value
2535 * Get a free slot and lock it until device management command
2538 * Returns false if free slot is unavailable for locking, else
2539 * return true with tag value in @tag.
2541 static bool ufshcd_get_dev_cmd_tag(struct ufs_hba *hba, int *tag_out)
2551 tmp = ~hba->lrb_in_use;
2552 tag = find_last_bit(&tmp, hba->nutrs);
2553 if (tag >= hba->nutrs)
2555 } while (test_and_set_bit_lock(tag, &hba->lrb_in_use));
2563 static inline void ufshcd_put_dev_cmd_tag(struct ufs_hba *hba, int tag)
2565 clear_bit_unlock(tag, &hba->lrb_in_use);
2569 * ufshcd_exec_dev_cmd - API for sending device management requests
2571 * @cmd_type - specifies the type (NOP, Query...)
2572 * @timeout - time in seconds
2574 * NOTE: Since there is only one available tag for device management commands,
2575 * it is expected you hold the hba->dev_cmd.lock mutex.
2577 static int ufshcd_exec_dev_cmd(struct ufs_hba *hba,
2578 enum dev_cmd_type cmd_type, int timeout)
2580 struct ufshcd_lrb *lrbp;
2583 struct completion wait;
2584 unsigned long flags;
2586 down_read(&hba->clk_scaling_lock);
2589 * Get free slot, sleep if slots are unavailable.
2590 * Even though we use wait_event() which sleeps indefinitely,
2591 * the maximum wait time is bounded by SCSI request timeout.
2593 wait_event(hba->dev_cmd.tag_wq, ufshcd_get_dev_cmd_tag(hba, &tag));
2595 init_completion(&wait);
2596 lrbp = &hba->lrb[tag];
2598 err = ufshcd_compose_dev_cmd(hba, lrbp, cmd_type, tag);
2602 hba->dev_cmd.complete = &wait;
2604 /* Make sure descriptors are ready before ringing the doorbell */
2606 spin_lock_irqsave(hba->host->host_lock, flags);
2607 ufshcd_vops_setup_xfer_req(hba, tag, (lrbp->cmd ? true : false));
2608 ufshcd_send_command(hba, tag);
2609 spin_unlock_irqrestore(hba->host->host_lock, flags);
2611 err = ufshcd_wait_for_dev_cmd(hba, lrbp, timeout);
2614 ufshcd_put_dev_cmd_tag(hba, tag);
2615 wake_up(&hba->dev_cmd.tag_wq);
2616 up_read(&hba->clk_scaling_lock);
2621 * ufshcd_init_query() - init the query response and request parameters
2622 * @hba: per-adapter instance
2623 * @request: address of the request pointer to be initialized
2624 * @response: address of the response pointer to be initialized
2625 * @opcode: operation to perform
2626 * @idn: flag idn to access
2627 * @index: LU number to access
2628 * @selector: query/flag/descriptor further identification
2630 static inline void ufshcd_init_query(struct ufs_hba *hba,
2631 struct ufs_query_req **request, struct ufs_query_res **response,
2632 enum query_opcode opcode, u8 idn, u8 index, u8 selector)
2634 *request = &hba->dev_cmd.query.request;
2635 *response = &hba->dev_cmd.query.response;
2636 memset(*request, 0, sizeof(struct ufs_query_req));
2637 memset(*response, 0, sizeof(struct ufs_query_res));
2638 (*request)->upiu_req.opcode = opcode;
2639 (*request)->upiu_req.idn = idn;
2640 (*request)->upiu_req.index = index;
2641 (*request)->upiu_req.selector = selector;
2644 static int ufshcd_query_flag_retry(struct ufs_hba *hba,
2645 enum query_opcode opcode, enum flag_idn idn, bool *flag_res)
2650 for (retries = 0; retries < QUERY_REQ_RETRIES; retries++) {
2651 ret = ufshcd_query_flag(hba, opcode, idn, flag_res);
2654 "%s: failed with error %d, retries %d\n",
2655 __func__, ret, retries);
2662 "%s: query attribute, opcode %d, idn %d, failed with error %d after %d retires\n",
2663 __func__, opcode, idn, ret, retries);
2668 * ufshcd_query_flag() - API function for sending flag query requests
2669 * hba: per-adapter instance
2670 * query_opcode: flag query to perform
2671 * idn: flag idn to access
2672 * flag_res: the flag value after the query request completes
2674 * Returns 0 for success, non-zero in case of failure
2676 int ufshcd_query_flag(struct ufs_hba *hba, enum query_opcode opcode,
2677 enum flag_idn idn, bool *flag_res)
2679 struct ufs_query_req *request = NULL;
2680 struct ufs_query_res *response = NULL;
2681 int err, index = 0, selector = 0;
2682 int timeout = QUERY_REQ_TIMEOUT;
2686 ufshcd_hold(hba, false);
2687 mutex_lock(&hba->dev_cmd.lock);
2688 ufshcd_init_query(hba, &request, &response, opcode, idn, index,
2692 case UPIU_QUERY_OPCODE_SET_FLAG:
2693 case UPIU_QUERY_OPCODE_CLEAR_FLAG:
2694 case UPIU_QUERY_OPCODE_TOGGLE_FLAG:
2695 request->query_func = UPIU_QUERY_FUNC_STANDARD_WRITE_REQUEST;
2697 case UPIU_QUERY_OPCODE_READ_FLAG:
2698 request->query_func = UPIU_QUERY_FUNC_STANDARD_READ_REQUEST;
2700 /* No dummy reads */
2701 dev_err(hba->dev, "%s: Invalid argument for read request\n",
2709 "%s: Expected query flag opcode but got = %d\n",
2715 err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_QUERY, timeout);
2719 "%s: Sending flag query for idn %d failed, err = %d\n",
2720 __func__, idn, err);
2725 *flag_res = (be32_to_cpu(response->upiu_res.value) &
2726 MASK_QUERY_UPIU_FLAG_LOC) & 0x1;
2729 mutex_unlock(&hba->dev_cmd.lock);
2730 ufshcd_release(hba);
2735 * ufshcd_query_attr - API function for sending attribute requests
2736 * hba: per-adapter instance
2737 * opcode: attribute opcode
2738 * idn: attribute idn to access
2739 * index: index field
2740 * selector: selector field
2741 * attr_val: the attribute value after the query request completes
2743 * Returns 0 for success, non-zero in case of failure
2745 static int ufshcd_query_attr(struct ufs_hba *hba, enum query_opcode opcode,
2746 enum attr_idn idn, u8 index, u8 selector, u32 *attr_val)
2748 struct ufs_query_req *request = NULL;
2749 struct ufs_query_res *response = NULL;
2754 ufshcd_hold(hba, false);
2756 dev_err(hba->dev, "%s: attribute value required for opcode 0x%x\n",
2762 mutex_lock(&hba->dev_cmd.lock);
2763 ufshcd_init_query(hba, &request, &response, opcode, idn, index,
2767 case UPIU_QUERY_OPCODE_WRITE_ATTR:
2768 request->query_func = UPIU_QUERY_FUNC_STANDARD_WRITE_REQUEST;
2769 request->upiu_req.value = cpu_to_be32(*attr_val);
2771 case UPIU_QUERY_OPCODE_READ_ATTR:
2772 request->query_func = UPIU_QUERY_FUNC_STANDARD_READ_REQUEST;
2775 dev_err(hba->dev, "%s: Expected query attr opcode but got = 0x%.2x\n",
2781 err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_QUERY, QUERY_REQ_TIMEOUT);
2784 dev_err(hba->dev, "%s: opcode 0x%.2x for idn %d failed, index %d, err = %d\n",
2785 __func__, opcode, idn, index, err);
2789 *attr_val = be32_to_cpu(response->upiu_res.value);
2792 mutex_unlock(&hba->dev_cmd.lock);
2794 ufshcd_release(hba);
2799 * ufshcd_query_attr_retry() - API function for sending query
2800 * attribute with retries
2801 * @hba: per-adapter instance
2802 * @opcode: attribute opcode
2803 * @idn: attribute idn to access
2804 * @index: index field
2805 * @selector: selector field
2806 * @attr_val: the attribute value after the query request
2809 * Returns 0 for success, non-zero in case of failure
2811 static int ufshcd_query_attr_retry(struct ufs_hba *hba,
2812 enum query_opcode opcode, enum attr_idn idn, u8 index, u8 selector,
2818 for (retries = QUERY_REQ_RETRIES; retries > 0; retries--) {
2819 ret = ufshcd_query_attr(hba, opcode, idn, index,
2820 selector, attr_val);
2822 dev_dbg(hba->dev, "%s: failed with error %d, retries %d\n",
2823 __func__, ret, retries);
2830 "%s: query attribute, idn %d, failed with error %d after %d retires\n",
2831 __func__, idn, ret, QUERY_REQ_RETRIES);
2835 static int __ufshcd_query_descriptor(struct ufs_hba *hba,
2836 enum query_opcode opcode, enum desc_idn idn, u8 index,
2837 u8 selector, u8 *desc_buf, int *buf_len)
2839 struct ufs_query_req *request = NULL;
2840 struct ufs_query_res *response = NULL;
2845 ufshcd_hold(hba, false);
2847 dev_err(hba->dev, "%s: descriptor buffer required for opcode 0x%x\n",
2853 if (*buf_len <= QUERY_DESC_MIN_SIZE || *buf_len > QUERY_DESC_MAX_SIZE) {
2854 dev_err(hba->dev, "%s: descriptor buffer size (%d) is out of range\n",
2855 __func__, *buf_len);
2860 mutex_lock(&hba->dev_cmd.lock);
2861 ufshcd_init_query(hba, &request, &response, opcode, idn, index,
2863 hba->dev_cmd.query.descriptor = desc_buf;
2864 request->upiu_req.length = cpu_to_be16(*buf_len);
2867 case UPIU_QUERY_OPCODE_WRITE_DESC:
2868 request->query_func = UPIU_QUERY_FUNC_STANDARD_WRITE_REQUEST;
2870 case UPIU_QUERY_OPCODE_READ_DESC:
2871 request->query_func = UPIU_QUERY_FUNC_STANDARD_READ_REQUEST;
2875 "%s: Expected query descriptor opcode but got = 0x%.2x\n",
2881 err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_QUERY, QUERY_REQ_TIMEOUT);
2884 dev_err(hba->dev, "%s: opcode 0x%.2x for idn %d failed, index %d, err = %d\n",
2885 __func__, opcode, idn, index, err);
2889 hba->dev_cmd.query.descriptor = NULL;
2890 *buf_len = be16_to_cpu(response->upiu_res.length);
2893 mutex_unlock(&hba->dev_cmd.lock);
2895 ufshcd_release(hba);
2900 * ufshcd_query_descriptor_retry - API function for sending descriptor
2902 * hba: per-adapter instance
2903 * opcode: attribute opcode
2904 * idn: attribute idn to access
2905 * index: index field
2906 * selector: selector field
2907 * desc_buf: the buffer that contains the descriptor
2908 * buf_len: length parameter passed to the device
2910 * Returns 0 for success, non-zero in case of failure.
2911 * The buf_len parameter will contain, on return, the length parameter
2912 * received on the response.
2914 static int ufshcd_query_descriptor_retry(struct ufs_hba *hba,
2915 enum query_opcode opcode,
2916 enum desc_idn idn, u8 index,
2918 u8 *desc_buf, int *buf_len)
2923 for (retries = QUERY_REQ_RETRIES; retries > 0; retries--) {
2924 err = __ufshcd_query_descriptor(hba, opcode, idn, index,
2925 selector, desc_buf, buf_len);
2926 if (!err || err == -EINVAL)
2934 * ufshcd_read_desc_param - read the specified descriptor parameter
2935 * @hba: Pointer to adapter instance
2936 * @desc_id: descriptor idn value
2937 * @desc_index: descriptor index
2938 * @param_offset: offset of the parameter to read
2939 * @param_read_buf: pointer to buffer where parameter would be read
2940 * @param_size: sizeof(param_read_buf)
2942 * Return 0 in case of success, non-zero otherwise
2944 static int ufshcd_read_desc_param(struct ufs_hba *hba,
2945 enum desc_idn desc_id,
2954 bool is_kmalloc = true;
2957 if (desc_id >= QUERY_DESC_IDN_MAX)
2960 buff_len = ufs_query_desc_max_size[desc_id];
2961 if ((param_offset + param_size) > buff_len)
2964 if (!param_offset && (param_size == buff_len)) {
2965 /* memory space already available to hold full descriptor */
2966 desc_buf = param_read_buf;
2969 /* allocate memory to hold full descriptor */
2970 desc_buf = kmalloc(buff_len, GFP_KERNEL);
2975 ret = ufshcd_query_descriptor_retry(hba, UPIU_QUERY_OPCODE_READ_DESC,
2976 desc_id, desc_index, 0, desc_buf,
2980 dev_err(hba->dev, "%s: Failed reading descriptor. desc_id %d, desc_index %d, param_offset %d, ret %d",
2981 __func__, desc_id, desc_index, param_offset, ret);
2987 if (desc_buf[QUERY_DESC_DESC_TYPE_OFFSET] != desc_id) {
2988 dev_err(hba->dev, "%s: invalid desc_id %d in descriptor header",
2989 __func__, desc_buf[QUERY_DESC_DESC_TYPE_OFFSET]);
2995 * While reading variable size descriptors (like string descriptor),
2996 * some UFS devices may report the "LENGTH" (field in "Transaction
2997 * Specific fields" of Query Response UPIU) same as what was requested
2998 * in Query Request UPIU instead of reporting the actual size of the
2999 * variable size descriptor.
3000 * Although it's safe to ignore the "LENGTH" field for variable size
3001 * descriptors as we can always derive the length of the descriptor from
3002 * the descriptor header fields. Hence this change impose the length
3003 * match check only for fixed size descriptors (for which we always
3004 * request the correct size as part of Query Request UPIU).
3006 if ((desc_id != QUERY_DESC_IDN_STRING) &&
3007 (buff_len != desc_buf[QUERY_DESC_LENGTH_OFFSET])) {
3008 dev_err(hba->dev, "%s: desc_buf length mismatch: buff_len %d, buff_len(desc_header) %d",
3009 __func__, buff_len, desc_buf[QUERY_DESC_LENGTH_OFFSET]);
3015 memcpy(param_read_buf, &desc_buf[param_offset], param_size);
3022 static inline int ufshcd_read_desc(struct ufs_hba *hba,
3023 enum desc_idn desc_id,
3028 return ufshcd_read_desc_param(hba, desc_id, desc_index, 0, buf, size);
3031 static inline int ufshcd_read_power_desc(struct ufs_hba *hba,
3035 return ufshcd_read_desc(hba, QUERY_DESC_IDN_POWER, 0, buf, size);
3038 static int ufshcd_read_device_desc(struct ufs_hba *hba, u8 *buf, u32 size)
3040 return ufshcd_read_desc(hba, QUERY_DESC_IDN_DEVICE, 0, buf, size);
3044 * ufshcd_read_string_desc - read string descriptor
3045 * @hba: pointer to adapter instance
3046 * @desc_index: descriptor index
3047 * @buf: pointer to buffer where descriptor would be read
3048 * @size: size of buf
3049 * @ascii: if true convert from unicode to ascii characters
3051 * Return 0 in case of success, non-zero otherwise
3053 #define ASCII_STD true
3054 static int ufshcd_read_string_desc(struct ufs_hba *hba, int desc_index,
3055 u8 *buf, u32 size, bool ascii)
3059 err = ufshcd_read_desc(hba,
3060 QUERY_DESC_IDN_STRING, desc_index, buf, size);
3063 dev_err(hba->dev, "%s: reading String Desc failed after %d retries. err = %d\n",
3064 __func__, QUERY_REQ_RETRIES, err);
3075 /* remove header and divide by 2 to move from UTF16 to UTF8 */
3076 ascii_len = (desc_len - QUERY_DESC_HDR_SIZE) / 2 + 1;
3077 if (size < ascii_len + QUERY_DESC_HDR_SIZE) {
3078 dev_err(hba->dev, "%s: buffer allocated size is too small\n",
3084 buff_ascii = kmalloc(ascii_len, GFP_KERNEL);
3091 * the descriptor contains string in UTF16 format
3092 * we need to convert to utf-8 so it can be displayed
3094 utf16s_to_utf8s((wchar_t *)&buf[QUERY_DESC_HDR_SIZE],
3095 desc_len - QUERY_DESC_HDR_SIZE,
3096 UTF16_BIG_ENDIAN, buff_ascii, ascii_len);
3098 /* replace non-printable or non-ASCII characters with spaces */
3099 for (i = 0; i < ascii_len; i++)
3100 ufshcd_remove_non_printable(&buff_ascii[i]);
3102 memset(buf + QUERY_DESC_HDR_SIZE, 0,
3103 size - QUERY_DESC_HDR_SIZE);
3104 memcpy(buf + QUERY_DESC_HDR_SIZE, buff_ascii, ascii_len);
3105 buf[QUERY_DESC_LENGTH_OFFSET] = ascii_len + QUERY_DESC_HDR_SIZE;
3113 * ufshcd_read_unit_desc_param - read the specified unit descriptor parameter
3114 * @hba: Pointer to adapter instance
3116 * @param_offset: offset of the parameter to read
3117 * @param_read_buf: pointer to buffer where parameter would be read
3118 * @param_size: sizeof(param_read_buf)
3120 * Return 0 in case of success, non-zero otherwise
3122 static inline int ufshcd_read_unit_desc_param(struct ufs_hba *hba,
3124 enum unit_desc_param param_offset,
3129 * Unit descriptors are only available for general purpose LUs (LUN id
3130 * from 0 to 7) and RPMB Well known LU.
3132 if (lun != UFS_UPIU_RPMB_WLUN && (lun >= UFS_UPIU_MAX_GENERAL_LUN))
3135 return ufshcd_read_desc_param(hba, QUERY_DESC_IDN_UNIT, lun,
3136 param_offset, param_read_buf, param_size);
3140 * ufshcd_memory_alloc - allocate memory for host memory space data structures
3141 * @hba: per adapter instance
3143 * 1. Allocate DMA memory for Command Descriptor array
3144 * Each command descriptor consist of Command UPIU, Response UPIU and PRDT
3145 * 2. Allocate DMA memory for UTP Transfer Request Descriptor List (UTRDL).
3146 * 3. Allocate DMA memory for UTP Task Management Request Descriptor List
3148 * 4. Allocate memory for local reference block(lrb).
3150 * Returns 0 for success, non-zero in case of failure
3152 static int ufshcd_memory_alloc(struct ufs_hba *hba)
3154 size_t utmrdl_size, utrdl_size, ucdl_size;
3156 /* Allocate memory for UTP command descriptors */
3157 ucdl_size = (sizeof(struct utp_transfer_cmd_desc) * hba->nutrs);
3158 hba->ucdl_base_addr = dmam_alloc_coherent(hba->dev,
3160 &hba->ucdl_dma_addr,
3164 * UFSHCI requires UTP command descriptor to be 128 byte aligned.
3165 * make sure hba->ucdl_dma_addr is aligned to PAGE_SIZE
3166 * if hba->ucdl_dma_addr is aligned to PAGE_SIZE, then it will
3167 * be aligned to 128 bytes as well
3169 if (!hba->ucdl_base_addr ||
3170 WARN_ON(hba->ucdl_dma_addr & (PAGE_SIZE - 1))) {
3172 "Command Descriptor Memory allocation failed\n");
3177 * Allocate memory for UTP Transfer descriptors
3178 * UFSHCI requires 1024 byte alignment of UTRD
3180 utrdl_size = (sizeof(struct utp_transfer_req_desc) * hba->nutrs);
3181 hba->utrdl_base_addr = dmam_alloc_coherent(hba->dev,
3183 &hba->utrdl_dma_addr,
3185 if (!hba->utrdl_base_addr ||
3186 WARN_ON(hba->utrdl_dma_addr & (PAGE_SIZE - 1))) {
3188 "Transfer Descriptor Memory allocation failed\n");
3193 * Allocate memory for UTP Task Management descriptors
3194 * UFSHCI requires 1024 byte alignment of UTMRD
3196 utmrdl_size = sizeof(struct utp_task_req_desc) * hba->nutmrs;
3197 hba->utmrdl_base_addr = dmam_alloc_coherent(hba->dev,
3199 &hba->utmrdl_dma_addr,
3201 if (!hba->utmrdl_base_addr ||
3202 WARN_ON(hba->utmrdl_dma_addr & (PAGE_SIZE - 1))) {
3204 "Task Management Descriptor Memory allocation failed\n");
3208 /* Allocate memory for local reference block */
3209 hba->lrb = devm_kzalloc(hba->dev,
3210 hba->nutrs * sizeof(struct ufshcd_lrb),
3213 dev_err(hba->dev, "LRB Memory allocation failed\n");
3222 * ufshcd_host_memory_configure - configure local reference block with
3224 * @hba: per adapter instance
3226 * Configure Host memory space
3227 * 1. Update Corresponding UTRD.UCDBA and UTRD.UCDBAU with UCD DMA
3229 * 2. Update each UTRD with Response UPIU offset, Response UPIU length
3231 * 3. Save the corresponding addresses of UTRD, UCD.CMD, UCD.RSP and UCD.PRDT
3232 * into local reference block.
3234 static void ufshcd_host_memory_configure(struct ufs_hba *hba)
3236 struct utp_transfer_cmd_desc *cmd_descp;
3237 struct utp_transfer_req_desc *utrdlp;
3238 dma_addr_t cmd_desc_dma_addr;
3239 dma_addr_t cmd_desc_element_addr;
3240 u16 response_offset;
3245 utrdlp = hba->utrdl_base_addr;
3246 cmd_descp = hba->ucdl_base_addr;
3249 offsetof(struct utp_transfer_cmd_desc, response_upiu);
3251 offsetof(struct utp_transfer_cmd_desc, prd_table);
3253 cmd_desc_size = sizeof(struct utp_transfer_cmd_desc);
3254 cmd_desc_dma_addr = hba->ucdl_dma_addr;
3256 for (i = 0; i < hba->nutrs; i++) {
3257 /* Configure UTRD with command descriptor base address */
3258 cmd_desc_element_addr =
3259 (cmd_desc_dma_addr + (cmd_desc_size * i));
3260 utrdlp[i].command_desc_base_addr_lo =
3261 cpu_to_le32(lower_32_bits(cmd_desc_element_addr));
3262 utrdlp[i].command_desc_base_addr_hi =
3263 cpu_to_le32(upper_32_bits(cmd_desc_element_addr));
3265 /* Response upiu and prdt offset should be in double words */
3266 if (hba->quirks & UFSHCD_QUIRK_PRDT_BYTE_GRAN) {
3267 utrdlp[i].response_upiu_offset =
3268 cpu_to_le16(response_offset);
3269 utrdlp[i].prd_table_offset =
3270 cpu_to_le16(prdt_offset);
3271 utrdlp[i].response_upiu_length =
3272 cpu_to_le16(ALIGNED_UPIU_SIZE);
3274 utrdlp[i].response_upiu_offset =
3275 cpu_to_le16((response_offset >> 2));
3276 utrdlp[i].prd_table_offset =
3277 cpu_to_le16((prdt_offset >> 2));
3278 utrdlp[i].response_upiu_length =
3279 cpu_to_le16(ALIGNED_UPIU_SIZE >> 2);
3282 hba->lrb[i].utr_descriptor_ptr = (utrdlp + i);
3283 hba->lrb[i].utrd_dma_addr = hba->utrdl_dma_addr +
3284 (i * sizeof(struct utp_transfer_req_desc));
3285 hba->lrb[i].ucd_req_ptr =
3286 (struct utp_upiu_req *)(cmd_descp + i);
3287 hba->lrb[i].ucd_req_dma_addr = cmd_desc_element_addr;
3288 hba->lrb[i].ucd_rsp_ptr =
3289 (struct utp_upiu_rsp *)cmd_descp[i].response_upiu;
3290 hba->lrb[i].ucd_rsp_dma_addr = cmd_desc_element_addr +
3292 hba->lrb[i].ucd_prdt_ptr =
3293 (struct ufshcd_sg_entry *)cmd_descp[i].prd_table;
3294 hba->lrb[i].ucd_prdt_dma_addr = cmd_desc_element_addr +
3300 * ufshcd_dme_link_startup - Notify Unipro to perform link startup
3301 * @hba: per adapter instance
3303 * UIC_CMD_DME_LINK_STARTUP command must be issued to Unipro layer,
3304 * in order to initialize the Unipro link startup procedure.
3305 * Once the Unipro links are up, the device connected to the controller
3308 * Returns 0 on success, non-zero value on failure
3310 static int ufshcd_dme_link_startup(struct ufs_hba *hba)
3312 struct uic_command uic_cmd = {0};
3315 uic_cmd.command = UIC_CMD_DME_LINK_STARTUP;
3317 ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
3320 "dme-link-startup: error code %d\n", ret);
3324 static inline void ufshcd_add_delay_before_dme_cmd(struct ufs_hba *hba)
3326 #define MIN_DELAY_BEFORE_DME_CMDS_US 1000
3327 unsigned long min_sleep_time_us;
3329 if (!(hba->quirks & UFSHCD_QUIRK_DELAY_BEFORE_DME_CMDS))
3333 * last_dme_cmd_tstamp will be 0 only for 1st call to
3336 if (unlikely(!ktime_to_us(hba->last_dme_cmd_tstamp))) {
3337 min_sleep_time_us = MIN_DELAY_BEFORE_DME_CMDS_US;
3339 unsigned long delta =
3340 (unsigned long) ktime_to_us(
3341 ktime_sub(ktime_get(),
3342 hba->last_dme_cmd_tstamp));
3344 if (delta < MIN_DELAY_BEFORE_DME_CMDS_US)
3346 MIN_DELAY_BEFORE_DME_CMDS_US - delta;
3348 return; /* no more delay required */
3351 /* allow sleep for extra 50us if needed */
3352 usleep_range(min_sleep_time_us, min_sleep_time_us + 50);
3356 * ufshcd_dme_set_attr - UIC command for DME_SET, DME_PEER_SET
3357 * @hba: per adapter instance
3358 * @attr_sel: uic command argument1
3359 * @attr_set: attribute set type as uic command argument2
3360 * @mib_val: setting value as uic command argument3
3361 * @peer: indicate whether peer or local
3363 * Returns 0 on success, non-zero value on failure
3365 int ufshcd_dme_set_attr(struct ufs_hba *hba, u32 attr_sel,
3366 u8 attr_set, u32 mib_val, u8 peer)
3368 struct uic_command uic_cmd = {0};
3369 static const char *const action[] = {
3373 const char *set = action[!!peer];
3375 int retries = UFS_UIC_COMMAND_RETRIES;
3377 uic_cmd.command = peer ?
3378 UIC_CMD_DME_PEER_SET : UIC_CMD_DME_SET;
3379 uic_cmd.argument1 = attr_sel;
3380 uic_cmd.argument2 = UIC_ARG_ATTR_TYPE(attr_set);
3381 uic_cmd.argument3 = mib_val;
3384 /* for peer attributes we retry upon failure */
3385 ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
3387 dev_dbg(hba->dev, "%s: attr-id 0x%x val 0x%x error code %d\n",
3388 set, UIC_GET_ATTR_ID(attr_sel), mib_val, ret);
3389 } while (ret && peer && --retries);
3392 dev_err(hba->dev, "%s: attr-id 0x%x val 0x%x failed %d retries\n",
3393 set, UIC_GET_ATTR_ID(attr_sel), mib_val,
3394 UFS_UIC_COMMAND_RETRIES - retries);
3398 EXPORT_SYMBOL_GPL(ufshcd_dme_set_attr);
3401 * ufshcd_dme_get_attr - UIC command for DME_GET, DME_PEER_GET
3402 * @hba: per adapter instance
3403 * @attr_sel: uic command argument1
3404 * @mib_val: the value of the attribute as returned by the UIC command
3405 * @peer: indicate whether peer or local
3407 * Returns 0 on success, non-zero value on failure
3409 int ufshcd_dme_get_attr(struct ufs_hba *hba, u32 attr_sel,
3410 u32 *mib_val, u8 peer)
3412 struct uic_command uic_cmd = {0};
3413 static const char *const action[] = {
3417 const char *get = action[!!peer];
3419 int retries = UFS_UIC_COMMAND_RETRIES;
3420 struct ufs_pa_layer_attr orig_pwr_info;
3421 struct ufs_pa_layer_attr temp_pwr_info;
3422 bool pwr_mode_change = false;
3424 if (peer && (hba->quirks & UFSHCD_QUIRK_DME_PEER_ACCESS_AUTO_MODE)) {
3425 orig_pwr_info = hba->pwr_info;
3426 temp_pwr_info = orig_pwr_info;
3428 if (orig_pwr_info.pwr_tx == FAST_MODE ||
3429 orig_pwr_info.pwr_rx == FAST_MODE) {
3430 temp_pwr_info.pwr_tx = FASTAUTO_MODE;
3431 temp_pwr_info.pwr_rx = FASTAUTO_MODE;
3432 pwr_mode_change = true;
3433 } else if (orig_pwr_info.pwr_tx == SLOW_MODE ||
3434 orig_pwr_info.pwr_rx == SLOW_MODE) {
3435 temp_pwr_info.pwr_tx = SLOWAUTO_MODE;
3436 temp_pwr_info.pwr_rx = SLOWAUTO_MODE;
3437 pwr_mode_change = true;
3439 if (pwr_mode_change) {
3440 ret = ufshcd_change_power_mode(hba, &temp_pwr_info);
3446 uic_cmd.command = peer ?
3447 UIC_CMD_DME_PEER_GET : UIC_CMD_DME_GET;
3448 uic_cmd.argument1 = attr_sel;
3451 /* for peer attributes we retry upon failure */
3452 ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
3454 dev_dbg(hba->dev, "%s: attr-id 0x%x error code %d\n",
3455 get, UIC_GET_ATTR_ID(attr_sel), ret);
3456 } while (ret && peer && --retries);
3459 dev_err(hba->dev, "%s: attr-id 0x%x failed %d retries\n",
3460 get, UIC_GET_ATTR_ID(attr_sel),
3461 UFS_UIC_COMMAND_RETRIES - retries);
3463 if (mib_val && !ret)
3464 *mib_val = uic_cmd.argument3;
3466 if (peer && (hba->quirks & UFSHCD_QUIRK_DME_PEER_ACCESS_AUTO_MODE)
3468 ufshcd_change_power_mode(hba, &orig_pwr_info);
3472 EXPORT_SYMBOL_GPL(ufshcd_dme_get_attr);
3475 * ufshcd_uic_pwr_ctrl - executes UIC commands (which affects the link power
3476 * state) and waits for it to take effect.
3478 * @hba: per adapter instance
3479 * @cmd: UIC command to execute
3481 * DME operations like DME_SET(PA_PWRMODE), DME_HIBERNATE_ENTER &
3482 * DME_HIBERNATE_EXIT commands take some time to take its effect on both host
3483 * and device UniPro link and hence it's final completion would be indicated by
3484 * dedicated status bits in Interrupt Status register (UPMS, UHES, UHXS) in
3485 * addition to normal UIC command completion Status (UCCS). This function only
3486 * returns after the relevant status bits indicate the completion.
3488 * Returns 0 on success, non-zero value on failure
3490 static int ufshcd_uic_pwr_ctrl(struct ufs_hba *hba, struct uic_command *cmd)
3492 struct completion uic_async_done;
3493 unsigned long flags;
3496 bool reenable_intr = false;
3498 mutex_lock(&hba->uic_cmd_mutex);
3499 init_completion(&uic_async_done);
3500 ufshcd_add_delay_before_dme_cmd(hba);
3502 spin_lock_irqsave(hba->host->host_lock, flags);
3503 hba->uic_async_done = &uic_async_done;
3504 if (ufshcd_readl(hba, REG_INTERRUPT_ENABLE) & UIC_COMMAND_COMPL) {
3505 ufshcd_disable_intr(hba, UIC_COMMAND_COMPL);
3507 * Make sure UIC command completion interrupt is disabled before
3508 * issuing UIC command.
3511 reenable_intr = true;
3513 ret = __ufshcd_send_uic_cmd(hba, cmd, false);
3514 spin_unlock_irqrestore(hba->host->host_lock, flags);
3517 "pwr ctrl cmd 0x%x with mode 0x%x uic error %d\n",
3518 cmd->command, cmd->argument3, ret);
3522 if (!wait_for_completion_timeout(hba->uic_async_done,
3523 msecs_to_jiffies(UIC_CMD_TIMEOUT))) {
3525 "pwr ctrl cmd 0x%x with mode 0x%x completion timeout\n",
3526 cmd->command, cmd->argument3);
3531 status = ufshcd_get_upmcrs(hba);
3532 if (status != PWR_LOCAL) {
3534 "pwr ctrl cmd 0x%0x failed, host upmcrs:0x%x\n",
3535 cmd->command, status);
3536 ret = (status != PWR_OK) ? status : -1;
3540 ufshcd_print_host_state(hba);
3541 ufshcd_print_pwr_info(hba);
3542 ufshcd_print_host_regs(hba);
3545 spin_lock_irqsave(hba->host->host_lock, flags);
3546 hba->active_uic_cmd = NULL;
3547 hba->uic_async_done = NULL;
3549 ufshcd_enable_intr(hba, UIC_COMMAND_COMPL);
3550 spin_unlock_irqrestore(hba->host->host_lock, flags);
3551 mutex_unlock(&hba->uic_cmd_mutex);
3557 * ufshcd_uic_change_pwr_mode - Perform the UIC power mode chage
3558 * using DME_SET primitives.
3559 * @hba: per adapter instance
3560 * @mode: powr mode value
3562 * Returns 0 on success, non-zero value on failure
3564 static int ufshcd_uic_change_pwr_mode(struct ufs_hba *hba, u8 mode)
3566 struct uic_command uic_cmd = {0};
3569 if (hba->quirks & UFSHCD_QUIRK_BROKEN_PA_RXHSUNTERMCAP) {
3570 ret = ufshcd_dme_set(hba,
3571 UIC_ARG_MIB_SEL(PA_RXHSUNTERMCAP, 0), 1);
3573 dev_err(hba->dev, "%s: failed to enable PA_RXHSUNTERMCAP ret %d\n",
3579 uic_cmd.command = UIC_CMD_DME_SET;
3580 uic_cmd.argument1 = UIC_ARG_MIB(PA_PWRMODE);
3581 uic_cmd.argument3 = mode;
3582 ufshcd_hold(hba, false);
3583 ret = ufshcd_uic_pwr_ctrl(hba, &uic_cmd);
3584 ufshcd_release(hba);
3590 static int ufshcd_link_recovery(struct ufs_hba *hba)
3593 unsigned long flags;
3595 spin_lock_irqsave(hba->host->host_lock, flags);
3596 hba->ufshcd_state = UFSHCD_STATE_RESET;
3597 ufshcd_set_eh_in_progress(hba);
3598 spin_unlock_irqrestore(hba->host->host_lock, flags);
3600 ret = ufshcd_host_reset_and_restore(hba);
3602 spin_lock_irqsave(hba->host->host_lock, flags);
3604 hba->ufshcd_state = UFSHCD_STATE_ERROR;
3605 ufshcd_clear_eh_in_progress(hba);
3606 spin_unlock_irqrestore(hba->host->host_lock, flags);
3609 dev_err(hba->dev, "%s: link recovery failed, err %d",
3615 static int __ufshcd_uic_hibern8_enter(struct ufs_hba *hba)
3618 struct uic_command uic_cmd = {0};
3619 ktime_t start = ktime_get();
3621 ufshcd_vops_hibern8_notify(hba, UIC_CMD_DME_HIBER_ENTER, PRE_CHANGE);
3623 uic_cmd.command = UIC_CMD_DME_HIBER_ENTER;
3624 ret = ufshcd_uic_pwr_ctrl(hba, &uic_cmd);
3625 trace_ufshcd_profile_hibern8(dev_name(hba->dev), "enter",
3626 ktime_to_us(ktime_sub(ktime_get(), start)), ret);
3629 dev_err(hba->dev, "%s: hibern8 enter failed. ret = %d\n",
3633 * If link recovery fails then return error so that caller
3634 * don't retry the hibern8 enter again.
3636 if (ufshcd_link_recovery(hba))
3639 ufshcd_vops_hibern8_notify(hba, UIC_CMD_DME_HIBER_ENTER,
3645 static int ufshcd_uic_hibern8_enter(struct ufs_hba *hba)
3647 int ret = 0, retries;
3649 for (retries = UIC_HIBERN8_ENTER_RETRIES; retries > 0; retries--) {
3650 ret = __ufshcd_uic_hibern8_enter(hba);
3651 if (!ret || ret == -ENOLINK)
3658 static int ufshcd_uic_hibern8_exit(struct ufs_hba *hba)
3660 struct uic_command uic_cmd = {0};
3662 ktime_t start = ktime_get();
3664 ufshcd_vops_hibern8_notify(hba, UIC_CMD_DME_HIBER_EXIT, PRE_CHANGE);
3666 uic_cmd.command = UIC_CMD_DME_HIBER_EXIT;
3667 ret = ufshcd_uic_pwr_ctrl(hba, &uic_cmd);
3668 trace_ufshcd_profile_hibern8(dev_name(hba->dev), "exit",
3669 ktime_to_us(ktime_sub(ktime_get(), start)), ret);
3672 dev_err(hba->dev, "%s: hibern8 exit failed. ret = %d\n",
3674 ret = ufshcd_link_recovery(hba);
3676 ufshcd_vops_hibern8_notify(hba, UIC_CMD_DME_HIBER_EXIT,
3678 hba->ufs_stats.last_hibern8_exit_tstamp = ktime_get();
3679 hba->ufs_stats.hibern8_exit_cnt++;
3686 * ufshcd_init_pwr_info - setting the POR (power on reset)
3687 * values in hba power info
3688 * @hba: per-adapter instance
3690 static void ufshcd_init_pwr_info(struct ufs_hba *hba)
3692 hba->pwr_info.gear_rx = UFS_PWM_G1;
3693 hba->pwr_info.gear_tx = UFS_PWM_G1;
3694 hba->pwr_info.lane_rx = 1;
3695 hba->pwr_info.lane_tx = 1;
3696 hba->pwr_info.pwr_rx = SLOWAUTO_MODE;
3697 hba->pwr_info.pwr_tx = SLOWAUTO_MODE;
3698 hba->pwr_info.hs_rate = 0;
3702 * ufshcd_get_max_pwr_mode - reads the max power mode negotiated with device
3703 * @hba: per-adapter instance
3705 static int ufshcd_get_max_pwr_mode(struct ufs_hba *hba)
3707 struct ufs_pa_layer_attr *pwr_info = &hba->max_pwr_info.info;
3709 if (hba->max_pwr_info.is_valid)
3712 pwr_info->pwr_tx = FAST_MODE;
3713 pwr_info->pwr_rx = FAST_MODE;
3714 pwr_info->hs_rate = PA_HS_MODE_B;
3716 /* Get the connected lane count */
3717 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_CONNECTEDRXDATALANES),
3718 &pwr_info->lane_rx);
3719 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_CONNECTEDTXDATALANES),
3720 &pwr_info->lane_tx);
3722 if (!pwr_info->lane_rx || !pwr_info->lane_tx) {
3723 dev_err(hba->dev, "%s: invalid connected lanes value. rx=%d, tx=%d\n",
3731 * First, get the maximum gears of HS speed.
3732 * If a zero value, it means there is no HSGEAR capability.
3733 * Then, get the maximum gears of PWM speed.
3735 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_MAXRXHSGEAR), &pwr_info->gear_rx);
3736 if (!pwr_info->gear_rx) {
3737 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_MAXRXPWMGEAR),
3738 &pwr_info->gear_rx);
3739 if (!pwr_info->gear_rx) {
3740 dev_err(hba->dev, "%s: invalid max pwm rx gear read = %d\n",
3741 __func__, pwr_info->gear_rx);
3744 pwr_info->pwr_rx = SLOW_MODE;
3747 ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_MAXRXHSGEAR),
3748 &pwr_info->gear_tx);
3749 if (!pwr_info->gear_tx) {
3750 ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_MAXRXPWMGEAR),
3751 &pwr_info->gear_tx);
3752 if (!pwr_info->gear_tx) {
3753 dev_err(hba->dev, "%s: invalid max pwm tx gear read = %d\n",
3754 __func__, pwr_info->gear_tx);
3757 pwr_info->pwr_tx = SLOW_MODE;
3760 hba->max_pwr_info.is_valid = true;
3764 static int ufshcd_change_power_mode(struct ufs_hba *hba,
3765 struct ufs_pa_layer_attr *pwr_mode)
3769 /* if already configured to the requested pwr_mode */
3770 if (pwr_mode->gear_rx == hba->pwr_info.gear_rx &&
3771 pwr_mode->gear_tx == hba->pwr_info.gear_tx &&
3772 pwr_mode->lane_rx == hba->pwr_info.lane_rx &&
3773 pwr_mode->lane_tx == hba->pwr_info.lane_tx &&
3774 pwr_mode->pwr_rx == hba->pwr_info.pwr_rx &&
3775 pwr_mode->pwr_tx == hba->pwr_info.pwr_tx &&
3776 pwr_mode->hs_rate == hba->pwr_info.hs_rate) {
3777 dev_dbg(hba->dev, "%s: power already configured\n", __func__);
3782 * Configure attributes for power mode change with below.
3783 * - PA_RXGEAR, PA_ACTIVERXDATALANES, PA_RXTERMINATION,
3784 * - PA_TXGEAR, PA_ACTIVETXDATALANES, PA_TXTERMINATION,
3787 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_RXGEAR), pwr_mode->gear_rx);
3788 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_ACTIVERXDATALANES),
3790 if (pwr_mode->pwr_rx == FASTAUTO_MODE ||
3791 pwr_mode->pwr_rx == FAST_MODE)
3792 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_RXTERMINATION), TRUE);
3794 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_RXTERMINATION), FALSE);
3796 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TXGEAR), pwr_mode->gear_tx);
3797 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_ACTIVETXDATALANES),
3799 if (pwr_mode->pwr_tx == FASTAUTO_MODE ||
3800 pwr_mode->pwr_tx == FAST_MODE)
3801 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TXTERMINATION), TRUE);
3803 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TXTERMINATION), FALSE);
3805 if (pwr_mode->pwr_rx == FASTAUTO_MODE ||
3806 pwr_mode->pwr_tx == FASTAUTO_MODE ||
3807 pwr_mode->pwr_rx == FAST_MODE ||
3808 pwr_mode->pwr_tx == FAST_MODE)
3809 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_HSSERIES),
3812 ret = ufshcd_uic_change_pwr_mode(hba, pwr_mode->pwr_rx << 4
3813 | pwr_mode->pwr_tx);
3817 "%s: power mode change failed %d\n", __func__, ret);
3819 ufshcd_vops_pwr_change_notify(hba, POST_CHANGE, NULL,
3822 memcpy(&hba->pwr_info, pwr_mode,
3823 sizeof(struct ufs_pa_layer_attr));
3830 * ufshcd_config_pwr_mode - configure a new power mode
3831 * @hba: per-adapter instance
3832 * @desired_pwr_mode: desired power configuration
3834 static int ufshcd_config_pwr_mode(struct ufs_hba *hba,
3835 struct ufs_pa_layer_attr *desired_pwr_mode)
3837 struct ufs_pa_layer_attr final_params = { 0 };
3840 ret = ufshcd_vops_pwr_change_notify(hba, PRE_CHANGE,
3841 desired_pwr_mode, &final_params);
3844 memcpy(&final_params, desired_pwr_mode, sizeof(final_params));
3846 ret = ufshcd_change_power_mode(hba, &final_params);
3848 ufshcd_print_pwr_info(hba);
3854 * ufshcd_complete_dev_init() - checks device readiness
3855 * hba: per-adapter instance
3857 * Set fDeviceInit flag and poll until device toggles it.
3859 static int ufshcd_complete_dev_init(struct ufs_hba *hba)
3865 err = ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_SET_FLAG,
3866 QUERY_FLAG_IDN_FDEVICEINIT, NULL);
3869 "%s setting fDeviceInit flag failed with error %d\n",
3874 /* poll for max. 1000 iterations for fDeviceInit flag to clear */
3875 for (i = 0; i < 1000 && !err && flag_res; i++)
3876 err = ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_READ_FLAG,
3877 QUERY_FLAG_IDN_FDEVICEINIT, &flag_res);
3881 "%s reading fDeviceInit flag failed with error %d\n",
3885 "%s fDeviceInit was not cleared by the device\n",
3893 * ufshcd_make_hba_operational - Make UFS controller operational
3894 * @hba: per adapter instance
3896 * To bring UFS host controller to operational state,
3897 * 1. Enable required interrupts
3898 * 2. Configure interrupt aggregation
3899 * 3. Program UTRL and UTMRL base address
3900 * 4. Configure run-stop-registers
3902 * Returns 0 on success, non-zero value on failure
3904 static int ufshcd_make_hba_operational(struct ufs_hba *hba)
3909 /* Enable required interrupts */
3910 ufshcd_enable_intr(hba, UFSHCD_ENABLE_INTRS);
3912 /* Configure interrupt aggregation */
3913 if (ufshcd_is_intr_aggr_allowed(hba))
3914 ufshcd_config_intr_aggr(hba, hba->nutrs - 1, INT_AGGR_DEF_TO);
3916 ufshcd_disable_intr_aggr(hba);
3918 /* Configure UTRL and UTMRL base address registers */
3919 ufshcd_writel(hba, lower_32_bits(hba->utrdl_dma_addr),
3920 REG_UTP_TRANSFER_REQ_LIST_BASE_L);
3921 ufshcd_writel(hba, upper_32_bits(hba->utrdl_dma_addr),
3922 REG_UTP_TRANSFER_REQ_LIST_BASE_H);
3923 ufshcd_writel(hba, lower_32_bits(hba->utmrdl_dma_addr),
3924 REG_UTP_TASK_REQ_LIST_BASE_L);
3925 ufshcd_writel(hba, upper_32_bits(hba->utmrdl_dma_addr),
3926 REG_UTP_TASK_REQ_LIST_BASE_H);
3929 * Make sure base address and interrupt setup are updated before
3930 * enabling the run/stop registers below.
3935 * UCRDY, UTMRLDY and UTRLRDY bits must be 1
3937 reg = ufshcd_readl(hba, REG_CONTROLLER_STATUS);
3938 if (!(ufshcd_get_lists_status(reg))) {
3939 ufshcd_enable_run_stop_reg(hba);
3942 "Host controller not ready to process requests");
3952 * ufshcd_hba_stop - Send controller to reset state
3953 * @hba: per adapter instance
3954 * @can_sleep: perform sleep or just spin
3956 static inline void ufshcd_hba_stop(struct ufs_hba *hba, bool can_sleep)
3960 ufshcd_writel(hba, CONTROLLER_DISABLE, REG_CONTROLLER_ENABLE);
3961 err = ufshcd_wait_for_register(hba, REG_CONTROLLER_ENABLE,
3962 CONTROLLER_ENABLE, CONTROLLER_DISABLE,
3965 dev_err(hba->dev, "%s: Controller disable failed\n", __func__);
3969 * ufshcd_hba_enable - initialize the controller
3970 * @hba: per adapter instance
3972 * The controller resets itself and controller firmware initialization
3973 * sequence kicks off. When controller is ready it will set
3974 * the Host Controller Enable bit to 1.
3976 * Returns 0 on success, non-zero value on failure
3978 static int ufshcd_hba_enable(struct ufs_hba *hba)
3983 * msleep of 1 and 5 used in this function might result in msleep(20),
3984 * but it was necessary to send the UFS FPGA to reset mode during
3985 * development and testing of this driver. msleep can be changed to
3986 * mdelay and retry count can be reduced based on the controller.
3988 if (!ufshcd_is_hba_active(hba))
3989 /* change controller state to "reset state" */
3990 ufshcd_hba_stop(hba, true);
3992 /* UniPro link is disabled at this point */
3993 ufshcd_set_link_off(hba);
3995 ufshcd_vops_hce_enable_notify(hba, PRE_CHANGE);
3997 /* start controller initialization sequence */
3998 ufshcd_hba_start(hba);
4001 * To initialize a UFS host controller HCE bit must be set to 1.
4002 * During initialization the HCE bit value changes from 1->0->1.
4003 * When the host controller completes initialization sequence
4004 * it sets the value of HCE bit to 1. The same HCE bit is read back
4005 * to check if the controller has completed initialization sequence.
4006 * So without this delay the value HCE = 1, set in the previous
4007 * instruction might be read back.
4008 * This delay can be changed based on the controller.
4012 /* wait for the host controller to complete initialization */
4014 while (ufshcd_is_hba_active(hba)) {
4019 "Controller enable failed\n");
4025 /* enable UIC related interrupts */
4026 ufshcd_enable_intr(hba, UFSHCD_UIC_MASK);
4028 ufshcd_vops_hce_enable_notify(hba, POST_CHANGE);
4033 static int ufshcd_disable_tx_lcc(struct ufs_hba *hba, bool peer)
4035 int tx_lanes, i, err = 0;
4038 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_CONNECTEDTXDATALANES),
4041 ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_CONNECTEDTXDATALANES),
4043 for (i = 0; i < tx_lanes; i++) {
4045 err = ufshcd_dme_set(hba,
4046 UIC_ARG_MIB_SEL(TX_LCC_ENABLE,
4047 UIC_ARG_MPHY_TX_GEN_SEL_INDEX(i)),
4050 err = ufshcd_dme_peer_set(hba,
4051 UIC_ARG_MIB_SEL(TX_LCC_ENABLE,
4052 UIC_ARG_MPHY_TX_GEN_SEL_INDEX(i)),
4055 dev_err(hba->dev, "%s: TX LCC Disable failed, peer = %d, lane = %d, err = %d",
4056 __func__, peer, i, err);
4064 static inline int ufshcd_disable_device_tx_lcc(struct ufs_hba *hba)
4066 return ufshcd_disable_tx_lcc(hba, true);
4070 * ufshcd_link_startup - Initialize unipro link startup
4071 * @hba: per adapter instance
4073 * Returns 0 for success, non-zero in case of failure
4075 static int ufshcd_link_startup(struct ufs_hba *hba)
4078 int retries = DME_LINKSTARTUP_RETRIES;
4079 bool link_startup_again = false;
4082 * If UFS device isn't active then we will have to issue link startup
4083 * 2 times to make sure the device state move to active.
4085 if (!ufshcd_is_ufs_dev_active(hba))
4086 link_startup_again = true;
4090 ufshcd_vops_link_startup_notify(hba, PRE_CHANGE);
4092 ret = ufshcd_dme_link_startup(hba);
4094 /* check if device is detected by inter-connect layer */
4095 if (!ret && !ufshcd_is_device_present(hba)) {
4096 dev_err(hba->dev, "%s: Device not present\n", __func__);
4102 * DME link lost indication is only received when link is up,
4103 * but we can't be sure if the link is up until link startup
4104 * succeeds. So reset the local Uni-Pro and try again.
4106 if (ret && ufshcd_hba_enable(hba))
4108 } while (ret && retries--);
4111 /* failed to get the link up... retire */
4114 if (link_startup_again) {
4115 link_startup_again = false;
4116 retries = DME_LINKSTARTUP_RETRIES;
4120 /* Mark that link is up in PWM-G1, 1-lane, SLOW-AUTO mode */
4121 ufshcd_init_pwr_info(hba);
4122 ufshcd_print_pwr_info(hba);
4124 if (hba->quirks & UFSHCD_QUIRK_BROKEN_LCC) {
4125 ret = ufshcd_disable_device_tx_lcc(hba);
4130 /* Include any host controller configuration via UIC commands */
4131 ret = ufshcd_vops_link_startup_notify(hba, POST_CHANGE);
4135 ret = ufshcd_make_hba_operational(hba);
4138 dev_err(hba->dev, "link startup failed %d\n", ret);
4139 ufshcd_print_host_state(hba);
4140 ufshcd_print_pwr_info(hba);
4141 ufshcd_print_host_regs(hba);
4147 * ufshcd_verify_dev_init() - Verify device initialization
4148 * @hba: per-adapter instance
4150 * Send NOP OUT UPIU and wait for NOP IN response to check whether the
4151 * device Transport Protocol (UTP) layer is ready after a reset.
4152 * If the UTP layer at the device side is not initialized, it may
4153 * not respond with NOP IN UPIU within timeout of %NOP_OUT_TIMEOUT
4154 * and we retry sending NOP OUT for %NOP_OUT_RETRIES iterations.
4156 static int ufshcd_verify_dev_init(struct ufs_hba *hba)
4161 ufshcd_hold(hba, false);
4162 mutex_lock(&hba->dev_cmd.lock);
4163 for (retries = NOP_OUT_RETRIES; retries > 0; retries--) {
4164 err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_NOP,
4167 if (!err || err == -ETIMEDOUT)
4170 dev_dbg(hba->dev, "%s: error %d retrying\n", __func__, err);
4172 mutex_unlock(&hba->dev_cmd.lock);
4173 ufshcd_release(hba);
4176 dev_err(hba->dev, "%s: NOP OUT failed %d\n", __func__, err);
4181 * ufshcd_set_queue_depth - set lun queue depth
4182 * @sdev: pointer to SCSI device
4184 * Read bLUQueueDepth value and activate scsi tagged command
4185 * queueing. For WLUN, queue depth is set to 1. For best-effort
4186 * cases (bLUQueueDepth = 0) the queue depth is set to a maximum
4187 * value that host can queue.
4189 static void ufshcd_set_queue_depth(struct scsi_device *sdev)
4193 struct ufs_hba *hba;
4195 hba = shost_priv(sdev->host);
4197 lun_qdepth = hba->nutrs;
4198 ret = ufshcd_read_unit_desc_param(hba,
4199 ufshcd_scsi_to_upiu_lun(sdev->lun),
4200 UNIT_DESC_PARAM_LU_Q_DEPTH,
4202 sizeof(lun_qdepth));
4204 /* Some WLUN doesn't support unit descriptor */
4205 if (ret == -EOPNOTSUPP)
4207 else if (!lun_qdepth)
4208 /* eventually, we can figure out the real queue depth */
4209 lun_qdepth = hba->nutrs;
4211 lun_qdepth = min_t(int, lun_qdepth, hba->nutrs);
4213 dev_dbg(hba->dev, "%s: activate tcq with queue depth %d\n",
4214 __func__, lun_qdepth);
4215 scsi_change_queue_depth(sdev, lun_qdepth);
4219 * ufshcd_get_lu_wp - returns the "b_lu_write_protect" from UNIT DESCRIPTOR
4220 * @hba: per-adapter instance
4221 * @lun: UFS device lun id
4222 * @b_lu_write_protect: pointer to buffer to hold the LU's write protect info
4224 * Returns 0 in case of success and b_lu_write_protect status would be returned
4225 * @b_lu_write_protect parameter.
4226 * Returns -ENOTSUPP if reading b_lu_write_protect is not supported.
4227 * Returns -EINVAL in case of invalid parameters passed to this function.
4229 static int ufshcd_get_lu_wp(struct ufs_hba *hba,
4231 u8 *b_lu_write_protect)
4235 if (!b_lu_write_protect)
4238 * According to UFS device spec, RPMB LU can't be write
4239 * protected so skip reading bLUWriteProtect parameter for
4240 * it. For other W-LUs, UNIT DESCRIPTOR is not available.
4242 else if (lun >= UFS_UPIU_MAX_GENERAL_LUN)
4245 ret = ufshcd_read_unit_desc_param(hba,
4247 UNIT_DESC_PARAM_LU_WR_PROTECT,
4249 sizeof(*b_lu_write_protect));
4254 * ufshcd_get_lu_power_on_wp_status - get LU's power on write protect
4256 * @hba: per-adapter instance
4257 * @sdev: pointer to SCSI device
4260 static inline void ufshcd_get_lu_power_on_wp_status(struct ufs_hba *hba,
4261 struct scsi_device *sdev)
4263 if (hba->dev_info.f_power_on_wp_en &&
4264 !hba->dev_info.is_lu_power_on_wp) {
4265 u8 b_lu_write_protect;
4267 if (!ufshcd_get_lu_wp(hba, ufshcd_scsi_to_upiu_lun(sdev->lun),
4268 &b_lu_write_protect) &&
4269 (b_lu_write_protect == UFS_LU_POWER_ON_WP))
4270 hba->dev_info.is_lu_power_on_wp = true;
4275 * ufshcd_slave_alloc - handle initial SCSI device configurations
4276 * @sdev: pointer to SCSI device
4280 static int ufshcd_slave_alloc(struct scsi_device *sdev)
4282 struct ufs_hba *hba;
4284 hba = shost_priv(sdev->host);
4286 /* Mode sense(6) is not supported by UFS, so use Mode sense(10) */
4287 sdev->use_10_for_ms = 1;
4289 /* allow SCSI layer to restart the device in case of errors */
4290 sdev->allow_restart = 1;
4292 /* REPORT SUPPORTED OPERATION CODES is not supported */
4293 sdev->no_report_opcodes = 1;
4296 ufshcd_set_queue_depth(sdev);
4298 ufshcd_get_lu_power_on_wp_status(hba, sdev);
4304 * ufshcd_change_queue_depth - change queue depth
4305 * @sdev: pointer to SCSI device
4306 * @depth: required depth to set
4308 * Change queue depth and make sure the max. limits are not crossed.
4310 static int ufshcd_change_queue_depth(struct scsi_device *sdev, int depth)
4312 struct ufs_hba *hba = shost_priv(sdev->host);
4314 if (depth > hba->nutrs)
4316 return scsi_change_queue_depth(sdev, depth);
4320 * ufshcd_slave_configure - adjust SCSI device configurations
4321 * @sdev: pointer to SCSI device
4323 static int ufshcd_slave_configure(struct scsi_device *sdev)
4325 struct request_queue *q = sdev->request_queue;
4327 blk_queue_update_dma_pad(q, PRDT_DATA_BYTE_COUNT_PAD - 1);
4328 blk_queue_max_segment_size(q, PRDT_DATA_BYTE_COUNT_MAX);
4334 * ufshcd_slave_destroy - remove SCSI device configurations
4335 * @sdev: pointer to SCSI device
4337 static void ufshcd_slave_destroy(struct scsi_device *sdev)
4339 struct ufs_hba *hba;
4341 hba = shost_priv(sdev->host);
4342 /* Drop the reference as it won't be needed anymore */
4343 if (ufshcd_scsi_to_upiu_lun(sdev->lun) == UFS_UPIU_UFS_DEVICE_WLUN) {
4344 unsigned long flags;
4346 spin_lock_irqsave(hba->host->host_lock, flags);
4347 hba->sdev_ufs_device = NULL;
4348 spin_unlock_irqrestore(hba->host->host_lock, flags);
4353 * ufshcd_task_req_compl - handle task management request completion
4354 * @hba: per adapter instance
4355 * @index: index of the completed request
4356 * @resp: task management service response
4358 * Returns non-zero value on error, zero on success
4360 static int ufshcd_task_req_compl(struct ufs_hba *hba, u32 index, u8 *resp)
4362 struct utp_task_req_desc *task_req_descp;
4363 struct utp_upiu_task_rsp *task_rsp_upiup;
4364 unsigned long flags;
4368 spin_lock_irqsave(hba->host->host_lock, flags);
4370 /* Clear completed tasks from outstanding_tasks */
4371 __clear_bit(index, &hba->outstanding_tasks);
4373 task_req_descp = hba->utmrdl_base_addr;
4374 ocs_value = ufshcd_get_tmr_ocs(&task_req_descp[index]);
4376 if (ocs_value == OCS_SUCCESS) {
4377 task_rsp_upiup = (struct utp_upiu_task_rsp *)
4378 task_req_descp[index].task_rsp_upiu;
4379 task_result = be32_to_cpu(task_rsp_upiup->output_param1);
4380 task_result = task_result & MASK_TM_SERVICE_RESP;
4382 *resp = (u8)task_result;
4384 dev_err(hba->dev, "%s: failed, ocs = 0x%x\n",
4385 __func__, ocs_value);
4387 spin_unlock_irqrestore(hba->host->host_lock, flags);
4393 * ufshcd_scsi_cmd_status - Update SCSI command result based on SCSI status
4394 * @lrb: pointer to local reference block of completed command
4395 * @scsi_status: SCSI command status
4397 * Returns value base on SCSI command status
4400 ufshcd_scsi_cmd_status(struct ufshcd_lrb *lrbp, int scsi_status)
4404 switch (scsi_status) {
4405 case SAM_STAT_CHECK_CONDITION:
4406 ufshcd_copy_sense_data(lrbp);
4408 result |= DID_OK << 16 |
4409 COMMAND_COMPLETE << 8 |
4412 case SAM_STAT_TASK_SET_FULL:
4414 case SAM_STAT_TASK_ABORTED:
4415 ufshcd_copy_sense_data(lrbp);
4416 result |= scsi_status;
4419 result |= DID_ERROR << 16;
4421 } /* end of switch */
4427 * ufshcd_transfer_rsp_status - Get overall status of the response
4428 * @hba: per adapter instance
4429 * @lrb: pointer to local reference block of completed command
4431 * Returns result of the command to notify SCSI midlayer
4434 ufshcd_transfer_rsp_status(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
4440 /* overall command status of utrd */
4441 ocs = ufshcd_get_tr_ocs(lrbp);
4445 result = ufshcd_get_req_rsp(lrbp->ucd_rsp_ptr);
4446 hba->ufs_stats.last_hibern8_exit_tstamp = ktime_set(0, 0);
4448 case UPIU_TRANSACTION_RESPONSE:
4450 * get the response UPIU result to extract
4451 * the SCSI command status
4453 result = ufshcd_get_rsp_upiu_result(lrbp->ucd_rsp_ptr);
4456 * get the result based on SCSI status response
4457 * to notify the SCSI midlayer of the command status
4459 scsi_status = result & MASK_SCSI_STATUS;
4460 result = ufshcd_scsi_cmd_status(lrbp, scsi_status);
4463 * Currently we are only supporting BKOPs exception
4464 * events hence we can ignore BKOPs exception event
4465 * during power management callbacks. BKOPs exception
4466 * event is not expected to be raised in runtime suspend
4467 * callback as it allows the urgent bkops.
4468 * During system suspend, we are anyway forcefully
4469 * disabling the bkops and if urgent bkops is needed
4470 * it will be enabled on system resume. Long term
4471 * solution could be to abort the system suspend if
4472 * UFS device needs urgent BKOPs.
4474 if (!hba->pm_op_in_progress &&
4475 ufshcd_is_exception_event(lrbp->ucd_rsp_ptr))
4476 schedule_work(&hba->eeh_work);
4478 case UPIU_TRANSACTION_REJECT_UPIU:
4479 /* TODO: handle Reject UPIU Response */
4480 result = DID_ERROR << 16;
4482 "Reject UPIU not fully implemented\n");
4485 result = DID_ERROR << 16;
4487 "Unexpected request response code = %x\n",
4493 result |= DID_ABORT << 16;
4495 case OCS_INVALID_COMMAND_STATUS:
4496 result |= DID_REQUEUE << 16;
4498 case OCS_INVALID_CMD_TABLE_ATTR:
4499 case OCS_INVALID_PRDT_ATTR:
4500 case OCS_MISMATCH_DATA_BUF_SIZE:
4501 case OCS_MISMATCH_RESP_UPIU_SIZE:
4502 case OCS_PEER_COMM_FAILURE:
4503 case OCS_FATAL_ERROR:
4505 result |= DID_ERROR << 16;
4507 "OCS error from controller = %x for tag %d\n",
4508 ocs, lrbp->task_tag);
4509 ufshcd_print_host_regs(hba);
4510 ufshcd_print_host_state(hba);
4512 } /* end of switch */
4514 if (host_byte(result) != DID_OK)
4515 ufshcd_print_trs(hba, 1 << lrbp->task_tag, true);
4520 * ufshcd_uic_cmd_compl - handle completion of uic command
4521 * @hba: per adapter instance
4522 * @intr_status: interrupt status generated by the controller
4524 static void ufshcd_uic_cmd_compl(struct ufs_hba *hba, u32 intr_status)
4526 if ((intr_status & UIC_COMMAND_COMPL) && hba->active_uic_cmd) {
4527 hba->active_uic_cmd->argument2 |=
4528 ufshcd_get_uic_cmd_result(hba);
4529 hba->active_uic_cmd->argument3 =
4530 ufshcd_get_dme_attr_val(hba);
4531 complete(&hba->active_uic_cmd->done);
4534 if ((intr_status & UFSHCD_UIC_PWR_MASK) && hba->uic_async_done)
4535 complete(hba->uic_async_done);
4539 * __ufshcd_transfer_req_compl - handle SCSI and query command completion
4540 * @hba: per adapter instance
4541 * @completed_reqs: requests to complete
4543 static void __ufshcd_transfer_req_compl(struct ufs_hba *hba,
4544 unsigned long completed_reqs)
4546 struct ufshcd_lrb *lrbp;
4547 struct scsi_cmnd *cmd;
4551 for_each_set_bit(index, &completed_reqs, hba->nutrs) {
4552 lrbp = &hba->lrb[index];
4555 ufshcd_add_command_trace(hba, index, "complete");
4556 result = ufshcd_transfer_rsp_status(hba, lrbp);
4557 scsi_dma_unmap(cmd);
4558 cmd->result = result;
4559 /* Mark completed command as NULL in LRB */
4561 clear_bit_unlock(index, &hba->lrb_in_use);
4562 /* Do not touch lrbp after scsi done */
4563 cmd->scsi_done(cmd);
4564 __ufshcd_release(hba);
4565 } else if (lrbp->command_type == UTP_CMD_TYPE_DEV_MANAGE ||
4566 lrbp->command_type == UTP_CMD_TYPE_UFS_STORAGE) {
4567 if (hba->dev_cmd.complete) {
4568 ufshcd_add_command_trace(hba, index,
4570 complete(hba->dev_cmd.complete);
4573 if (ufshcd_is_clkscaling_supported(hba))
4574 hba->clk_scaling.active_reqs--;
4575 if (ufshcd_is_clkscaling_supported(hba))
4576 hba->clk_scaling.active_reqs--;
4579 /* clear corresponding bits of completed commands */
4580 hba->outstanding_reqs ^= completed_reqs;
4582 ufshcd_clk_scaling_update_busy(hba);
4584 /* we might have free'd some tags above */
4585 wake_up(&hba->dev_cmd.tag_wq);
4589 * ufshcd_transfer_req_compl - handle SCSI and query command completion
4590 * @hba: per adapter instance
4592 static void ufshcd_transfer_req_compl(struct ufs_hba *hba)
4594 unsigned long completed_reqs;
4597 /* Resetting interrupt aggregation counters first and reading the
4598 * DOOR_BELL afterward allows us to handle all the completed requests.
4599 * In order to prevent other interrupts starvation the DB is read once
4600 * after reset. The down side of this solution is the possibility of
4601 * false interrupt if device completes another request after resetting
4602 * aggregation and before reading the DB.
4604 if (ufshcd_is_intr_aggr_allowed(hba))
4605 ufshcd_reset_intr_aggr(hba);
4607 tr_doorbell = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
4608 completed_reqs = tr_doorbell ^ hba->outstanding_reqs;
4610 __ufshcd_transfer_req_compl(hba, completed_reqs);
4614 * ufshcd_disable_ee - disable exception event
4615 * @hba: per-adapter instance
4616 * @mask: exception event to disable
4618 * Disables exception event in the device so that the EVENT_ALERT
4621 * Returns zero on success, non-zero error value on failure.
4623 static int ufshcd_disable_ee(struct ufs_hba *hba, u16 mask)
4628 if (!(hba->ee_ctrl_mask & mask))
4631 val = hba->ee_ctrl_mask & ~mask;
4632 val &= 0xFFFF; /* 2 bytes */
4633 err = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_WRITE_ATTR,
4634 QUERY_ATTR_IDN_EE_CONTROL, 0, 0, &val);
4636 hba->ee_ctrl_mask &= ~mask;
4642 * ufshcd_enable_ee - enable exception event
4643 * @hba: per-adapter instance
4644 * @mask: exception event to enable
4646 * Enable corresponding exception event in the device to allow
4647 * device to alert host in critical scenarios.
4649 * Returns zero on success, non-zero error value on failure.
4651 static int ufshcd_enable_ee(struct ufs_hba *hba, u16 mask)
4656 if (hba->ee_ctrl_mask & mask)
4659 val = hba->ee_ctrl_mask | mask;
4660 val &= 0xFFFF; /* 2 bytes */
4661 err = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_WRITE_ATTR,
4662 QUERY_ATTR_IDN_EE_CONTROL, 0, 0, &val);
4664 hba->ee_ctrl_mask |= mask;
4670 * ufshcd_enable_auto_bkops - Allow device managed BKOPS
4671 * @hba: per-adapter instance
4673 * Allow device to manage background operations on its own. Enabling
4674 * this might lead to inconsistent latencies during normal data transfers
4675 * as the device is allowed to manage its own way of handling background
4678 * Returns zero on success, non-zero on failure.
4680 static int ufshcd_enable_auto_bkops(struct ufs_hba *hba)
4684 if (hba->auto_bkops_enabled)
4687 err = ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_SET_FLAG,
4688 QUERY_FLAG_IDN_BKOPS_EN, NULL);
4690 dev_err(hba->dev, "%s: failed to enable bkops %d\n",
4695 hba->auto_bkops_enabled = true;
4696 trace_ufshcd_auto_bkops_state(dev_name(hba->dev), "Enabled");
4698 /* No need of URGENT_BKOPS exception from the device */
4699 err = ufshcd_disable_ee(hba, MASK_EE_URGENT_BKOPS);
4701 dev_err(hba->dev, "%s: failed to disable exception event %d\n",
4708 * ufshcd_disable_auto_bkops - block device in doing background operations
4709 * @hba: per-adapter instance
4711 * Disabling background operations improves command response latency but
4712 * has drawback of device moving into critical state where the device is
4713 * not-operable. Make sure to call ufshcd_enable_auto_bkops() whenever the
4714 * host is idle so that BKOPS are managed effectively without any negative
4717 * Returns zero on success, non-zero on failure.
4719 static int ufshcd_disable_auto_bkops(struct ufs_hba *hba)
4723 if (!hba->auto_bkops_enabled)
4727 * If host assisted BKOPs is to be enabled, make sure
4728 * urgent bkops exception is allowed.
4730 err = ufshcd_enable_ee(hba, MASK_EE_URGENT_BKOPS);
4732 dev_err(hba->dev, "%s: failed to enable exception event %d\n",
4737 err = ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_CLEAR_FLAG,
4738 QUERY_FLAG_IDN_BKOPS_EN, NULL);
4740 dev_err(hba->dev, "%s: failed to disable bkops %d\n",
4742 ufshcd_disable_ee(hba, MASK_EE_URGENT_BKOPS);
4746 hba->auto_bkops_enabled = false;
4747 trace_ufshcd_auto_bkops_state(dev_name(hba->dev), "Disabled");
4753 * ufshcd_force_reset_auto_bkops - force reset auto bkops state
4754 * @hba: per adapter instance
4756 * After a device reset the device may toggle the BKOPS_EN flag
4757 * to default value. The s/w tracking variables should be updated
4758 * as well. This function would change the auto-bkops state based on
4759 * UFSHCD_CAP_KEEP_AUTO_BKOPS_ENABLED_EXCEPT_SUSPEND.
4761 static void ufshcd_force_reset_auto_bkops(struct ufs_hba *hba)
4763 if (ufshcd_keep_autobkops_enabled_except_suspend(hba)) {
4764 hba->auto_bkops_enabled = false;
4765 hba->ee_ctrl_mask |= MASK_EE_URGENT_BKOPS;
4766 ufshcd_enable_auto_bkops(hba);
4768 hba->auto_bkops_enabled = true;
4769 hba->ee_ctrl_mask &= ~MASK_EE_URGENT_BKOPS;
4770 ufshcd_disable_auto_bkops(hba);
4774 static inline int ufshcd_get_bkops_status(struct ufs_hba *hba, u32 *status)
4776 return ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
4777 QUERY_ATTR_IDN_BKOPS_STATUS, 0, 0, status);
4781 * ufshcd_bkops_ctrl - control the auto bkops based on current bkops status
4782 * @hba: per-adapter instance
4783 * @status: bkops_status value
4785 * Read the bkops_status from the UFS device and Enable fBackgroundOpsEn
4786 * flag in the device to permit background operations if the device
4787 * bkops_status is greater than or equal to "status" argument passed to
4788 * this function, disable otherwise.
4790 * Returns 0 for success, non-zero in case of failure.
4792 * NOTE: Caller of this function can check the "hba->auto_bkops_enabled" flag
4793 * to know whether auto bkops is enabled or disabled after this function
4794 * returns control to it.
4796 static int ufshcd_bkops_ctrl(struct ufs_hba *hba,
4797 enum bkops_status status)
4800 u32 curr_status = 0;
4802 err = ufshcd_get_bkops_status(hba, &curr_status);
4804 dev_err(hba->dev, "%s: failed to get BKOPS status %d\n",
4807 } else if (curr_status > BKOPS_STATUS_MAX) {
4808 dev_err(hba->dev, "%s: invalid BKOPS status %d\n",
4809 __func__, curr_status);
4814 if (curr_status >= status)
4815 err = ufshcd_enable_auto_bkops(hba);
4817 err = ufshcd_disable_auto_bkops(hba);
4823 * ufshcd_urgent_bkops - handle urgent bkops exception event
4824 * @hba: per-adapter instance
4826 * Enable fBackgroundOpsEn flag in the device to permit background
4829 * If BKOPs is enabled, this function returns 0, 1 if the bkops in not enabled
4830 * and negative error value for any other failure.
4832 static int ufshcd_urgent_bkops(struct ufs_hba *hba)
4834 return ufshcd_bkops_ctrl(hba, hba->urgent_bkops_lvl);
4837 static inline int ufshcd_get_ee_status(struct ufs_hba *hba, u32 *status)
4839 return ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
4840 QUERY_ATTR_IDN_EE_STATUS, 0, 0, status);
4843 static void ufshcd_bkops_exception_event_handler(struct ufs_hba *hba)
4846 u32 curr_status = 0;
4848 if (hba->is_urgent_bkops_lvl_checked)
4849 goto enable_auto_bkops;
4851 err = ufshcd_get_bkops_status(hba, &curr_status);
4853 dev_err(hba->dev, "%s: failed to get BKOPS status %d\n",
4859 * We are seeing that some devices are raising the urgent bkops
4860 * exception events even when BKOPS status doesn't indicate performace
4861 * impacted or critical. Handle these device by determining their urgent
4862 * bkops status at runtime.
4864 if (curr_status < BKOPS_STATUS_PERF_IMPACT) {
4865 dev_err(hba->dev, "%s: device raised urgent BKOPS exception for bkops status %d\n",
4866 __func__, curr_status);
4867 /* update the current status as the urgent bkops level */
4868 hba->urgent_bkops_lvl = curr_status;
4869 hba->is_urgent_bkops_lvl_checked = true;
4873 err = ufshcd_enable_auto_bkops(hba);
4876 dev_err(hba->dev, "%s: failed to handle urgent bkops %d\n",
4881 * ufshcd_exception_event_handler - handle exceptions raised by device
4882 * @work: pointer to work data
4884 * Read bExceptionEventStatus attribute from the device and handle the
4885 * exception event accordingly.
4887 static void ufshcd_exception_event_handler(struct work_struct *work)
4889 struct ufs_hba *hba;
4892 hba = container_of(work, struct ufs_hba, eeh_work);
4894 pm_runtime_get_sync(hba->dev);
4895 err = ufshcd_get_ee_status(hba, &status);
4897 dev_err(hba->dev, "%s: failed to get exception status %d\n",
4902 status &= hba->ee_ctrl_mask;
4904 if (status & MASK_EE_URGENT_BKOPS)
4905 ufshcd_bkops_exception_event_handler(hba);
4908 pm_runtime_put_sync(hba->dev);
4912 /* Complete requests that have door-bell cleared */
4913 static void ufshcd_complete_requests(struct ufs_hba *hba)
4915 ufshcd_transfer_req_compl(hba);
4916 ufshcd_tmc_handler(hba);
4920 * ufshcd_quirk_dl_nac_errors - This function checks if error handling is
4921 * to recover from the DL NAC errors or not.
4922 * @hba: per-adapter instance
4924 * Returns true if error handling is required, false otherwise
4926 static bool ufshcd_quirk_dl_nac_errors(struct ufs_hba *hba)
4928 unsigned long flags;
4929 bool err_handling = true;
4931 spin_lock_irqsave(hba->host->host_lock, flags);
4933 * UFS_DEVICE_QUIRK_RECOVERY_FROM_DL_NAC_ERRORS only workaround the
4934 * device fatal error and/or DL NAC & REPLAY timeout errors.
4936 if (hba->saved_err & (CONTROLLER_FATAL_ERROR | SYSTEM_BUS_FATAL_ERROR))
4939 if ((hba->saved_err & DEVICE_FATAL_ERROR) ||
4940 ((hba->saved_err & UIC_ERROR) &&
4941 (hba->saved_uic_err & UFSHCD_UIC_DL_TCx_REPLAY_ERROR)))
4944 if ((hba->saved_err & UIC_ERROR) &&
4945 (hba->saved_uic_err & UFSHCD_UIC_DL_NAC_RECEIVED_ERROR)) {
4948 * wait for 50ms to see if we can get any other errors or not.
4950 spin_unlock_irqrestore(hba->host->host_lock, flags);
4952 spin_lock_irqsave(hba->host->host_lock, flags);
4955 * now check if we have got any other severe errors other than
4958 if ((hba->saved_err & INT_FATAL_ERRORS) ||
4959 ((hba->saved_err & UIC_ERROR) &&
4960 (hba->saved_uic_err & ~UFSHCD_UIC_DL_NAC_RECEIVED_ERROR)))
4964 * As DL NAC is the only error received so far, send out NOP
4965 * command to confirm if link is still active or not.
4966 * - If we don't get any response then do error recovery.
4967 * - If we get response then clear the DL NAC error bit.
4970 spin_unlock_irqrestore(hba->host->host_lock, flags);
4971 err = ufshcd_verify_dev_init(hba);
4972 spin_lock_irqsave(hba->host->host_lock, flags);
4977 /* Link seems to be alive hence ignore the DL NAC errors */
4978 if (hba->saved_uic_err == UFSHCD_UIC_DL_NAC_RECEIVED_ERROR)
4979 hba->saved_err &= ~UIC_ERROR;
4980 /* clear NAC error */
4981 hba->saved_uic_err &= ~UFSHCD_UIC_DL_NAC_RECEIVED_ERROR;
4982 if (!hba->saved_uic_err) {
4983 err_handling = false;
4988 spin_unlock_irqrestore(hba->host->host_lock, flags);
4989 return err_handling;
4993 * ufshcd_err_handler - handle UFS errors that require s/w attention
4994 * @work: pointer to work structure
4996 static void ufshcd_err_handler(struct work_struct *work)
4998 struct ufs_hba *hba;
4999 unsigned long flags;
5004 bool needs_reset = false;
5006 hba = container_of(work, struct ufs_hba, eh_work);
5008 pm_runtime_get_sync(hba->dev);
5009 ufshcd_hold(hba, false);
5011 spin_lock_irqsave(hba->host->host_lock, flags);
5012 if (hba->ufshcd_state == UFSHCD_STATE_RESET)
5015 hba->ufshcd_state = UFSHCD_STATE_RESET;
5016 ufshcd_set_eh_in_progress(hba);
5018 /* Complete requests that have door-bell cleared by h/w */
5019 ufshcd_complete_requests(hba);
5021 if (hba->dev_quirks & UFS_DEVICE_QUIRK_RECOVERY_FROM_DL_NAC_ERRORS) {
5024 spin_unlock_irqrestore(hba->host->host_lock, flags);
5025 /* release the lock as ufshcd_quirk_dl_nac_errors() may sleep */
5026 ret = ufshcd_quirk_dl_nac_errors(hba);
5027 spin_lock_irqsave(hba->host->host_lock, flags);
5029 goto skip_err_handling;
5031 if ((hba->saved_err & INT_FATAL_ERRORS) ||
5032 ((hba->saved_err & UIC_ERROR) &&
5033 (hba->saved_uic_err & (UFSHCD_UIC_DL_PA_INIT_ERROR |
5034 UFSHCD_UIC_DL_NAC_RECEIVED_ERROR |
5035 UFSHCD_UIC_DL_TCx_REPLAY_ERROR))))
5039 * if host reset is required then skip clearing the pending
5040 * transfers forcefully because they will automatically get
5041 * cleared after link startup.
5044 goto skip_pending_xfer_clear;
5046 /* release lock as clear command might sleep */
5047 spin_unlock_irqrestore(hba->host->host_lock, flags);
5048 /* Clear pending transfer requests */
5049 for_each_set_bit(tag, &hba->outstanding_reqs, hba->nutrs) {
5050 if (ufshcd_clear_cmd(hba, tag)) {
5052 goto lock_skip_pending_xfer_clear;
5056 /* Clear pending task management requests */
5057 for_each_set_bit(tag, &hba->outstanding_tasks, hba->nutmrs) {
5058 if (ufshcd_clear_tm_cmd(hba, tag)) {
5060 goto lock_skip_pending_xfer_clear;
5064 lock_skip_pending_xfer_clear:
5065 spin_lock_irqsave(hba->host->host_lock, flags);
5067 /* Complete the requests that are cleared by s/w */
5068 ufshcd_complete_requests(hba);
5070 if (err_xfer || err_tm)
5073 skip_pending_xfer_clear:
5074 /* Fatal errors need reset */
5076 unsigned long max_doorbells = (1UL << hba->nutrs) - 1;
5079 * ufshcd_reset_and_restore() does the link reinitialization
5080 * which will need atleast one empty doorbell slot to send the
5081 * device management commands (NOP and query commands).
5082 * If there is no slot empty at this moment then free up last
5085 if (hba->outstanding_reqs == max_doorbells)
5086 __ufshcd_transfer_req_compl(hba,
5087 (1UL << (hba->nutrs - 1)));
5089 spin_unlock_irqrestore(hba->host->host_lock, flags);
5090 err = ufshcd_reset_and_restore(hba);
5091 spin_lock_irqsave(hba->host->host_lock, flags);
5093 dev_err(hba->dev, "%s: reset and restore failed\n",
5095 hba->ufshcd_state = UFSHCD_STATE_ERROR;
5098 * Inform scsi mid-layer that we did reset and allow to handle
5099 * Unit Attention properly.
5101 scsi_report_bus_reset(hba->host, 0);
5103 hba->saved_uic_err = 0;
5108 hba->ufshcd_state = UFSHCD_STATE_OPERATIONAL;
5109 if (hba->saved_err || hba->saved_uic_err)
5110 dev_err_ratelimited(hba->dev, "%s: exit: saved_err 0x%x saved_uic_err 0x%x",
5111 __func__, hba->saved_err, hba->saved_uic_err);
5114 ufshcd_clear_eh_in_progress(hba);
5117 spin_unlock_irqrestore(hba->host->host_lock, flags);
5118 scsi_unblock_requests(hba->host);
5119 ufshcd_release(hba);
5120 pm_runtime_put_sync(hba->dev);
5123 static void ufshcd_update_uic_reg_hist(struct ufs_uic_err_reg_hist *reg_hist,
5126 reg_hist->reg[reg_hist->pos] = reg;
5127 reg_hist->tstamp[reg_hist->pos] = ktime_get();
5128 reg_hist->pos = (reg_hist->pos + 1) % UIC_ERR_REG_HIST_LENGTH;
5132 * ufshcd_update_uic_error - check and set fatal UIC error flags.
5133 * @hba: per-adapter instance
5135 static void ufshcd_update_uic_error(struct ufs_hba *hba)
5139 /* PHY layer lane error */
5140 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_PHY_ADAPTER_LAYER);
5141 /* Ignore LINERESET indication, as this is not an error */
5142 if ((reg & UIC_PHY_ADAPTER_LAYER_ERROR) &&
5143 (reg & UIC_PHY_ADAPTER_LAYER_LANE_ERR_MASK)) {
5145 * To know whether this error is fatal or not, DB timeout
5146 * must be checked but this error is handled separately.
5148 dev_dbg(hba->dev, "%s: UIC Lane error reported\n", __func__);
5149 ufshcd_update_uic_reg_hist(&hba->ufs_stats.pa_err, reg);
5152 /* PA_INIT_ERROR is fatal and needs UIC reset */
5153 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_DATA_LINK_LAYER);
5155 ufshcd_update_uic_reg_hist(&hba->ufs_stats.dl_err, reg);
5157 if (reg & UIC_DATA_LINK_LAYER_ERROR_PA_INIT)
5158 hba->uic_error |= UFSHCD_UIC_DL_PA_INIT_ERROR;
5159 else if (hba->dev_quirks &
5160 UFS_DEVICE_QUIRK_RECOVERY_FROM_DL_NAC_ERRORS) {
5161 if (reg & UIC_DATA_LINK_LAYER_ERROR_NAC_RECEIVED)
5163 UFSHCD_UIC_DL_NAC_RECEIVED_ERROR;
5164 else if (reg & UIC_DATA_LINK_LAYER_ERROR_TCx_REPLAY_TIMEOUT)
5165 hba->uic_error |= UFSHCD_UIC_DL_TCx_REPLAY_ERROR;
5168 /* UIC NL/TL/DME errors needs software retry */
5169 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_NETWORK_LAYER);
5171 ufshcd_update_uic_reg_hist(&hba->ufs_stats.nl_err, reg);
5172 hba->uic_error |= UFSHCD_UIC_NL_ERROR;
5175 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_TRANSPORT_LAYER);
5177 ufshcd_update_uic_reg_hist(&hba->ufs_stats.tl_err, reg);
5178 hba->uic_error |= UFSHCD_UIC_TL_ERROR;
5181 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_DME);
5183 ufshcd_update_uic_reg_hist(&hba->ufs_stats.dme_err, reg);
5184 hba->uic_error |= UFSHCD_UIC_DME_ERROR;
5187 dev_dbg(hba->dev, "%s: UIC error flags = 0x%08x\n",
5188 __func__, hba->uic_error);
5192 * ufshcd_check_errors - Check for errors that need s/w attention
5193 * @hba: per-adapter instance
5195 static void ufshcd_check_errors(struct ufs_hba *hba)
5197 bool queue_eh_work = false;
5199 if (hba->errors & INT_FATAL_ERRORS)
5200 queue_eh_work = true;
5202 if (hba->errors & UIC_ERROR) {
5204 ufshcd_update_uic_error(hba);
5206 queue_eh_work = true;
5209 if (queue_eh_work) {
5211 * update the transfer error masks to sticky bits, let's do this
5212 * irrespective of current ufshcd_state.
5214 hba->saved_err |= hba->errors;
5215 hba->saved_uic_err |= hba->uic_error;
5217 /* handle fatal errors only when link is functional */
5218 if (hba->ufshcd_state == UFSHCD_STATE_OPERATIONAL) {
5219 /* block commands from scsi mid-layer */
5220 scsi_block_requests(hba->host);
5222 hba->ufshcd_state = UFSHCD_STATE_EH_SCHEDULED;
5224 /* dump controller state before resetting */
5225 if (hba->saved_err & (INT_FATAL_ERRORS | UIC_ERROR)) {
5226 bool pr_prdt = !!(hba->saved_err &
5227 SYSTEM_BUS_FATAL_ERROR);
5229 dev_err(hba->dev, "%s: saved_err 0x%x saved_uic_err 0x%x\n",
5230 __func__, hba->saved_err,
5231 hba->saved_uic_err);
5233 ufshcd_print_host_regs(hba);
5234 ufshcd_print_pwr_info(hba);
5235 ufshcd_print_tmrs(hba, hba->outstanding_tasks);
5236 ufshcd_print_trs(hba, hba->outstanding_reqs,
5239 schedule_work(&hba->eh_work);
5243 * if (!queue_eh_work) -
5244 * Other errors are either non-fatal where host recovers
5245 * itself without s/w intervention or errors that will be
5246 * handled by the SCSI core layer.
5251 * ufshcd_tmc_handler - handle task management function completion
5252 * @hba: per adapter instance
5254 static void ufshcd_tmc_handler(struct ufs_hba *hba)
5258 tm_doorbell = ufshcd_readl(hba, REG_UTP_TASK_REQ_DOOR_BELL);
5259 hba->tm_condition = tm_doorbell ^ hba->outstanding_tasks;
5260 wake_up(&hba->tm_wq);
5264 * ufshcd_sl_intr - Interrupt service routine
5265 * @hba: per adapter instance
5266 * @intr_status: contains interrupts generated by the controller
5268 static void ufshcd_sl_intr(struct ufs_hba *hba, u32 intr_status)
5270 hba->errors = UFSHCD_ERROR_MASK & intr_status;
5272 ufshcd_check_errors(hba);
5274 if (intr_status & UFSHCD_UIC_MASK)
5275 ufshcd_uic_cmd_compl(hba, intr_status);
5277 if (intr_status & UTP_TASK_REQ_COMPL)
5278 ufshcd_tmc_handler(hba);
5280 if (intr_status & UTP_TRANSFER_REQ_COMPL)
5281 ufshcd_transfer_req_compl(hba);
5285 * ufshcd_intr - Main interrupt service routine
5287 * @__hba: pointer to adapter instance
5289 * Returns IRQ_HANDLED - If interrupt is valid
5290 * IRQ_NONE - If invalid interrupt
5292 static irqreturn_t ufshcd_intr(int irq, void *__hba)
5294 u32 intr_status, enabled_intr_status;
5295 irqreturn_t retval = IRQ_NONE;
5296 struct ufs_hba *hba = __hba;
5298 spin_lock(hba->host->host_lock);
5299 intr_status = ufshcd_readl(hba, REG_INTERRUPT_STATUS);
5300 enabled_intr_status =
5301 intr_status & ufshcd_readl(hba, REG_INTERRUPT_ENABLE);
5304 ufshcd_writel(hba, intr_status, REG_INTERRUPT_STATUS);
5306 if (enabled_intr_status) {
5307 ufshcd_sl_intr(hba, enabled_intr_status);
5308 retval = IRQ_HANDLED;
5310 spin_unlock(hba->host->host_lock);
5314 static int ufshcd_clear_tm_cmd(struct ufs_hba *hba, int tag)
5317 u32 mask = 1 << tag;
5318 unsigned long flags;
5320 if (!test_bit(tag, &hba->outstanding_tasks))
5323 spin_lock_irqsave(hba->host->host_lock, flags);
5324 ufshcd_writel(hba, ~(1 << tag), REG_UTP_TASK_REQ_LIST_CLEAR);
5325 spin_unlock_irqrestore(hba->host->host_lock, flags);
5327 /* poll for max. 1 sec to clear door bell register by h/w */
5328 err = ufshcd_wait_for_register(hba,
5329 REG_UTP_TASK_REQ_DOOR_BELL,
5330 mask, 0, 1000, 1000, true);
5336 * ufshcd_issue_tm_cmd - issues task management commands to controller
5337 * @hba: per adapter instance
5338 * @lun_id: LUN ID to which TM command is sent
5339 * @task_id: task ID to which the TM command is applicable
5340 * @tm_function: task management function opcode
5341 * @tm_response: task management service response return value
5343 * Returns non-zero value on error, zero on success.
5345 static int ufshcd_issue_tm_cmd(struct ufs_hba *hba, int lun_id, int task_id,
5346 u8 tm_function, u8 *tm_response)
5348 struct utp_task_req_desc *task_req_descp;
5349 struct utp_upiu_task_req *task_req_upiup;
5350 struct Scsi_Host *host;
5351 unsigned long flags;
5359 * Get free slot, sleep if slots are unavailable.
5360 * Even though we use wait_event() which sleeps indefinitely,
5361 * the maximum wait time is bounded by %TM_CMD_TIMEOUT.
5363 wait_event(hba->tm_tag_wq, ufshcd_get_tm_free_slot(hba, &free_slot));
5364 ufshcd_hold(hba, false);
5366 spin_lock_irqsave(host->host_lock, flags);
5367 task_req_descp = hba->utmrdl_base_addr;
5368 task_req_descp += free_slot;
5370 /* Configure task request descriptor */
5371 task_req_descp->header.dword_0 = cpu_to_le32(UTP_REQ_DESC_INT_CMD);
5372 task_req_descp->header.dword_2 =
5373 cpu_to_le32(OCS_INVALID_COMMAND_STATUS);
5375 /* Configure task request UPIU */
5377 (struct utp_upiu_task_req *) task_req_descp->task_req_upiu;
5378 task_tag = hba->nutrs + free_slot;
5379 task_req_upiup->header.dword_0 =
5380 UPIU_HEADER_DWORD(UPIU_TRANSACTION_TASK_REQ, 0,
5382 task_req_upiup->header.dword_1 =
5383 UPIU_HEADER_DWORD(0, tm_function, 0, 0);
5385 * The host shall provide the same value for LUN field in the basic
5386 * header and for Input Parameter.
5388 task_req_upiup->input_param1 = cpu_to_be32(lun_id);
5389 task_req_upiup->input_param2 = cpu_to_be32(task_id);
5391 ufshcd_vops_setup_task_mgmt(hba, free_slot, tm_function);
5393 /* send command to the controller */
5394 __set_bit(free_slot, &hba->outstanding_tasks);
5396 /* Make sure descriptors are ready before ringing the task doorbell */
5399 ufshcd_writel(hba, 1 << free_slot, REG_UTP_TASK_REQ_DOOR_BELL);
5400 /* Make sure that doorbell is committed immediately */
5403 spin_unlock_irqrestore(host->host_lock, flags);
5405 /* wait until the task management command is completed */
5406 err = wait_event_timeout(hba->tm_wq,
5407 test_bit(free_slot, &hba->tm_condition),
5408 msecs_to_jiffies(TM_CMD_TIMEOUT));
5410 dev_err(hba->dev, "%s: task management cmd 0x%.2x timed-out\n",
5411 __func__, tm_function);
5412 if (ufshcd_clear_tm_cmd(hba, free_slot))
5413 dev_WARN(hba->dev, "%s: unable clear tm cmd (slot %d) after timeout\n",
5414 __func__, free_slot);
5417 err = ufshcd_task_req_compl(hba, free_slot, tm_response);
5420 clear_bit(free_slot, &hba->tm_condition);
5421 ufshcd_put_tm_slot(hba, free_slot);
5422 wake_up(&hba->tm_tag_wq);
5424 ufshcd_release(hba);
5429 * ufshcd_eh_device_reset_handler - device reset handler registered to
5431 * @cmd: SCSI command pointer
5433 * Returns SUCCESS/FAILED
5435 static int ufshcd_eh_device_reset_handler(struct scsi_cmnd *cmd)
5437 struct Scsi_Host *host;
5438 struct ufs_hba *hba;
5443 struct ufshcd_lrb *lrbp;
5444 unsigned long flags;
5446 host = cmd->device->host;
5447 hba = shost_priv(host);
5448 tag = cmd->request->tag;
5450 lrbp = &hba->lrb[tag];
5451 err = ufshcd_issue_tm_cmd(hba, lrbp->lun, 0, UFS_LOGICAL_RESET, &resp);
5452 if (err || resp != UPIU_TASK_MANAGEMENT_FUNC_COMPL) {
5458 /* clear the commands that were pending for corresponding LUN */
5459 for_each_set_bit(pos, &hba->outstanding_reqs, hba->nutrs) {
5460 if (hba->lrb[pos].lun == lrbp->lun) {
5461 err = ufshcd_clear_cmd(hba, pos);
5466 spin_lock_irqsave(host->host_lock, flags);
5467 ufshcd_transfer_req_compl(hba);
5468 spin_unlock_irqrestore(host->host_lock, flags);
5471 hba->req_abort_count = 0;
5475 dev_err(hba->dev, "%s: failed with err %d\n", __func__, err);
5481 static void ufshcd_set_req_abort_skip(struct ufs_hba *hba, unsigned long bitmap)
5483 struct ufshcd_lrb *lrbp;
5486 for_each_set_bit(tag, &bitmap, hba->nutrs) {
5487 lrbp = &hba->lrb[tag];
5488 lrbp->req_abort_skip = true;
5493 * ufshcd_abort - abort a specific command
5494 * @cmd: SCSI command pointer
5496 * Abort the pending command in device by sending UFS_ABORT_TASK task management
5497 * command, and in host controller by clearing the door-bell register. There can
5498 * be race between controller sending the command to the device while abort is
5499 * issued. To avoid that, first issue UFS_QUERY_TASK to check if the command is
5500 * really issued and then try to abort it.
5502 * Returns SUCCESS/FAILED
5504 static int ufshcd_abort(struct scsi_cmnd *cmd)
5506 struct Scsi_Host *host;
5507 struct ufs_hba *hba;
5508 unsigned long flags;
5513 struct ufshcd_lrb *lrbp;
5516 host = cmd->device->host;
5517 hba = shost_priv(host);
5518 tag = cmd->request->tag;
5519 lrbp = &hba->lrb[tag];
5520 if (!ufshcd_valid_tag(hba, tag)) {
5522 "%s: invalid command tag %d: cmd=0x%p, cmd->request=0x%p",
5523 __func__, tag, cmd, cmd->request);
5528 * Task abort to the device W-LUN is illegal. When this command
5529 * will fail, due to spec violation, scsi err handling next step
5530 * will be to send LU reset which, again, is a spec violation.
5531 * To avoid these unnecessary/illegal step we skip to the last error
5532 * handling stage: reset and restore.
5534 if (lrbp->lun == UFS_UPIU_UFS_DEVICE_WLUN)
5535 return ufshcd_eh_host_reset_handler(cmd);
5537 ufshcd_hold(hba, false);
5538 reg = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
5539 /* If command is already aborted/completed, return SUCCESS */
5540 if (!(test_bit(tag, &hba->outstanding_reqs))) {
5542 "%s: cmd at tag %d already completed, outstanding=0x%lx, doorbell=0x%x\n",
5543 __func__, tag, hba->outstanding_reqs, reg);
5547 if (!(reg & (1 << tag))) {
5549 "%s: cmd was completed, but without a notifying intr, tag = %d",
5553 /* Print Transfer Request of aborted task */
5554 dev_err(hba->dev, "%s: Device abort task at tag %d\n", __func__, tag);
5557 * Print detailed info about aborted request.
5558 * As more than one request might get aborted at the same time,
5559 * print full information only for the first aborted request in order
5560 * to reduce repeated printouts. For other aborted requests only print
5563 scsi_print_command(hba->lrb[tag].cmd);
5564 if (!hba->req_abort_count) {
5565 ufshcd_print_host_regs(hba);
5566 ufshcd_print_host_state(hba);
5567 ufshcd_print_pwr_info(hba);
5568 ufshcd_print_trs(hba, 1 << tag, true);
5570 ufshcd_print_trs(hba, 1 << tag, false);
5572 hba->req_abort_count++;
5574 /* Skip task abort in case previous aborts failed and report failure */
5575 if (lrbp->req_abort_skip) {
5580 for (poll_cnt = 100; poll_cnt; poll_cnt--) {
5581 err = ufshcd_issue_tm_cmd(hba, lrbp->lun, lrbp->task_tag,
5582 UFS_QUERY_TASK, &resp);
5583 if (!err && resp == UPIU_TASK_MANAGEMENT_FUNC_SUCCEEDED) {
5584 /* cmd pending in the device */
5585 dev_err(hba->dev, "%s: cmd pending in the device. tag = %d\n",
5588 } else if (!err && resp == UPIU_TASK_MANAGEMENT_FUNC_COMPL) {
5590 * cmd not pending in the device, check if it is
5593 dev_err(hba->dev, "%s: cmd at tag %d not pending in the device.\n",
5595 reg = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
5596 if (reg & (1 << tag)) {
5597 /* sleep for max. 200us to stabilize */
5598 usleep_range(100, 200);
5601 /* command completed already */
5602 dev_err(hba->dev, "%s: cmd at tag %d successfully cleared from DB.\n",
5607 "%s: no response from device. tag = %d, err %d\n",
5608 __func__, tag, err);
5610 err = resp; /* service response error */
5620 err = ufshcd_issue_tm_cmd(hba, lrbp->lun, lrbp->task_tag,
5621 UFS_ABORT_TASK, &resp);
5622 if (err || resp != UPIU_TASK_MANAGEMENT_FUNC_COMPL) {
5624 err = resp; /* service response error */
5625 dev_err(hba->dev, "%s: issued. tag = %d, err %d\n",
5626 __func__, tag, err);
5631 err = ufshcd_clear_cmd(hba, tag);
5633 dev_err(hba->dev, "%s: Failed clearing cmd at tag %d, err %d\n",
5634 __func__, tag, err);
5638 scsi_dma_unmap(cmd);
5640 spin_lock_irqsave(host->host_lock, flags);
5641 ufshcd_outstanding_req_clear(hba, tag);
5642 hba->lrb[tag].cmd = NULL;
5643 spin_unlock_irqrestore(host->host_lock, flags);
5645 clear_bit_unlock(tag, &hba->lrb_in_use);
5646 wake_up(&hba->dev_cmd.tag_wq);
5652 dev_err(hba->dev, "%s: failed with err %d\n", __func__, err);
5653 ufshcd_set_req_abort_skip(hba, hba->outstanding_reqs);
5658 * This ufshcd_release() corresponds to the original scsi cmd that got
5659 * aborted here (as we won't get any IRQ for it).
5661 ufshcd_release(hba);
5666 * ufshcd_host_reset_and_restore - reset and restore host controller
5667 * @hba: per-adapter instance
5669 * Note that host controller reset may issue DME_RESET to
5670 * local and remote (device) Uni-Pro stack and the attributes
5671 * are reset to default state.
5673 * Returns zero on success, non-zero on failure
5675 static int ufshcd_host_reset_and_restore(struct ufs_hba *hba)
5678 unsigned long flags;
5680 /* Reset the host controller */
5681 spin_lock_irqsave(hba->host->host_lock, flags);
5682 ufshcd_hba_stop(hba, false);
5683 spin_unlock_irqrestore(hba->host->host_lock, flags);
5685 /* scale up clocks to max frequency before full reinitialization */
5686 ufshcd_scale_clks(hba, true);
5688 err = ufshcd_hba_enable(hba);
5692 /* Establish the link again and restore the device */
5693 err = ufshcd_probe_hba(hba);
5695 if (!err && (hba->ufshcd_state != UFSHCD_STATE_OPERATIONAL))
5699 dev_err(hba->dev, "%s: Host init failed %d\n", __func__, err);
5705 * ufshcd_reset_and_restore - reset and re-initialize host/device
5706 * @hba: per-adapter instance
5708 * Reset and recover device, host and re-establish link. This
5709 * is helpful to recover the communication in fatal error conditions.
5711 * Returns zero on success, non-zero on failure
5713 static int ufshcd_reset_and_restore(struct ufs_hba *hba)
5716 unsigned long flags;
5717 int retries = MAX_HOST_RESET_RETRIES;
5720 err = ufshcd_host_reset_and_restore(hba);
5721 } while (err && --retries);
5724 * After reset the door-bell might be cleared, complete
5725 * outstanding requests in s/w here.
5727 spin_lock_irqsave(hba->host->host_lock, flags);
5728 ufshcd_transfer_req_compl(hba);
5729 ufshcd_tmc_handler(hba);
5730 spin_unlock_irqrestore(hba->host->host_lock, flags);
5736 * ufshcd_eh_host_reset_handler - host reset handler registered to scsi layer
5737 * @cmd - SCSI command pointer
5739 * Returns SUCCESS/FAILED
5741 static int ufshcd_eh_host_reset_handler(struct scsi_cmnd *cmd)
5744 unsigned long flags;
5745 struct ufs_hba *hba;
5747 hba = shost_priv(cmd->device->host);
5749 ufshcd_hold(hba, false);
5751 * Check if there is any race with fatal error handling.
5752 * If so, wait for it to complete. Even though fatal error
5753 * handling does reset and restore in some cases, don't assume
5754 * anything out of it. We are just avoiding race here.
5757 spin_lock_irqsave(hba->host->host_lock, flags);
5758 if (!(work_pending(&hba->eh_work) ||
5759 hba->ufshcd_state == UFSHCD_STATE_RESET))
5761 spin_unlock_irqrestore(hba->host->host_lock, flags);
5762 dev_dbg(hba->dev, "%s: reset in progress\n", __func__);
5763 flush_work(&hba->eh_work);
5766 hba->ufshcd_state = UFSHCD_STATE_RESET;
5767 ufshcd_set_eh_in_progress(hba);
5768 spin_unlock_irqrestore(hba->host->host_lock, flags);
5770 err = ufshcd_reset_and_restore(hba);
5772 spin_lock_irqsave(hba->host->host_lock, flags);
5775 hba->ufshcd_state = UFSHCD_STATE_OPERATIONAL;
5778 hba->ufshcd_state = UFSHCD_STATE_ERROR;
5780 ufshcd_clear_eh_in_progress(hba);
5781 spin_unlock_irqrestore(hba->host->host_lock, flags);
5783 ufshcd_release(hba);
5788 * ufshcd_get_max_icc_level - calculate the ICC level
5789 * @sup_curr_uA: max. current supported by the regulator
5790 * @start_scan: row at the desc table to start scan from
5791 * @buff: power descriptor buffer
5793 * Returns calculated max ICC level for specific regulator
5795 static u32 ufshcd_get_max_icc_level(int sup_curr_uA, u32 start_scan, char *buff)
5802 for (i = start_scan; i >= 0; i--) {
5803 data = be16_to_cpup((__be16 *)&buff[2 * i]);
5804 unit = (data & ATTR_ICC_LVL_UNIT_MASK) >>
5805 ATTR_ICC_LVL_UNIT_OFFSET;
5806 curr_uA = data & ATTR_ICC_LVL_VALUE_MASK;
5808 case UFSHCD_NANO_AMP:
5809 curr_uA = curr_uA / 1000;
5811 case UFSHCD_MILI_AMP:
5812 curr_uA = curr_uA * 1000;
5815 curr_uA = curr_uA * 1000 * 1000;
5817 case UFSHCD_MICRO_AMP:
5821 if (sup_curr_uA >= curr_uA)
5826 pr_err("%s: Couldn't find valid icc_level = %d", __func__, i);
5833 * ufshcd_calc_icc_level - calculate the max ICC level
5834 * In case regulators are not initialized we'll return 0
5835 * @hba: per-adapter instance
5836 * @desc_buf: power descriptor buffer to extract ICC levels from.
5837 * @len: length of desc_buff
5839 * Returns calculated ICC level
5841 static u32 ufshcd_find_max_sup_active_icc_level(struct ufs_hba *hba,
5842 u8 *desc_buf, int len)
5846 if (!hba->vreg_info.vcc || !hba->vreg_info.vccq ||
5847 !hba->vreg_info.vccq2) {
5849 "%s: Regulator capability was not set, actvIccLevel=%d",
5850 __func__, icc_level);
5854 if (hba->vreg_info.vcc)
5855 icc_level = ufshcd_get_max_icc_level(
5856 hba->vreg_info.vcc->max_uA,
5857 POWER_DESC_MAX_ACTV_ICC_LVLS - 1,
5858 &desc_buf[PWR_DESC_ACTIVE_LVLS_VCC_0]);
5860 if (hba->vreg_info.vccq)
5861 icc_level = ufshcd_get_max_icc_level(
5862 hba->vreg_info.vccq->max_uA,
5864 &desc_buf[PWR_DESC_ACTIVE_LVLS_VCCQ_0]);
5866 if (hba->vreg_info.vccq2)
5867 icc_level = ufshcd_get_max_icc_level(
5868 hba->vreg_info.vccq2->max_uA,
5870 &desc_buf[PWR_DESC_ACTIVE_LVLS_VCCQ2_0]);
5875 static void ufshcd_init_icc_levels(struct ufs_hba *hba)
5878 int buff_len = QUERY_DESC_POWER_MAX_SIZE;
5879 u8 desc_buf[QUERY_DESC_POWER_MAX_SIZE];
5881 ret = ufshcd_read_power_desc(hba, desc_buf, buff_len);
5884 "%s: Failed reading power descriptor.len = %d ret = %d",
5885 __func__, buff_len, ret);
5889 hba->init_prefetch_data.icc_level =
5890 ufshcd_find_max_sup_active_icc_level(hba,
5891 desc_buf, buff_len);
5892 dev_dbg(hba->dev, "%s: setting icc_level 0x%x",
5893 __func__, hba->init_prefetch_data.icc_level);
5895 ret = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_WRITE_ATTR,
5896 QUERY_ATTR_IDN_ACTIVE_ICC_LVL, 0, 0,
5897 &hba->init_prefetch_data.icc_level);
5901 "%s: Failed configuring bActiveICCLevel = %d ret = %d",
5902 __func__, hba->init_prefetch_data.icc_level , ret);
5907 * ufshcd_scsi_add_wlus - Adds required W-LUs
5908 * @hba: per-adapter instance
5910 * UFS device specification requires the UFS devices to support 4 well known
5912 * "REPORT_LUNS" (address: 01h)
5913 * "UFS Device" (address: 50h)
5914 * "RPMB" (address: 44h)
5915 * "BOOT" (address: 30h)
5916 * UFS device's power management needs to be controlled by "POWER CONDITION"
5917 * field of SSU (START STOP UNIT) command. But this "power condition" field
5918 * will take effect only when its sent to "UFS device" well known logical unit
5919 * hence we require the scsi_device instance to represent this logical unit in
5920 * order for the UFS host driver to send the SSU command for power management.
5922 * We also require the scsi_device instance for "RPMB" (Replay Protected Memory
5923 * Block) LU so user space process can control this LU. User space may also
5924 * want to have access to BOOT LU.
5926 * This function adds scsi device instances for each of all well known LUs
5927 * (except "REPORT LUNS" LU).
5929 * Returns zero on success (all required W-LUs are added successfully),
5930 * non-zero error value on failure (if failed to add any of the required W-LU).
5932 static int ufshcd_scsi_add_wlus(struct ufs_hba *hba)
5935 struct scsi_device *sdev_rpmb;
5936 struct scsi_device *sdev_boot;
5938 hba->sdev_ufs_device = __scsi_add_device(hba->host, 0, 0,
5939 ufshcd_upiu_wlun_to_scsi_wlun(UFS_UPIU_UFS_DEVICE_WLUN), NULL);
5940 if (IS_ERR(hba->sdev_ufs_device)) {
5941 ret = PTR_ERR(hba->sdev_ufs_device);
5942 hba->sdev_ufs_device = NULL;
5945 scsi_device_put(hba->sdev_ufs_device);
5947 sdev_boot = __scsi_add_device(hba->host, 0, 0,
5948 ufshcd_upiu_wlun_to_scsi_wlun(UFS_UPIU_BOOT_WLUN), NULL);
5949 if (IS_ERR(sdev_boot)) {
5950 ret = PTR_ERR(sdev_boot);
5951 goto remove_sdev_ufs_device;
5953 scsi_device_put(sdev_boot);
5955 sdev_rpmb = __scsi_add_device(hba->host, 0, 0,
5956 ufshcd_upiu_wlun_to_scsi_wlun(UFS_UPIU_RPMB_WLUN), NULL);
5957 if (IS_ERR(sdev_rpmb)) {
5958 ret = PTR_ERR(sdev_rpmb);
5959 goto remove_sdev_boot;
5961 scsi_device_put(sdev_rpmb);
5965 scsi_remove_device(sdev_boot);
5966 remove_sdev_ufs_device:
5967 scsi_remove_device(hba->sdev_ufs_device);
5972 static int ufs_get_device_desc(struct ufs_hba *hba,
5973 struct ufs_dev_desc *dev_desc)
5977 u8 str_desc_buf[QUERY_DESC_STRING_MAX_SIZE + 1] = {0};
5978 u8 desc_buf[QUERY_DESC_DEVICE_MAX_SIZE];
5980 err = ufshcd_read_device_desc(hba, desc_buf,
5981 QUERY_DESC_DEVICE_MAX_SIZE);
5983 dev_err(hba->dev, "%s: Failed reading Device Desc. err = %d\n",
5989 * getting vendor (manufacturerID) and Bank Index in big endian
5992 dev_desc->wmanufacturerid = desc_buf[DEVICE_DESC_PARAM_MANF_ID] << 8 |
5993 desc_buf[DEVICE_DESC_PARAM_MANF_ID + 1];
5995 model_index = desc_buf[DEVICE_DESC_PARAM_PRDCT_NAME];
5997 err = ufshcd_read_string_desc(hba, model_index, str_desc_buf,
5998 QUERY_DESC_STRING_MAX_SIZE, ASCII_STD);
6000 dev_err(hba->dev, "%s: Failed reading Product Name. err = %d\n",
6005 str_desc_buf[QUERY_DESC_STRING_MAX_SIZE] = '\0';
6006 strlcpy(dev_desc->model, (str_desc_buf + QUERY_DESC_HDR_SIZE),
6007 min_t(u8, str_desc_buf[QUERY_DESC_LENGTH_OFFSET],
6010 /* Null terminate the model string */
6011 dev_desc->model[MAX_MODEL_LEN] = '\0';
6017 static void ufs_fixup_device_setup(struct ufs_hba *hba,
6018 struct ufs_dev_desc *dev_desc)
6020 struct ufs_dev_fix *f;
6022 for (f = ufs_fixups; f->quirk; f++) {
6023 if ((f->card.wmanufacturerid == dev_desc->wmanufacturerid ||
6024 f->card.wmanufacturerid == UFS_ANY_VENDOR) &&
6025 (STR_PRFX_EQUAL(f->card.model, dev_desc->model) ||
6026 !strcmp(f->card.model, UFS_ANY_MODEL)))
6027 hba->dev_quirks |= f->quirk;
6032 * ufshcd_tune_pa_tactivate - Tunes PA_TActivate of local UniPro
6033 * @hba: per-adapter instance
6035 * PA_TActivate parameter can be tuned manually if UniPro version is less than
6036 * 1.61. PA_TActivate needs to be greater than or equal to peerM-PHY's
6037 * RX_MIN_ACTIVATETIME_CAPABILITY attribute. This optimal value can help reduce
6038 * the hibern8 exit latency.
6040 * Returns zero on success, non-zero error value on failure.
6042 static int ufshcd_tune_pa_tactivate(struct ufs_hba *hba)
6045 u32 peer_rx_min_activatetime = 0, tuned_pa_tactivate;
6047 ret = ufshcd_dme_peer_get(hba,
6049 RX_MIN_ACTIVATETIME_CAPABILITY,
6050 UIC_ARG_MPHY_RX_GEN_SEL_INDEX(0)),
6051 &peer_rx_min_activatetime);
6055 /* make sure proper unit conversion is applied */
6056 tuned_pa_tactivate =
6057 ((peer_rx_min_activatetime * RX_MIN_ACTIVATETIME_UNIT_US)
6058 / PA_TACTIVATE_TIME_UNIT_US);
6059 ret = ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TACTIVATE),
6060 tuned_pa_tactivate);
6067 * ufshcd_tune_pa_hibern8time - Tunes PA_Hibern8Time of local UniPro
6068 * @hba: per-adapter instance
6070 * PA_Hibern8Time parameter can be tuned manually if UniPro version is less than
6071 * 1.61. PA_Hibern8Time needs to be maximum of local M-PHY's
6072 * TX_HIBERN8TIME_CAPABILITY & peer M-PHY's RX_HIBERN8TIME_CAPABILITY.
6073 * This optimal value can help reduce the hibern8 exit latency.
6075 * Returns zero on success, non-zero error value on failure.
6077 static int ufshcd_tune_pa_hibern8time(struct ufs_hba *hba)
6080 u32 local_tx_hibern8_time_cap = 0, peer_rx_hibern8_time_cap = 0;
6081 u32 max_hibern8_time, tuned_pa_hibern8time;
6083 ret = ufshcd_dme_get(hba,
6084 UIC_ARG_MIB_SEL(TX_HIBERN8TIME_CAPABILITY,
6085 UIC_ARG_MPHY_TX_GEN_SEL_INDEX(0)),
6086 &local_tx_hibern8_time_cap);
6090 ret = ufshcd_dme_peer_get(hba,
6091 UIC_ARG_MIB_SEL(RX_HIBERN8TIME_CAPABILITY,
6092 UIC_ARG_MPHY_RX_GEN_SEL_INDEX(0)),
6093 &peer_rx_hibern8_time_cap);
6097 max_hibern8_time = max(local_tx_hibern8_time_cap,
6098 peer_rx_hibern8_time_cap);
6099 /* make sure proper unit conversion is applied */
6100 tuned_pa_hibern8time = ((max_hibern8_time * HIBERN8TIME_UNIT_US)
6101 / PA_HIBERN8_TIME_UNIT_US);
6102 ret = ufshcd_dme_set(hba, UIC_ARG_MIB(PA_HIBERN8TIME),
6103 tuned_pa_hibern8time);
6109 * ufshcd_quirk_tune_host_pa_tactivate - Ensures that host PA_TACTIVATE is
6110 * less than device PA_TACTIVATE time.
6111 * @hba: per-adapter instance
6113 * Some UFS devices require host PA_TACTIVATE to be lower than device
6114 * PA_TACTIVATE, we need to enable UFS_DEVICE_QUIRK_HOST_PA_TACTIVATE quirk
6117 * Returns zero on success, non-zero error value on failure.
6119 static int ufshcd_quirk_tune_host_pa_tactivate(struct ufs_hba *hba)
6122 u32 granularity, peer_granularity;
6123 u32 pa_tactivate, peer_pa_tactivate;
6124 u32 pa_tactivate_us, peer_pa_tactivate_us;
6125 u8 gran_to_us_table[] = {1, 4, 8, 16, 32, 100};
6127 ret = ufshcd_dme_get(hba, UIC_ARG_MIB(PA_GRANULARITY),
6132 ret = ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_GRANULARITY),
6137 if ((granularity < PA_GRANULARITY_MIN_VAL) ||
6138 (granularity > PA_GRANULARITY_MAX_VAL)) {
6139 dev_err(hba->dev, "%s: invalid host PA_GRANULARITY %d",
6140 __func__, granularity);
6144 if ((peer_granularity < PA_GRANULARITY_MIN_VAL) ||
6145 (peer_granularity > PA_GRANULARITY_MAX_VAL)) {
6146 dev_err(hba->dev, "%s: invalid device PA_GRANULARITY %d",
6147 __func__, peer_granularity);
6151 ret = ufshcd_dme_get(hba, UIC_ARG_MIB(PA_TACTIVATE), &pa_tactivate);
6155 ret = ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_TACTIVATE),
6156 &peer_pa_tactivate);
6160 pa_tactivate_us = pa_tactivate * gran_to_us_table[granularity - 1];
6161 peer_pa_tactivate_us = peer_pa_tactivate *
6162 gran_to_us_table[peer_granularity - 1];
6164 if (pa_tactivate_us > peer_pa_tactivate_us) {
6165 u32 new_peer_pa_tactivate;
6167 new_peer_pa_tactivate = pa_tactivate_us /
6168 gran_to_us_table[peer_granularity - 1];
6169 new_peer_pa_tactivate++;
6170 ret = ufshcd_dme_peer_set(hba, UIC_ARG_MIB(PA_TACTIVATE),
6171 new_peer_pa_tactivate);
6178 static void ufshcd_tune_unipro_params(struct ufs_hba *hba)
6180 if (ufshcd_is_unipro_pa_params_tuning_req(hba)) {
6181 ufshcd_tune_pa_tactivate(hba);
6182 ufshcd_tune_pa_hibern8time(hba);
6185 if (hba->dev_quirks & UFS_DEVICE_QUIRK_PA_TACTIVATE)
6186 /* set 1ms timeout for PA_TACTIVATE */
6187 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TACTIVATE), 10);
6189 if (hba->dev_quirks & UFS_DEVICE_QUIRK_HOST_PA_TACTIVATE)
6190 ufshcd_quirk_tune_host_pa_tactivate(hba);
6192 ufshcd_vops_apply_dev_quirks(hba);
6195 static void ufshcd_clear_dbg_ufs_stats(struct ufs_hba *hba)
6197 int err_reg_hist_size = sizeof(struct ufs_uic_err_reg_hist);
6199 hba->ufs_stats.hibern8_exit_cnt = 0;
6200 hba->ufs_stats.last_hibern8_exit_tstamp = ktime_set(0, 0);
6202 memset(&hba->ufs_stats.pa_err, 0, err_reg_hist_size);
6203 memset(&hba->ufs_stats.dl_err, 0, err_reg_hist_size);
6204 memset(&hba->ufs_stats.nl_err, 0, err_reg_hist_size);
6205 memset(&hba->ufs_stats.tl_err, 0, err_reg_hist_size);
6206 memset(&hba->ufs_stats.dme_err, 0, err_reg_hist_size);
6208 hba->req_abort_count = 0;
6212 * ufshcd_probe_hba - probe hba to detect device and initialize
6213 * @hba: per-adapter instance
6215 * Execute link-startup and verify device initialization
6217 static int ufshcd_probe_hba(struct ufs_hba *hba)
6219 struct ufs_dev_desc card = {0};
6221 ktime_t start = ktime_get();
6223 ret = ufshcd_link_startup(hba);
6227 /* set the default level for urgent bkops */
6228 hba->urgent_bkops_lvl = BKOPS_STATUS_PERF_IMPACT;
6229 hba->is_urgent_bkops_lvl_checked = false;
6231 /* Debug counters initialization */
6232 ufshcd_clear_dbg_ufs_stats(hba);
6234 /* UniPro link is active now */
6235 ufshcd_set_link_active(hba);
6237 ret = ufshcd_verify_dev_init(hba);
6241 ret = ufshcd_complete_dev_init(hba);
6245 ret = ufs_get_device_desc(hba, &card);
6247 dev_err(hba->dev, "%s: Failed getting device info. err = %d\n",
6252 ufs_fixup_device_setup(hba, &card);
6253 ufshcd_tune_unipro_params(hba);
6255 ret = ufshcd_set_vccq_rail_unused(hba,
6256 (hba->dev_quirks & UFS_DEVICE_NO_VCCQ) ? true : false);
6260 /* UFS device is also active now */
6261 ufshcd_set_ufs_dev_active(hba);
6262 ufshcd_force_reset_auto_bkops(hba);
6263 hba->wlun_dev_clr_ua = true;
6265 if (ufshcd_get_max_pwr_mode(hba)) {
6267 "%s: Failed getting max supported power mode\n",
6270 ret = ufshcd_config_pwr_mode(hba, &hba->max_pwr_info.info);
6272 dev_err(hba->dev, "%s: Failed setting power mode, err = %d\n",
6278 /* set the state as operational after switching to desired gear */
6279 hba->ufshcd_state = UFSHCD_STATE_OPERATIONAL;
6281 * If we are in error handling context or in power management callbacks
6282 * context, no need to scan the host
6284 if (!ufshcd_eh_in_progress(hba) && !hba->pm_op_in_progress) {
6287 /* clear any previous UFS device information */
6288 memset(&hba->dev_info, 0, sizeof(hba->dev_info));
6289 if (!ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_READ_FLAG,
6290 QUERY_FLAG_IDN_PWR_ON_WPE, &flag))
6291 hba->dev_info.f_power_on_wp_en = flag;
6293 if (!hba->is_init_prefetch)
6294 ufshcd_init_icc_levels(hba);
6296 /* Add required well known logical units to scsi mid layer */
6297 if (ufshcd_scsi_add_wlus(hba))
6300 /* Initialize devfreq after UFS device is detected */
6301 if (ufshcd_is_clkscaling_supported(hba)) {
6302 memcpy(&hba->clk_scaling.saved_pwr_info.info,
6304 sizeof(struct ufs_pa_layer_attr));
6305 hba->clk_scaling.saved_pwr_info.is_valid = true;
6306 if (!hba->devfreq) {
6307 hba->devfreq = devm_devfreq_add_device(hba->dev,
6308 &ufs_devfreq_profile,
6311 if (IS_ERR(hba->devfreq)) {
6312 ret = PTR_ERR(hba->devfreq);
6313 dev_err(hba->dev, "Unable to register with devfreq %d\n",
6318 hba->clk_scaling.is_allowed = true;
6321 scsi_scan_host(hba->host);
6322 pm_runtime_put_sync(hba->dev);
6325 if (!hba->is_init_prefetch)
6326 hba->is_init_prefetch = true;
6330 * If we failed to initialize the device or the device is not
6331 * present, turn off the power/clocks etc.
6333 if (ret && !ufshcd_eh_in_progress(hba) && !hba->pm_op_in_progress) {
6334 pm_runtime_put_sync(hba->dev);
6335 ufshcd_hba_exit(hba);
6338 trace_ufshcd_init(dev_name(hba->dev), ret,
6339 ktime_to_us(ktime_sub(ktime_get(), start)),
6340 hba->curr_dev_pwr_mode, hba->uic_link_state);
6345 * ufshcd_async_scan - asynchronous execution for probing hba
6346 * @data: data pointer to pass to this function
6347 * @cookie: cookie data
6349 static void ufshcd_async_scan(void *data, async_cookie_t cookie)
6351 struct ufs_hba *hba = (struct ufs_hba *)data;
6353 ufshcd_probe_hba(hba);
6356 static enum blk_eh_timer_return ufshcd_eh_timed_out(struct scsi_cmnd *scmd)
6358 unsigned long flags;
6359 struct Scsi_Host *host;
6360 struct ufs_hba *hba;
6364 if (!scmd || !scmd->device || !scmd->device->host)
6365 return BLK_EH_NOT_HANDLED;
6367 host = scmd->device->host;
6368 hba = shost_priv(host);
6370 return BLK_EH_NOT_HANDLED;
6372 spin_lock_irqsave(host->host_lock, flags);
6374 for_each_set_bit(index, &hba->outstanding_reqs, hba->nutrs) {
6375 if (hba->lrb[index].cmd == scmd) {
6381 spin_unlock_irqrestore(host->host_lock, flags);
6384 * Bypass SCSI error handling and reset the block layer timer if this
6385 * SCSI command was not actually dispatched to UFS driver, otherwise
6386 * let SCSI layer handle the error as usual.
6388 return found ? BLK_EH_NOT_HANDLED : BLK_EH_RESET_TIMER;
6391 static struct scsi_host_template ufshcd_driver_template = {
6392 .module = THIS_MODULE,
6394 .proc_name = UFSHCD,
6395 .queuecommand = ufshcd_queuecommand,
6396 .slave_alloc = ufshcd_slave_alloc,
6397 .slave_configure = ufshcd_slave_configure,
6398 .slave_destroy = ufshcd_slave_destroy,
6399 .change_queue_depth = ufshcd_change_queue_depth,
6400 .eh_abort_handler = ufshcd_abort,
6401 .eh_device_reset_handler = ufshcd_eh_device_reset_handler,
6402 .eh_host_reset_handler = ufshcd_eh_host_reset_handler,
6403 .eh_timed_out = ufshcd_eh_timed_out,
6405 .sg_tablesize = SG_ALL,
6406 .cmd_per_lun = UFSHCD_CMD_PER_LUN,
6407 .can_queue = UFSHCD_CAN_QUEUE,
6408 .max_host_blocked = 1,
6409 .track_queue_depth = 1,
6412 static int ufshcd_config_vreg_load(struct device *dev, struct ufs_vreg *vreg,
6420 ret = regulator_set_load(vreg->reg, ua);
6422 dev_err(dev, "%s: %s set load (ua=%d) failed, err=%d\n",
6423 __func__, vreg->name, ua, ret);
6429 static inline int ufshcd_config_vreg_lpm(struct ufs_hba *hba,
6430 struct ufs_vreg *vreg)
6434 else if (vreg->unused)
6437 return ufshcd_config_vreg_load(hba->dev, vreg,
6438 UFS_VREG_LPM_LOAD_UA);
6441 static inline int ufshcd_config_vreg_hpm(struct ufs_hba *hba,
6442 struct ufs_vreg *vreg)
6446 else if (vreg->unused)
6449 return ufshcd_config_vreg_load(hba->dev, vreg, vreg->max_uA);
6452 static int ufshcd_config_vreg(struct device *dev,
6453 struct ufs_vreg *vreg, bool on)
6456 struct regulator *reg = vreg->reg;
6457 const char *name = vreg->name;
6458 int min_uV, uA_load;
6462 if (regulator_count_voltages(reg) > 0) {
6463 min_uV = on ? vreg->min_uV : 0;
6464 ret = regulator_set_voltage(reg, min_uV, vreg->max_uV);
6466 dev_err(dev, "%s: %s set voltage failed, err=%d\n",
6467 __func__, name, ret);
6471 uA_load = on ? vreg->max_uA : 0;
6472 ret = ufshcd_config_vreg_load(dev, vreg, uA_load);
6480 static int ufshcd_enable_vreg(struct device *dev, struct ufs_vreg *vreg)
6486 else if (vreg->enabled || vreg->unused)
6489 ret = ufshcd_config_vreg(dev, vreg, true);
6491 ret = regulator_enable(vreg->reg);
6494 vreg->enabled = true;
6496 dev_err(dev, "%s: %s enable failed, err=%d\n",
6497 __func__, vreg->name, ret);
6502 static int ufshcd_disable_vreg(struct device *dev, struct ufs_vreg *vreg)
6508 else if (!vreg->enabled || vreg->unused)
6511 ret = regulator_disable(vreg->reg);
6514 /* ignore errors on applying disable config */
6515 ufshcd_config_vreg(dev, vreg, false);
6516 vreg->enabled = false;
6518 dev_err(dev, "%s: %s disable failed, err=%d\n",
6519 __func__, vreg->name, ret);
6525 static int ufshcd_setup_vreg(struct ufs_hba *hba, bool on)
6528 struct device *dev = hba->dev;
6529 struct ufs_vreg_info *info = &hba->vreg_info;
6534 ret = ufshcd_toggle_vreg(dev, info->vcc, on);
6538 ret = ufshcd_toggle_vreg(dev, info->vccq, on);
6542 ret = ufshcd_toggle_vreg(dev, info->vccq2, on);
6548 ufshcd_toggle_vreg(dev, info->vccq2, false);
6549 ufshcd_toggle_vreg(dev, info->vccq, false);
6550 ufshcd_toggle_vreg(dev, info->vcc, false);
6555 static int ufshcd_setup_hba_vreg(struct ufs_hba *hba, bool on)
6557 struct ufs_vreg_info *info = &hba->vreg_info;
6560 return ufshcd_toggle_vreg(hba->dev, info->vdd_hba, on);
6565 static int ufshcd_get_vreg(struct device *dev, struct ufs_vreg *vreg)
6572 vreg->reg = devm_regulator_get(dev, vreg->name);
6573 if (IS_ERR(vreg->reg)) {
6574 ret = PTR_ERR(vreg->reg);
6575 dev_err(dev, "%s: %s get failed, err=%d\n",
6576 __func__, vreg->name, ret);
6582 static int ufshcd_init_vreg(struct ufs_hba *hba)
6585 struct device *dev = hba->dev;
6586 struct ufs_vreg_info *info = &hba->vreg_info;
6591 ret = ufshcd_get_vreg(dev, info->vcc);
6595 ret = ufshcd_get_vreg(dev, info->vccq);
6599 ret = ufshcd_get_vreg(dev, info->vccq2);
6604 static int ufshcd_init_hba_vreg(struct ufs_hba *hba)
6606 struct ufs_vreg_info *info = &hba->vreg_info;
6609 return ufshcd_get_vreg(hba->dev, info->vdd_hba);
6614 static int ufshcd_set_vccq_rail_unused(struct ufs_hba *hba, bool unused)
6617 struct ufs_vreg_info *info = &hba->vreg_info;
6621 else if (!info->vccq)
6625 /* shut off the rail here */
6626 ret = ufshcd_toggle_vreg(hba->dev, info->vccq, false);
6628 * Mark this rail as no longer used, so it doesn't get enabled
6632 info->vccq->unused = true;
6635 * rail should have been already enabled hence just make sure
6636 * that unused flag is cleared.
6638 info->vccq->unused = false;
6644 static int __ufshcd_setup_clocks(struct ufs_hba *hba, bool on,
6648 struct ufs_clk_info *clki;
6649 struct list_head *head = &hba->clk_list_head;
6650 unsigned long flags;
6651 ktime_t start = ktime_get();
6652 bool clk_state_changed = false;
6654 if (!head || list_empty(head))
6657 ret = ufshcd_vops_setup_clocks(hba, on, PRE_CHANGE);
6661 list_for_each_entry(clki, head, list) {
6662 if (!IS_ERR_OR_NULL(clki->clk)) {
6663 if (skip_ref_clk && !strcmp(clki->name, "ref_clk"))
6666 clk_state_changed = on ^ clki->enabled;
6667 if (on && !clki->enabled) {
6668 ret = clk_prepare_enable(clki->clk);
6670 dev_err(hba->dev, "%s: %s prepare enable failed, %d\n",
6671 __func__, clki->name, ret);
6674 } else if (!on && clki->enabled) {
6675 clk_disable_unprepare(clki->clk);
6678 dev_dbg(hba->dev, "%s: clk: %s %sabled\n", __func__,
6679 clki->name, on ? "en" : "dis");
6683 ret = ufshcd_vops_setup_clocks(hba, on, POST_CHANGE);
6689 list_for_each_entry(clki, head, list) {
6690 if (!IS_ERR_OR_NULL(clki->clk) && clki->enabled)
6691 clk_disable_unprepare(clki->clk);
6693 } else if (!ret && on) {
6694 spin_lock_irqsave(hba->host->host_lock, flags);
6695 hba->clk_gating.state = CLKS_ON;
6696 trace_ufshcd_clk_gating(dev_name(hba->dev),
6697 hba->clk_gating.state);
6698 spin_unlock_irqrestore(hba->host->host_lock, flags);
6701 if (clk_state_changed)
6702 trace_ufshcd_profile_clk_gating(dev_name(hba->dev),
6703 (on ? "on" : "off"),
6704 ktime_to_us(ktime_sub(ktime_get(), start)), ret);
6708 static int ufshcd_setup_clocks(struct ufs_hba *hba, bool on)
6710 return __ufshcd_setup_clocks(hba, on, false);
6713 static int ufshcd_init_clocks(struct ufs_hba *hba)
6716 struct ufs_clk_info *clki;
6717 struct device *dev = hba->dev;
6718 struct list_head *head = &hba->clk_list_head;
6720 if (!head || list_empty(head))
6723 list_for_each_entry(clki, head, list) {
6727 clki->clk = devm_clk_get(dev, clki->name);
6728 if (IS_ERR(clki->clk)) {
6729 ret = PTR_ERR(clki->clk);
6730 dev_err(dev, "%s: %s clk get failed, %d\n",
6731 __func__, clki->name, ret);
6735 if (clki->max_freq) {
6736 ret = clk_set_rate(clki->clk, clki->max_freq);
6738 dev_err(hba->dev, "%s: %s clk set rate(%dHz) failed, %d\n",
6739 __func__, clki->name,
6740 clki->max_freq, ret);
6743 clki->curr_freq = clki->max_freq;
6745 dev_dbg(dev, "%s: clk: %s, rate: %lu\n", __func__,
6746 clki->name, clk_get_rate(clki->clk));
6752 static int ufshcd_variant_hba_init(struct ufs_hba *hba)
6759 err = ufshcd_vops_init(hba);
6763 err = ufshcd_vops_setup_regulators(hba, true);
6770 ufshcd_vops_exit(hba);
6773 dev_err(hba->dev, "%s: variant %s init failed err %d\n",
6774 __func__, ufshcd_get_var_name(hba), err);
6778 static void ufshcd_variant_hba_exit(struct ufs_hba *hba)
6783 ufshcd_vops_setup_regulators(hba, false);
6785 ufshcd_vops_exit(hba);
6788 static int ufshcd_hba_init(struct ufs_hba *hba)
6793 * Handle host controller power separately from the UFS device power
6794 * rails as it will help controlling the UFS host controller power
6795 * collapse easily which is different than UFS device power collapse.
6796 * Also, enable the host controller power before we go ahead with rest
6797 * of the initialization here.
6799 err = ufshcd_init_hba_vreg(hba);
6803 err = ufshcd_setup_hba_vreg(hba, true);
6807 err = ufshcd_init_clocks(hba);
6809 goto out_disable_hba_vreg;
6811 err = ufshcd_setup_clocks(hba, true);
6813 goto out_disable_hba_vreg;
6815 err = ufshcd_init_vreg(hba);
6817 goto out_disable_clks;
6819 err = ufshcd_setup_vreg(hba, true);
6821 goto out_disable_clks;
6823 err = ufshcd_variant_hba_init(hba);
6825 goto out_disable_vreg;
6827 hba->is_powered = true;
6831 ufshcd_setup_vreg(hba, false);
6833 ufshcd_setup_clocks(hba, false);
6834 out_disable_hba_vreg:
6835 ufshcd_setup_hba_vreg(hba, false);
6840 static void ufshcd_hba_exit(struct ufs_hba *hba)
6842 if (hba->is_powered) {
6843 ufshcd_variant_hba_exit(hba);
6844 ufshcd_setup_vreg(hba, false);
6845 ufshcd_suspend_clkscaling(hba);
6846 if (ufshcd_is_clkscaling_supported(hba)) {
6848 ufshcd_suspend_clkscaling(hba);
6849 destroy_workqueue(hba->clk_scaling.workq);
6851 ufshcd_setup_clocks(hba, false);
6852 ufshcd_setup_hba_vreg(hba, false);
6853 hba->is_powered = false;
6858 ufshcd_send_request_sense(struct ufs_hba *hba, struct scsi_device *sdp)
6860 unsigned char cmd[6] = {REQUEST_SENSE,
6864 UFSHCD_REQ_SENSE_SIZE,
6869 buffer = kzalloc(UFSHCD_REQ_SENSE_SIZE, GFP_KERNEL);
6875 ret = scsi_execute(sdp, cmd, DMA_FROM_DEVICE, buffer,
6876 UFSHCD_REQ_SENSE_SIZE, NULL, NULL,
6877 msecs_to_jiffies(1000), 3, 0, RQF_PM, NULL);
6879 pr_err("%s: failed with err %d\n", __func__, ret);
6887 * ufshcd_set_dev_pwr_mode - sends START STOP UNIT command to set device
6889 * @hba: per adapter instance
6890 * @pwr_mode: device power mode to set
6892 * Returns 0 if requested power mode is set successfully
6893 * Returns non-zero if failed to set the requested power mode
6895 static int ufshcd_set_dev_pwr_mode(struct ufs_hba *hba,
6896 enum ufs_dev_pwr_mode pwr_mode)
6898 unsigned char cmd[6] = { START_STOP };
6899 struct scsi_sense_hdr sshdr;
6900 struct scsi_device *sdp;
6901 unsigned long flags;
6904 spin_lock_irqsave(hba->host->host_lock, flags);
6905 sdp = hba->sdev_ufs_device;
6907 ret = scsi_device_get(sdp);
6908 if (!ret && !scsi_device_online(sdp)) {
6910 scsi_device_put(sdp);
6915 spin_unlock_irqrestore(hba->host->host_lock, flags);
6921 * If scsi commands fail, the scsi mid-layer schedules scsi error-
6922 * handling, which would wait for host to be resumed. Since we know
6923 * we are functional while we are here, skip host resume in error
6926 hba->host->eh_noresume = 1;
6927 if (hba->wlun_dev_clr_ua) {
6928 ret = ufshcd_send_request_sense(hba, sdp);
6931 /* Unit attention condition is cleared now */
6932 hba->wlun_dev_clr_ua = false;
6935 cmd[4] = pwr_mode << 4;
6938 * Current function would be generally called from the power management
6939 * callbacks hence set the RQF_PM flag so that it doesn't resume the
6940 * already suspended childs.
6942 ret = scsi_execute(sdp, cmd, DMA_NONE, NULL, 0, NULL, &sshdr,
6943 START_STOP_TIMEOUT, 0, 0, RQF_PM, NULL);
6945 sdev_printk(KERN_WARNING, sdp,
6946 "START_STOP failed for power mode: %d, result %x\n",
6948 if (driver_byte(ret) & DRIVER_SENSE)
6949 scsi_print_sense_hdr(sdp, NULL, &sshdr);
6953 hba->curr_dev_pwr_mode = pwr_mode;
6955 scsi_device_put(sdp);
6956 hba->host->eh_noresume = 0;
6960 static int ufshcd_link_state_transition(struct ufs_hba *hba,
6961 enum uic_link_state req_link_state,
6962 int check_for_bkops)
6966 if (req_link_state == hba->uic_link_state)
6969 if (req_link_state == UIC_LINK_HIBERN8_STATE) {
6970 ret = ufshcd_uic_hibern8_enter(hba);
6972 ufshcd_set_link_hibern8(hba);
6977 * If autobkops is enabled, link can't be turned off because
6978 * turning off the link would also turn off the device.
6980 else if ((req_link_state == UIC_LINK_OFF_STATE) &&
6981 (!check_for_bkops || (check_for_bkops &&
6982 !hba->auto_bkops_enabled))) {
6984 * Let's make sure that link is in low power mode, we are doing
6985 * this currently by putting the link in Hibern8. Otherway to
6986 * put the link in low power mode is to send the DME end point
6987 * to device and then send the DME reset command to local
6988 * unipro. But putting the link in hibern8 is much faster.
6990 ret = ufshcd_uic_hibern8_enter(hba);
6994 * Change controller state to "reset state" which
6995 * should also put the link in off/reset state
6997 ufshcd_hba_stop(hba, true);
6999 * TODO: Check if we need any delay to make sure that
7000 * controller is reset
7002 ufshcd_set_link_off(hba);
7009 static void ufshcd_vreg_set_lpm(struct ufs_hba *hba)
7012 * It seems some UFS devices may keep drawing more than sleep current
7013 * (atleast for 500us) from UFS rails (especially from VCCQ rail).
7014 * To avoid this situation, add 2ms delay before putting these UFS
7015 * rails in LPM mode.
7017 if (!ufshcd_is_link_active(hba) &&
7018 hba->dev_quirks & UFS_DEVICE_QUIRK_DELAY_BEFORE_LPM)
7019 usleep_range(2000, 2100);
7022 * If UFS device is either in UFS_Sleep turn off VCC rail to save some
7025 * If UFS device and link is in OFF state, all power supplies (VCC,
7026 * VCCQ, VCCQ2) can be turned off if power on write protect is not
7027 * required. If UFS link is inactive (Hibern8 or OFF state) and device
7028 * is in sleep state, put VCCQ & VCCQ2 rails in LPM mode.
7030 * Ignore the error returned by ufshcd_toggle_vreg() as device is anyway
7031 * in low power state which would save some power.
7033 if (ufshcd_is_ufs_dev_poweroff(hba) && ufshcd_is_link_off(hba) &&
7034 !hba->dev_info.is_lu_power_on_wp) {
7035 ufshcd_setup_vreg(hba, false);
7036 } else if (!ufshcd_is_ufs_dev_active(hba)) {
7037 ufshcd_toggle_vreg(hba->dev, hba->vreg_info.vcc, false);
7038 if (!ufshcd_is_link_active(hba)) {
7039 ufshcd_config_vreg_lpm(hba, hba->vreg_info.vccq);
7040 ufshcd_config_vreg_lpm(hba, hba->vreg_info.vccq2);
7045 static int ufshcd_vreg_set_hpm(struct ufs_hba *hba)
7049 if (ufshcd_is_ufs_dev_poweroff(hba) && ufshcd_is_link_off(hba) &&
7050 !hba->dev_info.is_lu_power_on_wp) {
7051 ret = ufshcd_setup_vreg(hba, true);
7052 } else if (!ufshcd_is_ufs_dev_active(hba)) {
7053 if (!ret && !ufshcd_is_link_active(hba)) {
7054 ret = ufshcd_config_vreg_hpm(hba, hba->vreg_info.vccq);
7057 ret = ufshcd_config_vreg_hpm(hba, hba->vreg_info.vccq2);
7061 ret = ufshcd_toggle_vreg(hba->dev, hba->vreg_info.vcc, true);
7066 ufshcd_config_vreg_lpm(hba, hba->vreg_info.vccq);
7068 ufshcd_toggle_vreg(hba->dev, hba->vreg_info.vcc, false);
7073 static void ufshcd_hba_vreg_set_lpm(struct ufs_hba *hba)
7075 if (ufshcd_is_link_off(hba))
7076 ufshcd_setup_hba_vreg(hba, false);
7079 static void ufshcd_hba_vreg_set_hpm(struct ufs_hba *hba)
7081 if (ufshcd_is_link_off(hba))
7082 ufshcd_setup_hba_vreg(hba, true);
7086 * ufshcd_suspend - helper function for suspend operations
7087 * @hba: per adapter instance
7088 * @pm_op: desired low power operation type
7090 * This function will try to put the UFS device and link into low power
7091 * mode based on the "rpm_lvl" (Runtime PM level) or "spm_lvl"
7092 * (System PM level).
7094 * If this function is called during shutdown, it will make sure that
7095 * both UFS device and UFS link is powered off.
7097 * NOTE: UFS device & link must be active before we enter in this function.
7099 * Returns 0 for success and non-zero for failure
7101 static int ufshcd_suspend(struct ufs_hba *hba, enum ufs_pm_op pm_op)
7104 enum ufs_pm_level pm_lvl;
7105 enum ufs_dev_pwr_mode req_dev_pwr_mode;
7106 enum uic_link_state req_link_state;
7108 hba->pm_op_in_progress = 1;
7109 if (!ufshcd_is_shutdown_pm(pm_op)) {
7110 pm_lvl = ufshcd_is_runtime_pm(pm_op) ?
7111 hba->rpm_lvl : hba->spm_lvl;
7112 req_dev_pwr_mode = ufs_get_pm_lvl_to_dev_pwr_mode(pm_lvl);
7113 req_link_state = ufs_get_pm_lvl_to_link_pwr_state(pm_lvl);
7115 req_dev_pwr_mode = UFS_POWERDOWN_PWR_MODE;
7116 req_link_state = UIC_LINK_OFF_STATE;
7120 * If we can't transition into any of the low power modes
7121 * just gate the clocks.
7123 ufshcd_hold(hba, false);
7124 hba->clk_gating.is_suspended = true;
7126 if (hba->clk_scaling.is_allowed) {
7127 cancel_work_sync(&hba->clk_scaling.suspend_work);
7128 cancel_work_sync(&hba->clk_scaling.resume_work);
7129 ufshcd_suspend_clkscaling(hba);
7132 if (req_dev_pwr_mode == UFS_ACTIVE_PWR_MODE &&
7133 req_link_state == UIC_LINK_ACTIVE_STATE) {
7137 if ((req_dev_pwr_mode == hba->curr_dev_pwr_mode) &&
7138 (req_link_state == hba->uic_link_state))
7141 /* UFS device & link must be active before we enter in this function */
7142 if (!ufshcd_is_ufs_dev_active(hba) || !ufshcd_is_link_active(hba)) {
7147 if (ufshcd_is_runtime_pm(pm_op)) {
7148 if (ufshcd_can_autobkops_during_suspend(hba)) {
7150 * The device is idle with no requests in the queue,
7151 * allow background operations if bkops status shows
7152 * that performance might be impacted.
7154 ret = ufshcd_urgent_bkops(hba);
7158 /* make sure that auto bkops is disabled */
7159 ufshcd_disable_auto_bkops(hba);
7163 if ((req_dev_pwr_mode != hba->curr_dev_pwr_mode) &&
7164 ((ufshcd_is_runtime_pm(pm_op) && !hba->auto_bkops_enabled) ||
7165 !ufshcd_is_runtime_pm(pm_op))) {
7166 /* ensure that bkops is disabled */
7167 ufshcd_disable_auto_bkops(hba);
7168 ret = ufshcd_set_dev_pwr_mode(hba, req_dev_pwr_mode);
7173 ret = ufshcd_link_state_transition(hba, req_link_state, 1);
7175 goto set_dev_active;
7177 ufshcd_vreg_set_lpm(hba);
7181 * Call vendor specific suspend callback. As these callbacks may access
7182 * vendor specific host controller register space call them before the
7183 * host clocks are ON.
7185 ret = ufshcd_vops_suspend(hba, pm_op);
7187 goto set_link_active;
7189 if (!ufshcd_is_link_active(hba))
7190 ufshcd_setup_clocks(hba, false);
7192 /* If link is active, device ref_clk can't be switched off */
7193 __ufshcd_setup_clocks(hba, false, true);
7195 hba->clk_gating.state = CLKS_OFF;
7196 trace_ufshcd_clk_gating(dev_name(hba->dev), hba->clk_gating.state);
7198 * Disable the host irq as host controller as there won't be any
7199 * host controller transaction expected till resume.
7201 ufshcd_disable_irq(hba);
7202 /* Put the host controller in low power mode if possible */
7203 ufshcd_hba_vreg_set_lpm(hba);
7207 if (hba->clk_scaling.is_allowed)
7208 ufshcd_resume_clkscaling(hba);
7209 ufshcd_vreg_set_hpm(hba);
7210 if (ufshcd_is_link_hibern8(hba) && !ufshcd_uic_hibern8_exit(hba))
7211 ufshcd_set_link_active(hba);
7212 else if (ufshcd_is_link_off(hba))
7213 ufshcd_host_reset_and_restore(hba);
7215 if (!ufshcd_set_dev_pwr_mode(hba, UFS_ACTIVE_PWR_MODE))
7216 ufshcd_disable_auto_bkops(hba);
7218 if (hba->clk_scaling.is_allowed)
7219 ufshcd_resume_clkscaling(hba);
7220 hba->clk_gating.is_suspended = false;
7221 ufshcd_release(hba);
7223 hba->pm_op_in_progress = 0;
7228 * ufshcd_resume - helper function for resume operations
7229 * @hba: per adapter instance
7230 * @pm_op: runtime PM or system PM
7232 * This function basically brings the UFS device, UniPro link and controller
7235 * Returns 0 for success and non-zero for failure
7237 static int ufshcd_resume(struct ufs_hba *hba, enum ufs_pm_op pm_op)
7240 enum uic_link_state old_link_state;
7242 hba->pm_op_in_progress = 1;
7243 old_link_state = hba->uic_link_state;
7245 ufshcd_hba_vreg_set_hpm(hba);
7246 /* Make sure clocks are enabled before accessing controller */
7247 ret = ufshcd_setup_clocks(hba, true);
7251 /* enable the host irq as host controller would be active soon */
7252 ret = ufshcd_enable_irq(hba);
7254 goto disable_irq_and_vops_clks;
7256 ret = ufshcd_vreg_set_hpm(hba);
7258 goto disable_irq_and_vops_clks;
7261 * Call vendor specific resume callback. As these callbacks may access
7262 * vendor specific host controller register space call them when the
7263 * host clocks are ON.
7265 ret = ufshcd_vops_resume(hba, pm_op);
7269 if (ufshcd_is_link_hibern8(hba)) {
7270 ret = ufshcd_uic_hibern8_exit(hba);
7272 ufshcd_set_link_active(hba);
7274 goto vendor_suspend;
7275 } else if (ufshcd_is_link_off(hba)) {
7276 ret = ufshcd_host_reset_and_restore(hba);
7278 * ufshcd_host_reset_and_restore() should have already
7279 * set the link state as active
7281 if (ret || !ufshcd_is_link_active(hba))
7282 goto vendor_suspend;
7285 if (!ufshcd_is_ufs_dev_active(hba)) {
7286 ret = ufshcd_set_dev_pwr_mode(hba, UFS_ACTIVE_PWR_MODE);
7288 goto set_old_link_state;
7291 if (ufshcd_keep_autobkops_enabled_except_suspend(hba))
7292 ufshcd_enable_auto_bkops(hba);
7295 * If BKOPs operations are urgently needed at this moment then
7296 * keep auto-bkops enabled or else disable it.
7298 ufshcd_urgent_bkops(hba);
7300 hba->clk_gating.is_suspended = false;
7302 if (hba->clk_scaling.is_allowed)
7303 ufshcd_resume_clkscaling(hba);
7305 /* Schedule clock gating in case of no access to UFS device yet */
7306 ufshcd_release(hba);
7310 ufshcd_link_state_transition(hba, old_link_state, 0);
7312 ufshcd_vops_suspend(hba, pm_op);
7314 ufshcd_vreg_set_lpm(hba);
7315 disable_irq_and_vops_clks:
7316 ufshcd_disable_irq(hba);
7317 if (hba->clk_scaling.is_allowed)
7318 ufshcd_suspend_clkscaling(hba);
7319 ufshcd_setup_clocks(hba, false);
7321 hba->pm_op_in_progress = 0;
7326 * ufshcd_system_suspend - system suspend routine
7327 * @hba: per adapter instance
7328 * @pm_op: runtime PM or system PM
7330 * Check the description of ufshcd_suspend() function for more details.
7332 * Returns 0 for success and non-zero for failure
7334 int ufshcd_system_suspend(struct ufs_hba *hba)
7337 ktime_t start = ktime_get();
7339 if (!hba || !hba->is_powered)
7342 if ((ufs_get_pm_lvl_to_dev_pwr_mode(hba->spm_lvl) ==
7343 hba->curr_dev_pwr_mode) &&
7344 (ufs_get_pm_lvl_to_link_pwr_state(hba->spm_lvl) ==
7345 hba->uic_link_state))
7348 if (pm_runtime_suspended(hba->dev)) {
7350 * UFS device and/or UFS link low power states during runtime
7351 * suspend seems to be different than what is expected during
7352 * system suspend. Hence runtime resume the devic & link and
7353 * let the system suspend low power states to take effect.
7354 * TODO: If resume takes longer time, we might have optimize
7355 * it in future by not resuming everything if possible.
7357 ret = ufshcd_runtime_resume(hba);
7362 ret = ufshcd_suspend(hba, UFS_SYSTEM_PM);
7364 trace_ufshcd_system_suspend(dev_name(hba->dev), ret,
7365 ktime_to_us(ktime_sub(ktime_get(), start)),
7366 hba->curr_dev_pwr_mode, hba->uic_link_state);
7368 hba->is_sys_suspended = true;
7371 EXPORT_SYMBOL(ufshcd_system_suspend);
7374 * ufshcd_system_resume - system resume routine
7375 * @hba: per adapter instance
7377 * Returns 0 for success and non-zero for failure
7380 int ufshcd_system_resume(struct ufs_hba *hba)
7383 ktime_t start = ktime_get();
7388 if (!hba->is_powered || pm_runtime_suspended(hba->dev))
7390 * Let the runtime resume take care of resuming
7391 * if runtime suspended.
7395 ret = ufshcd_resume(hba, UFS_SYSTEM_PM);
7397 trace_ufshcd_system_resume(dev_name(hba->dev), ret,
7398 ktime_to_us(ktime_sub(ktime_get(), start)),
7399 hba->curr_dev_pwr_mode, hba->uic_link_state);
7402 EXPORT_SYMBOL(ufshcd_system_resume);
7405 * ufshcd_runtime_suspend - runtime suspend routine
7406 * @hba: per adapter instance
7408 * Check the description of ufshcd_suspend() function for more details.
7410 * Returns 0 for success and non-zero for failure
7412 int ufshcd_runtime_suspend(struct ufs_hba *hba)
7415 ktime_t start = ktime_get();
7420 if (!hba->is_powered)
7423 ret = ufshcd_suspend(hba, UFS_RUNTIME_PM);
7425 trace_ufshcd_runtime_suspend(dev_name(hba->dev), ret,
7426 ktime_to_us(ktime_sub(ktime_get(), start)),
7427 hba->curr_dev_pwr_mode, hba->uic_link_state);
7430 EXPORT_SYMBOL(ufshcd_runtime_suspend);
7433 * ufshcd_runtime_resume - runtime resume routine
7434 * @hba: per adapter instance
7436 * This function basically brings the UFS device, UniPro link and controller
7437 * to active state. Following operations are done in this function:
7439 * 1. Turn on all the controller related clocks
7440 * 2. Bring the UniPro link out of Hibernate state
7441 * 3. If UFS device is in sleep state, turn ON VCC rail and bring the UFS device
7443 * 4. If auto-bkops is enabled on the device, disable it.
7445 * So following would be the possible power state after this function return
7447 * S1: UFS device in Active state with VCC rail ON
7448 * UniPro link in Active state
7449 * All the UFS/UniPro controller clocks are ON
7451 * Returns 0 for success and non-zero for failure
7453 int ufshcd_runtime_resume(struct ufs_hba *hba)
7456 ktime_t start = ktime_get();
7461 if (!hba->is_powered)
7464 ret = ufshcd_resume(hba, UFS_RUNTIME_PM);
7466 trace_ufshcd_runtime_resume(dev_name(hba->dev), ret,
7467 ktime_to_us(ktime_sub(ktime_get(), start)),
7468 hba->curr_dev_pwr_mode, hba->uic_link_state);
7471 EXPORT_SYMBOL(ufshcd_runtime_resume);
7473 int ufshcd_runtime_idle(struct ufs_hba *hba)
7477 EXPORT_SYMBOL(ufshcd_runtime_idle);
7479 static inline ssize_t ufshcd_pm_lvl_store(struct device *dev,
7480 struct device_attribute *attr,
7481 const char *buf, size_t count,
7484 struct ufs_hba *hba = dev_get_drvdata(dev);
7485 unsigned long flags, value;
7487 if (kstrtoul(buf, 0, &value))
7490 if ((value < UFS_PM_LVL_0) || (value >= UFS_PM_LVL_MAX))
7493 spin_lock_irqsave(hba->host->host_lock, flags);
7495 hba->rpm_lvl = value;
7497 hba->spm_lvl = value;
7498 spin_unlock_irqrestore(hba->host->host_lock, flags);
7502 static ssize_t ufshcd_rpm_lvl_show(struct device *dev,
7503 struct device_attribute *attr, char *buf)
7505 struct ufs_hba *hba = dev_get_drvdata(dev);
7509 curr_len = snprintf(buf, PAGE_SIZE,
7510 "\nCurrent Runtime PM level [%d] => dev_state [%s] link_state [%s]\n",
7512 ufschd_ufs_dev_pwr_mode_to_string(
7513 ufs_pm_lvl_states[hba->rpm_lvl].dev_state),
7514 ufschd_uic_link_state_to_string(
7515 ufs_pm_lvl_states[hba->rpm_lvl].link_state));
7517 curr_len += snprintf((buf + curr_len), (PAGE_SIZE - curr_len),
7518 "\nAll available Runtime PM levels info:\n");
7519 for (lvl = UFS_PM_LVL_0; lvl < UFS_PM_LVL_MAX; lvl++)
7520 curr_len += snprintf((buf + curr_len), (PAGE_SIZE - curr_len),
7521 "\tRuntime PM level [%d] => dev_state [%s] link_state [%s]\n",
7523 ufschd_ufs_dev_pwr_mode_to_string(
7524 ufs_pm_lvl_states[lvl].dev_state),
7525 ufschd_uic_link_state_to_string(
7526 ufs_pm_lvl_states[lvl].link_state));
7531 static ssize_t ufshcd_rpm_lvl_store(struct device *dev,
7532 struct device_attribute *attr, const char *buf, size_t count)
7534 return ufshcd_pm_lvl_store(dev, attr, buf, count, true);
7537 static void ufshcd_add_rpm_lvl_sysfs_nodes(struct ufs_hba *hba)
7539 hba->rpm_lvl_attr.show = ufshcd_rpm_lvl_show;
7540 hba->rpm_lvl_attr.store = ufshcd_rpm_lvl_store;
7541 sysfs_attr_init(&hba->rpm_lvl_attr.attr);
7542 hba->rpm_lvl_attr.attr.name = "rpm_lvl";
7543 hba->rpm_lvl_attr.attr.mode = 0644;
7544 if (device_create_file(hba->dev, &hba->rpm_lvl_attr))
7545 dev_err(hba->dev, "Failed to create sysfs for rpm_lvl\n");
7548 static ssize_t ufshcd_spm_lvl_show(struct device *dev,
7549 struct device_attribute *attr, char *buf)
7551 struct ufs_hba *hba = dev_get_drvdata(dev);
7555 curr_len = snprintf(buf, PAGE_SIZE,
7556 "\nCurrent System PM level [%d] => dev_state [%s] link_state [%s]\n",
7558 ufschd_ufs_dev_pwr_mode_to_string(
7559 ufs_pm_lvl_states[hba->spm_lvl].dev_state),
7560 ufschd_uic_link_state_to_string(
7561 ufs_pm_lvl_states[hba->spm_lvl].link_state));
7563 curr_len += snprintf((buf + curr_len), (PAGE_SIZE - curr_len),
7564 "\nAll available System PM levels info:\n");
7565 for (lvl = UFS_PM_LVL_0; lvl < UFS_PM_LVL_MAX; lvl++)
7566 curr_len += snprintf((buf + curr_len), (PAGE_SIZE - curr_len),
7567 "\tSystem PM level [%d] => dev_state [%s] link_state [%s]\n",
7569 ufschd_ufs_dev_pwr_mode_to_string(
7570 ufs_pm_lvl_states[lvl].dev_state),
7571 ufschd_uic_link_state_to_string(
7572 ufs_pm_lvl_states[lvl].link_state));
7577 static ssize_t ufshcd_spm_lvl_store(struct device *dev,
7578 struct device_attribute *attr, const char *buf, size_t count)
7580 return ufshcd_pm_lvl_store(dev, attr, buf, count, false);
7583 static void ufshcd_add_spm_lvl_sysfs_nodes(struct ufs_hba *hba)
7585 hba->spm_lvl_attr.show = ufshcd_spm_lvl_show;
7586 hba->spm_lvl_attr.store = ufshcd_spm_lvl_store;
7587 sysfs_attr_init(&hba->spm_lvl_attr.attr);
7588 hba->spm_lvl_attr.attr.name = "spm_lvl";
7589 hba->spm_lvl_attr.attr.mode = 0644;
7590 if (device_create_file(hba->dev, &hba->spm_lvl_attr))
7591 dev_err(hba->dev, "Failed to create sysfs for spm_lvl\n");
7594 static inline void ufshcd_add_sysfs_nodes(struct ufs_hba *hba)
7596 ufshcd_add_rpm_lvl_sysfs_nodes(hba);
7597 ufshcd_add_spm_lvl_sysfs_nodes(hba);
7601 * ufshcd_shutdown - shutdown routine
7602 * @hba: per adapter instance
7604 * This function would power off both UFS device and UFS link.
7606 * Returns 0 always to allow force shutdown even in case of errors.
7608 int ufshcd_shutdown(struct ufs_hba *hba)
7612 if (ufshcd_is_ufs_dev_poweroff(hba) && ufshcd_is_link_off(hba))
7615 if (pm_runtime_suspended(hba->dev)) {
7616 ret = ufshcd_runtime_resume(hba);
7621 ret = ufshcd_suspend(hba, UFS_SHUTDOWN_PM);
7624 dev_err(hba->dev, "%s failed, err %d\n", __func__, ret);
7625 /* allow force shutdown even in case of errors */
7628 EXPORT_SYMBOL(ufshcd_shutdown);
7631 * ufshcd_remove - de-allocate SCSI host and host memory space
7632 * data structure memory
7633 * @hba - per adapter instance
7635 void ufshcd_remove(struct ufs_hba *hba)
7637 scsi_remove_host(hba->host);
7638 /* disable interrupts */
7639 ufshcd_disable_intr(hba, hba->intr_mask);
7640 ufshcd_hba_stop(hba, true);
7642 ufshcd_exit_clk_gating(hba);
7643 if (ufshcd_is_clkscaling_supported(hba))
7644 device_remove_file(hba->dev, &hba->clk_scaling.enable_attr);
7645 ufshcd_hba_exit(hba);
7647 EXPORT_SYMBOL_GPL(ufshcd_remove);
7650 * ufshcd_dealloc_host - deallocate Host Bus Adapter (HBA)
7651 * @hba: pointer to Host Bus Adapter (HBA)
7653 void ufshcd_dealloc_host(struct ufs_hba *hba)
7655 scsi_host_put(hba->host);
7657 EXPORT_SYMBOL_GPL(ufshcd_dealloc_host);
7660 * ufshcd_set_dma_mask - Set dma mask based on the controller
7661 * addressing capability
7662 * @hba: per adapter instance
7664 * Returns 0 for success, non-zero for failure
7666 static int ufshcd_set_dma_mask(struct ufs_hba *hba)
7668 if (hba->capabilities & MASK_64_ADDRESSING_SUPPORT) {
7669 if (!dma_set_mask_and_coherent(hba->dev, DMA_BIT_MASK(64)))
7672 return dma_set_mask_and_coherent(hba->dev, DMA_BIT_MASK(32));
7676 * ufshcd_alloc_host - allocate Host Bus Adapter (HBA)
7677 * @dev: pointer to device handle
7678 * @hba_handle: driver private handle
7679 * Returns 0 on success, non-zero value on failure
7681 int ufshcd_alloc_host(struct device *dev, struct ufs_hba **hba_handle)
7683 struct Scsi_Host *host;
7684 struct ufs_hba *hba;
7689 "Invalid memory reference for dev is NULL\n");
7694 host = scsi_host_alloc(&ufshcd_driver_template,
7695 sizeof(struct ufs_hba));
7697 dev_err(dev, "scsi_host_alloc failed\n");
7701 hba = shost_priv(host);
7709 EXPORT_SYMBOL(ufshcd_alloc_host);
7712 * ufshcd_init - Driver initialization routine
7713 * @hba: per-adapter instance
7714 * @mmio_base: base register address
7715 * @irq: Interrupt line of device
7716 * Returns 0 on success, non-zero value on failure
7718 int ufshcd_init(struct ufs_hba *hba, void __iomem *mmio_base, unsigned int irq)
7721 struct Scsi_Host *host = hba->host;
7722 struct device *dev = hba->dev;
7726 "Invalid memory reference for mmio_base is NULL\n");
7731 hba->mmio_base = mmio_base;
7734 err = ufshcd_hba_init(hba);
7738 /* Read capabilities registers */
7739 ufshcd_hba_capabilities(hba);
7741 /* Get UFS version supported by the controller */
7742 hba->ufs_version = ufshcd_get_ufs_version(hba);
7744 if ((hba->ufs_version != UFSHCI_VERSION_10) &&
7745 (hba->ufs_version != UFSHCI_VERSION_11) &&
7746 (hba->ufs_version != UFSHCI_VERSION_20) &&
7747 (hba->ufs_version != UFSHCI_VERSION_21))
7748 dev_err(hba->dev, "invalid UFS version 0x%x\n",
7751 /* Get Interrupt bit mask per version */
7752 hba->intr_mask = ufshcd_get_intr_mask(hba);
7754 err = ufshcd_set_dma_mask(hba);
7756 dev_err(hba->dev, "set dma mask failed\n");
7760 /* Allocate memory for host memory space */
7761 err = ufshcd_memory_alloc(hba);
7763 dev_err(hba->dev, "Memory allocation failed\n");
7768 ufshcd_host_memory_configure(hba);
7770 host->can_queue = hba->nutrs;
7771 host->cmd_per_lun = hba->nutrs;
7772 host->max_id = UFSHCD_MAX_ID;
7773 host->max_lun = UFS_MAX_LUNS;
7774 host->max_channel = UFSHCD_MAX_CHANNEL;
7775 host->unique_id = host->host_no;
7776 host->max_cmd_len = MAX_CDB_SIZE;
7778 hba->max_pwr_info.is_valid = false;
7780 /* Initailize wait queue for task management */
7781 init_waitqueue_head(&hba->tm_wq);
7782 init_waitqueue_head(&hba->tm_tag_wq);
7784 /* Initialize work queues */
7785 INIT_WORK(&hba->eh_work, ufshcd_err_handler);
7786 INIT_WORK(&hba->eeh_work, ufshcd_exception_event_handler);
7788 /* Initialize UIC command mutex */
7789 mutex_init(&hba->uic_cmd_mutex);
7791 /* Initialize mutex for device management commands */
7792 mutex_init(&hba->dev_cmd.lock);
7794 init_rwsem(&hba->clk_scaling_lock);
7796 /* Initialize device management tag acquire wait queue */
7797 init_waitqueue_head(&hba->dev_cmd.tag_wq);
7799 ufshcd_init_clk_gating(hba);
7802 * In order to avoid any spurious interrupt immediately after
7803 * registering UFS controller interrupt handler, clear any pending UFS
7804 * interrupt status and disable all the UFS interrupts.
7806 ufshcd_writel(hba, ufshcd_readl(hba, REG_INTERRUPT_STATUS),
7807 REG_INTERRUPT_STATUS);
7808 ufshcd_writel(hba, 0, REG_INTERRUPT_ENABLE);
7810 * Make sure that UFS interrupts are disabled and any pending interrupt
7811 * status is cleared before registering UFS interrupt handler.
7815 /* IRQ registration */
7816 err = devm_request_irq(dev, irq, ufshcd_intr, IRQF_SHARED, UFSHCD, hba);
7818 dev_err(hba->dev, "request irq failed\n");
7821 hba->is_irq_enabled = true;
7824 err = scsi_add_host(host, hba->dev);
7826 dev_err(hba->dev, "scsi_add_host failed\n");
7830 /* Host controller enable */
7831 err = ufshcd_hba_enable(hba);
7833 dev_err(hba->dev, "Host controller enable failed\n");
7834 ufshcd_print_host_regs(hba);
7835 ufshcd_print_host_state(hba);
7836 goto out_remove_scsi_host;
7839 if (ufshcd_is_clkscaling_supported(hba)) {
7840 char wq_name[sizeof("ufs_clkscaling_00")];
7842 INIT_WORK(&hba->clk_scaling.suspend_work,
7843 ufshcd_clk_scaling_suspend_work);
7844 INIT_WORK(&hba->clk_scaling.resume_work,
7845 ufshcd_clk_scaling_resume_work);
7847 snprintf(wq_name, sizeof(wq_name), "ufs_clkscaling_%d",
7849 hba->clk_scaling.workq = create_singlethread_workqueue(wq_name);
7851 ufshcd_clkscaling_init_sysfs(hba);
7855 * Set the default power management level for runtime and system PM.
7856 * Default power saving mode is to keep UFS link in Hibern8 state
7857 * and UFS device in sleep state.
7859 hba->rpm_lvl = ufs_get_desired_pm_lvl_for_dev_link_state(
7861 UIC_LINK_HIBERN8_STATE);
7862 hba->spm_lvl = ufs_get_desired_pm_lvl_for_dev_link_state(
7864 UIC_LINK_HIBERN8_STATE);
7866 /* Hold auto suspend until async scan completes */
7867 pm_runtime_get_sync(dev);
7870 * We are assuming that device wasn't put in sleep/power-down
7871 * state exclusively during the boot stage before kernel.
7872 * This assumption helps avoid doing link startup twice during
7873 * ufshcd_probe_hba().
7875 ufshcd_set_ufs_dev_active(hba);
7877 async_schedule(ufshcd_async_scan, hba);
7878 ufshcd_add_sysfs_nodes(hba);
7882 out_remove_scsi_host:
7883 scsi_remove_host(hba->host);
7885 ufshcd_exit_clk_gating(hba);
7887 hba->is_irq_enabled = false;
7888 ufshcd_hba_exit(hba);
7892 EXPORT_SYMBOL_GPL(ufshcd_init);
7894 MODULE_AUTHOR("Santosh Yaragnavi <santosh.sy@samsung.com>");
7895 MODULE_AUTHOR("Vinayak Holikatti <h.vinayak@samsung.com>");
7896 MODULE_DESCRIPTION("Generic UFS host controller driver Core");
7897 MODULE_LICENSE("GPL");
7898 MODULE_VERSION(UFSHCD_DRIVER_VERSION);