2 * Universal Flash Storage Host controller driver Core
4 * This code is based on drivers/scsi/ufs/ufshcd.c
5 * Copyright (C) 2011-2013 Samsung India Software Operations
6 * Copyright (c) 2013-2016, The Linux Foundation. All rights reserved.
9 * Santosh Yaraganavi <santosh.sy@samsung.com>
10 * Vinayak Holikatti <h.vinayak@samsung.com>
12 * This program is free software; you can redistribute it and/or
13 * modify it under the terms of the GNU General Public License
14 * as published by the Free Software Foundation; either version 2
15 * of the License, or (at your option) any later version.
16 * See the COPYING file in the top-level directory or visit
17 * <http://www.gnu.org/licenses/gpl-2.0.html>
19 * This program is distributed in the hope that it will be useful,
20 * but WITHOUT ANY WARRANTY; without even the implied warranty of
21 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22 * GNU General Public License for more details.
24 * This program is provided "AS IS" and "WITH ALL FAULTS" and
25 * without warranty of any kind. You are solely responsible for
26 * determining the appropriateness of using and distributing
27 * the program and assume all risks associated with your exercise
28 * of rights with respect to the program, including but not limited
29 * to infringement of third party rights, the risks and costs of
30 * program errors, damage to or loss of data, programs or equipment,
31 * and unavailability or interruption of operations. Under no
32 * circumstances will the contributor of this Program be liable for
33 * any damages of any kind arising from your use or distribution of
36 * The Linux Foundation chooses to take subject only to the GPLv2
37 * license terms, and distributes only under these terms.
40 #include <linux/async.h>
41 #include <linux/devfreq.h>
42 #include <linux/nls.h>
44 #include <linux/bitfield.h>
46 #include "ufs_quirks.h"
48 #include "ufs-sysfs.h"
50 #define CREATE_TRACE_POINTS
51 #include <trace/events/ufs.h>
53 #define UFSHCD_REQ_SENSE_SIZE 18
55 #define UFSHCD_ENABLE_INTRS (UTP_TRANSFER_REQ_COMPL |\
58 /* UIC command timeout, unit: ms */
59 #define UIC_CMD_TIMEOUT 500
61 /* NOP OUT retries waiting for NOP IN response */
62 #define NOP_OUT_RETRIES 10
63 /* Timeout after 30 msecs if NOP OUT hangs without response */
64 #define NOP_OUT_TIMEOUT 30 /* msecs */
66 /* Query request retries */
67 #define QUERY_REQ_RETRIES 3
68 /* Query request timeout */
69 #define QUERY_REQ_TIMEOUT 1500 /* 1.5 seconds */
71 /* Task management command timeout */
72 #define TM_CMD_TIMEOUT 100 /* msecs */
74 /* maximum number of retries for a general UIC command */
75 #define UFS_UIC_COMMAND_RETRIES 3
77 /* maximum number of link-startup retries */
78 #define DME_LINKSTARTUP_RETRIES 3
80 /* Maximum retries for Hibern8 enter */
81 #define UIC_HIBERN8_ENTER_RETRIES 3
83 /* maximum number of reset retries before giving up */
84 #define MAX_HOST_RESET_RETRIES 5
86 /* Expose the flag value from utp_upiu_query.value */
87 #define MASK_QUERY_UPIU_FLAG_LOC 0xFF
89 /* Interrupt aggregation default timeout, unit: 40us */
90 #define INT_AGGR_DEF_TO 0x02
92 #define ufshcd_toggle_vreg(_dev, _vreg, _on) \
96 _ret = ufshcd_enable_vreg(_dev, _vreg); \
98 _ret = ufshcd_disable_vreg(_dev, _vreg); \
102 #define ufshcd_hex_dump(prefix_str, buf, len) \
103 print_hex_dump(KERN_ERR, prefix_str, DUMP_PREFIX_OFFSET, 16, 4, buf, len, false)
106 UFSHCD_MAX_CHANNEL = 0,
108 UFSHCD_CMD_PER_LUN = 32,
109 UFSHCD_CAN_QUEUE = 32,
116 UFSHCD_STATE_OPERATIONAL,
117 UFSHCD_STATE_EH_SCHEDULED,
120 /* UFSHCD error handling flags */
122 UFSHCD_EH_IN_PROGRESS = (1 << 0),
125 /* UFSHCD UIC layer error flags */
127 UFSHCD_UIC_DL_PA_INIT_ERROR = (1 << 0), /* Data link layer error */
128 UFSHCD_UIC_DL_NAC_RECEIVED_ERROR = (1 << 1), /* Data link layer error */
129 UFSHCD_UIC_DL_TCx_REPLAY_ERROR = (1 << 2), /* Data link layer error */
130 UFSHCD_UIC_NL_ERROR = (1 << 3), /* Network layer error */
131 UFSHCD_UIC_TL_ERROR = (1 << 4), /* Transport Layer error */
132 UFSHCD_UIC_DME_ERROR = (1 << 5), /* DME error */
135 #define ufshcd_set_eh_in_progress(h) \
136 ((h)->eh_flags |= UFSHCD_EH_IN_PROGRESS)
137 #define ufshcd_eh_in_progress(h) \
138 ((h)->eh_flags & UFSHCD_EH_IN_PROGRESS)
139 #define ufshcd_clear_eh_in_progress(h) \
140 ((h)->eh_flags &= ~UFSHCD_EH_IN_PROGRESS)
142 #define ufshcd_set_ufs_dev_active(h) \
143 ((h)->curr_dev_pwr_mode = UFS_ACTIVE_PWR_MODE)
144 #define ufshcd_set_ufs_dev_sleep(h) \
145 ((h)->curr_dev_pwr_mode = UFS_SLEEP_PWR_MODE)
146 #define ufshcd_set_ufs_dev_poweroff(h) \
147 ((h)->curr_dev_pwr_mode = UFS_POWERDOWN_PWR_MODE)
148 #define ufshcd_is_ufs_dev_active(h) \
149 ((h)->curr_dev_pwr_mode == UFS_ACTIVE_PWR_MODE)
150 #define ufshcd_is_ufs_dev_sleep(h) \
151 ((h)->curr_dev_pwr_mode == UFS_SLEEP_PWR_MODE)
152 #define ufshcd_is_ufs_dev_poweroff(h) \
153 ((h)->curr_dev_pwr_mode == UFS_POWERDOWN_PWR_MODE)
155 struct ufs_pm_lvl_states ufs_pm_lvl_states[] = {
156 {UFS_ACTIVE_PWR_MODE, UIC_LINK_ACTIVE_STATE},
157 {UFS_ACTIVE_PWR_MODE, UIC_LINK_HIBERN8_STATE},
158 {UFS_SLEEP_PWR_MODE, UIC_LINK_ACTIVE_STATE},
159 {UFS_SLEEP_PWR_MODE, UIC_LINK_HIBERN8_STATE},
160 {UFS_POWERDOWN_PWR_MODE, UIC_LINK_HIBERN8_STATE},
161 {UFS_POWERDOWN_PWR_MODE, UIC_LINK_OFF_STATE},
164 static inline enum ufs_dev_pwr_mode
165 ufs_get_pm_lvl_to_dev_pwr_mode(enum ufs_pm_level lvl)
167 return ufs_pm_lvl_states[lvl].dev_state;
170 static inline enum uic_link_state
171 ufs_get_pm_lvl_to_link_pwr_state(enum ufs_pm_level lvl)
173 return ufs_pm_lvl_states[lvl].link_state;
176 static inline enum ufs_pm_level
177 ufs_get_desired_pm_lvl_for_dev_link_state(enum ufs_dev_pwr_mode dev_state,
178 enum uic_link_state link_state)
180 enum ufs_pm_level lvl;
182 for (lvl = UFS_PM_LVL_0; lvl < UFS_PM_LVL_MAX; lvl++) {
183 if ((ufs_pm_lvl_states[lvl].dev_state == dev_state) &&
184 (ufs_pm_lvl_states[lvl].link_state == link_state))
188 /* if no match found, return the level 0 */
192 static struct ufs_dev_fix ufs_fixups[] = {
193 /* UFS cards deviations table */
194 UFS_FIX(UFS_VENDOR_SAMSUNG, UFS_ANY_MODEL,
195 UFS_DEVICE_QUIRK_DELAY_BEFORE_LPM),
196 UFS_FIX(UFS_VENDOR_SAMSUNG, UFS_ANY_MODEL, UFS_DEVICE_NO_VCCQ),
197 UFS_FIX(UFS_VENDOR_SAMSUNG, UFS_ANY_MODEL,
198 UFS_DEVICE_QUIRK_RECOVERY_FROM_DL_NAC_ERRORS),
199 UFS_FIX(UFS_VENDOR_SAMSUNG, UFS_ANY_MODEL,
200 UFS_DEVICE_NO_FASTAUTO),
201 UFS_FIX(UFS_VENDOR_SAMSUNG, UFS_ANY_MODEL,
202 UFS_DEVICE_QUIRK_HOST_PA_TACTIVATE),
203 UFS_FIX(UFS_VENDOR_TOSHIBA, UFS_ANY_MODEL,
204 UFS_DEVICE_QUIRK_DELAY_BEFORE_LPM),
205 UFS_FIX(UFS_VENDOR_TOSHIBA, "THGLF2G9C8KBADG",
206 UFS_DEVICE_QUIRK_PA_TACTIVATE),
207 UFS_FIX(UFS_VENDOR_TOSHIBA, "THGLF2G9D8KBADG",
208 UFS_DEVICE_QUIRK_PA_TACTIVATE),
209 UFS_FIX(UFS_VENDOR_SKHYNIX, UFS_ANY_MODEL, UFS_DEVICE_NO_VCCQ),
210 UFS_FIX(UFS_VENDOR_SKHYNIX, UFS_ANY_MODEL,
211 UFS_DEVICE_QUIRK_HOST_PA_SAVECONFIGTIME),
216 static void ufshcd_tmc_handler(struct ufs_hba *hba);
217 static void ufshcd_async_scan(void *data, async_cookie_t cookie);
218 static int ufshcd_reset_and_restore(struct ufs_hba *hba);
219 static int ufshcd_eh_host_reset_handler(struct scsi_cmnd *cmd);
220 static int ufshcd_clear_tm_cmd(struct ufs_hba *hba, int tag);
221 static void ufshcd_hba_exit(struct ufs_hba *hba);
222 static int ufshcd_probe_hba(struct ufs_hba *hba);
223 static int __ufshcd_setup_clocks(struct ufs_hba *hba, bool on,
225 static int ufshcd_setup_clocks(struct ufs_hba *hba, bool on);
226 static int ufshcd_set_vccq_rail_unused(struct ufs_hba *hba, bool unused);
227 static int ufshcd_uic_hibern8_exit(struct ufs_hba *hba);
228 static int ufshcd_uic_hibern8_enter(struct ufs_hba *hba);
229 static inline void ufshcd_add_delay_before_dme_cmd(struct ufs_hba *hba);
230 static int ufshcd_host_reset_and_restore(struct ufs_hba *hba);
231 static void ufshcd_resume_clkscaling(struct ufs_hba *hba);
232 static void ufshcd_suspend_clkscaling(struct ufs_hba *hba);
233 static void __ufshcd_suspend_clkscaling(struct ufs_hba *hba);
234 static int ufshcd_scale_clks(struct ufs_hba *hba, bool scale_up);
235 static irqreturn_t ufshcd_intr(int irq, void *__hba);
236 static int ufshcd_config_pwr_mode(struct ufs_hba *hba,
237 struct ufs_pa_layer_attr *desired_pwr_mode);
238 static int ufshcd_change_power_mode(struct ufs_hba *hba,
239 struct ufs_pa_layer_attr *pwr_mode);
240 static inline bool ufshcd_valid_tag(struct ufs_hba *hba, int tag)
242 return tag >= 0 && tag < hba->nutrs;
245 static inline int ufshcd_enable_irq(struct ufs_hba *hba)
249 if (!hba->is_irq_enabled) {
250 ret = request_irq(hba->irq, ufshcd_intr, IRQF_SHARED, UFSHCD,
253 dev_err(hba->dev, "%s: request_irq failed, ret=%d\n",
255 hba->is_irq_enabled = true;
261 static inline void ufshcd_disable_irq(struct ufs_hba *hba)
263 if (hba->is_irq_enabled) {
264 free_irq(hba->irq, hba);
265 hba->is_irq_enabled = false;
269 /* replace non-printable or non-ASCII characters with spaces */
270 static inline void ufshcd_remove_non_printable(char *val)
275 if (*val < 0x20 || *val > 0x7e)
279 static void ufshcd_add_command_trace(struct ufs_hba *hba,
280 unsigned int tag, const char *str)
285 struct ufshcd_lrb *lrbp;
286 int transfer_len = -1;
288 if (!trace_ufshcd_command_enabled())
291 lrbp = &hba->lrb[tag];
293 if (lrbp->cmd) { /* data phase exists */
294 opcode = (u8)(*lrbp->cmd->cmnd);
295 if ((opcode == READ_10) || (opcode == WRITE_10)) {
297 * Currently we only fully trace read(10) and write(10)
300 if (lrbp->cmd->request && lrbp->cmd->request->bio)
302 lrbp->cmd->request->bio->bi_iter.bi_sector;
303 transfer_len = be32_to_cpu(
304 lrbp->ucd_req_ptr->sc.exp_data_transfer_len);
308 intr = ufshcd_readl(hba, REG_INTERRUPT_STATUS);
309 doorbell = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
310 trace_ufshcd_command(dev_name(hba->dev), str, tag,
311 doorbell, transfer_len, intr, lba, opcode);
314 static void ufshcd_print_clk_freqs(struct ufs_hba *hba)
316 struct ufs_clk_info *clki;
317 struct list_head *head = &hba->clk_list_head;
319 if (list_empty(head))
322 list_for_each_entry(clki, head, list) {
323 if (!IS_ERR_OR_NULL(clki->clk) && clki->min_freq &&
325 dev_err(hba->dev, "clk: %s, rate: %u\n",
326 clki->name, clki->curr_freq);
330 static void ufshcd_print_uic_err_hist(struct ufs_hba *hba,
331 struct ufs_uic_err_reg_hist *err_hist, char *err_name)
335 for (i = 0; i < UIC_ERR_REG_HIST_LENGTH; i++) {
336 int p = (i + err_hist->pos - 1) % UIC_ERR_REG_HIST_LENGTH;
338 if (err_hist->reg[p] == 0)
340 dev_err(hba->dev, "%s[%d] = 0x%x at %lld us\n", err_name, i,
341 err_hist->reg[p], ktime_to_us(err_hist->tstamp[p]));
345 static void ufshcd_print_host_regs(struct ufs_hba *hba)
348 * hex_dump reads its data without the readl macro. This might
349 * cause inconsistency issues on some platform, as the printed
350 * values may be from cache and not the most recent value.
351 * To know whether you are looking at an un-cached version verify
352 * that IORESOURCE_MEM flag is on when xxx_get_resource() is invoked
353 * during platform/pci probe function.
355 ufshcd_hex_dump("host regs: ", hba->mmio_base, UFSHCI_REG_SPACE_SIZE);
356 dev_err(hba->dev, "hba->ufs_version = 0x%x, hba->capabilities = 0x%x\n",
357 hba->ufs_version, hba->capabilities);
359 "hba->outstanding_reqs = 0x%x, hba->outstanding_tasks = 0x%x\n",
360 (u32)hba->outstanding_reqs, (u32)hba->outstanding_tasks);
362 "last_hibern8_exit_tstamp at %lld us, hibern8_exit_cnt = %d\n",
363 ktime_to_us(hba->ufs_stats.last_hibern8_exit_tstamp),
364 hba->ufs_stats.hibern8_exit_cnt);
366 ufshcd_print_uic_err_hist(hba, &hba->ufs_stats.pa_err, "pa_err");
367 ufshcd_print_uic_err_hist(hba, &hba->ufs_stats.dl_err, "dl_err");
368 ufshcd_print_uic_err_hist(hba, &hba->ufs_stats.nl_err, "nl_err");
369 ufshcd_print_uic_err_hist(hba, &hba->ufs_stats.tl_err, "tl_err");
370 ufshcd_print_uic_err_hist(hba, &hba->ufs_stats.dme_err, "dme_err");
372 ufshcd_print_clk_freqs(hba);
374 if (hba->vops && hba->vops->dbg_register_dump)
375 hba->vops->dbg_register_dump(hba);
379 void ufshcd_print_trs(struct ufs_hba *hba, unsigned long bitmap, bool pr_prdt)
381 struct ufshcd_lrb *lrbp;
385 for_each_set_bit(tag, &bitmap, hba->nutrs) {
386 lrbp = &hba->lrb[tag];
388 dev_err(hba->dev, "UPIU[%d] - issue time %lld us\n",
389 tag, ktime_to_us(lrbp->issue_time_stamp));
390 dev_err(hba->dev, "UPIU[%d] - complete time %lld us\n",
391 tag, ktime_to_us(lrbp->compl_time_stamp));
393 "UPIU[%d] - Transfer Request Descriptor phys@0x%llx\n",
394 tag, (u64)lrbp->utrd_dma_addr);
396 ufshcd_hex_dump("UPIU TRD: ", lrbp->utr_descriptor_ptr,
397 sizeof(struct utp_transfer_req_desc));
398 dev_err(hba->dev, "UPIU[%d] - Request UPIU phys@0x%llx\n", tag,
399 (u64)lrbp->ucd_req_dma_addr);
400 ufshcd_hex_dump("UPIU REQ: ", lrbp->ucd_req_ptr,
401 sizeof(struct utp_upiu_req));
402 dev_err(hba->dev, "UPIU[%d] - Response UPIU phys@0x%llx\n", tag,
403 (u64)lrbp->ucd_rsp_dma_addr);
404 ufshcd_hex_dump("UPIU RSP: ", lrbp->ucd_rsp_ptr,
405 sizeof(struct utp_upiu_rsp));
407 prdt_length = le16_to_cpu(
408 lrbp->utr_descriptor_ptr->prd_table_length);
410 "UPIU[%d] - PRDT - %d entries phys@0x%llx\n",
412 (u64)lrbp->ucd_prdt_dma_addr);
415 ufshcd_hex_dump("UPIU PRDT: ", lrbp->ucd_prdt_ptr,
416 sizeof(struct ufshcd_sg_entry) * prdt_length);
420 static void ufshcd_print_tmrs(struct ufs_hba *hba, unsigned long bitmap)
422 struct utp_task_req_desc *tmrdp;
425 for_each_set_bit(tag, &bitmap, hba->nutmrs) {
426 tmrdp = &hba->utmrdl_base_addr[tag];
427 dev_err(hba->dev, "TM[%d] - Task Management Header\n", tag);
428 ufshcd_hex_dump("TM TRD: ", &tmrdp->header,
429 sizeof(struct request_desc_header));
430 dev_err(hba->dev, "TM[%d] - Task Management Request UPIU\n",
432 ufshcd_hex_dump("TM REQ: ", tmrdp->task_req_upiu,
433 sizeof(struct utp_upiu_req));
434 dev_err(hba->dev, "TM[%d] - Task Management Response UPIU\n",
436 ufshcd_hex_dump("TM RSP: ", tmrdp->task_rsp_upiu,
437 sizeof(struct utp_task_req_desc));
441 static void ufshcd_print_host_state(struct ufs_hba *hba)
443 dev_err(hba->dev, "UFS Host state=%d\n", hba->ufshcd_state);
444 dev_err(hba->dev, "lrb in use=0x%lx, outstanding reqs=0x%lx tasks=0x%lx\n",
445 hba->lrb_in_use, hba->outstanding_reqs, hba->outstanding_tasks);
446 dev_err(hba->dev, "saved_err=0x%x, saved_uic_err=0x%x\n",
447 hba->saved_err, hba->saved_uic_err);
448 dev_err(hba->dev, "Device power mode=%d, UIC link state=%d\n",
449 hba->curr_dev_pwr_mode, hba->uic_link_state);
450 dev_err(hba->dev, "PM in progress=%d, sys. suspended=%d\n",
451 hba->pm_op_in_progress, hba->is_sys_suspended);
452 dev_err(hba->dev, "Auto BKOPS=%d, Host self-block=%d\n",
453 hba->auto_bkops_enabled, hba->host->host_self_blocked);
454 dev_err(hba->dev, "Clk gate=%d\n", hba->clk_gating.state);
455 dev_err(hba->dev, "error handling flags=0x%x, req. abort count=%d\n",
456 hba->eh_flags, hba->req_abort_count);
457 dev_err(hba->dev, "Host capabilities=0x%x, caps=0x%x\n",
458 hba->capabilities, hba->caps);
459 dev_err(hba->dev, "quirks=0x%x, dev. quirks=0x%x\n", hba->quirks,
464 * ufshcd_print_pwr_info - print power params as saved in hba
466 * @hba: per-adapter instance
468 static void ufshcd_print_pwr_info(struct ufs_hba *hba)
470 static const char * const names[] = {
480 dev_err(hba->dev, "%s:[RX, TX]: gear=[%d, %d], lane[%d, %d], pwr[%s, %s], rate = %d\n",
482 hba->pwr_info.gear_rx, hba->pwr_info.gear_tx,
483 hba->pwr_info.lane_rx, hba->pwr_info.lane_tx,
484 names[hba->pwr_info.pwr_rx],
485 names[hba->pwr_info.pwr_tx],
486 hba->pwr_info.hs_rate);
490 * ufshcd_wait_for_register - wait for register value to change
491 * @hba - per-adapter interface
492 * @reg - mmio register offset
493 * @mask - mask to apply to read register value
494 * @val - wait condition
495 * @interval_us - polling interval in microsecs
496 * @timeout_ms - timeout in millisecs
497 * @can_sleep - perform sleep or just spin
499 * Returns -ETIMEDOUT on error, zero on success
501 int ufshcd_wait_for_register(struct ufs_hba *hba, u32 reg, u32 mask,
502 u32 val, unsigned long interval_us,
503 unsigned long timeout_ms, bool can_sleep)
506 unsigned long timeout = jiffies + msecs_to_jiffies(timeout_ms);
508 /* ignore bits that we don't intend to wait on */
511 while ((ufshcd_readl(hba, reg) & mask) != val) {
513 usleep_range(interval_us, interval_us + 50);
516 if (time_after(jiffies, timeout)) {
517 if ((ufshcd_readl(hba, reg) & mask) != val)
527 * ufshcd_get_intr_mask - Get the interrupt bit mask
528 * @hba: Pointer to adapter instance
530 * Returns interrupt bit mask per version
532 static inline u32 ufshcd_get_intr_mask(struct ufs_hba *hba)
536 switch (hba->ufs_version) {
537 case UFSHCI_VERSION_10:
538 intr_mask = INTERRUPT_MASK_ALL_VER_10;
540 case UFSHCI_VERSION_11:
541 case UFSHCI_VERSION_20:
542 intr_mask = INTERRUPT_MASK_ALL_VER_11;
544 case UFSHCI_VERSION_21:
546 intr_mask = INTERRUPT_MASK_ALL_VER_21;
554 * ufshcd_get_ufs_version - Get the UFS version supported by the HBA
555 * @hba: Pointer to adapter instance
557 * Returns UFSHCI version supported by the controller
559 static inline u32 ufshcd_get_ufs_version(struct ufs_hba *hba)
561 if (hba->quirks & UFSHCD_QUIRK_BROKEN_UFS_HCI_VERSION)
562 return ufshcd_vops_get_ufs_hci_version(hba);
564 return ufshcd_readl(hba, REG_UFS_VERSION);
568 * ufshcd_is_device_present - Check if any device connected to
569 * the host controller
570 * @hba: pointer to adapter instance
572 * Returns true if device present, false if no device detected
574 static inline bool ufshcd_is_device_present(struct ufs_hba *hba)
576 return (ufshcd_readl(hba, REG_CONTROLLER_STATUS) &
577 DEVICE_PRESENT) ? true : false;
581 * ufshcd_get_tr_ocs - Get the UTRD Overall Command Status
582 * @lrbp: pointer to local command reference block
584 * This function is used to get the OCS field from UTRD
585 * Returns the OCS field in the UTRD
587 static inline int ufshcd_get_tr_ocs(struct ufshcd_lrb *lrbp)
589 return le32_to_cpu(lrbp->utr_descriptor_ptr->header.dword_2) & MASK_OCS;
593 * ufshcd_get_tmr_ocs - Get the UTMRD Overall Command Status
594 * @task_req_descp: pointer to utp_task_req_desc structure
596 * This function is used to get the OCS field from UTMRD
597 * Returns the OCS field in the UTMRD
600 ufshcd_get_tmr_ocs(struct utp_task_req_desc *task_req_descp)
602 return le32_to_cpu(task_req_descp->header.dword_2) & MASK_OCS;
606 * ufshcd_get_tm_free_slot - get a free slot for task management request
607 * @hba: per adapter instance
608 * @free_slot: pointer to variable with available slot value
610 * Get a free tag and lock it until ufshcd_put_tm_slot() is called.
611 * Returns 0 if free slot is not available, else return 1 with tag value
614 static bool ufshcd_get_tm_free_slot(struct ufs_hba *hba, int *free_slot)
623 tag = find_first_zero_bit(&hba->tm_slots_in_use, hba->nutmrs);
624 if (tag >= hba->nutmrs)
626 } while (test_and_set_bit_lock(tag, &hba->tm_slots_in_use));
634 static inline void ufshcd_put_tm_slot(struct ufs_hba *hba, int slot)
636 clear_bit_unlock(slot, &hba->tm_slots_in_use);
640 * ufshcd_utrl_clear - Clear a bit in UTRLCLR register
641 * @hba: per adapter instance
642 * @pos: position of the bit to be cleared
644 static inline void ufshcd_utrl_clear(struct ufs_hba *hba, u32 pos)
646 ufshcd_writel(hba, ~(1 << pos), REG_UTP_TRANSFER_REQ_LIST_CLEAR);
650 * ufshcd_outstanding_req_clear - Clear a bit in outstanding request field
651 * @hba: per adapter instance
652 * @tag: position of the bit to be cleared
654 static inline void ufshcd_outstanding_req_clear(struct ufs_hba *hba, int tag)
656 __clear_bit(tag, &hba->outstanding_reqs);
660 * ufshcd_get_lists_status - Check UCRDY, UTRLRDY and UTMRLRDY
661 * @reg: Register value of host controller status
663 * Returns integer, 0 on Success and positive value if failed
665 static inline int ufshcd_get_lists_status(u32 reg)
667 return !((reg & UFSHCD_STATUS_READY) == UFSHCD_STATUS_READY);
671 * ufshcd_get_uic_cmd_result - Get the UIC command result
672 * @hba: Pointer to adapter instance
674 * This function gets the result of UIC command completion
675 * Returns 0 on success, non zero value on error
677 static inline int ufshcd_get_uic_cmd_result(struct ufs_hba *hba)
679 return ufshcd_readl(hba, REG_UIC_COMMAND_ARG_2) &
680 MASK_UIC_COMMAND_RESULT;
684 * ufshcd_get_dme_attr_val - Get the value of attribute returned by UIC command
685 * @hba: Pointer to adapter instance
687 * This function gets UIC command argument3
688 * Returns 0 on success, non zero value on error
690 static inline u32 ufshcd_get_dme_attr_val(struct ufs_hba *hba)
692 return ufshcd_readl(hba, REG_UIC_COMMAND_ARG_3);
696 * ufshcd_get_req_rsp - returns the TR response transaction type
697 * @ucd_rsp_ptr: pointer to response UPIU
700 ufshcd_get_req_rsp(struct utp_upiu_rsp *ucd_rsp_ptr)
702 return be32_to_cpu(ucd_rsp_ptr->header.dword_0) >> 24;
706 * ufshcd_get_rsp_upiu_result - Get the result from response UPIU
707 * @ucd_rsp_ptr: pointer to response UPIU
709 * This function gets the response status and scsi_status from response UPIU
710 * Returns the response result code.
713 ufshcd_get_rsp_upiu_result(struct utp_upiu_rsp *ucd_rsp_ptr)
715 return be32_to_cpu(ucd_rsp_ptr->header.dword_1) & MASK_RSP_UPIU_RESULT;
719 * ufshcd_get_rsp_upiu_data_seg_len - Get the data segment length
721 * @ucd_rsp_ptr: pointer to response UPIU
723 * Return the data segment length.
725 static inline unsigned int
726 ufshcd_get_rsp_upiu_data_seg_len(struct utp_upiu_rsp *ucd_rsp_ptr)
728 return be32_to_cpu(ucd_rsp_ptr->header.dword_2) &
729 MASK_RSP_UPIU_DATA_SEG_LEN;
733 * ufshcd_is_exception_event - Check if the device raised an exception event
734 * @ucd_rsp_ptr: pointer to response UPIU
736 * The function checks if the device raised an exception event indicated in
737 * the Device Information field of response UPIU.
739 * Returns true if exception is raised, false otherwise.
741 static inline bool ufshcd_is_exception_event(struct utp_upiu_rsp *ucd_rsp_ptr)
743 return be32_to_cpu(ucd_rsp_ptr->header.dword_2) &
744 MASK_RSP_EXCEPTION_EVENT ? true : false;
748 * ufshcd_reset_intr_aggr - Reset interrupt aggregation values.
749 * @hba: per adapter instance
752 ufshcd_reset_intr_aggr(struct ufs_hba *hba)
754 ufshcd_writel(hba, INT_AGGR_ENABLE |
755 INT_AGGR_COUNTER_AND_TIMER_RESET,
756 REG_UTP_TRANSFER_REQ_INT_AGG_CONTROL);
760 * ufshcd_config_intr_aggr - Configure interrupt aggregation values.
761 * @hba: per adapter instance
762 * @cnt: Interrupt aggregation counter threshold
763 * @tmout: Interrupt aggregation timeout value
766 ufshcd_config_intr_aggr(struct ufs_hba *hba, u8 cnt, u8 tmout)
768 ufshcd_writel(hba, INT_AGGR_ENABLE | INT_AGGR_PARAM_WRITE |
769 INT_AGGR_COUNTER_THLD_VAL(cnt) |
770 INT_AGGR_TIMEOUT_VAL(tmout),
771 REG_UTP_TRANSFER_REQ_INT_AGG_CONTROL);
775 * ufshcd_disable_intr_aggr - Disables interrupt aggregation.
776 * @hba: per adapter instance
778 static inline void ufshcd_disable_intr_aggr(struct ufs_hba *hba)
780 ufshcd_writel(hba, 0, REG_UTP_TRANSFER_REQ_INT_AGG_CONTROL);
784 * ufshcd_enable_run_stop_reg - Enable run-stop registers,
785 * When run-stop registers are set to 1, it indicates the
786 * host controller that it can process the requests
787 * @hba: per adapter instance
789 static void ufshcd_enable_run_stop_reg(struct ufs_hba *hba)
791 ufshcd_writel(hba, UTP_TASK_REQ_LIST_RUN_STOP_BIT,
792 REG_UTP_TASK_REQ_LIST_RUN_STOP);
793 ufshcd_writel(hba, UTP_TRANSFER_REQ_LIST_RUN_STOP_BIT,
794 REG_UTP_TRANSFER_REQ_LIST_RUN_STOP);
798 * ufshcd_hba_start - Start controller initialization sequence
799 * @hba: per adapter instance
801 static inline void ufshcd_hba_start(struct ufs_hba *hba)
803 ufshcd_writel(hba, CONTROLLER_ENABLE, REG_CONTROLLER_ENABLE);
807 * ufshcd_is_hba_active - Get controller state
808 * @hba: per adapter instance
810 * Returns false if controller is active, true otherwise
812 static inline bool ufshcd_is_hba_active(struct ufs_hba *hba)
814 return (ufshcd_readl(hba, REG_CONTROLLER_ENABLE) & CONTROLLER_ENABLE)
818 u32 ufshcd_get_local_unipro_ver(struct ufs_hba *hba)
820 /* HCI version 1.0 and 1.1 supports UniPro 1.41 */
821 if ((hba->ufs_version == UFSHCI_VERSION_10) ||
822 (hba->ufs_version == UFSHCI_VERSION_11))
823 return UFS_UNIPRO_VER_1_41;
825 return UFS_UNIPRO_VER_1_6;
827 EXPORT_SYMBOL(ufshcd_get_local_unipro_ver);
829 static bool ufshcd_is_unipro_pa_params_tuning_req(struct ufs_hba *hba)
832 * If both host and device support UniPro ver1.6 or later, PA layer
833 * parameters tuning happens during link startup itself.
835 * We can manually tune PA layer parameters if either host or device
836 * doesn't support UniPro ver 1.6 or later. But to keep manual tuning
837 * logic simple, we will only do manual tuning if local unipro version
838 * doesn't support ver1.6 or later.
840 if (ufshcd_get_local_unipro_ver(hba) < UFS_UNIPRO_VER_1_6)
846 static int ufshcd_scale_clks(struct ufs_hba *hba, bool scale_up)
849 struct ufs_clk_info *clki;
850 struct list_head *head = &hba->clk_list_head;
851 ktime_t start = ktime_get();
852 bool clk_state_changed = false;
854 if (list_empty(head))
857 ret = ufshcd_vops_clk_scale_notify(hba, scale_up, PRE_CHANGE);
861 list_for_each_entry(clki, head, list) {
862 if (!IS_ERR_OR_NULL(clki->clk)) {
863 if (scale_up && clki->max_freq) {
864 if (clki->curr_freq == clki->max_freq)
867 clk_state_changed = true;
868 ret = clk_set_rate(clki->clk, clki->max_freq);
870 dev_err(hba->dev, "%s: %s clk set rate(%dHz) failed, %d\n",
871 __func__, clki->name,
872 clki->max_freq, ret);
875 trace_ufshcd_clk_scaling(dev_name(hba->dev),
876 "scaled up", clki->name,
880 clki->curr_freq = clki->max_freq;
882 } else if (!scale_up && clki->min_freq) {
883 if (clki->curr_freq == clki->min_freq)
886 clk_state_changed = true;
887 ret = clk_set_rate(clki->clk, clki->min_freq);
889 dev_err(hba->dev, "%s: %s clk set rate(%dHz) failed, %d\n",
890 __func__, clki->name,
891 clki->min_freq, ret);
894 trace_ufshcd_clk_scaling(dev_name(hba->dev),
895 "scaled down", clki->name,
898 clki->curr_freq = clki->min_freq;
901 dev_dbg(hba->dev, "%s: clk: %s, rate: %lu\n", __func__,
902 clki->name, clk_get_rate(clki->clk));
905 ret = ufshcd_vops_clk_scale_notify(hba, scale_up, POST_CHANGE);
908 if (clk_state_changed)
909 trace_ufshcd_profile_clk_scaling(dev_name(hba->dev),
910 (scale_up ? "up" : "down"),
911 ktime_to_us(ktime_sub(ktime_get(), start)), ret);
916 * ufshcd_is_devfreq_scaling_required - check if scaling is required or not
917 * @hba: per adapter instance
918 * @scale_up: True if scaling up and false if scaling down
920 * Returns true if scaling is required, false otherwise.
922 static bool ufshcd_is_devfreq_scaling_required(struct ufs_hba *hba,
925 struct ufs_clk_info *clki;
926 struct list_head *head = &hba->clk_list_head;
928 if (list_empty(head))
931 list_for_each_entry(clki, head, list) {
932 if (!IS_ERR_OR_NULL(clki->clk)) {
933 if (scale_up && clki->max_freq) {
934 if (clki->curr_freq == clki->max_freq)
937 } else if (!scale_up && clki->min_freq) {
938 if (clki->curr_freq == clki->min_freq)
948 static int ufshcd_wait_for_doorbell_clr(struct ufs_hba *hba,
955 bool timeout = false, do_last_check = false;
958 ufshcd_hold(hba, false);
959 spin_lock_irqsave(hba->host->host_lock, flags);
961 * Wait for all the outstanding tasks/transfer requests.
962 * Verify by checking the doorbell registers are clear.
966 if (hba->ufshcd_state != UFSHCD_STATE_OPERATIONAL) {
971 tm_doorbell = ufshcd_readl(hba, REG_UTP_TASK_REQ_DOOR_BELL);
972 tr_doorbell = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
973 if (!tm_doorbell && !tr_doorbell) {
976 } else if (do_last_check) {
980 spin_unlock_irqrestore(hba->host->host_lock, flags);
982 if (ktime_to_us(ktime_sub(ktime_get(), start)) >
986 * We might have scheduled out for long time so make
987 * sure to check if doorbells are cleared by this time
990 do_last_check = true;
992 spin_lock_irqsave(hba->host->host_lock, flags);
993 } while (tm_doorbell || tr_doorbell);
997 "%s: timedout waiting for doorbell to clear (tm=0x%x, tr=0x%x)\n",
998 __func__, tm_doorbell, tr_doorbell);
1002 spin_unlock_irqrestore(hba->host->host_lock, flags);
1003 ufshcd_release(hba);
1008 * ufshcd_scale_gear - scale up/down UFS gear
1009 * @hba: per adapter instance
1010 * @scale_up: True for scaling up gear and false for scaling down
1012 * Returns 0 for success,
1013 * Returns -EBUSY if scaling can't happen at this time
1014 * Returns non-zero for any other errors
1016 static int ufshcd_scale_gear(struct ufs_hba *hba, bool scale_up)
1018 #define UFS_MIN_GEAR_TO_SCALE_DOWN UFS_HS_G1
1020 struct ufs_pa_layer_attr new_pwr_info;
1023 memcpy(&new_pwr_info, &hba->clk_scaling.saved_pwr_info.info,
1024 sizeof(struct ufs_pa_layer_attr));
1026 memcpy(&new_pwr_info, &hba->pwr_info,
1027 sizeof(struct ufs_pa_layer_attr));
1029 if (hba->pwr_info.gear_tx > UFS_MIN_GEAR_TO_SCALE_DOWN
1030 || hba->pwr_info.gear_rx > UFS_MIN_GEAR_TO_SCALE_DOWN) {
1031 /* save the current power mode */
1032 memcpy(&hba->clk_scaling.saved_pwr_info.info,
1034 sizeof(struct ufs_pa_layer_attr));
1036 /* scale down gear */
1037 new_pwr_info.gear_tx = UFS_MIN_GEAR_TO_SCALE_DOWN;
1038 new_pwr_info.gear_rx = UFS_MIN_GEAR_TO_SCALE_DOWN;
1042 /* check if the power mode needs to be changed or not? */
1043 ret = ufshcd_change_power_mode(hba, &new_pwr_info);
1046 dev_err(hba->dev, "%s: failed err %d, old gear: (tx %d rx %d), new gear: (tx %d rx %d)",
1048 hba->pwr_info.gear_tx, hba->pwr_info.gear_rx,
1049 new_pwr_info.gear_tx, new_pwr_info.gear_rx);
1054 static int ufshcd_clock_scaling_prepare(struct ufs_hba *hba)
1056 #define DOORBELL_CLR_TOUT_US (1000 * 1000) /* 1 sec */
1059 * make sure that there are no outstanding requests when
1060 * clock scaling is in progress
1062 scsi_block_requests(hba->host);
1063 down_write(&hba->clk_scaling_lock);
1064 if (ufshcd_wait_for_doorbell_clr(hba, DOORBELL_CLR_TOUT_US)) {
1066 up_write(&hba->clk_scaling_lock);
1067 scsi_unblock_requests(hba->host);
1073 static void ufshcd_clock_scaling_unprepare(struct ufs_hba *hba)
1075 up_write(&hba->clk_scaling_lock);
1076 scsi_unblock_requests(hba->host);
1080 * ufshcd_devfreq_scale - scale up/down UFS clocks and gear
1081 * @hba: per adapter instance
1082 * @scale_up: True for scaling up and false for scalin down
1084 * Returns 0 for success,
1085 * Returns -EBUSY if scaling can't happen at this time
1086 * Returns non-zero for any other errors
1088 static int ufshcd_devfreq_scale(struct ufs_hba *hba, bool scale_up)
1092 /* let's not get into low power until clock scaling is completed */
1093 ufshcd_hold(hba, false);
1095 ret = ufshcd_clock_scaling_prepare(hba);
1099 /* scale down the gear before scaling down clocks */
1101 ret = ufshcd_scale_gear(hba, false);
1106 ret = ufshcd_scale_clks(hba, scale_up);
1109 ufshcd_scale_gear(hba, true);
1113 /* scale up the gear after scaling up clocks */
1115 ret = ufshcd_scale_gear(hba, true);
1117 ufshcd_scale_clks(hba, false);
1122 ret = ufshcd_vops_clk_scale_notify(hba, scale_up, POST_CHANGE);
1125 ufshcd_clock_scaling_unprepare(hba);
1126 ufshcd_release(hba);
1130 static void ufshcd_clk_scaling_suspend_work(struct work_struct *work)
1132 struct ufs_hba *hba = container_of(work, struct ufs_hba,
1133 clk_scaling.suspend_work);
1134 unsigned long irq_flags;
1136 spin_lock_irqsave(hba->host->host_lock, irq_flags);
1137 if (hba->clk_scaling.active_reqs || hba->clk_scaling.is_suspended) {
1138 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1141 hba->clk_scaling.is_suspended = true;
1142 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1144 __ufshcd_suspend_clkscaling(hba);
1147 static void ufshcd_clk_scaling_resume_work(struct work_struct *work)
1149 struct ufs_hba *hba = container_of(work, struct ufs_hba,
1150 clk_scaling.resume_work);
1151 unsigned long irq_flags;
1153 spin_lock_irqsave(hba->host->host_lock, irq_flags);
1154 if (!hba->clk_scaling.is_suspended) {
1155 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1158 hba->clk_scaling.is_suspended = false;
1159 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1161 devfreq_resume_device(hba->devfreq);
1164 static int ufshcd_devfreq_target(struct device *dev,
1165 unsigned long *freq, u32 flags)
1168 struct ufs_hba *hba = dev_get_drvdata(dev);
1170 bool scale_up, sched_clk_scaling_suspend_work = false;
1171 unsigned long irq_flags;
1173 if (!ufshcd_is_clkscaling_supported(hba))
1176 if ((*freq > 0) && (*freq < UINT_MAX)) {
1177 dev_err(hba->dev, "%s: invalid freq = %lu\n", __func__, *freq);
1181 spin_lock_irqsave(hba->host->host_lock, irq_flags);
1182 if (ufshcd_eh_in_progress(hba)) {
1183 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1187 if (!hba->clk_scaling.active_reqs)
1188 sched_clk_scaling_suspend_work = true;
1190 scale_up = (*freq == UINT_MAX) ? true : false;
1191 if (!ufshcd_is_devfreq_scaling_required(hba, scale_up)) {
1192 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1194 goto out; /* no state change required */
1196 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1198 start = ktime_get();
1199 ret = ufshcd_devfreq_scale(hba, scale_up);
1201 trace_ufshcd_profile_clk_scaling(dev_name(hba->dev),
1202 (scale_up ? "up" : "down"),
1203 ktime_to_us(ktime_sub(ktime_get(), start)), ret);
1206 if (sched_clk_scaling_suspend_work)
1207 queue_work(hba->clk_scaling.workq,
1208 &hba->clk_scaling.suspend_work);
1214 static int ufshcd_devfreq_get_dev_status(struct device *dev,
1215 struct devfreq_dev_status *stat)
1217 struct ufs_hba *hba = dev_get_drvdata(dev);
1218 struct ufs_clk_scaling *scaling = &hba->clk_scaling;
1219 unsigned long flags;
1221 if (!ufshcd_is_clkscaling_supported(hba))
1224 memset(stat, 0, sizeof(*stat));
1226 spin_lock_irqsave(hba->host->host_lock, flags);
1227 if (!scaling->window_start_t)
1230 if (scaling->is_busy_started)
1231 scaling->tot_busy_t += ktime_to_us(ktime_sub(ktime_get(),
1232 scaling->busy_start_t));
1234 stat->total_time = jiffies_to_usecs((long)jiffies -
1235 (long)scaling->window_start_t);
1236 stat->busy_time = scaling->tot_busy_t;
1238 scaling->window_start_t = jiffies;
1239 scaling->tot_busy_t = 0;
1241 if (hba->outstanding_reqs) {
1242 scaling->busy_start_t = ktime_get();
1243 scaling->is_busy_started = true;
1245 scaling->busy_start_t = 0;
1246 scaling->is_busy_started = false;
1248 spin_unlock_irqrestore(hba->host->host_lock, flags);
1252 static struct devfreq_dev_profile ufs_devfreq_profile = {
1254 .target = ufshcd_devfreq_target,
1255 .get_dev_status = ufshcd_devfreq_get_dev_status,
1258 static void __ufshcd_suspend_clkscaling(struct ufs_hba *hba)
1260 unsigned long flags;
1262 devfreq_suspend_device(hba->devfreq);
1263 spin_lock_irqsave(hba->host->host_lock, flags);
1264 hba->clk_scaling.window_start_t = 0;
1265 spin_unlock_irqrestore(hba->host->host_lock, flags);
1268 static void ufshcd_suspend_clkscaling(struct ufs_hba *hba)
1270 unsigned long flags;
1271 bool suspend = false;
1273 if (!ufshcd_is_clkscaling_supported(hba))
1276 spin_lock_irqsave(hba->host->host_lock, flags);
1277 if (!hba->clk_scaling.is_suspended) {
1279 hba->clk_scaling.is_suspended = true;
1281 spin_unlock_irqrestore(hba->host->host_lock, flags);
1284 __ufshcd_suspend_clkscaling(hba);
1287 static void ufshcd_resume_clkscaling(struct ufs_hba *hba)
1289 unsigned long flags;
1290 bool resume = false;
1292 if (!ufshcd_is_clkscaling_supported(hba))
1295 spin_lock_irqsave(hba->host->host_lock, flags);
1296 if (hba->clk_scaling.is_suspended) {
1298 hba->clk_scaling.is_suspended = false;
1300 spin_unlock_irqrestore(hba->host->host_lock, flags);
1303 devfreq_resume_device(hba->devfreq);
1306 static ssize_t ufshcd_clkscale_enable_show(struct device *dev,
1307 struct device_attribute *attr, char *buf)
1309 struct ufs_hba *hba = dev_get_drvdata(dev);
1311 return snprintf(buf, PAGE_SIZE, "%d\n", hba->clk_scaling.is_allowed);
1314 static ssize_t ufshcd_clkscale_enable_store(struct device *dev,
1315 struct device_attribute *attr, const char *buf, size_t count)
1317 struct ufs_hba *hba = dev_get_drvdata(dev);
1321 if (kstrtou32(buf, 0, &value))
1325 if (value == hba->clk_scaling.is_allowed)
1328 pm_runtime_get_sync(hba->dev);
1329 ufshcd_hold(hba, false);
1331 cancel_work_sync(&hba->clk_scaling.suspend_work);
1332 cancel_work_sync(&hba->clk_scaling.resume_work);
1334 hba->clk_scaling.is_allowed = value;
1337 ufshcd_resume_clkscaling(hba);
1339 ufshcd_suspend_clkscaling(hba);
1340 err = ufshcd_devfreq_scale(hba, true);
1342 dev_err(hba->dev, "%s: failed to scale clocks up %d\n",
1346 ufshcd_release(hba);
1347 pm_runtime_put_sync(hba->dev);
1352 static void ufshcd_clkscaling_init_sysfs(struct ufs_hba *hba)
1354 hba->clk_scaling.enable_attr.show = ufshcd_clkscale_enable_show;
1355 hba->clk_scaling.enable_attr.store = ufshcd_clkscale_enable_store;
1356 sysfs_attr_init(&hba->clk_scaling.enable_attr.attr);
1357 hba->clk_scaling.enable_attr.attr.name = "clkscale_enable";
1358 hba->clk_scaling.enable_attr.attr.mode = 0644;
1359 if (device_create_file(hba->dev, &hba->clk_scaling.enable_attr))
1360 dev_err(hba->dev, "Failed to create sysfs for clkscale_enable\n");
1363 static void ufshcd_ungate_work(struct work_struct *work)
1366 unsigned long flags;
1367 struct ufs_hba *hba = container_of(work, struct ufs_hba,
1368 clk_gating.ungate_work);
1370 cancel_delayed_work_sync(&hba->clk_gating.gate_work);
1372 spin_lock_irqsave(hba->host->host_lock, flags);
1373 if (hba->clk_gating.state == CLKS_ON) {
1374 spin_unlock_irqrestore(hba->host->host_lock, flags);
1378 spin_unlock_irqrestore(hba->host->host_lock, flags);
1379 ufshcd_setup_clocks(hba, true);
1381 /* Exit from hibern8 */
1382 if (ufshcd_can_hibern8_during_gating(hba)) {
1383 /* Prevent gating in this path */
1384 hba->clk_gating.is_suspended = true;
1385 if (ufshcd_is_link_hibern8(hba)) {
1386 ret = ufshcd_uic_hibern8_exit(hba);
1388 dev_err(hba->dev, "%s: hibern8 exit failed %d\n",
1391 ufshcd_set_link_active(hba);
1393 hba->clk_gating.is_suspended = false;
1396 scsi_unblock_requests(hba->host);
1400 * ufshcd_hold - Enable clocks that were gated earlier due to ufshcd_release.
1401 * Also, exit from hibern8 mode and set the link as active.
1402 * @hba: per adapter instance
1403 * @async: This indicates whether caller should ungate clocks asynchronously.
1405 int ufshcd_hold(struct ufs_hba *hba, bool async)
1408 unsigned long flags;
1410 if (!ufshcd_is_clkgating_allowed(hba))
1412 spin_lock_irqsave(hba->host->host_lock, flags);
1413 hba->clk_gating.active_reqs++;
1415 if (ufshcd_eh_in_progress(hba)) {
1416 spin_unlock_irqrestore(hba->host->host_lock, flags);
1421 switch (hba->clk_gating.state) {
1424 * Wait for the ungate work to complete if in progress.
1425 * Though the clocks may be in ON state, the link could
1426 * still be in hibner8 state if hibern8 is allowed
1427 * during clock gating.
1428 * Make sure we exit hibern8 state also in addition to
1431 if (ufshcd_can_hibern8_during_gating(hba) &&
1432 ufshcd_is_link_hibern8(hba)) {
1433 spin_unlock_irqrestore(hba->host->host_lock, flags);
1434 flush_work(&hba->clk_gating.ungate_work);
1435 spin_lock_irqsave(hba->host->host_lock, flags);
1440 if (cancel_delayed_work(&hba->clk_gating.gate_work)) {
1441 hba->clk_gating.state = CLKS_ON;
1442 trace_ufshcd_clk_gating(dev_name(hba->dev),
1443 hba->clk_gating.state);
1447 * If we are here, it means gating work is either done or
1448 * currently running. Hence, fall through to cancel gating
1449 * work and to enable clocks.
1452 scsi_block_requests(hba->host);
1453 hba->clk_gating.state = REQ_CLKS_ON;
1454 trace_ufshcd_clk_gating(dev_name(hba->dev),
1455 hba->clk_gating.state);
1456 schedule_work(&hba->clk_gating.ungate_work);
1458 * fall through to check if we should wait for this
1459 * work to be done or not.
1464 hba->clk_gating.active_reqs--;
1468 spin_unlock_irqrestore(hba->host->host_lock, flags);
1469 flush_work(&hba->clk_gating.ungate_work);
1470 /* Make sure state is CLKS_ON before returning */
1471 spin_lock_irqsave(hba->host->host_lock, flags);
1474 dev_err(hba->dev, "%s: clk gating is in invalid state %d\n",
1475 __func__, hba->clk_gating.state);
1478 spin_unlock_irqrestore(hba->host->host_lock, flags);
1482 EXPORT_SYMBOL_GPL(ufshcd_hold);
1484 static void ufshcd_gate_work(struct work_struct *work)
1486 struct ufs_hba *hba = container_of(work, struct ufs_hba,
1487 clk_gating.gate_work.work);
1488 unsigned long flags;
1490 spin_lock_irqsave(hba->host->host_lock, flags);
1492 * In case you are here to cancel this work the gating state
1493 * would be marked as REQ_CLKS_ON. In this case save time by
1494 * skipping the gating work and exit after changing the clock
1497 if (hba->clk_gating.is_suspended ||
1498 (hba->clk_gating.state == REQ_CLKS_ON)) {
1499 hba->clk_gating.state = CLKS_ON;
1500 trace_ufshcd_clk_gating(dev_name(hba->dev),
1501 hba->clk_gating.state);
1505 if (hba->clk_gating.active_reqs
1506 || hba->ufshcd_state != UFSHCD_STATE_OPERATIONAL
1507 || hba->lrb_in_use || hba->outstanding_tasks
1508 || hba->active_uic_cmd || hba->uic_async_done)
1511 spin_unlock_irqrestore(hba->host->host_lock, flags);
1513 /* put the link into hibern8 mode before turning off clocks */
1514 if (ufshcd_can_hibern8_during_gating(hba)) {
1515 if (ufshcd_uic_hibern8_enter(hba)) {
1516 hba->clk_gating.state = CLKS_ON;
1517 trace_ufshcd_clk_gating(dev_name(hba->dev),
1518 hba->clk_gating.state);
1521 ufshcd_set_link_hibern8(hba);
1524 if (!ufshcd_is_link_active(hba))
1525 ufshcd_setup_clocks(hba, false);
1527 /* If link is active, device ref_clk can't be switched off */
1528 __ufshcd_setup_clocks(hba, false, true);
1531 * In case you are here to cancel this work the gating state
1532 * would be marked as REQ_CLKS_ON. In this case keep the state
1533 * as REQ_CLKS_ON which would anyway imply that clocks are off
1534 * and a request to turn them on is pending. By doing this way,
1535 * we keep the state machine in tact and this would ultimately
1536 * prevent from doing cancel work multiple times when there are
1537 * new requests arriving before the current cancel work is done.
1539 spin_lock_irqsave(hba->host->host_lock, flags);
1540 if (hba->clk_gating.state == REQ_CLKS_OFF) {
1541 hba->clk_gating.state = CLKS_OFF;
1542 trace_ufshcd_clk_gating(dev_name(hba->dev),
1543 hba->clk_gating.state);
1546 spin_unlock_irqrestore(hba->host->host_lock, flags);
1551 /* host lock must be held before calling this variant */
1552 static void __ufshcd_release(struct ufs_hba *hba)
1554 if (!ufshcd_is_clkgating_allowed(hba))
1557 hba->clk_gating.active_reqs--;
1559 if (hba->clk_gating.active_reqs || hba->clk_gating.is_suspended
1560 || hba->ufshcd_state != UFSHCD_STATE_OPERATIONAL
1561 || hba->lrb_in_use || hba->outstanding_tasks
1562 || hba->active_uic_cmd || hba->uic_async_done
1563 || ufshcd_eh_in_progress(hba))
1566 hba->clk_gating.state = REQ_CLKS_OFF;
1567 trace_ufshcd_clk_gating(dev_name(hba->dev), hba->clk_gating.state);
1568 schedule_delayed_work(&hba->clk_gating.gate_work,
1569 msecs_to_jiffies(hba->clk_gating.delay_ms));
1572 void ufshcd_release(struct ufs_hba *hba)
1574 unsigned long flags;
1576 spin_lock_irqsave(hba->host->host_lock, flags);
1577 __ufshcd_release(hba);
1578 spin_unlock_irqrestore(hba->host->host_lock, flags);
1580 EXPORT_SYMBOL_GPL(ufshcd_release);
1582 static ssize_t ufshcd_clkgate_delay_show(struct device *dev,
1583 struct device_attribute *attr, char *buf)
1585 struct ufs_hba *hba = dev_get_drvdata(dev);
1587 return snprintf(buf, PAGE_SIZE, "%lu\n", hba->clk_gating.delay_ms);
1590 static ssize_t ufshcd_clkgate_delay_store(struct device *dev,
1591 struct device_attribute *attr, const char *buf, size_t count)
1593 struct ufs_hba *hba = dev_get_drvdata(dev);
1594 unsigned long flags, value;
1596 if (kstrtoul(buf, 0, &value))
1599 spin_lock_irqsave(hba->host->host_lock, flags);
1600 hba->clk_gating.delay_ms = value;
1601 spin_unlock_irqrestore(hba->host->host_lock, flags);
1605 static ssize_t ufshcd_clkgate_enable_show(struct device *dev,
1606 struct device_attribute *attr, char *buf)
1608 struct ufs_hba *hba = dev_get_drvdata(dev);
1610 return snprintf(buf, PAGE_SIZE, "%d\n", hba->clk_gating.is_enabled);
1613 static ssize_t ufshcd_clkgate_enable_store(struct device *dev,
1614 struct device_attribute *attr, const char *buf, size_t count)
1616 struct ufs_hba *hba = dev_get_drvdata(dev);
1617 unsigned long flags;
1620 if (kstrtou32(buf, 0, &value))
1624 if (value == hba->clk_gating.is_enabled)
1628 ufshcd_release(hba);
1630 spin_lock_irqsave(hba->host->host_lock, flags);
1631 hba->clk_gating.active_reqs++;
1632 spin_unlock_irqrestore(hba->host->host_lock, flags);
1635 hba->clk_gating.is_enabled = value;
1640 static void ufshcd_init_clk_gating(struct ufs_hba *hba)
1642 if (!ufshcd_is_clkgating_allowed(hba))
1645 hba->clk_gating.delay_ms = 150;
1646 INIT_DELAYED_WORK(&hba->clk_gating.gate_work, ufshcd_gate_work);
1647 INIT_WORK(&hba->clk_gating.ungate_work, ufshcd_ungate_work);
1649 hba->clk_gating.is_enabled = true;
1651 hba->clk_gating.delay_attr.show = ufshcd_clkgate_delay_show;
1652 hba->clk_gating.delay_attr.store = ufshcd_clkgate_delay_store;
1653 sysfs_attr_init(&hba->clk_gating.delay_attr.attr);
1654 hba->clk_gating.delay_attr.attr.name = "clkgate_delay_ms";
1655 hba->clk_gating.delay_attr.attr.mode = 0644;
1656 if (device_create_file(hba->dev, &hba->clk_gating.delay_attr))
1657 dev_err(hba->dev, "Failed to create sysfs for clkgate_delay\n");
1659 hba->clk_gating.enable_attr.show = ufshcd_clkgate_enable_show;
1660 hba->clk_gating.enable_attr.store = ufshcd_clkgate_enable_store;
1661 sysfs_attr_init(&hba->clk_gating.enable_attr.attr);
1662 hba->clk_gating.enable_attr.attr.name = "clkgate_enable";
1663 hba->clk_gating.enable_attr.attr.mode = 0644;
1664 if (device_create_file(hba->dev, &hba->clk_gating.enable_attr))
1665 dev_err(hba->dev, "Failed to create sysfs for clkgate_enable\n");
1668 static void ufshcd_exit_clk_gating(struct ufs_hba *hba)
1670 if (!ufshcd_is_clkgating_allowed(hba))
1672 device_remove_file(hba->dev, &hba->clk_gating.delay_attr);
1673 device_remove_file(hba->dev, &hba->clk_gating.enable_attr);
1674 cancel_work_sync(&hba->clk_gating.ungate_work);
1675 cancel_delayed_work_sync(&hba->clk_gating.gate_work);
1678 /* Must be called with host lock acquired */
1679 static void ufshcd_clk_scaling_start_busy(struct ufs_hba *hba)
1681 bool queue_resume_work = false;
1683 if (!ufshcd_is_clkscaling_supported(hba))
1686 if (!hba->clk_scaling.active_reqs++)
1687 queue_resume_work = true;
1689 if (!hba->clk_scaling.is_allowed || hba->pm_op_in_progress)
1692 if (queue_resume_work)
1693 queue_work(hba->clk_scaling.workq,
1694 &hba->clk_scaling.resume_work);
1696 if (!hba->clk_scaling.window_start_t) {
1697 hba->clk_scaling.window_start_t = jiffies;
1698 hba->clk_scaling.tot_busy_t = 0;
1699 hba->clk_scaling.is_busy_started = false;
1702 if (!hba->clk_scaling.is_busy_started) {
1703 hba->clk_scaling.busy_start_t = ktime_get();
1704 hba->clk_scaling.is_busy_started = true;
1708 static void ufshcd_clk_scaling_update_busy(struct ufs_hba *hba)
1710 struct ufs_clk_scaling *scaling = &hba->clk_scaling;
1712 if (!ufshcd_is_clkscaling_supported(hba))
1715 if (!hba->outstanding_reqs && scaling->is_busy_started) {
1716 scaling->tot_busy_t += ktime_to_us(ktime_sub(ktime_get(),
1717 scaling->busy_start_t));
1718 scaling->busy_start_t = 0;
1719 scaling->is_busy_started = false;
1723 * ufshcd_send_command - Send SCSI or device management commands
1724 * @hba: per adapter instance
1725 * @task_tag: Task tag of the command
1728 void ufshcd_send_command(struct ufs_hba *hba, unsigned int task_tag)
1730 hba->lrb[task_tag].issue_time_stamp = ktime_get();
1731 hba->lrb[task_tag].compl_time_stamp = ktime_set(0, 0);
1732 ufshcd_clk_scaling_start_busy(hba);
1733 __set_bit(task_tag, &hba->outstanding_reqs);
1734 ufshcd_writel(hba, 1 << task_tag, REG_UTP_TRANSFER_REQ_DOOR_BELL);
1735 /* Make sure that doorbell is committed immediately */
1737 ufshcd_add_command_trace(hba, task_tag, "send");
1741 * ufshcd_copy_sense_data - Copy sense data in case of check condition
1742 * @lrbp: pointer to local reference block
1744 static inline void ufshcd_copy_sense_data(struct ufshcd_lrb *lrbp)
1747 if (lrbp->sense_buffer &&
1748 ufshcd_get_rsp_upiu_data_seg_len(lrbp->ucd_rsp_ptr)) {
1751 len = be16_to_cpu(lrbp->ucd_rsp_ptr->sr.sense_data_len);
1752 len_to_copy = min_t(int, RESPONSE_UPIU_SENSE_DATA_LENGTH, len);
1754 memcpy(lrbp->sense_buffer,
1755 lrbp->ucd_rsp_ptr->sr.sense_data,
1756 min_t(int, len_to_copy, UFSHCD_REQ_SENSE_SIZE));
1761 * ufshcd_copy_query_response() - Copy the Query Response and the data
1763 * @hba: per adapter instance
1764 * @lrbp: pointer to local reference block
1767 int ufshcd_copy_query_response(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
1769 struct ufs_query_res *query_res = &hba->dev_cmd.query.response;
1771 memcpy(&query_res->upiu_res, &lrbp->ucd_rsp_ptr->qr, QUERY_OSF_SIZE);
1773 /* Get the descriptor */
1774 if (lrbp->ucd_rsp_ptr->qr.opcode == UPIU_QUERY_OPCODE_READ_DESC) {
1775 u8 *descp = (u8 *)lrbp->ucd_rsp_ptr +
1776 GENERAL_UPIU_REQUEST_SIZE;
1780 /* data segment length */
1781 resp_len = be32_to_cpu(lrbp->ucd_rsp_ptr->header.dword_2) &
1782 MASK_QUERY_DATA_SEG_LEN;
1783 buf_len = be16_to_cpu(
1784 hba->dev_cmd.query.request.upiu_req.length);
1785 if (likely(buf_len >= resp_len)) {
1786 memcpy(hba->dev_cmd.query.descriptor, descp, resp_len);
1789 "%s: Response size is bigger than buffer",
1799 * ufshcd_hba_capabilities - Read controller capabilities
1800 * @hba: per adapter instance
1802 static inline void ufshcd_hba_capabilities(struct ufs_hba *hba)
1804 hba->capabilities = ufshcd_readl(hba, REG_CONTROLLER_CAPABILITIES);
1806 /* nutrs and nutmrs are 0 based values */
1807 hba->nutrs = (hba->capabilities & MASK_TRANSFER_REQUESTS_SLOTS) + 1;
1809 ((hba->capabilities & MASK_TASK_MANAGEMENT_REQUEST_SLOTS) >> 16) + 1;
1813 * ufshcd_ready_for_uic_cmd - Check if controller is ready
1814 * to accept UIC commands
1815 * @hba: per adapter instance
1816 * Return true on success, else false
1818 static inline bool ufshcd_ready_for_uic_cmd(struct ufs_hba *hba)
1820 if (ufshcd_readl(hba, REG_CONTROLLER_STATUS) & UIC_COMMAND_READY)
1827 * ufshcd_get_upmcrs - Get the power mode change request status
1828 * @hba: Pointer to adapter instance
1830 * This function gets the UPMCRS field of HCS register
1831 * Returns value of UPMCRS field
1833 static inline u8 ufshcd_get_upmcrs(struct ufs_hba *hba)
1835 return (ufshcd_readl(hba, REG_CONTROLLER_STATUS) >> 8) & 0x7;
1839 * ufshcd_dispatch_uic_cmd - Dispatch UIC commands to unipro layers
1840 * @hba: per adapter instance
1841 * @uic_cmd: UIC command
1843 * Mutex must be held.
1846 ufshcd_dispatch_uic_cmd(struct ufs_hba *hba, struct uic_command *uic_cmd)
1848 WARN_ON(hba->active_uic_cmd);
1850 hba->active_uic_cmd = uic_cmd;
1853 ufshcd_writel(hba, uic_cmd->argument1, REG_UIC_COMMAND_ARG_1);
1854 ufshcd_writel(hba, uic_cmd->argument2, REG_UIC_COMMAND_ARG_2);
1855 ufshcd_writel(hba, uic_cmd->argument3, REG_UIC_COMMAND_ARG_3);
1858 ufshcd_writel(hba, uic_cmd->command & COMMAND_OPCODE_MASK,
1863 * ufshcd_wait_for_uic_cmd - Wait complectioin of UIC command
1864 * @hba: per adapter instance
1865 * @uic_cmd: UIC command
1867 * Must be called with mutex held.
1868 * Returns 0 only if success.
1871 ufshcd_wait_for_uic_cmd(struct ufs_hba *hba, struct uic_command *uic_cmd)
1874 unsigned long flags;
1876 if (wait_for_completion_timeout(&uic_cmd->done,
1877 msecs_to_jiffies(UIC_CMD_TIMEOUT)))
1878 ret = uic_cmd->argument2 & MASK_UIC_COMMAND_RESULT;
1882 spin_lock_irqsave(hba->host->host_lock, flags);
1883 hba->active_uic_cmd = NULL;
1884 spin_unlock_irqrestore(hba->host->host_lock, flags);
1890 * __ufshcd_send_uic_cmd - Send UIC commands and retrieve the result
1891 * @hba: per adapter instance
1892 * @uic_cmd: UIC command
1893 * @completion: initialize the completion only if this is set to true
1895 * Identical to ufshcd_send_uic_cmd() expect mutex. Must be called
1896 * with mutex held and host_lock locked.
1897 * Returns 0 only if success.
1900 __ufshcd_send_uic_cmd(struct ufs_hba *hba, struct uic_command *uic_cmd,
1903 if (!ufshcd_ready_for_uic_cmd(hba)) {
1905 "Controller not ready to accept UIC commands\n");
1910 init_completion(&uic_cmd->done);
1912 ufshcd_dispatch_uic_cmd(hba, uic_cmd);
1918 * ufshcd_send_uic_cmd - Send UIC commands and retrieve the result
1919 * @hba: per adapter instance
1920 * @uic_cmd: UIC command
1922 * Returns 0 only if success.
1925 ufshcd_send_uic_cmd(struct ufs_hba *hba, struct uic_command *uic_cmd)
1928 unsigned long flags;
1930 ufshcd_hold(hba, false);
1931 mutex_lock(&hba->uic_cmd_mutex);
1932 ufshcd_add_delay_before_dme_cmd(hba);
1934 spin_lock_irqsave(hba->host->host_lock, flags);
1935 ret = __ufshcd_send_uic_cmd(hba, uic_cmd, true);
1936 spin_unlock_irqrestore(hba->host->host_lock, flags);
1938 ret = ufshcd_wait_for_uic_cmd(hba, uic_cmd);
1940 mutex_unlock(&hba->uic_cmd_mutex);
1942 ufshcd_release(hba);
1947 * ufshcd_map_sg - Map scatter-gather list to prdt
1948 * @hba: per adapter instance
1949 * @lrbp: pointer to local reference block
1951 * Returns 0 in case of success, non-zero value in case of failure
1953 static int ufshcd_map_sg(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
1955 struct ufshcd_sg_entry *prd_table;
1956 struct scatterlist *sg;
1957 struct scsi_cmnd *cmd;
1962 sg_segments = scsi_dma_map(cmd);
1963 if (sg_segments < 0)
1967 if (hba->quirks & UFSHCD_QUIRK_PRDT_BYTE_GRAN)
1968 lrbp->utr_descriptor_ptr->prd_table_length =
1969 cpu_to_le16((u16)(sg_segments *
1970 sizeof(struct ufshcd_sg_entry)));
1972 lrbp->utr_descriptor_ptr->prd_table_length =
1973 cpu_to_le16((u16) (sg_segments));
1975 prd_table = (struct ufshcd_sg_entry *)lrbp->ucd_prdt_ptr;
1977 scsi_for_each_sg(cmd, sg, sg_segments, i) {
1979 cpu_to_le32(((u32) sg_dma_len(sg))-1);
1980 prd_table[i].base_addr =
1981 cpu_to_le32(lower_32_bits(sg->dma_address));
1982 prd_table[i].upper_addr =
1983 cpu_to_le32(upper_32_bits(sg->dma_address));
1984 prd_table[i].reserved = 0;
1987 lrbp->utr_descriptor_ptr->prd_table_length = 0;
1994 * ufshcd_enable_intr - enable interrupts
1995 * @hba: per adapter instance
1996 * @intrs: interrupt bits
1998 static void ufshcd_enable_intr(struct ufs_hba *hba, u32 intrs)
2000 u32 set = ufshcd_readl(hba, REG_INTERRUPT_ENABLE);
2002 if (hba->ufs_version == UFSHCI_VERSION_10) {
2004 rw = set & INTERRUPT_MASK_RW_VER_10;
2005 set = rw | ((set ^ intrs) & intrs);
2010 ufshcd_writel(hba, set, REG_INTERRUPT_ENABLE);
2014 * ufshcd_disable_intr - disable interrupts
2015 * @hba: per adapter instance
2016 * @intrs: interrupt bits
2018 static void ufshcd_disable_intr(struct ufs_hba *hba, u32 intrs)
2020 u32 set = ufshcd_readl(hba, REG_INTERRUPT_ENABLE);
2022 if (hba->ufs_version == UFSHCI_VERSION_10) {
2024 rw = (set & INTERRUPT_MASK_RW_VER_10) &
2025 ~(intrs & INTERRUPT_MASK_RW_VER_10);
2026 set = rw | ((set & intrs) & ~INTERRUPT_MASK_RW_VER_10);
2032 ufshcd_writel(hba, set, REG_INTERRUPT_ENABLE);
2036 * ufshcd_prepare_req_desc_hdr() - Fills the requests header
2037 * descriptor according to request
2038 * @lrbp: pointer to local reference block
2039 * @upiu_flags: flags required in the header
2040 * @cmd_dir: requests data direction
2042 static void ufshcd_prepare_req_desc_hdr(struct ufshcd_lrb *lrbp,
2043 u32 *upiu_flags, enum dma_data_direction cmd_dir)
2045 struct utp_transfer_req_desc *req_desc = lrbp->utr_descriptor_ptr;
2049 if (cmd_dir == DMA_FROM_DEVICE) {
2050 data_direction = UTP_DEVICE_TO_HOST;
2051 *upiu_flags = UPIU_CMD_FLAGS_READ;
2052 } else if (cmd_dir == DMA_TO_DEVICE) {
2053 data_direction = UTP_HOST_TO_DEVICE;
2054 *upiu_flags = UPIU_CMD_FLAGS_WRITE;
2056 data_direction = UTP_NO_DATA_TRANSFER;
2057 *upiu_flags = UPIU_CMD_FLAGS_NONE;
2060 dword_0 = data_direction | (lrbp->command_type
2061 << UPIU_COMMAND_TYPE_OFFSET);
2063 dword_0 |= UTP_REQ_DESC_INT_CMD;
2065 /* Transfer request descriptor header fields */
2066 req_desc->header.dword_0 = cpu_to_le32(dword_0);
2067 /* dword_1 is reserved, hence it is set to 0 */
2068 req_desc->header.dword_1 = 0;
2070 * assigning invalid value for command status. Controller
2071 * updates OCS on command completion, with the command
2074 req_desc->header.dword_2 =
2075 cpu_to_le32(OCS_INVALID_COMMAND_STATUS);
2076 /* dword_3 is reserved, hence it is set to 0 */
2077 req_desc->header.dword_3 = 0;
2079 req_desc->prd_table_length = 0;
2083 * ufshcd_prepare_utp_scsi_cmd_upiu() - fills the utp_transfer_req_desc,
2085 * @lrbp: local reference block pointer
2086 * @upiu_flags: flags
2089 void ufshcd_prepare_utp_scsi_cmd_upiu(struct ufshcd_lrb *lrbp, u32 upiu_flags)
2091 struct utp_upiu_req *ucd_req_ptr = lrbp->ucd_req_ptr;
2092 unsigned short cdb_len;
2094 /* command descriptor fields */
2095 ucd_req_ptr->header.dword_0 = UPIU_HEADER_DWORD(
2096 UPIU_TRANSACTION_COMMAND, upiu_flags,
2097 lrbp->lun, lrbp->task_tag);
2098 ucd_req_ptr->header.dword_1 = UPIU_HEADER_DWORD(
2099 UPIU_COMMAND_SET_TYPE_SCSI, 0, 0, 0);
2101 /* Total EHS length and Data segment length will be zero */
2102 ucd_req_ptr->header.dword_2 = 0;
2104 ucd_req_ptr->sc.exp_data_transfer_len =
2105 cpu_to_be32(lrbp->cmd->sdb.length);
2107 cdb_len = min_t(unsigned short, lrbp->cmd->cmd_len, MAX_CDB_SIZE);
2108 memset(ucd_req_ptr->sc.cdb, 0, MAX_CDB_SIZE);
2109 memcpy(ucd_req_ptr->sc.cdb, lrbp->cmd->cmnd, cdb_len);
2111 memset(lrbp->ucd_rsp_ptr, 0, sizeof(struct utp_upiu_rsp));
2115 * ufshcd_prepare_utp_query_req_upiu() - fills the utp_transfer_req_desc,
2118 * @lrbp: local reference block pointer
2119 * @upiu_flags: flags
2121 static void ufshcd_prepare_utp_query_req_upiu(struct ufs_hba *hba,
2122 struct ufshcd_lrb *lrbp, u32 upiu_flags)
2124 struct utp_upiu_req *ucd_req_ptr = lrbp->ucd_req_ptr;
2125 struct ufs_query *query = &hba->dev_cmd.query;
2126 u16 len = be16_to_cpu(query->request.upiu_req.length);
2127 u8 *descp = (u8 *)lrbp->ucd_req_ptr + GENERAL_UPIU_REQUEST_SIZE;
2129 /* Query request header */
2130 ucd_req_ptr->header.dword_0 = UPIU_HEADER_DWORD(
2131 UPIU_TRANSACTION_QUERY_REQ, upiu_flags,
2132 lrbp->lun, lrbp->task_tag);
2133 ucd_req_ptr->header.dword_1 = UPIU_HEADER_DWORD(
2134 0, query->request.query_func, 0, 0);
2136 /* Data segment length only need for WRITE_DESC */
2137 if (query->request.upiu_req.opcode == UPIU_QUERY_OPCODE_WRITE_DESC)
2138 ucd_req_ptr->header.dword_2 =
2139 UPIU_HEADER_DWORD(0, 0, (len >> 8), (u8)len);
2141 ucd_req_ptr->header.dword_2 = 0;
2143 /* Copy the Query Request buffer as is */
2144 memcpy(&ucd_req_ptr->qr, &query->request.upiu_req,
2147 /* Copy the Descriptor */
2148 if (query->request.upiu_req.opcode == UPIU_QUERY_OPCODE_WRITE_DESC)
2149 memcpy(descp, query->descriptor, len);
2151 memset(lrbp->ucd_rsp_ptr, 0, sizeof(struct utp_upiu_rsp));
2154 static inline void ufshcd_prepare_utp_nop_upiu(struct ufshcd_lrb *lrbp)
2156 struct utp_upiu_req *ucd_req_ptr = lrbp->ucd_req_ptr;
2158 memset(ucd_req_ptr, 0, sizeof(struct utp_upiu_req));
2160 /* command descriptor fields */
2161 ucd_req_ptr->header.dword_0 =
2163 UPIU_TRANSACTION_NOP_OUT, 0, 0, lrbp->task_tag);
2164 /* clear rest of the fields of basic header */
2165 ucd_req_ptr->header.dword_1 = 0;
2166 ucd_req_ptr->header.dword_2 = 0;
2168 memset(lrbp->ucd_rsp_ptr, 0, sizeof(struct utp_upiu_rsp));
2172 * ufshcd_comp_devman_upiu - UFS Protocol Information Unit(UPIU)
2173 * for Device Management Purposes
2174 * @hba: per adapter instance
2175 * @lrbp: pointer to local reference block
2177 static int ufshcd_comp_devman_upiu(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
2182 if ((hba->ufs_version == UFSHCI_VERSION_10) ||
2183 (hba->ufs_version == UFSHCI_VERSION_11))
2184 lrbp->command_type = UTP_CMD_TYPE_DEV_MANAGE;
2186 lrbp->command_type = UTP_CMD_TYPE_UFS_STORAGE;
2188 ufshcd_prepare_req_desc_hdr(lrbp, &upiu_flags, DMA_NONE);
2189 if (hba->dev_cmd.type == DEV_CMD_TYPE_QUERY)
2190 ufshcd_prepare_utp_query_req_upiu(hba, lrbp, upiu_flags);
2191 else if (hba->dev_cmd.type == DEV_CMD_TYPE_NOP)
2192 ufshcd_prepare_utp_nop_upiu(lrbp);
2200 * ufshcd_comp_scsi_upiu - UFS Protocol Information Unit(UPIU)
2202 * @hba: per adapter instance
2203 * @lrbp: pointer to local reference block
2205 static int ufshcd_comp_scsi_upiu(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
2210 if ((hba->ufs_version == UFSHCI_VERSION_10) ||
2211 (hba->ufs_version == UFSHCI_VERSION_11))
2212 lrbp->command_type = UTP_CMD_TYPE_SCSI;
2214 lrbp->command_type = UTP_CMD_TYPE_UFS_STORAGE;
2216 if (likely(lrbp->cmd)) {
2217 ufshcd_prepare_req_desc_hdr(lrbp, &upiu_flags,
2218 lrbp->cmd->sc_data_direction);
2219 ufshcd_prepare_utp_scsi_cmd_upiu(lrbp, upiu_flags);
2228 * ufshcd_upiu_wlun_to_scsi_wlun - maps UPIU W-LUN id to SCSI W-LUN ID
2229 * @upiu_wlun_id: UPIU W-LUN id
2231 * Returns SCSI W-LUN id
2233 static inline u16 ufshcd_upiu_wlun_to_scsi_wlun(u8 upiu_wlun_id)
2235 return (upiu_wlun_id & ~UFS_UPIU_WLUN_ID) | SCSI_W_LUN_BASE;
2239 * ufshcd_queuecommand - main entry point for SCSI requests
2240 * @host: SCSI host pointer
2241 * @cmd: command from SCSI Midlayer
2243 * Returns 0 for success, non-zero in case of failure
2245 static int ufshcd_queuecommand(struct Scsi_Host *host, struct scsi_cmnd *cmd)
2247 struct ufshcd_lrb *lrbp;
2248 struct ufs_hba *hba;
2249 unsigned long flags;
2253 hba = shost_priv(host);
2255 tag = cmd->request->tag;
2256 if (!ufshcd_valid_tag(hba, tag)) {
2258 "%s: invalid command tag %d: cmd=0x%p, cmd->request=0x%p",
2259 __func__, tag, cmd, cmd->request);
2263 if (!down_read_trylock(&hba->clk_scaling_lock))
2264 return SCSI_MLQUEUE_HOST_BUSY;
2266 spin_lock_irqsave(hba->host->host_lock, flags);
2267 switch (hba->ufshcd_state) {
2268 case UFSHCD_STATE_OPERATIONAL:
2270 case UFSHCD_STATE_EH_SCHEDULED:
2271 case UFSHCD_STATE_RESET:
2272 err = SCSI_MLQUEUE_HOST_BUSY;
2274 case UFSHCD_STATE_ERROR:
2275 set_host_byte(cmd, DID_ERROR);
2276 cmd->scsi_done(cmd);
2279 dev_WARN_ONCE(hba->dev, 1, "%s: invalid state %d\n",
2280 __func__, hba->ufshcd_state);
2281 set_host_byte(cmd, DID_BAD_TARGET);
2282 cmd->scsi_done(cmd);
2286 /* if error handling is in progress, don't issue commands */
2287 if (ufshcd_eh_in_progress(hba)) {
2288 set_host_byte(cmd, DID_ERROR);
2289 cmd->scsi_done(cmd);
2292 spin_unlock_irqrestore(hba->host->host_lock, flags);
2294 hba->req_abort_count = 0;
2296 /* acquire the tag to make sure device cmds don't use it */
2297 if (test_and_set_bit_lock(tag, &hba->lrb_in_use)) {
2299 * Dev manage command in progress, requeue the command.
2300 * Requeuing the command helps in cases where the request *may*
2301 * find different tag instead of waiting for dev manage command
2304 err = SCSI_MLQUEUE_HOST_BUSY;
2308 err = ufshcd_hold(hba, true);
2310 err = SCSI_MLQUEUE_HOST_BUSY;
2311 clear_bit_unlock(tag, &hba->lrb_in_use);
2314 WARN_ON(hba->clk_gating.state != CLKS_ON);
2316 lrbp = &hba->lrb[tag];
2320 lrbp->sense_bufflen = UFSHCD_REQ_SENSE_SIZE;
2321 lrbp->sense_buffer = cmd->sense_buffer;
2322 lrbp->task_tag = tag;
2323 lrbp->lun = ufshcd_scsi_to_upiu_lun(cmd->device->lun);
2324 lrbp->intr_cmd = !ufshcd_is_intr_aggr_allowed(hba) ? true : false;
2325 lrbp->req_abort_skip = false;
2327 ufshcd_comp_scsi_upiu(hba, lrbp);
2329 err = ufshcd_map_sg(hba, lrbp);
2332 clear_bit_unlock(tag, &hba->lrb_in_use);
2335 /* Make sure descriptors are ready before ringing the doorbell */
2338 /* issue command to the controller */
2339 spin_lock_irqsave(hba->host->host_lock, flags);
2340 ufshcd_vops_setup_xfer_req(hba, tag, (lrbp->cmd ? true : false));
2341 ufshcd_send_command(hba, tag);
2343 spin_unlock_irqrestore(hba->host->host_lock, flags);
2345 up_read(&hba->clk_scaling_lock);
2349 static int ufshcd_compose_dev_cmd(struct ufs_hba *hba,
2350 struct ufshcd_lrb *lrbp, enum dev_cmd_type cmd_type, int tag)
2353 lrbp->sense_bufflen = 0;
2354 lrbp->sense_buffer = NULL;
2355 lrbp->task_tag = tag;
2356 lrbp->lun = 0; /* device management cmd is not specific to any LUN */
2357 lrbp->intr_cmd = true; /* No interrupt aggregation */
2358 hba->dev_cmd.type = cmd_type;
2360 return ufshcd_comp_devman_upiu(hba, lrbp);
2364 ufshcd_clear_cmd(struct ufs_hba *hba, int tag)
2367 unsigned long flags;
2368 u32 mask = 1 << tag;
2370 /* clear outstanding transaction before retry */
2371 spin_lock_irqsave(hba->host->host_lock, flags);
2372 ufshcd_utrl_clear(hba, tag);
2373 spin_unlock_irqrestore(hba->host->host_lock, flags);
2376 * wait for for h/w to clear corresponding bit in door-bell.
2377 * max. wait is 1 sec.
2379 err = ufshcd_wait_for_register(hba,
2380 REG_UTP_TRANSFER_REQ_DOOR_BELL,
2381 mask, ~mask, 1000, 1000, true);
2387 ufshcd_check_query_response(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
2389 struct ufs_query_res *query_res = &hba->dev_cmd.query.response;
2391 /* Get the UPIU response */
2392 query_res->response = ufshcd_get_rsp_upiu_result(lrbp->ucd_rsp_ptr) >>
2393 UPIU_RSP_CODE_OFFSET;
2394 return query_res->response;
2398 * ufshcd_dev_cmd_completion() - handles device management command responses
2399 * @hba: per adapter instance
2400 * @lrbp: pointer to local reference block
2403 ufshcd_dev_cmd_completion(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
2408 hba->ufs_stats.last_hibern8_exit_tstamp = ktime_set(0, 0);
2409 resp = ufshcd_get_req_rsp(lrbp->ucd_rsp_ptr);
2412 case UPIU_TRANSACTION_NOP_IN:
2413 if (hba->dev_cmd.type != DEV_CMD_TYPE_NOP) {
2415 dev_err(hba->dev, "%s: unexpected response %x\n",
2419 case UPIU_TRANSACTION_QUERY_RSP:
2420 err = ufshcd_check_query_response(hba, lrbp);
2422 err = ufshcd_copy_query_response(hba, lrbp);
2424 case UPIU_TRANSACTION_REJECT_UPIU:
2425 /* TODO: handle Reject UPIU Response */
2427 dev_err(hba->dev, "%s: Reject UPIU not fully implemented\n",
2432 dev_err(hba->dev, "%s: Invalid device management cmd response: %x\n",
2440 static int ufshcd_wait_for_dev_cmd(struct ufs_hba *hba,
2441 struct ufshcd_lrb *lrbp, int max_timeout)
2444 unsigned long time_left;
2445 unsigned long flags;
2447 time_left = wait_for_completion_timeout(hba->dev_cmd.complete,
2448 msecs_to_jiffies(max_timeout));
2450 /* Make sure descriptors are ready before ringing the doorbell */
2452 spin_lock_irqsave(hba->host->host_lock, flags);
2453 hba->dev_cmd.complete = NULL;
2454 if (likely(time_left)) {
2455 err = ufshcd_get_tr_ocs(lrbp);
2457 err = ufshcd_dev_cmd_completion(hba, lrbp);
2459 spin_unlock_irqrestore(hba->host->host_lock, flags);
2463 dev_dbg(hba->dev, "%s: dev_cmd request timedout, tag %d\n",
2464 __func__, lrbp->task_tag);
2465 if (!ufshcd_clear_cmd(hba, lrbp->task_tag))
2466 /* successfully cleared the command, retry if needed */
2469 * in case of an error, after clearing the doorbell,
2470 * we also need to clear the outstanding_request
2473 ufshcd_outstanding_req_clear(hba, lrbp->task_tag);
2480 * ufshcd_get_dev_cmd_tag - Get device management command tag
2481 * @hba: per-adapter instance
2482 * @tag_out: pointer to variable with available slot value
2484 * Get a free slot and lock it until device management command
2487 * Returns false if free slot is unavailable for locking, else
2488 * return true with tag value in @tag.
2490 static bool ufshcd_get_dev_cmd_tag(struct ufs_hba *hba, int *tag_out)
2500 tmp = ~hba->lrb_in_use;
2501 tag = find_last_bit(&tmp, hba->nutrs);
2502 if (tag >= hba->nutrs)
2504 } while (test_and_set_bit_lock(tag, &hba->lrb_in_use));
2512 static inline void ufshcd_put_dev_cmd_tag(struct ufs_hba *hba, int tag)
2514 clear_bit_unlock(tag, &hba->lrb_in_use);
2518 * ufshcd_exec_dev_cmd - API for sending device management requests
2520 * @cmd_type: specifies the type (NOP, Query...)
2521 * @timeout: time in seconds
2523 * NOTE: Since there is only one available tag for device management commands,
2524 * it is expected you hold the hba->dev_cmd.lock mutex.
2526 static int ufshcd_exec_dev_cmd(struct ufs_hba *hba,
2527 enum dev_cmd_type cmd_type, int timeout)
2529 struct ufshcd_lrb *lrbp;
2532 struct completion wait;
2533 unsigned long flags;
2535 down_read(&hba->clk_scaling_lock);
2538 * Get free slot, sleep if slots are unavailable.
2539 * Even though we use wait_event() which sleeps indefinitely,
2540 * the maximum wait time is bounded by SCSI request timeout.
2542 wait_event(hba->dev_cmd.tag_wq, ufshcd_get_dev_cmd_tag(hba, &tag));
2544 init_completion(&wait);
2545 lrbp = &hba->lrb[tag];
2547 err = ufshcd_compose_dev_cmd(hba, lrbp, cmd_type, tag);
2551 hba->dev_cmd.complete = &wait;
2553 /* Make sure descriptors are ready before ringing the doorbell */
2555 spin_lock_irqsave(hba->host->host_lock, flags);
2556 ufshcd_vops_setup_xfer_req(hba, tag, (lrbp->cmd ? true : false));
2557 ufshcd_send_command(hba, tag);
2558 spin_unlock_irqrestore(hba->host->host_lock, flags);
2560 err = ufshcd_wait_for_dev_cmd(hba, lrbp, timeout);
2563 ufshcd_put_dev_cmd_tag(hba, tag);
2564 wake_up(&hba->dev_cmd.tag_wq);
2565 up_read(&hba->clk_scaling_lock);
2570 * ufshcd_init_query() - init the query response and request parameters
2571 * @hba: per-adapter instance
2572 * @request: address of the request pointer to be initialized
2573 * @response: address of the response pointer to be initialized
2574 * @opcode: operation to perform
2575 * @idn: flag idn to access
2576 * @index: LU number to access
2577 * @selector: query/flag/descriptor further identification
2579 static inline void ufshcd_init_query(struct ufs_hba *hba,
2580 struct ufs_query_req **request, struct ufs_query_res **response,
2581 enum query_opcode opcode, u8 idn, u8 index, u8 selector)
2583 *request = &hba->dev_cmd.query.request;
2584 *response = &hba->dev_cmd.query.response;
2585 memset(*request, 0, sizeof(struct ufs_query_req));
2586 memset(*response, 0, sizeof(struct ufs_query_res));
2587 (*request)->upiu_req.opcode = opcode;
2588 (*request)->upiu_req.idn = idn;
2589 (*request)->upiu_req.index = index;
2590 (*request)->upiu_req.selector = selector;
2593 static int ufshcd_query_flag_retry(struct ufs_hba *hba,
2594 enum query_opcode opcode, enum flag_idn idn, bool *flag_res)
2599 for (retries = 0; retries < QUERY_REQ_RETRIES; retries++) {
2600 ret = ufshcd_query_flag(hba, opcode, idn, flag_res);
2603 "%s: failed with error %d, retries %d\n",
2604 __func__, ret, retries);
2611 "%s: query attribute, opcode %d, idn %d, failed with error %d after %d retires\n",
2612 __func__, opcode, idn, ret, retries);
2617 * ufshcd_query_flag() - API function for sending flag query requests
2618 * @hba: per-adapter instance
2619 * @opcode: flag query to perform
2620 * @idn: flag idn to access
2621 * @flag_res: the flag value after the query request completes
2623 * Returns 0 for success, non-zero in case of failure
2625 int ufshcd_query_flag(struct ufs_hba *hba, enum query_opcode opcode,
2626 enum flag_idn idn, bool *flag_res)
2628 struct ufs_query_req *request = NULL;
2629 struct ufs_query_res *response = NULL;
2630 int err, index = 0, selector = 0;
2631 int timeout = QUERY_REQ_TIMEOUT;
2635 ufshcd_hold(hba, false);
2636 mutex_lock(&hba->dev_cmd.lock);
2637 ufshcd_init_query(hba, &request, &response, opcode, idn, index,
2641 case UPIU_QUERY_OPCODE_SET_FLAG:
2642 case UPIU_QUERY_OPCODE_CLEAR_FLAG:
2643 case UPIU_QUERY_OPCODE_TOGGLE_FLAG:
2644 request->query_func = UPIU_QUERY_FUNC_STANDARD_WRITE_REQUEST;
2646 case UPIU_QUERY_OPCODE_READ_FLAG:
2647 request->query_func = UPIU_QUERY_FUNC_STANDARD_READ_REQUEST;
2649 /* No dummy reads */
2650 dev_err(hba->dev, "%s: Invalid argument for read request\n",
2658 "%s: Expected query flag opcode but got = %d\n",
2664 err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_QUERY, timeout);
2668 "%s: Sending flag query for idn %d failed, err = %d\n",
2669 __func__, idn, err);
2674 *flag_res = (be32_to_cpu(response->upiu_res.value) &
2675 MASK_QUERY_UPIU_FLAG_LOC) & 0x1;
2678 mutex_unlock(&hba->dev_cmd.lock);
2679 ufshcd_release(hba);
2684 * ufshcd_query_attr - API function for sending attribute requests
2685 * @hba: per-adapter instance
2686 * @opcode: attribute opcode
2687 * @idn: attribute idn to access
2688 * @index: index field
2689 * @selector: selector field
2690 * @attr_val: the attribute value after the query request completes
2692 * Returns 0 for success, non-zero in case of failure
2694 int ufshcd_query_attr(struct ufs_hba *hba, enum query_opcode opcode,
2695 enum attr_idn idn, u8 index, u8 selector, u32 *attr_val)
2697 struct ufs_query_req *request = NULL;
2698 struct ufs_query_res *response = NULL;
2703 ufshcd_hold(hba, false);
2705 dev_err(hba->dev, "%s: attribute value required for opcode 0x%x\n",
2711 mutex_lock(&hba->dev_cmd.lock);
2712 ufshcd_init_query(hba, &request, &response, opcode, idn, index,
2716 case UPIU_QUERY_OPCODE_WRITE_ATTR:
2717 request->query_func = UPIU_QUERY_FUNC_STANDARD_WRITE_REQUEST;
2718 request->upiu_req.value = cpu_to_be32(*attr_val);
2720 case UPIU_QUERY_OPCODE_READ_ATTR:
2721 request->query_func = UPIU_QUERY_FUNC_STANDARD_READ_REQUEST;
2724 dev_err(hba->dev, "%s: Expected query attr opcode but got = 0x%.2x\n",
2730 err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_QUERY, QUERY_REQ_TIMEOUT);
2733 dev_err(hba->dev, "%s: opcode 0x%.2x for idn %d failed, index %d, err = %d\n",
2734 __func__, opcode, idn, index, err);
2738 *attr_val = be32_to_cpu(response->upiu_res.value);
2741 mutex_unlock(&hba->dev_cmd.lock);
2743 ufshcd_release(hba);
2748 * ufshcd_query_attr_retry() - API function for sending query
2749 * attribute with retries
2750 * @hba: per-adapter instance
2751 * @opcode: attribute opcode
2752 * @idn: attribute idn to access
2753 * @index: index field
2754 * @selector: selector field
2755 * @attr_val: the attribute value after the query request
2758 * Returns 0 for success, non-zero in case of failure
2760 static int ufshcd_query_attr_retry(struct ufs_hba *hba,
2761 enum query_opcode opcode, enum attr_idn idn, u8 index, u8 selector,
2767 for (retries = QUERY_REQ_RETRIES; retries > 0; retries--) {
2768 ret = ufshcd_query_attr(hba, opcode, idn, index,
2769 selector, attr_val);
2771 dev_dbg(hba->dev, "%s: failed with error %d, retries %d\n",
2772 __func__, ret, retries);
2779 "%s: query attribute, idn %d, failed with error %d after %d retires\n",
2780 __func__, idn, ret, QUERY_REQ_RETRIES);
2784 static int __ufshcd_query_descriptor(struct ufs_hba *hba,
2785 enum query_opcode opcode, enum desc_idn idn, u8 index,
2786 u8 selector, u8 *desc_buf, int *buf_len)
2788 struct ufs_query_req *request = NULL;
2789 struct ufs_query_res *response = NULL;
2794 ufshcd_hold(hba, false);
2796 dev_err(hba->dev, "%s: descriptor buffer required for opcode 0x%x\n",
2802 if (*buf_len < QUERY_DESC_MIN_SIZE || *buf_len > QUERY_DESC_MAX_SIZE) {
2803 dev_err(hba->dev, "%s: descriptor buffer size (%d) is out of range\n",
2804 __func__, *buf_len);
2809 mutex_lock(&hba->dev_cmd.lock);
2810 ufshcd_init_query(hba, &request, &response, opcode, idn, index,
2812 hba->dev_cmd.query.descriptor = desc_buf;
2813 request->upiu_req.length = cpu_to_be16(*buf_len);
2816 case UPIU_QUERY_OPCODE_WRITE_DESC:
2817 request->query_func = UPIU_QUERY_FUNC_STANDARD_WRITE_REQUEST;
2819 case UPIU_QUERY_OPCODE_READ_DESC:
2820 request->query_func = UPIU_QUERY_FUNC_STANDARD_READ_REQUEST;
2824 "%s: Expected query descriptor opcode but got = 0x%.2x\n",
2830 err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_QUERY, QUERY_REQ_TIMEOUT);
2833 dev_err(hba->dev, "%s: opcode 0x%.2x for idn %d failed, index %d, err = %d\n",
2834 __func__, opcode, idn, index, err);
2838 hba->dev_cmd.query.descriptor = NULL;
2839 *buf_len = be16_to_cpu(response->upiu_res.length);
2842 mutex_unlock(&hba->dev_cmd.lock);
2844 ufshcd_release(hba);
2849 * ufshcd_query_descriptor_retry - API function for sending descriptor requests
2850 * @hba: per-adapter instance
2851 * @opcode: attribute opcode
2852 * @idn: attribute idn to access
2853 * @index: index field
2854 * @selector: selector field
2855 * @desc_buf: the buffer that contains the descriptor
2856 * @buf_len: length parameter passed to the device
2858 * Returns 0 for success, non-zero in case of failure.
2859 * The buf_len parameter will contain, on return, the length parameter
2860 * received on the response.
2862 int ufshcd_query_descriptor_retry(struct ufs_hba *hba,
2863 enum query_opcode opcode,
2864 enum desc_idn idn, u8 index,
2866 u8 *desc_buf, int *buf_len)
2871 for (retries = QUERY_REQ_RETRIES; retries > 0; retries--) {
2872 err = __ufshcd_query_descriptor(hba, opcode, idn, index,
2873 selector, desc_buf, buf_len);
2874 if (!err || err == -EINVAL)
2882 * ufshcd_read_desc_length - read the specified descriptor length from header
2883 * @hba: Pointer to adapter instance
2884 * @desc_id: descriptor idn value
2885 * @desc_index: descriptor index
2886 * @desc_length: pointer to variable to read the length of descriptor
2888 * Return 0 in case of success, non-zero otherwise
2890 static int ufshcd_read_desc_length(struct ufs_hba *hba,
2891 enum desc_idn desc_id,
2896 u8 header[QUERY_DESC_HDR_SIZE];
2897 int header_len = QUERY_DESC_HDR_SIZE;
2899 if (desc_id >= QUERY_DESC_IDN_MAX)
2902 ret = ufshcd_query_descriptor_retry(hba, UPIU_QUERY_OPCODE_READ_DESC,
2903 desc_id, desc_index, 0, header,
2907 dev_err(hba->dev, "%s: Failed to get descriptor header id %d",
2910 } else if (desc_id != header[QUERY_DESC_DESC_TYPE_OFFSET]) {
2911 dev_warn(hba->dev, "%s: descriptor header id %d and desc_id %d mismatch",
2912 __func__, header[QUERY_DESC_DESC_TYPE_OFFSET],
2917 *desc_length = header[QUERY_DESC_LENGTH_OFFSET];
2923 * ufshcd_map_desc_id_to_length - map descriptor IDN to its length
2924 * @hba: Pointer to adapter instance
2925 * @desc_id: descriptor idn value
2926 * @desc_len: mapped desc length (out)
2928 * Return 0 in case of success, non-zero otherwise
2930 int ufshcd_map_desc_id_to_length(struct ufs_hba *hba,
2931 enum desc_idn desc_id, int *desc_len)
2934 case QUERY_DESC_IDN_DEVICE:
2935 *desc_len = hba->desc_size.dev_desc;
2937 case QUERY_DESC_IDN_POWER:
2938 *desc_len = hba->desc_size.pwr_desc;
2940 case QUERY_DESC_IDN_GEOMETRY:
2941 *desc_len = hba->desc_size.geom_desc;
2943 case QUERY_DESC_IDN_CONFIGURATION:
2944 *desc_len = hba->desc_size.conf_desc;
2946 case QUERY_DESC_IDN_UNIT:
2947 *desc_len = hba->desc_size.unit_desc;
2949 case QUERY_DESC_IDN_INTERCONNECT:
2950 *desc_len = hba->desc_size.interc_desc;
2952 case QUERY_DESC_IDN_STRING:
2953 *desc_len = QUERY_DESC_MAX_SIZE;
2955 case QUERY_DESC_IDN_HEALTH:
2956 *desc_len = hba->desc_size.hlth_desc;
2958 case QUERY_DESC_IDN_RFU_0:
2959 case QUERY_DESC_IDN_RFU_1:
2968 EXPORT_SYMBOL(ufshcd_map_desc_id_to_length);
2971 * ufshcd_read_desc_param - read the specified descriptor parameter
2972 * @hba: Pointer to adapter instance
2973 * @desc_id: descriptor idn value
2974 * @desc_index: descriptor index
2975 * @param_offset: offset of the parameter to read
2976 * @param_read_buf: pointer to buffer where parameter would be read
2977 * @param_size: sizeof(param_read_buf)
2979 * Return 0 in case of success, non-zero otherwise
2981 int ufshcd_read_desc_param(struct ufs_hba *hba,
2982 enum desc_idn desc_id,
2991 bool is_kmalloc = true;
2994 if (desc_id >= QUERY_DESC_IDN_MAX || !param_size)
2997 /* Get the max length of descriptor from structure filled up at probe
3000 ret = ufshcd_map_desc_id_to_length(hba, desc_id, &buff_len);
3003 if (ret || !buff_len) {
3004 dev_err(hba->dev, "%s: Failed to get full descriptor length",
3009 /* Check whether we need temp memory */
3010 if (param_offset != 0 || param_size < buff_len) {
3011 desc_buf = kmalloc(buff_len, GFP_KERNEL);
3015 desc_buf = param_read_buf;
3019 /* Request for full descriptor */
3020 ret = ufshcd_query_descriptor_retry(hba, UPIU_QUERY_OPCODE_READ_DESC,
3021 desc_id, desc_index, 0,
3022 desc_buf, &buff_len);
3025 dev_err(hba->dev, "%s: Failed reading descriptor. desc_id %d, desc_index %d, param_offset %d, ret %d",
3026 __func__, desc_id, desc_index, param_offset, ret);
3031 if (desc_buf[QUERY_DESC_DESC_TYPE_OFFSET] != desc_id) {
3032 dev_err(hba->dev, "%s: invalid desc_id %d in descriptor header",
3033 __func__, desc_buf[QUERY_DESC_DESC_TYPE_OFFSET]);
3038 /* Check wherher we will not copy more data, than available */
3039 if (is_kmalloc && param_size > buff_len)
3040 param_size = buff_len;
3043 memcpy(param_read_buf, &desc_buf[param_offset], param_size);
3050 static inline int ufshcd_read_desc(struct ufs_hba *hba,
3051 enum desc_idn desc_id,
3056 return ufshcd_read_desc_param(hba, desc_id, desc_index, 0, buf, size);
3059 static inline int ufshcd_read_power_desc(struct ufs_hba *hba,
3063 return ufshcd_read_desc(hba, QUERY_DESC_IDN_POWER, 0, buf, size);
3066 static int ufshcd_read_device_desc(struct ufs_hba *hba, u8 *buf, u32 size)
3068 return ufshcd_read_desc(hba, QUERY_DESC_IDN_DEVICE, 0, buf, size);
3072 * ufshcd_read_string_desc - read string descriptor
3073 * @hba: pointer to adapter instance
3074 * @desc_index: descriptor index
3075 * @buf: pointer to buffer where descriptor would be read
3076 * @size: size of buf
3077 * @ascii: if true convert from unicode to ascii characters
3079 * Return 0 in case of success, non-zero otherwise
3081 int ufshcd_read_string_desc(struct ufs_hba *hba, int desc_index,
3082 u8 *buf, u32 size, bool ascii)
3086 err = ufshcd_read_desc(hba,
3087 QUERY_DESC_IDN_STRING, desc_index, buf, size);
3090 dev_err(hba->dev, "%s: reading String Desc failed after %d retries. err = %d\n",
3091 __func__, QUERY_REQ_RETRIES, err);
3102 /* remove header and divide by 2 to move from UTF16 to UTF8 */
3103 ascii_len = (desc_len - QUERY_DESC_HDR_SIZE) / 2 + 1;
3104 if (size < ascii_len + QUERY_DESC_HDR_SIZE) {
3105 dev_err(hba->dev, "%s: buffer allocated size is too small\n",
3111 buff_ascii = kmalloc(ascii_len, GFP_KERNEL);
3118 * the descriptor contains string in UTF16 format
3119 * we need to convert to utf-8 so it can be displayed
3121 utf16s_to_utf8s((wchar_t *)&buf[QUERY_DESC_HDR_SIZE],
3122 desc_len - QUERY_DESC_HDR_SIZE,
3123 UTF16_BIG_ENDIAN, buff_ascii, ascii_len);
3125 /* replace non-printable or non-ASCII characters with spaces */
3126 for (i = 0; i < ascii_len; i++)
3127 ufshcd_remove_non_printable(&buff_ascii[i]);
3129 memset(buf + QUERY_DESC_HDR_SIZE, 0,
3130 size - QUERY_DESC_HDR_SIZE);
3131 memcpy(buf + QUERY_DESC_HDR_SIZE, buff_ascii, ascii_len);
3132 buf[QUERY_DESC_LENGTH_OFFSET] = ascii_len + QUERY_DESC_HDR_SIZE;
3140 * ufshcd_read_unit_desc_param - read the specified unit descriptor parameter
3141 * @hba: Pointer to adapter instance
3143 * @param_offset: offset of the parameter to read
3144 * @param_read_buf: pointer to buffer where parameter would be read
3145 * @param_size: sizeof(param_read_buf)
3147 * Return 0 in case of success, non-zero otherwise
3149 static inline int ufshcd_read_unit_desc_param(struct ufs_hba *hba,
3151 enum unit_desc_param param_offset,
3156 * Unit descriptors are only available for general purpose LUs (LUN id
3157 * from 0 to 7) and RPMB Well known LU.
3159 if (!ufs_is_valid_unit_desc_lun(lun))
3162 return ufshcd_read_desc_param(hba, QUERY_DESC_IDN_UNIT, lun,
3163 param_offset, param_read_buf, param_size);
3167 * ufshcd_memory_alloc - allocate memory for host memory space data structures
3168 * @hba: per adapter instance
3170 * 1. Allocate DMA memory for Command Descriptor array
3171 * Each command descriptor consist of Command UPIU, Response UPIU and PRDT
3172 * 2. Allocate DMA memory for UTP Transfer Request Descriptor List (UTRDL).
3173 * 3. Allocate DMA memory for UTP Task Management Request Descriptor List
3175 * 4. Allocate memory for local reference block(lrb).
3177 * Returns 0 for success, non-zero in case of failure
3179 static int ufshcd_memory_alloc(struct ufs_hba *hba)
3181 size_t utmrdl_size, utrdl_size, ucdl_size;
3183 /* Allocate memory for UTP command descriptors */
3184 ucdl_size = (sizeof(struct utp_transfer_cmd_desc) * hba->nutrs);
3185 hba->ucdl_base_addr = dmam_alloc_coherent(hba->dev,
3187 &hba->ucdl_dma_addr,
3191 * UFSHCI requires UTP command descriptor to be 128 byte aligned.
3192 * make sure hba->ucdl_dma_addr is aligned to PAGE_SIZE
3193 * if hba->ucdl_dma_addr is aligned to PAGE_SIZE, then it will
3194 * be aligned to 128 bytes as well
3196 if (!hba->ucdl_base_addr ||
3197 WARN_ON(hba->ucdl_dma_addr & (PAGE_SIZE - 1))) {
3199 "Command Descriptor Memory allocation failed\n");
3204 * Allocate memory for UTP Transfer descriptors
3205 * UFSHCI requires 1024 byte alignment of UTRD
3207 utrdl_size = (sizeof(struct utp_transfer_req_desc) * hba->nutrs);
3208 hba->utrdl_base_addr = dmam_alloc_coherent(hba->dev,
3210 &hba->utrdl_dma_addr,
3212 if (!hba->utrdl_base_addr ||
3213 WARN_ON(hba->utrdl_dma_addr & (PAGE_SIZE - 1))) {
3215 "Transfer Descriptor Memory allocation failed\n");
3220 * Allocate memory for UTP Task Management descriptors
3221 * UFSHCI requires 1024 byte alignment of UTMRD
3223 utmrdl_size = sizeof(struct utp_task_req_desc) * hba->nutmrs;
3224 hba->utmrdl_base_addr = dmam_alloc_coherent(hba->dev,
3226 &hba->utmrdl_dma_addr,
3228 if (!hba->utmrdl_base_addr ||
3229 WARN_ON(hba->utmrdl_dma_addr & (PAGE_SIZE - 1))) {
3231 "Task Management Descriptor Memory allocation failed\n");
3235 /* Allocate memory for local reference block */
3236 hba->lrb = devm_kzalloc(hba->dev,
3237 hba->nutrs * sizeof(struct ufshcd_lrb),
3240 dev_err(hba->dev, "LRB Memory allocation failed\n");
3249 * ufshcd_host_memory_configure - configure local reference block with
3251 * @hba: per adapter instance
3253 * Configure Host memory space
3254 * 1. Update Corresponding UTRD.UCDBA and UTRD.UCDBAU with UCD DMA
3256 * 2. Update each UTRD with Response UPIU offset, Response UPIU length
3258 * 3. Save the corresponding addresses of UTRD, UCD.CMD, UCD.RSP and UCD.PRDT
3259 * into local reference block.
3261 static void ufshcd_host_memory_configure(struct ufs_hba *hba)
3263 struct utp_transfer_cmd_desc *cmd_descp;
3264 struct utp_transfer_req_desc *utrdlp;
3265 dma_addr_t cmd_desc_dma_addr;
3266 dma_addr_t cmd_desc_element_addr;
3267 u16 response_offset;
3272 utrdlp = hba->utrdl_base_addr;
3273 cmd_descp = hba->ucdl_base_addr;
3276 offsetof(struct utp_transfer_cmd_desc, response_upiu);
3278 offsetof(struct utp_transfer_cmd_desc, prd_table);
3280 cmd_desc_size = sizeof(struct utp_transfer_cmd_desc);
3281 cmd_desc_dma_addr = hba->ucdl_dma_addr;
3283 for (i = 0; i < hba->nutrs; i++) {
3284 /* Configure UTRD with command descriptor base address */
3285 cmd_desc_element_addr =
3286 (cmd_desc_dma_addr + (cmd_desc_size * i));
3287 utrdlp[i].command_desc_base_addr_lo =
3288 cpu_to_le32(lower_32_bits(cmd_desc_element_addr));
3289 utrdlp[i].command_desc_base_addr_hi =
3290 cpu_to_le32(upper_32_bits(cmd_desc_element_addr));
3292 /* Response upiu and prdt offset should be in double words */
3293 if (hba->quirks & UFSHCD_QUIRK_PRDT_BYTE_GRAN) {
3294 utrdlp[i].response_upiu_offset =
3295 cpu_to_le16(response_offset);
3296 utrdlp[i].prd_table_offset =
3297 cpu_to_le16(prdt_offset);
3298 utrdlp[i].response_upiu_length =
3299 cpu_to_le16(ALIGNED_UPIU_SIZE);
3301 utrdlp[i].response_upiu_offset =
3302 cpu_to_le16((response_offset >> 2));
3303 utrdlp[i].prd_table_offset =
3304 cpu_to_le16((prdt_offset >> 2));
3305 utrdlp[i].response_upiu_length =
3306 cpu_to_le16(ALIGNED_UPIU_SIZE >> 2);
3309 hba->lrb[i].utr_descriptor_ptr = (utrdlp + i);
3310 hba->lrb[i].utrd_dma_addr = hba->utrdl_dma_addr +
3311 (i * sizeof(struct utp_transfer_req_desc));
3312 hba->lrb[i].ucd_req_ptr =
3313 (struct utp_upiu_req *)(cmd_descp + i);
3314 hba->lrb[i].ucd_req_dma_addr = cmd_desc_element_addr;
3315 hba->lrb[i].ucd_rsp_ptr =
3316 (struct utp_upiu_rsp *)cmd_descp[i].response_upiu;
3317 hba->lrb[i].ucd_rsp_dma_addr = cmd_desc_element_addr +
3319 hba->lrb[i].ucd_prdt_ptr =
3320 (struct ufshcd_sg_entry *)cmd_descp[i].prd_table;
3321 hba->lrb[i].ucd_prdt_dma_addr = cmd_desc_element_addr +
3327 * ufshcd_dme_link_startup - Notify Unipro to perform link startup
3328 * @hba: per adapter instance
3330 * UIC_CMD_DME_LINK_STARTUP command must be issued to Unipro layer,
3331 * in order to initialize the Unipro link startup procedure.
3332 * Once the Unipro links are up, the device connected to the controller
3335 * Returns 0 on success, non-zero value on failure
3337 static int ufshcd_dme_link_startup(struct ufs_hba *hba)
3339 struct uic_command uic_cmd = {0};
3342 uic_cmd.command = UIC_CMD_DME_LINK_STARTUP;
3344 ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
3347 "dme-link-startup: error code %d\n", ret);
3351 static inline void ufshcd_add_delay_before_dme_cmd(struct ufs_hba *hba)
3353 #define MIN_DELAY_BEFORE_DME_CMDS_US 1000
3354 unsigned long min_sleep_time_us;
3356 if (!(hba->quirks & UFSHCD_QUIRK_DELAY_BEFORE_DME_CMDS))
3360 * last_dme_cmd_tstamp will be 0 only for 1st call to
3363 if (unlikely(!ktime_to_us(hba->last_dme_cmd_tstamp))) {
3364 min_sleep_time_us = MIN_DELAY_BEFORE_DME_CMDS_US;
3366 unsigned long delta =
3367 (unsigned long) ktime_to_us(
3368 ktime_sub(ktime_get(),
3369 hba->last_dme_cmd_tstamp));
3371 if (delta < MIN_DELAY_BEFORE_DME_CMDS_US)
3373 MIN_DELAY_BEFORE_DME_CMDS_US - delta;
3375 return; /* no more delay required */
3378 /* allow sleep for extra 50us if needed */
3379 usleep_range(min_sleep_time_us, min_sleep_time_us + 50);
3383 * ufshcd_dme_set_attr - UIC command for DME_SET, DME_PEER_SET
3384 * @hba: per adapter instance
3385 * @attr_sel: uic command argument1
3386 * @attr_set: attribute set type as uic command argument2
3387 * @mib_val: setting value as uic command argument3
3388 * @peer: indicate whether peer or local
3390 * Returns 0 on success, non-zero value on failure
3392 int ufshcd_dme_set_attr(struct ufs_hba *hba, u32 attr_sel,
3393 u8 attr_set, u32 mib_val, u8 peer)
3395 struct uic_command uic_cmd = {0};
3396 static const char *const action[] = {
3400 const char *set = action[!!peer];
3402 int retries = UFS_UIC_COMMAND_RETRIES;
3404 uic_cmd.command = peer ?
3405 UIC_CMD_DME_PEER_SET : UIC_CMD_DME_SET;
3406 uic_cmd.argument1 = attr_sel;
3407 uic_cmd.argument2 = UIC_ARG_ATTR_TYPE(attr_set);
3408 uic_cmd.argument3 = mib_val;
3411 /* for peer attributes we retry upon failure */
3412 ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
3414 dev_dbg(hba->dev, "%s: attr-id 0x%x val 0x%x error code %d\n",
3415 set, UIC_GET_ATTR_ID(attr_sel), mib_val, ret);
3416 } while (ret && peer && --retries);
3419 dev_err(hba->dev, "%s: attr-id 0x%x val 0x%x failed %d retries\n",
3420 set, UIC_GET_ATTR_ID(attr_sel), mib_val,
3421 UFS_UIC_COMMAND_RETRIES - retries);
3425 EXPORT_SYMBOL_GPL(ufshcd_dme_set_attr);
3428 * ufshcd_dme_get_attr - UIC command for DME_GET, DME_PEER_GET
3429 * @hba: per adapter instance
3430 * @attr_sel: uic command argument1
3431 * @mib_val: the value of the attribute as returned by the UIC command
3432 * @peer: indicate whether peer or local
3434 * Returns 0 on success, non-zero value on failure
3436 int ufshcd_dme_get_attr(struct ufs_hba *hba, u32 attr_sel,
3437 u32 *mib_val, u8 peer)
3439 struct uic_command uic_cmd = {0};
3440 static const char *const action[] = {
3444 const char *get = action[!!peer];
3446 int retries = UFS_UIC_COMMAND_RETRIES;
3447 struct ufs_pa_layer_attr orig_pwr_info;
3448 struct ufs_pa_layer_attr temp_pwr_info;
3449 bool pwr_mode_change = false;
3451 if (peer && (hba->quirks & UFSHCD_QUIRK_DME_PEER_ACCESS_AUTO_MODE)) {
3452 orig_pwr_info = hba->pwr_info;
3453 temp_pwr_info = orig_pwr_info;
3455 if (orig_pwr_info.pwr_tx == FAST_MODE ||
3456 orig_pwr_info.pwr_rx == FAST_MODE) {
3457 temp_pwr_info.pwr_tx = FASTAUTO_MODE;
3458 temp_pwr_info.pwr_rx = FASTAUTO_MODE;
3459 pwr_mode_change = true;
3460 } else if (orig_pwr_info.pwr_tx == SLOW_MODE ||
3461 orig_pwr_info.pwr_rx == SLOW_MODE) {
3462 temp_pwr_info.pwr_tx = SLOWAUTO_MODE;
3463 temp_pwr_info.pwr_rx = SLOWAUTO_MODE;
3464 pwr_mode_change = true;
3466 if (pwr_mode_change) {
3467 ret = ufshcd_change_power_mode(hba, &temp_pwr_info);
3473 uic_cmd.command = peer ?
3474 UIC_CMD_DME_PEER_GET : UIC_CMD_DME_GET;
3475 uic_cmd.argument1 = attr_sel;
3478 /* for peer attributes we retry upon failure */
3479 ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
3481 dev_dbg(hba->dev, "%s: attr-id 0x%x error code %d\n",
3482 get, UIC_GET_ATTR_ID(attr_sel), ret);
3483 } while (ret && peer && --retries);
3486 dev_err(hba->dev, "%s: attr-id 0x%x failed %d retries\n",
3487 get, UIC_GET_ATTR_ID(attr_sel),
3488 UFS_UIC_COMMAND_RETRIES - retries);
3490 if (mib_val && !ret)
3491 *mib_val = uic_cmd.argument3;
3493 if (peer && (hba->quirks & UFSHCD_QUIRK_DME_PEER_ACCESS_AUTO_MODE)
3495 ufshcd_change_power_mode(hba, &orig_pwr_info);
3499 EXPORT_SYMBOL_GPL(ufshcd_dme_get_attr);
3502 * ufshcd_uic_pwr_ctrl - executes UIC commands (which affects the link power
3503 * state) and waits for it to take effect.
3505 * @hba: per adapter instance
3506 * @cmd: UIC command to execute
3508 * DME operations like DME_SET(PA_PWRMODE), DME_HIBERNATE_ENTER &
3509 * DME_HIBERNATE_EXIT commands take some time to take its effect on both host
3510 * and device UniPro link and hence it's final completion would be indicated by
3511 * dedicated status bits in Interrupt Status register (UPMS, UHES, UHXS) in
3512 * addition to normal UIC command completion Status (UCCS). This function only
3513 * returns after the relevant status bits indicate the completion.
3515 * Returns 0 on success, non-zero value on failure
3517 static int ufshcd_uic_pwr_ctrl(struct ufs_hba *hba, struct uic_command *cmd)
3519 struct completion uic_async_done;
3520 unsigned long flags;
3523 bool reenable_intr = false;
3525 mutex_lock(&hba->uic_cmd_mutex);
3526 init_completion(&uic_async_done);
3527 ufshcd_add_delay_before_dme_cmd(hba);
3529 spin_lock_irqsave(hba->host->host_lock, flags);
3530 hba->uic_async_done = &uic_async_done;
3531 if (ufshcd_readl(hba, REG_INTERRUPT_ENABLE) & UIC_COMMAND_COMPL) {
3532 ufshcd_disable_intr(hba, UIC_COMMAND_COMPL);
3534 * Make sure UIC command completion interrupt is disabled before
3535 * issuing UIC command.
3538 reenable_intr = true;
3540 ret = __ufshcd_send_uic_cmd(hba, cmd, false);
3541 spin_unlock_irqrestore(hba->host->host_lock, flags);
3544 "pwr ctrl cmd 0x%x with mode 0x%x uic error %d\n",
3545 cmd->command, cmd->argument3, ret);
3549 if (!wait_for_completion_timeout(hba->uic_async_done,
3550 msecs_to_jiffies(UIC_CMD_TIMEOUT))) {
3552 "pwr ctrl cmd 0x%x with mode 0x%x completion timeout\n",
3553 cmd->command, cmd->argument3);
3558 status = ufshcd_get_upmcrs(hba);
3559 if (status != PWR_LOCAL) {
3561 "pwr ctrl cmd 0x%x failed, host upmcrs:0x%x\n",
3562 cmd->command, status);
3563 ret = (status != PWR_OK) ? status : -1;
3567 ufshcd_print_host_state(hba);
3568 ufshcd_print_pwr_info(hba);
3569 ufshcd_print_host_regs(hba);
3572 spin_lock_irqsave(hba->host->host_lock, flags);
3573 hba->active_uic_cmd = NULL;
3574 hba->uic_async_done = NULL;
3576 ufshcd_enable_intr(hba, UIC_COMMAND_COMPL);
3577 spin_unlock_irqrestore(hba->host->host_lock, flags);
3578 mutex_unlock(&hba->uic_cmd_mutex);
3584 * ufshcd_uic_change_pwr_mode - Perform the UIC power mode chage
3585 * using DME_SET primitives.
3586 * @hba: per adapter instance
3587 * @mode: powr mode value
3589 * Returns 0 on success, non-zero value on failure
3591 static int ufshcd_uic_change_pwr_mode(struct ufs_hba *hba, u8 mode)
3593 struct uic_command uic_cmd = {0};
3596 if (hba->quirks & UFSHCD_QUIRK_BROKEN_PA_RXHSUNTERMCAP) {
3597 ret = ufshcd_dme_set(hba,
3598 UIC_ARG_MIB_SEL(PA_RXHSUNTERMCAP, 0), 1);
3600 dev_err(hba->dev, "%s: failed to enable PA_RXHSUNTERMCAP ret %d\n",
3606 uic_cmd.command = UIC_CMD_DME_SET;
3607 uic_cmd.argument1 = UIC_ARG_MIB(PA_PWRMODE);
3608 uic_cmd.argument3 = mode;
3609 ufshcd_hold(hba, false);
3610 ret = ufshcd_uic_pwr_ctrl(hba, &uic_cmd);
3611 ufshcd_release(hba);
3617 static int ufshcd_link_recovery(struct ufs_hba *hba)
3620 unsigned long flags;
3622 spin_lock_irqsave(hba->host->host_lock, flags);
3623 hba->ufshcd_state = UFSHCD_STATE_RESET;
3624 ufshcd_set_eh_in_progress(hba);
3625 spin_unlock_irqrestore(hba->host->host_lock, flags);
3627 ret = ufshcd_host_reset_and_restore(hba);
3629 spin_lock_irqsave(hba->host->host_lock, flags);
3631 hba->ufshcd_state = UFSHCD_STATE_ERROR;
3632 ufshcd_clear_eh_in_progress(hba);
3633 spin_unlock_irqrestore(hba->host->host_lock, flags);
3636 dev_err(hba->dev, "%s: link recovery failed, err %d",
3642 static int __ufshcd_uic_hibern8_enter(struct ufs_hba *hba)
3645 struct uic_command uic_cmd = {0};
3646 ktime_t start = ktime_get();
3648 ufshcd_vops_hibern8_notify(hba, UIC_CMD_DME_HIBER_ENTER, PRE_CHANGE);
3650 uic_cmd.command = UIC_CMD_DME_HIBER_ENTER;
3651 ret = ufshcd_uic_pwr_ctrl(hba, &uic_cmd);
3652 trace_ufshcd_profile_hibern8(dev_name(hba->dev), "enter",
3653 ktime_to_us(ktime_sub(ktime_get(), start)), ret);
3656 dev_err(hba->dev, "%s: hibern8 enter failed. ret = %d\n",
3660 * If link recovery fails then return error so that caller
3661 * don't retry the hibern8 enter again.
3663 if (ufshcd_link_recovery(hba))
3666 ufshcd_vops_hibern8_notify(hba, UIC_CMD_DME_HIBER_ENTER,
3672 static int ufshcd_uic_hibern8_enter(struct ufs_hba *hba)
3674 int ret = 0, retries;
3676 for (retries = UIC_HIBERN8_ENTER_RETRIES; retries > 0; retries--) {
3677 ret = __ufshcd_uic_hibern8_enter(hba);
3678 if (!ret || ret == -ENOLINK)
3685 static int ufshcd_uic_hibern8_exit(struct ufs_hba *hba)
3687 struct uic_command uic_cmd = {0};
3689 ktime_t start = ktime_get();
3691 ufshcd_vops_hibern8_notify(hba, UIC_CMD_DME_HIBER_EXIT, PRE_CHANGE);
3693 uic_cmd.command = UIC_CMD_DME_HIBER_EXIT;
3694 ret = ufshcd_uic_pwr_ctrl(hba, &uic_cmd);
3695 trace_ufshcd_profile_hibern8(dev_name(hba->dev), "exit",
3696 ktime_to_us(ktime_sub(ktime_get(), start)), ret);
3699 dev_err(hba->dev, "%s: hibern8 exit failed. ret = %d\n",
3701 ret = ufshcd_link_recovery(hba);
3703 ufshcd_vops_hibern8_notify(hba, UIC_CMD_DME_HIBER_EXIT,
3705 hba->ufs_stats.last_hibern8_exit_tstamp = ktime_get();
3706 hba->ufs_stats.hibern8_exit_cnt++;
3712 static void ufshcd_auto_hibern8_enable(struct ufs_hba *hba)
3714 unsigned long flags;
3716 if (!(hba->capabilities & MASK_AUTO_HIBERN8_SUPPORT) || !hba->ahit)
3719 spin_lock_irqsave(hba->host->host_lock, flags);
3720 ufshcd_writel(hba, hba->ahit, REG_AUTO_HIBERNATE_IDLE_TIMER);
3721 spin_unlock_irqrestore(hba->host->host_lock, flags);
3725 * ufshcd_init_pwr_info - setting the POR (power on reset)
3726 * values in hba power info
3727 * @hba: per-adapter instance
3729 static void ufshcd_init_pwr_info(struct ufs_hba *hba)
3731 hba->pwr_info.gear_rx = UFS_PWM_G1;
3732 hba->pwr_info.gear_tx = UFS_PWM_G1;
3733 hba->pwr_info.lane_rx = 1;
3734 hba->pwr_info.lane_tx = 1;
3735 hba->pwr_info.pwr_rx = SLOWAUTO_MODE;
3736 hba->pwr_info.pwr_tx = SLOWAUTO_MODE;
3737 hba->pwr_info.hs_rate = 0;
3741 * ufshcd_get_max_pwr_mode - reads the max power mode negotiated with device
3742 * @hba: per-adapter instance
3744 static int ufshcd_get_max_pwr_mode(struct ufs_hba *hba)
3746 struct ufs_pa_layer_attr *pwr_info = &hba->max_pwr_info.info;
3748 if (hba->max_pwr_info.is_valid)
3751 pwr_info->pwr_tx = FAST_MODE;
3752 pwr_info->pwr_rx = FAST_MODE;
3753 pwr_info->hs_rate = PA_HS_MODE_B;
3755 /* Get the connected lane count */
3756 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_CONNECTEDRXDATALANES),
3757 &pwr_info->lane_rx);
3758 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_CONNECTEDTXDATALANES),
3759 &pwr_info->lane_tx);
3761 if (!pwr_info->lane_rx || !pwr_info->lane_tx) {
3762 dev_err(hba->dev, "%s: invalid connected lanes value. rx=%d, tx=%d\n",
3770 * First, get the maximum gears of HS speed.
3771 * If a zero value, it means there is no HSGEAR capability.
3772 * Then, get the maximum gears of PWM speed.
3774 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_MAXRXHSGEAR), &pwr_info->gear_rx);
3775 if (!pwr_info->gear_rx) {
3776 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_MAXRXPWMGEAR),
3777 &pwr_info->gear_rx);
3778 if (!pwr_info->gear_rx) {
3779 dev_err(hba->dev, "%s: invalid max pwm rx gear read = %d\n",
3780 __func__, pwr_info->gear_rx);
3783 pwr_info->pwr_rx = SLOW_MODE;
3786 ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_MAXRXHSGEAR),
3787 &pwr_info->gear_tx);
3788 if (!pwr_info->gear_tx) {
3789 ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_MAXRXPWMGEAR),
3790 &pwr_info->gear_tx);
3791 if (!pwr_info->gear_tx) {
3792 dev_err(hba->dev, "%s: invalid max pwm tx gear read = %d\n",
3793 __func__, pwr_info->gear_tx);
3796 pwr_info->pwr_tx = SLOW_MODE;
3799 hba->max_pwr_info.is_valid = true;
3803 static int ufshcd_change_power_mode(struct ufs_hba *hba,
3804 struct ufs_pa_layer_attr *pwr_mode)
3808 /* if already configured to the requested pwr_mode */
3809 if (pwr_mode->gear_rx == hba->pwr_info.gear_rx &&
3810 pwr_mode->gear_tx == hba->pwr_info.gear_tx &&
3811 pwr_mode->lane_rx == hba->pwr_info.lane_rx &&
3812 pwr_mode->lane_tx == hba->pwr_info.lane_tx &&
3813 pwr_mode->pwr_rx == hba->pwr_info.pwr_rx &&
3814 pwr_mode->pwr_tx == hba->pwr_info.pwr_tx &&
3815 pwr_mode->hs_rate == hba->pwr_info.hs_rate) {
3816 dev_dbg(hba->dev, "%s: power already configured\n", __func__);
3821 * Configure attributes for power mode change with below.
3822 * - PA_RXGEAR, PA_ACTIVERXDATALANES, PA_RXTERMINATION,
3823 * - PA_TXGEAR, PA_ACTIVETXDATALANES, PA_TXTERMINATION,
3826 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_RXGEAR), pwr_mode->gear_rx);
3827 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_ACTIVERXDATALANES),
3829 if (pwr_mode->pwr_rx == FASTAUTO_MODE ||
3830 pwr_mode->pwr_rx == FAST_MODE)
3831 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_RXTERMINATION), TRUE);
3833 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_RXTERMINATION), FALSE);
3835 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TXGEAR), pwr_mode->gear_tx);
3836 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_ACTIVETXDATALANES),
3838 if (pwr_mode->pwr_tx == FASTAUTO_MODE ||
3839 pwr_mode->pwr_tx == FAST_MODE)
3840 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TXTERMINATION), TRUE);
3842 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TXTERMINATION), FALSE);
3844 if (pwr_mode->pwr_rx == FASTAUTO_MODE ||
3845 pwr_mode->pwr_tx == FASTAUTO_MODE ||
3846 pwr_mode->pwr_rx == FAST_MODE ||
3847 pwr_mode->pwr_tx == FAST_MODE)
3848 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_HSSERIES),
3851 ret = ufshcd_uic_change_pwr_mode(hba, pwr_mode->pwr_rx << 4
3852 | pwr_mode->pwr_tx);
3856 "%s: power mode change failed %d\n", __func__, ret);
3858 ufshcd_vops_pwr_change_notify(hba, POST_CHANGE, NULL,
3861 memcpy(&hba->pwr_info, pwr_mode,
3862 sizeof(struct ufs_pa_layer_attr));
3869 * ufshcd_config_pwr_mode - configure a new power mode
3870 * @hba: per-adapter instance
3871 * @desired_pwr_mode: desired power configuration
3873 static int ufshcd_config_pwr_mode(struct ufs_hba *hba,
3874 struct ufs_pa_layer_attr *desired_pwr_mode)
3876 struct ufs_pa_layer_attr final_params = { 0 };
3879 ret = ufshcd_vops_pwr_change_notify(hba, PRE_CHANGE,
3880 desired_pwr_mode, &final_params);
3883 memcpy(&final_params, desired_pwr_mode, sizeof(final_params));
3885 ret = ufshcd_change_power_mode(hba, &final_params);
3887 ufshcd_print_pwr_info(hba);
3893 * ufshcd_complete_dev_init() - checks device readiness
3894 * @hba: per-adapter instance
3896 * Set fDeviceInit flag and poll until device toggles it.
3898 static int ufshcd_complete_dev_init(struct ufs_hba *hba)
3904 err = ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_SET_FLAG,
3905 QUERY_FLAG_IDN_FDEVICEINIT, NULL);
3908 "%s setting fDeviceInit flag failed with error %d\n",
3913 /* poll for max. 1000 iterations for fDeviceInit flag to clear */
3914 for (i = 0; i < 1000 && !err && flag_res; i++)
3915 err = ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_READ_FLAG,
3916 QUERY_FLAG_IDN_FDEVICEINIT, &flag_res);
3920 "%s reading fDeviceInit flag failed with error %d\n",
3924 "%s fDeviceInit was not cleared by the device\n",
3932 * ufshcd_make_hba_operational - Make UFS controller operational
3933 * @hba: per adapter instance
3935 * To bring UFS host controller to operational state,
3936 * 1. Enable required interrupts
3937 * 2. Configure interrupt aggregation
3938 * 3. Program UTRL and UTMRL base address
3939 * 4. Configure run-stop-registers
3941 * Returns 0 on success, non-zero value on failure
3943 static int ufshcd_make_hba_operational(struct ufs_hba *hba)
3948 /* Enable required interrupts */
3949 ufshcd_enable_intr(hba, UFSHCD_ENABLE_INTRS);
3951 /* Configure interrupt aggregation */
3952 if (ufshcd_is_intr_aggr_allowed(hba))
3953 ufshcd_config_intr_aggr(hba, hba->nutrs - 1, INT_AGGR_DEF_TO);
3955 ufshcd_disable_intr_aggr(hba);
3957 /* Configure UTRL and UTMRL base address registers */
3958 ufshcd_writel(hba, lower_32_bits(hba->utrdl_dma_addr),
3959 REG_UTP_TRANSFER_REQ_LIST_BASE_L);
3960 ufshcd_writel(hba, upper_32_bits(hba->utrdl_dma_addr),
3961 REG_UTP_TRANSFER_REQ_LIST_BASE_H);
3962 ufshcd_writel(hba, lower_32_bits(hba->utmrdl_dma_addr),
3963 REG_UTP_TASK_REQ_LIST_BASE_L);
3964 ufshcd_writel(hba, upper_32_bits(hba->utmrdl_dma_addr),
3965 REG_UTP_TASK_REQ_LIST_BASE_H);
3968 * Make sure base address and interrupt setup are updated before
3969 * enabling the run/stop registers below.
3974 * UCRDY, UTMRLDY and UTRLRDY bits must be 1
3976 reg = ufshcd_readl(hba, REG_CONTROLLER_STATUS);
3977 if (!(ufshcd_get_lists_status(reg))) {
3978 ufshcd_enable_run_stop_reg(hba);
3981 "Host controller not ready to process requests");
3991 * ufshcd_hba_stop - Send controller to reset state
3992 * @hba: per adapter instance
3993 * @can_sleep: perform sleep or just spin
3995 static inline void ufshcd_hba_stop(struct ufs_hba *hba, bool can_sleep)
3999 ufshcd_writel(hba, CONTROLLER_DISABLE, REG_CONTROLLER_ENABLE);
4000 err = ufshcd_wait_for_register(hba, REG_CONTROLLER_ENABLE,
4001 CONTROLLER_ENABLE, CONTROLLER_DISABLE,
4004 dev_err(hba->dev, "%s: Controller disable failed\n", __func__);
4008 * ufshcd_hba_enable - initialize the controller
4009 * @hba: per adapter instance
4011 * The controller resets itself and controller firmware initialization
4012 * sequence kicks off. When controller is ready it will set
4013 * the Host Controller Enable bit to 1.
4015 * Returns 0 on success, non-zero value on failure
4017 static int ufshcd_hba_enable(struct ufs_hba *hba)
4022 * msleep of 1 and 5 used in this function might result in msleep(20),
4023 * but it was necessary to send the UFS FPGA to reset mode during
4024 * development and testing of this driver. msleep can be changed to
4025 * mdelay and retry count can be reduced based on the controller.
4027 if (!ufshcd_is_hba_active(hba))
4028 /* change controller state to "reset state" */
4029 ufshcd_hba_stop(hba, true);
4031 /* UniPro link is disabled at this point */
4032 ufshcd_set_link_off(hba);
4034 ufshcd_vops_hce_enable_notify(hba, PRE_CHANGE);
4036 /* start controller initialization sequence */
4037 ufshcd_hba_start(hba);
4040 * To initialize a UFS host controller HCE bit must be set to 1.
4041 * During initialization the HCE bit value changes from 1->0->1.
4042 * When the host controller completes initialization sequence
4043 * it sets the value of HCE bit to 1. The same HCE bit is read back
4044 * to check if the controller has completed initialization sequence.
4045 * So without this delay the value HCE = 1, set in the previous
4046 * instruction might be read back.
4047 * This delay can be changed based on the controller.
4051 /* wait for the host controller to complete initialization */
4053 while (ufshcd_is_hba_active(hba)) {
4058 "Controller enable failed\n");
4064 /* enable UIC related interrupts */
4065 ufshcd_enable_intr(hba, UFSHCD_UIC_MASK);
4067 ufshcd_vops_hce_enable_notify(hba, POST_CHANGE);
4072 static int ufshcd_disable_tx_lcc(struct ufs_hba *hba, bool peer)
4074 int tx_lanes, i, err = 0;
4077 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_CONNECTEDTXDATALANES),
4080 ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_CONNECTEDTXDATALANES),
4082 for (i = 0; i < tx_lanes; i++) {
4084 err = ufshcd_dme_set(hba,
4085 UIC_ARG_MIB_SEL(TX_LCC_ENABLE,
4086 UIC_ARG_MPHY_TX_GEN_SEL_INDEX(i)),
4089 err = ufshcd_dme_peer_set(hba,
4090 UIC_ARG_MIB_SEL(TX_LCC_ENABLE,
4091 UIC_ARG_MPHY_TX_GEN_SEL_INDEX(i)),
4094 dev_err(hba->dev, "%s: TX LCC Disable failed, peer = %d, lane = %d, err = %d",
4095 __func__, peer, i, err);
4103 static inline int ufshcd_disable_device_tx_lcc(struct ufs_hba *hba)
4105 return ufshcd_disable_tx_lcc(hba, true);
4109 * ufshcd_link_startup - Initialize unipro link startup
4110 * @hba: per adapter instance
4112 * Returns 0 for success, non-zero in case of failure
4114 static int ufshcd_link_startup(struct ufs_hba *hba)
4117 int retries = DME_LINKSTARTUP_RETRIES;
4118 bool link_startup_again = false;
4121 * If UFS device isn't active then we will have to issue link startup
4122 * 2 times to make sure the device state move to active.
4124 if (!ufshcd_is_ufs_dev_active(hba))
4125 link_startup_again = true;
4129 ufshcd_vops_link_startup_notify(hba, PRE_CHANGE);
4131 ret = ufshcd_dme_link_startup(hba);
4133 /* check if device is detected by inter-connect layer */
4134 if (!ret && !ufshcd_is_device_present(hba)) {
4135 dev_err(hba->dev, "%s: Device not present\n", __func__);
4141 * DME link lost indication is only received when link is up,
4142 * but we can't be sure if the link is up until link startup
4143 * succeeds. So reset the local Uni-Pro and try again.
4145 if (ret && ufshcd_hba_enable(hba))
4147 } while (ret && retries--);
4150 /* failed to get the link up... retire */
4153 if (link_startup_again) {
4154 link_startup_again = false;
4155 retries = DME_LINKSTARTUP_RETRIES;
4159 /* Mark that link is up in PWM-G1, 1-lane, SLOW-AUTO mode */
4160 ufshcd_init_pwr_info(hba);
4161 ufshcd_print_pwr_info(hba);
4163 if (hba->quirks & UFSHCD_QUIRK_BROKEN_LCC) {
4164 ret = ufshcd_disable_device_tx_lcc(hba);
4169 /* Include any host controller configuration via UIC commands */
4170 ret = ufshcd_vops_link_startup_notify(hba, POST_CHANGE);
4174 ret = ufshcd_make_hba_operational(hba);
4177 dev_err(hba->dev, "link startup failed %d\n", ret);
4178 ufshcd_print_host_state(hba);
4179 ufshcd_print_pwr_info(hba);
4180 ufshcd_print_host_regs(hba);
4186 * ufshcd_verify_dev_init() - Verify device initialization
4187 * @hba: per-adapter instance
4189 * Send NOP OUT UPIU and wait for NOP IN response to check whether the
4190 * device Transport Protocol (UTP) layer is ready after a reset.
4191 * If the UTP layer at the device side is not initialized, it may
4192 * not respond with NOP IN UPIU within timeout of %NOP_OUT_TIMEOUT
4193 * and we retry sending NOP OUT for %NOP_OUT_RETRIES iterations.
4195 static int ufshcd_verify_dev_init(struct ufs_hba *hba)
4200 ufshcd_hold(hba, false);
4201 mutex_lock(&hba->dev_cmd.lock);
4202 for (retries = NOP_OUT_RETRIES; retries > 0; retries--) {
4203 err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_NOP,
4206 if (!err || err == -ETIMEDOUT)
4209 dev_dbg(hba->dev, "%s: error %d retrying\n", __func__, err);
4211 mutex_unlock(&hba->dev_cmd.lock);
4212 ufshcd_release(hba);
4215 dev_err(hba->dev, "%s: NOP OUT failed %d\n", __func__, err);
4220 * ufshcd_set_queue_depth - set lun queue depth
4221 * @sdev: pointer to SCSI device
4223 * Read bLUQueueDepth value and activate scsi tagged command
4224 * queueing. For WLUN, queue depth is set to 1. For best-effort
4225 * cases (bLUQueueDepth = 0) the queue depth is set to a maximum
4226 * value that host can queue.
4228 static void ufshcd_set_queue_depth(struct scsi_device *sdev)
4232 struct ufs_hba *hba;
4234 hba = shost_priv(sdev->host);
4236 lun_qdepth = hba->nutrs;
4237 ret = ufshcd_read_unit_desc_param(hba,
4238 ufshcd_scsi_to_upiu_lun(sdev->lun),
4239 UNIT_DESC_PARAM_LU_Q_DEPTH,
4241 sizeof(lun_qdepth));
4243 /* Some WLUN doesn't support unit descriptor */
4244 if (ret == -EOPNOTSUPP)
4246 else if (!lun_qdepth)
4247 /* eventually, we can figure out the real queue depth */
4248 lun_qdepth = hba->nutrs;
4250 lun_qdepth = min_t(int, lun_qdepth, hba->nutrs);
4252 dev_dbg(hba->dev, "%s: activate tcq with queue depth %d\n",
4253 __func__, lun_qdepth);
4254 scsi_change_queue_depth(sdev, lun_qdepth);
4258 * ufshcd_get_lu_wp - returns the "b_lu_write_protect" from UNIT DESCRIPTOR
4259 * @hba: per-adapter instance
4260 * @lun: UFS device lun id
4261 * @b_lu_write_protect: pointer to buffer to hold the LU's write protect info
4263 * Returns 0 in case of success and b_lu_write_protect status would be returned
4264 * @b_lu_write_protect parameter.
4265 * Returns -ENOTSUPP if reading b_lu_write_protect is not supported.
4266 * Returns -EINVAL in case of invalid parameters passed to this function.
4268 static int ufshcd_get_lu_wp(struct ufs_hba *hba,
4270 u8 *b_lu_write_protect)
4274 if (!b_lu_write_protect)
4277 * According to UFS device spec, RPMB LU can't be write
4278 * protected so skip reading bLUWriteProtect parameter for
4279 * it. For other W-LUs, UNIT DESCRIPTOR is not available.
4281 else if (lun >= UFS_UPIU_MAX_GENERAL_LUN)
4284 ret = ufshcd_read_unit_desc_param(hba,
4286 UNIT_DESC_PARAM_LU_WR_PROTECT,
4288 sizeof(*b_lu_write_protect));
4293 * ufshcd_get_lu_power_on_wp_status - get LU's power on write protect
4295 * @hba: per-adapter instance
4296 * @sdev: pointer to SCSI device
4299 static inline void ufshcd_get_lu_power_on_wp_status(struct ufs_hba *hba,
4300 struct scsi_device *sdev)
4302 if (hba->dev_info.f_power_on_wp_en &&
4303 !hba->dev_info.is_lu_power_on_wp) {
4304 u8 b_lu_write_protect;
4306 if (!ufshcd_get_lu_wp(hba, ufshcd_scsi_to_upiu_lun(sdev->lun),
4307 &b_lu_write_protect) &&
4308 (b_lu_write_protect == UFS_LU_POWER_ON_WP))
4309 hba->dev_info.is_lu_power_on_wp = true;
4314 * ufshcd_slave_alloc - handle initial SCSI device configurations
4315 * @sdev: pointer to SCSI device
4319 static int ufshcd_slave_alloc(struct scsi_device *sdev)
4321 struct ufs_hba *hba;
4323 hba = shost_priv(sdev->host);
4325 /* Mode sense(6) is not supported by UFS, so use Mode sense(10) */
4326 sdev->use_10_for_ms = 1;
4328 /* allow SCSI layer to restart the device in case of errors */
4329 sdev->allow_restart = 1;
4331 /* REPORT SUPPORTED OPERATION CODES is not supported */
4332 sdev->no_report_opcodes = 1;
4334 /* WRITE_SAME command is not supported */
4335 sdev->no_write_same = 1;
4337 ufshcd_set_queue_depth(sdev);
4339 ufshcd_get_lu_power_on_wp_status(hba, sdev);
4345 * ufshcd_change_queue_depth - change queue depth
4346 * @sdev: pointer to SCSI device
4347 * @depth: required depth to set
4349 * Change queue depth and make sure the max. limits are not crossed.
4351 static int ufshcd_change_queue_depth(struct scsi_device *sdev, int depth)
4353 struct ufs_hba *hba = shost_priv(sdev->host);
4355 if (depth > hba->nutrs)
4357 return scsi_change_queue_depth(sdev, depth);
4361 * ufshcd_slave_configure - adjust SCSI device configurations
4362 * @sdev: pointer to SCSI device
4364 static int ufshcd_slave_configure(struct scsi_device *sdev)
4366 struct request_queue *q = sdev->request_queue;
4368 blk_queue_update_dma_pad(q, PRDT_DATA_BYTE_COUNT_PAD - 1);
4369 blk_queue_max_segment_size(q, PRDT_DATA_BYTE_COUNT_MAX);
4375 * ufshcd_slave_destroy - remove SCSI device configurations
4376 * @sdev: pointer to SCSI device
4378 static void ufshcd_slave_destroy(struct scsi_device *sdev)
4380 struct ufs_hba *hba;
4382 hba = shost_priv(sdev->host);
4383 /* Drop the reference as it won't be needed anymore */
4384 if (ufshcd_scsi_to_upiu_lun(sdev->lun) == UFS_UPIU_UFS_DEVICE_WLUN) {
4385 unsigned long flags;
4387 spin_lock_irqsave(hba->host->host_lock, flags);
4388 hba->sdev_ufs_device = NULL;
4389 spin_unlock_irqrestore(hba->host->host_lock, flags);
4394 * ufshcd_task_req_compl - handle task management request completion
4395 * @hba: per adapter instance
4396 * @index: index of the completed request
4397 * @resp: task management service response
4399 * Returns non-zero value on error, zero on success
4401 static int ufshcd_task_req_compl(struct ufs_hba *hba, u32 index, u8 *resp)
4403 struct utp_task_req_desc *task_req_descp;
4404 struct utp_upiu_task_rsp *task_rsp_upiup;
4405 unsigned long flags;
4409 spin_lock_irqsave(hba->host->host_lock, flags);
4411 /* Clear completed tasks from outstanding_tasks */
4412 __clear_bit(index, &hba->outstanding_tasks);
4414 task_req_descp = hba->utmrdl_base_addr;
4415 ocs_value = ufshcd_get_tmr_ocs(&task_req_descp[index]);
4417 if (ocs_value == OCS_SUCCESS) {
4418 task_rsp_upiup = (struct utp_upiu_task_rsp *)
4419 task_req_descp[index].task_rsp_upiu;
4420 task_result = be32_to_cpu(task_rsp_upiup->output_param1);
4421 task_result = task_result & MASK_TM_SERVICE_RESP;
4423 *resp = (u8)task_result;
4425 dev_err(hba->dev, "%s: failed, ocs = 0x%x\n",
4426 __func__, ocs_value);
4428 spin_unlock_irqrestore(hba->host->host_lock, flags);
4434 * ufshcd_scsi_cmd_status - Update SCSI command result based on SCSI status
4435 * @lrbp: pointer to local reference block of completed command
4436 * @scsi_status: SCSI command status
4438 * Returns value base on SCSI command status
4441 ufshcd_scsi_cmd_status(struct ufshcd_lrb *lrbp, int scsi_status)
4445 switch (scsi_status) {
4446 case SAM_STAT_CHECK_CONDITION:
4447 ufshcd_copy_sense_data(lrbp);
4449 result |= DID_OK << 16 |
4450 COMMAND_COMPLETE << 8 |
4453 case SAM_STAT_TASK_SET_FULL:
4455 case SAM_STAT_TASK_ABORTED:
4456 ufshcd_copy_sense_data(lrbp);
4457 result |= scsi_status;
4460 result |= DID_ERROR << 16;
4462 } /* end of switch */
4468 * ufshcd_transfer_rsp_status - Get overall status of the response
4469 * @hba: per adapter instance
4470 * @lrbp: pointer to local reference block of completed command
4472 * Returns result of the command to notify SCSI midlayer
4475 ufshcd_transfer_rsp_status(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
4481 /* overall command status of utrd */
4482 ocs = ufshcd_get_tr_ocs(lrbp);
4486 result = ufshcd_get_req_rsp(lrbp->ucd_rsp_ptr);
4487 hba->ufs_stats.last_hibern8_exit_tstamp = ktime_set(0, 0);
4489 case UPIU_TRANSACTION_RESPONSE:
4491 * get the response UPIU result to extract
4492 * the SCSI command status
4494 result = ufshcd_get_rsp_upiu_result(lrbp->ucd_rsp_ptr);
4497 * get the result based on SCSI status response
4498 * to notify the SCSI midlayer of the command status
4500 scsi_status = result & MASK_SCSI_STATUS;
4501 result = ufshcd_scsi_cmd_status(lrbp, scsi_status);
4504 * Currently we are only supporting BKOPs exception
4505 * events hence we can ignore BKOPs exception event
4506 * during power management callbacks. BKOPs exception
4507 * event is not expected to be raised in runtime suspend
4508 * callback as it allows the urgent bkops.
4509 * During system suspend, we are anyway forcefully
4510 * disabling the bkops and if urgent bkops is needed
4511 * it will be enabled on system resume. Long term
4512 * solution could be to abort the system suspend if
4513 * UFS device needs urgent BKOPs.
4515 if (!hba->pm_op_in_progress &&
4516 ufshcd_is_exception_event(lrbp->ucd_rsp_ptr))
4517 schedule_work(&hba->eeh_work);
4519 case UPIU_TRANSACTION_REJECT_UPIU:
4520 /* TODO: handle Reject UPIU Response */
4521 result = DID_ERROR << 16;
4523 "Reject UPIU not fully implemented\n");
4526 result = DID_ERROR << 16;
4528 "Unexpected request response code = %x\n",
4534 result |= DID_ABORT << 16;
4536 case OCS_INVALID_COMMAND_STATUS:
4537 result |= DID_REQUEUE << 16;
4539 case OCS_INVALID_CMD_TABLE_ATTR:
4540 case OCS_INVALID_PRDT_ATTR:
4541 case OCS_MISMATCH_DATA_BUF_SIZE:
4542 case OCS_MISMATCH_RESP_UPIU_SIZE:
4543 case OCS_PEER_COMM_FAILURE:
4544 case OCS_FATAL_ERROR:
4546 result |= DID_ERROR << 16;
4548 "OCS error from controller = %x for tag %d\n",
4549 ocs, lrbp->task_tag);
4550 ufshcd_print_host_regs(hba);
4551 ufshcd_print_host_state(hba);
4553 } /* end of switch */
4555 if (host_byte(result) != DID_OK)
4556 ufshcd_print_trs(hba, 1 << lrbp->task_tag, true);
4561 * ufshcd_uic_cmd_compl - handle completion of uic command
4562 * @hba: per adapter instance
4563 * @intr_status: interrupt status generated by the controller
4565 static void ufshcd_uic_cmd_compl(struct ufs_hba *hba, u32 intr_status)
4567 if ((intr_status & UIC_COMMAND_COMPL) && hba->active_uic_cmd) {
4568 hba->active_uic_cmd->argument2 |=
4569 ufshcd_get_uic_cmd_result(hba);
4570 hba->active_uic_cmd->argument3 =
4571 ufshcd_get_dme_attr_val(hba);
4572 complete(&hba->active_uic_cmd->done);
4575 if ((intr_status & UFSHCD_UIC_PWR_MASK) && hba->uic_async_done)
4576 complete(hba->uic_async_done);
4580 * __ufshcd_transfer_req_compl - handle SCSI and query command completion
4581 * @hba: per adapter instance
4582 * @completed_reqs: requests to complete
4584 static void __ufshcd_transfer_req_compl(struct ufs_hba *hba,
4585 unsigned long completed_reqs)
4587 struct ufshcd_lrb *lrbp;
4588 struct scsi_cmnd *cmd;
4592 for_each_set_bit(index, &completed_reqs, hba->nutrs) {
4593 lrbp = &hba->lrb[index];
4596 ufshcd_add_command_trace(hba, index, "complete");
4597 result = ufshcd_transfer_rsp_status(hba, lrbp);
4598 scsi_dma_unmap(cmd);
4599 cmd->result = result;
4600 /* Mark completed command as NULL in LRB */
4602 clear_bit_unlock(index, &hba->lrb_in_use);
4603 /* Do not touch lrbp after scsi done */
4604 cmd->scsi_done(cmd);
4605 __ufshcd_release(hba);
4606 } else if (lrbp->command_type == UTP_CMD_TYPE_DEV_MANAGE ||
4607 lrbp->command_type == UTP_CMD_TYPE_UFS_STORAGE) {
4608 if (hba->dev_cmd.complete) {
4609 ufshcd_add_command_trace(hba, index,
4611 complete(hba->dev_cmd.complete);
4614 if (ufshcd_is_clkscaling_supported(hba))
4615 hba->clk_scaling.active_reqs--;
4617 lrbp->compl_time_stamp = ktime_get();
4620 /* clear corresponding bits of completed commands */
4621 hba->outstanding_reqs ^= completed_reqs;
4623 ufshcd_clk_scaling_update_busy(hba);
4625 /* we might have free'd some tags above */
4626 wake_up(&hba->dev_cmd.tag_wq);
4630 * ufshcd_transfer_req_compl - handle SCSI and query command completion
4631 * @hba: per adapter instance
4633 static void ufshcd_transfer_req_compl(struct ufs_hba *hba)
4635 unsigned long completed_reqs;
4638 /* Resetting interrupt aggregation counters first and reading the
4639 * DOOR_BELL afterward allows us to handle all the completed requests.
4640 * In order to prevent other interrupts starvation the DB is read once
4641 * after reset. The down side of this solution is the possibility of
4642 * false interrupt if device completes another request after resetting
4643 * aggregation and before reading the DB.
4645 if (ufshcd_is_intr_aggr_allowed(hba))
4646 ufshcd_reset_intr_aggr(hba);
4648 tr_doorbell = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
4649 completed_reqs = tr_doorbell ^ hba->outstanding_reqs;
4651 __ufshcd_transfer_req_compl(hba, completed_reqs);
4655 * ufshcd_disable_ee - disable exception event
4656 * @hba: per-adapter instance
4657 * @mask: exception event to disable
4659 * Disables exception event in the device so that the EVENT_ALERT
4662 * Returns zero on success, non-zero error value on failure.
4664 static int ufshcd_disable_ee(struct ufs_hba *hba, u16 mask)
4669 if (!(hba->ee_ctrl_mask & mask))
4672 val = hba->ee_ctrl_mask & ~mask;
4673 val &= MASK_EE_STATUS;
4674 err = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_WRITE_ATTR,
4675 QUERY_ATTR_IDN_EE_CONTROL, 0, 0, &val);
4677 hba->ee_ctrl_mask &= ~mask;
4683 * ufshcd_enable_ee - enable exception event
4684 * @hba: per-adapter instance
4685 * @mask: exception event to enable
4687 * Enable corresponding exception event in the device to allow
4688 * device to alert host in critical scenarios.
4690 * Returns zero on success, non-zero error value on failure.
4692 static int ufshcd_enable_ee(struct ufs_hba *hba, u16 mask)
4697 if (hba->ee_ctrl_mask & mask)
4700 val = hba->ee_ctrl_mask | mask;
4701 val &= MASK_EE_STATUS;
4702 err = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_WRITE_ATTR,
4703 QUERY_ATTR_IDN_EE_CONTROL, 0, 0, &val);
4705 hba->ee_ctrl_mask |= mask;
4711 * ufshcd_enable_auto_bkops - Allow device managed BKOPS
4712 * @hba: per-adapter instance
4714 * Allow device to manage background operations on its own. Enabling
4715 * this might lead to inconsistent latencies during normal data transfers
4716 * as the device is allowed to manage its own way of handling background
4719 * Returns zero on success, non-zero on failure.
4721 static int ufshcd_enable_auto_bkops(struct ufs_hba *hba)
4725 if (hba->auto_bkops_enabled)
4728 err = ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_SET_FLAG,
4729 QUERY_FLAG_IDN_BKOPS_EN, NULL);
4731 dev_err(hba->dev, "%s: failed to enable bkops %d\n",
4736 hba->auto_bkops_enabled = true;
4737 trace_ufshcd_auto_bkops_state(dev_name(hba->dev), "Enabled");
4739 /* No need of URGENT_BKOPS exception from the device */
4740 err = ufshcd_disable_ee(hba, MASK_EE_URGENT_BKOPS);
4742 dev_err(hba->dev, "%s: failed to disable exception event %d\n",
4749 * ufshcd_disable_auto_bkops - block device in doing background operations
4750 * @hba: per-adapter instance
4752 * Disabling background operations improves command response latency but
4753 * has drawback of device moving into critical state where the device is
4754 * not-operable. Make sure to call ufshcd_enable_auto_bkops() whenever the
4755 * host is idle so that BKOPS are managed effectively without any negative
4758 * Returns zero on success, non-zero on failure.
4760 static int ufshcd_disable_auto_bkops(struct ufs_hba *hba)
4764 if (!hba->auto_bkops_enabled)
4768 * If host assisted BKOPs is to be enabled, make sure
4769 * urgent bkops exception is allowed.
4771 err = ufshcd_enable_ee(hba, MASK_EE_URGENT_BKOPS);
4773 dev_err(hba->dev, "%s: failed to enable exception event %d\n",
4778 err = ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_CLEAR_FLAG,
4779 QUERY_FLAG_IDN_BKOPS_EN, NULL);
4781 dev_err(hba->dev, "%s: failed to disable bkops %d\n",
4783 ufshcd_disable_ee(hba, MASK_EE_URGENT_BKOPS);
4787 hba->auto_bkops_enabled = false;
4788 trace_ufshcd_auto_bkops_state(dev_name(hba->dev), "Disabled");
4794 * ufshcd_force_reset_auto_bkops - force reset auto bkops state
4795 * @hba: per adapter instance
4797 * After a device reset the device may toggle the BKOPS_EN flag
4798 * to default value. The s/w tracking variables should be updated
4799 * as well. This function would change the auto-bkops state based on
4800 * UFSHCD_CAP_KEEP_AUTO_BKOPS_ENABLED_EXCEPT_SUSPEND.
4802 static void ufshcd_force_reset_auto_bkops(struct ufs_hba *hba)
4804 if (ufshcd_keep_autobkops_enabled_except_suspend(hba)) {
4805 hba->auto_bkops_enabled = false;
4806 hba->ee_ctrl_mask |= MASK_EE_URGENT_BKOPS;
4807 ufshcd_enable_auto_bkops(hba);
4809 hba->auto_bkops_enabled = true;
4810 hba->ee_ctrl_mask &= ~MASK_EE_URGENT_BKOPS;
4811 ufshcd_disable_auto_bkops(hba);
4815 static inline int ufshcd_get_bkops_status(struct ufs_hba *hba, u32 *status)
4817 return ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
4818 QUERY_ATTR_IDN_BKOPS_STATUS, 0, 0, status);
4822 * ufshcd_bkops_ctrl - control the auto bkops based on current bkops status
4823 * @hba: per-adapter instance
4824 * @status: bkops_status value
4826 * Read the bkops_status from the UFS device and Enable fBackgroundOpsEn
4827 * flag in the device to permit background operations if the device
4828 * bkops_status is greater than or equal to "status" argument passed to
4829 * this function, disable otherwise.
4831 * Returns 0 for success, non-zero in case of failure.
4833 * NOTE: Caller of this function can check the "hba->auto_bkops_enabled" flag
4834 * to know whether auto bkops is enabled or disabled after this function
4835 * returns control to it.
4837 static int ufshcd_bkops_ctrl(struct ufs_hba *hba,
4838 enum bkops_status status)
4841 u32 curr_status = 0;
4843 err = ufshcd_get_bkops_status(hba, &curr_status);
4845 dev_err(hba->dev, "%s: failed to get BKOPS status %d\n",
4848 } else if (curr_status > BKOPS_STATUS_MAX) {
4849 dev_err(hba->dev, "%s: invalid BKOPS status %d\n",
4850 __func__, curr_status);
4855 if (curr_status >= status)
4856 err = ufshcd_enable_auto_bkops(hba);
4858 err = ufshcd_disable_auto_bkops(hba);
4864 * ufshcd_urgent_bkops - handle urgent bkops exception event
4865 * @hba: per-adapter instance
4867 * Enable fBackgroundOpsEn flag in the device to permit background
4870 * If BKOPs is enabled, this function returns 0, 1 if the bkops in not enabled
4871 * and negative error value for any other failure.
4873 static int ufshcd_urgent_bkops(struct ufs_hba *hba)
4875 return ufshcd_bkops_ctrl(hba, hba->urgent_bkops_lvl);
4878 static inline int ufshcd_get_ee_status(struct ufs_hba *hba, u32 *status)
4880 return ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
4881 QUERY_ATTR_IDN_EE_STATUS, 0, 0, status);
4884 static void ufshcd_bkops_exception_event_handler(struct ufs_hba *hba)
4887 u32 curr_status = 0;
4889 if (hba->is_urgent_bkops_lvl_checked)
4890 goto enable_auto_bkops;
4892 err = ufshcd_get_bkops_status(hba, &curr_status);
4894 dev_err(hba->dev, "%s: failed to get BKOPS status %d\n",
4900 * We are seeing that some devices are raising the urgent bkops
4901 * exception events even when BKOPS status doesn't indicate performace
4902 * impacted or critical. Handle these device by determining their urgent
4903 * bkops status at runtime.
4905 if (curr_status < BKOPS_STATUS_PERF_IMPACT) {
4906 dev_err(hba->dev, "%s: device raised urgent BKOPS exception for bkops status %d\n",
4907 __func__, curr_status);
4908 /* update the current status as the urgent bkops level */
4909 hba->urgent_bkops_lvl = curr_status;
4910 hba->is_urgent_bkops_lvl_checked = true;
4914 err = ufshcd_enable_auto_bkops(hba);
4917 dev_err(hba->dev, "%s: failed to handle urgent bkops %d\n",
4922 * ufshcd_exception_event_handler - handle exceptions raised by device
4923 * @work: pointer to work data
4925 * Read bExceptionEventStatus attribute from the device and handle the
4926 * exception event accordingly.
4928 static void ufshcd_exception_event_handler(struct work_struct *work)
4930 struct ufs_hba *hba;
4933 hba = container_of(work, struct ufs_hba, eeh_work);
4935 pm_runtime_get_sync(hba->dev);
4936 err = ufshcd_get_ee_status(hba, &status);
4938 dev_err(hba->dev, "%s: failed to get exception status %d\n",
4943 status &= hba->ee_ctrl_mask;
4945 if (status & MASK_EE_URGENT_BKOPS)
4946 ufshcd_bkops_exception_event_handler(hba);
4949 pm_runtime_put_sync(hba->dev);
4953 /* Complete requests that have door-bell cleared */
4954 static void ufshcd_complete_requests(struct ufs_hba *hba)
4956 ufshcd_transfer_req_compl(hba);
4957 ufshcd_tmc_handler(hba);
4961 * ufshcd_quirk_dl_nac_errors - This function checks if error handling is
4962 * to recover from the DL NAC errors or not.
4963 * @hba: per-adapter instance
4965 * Returns true if error handling is required, false otherwise
4967 static bool ufshcd_quirk_dl_nac_errors(struct ufs_hba *hba)
4969 unsigned long flags;
4970 bool err_handling = true;
4972 spin_lock_irqsave(hba->host->host_lock, flags);
4974 * UFS_DEVICE_QUIRK_RECOVERY_FROM_DL_NAC_ERRORS only workaround the
4975 * device fatal error and/or DL NAC & REPLAY timeout errors.
4977 if (hba->saved_err & (CONTROLLER_FATAL_ERROR | SYSTEM_BUS_FATAL_ERROR))
4980 if ((hba->saved_err & DEVICE_FATAL_ERROR) ||
4981 ((hba->saved_err & UIC_ERROR) &&
4982 (hba->saved_uic_err & UFSHCD_UIC_DL_TCx_REPLAY_ERROR)))
4985 if ((hba->saved_err & UIC_ERROR) &&
4986 (hba->saved_uic_err & UFSHCD_UIC_DL_NAC_RECEIVED_ERROR)) {
4989 * wait for 50ms to see if we can get any other errors or not.
4991 spin_unlock_irqrestore(hba->host->host_lock, flags);
4993 spin_lock_irqsave(hba->host->host_lock, flags);
4996 * now check if we have got any other severe errors other than
4999 if ((hba->saved_err & INT_FATAL_ERRORS) ||
5000 ((hba->saved_err & UIC_ERROR) &&
5001 (hba->saved_uic_err & ~UFSHCD_UIC_DL_NAC_RECEIVED_ERROR)))
5005 * As DL NAC is the only error received so far, send out NOP
5006 * command to confirm if link is still active or not.
5007 * - If we don't get any response then do error recovery.
5008 * - If we get response then clear the DL NAC error bit.
5011 spin_unlock_irqrestore(hba->host->host_lock, flags);
5012 err = ufshcd_verify_dev_init(hba);
5013 spin_lock_irqsave(hba->host->host_lock, flags);
5018 /* Link seems to be alive hence ignore the DL NAC errors */
5019 if (hba->saved_uic_err == UFSHCD_UIC_DL_NAC_RECEIVED_ERROR)
5020 hba->saved_err &= ~UIC_ERROR;
5021 /* clear NAC error */
5022 hba->saved_uic_err &= ~UFSHCD_UIC_DL_NAC_RECEIVED_ERROR;
5023 if (!hba->saved_uic_err) {
5024 err_handling = false;
5029 spin_unlock_irqrestore(hba->host->host_lock, flags);
5030 return err_handling;
5034 * ufshcd_err_handler - handle UFS errors that require s/w attention
5035 * @work: pointer to work structure
5037 static void ufshcd_err_handler(struct work_struct *work)
5039 struct ufs_hba *hba;
5040 unsigned long flags;
5045 bool needs_reset = false;
5047 hba = container_of(work, struct ufs_hba, eh_work);
5049 pm_runtime_get_sync(hba->dev);
5050 ufshcd_hold(hba, false);
5052 spin_lock_irqsave(hba->host->host_lock, flags);
5053 if (hba->ufshcd_state == UFSHCD_STATE_RESET)
5056 hba->ufshcd_state = UFSHCD_STATE_RESET;
5057 ufshcd_set_eh_in_progress(hba);
5059 /* Complete requests that have door-bell cleared by h/w */
5060 ufshcd_complete_requests(hba);
5062 if (hba->dev_quirks & UFS_DEVICE_QUIRK_RECOVERY_FROM_DL_NAC_ERRORS) {
5065 spin_unlock_irqrestore(hba->host->host_lock, flags);
5066 /* release the lock as ufshcd_quirk_dl_nac_errors() may sleep */
5067 ret = ufshcd_quirk_dl_nac_errors(hba);
5068 spin_lock_irqsave(hba->host->host_lock, flags);
5070 goto skip_err_handling;
5072 if ((hba->saved_err & INT_FATAL_ERRORS) ||
5073 ((hba->saved_err & UIC_ERROR) &&
5074 (hba->saved_uic_err & (UFSHCD_UIC_DL_PA_INIT_ERROR |
5075 UFSHCD_UIC_DL_NAC_RECEIVED_ERROR |
5076 UFSHCD_UIC_DL_TCx_REPLAY_ERROR))))
5080 * if host reset is required then skip clearing the pending
5081 * transfers forcefully because they will automatically get
5082 * cleared after link startup.
5085 goto skip_pending_xfer_clear;
5087 /* release lock as clear command might sleep */
5088 spin_unlock_irqrestore(hba->host->host_lock, flags);
5089 /* Clear pending transfer requests */
5090 for_each_set_bit(tag, &hba->outstanding_reqs, hba->nutrs) {
5091 if (ufshcd_clear_cmd(hba, tag)) {
5093 goto lock_skip_pending_xfer_clear;
5097 /* Clear pending task management requests */
5098 for_each_set_bit(tag, &hba->outstanding_tasks, hba->nutmrs) {
5099 if (ufshcd_clear_tm_cmd(hba, tag)) {
5101 goto lock_skip_pending_xfer_clear;
5105 lock_skip_pending_xfer_clear:
5106 spin_lock_irqsave(hba->host->host_lock, flags);
5108 /* Complete the requests that are cleared by s/w */
5109 ufshcd_complete_requests(hba);
5111 if (err_xfer || err_tm)
5114 skip_pending_xfer_clear:
5115 /* Fatal errors need reset */
5117 unsigned long max_doorbells = (1UL << hba->nutrs) - 1;
5120 * ufshcd_reset_and_restore() does the link reinitialization
5121 * which will need atleast one empty doorbell slot to send the
5122 * device management commands (NOP and query commands).
5123 * If there is no slot empty at this moment then free up last
5126 if (hba->outstanding_reqs == max_doorbells)
5127 __ufshcd_transfer_req_compl(hba,
5128 (1UL << (hba->nutrs - 1)));
5130 spin_unlock_irqrestore(hba->host->host_lock, flags);
5131 err = ufshcd_reset_and_restore(hba);
5132 spin_lock_irqsave(hba->host->host_lock, flags);
5134 dev_err(hba->dev, "%s: reset and restore failed\n",
5136 hba->ufshcd_state = UFSHCD_STATE_ERROR;
5139 * Inform scsi mid-layer that we did reset and allow to handle
5140 * Unit Attention properly.
5142 scsi_report_bus_reset(hba->host, 0);
5144 hba->saved_uic_err = 0;
5149 hba->ufshcd_state = UFSHCD_STATE_OPERATIONAL;
5150 if (hba->saved_err || hba->saved_uic_err)
5151 dev_err_ratelimited(hba->dev, "%s: exit: saved_err 0x%x saved_uic_err 0x%x",
5152 __func__, hba->saved_err, hba->saved_uic_err);
5155 ufshcd_clear_eh_in_progress(hba);
5158 spin_unlock_irqrestore(hba->host->host_lock, flags);
5159 scsi_unblock_requests(hba->host);
5160 ufshcd_release(hba);
5161 pm_runtime_put_sync(hba->dev);
5164 static void ufshcd_update_uic_reg_hist(struct ufs_uic_err_reg_hist *reg_hist,
5167 reg_hist->reg[reg_hist->pos] = reg;
5168 reg_hist->tstamp[reg_hist->pos] = ktime_get();
5169 reg_hist->pos = (reg_hist->pos + 1) % UIC_ERR_REG_HIST_LENGTH;
5173 * ufshcd_update_uic_error - check and set fatal UIC error flags.
5174 * @hba: per-adapter instance
5176 static void ufshcd_update_uic_error(struct ufs_hba *hba)
5180 /* PHY layer lane error */
5181 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_PHY_ADAPTER_LAYER);
5182 /* Ignore LINERESET indication, as this is not an error */
5183 if ((reg & UIC_PHY_ADAPTER_LAYER_ERROR) &&
5184 (reg & UIC_PHY_ADAPTER_LAYER_LANE_ERR_MASK)) {
5186 * To know whether this error is fatal or not, DB timeout
5187 * must be checked but this error is handled separately.
5189 dev_dbg(hba->dev, "%s: UIC Lane error reported\n", __func__);
5190 ufshcd_update_uic_reg_hist(&hba->ufs_stats.pa_err, reg);
5193 /* PA_INIT_ERROR is fatal and needs UIC reset */
5194 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_DATA_LINK_LAYER);
5196 ufshcd_update_uic_reg_hist(&hba->ufs_stats.dl_err, reg);
5198 if (reg & UIC_DATA_LINK_LAYER_ERROR_PA_INIT)
5199 hba->uic_error |= UFSHCD_UIC_DL_PA_INIT_ERROR;
5200 else if (hba->dev_quirks &
5201 UFS_DEVICE_QUIRK_RECOVERY_FROM_DL_NAC_ERRORS) {
5202 if (reg & UIC_DATA_LINK_LAYER_ERROR_NAC_RECEIVED)
5204 UFSHCD_UIC_DL_NAC_RECEIVED_ERROR;
5205 else if (reg & UIC_DATA_LINK_LAYER_ERROR_TCx_REPLAY_TIMEOUT)
5206 hba->uic_error |= UFSHCD_UIC_DL_TCx_REPLAY_ERROR;
5209 /* UIC NL/TL/DME errors needs software retry */
5210 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_NETWORK_LAYER);
5212 ufshcd_update_uic_reg_hist(&hba->ufs_stats.nl_err, reg);
5213 hba->uic_error |= UFSHCD_UIC_NL_ERROR;
5216 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_TRANSPORT_LAYER);
5218 ufshcd_update_uic_reg_hist(&hba->ufs_stats.tl_err, reg);
5219 hba->uic_error |= UFSHCD_UIC_TL_ERROR;
5222 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_DME);
5224 ufshcd_update_uic_reg_hist(&hba->ufs_stats.dme_err, reg);
5225 hba->uic_error |= UFSHCD_UIC_DME_ERROR;
5228 dev_dbg(hba->dev, "%s: UIC error flags = 0x%08x\n",
5229 __func__, hba->uic_error);
5233 * ufshcd_check_errors - Check for errors that need s/w attention
5234 * @hba: per-adapter instance
5236 static void ufshcd_check_errors(struct ufs_hba *hba)
5238 bool queue_eh_work = false;
5240 if (hba->errors & INT_FATAL_ERRORS)
5241 queue_eh_work = true;
5243 if (hba->errors & UIC_ERROR) {
5245 ufshcd_update_uic_error(hba);
5247 queue_eh_work = true;
5250 if (queue_eh_work) {
5252 * update the transfer error masks to sticky bits, let's do this
5253 * irrespective of current ufshcd_state.
5255 hba->saved_err |= hba->errors;
5256 hba->saved_uic_err |= hba->uic_error;
5258 /* handle fatal errors only when link is functional */
5259 if (hba->ufshcd_state == UFSHCD_STATE_OPERATIONAL) {
5260 /* block commands from scsi mid-layer */
5261 scsi_block_requests(hba->host);
5263 hba->ufshcd_state = UFSHCD_STATE_EH_SCHEDULED;
5265 /* dump controller state before resetting */
5266 if (hba->saved_err & (INT_FATAL_ERRORS | UIC_ERROR)) {
5267 bool pr_prdt = !!(hba->saved_err &
5268 SYSTEM_BUS_FATAL_ERROR);
5270 dev_err(hba->dev, "%s: saved_err 0x%x saved_uic_err 0x%x\n",
5271 __func__, hba->saved_err,
5272 hba->saved_uic_err);
5274 ufshcd_print_host_regs(hba);
5275 ufshcd_print_pwr_info(hba);
5276 ufshcd_print_tmrs(hba, hba->outstanding_tasks);
5277 ufshcd_print_trs(hba, hba->outstanding_reqs,
5280 schedule_work(&hba->eh_work);
5284 * if (!queue_eh_work) -
5285 * Other errors are either non-fatal where host recovers
5286 * itself without s/w intervention or errors that will be
5287 * handled by the SCSI core layer.
5292 * ufshcd_tmc_handler - handle task management function completion
5293 * @hba: per adapter instance
5295 static void ufshcd_tmc_handler(struct ufs_hba *hba)
5299 tm_doorbell = ufshcd_readl(hba, REG_UTP_TASK_REQ_DOOR_BELL);
5300 hba->tm_condition = tm_doorbell ^ hba->outstanding_tasks;
5301 wake_up(&hba->tm_wq);
5305 * ufshcd_sl_intr - Interrupt service routine
5306 * @hba: per adapter instance
5307 * @intr_status: contains interrupts generated by the controller
5309 static void ufshcd_sl_intr(struct ufs_hba *hba, u32 intr_status)
5311 hba->errors = UFSHCD_ERROR_MASK & intr_status;
5313 ufshcd_check_errors(hba);
5315 if (intr_status & UFSHCD_UIC_MASK)
5316 ufshcd_uic_cmd_compl(hba, intr_status);
5318 if (intr_status & UTP_TASK_REQ_COMPL)
5319 ufshcd_tmc_handler(hba);
5321 if (intr_status & UTP_TRANSFER_REQ_COMPL)
5322 ufshcd_transfer_req_compl(hba);
5326 * ufshcd_intr - Main interrupt service routine
5328 * @__hba: pointer to adapter instance
5330 * Returns IRQ_HANDLED - If interrupt is valid
5331 * IRQ_NONE - If invalid interrupt
5333 static irqreturn_t ufshcd_intr(int irq, void *__hba)
5335 u32 intr_status, enabled_intr_status;
5336 irqreturn_t retval = IRQ_NONE;
5337 struct ufs_hba *hba = __hba;
5339 spin_lock(hba->host->host_lock);
5340 intr_status = ufshcd_readl(hba, REG_INTERRUPT_STATUS);
5341 enabled_intr_status =
5342 intr_status & ufshcd_readl(hba, REG_INTERRUPT_ENABLE);
5345 ufshcd_writel(hba, intr_status, REG_INTERRUPT_STATUS);
5347 if (enabled_intr_status) {
5348 ufshcd_sl_intr(hba, enabled_intr_status);
5349 retval = IRQ_HANDLED;
5351 spin_unlock(hba->host->host_lock);
5355 static int ufshcd_clear_tm_cmd(struct ufs_hba *hba, int tag)
5358 u32 mask = 1 << tag;
5359 unsigned long flags;
5361 if (!test_bit(tag, &hba->outstanding_tasks))
5364 spin_lock_irqsave(hba->host->host_lock, flags);
5365 ufshcd_writel(hba, ~(1 << tag), REG_UTP_TASK_REQ_LIST_CLEAR);
5366 spin_unlock_irqrestore(hba->host->host_lock, flags);
5368 /* poll for max. 1 sec to clear door bell register by h/w */
5369 err = ufshcd_wait_for_register(hba,
5370 REG_UTP_TASK_REQ_DOOR_BELL,
5371 mask, 0, 1000, 1000, true);
5377 * ufshcd_issue_tm_cmd - issues task management commands to controller
5378 * @hba: per adapter instance
5379 * @lun_id: LUN ID to which TM command is sent
5380 * @task_id: task ID to which the TM command is applicable
5381 * @tm_function: task management function opcode
5382 * @tm_response: task management service response return value
5384 * Returns non-zero value on error, zero on success.
5386 static int ufshcd_issue_tm_cmd(struct ufs_hba *hba, int lun_id, int task_id,
5387 u8 tm_function, u8 *tm_response)
5389 struct utp_task_req_desc *task_req_descp;
5390 struct utp_upiu_task_req *task_req_upiup;
5391 struct Scsi_Host *host;
5392 unsigned long flags;
5400 * Get free slot, sleep if slots are unavailable.
5401 * Even though we use wait_event() which sleeps indefinitely,
5402 * the maximum wait time is bounded by %TM_CMD_TIMEOUT.
5404 wait_event(hba->tm_tag_wq, ufshcd_get_tm_free_slot(hba, &free_slot));
5405 ufshcd_hold(hba, false);
5407 spin_lock_irqsave(host->host_lock, flags);
5408 task_req_descp = hba->utmrdl_base_addr;
5409 task_req_descp += free_slot;
5411 /* Configure task request descriptor */
5412 task_req_descp->header.dword_0 = cpu_to_le32(UTP_REQ_DESC_INT_CMD);
5413 task_req_descp->header.dword_2 =
5414 cpu_to_le32(OCS_INVALID_COMMAND_STATUS);
5416 /* Configure task request UPIU */
5418 (struct utp_upiu_task_req *) task_req_descp->task_req_upiu;
5419 task_tag = hba->nutrs + free_slot;
5420 task_req_upiup->header.dword_0 =
5421 UPIU_HEADER_DWORD(UPIU_TRANSACTION_TASK_REQ, 0,
5423 task_req_upiup->header.dword_1 =
5424 UPIU_HEADER_DWORD(0, tm_function, 0, 0);
5426 * The host shall provide the same value for LUN field in the basic
5427 * header and for Input Parameter.
5429 task_req_upiup->input_param1 = cpu_to_be32(lun_id);
5430 task_req_upiup->input_param2 = cpu_to_be32(task_id);
5432 ufshcd_vops_setup_task_mgmt(hba, free_slot, tm_function);
5434 /* send command to the controller */
5435 __set_bit(free_slot, &hba->outstanding_tasks);
5437 /* Make sure descriptors are ready before ringing the task doorbell */
5440 ufshcd_writel(hba, 1 << free_slot, REG_UTP_TASK_REQ_DOOR_BELL);
5441 /* Make sure that doorbell is committed immediately */
5444 spin_unlock_irqrestore(host->host_lock, flags);
5446 /* wait until the task management command is completed */
5447 err = wait_event_timeout(hba->tm_wq,
5448 test_bit(free_slot, &hba->tm_condition),
5449 msecs_to_jiffies(TM_CMD_TIMEOUT));
5451 dev_err(hba->dev, "%s: task management cmd 0x%.2x timed-out\n",
5452 __func__, tm_function);
5453 if (ufshcd_clear_tm_cmd(hba, free_slot))
5454 dev_WARN(hba->dev, "%s: unable clear tm cmd (slot %d) after timeout\n",
5455 __func__, free_slot);
5458 err = ufshcd_task_req_compl(hba, free_slot, tm_response);
5461 clear_bit(free_slot, &hba->tm_condition);
5462 ufshcd_put_tm_slot(hba, free_slot);
5463 wake_up(&hba->tm_tag_wq);
5465 ufshcd_release(hba);
5470 * ufshcd_eh_device_reset_handler - device reset handler registered to
5472 * @cmd: SCSI command pointer
5474 * Returns SUCCESS/FAILED
5476 static int ufshcd_eh_device_reset_handler(struct scsi_cmnd *cmd)
5478 struct Scsi_Host *host;
5479 struct ufs_hba *hba;
5484 struct ufshcd_lrb *lrbp;
5485 unsigned long flags;
5487 host = cmd->device->host;
5488 hba = shost_priv(host);
5489 tag = cmd->request->tag;
5491 lrbp = &hba->lrb[tag];
5492 err = ufshcd_issue_tm_cmd(hba, lrbp->lun, 0, UFS_LOGICAL_RESET, &resp);
5493 if (err || resp != UPIU_TASK_MANAGEMENT_FUNC_COMPL) {
5499 /* clear the commands that were pending for corresponding LUN */
5500 for_each_set_bit(pos, &hba->outstanding_reqs, hba->nutrs) {
5501 if (hba->lrb[pos].lun == lrbp->lun) {
5502 err = ufshcd_clear_cmd(hba, pos);
5507 spin_lock_irqsave(host->host_lock, flags);
5508 ufshcd_transfer_req_compl(hba);
5509 spin_unlock_irqrestore(host->host_lock, flags);
5512 hba->req_abort_count = 0;
5516 dev_err(hba->dev, "%s: failed with err %d\n", __func__, err);
5522 static void ufshcd_set_req_abort_skip(struct ufs_hba *hba, unsigned long bitmap)
5524 struct ufshcd_lrb *lrbp;
5527 for_each_set_bit(tag, &bitmap, hba->nutrs) {
5528 lrbp = &hba->lrb[tag];
5529 lrbp->req_abort_skip = true;
5534 * ufshcd_abort - abort a specific command
5535 * @cmd: SCSI command pointer
5537 * Abort the pending command in device by sending UFS_ABORT_TASK task management
5538 * command, and in host controller by clearing the door-bell register. There can
5539 * be race between controller sending the command to the device while abort is
5540 * issued. To avoid that, first issue UFS_QUERY_TASK to check if the command is
5541 * really issued and then try to abort it.
5543 * Returns SUCCESS/FAILED
5545 static int ufshcd_abort(struct scsi_cmnd *cmd)
5547 struct Scsi_Host *host;
5548 struct ufs_hba *hba;
5549 unsigned long flags;
5554 struct ufshcd_lrb *lrbp;
5557 host = cmd->device->host;
5558 hba = shost_priv(host);
5559 tag = cmd->request->tag;
5560 lrbp = &hba->lrb[tag];
5561 if (!ufshcd_valid_tag(hba, tag)) {
5563 "%s: invalid command tag %d: cmd=0x%p, cmd->request=0x%p",
5564 __func__, tag, cmd, cmd->request);
5569 * Task abort to the device W-LUN is illegal. When this command
5570 * will fail, due to spec violation, scsi err handling next step
5571 * will be to send LU reset which, again, is a spec violation.
5572 * To avoid these unnecessary/illegal step we skip to the last error
5573 * handling stage: reset and restore.
5575 if (lrbp->lun == UFS_UPIU_UFS_DEVICE_WLUN)
5576 return ufshcd_eh_host_reset_handler(cmd);
5578 ufshcd_hold(hba, false);
5579 reg = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
5580 /* If command is already aborted/completed, return SUCCESS */
5581 if (!(test_bit(tag, &hba->outstanding_reqs))) {
5583 "%s: cmd at tag %d already completed, outstanding=0x%lx, doorbell=0x%x\n",
5584 __func__, tag, hba->outstanding_reqs, reg);
5588 if (!(reg & (1 << tag))) {
5590 "%s: cmd was completed, but without a notifying intr, tag = %d",
5594 /* Print Transfer Request of aborted task */
5595 dev_err(hba->dev, "%s: Device abort task at tag %d\n", __func__, tag);
5598 * Print detailed info about aborted request.
5599 * As more than one request might get aborted at the same time,
5600 * print full information only for the first aborted request in order
5601 * to reduce repeated printouts. For other aborted requests only print
5604 scsi_print_command(hba->lrb[tag].cmd);
5605 if (!hba->req_abort_count) {
5606 ufshcd_print_host_regs(hba);
5607 ufshcd_print_host_state(hba);
5608 ufshcd_print_pwr_info(hba);
5609 ufshcd_print_trs(hba, 1 << tag, true);
5611 ufshcd_print_trs(hba, 1 << tag, false);
5613 hba->req_abort_count++;
5615 /* Skip task abort in case previous aborts failed and report failure */
5616 if (lrbp->req_abort_skip) {
5621 for (poll_cnt = 100; poll_cnt; poll_cnt--) {
5622 err = ufshcd_issue_tm_cmd(hba, lrbp->lun, lrbp->task_tag,
5623 UFS_QUERY_TASK, &resp);
5624 if (!err && resp == UPIU_TASK_MANAGEMENT_FUNC_SUCCEEDED) {
5625 /* cmd pending in the device */
5626 dev_err(hba->dev, "%s: cmd pending in the device. tag = %d\n",
5629 } else if (!err && resp == UPIU_TASK_MANAGEMENT_FUNC_COMPL) {
5631 * cmd not pending in the device, check if it is
5634 dev_err(hba->dev, "%s: cmd at tag %d not pending in the device.\n",
5636 reg = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
5637 if (reg & (1 << tag)) {
5638 /* sleep for max. 200us to stabilize */
5639 usleep_range(100, 200);
5642 /* command completed already */
5643 dev_err(hba->dev, "%s: cmd at tag %d successfully cleared from DB.\n",
5648 "%s: no response from device. tag = %d, err %d\n",
5649 __func__, tag, err);
5651 err = resp; /* service response error */
5661 err = ufshcd_issue_tm_cmd(hba, lrbp->lun, lrbp->task_tag,
5662 UFS_ABORT_TASK, &resp);
5663 if (err || resp != UPIU_TASK_MANAGEMENT_FUNC_COMPL) {
5665 err = resp; /* service response error */
5666 dev_err(hba->dev, "%s: issued. tag = %d, err %d\n",
5667 __func__, tag, err);
5672 err = ufshcd_clear_cmd(hba, tag);
5674 dev_err(hba->dev, "%s: Failed clearing cmd at tag %d, err %d\n",
5675 __func__, tag, err);
5679 scsi_dma_unmap(cmd);
5681 spin_lock_irqsave(host->host_lock, flags);
5682 ufshcd_outstanding_req_clear(hba, tag);
5683 hba->lrb[tag].cmd = NULL;
5684 spin_unlock_irqrestore(host->host_lock, flags);
5686 clear_bit_unlock(tag, &hba->lrb_in_use);
5687 wake_up(&hba->dev_cmd.tag_wq);
5693 dev_err(hba->dev, "%s: failed with err %d\n", __func__, err);
5694 ufshcd_set_req_abort_skip(hba, hba->outstanding_reqs);
5699 * This ufshcd_release() corresponds to the original scsi cmd that got
5700 * aborted here (as we won't get any IRQ for it).
5702 ufshcd_release(hba);
5707 * ufshcd_host_reset_and_restore - reset and restore host controller
5708 * @hba: per-adapter instance
5710 * Note that host controller reset may issue DME_RESET to
5711 * local and remote (device) Uni-Pro stack and the attributes
5712 * are reset to default state.
5714 * Returns zero on success, non-zero on failure
5716 static int ufshcd_host_reset_and_restore(struct ufs_hba *hba)
5719 unsigned long flags;
5721 /* Reset the host controller */
5722 spin_lock_irqsave(hba->host->host_lock, flags);
5723 ufshcd_hba_stop(hba, false);
5724 spin_unlock_irqrestore(hba->host->host_lock, flags);
5726 /* scale up clocks to max frequency before full reinitialization */
5727 ufshcd_scale_clks(hba, true);
5729 err = ufshcd_hba_enable(hba);
5733 /* Establish the link again and restore the device */
5734 err = ufshcd_probe_hba(hba);
5736 if (!err && (hba->ufshcd_state != UFSHCD_STATE_OPERATIONAL))
5740 dev_err(hba->dev, "%s: Host init failed %d\n", __func__, err);
5746 * ufshcd_reset_and_restore - reset and re-initialize host/device
5747 * @hba: per-adapter instance
5749 * Reset and recover device, host and re-establish link. This
5750 * is helpful to recover the communication in fatal error conditions.
5752 * Returns zero on success, non-zero on failure
5754 static int ufshcd_reset_and_restore(struct ufs_hba *hba)
5757 unsigned long flags;
5758 int retries = MAX_HOST_RESET_RETRIES;
5761 err = ufshcd_host_reset_and_restore(hba);
5762 } while (err && --retries);
5765 * After reset the door-bell might be cleared, complete
5766 * outstanding requests in s/w here.
5768 spin_lock_irqsave(hba->host->host_lock, flags);
5769 ufshcd_transfer_req_compl(hba);
5770 ufshcd_tmc_handler(hba);
5771 spin_unlock_irqrestore(hba->host->host_lock, flags);
5777 * ufshcd_eh_host_reset_handler - host reset handler registered to scsi layer
5778 * @cmd: SCSI command pointer
5780 * Returns SUCCESS/FAILED
5782 static int ufshcd_eh_host_reset_handler(struct scsi_cmnd *cmd)
5785 unsigned long flags;
5786 struct ufs_hba *hba;
5788 hba = shost_priv(cmd->device->host);
5790 ufshcd_hold(hba, false);
5792 * Check if there is any race with fatal error handling.
5793 * If so, wait for it to complete. Even though fatal error
5794 * handling does reset and restore in some cases, don't assume
5795 * anything out of it. We are just avoiding race here.
5798 spin_lock_irqsave(hba->host->host_lock, flags);
5799 if (!(work_pending(&hba->eh_work) ||
5800 hba->ufshcd_state == UFSHCD_STATE_RESET ||
5801 hba->ufshcd_state == UFSHCD_STATE_EH_SCHEDULED))
5803 spin_unlock_irqrestore(hba->host->host_lock, flags);
5804 dev_dbg(hba->dev, "%s: reset in progress\n", __func__);
5805 flush_work(&hba->eh_work);
5808 hba->ufshcd_state = UFSHCD_STATE_RESET;
5809 ufshcd_set_eh_in_progress(hba);
5810 spin_unlock_irqrestore(hba->host->host_lock, flags);
5812 err = ufshcd_reset_and_restore(hba);
5814 spin_lock_irqsave(hba->host->host_lock, flags);
5817 hba->ufshcd_state = UFSHCD_STATE_OPERATIONAL;
5820 hba->ufshcd_state = UFSHCD_STATE_ERROR;
5822 ufshcd_clear_eh_in_progress(hba);
5823 spin_unlock_irqrestore(hba->host->host_lock, flags);
5825 ufshcd_release(hba);
5830 * ufshcd_get_max_icc_level - calculate the ICC level
5831 * @sup_curr_uA: max. current supported by the regulator
5832 * @start_scan: row at the desc table to start scan from
5833 * @buff: power descriptor buffer
5835 * Returns calculated max ICC level for specific regulator
5837 static u32 ufshcd_get_max_icc_level(int sup_curr_uA, u32 start_scan, char *buff)
5844 for (i = start_scan; i >= 0; i--) {
5845 data = be16_to_cpup((__be16 *)&buff[2 * i]);
5846 unit = (data & ATTR_ICC_LVL_UNIT_MASK) >>
5847 ATTR_ICC_LVL_UNIT_OFFSET;
5848 curr_uA = data & ATTR_ICC_LVL_VALUE_MASK;
5850 case UFSHCD_NANO_AMP:
5851 curr_uA = curr_uA / 1000;
5853 case UFSHCD_MILI_AMP:
5854 curr_uA = curr_uA * 1000;
5857 curr_uA = curr_uA * 1000 * 1000;
5859 case UFSHCD_MICRO_AMP:
5863 if (sup_curr_uA >= curr_uA)
5868 pr_err("%s: Couldn't find valid icc_level = %d", __func__, i);
5875 * ufshcd_calc_icc_level - calculate the max ICC level
5876 * In case regulators are not initialized we'll return 0
5877 * @hba: per-adapter instance
5878 * @desc_buf: power descriptor buffer to extract ICC levels from.
5879 * @len: length of desc_buff
5881 * Returns calculated ICC level
5883 static u32 ufshcd_find_max_sup_active_icc_level(struct ufs_hba *hba,
5884 u8 *desc_buf, int len)
5888 if (!hba->vreg_info.vcc || !hba->vreg_info.vccq ||
5889 !hba->vreg_info.vccq2) {
5891 "%s: Regulator capability was not set, actvIccLevel=%d",
5892 __func__, icc_level);
5896 if (hba->vreg_info.vcc)
5897 icc_level = ufshcd_get_max_icc_level(
5898 hba->vreg_info.vcc->max_uA,
5899 POWER_DESC_MAX_ACTV_ICC_LVLS - 1,
5900 &desc_buf[PWR_DESC_ACTIVE_LVLS_VCC_0]);
5902 if (hba->vreg_info.vccq)
5903 icc_level = ufshcd_get_max_icc_level(
5904 hba->vreg_info.vccq->max_uA,
5906 &desc_buf[PWR_DESC_ACTIVE_LVLS_VCCQ_0]);
5908 if (hba->vreg_info.vccq2)
5909 icc_level = ufshcd_get_max_icc_level(
5910 hba->vreg_info.vccq2->max_uA,
5912 &desc_buf[PWR_DESC_ACTIVE_LVLS_VCCQ2_0]);
5917 static void ufshcd_init_icc_levels(struct ufs_hba *hba)
5920 int buff_len = hba->desc_size.pwr_desc;
5921 u8 desc_buf[hba->desc_size.pwr_desc];
5923 ret = ufshcd_read_power_desc(hba, desc_buf, buff_len);
5926 "%s: Failed reading power descriptor.len = %d ret = %d",
5927 __func__, buff_len, ret);
5931 hba->init_prefetch_data.icc_level =
5932 ufshcd_find_max_sup_active_icc_level(hba,
5933 desc_buf, buff_len);
5934 dev_dbg(hba->dev, "%s: setting icc_level 0x%x",
5935 __func__, hba->init_prefetch_data.icc_level);
5937 ret = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_WRITE_ATTR,
5938 QUERY_ATTR_IDN_ACTIVE_ICC_LVL, 0, 0,
5939 &hba->init_prefetch_data.icc_level);
5943 "%s: Failed configuring bActiveICCLevel = %d ret = %d",
5944 __func__, hba->init_prefetch_data.icc_level , ret);
5949 * ufshcd_scsi_add_wlus - Adds required W-LUs
5950 * @hba: per-adapter instance
5952 * UFS device specification requires the UFS devices to support 4 well known
5954 * "REPORT_LUNS" (address: 01h)
5955 * "UFS Device" (address: 50h)
5956 * "RPMB" (address: 44h)
5957 * "BOOT" (address: 30h)
5958 * UFS device's power management needs to be controlled by "POWER CONDITION"
5959 * field of SSU (START STOP UNIT) command. But this "power condition" field
5960 * will take effect only when its sent to "UFS device" well known logical unit
5961 * hence we require the scsi_device instance to represent this logical unit in
5962 * order for the UFS host driver to send the SSU command for power management.
5964 * We also require the scsi_device instance for "RPMB" (Replay Protected Memory
5965 * Block) LU so user space process can control this LU. User space may also
5966 * want to have access to BOOT LU.
5968 * This function adds scsi device instances for each of all well known LUs
5969 * (except "REPORT LUNS" LU).
5971 * Returns zero on success (all required W-LUs are added successfully),
5972 * non-zero error value on failure (if failed to add any of the required W-LU).
5974 static int ufshcd_scsi_add_wlus(struct ufs_hba *hba)
5977 struct scsi_device *sdev_rpmb;
5978 struct scsi_device *sdev_boot;
5980 hba->sdev_ufs_device = __scsi_add_device(hba->host, 0, 0,
5981 ufshcd_upiu_wlun_to_scsi_wlun(UFS_UPIU_UFS_DEVICE_WLUN), NULL);
5982 if (IS_ERR(hba->sdev_ufs_device)) {
5983 ret = PTR_ERR(hba->sdev_ufs_device);
5984 hba->sdev_ufs_device = NULL;
5987 scsi_device_put(hba->sdev_ufs_device);
5989 sdev_rpmb = __scsi_add_device(hba->host, 0, 0,
5990 ufshcd_upiu_wlun_to_scsi_wlun(UFS_UPIU_RPMB_WLUN), NULL);
5991 if (IS_ERR(sdev_rpmb)) {
5992 ret = PTR_ERR(sdev_rpmb);
5993 goto remove_sdev_ufs_device;
5995 scsi_device_put(sdev_rpmb);
5997 sdev_boot = __scsi_add_device(hba->host, 0, 0,
5998 ufshcd_upiu_wlun_to_scsi_wlun(UFS_UPIU_BOOT_WLUN), NULL);
5999 if (IS_ERR(sdev_boot))
6000 dev_err(hba->dev, "%s: BOOT WLUN not found\n", __func__);
6002 scsi_device_put(sdev_boot);
6005 remove_sdev_ufs_device:
6006 scsi_remove_device(hba->sdev_ufs_device);
6011 static int ufs_get_device_desc(struct ufs_hba *hba,
6012 struct ufs_dev_desc *dev_desc)
6016 u8 str_desc_buf[QUERY_DESC_MAX_SIZE + 1] = {0};
6017 u8 desc_buf[hba->desc_size.dev_desc];
6019 err = ufshcd_read_device_desc(hba, desc_buf, hba->desc_size.dev_desc);
6021 dev_err(hba->dev, "%s: Failed reading Device Desc. err = %d\n",
6027 * getting vendor (manufacturerID) and Bank Index in big endian
6030 dev_desc->wmanufacturerid = desc_buf[DEVICE_DESC_PARAM_MANF_ID] << 8 |
6031 desc_buf[DEVICE_DESC_PARAM_MANF_ID + 1];
6033 model_index = desc_buf[DEVICE_DESC_PARAM_PRDCT_NAME];
6035 err = ufshcd_read_string_desc(hba, model_index, str_desc_buf,
6036 QUERY_DESC_MAX_SIZE, true/*ASCII*/);
6038 dev_err(hba->dev, "%s: Failed reading Product Name. err = %d\n",
6043 str_desc_buf[QUERY_DESC_MAX_SIZE] = '\0';
6044 strlcpy(dev_desc->model, (str_desc_buf + QUERY_DESC_HDR_SIZE),
6045 min_t(u8, str_desc_buf[QUERY_DESC_LENGTH_OFFSET],
6048 /* Null terminate the model string */
6049 dev_desc->model[MAX_MODEL_LEN] = '\0';
6055 static void ufs_fixup_device_setup(struct ufs_hba *hba,
6056 struct ufs_dev_desc *dev_desc)
6058 struct ufs_dev_fix *f;
6060 for (f = ufs_fixups; f->quirk; f++) {
6061 if ((f->card.wmanufacturerid == dev_desc->wmanufacturerid ||
6062 f->card.wmanufacturerid == UFS_ANY_VENDOR) &&
6063 (STR_PRFX_EQUAL(f->card.model, dev_desc->model) ||
6064 !strcmp(f->card.model, UFS_ANY_MODEL)))
6065 hba->dev_quirks |= f->quirk;
6070 * ufshcd_tune_pa_tactivate - Tunes PA_TActivate of local UniPro
6071 * @hba: per-adapter instance
6073 * PA_TActivate parameter can be tuned manually if UniPro version is less than
6074 * 1.61. PA_TActivate needs to be greater than or equal to peerM-PHY's
6075 * RX_MIN_ACTIVATETIME_CAPABILITY attribute. This optimal value can help reduce
6076 * the hibern8 exit latency.
6078 * Returns zero on success, non-zero error value on failure.
6080 static int ufshcd_tune_pa_tactivate(struct ufs_hba *hba)
6083 u32 peer_rx_min_activatetime = 0, tuned_pa_tactivate;
6085 ret = ufshcd_dme_peer_get(hba,
6087 RX_MIN_ACTIVATETIME_CAPABILITY,
6088 UIC_ARG_MPHY_RX_GEN_SEL_INDEX(0)),
6089 &peer_rx_min_activatetime);
6093 /* make sure proper unit conversion is applied */
6094 tuned_pa_tactivate =
6095 ((peer_rx_min_activatetime * RX_MIN_ACTIVATETIME_UNIT_US)
6096 / PA_TACTIVATE_TIME_UNIT_US);
6097 ret = ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TACTIVATE),
6098 tuned_pa_tactivate);
6105 * ufshcd_tune_pa_hibern8time - Tunes PA_Hibern8Time of local UniPro
6106 * @hba: per-adapter instance
6108 * PA_Hibern8Time parameter can be tuned manually if UniPro version is less than
6109 * 1.61. PA_Hibern8Time needs to be maximum of local M-PHY's
6110 * TX_HIBERN8TIME_CAPABILITY & peer M-PHY's RX_HIBERN8TIME_CAPABILITY.
6111 * This optimal value can help reduce the hibern8 exit latency.
6113 * Returns zero on success, non-zero error value on failure.
6115 static int ufshcd_tune_pa_hibern8time(struct ufs_hba *hba)
6118 u32 local_tx_hibern8_time_cap = 0, peer_rx_hibern8_time_cap = 0;
6119 u32 max_hibern8_time, tuned_pa_hibern8time;
6121 ret = ufshcd_dme_get(hba,
6122 UIC_ARG_MIB_SEL(TX_HIBERN8TIME_CAPABILITY,
6123 UIC_ARG_MPHY_TX_GEN_SEL_INDEX(0)),
6124 &local_tx_hibern8_time_cap);
6128 ret = ufshcd_dme_peer_get(hba,
6129 UIC_ARG_MIB_SEL(RX_HIBERN8TIME_CAPABILITY,
6130 UIC_ARG_MPHY_RX_GEN_SEL_INDEX(0)),
6131 &peer_rx_hibern8_time_cap);
6135 max_hibern8_time = max(local_tx_hibern8_time_cap,
6136 peer_rx_hibern8_time_cap);
6137 /* make sure proper unit conversion is applied */
6138 tuned_pa_hibern8time = ((max_hibern8_time * HIBERN8TIME_UNIT_US)
6139 / PA_HIBERN8_TIME_UNIT_US);
6140 ret = ufshcd_dme_set(hba, UIC_ARG_MIB(PA_HIBERN8TIME),
6141 tuned_pa_hibern8time);
6147 * ufshcd_quirk_tune_host_pa_tactivate - Ensures that host PA_TACTIVATE is
6148 * less than device PA_TACTIVATE time.
6149 * @hba: per-adapter instance
6151 * Some UFS devices require host PA_TACTIVATE to be lower than device
6152 * PA_TACTIVATE, we need to enable UFS_DEVICE_QUIRK_HOST_PA_TACTIVATE quirk
6155 * Returns zero on success, non-zero error value on failure.
6157 static int ufshcd_quirk_tune_host_pa_tactivate(struct ufs_hba *hba)
6160 u32 granularity, peer_granularity;
6161 u32 pa_tactivate, peer_pa_tactivate;
6162 u32 pa_tactivate_us, peer_pa_tactivate_us;
6163 u8 gran_to_us_table[] = {1, 4, 8, 16, 32, 100};
6165 ret = ufshcd_dme_get(hba, UIC_ARG_MIB(PA_GRANULARITY),
6170 ret = ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_GRANULARITY),
6175 if ((granularity < PA_GRANULARITY_MIN_VAL) ||
6176 (granularity > PA_GRANULARITY_MAX_VAL)) {
6177 dev_err(hba->dev, "%s: invalid host PA_GRANULARITY %d",
6178 __func__, granularity);
6182 if ((peer_granularity < PA_GRANULARITY_MIN_VAL) ||
6183 (peer_granularity > PA_GRANULARITY_MAX_VAL)) {
6184 dev_err(hba->dev, "%s: invalid device PA_GRANULARITY %d",
6185 __func__, peer_granularity);
6189 ret = ufshcd_dme_get(hba, UIC_ARG_MIB(PA_TACTIVATE), &pa_tactivate);
6193 ret = ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_TACTIVATE),
6194 &peer_pa_tactivate);
6198 pa_tactivate_us = pa_tactivate * gran_to_us_table[granularity - 1];
6199 peer_pa_tactivate_us = peer_pa_tactivate *
6200 gran_to_us_table[peer_granularity - 1];
6202 if (pa_tactivate_us > peer_pa_tactivate_us) {
6203 u32 new_peer_pa_tactivate;
6205 new_peer_pa_tactivate = pa_tactivate_us /
6206 gran_to_us_table[peer_granularity - 1];
6207 new_peer_pa_tactivate++;
6208 ret = ufshcd_dme_peer_set(hba, UIC_ARG_MIB(PA_TACTIVATE),
6209 new_peer_pa_tactivate);
6216 static void ufshcd_tune_unipro_params(struct ufs_hba *hba)
6218 if (ufshcd_is_unipro_pa_params_tuning_req(hba)) {
6219 ufshcd_tune_pa_tactivate(hba);
6220 ufshcd_tune_pa_hibern8time(hba);
6223 if (hba->dev_quirks & UFS_DEVICE_QUIRK_PA_TACTIVATE)
6224 /* set 1ms timeout for PA_TACTIVATE */
6225 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TACTIVATE), 10);
6227 if (hba->dev_quirks & UFS_DEVICE_QUIRK_HOST_PA_TACTIVATE)
6228 ufshcd_quirk_tune_host_pa_tactivate(hba);
6230 ufshcd_vops_apply_dev_quirks(hba);
6233 static void ufshcd_clear_dbg_ufs_stats(struct ufs_hba *hba)
6235 int err_reg_hist_size = sizeof(struct ufs_uic_err_reg_hist);
6237 hba->ufs_stats.hibern8_exit_cnt = 0;
6238 hba->ufs_stats.last_hibern8_exit_tstamp = ktime_set(0, 0);
6240 memset(&hba->ufs_stats.pa_err, 0, err_reg_hist_size);
6241 memset(&hba->ufs_stats.dl_err, 0, err_reg_hist_size);
6242 memset(&hba->ufs_stats.nl_err, 0, err_reg_hist_size);
6243 memset(&hba->ufs_stats.tl_err, 0, err_reg_hist_size);
6244 memset(&hba->ufs_stats.dme_err, 0, err_reg_hist_size);
6246 hba->req_abort_count = 0;
6249 static void ufshcd_init_desc_sizes(struct ufs_hba *hba)
6253 err = ufshcd_read_desc_length(hba, QUERY_DESC_IDN_DEVICE, 0,
6254 &hba->desc_size.dev_desc);
6256 hba->desc_size.dev_desc = QUERY_DESC_DEVICE_DEF_SIZE;
6258 err = ufshcd_read_desc_length(hba, QUERY_DESC_IDN_POWER, 0,
6259 &hba->desc_size.pwr_desc);
6261 hba->desc_size.pwr_desc = QUERY_DESC_POWER_DEF_SIZE;
6263 err = ufshcd_read_desc_length(hba, QUERY_DESC_IDN_INTERCONNECT, 0,
6264 &hba->desc_size.interc_desc);
6266 hba->desc_size.interc_desc = QUERY_DESC_INTERCONNECT_DEF_SIZE;
6268 err = ufshcd_read_desc_length(hba, QUERY_DESC_IDN_CONFIGURATION, 0,
6269 &hba->desc_size.conf_desc);
6271 hba->desc_size.conf_desc = QUERY_DESC_CONFIGURATION_DEF_SIZE;
6273 err = ufshcd_read_desc_length(hba, QUERY_DESC_IDN_UNIT, 0,
6274 &hba->desc_size.unit_desc);
6276 hba->desc_size.unit_desc = QUERY_DESC_UNIT_DEF_SIZE;
6278 err = ufshcd_read_desc_length(hba, QUERY_DESC_IDN_GEOMETRY, 0,
6279 &hba->desc_size.geom_desc);
6281 hba->desc_size.geom_desc = QUERY_DESC_GEOMETRY_DEF_SIZE;
6282 err = ufshcd_read_desc_length(hba, QUERY_DESC_IDN_HEALTH, 0,
6283 &hba->desc_size.hlth_desc);
6285 hba->desc_size.hlth_desc = QUERY_DESC_HEALTH_DEF_SIZE;
6288 static void ufshcd_def_desc_sizes(struct ufs_hba *hba)
6290 hba->desc_size.dev_desc = QUERY_DESC_DEVICE_DEF_SIZE;
6291 hba->desc_size.pwr_desc = QUERY_DESC_POWER_DEF_SIZE;
6292 hba->desc_size.interc_desc = QUERY_DESC_INTERCONNECT_DEF_SIZE;
6293 hba->desc_size.conf_desc = QUERY_DESC_CONFIGURATION_DEF_SIZE;
6294 hba->desc_size.unit_desc = QUERY_DESC_UNIT_DEF_SIZE;
6295 hba->desc_size.geom_desc = QUERY_DESC_GEOMETRY_DEF_SIZE;
6296 hba->desc_size.hlth_desc = QUERY_DESC_HEALTH_DEF_SIZE;
6300 * ufshcd_probe_hba - probe hba to detect device and initialize
6301 * @hba: per-adapter instance
6303 * Execute link-startup and verify device initialization
6305 static int ufshcd_probe_hba(struct ufs_hba *hba)
6307 struct ufs_dev_desc card = {0};
6309 ktime_t start = ktime_get();
6311 ret = ufshcd_link_startup(hba);
6315 /* set the default level for urgent bkops */
6316 hba->urgent_bkops_lvl = BKOPS_STATUS_PERF_IMPACT;
6317 hba->is_urgent_bkops_lvl_checked = false;
6319 /* Debug counters initialization */
6320 ufshcd_clear_dbg_ufs_stats(hba);
6322 /* UniPro link is active now */
6323 ufshcd_set_link_active(hba);
6325 /* Enable Auto-Hibernate if configured */
6326 ufshcd_auto_hibern8_enable(hba);
6328 ret = ufshcd_verify_dev_init(hba);
6332 ret = ufshcd_complete_dev_init(hba);
6336 /* Init check for device descriptor sizes */
6337 ufshcd_init_desc_sizes(hba);
6339 ret = ufs_get_device_desc(hba, &card);
6341 dev_err(hba->dev, "%s: Failed getting device info. err = %d\n",
6346 ufs_fixup_device_setup(hba, &card);
6347 ufshcd_tune_unipro_params(hba);
6349 ret = ufshcd_set_vccq_rail_unused(hba,
6350 (hba->dev_quirks & UFS_DEVICE_NO_VCCQ) ? true : false);
6354 /* UFS device is also active now */
6355 ufshcd_set_ufs_dev_active(hba);
6356 ufshcd_force_reset_auto_bkops(hba);
6357 hba->wlun_dev_clr_ua = true;
6359 if (ufshcd_get_max_pwr_mode(hba)) {
6361 "%s: Failed getting max supported power mode\n",
6364 ret = ufshcd_config_pwr_mode(hba, &hba->max_pwr_info.info);
6366 dev_err(hba->dev, "%s: Failed setting power mode, err = %d\n",
6372 /* set the state as operational after switching to desired gear */
6373 hba->ufshcd_state = UFSHCD_STATE_OPERATIONAL;
6376 * If we are in error handling context or in power management callbacks
6377 * context, no need to scan the host
6379 if (!ufshcd_eh_in_progress(hba) && !hba->pm_op_in_progress) {
6382 /* clear any previous UFS device information */
6383 memset(&hba->dev_info, 0, sizeof(hba->dev_info));
6384 if (!ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_READ_FLAG,
6385 QUERY_FLAG_IDN_PWR_ON_WPE, &flag))
6386 hba->dev_info.f_power_on_wp_en = flag;
6388 if (!hba->is_init_prefetch)
6389 ufshcd_init_icc_levels(hba);
6391 /* Add required well known logical units to scsi mid layer */
6392 if (ufshcd_scsi_add_wlus(hba))
6395 /* Initialize devfreq after UFS device is detected */
6396 if (ufshcd_is_clkscaling_supported(hba)) {
6397 memcpy(&hba->clk_scaling.saved_pwr_info.info,
6399 sizeof(struct ufs_pa_layer_attr));
6400 hba->clk_scaling.saved_pwr_info.is_valid = true;
6401 if (!hba->devfreq) {
6402 hba->devfreq = devm_devfreq_add_device(hba->dev,
6403 &ufs_devfreq_profile,
6406 if (IS_ERR(hba->devfreq)) {
6407 ret = PTR_ERR(hba->devfreq);
6408 dev_err(hba->dev, "Unable to register with devfreq %d\n",
6413 hba->clk_scaling.is_allowed = true;
6416 scsi_scan_host(hba->host);
6417 pm_runtime_put_sync(hba->dev);
6420 if (!hba->is_init_prefetch)
6421 hba->is_init_prefetch = true;
6425 * If we failed to initialize the device or the device is not
6426 * present, turn off the power/clocks etc.
6428 if (ret && !ufshcd_eh_in_progress(hba) && !hba->pm_op_in_progress) {
6429 pm_runtime_put_sync(hba->dev);
6430 ufshcd_hba_exit(hba);
6433 trace_ufshcd_init(dev_name(hba->dev), ret,
6434 ktime_to_us(ktime_sub(ktime_get(), start)),
6435 hba->curr_dev_pwr_mode, hba->uic_link_state);
6440 * ufshcd_async_scan - asynchronous execution for probing hba
6441 * @data: data pointer to pass to this function
6442 * @cookie: cookie data
6444 static void ufshcd_async_scan(void *data, async_cookie_t cookie)
6446 struct ufs_hba *hba = (struct ufs_hba *)data;
6448 ufshcd_probe_hba(hba);
6451 static enum blk_eh_timer_return ufshcd_eh_timed_out(struct scsi_cmnd *scmd)
6453 unsigned long flags;
6454 struct Scsi_Host *host;
6455 struct ufs_hba *hba;
6459 if (!scmd || !scmd->device || !scmd->device->host)
6460 return BLK_EH_NOT_HANDLED;
6462 host = scmd->device->host;
6463 hba = shost_priv(host);
6465 return BLK_EH_NOT_HANDLED;
6467 spin_lock_irqsave(host->host_lock, flags);
6469 for_each_set_bit(index, &hba->outstanding_reqs, hba->nutrs) {
6470 if (hba->lrb[index].cmd == scmd) {
6476 spin_unlock_irqrestore(host->host_lock, flags);
6479 * Bypass SCSI error handling and reset the block layer timer if this
6480 * SCSI command was not actually dispatched to UFS driver, otherwise
6481 * let SCSI layer handle the error as usual.
6483 return found ? BLK_EH_NOT_HANDLED : BLK_EH_RESET_TIMER;
6486 static const struct attribute_group *ufshcd_driver_groups[] = {
6487 &ufs_sysfs_unit_descriptor_group,
6488 &ufs_sysfs_lun_attributes_group,
6492 static struct scsi_host_template ufshcd_driver_template = {
6493 .module = THIS_MODULE,
6495 .proc_name = UFSHCD,
6496 .queuecommand = ufshcd_queuecommand,
6497 .slave_alloc = ufshcd_slave_alloc,
6498 .slave_configure = ufshcd_slave_configure,
6499 .slave_destroy = ufshcd_slave_destroy,
6500 .change_queue_depth = ufshcd_change_queue_depth,
6501 .eh_abort_handler = ufshcd_abort,
6502 .eh_device_reset_handler = ufshcd_eh_device_reset_handler,
6503 .eh_host_reset_handler = ufshcd_eh_host_reset_handler,
6504 .eh_timed_out = ufshcd_eh_timed_out,
6506 .sg_tablesize = SG_ALL,
6507 .cmd_per_lun = UFSHCD_CMD_PER_LUN,
6508 .can_queue = UFSHCD_CAN_QUEUE,
6509 .max_host_blocked = 1,
6510 .track_queue_depth = 1,
6511 .sdev_groups = ufshcd_driver_groups,
6514 static int ufshcd_config_vreg_load(struct device *dev, struct ufs_vreg *vreg,
6522 ret = regulator_set_load(vreg->reg, ua);
6524 dev_err(dev, "%s: %s set load (ua=%d) failed, err=%d\n",
6525 __func__, vreg->name, ua, ret);
6531 static inline int ufshcd_config_vreg_lpm(struct ufs_hba *hba,
6532 struct ufs_vreg *vreg)
6536 else if (vreg->unused)
6539 return ufshcd_config_vreg_load(hba->dev, vreg,
6540 UFS_VREG_LPM_LOAD_UA);
6543 static inline int ufshcd_config_vreg_hpm(struct ufs_hba *hba,
6544 struct ufs_vreg *vreg)
6548 else if (vreg->unused)
6551 return ufshcd_config_vreg_load(hba->dev, vreg, vreg->max_uA);
6554 static int ufshcd_config_vreg(struct device *dev,
6555 struct ufs_vreg *vreg, bool on)
6558 struct regulator *reg;
6560 int min_uV, uA_load;
6567 if (regulator_count_voltages(reg) > 0) {
6568 min_uV = on ? vreg->min_uV : 0;
6569 ret = regulator_set_voltage(reg, min_uV, vreg->max_uV);
6571 dev_err(dev, "%s: %s set voltage failed, err=%d\n",
6572 __func__, name, ret);
6576 uA_load = on ? vreg->max_uA : 0;
6577 ret = ufshcd_config_vreg_load(dev, vreg, uA_load);
6585 static int ufshcd_enable_vreg(struct device *dev, struct ufs_vreg *vreg)
6591 else if (vreg->enabled || vreg->unused)
6594 ret = ufshcd_config_vreg(dev, vreg, true);
6596 ret = regulator_enable(vreg->reg);
6599 vreg->enabled = true;
6601 dev_err(dev, "%s: %s enable failed, err=%d\n",
6602 __func__, vreg->name, ret);
6607 static int ufshcd_disable_vreg(struct device *dev, struct ufs_vreg *vreg)
6613 else if (!vreg->enabled || vreg->unused)
6616 ret = regulator_disable(vreg->reg);
6619 /* ignore errors on applying disable config */
6620 ufshcd_config_vreg(dev, vreg, false);
6621 vreg->enabled = false;
6623 dev_err(dev, "%s: %s disable failed, err=%d\n",
6624 __func__, vreg->name, ret);
6630 static int ufshcd_setup_vreg(struct ufs_hba *hba, bool on)
6633 struct device *dev = hba->dev;
6634 struct ufs_vreg_info *info = &hba->vreg_info;
6639 ret = ufshcd_toggle_vreg(dev, info->vcc, on);
6643 ret = ufshcd_toggle_vreg(dev, info->vccq, on);
6647 ret = ufshcd_toggle_vreg(dev, info->vccq2, on);
6653 ufshcd_toggle_vreg(dev, info->vccq2, false);
6654 ufshcd_toggle_vreg(dev, info->vccq, false);
6655 ufshcd_toggle_vreg(dev, info->vcc, false);
6660 static int ufshcd_setup_hba_vreg(struct ufs_hba *hba, bool on)
6662 struct ufs_vreg_info *info = &hba->vreg_info;
6665 return ufshcd_toggle_vreg(hba->dev, info->vdd_hba, on);
6670 static int ufshcd_get_vreg(struct device *dev, struct ufs_vreg *vreg)
6677 vreg->reg = devm_regulator_get(dev, vreg->name);
6678 if (IS_ERR(vreg->reg)) {
6679 ret = PTR_ERR(vreg->reg);
6680 dev_err(dev, "%s: %s get failed, err=%d\n",
6681 __func__, vreg->name, ret);
6687 static int ufshcd_init_vreg(struct ufs_hba *hba)
6690 struct device *dev = hba->dev;
6691 struct ufs_vreg_info *info = &hba->vreg_info;
6696 ret = ufshcd_get_vreg(dev, info->vcc);
6700 ret = ufshcd_get_vreg(dev, info->vccq);
6704 ret = ufshcd_get_vreg(dev, info->vccq2);
6709 static int ufshcd_init_hba_vreg(struct ufs_hba *hba)
6711 struct ufs_vreg_info *info = &hba->vreg_info;
6714 return ufshcd_get_vreg(hba->dev, info->vdd_hba);
6719 static int ufshcd_set_vccq_rail_unused(struct ufs_hba *hba, bool unused)
6722 struct ufs_vreg_info *info = &hba->vreg_info;
6726 else if (!info->vccq)
6730 /* shut off the rail here */
6731 ret = ufshcd_toggle_vreg(hba->dev, info->vccq, false);
6733 * Mark this rail as no longer used, so it doesn't get enabled
6737 info->vccq->unused = true;
6740 * rail should have been already enabled hence just make sure
6741 * that unused flag is cleared.
6743 info->vccq->unused = false;
6749 static int __ufshcd_setup_clocks(struct ufs_hba *hba, bool on,
6753 struct ufs_clk_info *clki;
6754 struct list_head *head = &hba->clk_list_head;
6755 unsigned long flags;
6756 ktime_t start = ktime_get();
6757 bool clk_state_changed = false;
6759 if (list_empty(head))
6762 ret = ufshcd_vops_setup_clocks(hba, on, PRE_CHANGE);
6766 list_for_each_entry(clki, head, list) {
6767 if (!IS_ERR_OR_NULL(clki->clk)) {
6768 if (skip_ref_clk && !strcmp(clki->name, "ref_clk"))
6771 clk_state_changed = on ^ clki->enabled;
6772 if (on && !clki->enabled) {
6773 ret = clk_prepare_enable(clki->clk);
6775 dev_err(hba->dev, "%s: %s prepare enable failed, %d\n",
6776 __func__, clki->name, ret);
6779 } else if (!on && clki->enabled) {
6780 clk_disable_unprepare(clki->clk);
6783 dev_dbg(hba->dev, "%s: clk: %s %sabled\n", __func__,
6784 clki->name, on ? "en" : "dis");
6788 ret = ufshcd_vops_setup_clocks(hba, on, POST_CHANGE);
6794 list_for_each_entry(clki, head, list) {
6795 if (!IS_ERR_OR_NULL(clki->clk) && clki->enabled)
6796 clk_disable_unprepare(clki->clk);
6798 } else if (!ret && on) {
6799 spin_lock_irqsave(hba->host->host_lock, flags);
6800 hba->clk_gating.state = CLKS_ON;
6801 trace_ufshcd_clk_gating(dev_name(hba->dev),
6802 hba->clk_gating.state);
6803 spin_unlock_irqrestore(hba->host->host_lock, flags);
6806 if (clk_state_changed)
6807 trace_ufshcd_profile_clk_gating(dev_name(hba->dev),
6808 (on ? "on" : "off"),
6809 ktime_to_us(ktime_sub(ktime_get(), start)), ret);
6813 static int ufshcd_setup_clocks(struct ufs_hba *hba, bool on)
6815 return __ufshcd_setup_clocks(hba, on, false);
6818 static int ufshcd_init_clocks(struct ufs_hba *hba)
6821 struct ufs_clk_info *clki;
6822 struct device *dev = hba->dev;
6823 struct list_head *head = &hba->clk_list_head;
6825 if (list_empty(head))
6828 list_for_each_entry(clki, head, list) {
6832 clki->clk = devm_clk_get(dev, clki->name);
6833 if (IS_ERR(clki->clk)) {
6834 ret = PTR_ERR(clki->clk);
6835 dev_err(dev, "%s: %s clk get failed, %d\n",
6836 __func__, clki->name, ret);
6840 if (clki->max_freq) {
6841 ret = clk_set_rate(clki->clk, clki->max_freq);
6843 dev_err(hba->dev, "%s: %s clk set rate(%dHz) failed, %d\n",
6844 __func__, clki->name,
6845 clki->max_freq, ret);
6848 clki->curr_freq = clki->max_freq;
6850 dev_dbg(dev, "%s: clk: %s, rate: %lu\n", __func__,
6851 clki->name, clk_get_rate(clki->clk));
6857 static int ufshcd_variant_hba_init(struct ufs_hba *hba)
6864 err = ufshcd_vops_init(hba);
6868 err = ufshcd_vops_setup_regulators(hba, true);
6875 ufshcd_vops_exit(hba);
6878 dev_err(hba->dev, "%s: variant %s init failed err %d\n",
6879 __func__, ufshcd_get_var_name(hba), err);
6883 static void ufshcd_variant_hba_exit(struct ufs_hba *hba)
6888 ufshcd_vops_setup_regulators(hba, false);
6890 ufshcd_vops_exit(hba);
6893 static int ufshcd_hba_init(struct ufs_hba *hba)
6898 * Handle host controller power separately from the UFS device power
6899 * rails as it will help controlling the UFS host controller power
6900 * collapse easily which is different than UFS device power collapse.
6901 * Also, enable the host controller power before we go ahead with rest
6902 * of the initialization here.
6904 err = ufshcd_init_hba_vreg(hba);
6908 err = ufshcd_setup_hba_vreg(hba, true);
6912 err = ufshcd_init_clocks(hba);
6914 goto out_disable_hba_vreg;
6916 err = ufshcd_setup_clocks(hba, true);
6918 goto out_disable_hba_vreg;
6920 err = ufshcd_init_vreg(hba);
6922 goto out_disable_clks;
6924 err = ufshcd_setup_vreg(hba, true);
6926 goto out_disable_clks;
6928 err = ufshcd_variant_hba_init(hba);
6930 goto out_disable_vreg;
6932 hba->is_powered = true;
6936 ufshcd_setup_vreg(hba, false);
6938 ufshcd_setup_clocks(hba, false);
6939 out_disable_hba_vreg:
6940 ufshcd_setup_hba_vreg(hba, false);
6945 static void ufshcd_hba_exit(struct ufs_hba *hba)
6947 if (hba->is_powered) {
6948 ufshcd_variant_hba_exit(hba);
6949 ufshcd_setup_vreg(hba, false);
6950 ufshcd_suspend_clkscaling(hba);
6951 if (ufshcd_is_clkscaling_supported(hba)) {
6953 ufshcd_suspend_clkscaling(hba);
6954 destroy_workqueue(hba->clk_scaling.workq);
6956 ufshcd_setup_clocks(hba, false);
6957 ufshcd_setup_hba_vreg(hba, false);
6958 hba->is_powered = false;
6963 ufshcd_send_request_sense(struct ufs_hba *hba, struct scsi_device *sdp)
6965 unsigned char cmd[6] = {REQUEST_SENSE,
6969 UFSHCD_REQ_SENSE_SIZE,
6974 buffer = kzalloc(UFSHCD_REQ_SENSE_SIZE, GFP_KERNEL);
6980 ret = scsi_execute(sdp, cmd, DMA_FROM_DEVICE, buffer,
6981 UFSHCD_REQ_SENSE_SIZE, NULL, NULL,
6982 msecs_to_jiffies(1000), 3, 0, RQF_PM, NULL);
6984 pr_err("%s: failed with err %d\n", __func__, ret);
6992 * ufshcd_set_dev_pwr_mode - sends START STOP UNIT command to set device
6994 * @hba: per adapter instance
6995 * @pwr_mode: device power mode to set
6997 * Returns 0 if requested power mode is set successfully
6998 * Returns non-zero if failed to set the requested power mode
7000 static int ufshcd_set_dev_pwr_mode(struct ufs_hba *hba,
7001 enum ufs_dev_pwr_mode pwr_mode)
7003 unsigned char cmd[6] = { START_STOP };
7004 struct scsi_sense_hdr sshdr;
7005 struct scsi_device *sdp;
7006 unsigned long flags;
7009 spin_lock_irqsave(hba->host->host_lock, flags);
7010 sdp = hba->sdev_ufs_device;
7012 ret = scsi_device_get(sdp);
7013 if (!ret && !scsi_device_online(sdp)) {
7015 scsi_device_put(sdp);
7020 spin_unlock_irqrestore(hba->host->host_lock, flags);
7026 * If scsi commands fail, the scsi mid-layer schedules scsi error-
7027 * handling, which would wait for host to be resumed. Since we know
7028 * we are functional while we are here, skip host resume in error
7031 hba->host->eh_noresume = 1;
7032 if (hba->wlun_dev_clr_ua) {
7033 ret = ufshcd_send_request_sense(hba, sdp);
7036 /* Unit attention condition is cleared now */
7037 hba->wlun_dev_clr_ua = false;
7040 cmd[4] = pwr_mode << 4;
7043 * Current function would be generally called from the power management
7044 * callbacks hence set the RQF_PM flag so that it doesn't resume the
7045 * already suspended childs.
7047 ret = scsi_execute(sdp, cmd, DMA_NONE, NULL, 0, NULL, &sshdr,
7048 START_STOP_TIMEOUT, 0, 0, RQF_PM, NULL);
7050 sdev_printk(KERN_WARNING, sdp,
7051 "START_STOP failed for power mode: %d, result %x\n",
7053 if (driver_byte(ret) & DRIVER_SENSE)
7054 scsi_print_sense_hdr(sdp, NULL, &sshdr);
7058 hba->curr_dev_pwr_mode = pwr_mode;
7060 scsi_device_put(sdp);
7061 hba->host->eh_noresume = 0;
7065 static int ufshcd_link_state_transition(struct ufs_hba *hba,
7066 enum uic_link_state req_link_state,
7067 int check_for_bkops)
7071 if (req_link_state == hba->uic_link_state)
7074 if (req_link_state == UIC_LINK_HIBERN8_STATE) {
7075 ret = ufshcd_uic_hibern8_enter(hba);
7077 ufshcd_set_link_hibern8(hba);
7082 * If autobkops is enabled, link can't be turned off because
7083 * turning off the link would also turn off the device.
7085 else if ((req_link_state == UIC_LINK_OFF_STATE) &&
7086 (!check_for_bkops || (check_for_bkops &&
7087 !hba->auto_bkops_enabled))) {
7089 * Let's make sure that link is in low power mode, we are doing
7090 * this currently by putting the link in Hibern8. Otherway to
7091 * put the link in low power mode is to send the DME end point
7092 * to device and then send the DME reset command to local
7093 * unipro. But putting the link in hibern8 is much faster.
7095 ret = ufshcd_uic_hibern8_enter(hba);
7099 * Change controller state to "reset state" which
7100 * should also put the link in off/reset state
7102 ufshcd_hba_stop(hba, true);
7104 * TODO: Check if we need any delay to make sure that
7105 * controller is reset
7107 ufshcd_set_link_off(hba);
7114 static void ufshcd_vreg_set_lpm(struct ufs_hba *hba)
7117 * It seems some UFS devices may keep drawing more than sleep current
7118 * (atleast for 500us) from UFS rails (especially from VCCQ rail).
7119 * To avoid this situation, add 2ms delay before putting these UFS
7120 * rails in LPM mode.
7122 if (!ufshcd_is_link_active(hba) &&
7123 hba->dev_quirks & UFS_DEVICE_QUIRK_DELAY_BEFORE_LPM)
7124 usleep_range(2000, 2100);
7127 * If UFS device is either in UFS_Sleep turn off VCC rail to save some
7130 * If UFS device and link is in OFF state, all power supplies (VCC,
7131 * VCCQ, VCCQ2) can be turned off if power on write protect is not
7132 * required. If UFS link is inactive (Hibern8 or OFF state) and device
7133 * is in sleep state, put VCCQ & VCCQ2 rails in LPM mode.
7135 * Ignore the error returned by ufshcd_toggle_vreg() as device is anyway
7136 * in low power state which would save some power.
7138 if (ufshcd_is_ufs_dev_poweroff(hba) && ufshcd_is_link_off(hba) &&
7139 !hba->dev_info.is_lu_power_on_wp) {
7140 ufshcd_setup_vreg(hba, false);
7141 } else if (!ufshcd_is_ufs_dev_active(hba)) {
7142 ufshcd_toggle_vreg(hba->dev, hba->vreg_info.vcc, false);
7143 if (!ufshcd_is_link_active(hba)) {
7144 ufshcd_config_vreg_lpm(hba, hba->vreg_info.vccq);
7145 ufshcd_config_vreg_lpm(hba, hba->vreg_info.vccq2);
7150 static int ufshcd_vreg_set_hpm(struct ufs_hba *hba)
7154 if (ufshcd_is_ufs_dev_poweroff(hba) && ufshcd_is_link_off(hba) &&
7155 !hba->dev_info.is_lu_power_on_wp) {
7156 ret = ufshcd_setup_vreg(hba, true);
7157 } else if (!ufshcd_is_ufs_dev_active(hba)) {
7158 if (!ret && !ufshcd_is_link_active(hba)) {
7159 ret = ufshcd_config_vreg_hpm(hba, hba->vreg_info.vccq);
7162 ret = ufshcd_config_vreg_hpm(hba, hba->vreg_info.vccq2);
7166 ret = ufshcd_toggle_vreg(hba->dev, hba->vreg_info.vcc, true);
7171 ufshcd_config_vreg_lpm(hba, hba->vreg_info.vccq);
7173 ufshcd_toggle_vreg(hba->dev, hba->vreg_info.vcc, false);
7178 static void ufshcd_hba_vreg_set_lpm(struct ufs_hba *hba)
7180 if (ufshcd_is_link_off(hba))
7181 ufshcd_setup_hba_vreg(hba, false);
7184 static void ufshcd_hba_vreg_set_hpm(struct ufs_hba *hba)
7186 if (ufshcd_is_link_off(hba))
7187 ufshcd_setup_hba_vreg(hba, true);
7191 * ufshcd_suspend - helper function for suspend operations
7192 * @hba: per adapter instance
7193 * @pm_op: desired low power operation type
7195 * This function will try to put the UFS device and link into low power
7196 * mode based on the "rpm_lvl" (Runtime PM level) or "spm_lvl"
7197 * (System PM level).
7199 * If this function is called during shutdown, it will make sure that
7200 * both UFS device and UFS link is powered off.
7202 * NOTE: UFS device & link must be active before we enter in this function.
7204 * Returns 0 for success and non-zero for failure
7206 static int ufshcd_suspend(struct ufs_hba *hba, enum ufs_pm_op pm_op)
7209 enum ufs_pm_level pm_lvl;
7210 enum ufs_dev_pwr_mode req_dev_pwr_mode;
7211 enum uic_link_state req_link_state;
7213 hba->pm_op_in_progress = 1;
7214 if (!ufshcd_is_shutdown_pm(pm_op)) {
7215 pm_lvl = ufshcd_is_runtime_pm(pm_op) ?
7216 hba->rpm_lvl : hba->spm_lvl;
7217 req_dev_pwr_mode = ufs_get_pm_lvl_to_dev_pwr_mode(pm_lvl);
7218 req_link_state = ufs_get_pm_lvl_to_link_pwr_state(pm_lvl);
7220 req_dev_pwr_mode = UFS_POWERDOWN_PWR_MODE;
7221 req_link_state = UIC_LINK_OFF_STATE;
7225 * If we can't transition into any of the low power modes
7226 * just gate the clocks.
7228 ufshcd_hold(hba, false);
7229 hba->clk_gating.is_suspended = true;
7231 if (hba->clk_scaling.is_allowed) {
7232 cancel_work_sync(&hba->clk_scaling.suspend_work);
7233 cancel_work_sync(&hba->clk_scaling.resume_work);
7234 ufshcd_suspend_clkscaling(hba);
7237 if (req_dev_pwr_mode == UFS_ACTIVE_PWR_MODE &&
7238 req_link_state == UIC_LINK_ACTIVE_STATE) {
7242 if ((req_dev_pwr_mode == hba->curr_dev_pwr_mode) &&
7243 (req_link_state == hba->uic_link_state))
7246 /* UFS device & link must be active before we enter in this function */
7247 if (!ufshcd_is_ufs_dev_active(hba) || !ufshcd_is_link_active(hba)) {
7252 if (ufshcd_is_runtime_pm(pm_op)) {
7253 if (ufshcd_can_autobkops_during_suspend(hba)) {
7255 * The device is idle with no requests in the queue,
7256 * allow background operations if bkops status shows
7257 * that performance might be impacted.
7259 ret = ufshcd_urgent_bkops(hba);
7263 /* make sure that auto bkops is disabled */
7264 ufshcd_disable_auto_bkops(hba);
7268 if ((req_dev_pwr_mode != hba->curr_dev_pwr_mode) &&
7269 ((ufshcd_is_runtime_pm(pm_op) && !hba->auto_bkops_enabled) ||
7270 !ufshcd_is_runtime_pm(pm_op))) {
7271 /* ensure that bkops is disabled */
7272 ufshcd_disable_auto_bkops(hba);
7273 ret = ufshcd_set_dev_pwr_mode(hba, req_dev_pwr_mode);
7278 ret = ufshcd_link_state_transition(hba, req_link_state, 1);
7280 goto set_dev_active;
7282 ufshcd_vreg_set_lpm(hba);
7286 * Call vendor specific suspend callback. As these callbacks may access
7287 * vendor specific host controller register space call them before the
7288 * host clocks are ON.
7290 ret = ufshcd_vops_suspend(hba, pm_op);
7292 goto set_link_active;
7294 if (!ufshcd_is_link_active(hba))
7295 ufshcd_setup_clocks(hba, false);
7297 /* If link is active, device ref_clk can't be switched off */
7298 __ufshcd_setup_clocks(hba, false, true);
7300 hba->clk_gating.state = CLKS_OFF;
7301 trace_ufshcd_clk_gating(dev_name(hba->dev), hba->clk_gating.state);
7303 * Disable the host irq as host controller as there won't be any
7304 * host controller transaction expected till resume.
7306 ufshcd_disable_irq(hba);
7307 /* Put the host controller in low power mode if possible */
7308 ufshcd_hba_vreg_set_lpm(hba);
7312 if (hba->clk_scaling.is_allowed)
7313 ufshcd_resume_clkscaling(hba);
7314 ufshcd_vreg_set_hpm(hba);
7315 if (ufshcd_is_link_hibern8(hba) && !ufshcd_uic_hibern8_exit(hba))
7316 ufshcd_set_link_active(hba);
7317 else if (ufshcd_is_link_off(hba))
7318 ufshcd_host_reset_and_restore(hba);
7320 if (!ufshcd_set_dev_pwr_mode(hba, UFS_ACTIVE_PWR_MODE))
7321 ufshcd_disable_auto_bkops(hba);
7323 if (hba->clk_scaling.is_allowed)
7324 ufshcd_resume_clkscaling(hba);
7325 hba->clk_gating.is_suspended = false;
7326 ufshcd_release(hba);
7328 hba->pm_op_in_progress = 0;
7333 * ufshcd_resume - helper function for resume operations
7334 * @hba: per adapter instance
7335 * @pm_op: runtime PM or system PM
7337 * This function basically brings the UFS device, UniPro link and controller
7340 * Returns 0 for success and non-zero for failure
7342 static int ufshcd_resume(struct ufs_hba *hba, enum ufs_pm_op pm_op)
7345 enum uic_link_state old_link_state;
7347 hba->pm_op_in_progress = 1;
7348 old_link_state = hba->uic_link_state;
7350 ufshcd_hba_vreg_set_hpm(hba);
7351 /* Make sure clocks are enabled before accessing controller */
7352 ret = ufshcd_setup_clocks(hba, true);
7356 /* enable the host irq as host controller would be active soon */
7357 ret = ufshcd_enable_irq(hba);
7359 goto disable_irq_and_vops_clks;
7361 ret = ufshcd_vreg_set_hpm(hba);
7363 goto disable_irq_and_vops_clks;
7366 * Call vendor specific resume callback. As these callbacks may access
7367 * vendor specific host controller register space call them when the
7368 * host clocks are ON.
7370 ret = ufshcd_vops_resume(hba, pm_op);
7374 if (ufshcd_is_link_hibern8(hba)) {
7375 ret = ufshcd_uic_hibern8_exit(hba);
7377 ufshcd_set_link_active(hba);
7379 goto vendor_suspend;
7380 } else if (ufshcd_is_link_off(hba)) {
7381 ret = ufshcd_host_reset_and_restore(hba);
7383 * ufshcd_host_reset_and_restore() should have already
7384 * set the link state as active
7386 if (ret || !ufshcd_is_link_active(hba))
7387 goto vendor_suspend;
7390 if (!ufshcd_is_ufs_dev_active(hba)) {
7391 ret = ufshcd_set_dev_pwr_mode(hba, UFS_ACTIVE_PWR_MODE);
7393 goto set_old_link_state;
7396 if (ufshcd_keep_autobkops_enabled_except_suspend(hba))
7397 ufshcd_enable_auto_bkops(hba);
7400 * If BKOPs operations are urgently needed at this moment then
7401 * keep auto-bkops enabled or else disable it.
7403 ufshcd_urgent_bkops(hba);
7405 hba->clk_gating.is_suspended = false;
7407 if (hba->clk_scaling.is_allowed)
7408 ufshcd_resume_clkscaling(hba);
7410 /* Schedule clock gating in case of no access to UFS device yet */
7411 ufshcd_release(hba);
7413 /* Enable Auto-Hibernate if configured */
7414 ufshcd_auto_hibern8_enable(hba);
7419 ufshcd_link_state_transition(hba, old_link_state, 0);
7421 ufshcd_vops_suspend(hba, pm_op);
7423 ufshcd_vreg_set_lpm(hba);
7424 disable_irq_and_vops_clks:
7425 ufshcd_disable_irq(hba);
7426 if (hba->clk_scaling.is_allowed)
7427 ufshcd_suspend_clkscaling(hba);
7428 ufshcd_setup_clocks(hba, false);
7430 hba->pm_op_in_progress = 0;
7435 * ufshcd_system_suspend - system suspend routine
7436 * @hba: per adapter instance
7438 * Check the description of ufshcd_suspend() function for more details.
7440 * Returns 0 for success and non-zero for failure
7442 int ufshcd_system_suspend(struct ufs_hba *hba)
7445 ktime_t start = ktime_get();
7447 if (!hba || !hba->is_powered)
7450 if ((ufs_get_pm_lvl_to_dev_pwr_mode(hba->spm_lvl) ==
7451 hba->curr_dev_pwr_mode) &&
7452 (ufs_get_pm_lvl_to_link_pwr_state(hba->spm_lvl) ==
7453 hba->uic_link_state))
7456 if (pm_runtime_suspended(hba->dev)) {
7458 * UFS device and/or UFS link low power states during runtime
7459 * suspend seems to be different than what is expected during
7460 * system suspend. Hence runtime resume the devic & link and
7461 * let the system suspend low power states to take effect.
7462 * TODO: If resume takes longer time, we might have optimize
7463 * it in future by not resuming everything if possible.
7465 ret = ufshcd_runtime_resume(hba);
7470 ret = ufshcd_suspend(hba, UFS_SYSTEM_PM);
7472 trace_ufshcd_system_suspend(dev_name(hba->dev), ret,
7473 ktime_to_us(ktime_sub(ktime_get(), start)),
7474 hba->curr_dev_pwr_mode, hba->uic_link_state);
7476 hba->is_sys_suspended = true;
7479 EXPORT_SYMBOL(ufshcd_system_suspend);
7482 * ufshcd_system_resume - system resume routine
7483 * @hba: per adapter instance
7485 * Returns 0 for success and non-zero for failure
7488 int ufshcd_system_resume(struct ufs_hba *hba)
7491 ktime_t start = ktime_get();
7496 if (!hba->is_powered || pm_runtime_suspended(hba->dev))
7498 * Let the runtime resume take care of resuming
7499 * if runtime suspended.
7503 ret = ufshcd_resume(hba, UFS_SYSTEM_PM);
7505 trace_ufshcd_system_resume(dev_name(hba->dev), ret,
7506 ktime_to_us(ktime_sub(ktime_get(), start)),
7507 hba->curr_dev_pwr_mode, hba->uic_link_state);
7510 EXPORT_SYMBOL(ufshcd_system_resume);
7513 * ufshcd_runtime_suspend - runtime suspend routine
7514 * @hba: per adapter instance
7516 * Check the description of ufshcd_suspend() function for more details.
7518 * Returns 0 for success and non-zero for failure
7520 int ufshcd_runtime_suspend(struct ufs_hba *hba)
7523 ktime_t start = ktime_get();
7528 if (!hba->is_powered)
7531 ret = ufshcd_suspend(hba, UFS_RUNTIME_PM);
7533 trace_ufshcd_runtime_suspend(dev_name(hba->dev), ret,
7534 ktime_to_us(ktime_sub(ktime_get(), start)),
7535 hba->curr_dev_pwr_mode, hba->uic_link_state);
7538 EXPORT_SYMBOL(ufshcd_runtime_suspend);
7541 * ufshcd_runtime_resume - runtime resume routine
7542 * @hba: per adapter instance
7544 * This function basically brings the UFS device, UniPro link and controller
7545 * to active state. Following operations are done in this function:
7547 * 1. Turn on all the controller related clocks
7548 * 2. Bring the UniPro link out of Hibernate state
7549 * 3. If UFS device is in sleep state, turn ON VCC rail and bring the UFS device
7551 * 4. If auto-bkops is enabled on the device, disable it.
7553 * So following would be the possible power state after this function return
7555 * S1: UFS device in Active state with VCC rail ON
7556 * UniPro link in Active state
7557 * All the UFS/UniPro controller clocks are ON
7559 * Returns 0 for success and non-zero for failure
7561 int ufshcd_runtime_resume(struct ufs_hba *hba)
7564 ktime_t start = ktime_get();
7569 if (!hba->is_powered)
7572 ret = ufshcd_resume(hba, UFS_RUNTIME_PM);
7574 trace_ufshcd_runtime_resume(dev_name(hba->dev), ret,
7575 ktime_to_us(ktime_sub(ktime_get(), start)),
7576 hba->curr_dev_pwr_mode, hba->uic_link_state);
7579 EXPORT_SYMBOL(ufshcd_runtime_resume);
7581 int ufshcd_runtime_idle(struct ufs_hba *hba)
7585 EXPORT_SYMBOL(ufshcd_runtime_idle);
7588 * ufshcd_shutdown - shutdown routine
7589 * @hba: per adapter instance
7591 * This function would power off both UFS device and UFS link.
7593 * Returns 0 always to allow force shutdown even in case of errors.
7595 int ufshcd_shutdown(struct ufs_hba *hba)
7599 if (ufshcd_is_ufs_dev_poweroff(hba) && ufshcd_is_link_off(hba))
7602 if (pm_runtime_suspended(hba->dev)) {
7603 ret = ufshcd_runtime_resume(hba);
7608 ret = ufshcd_suspend(hba, UFS_SHUTDOWN_PM);
7611 dev_err(hba->dev, "%s failed, err %d\n", __func__, ret);
7612 /* allow force shutdown even in case of errors */
7615 EXPORT_SYMBOL(ufshcd_shutdown);
7618 * ufshcd_remove - de-allocate SCSI host and host memory space
7619 * data structure memory
7620 * @hba: per adapter instance
7622 void ufshcd_remove(struct ufs_hba *hba)
7624 ufs_sysfs_remove_nodes(hba->dev);
7625 scsi_remove_host(hba->host);
7626 /* disable interrupts */
7627 ufshcd_disable_intr(hba, hba->intr_mask);
7628 ufshcd_hba_stop(hba, true);
7630 ufshcd_exit_clk_gating(hba);
7631 if (ufshcd_is_clkscaling_supported(hba))
7632 device_remove_file(hba->dev, &hba->clk_scaling.enable_attr);
7633 ufshcd_hba_exit(hba);
7635 EXPORT_SYMBOL_GPL(ufshcd_remove);
7638 * ufshcd_dealloc_host - deallocate Host Bus Adapter (HBA)
7639 * @hba: pointer to Host Bus Adapter (HBA)
7641 void ufshcd_dealloc_host(struct ufs_hba *hba)
7643 scsi_host_put(hba->host);
7645 EXPORT_SYMBOL_GPL(ufshcd_dealloc_host);
7648 * ufshcd_set_dma_mask - Set dma mask based on the controller
7649 * addressing capability
7650 * @hba: per adapter instance
7652 * Returns 0 for success, non-zero for failure
7654 static int ufshcd_set_dma_mask(struct ufs_hba *hba)
7656 if (hba->capabilities & MASK_64_ADDRESSING_SUPPORT) {
7657 if (!dma_set_mask_and_coherent(hba->dev, DMA_BIT_MASK(64)))
7660 return dma_set_mask_and_coherent(hba->dev, DMA_BIT_MASK(32));
7664 * ufshcd_alloc_host - allocate Host Bus Adapter (HBA)
7665 * @dev: pointer to device handle
7666 * @hba_handle: driver private handle
7667 * Returns 0 on success, non-zero value on failure
7669 int ufshcd_alloc_host(struct device *dev, struct ufs_hba **hba_handle)
7671 struct Scsi_Host *host;
7672 struct ufs_hba *hba;
7677 "Invalid memory reference for dev is NULL\n");
7682 host = scsi_host_alloc(&ufshcd_driver_template,
7683 sizeof(struct ufs_hba));
7685 dev_err(dev, "scsi_host_alloc failed\n");
7689 hba = shost_priv(host);
7694 INIT_LIST_HEAD(&hba->clk_list_head);
7699 EXPORT_SYMBOL(ufshcd_alloc_host);
7702 * ufshcd_init - Driver initialization routine
7703 * @hba: per-adapter instance
7704 * @mmio_base: base register address
7705 * @irq: Interrupt line of device
7706 * Returns 0 on success, non-zero value on failure
7708 int ufshcd_init(struct ufs_hba *hba, void __iomem *mmio_base, unsigned int irq)
7711 struct Scsi_Host *host = hba->host;
7712 struct device *dev = hba->dev;
7716 "Invalid memory reference for mmio_base is NULL\n");
7721 hba->mmio_base = mmio_base;
7724 /* Set descriptor lengths to specification defaults */
7725 ufshcd_def_desc_sizes(hba);
7727 err = ufshcd_hba_init(hba);
7731 /* Read capabilities registers */
7732 ufshcd_hba_capabilities(hba);
7734 /* Get UFS version supported by the controller */
7735 hba->ufs_version = ufshcd_get_ufs_version(hba);
7737 if ((hba->ufs_version != UFSHCI_VERSION_10) &&
7738 (hba->ufs_version != UFSHCI_VERSION_11) &&
7739 (hba->ufs_version != UFSHCI_VERSION_20) &&
7740 (hba->ufs_version != UFSHCI_VERSION_21))
7741 dev_err(hba->dev, "invalid UFS version 0x%x\n",
7744 /* Get Interrupt bit mask per version */
7745 hba->intr_mask = ufshcd_get_intr_mask(hba);
7747 err = ufshcd_set_dma_mask(hba);
7749 dev_err(hba->dev, "set dma mask failed\n");
7753 /* Allocate memory for host memory space */
7754 err = ufshcd_memory_alloc(hba);
7756 dev_err(hba->dev, "Memory allocation failed\n");
7761 ufshcd_host_memory_configure(hba);
7763 host->can_queue = hba->nutrs;
7764 host->cmd_per_lun = hba->nutrs;
7765 host->max_id = UFSHCD_MAX_ID;
7766 host->max_lun = UFS_MAX_LUNS;
7767 host->max_channel = UFSHCD_MAX_CHANNEL;
7768 host->unique_id = host->host_no;
7769 host->max_cmd_len = MAX_CDB_SIZE;
7771 hba->max_pwr_info.is_valid = false;
7773 /* Initailize wait queue for task management */
7774 init_waitqueue_head(&hba->tm_wq);
7775 init_waitqueue_head(&hba->tm_tag_wq);
7777 /* Initialize work queues */
7778 INIT_WORK(&hba->eh_work, ufshcd_err_handler);
7779 INIT_WORK(&hba->eeh_work, ufshcd_exception_event_handler);
7781 /* Initialize UIC command mutex */
7782 mutex_init(&hba->uic_cmd_mutex);
7784 /* Initialize mutex for device management commands */
7785 mutex_init(&hba->dev_cmd.lock);
7787 init_rwsem(&hba->clk_scaling_lock);
7789 /* Initialize device management tag acquire wait queue */
7790 init_waitqueue_head(&hba->dev_cmd.tag_wq);
7792 ufshcd_init_clk_gating(hba);
7795 * In order to avoid any spurious interrupt immediately after
7796 * registering UFS controller interrupt handler, clear any pending UFS
7797 * interrupt status and disable all the UFS interrupts.
7799 ufshcd_writel(hba, ufshcd_readl(hba, REG_INTERRUPT_STATUS),
7800 REG_INTERRUPT_STATUS);
7801 ufshcd_writel(hba, 0, REG_INTERRUPT_ENABLE);
7803 * Make sure that UFS interrupts are disabled and any pending interrupt
7804 * status is cleared before registering UFS interrupt handler.
7808 /* IRQ registration */
7809 err = devm_request_irq(dev, irq, ufshcd_intr, IRQF_SHARED, UFSHCD, hba);
7811 dev_err(hba->dev, "request irq failed\n");
7814 hba->is_irq_enabled = true;
7817 err = scsi_add_host(host, hba->dev);
7819 dev_err(hba->dev, "scsi_add_host failed\n");
7823 /* Host controller enable */
7824 err = ufshcd_hba_enable(hba);
7826 dev_err(hba->dev, "Host controller enable failed\n");
7827 ufshcd_print_host_regs(hba);
7828 ufshcd_print_host_state(hba);
7829 goto out_remove_scsi_host;
7832 if (ufshcd_is_clkscaling_supported(hba)) {
7833 char wq_name[sizeof("ufs_clkscaling_00")];
7835 INIT_WORK(&hba->clk_scaling.suspend_work,
7836 ufshcd_clk_scaling_suspend_work);
7837 INIT_WORK(&hba->clk_scaling.resume_work,
7838 ufshcd_clk_scaling_resume_work);
7840 snprintf(wq_name, sizeof(wq_name), "ufs_clkscaling_%d",
7842 hba->clk_scaling.workq = create_singlethread_workqueue(wq_name);
7844 ufshcd_clkscaling_init_sysfs(hba);
7848 * Set the default power management level for runtime and system PM.
7849 * Default power saving mode is to keep UFS link in Hibern8 state
7850 * and UFS device in sleep state.
7852 hba->rpm_lvl = ufs_get_desired_pm_lvl_for_dev_link_state(
7854 UIC_LINK_HIBERN8_STATE);
7855 hba->spm_lvl = ufs_get_desired_pm_lvl_for_dev_link_state(
7857 UIC_LINK_HIBERN8_STATE);
7859 /* Set the default auto-hiberate idle timer value to 150 ms */
7860 if (hba->capabilities & MASK_AUTO_HIBERN8_SUPPORT) {
7861 hba->ahit = FIELD_PREP(UFSHCI_AHIBERN8_TIMER_MASK, 150) |
7862 FIELD_PREP(UFSHCI_AHIBERN8_SCALE_MASK, 3);
7865 /* Hold auto suspend until async scan completes */
7866 pm_runtime_get_sync(dev);
7869 * We are assuming that device wasn't put in sleep/power-down
7870 * state exclusively during the boot stage before kernel.
7871 * This assumption helps avoid doing link startup twice during
7872 * ufshcd_probe_hba().
7874 ufshcd_set_ufs_dev_active(hba);
7876 async_schedule(ufshcd_async_scan, hba);
7877 ufs_sysfs_add_nodes(hba->dev);
7881 out_remove_scsi_host:
7882 scsi_remove_host(hba->host);
7884 ufshcd_exit_clk_gating(hba);
7886 hba->is_irq_enabled = false;
7887 ufshcd_hba_exit(hba);
7891 EXPORT_SYMBOL_GPL(ufshcd_init);
7893 MODULE_AUTHOR("Santosh Yaragnavi <santosh.sy@samsung.com>");
7894 MODULE_AUTHOR("Vinayak Holikatti <h.vinayak@samsung.com>");
7895 MODULE_DESCRIPTION("Generic UFS host controller driver Core");
7896 MODULE_LICENSE("GPL");
7897 MODULE_VERSION(UFSHCD_DRIVER_VERSION);