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 if (hba->quirks & UFSHCI_QUIRK_BROKEN_REQ_LIST_CLR)
647 ufshcd_writel(hba, (1 << pos), REG_UTP_TRANSFER_REQ_LIST_CLEAR);
649 ufshcd_writel(hba, ~(1 << pos),
650 REG_UTP_TRANSFER_REQ_LIST_CLEAR);
654 * ufshcd_utmrl_clear - Clear a bit in UTRMLCLR register
655 * @hba: per adapter instance
656 * @pos: position of the bit to be cleared
658 static inline void ufshcd_utmrl_clear(struct ufs_hba *hba, u32 pos)
660 if (hba->quirks & UFSHCI_QUIRK_BROKEN_REQ_LIST_CLR)
661 ufshcd_writel(hba, (1 << pos), REG_UTP_TASK_REQ_LIST_CLEAR);
663 ufshcd_writel(hba, ~(1 << pos), REG_UTP_TASK_REQ_LIST_CLEAR);
667 * ufshcd_outstanding_req_clear - Clear a bit in outstanding request field
668 * @hba: per adapter instance
669 * @tag: position of the bit to be cleared
671 static inline void ufshcd_outstanding_req_clear(struct ufs_hba *hba, int tag)
673 __clear_bit(tag, &hba->outstanding_reqs);
677 * ufshcd_get_lists_status - Check UCRDY, UTRLRDY and UTMRLRDY
678 * @reg: Register value of host controller status
680 * Returns integer, 0 on Success and positive value if failed
682 static inline int ufshcd_get_lists_status(u32 reg)
684 return !((reg & UFSHCD_STATUS_READY) == UFSHCD_STATUS_READY);
688 * ufshcd_get_uic_cmd_result - Get the UIC command result
689 * @hba: Pointer to adapter instance
691 * This function gets the result of UIC command completion
692 * Returns 0 on success, non zero value on error
694 static inline int ufshcd_get_uic_cmd_result(struct ufs_hba *hba)
696 return ufshcd_readl(hba, REG_UIC_COMMAND_ARG_2) &
697 MASK_UIC_COMMAND_RESULT;
701 * ufshcd_get_dme_attr_val - Get the value of attribute returned by UIC command
702 * @hba: Pointer to adapter instance
704 * This function gets UIC command argument3
705 * Returns 0 on success, non zero value on error
707 static inline u32 ufshcd_get_dme_attr_val(struct ufs_hba *hba)
709 return ufshcd_readl(hba, REG_UIC_COMMAND_ARG_3);
713 * ufshcd_get_req_rsp - returns the TR response transaction type
714 * @ucd_rsp_ptr: pointer to response UPIU
717 ufshcd_get_req_rsp(struct utp_upiu_rsp *ucd_rsp_ptr)
719 return be32_to_cpu(ucd_rsp_ptr->header.dword_0) >> 24;
723 * ufshcd_get_rsp_upiu_result - Get the result from response UPIU
724 * @ucd_rsp_ptr: pointer to response UPIU
726 * This function gets the response status and scsi_status from response UPIU
727 * Returns the response result code.
730 ufshcd_get_rsp_upiu_result(struct utp_upiu_rsp *ucd_rsp_ptr)
732 return be32_to_cpu(ucd_rsp_ptr->header.dword_1) & MASK_RSP_UPIU_RESULT;
736 * ufshcd_get_rsp_upiu_data_seg_len - Get the data segment length
738 * @ucd_rsp_ptr: pointer to response UPIU
740 * Return the data segment length.
742 static inline unsigned int
743 ufshcd_get_rsp_upiu_data_seg_len(struct utp_upiu_rsp *ucd_rsp_ptr)
745 return be32_to_cpu(ucd_rsp_ptr->header.dword_2) &
746 MASK_RSP_UPIU_DATA_SEG_LEN;
750 * ufshcd_is_exception_event - Check if the device raised an exception event
751 * @ucd_rsp_ptr: pointer to response UPIU
753 * The function checks if the device raised an exception event indicated in
754 * the Device Information field of response UPIU.
756 * Returns true if exception is raised, false otherwise.
758 static inline bool ufshcd_is_exception_event(struct utp_upiu_rsp *ucd_rsp_ptr)
760 return be32_to_cpu(ucd_rsp_ptr->header.dword_2) &
761 MASK_RSP_EXCEPTION_EVENT ? true : false;
765 * ufshcd_reset_intr_aggr - Reset interrupt aggregation values.
766 * @hba: per adapter instance
769 ufshcd_reset_intr_aggr(struct ufs_hba *hba)
771 ufshcd_writel(hba, INT_AGGR_ENABLE |
772 INT_AGGR_COUNTER_AND_TIMER_RESET,
773 REG_UTP_TRANSFER_REQ_INT_AGG_CONTROL);
777 * ufshcd_config_intr_aggr - Configure interrupt aggregation values.
778 * @hba: per adapter instance
779 * @cnt: Interrupt aggregation counter threshold
780 * @tmout: Interrupt aggregation timeout value
783 ufshcd_config_intr_aggr(struct ufs_hba *hba, u8 cnt, u8 tmout)
785 ufshcd_writel(hba, INT_AGGR_ENABLE | INT_AGGR_PARAM_WRITE |
786 INT_AGGR_COUNTER_THLD_VAL(cnt) |
787 INT_AGGR_TIMEOUT_VAL(tmout),
788 REG_UTP_TRANSFER_REQ_INT_AGG_CONTROL);
792 * ufshcd_disable_intr_aggr - Disables interrupt aggregation.
793 * @hba: per adapter instance
795 static inline void ufshcd_disable_intr_aggr(struct ufs_hba *hba)
797 ufshcd_writel(hba, 0, REG_UTP_TRANSFER_REQ_INT_AGG_CONTROL);
801 * ufshcd_enable_run_stop_reg - Enable run-stop registers,
802 * When run-stop registers are set to 1, it indicates the
803 * host controller that it can process the requests
804 * @hba: per adapter instance
806 static void ufshcd_enable_run_stop_reg(struct ufs_hba *hba)
808 ufshcd_writel(hba, UTP_TASK_REQ_LIST_RUN_STOP_BIT,
809 REG_UTP_TASK_REQ_LIST_RUN_STOP);
810 ufshcd_writel(hba, UTP_TRANSFER_REQ_LIST_RUN_STOP_BIT,
811 REG_UTP_TRANSFER_REQ_LIST_RUN_STOP);
815 * ufshcd_hba_start - Start controller initialization sequence
816 * @hba: per adapter instance
818 static inline void ufshcd_hba_start(struct ufs_hba *hba)
820 ufshcd_writel(hba, CONTROLLER_ENABLE, REG_CONTROLLER_ENABLE);
824 * ufshcd_is_hba_active - Get controller state
825 * @hba: per adapter instance
827 * Returns false if controller is active, true otherwise
829 static inline bool ufshcd_is_hba_active(struct ufs_hba *hba)
831 return (ufshcd_readl(hba, REG_CONTROLLER_ENABLE) & CONTROLLER_ENABLE)
835 u32 ufshcd_get_local_unipro_ver(struct ufs_hba *hba)
837 /* HCI version 1.0 and 1.1 supports UniPro 1.41 */
838 if ((hba->ufs_version == UFSHCI_VERSION_10) ||
839 (hba->ufs_version == UFSHCI_VERSION_11))
840 return UFS_UNIPRO_VER_1_41;
842 return UFS_UNIPRO_VER_1_6;
844 EXPORT_SYMBOL(ufshcd_get_local_unipro_ver);
846 static bool ufshcd_is_unipro_pa_params_tuning_req(struct ufs_hba *hba)
849 * If both host and device support UniPro ver1.6 or later, PA layer
850 * parameters tuning happens during link startup itself.
852 * We can manually tune PA layer parameters if either host or device
853 * doesn't support UniPro ver 1.6 or later. But to keep manual tuning
854 * logic simple, we will only do manual tuning if local unipro version
855 * doesn't support ver1.6 or later.
857 if (ufshcd_get_local_unipro_ver(hba) < UFS_UNIPRO_VER_1_6)
863 static int ufshcd_scale_clks(struct ufs_hba *hba, bool scale_up)
866 struct ufs_clk_info *clki;
867 struct list_head *head = &hba->clk_list_head;
868 ktime_t start = ktime_get();
869 bool clk_state_changed = false;
871 if (list_empty(head))
874 ret = ufshcd_vops_clk_scale_notify(hba, scale_up, PRE_CHANGE);
878 list_for_each_entry(clki, head, list) {
879 if (!IS_ERR_OR_NULL(clki->clk)) {
880 if (scale_up && clki->max_freq) {
881 if (clki->curr_freq == clki->max_freq)
884 clk_state_changed = true;
885 ret = clk_set_rate(clki->clk, clki->max_freq);
887 dev_err(hba->dev, "%s: %s clk set rate(%dHz) failed, %d\n",
888 __func__, clki->name,
889 clki->max_freq, ret);
892 trace_ufshcd_clk_scaling(dev_name(hba->dev),
893 "scaled up", clki->name,
897 clki->curr_freq = clki->max_freq;
899 } else if (!scale_up && clki->min_freq) {
900 if (clki->curr_freq == clki->min_freq)
903 clk_state_changed = true;
904 ret = clk_set_rate(clki->clk, clki->min_freq);
906 dev_err(hba->dev, "%s: %s clk set rate(%dHz) failed, %d\n",
907 __func__, clki->name,
908 clki->min_freq, ret);
911 trace_ufshcd_clk_scaling(dev_name(hba->dev),
912 "scaled down", clki->name,
915 clki->curr_freq = clki->min_freq;
918 dev_dbg(hba->dev, "%s: clk: %s, rate: %lu\n", __func__,
919 clki->name, clk_get_rate(clki->clk));
922 ret = ufshcd_vops_clk_scale_notify(hba, scale_up, POST_CHANGE);
925 if (clk_state_changed)
926 trace_ufshcd_profile_clk_scaling(dev_name(hba->dev),
927 (scale_up ? "up" : "down"),
928 ktime_to_us(ktime_sub(ktime_get(), start)), ret);
933 * ufshcd_is_devfreq_scaling_required - check if scaling is required or not
934 * @hba: per adapter instance
935 * @scale_up: True if scaling up and false if scaling down
937 * Returns true if scaling is required, false otherwise.
939 static bool ufshcd_is_devfreq_scaling_required(struct ufs_hba *hba,
942 struct ufs_clk_info *clki;
943 struct list_head *head = &hba->clk_list_head;
945 if (list_empty(head))
948 list_for_each_entry(clki, head, list) {
949 if (!IS_ERR_OR_NULL(clki->clk)) {
950 if (scale_up && clki->max_freq) {
951 if (clki->curr_freq == clki->max_freq)
954 } else if (!scale_up && clki->min_freq) {
955 if (clki->curr_freq == clki->min_freq)
965 static int ufshcd_wait_for_doorbell_clr(struct ufs_hba *hba,
972 bool timeout = false, do_last_check = false;
975 ufshcd_hold(hba, false);
976 spin_lock_irqsave(hba->host->host_lock, flags);
978 * Wait for all the outstanding tasks/transfer requests.
979 * Verify by checking the doorbell registers are clear.
983 if (hba->ufshcd_state != UFSHCD_STATE_OPERATIONAL) {
988 tm_doorbell = ufshcd_readl(hba, REG_UTP_TASK_REQ_DOOR_BELL);
989 tr_doorbell = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
990 if (!tm_doorbell && !tr_doorbell) {
993 } else if (do_last_check) {
997 spin_unlock_irqrestore(hba->host->host_lock, flags);
999 if (ktime_to_us(ktime_sub(ktime_get(), start)) >
1003 * We might have scheduled out for long time so make
1004 * sure to check if doorbells are cleared by this time
1007 do_last_check = true;
1009 spin_lock_irqsave(hba->host->host_lock, flags);
1010 } while (tm_doorbell || tr_doorbell);
1014 "%s: timedout waiting for doorbell to clear (tm=0x%x, tr=0x%x)\n",
1015 __func__, tm_doorbell, tr_doorbell);
1019 spin_unlock_irqrestore(hba->host->host_lock, flags);
1020 ufshcd_release(hba);
1025 * ufshcd_scale_gear - scale up/down UFS gear
1026 * @hba: per adapter instance
1027 * @scale_up: True for scaling up gear and false for scaling down
1029 * Returns 0 for success,
1030 * Returns -EBUSY if scaling can't happen at this time
1031 * Returns non-zero for any other errors
1033 static int ufshcd_scale_gear(struct ufs_hba *hba, bool scale_up)
1035 #define UFS_MIN_GEAR_TO_SCALE_DOWN UFS_HS_G1
1037 struct ufs_pa_layer_attr new_pwr_info;
1040 memcpy(&new_pwr_info, &hba->clk_scaling.saved_pwr_info.info,
1041 sizeof(struct ufs_pa_layer_attr));
1043 memcpy(&new_pwr_info, &hba->pwr_info,
1044 sizeof(struct ufs_pa_layer_attr));
1046 if (hba->pwr_info.gear_tx > UFS_MIN_GEAR_TO_SCALE_DOWN
1047 || hba->pwr_info.gear_rx > UFS_MIN_GEAR_TO_SCALE_DOWN) {
1048 /* save the current power mode */
1049 memcpy(&hba->clk_scaling.saved_pwr_info.info,
1051 sizeof(struct ufs_pa_layer_attr));
1053 /* scale down gear */
1054 new_pwr_info.gear_tx = UFS_MIN_GEAR_TO_SCALE_DOWN;
1055 new_pwr_info.gear_rx = UFS_MIN_GEAR_TO_SCALE_DOWN;
1059 /* check if the power mode needs to be changed or not? */
1060 ret = ufshcd_change_power_mode(hba, &new_pwr_info);
1063 dev_err(hba->dev, "%s: failed err %d, old gear: (tx %d rx %d), new gear: (tx %d rx %d)",
1065 hba->pwr_info.gear_tx, hba->pwr_info.gear_rx,
1066 new_pwr_info.gear_tx, new_pwr_info.gear_rx);
1071 static int ufshcd_clock_scaling_prepare(struct ufs_hba *hba)
1073 #define DOORBELL_CLR_TOUT_US (1000 * 1000) /* 1 sec */
1076 * make sure that there are no outstanding requests when
1077 * clock scaling is in progress
1079 scsi_block_requests(hba->host);
1080 down_write(&hba->clk_scaling_lock);
1081 if (ufshcd_wait_for_doorbell_clr(hba, DOORBELL_CLR_TOUT_US)) {
1083 up_write(&hba->clk_scaling_lock);
1084 scsi_unblock_requests(hba->host);
1090 static void ufshcd_clock_scaling_unprepare(struct ufs_hba *hba)
1092 up_write(&hba->clk_scaling_lock);
1093 scsi_unblock_requests(hba->host);
1097 * ufshcd_devfreq_scale - scale up/down UFS clocks and gear
1098 * @hba: per adapter instance
1099 * @scale_up: True for scaling up and false for scalin down
1101 * Returns 0 for success,
1102 * Returns -EBUSY if scaling can't happen at this time
1103 * Returns non-zero for any other errors
1105 static int ufshcd_devfreq_scale(struct ufs_hba *hba, bool scale_up)
1109 /* let's not get into low power until clock scaling is completed */
1110 ufshcd_hold(hba, false);
1112 ret = ufshcd_clock_scaling_prepare(hba);
1116 /* scale down the gear before scaling down clocks */
1118 ret = ufshcd_scale_gear(hba, false);
1123 ret = ufshcd_scale_clks(hba, scale_up);
1126 ufshcd_scale_gear(hba, true);
1130 /* scale up the gear after scaling up clocks */
1132 ret = ufshcd_scale_gear(hba, true);
1134 ufshcd_scale_clks(hba, false);
1139 ret = ufshcd_vops_clk_scale_notify(hba, scale_up, POST_CHANGE);
1142 ufshcd_clock_scaling_unprepare(hba);
1143 ufshcd_release(hba);
1147 static void ufshcd_clk_scaling_suspend_work(struct work_struct *work)
1149 struct ufs_hba *hba = container_of(work, struct ufs_hba,
1150 clk_scaling.suspend_work);
1151 unsigned long irq_flags;
1153 spin_lock_irqsave(hba->host->host_lock, irq_flags);
1154 if (hba->clk_scaling.active_reqs || hba->clk_scaling.is_suspended) {
1155 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1158 hba->clk_scaling.is_suspended = true;
1159 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1161 __ufshcd_suspend_clkscaling(hba);
1164 static void ufshcd_clk_scaling_resume_work(struct work_struct *work)
1166 struct ufs_hba *hba = container_of(work, struct ufs_hba,
1167 clk_scaling.resume_work);
1168 unsigned long irq_flags;
1170 spin_lock_irqsave(hba->host->host_lock, irq_flags);
1171 if (!hba->clk_scaling.is_suspended) {
1172 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1175 hba->clk_scaling.is_suspended = false;
1176 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1178 devfreq_resume_device(hba->devfreq);
1181 static int ufshcd_devfreq_target(struct device *dev,
1182 unsigned long *freq, u32 flags)
1185 struct ufs_hba *hba = dev_get_drvdata(dev);
1187 bool scale_up, sched_clk_scaling_suspend_work = false;
1188 unsigned long irq_flags;
1190 if (!ufshcd_is_clkscaling_supported(hba))
1193 if ((*freq > 0) && (*freq < UINT_MAX)) {
1194 dev_err(hba->dev, "%s: invalid freq = %lu\n", __func__, *freq);
1198 spin_lock_irqsave(hba->host->host_lock, irq_flags);
1199 if (ufshcd_eh_in_progress(hba)) {
1200 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1204 if (!hba->clk_scaling.active_reqs)
1205 sched_clk_scaling_suspend_work = true;
1207 scale_up = (*freq == UINT_MAX) ? true : false;
1208 if (!ufshcd_is_devfreq_scaling_required(hba, scale_up)) {
1209 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1211 goto out; /* no state change required */
1213 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1215 start = ktime_get();
1216 ret = ufshcd_devfreq_scale(hba, scale_up);
1218 trace_ufshcd_profile_clk_scaling(dev_name(hba->dev),
1219 (scale_up ? "up" : "down"),
1220 ktime_to_us(ktime_sub(ktime_get(), start)), ret);
1223 if (sched_clk_scaling_suspend_work)
1224 queue_work(hba->clk_scaling.workq,
1225 &hba->clk_scaling.suspend_work);
1231 static int ufshcd_devfreq_get_dev_status(struct device *dev,
1232 struct devfreq_dev_status *stat)
1234 struct ufs_hba *hba = dev_get_drvdata(dev);
1235 struct ufs_clk_scaling *scaling = &hba->clk_scaling;
1236 unsigned long flags;
1238 if (!ufshcd_is_clkscaling_supported(hba))
1241 memset(stat, 0, sizeof(*stat));
1243 spin_lock_irqsave(hba->host->host_lock, flags);
1244 if (!scaling->window_start_t)
1247 if (scaling->is_busy_started)
1248 scaling->tot_busy_t += ktime_to_us(ktime_sub(ktime_get(),
1249 scaling->busy_start_t));
1251 stat->total_time = jiffies_to_usecs((long)jiffies -
1252 (long)scaling->window_start_t);
1253 stat->busy_time = scaling->tot_busy_t;
1255 scaling->window_start_t = jiffies;
1256 scaling->tot_busy_t = 0;
1258 if (hba->outstanding_reqs) {
1259 scaling->busy_start_t = ktime_get();
1260 scaling->is_busy_started = true;
1262 scaling->busy_start_t = 0;
1263 scaling->is_busy_started = false;
1265 spin_unlock_irqrestore(hba->host->host_lock, flags);
1269 static struct devfreq_dev_profile ufs_devfreq_profile = {
1271 .target = ufshcd_devfreq_target,
1272 .get_dev_status = ufshcd_devfreq_get_dev_status,
1275 static void __ufshcd_suspend_clkscaling(struct ufs_hba *hba)
1277 unsigned long flags;
1279 devfreq_suspend_device(hba->devfreq);
1280 spin_lock_irqsave(hba->host->host_lock, flags);
1281 hba->clk_scaling.window_start_t = 0;
1282 spin_unlock_irqrestore(hba->host->host_lock, flags);
1285 static void ufshcd_suspend_clkscaling(struct ufs_hba *hba)
1287 unsigned long flags;
1288 bool suspend = false;
1290 if (!ufshcd_is_clkscaling_supported(hba))
1293 spin_lock_irqsave(hba->host->host_lock, flags);
1294 if (!hba->clk_scaling.is_suspended) {
1296 hba->clk_scaling.is_suspended = true;
1298 spin_unlock_irqrestore(hba->host->host_lock, flags);
1301 __ufshcd_suspend_clkscaling(hba);
1304 static void ufshcd_resume_clkscaling(struct ufs_hba *hba)
1306 unsigned long flags;
1307 bool resume = false;
1309 if (!ufshcd_is_clkscaling_supported(hba))
1312 spin_lock_irqsave(hba->host->host_lock, flags);
1313 if (hba->clk_scaling.is_suspended) {
1315 hba->clk_scaling.is_suspended = false;
1317 spin_unlock_irqrestore(hba->host->host_lock, flags);
1320 devfreq_resume_device(hba->devfreq);
1323 static ssize_t ufshcd_clkscale_enable_show(struct device *dev,
1324 struct device_attribute *attr, char *buf)
1326 struct ufs_hba *hba = dev_get_drvdata(dev);
1328 return snprintf(buf, PAGE_SIZE, "%d\n", hba->clk_scaling.is_allowed);
1331 static ssize_t ufshcd_clkscale_enable_store(struct device *dev,
1332 struct device_attribute *attr, const char *buf, size_t count)
1334 struct ufs_hba *hba = dev_get_drvdata(dev);
1338 if (kstrtou32(buf, 0, &value))
1342 if (value == hba->clk_scaling.is_allowed)
1345 pm_runtime_get_sync(hba->dev);
1346 ufshcd_hold(hba, false);
1348 cancel_work_sync(&hba->clk_scaling.suspend_work);
1349 cancel_work_sync(&hba->clk_scaling.resume_work);
1351 hba->clk_scaling.is_allowed = value;
1354 ufshcd_resume_clkscaling(hba);
1356 ufshcd_suspend_clkscaling(hba);
1357 err = ufshcd_devfreq_scale(hba, true);
1359 dev_err(hba->dev, "%s: failed to scale clocks up %d\n",
1363 ufshcd_release(hba);
1364 pm_runtime_put_sync(hba->dev);
1369 static void ufshcd_clkscaling_init_sysfs(struct ufs_hba *hba)
1371 hba->clk_scaling.enable_attr.show = ufshcd_clkscale_enable_show;
1372 hba->clk_scaling.enable_attr.store = ufshcd_clkscale_enable_store;
1373 sysfs_attr_init(&hba->clk_scaling.enable_attr.attr);
1374 hba->clk_scaling.enable_attr.attr.name = "clkscale_enable";
1375 hba->clk_scaling.enable_attr.attr.mode = 0644;
1376 if (device_create_file(hba->dev, &hba->clk_scaling.enable_attr))
1377 dev_err(hba->dev, "Failed to create sysfs for clkscale_enable\n");
1380 static void ufshcd_ungate_work(struct work_struct *work)
1383 unsigned long flags;
1384 struct ufs_hba *hba = container_of(work, struct ufs_hba,
1385 clk_gating.ungate_work);
1387 cancel_delayed_work_sync(&hba->clk_gating.gate_work);
1389 spin_lock_irqsave(hba->host->host_lock, flags);
1390 if (hba->clk_gating.state == CLKS_ON) {
1391 spin_unlock_irqrestore(hba->host->host_lock, flags);
1395 spin_unlock_irqrestore(hba->host->host_lock, flags);
1396 ufshcd_setup_clocks(hba, true);
1398 /* Exit from hibern8 */
1399 if (ufshcd_can_hibern8_during_gating(hba)) {
1400 /* Prevent gating in this path */
1401 hba->clk_gating.is_suspended = true;
1402 if (ufshcd_is_link_hibern8(hba)) {
1403 ret = ufshcd_uic_hibern8_exit(hba);
1405 dev_err(hba->dev, "%s: hibern8 exit failed %d\n",
1408 ufshcd_set_link_active(hba);
1410 hba->clk_gating.is_suspended = false;
1413 scsi_unblock_requests(hba->host);
1417 * ufshcd_hold - Enable clocks that were gated earlier due to ufshcd_release.
1418 * Also, exit from hibern8 mode and set the link as active.
1419 * @hba: per adapter instance
1420 * @async: This indicates whether caller should ungate clocks asynchronously.
1422 int ufshcd_hold(struct ufs_hba *hba, bool async)
1425 unsigned long flags;
1427 if (!ufshcd_is_clkgating_allowed(hba))
1429 spin_lock_irqsave(hba->host->host_lock, flags);
1430 hba->clk_gating.active_reqs++;
1432 if (ufshcd_eh_in_progress(hba)) {
1433 spin_unlock_irqrestore(hba->host->host_lock, flags);
1438 switch (hba->clk_gating.state) {
1441 * Wait for the ungate work to complete if in progress.
1442 * Though the clocks may be in ON state, the link could
1443 * still be in hibner8 state if hibern8 is allowed
1444 * during clock gating.
1445 * Make sure we exit hibern8 state also in addition to
1448 if (ufshcd_can_hibern8_during_gating(hba) &&
1449 ufshcd_is_link_hibern8(hba)) {
1450 spin_unlock_irqrestore(hba->host->host_lock, flags);
1451 flush_work(&hba->clk_gating.ungate_work);
1452 spin_lock_irqsave(hba->host->host_lock, flags);
1457 if (cancel_delayed_work(&hba->clk_gating.gate_work)) {
1458 hba->clk_gating.state = CLKS_ON;
1459 trace_ufshcd_clk_gating(dev_name(hba->dev),
1460 hba->clk_gating.state);
1464 * If we are here, it means gating work is either done or
1465 * currently running. Hence, fall through to cancel gating
1466 * work and to enable clocks.
1469 scsi_block_requests(hba->host);
1470 hba->clk_gating.state = REQ_CLKS_ON;
1471 trace_ufshcd_clk_gating(dev_name(hba->dev),
1472 hba->clk_gating.state);
1473 schedule_work(&hba->clk_gating.ungate_work);
1475 * fall through to check if we should wait for this
1476 * work to be done or not.
1481 hba->clk_gating.active_reqs--;
1485 spin_unlock_irqrestore(hba->host->host_lock, flags);
1486 flush_work(&hba->clk_gating.ungate_work);
1487 /* Make sure state is CLKS_ON before returning */
1488 spin_lock_irqsave(hba->host->host_lock, flags);
1491 dev_err(hba->dev, "%s: clk gating is in invalid state %d\n",
1492 __func__, hba->clk_gating.state);
1495 spin_unlock_irqrestore(hba->host->host_lock, flags);
1499 EXPORT_SYMBOL_GPL(ufshcd_hold);
1501 static void ufshcd_gate_work(struct work_struct *work)
1503 struct ufs_hba *hba = container_of(work, struct ufs_hba,
1504 clk_gating.gate_work.work);
1505 unsigned long flags;
1507 spin_lock_irqsave(hba->host->host_lock, flags);
1509 * In case you are here to cancel this work the gating state
1510 * would be marked as REQ_CLKS_ON. In this case save time by
1511 * skipping the gating work and exit after changing the clock
1514 if (hba->clk_gating.is_suspended ||
1515 (hba->clk_gating.state == REQ_CLKS_ON)) {
1516 hba->clk_gating.state = CLKS_ON;
1517 trace_ufshcd_clk_gating(dev_name(hba->dev),
1518 hba->clk_gating.state);
1522 if (hba->clk_gating.active_reqs
1523 || hba->ufshcd_state != UFSHCD_STATE_OPERATIONAL
1524 || hba->lrb_in_use || hba->outstanding_tasks
1525 || hba->active_uic_cmd || hba->uic_async_done)
1528 spin_unlock_irqrestore(hba->host->host_lock, flags);
1530 /* put the link into hibern8 mode before turning off clocks */
1531 if (ufshcd_can_hibern8_during_gating(hba)) {
1532 if (ufshcd_uic_hibern8_enter(hba)) {
1533 hba->clk_gating.state = CLKS_ON;
1534 trace_ufshcd_clk_gating(dev_name(hba->dev),
1535 hba->clk_gating.state);
1538 ufshcd_set_link_hibern8(hba);
1541 if (!ufshcd_is_link_active(hba))
1542 ufshcd_setup_clocks(hba, false);
1544 /* If link is active, device ref_clk can't be switched off */
1545 __ufshcd_setup_clocks(hba, false, true);
1548 * In case you are here to cancel this work the gating state
1549 * would be marked as REQ_CLKS_ON. In this case keep the state
1550 * as REQ_CLKS_ON which would anyway imply that clocks are off
1551 * and a request to turn them on is pending. By doing this way,
1552 * we keep the state machine in tact and this would ultimately
1553 * prevent from doing cancel work multiple times when there are
1554 * new requests arriving before the current cancel work is done.
1556 spin_lock_irqsave(hba->host->host_lock, flags);
1557 if (hba->clk_gating.state == REQ_CLKS_OFF) {
1558 hba->clk_gating.state = CLKS_OFF;
1559 trace_ufshcd_clk_gating(dev_name(hba->dev),
1560 hba->clk_gating.state);
1563 spin_unlock_irqrestore(hba->host->host_lock, flags);
1568 /* host lock must be held before calling this variant */
1569 static void __ufshcd_release(struct ufs_hba *hba)
1571 if (!ufshcd_is_clkgating_allowed(hba))
1574 hba->clk_gating.active_reqs--;
1576 if (hba->clk_gating.active_reqs || hba->clk_gating.is_suspended
1577 || hba->ufshcd_state != UFSHCD_STATE_OPERATIONAL
1578 || hba->lrb_in_use || hba->outstanding_tasks
1579 || hba->active_uic_cmd || hba->uic_async_done
1580 || ufshcd_eh_in_progress(hba))
1583 hba->clk_gating.state = REQ_CLKS_OFF;
1584 trace_ufshcd_clk_gating(dev_name(hba->dev), hba->clk_gating.state);
1585 schedule_delayed_work(&hba->clk_gating.gate_work,
1586 msecs_to_jiffies(hba->clk_gating.delay_ms));
1589 void ufshcd_release(struct ufs_hba *hba)
1591 unsigned long flags;
1593 spin_lock_irqsave(hba->host->host_lock, flags);
1594 __ufshcd_release(hba);
1595 spin_unlock_irqrestore(hba->host->host_lock, flags);
1597 EXPORT_SYMBOL_GPL(ufshcd_release);
1599 static ssize_t ufshcd_clkgate_delay_show(struct device *dev,
1600 struct device_attribute *attr, char *buf)
1602 struct ufs_hba *hba = dev_get_drvdata(dev);
1604 return snprintf(buf, PAGE_SIZE, "%lu\n", hba->clk_gating.delay_ms);
1607 static ssize_t ufshcd_clkgate_delay_store(struct device *dev,
1608 struct device_attribute *attr, const char *buf, size_t count)
1610 struct ufs_hba *hba = dev_get_drvdata(dev);
1611 unsigned long flags, value;
1613 if (kstrtoul(buf, 0, &value))
1616 spin_lock_irqsave(hba->host->host_lock, flags);
1617 hba->clk_gating.delay_ms = value;
1618 spin_unlock_irqrestore(hba->host->host_lock, flags);
1622 static ssize_t ufshcd_clkgate_enable_show(struct device *dev,
1623 struct device_attribute *attr, char *buf)
1625 struct ufs_hba *hba = dev_get_drvdata(dev);
1627 return snprintf(buf, PAGE_SIZE, "%d\n", hba->clk_gating.is_enabled);
1630 static ssize_t ufshcd_clkgate_enable_store(struct device *dev,
1631 struct device_attribute *attr, const char *buf, size_t count)
1633 struct ufs_hba *hba = dev_get_drvdata(dev);
1634 unsigned long flags;
1637 if (kstrtou32(buf, 0, &value))
1641 if (value == hba->clk_gating.is_enabled)
1645 ufshcd_release(hba);
1647 spin_lock_irqsave(hba->host->host_lock, flags);
1648 hba->clk_gating.active_reqs++;
1649 spin_unlock_irqrestore(hba->host->host_lock, flags);
1652 hba->clk_gating.is_enabled = value;
1657 static void ufshcd_init_clk_gating(struct ufs_hba *hba)
1659 if (!ufshcd_is_clkgating_allowed(hba))
1662 hba->clk_gating.delay_ms = 150;
1663 INIT_DELAYED_WORK(&hba->clk_gating.gate_work, ufshcd_gate_work);
1664 INIT_WORK(&hba->clk_gating.ungate_work, ufshcd_ungate_work);
1666 hba->clk_gating.is_enabled = true;
1668 hba->clk_gating.delay_attr.show = ufshcd_clkgate_delay_show;
1669 hba->clk_gating.delay_attr.store = ufshcd_clkgate_delay_store;
1670 sysfs_attr_init(&hba->clk_gating.delay_attr.attr);
1671 hba->clk_gating.delay_attr.attr.name = "clkgate_delay_ms";
1672 hba->clk_gating.delay_attr.attr.mode = 0644;
1673 if (device_create_file(hba->dev, &hba->clk_gating.delay_attr))
1674 dev_err(hba->dev, "Failed to create sysfs for clkgate_delay\n");
1676 hba->clk_gating.enable_attr.show = ufshcd_clkgate_enable_show;
1677 hba->clk_gating.enable_attr.store = ufshcd_clkgate_enable_store;
1678 sysfs_attr_init(&hba->clk_gating.enable_attr.attr);
1679 hba->clk_gating.enable_attr.attr.name = "clkgate_enable";
1680 hba->clk_gating.enable_attr.attr.mode = 0644;
1681 if (device_create_file(hba->dev, &hba->clk_gating.enable_attr))
1682 dev_err(hba->dev, "Failed to create sysfs for clkgate_enable\n");
1685 static void ufshcd_exit_clk_gating(struct ufs_hba *hba)
1687 if (!ufshcd_is_clkgating_allowed(hba))
1689 device_remove_file(hba->dev, &hba->clk_gating.delay_attr);
1690 device_remove_file(hba->dev, &hba->clk_gating.enable_attr);
1691 cancel_work_sync(&hba->clk_gating.ungate_work);
1692 cancel_delayed_work_sync(&hba->clk_gating.gate_work);
1695 /* Must be called with host lock acquired */
1696 static void ufshcd_clk_scaling_start_busy(struct ufs_hba *hba)
1698 bool queue_resume_work = false;
1700 if (!ufshcd_is_clkscaling_supported(hba))
1703 if (!hba->clk_scaling.active_reqs++)
1704 queue_resume_work = true;
1706 if (!hba->clk_scaling.is_allowed || hba->pm_op_in_progress)
1709 if (queue_resume_work)
1710 queue_work(hba->clk_scaling.workq,
1711 &hba->clk_scaling.resume_work);
1713 if (!hba->clk_scaling.window_start_t) {
1714 hba->clk_scaling.window_start_t = jiffies;
1715 hba->clk_scaling.tot_busy_t = 0;
1716 hba->clk_scaling.is_busy_started = false;
1719 if (!hba->clk_scaling.is_busy_started) {
1720 hba->clk_scaling.busy_start_t = ktime_get();
1721 hba->clk_scaling.is_busy_started = true;
1725 static void ufshcd_clk_scaling_update_busy(struct ufs_hba *hba)
1727 struct ufs_clk_scaling *scaling = &hba->clk_scaling;
1729 if (!ufshcd_is_clkscaling_supported(hba))
1732 if (!hba->outstanding_reqs && scaling->is_busy_started) {
1733 scaling->tot_busy_t += ktime_to_us(ktime_sub(ktime_get(),
1734 scaling->busy_start_t));
1735 scaling->busy_start_t = 0;
1736 scaling->is_busy_started = false;
1740 * ufshcd_send_command - Send SCSI or device management commands
1741 * @hba: per adapter instance
1742 * @task_tag: Task tag of the command
1745 void ufshcd_send_command(struct ufs_hba *hba, unsigned int task_tag)
1747 hba->lrb[task_tag].issue_time_stamp = ktime_get();
1748 hba->lrb[task_tag].compl_time_stamp = ktime_set(0, 0);
1749 ufshcd_clk_scaling_start_busy(hba);
1750 __set_bit(task_tag, &hba->outstanding_reqs);
1751 ufshcd_writel(hba, 1 << task_tag, REG_UTP_TRANSFER_REQ_DOOR_BELL);
1752 /* Make sure that doorbell is committed immediately */
1754 ufshcd_add_command_trace(hba, task_tag, "send");
1758 * ufshcd_copy_sense_data - Copy sense data in case of check condition
1759 * @lrbp: pointer to local reference block
1761 static inline void ufshcd_copy_sense_data(struct ufshcd_lrb *lrbp)
1764 if (lrbp->sense_buffer &&
1765 ufshcd_get_rsp_upiu_data_seg_len(lrbp->ucd_rsp_ptr)) {
1768 len = be16_to_cpu(lrbp->ucd_rsp_ptr->sr.sense_data_len);
1769 len_to_copy = min_t(int, RESPONSE_UPIU_SENSE_DATA_LENGTH, len);
1771 memcpy(lrbp->sense_buffer,
1772 lrbp->ucd_rsp_ptr->sr.sense_data,
1773 min_t(int, len_to_copy, UFSHCD_REQ_SENSE_SIZE));
1778 * ufshcd_copy_query_response() - Copy the Query Response and the data
1780 * @hba: per adapter instance
1781 * @lrbp: pointer to local reference block
1784 int ufshcd_copy_query_response(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
1786 struct ufs_query_res *query_res = &hba->dev_cmd.query.response;
1788 memcpy(&query_res->upiu_res, &lrbp->ucd_rsp_ptr->qr, QUERY_OSF_SIZE);
1790 /* Get the descriptor */
1791 if (lrbp->ucd_rsp_ptr->qr.opcode == UPIU_QUERY_OPCODE_READ_DESC) {
1792 u8 *descp = (u8 *)lrbp->ucd_rsp_ptr +
1793 GENERAL_UPIU_REQUEST_SIZE;
1797 /* data segment length */
1798 resp_len = be32_to_cpu(lrbp->ucd_rsp_ptr->header.dword_2) &
1799 MASK_QUERY_DATA_SEG_LEN;
1800 buf_len = be16_to_cpu(
1801 hba->dev_cmd.query.request.upiu_req.length);
1802 if (likely(buf_len >= resp_len)) {
1803 memcpy(hba->dev_cmd.query.descriptor, descp, resp_len);
1806 "%s: Response size is bigger than buffer",
1816 * ufshcd_hba_capabilities - Read controller capabilities
1817 * @hba: per adapter instance
1819 static inline void ufshcd_hba_capabilities(struct ufs_hba *hba)
1821 hba->capabilities = ufshcd_readl(hba, REG_CONTROLLER_CAPABILITIES);
1823 /* nutrs and nutmrs are 0 based values */
1824 hba->nutrs = (hba->capabilities & MASK_TRANSFER_REQUESTS_SLOTS) + 1;
1826 ((hba->capabilities & MASK_TASK_MANAGEMENT_REQUEST_SLOTS) >> 16) + 1;
1830 * ufshcd_ready_for_uic_cmd - Check if controller is ready
1831 * to accept UIC commands
1832 * @hba: per adapter instance
1833 * Return true on success, else false
1835 static inline bool ufshcd_ready_for_uic_cmd(struct ufs_hba *hba)
1837 if (ufshcd_readl(hba, REG_CONTROLLER_STATUS) & UIC_COMMAND_READY)
1844 * ufshcd_get_upmcrs - Get the power mode change request status
1845 * @hba: Pointer to adapter instance
1847 * This function gets the UPMCRS field of HCS register
1848 * Returns value of UPMCRS field
1850 static inline u8 ufshcd_get_upmcrs(struct ufs_hba *hba)
1852 return (ufshcd_readl(hba, REG_CONTROLLER_STATUS) >> 8) & 0x7;
1856 * ufshcd_dispatch_uic_cmd - Dispatch UIC commands to unipro layers
1857 * @hba: per adapter instance
1858 * @uic_cmd: UIC command
1860 * Mutex must be held.
1863 ufshcd_dispatch_uic_cmd(struct ufs_hba *hba, struct uic_command *uic_cmd)
1865 WARN_ON(hba->active_uic_cmd);
1867 hba->active_uic_cmd = uic_cmd;
1870 ufshcd_writel(hba, uic_cmd->argument1, REG_UIC_COMMAND_ARG_1);
1871 ufshcd_writel(hba, uic_cmd->argument2, REG_UIC_COMMAND_ARG_2);
1872 ufshcd_writel(hba, uic_cmd->argument3, REG_UIC_COMMAND_ARG_3);
1875 ufshcd_writel(hba, uic_cmd->command & COMMAND_OPCODE_MASK,
1880 * ufshcd_wait_for_uic_cmd - Wait complectioin of UIC command
1881 * @hba: per adapter instance
1882 * @uic_cmd: UIC command
1884 * Must be called with mutex held.
1885 * Returns 0 only if success.
1888 ufshcd_wait_for_uic_cmd(struct ufs_hba *hba, struct uic_command *uic_cmd)
1891 unsigned long flags;
1893 if (wait_for_completion_timeout(&uic_cmd->done,
1894 msecs_to_jiffies(UIC_CMD_TIMEOUT)))
1895 ret = uic_cmd->argument2 & MASK_UIC_COMMAND_RESULT;
1899 spin_lock_irqsave(hba->host->host_lock, flags);
1900 hba->active_uic_cmd = NULL;
1901 spin_unlock_irqrestore(hba->host->host_lock, flags);
1907 * __ufshcd_send_uic_cmd - Send UIC commands and retrieve the result
1908 * @hba: per adapter instance
1909 * @uic_cmd: UIC command
1910 * @completion: initialize the completion only if this is set to true
1912 * Identical to ufshcd_send_uic_cmd() expect mutex. Must be called
1913 * with mutex held and host_lock locked.
1914 * Returns 0 only if success.
1917 __ufshcd_send_uic_cmd(struct ufs_hba *hba, struct uic_command *uic_cmd,
1920 if (!ufshcd_ready_for_uic_cmd(hba)) {
1922 "Controller not ready to accept UIC commands\n");
1927 init_completion(&uic_cmd->done);
1929 ufshcd_dispatch_uic_cmd(hba, uic_cmd);
1935 * ufshcd_send_uic_cmd - Send UIC commands and retrieve the result
1936 * @hba: per adapter instance
1937 * @uic_cmd: UIC command
1939 * Returns 0 only if success.
1942 ufshcd_send_uic_cmd(struct ufs_hba *hba, struct uic_command *uic_cmd)
1945 unsigned long flags;
1947 ufshcd_hold(hba, false);
1948 mutex_lock(&hba->uic_cmd_mutex);
1949 ufshcd_add_delay_before_dme_cmd(hba);
1951 spin_lock_irqsave(hba->host->host_lock, flags);
1952 ret = __ufshcd_send_uic_cmd(hba, uic_cmd, true);
1953 spin_unlock_irqrestore(hba->host->host_lock, flags);
1955 ret = ufshcd_wait_for_uic_cmd(hba, uic_cmd);
1957 mutex_unlock(&hba->uic_cmd_mutex);
1959 ufshcd_release(hba);
1964 * ufshcd_map_sg - Map scatter-gather list to prdt
1965 * @hba: per adapter instance
1966 * @lrbp: pointer to local reference block
1968 * Returns 0 in case of success, non-zero value in case of failure
1970 static int ufshcd_map_sg(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
1972 struct ufshcd_sg_entry *prd_table;
1973 struct scatterlist *sg;
1974 struct scsi_cmnd *cmd;
1979 sg_segments = scsi_dma_map(cmd);
1980 if (sg_segments < 0)
1984 if (hba->quirks & UFSHCD_QUIRK_PRDT_BYTE_GRAN)
1985 lrbp->utr_descriptor_ptr->prd_table_length =
1986 cpu_to_le16((u16)(sg_segments *
1987 sizeof(struct ufshcd_sg_entry)));
1989 lrbp->utr_descriptor_ptr->prd_table_length =
1990 cpu_to_le16((u16) (sg_segments));
1992 prd_table = (struct ufshcd_sg_entry *)lrbp->ucd_prdt_ptr;
1994 scsi_for_each_sg(cmd, sg, sg_segments, i) {
1996 cpu_to_le32(((u32) sg_dma_len(sg))-1);
1997 prd_table[i].base_addr =
1998 cpu_to_le32(lower_32_bits(sg->dma_address));
1999 prd_table[i].upper_addr =
2000 cpu_to_le32(upper_32_bits(sg->dma_address));
2001 prd_table[i].reserved = 0;
2004 lrbp->utr_descriptor_ptr->prd_table_length = 0;
2011 * ufshcd_enable_intr - enable interrupts
2012 * @hba: per adapter instance
2013 * @intrs: interrupt bits
2015 static void ufshcd_enable_intr(struct ufs_hba *hba, u32 intrs)
2017 u32 set = ufshcd_readl(hba, REG_INTERRUPT_ENABLE);
2019 if (hba->ufs_version == UFSHCI_VERSION_10) {
2021 rw = set & INTERRUPT_MASK_RW_VER_10;
2022 set = rw | ((set ^ intrs) & intrs);
2027 ufshcd_writel(hba, set, REG_INTERRUPT_ENABLE);
2031 * ufshcd_disable_intr - disable interrupts
2032 * @hba: per adapter instance
2033 * @intrs: interrupt bits
2035 static void ufshcd_disable_intr(struct ufs_hba *hba, u32 intrs)
2037 u32 set = ufshcd_readl(hba, REG_INTERRUPT_ENABLE);
2039 if (hba->ufs_version == UFSHCI_VERSION_10) {
2041 rw = (set & INTERRUPT_MASK_RW_VER_10) &
2042 ~(intrs & INTERRUPT_MASK_RW_VER_10);
2043 set = rw | ((set & intrs) & ~INTERRUPT_MASK_RW_VER_10);
2049 ufshcd_writel(hba, set, REG_INTERRUPT_ENABLE);
2053 * ufshcd_prepare_req_desc_hdr() - Fills the requests header
2054 * descriptor according to request
2055 * @lrbp: pointer to local reference block
2056 * @upiu_flags: flags required in the header
2057 * @cmd_dir: requests data direction
2059 static void ufshcd_prepare_req_desc_hdr(struct ufshcd_lrb *lrbp,
2060 u32 *upiu_flags, enum dma_data_direction cmd_dir)
2062 struct utp_transfer_req_desc *req_desc = lrbp->utr_descriptor_ptr;
2066 if (cmd_dir == DMA_FROM_DEVICE) {
2067 data_direction = UTP_DEVICE_TO_HOST;
2068 *upiu_flags = UPIU_CMD_FLAGS_READ;
2069 } else if (cmd_dir == DMA_TO_DEVICE) {
2070 data_direction = UTP_HOST_TO_DEVICE;
2071 *upiu_flags = UPIU_CMD_FLAGS_WRITE;
2073 data_direction = UTP_NO_DATA_TRANSFER;
2074 *upiu_flags = UPIU_CMD_FLAGS_NONE;
2077 dword_0 = data_direction | (lrbp->command_type
2078 << UPIU_COMMAND_TYPE_OFFSET);
2080 dword_0 |= UTP_REQ_DESC_INT_CMD;
2082 /* Transfer request descriptor header fields */
2083 req_desc->header.dword_0 = cpu_to_le32(dword_0);
2084 /* dword_1 is reserved, hence it is set to 0 */
2085 req_desc->header.dword_1 = 0;
2087 * assigning invalid value for command status. Controller
2088 * updates OCS on command completion, with the command
2091 req_desc->header.dword_2 =
2092 cpu_to_le32(OCS_INVALID_COMMAND_STATUS);
2093 /* dword_3 is reserved, hence it is set to 0 */
2094 req_desc->header.dword_3 = 0;
2096 req_desc->prd_table_length = 0;
2100 * ufshcd_prepare_utp_scsi_cmd_upiu() - fills the utp_transfer_req_desc,
2102 * @lrbp: local reference block pointer
2103 * @upiu_flags: flags
2106 void ufshcd_prepare_utp_scsi_cmd_upiu(struct ufshcd_lrb *lrbp, u32 upiu_flags)
2108 struct utp_upiu_req *ucd_req_ptr = lrbp->ucd_req_ptr;
2109 unsigned short cdb_len;
2111 /* command descriptor fields */
2112 ucd_req_ptr->header.dword_0 = UPIU_HEADER_DWORD(
2113 UPIU_TRANSACTION_COMMAND, upiu_flags,
2114 lrbp->lun, lrbp->task_tag);
2115 ucd_req_ptr->header.dword_1 = UPIU_HEADER_DWORD(
2116 UPIU_COMMAND_SET_TYPE_SCSI, 0, 0, 0);
2118 /* Total EHS length and Data segment length will be zero */
2119 ucd_req_ptr->header.dword_2 = 0;
2121 ucd_req_ptr->sc.exp_data_transfer_len =
2122 cpu_to_be32(lrbp->cmd->sdb.length);
2124 cdb_len = min_t(unsigned short, lrbp->cmd->cmd_len, MAX_CDB_SIZE);
2125 memset(ucd_req_ptr->sc.cdb, 0, MAX_CDB_SIZE);
2126 memcpy(ucd_req_ptr->sc.cdb, lrbp->cmd->cmnd, cdb_len);
2128 memset(lrbp->ucd_rsp_ptr, 0, sizeof(struct utp_upiu_rsp));
2132 * ufshcd_prepare_utp_query_req_upiu() - fills the utp_transfer_req_desc,
2135 * @lrbp: local reference block pointer
2136 * @upiu_flags: flags
2138 static void ufshcd_prepare_utp_query_req_upiu(struct ufs_hba *hba,
2139 struct ufshcd_lrb *lrbp, u32 upiu_flags)
2141 struct utp_upiu_req *ucd_req_ptr = lrbp->ucd_req_ptr;
2142 struct ufs_query *query = &hba->dev_cmd.query;
2143 u16 len = be16_to_cpu(query->request.upiu_req.length);
2144 u8 *descp = (u8 *)lrbp->ucd_req_ptr + GENERAL_UPIU_REQUEST_SIZE;
2146 /* Query request header */
2147 ucd_req_ptr->header.dword_0 = UPIU_HEADER_DWORD(
2148 UPIU_TRANSACTION_QUERY_REQ, upiu_flags,
2149 lrbp->lun, lrbp->task_tag);
2150 ucd_req_ptr->header.dword_1 = UPIU_HEADER_DWORD(
2151 0, query->request.query_func, 0, 0);
2153 /* Data segment length only need for WRITE_DESC */
2154 if (query->request.upiu_req.opcode == UPIU_QUERY_OPCODE_WRITE_DESC)
2155 ucd_req_ptr->header.dword_2 =
2156 UPIU_HEADER_DWORD(0, 0, (len >> 8), (u8)len);
2158 ucd_req_ptr->header.dword_2 = 0;
2160 /* Copy the Query Request buffer as is */
2161 memcpy(&ucd_req_ptr->qr, &query->request.upiu_req,
2164 /* Copy the Descriptor */
2165 if (query->request.upiu_req.opcode == UPIU_QUERY_OPCODE_WRITE_DESC)
2166 memcpy(descp, query->descriptor, len);
2168 memset(lrbp->ucd_rsp_ptr, 0, sizeof(struct utp_upiu_rsp));
2171 static inline void ufshcd_prepare_utp_nop_upiu(struct ufshcd_lrb *lrbp)
2173 struct utp_upiu_req *ucd_req_ptr = lrbp->ucd_req_ptr;
2175 memset(ucd_req_ptr, 0, sizeof(struct utp_upiu_req));
2177 /* command descriptor fields */
2178 ucd_req_ptr->header.dword_0 =
2180 UPIU_TRANSACTION_NOP_OUT, 0, 0, lrbp->task_tag);
2181 /* clear rest of the fields of basic header */
2182 ucd_req_ptr->header.dword_1 = 0;
2183 ucd_req_ptr->header.dword_2 = 0;
2185 memset(lrbp->ucd_rsp_ptr, 0, sizeof(struct utp_upiu_rsp));
2189 * ufshcd_comp_devman_upiu - UFS Protocol Information Unit(UPIU)
2190 * for Device Management Purposes
2191 * @hba: per adapter instance
2192 * @lrbp: pointer to local reference block
2194 static int ufshcd_comp_devman_upiu(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
2199 if ((hba->ufs_version == UFSHCI_VERSION_10) ||
2200 (hba->ufs_version == UFSHCI_VERSION_11))
2201 lrbp->command_type = UTP_CMD_TYPE_DEV_MANAGE;
2203 lrbp->command_type = UTP_CMD_TYPE_UFS_STORAGE;
2205 ufshcd_prepare_req_desc_hdr(lrbp, &upiu_flags, DMA_NONE);
2206 if (hba->dev_cmd.type == DEV_CMD_TYPE_QUERY)
2207 ufshcd_prepare_utp_query_req_upiu(hba, lrbp, upiu_flags);
2208 else if (hba->dev_cmd.type == DEV_CMD_TYPE_NOP)
2209 ufshcd_prepare_utp_nop_upiu(lrbp);
2217 * ufshcd_comp_scsi_upiu - UFS Protocol Information Unit(UPIU)
2219 * @hba: per adapter instance
2220 * @lrbp: pointer to local reference block
2222 static int ufshcd_comp_scsi_upiu(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
2227 if ((hba->ufs_version == UFSHCI_VERSION_10) ||
2228 (hba->ufs_version == UFSHCI_VERSION_11))
2229 lrbp->command_type = UTP_CMD_TYPE_SCSI;
2231 lrbp->command_type = UTP_CMD_TYPE_UFS_STORAGE;
2233 if (likely(lrbp->cmd)) {
2234 ufshcd_prepare_req_desc_hdr(lrbp, &upiu_flags,
2235 lrbp->cmd->sc_data_direction);
2236 ufshcd_prepare_utp_scsi_cmd_upiu(lrbp, upiu_flags);
2245 * ufshcd_upiu_wlun_to_scsi_wlun - maps UPIU W-LUN id to SCSI W-LUN ID
2246 * @upiu_wlun_id: UPIU W-LUN id
2248 * Returns SCSI W-LUN id
2250 static inline u16 ufshcd_upiu_wlun_to_scsi_wlun(u8 upiu_wlun_id)
2252 return (upiu_wlun_id & ~UFS_UPIU_WLUN_ID) | SCSI_W_LUN_BASE;
2256 * ufshcd_queuecommand - main entry point for SCSI requests
2257 * @host: SCSI host pointer
2258 * @cmd: command from SCSI Midlayer
2260 * Returns 0 for success, non-zero in case of failure
2262 static int ufshcd_queuecommand(struct Scsi_Host *host, struct scsi_cmnd *cmd)
2264 struct ufshcd_lrb *lrbp;
2265 struct ufs_hba *hba;
2266 unsigned long flags;
2270 hba = shost_priv(host);
2272 tag = cmd->request->tag;
2273 if (!ufshcd_valid_tag(hba, tag)) {
2275 "%s: invalid command tag %d: cmd=0x%p, cmd->request=0x%p",
2276 __func__, tag, cmd, cmd->request);
2280 if (!down_read_trylock(&hba->clk_scaling_lock))
2281 return SCSI_MLQUEUE_HOST_BUSY;
2283 spin_lock_irqsave(hba->host->host_lock, flags);
2284 switch (hba->ufshcd_state) {
2285 case UFSHCD_STATE_OPERATIONAL:
2287 case UFSHCD_STATE_EH_SCHEDULED:
2288 case UFSHCD_STATE_RESET:
2289 err = SCSI_MLQUEUE_HOST_BUSY;
2291 case UFSHCD_STATE_ERROR:
2292 set_host_byte(cmd, DID_ERROR);
2293 cmd->scsi_done(cmd);
2296 dev_WARN_ONCE(hba->dev, 1, "%s: invalid state %d\n",
2297 __func__, hba->ufshcd_state);
2298 set_host_byte(cmd, DID_BAD_TARGET);
2299 cmd->scsi_done(cmd);
2303 /* if error handling is in progress, don't issue commands */
2304 if (ufshcd_eh_in_progress(hba)) {
2305 set_host_byte(cmd, DID_ERROR);
2306 cmd->scsi_done(cmd);
2309 spin_unlock_irqrestore(hba->host->host_lock, flags);
2311 hba->req_abort_count = 0;
2313 /* acquire the tag to make sure device cmds don't use it */
2314 if (test_and_set_bit_lock(tag, &hba->lrb_in_use)) {
2316 * Dev manage command in progress, requeue the command.
2317 * Requeuing the command helps in cases where the request *may*
2318 * find different tag instead of waiting for dev manage command
2321 err = SCSI_MLQUEUE_HOST_BUSY;
2325 err = ufshcd_hold(hba, true);
2327 err = SCSI_MLQUEUE_HOST_BUSY;
2328 clear_bit_unlock(tag, &hba->lrb_in_use);
2331 WARN_ON(hba->clk_gating.state != CLKS_ON);
2333 lrbp = &hba->lrb[tag];
2337 lrbp->sense_bufflen = UFSHCD_REQ_SENSE_SIZE;
2338 lrbp->sense_buffer = cmd->sense_buffer;
2339 lrbp->task_tag = tag;
2340 lrbp->lun = ufshcd_scsi_to_upiu_lun(cmd->device->lun);
2341 lrbp->intr_cmd = !ufshcd_is_intr_aggr_allowed(hba) ? true : false;
2342 lrbp->req_abort_skip = false;
2344 ufshcd_comp_scsi_upiu(hba, lrbp);
2346 err = ufshcd_map_sg(hba, lrbp);
2349 clear_bit_unlock(tag, &hba->lrb_in_use);
2352 /* Make sure descriptors are ready before ringing the doorbell */
2355 /* issue command to the controller */
2356 spin_lock_irqsave(hba->host->host_lock, flags);
2357 ufshcd_vops_setup_xfer_req(hba, tag, (lrbp->cmd ? true : false));
2358 ufshcd_send_command(hba, tag);
2360 spin_unlock_irqrestore(hba->host->host_lock, flags);
2362 up_read(&hba->clk_scaling_lock);
2366 static int ufshcd_compose_dev_cmd(struct ufs_hba *hba,
2367 struct ufshcd_lrb *lrbp, enum dev_cmd_type cmd_type, int tag)
2370 lrbp->sense_bufflen = 0;
2371 lrbp->sense_buffer = NULL;
2372 lrbp->task_tag = tag;
2373 lrbp->lun = 0; /* device management cmd is not specific to any LUN */
2374 lrbp->intr_cmd = true; /* No interrupt aggregation */
2375 hba->dev_cmd.type = cmd_type;
2377 return ufshcd_comp_devman_upiu(hba, lrbp);
2381 ufshcd_clear_cmd(struct ufs_hba *hba, int tag)
2384 unsigned long flags;
2385 u32 mask = 1 << tag;
2387 /* clear outstanding transaction before retry */
2388 spin_lock_irqsave(hba->host->host_lock, flags);
2389 ufshcd_utrl_clear(hba, tag);
2390 spin_unlock_irqrestore(hba->host->host_lock, flags);
2393 * wait for for h/w to clear corresponding bit in door-bell.
2394 * max. wait is 1 sec.
2396 err = ufshcd_wait_for_register(hba,
2397 REG_UTP_TRANSFER_REQ_DOOR_BELL,
2398 mask, ~mask, 1000, 1000, true);
2404 ufshcd_check_query_response(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
2406 struct ufs_query_res *query_res = &hba->dev_cmd.query.response;
2408 /* Get the UPIU response */
2409 query_res->response = ufshcd_get_rsp_upiu_result(lrbp->ucd_rsp_ptr) >>
2410 UPIU_RSP_CODE_OFFSET;
2411 return query_res->response;
2415 * ufshcd_dev_cmd_completion() - handles device management command responses
2416 * @hba: per adapter instance
2417 * @lrbp: pointer to local reference block
2420 ufshcd_dev_cmd_completion(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
2425 hba->ufs_stats.last_hibern8_exit_tstamp = ktime_set(0, 0);
2426 resp = ufshcd_get_req_rsp(lrbp->ucd_rsp_ptr);
2429 case UPIU_TRANSACTION_NOP_IN:
2430 if (hba->dev_cmd.type != DEV_CMD_TYPE_NOP) {
2432 dev_err(hba->dev, "%s: unexpected response %x\n",
2436 case UPIU_TRANSACTION_QUERY_RSP:
2437 err = ufshcd_check_query_response(hba, lrbp);
2439 err = ufshcd_copy_query_response(hba, lrbp);
2441 case UPIU_TRANSACTION_REJECT_UPIU:
2442 /* TODO: handle Reject UPIU Response */
2444 dev_err(hba->dev, "%s: Reject UPIU not fully implemented\n",
2449 dev_err(hba->dev, "%s: Invalid device management cmd response: %x\n",
2457 static int ufshcd_wait_for_dev_cmd(struct ufs_hba *hba,
2458 struct ufshcd_lrb *lrbp, int max_timeout)
2461 unsigned long time_left;
2462 unsigned long flags;
2464 time_left = wait_for_completion_timeout(hba->dev_cmd.complete,
2465 msecs_to_jiffies(max_timeout));
2467 /* Make sure descriptors are ready before ringing the doorbell */
2469 spin_lock_irqsave(hba->host->host_lock, flags);
2470 hba->dev_cmd.complete = NULL;
2471 if (likely(time_left)) {
2472 err = ufshcd_get_tr_ocs(lrbp);
2474 err = ufshcd_dev_cmd_completion(hba, lrbp);
2476 spin_unlock_irqrestore(hba->host->host_lock, flags);
2480 dev_dbg(hba->dev, "%s: dev_cmd request timedout, tag %d\n",
2481 __func__, lrbp->task_tag);
2482 if (!ufshcd_clear_cmd(hba, lrbp->task_tag))
2483 /* successfully cleared the command, retry if needed */
2486 * in case of an error, after clearing the doorbell,
2487 * we also need to clear the outstanding_request
2490 ufshcd_outstanding_req_clear(hba, lrbp->task_tag);
2497 * ufshcd_get_dev_cmd_tag - Get device management command tag
2498 * @hba: per-adapter instance
2499 * @tag_out: pointer to variable with available slot value
2501 * Get a free slot and lock it until device management command
2504 * Returns false if free slot is unavailable for locking, else
2505 * return true with tag value in @tag.
2507 static bool ufshcd_get_dev_cmd_tag(struct ufs_hba *hba, int *tag_out)
2517 tmp = ~hba->lrb_in_use;
2518 tag = find_last_bit(&tmp, hba->nutrs);
2519 if (tag >= hba->nutrs)
2521 } while (test_and_set_bit_lock(tag, &hba->lrb_in_use));
2529 static inline void ufshcd_put_dev_cmd_tag(struct ufs_hba *hba, int tag)
2531 clear_bit_unlock(tag, &hba->lrb_in_use);
2535 * ufshcd_exec_dev_cmd - API for sending device management requests
2537 * @cmd_type: specifies the type (NOP, Query...)
2538 * @timeout: time in seconds
2540 * NOTE: Since there is only one available tag for device management commands,
2541 * it is expected you hold the hba->dev_cmd.lock mutex.
2543 static int ufshcd_exec_dev_cmd(struct ufs_hba *hba,
2544 enum dev_cmd_type cmd_type, int timeout)
2546 struct ufshcd_lrb *lrbp;
2549 struct completion wait;
2550 unsigned long flags;
2552 down_read(&hba->clk_scaling_lock);
2555 * Get free slot, sleep if slots are unavailable.
2556 * Even though we use wait_event() which sleeps indefinitely,
2557 * the maximum wait time is bounded by SCSI request timeout.
2559 wait_event(hba->dev_cmd.tag_wq, ufshcd_get_dev_cmd_tag(hba, &tag));
2561 init_completion(&wait);
2562 lrbp = &hba->lrb[tag];
2564 err = ufshcd_compose_dev_cmd(hba, lrbp, cmd_type, tag);
2568 hba->dev_cmd.complete = &wait;
2570 /* Make sure descriptors are ready before ringing the doorbell */
2572 spin_lock_irqsave(hba->host->host_lock, flags);
2573 ufshcd_vops_setup_xfer_req(hba, tag, (lrbp->cmd ? true : false));
2574 ufshcd_send_command(hba, tag);
2575 spin_unlock_irqrestore(hba->host->host_lock, flags);
2577 err = ufshcd_wait_for_dev_cmd(hba, lrbp, timeout);
2580 ufshcd_put_dev_cmd_tag(hba, tag);
2581 wake_up(&hba->dev_cmd.tag_wq);
2582 up_read(&hba->clk_scaling_lock);
2587 * ufshcd_init_query() - init the query response and request parameters
2588 * @hba: per-adapter instance
2589 * @request: address of the request pointer to be initialized
2590 * @response: address of the response pointer to be initialized
2591 * @opcode: operation to perform
2592 * @idn: flag idn to access
2593 * @index: LU number to access
2594 * @selector: query/flag/descriptor further identification
2596 static inline void ufshcd_init_query(struct ufs_hba *hba,
2597 struct ufs_query_req **request, struct ufs_query_res **response,
2598 enum query_opcode opcode, u8 idn, u8 index, u8 selector)
2600 *request = &hba->dev_cmd.query.request;
2601 *response = &hba->dev_cmd.query.response;
2602 memset(*request, 0, sizeof(struct ufs_query_req));
2603 memset(*response, 0, sizeof(struct ufs_query_res));
2604 (*request)->upiu_req.opcode = opcode;
2605 (*request)->upiu_req.idn = idn;
2606 (*request)->upiu_req.index = index;
2607 (*request)->upiu_req.selector = selector;
2610 static int ufshcd_query_flag_retry(struct ufs_hba *hba,
2611 enum query_opcode opcode, enum flag_idn idn, bool *flag_res)
2616 for (retries = 0; retries < QUERY_REQ_RETRIES; retries++) {
2617 ret = ufshcd_query_flag(hba, opcode, idn, flag_res);
2620 "%s: failed with error %d, retries %d\n",
2621 __func__, ret, retries);
2628 "%s: query attribute, opcode %d, idn %d, failed with error %d after %d retires\n",
2629 __func__, opcode, idn, ret, retries);
2634 * ufshcd_query_flag() - API function for sending flag query requests
2635 * @hba: per-adapter instance
2636 * @opcode: flag query to perform
2637 * @idn: flag idn to access
2638 * @flag_res: the flag value after the query request completes
2640 * Returns 0 for success, non-zero in case of failure
2642 int ufshcd_query_flag(struct ufs_hba *hba, enum query_opcode opcode,
2643 enum flag_idn idn, bool *flag_res)
2645 struct ufs_query_req *request = NULL;
2646 struct ufs_query_res *response = NULL;
2647 int err, index = 0, selector = 0;
2648 int timeout = QUERY_REQ_TIMEOUT;
2652 ufshcd_hold(hba, false);
2653 mutex_lock(&hba->dev_cmd.lock);
2654 ufshcd_init_query(hba, &request, &response, opcode, idn, index,
2658 case UPIU_QUERY_OPCODE_SET_FLAG:
2659 case UPIU_QUERY_OPCODE_CLEAR_FLAG:
2660 case UPIU_QUERY_OPCODE_TOGGLE_FLAG:
2661 request->query_func = UPIU_QUERY_FUNC_STANDARD_WRITE_REQUEST;
2663 case UPIU_QUERY_OPCODE_READ_FLAG:
2664 request->query_func = UPIU_QUERY_FUNC_STANDARD_READ_REQUEST;
2666 /* No dummy reads */
2667 dev_err(hba->dev, "%s: Invalid argument for read request\n",
2675 "%s: Expected query flag opcode but got = %d\n",
2681 err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_QUERY, timeout);
2685 "%s: Sending flag query for idn %d failed, err = %d\n",
2686 __func__, idn, err);
2691 *flag_res = (be32_to_cpu(response->upiu_res.value) &
2692 MASK_QUERY_UPIU_FLAG_LOC) & 0x1;
2695 mutex_unlock(&hba->dev_cmd.lock);
2696 ufshcd_release(hba);
2701 * ufshcd_query_attr - API function for sending attribute requests
2702 * @hba: per-adapter instance
2703 * @opcode: attribute opcode
2704 * @idn: attribute idn to access
2705 * @index: index field
2706 * @selector: selector field
2707 * @attr_val: the attribute value after the query request completes
2709 * Returns 0 for success, non-zero in case of failure
2711 int ufshcd_query_attr(struct ufs_hba *hba, enum query_opcode opcode,
2712 enum attr_idn idn, u8 index, u8 selector, u32 *attr_val)
2714 struct ufs_query_req *request = NULL;
2715 struct ufs_query_res *response = NULL;
2720 ufshcd_hold(hba, false);
2722 dev_err(hba->dev, "%s: attribute value required for opcode 0x%x\n",
2728 mutex_lock(&hba->dev_cmd.lock);
2729 ufshcd_init_query(hba, &request, &response, opcode, idn, index,
2733 case UPIU_QUERY_OPCODE_WRITE_ATTR:
2734 request->query_func = UPIU_QUERY_FUNC_STANDARD_WRITE_REQUEST;
2735 request->upiu_req.value = cpu_to_be32(*attr_val);
2737 case UPIU_QUERY_OPCODE_READ_ATTR:
2738 request->query_func = UPIU_QUERY_FUNC_STANDARD_READ_REQUEST;
2741 dev_err(hba->dev, "%s: Expected query attr opcode but got = 0x%.2x\n",
2747 err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_QUERY, QUERY_REQ_TIMEOUT);
2750 dev_err(hba->dev, "%s: opcode 0x%.2x for idn %d failed, index %d, err = %d\n",
2751 __func__, opcode, idn, index, err);
2755 *attr_val = be32_to_cpu(response->upiu_res.value);
2758 mutex_unlock(&hba->dev_cmd.lock);
2760 ufshcd_release(hba);
2765 * ufshcd_query_attr_retry() - API function for sending query
2766 * attribute with retries
2767 * @hba: per-adapter instance
2768 * @opcode: attribute opcode
2769 * @idn: attribute idn to access
2770 * @index: index field
2771 * @selector: selector field
2772 * @attr_val: the attribute value after the query request
2775 * Returns 0 for success, non-zero in case of failure
2777 static int ufshcd_query_attr_retry(struct ufs_hba *hba,
2778 enum query_opcode opcode, enum attr_idn idn, u8 index, u8 selector,
2784 for (retries = QUERY_REQ_RETRIES; retries > 0; retries--) {
2785 ret = ufshcd_query_attr(hba, opcode, idn, index,
2786 selector, attr_val);
2788 dev_dbg(hba->dev, "%s: failed with error %d, retries %d\n",
2789 __func__, ret, retries);
2796 "%s: query attribute, idn %d, failed with error %d after %d retires\n",
2797 __func__, idn, ret, QUERY_REQ_RETRIES);
2801 static int __ufshcd_query_descriptor(struct ufs_hba *hba,
2802 enum query_opcode opcode, enum desc_idn idn, u8 index,
2803 u8 selector, u8 *desc_buf, int *buf_len)
2805 struct ufs_query_req *request = NULL;
2806 struct ufs_query_res *response = NULL;
2811 ufshcd_hold(hba, false);
2813 dev_err(hba->dev, "%s: descriptor buffer required for opcode 0x%x\n",
2819 if (*buf_len < QUERY_DESC_MIN_SIZE || *buf_len > QUERY_DESC_MAX_SIZE) {
2820 dev_err(hba->dev, "%s: descriptor buffer size (%d) is out of range\n",
2821 __func__, *buf_len);
2826 mutex_lock(&hba->dev_cmd.lock);
2827 ufshcd_init_query(hba, &request, &response, opcode, idn, index,
2829 hba->dev_cmd.query.descriptor = desc_buf;
2830 request->upiu_req.length = cpu_to_be16(*buf_len);
2833 case UPIU_QUERY_OPCODE_WRITE_DESC:
2834 request->query_func = UPIU_QUERY_FUNC_STANDARD_WRITE_REQUEST;
2836 case UPIU_QUERY_OPCODE_READ_DESC:
2837 request->query_func = UPIU_QUERY_FUNC_STANDARD_READ_REQUEST;
2841 "%s: Expected query descriptor opcode but got = 0x%.2x\n",
2847 err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_QUERY, QUERY_REQ_TIMEOUT);
2850 dev_err(hba->dev, "%s: opcode 0x%.2x for idn %d failed, index %d, err = %d\n",
2851 __func__, opcode, idn, index, err);
2855 hba->dev_cmd.query.descriptor = NULL;
2856 *buf_len = be16_to_cpu(response->upiu_res.length);
2859 mutex_unlock(&hba->dev_cmd.lock);
2861 ufshcd_release(hba);
2866 * ufshcd_query_descriptor_retry - API function for sending descriptor requests
2867 * @hba: per-adapter instance
2868 * @opcode: attribute opcode
2869 * @idn: attribute idn to access
2870 * @index: index field
2871 * @selector: selector field
2872 * @desc_buf: the buffer that contains the descriptor
2873 * @buf_len: length parameter passed to the device
2875 * Returns 0 for success, non-zero in case of failure.
2876 * The buf_len parameter will contain, on return, the length parameter
2877 * received on the response.
2879 int ufshcd_query_descriptor_retry(struct ufs_hba *hba,
2880 enum query_opcode opcode,
2881 enum desc_idn idn, u8 index,
2883 u8 *desc_buf, int *buf_len)
2888 for (retries = QUERY_REQ_RETRIES; retries > 0; retries--) {
2889 err = __ufshcd_query_descriptor(hba, opcode, idn, index,
2890 selector, desc_buf, buf_len);
2891 if (!err || err == -EINVAL)
2899 * ufshcd_read_desc_length - read the specified descriptor length from header
2900 * @hba: Pointer to adapter instance
2901 * @desc_id: descriptor idn value
2902 * @desc_index: descriptor index
2903 * @desc_length: pointer to variable to read the length of descriptor
2905 * Return 0 in case of success, non-zero otherwise
2907 static int ufshcd_read_desc_length(struct ufs_hba *hba,
2908 enum desc_idn desc_id,
2913 u8 header[QUERY_DESC_HDR_SIZE];
2914 int header_len = QUERY_DESC_HDR_SIZE;
2916 if (desc_id >= QUERY_DESC_IDN_MAX)
2919 ret = ufshcd_query_descriptor_retry(hba, UPIU_QUERY_OPCODE_READ_DESC,
2920 desc_id, desc_index, 0, header,
2924 dev_err(hba->dev, "%s: Failed to get descriptor header id %d",
2927 } else if (desc_id != header[QUERY_DESC_DESC_TYPE_OFFSET]) {
2928 dev_warn(hba->dev, "%s: descriptor header id %d and desc_id %d mismatch",
2929 __func__, header[QUERY_DESC_DESC_TYPE_OFFSET],
2934 *desc_length = header[QUERY_DESC_LENGTH_OFFSET];
2940 * ufshcd_map_desc_id_to_length - map descriptor IDN to its length
2941 * @hba: Pointer to adapter instance
2942 * @desc_id: descriptor idn value
2943 * @desc_len: mapped desc length (out)
2945 * Return 0 in case of success, non-zero otherwise
2947 int ufshcd_map_desc_id_to_length(struct ufs_hba *hba,
2948 enum desc_idn desc_id, int *desc_len)
2951 case QUERY_DESC_IDN_DEVICE:
2952 *desc_len = hba->desc_size.dev_desc;
2954 case QUERY_DESC_IDN_POWER:
2955 *desc_len = hba->desc_size.pwr_desc;
2957 case QUERY_DESC_IDN_GEOMETRY:
2958 *desc_len = hba->desc_size.geom_desc;
2960 case QUERY_DESC_IDN_CONFIGURATION:
2961 *desc_len = hba->desc_size.conf_desc;
2963 case QUERY_DESC_IDN_UNIT:
2964 *desc_len = hba->desc_size.unit_desc;
2966 case QUERY_DESC_IDN_INTERCONNECT:
2967 *desc_len = hba->desc_size.interc_desc;
2969 case QUERY_DESC_IDN_STRING:
2970 *desc_len = QUERY_DESC_MAX_SIZE;
2972 case QUERY_DESC_IDN_HEALTH:
2973 *desc_len = hba->desc_size.hlth_desc;
2975 case QUERY_DESC_IDN_RFU_0:
2976 case QUERY_DESC_IDN_RFU_1:
2985 EXPORT_SYMBOL(ufshcd_map_desc_id_to_length);
2988 * ufshcd_read_desc_param - read the specified descriptor parameter
2989 * @hba: Pointer to adapter instance
2990 * @desc_id: descriptor idn value
2991 * @desc_index: descriptor index
2992 * @param_offset: offset of the parameter to read
2993 * @param_read_buf: pointer to buffer where parameter would be read
2994 * @param_size: sizeof(param_read_buf)
2996 * Return 0 in case of success, non-zero otherwise
2998 int ufshcd_read_desc_param(struct ufs_hba *hba,
2999 enum desc_idn desc_id,
3008 bool is_kmalloc = true;
3011 if (desc_id >= QUERY_DESC_IDN_MAX || !param_size)
3014 /* Get the max length of descriptor from structure filled up at probe
3017 ret = ufshcd_map_desc_id_to_length(hba, desc_id, &buff_len);
3020 if (ret || !buff_len) {
3021 dev_err(hba->dev, "%s: Failed to get full descriptor length",
3026 /* Check whether we need temp memory */
3027 if (param_offset != 0 || param_size < buff_len) {
3028 desc_buf = kmalloc(buff_len, GFP_KERNEL);
3032 desc_buf = param_read_buf;
3036 /* Request for full descriptor */
3037 ret = ufshcd_query_descriptor_retry(hba, UPIU_QUERY_OPCODE_READ_DESC,
3038 desc_id, desc_index, 0,
3039 desc_buf, &buff_len);
3042 dev_err(hba->dev, "%s: Failed reading descriptor. desc_id %d, desc_index %d, param_offset %d, ret %d",
3043 __func__, desc_id, desc_index, param_offset, ret);
3048 if (desc_buf[QUERY_DESC_DESC_TYPE_OFFSET] != desc_id) {
3049 dev_err(hba->dev, "%s: invalid desc_id %d in descriptor header",
3050 __func__, desc_buf[QUERY_DESC_DESC_TYPE_OFFSET]);
3055 /* Check wherher we will not copy more data, than available */
3056 if (is_kmalloc && param_size > buff_len)
3057 param_size = buff_len;
3060 memcpy(param_read_buf, &desc_buf[param_offset], param_size);
3067 static inline int ufshcd_read_desc(struct ufs_hba *hba,
3068 enum desc_idn desc_id,
3073 return ufshcd_read_desc_param(hba, desc_id, desc_index, 0, buf, size);
3076 static inline int ufshcd_read_power_desc(struct ufs_hba *hba,
3080 return ufshcd_read_desc(hba, QUERY_DESC_IDN_POWER, 0, buf, size);
3083 static int ufshcd_read_device_desc(struct ufs_hba *hba, u8 *buf, u32 size)
3085 return ufshcd_read_desc(hba, QUERY_DESC_IDN_DEVICE, 0, buf, size);
3089 * ufshcd_read_string_desc - read string descriptor
3090 * @hba: pointer to adapter instance
3091 * @desc_index: descriptor index
3092 * @buf: pointer to buffer where descriptor would be read
3093 * @size: size of buf
3094 * @ascii: if true convert from unicode to ascii characters
3096 * Return 0 in case of success, non-zero otherwise
3098 int ufshcd_read_string_desc(struct ufs_hba *hba, int desc_index,
3099 u8 *buf, u32 size, bool ascii)
3103 err = ufshcd_read_desc(hba,
3104 QUERY_DESC_IDN_STRING, desc_index, buf, size);
3107 dev_err(hba->dev, "%s: reading String Desc failed after %d retries. err = %d\n",
3108 __func__, QUERY_REQ_RETRIES, err);
3119 /* remove header and divide by 2 to move from UTF16 to UTF8 */
3120 ascii_len = (desc_len - QUERY_DESC_HDR_SIZE) / 2 + 1;
3121 if (size < ascii_len + QUERY_DESC_HDR_SIZE) {
3122 dev_err(hba->dev, "%s: buffer allocated size is too small\n",
3128 buff_ascii = kmalloc(ascii_len, GFP_KERNEL);
3135 * the descriptor contains string in UTF16 format
3136 * we need to convert to utf-8 so it can be displayed
3138 utf16s_to_utf8s((wchar_t *)&buf[QUERY_DESC_HDR_SIZE],
3139 desc_len - QUERY_DESC_HDR_SIZE,
3140 UTF16_BIG_ENDIAN, buff_ascii, ascii_len);
3142 /* replace non-printable or non-ASCII characters with spaces */
3143 for (i = 0; i < ascii_len; i++)
3144 ufshcd_remove_non_printable(&buff_ascii[i]);
3146 memset(buf + QUERY_DESC_HDR_SIZE, 0,
3147 size - QUERY_DESC_HDR_SIZE);
3148 memcpy(buf + QUERY_DESC_HDR_SIZE, buff_ascii, ascii_len);
3149 buf[QUERY_DESC_LENGTH_OFFSET] = ascii_len + QUERY_DESC_HDR_SIZE;
3157 * ufshcd_read_unit_desc_param - read the specified unit descriptor parameter
3158 * @hba: Pointer to adapter instance
3160 * @param_offset: offset of the parameter to read
3161 * @param_read_buf: pointer to buffer where parameter would be read
3162 * @param_size: sizeof(param_read_buf)
3164 * Return 0 in case of success, non-zero otherwise
3166 static inline int ufshcd_read_unit_desc_param(struct ufs_hba *hba,
3168 enum unit_desc_param param_offset,
3173 * Unit descriptors are only available for general purpose LUs (LUN id
3174 * from 0 to 7) and RPMB Well known LU.
3176 if (!ufs_is_valid_unit_desc_lun(lun))
3179 return ufshcd_read_desc_param(hba, QUERY_DESC_IDN_UNIT, lun,
3180 param_offset, param_read_buf, param_size);
3184 * ufshcd_memory_alloc - allocate memory for host memory space data structures
3185 * @hba: per adapter instance
3187 * 1. Allocate DMA memory for Command Descriptor array
3188 * Each command descriptor consist of Command UPIU, Response UPIU and PRDT
3189 * 2. Allocate DMA memory for UTP Transfer Request Descriptor List (UTRDL).
3190 * 3. Allocate DMA memory for UTP Task Management Request Descriptor List
3192 * 4. Allocate memory for local reference block(lrb).
3194 * Returns 0 for success, non-zero in case of failure
3196 static int ufshcd_memory_alloc(struct ufs_hba *hba)
3198 size_t utmrdl_size, utrdl_size, ucdl_size;
3200 /* Allocate memory for UTP command descriptors */
3201 ucdl_size = (sizeof(struct utp_transfer_cmd_desc) * hba->nutrs);
3202 hba->ucdl_base_addr = dmam_alloc_coherent(hba->dev,
3204 &hba->ucdl_dma_addr,
3208 * UFSHCI requires UTP command descriptor to be 128 byte aligned.
3209 * make sure hba->ucdl_dma_addr is aligned to PAGE_SIZE
3210 * if hba->ucdl_dma_addr is aligned to PAGE_SIZE, then it will
3211 * be aligned to 128 bytes as well
3213 if (!hba->ucdl_base_addr ||
3214 WARN_ON(hba->ucdl_dma_addr & (PAGE_SIZE - 1))) {
3216 "Command Descriptor Memory allocation failed\n");
3221 * Allocate memory for UTP Transfer descriptors
3222 * UFSHCI requires 1024 byte alignment of UTRD
3224 utrdl_size = (sizeof(struct utp_transfer_req_desc) * hba->nutrs);
3225 hba->utrdl_base_addr = dmam_alloc_coherent(hba->dev,
3227 &hba->utrdl_dma_addr,
3229 if (!hba->utrdl_base_addr ||
3230 WARN_ON(hba->utrdl_dma_addr & (PAGE_SIZE - 1))) {
3232 "Transfer Descriptor Memory allocation failed\n");
3237 * Allocate memory for UTP Task Management descriptors
3238 * UFSHCI requires 1024 byte alignment of UTMRD
3240 utmrdl_size = sizeof(struct utp_task_req_desc) * hba->nutmrs;
3241 hba->utmrdl_base_addr = dmam_alloc_coherent(hba->dev,
3243 &hba->utmrdl_dma_addr,
3245 if (!hba->utmrdl_base_addr ||
3246 WARN_ON(hba->utmrdl_dma_addr & (PAGE_SIZE - 1))) {
3248 "Task Management Descriptor Memory allocation failed\n");
3252 /* Allocate memory for local reference block */
3253 hba->lrb = devm_kzalloc(hba->dev,
3254 hba->nutrs * sizeof(struct ufshcd_lrb),
3257 dev_err(hba->dev, "LRB Memory allocation failed\n");
3266 * ufshcd_host_memory_configure - configure local reference block with
3268 * @hba: per adapter instance
3270 * Configure Host memory space
3271 * 1. Update Corresponding UTRD.UCDBA and UTRD.UCDBAU with UCD DMA
3273 * 2. Update each UTRD with Response UPIU offset, Response UPIU length
3275 * 3. Save the corresponding addresses of UTRD, UCD.CMD, UCD.RSP and UCD.PRDT
3276 * into local reference block.
3278 static void ufshcd_host_memory_configure(struct ufs_hba *hba)
3280 struct utp_transfer_cmd_desc *cmd_descp;
3281 struct utp_transfer_req_desc *utrdlp;
3282 dma_addr_t cmd_desc_dma_addr;
3283 dma_addr_t cmd_desc_element_addr;
3284 u16 response_offset;
3289 utrdlp = hba->utrdl_base_addr;
3290 cmd_descp = hba->ucdl_base_addr;
3293 offsetof(struct utp_transfer_cmd_desc, response_upiu);
3295 offsetof(struct utp_transfer_cmd_desc, prd_table);
3297 cmd_desc_size = sizeof(struct utp_transfer_cmd_desc);
3298 cmd_desc_dma_addr = hba->ucdl_dma_addr;
3300 for (i = 0; i < hba->nutrs; i++) {
3301 /* Configure UTRD with command descriptor base address */
3302 cmd_desc_element_addr =
3303 (cmd_desc_dma_addr + (cmd_desc_size * i));
3304 utrdlp[i].command_desc_base_addr_lo =
3305 cpu_to_le32(lower_32_bits(cmd_desc_element_addr));
3306 utrdlp[i].command_desc_base_addr_hi =
3307 cpu_to_le32(upper_32_bits(cmd_desc_element_addr));
3309 /* Response upiu and prdt offset should be in double words */
3310 if (hba->quirks & UFSHCD_QUIRK_PRDT_BYTE_GRAN) {
3311 utrdlp[i].response_upiu_offset =
3312 cpu_to_le16(response_offset);
3313 utrdlp[i].prd_table_offset =
3314 cpu_to_le16(prdt_offset);
3315 utrdlp[i].response_upiu_length =
3316 cpu_to_le16(ALIGNED_UPIU_SIZE);
3318 utrdlp[i].response_upiu_offset =
3319 cpu_to_le16((response_offset >> 2));
3320 utrdlp[i].prd_table_offset =
3321 cpu_to_le16((prdt_offset >> 2));
3322 utrdlp[i].response_upiu_length =
3323 cpu_to_le16(ALIGNED_UPIU_SIZE >> 2);
3326 hba->lrb[i].utr_descriptor_ptr = (utrdlp + i);
3327 hba->lrb[i].utrd_dma_addr = hba->utrdl_dma_addr +
3328 (i * sizeof(struct utp_transfer_req_desc));
3329 hba->lrb[i].ucd_req_ptr =
3330 (struct utp_upiu_req *)(cmd_descp + i);
3331 hba->lrb[i].ucd_req_dma_addr = cmd_desc_element_addr;
3332 hba->lrb[i].ucd_rsp_ptr =
3333 (struct utp_upiu_rsp *)cmd_descp[i].response_upiu;
3334 hba->lrb[i].ucd_rsp_dma_addr = cmd_desc_element_addr +
3336 hba->lrb[i].ucd_prdt_ptr =
3337 (struct ufshcd_sg_entry *)cmd_descp[i].prd_table;
3338 hba->lrb[i].ucd_prdt_dma_addr = cmd_desc_element_addr +
3344 * ufshcd_dme_link_startup - Notify Unipro to perform link startup
3345 * @hba: per adapter instance
3347 * UIC_CMD_DME_LINK_STARTUP command must be issued to Unipro layer,
3348 * in order to initialize the Unipro link startup procedure.
3349 * Once the Unipro links are up, the device connected to the controller
3352 * Returns 0 on success, non-zero value on failure
3354 static int ufshcd_dme_link_startup(struct ufs_hba *hba)
3356 struct uic_command uic_cmd = {0};
3359 uic_cmd.command = UIC_CMD_DME_LINK_STARTUP;
3361 ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
3364 "dme-link-startup: error code %d\n", ret);
3368 static inline void ufshcd_add_delay_before_dme_cmd(struct ufs_hba *hba)
3370 #define MIN_DELAY_BEFORE_DME_CMDS_US 1000
3371 unsigned long min_sleep_time_us;
3373 if (!(hba->quirks & UFSHCD_QUIRK_DELAY_BEFORE_DME_CMDS))
3377 * last_dme_cmd_tstamp will be 0 only for 1st call to
3380 if (unlikely(!ktime_to_us(hba->last_dme_cmd_tstamp))) {
3381 min_sleep_time_us = MIN_DELAY_BEFORE_DME_CMDS_US;
3383 unsigned long delta =
3384 (unsigned long) ktime_to_us(
3385 ktime_sub(ktime_get(),
3386 hba->last_dme_cmd_tstamp));
3388 if (delta < MIN_DELAY_BEFORE_DME_CMDS_US)
3390 MIN_DELAY_BEFORE_DME_CMDS_US - delta;
3392 return; /* no more delay required */
3395 /* allow sleep for extra 50us if needed */
3396 usleep_range(min_sleep_time_us, min_sleep_time_us + 50);
3400 * ufshcd_dme_set_attr - UIC command for DME_SET, DME_PEER_SET
3401 * @hba: per adapter instance
3402 * @attr_sel: uic command argument1
3403 * @attr_set: attribute set type as uic command argument2
3404 * @mib_val: setting value as uic command argument3
3405 * @peer: indicate whether peer or local
3407 * Returns 0 on success, non-zero value on failure
3409 int ufshcd_dme_set_attr(struct ufs_hba *hba, u32 attr_sel,
3410 u8 attr_set, u32 mib_val, u8 peer)
3412 struct uic_command uic_cmd = {0};
3413 static const char *const action[] = {
3417 const char *set = action[!!peer];
3419 int retries = UFS_UIC_COMMAND_RETRIES;
3421 uic_cmd.command = peer ?
3422 UIC_CMD_DME_PEER_SET : UIC_CMD_DME_SET;
3423 uic_cmd.argument1 = attr_sel;
3424 uic_cmd.argument2 = UIC_ARG_ATTR_TYPE(attr_set);
3425 uic_cmd.argument3 = mib_val;
3428 /* for peer attributes we retry upon failure */
3429 ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
3431 dev_dbg(hba->dev, "%s: attr-id 0x%x val 0x%x error code %d\n",
3432 set, UIC_GET_ATTR_ID(attr_sel), mib_val, ret);
3433 } while (ret && peer && --retries);
3436 dev_err(hba->dev, "%s: attr-id 0x%x val 0x%x failed %d retries\n",
3437 set, UIC_GET_ATTR_ID(attr_sel), mib_val,
3438 UFS_UIC_COMMAND_RETRIES - retries);
3442 EXPORT_SYMBOL_GPL(ufshcd_dme_set_attr);
3445 * ufshcd_dme_get_attr - UIC command for DME_GET, DME_PEER_GET
3446 * @hba: per adapter instance
3447 * @attr_sel: uic command argument1
3448 * @mib_val: the value of the attribute as returned by the UIC command
3449 * @peer: indicate whether peer or local
3451 * Returns 0 on success, non-zero value on failure
3453 int ufshcd_dme_get_attr(struct ufs_hba *hba, u32 attr_sel,
3454 u32 *mib_val, u8 peer)
3456 struct uic_command uic_cmd = {0};
3457 static const char *const action[] = {
3461 const char *get = action[!!peer];
3463 int retries = UFS_UIC_COMMAND_RETRIES;
3464 struct ufs_pa_layer_attr orig_pwr_info;
3465 struct ufs_pa_layer_attr temp_pwr_info;
3466 bool pwr_mode_change = false;
3468 if (peer && (hba->quirks & UFSHCD_QUIRK_DME_PEER_ACCESS_AUTO_MODE)) {
3469 orig_pwr_info = hba->pwr_info;
3470 temp_pwr_info = orig_pwr_info;
3472 if (orig_pwr_info.pwr_tx == FAST_MODE ||
3473 orig_pwr_info.pwr_rx == FAST_MODE) {
3474 temp_pwr_info.pwr_tx = FASTAUTO_MODE;
3475 temp_pwr_info.pwr_rx = FASTAUTO_MODE;
3476 pwr_mode_change = true;
3477 } else if (orig_pwr_info.pwr_tx == SLOW_MODE ||
3478 orig_pwr_info.pwr_rx == SLOW_MODE) {
3479 temp_pwr_info.pwr_tx = SLOWAUTO_MODE;
3480 temp_pwr_info.pwr_rx = SLOWAUTO_MODE;
3481 pwr_mode_change = true;
3483 if (pwr_mode_change) {
3484 ret = ufshcd_change_power_mode(hba, &temp_pwr_info);
3490 uic_cmd.command = peer ?
3491 UIC_CMD_DME_PEER_GET : UIC_CMD_DME_GET;
3492 uic_cmd.argument1 = attr_sel;
3495 /* for peer attributes we retry upon failure */
3496 ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
3498 dev_dbg(hba->dev, "%s: attr-id 0x%x error code %d\n",
3499 get, UIC_GET_ATTR_ID(attr_sel), ret);
3500 } while (ret && peer && --retries);
3503 dev_err(hba->dev, "%s: attr-id 0x%x failed %d retries\n",
3504 get, UIC_GET_ATTR_ID(attr_sel),
3505 UFS_UIC_COMMAND_RETRIES - retries);
3507 if (mib_val && !ret)
3508 *mib_val = uic_cmd.argument3;
3510 if (peer && (hba->quirks & UFSHCD_QUIRK_DME_PEER_ACCESS_AUTO_MODE)
3512 ufshcd_change_power_mode(hba, &orig_pwr_info);
3516 EXPORT_SYMBOL_GPL(ufshcd_dme_get_attr);
3519 * ufshcd_uic_pwr_ctrl - executes UIC commands (which affects the link power
3520 * state) and waits for it to take effect.
3522 * @hba: per adapter instance
3523 * @cmd: UIC command to execute
3525 * DME operations like DME_SET(PA_PWRMODE), DME_HIBERNATE_ENTER &
3526 * DME_HIBERNATE_EXIT commands take some time to take its effect on both host
3527 * and device UniPro link and hence it's final completion would be indicated by
3528 * dedicated status bits in Interrupt Status register (UPMS, UHES, UHXS) in
3529 * addition to normal UIC command completion Status (UCCS). This function only
3530 * returns after the relevant status bits indicate the completion.
3532 * Returns 0 on success, non-zero value on failure
3534 static int ufshcd_uic_pwr_ctrl(struct ufs_hba *hba, struct uic_command *cmd)
3536 struct completion uic_async_done;
3537 unsigned long flags;
3540 bool reenable_intr = false;
3542 mutex_lock(&hba->uic_cmd_mutex);
3543 init_completion(&uic_async_done);
3544 ufshcd_add_delay_before_dme_cmd(hba);
3546 spin_lock_irqsave(hba->host->host_lock, flags);
3547 hba->uic_async_done = &uic_async_done;
3548 if (ufshcd_readl(hba, REG_INTERRUPT_ENABLE) & UIC_COMMAND_COMPL) {
3549 ufshcd_disable_intr(hba, UIC_COMMAND_COMPL);
3551 * Make sure UIC command completion interrupt is disabled before
3552 * issuing UIC command.
3555 reenable_intr = true;
3557 ret = __ufshcd_send_uic_cmd(hba, cmd, false);
3558 spin_unlock_irqrestore(hba->host->host_lock, flags);
3561 "pwr ctrl cmd 0x%x with mode 0x%x uic error %d\n",
3562 cmd->command, cmd->argument3, ret);
3566 if (!wait_for_completion_timeout(hba->uic_async_done,
3567 msecs_to_jiffies(UIC_CMD_TIMEOUT))) {
3569 "pwr ctrl cmd 0x%x with mode 0x%x completion timeout\n",
3570 cmd->command, cmd->argument3);
3575 status = ufshcd_get_upmcrs(hba);
3576 if (status != PWR_LOCAL) {
3578 "pwr ctrl cmd 0x%x failed, host upmcrs:0x%x\n",
3579 cmd->command, status);
3580 ret = (status != PWR_OK) ? status : -1;
3584 ufshcd_print_host_state(hba);
3585 ufshcd_print_pwr_info(hba);
3586 ufshcd_print_host_regs(hba);
3589 spin_lock_irqsave(hba->host->host_lock, flags);
3590 hba->active_uic_cmd = NULL;
3591 hba->uic_async_done = NULL;
3593 ufshcd_enable_intr(hba, UIC_COMMAND_COMPL);
3594 spin_unlock_irqrestore(hba->host->host_lock, flags);
3595 mutex_unlock(&hba->uic_cmd_mutex);
3601 * ufshcd_uic_change_pwr_mode - Perform the UIC power mode chage
3602 * using DME_SET primitives.
3603 * @hba: per adapter instance
3604 * @mode: powr mode value
3606 * Returns 0 on success, non-zero value on failure
3608 static int ufshcd_uic_change_pwr_mode(struct ufs_hba *hba, u8 mode)
3610 struct uic_command uic_cmd = {0};
3613 if (hba->quirks & UFSHCD_QUIRK_BROKEN_PA_RXHSUNTERMCAP) {
3614 ret = ufshcd_dme_set(hba,
3615 UIC_ARG_MIB_SEL(PA_RXHSUNTERMCAP, 0), 1);
3617 dev_err(hba->dev, "%s: failed to enable PA_RXHSUNTERMCAP ret %d\n",
3623 uic_cmd.command = UIC_CMD_DME_SET;
3624 uic_cmd.argument1 = UIC_ARG_MIB(PA_PWRMODE);
3625 uic_cmd.argument3 = mode;
3626 ufshcd_hold(hba, false);
3627 ret = ufshcd_uic_pwr_ctrl(hba, &uic_cmd);
3628 ufshcd_release(hba);
3634 static int ufshcd_link_recovery(struct ufs_hba *hba)
3637 unsigned long flags;
3639 spin_lock_irqsave(hba->host->host_lock, flags);
3640 hba->ufshcd_state = UFSHCD_STATE_RESET;
3641 ufshcd_set_eh_in_progress(hba);
3642 spin_unlock_irqrestore(hba->host->host_lock, flags);
3644 ret = ufshcd_host_reset_and_restore(hba);
3646 spin_lock_irqsave(hba->host->host_lock, flags);
3648 hba->ufshcd_state = UFSHCD_STATE_ERROR;
3649 ufshcd_clear_eh_in_progress(hba);
3650 spin_unlock_irqrestore(hba->host->host_lock, flags);
3653 dev_err(hba->dev, "%s: link recovery failed, err %d",
3659 static int __ufshcd_uic_hibern8_enter(struct ufs_hba *hba)
3662 struct uic_command uic_cmd = {0};
3663 ktime_t start = ktime_get();
3665 ufshcd_vops_hibern8_notify(hba, UIC_CMD_DME_HIBER_ENTER, PRE_CHANGE);
3667 uic_cmd.command = UIC_CMD_DME_HIBER_ENTER;
3668 ret = ufshcd_uic_pwr_ctrl(hba, &uic_cmd);
3669 trace_ufshcd_profile_hibern8(dev_name(hba->dev), "enter",
3670 ktime_to_us(ktime_sub(ktime_get(), start)), ret);
3673 dev_err(hba->dev, "%s: hibern8 enter failed. ret = %d\n",
3677 * If link recovery fails then return error so that caller
3678 * don't retry the hibern8 enter again.
3680 if (ufshcd_link_recovery(hba))
3683 ufshcd_vops_hibern8_notify(hba, UIC_CMD_DME_HIBER_ENTER,
3689 static int ufshcd_uic_hibern8_enter(struct ufs_hba *hba)
3691 int ret = 0, retries;
3693 for (retries = UIC_HIBERN8_ENTER_RETRIES; retries > 0; retries--) {
3694 ret = __ufshcd_uic_hibern8_enter(hba);
3695 if (!ret || ret == -ENOLINK)
3702 static int ufshcd_uic_hibern8_exit(struct ufs_hba *hba)
3704 struct uic_command uic_cmd = {0};
3706 ktime_t start = ktime_get();
3708 ufshcd_vops_hibern8_notify(hba, UIC_CMD_DME_HIBER_EXIT, PRE_CHANGE);
3710 uic_cmd.command = UIC_CMD_DME_HIBER_EXIT;
3711 ret = ufshcd_uic_pwr_ctrl(hba, &uic_cmd);
3712 trace_ufshcd_profile_hibern8(dev_name(hba->dev), "exit",
3713 ktime_to_us(ktime_sub(ktime_get(), start)), ret);
3716 dev_err(hba->dev, "%s: hibern8 exit failed. ret = %d\n",
3718 ret = ufshcd_link_recovery(hba);
3720 ufshcd_vops_hibern8_notify(hba, UIC_CMD_DME_HIBER_EXIT,
3722 hba->ufs_stats.last_hibern8_exit_tstamp = ktime_get();
3723 hba->ufs_stats.hibern8_exit_cnt++;
3729 static void ufshcd_auto_hibern8_enable(struct ufs_hba *hba)
3731 unsigned long flags;
3733 if (!(hba->capabilities & MASK_AUTO_HIBERN8_SUPPORT) || !hba->ahit)
3736 spin_lock_irqsave(hba->host->host_lock, flags);
3737 ufshcd_writel(hba, hba->ahit, REG_AUTO_HIBERNATE_IDLE_TIMER);
3738 spin_unlock_irqrestore(hba->host->host_lock, flags);
3742 * ufshcd_init_pwr_info - setting the POR (power on reset)
3743 * values in hba power info
3744 * @hba: per-adapter instance
3746 static void ufshcd_init_pwr_info(struct ufs_hba *hba)
3748 hba->pwr_info.gear_rx = UFS_PWM_G1;
3749 hba->pwr_info.gear_tx = UFS_PWM_G1;
3750 hba->pwr_info.lane_rx = 1;
3751 hba->pwr_info.lane_tx = 1;
3752 hba->pwr_info.pwr_rx = SLOWAUTO_MODE;
3753 hba->pwr_info.pwr_tx = SLOWAUTO_MODE;
3754 hba->pwr_info.hs_rate = 0;
3758 * ufshcd_get_max_pwr_mode - reads the max power mode negotiated with device
3759 * @hba: per-adapter instance
3761 static int ufshcd_get_max_pwr_mode(struct ufs_hba *hba)
3763 struct ufs_pa_layer_attr *pwr_info = &hba->max_pwr_info.info;
3765 if (hba->max_pwr_info.is_valid)
3768 pwr_info->pwr_tx = FAST_MODE;
3769 pwr_info->pwr_rx = FAST_MODE;
3770 pwr_info->hs_rate = PA_HS_MODE_B;
3772 /* Get the connected lane count */
3773 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_CONNECTEDRXDATALANES),
3774 &pwr_info->lane_rx);
3775 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_CONNECTEDTXDATALANES),
3776 &pwr_info->lane_tx);
3778 if (!pwr_info->lane_rx || !pwr_info->lane_tx) {
3779 dev_err(hba->dev, "%s: invalid connected lanes value. rx=%d, tx=%d\n",
3787 * First, get the maximum gears of HS speed.
3788 * If a zero value, it means there is no HSGEAR capability.
3789 * Then, get the maximum gears of PWM speed.
3791 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_MAXRXHSGEAR), &pwr_info->gear_rx);
3792 if (!pwr_info->gear_rx) {
3793 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_MAXRXPWMGEAR),
3794 &pwr_info->gear_rx);
3795 if (!pwr_info->gear_rx) {
3796 dev_err(hba->dev, "%s: invalid max pwm rx gear read = %d\n",
3797 __func__, pwr_info->gear_rx);
3800 pwr_info->pwr_rx = SLOW_MODE;
3803 ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_MAXRXHSGEAR),
3804 &pwr_info->gear_tx);
3805 if (!pwr_info->gear_tx) {
3806 ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_MAXRXPWMGEAR),
3807 &pwr_info->gear_tx);
3808 if (!pwr_info->gear_tx) {
3809 dev_err(hba->dev, "%s: invalid max pwm tx gear read = %d\n",
3810 __func__, pwr_info->gear_tx);
3813 pwr_info->pwr_tx = SLOW_MODE;
3816 hba->max_pwr_info.is_valid = true;
3820 static int ufshcd_change_power_mode(struct ufs_hba *hba,
3821 struct ufs_pa_layer_attr *pwr_mode)
3825 /* if already configured to the requested pwr_mode */
3826 if (pwr_mode->gear_rx == hba->pwr_info.gear_rx &&
3827 pwr_mode->gear_tx == hba->pwr_info.gear_tx &&
3828 pwr_mode->lane_rx == hba->pwr_info.lane_rx &&
3829 pwr_mode->lane_tx == hba->pwr_info.lane_tx &&
3830 pwr_mode->pwr_rx == hba->pwr_info.pwr_rx &&
3831 pwr_mode->pwr_tx == hba->pwr_info.pwr_tx &&
3832 pwr_mode->hs_rate == hba->pwr_info.hs_rate) {
3833 dev_dbg(hba->dev, "%s: power already configured\n", __func__);
3838 * Configure attributes for power mode change with below.
3839 * - PA_RXGEAR, PA_ACTIVERXDATALANES, PA_RXTERMINATION,
3840 * - PA_TXGEAR, PA_ACTIVETXDATALANES, PA_TXTERMINATION,
3843 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_RXGEAR), pwr_mode->gear_rx);
3844 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_ACTIVERXDATALANES),
3846 if (pwr_mode->pwr_rx == FASTAUTO_MODE ||
3847 pwr_mode->pwr_rx == FAST_MODE)
3848 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_RXTERMINATION), TRUE);
3850 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_RXTERMINATION), FALSE);
3852 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TXGEAR), pwr_mode->gear_tx);
3853 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_ACTIVETXDATALANES),
3855 if (pwr_mode->pwr_tx == FASTAUTO_MODE ||
3856 pwr_mode->pwr_tx == FAST_MODE)
3857 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TXTERMINATION), TRUE);
3859 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TXTERMINATION), FALSE);
3861 if (pwr_mode->pwr_rx == FASTAUTO_MODE ||
3862 pwr_mode->pwr_tx == FASTAUTO_MODE ||
3863 pwr_mode->pwr_rx == FAST_MODE ||
3864 pwr_mode->pwr_tx == FAST_MODE)
3865 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_HSSERIES),
3868 ret = ufshcd_uic_change_pwr_mode(hba, pwr_mode->pwr_rx << 4
3869 | pwr_mode->pwr_tx);
3873 "%s: power mode change failed %d\n", __func__, ret);
3875 ufshcd_vops_pwr_change_notify(hba, POST_CHANGE, NULL,
3878 memcpy(&hba->pwr_info, pwr_mode,
3879 sizeof(struct ufs_pa_layer_attr));
3886 * ufshcd_config_pwr_mode - configure a new power mode
3887 * @hba: per-adapter instance
3888 * @desired_pwr_mode: desired power configuration
3890 static int ufshcd_config_pwr_mode(struct ufs_hba *hba,
3891 struct ufs_pa_layer_attr *desired_pwr_mode)
3893 struct ufs_pa_layer_attr final_params = { 0 };
3896 ret = ufshcd_vops_pwr_change_notify(hba, PRE_CHANGE,
3897 desired_pwr_mode, &final_params);
3900 memcpy(&final_params, desired_pwr_mode, sizeof(final_params));
3902 ret = ufshcd_change_power_mode(hba, &final_params);
3904 ufshcd_print_pwr_info(hba);
3910 * ufshcd_complete_dev_init() - checks device readiness
3911 * @hba: per-adapter instance
3913 * Set fDeviceInit flag and poll until device toggles it.
3915 static int ufshcd_complete_dev_init(struct ufs_hba *hba)
3921 err = ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_SET_FLAG,
3922 QUERY_FLAG_IDN_FDEVICEINIT, NULL);
3925 "%s setting fDeviceInit flag failed with error %d\n",
3930 /* poll for max. 1000 iterations for fDeviceInit flag to clear */
3931 for (i = 0; i < 1000 && !err && flag_res; i++)
3932 err = ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_READ_FLAG,
3933 QUERY_FLAG_IDN_FDEVICEINIT, &flag_res);
3937 "%s reading fDeviceInit flag failed with error %d\n",
3941 "%s fDeviceInit was not cleared by the device\n",
3949 * ufshcd_make_hba_operational - Make UFS controller operational
3950 * @hba: per adapter instance
3952 * To bring UFS host controller to operational state,
3953 * 1. Enable required interrupts
3954 * 2. Configure interrupt aggregation
3955 * 3. Program UTRL and UTMRL base address
3956 * 4. Configure run-stop-registers
3958 * Returns 0 on success, non-zero value on failure
3960 static int ufshcd_make_hba_operational(struct ufs_hba *hba)
3965 /* Enable required interrupts */
3966 ufshcd_enable_intr(hba, UFSHCD_ENABLE_INTRS);
3968 /* Configure interrupt aggregation */
3969 if (ufshcd_is_intr_aggr_allowed(hba))
3970 ufshcd_config_intr_aggr(hba, hba->nutrs - 1, INT_AGGR_DEF_TO);
3972 ufshcd_disable_intr_aggr(hba);
3974 /* Configure UTRL and UTMRL base address registers */
3975 ufshcd_writel(hba, lower_32_bits(hba->utrdl_dma_addr),
3976 REG_UTP_TRANSFER_REQ_LIST_BASE_L);
3977 ufshcd_writel(hba, upper_32_bits(hba->utrdl_dma_addr),
3978 REG_UTP_TRANSFER_REQ_LIST_BASE_H);
3979 ufshcd_writel(hba, lower_32_bits(hba->utmrdl_dma_addr),
3980 REG_UTP_TASK_REQ_LIST_BASE_L);
3981 ufshcd_writel(hba, upper_32_bits(hba->utmrdl_dma_addr),
3982 REG_UTP_TASK_REQ_LIST_BASE_H);
3985 * Make sure base address and interrupt setup are updated before
3986 * enabling the run/stop registers below.
3991 * UCRDY, UTMRLDY and UTRLRDY bits must be 1
3993 reg = ufshcd_readl(hba, REG_CONTROLLER_STATUS);
3994 if (!(ufshcd_get_lists_status(reg))) {
3995 ufshcd_enable_run_stop_reg(hba);
3998 "Host controller not ready to process requests");
4008 * ufshcd_hba_stop - Send controller to reset state
4009 * @hba: per adapter instance
4010 * @can_sleep: perform sleep or just spin
4012 static inline void ufshcd_hba_stop(struct ufs_hba *hba, bool can_sleep)
4016 ufshcd_writel(hba, CONTROLLER_DISABLE, REG_CONTROLLER_ENABLE);
4017 err = ufshcd_wait_for_register(hba, REG_CONTROLLER_ENABLE,
4018 CONTROLLER_ENABLE, CONTROLLER_DISABLE,
4021 dev_err(hba->dev, "%s: Controller disable failed\n", __func__);
4025 * ufshcd_hba_enable - initialize the controller
4026 * @hba: per adapter instance
4028 * The controller resets itself and controller firmware initialization
4029 * sequence kicks off. When controller is ready it will set
4030 * the Host Controller Enable bit to 1.
4032 * Returns 0 on success, non-zero value on failure
4034 static int ufshcd_hba_enable(struct ufs_hba *hba)
4039 * msleep of 1 and 5 used in this function might result in msleep(20),
4040 * but it was necessary to send the UFS FPGA to reset mode during
4041 * development and testing of this driver. msleep can be changed to
4042 * mdelay and retry count can be reduced based on the controller.
4044 if (!ufshcd_is_hba_active(hba))
4045 /* change controller state to "reset state" */
4046 ufshcd_hba_stop(hba, true);
4048 /* UniPro link is disabled at this point */
4049 ufshcd_set_link_off(hba);
4051 ufshcd_vops_hce_enable_notify(hba, PRE_CHANGE);
4053 /* start controller initialization sequence */
4054 ufshcd_hba_start(hba);
4057 * To initialize a UFS host controller HCE bit must be set to 1.
4058 * During initialization the HCE bit value changes from 1->0->1.
4059 * When the host controller completes initialization sequence
4060 * it sets the value of HCE bit to 1. The same HCE bit is read back
4061 * to check if the controller has completed initialization sequence.
4062 * So without this delay the value HCE = 1, set in the previous
4063 * instruction might be read back.
4064 * This delay can be changed based on the controller.
4068 /* wait for the host controller to complete initialization */
4070 while (ufshcd_is_hba_active(hba)) {
4075 "Controller enable failed\n");
4081 /* enable UIC related interrupts */
4082 ufshcd_enable_intr(hba, UFSHCD_UIC_MASK);
4084 ufshcd_vops_hce_enable_notify(hba, POST_CHANGE);
4089 static int ufshcd_disable_tx_lcc(struct ufs_hba *hba, bool peer)
4091 int tx_lanes, i, err = 0;
4094 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_CONNECTEDTXDATALANES),
4097 ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_CONNECTEDTXDATALANES),
4099 for (i = 0; i < tx_lanes; i++) {
4101 err = ufshcd_dme_set(hba,
4102 UIC_ARG_MIB_SEL(TX_LCC_ENABLE,
4103 UIC_ARG_MPHY_TX_GEN_SEL_INDEX(i)),
4106 err = ufshcd_dme_peer_set(hba,
4107 UIC_ARG_MIB_SEL(TX_LCC_ENABLE,
4108 UIC_ARG_MPHY_TX_GEN_SEL_INDEX(i)),
4111 dev_err(hba->dev, "%s: TX LCC Disable failed, peer = %d, lane = %d, err = %d",
4112 __func__, peer, i, err);
4120 static inline int ufshcd_disable_device_tx_lcc(struct ufs_hba *hba)
4122 return ufshcd_disable_tx_lcc(hba, true);
4126 * ufshcd_link_startup - Initialize unipro link startup
4127 * @hba: per adapter instance
4129 * Returns 0 for success, non-zero in case of failure
4131 static int ufshcd_link_startup(struct ufs_hba *hba)
4134 int retries = DME_LINKSTARTUP_RETRIES;
4135 bool link_startup_again = false;
4138 * If UFS device isn't active then we will have to issue link startup
4139 * 2 times to make sure the device state move to active.
4141 if (!ufshcd_is_ufs_dev_active(hba))
4142 link_startup_again = true;
4146 ufshcd_vops_link_startup_notify(hba, PRE_CHANGE);
4148 ret = ufshcd_dme_link_startup(hba);
4150 /* check if device is detected by inter-connect layer */
4151 if (!ret && !ufshcd_is_device_present(hba)) {
4152 dev_err(hba->dev, "%s: Device not present\n", __func__);
4158 * DME link lost indication is only received when link is up,
4159 * but we can't be sure if the link is up until link startup
4160 * succeeds. So reset the local Uni-Pro and try again.
4162 if (ret && ufshcd_hba_enable(hba))
4164 } while (ret && retries--);
4167 /* failed to get the link up... retire */
4170 if (link_startup_again) {
4171 link_startup_again = false;
4172 retries = DME_LINKSTARTUP_RETRIES;
4176 /* Mark that link is up in PWM-G1, 1-lane, SLOW-AUTO mode */
4177 ufshcd_init_pwr_info(hba);
4178 ufshcd_print_pwr_info(hba);
4180 if (hba->quirks & UFSHCD_QUIRK_BROKEN_LCC) {
4181 ret = ufshcd_disable_device_tx_lcc(hba);
4186 /* Include any host controller configuration via UIC commands */
4187 ret = ufshcd_vops_link_startup_notify(hba, POST_CHANGE);
4191 ret = ufshcd_make_hba_operational(hba);
4194 dev_err(hba->dev, "link startup failed %d\n", ret);
4195 ufshcd_print_host_state(hba);
4196 ufshcd_print_pwr_info(hba);
4197 ufshcd_print_host_regs(hba);
4203 * ufshcd_verify_dev_init() - Verify device initialization
4204 * @hba: per-adapter instance
4206 * Send NOP OUT UPIU and wait for NOP IN response to check whether the
4207 * device Transport Protocol (UTP) layer is ready after a reset.
4208 * If the UTP layer at the device side is not initialized, it may
4209 * not respond with NOP IN UPIU within timeout of %NOP_OUT_TIMEOUT
4210 * and we retry sending NOP OUT for %NOP_OUT_RETRIES iterations.
4212 static int ufshcd_verify_dev_init(struct ufs_hba *hba)
4217 ufshcd_hold(hba, false);
4218 mutex_lock(&hba->dev_cmd.lock);
4219 for (retries = NOP_OUT_RETRIES; retries > 0; retries--) {
4220 err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_NOP,
4223 if (!err || err == -ETIMEDOUT)
4226 dev_dbg(hba->dev, "%s: error %d retrying\n", __func__, err);
4228 mutex_unlock(&hba->dev_cmd.lock);
4229 ufshcd_release(hba);
4232 dev_err(hba->dev, "%s: NOP OUT failed %d\n", __func__, err);
4237 * ufshcd_set_queue_depth - set lun queue depth
4238 * @sdev: pointer to SCSI device
4240 * Read bLUQueueDepth value and activate scsi tagged command
4241 * queueing. For WLUN, queue depth is set to 1. For best-effort
4242 * cases (bLUQueueDepth = 0) the queue depth is set to a maximum
4243 * value that host can queue.
4245 static void ufshcd_set_queue_depth(struct scsi_device *sdev)
4249 struct ufs_hba *hba;
4251 hba = shost_priv(sdev->host);
4253 lun_qdepth = hba->nutrs;
4254 ret = ufshcd_read_unit_desc_param(hba,
4255 ufshcd_scsi_to_upiu_lun(sdev->lun),
4256 UNIT_DESC_PARAM_LU_Q_DEPTH,
4258 sizeof(lun_qdepth));
4260 /* Some WLUN doesn't support unit descriptor */
4261 if (ret == -EOPNOTSUPP)
4263 else if (!lun_qdepth)
4264 /* eventually, we can figure out the real queue depth */
4265 lun_qdepth = hba->nutrs;
4267 lun_qdepth = min_t(int, lun_qdepth, hba->nutrs);
4269 dev_dbg(hba->dev, "%s: activate tcq with queue depth %d\n",
4270 __func__, lun_qdepth);
4271 scsi_change_queue_depth(sdev, lun_qdepth);
4275 * ufshcd_get_lu_wp - returns the "b_lu_write_protect" from UNIT DESCRIPTOR
4276 * @hba: per-adapter instance
4277 * @lun: UFS device lun id
4278 * @b_lu_write_protect: pointer to buffer to hold the LU's write protect info
4280 * Returns 0 in case of success and b_lu_write_protect status would be returned
4281 * @b_lu_write_protect parameter.
4282 * Returns -ENOTSUPP if reading b_lu_write_protect is not supported.
4283 * Returns -EINVAL in case of invalid parameters passed to this function.
4285 static int ufshcd_get_lu_wp(struct ufs_hba *hba,
4287 u8 *b_lu_write_protect)
4291 if (!b_lu_write_protect)
4294 * According to UFS device spec, RPMB LU can't be write
4295 * protected so skip reading bLUWriteProtect parameter for
4296 * it. For other W-LUs, UNIT DESCRIPTOR is not available.
4298 else if (lun >= UFS_UPIU_MAX_GENERAL_LUN)
4301 ret = ufshcd_read_unit_desc_param(hba,
4303 UNIT_DESC_PARAM_LU_WR_PROTECT,
4305 sizeof(*b_lu_write_protect));
4310 * ufshcd_get_lu_power_on_wp_status - get LU's power on write protect
4312 * @hba: per-adapter instance
4313 * @sdev: pointer to SCSI device
4316 static inline void ufshcd_get_lu_power_on_wp_status(struct ufs_hba *hba,
4317 struct scsi_device *sdev)
4319 if (hba->dev_info.f_power_on_wp_en &&
4320 !hba->dev_info.is_lu_power_on_wp) {
4321 u8 b_lu_write_protect;
4323 if (!ufshcd_get_lu_wp(hba, ufshcd_scsi_to_upiu_lun(sdev->lun),
4324 &b_lu_write_protect) &&
4325 (b_lu_write_protect == UFS_LU_POWER_ON_WP))
4326 hba->dev_info.is_lu_power_on_wp = true;
4331 * ufshcd_slave_alloc - handle initial SCSI device configurations
4332 * @sdev: pointer to SCSI device
4336 static int ufshcd_slave_alloc(struct scsi_device *sdev)
4338 struct ufs_hba *hba;
4340 hba = shost_priv(sdev->host);
4342 /* Mode sense(6) is not supported by UFS, so use Mode sense(10) */
4343 sdev->use_10_for_ms = 1;
4345 /* allow SCSI layer to restart the device in case of errors */
4346 sdev->allow_restart = 1;
4348 /* REPORT SUPPORTED OPERATION CODES is not supported */
4349 sdev->no_report_opcodes = 1;
4351 /* WRITE_SAME command is not supported */
4352 sdev->no_write_same = 1;
4354 ufshcd_set_queue_depth(sdev);
4356 ufshcd_get_lu_power_on_wp_status(hba, sdev);
4362 * ufshcd_change_queue_depth - change queue depth
4363 * @sdev: pointer to SCSI device
4364 * @depth: required depth to set
4366 * Change queue depth and make sure the max. limits are not crossed.
4368 static int ufshcd_change_queue_depth(struct scsi_device *sdev, int depth)
4370 struct ufs_hba *hba = shost_priv(sdev->host);
4372 if (depth > hba->nutrs)
4374 return scsi_change_queue_depth(sdev, depth);
4378 * ufshcd_slave_configure - adjust SCSI device configurations
4379 * @sdev: pointer to SCSI device
4381 static int ufshcd_slave_configure(struct scsi_device *sdev)
4383 struct request_queue *q = sdev->request_queue;
4385 blk_queue_update_dma_pad(q, PRDT_DATA_BYTE_COUNT_PAD - 1);
4386 blk_queue_max_segment_size(q, PRDT_DATA_BYTE_COUNT_MAX);
4392 * ufshcd_slave_destroy - remove SCSI device configurations
4393 * @sdev: pointer to SCSI device
4395 static void ufshcd_slave_destroy(struct scsi_device *sdev)
4397 struct ufs_hba *hba;
4399 hba = shost_priv(sdev->host);
4400 /* Drop the reference as it won't be needed anymore */
4401 if (ufshcd_scsi_to_upiu_lun(sdev->lun) == UFS_UPIU_UFS_DEVICE_WLUN) {
4402 unsigned long flags;
4404 spin_lock_irqsave(hba->host->host_lock, flags);
4405 hba->sdev_ufs_device = NULL;
4406 spin_unlock_irqrestore(hba->host->host_lock, flags);
4411 * ufshcd_task_req_compl - handle task management request completion
4412 * @hba: per adapter instance
4413 * @index: index of the completed request
4414 * @resp: task management service response
4416 * Returns non-zero value on error, zero on success
4418 static int ufshcd_task_req_compl(struct ufs_hba *hba, u32 index, u8 *resp)
4420 struct utp_task_req_desc *task_req_descp;
4421 struct utp_upiu_task_rsp *task_rsp_upiup;
4422 unsigned long flags;
4426 spin_lock_irqsave(hba->host->host_lock, flags);
4428 /* Clear completed tasks from outstanding_tasks */
4429 __clear_bit(index, &hba->outstanding_tasks);
4431 task_req_descp = hba->utmrdl_base_addr;
4432 ocs_value = ufshcd_get_tmr_ocs(&task_req_descp[index]);
4434 if (ocs_value == OCS_SUCCESS) {
4435 task_rsp_upiup = (struct utp_upiu_task_rsp *)
4436 task_req_descp[index].task_rsp_upiu;
4437 task_result = be32_to_cpu(task_rsp_upiup->output_param1);
4438 task_result = task_result & MASK_TM_SERVICE_RESP;
4440 *resp = (u8)task_result;
4442 dev_err(hba->dev, "%s: failed, ocs = 0x%x\n",
4443 __func__, ocs_value);
4445 spin_unlock_irqrestore(hba->host->host_lock, flags);
4451 * ufshcd_scsi_cmd_status - Update SCSI command result based on SCSI status
4452 * @lrbp: pointer to local reference block of completed command
4453 * @scsi_status: SCSI command status
4455 * Returns value base on SCSI command status
4458 ufshcd_scsi_cmd_status(struct ufshcd_lrb *lrbp, int scsi_status)
4462 switch (scsi_status) {
4463 case SAM_STAT_CHECK_CONDITION:
4464 ufshcd_copy_sense_data(lrbp);
4466 result |= DID_OK << 16 |
4467 COMMAND_COMPLETE << 8 |
4470 case SAM_STAT_TASK_SET_FULL:
4472 case SAM_STAT_TASK_ABORTED:
4473 ufshcd_copy_sense_data(lrbp);
4474 result |= scsi_status;
4477 result |= DID_ERROR << 16;
4479 } /* end of switch */
4485 * ufshcd_transfer_rsp_status - Get overall status of the response
4486 * @hba: per adapter instance
4487 * @lrbp: pointer to local reference block of completed command
4489 * Returns result of the command to notify SCSI midlayer
4492 ufshcd_transfer_rsp_status(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
4498 /* overall command status of utrd */
4499 ocs = ufshcd_get_tr_ocs(lrbp);
4503 result = ufshcd_get_req_rsp(lrbp->ucd_rsp_ptr);
4504 hba->ufs_stats.last_hibern8_exit_tstamp = ktime_set(0, 0);
4506 case UPIU_TRANSACTION_RESPONSE:
4508 * get the response UPIU result to extract
4509 * the SCSI command status
4511 result = ufshcd_get_rsp_upiu_result(lrbp->ucd_rsp_ptr);
4514 * get the result based on SCSI status response
4515 * to notify the SCSI midlayer of the command status
4517 scsi_status = result & MASK_SCSI_STATUS;
4518 result = ufshcd_scsi_cmd_status(lrbp, scsi_status);
4521 * Currently we are only supporting BKOPs exception
4522 * events hence we can ignore BKOPs exception event
4523 * during power management callbacks. BKOPs exception
4524 * event is not expected to be raised in runtime suspend
4525 * callback as it allows the urgent bkops.
4526 * During system suspend, we are anyway forcefully
4527 * disabling the bkops and if urgent bkops is needed
4528 * it will be enabled on system resume. Long term
4529 * solution could be to abort the system suspend if
4530 * UFS device needs urgent BKOPs.
4532 if (!hba->pm_op_in_progress &&
4533 ufshcd_is_exception_event(lrbp->ucd_rsp_ptr))
4534 schedule_work(&hba->eeh_work);
4536 case UPIU_TRANSACTION_REJECT_UPIU:
4537 /* TODO: handle Reject UPIU Response */
4538 result = DID_ERROR << 16;
4540 "Reject UPIU not fully implemented\n");
4543 result = DID_ERROR << 16;
4545 "Unexpected request response code = %x\n",
4551 result |= DID_ABORT << 16;
4553 case OCS_INVALID_COMMAND_STATUS:
4554 result |= DID_REQUEUE << 16;
4556 case OCS_INVALID_CMD_TABLE_ATTR:
4557 case OCS_INVALID_PRDT_ATTR:
4558 case OCS_MISMATCH_DATA_BUF_SIZE:
4559 case OCS_MISMATCH_RESP_UPIU_SIZE:
4560 case OCS_PEER_COMM_FAILURE:
4561 case OCS_FATAL_ERROR:
4563 result |= DID_ERROR << 16;
4565 "OCS error from controller = %x for tag %d\n",
4566 ocs, lrbp->task_tag);
4567 ufshcd_print_host_regs(hba);
4568 ufshcd_print_host_state(hba);
4570 } /* end of switch */
4572 if (host_byte(result) != DID_OK)
4573 ufshcd_print_trs(hba, 1 << lrbp->task_tag, true);
4578 * ufshcd_uic_cmd_compl - handle completion of uic command
4579 * @hba: per adapter instance
4580 * @intr_status: interrupt status generated by the controller
4582 static void ufshcd_uic_cmd_compl(struct ufs_hba *hba, u32 intr_status)
4584 if ((intr_status & UIC_COMMAND_COMPL) && hba->active_uic_cmd) {
4585 hba->active_uic_cmd->argument2 |=
4586 ufshcd_get_uic_cmd_result(hba);
4587 hba->active_uic_cmd->argument3 =
4588 ufshcd_get_dme_attr_val(hba);
4589 complete(&hba->active_uic_cmd->done);
4592 if ((intr_status & UFSHCD_UIC_PWR_MASK) && hba->uic_async_done)
4593 complete(hba->uic_async_done);
4597 * __ufshcd_transfer_req_compl - handle SCSI and query command completion
4598 * @hba: per adapter instance
4599 * @completed_reqs: requests to complete
4601 static void __ufshcd_transfer_req_compl(struct ufs_hba *hba,
4602 unsigned long completed_reqs)
4604 struct ufshcd_lrb *lrbp;
4605 struct scsi_cmnd *cmd;
4609 for_each_set_bit(index, &completed_reqs, hba->nutrs) {
4610 lrbp = &hba->lrb[index];
4613 ufshcd_add_command_trace(hba, index, "complete");
4614 result = ufshcd_transfer_rsp_status(hba, lrbp);
4615 scsi_dma_unmap(cmd);
4616 cmd->result = result;
4617 /* Mark completed command as NULL in LRB */
4619 clear_bit_unlock(index, &hba->lrb_in_use);
4620 /* Do not touch lrbp after scsi done */
4621 cmd->scsi_done(cmd);
4622 __ufshcd_release(hba);
4623 } else if (lrbp->command_type == UTP_CMD_TYPE_DEV_MANAGE ||
4624 lrbp->command_type == UTP_CMD_TYPE_UFS_STORAGE) {
4625 if (hba->dev_cmd.complete) {
4626 ufshcd_add_command_trace(hba, index,
4628 complete(hba->dev_cmd.complete);
4631 if (ufshcd_is_clkscaling_supported(hba))
4632 hba->clk_scaling.active_reqs--;
4634 lrbp->compl_time_stamp = ktime_get();
4637 /* clear corresponding bits of completed commands */
4638 hba->outstanding_reqs ^= completed_reqs;
4640 ufshcd_clk_scaling_update_busy(hba);
4642 /* we might have free'd some tags above */
4643 wake_up(&hba->dev_cmd.tag_wq);
4647 * ufshcd_transfer_req_compl - handle SCSI and query command completion
4648 * @hba: per adapter instance
4650 static void ufshcd_transfer_req_compl(struct ufs_hba *hba)
4652 unsigned long completed_reqs;
4655 /* Resetting interrupt aggregation counters first and reading the
4656 * DOOR_BELL afterward allows us to handle all the completed requests.
4657 * In order to prevent other interrupts starvation the DB is read once
4658 * after reset. The down side of this solution is the possibility of
4659 * false interrupt if device completes another request after resetting
4660 * aggregation and before reading the DB.
4662 if (ufshcd_is_intr_aggr_allowed(hba))
4663 ufshcd_reset_intr_aggr(hba);
4665 tr_doorbell = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
4666 completed_reqs = tr_doorbell ^ hba->outstanding_reqs;
4668 __ufshcd_transfer_req_compl(hba, completed_reqs);
4672 * ufshcd_disable_ee - disable exception event
4673 * @hba: per-adapter instance
4674 * @mask: exception event to disable
4676 * Disables exception event in the device so that the EVENT_ALERT
4679 * Returns zero on success, non-zero error value on failure.
4681 static int ufshcd_disable_ee(struct ufs_hba *hba, u16 mask)
4686 if (!(hba->ee_ctrl_mask & mask))
4689 val = hba->ee_ctrl_mask & ~mask;
4690 val &= MASK_EE_STATUS;
4691 err = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_WRITE_ATTR,
4692 QUERY_ATTR_IDN_EE_CONTROL, 0, 0, &val);
4694 hba->ee_ctrl_mask &= ~mask;
4700 * ufshcd_enable_ee - enable exception event
4701 * @hba: per-adapter instance
4702 * @mask: exception event to enable
4704 * Enable corresponding exception event in the device to allow
4705 * device to alert host in critical scenarios.
4707 * Returns zero on success, non-zero error value on failure.
4709 static int ufshcd_enable_ee(struct ufs_hba *hba, u16 mask)
4714 if (hba->ee_ctrl_mask & mask)
4717 val = hba->ee_ctrl_mask | mask;
4718 val &= MASK_EE_STATUS;
4719 err = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_WRITE_ATTR,
4720 QUERY_ATTR_IDN_EE_CONTROL, 0, 0, &val);
4722 hba->ee_ctrl_mask |= mask;
4728 * ufshcd_enable_auto_bkops - Allow device managed BKOPS
4729 * @hba: per-adapter instance
4731 * Allow device to manage background operations on its own. Enabling
4732 * this might lead to inconsistent latencies during normal data transfers
4733 * as the device is allowed to manage its own way of handling background
4736 * Returns zero on success, non-zero on failure.
4738 static int ufshcd_enable_auto_bkops(struct ufs_hba *hba)
4742 if (hba->auto_bkops_enabled)
4745 err = ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_SET_FLAG,
4746 QUERY_FLAG_IDN_BKOPS_EN, NULL);
4748 dev_err(hba->dev, "%s: failed to enable bkops %d\n",
4753 hba->auto_bkops_enabled = true;
4754 trace_ufshcd_auto_bkops_state(dev_name(hba->dev), "Enabled");
4756 /* No need of URGENT_BKOPS exception from the device */
4757 err = ufshcd_disable_ee(hba, MASK_EE_URGENT_BKOPS);
4759 dev_err(hba->dev, "%s: failed to disable exception event %d\n",
4766 * ufshcd_disable_auto_bkops - block device in doing background operations
4767 * @hba: per-adapter instance
4769 * Disabling background operations improves command response latency but
4770 * has drawback of device moving into critical state where the device is
4771 * not-operable. Make sure to call ufshcd_enable_auto_bkops() whenever the
4772 * host is idle so that BKOPS are managed effectively without any negative
4775 * Returns zero on success, non-zero on failure.
4777 static int ufshcd_disable_auto_bkops(struct ufs_hba *hba)
4781 if (!hba->auto_bkops_enabled)
4785 * If host assisted BKOPs is to be enabled, make sure
4786 * urgent bkops exception is allowed.
4788 err = ufshcd_enable_ee(hba, MASK_EE_URGENT_BKOPS);
4790 dev_err(hba->dev, "%s: failed to enable exception event %d\n",
4795 err = ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_CLEAR_FLAG,
4796 QUERY_FLAG_IDN_BKOPS_EN, NULL);
4798 dev_err(hba->dev, "%s: failed to disable bkops %d\n",
4800 ufshcd_disable_ee(hba, MASK_EE_URGENT_BKOPS);
4804 hba->auto_bkops_enabled = false;
4805 trace_ufshcd_auto_bkops_state(dev_name(hba->dev), "Disabled");
4811 * ufshcd_force_reset_auto_bkops - force reset auto bkops state
4812 * @hba: per adapter instance
4814 * After a device reset the device may toggle the BKOPS_EN flag
4815 * to default value. The s/w tracking variables should be updated
4816 * as well. This function would change the auto-bkops state based on
4817 * UFSHCD_CAP_KEEP_AUTO_BKOPS_ENABLED_EXCEPT_SUSPEND.
4819 static void ufshcd_force_reset_auto_bkops(struct ufs_hba *hba)
4821 if (ufshcd_keep_autobkops_enabled_except_suspend(hba)) {
4822 hba->auto_bkops_enabled = false;
4823 hba->ee_ctrl_mask |= MASK_EE_URGENT_BKOPS;
4824 ufshcd_enable_auto_bkops(hba);
4826 hba->auto_bkops_enabled = true;
4827 hba->ee_ctrl_mask &= ~MASK_EE_URGENT_BKOPS;
4828 ufshcd_disable_auto_bkops(hba);
4832 static inline int ufshcd_get_bkops_status(struct ufs_hba *hba, u32 *status)
4834 return ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
4835 QUERY_ATTR_IDN_BKOPS_STATUS, 0, 0, status);
4839 * ufshcd_bkops_ctrl - control the auto bkops based on current bkops status
4840 * @hba: per-adapter instance
4841 * @status: bkops_status value
4843 * Read the bkops_status from the UFS device and Enable fBackgroundOpsEn
4844 * flag in the device to permit background operations if the device
4845 * bkops_status is greater than or equal to "status" argument passed to
4846 * this function, disable otherwise.
4848 * Returns 0 for success, non-zero in case of failure.
4850 * NOTE: Caller of this function can check the "hba->auto_bkops_enabled" flag
4851 * to know whether auto bkops is enabled or disabled after this function
4852 * returns control to it.
4854 static int ufshcd_bkops_ctrl(struct ufs_hba *hba,
4855 enum bkops_status status)
4858 u32 curr_status = 0;
4860 err = ufshcd_get_bkops_status(hba, &curr_status);
4862 dev_err(hba->dev, "%s: failed to get BKOPS status %d\n",
4865 } else if (curr_status > BKOPS_STATUS_MAX) {
4866 dev_err(hba->dev, "%s: invalid BKOPS status %d\n",
4867 __func__, curr_status);
4872 if (curr_status >= status)
4873 err = ufshcd_enable_auto_bkops(hba);
4875 err = ufshcd_disable_auto_bkops(hba);
4881 * ufshcd_urgent_bkops - handle urgent bkops exception event
4882 * @hba: per-adapter instance
4884 * Enable fBackgroundOpsEn flag in the device to permit background
4887 * If BKOPs is enabled, this function returns 0, 1 if the bkops in not enabled
4888 * and negative error value for any other failure.
4890 static int ufshcd_urgent_bkops(struct ufs_hba *hba)
4892 return ufshcd_bkops_ctrl(hba, hba->urgent_bkops_lvl);
4895 static inline int ufshcd_get_ee_status(struct ufs_hba *hba, u32 *status)
4897 return ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
4898 QUERY_ATTR_IDN_EE_STATUS, 0, 0, status);
4901 static void ufshcd_bkops_exception_event_handler(struct ufs_hba *hba)
4904 u32 curr_status = 0;
4906 if (hba->is_urgent_bkops_lvl_checked)
4907 goto enable_auto_bkops;
4909 err = ufshcd_get_bkops_status(hba, &curr_status);
4911 dev_err(hba->dev, "%s: failed to get BKOPS status %d\n",
4917 * We are seeing that some devices are raising the urgent bkops
4918 * exception events even when BKOPS status doesn't indicate performace
4919 * impacted or critical. Handle these device by determining their urgent
4920 * bkops status at runtime.
4922 if (curr_status < BKOPS_STATUS_PERF_IMPACT) {
4923 dev_err(hba->dev, "%s: device raised urgent BKOPS exception for bkops status %d\n",
4924 __func__, curr_status);
4925 /* update the current status as the urgent bkops level */
4926 hba->urgent_bkops_lvl = curr_status;
4927 hba->is_urgent_bkops_lvl_checked = true;
4931 err = ufshcd_enable_auto_bkops(hba);
4934 dev_err(hba->dev, "%s: failed to handle urgent bkops %d\n",
4939 * ufshcd_exception_event_handler - handle exceptions raised by device
4940 * @work: pointer to work data
4942 * Read bExceptionEventStatus attribute from the device and handle the
4943 * exception event accordingly.
4945 static void ufshcd_exception_event_handler(struct work_struct *work)
4947 struct ufs_hba *hba;
4950 hba = container_of(work, struct ufs_hba, eeh_work);
4952 pm_runtime_get_sync(hba->dev);
4953 err = ufshcd_get_ee_status(hba, &status);
4955 dev_err(hba->dev, "%s: failed to get exception status %d\n",
4960 status &= hba->ee_ctrl_mask;
4962 if (status & MASK_EE_URGENT_BKOPS)
4963 ufshcd_bkops_exception_event_handler(hba);
4966 pm_runtime_put_sync(hba->dev);
4970 /* Complete requests that have door-bell cleared */
4971 static void ufshcd_complete_requests(struct ufs_hba *hba)
4973 ufshcd_transfer_req_compl(hba);
4974 ufshcd_tmc_handler(hba);
4978 * ufshcd_quirk_dl_nac_errors - This function checks if error handling is
4979 * to recover from the DL NAC errors or not.
4980 * @hba: per-adapter instance
4982 * Returns true if error handling is required, false otherwise
4984 static bool ufshcd_quirk_dl_nac_errors(struct ufs_hba *hba)
4986 unsigned long flags;
4987 bool err_handling = true;
4989 spin_lock_irqsave(hba->host->host_lock, flags);
4991 * UFS_DEVICE_QUIRK_RECOVERY_FROM_DL_NAC_ERRORS only workaround the
4992 * device fatal error and/or DL NAC & REPLAY timeout errors.
4994 if (hba->saved_err & (CONTROLLER_FATAL_ERROR | SYSTEM_BUS_FATAL_ERROR))
4997 if ((hba->saved_err & DEVICE_FATAL_ERROR) ||
4998 ((hba->saved_err & UIC_ERROR) &&
4999 (hba->saved_uic_err & UFSHCD_UIC_DL_TCx_REPLAY_ERROR)))
5002 if ((hba->saved_err & UIC_ERROR) &&
5003 (hba->saved_uic_err & UFSHCD_UIC_DL_NAC_RECEIVED_ERROR)) {
5006 * wait for 50ms to see if we can get any other errors or not.
5008 spin_unlock_irqrestore(hba->host->host_lock, flags);
5010 spin_lock_irqsave(hba->host->host_lock, flags);
5013 * now check if we have got any other severe errors other than
5016 if ((hba->saved_err & INT_FATAL_ERRORS) ||
5017 ((hba->saved_err & UIC_ERROR) &&
5018 (hba->saved_uic_err & ~UFSHCD_UIC_DL_NAC_RECEIVED_ERROR)))
5022 * As DL NAC is the only error received so far, send out NOP
5023 * command to confirm if link is still active or not.
5024 * - If we don't get any response then do error recovery.
5025 * - If we get response then clear the DL NAC error bit.
5028 spin_unlock_irqrestore(hba->host->host_lock, flags);
5029 err = ufshcd_verify_dev_init(hba);
5030 spin_lock_irqsave(hba->host->host_lock, flags);
5035 /* Link seems to be alive hence ignore the DL NAC errors */
5036 if (hba->saved_uic_err == UFSHCD_UIC_DL_NAC_RECEIVED_ERROR)
5037 hba->saved_err &= ~UIC_ERROR;
5038 /* clear NAC error */
5039 hba->saved_uic_err &= ~UFSHCD_UIC_DL_NAC_RECEIVED_ERROR;
5040 if (!hba->saved_uic_err) {
5041 err_handling = false;
5046 spin_unlock_irqrestore(hba->host->host_lock, flags);
5047 return err_handling;
5051 * ufshcd_err_handler - handle UFS errors that require s/w attention
5052 * @work: pointer to work structure
5054 static void ufshcd_err_handler(struct work_struct *work)
5056 struct ufs_hba *hba;
5057 unsigned long flags;
5062 bool needs_reset = false;
5064 hba = container_of(work, struct ufs_hba, eh_work);
5066 pm_runtime_get_sync(hba->dev);
5067 ufshcd_hold(hba, false);
5069 spin_lock_irqsave(hba->host->host_lock, flags);
5070 if (hba->ufshcd_state == UFSHCD_STATE_RESET)
5073 hba->ufshcd_state = UFSHCD_STATE_RESET;
5074 ufshcd_set_eh_in_progress(hba);
5076 /* Complete requests that have door-bell cleared by h/w */
5077 ufshcd_complete_requests(hba);
5079 if (hba->dev_quirks & UFS_DEVICE_QUIRK_RECOVERY_FROM_DL_NAC_ERRORS) {
5082 spin_unlock_irqrestore(hba->host->host_lock, flags);
5083 /* release the lock as ufshcd_quirk_dl_nac_errors() may sleep */
5084 ret = ufshcd_quirk_dl_nac_errors(hba);
5085 spin_lock_irqsave(hba->host->host_lock, flags);
5087 goto skip_err_handling;
5089 if ((hba->saved_err & INT_FATAL_ERRORS) ||
5090 ((hba->saved_err & UIC_ERROR) &&
5091 (hba->saved_uic_err & (UFSHCD_UIC_DL_PA_INIT_ERROR |
5092 UFSHCD_UIC_DL_NAC_RECEIVED_ERROR |
5093 UFSHCD_UIC_DL_TCx_REPLAY_ERROR))))
5097 * if host reset is required then skip clearing the pending
5098 * transfers forcefully because they will automatically get
5099 * cleared after link startup.
5102 goto skip_pending_xfer_clear;
5104 /* release lock as clear command might sleep */
5105 spin_unlock_irqrestore(hba->host->host_lock, flags);
5106 /* Clear pending transfer requests */
5107 for_each_set_bit(tag, &hba->outstanding_reqs, hba->nutrs) {
5108 if (ufshcd_clear_cmd(hba, tag)) {
5110 goto lock_skip_pending_xfer_clear;
5114 /* Clear pending task management requests */
5115 for_each_set_bit(tag, &hba->outstanding_tasks, hba->nutmrs) {
5116 if (ufshcd_clear_tm_cmd(hba, tag)) {
5118 goto lock_skip_pending_xfer_clear;
5122 lock_skip_pending_xfer_clear:
5123 spin_lock_irqsave(hba->host->host_lock, flags);
5125 /* Complete the requests that are cleared by s/w */
5126 ufshcd_complete_requests(hba);
5128 if (err_xfer || err_tm)
5131 skip_pending_xfer_clear:
5132 /* Fatal errors need reset */
5134 unsigned long max_doorbells = (1UL << hba->nutrs) - 1;
5137 * ufshcd_reset_and_restore() does the link reinitialization
5138 * which will need atleast one empty doorbell slot to send the
5139 * device management commands (NOP and query commands).
5140 * If there is no slot empty at this moment then free up last
5143 if (hba->outstanding_reqs == max_doorbells)
5144 __ufshcd_transfer_req_compl(hba,
5145 (1UL << (hba->nutrs - 1)));
5147 spin_unlock_irqrestore(hba->host->host_lock, flags);
5148 err = ufshcd_reset_and_restore(hba);
5149 spin_lock_irqsave(hba->host->host_lock, flags);
5151 dev_err(hba->dev, "%s: reset and restore failed\n",
5153 hba->ufshcd_state = UFSHCD_STATE_ERROR;
5156 * Inform scsi mid-layer that we did reset and allow to handle
5157 * Unit Attention properly.
5159 scsi_report_bus_reset(hba->host, 0);
5161 hba->saved_uic_err = 0;
5166 hba->ufshcd_state = UFSHCD_STATE_OPERATIONAL;
5167 if (hba->saved_err || hba->saved_uic_err)
5168 dev_err_ratelimited(hba->dev, "%s: exit: saved_err 0x%x saved_uic_err 0x%x",
5169 __func__, hba->saved_err, hba->saved_uic_err);
5172 ufshcd_clear_eh_in_progress(hba);
5175 spin_unlock_irqrestore(hba->host->host_lock, flags);
5176 scsi_unblock_requests(hba->host);
5177 ufshcd_release(hba);
5178 pm_runtime_put_sync(hba->dev);
5181 static void ufshcd_update_uic_reg_hist(struct ufs_uic_err_reg_hist *reg_hist,
5184 reg_hist->reg[reg_hist->pos] = reg;
5185 reg_hist->tstamp[reg_hist->pos] = ktime_get();
5186 reg_hist->pos = (reg_hist->pos + 1) % UIC_ERR_REG_HIST_LENGTH;
5190 * ufshcd_update_uic_error - check and set fatal UIC error flags.
5191 * @hba: per-adapter instance
5193 static void ufshcd_update_uic_error(struct ufs_hba *hba)
5197 /* PHY layer lane error */
5198 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_PHY_ADAPTER_LAYER);
5199 /* Ignore LINERESET indication, as this is not an error */
5200 if ((reg & UIC_PHY_ADAPTER_LAYER_ERROR) &&
5201 (reg & UIC_PHY_ADAPTER_LAYER_LANE_ERR_MASK)) {
5203 * To know whether this error is fatal or not, DB timeout
5204 * must be checked but this error is handled separately.
5206 dev_dbg(hba->dev, "%s: UIC Lane error reported\n", __func__);
5207 ufshcd_update_uic_reg_hist(&hba->ufs_stats.pa_err, reg);
5210 /* PA_INIT_ERROR is fatal and needs UIC reset */
5211 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_DATA_LINK_LAYER);
5213 ufshcd_update_uic_reg_hist(&hba->ufs_stats.dl_err, reg);
5215 if (reg & UIC_DATA_LINK_LAYER_ERROR_PA_INIT)
5216 hba->uic_error |= UFSHCD_UIC_DL_PA_INIT_ERROR;
5217 else if (hba->dev_quirks &
5218 UFS_DEVICE_QUIRK_RECOVERY_FROM_DL_NAC_ERRORS) {
5219 if (reg & UIC_DATA_LINK_LAYER_ERROR_NAC_RECEIVED)
5221 UFSHCD_UIC_DL_NAC_RECEIVED_ERROR;
5222 else if (reg & UIC_DATA_LINK_LAYER_ERROR_TCx_REPLAY_TIMEOUT)
5223 hba->uic_error |= UFSHCD_UIC_DL_TCx_REPLAY_ERROR;
5226 /* UIC NL/TL/DME errors needs software retry */
5227 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_NETWORK_LAYER);
5229 ufshcd_update_uic_reg_hist(&hba->ufs_stats.nl_err, reg);
5230 hba->uic_error |= UFSHCD_UIC_NL_ERROR;
5233 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_TRANSPORT_LAYER);
5235 ufshcd_update_uic_reg_hist(&hba->ufs_stats.tl_err, reg);
5236 hba->uic_error |= UFSHCD_UIC_TL_ERROR;
5239 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_DME);
5241 ufshcd_update_uic_reg_hist(&hba->ufs_stats.dme_err, reg);
5242 hba->uic_error |= UFSHCD_UIC_DME_ERROR;
5245 dev_dbg(hba->dev, "%s: UIC error flags = 0x%08x\n",
5246 __func__, hba->uic_error);
5250 * ufshcd_check_errors - Check for errors that need s/w attention
5251 * @hba: per-adapter instance
5253 static void ufshcd_check_errors(struct ufs_hba *hba)
5255 bool queue_eh_work = false;
5257 if (hba->errors & INT_FATAL_ERRORS)
5258 queue_eh_work = true;
5260 if (hba->errors & UIC_ERROR) {
5262 ufshcd_update_uic_error(hba);
5264 queue_eh_work = true;
5267 if (queue_eh_work) {
5269 * update the transfer error masks to sticky bits, let's do this
5270 * irrespective of current ufshcd_state.
5272 hba->saved_err |= hba->errors;
5273 hba->saved_uic_err |= hba->uic_error;
5275 /* handle fatal errors only when link is functional */
5276 if (hba->ufshcd_state == UFSHCD_STATE_OPERATIONAL) {
5277 /* block commands from scsi mid-layer */
5278 scsi_block_requests(hba->host);
5280 hba->ufshcd_state = UFSHCD_STATE_EH_SCHEDULED;
5282 /* dump controller state before resetting */
5283 if (hba->saved_err & (INT_FATAL_ERRORS | UIC_ERROR)) {
5284 bool pr_prdt = !!(hba->saved_err &
5285 SYSTEM_BUS_FATAL_ERROR);
5287 dev_err(hba->dev, "%s: saved_err 0x%x saved_uic_err 0x%x\n",
5288 __func__, hba->saved_err,
5289 hba->saved_uic_err);
5291 ufshcd_print_host_regs(hba);
5292 ufshcd_print_pwr_info(hba);
5293 ufshcd_print_tmrs(hba, hba->outstanding_tasks);
5294 ufshcd_print_trs(hba, hba->outstanding_reqs,
5297 schedule_work(&hba->eh_work);
5301 * if (!queue_eh_work) -
5302 * Other errors are either non-fatal where host recovers
5303 * itself without s/w intervention or errors that will be
5304 * handled by the SCSI core layer.
5309 * ufshcd_tmc_handler - handle task management function completion
5310 * @hba: per adapter instance
5312 static void ufshcd_tmc_handler(struct ufs_hba *hba)
5316 tm_doorbell = ufshcd_readl(hba, REG_UTP_TASK_REQ_DOOR_BELL);
5317 hba->tm_condition = tm_doorbell ^ hba->outstanding_tasks;
5318 wake_up(&hba->tm_wq);
5322 * ufshcd_sl_intr - Interrupt service routine
5323 * @hba: per adapter instance
5324 * @intr_status: contains interrupts generated by the controller
5326 static void ufshcd_sl_intr(struct ufs_hba *hba, u32 intr_status)
5328 hba->errors = UFSHCD_ERROR_MASK & intr_status;
5330 ufshcd_check_errors(hba);
5332 if (intr_status & UFSHCD_UIC_MASK)
5333 ufshcd_uic_cmd_compl(hba, intr_status);
5335 if (intr_status & UTP_TASK_REQ_COMPL)
5336 ufshcd_tmc_handler(hba);
5338 if (intr_status & UTP_TRANSFER_REQ_COMPL)
5339 ufshcd_transfer_req_compl(hba);
5343 * ufshcd_intr - Main interrupt service routine
5345 * @__hba: pointer to adapter instance
5347 * Returns IRQ_HANDLED - If interrupt is valid
5348 * IRQ_NONE - If invalid interrupt
5350 static irqreturn_t ufshcd_intr(int irq, void *__hba)
5352 u32 intr_status, enabled_intr_status;
5353 irqreturn_t retval = IRQ_NONE;
5354 struct ufs_hba *hba = __hba;
5356 spin_lock(hba->host->host_lock);
5357 intr_status = ufshcd_readl(hba, REG_INTERRUPT_STATUS);
5358 enabled_intr_status =
5359 intr_status & ufshcd_readl(hba, REG_INTERRUPT_ENABLE);
5362 ufshcd_writel(hba, intr_status, REG_INTERRUPT_STATUS);
5364 if (enabled_intr_status) {
5365 ufshcd_sl_intr(hba, enabled_intr_status);
5366 retval = IRQ_HANDLED;
5368 spin_unlock(hba->host->host_lock);
5372 static int ufshcd_clear_tm_cmd(struct ufs_hba *hba, int tag)
5375 u32 mask = 1 << tag;
5376 unsigned long flags;
5378 if (!test_bit(tag, &hba->outstanding_tasks))
5381 spin_lock_irqsave(hba->host->host_lock, flags);
5382 ufshcd_utmrl_clear(hba, tag);
5383 spin_unlock_irqrestore(hba->host->host_lock, flags);
5385 /* poll for max. 1 sec to clear door bell register by h/w */
5386 err = ufshcd_wait_for_register(hba,
5387 REG_UTP_TASK_REQ_DOOR_BELL,
5388 mask, 0, 1000, 1000, true);
5394 * ufshcd_issue_tm_cmd - issues task management commands to controller
5395 * @hba: per adapter instance
5396 * @lun_id: LUN ID to which TM command is sent
5397 * @task_id: task ID to which the TM command is applicable
5398 * @tm_function: task management function opcode
5399 * @tm_response: task management service response return value
5401 * Returns non-zero value on error, zero on success.
5403 static int ufshcd_issue_tm_cmd(struct ufs_hba *hba, int lun_id, int task_id,
5404 u8 tm_function, u8 *tm_response)
5406 struct utp_task_req_desc *task_req_descp;
5407 struct utp_upiu_task_req *task_req_upiup;
5408 struct Scsi_Host *host;
5409 unsigned long flags;
5417 * Get free slot, sleep if slots are unavailable.
5418 * Even though we use wait_event() which sleeps indefinitely,
5419 * the maximum wait time is bounded by %TM_CMD_TIMEOUT.
5421 wait_event(hba->tm_tag_wq, ufshcd_get_tm_free_slot(hba, &free_slot));
5422 ufshcd_hold(hba, false);
5424 spin_lock_irqsave(host->host_lock, flags);
5425 task_req_descp = hba->utmrdl_base_addr;
5426 task_req_descp += free_slot;
5428 /* Configure task request descriptor */
5429 task_req_descp->header.dword_0 = cpu_to_le32(UTP_REQ_DESC_INT_CMD);
5430 task_req_descp->header.dword_2 =
5431 cpu_to_le32(OCS_INVALID_COMMAND_STATUS);
5433 /* Configure task request UPIU */
5435 (struct utp_upiu_task_req *) task_req_descp->task_req_upiu;
5436 task_tag = hba->nutrs + free_slot;
5437 task_req_upiup->header.dword_0 =
5438 UPIU_HEADER_DWORD(UPIU_TRANSACTION_TASK_REQ, 0,
5440 task_req_upiup->header.dword_1 =
5441 UPIU_HEADER_DWORD(0, tm_function, 0, 0);
5443 * The host shall provide the same value for LUN field in the basic
5444 * header and for Input Parameter.
5446 task_req_upiup->input_param1 = cpu_to_be32(lun_id);
5447 task_req_upiup->input_param2 = cpu_to_be32(task_id);
5449 ufshcd_vops_setup_task_mgmt(hba, free_slot, tm_function);
5451 /* send command to the controller */
5452 __set_bit(free_slot, &hba->outstanding_tasks);
5454 /* Make sure descriptors are ready before ringing the task doorbell */
5457 ufshcd_writel(hba, 1 << free_slot, REG_UTP_TASK_REQ_DOOR_BELL);
5458 /* Make sure that doorbell is committed immediately */
5461 spin_unlock_irqrestore(host->host_lock, flags);
5463 /* wait until the task management command is completed */
5464 err = wait_event_timeout(hba->tm_wq,
5465 test_bit(free_slot, &hba->tm_condition),
5466 msecs_to_jiffies(TM_CMD_TIMEOUT));
5468 dev_err(hba->dev, "%s: task management cmd 0x%.2x timed-out\n",
5469 __func__, tm_function);
5470 if (ufshcd_clear_tm_cmd(hba, free_slot))
5471 dev_WARN(hba->dev, "%s: unable clear tm cmd (slot %d) after timeout\n",
5472 __func__, free_slot);
5475 err = ufshcd_task_req_compl(hba, free_slot, tm_response);
5478 clear_bit(free_slot, &hba->tm_condition);
5479 ufshcd_put_tm_slot(hba, free_slot);
5480 wake_up(&hba->tm_tag_wq);
5482 ufshcd_release(hba);
5487 * ufshcd_eh_device_reset_handler - device reset handler registered to
5489 * @cmd: SCSI command pointer
5491 * Returns SUCCESS/FAILED
5493 static int ufshcd_eh_device_reset_handler(struct scsi_cmnd *cmd)
5495 struct Scsi_Host *host;
5496 struct ufs_hba *hba;
5501 struct ufshcd_lrb *lrbp;
5502 unsigned long flags;
5504 host = cmd->device->host;
5505 hba = shost_priv(host);
5506 tag = cmd->request->tag;
5508 lrbp = &hba->lrb[tag];
5509 err = ufshcd_issue_tm_cmd(hba, lrbp->lun, 0, UFS_LOGICAL_RESET, &resp);
5510 if (err || resp != UPIU_TASK_MANAGEMENT_FUNC_COMPL) {
5516 /* clear the commands that were pending for corresponding LUN */
5517 for_each_set_bit(pos, &hba->outstanding_reqs, hba->nutrs) {
5518 if (hba->lrb[pos].lun == lrbp->lun) {
5519 err = ufshcd_clear_cmd(hba, pos);
5524 spin_lock_irqsave(host->host_lock, flags);
5525 ufshcd_transfer_req_compl(hba);
5526 spin_unlock_irqrestore(host->host_lock, flags);
5529 hba->req_abort_count = 0;
5533 dev_err(hba->dev, "%s: failed with err %d\n", __func__, err);
5539 static void ufshcd_set_req_abort_skip(struct ufs_hba *hba, unsigned long bitmap)
5541 struct ufshcd_lrb *lrbp;
5544 for_each_set_bit(tag, &bitmap, hba->nutrs) {
5545 lrbp = &hba->lrb[tag];
5546 lrbp->req_abort_skip = true;
5551 * ufshcd_abort - abort a specific command
5552 * @cmd: SCSI command pointer
5554 * Abort the pending command in device by sending UFS_ABORT_TASK task management
5555 * command, and in host controller by clearing the door-bell register. There can
5556 * be race between controller sending the command to the device while abort is
5557 * issued. To avoid that, first issue UFS_QUERY_TASK to check if the command is
5558 * really issued and then try to abort it.
5560 * Returns SUCCESS/FAILED
5562 static int ufshcd_abort(struct scsi_cmnd *cmd)
5564 struct Scsi_Host *host;
5565 struct ufs_hba *hba;
5566 unsigned long flags;
5571 struct ufshcd_lrb *lrbp;
5574 host = cmd->device->host;
5575 hba = shost_priv(host);
5576 tag = cmd->request->tag;
5577 lrbp = &hba->lrb[tag];
5578 if (!ufshcd_valid_tag(hba, tag)) {
5580 "%s: invalid command tag %d: cmd=0x%p, cmd->request=0x%p",
5581 __func__, tag, cmd, cmd->request);
5586 * Task abort to the device W-LUN is illegal. When this command
5587 * will fail, due to spec violation, scsi err handling next step
5588 * will be to send LU reset which, again, is a spec violation.
5589 * To avoid these unnecessary/illegal step we skip to the last error
5590 * handling stage: reset and restore.
5592 if (lrbp->lun == UFS_UPIU_UFS_DEVICE_WLUN)
5593 return ufshcd_eh_host_reset_handler(cmd);
5595 ufshcd_hold(hba, false);
5596 reg = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
5597 /* If command is already aborted/completed, return SUCCESS */
5598 if (!(test_bit(tag, &hba->outstanding_reqs))) {
5600 "%s: cmd at tag %d already completed, outstanding=0x%lx, doorbell=0x%x\n",
5601 __func__, tag, hba->outstanding_reqs, reg);
5605 if (!(reg & (1 << tag))) {
5607 "%s: cmd was completed, but without a notifying intr, tag = %d",
5611 /* Print Transfer Request of aborted task */
5612 dev_err(hba->dev, "%s: Device abort task at tag %d\n", __func__, tag);
5615 * Print detailed info about aborted request.
5616 * As more than one request might get aborted at the same time,
5617 * print full information only for the first aborted request in order
5618 * to reduce repeated printouts. For other aborted requests only print
5621 scsi_print_command(hba->lrb[tag].cmd);
5622 if (!hba->req_abort_count) {
5623 ufshcd_print_host_regs(hba);
5624 ufshcd_print_host_state(hba);
5625 ufshcd_print_pwr_info(hba);
5626 ufshcd_print_trs(hba, 1 << tag, true);
5628 ufshcd_print_trs(hba, 1 << tag, false);
5630 hba->req_abort_count++;
5632 /* Skip task abort in case previous aborts failed and report failure */
5633 if (lrbp->req_abort_skip) {
5638 for (poll_cnt = 100; poll_cnt; poll_cnt--) {
5639 err = ufshcd_issue_tm_cmd(hba, lrbp->lun, lrbp->task_tag,
5640 UFS_QUERY_TASK, &resp);
5641 if (!err && resp == UPIU_TASK_MANAGEMENT_FUNC_SUCCEEDED) {
5642 /* cmd pending in the device */
5643 dev_err(hba->dev, "%s: cmd pending in the device. tag = %d\n",
5646 } else if (!err && resp == UPIU_TASK_MANAGEMENT_FUNC_COMPL) {
5648 * cmd not pending in the device, check if it is
5651 dev_err(hba->dev, "%s: cmd at tag %d not pending in the device.\n",
5653 reg = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
5654 if (reg & (1 << tag)) {
5655 /* sleep for max. 200us to stabilize */
5656 usleep_range(100, 200);
5659 /* command completed already */
5660 dev_err(hba->dev, "%s: cmd at tag %d successfully cleared from DB.\n",
5665 "%s: no response from device. tag = %d, err %d\n",
5666 __func__, tag, err);
5668 err = resp; /* service response error */
5678 err = ufshcd_issue_tm_cmd(hba, lrbp->lun, lrbp->task_tag,
5679 UFS_ABORT_TASK, &resp);
5680 if (err || resp != UPIU_TASK_MANAGEMENT_FUNC_COMPL) {
5682 err = resp; /* service response error */
5683 dev_err(hba->dev, "%s: issued. tag = %d, err %d\n",
5684 __func__, tag, err);
5689 err = ufshcd_clear_cmd(hba, tag);
5691 dev_err(hba->dev, "%s: Failed clearing cmd at tag %d, err %d\n",
5692 __func__, tag, err);
5696 scsi_dma_unmap(cmd);
5698 spin_lock_irqsave(host->host_lock, flags);
5699 ufshcd_outstanding_req_clear(hba, tag);
5700 hba->lrb[tag].cmd = NULL;
5701 spin_unlock_irqrestore(host->host_lock, flags);
5703 clear_bit_unlock(tag, &hba->lrb_in_use);
5704 wake_up(&hba->dev_cmd.tag_wq);
5710 dev_err(hba->dev, "%s: failed with err %d\n", __func__, err);
5711 ufshcd_set_req_abort_skip(hba, hba->outstanding_reqs);
5716 * This ufshcd_release() corresponds to the original scsi cmd that got
5717 * aborted here (as we won't get any IRQ for it).
5719 ufshcd_release(hba);
5724 * ufshcd_host_reset_and_restore - reset and restore host controller
5725 * @hba: per-adapter instance
5727 * Note that host controller reset may issue DME_RESET to
5728 * local and remote (device) Uni-Pro stack and the attributes
5729 * are reset to default state.
5731 * Returns zero on success, non-zero on failure
5733 static int ufshcd_host_reset_and_restore(struct ufs_hba *hba)
5736 unsigned long flags;
5738 /* Reset the host controller */
5739 spin_lock_irqsave(hba->host->host_lock, flags);
5740 ufshcd_hba_stop(hba, false);
5741 spin_unlock_irqrestore(hba->host->host_lock, flags);
5743 /* scale up clocks to max frequency before full reinitialization */
5744 ufshcd_scale_clks(hba, true);
5746 err = ufshcd_hba_enable(hba);
5750 /* Establish the link again and restore the device */
5751 err = ufshcd_probe_hba(hba);
5753 if (!err && (hba->ufshcd_state != UFSHCD_STATE_OPERATIONAL))
5757 dev_err(hba->dev, "%s: Host init failed %d\n", __func__, err);
5763 * ufshcd_reset_and_restore - reset and re-initialize host/device
5764 * @hba: per-adapter instance
5766 * Reset and recover device, host and re-establish link. This
5767 * is helpful to recover the communication in fatal error conditions.
5769 * Returns zero on success, non-zero on failure
5771 static int ufshcd_reset_and_restore(struct ufs_hba *hba)
5774 unsigned long flags;
5775 int retries = MAX_HOST_RESET_RETRIES;
5778 err = ufshcd_host_reset_and_restore(hba);
5779 } while (err && --retries);
5782 * After reset the door-bell might be cleared, complete
5783 * outstanding requests in s/w here.
5785 spin_lock_irqsave(hba->host->host_lock, flags);
5786 ufshcd_transfer_req_compl(hba);
5787 ufshcd_tmc_handler(hba);
5788 spin_unlock_irqrestore(hba->host->host_lock, flags);
5794 * ufshcd_eh_host_reset_handler - host reset handler registered to scsi layer
5795 * @cmd: SCSI command pointer
5797 * Returns SUCCESS/FAILED
5799 static int ufshcd_eh_host_reset_handler(struct scsi_cmnd *cmd)
5802 unsigned long flags;
5803 struct ufs_hba *hba;
5805 hba = shost_priv(cmd->device->host);
5807 ufshcd_hold(hba, false);
5809 * Check if there is any race with fatal error handling.
5810 * If so, wait for it to complete. Even though fatal error
5811 * handling does reset and restore in some cases, don't assume
5812 * anything out of it. We are just avoiding race here.
5815 spin_lock_irqsave(hba->host->host_lock, flags);
5816 if (!(work_pending(&hba->eh_work) ||
5817 hba->ufshcd_state == UFSHCD_STATE_RESET ||
5818 hba->ufshcd_state == UFSHCD_STATE_EH_SCHEDULED))
5820 spin_unlock_irqrestore(hba->host->host_lock, flags);
5821 dev_dbg(hba->dev, "%s: reset in progress\n", __func__);
5822 flush_work(&hba->eh_work);
5825 hba->ufshcd_state = UFSHCD_STATE_RESET;
5826 ufshcd_set_eh_in_progress(hba);
5827 spin_unlock_irqrestore(hba->host->host_lock, flags);
5829 err = ufshcd_reset_and_restore(hba);
5831 spin_lock_irqsave(hba->host->host_lock, flags);
5834 hba->ufshcd_state = UFSHCD_STATE_OPERATIONAL;
5837 hba->ufshcd_state = UFSHCD_STATE_ERROR;
5839 ufshcd_clear_eh_in_progress(hba);
5840 spin_unlock_irqrestore(hba->host->host_lock, flags);
5842 ufshcd_release(hba);
5847 * ufshcd_get_max_icc_level - calculate the ICC level
5848 * @sup_curr_uA: max. current supported by the regulator
5849 * @start_scan: row at the desc table to start scan from
5850 * @buff: power descriptor buffer
5852 * Returns calculated max ICC level for specific regulator
5854 static u32 ufshcd_get_max_icc_level(int sup_curr_uA, u32 start_scan, char *buff)
5861 for (i = start_scan; i >= 0; i--) {
5862 data = be16_to_cpup((__be16 *)&buff[2 * i]);
5863 unit = (data & ATTR_ICC_LVL_UNIT_MASK) >>
5864 ATTR_ICC_LVL_UNIT_OFFSET;
5865 curr_uA = data & ATTR_ICC_LVL_VALUE_MASK;
5867 case UFSHCD_NANO_AMP:
5868 curr_uA = curr_uA / 1000;
5870 case UFSHCD_MILI_AMP:
5871 curr_uA = curr_uA * 1000;
5874 curr_uA = curr_uA * 1000 * 1000;
5876 case UFSHCD_MICRO_AMP:
5880 if (sup_curr_uA >= curr_uA)
5885 pr_err("%s: Couldn't find valid icc_level = %d", __func__, i);
5892 * ufshcd_calc_icc_level - calculate the max ICC level
5893 * In case regulators are not initialized we'll return 0
5894 * @hba: per-adapter instance
5895 * @desc_buf: power descriptor buffer to extract ICC levels from.
5896 * @len: length of desc_buff
5898 * Returns calculated ICC level
5900 static u32 ufshcd_find_max_sup_active_icc_level(struct ufs_hba *hba,
5901 u8 *desc_buf, int len)
5905 if (!hba->vreg_info.vcc || !hba->vreg_info.vccq ||
5906 !hba->vreg_info.vccq2) {
5908 "%s: Regulator capability was not set, actvIccLevel=%d",
5909 __func__, icc_level);
5913 if (hba->vreg_info.vcc)
5914 icc_level = ufshcd_get_max_icc_level(
5915 hba->vreg_info.vcc->max_uA,
5916 POWER_DESC_MAX_ACTV_ICC_LVLS - 1,
5917 &desc_buf[PWR_DESC_ACTIVE_LVLS_VCC_0]);
5919 if (hba->vreg_info.vccq)
5920 icc_level = ufshcd_get_max_icc_level(
5921 hba->vreg_info.vccq->max_uA,
5923 &desc_buf[PWR_DESC_ACTIVE_LVLS_VCCQ_0]);
5925 if (hba->vreg_info.vccq2)
5926 icc_level = ufshcd_get_max_icc_level(
5927 hba->vreg_info.vccq2->max_uA,
5929 &desc_buf[PWR_DESC_ACTIVE_LVLS_VCCQ2_0]);
5934 static void ufshcd_init_icc_levels(struct ufs_hba *hba)
5937 int buff_len = hba->desc_size.pwr_desc;
5940 desc_buf = kmalloc(buff_len, GFP_KERNEL);
5944 ret = ufshcd_read_power_desc(hba, desc_buf, buff_len);
5947 "%s: Failed reading power descriptor.len = %d ret = %d",
5948 __func__, buff_len, ret);
5952 hba->init_prefetch_data.icc_level =
5953 ufshcd_find_max_sup_active_icc_level(hba,
5954 desc_buf, buff_len);
5955 dev_dbg(hba->dev, "%s: setting icc_level 0x%x",
5956 __func__, hba->init_prefetch_data.icc_level);
5958 ret = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_WRITE_ATTR,
5959 QUERY_ATTR_IDN_ACTIVE_ICC_LVL, 0, 0,
5960 &hba->init_prefetch_data.icc_level);
5964 "%s: Failed configuring bActiveICCLevel = %d ret = %d",
5965 __func__, hba->init_prefetch_data.icc_level , ret);
5972 * ufshcd_scsi_add_wlus - Adds required W-LUs
5973 * @hba: per-adapter instance
5975 * UFS device specification requires the UFS devices to support 4 well known
5977 * "REPORT_LUNS" (address: 01h)
5978 * "UFS Device" (address: 50h)
5979 * "RPMB" (address: 44h)
5980 * "BOOT" (address: 30h)
5981 * UFS device's power management needs to be controlled by "POWER CONDITION"
5982 * field of SSU (START STOP UNIT) command. But this "power condition" field
5983 * will take effect only when its sent to "UFS device" well known logical unit
5984 * hence we require the scsi_device instance to represent this logical unit in
5985 * order for the UFS host driver to send the SSU command for power management.
5987 * We also require the scsi_device instance for "RPMB" (Replay Protected Memory
5988 * Block) LU so user space process can control this LU. User space may also
5989 * want to have access to BOOT LU.
5991 * This function adds scsi device instances for each of all well known LUs
5992 * (except "REPORT LUNS" LU).
5994 * Returns zero on success (all required W-LUs are added successfully),
5995 * non-zero error value on failure (if failed to add any of the required W-LU).
5997 static int ufshcd_scsi_add_wlus(struct ufs_hba *hba)
6000 struct scsi_device *sdev_rpmb;
6001 struct scsi_device *sdev_boot;
6003 hba->sdev_ufs_device = __scsi_add_device(hba->host, 0, 0,
6004 ufshcd_upiu_wlun_to_scsi_wlun(UFS_UPIU_UFS_DEVICE_WLUN), NULL);
6005 if (IS_ERR(hba->sdev_ufs_device)) {
6006 ret = PTR_ERR(hba->sdev_ufs_device);
6007 hba->sdev_ufs_device = NULL;
6010 scsi_device_put(hba->sdev_ufs_device);
6012 sdev_rpmb = __scsi_add_device(hba->host, 0, 0,
6013 ufshcd_upiu_wlun_to_scsi_wlun(UFS_UPIU_RPMB_WLUN), NULL);
6014 if (IS_ERR(sdev_rpmb)) {
6015 ret = PTR_ERR(sdev_rpmb);
6016 goto remove_sdev_ufs_device;
6018 scsi_device_put(sdev_rpmb);
6020 sdev_boot = __scsi_add_device(hba->host, 0, 0,
6021 ufshcd_upiu_wlun_to_scsi_wlun(UFS_UPIU_BOOT_WLUN), NULL);
6022 if (IS_ERR(sdev_boot))
6023 dev_err(hba->dev, "%s: BOOT WLUN not found\n", __func__);
6025 scsi_device_put(sdev_boot);
6028 remove_sdev_ufs_device:
6029 scsi_remove_device(hba->sdev_ufs_device);
6034 static int ufs_get_device_desc(struct ufs_hba *hba,
6035 struct ufs_dev_desc *dev_desc)
6042 buff_len = max_t(size_t, hba->desc_size.dev_desc,
6043 QUERY_DESC_MAX_SIZE + 1);
6044 desc_buf = kmalloc(buff_len, GFP_KERNEL);
6050 err = ufshcd_read_device_desc(hba, desc_buf, hba->desc_size.dev_desc);
6052 dev_err(hba->dev, "%s: Failed reading Device Desc. err = %d\n",
6058 * getting vendor (manufacturerID) and Bank Index in big endian
6061 dev_desc->wmanufacturerid = desc_buf[DEVICE_DESC_PARAM_MANF_ID] << 8 |
6062 desc_buf[DEVICE_DESC_PARAM_MANF_ID + 1];
6064 model_index = desc_buf[DEVICE_DESC_PARAM_PRDCT_NAME];
6066 /* Zero-pad entire buffer for string termination. */
6067 memset(desc_buf, 0, buff_len);
6069 err = ufshcd_read_string_desc(hba, model_index, desc_buf,
6070 QUERY_DESC_MAX_SIZE, true/*ASCII*/);
6072 dev_err(hba->dev, "%s: Failed reading Product Name. err = %d\n",
6077 desc_buf[QUERY_DESC_MAX_SIZE] = '\0';
6078 strlcpy(dev_desc->model, (desc_buf + QUERY_DESC_HDR_SIZE),
6079 min_t(u8, desc_buf[QUERY_DESC_LENGTH_OFFSET],
6082 /* Null terminate the model string */
6083 dev_desc->model[MAX_MODEL_LEN] = '\0';
6090 static void ufs_fixup_device_setup(struct ufs_hba *hba,
6091 struct ufs_dev_desc *dev_desc)
6093 struct ufs_dev_fix *f;
6095 for (f = ufs_fixups; f->quirk; f++) {
6096 if ((f->card.wmanufacturerid == dev_desc->wmanufacturerid ||
6097 f->card.wmanufacturerid == UFS_ANY_VENDOR) &&
6098 (STR_PRFX_EQUAL(f->card.model, dev_desc->model) ||
6099 !strcmp(f->card.model, UFS_ANY_MODEL)))
6100 hba->dev_quirks |= f->quirk;
6105 * ufshcd_tune_pa_tactivate - Tunes PA_TActivate of local UniPro
6106 * @hba: per-adapter instance
6108 * PA_TActivate parameter can be tuned manually if UniPro version is less than
6109 * 1.61. PA_TActivate needs to be greater than or equal to peerM-PHY's
6110 * RX_MIN_ACTIVATETIME_CAPABILITY attribute. This optimal value can help reduce
6111 * the hibern8 exit latency.
6113 * Returns zero on success, non-zero error value on failure.
6115 static int ufshcd_tune_pa_tactivate(struct ufs_hba *hba)
6118 u32 peer_rx_min_activatetime = 0, tuned_pa_tactivate;
6120 ret = ufshcd_dme_peer_get(hba,
6122 RX_MIN_ACTIVATETIME_CAPABILITY,
6123 UIC_ARG_MPHY_RX_GEN_SEL_INDEX(0)),
6124 &peer_rx_min_activatetime);
6128 /* make sure proper unit conversion is applied */
6129 tuned_pa_tactivate =
6130 ((peer_rx_min_activatetime * RX_MIN_ACTIVATETIME_UNIT_US)
6131 / PA_TACTIVATE_TIME_UNIT_US);
6132 ret = ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TACTIVATE),
6133 tuned_pa_tactivate);
6140 * ufshcd_tune_pa_hibern8time - Tunes PA_Hibern8Time of local UniPro
6141 * @hba: per-adapter instance
6143 * PA_Hibern8Time parameter can be tuned manually if UniPro version is less than
6144 * 1.61. PA_Hibern8Time needs to be maximum of local M-PHY's
6145 * TX_HIBERN8TIME_CAPABILITY & peer M-PHY's RX_HIBERN8TIME_CAPABILITY.
6146 * This optimal value can help reduce the hibern8 exit latency.
6148 * Returns zero on success, non-zero error value on failure.
6150 static int ufshcd_tune_pa_hibern8time(struct ufs_hba *hba)
6153 u32 local_tx_hibern8_time_cap = 0, peer_rx_hibern8_time_cap = 0;
6154 u32 max_hibern8_time, tuned_pa_hibern8time;
6156 ret = ufshcd_dme_get(hba,
6157 UIC_ARG_MIB_SEL(TX_HIBERN8TIME_CAPABILITY,
6158 UIC_ARG_MPHY_TX_GEN_SEL_INDEX(0)),
6159 &local_tx_hibern8_time_cap);
6163 ret = ufshcd_dme_peer_get(hba,
6164 UIC_ARG_MIB_SEL(RX_HIBERN8TIME_CAPABILITY,
6165 UIC_ARG_MPHY_RX_GEN_SEL_INDEX(0)),
6166 &peer_rx_hibern8_time_cap);
6170 max_hibern8_time = max(local_tx_hibern8_time_cap,
6171 peer_rx_hibern8_time_cap);
6172 /* make sure proper unit conversion is applied */
6173 tuned_pa_hibern8time = ((max_hibern8_time * HIBERN8TIME_UNIT_US)
6174 / PA_HIBERN8_TIME_UNIT_US);
6175 ret = ufshcd_dme_set(hba, UIC_ARG_MIB(PA_HIBERN8TIME),
6176 tuned_pa_hibern8time);
6182 * ufshcd_quirk_tune_host_pa_tactivate - Ensures that host PA_TACTIVATE is
6183 * less than device PA_TACTIVATE time.
6184 * @hba: per-adapter instance
6186 * Some UFS devices require host PA_TACTIVATE to be lower than device
6187 * PA_TACTIVATE, we need to enable UFS_DEVICE_QUIRK_HOST_PA_TACTIVATE quirk
6190 * Returns zero on success, non-zero error value on failure.
6192 static int ufshcd_quirk_tune_host_pa_tactivate(struct ufs_hba *hba)
6195 u32 granularity, peer_granularity;
6196 u32 pa_tactivate, peer_pa_tactivate;
6197 u32 pa_tactivate_us, peer_pa_tactivate_us;
6198 u8 gran_to_us_table[] = {1, 4, 8, 16, 32, 100};
6200 ret = ufshcd_dme_get(hba, UIC_ARG_MIB(PA_GRANULARITY),
6205 ret = ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_GRANULARITY),
6210 if ((granularity < PA_GRANULARITY_MIN_VAL) ||
6211 (granularity > PA_GRANULARITY_MAX_VAL)) {
6212 dev_err(hba->dev, "%s: invalid host PA_GRANULARITY %d",
6213 __func__, granularity);
6217 if ((peer_granularity < PA_GRANULARITY_MIN_VAL) ||
6218 (peer_granularity > PA_GRANULARITY_MAX_VAL)) {
6219 dev_err(hba->dev, "%s: invalid device PA_GRANULARITY %d",
6220 __func__, peer_granularity);
6224 ret = ufshcd_dme_get(hba, UIC_ARG_MIB(PA_TACTIVATE), &pa_tactivate);
6228 ret = ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_TACTIVATE),
6229 &peer_pa_tactivate);
6233 pa_tactivate_us = pa_tactivate * gran_to_us_table[granularity - 1];
6234 peer_pa_tactivate_us = peer_pa_tactivate *
6235 gran_to_us_table[peer_granularity - 1];
6237 if (pa_tactivate_us > peer_pa_tactivate_us) {
6238 u32 new_peer_pa_tactivate;
6240 new_peer_pa_tactivate = pa_tactivate_us /
6241 gran_to_us_table[peer_granularity - 1];
6242 new_peer_pa_tactivate++;
6243 ret = ufshcd_dme_peer_set(hba, UIC_ARG_MIB(PA_TACTIVATE),
6244 new_peer_pa_tactivate);
6251 static void ufshcd_tune_unipro_params(struct ufs_hba *hba)
6253 if (ufshcd_is_unipro_pa_params_tuning_req(hba)) {
6254 ufshcd_tune_pa_tactivate(hba);
6255 ufshcd_tune_pa_hibern8time(hba);
6258 if (hba->dev_quirks & UFS_DEVICE_QUIRK_PA_TACTIVATE)
6259 /* set 1ms timeout for PA_TACTIVATE */
6260 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TACTIVATE), 10);
6262 if (hba->dev_quirks & UFS_DEVICE_QUIRK_HOST_PA_TACTIVATE)
6263 ufshcd_quirk_tune_host_pa_tactivate(hba);
6265 ufshcd_vops_apply_dev_quirks(hba);
6268 static void ufshcd_clear_dbg_ufs_stats(struct ufs_hba *hba)
6270 int err_reg_hist_size = sizeof(struct ufs_uic_err_reg_hist);
6272 hba->ufs_stats.hibern8_exit_cnt = 0;
6273 hba->ufs_stats.last_hibern8_exit_tstamp = ktime_set(0, 0);
6275 memset(&hba->ufs_stats.pa_err, 0, err_reg_hist_size);
6276 memset(&hba->ufs_stats.dl_err, 0, err_reg_hist_size);
6277 memset(&hba->ufs_stats.nl_err, 0, err_reg_hist_size);
6278 memset(&hba->ufs_stats.tl_err, 0, err_reg_hist_size);
6279 memset(&hba->ufs_stats.dme_err, 0, err_reg_hist_size);
6281 hba->req_abort_count = 0;
6284 static void ufshcd_init_desc_sizes(struct ufs_hba *hba)
6288 err = ufshcd_read_desc_length(hba, QUERY_DESC_IDN_DEVICE, 0,
6289 &hba->desc_size.dev_desc);
6291 hba->desc_size.dev_desc = QUERY_DESC_DEVICE_DEF_SIZE;
6293 err = ufshcd_read_desc_length(hba, QUERY_DESC_IDN_POWER, 0,
6294 &hba->desc_size.pwr_desc);
6296 hba->desc_size.pwr_desc = QUERY_DESC_POWER_DEF_SIZE;
6298 err = ufshcd_read_desc_length(hba, QUERY_DESC_IDN_INTERCONNECT, 0,
6299 &hba->desc_size.interc_desc);
6301 hba->desc_size.interc_desc = QUERY_DESC_INTERCONNECT_DEF_SIZE;
6303 err = ufshcd_read_desc_length(hba, QUERY_DESC_IDN_CONFIGURATION, 0,
6304 &hba->desc_size.conf_desc);
6306 hba->desc_size.conf_desc = QUERY_DESC_CONFIGURATION_DEF_SIZE;
6308 err = ufshcd_read_desc_length(hba, QUERY_DESC_IDN_UNIT, 0,
6309 &hba->desc_size.unit_desc);
6311 hba->desc_size.unit_desc = QUERY_DESC_UNIT_DEF_SIZE;
6313 err = ufshcd_read_desc_length(hba, QUERY_DESC_IDN_GEOMETRY, 0,
6314 &hba->desc_size.geom_desc);
6316 hba->desc_size.geom_desc = QUERY_DESC_GEOMETRY_DEF_SIZE;
6317 err = ufshcd_read_desc_length(hba, QUERY_DESC_IDN_HEALTH, 0,
6318 &hba->desc_size.hlth_desc);
6320 hba->desc_size.hlth_desc = QUERY_DESC_HEALTH_DEF_SIZE;
6323 static void ufshcd_def_desc_sizes(struct ufs_hba *hba)
6325 hba->desc_size.dev_desc = QUERY_DESC_DEVICE_DEF_SIZE;
6326 hba->desc_size.pwr_desc = QUERY_DESC_POWER_DEF_SIZE;
6327 hba->desc_size.interc_desc = QUERY_DESC_INTERCONNECT_DEF_SIZE;
6328 hba->desc_size.conf_desc = QUERY_DESC_CONFIGURATION_DEF_SIZE;
6329 hba->desc_size.unit_desc = QUERY_DESC_UNIT_DEF_SIZE;
6330 hba->desc_size.geom_desc = QUERY_DESC_GEOMETRY_DEF_SIZE;
6331 hba->desc_size.hlth_desc = QUERY_DESC_HEALTH_DEF_SIZE;
6335 * ufshcd_probe_hba - probe hba to detect device and initialize
6336 * @hba: per-adapter instance
6338 * Execute link-startup and verify device initialization
6340 static int ufshcd_probe_hba(struct ufs_hba *hba)
6342 struct ufs_dev_desc card = {0};
6344 ktime_t start = ktime_get();
6346 ret = ufshcd_link_startup(hba);
6350 /* set the default level for urgent bkops */
6351 hba->urgent_bkops_lvl = BKOPS_STATUS_PERF_IMPACT;
6352 hba->is_urgent_bkops_lvl_checked = false;
6354 /* Debug counters initialization */
6355 ufshcd_clear_dbg_ufs_stats(hba);
6357 /* UniPro link is active now */
6358 ufshcd_set_link_active(hba);
6360 /* Enable Auto-Hibernate if configured */
6361 ufshcd_auto_hibern8_enable(hba);
6363 ret = ufshcd_verify_dev_init(hba);
6367 ret = ufshcd_complete_dev_init(hba);
6371 /* Init check for device descriptor sizes */
6372 ufshcd_init_desc_sizes(hba);
6374 ret = ufs_get_device_desc(hba, &card);
6376 dev_err(hba->dev, "%s: Failed getting device info. err = %d\n",
6381 ufs_fixup_device_setup(hba, &card);
6382 ufshcd_tune_unipro_params(hba);
6384 ret = ufshcd_set_vccq_rail_unused(hba,
6385 (hba->dev_quirks & UFS_DEVICE_NO_VCCQ) ? true : false);
6389 /* UFS device is also active now */
6390 ufshcd_set_ufs_dev_active(hba);
6391 ufshcd_force_reset_auto_bkops(hba);
6392 hba->wlun_dev_clr_ua = true;
6394 if (ufshcd_get_max_pwr_mode(hba)) {
6396 "%s: Failed getting max supported power mode\n",
6399 ret = ufshcd_config_pwr_mode(hba, &hba->max_pwr_info.info);
6401 dev_err(hba->dev, "%s: Failed setting power mode, err = %d\n",
6407 /* set the state as operational after switching to desired gear */
6408 hba->ufshcd_state = UFSHCD_STATE_OPERATIONAL;
6411 * If we are in error handling context or in power management callbacks
6412 * context, no need to scan the host
6414 if (!ufshcd_eh_in_progress(hba) && !hba->pm_op_in_progress) {
6417 /* clear any previous UFS device information */
6418 memset(&hba->dev_info, 0, sizeof(hba->dev_info));
6419 if (!ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_READ_FLAG,
6420 QUERY_FLAG_IDN_PWR_ON_WPE, &flag))
6421 hba->dev_info.f_power_on_wp_en = flag;
6423 if (!hba->is_init_prefetch)
6424 ufshcd_init_icc_levels(hba);
6426 /* Add required well known logical units to scsi mid layer */
6427 if (ufshcd_scsi_add_wlus(hba))
6430 /* Initialize devfreq after UFS device is detected */
6431 if (ufshcd_is_clkscaling_supported(hba)) {
6432 memcpy(&hba->clk_scaling.saved_pwr_info.info,
6434 sizeof(struct ufs_pa_layer_attr));
6435 hba->clk_scaling.saved_pwr_info.is_valid = true;
6436 if (!hba->devfreq) {
6437 hba->devfreq = devm_devfreq_add_device(hba->dev,
6438 &ufs_devfreq_profile,
6441 if (IS_ERR(hba->devfreq)) {
6442 ret = PTR_ERR(hba->devfreq);
6443 dev_err(hba->dev, "Unable to register with devfreq %d\n",
6448 hba->clk_scaling.is_allowed = true;
6451 scsi_scan_host(hba->host);
6452 pm_runtime_put_sync(hba->dev);
6455 if (!hba->is_init_prefetch)
6456 hba->is_init_prefetch = true;
6460 * If we failed to initialize the device or the device is not
6461 * present, turn off the power/clocks etc.
6463 if (ret && !ufshcd_eh_in_progress(hba) && !hba->pm_op_in_progress) {
6464 pm_runtime_put_sync(hba->dev);
6465 ufshcd_hba_exit(hba);
6468 trace_ufshcd_init(dev_name(hba->dev), ret,
6469 ktime_to_us(ktime_sub(ktime_get(), start)),
6470 hba->curr_dev_pwr_mode, hba->uic_link_state);
6475 * ufshcd_async_scan - asynchronous execution for probing hba
6476 * @data: data pointer to pass to this function
6477 * @cookie: cookie data
6479 static void ufshcd_async_scan(void *data, async_cookie_t cookie)
6481 struct ufs_hba *hba = (struct ufs_hba *)data;
6483 ufshcd_probe_hba(hba);
6486 static enum blk_eh_timer_return ufshcd_eh_timed_out(struct scsi_cmnd *scmd)
6488 unsigned long flags;
6489 struct Scsi_Host *host;
6490 struct ufs_hba *hba;
6494 if (!scmd || !scmd->device || !scmd->device->host)
6495 return BLK_EH_NOT_HANDLED;
6497 host = scmd->device->host;
6498 hba = shost_priv(host);
6500 return BLK_EH_NOT_HANDLED;
6502 spin_lock_irqsave(host->host_lock, flags);
6504 for_each_set_bit(index, &hba->outstanding_reqs, hba->nutrs) {
6505 if (hba->lrb[index].cmd == scmd) {
6511 spin_unlock_irqrestore(host->host_lock, flags);
6514 * Bypass SCSI error handling and reset the block layer timer if this
6515 * SCSI command was not actually dispatched to UFS driver, otherwise
6516 * let SCSI layer handle the error as usual.
6518 return found ? BLK_EH_NOT_HANDLED : BLK_EH_RESET_TIMER;
6521 static const struct attribute_group *ufshcd_driver_groups[] = {
6522 &ufs_sysfs_unit_descriptor_group,
6523 &ufs_sysfs_lun_attributes_group,
6527 static struct scsi_host_template ufshcd_driver_template = {
6528 .module = THIS_MODULE,
6530 .proc_name = UFSHCD,
6531 .queuecommand = ufshcd_queuecommand,
6532 .slave_alloc = ufshcd_slave_alloc,
6533 .slave_configure = ufshcd_slave_configure,
6534 .slave_destroy = ufshcd_slave_destroy,
6535 .change_queue_depth = ufshcd_change_queue_depth,
6536 .eh_abort_handler = ufshcd_abort,
6537 .eh_device_reset_handler = ufshcd_eh_device_reset_handler,
6538 .eh_host_reset_handler = ufshcd_eh_host_reset_handler,
6539 .eh_timed_out = ufshcd_eh_timed_out,
6541 .sg_tablesize = SG_ALL,
6542 .cmd_per_lun = UFSHCD_CMD_PER_LUN,
6543 .can_queue = UFSHCD_CAN_QUEUE,
6544 .max_host_blocked = 1,
6545 .track_queue_depth = 1,
6546 .sdev_groups = ufshcd_driver_groups,
6549 static int ufshcd_config_vreg_load(struct device *dev, struct ufs_vreg *vreg,
6557 ret = regulator_set_load(vreg->reg, ua);
6559 dev_err(dev, "%s: %s set load (ua=%d) failed, err=%d\n",
6560 __func__, vreg->name, ua, ret);
6566 static inline int ufshcd_config_vreg_lpm(struct ufs_hba *hba,
6567 struct ufs_vreg *vreg)
6571 else if (vreg->unused)
6574 return ufshcd_config_vreg_load(hba->dev, vreg,
6575 UFS_VREG_LPM_LOAD_UA);
6578 static inline int ufshcd_config_vreg_hpm(struct ufs_hba *hba,
6579 struct ufs_vreg *vreg)
6583 else if (vreg->unused)
6586 return ufshcd_config_vreg_load(hba->dev, vreg, vreg->max_uA);
6589 static int ufshcd_config_vreg(struct device *dev,
6590 struct ufs_vreg *vreg, bool on)
6593 struct regulator *reg;
6595 int min_uV, uA_load;
6602 if (regulator_count_voltages(reg) > 0) {
6603 min_uV = on ? vreg->min_uV : 0;
6604 ret = regulator_set_voltage(reg, min_uV, vreg->max_uV);
6606 dev_err(dev, "%s: %s set voltage failed, err=%d\n",
6607 __func__, name, ret);
6611 uA_load = on ? vreg->max_uA : 0;
6612 ret = ufshcd_config_vreg_load(dev, vreg, uA_load);
6620 static int ufshcd_enable_vreg(struct device *dev, struct ufs_vreg *vreg)
6626 else if (vreg->enabled || vreg->unused)
6629 ret = ufshcd_config_vreg(dev, vreg, true);
6631 ret = regulator_enable(vreg->reg);
6634 vreg->enabled = true;
6636 dev_err(dev, "%s: %s enable failed, err=%d\n",
6637 __func__, vreg->name, ret);
6642 static int ufshcd_disable_vreg(struct device *dev, struct ufs_vreg *vreg)
6648 else if (!vreg->enabled || vreg->unused)
6651 ret = regulator_disable(vreg->reg);
6654 /* ignore errors on applying disable config */
6655 ufshcd_config_vreg(dev, vreg, false);
6656 vreg->enabled = false;
6658 dev_err(dev, "%s: %s disable failed, err=%d\n",
6659 __func__, vreg->name, ret);
6665 static int ufshcd_setup_vreg(struct ufs_hba *hba, bool on)
6668 struct device *dev = hba->dev;
6669 struct ufs_vreg_info *info = &hba->vreg_info;
6674 ret = ufshcd_toggle_vreg(dev, info->vcc, on);
6678 ret = ufshcd_toggle_vreg(dev, info->vccq, on);
6682 ret = ufshcd_toggle_vreg(dev, info->vccq2, on);
6688 ufshcd_toggle_vreg(dev, info->vccq2, false);
6689 ufshcd_toggle_vreg(dev, info->vccq, false);
6690 ufshcd_toggle_vreg(dev, info->vcc, false);
6695 static int ufshcd_setup_hba_vreg(struct ufs_hba *hba, bool on)
6697 struct ufs_vreg_info *info = &hba->vreg_info;
6700 return ufshcd_toggle_vreg(hba->dev, info->vdd_hba, on);
6705 static int ufshcd_get_vreg(struct device *dev, struct ufs_vreg *vreg)
6712 vreg->reg = devm_regulator_get(dev, vreg->name);
6713 if (IS_ERR(vreg->reg)) {
6714 ret = PTR_ERR(vreg->reg);
6715 dev_err(dev, "%s: %s get failed, err=%d\n",
6716 __func__, vreg->name, ret);
6722 static int ufshcd_init_vreg(struct ufs_hba *hba)
6725 struct device *dev = hba->dev;
6726 struct ufs_vreg_info *info = &hba->vreg_info;
6731 ret = ufshcd_get_vreg(dev, info->vcc);
6735 ret = ufshcd_get_vreg(dev, info->vccq);
6739 ret = ufshcd_get_vreg(dev, info->vccq2);
6744 static int ufshcd_init_hba_vreg(struct ufs_hba *hba)
6746 struct ufs_vreg_info *info = &hba->vreg_info;
6749 return ufshcd_get_vreg(hba->dev, info->vdd_hba);
6754 static int ufshcd_set_vccq_rail_unused(struct ufs_hba *hba, bool unused)
6757 struct ufs_vreg_info *info = &hba->vreg_info;
6761 else if (!info->vccq)
6765 /* shut off the rail here */
6766 ret = ufshcd_toggle_vreg(hba->dev, info->vccq, false);
6768 * Mark this rail as no longer used, so it doesn't get enabled
6772 info->vccq->unused = true;
6775 * rail should have been already enabled hence just make sure
6776 * that unused flag is cleared.
6778 info->vccq->unused = false;
6784 static int __ufshcd_setup_clocks(struct ufs_hba *hba, bool on,
6788 struct ufs_clk_info *clki;
6789 struct list_head *head = &hba->clk_list_head;
6790 unsigned long flags;
6791 ktime_t start = ktime_get();
6792 bool clk_state_changed = false;
6794 if (list_empty(head))
6797 ret = ufshcd_vops_setup_clocks(hba, on, PRE_CHANGE);
6801 list_for_each_entry(clki, head, list) {
6802 if (!IS_ERR_OR_NULL(clki->clk)) {
6803 if (skip_ref_clk && !strcmp(clki->name, "ref_clk"))
6806 clk_state_changed = on ^ clki->enabled;
6807 if (on && !clki->enabled) {
6808 ret = clk_prepare_enable(clki->clk);
6810 dev_err(hba->dev, "%s: %s prepare enable failed, %d\n",
6811 __func__, clki->name, ret);
6814 } else if (!on && clki->enabled) {
6815 clk_disable_unprepare(clki->clk);
6818 dev_dbg(hba->dev, "%s: clk: %s %sabled\n", __func__,
6819 clki->name, on ? "en" : "dis");
6823 ret = ufshcd_vops_setup_clocks(hba, on, POST_CHANGE);
6829 list_for_each_entry(clki, head, list) {
6830 if (!IS_ERR_OR_NULL(clki->clk) && clki->enabled)
6831 clk_disable_unprepare(clki->clk);
6833 } else if (!ret && on) {
6834 spin_lock_irqsave(hba->host->host_lock, flags);
6835 hba->clk_gating.state = CLKS_ON;
6836 trace_ufshcd_clk_gating(dev_name(hba->dev),
6837 hba->clk_gating.state);
6838 spin_unlock_irqrestore(hba->host->host_lock, flags);
6841 if (clk_state_changed)
6842 trace_ufshcd_profile_clk_gating(dev_name(hba->dev),
6843 (on ? "on" : "off"),
6844 ktime_to_us(ktime_sub(ktime_get(), start)), ret);
6848 static int ufshcd_setup_clocks(struct ufs_hba *hba, bool on)
6850 return __ufshcd_setup_clocks(hba, on, false);
6853 static int ufshcd_init_clocks(struct ufs_hba *hba)
6856 struct ufs_clk_info *clki;
6857 struct device *dev = hba->dev;
6858 struct list_head *head = &hba->clk_list_head;
6860 if (list_empty(head))
6863 list_for_each_entry(clki, head, list) {
6867 clki->clk = devm_clk_get(dev, clki->name);
6868 if (IS_ERR(clki->clk)) {
6869 ret = PTR_ERR(clki->clk);
6870 dev_err(dev, "%s: %s clk get failed, %d\n",
6871 __func__, clki->name, ret);
6875 if (clki->max_freq) {
6876 ret = clk_set_rate(clki->clk, clki->max_freq);
6878 dev_err(hba->dev, "%s: %s clk set rate(%dHz) failed, %d\n",
6879 __func__, clki->name,
6880 clki->max_freq, ret);
6883 clki->curr_freq = clki->max_freq;
6885 dev_dbg(dev, "%s: clk: %s, rate: %lu\n", __func__,
6886 clki->name, clk_get_rate(clki->clk));
6892 static int ufshcd_variant_hba_init(struct ufs_hba *hba)
6899 err = ufshcd_vops_init(hba);
6903 err = ufshcd_vops_setup_regulators(hba, true);
6910 ufshcd_vops_exit(hba);
6913 dev_err(hba->dev, "%s: variant %s init failed err %d\n",
6914 __func__, ufshcd_get_var_name(hba), err);
6918 static void ufshcd_variant_hba_exit(struct ufs_hba *hba)
6923 ufshcd_vops_setup_regulators(hba, false);
6925 ufshcd_vops_exit(hba);
6928 static int ufshcd_hba_init(struct ufs_hba *hba)
6933 * Handle host controller power separately from the UFS device power
6934 * rails as it will help controlling the UFS host controller power
6935 * collapse easily which is different than UFS device power collapse.
6936 * Also, enable the host controller power before we go ahead with rest
6937 * of the initialization here.
6939 err = ufshcd_init_hba_vreg(hba);
6943 err = ufshcd_setup_hba_vreg(hba, true);
6947 err = ufshcd_init_clocks(hba);
6949 goto out_disable_hba_vreg;
6951 err = ufshcd_setup_clocks(hba, true);
6953 goto out_disable_hba_vreg;
6955 err = ufshcd_init_vreg(hba);
6957 goto out_disable_clks;
6959 err = ufshcd_setup_vreg(hba, true);
6961 goto out_disable_clks;
6963 err = ufshcd_variant_hba_init(hba);
6965 goto out_disable_vreg;
6967 hba->is_powered = true;
6971 ufshcd_setup_vreg(hba, false);
6973 ufshcd_setup_clocks(hba, false);
6974 out_disable_hba_vreg:
6975 ufshcd_setup_hba_vreg(hba, false);
6980 static void ufshcd_hba_exit(struct ufs_hba *hba)
6982 if (hba->is_powered) {
6983 ufshcd_variant_hba_exit(hba);
6984 ufshcd_setup_vreg(hba, false);
6985 ufshcd_suspend_clkscaling(hba);
6986 if (ufshcd_is_clkscaling_supported(hba)) {
6988 ufshcd_suspend_clkscaling(hba);
6989 destroy_workqueue(hba->clk_scaling.workq);
6991 ufshcd_setup_clocks(hba, false);
6992 ufshcd_setup_hba_vreg(hba, false);
6993 hba->is_powered = false;
6998 ufshcd_send_request_sense(struct ufs_hba *hba, struct scsi_device *sdp)
7000 unsigned char cmd[6] = {REQUEST_SENSE,
7004 UFSHCD_REQ_SENSE_SIZE,
7009 buffer = kzalloc(UFSHCD_REQ_SENSE_SIZE, GFP_KERNEL);
7015 ret = scsi_execute(sdp, cmd, DMA_FROM_DEVICE, buffer,
7016 UFSHCD_REQ_SENSE_SIZE, NULL, NULL,
7017 msecs_to_jiffies(1000), 3, 0, RQF_PM, NULL);
7019 pr_err("%s: failed with err %d\n", __func__, ret);
7027 * ufshcd_set_dev_pwr_mode - sends START STOP UNIT command to set device
7029 * @hba: per adapter instance
7030 * @pwr_mode: device power mode to set
7032 * Returns 0 if requested power mode is set successfully
7033 * Returns non-zero if failed to set the requested power mode
7035 static int ufshcd_set_dev_pwr_mode(struct ufs_hba *hba,
7036 enum ufs_dev_pwr_mode pwr_mode)
7038 unsigned char cmd[6] = { START_STOP };
7039 struct scsi_sense_hdr sshdr;
7040 struct scsi_device *sdp;
7041 unsigned long flags;
7044 spin_lock_irqsave(hba->host->host_lock, flags);
7045 sdp = hba->sdev_ufs_device;
7047 ret = scsi_device_get(sdp);
7048 if (!ret && !scsi_device_online(sdp)) {
7050 scsi_device_put(sdp);
7055 spin_unlock_irqrestore(hba->host->host_lock, flags);
7061 * If scsi commands fail, the scsi mid-layer schedules scsi error-
7062 * handling, which would wait for host to be resumed. Since we know
7063 * we are functional while we are here, skip host resume in error
7066 hba->host->eh_noresume = 1;
7067 if (hba->wlun_dev_clr_ua) {
7068 ret = ufshcd_send_request_sense(hba, sdp);
7071 /* Unit attention condition is cleared now */
7072 hba->wlun_dev_clr_ua = false;
7075 cmd[4] = pwr_mode << 4;
7078 * Current function would be generally called from the power management
7079 * callbacks hence set the RQF_PM flag so that it doesn't resume the
7080 * already suspended childs.
7082 ret = scsi_execute(sdp, cmd, DMA_NONE, NULL, 0, NULL, &sshdr,
7083 START_STOP_TIMEOUT, 0, 0, RQF_PM, NULL);
7085 sdev_printk(KERN_WARNING, sdp,
7086 "START_STOP failed for power mode: %d, result %x\n",
7088 if (driver_byte(ret) & DRIVER_SENSE)
7089 scsi_print_sense_hdr(sdp, NULL, &sshdr);
7093 hba->curr_dev_pwr_mode = pwr_mode;
7095 scsi_device_put(sdp);
7096 hba->host->eh_noresume = 0;
7100 static int ufshcd_link_state_transition(struct ufs_hba *hba,
7101 enum uic_link_state req_link_state,
7102 int check_for_bkops)
7106 if (req_link_state == hba->uic_link_state)
7109 if (req_link_state == UIC_LINK_HIBERN8_STATE) {
7110 ret = ufshcd_uic_hibern8_enter(hba);
7112 ufshcd_set_link_hibern8(hba);
7117 * If autobkops is enabled, link can't be turned off because
7118 * turning off the link would also turn off the device.
7120 else if ((req_link_state == UIC_LINK_OFF_STATE) &&
7121 (!check_for_bkops || (check_for_bkops &&
7122 !hba->auto_bkops_enabled))) {
7124 * Let's make sure that link is in low power mode, we are doing
7125 * this currently by putting the link in Hibern8. Otherway to
7126 * put the link in low power mode is to send the DME end point
7127 * to device and then send the DME reset command to local
7128 * unipro. But putting the link in hibern8 is much faster.
7130 ret = ufshcd_uic_hibern8_enter(hba);
7134 * Change controller state to "reset state" which
7135 * should also put the link in off/reset state
7137 ufshcd_hba_stop(hba, true);
7139 * TODO: Check if we need any delay to make sure that
7140 * controller is reset
7142 ufshcd_set_link_off(hba);
7149 static void ufshcd_vreg_set_lpm(struct ufs_hba *hba)
7152 * It seems some UFS devices may keep drawing more than sleep current
7153 * (atleast for 500us) from UFS rails (especially from VCCQ rail).
7154 * To avoid this situation, add 2ms delay before putting these UFS
7155 * rails in LPM mode.
7157 if (!ufshcd_is_link_active(hba) &&
7158 hba->dev_quirks & UFS_DEVICE_QUIRK_DELAY_BEFORE_LPM)
7159 usleep_range(2000, 2100);
7162 * If UFS device is either in UFS_Sleep turn off VCC rail to save some
7165 * If UFS device and link is in OFF state, all power supplies (VCC,
7166 * VCCQ, VCCQ2) can be turned off if power on write protect is not
7167 * required. If UFS link is inactive (Hibern8 or OFF state) and device
7168 * is in sleep state, put VCCQ & VCCQ2 rails in LPM mode.
7170 * Ignore the error returned by ufshcd_toggle_vreg() as device is anyway
7171 * in low power state which would save some power.
7173 if (ufshcd_is_ufs_dev_poweroff(hba) && ufshcd_is_link_off(hba) &&
7174 !hba->dev_info.is_lu_power_on_wp) {
7175 ufshcd_setup_vreg(hba, false);
7176 } else if (!ufshcd_is_ufs_dev_active(hba)) {
7177 ufshcd_toggle_vreg(hba->dev, hba->vreg_info.vcc, false);
7178 if (!ufshcd_is_link_active(hba)) {
7179 ufshcd_config_vreg_lpm(hba, hba->vreg_info.vccq);
7180 ufshcd_config_vreg_lpm(hba, hba->vreg_info.vccq2);
7185 static int ufshcd_vreg_set_hpm(struct ufs_hba *hba)
7189 if (ufshcd_is_ufs_dev_poweroff(hba) && ufshcd_is_link_off(hba) &&
7190 !hba->dev_info.is_lu_power_on_wp) {
7191 ret = ufshcd_setup_vreg(hba, true);
7192 } else if (!ufshcd_is_ufs_dev_active(hba)) {
7193 if (!ret && !ufshcd_is_link_active(hba)) {
7194 ret = ufshcd_config_vreg_hpm(hba, hba->vreg_info.vccq);
7197 ret = ufshcd_config_vreg_hpm(hba, hba->vreg_info.vccq2);
7201 ret = ufshcd_toggle_vreg(hba->dev, hba->vreg_info.vcc, true);
7206 ufshcd_config_vreg_lpm(hba, hba->vreg_info.vccq);
7208 ufshcd_toggle_vreg(hba->dev, hba->vreg_info.vcc, false);
7213 static void ufshcd_hba_vreg_set_lpm(struct ufs_hba *hba)
7215 if (ufshcd_is_link_off(hba))
7216 ufshcd_setup_hba_vreg(hba, false);
7219 static void ufshcd_hba_vreg_set_hpm(struct ufs_hba *hba)
7221 if (ufshcd_is_link_off(hba))
7222 ufshcd_setup_hba_vreg(hba, true);
7226 * ufshcd_suspend - helper function for suspend operations
7227 * @hba: per adapter instance
7228 * @pm_op: desired low power operation type
7230 * This function will try to put the UFS device and link into low power
7231 * mode based on the "rpm_lvl" (Runtime PM level) or "spm_lvl"
7232 * (System PM level).
7234 * If this function is called during shutdown, it will make sure that
7235 * both UFS device and UFS link is powered off.
7237 * NOTE: UFS device & link must be active before we enter in this function.
7239 * Returns 0 for success and non-zero for failure
7241 static int ufshcd_suspend(struct ufs_hba *hba, enum ufs_pm_op pm_op)
7244 enum ufs_pm_level pm_lvl;
7245 enum ufs_dev_pwr_mode req_dev_pwr_mode;
7246 enum uic_link_state req_link_state;
7248 hba->pm_op_in_progress = 1;
7249 if (!ufshcd_is_shutdown_pm(pm_op)) {
7250 pm_lvl = ufshcd_is_runtime_pm(pm_op) ?
7251 hba->rpm_lvl : hba->spm_lvl;
7252 req_dev_pwr_mode = ufs_get_pm_lvl_to_dev_pwr_mode(pm_lvl);
7253 req_link_state = ufs_get_pm_lvl_to_link_pwr_state(pm_lvl);
7255 req_dev_pwr_mode = UFS_POWERDOWN_PWR_MODE;
7256 req_link_state = UIC_LINK_OFF_STATE;
7260 * If we can't transition into any of the low power modes
7261 * just gate the clocks.
7263 ufshcd_hold(hba, false);
7264 hba->clk_gating.is_suspended = true;
7266 if (hba->clk_scaling.is_allowed) {
7267 cancel_work_sync(&hba->clk_scaling.suspend_work);
7268 cancel_work_sync(&hba->clk_scaling.resume_work);
7269 ufshcd_suspend_clkscaling(hba);
7272 if (req_dev_pwr_mode == UFS_ACTIVE_PWR_MODE &&
7273 req_link_state == UIC_LINK_ACTIVE_STATE) {
7277 if ((req_dev_pwr_mode == hba->curr_dev_pwr_mode) &&
7278 (req_link_state == hba->uic_link_state))
7281 /* UFS device & link must be active before we enter in this function */
7282 if (!ufshcd_is_ufs_dev_active(hba) || !ufshcd_is_link_active(hba)) {
7287 if (ufshcd_is_runtime_pm(pm_op)) {
7288 if (ufshcd_can_autobkops_during_suspend(hba)) {
7290 * The device is idle with no requests in the queue,
7291 * allow background operations if bkops status shows
7292 * that performance might be impacted.
7294 ret = ufshcd_urgent_bkops(hba);
7298 /* make sure that auto bkops is disabled */
7299 ufshcd_disable_auto_bkops(hba);
7303 if ((req_dev_pwr_mode != hba->curr_dev_pwr_mode) &&
7304 ((ufshcd_is_runtime_pm(pm_op) && !hba->auto_bkops_enabled) ||
7305 !ufshcd_is_runtime_pm(pm_op))) {
7306 /* ensure that bkops is disabled */
7307 ufshcd_disable_auto_bkops(hba);
7308 ret = ufshcd_set_dev_pwr_mode(hba, req_dev_pwr_mode);
7313 ret = ufshcd_link_state_transition(hba, req_link_state, 1);
7315 goto set_dev_active;
7317 ufshcd_vreg_set_lpm(hba);
7321 * Call vendor specific suspend callback. As these callbacks may access
7322 * vendor specific host controller register space call them before the
7323 * host clocks are ON.
7325 ret = ufshcd_vops_suspend(hba, pm_op);
7327 goto set_link_active;
7329 if (!ufshcd_is_link_active(hba))
7330 ufshcd_setup_clocks(hba, false);
7332 /* If link is active, device ref_clk can't be switched off */
7333 __ufshcd_setup_clocks(hba, false, true);
7335 hba->clk_gating.state = CLKS_OFF;
7336 trace_ufshcd_clk_gating(dev_name(hba->dev), hba->clk_gating.state);
7338 * Disable the host irq as host controller as there won't be any
7339 * host controller transaction expected till resume.
7341 ufshcd_disable_irq(hba);
7342 /* Put the host controller in low power mode if possible */
7343 ufshcd_hba_vreg_set_lpm(hba);
7347 if (hba->clk_scaling.is_allowed)
7348 ufshcd_resume_clkscaling(hba);
7349 ufshcd_vreg_set_hpm(hba);
7350 if (ufshcd_is_link_hibern8(hba) && !ufshcd_uic_hibern8_exit(hba))
7351 ufshcd_set_link_active(hba);
7352 else if (ufshcd_is_link_off(hba))
7353 ufshcd_host_reset_and_restore(hba);
7355 if (!ufshcd_set_dev_pwr_mode(hba, UFS_ACTIVE_PWR_MODE))
7356 ufshcd_disable_auto_bkops(hba);
7358 if (hba->clk_scaling.is_allowed)
7359 ufshcd_resume_clkscaling(hba);
7360 hba->clk_gating.is_suspended = false;
7361 ufshcd_release(hba);
7363 hba->pm_op_in_progress = 0;
7368 * ufshcd_resume - helper function for resume operations
7369 * @hba: per adapter instance
7370 * @pm_op: runtime PM or system PM
7372 * This function basically brings the UFS device, UniPro link and controller
7375 * Returns 0 for success and non-zero for failure
7377 static int ufshcd_resume(struct ufs_hba *hba, enum ufs_pm_op pm_op)
7380 enum uic_link_state old_link_state;
7382 hba->pm_op_in_progress = 1;
7383 old_link_state = hba->uic_link_state;
7385 ufshcd_hba_vreg_set_hpm(hba);
7386 /* Make sure clocks are enabled before accessing controller */
7387 ret = ufshcd_setup_clocks(hba, true);
7391 /* enable the host irq as host controller would be active soon */
7392 ret = ufshcd_enable_irq(hba);
7394 goto disable_irq_and_vops_clks;
7396 ret = ufshcd_vreg_set_hpm(hba);
7398 goto disable_irq_and_vops_clks;
7401 * Call vendor specific resume callback. As these callbacks may access
7402 * vendor specific host controller register space call them when the
7403 * host clocks are ON.
7405 ret = ufshcd_vops_resume(hba, pm_op);
7409 if (ufshcd_is_link_hibern8(hba)) {
7410 ret = ufshcd_uic_hibern8_exit(hba);
7412 ufshcd_set_link_active(hba);
7414 goto vendor_suspend;
7415 } else if (ufshcd_is_link_off(hba)) {
7416 ret = ufshcd_host_reset_and_restore(hba);
7418 * ufshcd_host_reset_and_restore() should have already
7419 * set the link state as active
7421 if (ret || !ufshcd_is_link_active(hba))
7422 goto vendor_suspend;
7425 if (!ufshcd_is_ufs_dev_active(hba)) {
7426 ret = ufshcd_set_dev_pwr_mode(hba, UFS_ACTIVE_PWR_MODE);
7428 goto set_old_link_state;
7431 if (ufshcd_keep_autobkops_enabled_except_suspend(hba))
7432 ufshcd_enable_auto_bkops(hba);
7435 * If BKOPs operations are urgently needed at this moment then
7436 * keep auto-bkops enabled or else disable it.
7438 ufshcd_urgent_bkops(hba);
7440 hba->clk_gating.is_suspended = false;
7442 if (hba->clk_scaling.is_allowed)
7443 ufshcd_resume_clkscaling(hba);
7445 /* Schedule clock gating in case of no access to UFS device yet */
7446 ufshcd_release(hba);
7448 /* Enable Auto-Hibernate if configured */
7449 ufshcd_auto_hibern8_enable(hba);
7454 ufshcd_link_state_transition(hba, old_link_state, 0);
7456 ufshcd_vops_suspend(hba, pm_op);
7458 ufshcd_vreg_set_lpm(hba);
7459 disable_irq_and_vops_clks:
7460 ufshcd_disable_irq(hba);
7461 if (hba->clk_scaling.is_allowed)
7462 ufshcd_suspend_clkscaling(hba);
7463 ufshcd_setup_clocks(hba, false);
7465 hba->pm_op_in_progress = 0;
7470 * ufshcd_system_suspend - system suspend routine
7471 * @hba: per adapter instance
7473 * Check the description of ufshcd_suspend() function for more details.
7475 * Returns 0 for success and non-zero for failure
7477 int ufshcd_system_suspend(struct ufs_hba *hba)
7480 ktime_t start = ktime_get();
7482 if (!hba || !hba->is_powered)
7485 if ((ufs_get_pm_lvl_to_dev_pwr_mode(hba->spm_lvl) ==
7486 hba->curr_dev_pwr_mode) &&
7487 (ufs_get_pm_lvl_to_link_pwr_state(hba->spm_lvl) ==
7488 hba->uic_link_state))
7491 if (pm_runtime_suspended(hba->dev)) {
7493 * UFS device and/or UFS link low power states during runtime
7494 * suspend seems to be different than what is expected during
7495 * system suspend. Hence runtime resume the devic & link and
7496 * let the system suspend low power states to take effect.
7497 * TODO: If resume takes longer time, we might have optimize
7498 * it in future by not resuming everything if possible.
7500 ret = ufshcd_runtime_resume(hba);
7505 ret = ufshcd_suspend(hba, UFS_SYSTEM_PM);
7507 trace_ufshcd_system_suspend(dev_name(hba->dev), ret,
7508 ktime_to_us(ktime_sub(ktime_get(), start)),
7509 hba->curr_dev_pwr_mode, hba->uic_link_state);
7511 hba->is_sys_suspended = true;
7514 EXPORT_SYMBOL(ufshcd_system_suspend);
7517 * ufshcd_system_resume - system resume routine
7518 * @hba: per adapter instance
7520 * Returns 0 for success and non-zero for failure
7523 int ufshcd_system_resume(struct ufs_hba *hba)
7526 ktime_t start = ktime_get();
7531 if (!hba->is_powered || pm_runtime_suspended(hba->dev))
7533 * Let the runtime resume take care of resuming
7534 * if runtime suspended.
7538 ret = ufshcd_resume(hba, UFS_SYSTEM_PM);
7540 trace_ufshcd_system_resume(dev_name(hba->dev), ret,
7541 ktime_to_us(ktime_sub(ktime_get(), start)),
7542 hba->curr_dev_pwr_mode, hba->uic_link_state);
7545 EXPORT_SYMBOL(ufshcd_system_resume);
7548 * ufshcd_runtime_suspend - runtime suspend routine
7549 * @hba: per adapter instance
7551 * Check the description of ufshcd_suspend() function for more details.
7553 * Returns 0 for success and non-zero for failure
7555 int ufshcd_runtime_suspend(struct ufs_hba *hba)
7558 ktime_t start = ktime_get();
7563 if (!hba->is_powered)
7566 ret = ufshcd_suspend(hba, UFS_RUNTIME_PM);
7568 trace_ufshcd_runtime_suspend(dev_name(hba->dev), ret,
7569 ktime_to_us(ktime_sub(ktime_get(), start)),
7570 hba->curr_dev_pwr_mode, hba->uic_link_state);
7573 EXPORT_SYMBOL(ufshcd_runtime_suspend);
7576 * ufshcd_runtime_resume - runtime resume routine
7577 * @hba: per adapter instance
7579 * This function basically brings the UFS device, UniPro link and controller
7580 * to active state. Following operations are done in this function:
7582 * 1. Turn on all the controller related clocks
7583 * 2. Bring the UniPro link out of Hibernate state
7584 * 3. If UFS device is in sleep state, turn ON VCC rail and bring the UFS device
7586 * 4. If auto-bkops is enabled on the device, disable it.
7588 * So following would be the possible power state after this function return
7590 * S1: UFS device in Active state with VCC rail ON
7591 * UniPro link in Active state
7592 * All the UFS/UniPro controller clocks are ON
7594 * Returns 0 for success and non-zero for failure
7596 int ufshcd_runtime_resume(struct ufs_hba *hba)
7599 ktime_t start = ktime_get();
7604 if (!hba->is_powered)
7607 ret = ufshcd_resume(hba, UFS_RUNTIME_PM);
7609 trace_ufshcd_runtime_resume(dev_name(hba->dev), ret,
7610 ktime_to_us(ktime_sub(ktime_get(), start)),
7611 hba->curr_dev_pwr_mode, hba->uic_link_state);
7614 EXPORT_SYMBOL(ufshcd_runtime_resume);
7616 int ufshcd_runtime_idle(struct ufs_hba *hba)
7620 EXPORT_SYMBOL(ufshcd_runtime_idle);
7623 * ufshcd_shutdown - shutdown routine
7624 * @hba: per adapter instance
7626 * This function would power off both UFS device and UFS link.
7628 * Returns 0 always to allow force shutdown even in case of errors.
7630 int ufshcd_shutdown(struct ufs_hba *hba)
7634 if (ufshcd_is_ufs_dev_poweroff(hba) && ufshcd_is_link_off(hba))
7637 if (pm_runtime_suspended(hba->dev)) {
7638 ret = ufshcd_runtime_resume(hba);
7643 ret = ufshcd_suspend(hba, UFS_SHUTDOWN_PM);
7646 dev_err(hba->dev, "%s failed, err %d\n", __func__, ret);
7647 /* allow force shutdown even in case of errors */
7650 EXPORT_SYMBOL(ufshcd_shutdown);
7653 * ufshcd_remove - de-allocate SCSI host and host memory space
7654 * data structure memory
7655 * @hba: per adapter instance
7657 void ufshcd_remove(struct ufs_hba *hba)
7659 ufs_sysfs_remove_nodes(hba->dev);
7660 scsi_remove_host(hba->host);
7661 /* disable interrupts */
7662 ufshcd_disable_intr(hba, hba->intr_mask);
7663 ufshcd_hba_stop(hba, true);
7665 ufshcd_exit_clk_gating(hba);
7666 if (ufshcd_is_clkscaling_supported(hba))
7667 device_remove_file(hba->dev, &hba->clk_scaling.enable_attr);
7668 ufshcd_hba_exit(hba);
7670 EXPORT_SYMBOL_GPL(ufshcd_remove);
7673 * ufshcd_dealloc_host - deallocate Host Bus Adapter (HBA)
7674 * @hba: pointer to Host Bus Adapter (HBA)
7676 void ufshcd_dealloc_host(struct ufs_hba *hba)
7678 scsi_host_put(hba->host);
7680 EXPORT_SYMBOL_GPL(ufshcd_dealloc_host);
7683 * ufshcd_set_dma_mask - Set dma mask based on the controller
7684 * addressing capability
7685 * @hba: per adapter instance
7687 * Returns 0 for success, non-zero for failure
7689 static int ufshcd_set_dma_mask(struct ufs_hba *hba)
7691 if (hba->capabilities & MASK_64_ADDRESSING_SUPPORT) {
7692 if (!dma_set_mask_and_coherent(hba->dev, DMA_BIT_MASK(64)))
7695 return dma_set_mask_and_coherent(hba->dev, DMA_BIT_MASK(32));
7699 * ufshcd_alloc_host - allocate Host Bus Adapter (HBA)
7700 * @dev: pointer to device handle
7701 * @hba_handle: driver private handle
7702 * Returns 0 on success, non-zero value on failure
7704 int ufshcd_alloc_host(struct device *dev, struct ufs_hba **hba_handle)
7706 struct Scsi_Host *host;
7707 struct ufs_hba *hba;
7712 "Invalid memory reference for dev is NULL\n");
7717 host = scsi_host_alloc(&ufshcd_driver_template,
7718 sizeof(struct ufs_hba));
7720 dev_err(dev, "scsi_host_alloc failed\n");
7724 hba = shost_priv(host);
7729 INIT_LIST_HEAD(&hba->clk_list_head);
7734 EXPORT_SYMBOL(ufshcd_alloc_host);
7737 * ufshcd_init - Driver initialization routine
7738 * @hba: per-adapter instance
7739 * @mmio_base: base register address
7740 * @irq: Interrupt line of device
7741 * Returns 0 on success, non-zero value on failure
7743 int ufshcd_init(struct ufs_hba *hba, void __iomem *mmio_base, unsigned int irq)
7746 struct Scsi_Host *host = hba->host;
7747 struct device *dev = hba->dev;
7751 "Invalid memory reference for mmio_base is NULL\n");
7756 hba->mmio_base = mmio_base;
7759 /* Set descriptor lengths to specification defaults */
7760 ufshcd_def_desc_sizes(hba);
7762 err = ufshcd_hba_init(hba);
7766 /* Read capabilities registers */
7767 ufshcd_hba_capabilities(hba);
7769 /* Get UFS version supported by the controller */
7770 hba->ufs_version = ufshcd_get_ufs_version(hba);
7772 if ((hba->ufs_version != UFSHCI_VERSION_10) &&
7773 (hba->ufs_version != UFSHCI_VERSION_11) &&
7774 (hba->ufs_version != UFSHCI_VERSION_20) &&
7775 (hba->ufs_version != UFSHCI_VERSION_21))
7776 dev_err(hba->dev, "invalid UFS version 0x%x\n",
7779 /* Get Interrupt bit mask per version */
7780 hba->intr_mask = ufshcd_get_intr_mask(hba);
7782 err = ufshcd_set_dma_mask(hba);
7784 dev_err(hba->dev, "set dma mask failed\n");
7788 /* Allocate memory for host memory space */
7789 err = ufshcd_memory_alloc(hba);
7791 dev_err(hba->dev, "Memory allocation failed\n");
7796 ufshcd_host_memory_configure(hba);
7798 host->can_queue = hba->nutrs;
7799 host->cmd_per_lun = hba->nutrs;
7800 host->max_id = UFSHCD_MAX_ID;
7801 host->max_lun = UFS_MAX_LUNS;
7802 host->max_channel = UFSHCD_MAX_CHANNEL;
7803 host->unique_id = host->host_no;
7804 host->max_cmd_len = MAX_CDB_SIZE;
7806 hba->max_pwr_info.is_valid = false;
7808 /* Initailize wait queue for task management */
7809 init_waitqueue_head(&hba->tm_wq);
7810 init_waitqueue_head(&hba->tm_tag_wq);
7812 /* Initialize work queues */
7813 INIT_WORK(&hba->eh_work, ufshcd_err_handler);
7814 INIT_WORK(&hba->eeh_work, ufshcd_exception_event_handler);
7816 /* Initialize UIC command mutex */
7817 mutex_init(&hba->uic_cmd_mutex);
7819 /* Initialize mutex for device management commands */
7820 mutex_init(&hba->dev_cmd.lock);
7822 init_rwsem(&hba->clk_scaling_lock);
7824 /* Initialize device management tag acquire wait queue */
7825 init_waitqueue_head(&hba->dev_cmd.tag_wq);
7827 ufshcd_init_clk_gating(hba);
7830 * In order to avoid any spurious interrupt immediately after
7831 * registering UFS controller interrupt handler, clear any pending UFS
7832 * interrupt status and disable all the UFS interrupts.
7834 ufshcd_writel(hba, ufshcd_readl(hba, REG_INTERRUPT_STATUS),
7835 REG_INTERRUPT_STATUS);
7836 ufshcd_writel(hba, 0, REG_INTERRUPT_ENABLE);
7838 * Make sure that UFS interrupts are disabled and any pending interrupt
7839 * status is cleared before registering UFS interrupt handler.
7843 /* IRQ registration */
7844 err = devm_request_irq(dev, irq, ufshcd_intr, IRQF_SHARED, UFSHCD, hba);
7846 dev_err(hba->dev, "request irq failed\n");
7849 hba->is_irq_enabled = true;
7852 err = scsi_add_host(host, hba->dev);
7854 dev_err(hba->dev, "scsi_add_host failed\n");
7858 /* Host controller enable */
7859 err = ufshcd_hba_enable(hba);
7861 dev_err(hba->dev, "Host controller enable failed\n");
7862 ufshcd_print_host_regs(hba);
7863 ufshcd_print_host_state(hba);
7864 goto out_remove_scsi_host;
7867 if (ufshcd_is_clkscaling_supported(hba)) {
7868 char wq_name[sizeof("ufs_clkscaling_00")];
7870 INIT_WORK(&hba->clk_scaling.suspend_work,
7871 ufshcd_clk_scaling_suspend_work);
7872 INIT_WORK(&hba->clk_scaling.resume_work,
7873 ufshcd_clk_scaling_resume_work);
7875 snprintf(wq_name, sizeof(wq_name), "ufs_clkscaling_%d",
7877 hba->clk_scaling.workq = create_singlethread_workqueue(wq_name);
7879 ufshcd_clkscaling_init_sysfs(hba);
7883 * Set the default power management level for runtime and system PM.
7884 * Default power saving mode is to keep UFS link in Hibern8 state
7885 * and UFS device in sleep state.
7887 hba->rpm_lvl = ufs_get_desired_pm_lvl_for_dev_link_state(
7889 UIC_LINK_HIBERN8_STATE);
7890 hba->spm_lvl = ufs_get_desired_pm_lvl_for_dev_link_state(
7892 UIC_LINK_HIBERN8_STATE);
7894 /* Set the default auto-hiberate idle timer value to 150 ms */
7895 if (hba->capabilities & MASK_AUTO_HIBERN8_SUPPORT) {
7896 hba->ahit = FIELD_PREP(UFSHCI_AHIBERN8_TIMER_MASK, 150) |
7897 FIELD_PREP(UFSHCI_AHIBERN8_SCALE_MASK, 3);
7900 /* Hold auto suspend until async scan completes */
7901 pm_runtime_get_sync(dev);
7904 * We are assuming that device wasn't put in sleep/power-down
7905 * state exclusively during the boot stage before kernel.
7906 * This assumption helps avoid doing link startup twice during
7907 * ufshcd_probe_hba().
7909 ufshcd_set_ufs_dev_active(hba);
7911 async_schedule(ufshcd_async_scan, hba);
7912 ufs_sysfs_add_nodes(hba->dev);
7916 out_remove_scsi_host:
7917 scsi_remove_host(hba->host);
7919 ufshcd_exit_clk_gating(hba);
7921 hba->is_irq_enabled = false;
7922 ufshcd_hba_exit(hba);
7926 EXPORT_SYMBOL_GPL(ufshcd_init);
7928 MODULE_AUTHOR("Santosh Yaragnavi <santosh.sy@samsung.com>");
7929 MODULE_AUTHOR("Vinayak Holikatti <h.vinayak@samsung.com>");
7930 MODULE_DESCRIPTION("Generic UFS host controller driver Core");
7931 MODULE_LICENSE("GPL");
7932 MODULE_VERSION(UFSHCD_DRIVER_VERSION);