scsi: ufs: flush eh_work when eh_work scheduled.
[linux-2.6/btrfs-unstable.git] / drivers / scsi / ufs / ufshcd.c
blob5bc9dc14e075060aaacfba82a82ed21da08274f3
1 /*
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.
8 * Authors:
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
34 * this program.
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>
43 #include <linux/of.h>
44 #include "ufshcd.h"
45 #include "ufs_quirks.h"
46 #include "unipro.h"
48 #define CREATE_TRACE_POINTS
49 #include <trace/events/ufs.h>
51 #define UFSHCD_REQ_SENSE_SIZE 18
53 #define UFSHCD_ENABLE_INTRS (UTP_TRANSFER_REQ_COMPL |\
54 UTP_TASK_REQ_COMPL |\
55 UFSHCD_ERROR_MASK)
56 /* UIC command timeout, unit: ms */
57 #define UIC_CMD_TIMEOUT 500
59 /* NOP OUT retries waiting for NOP IN response */
60 #define NOP_OUT_RETRIES 10
61 /* Timeout after 30 msecs if NOP OUT hangs without response */
62 #define NOP_OUT_TIMEOUT 30 /* msecs */
64 /* Query request retries */
65 #define QUERY_REQ_RETRIES 3
66 /* Query request timeout */
67 #define QUERY_REQ_TIMEOUT 1500 /* 1.5 seconds */
69 /* Task management command timeout */
70 #define TM_CMD_TIMEOUT 100 /* msecs */
72 /* maximum number of retries for a general UIC command */
73 #define UFS_UIC_COMMAND_RETRIES 3
75 /* maximum number of link-startup retries */
76 #define DME_LINKSTARTUP_RETRIES 3
78 /* Maximum retries for Hibern8 enter */
79 #define UIC_HIBERN8_ENTER_RETRIES 3
81 /* maximum number of reset retries before giving up */
82 #define MAX_HOST_RESET_RETRIES 5
84 /* Expose the flag value from utp_upiu_query.value */
85 #define MASK_QUERY_UPIU_FLAG_LOC 0xFF
87 /* Interrupt aggregation default timeout, unit: 40us */
88 #define INT_AGGR_DEF_TO 0x02
90 #define ufshcd_toggle_vreg(_dev, _vreg, _on) \
91 ({ \
92 int _ret; \
93 if (_on) \
94 _ret = ufshcd_enable_vreg(_dev, _vreg); \
95 else \
96 _ret = ufshcd_disable_vreg(_dev, _vreg); \
97 _ret; \
100 #define ufshcd_hex_dump(prefix_str, buf, len) \
101 print_hex_dump(KERN_ERR, prefix_str, DUMP_PREFIX_OFFSET, 16, 4, buf, len, false)
103 enum {
104 UFSHCD_MAX_CHANNEL = 0,
105 UFSHCD_MAX_ID = 1,
106 UFSHCD_CMD_PER_LUN = 32,
107 UFSHCD_CAN_QUEUE = 32,
110 /* UFSHCD states */
111 enum {
112 UFSHCD_STATE_RESET,
113 UFSHCD_STATE_ERROR,
114 UFSHCD_STATE_OPERATIONAL,
115 UFSHCD_STATE_EH_SCHEDULED,
118 /* UFSHCD error handling flags */
119 enum {
120 UFSHCD_EH_IN_PROGRESS = (1 << 0),
123 /* UFSHCD UIC layer error flags */
124 enum {
125 UFSHCD_UIC_DL_PA_INIT_ERROR = (1 << 0), /* Data link layer error */
126 UFSHCD_UIC_DL_NAC_RECEIVED_ERROR = (1 << 1), /* Data link layer error */
127 UFSHCD_UIC_DL_TCx_REPLAY_ERROR = (1 << 2), /* Data link layer error */
128 UFSHCD_UIC_NL_ERROR = (1 << 3), /* Network layer error */
129 UFSHCD_UIC_TL_ERROR = (1 << 4), /* Transport Layer error */
130 UFSHCD_UIC_DME_ERROR = (1 << 5), /* DME error */
133 #define ufshcd_set_eh_in_progress(h) \
134 ((h)->eh_flags |= UFSHCD_EH_IN_PROGRESS)
135 #define ufshcd_eh_in_progress(h) \
136 ((h)->eh_flags & UFSHCD_EH_IN_PROGRESS)
137 #define ufshcd_clear_eh_in_progress(h) \
138 ((h)->eh_flags &= ~UFSHCD_EH_IN_PROGRESS)
140 #define ufshcd_set_ufs_dev_active(h) \
141 ((h)->curr_dev_pwr_mode = UFS_ACTIVE_PWR_MODE)
142 #define ufshcd_set_ufs_dev_sleep(h) \
143 ((h)->curr_dev_pwr_mode = UFS_SLEEP_PWR_MODE)
144 #define ufshcd_set_ufs_dev_poweroff(h) \
145 ((h)->curr_dev_pwr_mode = UFS_POWERDOWN_PWR_MODE)
146 #define ufshcd_is_ufs_dev_active(h) \
147 ((h)->curr_dev_pwr_mode == UFS_ACTIVE_PWR_MODE)
148 #define ufshcd_is_ufs_dev_sleep(h) \
149 ((h)->curr_dev_pwr_mode == UFS_SLEEP_PWR_MODE)
150 #define ufshcd_is_ufs_dev_poweroff(h) \
151 ((h)->curr_dev_pwr_mode == UFS_POWERDOWN_PWR_MODE)
153 static struct ufs_pm_lvl_states ufs_pm_lvl_states[] = {
154 {UFS_ACTIVE_PWR_MODE, UIC_LINK_ACTIVE_STATE},
155 {UFS_ACTIVE_PWR_MODE, UIC_LINK_HIBERN8_STATE},
156 {UFS_SLEEP_PWR_MODE, UIC_LINK_ACTIVE_STATE},
157 {UFS_SLEEP_PWR_MODE, UIC_LINK_HIBERN8_STATE},
158 {UFS_POWERDOWN_PWR_MODE, UIC_LINK_HIBERN8_STATE},
159 {UFS_POWERDOWN_PWR_MODE, UIC_LINK_OFF_STATE},
162 static inline enum ufs_dev_pwr_mode
163 ufs_get_pm_lvl_to_dev_pwr_mode(enum ufs_pm_level lvl)
165 return ufs_pm_lvl_states[lvl].dev_state;
168 static inline enum uic_link_state
169 ufs_get_pm_lvl_to_link_pwr_state(enum ufs_pm_level lvl)
171 return ufs_pm_lvl_states[lvl].link_state;
174 static inline enum ufs_pm_level
175 ufs_get_desired_pm_lvl_for_dev_link_state(enum ufs_dev_pwr_mode dev_state,
176 enum uic_link_state link_state)
178 enum ufs_pm_level lvl;
180 for (lvl = UFS_PM_LVL_0; lvl < UFS_PM_LVL_MAX; lvl++) {
181 if ((ufs_pm_lvl_states[lvl].dev_state == dev_state) &&
182 (ufs_pm_lvl_states[lvl].link_state == link_state))
183 return lvl;
186 /* if no match found, return the level 0 */
187 return UFS_PM_LVL_0;
190 static struct ufs_dev_fix ufs_fixups[] = {
191 /* UFS cards deviations table */
192 UFS_FIX(UFS_VENDOR_SAMSUNG, UFS_ANY_MODEL,
193 UFS_DEVICE_QUIRK_DELAY_BEFORE_LPM),
194 UFS_FIX(UFS_VENDOR_SAMSUNG, UFS_ANY_MODEL, UFS_DEVICE_NO_VCCQ),
195 UFS_FIX(UFS_VENDOR_SAMSUNG, UFS_ANY_MODEL,
196 UFS_DEVICE_QUIRK_RECOVERY_FROM_DL_NAC_ERRORS),
197 UFS_FIX(UFS_VENDOR_SAMSUNG, UFS_ANY_MODEL,
198 UFS_DEVICE_NO_FASTAUTO),
199 UFS_FIX(UFS_VENDOR_SAMSUNG, UFS_ANY_MODEL,
200 UFS_DEVICE_QUIRK_HOST_PA_TACTIVATE),
201 UFS_FIX(UFS_VENDOR_TOSHIBA, UFS_ANY_MODEL,
202 UFS_DEVICE_QUIRK_DELAY_BEFORE_LPM),
203 UFS_FIX(UFS_VENDOR_TOSHIBA, "THGLF2G9C8KBADG",
204 UFS_DEVICE_QUIRK_PA_TACTIVATE),
205 UFS_FIX(UFS_VENDOR_TOSHIBA, "THGLF2G9D8KBADG",
206 UFS_DEVICE_QUIRK_PA_TACTIVATE),
207 UFS_FIX(UFS_VENDOR_SKHYNIX, UFS_ANY_MODEL, UFS_DEVICE_NO_VCCQ),
208 UFS_FIX(UFS_VENDOR_SKHYNIX, UFS_ANY_MODEL,
209 UFS_DEVICE_QUIRK_HOST_PA_SAVECONFIGTIME),
211 END_FIX
214 static void ufshcd_tmc_handler(struct ufs_hba *hba);
215 static void ufshcd_async_scan(void *data, async_cookie_t cookie);
216 static int ufshcd_reset_and_restore(struct ufs_hba *hba);
217 static int ufshcd_eh_host_reset_handler(struct scsi_cmnd *cmd);
218 static int ufshcd_clear_tm_cmd(struct ufs_hba *hba, int tag);
219 static void ufshcd_hba_exit(struct ufs_hba *hba);
220 static int ufshcd_probe_hba(struct ufs_hba *hba);
221 static int __ufshcd_setup_clocks(struct ufs_hba *hba, bool on,
222 bool skip_ref_clk);
223 static int ufshcd_setup_clocks(struct ufs_hba *hba, bool on);
224 static int ufshcd_set_vccq_rail_unused(struct ufs_hba *hba, bool unused);
225 static int ufshcd_uic_hibern8_exit(struct ufs_hba *hba);
226 static int ufshcd_uic_hibern8_enter(struct ufs_hba *hba);
227 static inline void ufshcd_add_delay_before_dme_cmd(struct ufs_hba *hba);
228 static int ufshcd_host_reset_and_restore(struct ufs_hba *hba);
229 static void ufshcd_resume_clkscaling(struct ufs_hba *hba);
230 static void ufshcd_suspend_clkscaling(struct ufs_hba *hba);
231 static void __ufshcd_suspend_clkscaling(struct ufs_hba *hba);
232 static int ufshcd_scale_clks(struct ufs_hba *hba, bool scale_up);
233 static irqreturn_t ufshcd_intr(int irq, void *__hba);
234 static int ufshcd_config_pwr_mode(struct ufs_hba *hba,
235 struct ufs_pa_layer_attr *desired_pwr_mode);
236 static int ufshcd_change_power_mode(struct ufs_hba *hba,
237 struct ufs_pa_layer_attr *pwr_mode);
238 static inline bool ufshcd_valid_tag(struct ufs_hba *hba, int tag)
240 return tag >= 0 && tag < hba->nutrs;
243 static inline int ufshcd_enable_irq(struct ufs_hba *hba)
245 int ret = 0;
247 if (!hba->is_irq_enabled) {
248 ret = request_irq(hba->irq, ufshcd_intr, IRQF_SHARED, UFSHCD,
249 hba);
250 if (ret)
251 dev_err(hba->dev, "%s: request_irq failed, ret=%d\n",
252 __func__, ret);
253 hba->is_irq_enabled = true;
256 return ret;
259 static inline void ufshcd_disable_irq(struct ufs_hba *hba)
261 if (hba->is_irq_enabled) {
262 free_irq(hba->irq, hba);
263 hba->is_irq_enabled = false;
267 /* replace non-printable or non-ASCII characters with spaces */
268 static inline void ufshcd_remove_non_printable(char *val)
270 if (!val)
271 return;
273 if (*val < 0x20 || *val > 0x7e)
274 *val = ' ';
277 static void ufshcd_add_command_trace(struct ufs_hba *hba,
278 unsigned int tag, const char *str)
280 sector_t lba = -1;
281 u8 opcode = 0;
282 u32 intr, doorbell;
283 struct ufshcd_lrb *lrbp;
284 int transfer_len = -1;
286 if (!trace_ufshcd_command_enabled())
287 return;
289 lrbp = &hba->lrb[tag];
291 if (lrbp->cmd) { /* data phase exists */
292 opcode = (u8)(*lrbp->cmd->cmnd);
293 if ((opcode == READ_10) || (opcode == WRITE_10)) {
295 * Currently we only fully trace read(10) and write(10)
296 * commands
298 if (lrbp->cmd->request && lrbp->cmd->request->bio)
299 lba =
300 lrbp->cmd->request->bio->bi_iter.bi_sector;
301 transfer_len = be32_to_cpu(
302 lrbp->ucd_req_ptr->sc.exp_data_transfer_len);
306 intr = ufshcd_readl(hba, REG_INTERRUPT_STATUS);
307 doorbell = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
308 trace_ufshcd_command(dev_name(hba->dev), str, tag,
309 doorbell, transfer_len, intr, lba, opcode);
312 static void ufshcd_print_clk_freqs(struct ufs_hba *hba)
314 struct ufs_clk_info *clki;
315 struct list_head *head = &hba->clk_list_head;
317 if (list_empty(head))
318 return;
320 list_for_each_entry(clki, head, list) {
321 if (!IS_ERR_OR_NULL(clki->clk) && clki->min_freq &&
322 clki->max_freq)
323 dev_err(hba->dev, "clk: %s, rate: %u\n",
324 clki->name, clki->curr_freq);
328 static void ufshcd_print_uic_err_hist(struct ufs_hba *hba,
329 struct ufs_uic_err_reg_hist *err_hist, char *err_name)
331 int i;
333 for (i = 0; i < UIC_ERR_REG_HIST_LENGTH; i++) {
334 int p = (i + err_hist->pos - 1) % UIC_ERR_REG_HIST_LENGTH;
336 if (err_hist->reg[p] == 0)
337 continue;
338 dev_err(hba->dev, "%s[%d] = 0x%x at %lld us\n", err_name, i,
339 err_hist->reg[p], ktime_to_us(err_hist->tstamp[p]));
343 static void ufshcd_print_host_regs(struct ufs_hba *hba)
346 * hex_dump reads its data without the readl macro. This might
347 * cause inconsistency issues on some platform, as the printed
348 * values may be from cache and not the most recent value.
349 * To know whether you are looking at an un-cached version verify
350 * that IORESOURCE_MEM flag is on when xxx_get_resource() is invoked
351 * during platform/pci probe function.
353 ufshcd_hex_dump("host regs: ", hba->mmio_base, UFSHCI_REG_SPACE_SIZE);
354 dev_err(hba->dev, "hba->ufs_version = 0x%x, hba->capabilities = 0x%x\n",
355 hba->ufs_version, hba->capabilities);
356 dev_err(hba->dev,
357 "hba->outstanding_reqs = 0x%x, hba->outstanding_tasks = 0x%x\n",
358 (u32)hba->outstanding_reqs, (u32)hba->outstanding_tasks);
359 dev_err(hba->dev,
360 "last_hibern8_exit_tstamp at %lld us, hibern8_exit_cnt = %d\n",
361 ktime_to_us(hba->ufs_stats.last_hibern8_exit_tstamp),
362 hba->ufs_stats.hibern8_exit_cnt);
364 ufshcd_print_uic_err_hist(hba, &hba->ufs_stats.pa_err, "pa_err");
365 ufshcd_print_uic_err_hist(hba, &hba->ufs_stats.dl_err, "dl_err");
366 ufshcd_print_uic_err_hist(hba, &hba->ufs_stats.nl_err, "nl_err");
367 ufshcd_print_uic_err_hist(hba, &hba->ufs_stats.tl_err, "tl_err");
368 ufshcd_print_uic_err_hist(hba, &hba->ufs_stats.dme_err, "dme_err");
370 ufshcd_print_clk_freqs(hba);
372 if (hba->vops && hba->vops->dbg_register_dump)
373 hba->vops->dbg_register_dump(hba);
376 static
377 void ufshcd_print_trs(struct ufs_hba *hba, unsigned long bitmap, bool pr_prdt)
379 struct ufshcd_lrb *lrbp;
380 int prdt_length;
381 int tag;
383 for_each_set_bit(tag, &bitmap, hba->nutrs) {
384 lrbp = &hba->lrb[tag];
386 dev_err(hba->dev, "UPIU[%d] - issue time %lld us\n",
387 tag, ktime_to_us(lrbp->issue_time_stamp));
388 dev_err(hba->dev,
389 "UPIU[%d] - Transfer Request Descriptor phys@0x%llx\n",
390 tag, (u64)lrbp->utrd_dma_addr);
392 ufshcd_hex_dump("UPIU TRD: ", lrbp->utr_descriptor_ptr,
393 sizeof(struct utp_transfer_req_desc));
394 dev_err(hba->dev, "UPIU[%d] - Request UPIU phys@0x%llx\n", tag,
395 (u64)lrbp->ucd_req_dma_addr);
396 ufshcd_hex_dump("UPIU REQ: ", lrbp->ucd_req_ptr,
397 sizeof(struct utp_upiu_req));
398 dev_err(hba->dev, "UPIU[%d] - Response UPIU phys@0x%llx\n", tag,
399 (u64)lrbp->ucd_rsp_dma_addr);
400 ufshcd_hex_dump("UPIU RSP: ", lrbp->ucd_rsp_ptr,
401 sizeof(struct utp_upiu_rsp));
403 prdt_length = le16_to_cpu(
404 lrbp->utr_descriptor_ptr->prd_table_length);
405 dev_err(hba->dev,
406 "UPIU[%d] - PRDT - %d entries phys@0x%llx\n",
407 tag, prdt_length,
408 (u64)lrbp->ucd_prdt_dma_addr);
410 if (pr_prdt)
411 ufshcd_hex_dump("UPIU PRDT: ", lrbp->ucd_prdt_ptr,
412 sizeof(struct ufshcd_sg_entry) * prdt_length);
416 static void ufshcd_print_tmrs(struct ufs_hba *hba, unsigned long bitmap)
418 struct utp_task_req_desc *tmrdp;
419 int tag;
421 for_each_set_bit(tag, &bitmap, hba->nutmrs) {
422 tmrdp = &hba->utmrdl_base_addr[tag];
423 dev_err(hba->dev, "TM[%d] - Task Management Header\n", tag);
424 ufshcd_hex_dump("TM TRD: ", &tmrdp->header,
425 sizeof(struct request_desc_header));
426 dev_err(hba->dev, "TM[%d] - Task Management Request UPIU\n",
427 tag);
428 ufshcd_hex_dump("TM REQ: ", tmrdp->task_req_upiu,
429 sizeof(struct utp_upiu_req));
430 dev_err(hba->dev, "TM[%d] - Task Management Response UPIU\n",
431 tag);
432 ufshcd_hex_dump("TM RSP: ", tmrdp->task_rsp_upiu,
433 sizeof(struct utp_task_req_desc));
437 static void ufshcd_print_host_state(struct ufs_hba *hba)
439 dev_err(hba->dev, "UFS Host state=%d\n", hba->ufshcd_state);
440 dev_err(hba->dev, "lrb in use=0x%lx, outstanding reqs=0x%lx tasks=0x%lx\n",
441 hba->lrb_in_use, hba->outstanding_tasks, hba->outstanding_reqs);
442 dev_err(hba->dev, "saved_err=0x%x, saved_uic_err=0x%x\n",
443 hba->saved_err, hba->saved_uic_err);
444 dev_err(hba->dev, "Device power mode=%d, UIC link state=%d\n",
445 hba->curr_dev_pwr_mode, hba->uic_link_state);
446 dev_err(hba->dev, "PM in progress=%d, sys. suspended=%d\n",
447 hba->pm_op_in_progress, hba->is_sys_suspended);
448 dev_err(hba->dev, "Auto BKOPS=%d, Host self-block=%d\n",
449 hba->auto_bkops_enabled, hba->host->host_self_blocked);
450 dev_err(hba->dev, "Clk gate=%d\n", hba->clk_gating.state);
451 dev_err(hba->dev, "error handling flags=0x%x, req. abort count=%d\n",
452 hba->eh_flags, hba->req_abort_count);
453 dev_err(hba->dev, "Host capabilities=0x%x, caps=0x%x\n",
454 hba->capabilities, hba->caps);
455 dev_err(hba->dev, "quirks=0x%x, dev. quirks=0x%x\n", hba->quirks,
456 hba->dev_quirks);
460 * ufshcd_print_pwr_info - print power params as saved in hba
461 * power info
462 * @hba: per-adapter instance
464 static void ufshcd_print_pwr_info(struct ufs_hba *hba)
466 static const char * const names[] = {
467 "INVALID MODE",
468 "FAST MODE",
469 "SLOW_MODE",
470 "INVALID MODE",
471 "FASTAUTO_MODE",
472 "SLOWAUTO_MODE",
473 "INVALID MODE",
476 dev_err(hba->dev, "%s:[RX, TX]: gear=[%d, %d], lane[%d, %d], pwr[%s, %s], rate = %d\n",
477 __func__,
478 hba->pwr_info.gear_rx, hba->pwr_info.gear_tx,
479 hba->pwr_info.lane_rx, hba->pwr_info.lane_tx,
480 names[hba->pwr_info.pwr_rx],
481 names[hba->pwr_info.pwr_tx],
482 hba->pwr_info.hs_rate);
486 * ufshcd_wait_for_register - wait for register value to change
487 * @hba - per-adapter interface
488 * @reg - mmio register offset
489 * @mask - mask to apply to read register value
490 * @val - wait condition
491 * @interval_us - polling interval in microsecs
492 * @timeout_ms - timeout in millisecs
493 * @can_sleep - perform sleep or just spin
495 * Returns -ETIMEDOUT on error, zero on success
497 int ufshcd_wait_for_register(struct ufs_hba *hba, u32 reg, u32 mask,
498 u32 val, unsigned long interval_us,
499 unsigned long timeout_ms, bool can_sleep)
501 int err = 0;
502 unsigned long timeout = jiffies + msecs_to_jiffies(timeout_ms);
504 /* ignore bits that we don't intend to wait on */
505 val = val & mask;
507 while ((ufshcd_readl(hba, reg) & mask) != val) {
508 if (can_sleep)
509 usleep_range(interval_us, interval_us + 50);
510 else
511 udelay(interval_us);
512 if (time_after(jiffies, timeout)) {
513 if ((ufshcd_readl(hba, reg) & mask) != val)
514 err = -ETIMEDOUT;
515 break;
519 return err;
523 * ufshcd_get_intr_mask - Get the interrupt bit mask
524 * @hba - Pointer to adapter instance
526 * Returns interrupt bit mask per version
528 static inline u32 ufshcd_get_intr_mask(struct ufs_hba *hba)
530 u32 intr_mask = 0;
532 switch (hba->ufs_version) {
533 case UFSHCI_VERSION_10:
534 intr_mask = INTERRUPT_MASK_ALL_VER_10;
535 break;
536 case UFSHCI_VERSION_11:
537 case UFSHCI_VERSION_20:
538 intr_mask = INTERRUPT_MASK_ALL_VER_11;
539 break;
540 case UFSHCI_VERSION_21:
541 default:
542 intr_mask = INTERRUPT_MASK_ALL_VER_21;
543 break;
546 return intr_mask;
550 * ufshcd_get_ufs_version - Get the UFS version supported by the HBA
551 * @hba - Pointer to adapter instance
553 * Returns UFSHCI version supported by the controller
555 static inline u32 ufshcd_get_ufs_version(struct ufs_hba *hba)
557 if (hba->quirks & UFSHCD_QUIRK_BROKEN_UFS_HCI_VERSION)
558 return ufshcd_vops_get_ufs_hci_version(hba);
560 return ufshcd_readl(hba, REG_UFS_VERSION);
564 * ufshcd_is_device_present - Check if any device connected to
565 * the host controller
566 * @hba: pointer to adapter instance
568 * Returns true if device present, false if no device detected
570 static inline bool ufshcd_is_device_present(struct ufs_hba *hba)
572 return (ufshcd_readl(hba, REG_CONTROLLER_STATUS) &
573 DEVICE_PRESENT) ? true : false;
577 * ufshcd_get_tr_ocs - Get the UTRD Overall Command Status
578 * @lrb: pointer to local command reference block
580 * This function is used to get the OCS field from UTRD
581 * Returns the OCS field in the UTRD
583 static inline int ufshcd_get_tr_ocs(struct ufshcd_lrb *lrbp)
585 return le32_to_cpu(lrbp->utr_descriptor_ptr->header.dword_2) & MASK_OCS;
589 * ufshcd_get_tmr_ocs - Get the UTMRD Overall Command Status
590 * @task_req_descp: pointer to utp_task_req_desc structure
592 * This function is used to get the OCS field from UTMRD
593 * Returns the OCS field in the UTMRD
595 static inline int
596 ufshcd_get_tmr_ocs(struct utp_task_req_desc *task_req_descp)
598 return le32_to_cpu(task_req_descp->header.dword_2) & MASK_OCS;
602 * ufshcd_get_tm_free_slot - get a free slot for task management request
603 * @hba: per adapter instance
604 * @free_slot: pointer to variable with available slot value
606 * Get a free tag and lock it until ufshcd_put_tm_slot() is called.
607 * Returns 0 if free slot is not available, else return 1 with tag value
608 * in @free_slot.
610 static bool ufshcd_get_tm_free_slot(struct ufs_hba *hba, int *free_slot)
612 int tag;
613 bool ret = false;
615 if (!free_slot)
616 goto out;
618 do {
619 tag = find_first_zero_bit(&hba->tm_slots_in_use, hba->nutmrs);
620 if (tag >= hba->nutmrs)
621 goto out;
622 } while (test_and_set_bit_lock(tag, &hba->tm_slots_in_use));
624 *free_slot = tag;
625 ret = true;
626 out:
627 return ret;
630 static inline void ufshcd_put_tm_slot(struct ufs_hba *hba, int slot)
632 clear_bit_unlock(slot, &hba->tm_slots_in_use);
636 * ufshcd_utrl_clear - Clear a bit in UTRLCLR register
637 * @hba: per adapter instance
638 * @pos: position of the bit to be cleared
640 static inline void ufshcd_utrl_clear(struct ufs_hba *hba, u32 pos)
642 ufshcd_writel(hba, ~(1 << pos), REG_UTP_TRANSFER_REQ_LIST_CLEAR);
646 * ufshcd_outstanding_req_clear - Clear a bit in outstanding request field
647 * @hba: per adapter instance
648 * @tag: position of the bit to be cleared
650 static inline void ufshcd_outstanding_req_clear(struct ufs_hba *hba, int tag)
652 __clear_bit(tag, &hba->outstanding_reqs);
656 * ufshcd_get_lists_status - Check UCRDY, UTRLRDY and UTMRLRDY
657 * @reg: Register value of host controller status
659 * Returns integer, 0 on Success and positive value if failed
661 static inline int ufshcd_get_lists_status(u32 reg)
663 return !((reg & UFSHCD_STATUS_READY) == UFSHCD_STATUS_READY);
667 * ufshcd_get_uic_cmd_result - Get the UIC command result
668 * @hba: Pointer to adapter instance
670 * This function gets the result of UIC command completion
671 * Returns 0 on success, non zero value on error
673 static inline int ufshcd_get_uic_cmd_result(struct ufs_hba *hba)
675 return ufshcd_readl(hba, REG_UIC_COMMAND_ARG_2) &
676 MASK_UIC_COMMAND_RESULT;
680 * ufshcd_get_dme_attr_val - Get the value of attribute returned by UIC command
681 * @hba: Pointer to adapter instance
683 * This function gets UIC command argument3
684 * Returns 0 on success, non zero value on error
686 static inline u32 ufshcd_get_dme_attr_val(struct ufs_hba *hba)
688 return ufshcd_readl(hba, REG_UIC_COMMAND_ARG_3);
692 * ufshcd_get_req_rsp - returns the TR response transaction type
693 * @ucd_rsp_ptr: pointer to response UPIU
695 static inline int
696 ufshcd_get_req_rsp(struct utp_upiu_rsp *ucd_rsp_ptr)
698 return be32_to_cpu(ucd_rsp_ptr->header.dword_0) >> 24;
702 * ufshcd_get_rsp_upiu_result - Get the result from response UPIU
703 * @ucd_rsp_ptr: pointer to response UPIU
705 * This function gets the response status and scsi_status from response UPIU
706 * Returns the response result code.
708 static inline int
709 ufshcd_get_rsp_upiu_result(struct utp_upiu_rsp *ucd_rsp_ptr)
711 return be32_to_cpu(ucd_rsp_ptr->header.dword_1) & MASK_RSP_UPIU_RESULT;
715 * ufshcd_get_rsp_upiu_data_seg_len - Get the data segment length
716 * from response UPIU
717 * @ucd_rsp_ptr: pointer to response UPIU
719 * Return the data segment length.
721 static inline unsigned int
722 ufshcd_get_rsp_upiu_data_seg_len(struct utp_upiu_rsp *ucd_rsp_ptr)
724 return be32_to_cpu(ucd_rsp_ptr->header.dword_2) &
725 MASK_RSP_UPIU_DATA_SEG_LEN;
729 * ufshcd_is_exception_event - Check if the device raised an exception event
730 * @ucd_rsp_ptr: pointer to response UPIU
732 * The function checks if the device raised an exception event indicated in
733 * the Device Information field of response UPIU.
735 * Returns true if exception is raised, false otherwise.
737 static inline bool ufshcd_is_exception_event(struct utp_upiu_rsp *ucd_rsp_ptr)
739 return be32_to_cpu(ucd_rsp_ptr->header.dword_2) &
740 MASK_RSP_EXCEPTION_EVENT ? true : false;
744 * ufshcd_reset_intr_aggr - Reset interrupt aggregation values.
745 * @hba: per adapter instance
747 static inline void
748 ufshcd_reset_intr_aggr(struct ufs_hba *hba)
750 ufshcd_writel(hba, INT_AGGR_ENABLE |
751 INT_AGGR_COUNTER_AND_TIMER_RESET,
752 REG_UTP_TRANSFER_REQ_INT_AGG_CONTROL);
756 * ufshcd_config_intr_aggr - Configure interrupt aggregation values.
757 * @hba: per adapter instance
758 * @cnt: Interrupt aggregation counter threshold
759 * @tmout: Interrupt aggregation timeout value
761 static inline void
762 ufshcd_config_intr_aggr(struct ufs_hba *hba, u8 cnt, u8 tmout)
764 ufshcd_writel(hba, INT_AGGR_ENABLE | INT_AGGR_PARAM_WRITE |
765 INT_AGGR_COUNTER_THLD_VAL(cnt) |
766 INT_AGGR_TIMEOUT_VAL(tmout),
767 REG_UTP_TRANSFER_REQ_INT_AGG_CONTROL);
771 * ufshcd_disable_intr_aggr - Disables interrupt aggregation.
772 * @hba: per adapter instance
774 static inline void ufshcd_disable_intr_aggr(struct ufs_hba *hba)
776 ufshcd_writel(hba, 0, REG_UTP_TRANSFER_REQ_INT_AGG_CONTROL);
780 * ufshcd_enable_run_stop_reg - Enable run-stop registers,
781 * When run-stop registers are set to 1, it indicates the
782 * host controller that it can process the requests
783 * @hba: per adapter instance
785 static void ufshcd_enable_run_stop_reg(struct ufs_hba *hba)
787 ufshcd_writel(hba, UTP_TASK_REQ_LIST_RUN_STOP_BIT,
788 REG_UTP_TASK_REQ_LIST_RUN_STOP);
789 ufshcd_writel(hba, UTP_TRANSFER_REQ_LIST_RUN_STOP_BIT,
790 REG_UTP_TRANSFER_REQ_LIST_RUN_STOP);
794 * ufshcd_hba_start - Start controller initialization sequence
795 * @hba: per adapter instance
797 static inline void ufshcd_hba_start(struct ufs_hba *hba)
799 ufshcd_writel(hba, CONTROLLER_ENABLE, REG_CONTROLLER_ENABLE);
803 * ufshcd_is_hba_active - Get controller state
804 * @hba: per adapter instance
806 * Returns false if controller is active, true otherwise
808 static inline bool ufshcd_is_hba_active(struct ufs_hba *hba)
810 return (ufshcd_readl(hba, REG_CONTROLLER_ENABLE) & CONTROLLER_ENABLE)
811 ? false : true;
814 static const char *ufschd_uic_link_state_to_string(
815 enum uic_link_state state)
817 switch (state) {
818 case UIC_LINK_OFF_STATE: return "OFF";
819 case UIC_LINK_ACTIVE_STATE: return "ACTIVE";
820 case UIC_LINK_HIBERN8_STATE: return "HIBERN8";
821 default: return "UNKNOWN";
825 static const char *ufschd_ufs_dev_pwr_mode_to_string(
826 enum ufs_dev_pwr_mode state)
828 switch (state) {
829 case UFS_ACTIVE_PWR_MODE: return "ACTIVE";
830 case UFS_SLEEP_PWR_MODE: return "SLEEP";
831 case UFS_POWERDOWN_PWR_MODE: return "POWERDOWN";
832 default: return "UNKNOWN";
836 u32 ufshcd_get_local_unipro_ver(struct ufs_hba *hba)
838 /* HCI version 1.0 and 1.1 supports UniPro 1.41 */
839 if ((hba->ufs_version == UFSHCI_VERSION_10) ||
840 (hba->ufs_version == UFSHCI_VERSION_11))
841 return UFS_UNIPRO_VER_1_41;
842 else
843 return UFS_UNIPRO_VER_1_6;
845 EXPORT_SYMBOL(ufshcd_get_local_unipro_ver);
847 static bool ufshcd_is_unipro_pa_params_tuning_req(struct ufs_hba *hba)
850 * If both host and device support UniPro ver1.6 or later, PA layer
851 * parameters tuning happens during link startup itself.
853 * We can manually tune PA layer parameters if either host or device
854 * doesn't support UniPro ver 1.6 or later. But to keep manual tuning
855 * logic simple, we will only do manual tuning if local unipro version
856 * doesn't support ver1.6 or later.
858 if (ufshcd_get_local_unipro_ver(hba) < UFS_UNIPRO_VER_1_6)
859 return true;
860 else
861 return false;
864 static int ufshcd_scale_clks(struct ufs_hba *hba, bool scale_up)
866 int ret = 0;
867 struct ufs_clk_info *clki;
868 struct list_head *head = &hba->clk_list_head;
869 ktime_t start = ktime_get();
870 bool clk_state_changed = false;
872 if (list_empty(head))
873 goto out;
875 ret = ufshcd_vops_clk_scale_notify(hba, scale_up, PRE_CHANGE);
876 if (ret)
877 return ret;
879 list_for_each_entry(clki, head, list) {
880 if (!IS_ERR_OR_NULL(clki->clk)) {
881 if (scale_up && clki->max_freq) {
882 if (clki->curr_freq == clki->max_freq)
883 continue;
885 clk_state_changed = true;
886 ret = clk_set_rate(clki->clk, clki->max_freq);
887 if (ret) {
888 dev_err(hba->dev, "%s: %s clk set rate(%dHz) failed, %d\n",
889 __func__, clki->name,
890 clki->max_freq, ret);
891 break;
893 trace_ufshcd_clk_scaling(dev_name(hba->dev),
894 "scaled up", clki->name,
895 clki->curr_freq,
896 clki->max_freq);
898 clki->curr_freq = clki->max_freq;
900 } else if (!scale_up && clki->min_freq) {
901 if (clki->curr_freq == clki->min_freq)
902 continue;
904 clk_state_changed = true;
905 ret = clk_set_rate(clki->clk, clki->min_freq);
906 if (ret) {
907 dev_err(hba->dev, "%s: %s clk set rate(%dHz) failed, %d\n",
908 __func__, clki->name,
909 clki->min_freq, ret);
910 break;
912 trace_ufshcd_clk_scaling(dev_name(hba->dev),
913 "scaled down", clki->name,
914 clki->curr_freq,
915 clki->min_freq);
916 clki->curr_freq = clki->min_freq;
919 dev_dbg(hba->dev, "%s: clk: %s, rate: %lu\n", __func__,
920 clki->name, clk_get_rate(clki->clk));
923 ret = ufshcd_vops_clk_scale_notify(hba, scale_up, POST_CHANGE);
925 out:
926 if (clk_state_changed)
927 trace_ufshcd_profile_clk_scaling(dev_name(hba->dev),
928 (scale_up ? "up" : "down"),
929 ktime_to_us(ktime_sub(ktime_get(), start)), ret);
930 return ret;
934 * ufshcd_is_devfreq_scaling_required - check if scaling is required or not
935 * @hba: per adapter instance
936 * @scale_up: True if scaling up and false if scaling down
938 * Returns true if scaling is required, false otherwise.
940 static bool ufshcd_is_devfreq_scaling_required(struct ufs_hba *hba,
941 bool scale_up)
943 struct ufs_clk_info *clki;
944 struct list_head *head = &hba->clk_list_head;
946 if (list_empty(head))
947 return false;
949 list_for_each_entry(clki, head, list) {
950 if (!IS_ERR_OR_NULL(clki->clk)) {
951 if (scale_up && clki->max_freq) {
952 if (clki->curr_freq == clki->max_freq)
953 continue;
954 return true;
955 } else if (!scale_up && clki->min_freq) {
956 if (clki->curr_freq == clki->min_freq)
957 continue;
958 return true;
963 return false;
966 static int ufshcd_wait_for_doorbell_clr(struct ufs_hba *hba,
967 u64 wait_timeout_us)
969 unsigned long flags;
970 int ret = 0;
971 u32 tm_doorbell;
972 u32 tr_doorbell;
973 bool timeout = false, do_last_check = false;
974 ktime_t start;
976 ufshcd_hold(hba, false);
977 spin_lock_irqsave(hba->host->host_lock, flags);
979 * Wait for all the outstanding tasks/transfer requests.
980 * Verify by checking the doorbell registers are clear.
982 start = ktime_get();
983 do {
984 if (hba->ufshcd_state != UFSHCD_STATE_OPERATIONAL) {
985 ret = -EBUSY;
986 goto out;
989 tm_doorbell = ufshcd_readl(hba, REG_UTP_TASK_REQ_DOOR_BELL);
990 tr_doorbell = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
991 if (!tm_doorbell && !tr_doorbell) {
992 timeout = false;
993 break;
994 } else if (do_last_check) {
995 break;
998 spin_unlock_irqrestore(hba->host->host_lock, flags);
999 schedule();
1000 if (ktime_to_us(ktime_sub(ktime_get(), start)) >
1001 wait_timeout_us) {
1002 timeout = true;
1004 * We might have scheduled out for long time so make
1005 * sure to check if doorbells are cleared by this time
1006 * or not.
1008 do_last_check = true;
1010 spin_lock_irqsave(hba->host->host_lock, flags);
1011 } while (tm_doorbell || tr_doorbell);
1013 if (timeout) {
1014 dev_err(hba->dev,
1015 "%s: timedout waiting for doorbell to clear (tm=0x%x, tr=0x%x)\n",
1016 __func__, tm_doorbell, tr_doorbell);
1017 ret = -EBUSY;
1019 out:
1020 spin_unlock_irqrestore(hba->host->host_lock, flags);
1021 ufshcd_release(hba);
1022 return ret;
1026 * ufshcd_scale_gear - scale up/down UFS gear
1027 * @hba: per adapter instance
1028 * @scale_up: True for scaling up gear and false for scaling down
1030 * Returns 0 for success,
1031 * Returns -EBUSY if scaling can't happen at this time
1032 * Returns non-zero for any other errors
1034 static int ufshcd_scale_gear(struct ufs_hba *hba, bool scale_up)
1036 #define UFS_MIN_GEAR_TO_SCALE_DOWN UFS_HS_G1
1037 int ret = 0;
1038 struct ufs_pa_layer_attr new_pwr_info;
1040 if (scale_up) {
1041 memcpy(&new_pwr_info, &hba->clk_scaling.saved_pwr_info.info,
1042 sizeof(struct ufs_pa_layer_attr));
1043 } else {
1044 memcpy(&new_pwr_info, &hba->pwr_info,
1045 sizeof(struct ufs_pa_layer_attr));
1047 if (hba->pwr_info.gear_tx > UFS_MIN_GEAR_TO_SCALE_DOWN
1048 || hba->pwr_info.gear_rx > UFS_MIN_GEAR_TO_SCALE_DOWN) {
1049 /* save the current power mode */
1050 memcpy(&hba->clk_scaling.saved_pwr_info.info,
1051 &hba->pwr_info,
1052 sizeof(struct ufs_pa_layer_attr));
1054 /* scale down gear */
1055 new_pwr_info.gear_tx = UFS_MIN_GEAR_TO_SCALE_DOWN;
1056 new_pwr_info.gear_rx = UFS_MIN_GEAR_TO_SCALE_DOWN;
1060 /* check if the power mode needs to be changed or not? */
1061 ret = ufshcd_change_power_mode(hba, &new_pwr_info);
1063 if (ret)
1064 dev_err(hba->dev, "%s: failed err %d, old gear: (tx %d rx %d), new gear: (tx %d rx %d)",
1065 __func__, ret,
1066 hba->pwr_info.gear_tx, hba->pwr_info.gear_rx,
1067 new_pwr_info.gear_tx, new_pwr_info.gear_rx);
1069 return ret;
1072 static int ufshcd_clock_scaling_prepare(struct ufs_hba *hba)
1074 #define DOORBELL_CLR_TOUT_US (1000 * 1000) /* 1 sec */
1075 int ret = 0;
1077 * make sure that there are no outstanding requests when
1078 * clock scaling is in progress
1080 scsi_block_requests(hba->host);
1081 down_write(&hba->clk_scaling_lock);
1082 if (ufshcd_wait_for_doorbell_clr(hba, DOORBELL_CLR_TOUT_US)) {
1083 ret = -EBUSY;
1084 up_write(&hba->clk_scaling_lock);
1085 scsi_unblock_requests(hba->host);
1088 return ret;
1091 static void ufshcd_clock_scaling_unprepare(struct ufs_hba *hba)
1093 up_write(&hba->clk_scaling_lock);
1094 scsi_unblock_requests(hba->host);
1098 * ufshcd_devfreq_scale - scale up/down UFS clocks and gear
1099 * @hba: per adapter instance
1100 * @scale_up: True for scaling up and false for scalin down
1102 * Returns 0 for success,
1103 * Returns -EBUSY if scaling can't happen at this time
1104 * Returns non-zero for any other errors
1106 static int ufshcd_devfreq_scale(struct ufs_hba *hba, bool scale_up)
1108 int ret = 0;
1110 /* let's not get into low power until clock scaling is completed */
1111 ufshcd_hold(hba, false);
1113 ret = ufshcd_clock_scaling_prepare(hba);
1114 if (ret)
1115 return ret;
1117 /* scale down the gear before scaling down clocks */
1118 if (!scale_up) {
1119 ret = ufshcd_scale_gear(hba, false);
1120 if (ret)
1121 goto out;
1124 ret = ufshcd_scale_clks(hba, scale_up);
1125 if (ret) {
1126 if (!scale_up)
1127 ufshcd_scale_gear(hba, true);
1128 goto out;
1131 /* scale up the gear after scaling up clocks */
1132 if (scale_up) {
1133 ret = ufshcd_scale_gear(hba, true);
1134 if (ret) {
1135 ufshcd_scale_clks(hba, false);
1136 goto out;
1140 ret = ufshcd_vops_clk_scale_notify(hba, scale_up, POST_CHANGE);
1142 out:
1143 ufshcd_clock_scaling_unprepare(hba);
1144 ufshcd_release(hba);
1145 return ret;
1148 static void ufshcd_clk_scaling_suspend_work(struct work_struct *work)
1150 struct ufs_hba *hba = container_of(work, struct ufs_hba,
1151 clk_scaling.suspend_work);
1152 unsigned long irq_flags;
1154 spin_lock_irqsave(hba->host->host_lock, irq_flags);
1155 if (hba->clk_scaling.active_reqs || hba->clk_scaling.is_suspended) {
1156 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1157 return;
1159 hba->clk_scaling.is_suspended = true;
1160 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1162 __ufshcd_suspend_clkscaling(hba);
1165 static void ufshcd_clk_scaling_resume_work(struct work_struct *work)
1167 struct ufs_hba *hba = container_of(work, struct ufs_hba,
1168 clk_scaling.resume_work);
1169 unsigned long irq_flags;
1171 spin_lock_irqsave(hba->host->host_lock, irq_flags);
1172 if (!hba->clk_scaling.is_suspended) {
1173 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1174 return;
1176 hba->clk_scaling.is_suspended = false;
1177 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1179 devfreq_resume_device(hba->devfreq);
1182 static int ufshcd_devfreq_target(struct device *dev,
1183 unsigned long *freq, u32 flags)
1185 int ret = 0;
1186 struct ufs_hba *hba = dev_get_drvdata(dev);
1187 ktime_t start;
1188 bool scale_up, sched_clk_scaling_suspend_work = false;
1189 unsigned long irq_flags;
1191 if (!ufshcd_is_clkscaling_supported(hba))
1192 return -EINVAL;
1194 if ((*freq > 0) && (*freq < UINT_MAX)) {
1195 dev_err(hba->dev, "%s: invalid freq = %lu\n", __func__, *freq);
1196 return -EINVAL;
1199 spin_lock_irqsave(hba->host->host_lock, irq_flags);
1200 if (ufshcd_eh_in_progress(hba)) {
1201 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1202 return 0;
1205 if (!hba->clk_scaling.active_reqs)
1206 sched_clk_scaling_suspend_work = true;
1208 scale_up = (*freq == UINT_MAX) ? true : false;
1209 if (!ufshcd_is_devfreq_scaling_required(hba, scale_up)) {
1210 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1211 ret = 0;
1212 goto out; /* no state change required */
1214 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1216 start = ktime_get();
1217 ret = ufshcd_devfreq_scale(hba, scale_up);
1219 trace_ufshcd_profile_clk_scaling(dev_name(hba->dev),
1220 (scale_up ? "up" : "down"),
1221 ktime_to_us(ktime_sub(ktime_get(), start)), ret);
1223 out:
1224 if (sched_clk_scaling_suspend_work)
1225 queue_work(hba->clk_scaling.workq,
1226 &hba->clk_scaling.suspend_work);
1228 return ret;
1232 static int ufshcd_devfreq_get_dev_status(struct device *dev,
1233 struct devfreq_dev_status *stat)
1235 struct ufs_hba *hba = dev_get_drvdata(dev);
1236 struct ufs_clk_scaling *scaling = &hba->clk_scaling;
1237 unsigned long flags;
1239 if (!ufshcd_is_clkscaling_supported(hba))
1240 return -EINVAL;
1242 memset(stat, 0, sizeof(*stat));
1244 spin_lock_irqsave(hba->host->host_lock, flags);
1245 if (!scaling->window_start_t)
1246 goto start_window;
1248 if (scaling->is_busy_started)
1249 scaling->tot_busy_t += ktime_to_us(ktime_sub(ktime_get(),
1250 scaling->busy_start_t));
1252 stat->total_time = jiffies_to_usecs((long)jiffies -
1253 (long)scaling->window_start_t);
1254 stat->busy_time = scaling->tot_busy_t;
1255 start_window:
1256 scaling->window_start_t = jiffies;
1257 scaling->tot_busy_t = 0;
1259 if (hba->outstanding_reqs) {
1260 scaling->busy_start_t = ktime_get();
1261 scaling->is_busy_started = true;
1262 } else {
1263 scaling->busy_start_t = 0;
1264 scaling->is_busy_started = false;
1266 spin_unlock_irqrestore(hba->host->host_lock, flags);
1267 return 0;
1270 static struct devfreq_dev_profile ufs_devfreq_profile = {
1271 .polling_ms = 100,
1272 .target = ufshcd_devfreq_target,
1273 .get_dev_status = ufshcd_devfreq_get_dev_status,
1276 static void __ufshcd_suspend_clkscaling(struct ufs_hba *hba)
1278 unsigned long flags;
1280 devfreq_suspend_device(hba->devfreq);
1281 spin_lock_irqsave(hba->host->host_lock, flags);
1282 hba->clk_scaling.window_start_t = 0;
1283 spin_unlock_irqrestore(hba->host->host_lock, flags);
1286 static void ufshcd_suspend_clkscaling(struct ufs_hba *hba)
1288 unsigned long flags;
1289 bool suspend = false;
1291 if (!ufshcd_is_clkscaling_supported(hba))
1292 return;
1294 spin_lock_irqsave(hba->host->host_lock, flags);
1295 if (!hba->clk_scaling.is_suspended) {
1296 suspend = true;
1297 hba->clk_scaling.is_suspended = true;
1299 spin_unlock_irqrestore(hba->host->host_lock, flags);
1301 if (suspend)
1302 __ufshcd_suspend_clkscaling(hba);
1305 static void ufshcd_resume_clkscaling(struct ufs_hba *hba)
1307 unsigned long flags;
1308 bool resume = false;
1310 if (!ufshcd_is_clkscaling_supported(hba))
1311 return;
1313 spin_lock_irqsave(hba->host->host_lock, flags);
1314 if (hba->clk_scaling.is_suspended) {
1315 resume = true;
1316 hba->clk_scaling.is_suspended = false;
1318 spin_unlock_irqrestore(hba->host->host_lock, flags);
1320 if (resume)
1321 devfreq_resume_device(hba->devfreq);
1324 static ssize_t ufshcd_clkscale_enable_show(struct device *dev,
1325 struct device_attribute *attr, char *buf)
1327 struct ufs_hba *hba = dev_get_drvdata(dev);
1329 return snprintf(buf, PAGE_SIZE, "%d\n", hba->clk_scaling.is_allowed);
1332 static ssize_t ufshcd_clkscale_enable_store(struct device *dev,
1333 struct device_attribute *attr, const char *buf, size_t count)
1335 struct ufs_hba *hba = dev_get_drvdata(dev);
1336 u32 value;
1337 int err;
1339 if (kstrtou32(buf, 0, &value))
1340 return -EINVAL;
1342 value = !!value;
1343 if (value == hba->clk_scaling.is_allowed)
1344 goto out;
1346 pm_runtime_get_sync(hba->dev);
1347 ufshcd_hold(hba, false);
1349 cancel_work_sync(&hba->clk_scaling.suspend_work);
1350 cancel_work_sync(&hba->clk_scaling.resume_work);
1352 hba->clk_scaling.is_allowed = value;
1354 if (value) {
1355 ufshcd_resume_clkscaling(hba);
1356 } else {
1357 ufshcd_suspend_clkscaling(hba);
1358 err = ufshcd_devfreq_scale(hba, true);
1359 if (err)
1360 dev_err(hba->dev, "%s: failed to scale clocks up %d\n",
1361 __func__, err);
1364 ufshcd_release(hba);
1365 pm_runtime_put_sync(hba->dev);
1366 out:
1367 return count;
1370 static void ufshcd_clkscaling_init_sysfs(struct ufs_hba *hba)
1372 hba->clk_scaling.enable_attr.show = ufshcd_clkscale_enable_show;
1373 hba->clk_scaling.enable_attr.store = ufshcd_clkscale_enable_store;
1374 sysfs_attr_init(&hba->clk_scaling.enable_attr.attr);
1375 hba->clk_scaling.enable_attr.attr.name = "clkscale_enable";
1376 hba->clk_scaling.enable_attr.attr.mode = 0644;
1377 if (device_create_file(hba->dev, &hba->clk_scaling.enable_attr))
1378 dev_err(hba->dev, "Failed to create sysfs for clkscale_enable\n");
1381 static void ufshcd_ungate_work(struct work_struct *work)
1383 int ret;
1384 unsigned long flags;
1385 struct ufs_hba *hba = container_of(work, struct ufs_hba,
1386 clk_gating.ungate_work);
1388 cancel_delayed_work_sync(&hba->clk_gating.gate_work);
1390 spin_lock_irqsave(hba->host->host_lock, flags);
1391 if (hba->clk_gating.state == CLKS_ON) {
1392 spin_unlock_irqrestore(hba->host->host_lock, flags);
1393 goto unblock_reqs;
1396 spin_unlock_irqrestore(hba->host->host_lock, flags);
1397 ufshcd_setup_clocks(hba, true);
1399 /* Exit from hibern8 */
1400 if (ufshcd_can_hibern8_during_gating(hba)) {
1401 /* Prevent gating in this path */
1402 hba->clk_gating.is_suspended = true;
1403 if (ufshcd_is_link_hibern8(hba)) {
1404 ret = ufshcd_uic_hibern8_exit(hba);
1405 if (ret)
1406 dev_err(hba->dev, "%s: hibern8 exit failed %d\n",
1407 __func__, ret);
1408 else
1409 ufshcd_set_link_active(hba);
1411 hba->clk_gating.is_suspended = false;
1413 unblock_reqs:
1414 scsi_unblock_requests(hba->host);
1418 * ufshcd_hold - Enable clocks that were gated earlier due to ufshcd_release.
1419 * Also, exit from hibern8 mode and set the link as active.
1420 * @hba: per adapter instance
1421 * @async: This indicates whether caller should ungate clocks asynchronously.
1423 int ufshcd_hold(struct ufs_hba *hba, bool async)
1425 int rc = 0;
1426 unsigned long flags;
1428 if (!ufshcd_is_clkgating_allowed(hba))
1429 goto out;
1430 spin_lock_irqsave(hba->host->host_lock, flags);
1431 hba->clk_gating.active_reqs++;
1433 if (ufshcd_eh_in_progress(hba)) {
1434 spin_unlock_irqrestore(hba->host->host_lock, flags);
1435 return 0;
1438 start:
1439 switch (hba->clk_gating.state) {
1440 case CLKS_ON:
1442 * Wait for the ungate work to complete if in progress.
1443 * Though the clocks may be in ON state, the link could
1444 * still be in hibner8 state if hibern8 is allowed
1445 * during clock gating.
1446 * Make sure we exit hibern8 state also in addition to
1447 * clocks being ON.
1449 if (ufshcd_can_hibern8_during_gating(hba) &&
1450 ufshcd_is_link_hibern8(hba)) {
1451 spin_unlock_irqrestore(hba->host->host_lock, flags);
1452 flush_work(&hba->clk_gating.ungate_work);
1453 spin_lock_irqsave(hba->host->host_lock, flags);
1454 goto start;
1456 break;
1457 case REQ_CLKS_OFF:
1458 if (cancel_delayed_work(&hba->clk_gating.gate_work)) {
1459 hba->clk_gating.state = CLKS_ON;
1460 trace_ufshcd_clk_gating(dev_name(hba->dev),
1461 hba->clk_gating.state);
1462 break;
1465 * If we are here, it means gating work is either done or
1466 * currently running. Hence, fall through to cancel gating
1467 * work and to enable clocks.
1469 case CLKS_OFF:
1470 scsi_block_requests(hba->host);
1471 hba->clk_gating.state = REQ_CLKS_ON;
1472 trace_ufshcd_clk_gating(dev_name(hba->dev),
1473 hba->clk_gating.state);
1474 schedule_work(&hba->clk_gating.ungate_work);
1476 * fall through to check if we should wait for this
1477 * work to be done or not.
1479 case REQ_CLKS_ON:
1480 if (async) {
1481 rc = -EAGAIN;
1482 hba->clk_gating.active_reqs--;
1483 break;
1486 spin_unlock_irqrestore(hba->host->host_lock, flags);
1487 flush_work(&hba->clk_gating.ungate_work);
1488 /* Make sure state is CLKS_ON before returning */
1489 spin_lock_irqsave(hba->host->host_lock, flags);
1490 goto start;
1491 default:
1492 dev_err(hba->dev, "%s: clk gating is in invalid state %d\n",
1493 __func__, hba->clk_gating.state);
1494 break;
1496 spin_unlock_irqrestore(hba->host->host_lock, flags);
1497 out:
1498 return rc;
1500 EXPORT_SYMBOL_GPL(ufshcd_hold);
1502 static void ufshcd_gate_work(struct work_struct *work)
1504 struct ufs_hba *hba = container_of(work, struct ufs_hba,
1505 clk_gating.gate_work.work);
1506 unsigned long flags;
1508 spin_lock_irqsave(hba->host->host_lock, flags);
1510 * In case you are here to cancel this work the gating state
1511 * would be marked as REQ_CLKS_ON. In this case save time by
1512 * skipping the gating work and exit after changing the clock
1513 * state to CLKS_ON.
1515 if (hba->clk_gating.is_suspended ||
1516 (hba->clk_gating.state == REQ_CLKS_ON)) {
1517 hba->clk_gating.state = CLKS_ON;
1518 trace_ufshcd_clk_gating(dev_name(hba->dev),
1519 hba->clk_gating.state);
1520 goto rel_lock;
1523 if (hba->clk_gating.active_reqs
1524 || hba->ufshcd_state != UFSHCD_STATE_OPERATIONAL
1525 || hba->lrb_in_use || hba->outstanding_tasks
1526 || hba->active_uic_cmd || hba->uic_async_done)
1527 goto rel_lock;
1529 spin_unlock_irqrestore(hba->host->host_lock, flags);
1531 /* put the link into hibern8 mode before turning off clocks */
1532 if (ufshcd_can_hibern8_during_gating(hba)) {
1533 if (ufshcd_uic_hibern8_enter(hba)) {
1534 hba->clk_gating.state = CLKS_ON;
1535 trace_ufshcd_clk_gating(dev_name(hba->dev),
1536 hba->clk_gating.state);
1537 goto out;
1539 ufshcd_set_link_hibern8(hba);
1542 if (!ufshcd_is_link_active(hba))
1543 ufshcd_setup_clocks(hba, false);
1544 else
1545 /* If link is active, device ref_clk can't be switched off */
1546 __ufshcd_setup_clocks(hba, false, true);
1549 * In case you are here to cancel this work the gating state
1550 * would be marked as REQ_CLKS_ON. In this case keep the state
1551 * as REQ_CLKS_ON which would anyway imply that clocks are off
1552 * and a request to turn them on is pending. By doing this way,
1553 * we keep the state machine in tact and this would ultimately
1554 * prevent from doing cancel work multiple times when there are
1555 * new requests arriving before the current cancel work is done.
1557 spin_lock_irqsave(hba->host->host_lock, flags);
1558 if (hba->clk_gating.state == REQ_CLKS_OFF) {
1559 hba->clk_gating.state = CLKS_OFF;
1560 trace_ufshcd_clk_gating(dev_name(hba->dev),
1561 hba->clk_gating.state);
1563 rel_lock:
1564 spin_unlock_irqrestore(hba->host->host_lock, flags);
1565 out:
1566 return;
1569 /* host lock must be held before calling this variant */
1570 static void __ufshcd_release(struct ufs_hba *hba)
1572 if (!ufshcd_is_clkgating_allowed(hba))
1573 return;
1575 hba->clk_gating.active_reqs--;
1577 if (hba->clk_gating.active_reqs || hba->clk_gating.is_suspended
1578 || hba->ufshcd_state != UFSHCD_STATE_OPERATIONAL
1579 || hba->lrb_in_use || hba->outstanding_tasks
1580 || hba->active_uic_cmd || hba->uic_async_done
1581 || ufshcd_eh_in_progress(hba))
1582 return;
1584 hba->clk_gating.state = REQ_CLKS_OFF;
1585 trace_ufshcd_clk_gating(dev_name(hba->dev), hba->clk_gating.state);
1586 schedule_delayed_work(&hba->clk_gating.gate_work,
1587 msecs_to_jiffies(hba->clk_gating.delay_ms));
1590 void ufshcd_release(struct ufs_hba *hba)
1592 unsigned long flags;
1594 spin_lock_irqsave(hba->host->host_lock, flags);
1595 __ufshcd_release(hba);
1596 spin_unlock_irqrestore(hba->host->host_lock, flags);
1598 EXPORT_SYMBOL_GPL(ufshcd_release);
1600 static ssize_t ufshcd_clkgate_delay_show(struct device *dev,
1601 struct device_attribute *attr, char *buf)
1603 struct ufs_hba *hba = dev_get_drvdata(dev);
1605 return snprintf(buf, PAGE_SIZE, "%lu\n", hba->clk_gating.delay_ms);
1608 static ssize_t ufshcd_clkgate_delay_store(struct device *dev,
1609 struct device_attribute *attr, const char *buf, size_t count)
1611 struct ufs_hba *hba = dev_get_drvdata(dev);
1612 unsigned long flags, value;
1614 if (kstrtoul(buf, 0, &value))
1615 return -EINVAL;
1617 spin_lock_irqsave(hba->host->host_lock, flags);
1618 hba->clk_gating.delay_ms = value;
1619 spin_unlock_irqrestore(hba->host->host_lock, flags);
1620 return count;
1623 static ssize_t ufshcd_clkgate_enable_show(struct device *dev,
1624 struct device_attribute *attr, char *buf)
1626 struct ufs_hba *hba = dev_get_drvdata(dev);
1628 return snprintf(buf, PAGE_SIZE, "%d\n", hba->clk_gating.is_enabled);
1631 static ssize_t ufshcd_clkgate_enable_store(struct device *dev,
1632 struct device_attribute *attr, const char *buf, size_t count)
1634 struct ufs_hba *hba = dev_get_drvdata(dev);
1635 unsigned long flags;
1636 u32 value;
1638 if (kstrtou32(buf, 0, &value))
1639 return -EINVAL;
1641 value = !!value;
1642 if (value == hba->clk_gating.is_enabled)
1643 goto out;
1645 if (value) {
1646 ufshcd_release(hba);
1647 } else {
1648 spin_lock_irqsave(hba->host->host_lock, flags);
1649 hba->clk_gating.active_reqs++;
1650 spin_unlock_irqrestore(hba->host->host_lock, flags);
1653 hba->clk_gating.is_enabled = value;
1654 out:
1655 return count;
1658 static void ufshcd_init_clk_gating(struct ufs_hba *hba)
1660 if (!ufshcd_is_clkgating_allowed(hba))
1661 return;
1663 hba->clk_gating.delay_ms = 150;
1664 INIT_DELAYED_WORK(&hba->clk_gating.gate_work, ufshcd_gate_work);
1665 INIT_WORK(&hba->clk_gating.ungate_work, ufshcd_ungate_work);
1667 hba->clk_gating.is_enabled = true;
1669 hba->clk_gating.delay_attr.show = ufshcd_clkgate_delay_show;
1670 hba->clk_gating.delay_attr.store = ufshcd_clkgate_delay_store;
1671 sysfs_attr_init(&hba->clk_gating.delay_attr.attr);
1672 hba->clk_gating.delay_attr.attr.name = "clkgate_delay_ms";
1673 hba->clk_gating.delay_attr.attr.mode = 0644;
1674 if (device_create_file(hba->dev, &hba->clk_gating.delay_attr))
1675 dev_err(hba->dev, "Failed to create sysfs for clkgate_delay\n");
1677 hba->clk_gating.enable_attr.show = ufshcd_clkgate_enable_show;
1678 hba->clk_gating.enable_attr.store = ufshcd_clkgate_enable_store;
1679 sysfs_attr_init(&hba->clk_gating.enable_attr.attr);
1680 hba->clk_gating.enable_attr.attr.name = "clkgate_enable";
1681 hba->clk_gating.enable_attr.attr.mode = 0644;
1682 if (device_create_file(hba->dev, &hba->clk_gating.enable_attr))
1683 dev_err(hba->dev, "Failed to create sysfs for clkgate_enable\n");
1686 static void ufshcd_exit_clk_gating(struct ufs_hba *hba)
1688 if (!ufshcd_is_clkgating_allowed(hba))
1689 return;
1690 device_remove_file(hba->dev, &hba->clk_gating.delay_attr);
1691 device_remove_file(hba->dev, &hba->clk_gating.enable_attr);
1692 cancel_work_sync(&hba->clk_gating.ungate_work);
1693 cancel_delayed_work_sync(&hba->clk_gating.gate_work);
1696 /* Must be called with host lock acquired */
1697 static void ufshcd_clk_scaling_start_busy(struct ufs_hba *hba)
1699 bool queue_resume_work = false;
1701 if (!ufshcd_is_clkscaling_supported(hba))
1702 return;
1704 if (!hba->clk_scaling.active_reqs++)
1705 queue_resume_work = true;
1707 if (!hba->clk_scaling.is_allowed || hba->pm_op_in_progress)
1708 return;
1710 if (queue_resume_work)
1711 queue_work(hba->clk_scaling.workq,
1712 &hba->clk_scaling.resume_work);
1714 if (!hba->clk_scaling.window_start_t) {
1715 hba->clk_scaling.window_start_t = jiffies;
1716 hba->clk_scaling.tot_busy_t = 0;
1717 hba->clk_scaling.is_busy_started = false;
1720 if (!hba->clk_scaling.is_busy_started) {
1721 hba->clk_scaling.busy_start_t = ktime_get();
1722 hba->clk_scaling.is_busy_started = true;
1726 static void ufshcd_clk_scaling_update_busy(struct ufs_hba *hba)
1728 struct ufs_clk_scaling *scaling = &hba->clk_scaling;
1730 if (!ufshcd_is_clkscaling_supported(hba))
1731 return;
1733 if (!hba->outstanding_reqs && scaling->is_busy_started) {
1734 scaling->tot_busy_t += ktime_to_us(ktime_sub(ktime_get(),
1735 scaling->busy_start_t));
1736 scaling->busy_start_t = 0;
1737 scaling->is_busy_started = false;
1741 * ufshcd_send_command - Send SCSI or device management commands
1742 * @hba: per adapter instance
1743 * @task_tag: Task tag of the command
1745 static inline
1746 void ufshcd_send_command(struct ufs_hba *hba, unsigned int task_tag)
1748 hba->lrb[task_tag].issue_time_stamp = ktime_get();
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 */
1753 wmb();
1754 ufshcd_add_command_trace(hba, task_tag, "send");
1758 * ufshcd_copy_sense_data - Copy sense data in case of check condition
1759 * @lrb - pointer to local reference block
1761 static inline void ufshcd_copy_sense_data(struct ufshcd_lrb *lrbp)
1763 int len;
1764 if (lrbp->sense_buffer &&
1765 ufshcd_get_rsp_upiu_data_seg_len(lrbp->ucd_rsp_ptr)) {
1766 int len_to_copy;
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
1779 * descriptor
1780 * @hba: per adapter instance
1781 * @lrb - pointer to local reference block
1783 static
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;
1794 u16 resp_len;
1795 u16 buf_len;
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);
1804 } else {
1805 dev_warn(hba->dev,
1806 "%s: Response size is bigger than buffer",
1807 __func__);
1808 return -EINVAL;
1812 return 0;
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;
1825 hba->nutmrs =
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)
1838 return true;
1839 else
1840 return false;
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.
1862 static inline void
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;
1869 /* Write Args */
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);
1874 /* Write UIC Cmd */
1875 ufshcd_writel(hba, uic_cmd->command & COMMAND_OPCODE_MASK,
1876 REG_UIC_COMMAND);
1880 * ufshcd_wait_for_uic_cmd - Wait complectioin of UIC command
1881 * @hba: per adapter instance
1882 * @uic_command: UIC command
1884 * Must be called with mutex held.
1885 * Returns 0 only if success.
1887 static int
1888 ufshcd_wait_for_uic_cmd(struct ufs_hba *hba, struct uic_command *uic_cmd)
1890 int ret;
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;
1896 else
1897 ret = -ETIMEDOUT;
1899 spin_lock_irqsave(hba->host->host_lock, flags);
1900 hba->active_uic_cmd = NULL;
1901 spin_unlock_irqrestore(hba->host->host_lock, flags);
1903 return ret;
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.
1916 static int
1917 __ufshcd_send_uic_cmd(struct ufs_hba *hba, struct uic_command *uic_cmd,
1918 bool completion)
1920 if (!ufshcd_ready_for_uic_cmd(hba)) {
1921 dev_err(hba->dev,
1922 "Controller not ready to accept UIC commands\n");
1923 return -EIO;
1926 if (completion)
1927 init_completion(&uic_cmd->done);
1929 ufshcd_dispatch_uic_cmd(hba, uic_cmd);
1931 return 0;
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.
1941 static int
1942 ufshcd_send_uic_cmd(struct ufs_hba *hba, struct uic_command *uic_cmd)
1944 int ret;
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);
1954 if (!ret)
1955 ret = ufshcd_wait_for_uic_cmd(hba, uic_cmd);
1957 mutex_unlock(&hba->uic_cmd_mutex);
1959 ufshcd_release(hba);
1960 return ret;
1964 * ufshcd_map_sg - Map scatter-gather list to prdt
1965 * @lrbp - pointer to local reference block
1967 * Returns 0 in case of success, non-zero value in case of failure
1969 static int ufshcd_map_sg(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
1971 struct ufshcd_sg_entry *prd_table;
1972 struct scatterlist *sg;
1973 struct scsi_cmnd *cmd;
1974 int sg_segments;
1975 int i;
1977 cmd = lrbp->cmd;
1978 sg_segments = scsi_dma_map(cmd);
1979 if (sg_segments < 0)
1980 return sg_segments;
1982 if (sg_segments) {
1983 if (hba->quirks & UFSHCD_QUIRK_PRDT_BYTE_GRAN)
1984 lrbp->utr_descriptor_ptr->prd_table_length =
1985 cpu_to_le16((u16)(sg_segments *
1986 sizeof(struct ufshcd_sg_entry)));
1987 else
1988 lrbp->utr_descriptor_ptr->prd_table_length =
1989 cpu_to_le16((u16) (sg_segments));
1991 prd_table = (struct ufshcd_sg_entry *)lrbp->ucd_prdt_ptr;
1993 scsi_for_each_sg(cmd, sg, sg_segments, i) {
1994 prd_table[i].size =
1995 cpu_to_le32(((u32) sg_dma_len(sg))-1);
1996 prd_table[i].base_addr =
1997 cpu_to_le32(lower_32_bits(sg->dma_address));
1998 prd_table[i].upper_addr =
1999 cpu_to_le32(upper_32_bits(sg->dma_address));
2000 prd_table[i].reserved = 0;
2002 } else {
2003 lrbp->utr_descriptor_ptr->prd_table_length = 0;
2006 return 0;
2010 * ufshcd_enable_intr - enable interrupts
2011 * @hba: per adapter instance
2012 * @intrs: interrupt bits
2014 static void ufshcd_enable_intr(struct ufs_hba *hba, u32 intrs)
2016 u32 set = ufshcd_readl(hba, REG_INTERRUPT_ENABLE);
2018 if (hba->ufs_version == UFSHCI_VERSION_10) {
2019 u32 rw;
2020 rw = set & INTERRUPT_MASK_RW_VER_10;
2021 set = rw | ((set ^ intrs) & intrs);
2022 } else {
2023 set |= intrs;
2026 ufshcd_writel(hba, set, REG_INTERRUPT_ENABLE);
2030 * ufshcd_disable_intr - disable interrupts
2031 * @hba: per adapter instance
2032 * @intrs: interrupt bits
2034 static void ufshcd_disable_intr(struct ufs_hba *hba, u32 intrs)
2036 u32 set = ufshcd_readl(hba, REG_INTERRUPT_ENABLE);
2038 if (hba->ufs_version == UFSHCI_VERSION_10) {
2039 u32 rw;
2040 rw = (set & INTERRUPT_MASK_RW_VER_10) &
2041 ~(intrs & INTERRUPT_MASK_RW_VER_10);
2042 set = rw | ((set & intrs) & ~INTERRUPT_MASK_RW_VER_10);
2044 } else {
2045 set &= ~intrs;
2048 ufshcd_writel(hba, set, REG_INTERRUPT_ENABLE);
2052 * ufshcd_prepare_req_desc_hdr() - Fills the requests header
2053 * descriptor according to request
2054 * @lrbp: pointer to local reference block
2055 * @upiu_flags: flags required in the header
2056 * @cmd_dir: requests data direction
2058 static void ufshcd_prepare_req_desc_hdr(struct ufshcd_lrb *lrbp,
2059 u32 *upiu_flags, enum dma_data_direction cmd_dir)
2061 struct utp_transfer_req_desc *req_desc = lrbp->utr_descriptor_ptr;
2062 u32 data_direction;
2063 u32 dword_0;
2065 if (cmd_dir == DMA_FROM_DEVICE) {
2066 data_direction = UTP_DEVICE_TO_HOST;
2067 *upiu_flags = UPIU_CMD_FLAGS_READ;
2068 } else if (cmd_dir == DMA_TO_DEVICE) {
2069 data_direction = UTP_HOST_TO_DEVICE;
2070 *upiu_flags = UPIU_CMD_FLAGS_WRITE;
2071 } else {
2072 data_direction = UTP_NO_DATA_TRANSFER;
2073 *upiu_flags = UPIU_CMD_FLAGS_NONE;
2076 dword_0 = data_direction | (lrbp->command_type
2077 << UPIU_COMMAND_TYPE_OFFSET);
2078 if (lrbp->intr_cmd)
2079 dword_0 |= UTP_REQ_DESC_INT_CMD;
2081 /* Transfer request descriptor header fields */
2082 req_desc->header.dword_0 = cpu_to_le32(dword_0);
2083 /* dword_1 is reserved, hence it is set to 0 */
2084 req_desc->header.dword_1 = 0;
2086 * assigning invalid value for command status. Controller
2087 * updates OCS on command completion, with the command
2088 * status
2090 req_desc->header.dword_2 =
2091 cpu_to_le32(OCS_INVALID_COMMAND_STATUS);
2092 /* dword_3 is reserved, hence it is set to 0 */
2093 req_desc->header.dword_3 = 0;
2095 req_desc->prd_table_length = 0;
2099 * ufshcd_prepare_utp_scsi_cmd_upiu() - fills the utp_transfer_req_desc,
2100 * for scsi commands
2101 * @lrbp - local reference block pointer
2102 * @upiu_flags - flags
2104 static
2105 void ufshcd_prepare_utp_scsi_cmd_upiu(struct ufshcd_lrb *lrbp, u32 upiu_flags)
2107 struct utp_upiu_req *ucd_req_ptr = lrbp->ucd_req_ptr;
2108 unsigned short cdb_len;
2110 /* command descriptor fields */
2111 ucd_req_ptr->header.dword_0 = UPIU_HEADER_DWORD(
2112 UPIU_TRANSACTION_COMMAND, upiu_flags,
2113 lrbp->lun, lrbp->task_tag);
2114 ucd_req_ptr->header.dword_1 = UPIU_HEADER_DWORD(
2115 UPIU_COMMAND_SET_TYPE_SCSI, 0, 0, 0);
2117 /* Total EHS length and Data segment length will be zero */
2118 ucd_req_ptr->header.dword_2 = 0;
2120 ucd_req_ptr->sc.exp_data_transfer_len =
2121 cpu_to_be32(lrbp->cmd->sdb.length);
2123 cdb_len = min_t(unsigned short, lrbp->cmd->cmd_len, MAX_CDB_SIZE);
2124 memset(ucd_req_ptr->sc.cdb, 0, MAX_CDB_SIZE);
2125 memcpy(ucd_req_ptr->sc.cdb, lrbp->cmd->cmnd, cdb_len);
2127 memset(lrbp->ucd_rsp_ptr, 0, sizeof(struct utp_upiu_rsp));
2131 * ufshcd_prepare_utp_query_req_upiu() - fills the utp_transfer_req_desc,
2132 * for query requsts
2133 * @hba: UFS hba
2134 * @lrbp: local reference block pointer
2135 * @upiu_flags: flags
2137 static void ufshcd_prepare_utp_query_req_upiu(struct ufs_hba *hba,
2138 struct ufshcd_lrb *lrbp, u32 upiu_flags)
2140 struct utp_upiu_req *ucd_req_ptr = lrbp->ucd_req_ptr;
2141 struct ufs_query *query = &hba->dev_cmd.query;
2142 u16 len = be16_to_cpu(query->request.upiu_req.length);
2143 u8 *descp = (u8 *)lrbp->ucd_req_ptr + GENERAL_UPIU_REQUEST_SIZE;
2145 /* Query request header */
2146 ucd_req_ptr->header.dword_0 = UPIU_HEADER_DWORD(
2147 UPIU_TRANSACTION_QUERY_REQ, upiu_flags,
2148 lrbp->lun, lrbp->task_tag);
2149 ucd_req_ptr->header.dword_1 = UPIU_HEADER_DWORD(
2150 0, query->request.query_func, 0, 0);
2152 /* Data segment length only need for WRITE_DESC */
2153 if (query->request.upiu_req.opcode == UPIU_QUERY_OPCODE_WRITE_DESC)
2154 ucd_req_ptr->header.dword_2 =
2155 UPIU_HEADER_DWORD(0, 0, (len >> 8), (u8)len);
2156 else
2157 ucd_req_ptr->header.dword_2 = 0;
2159 /* Copy the Query Request buffer as is */
2160 memcpy(&ucd_req_ptr->qr, &query->request.upiu_req,
2161 QUERY_OSF_SIZE);
2163 /* Copy the Descriptor */
2164 if (query->request.upiu_req.opcode == UPIU_QUERY_OPCODE_WRITE_DESC)
2165 memcpy(descp, query->descriptor, len);
2167 memset(lrbp->ucd_rsp_ptr, 0, sizeof(struct utp_upiu_rsp));
2170 static inline void ufshcd_prepare_utp_nop_upiu(struct ufshcd_lrb *lrbp)
2172 struct utp_upiu_req *ucd_req_ptr = lrbp->ucd_req_ptr;
2174 memset(ucd_req_ptr, 0, sizeof(struct utp_upiu_req));
2176 /* command descriptor fields */
2177 ucd_req_ptr->header.dword_0 =
2178 UPIU_HEADER_DWORD(
2179 UPIU_TRANSACTION_NOP_OUT, 0, 0, lrbp->task_tag);
2180 /* clear rest of the fields of basic header */
2181 ucd_req_ptr->header.dword_1 = 0;
2182 ucd_req_ptr->header.dword_2 = 0;
2184 memset(lrbp->ucd_rsp_ptr, 0, sizeof(struct utp_upiu_rsp));
2188 * ufshcd_comp_devman_upiu - UFS Protocol Information Unit(UPIU)
2189 * for Device Management Purposes
2190 * @hba - per adapter instance
2191 * @lrb - pointer to local reference block
2193 static int ufshcd_comp_devman_upiu(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
2195 u32 upiu_flags;
2196 int ret = 0;
2198 if (hba->ufs_version == UFSHCI_VERSION_20)
2199 lrbp->command_type = UTP_CMD_TYPE_UFS_STORAGE;
2200 else
2201 lrbp->command_type = UTP_CMD_TYPE_DEV_MANAGE;
2203 ufshcd_prepare_req_desc_hdr(lrbp, &upiu_flags, DMA_NONE);
2204 if (hba->dev_cmd.type == DEV_CMD_TYPE_QUERY)
2205 ufshcd_prepare_utp_query_req_upiu(hba, lrbp, upiu_flags);
2206 else if (hba->dev_cmd.type == DEV_CMD_TYPE_NOP)
2207 ufshcd_prepare_utp_nop_upiu(lrbp);
2208 else
2209 ret = -EINVAL;
2211 return ret;
2215 * ufshcd_comp_scsi_upiu - UFS Protocol Information Unit(UPIU)
2216 * for SCSI Purposes
2217 * @hba - per adapter instance
2218 * @lrb - pointer to local reference block
2220 static int ufshcd_comp_scsi_upiu(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
2222 u32 upiu_flags;
2223 int ret = 0;
2225 if (hba->ufs_version == UFSHCI_VERSION_20)
2226 lrbp->command_type = UTP_CMD_TYPE_UFS_STORAGE;
2227 else
2228 lrbp->command_type = UTP_CMD_TYPE_SCSI;
2230 if (likely(lrbp->cmd)) {
2231 ufshcd_prepare_req_desc_hdr(lrbp, &upiu_flags,
2232 lrbp->cmd->sc_data_direction);
2233 ufshcd_prepare_utp_scsi_cmd_upiu(lrbp, upiu_flags);
2234 } else {
2235 ret = -EINVAL;
2238 return ret;
2242 * ufshcd_scsi_to_upiu_lun - maps scsi LUN to UPIU LUN
2243 * @scsi_lun: scsi LUN id
2245 * Returns UPIU LUN id
2247 static inline u8 ufshcd_scsi_to_upiu_lun(unsigned int scsi_lun)
2249 if (scsi_is_wlun(scsi_lun))
2250 return (scsi_lun & UFS_UPIU_MAX_UNIT_NUM_ID)
2251 | UFS_UPIU_WLUN_ID;
2252 else
2253 return scsi_lun & UFS_UPIU_MAX_UNIT_NUM_ID;
2257 * ufshcd_upiu_wlun_to_scsi_wlun - maps UPIU W-LUN id to SCSI W-LUN ID
2258 * @scsi_lun: UPIU W-LUN id
2260 * Returns SCSI W-LUN id
2262 static inline u16 ufshcd_upiu_wlun_to_scsi_wlun(u8 upiu_wlun_id)
2264 return (upiu_wlun_id & ~UFS_UPIU_WLUN_ID) | SCSI_W_LUN_BASE;
2268 * ufshcd_queuecommand - main entry point for SCSI requests
2269 * @cmd: command from SCSI Midlayer
2270 * @done: call back function
2272 * Returns 0 for success, non-zero in case of failure
2274 static int ufshcd_queuecommand(struct Scsi_Host *host, struct scsi_cmnd *cmd)
2276 struct ufshcd_lrb *lrbp;
2277 struct ufs_hba *hba;
2278 unsigned long flags;
2279 int tag;
2280 int err = 0;
2282 hba = shost_priv(host);
2284 tag = cmd->request->tag;
2285 if (!ufshcd_valid_tag(hba, tag)) {
2286 dev_err(hba->dev,
2287 "%s: invalid command tag %d: cmd=0x%p, cmd->request=0x%p",
2288 __func__, tag, cmd, cmd->request);
2289 BUG();
2292 if (!down_read_trylock(&hba->clk_scaling_lock))
2293 return SCSI_MLQUEUE_HOST_BUSY;
2295 spin_lock_irqsave(hba->host->host_lock, flags);
2296 switch (hba->ufshcd_state) {
2297 case UFSHCD_STATE_OPERATIONAL:
2298 break;
2299 case UFSHCD_STATE_EH_SCHEDULED:
2300 case UFSHCD_STATE_RESET:
2301 err = SCSI_MLQUEUE_HOST_BUSY;
2302 goto out_unlock;
2303 case UFSHCD_STATE_ERROR:
2304 set_host_byte(cmd, DID_ERROR);
2305 cmd->scsi_done(cmd);
2306 goto out_unlock;
2307 default:
2308 dev_WARN_ONCE(hba->dev, 1, "%s: invalid state %d\n",
2309 __func__, hba->ufshcd_state);
2310 set_host_byte(cmd, DID_BAD_TARGET);
2311 cmd->scsi_done(cmd);
2312 goto out_unlock;
2315 /* if error handling is in progress, don't issue commands */
2316 if (ufshcd_eh_in_progress(hba)) {
2317 set_host_byte(cmd, DID_ERROR);
2318 cmd->scsi_done(cmd);
2319 goto out_unlock;
2321 spin_unlock_irqrestore(hba->host->host_lock, flags);
2323 hba->req_abort_count = 0;
2325 /* acquire the tag to make sure device cmds don't use it */
2326 if (test_and_set_bit_lock(tag, &hba->lrb_in_use)) {
2328 * Dev manage command in progress, requeue the command.
2329 * Requeuing the command helps in cases where the request *may*
2330 * find different tag instead of waiting for dev manage command
2331 * completion.
2333 err = SCSI_MLQUEUE_HOST_BUSY;
2334 goto out;
2337 err = ufshcd_hold(hba, true);
2338 if (err) {
2339 err = SCSI_MLQUEUE_HOST_BUSY;
2340 clear_bit_unlock(tag, &hba->lrb_in_use);
2341 goto out;
2343 WARN_ON(hba->clk_gating.state != CLKS_ON);
2345 lrbp = &hba->lrb[tag];
2347 WARN_ON(lrbp->cmd);
2348 lrbp->cmd = cmd;
2349 lrbp->sense_bufflen = UFSHCD_REQ_SENSE_SIZE;
2350 lrbp->sense_buffer = cmd->sense_buffer;
2351 lrbp->task_tag = tag;
2352 lrbp->lun = ufshcd_scsi_to_upiu_lun(cmd->device->lun);
2353 lrbp->intr_cmd = !ufshcd_is_intr_aggr_allowed(hba) ? true : false;
2354 lrbp->req_abort_skip = false;
2356 ufshcd_comp_scsi_upiu(hba, lrbp);
2358 err = ufshcd_map_sg(hba, lrbp);
2359 if (err) {
2360 lrbp->cmd = NULL;
2361 clear_bit_unlock(tag, &hba->lrb_in_use);
2362 goto out;
2364 /* Make sure descriptors are ready before ringing the doorbell */
2365 wmb();
2367 /* issue command to the controller */
2368 spin_lock_irqsave(hba->host->host_lock, flags);
2369 ufshcd_vops_setup_xfer_req(hba, tag, (lrbp->cmd ? true : false));
2370 ufshcd_send_command(hba, tag);
2371 out_unlock:
2372 spin_unlock_irqrestore(hba->host->host_lock, flags);
2373 out:
2374 up_read(&hba->clk_scaling_lock);
2375 return err;
2378 static int ufshcd_compose_dev_cmd(struct ufs_hba *hba,
2379 struct ufshcd_lrb *lrbp, enum dev_cmd_type cmd_type, int tag)
2381 lrbp->cmd = NULL;
2382 lrbp->sense_bufflen = 0;
2383 lrbp->sense_buffer = NULL;
2384 lrbp->task_tag = tag;
2385 lrbp->lun = 0; /* device management cmd is not specific to any LUN */
2386 lrbp->intr_cmd = true; /* No interrupt aggregation */
2387 hba->dev_cmd.type = cmd_type;
2389 return ufshcd_comp_devman_upiu(hba, lrbp);
2392 static int
2393 ufshcd_clear_cmd(struct ufs_hba *hba, int tag)
2395 int err = 0;
2396 unsigned long flags;
2397 u32 mask = 1 << tag;
2399 /* clear outstanding transaction before retry */
2400 spin_lock_irqsave(hba->host->host_lock, flags);
2401 ufshcd_utrl_clear(hba, tag);
2402 spin_unlock_irqrestore(hba->host->host_lock, flags);
2405 * wait for for h/w to clear corresponding bit in door-bell.
2406 * max. wait is 1 sec.
2408 err = ufshcd_wait_for_register(hba,
2409 REG_UTP_TRANSFER_REQ_DOOR_BELL,
2410 mask, ~mask, 1000, 1000, true);
2412 return err;
2415 static int
2416 ufshcd_check_query_response(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
2418 struct ufs_query_res *query_res = &hba->dev_cmd.query.response;
2420 /* Get the UPIU response */
2421 query_res->response = ufshcd_get_rsp_upiu_result(lrbp->ucd_rsp_ptr) >>
2422 UPIU_RSP_CODE_OFFSET;
2423 return query_res->response;
2427 * ufshcd_dev_cmd_completion() - handles device management command responses
2428 * @hba: per adapter instance
2429 * @lrbp: pointer to local reference block
2431 static int
2432 ufshcd_dev_cmd_completion(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
2434 int resp;
2435 int err = 0;
2437 hba->ufs_stats.last_hibern8_exit_tstamp = ktime_set(0, 0);
2438 resp = ufshcd_get_req_rsp(lrbp->ucd_rsp_ptr);
2440 switch (resp) {
2441 case UPIU_TRANSACTION_NOP_IN:
2442 if (hba->dev_cmd.type != DEV_CMD_TYPE_NOP) {
2443 err = -EINVAL;
2444 dev_err(hba->dev, "%s: unexpected response %x\n",
2445 __func__, resp);
2447 break;
2448 case UPIU_TRANSACTION_QUERY_RSP:
2449 err = ufshcd_check_query_response(hba, lrbp);
2450 if (!err)
2451 err = ufshcd_copy_query_response(hba, lrbp);
2452 break;
2453 case UPIU_TRANSACTION_REJECT_UPIU:
2454 /* TODO: handle Reject UPIU Response */
2455 err = -EPERM;
2456 dev_err(hba->dev, "%s: Reject UPIU not fully implemented\n",
2457 __func__);
2458 break;
2459 default:
2460 err = -EINVAL;
2461 dev_err(hba->dev, "%s: Invalid device management cmd response: %x\n",
2462 __func__, resp);
2463 break;
2466 return err;
2469 static int ufshcd_wait_for_dev_cmd(struct ufs_hba *hba,
2470 struct ufshcd_lrb *lrbp, int max_timeout)
2472 int err = 0;
2473 unsigned long time_left;
2474 unsigned long flags;
2476 time_left = wait_for_completion_timeout(hba->dev_cmd.complete,
2477 msecs_to_jiffies(max_timeout));
2479 /* Make sure descriptors are ready before ringing the doorbell */
2480 wmb();
2481 spin_lock_irqsave(hba->host->host_lock, flags);
2482 hba->dev_cmd.complete = NULL;
2483 if (likely(time_left)) {
2484 err = ufshcd_get_tr_ocs(lrbp);
2485 if (!err)
2486 err = ufshcd_dev_cmd_completion(hba, lrbp);
2488 spin_unlock_irqrestore(hba->host->host_lock, flags);
2490 if (!time_left) {
2491 err = -ETIMEDOUT;
2492 dev_dbg(hba->dev, "%s: dev_cmd request timedout, tag %d\n",
2493 __func__, lrbp->task_tag);
2494 if (!ufshcd_clear_cmd(hba, lrbp->task_tag))
2495 /* successfully cleared the command, retry if needed */
2496 err = -EAGAIN;
2498 * in case of an error, after clearing the doorbell,
2499 * we also need to clear the outstanding_request
2500 * field in hba
2502 ufshcd_outstanding_req_clear(hba, lrbp->task_tag);
2505 return err;
2509 * ufshcd_get_dev_cmd_tag - Get device management command tag
2510 * @hba: per-adapter instance
2511 * @tag: pointer to variable with available slot value
2513 * Get a free slot and lock it until device management command
2514 * completes.
2516 * Returns false if free slot is unavailable for locking, else
2517 * return true with tag value in @tag.
2519 static bool ufshcd_get_dev_cmd_tag(struct ufs_hba *hba, int *tag_out)
2521 int tag;
2522 bool ret = false;
2523 unsigned long tmp;
2525 if (!tag_out)
2526 goto out;
2528 do {
2529 tmp = ~hba->lrb_in_use;
2530 tag = find_last_bit(&tmp, hba->nutrs);
2531 if (tag >= hba->nutrs)
2532 goto out;
2533 } while (test_and_set_bit_lock(tag, &hba->lrb_in_use));
2535 *tag_out = tag;
2536 ret = true;
2537 out:
2538 return ret;
2541 static inline void ufshcd_put_dev_cmd_tag(struct ufs_hba *hba, int tag)
2543 clear_bit_unlock(tag, &hba->lrb_in_use);
2547 * ufshcd_exec_dev_cmd - API for sending device management requests
2548 * @hba - UFS hba
2549 * @cmd_type - specifies the type (NOP, Query...)
2550 * @timeout - time in seconds
2552 * NOTE: Since there is only one available tag for device management commands,
2553 * it is expected you hold the hba->dev_cmd.lock mutex.
2555 static int ufshcd_exec_dev_cmd(struct ufs_hba *hba,
2556 enum dev_cmd_type cmd_type, int timeout)
2558 struct ufshcd_lrb *lrbp;
2559 int err;
2560 int tag;
2561 struct completion wait;
2562 unsigned long flags;
2564 down_read(&hba->clk_scaling_lock);
2567 * Get free slot, sleep if slots are unavailable.
2568 * Even though we use wait_event() which sleeps indefinitely,
2569 * the maximum wait time is bounded by SCSI request timeout.
2571 wait_event(hba->dev_cmd.tag_wq, ufshcd_get_dev_cmd_tag(hba, &tag));
2573 init_completion(&wait);
2574 lrbp = &hba->lrb[tag];
2575 WARN_ON(lrbp->cmd);
2576 err = ufshcd_compose_dev_cmd(hba, lrbp, cmd_type, tag);
2577 if (unlikely(err))
2578 goto out_put_tag;
2580 hba->dev_cmd.complete = &wait;
2582 /* Make sure descriptors are ready before ringing the doorbell */
2583 wmb();
2584 spin_lock_irqsave(hba->host->host_lock, flags);
2585 ufshcd_vops_setup_xfer_req(hba, tag, (lrbp->cmd ? true : false));
2586 ufshcd_send_command(hba, tag);
2587 spin_unlock_irqrestore(hba->host->host_lock, flags);
2589 err = ufshcd_wait_for_dev_cmd(hba, lrbp, timeout);
2591 out_put_tag:
2592 ufshcd_put_dev_cmd_tag(hba, tag);
2593 wake_up(&hba->dev_cmd.tag_wq);
2594 up_read(&hba->clk_scaling_lock);
2595 return err;
2599 * ufshcd_init_query() - init the query response and request parameters
2600 * @hba: per-adapter instance
2601 * @request: address of the request pointer to be initialized
2602 * @response: address of the response pointer to be initialized
2603 * @opcode: operation to perform
2604 * @idn: flag idn to access
2605 * @index: LU number to access
2606 * @selector: query/flag/descriptor further identification
2608 static inline void ufshcd_init_query(struct ufs_hba *hba,
2609 struct ufs_query_req **request, struct ufs_query_res **response,
2610 enum query_opcode opcode, u8 idn, u8 index, u8 selector)
2612 *request = &hba->dev_cmd.query.request;
2613 *response = &hba->dev_cmd.query.response;
2614 memset(*request, 0, sizeof(struct ufs_query_req));
2615 memset(*response, 0, sizeof(struct ufs_query_res));
2616 (*request)->upiu_req.opcode = opcode;
2617 (*request)->upiu_req.idn = idn;
2618 (*request)->upiu_req.index = index;
2619 (*request)->upiu_req.selector = selector;
2622 static int ufshcd_query_flag_retry(struct ufs_hba *hba,
2623 enum query_opcode opcode, enum flag_idn idn, bool *flag_res)
2625 int ret;
2626 int retries;
2628 for (retries = 0; retries < QUERY_REQ_RETRIES; retries++) {
2629 ret = ufshcd_query_flag(hba, opcode, idn, flag_res);
2630 if (ret)
2631 dev_dbg(hba->dev,
2632 "%s: failed with error %d, retries %d\n",
2633 __func__, ret, retries);
2634 else
2635 break;
2638 if (ret)
2639 dev_err(hba->dev,
2640 "%s: query attribute, opcode %d, idn %d, failed with error %d after %d retires\n",
2641 __func__, opcode, idn, ret, retries);
2642 return ret;
2646 * ufshcd_query_flag() - API function for sending flag query requests
2647 * hba: per-adapter instance
2648 * query_opcode: flag query to perform
2649 * idn: flag idn to access
2650 * flag_res: the flag value after the query request completes
2652 * Returns 0 for success, non-zero in case of failure
2654 int ufshcd_query_flag(struct ufs_hba *hba, enum query_opcode opcode,
2655 enum flag_idn idn, bool *flag_res)
2657 struct ufs_query_req *request = NULL;
2658 struct ufs_query_res *response = NULL;
2659 int err, index = 0, selector = 0;
2660 int timeout = QUERY_REQ_TIMEOUT;
2662 BUG_ON(!hba);
2664 ufshcd_hold(hba, false);
2665 mutex_lock(&hba->dev_cmd.lock);
2666 ufshcd_init_query(hba, &request, &response, opcode, idn, index,
2667 selector);
2669 switch (opcode) {
2670 case UPIU_QUERY_OPCODE_SET_FLAG:
2671 case UPIU_QUERY_OPCODE_CLEAR_FLAG:
2672 case UPIU_QUERY_OPCODE_TOGGLE_FLAG:
2673 request->query_func = UPIU_QUERY_FUNC_STANDARD_WRITE_REQUEST;
2674 break;
2675 case UPIU_QUERY_OPCODE_READ_FLAG:
2676 request->query_func = UPIU_QUERY_FUNC_STANDARD_READ_REQUEST;
2677 if (!flag_res) {
2678 /* No dummy reads */
2679 dev_err(hba->dev, "%s: Invalid argument for read request\n",
2680 __func__);
2681 err = -EINVAL;
2682 goto out_unlock;
2684 break;
2685 default:
2686 dev_err(hba->dev,
2687 "%s: Expected query flag opcode but got = %d\n",
2688 __func__, opcode);
2689 err = -EINVAL;
2690 goto out_unlock;
2693 err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_QUERY, timeout);
2695 if (err) {
2696 dev_err(hba->dev,
2697 "%s: Sending flag query for idn %d failed, err = %d\n",
2698 __func__, idn, err);
2699 goto out_unlock;
2702 if (flag_res)
2703 *flag_res = (be32_to_cpu(response->upiu_res.value) &
2704 MASK_QUERY_UPIU_FLAG_LOC) & 0x1;
2706 out_unlock:
2707 mutex_unlock(&hba->dev_cmd.lock);
2708 ufshcd_release(hba);
2709 return err;
2713 * ufshcd_query_attr - API function for sending attribute requests
2714 * hba: per-adapter instance
2715 * opcode: attribute opcode
2716 * idn: attribute idn to access
2717 * index: index field
2718 * selector: selector field
2719 * attr_val: the attribute value after the query request completes
2721 * Returns 0 for success, non-zero in case of failure
2723 static int ufshcd_query_attr(struct ufs_hba *hba, enum query_opcode opcode,
2724 enum attr_idn idn, u8 index, u8 selector, u32 *attr_val)
2726 struct ufs_query_req *request = NULL;
2727 struct ufs_query_res *response = NULL;
2728 int err;
2730 BUG_ON(!hba);
2732 ufshcd_hold(hba, false);
2733 if (!attr_val) {
2734 dev_err(hba->dev, "%s: attribute value required for opcode 0x%x\n",
2735 __func__, opcode);
2736 err = -EINVAL;
2737 goto out;
2740 mutex_lock(&hba->dev_cmd.lock);
2741 ufshcd_init_query(hba, &request, &response, opcode, idn, index,
2742 selector);
2744 switch (opcode) {
2745 case UPIU_QUERY_OPCODE_WRITE_ATTR:
2746 request->query_func = UPIU_QUERY_FUNC_STANDARD_WRITE_REQUEST;
2747 request->upiu_req.value = cpu_to_be32(*attr_val);
2748 break;
2749 case UPIU_QUERY_OPCODE_READ_ATTR:
2750 request->query_func = UPIU_QUERY_FUNC_STANDARD_READ_REQUEST;
2751 break;
2752 default:
2753 dev_err(hba->dev, "%s: Expected query attr opcode but got = 0x%.2x\n",
2754 __func__, opcode);
2755 err = -EINVAL;
2756 goto out_unlock;
2759 err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_QUERY, QUERY_REQ_TIMEOUT);
2761 if (err) {
2762 dev_err(hba->dev, "%s: opcode 0x%.2x for idn %d failed, index %d, err = %d\n",
2763 __func__, opcode, idn, index, err);
2764 goto out_unlock;
2767 *attr_val = be32_to_cpu(response->upiu_res.value);
2769 out_unlock:
2770 mutex_unlock(&hba->dev_cmd.lock);
2771 out:
2772 ufshcd_release(hba);
2773 return err;
2777 * ufshcd_query_attr_retry() - API function for sending query
2778 * attribute with retries
2779 * @hba: per-adapter instance
2780 * @opcode: attribute opcode
2781 * @idn: attribute idn to access
2782 * @index: index field
2783 * @selector: selector field
2784 * @attr_val: the attribute value after the query request
2785 * completes
2787 * Returns 0 for success, non-zero in case of failure
2789 static int ufshcd_query_attr_retry(struct ufs_hba *hba,
2790 enum query_opcode opcode, enum attr_idn idn, u8 index, u8 selector,
2791 u32 *attr_val)
2793 int ret = 0;
2794 u32 retries;
2796 for (retries = QUERY_REQ_RETRIES; retries > 0; retries--) {
2797 ret = ufshcd_query_attr(hba, opcode, idn, index,
2798 selector, attr_val);
2799 if (ret)
2800 dev_dbg(hba->dev, "%s: failed with error %d, retries %d\n",
2801 __func__, ret, retries);
2802 else
2803 break;
2806 if (ret)
2807 dev_err(hba->dev,
2808 "%s: query attribute, idn %d, failed with error %d after %d retires\n",
2809 __func__, idn, ret, QUERY_REQ_RETRIES);
2810 return ret;
2813 static int __ufshcd_query_descriptor(struct ufs_hba *hba,
2814 enum query_opcode opcode, enum desc_idn idn, u8 index,
2815 u8 selector, u8 *desc_buf, int *buf_len)
2817 struct ufs_query_req *request = NULL;
2818 struct ufs_query_res *response = NULL;
2819 int err;
2821 BUG_ON(!hba);
2823 ufshcd_hold(hba, false);
2824 if (!desc_buf) {
2825 dev_err(hba->dev, "%s: descriptor buffer required for opcode 0x%x\n",
2826 __func__, opcode);
2827 err = -EINVAL;
2828 goto out;
2831 if (*buf_len < QUERY_DESC_MIN_SIZE || *buf_len > QUERY_DESC_MAX_SIZE) {
2832 dev_err(hba->dev, "%s: descriptor buffer size (%d) is out of range\n",
2833 __func__, *buf_len);
2834 err = -EINVAL;
2835 goto out;
2838 mutex_lock(&hba->dev_cmd.lock);
2839 ufshcd_init_query(hba, &request, &response, opcode, idn, index,
2840 selector);
2841 hba->dev_cmd.query.descriptor = desc_buf;
2842 request->upiu_req.length = cpu_to_be16(*buf_len);
2844 switch (opcode) {
2845 case UPIU_QUERY_OPCODE_WRITE_DESC:
2846 request->query_func = UPIU_QUERY_FUNC_STANDARD_WRITE_REQUEST;
2847 break;
2848 case UPIU_QUERY_OPCODE_READ_DESC:
2849 request->query_func = UPIU_QUERY_FUNC_STANDARD_READ_REQUEST;
2850 break;
2851 default:
2852 dev_err(hba->dev,
2853 "%s: Expected query descriptor opcode but got = 0x%.2x\n",
2854 __func__, opcode);
2855 err = -EINVAL;
2856 goto out_unlock;
2859 err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_QUERY, QUERY_REQ_TIMEOUT);
2861 if (err) {
2862 dev_err(hba->dev, "%s: opcode 0x%.2x for idn %d failed, index %d, err = %d\n",
2863 __func__, opcode, idn, index, err);
2864 goto out_unlock;
2867 hba->dev_cmd.query.descriptor = NULL;
2868 *buf_len = be16_to_cpu(response->upiu_res.length);
2870 out_unlock:
2871 mutex_unlock(&hba->dev_cmd.lock);
2872 out:
2873 ufshcd_release(hba);
2874 return err;
2878 * ufshcd_query_descriptor_retry - API function for sending descriptor
2879 * requests
2880 * hba: per-adapter instance
2881 * opcode: attribute opcode
2882 * idn: attribute idn to access
2883 * index: index field
2884 * selector: selector field
2885 * desc_buf: the buffer that contains the descriptor
2886 * buf_len: length parameter passed to the device
2888 * Returns 0 for success, non-zero in case of failure.
2889 * The buf_len parameter will contain, on return, the length parameter
2890 * received on the response.
2892 static int ufshcd_query_descriptor_retry(struct ufs_hba *hba,
2893 enum query_opcode opcode,
2894 enum desc_idn idn, u8 index,
2895 u8 selector,
2896 u8 *desc_buf, int *buf_len)
2898 int err;
2899 int retries;
2901 for (retries = QUERY_REQ_RETRIES; retries > 0; retries--) {
2902 err = __ufshcd_query_descriptor(hba, opcode, idn, index,
2903 selector, desc_buf, buf_len);
2904 if (!err || err == -EINVAL)
2905 break;
2908 return err;
2912 * ufshcd_read_desc_length - read the specified descriptor length from header
2913 * @hba: Pointer to adapter instance
2914 * @desc_id: descriptor idn value
2915 * @desc_index: descriptor index
2916 * @desc_length: pointer to variable to read the length of descriptor
2918 * Return 0 in case of success, non-zero otherwise
2920 static int ufshcd_read_desc_length(struct ufs_hba *hba,
2921 enum desc_idn desc_id,
2922 int desc_index,
2923 int *desc_length)
2925 int ret;
2926 u8 header[QUERY_DESC_HDR_SIZE];
2927 int header_len = QUERY_DESC_HDR_SIZE;
2929 if (desc_id >= QUERY_DESC_IDN_MAX)
2930 return -EINVAL;
2932 ret = ufshcd_query_descriptor_retry(hba, UPIU_QUERY_OPCODE_READ_DESC,
2933 desc_id, desc_index, 0, header,
2934 &header_len);
2936 if (ret) {
2937 dev_err(hba->dev, "%s: Failed to get descriptor header id %d",
2938 __func__, desc_id);
2939 return ret;
2940 } else if (desc_id != header[QUERY_DESC_DESC_TYPE_OFFSET]) {
2941 dev_warn(hba->dev, "%s: descriptor header id %d and desc_id %d mismatch",
2942 __func__, header[QUERY_DESC_DESC_TYPE_OFFSET],
2943 desc_id);
2944 ret = -EINVAL;
2947 *desc_length = header[QUERY_DESC_LENGTH_OFFSET];
2948 return ret;
2953 * ufshcd_map_desc_id_to_length - map descriptor IDN to its length
2954 * @hba: Pointer to adapter instance
2955 * @desc_id: descriptor idn value
2956 * @desc_len: mapped desc length (out)
2958 * Return 0 in case of success, non-zero otherwise
2960 int ufshcd_map_desc_id_to_length(struct ufs_hba *hba,
2961 enum desc_idn desc_id, int *desc_len)
2963 switch (desc_id) {
2964 case QUERY_DESC_IDN_DEVICE:
2965 *desc_len = hba->desc_size.dev_desc;
2966 break;
2967 case QUERY_DESC_IDN_POWER:
2968 *desc_len = hba->desc_size.pwr_desc;
2969 break;
2970 case QUERY_DESC_IDN_GEOMETRY:
2971 *desc_len = hba->desc_size.geom_desc;
2972 break;
2973 case QUERY_DESC_IDN_CONFIGURATION:
2974 *desc_len = hba->desc_size.conf_desc;
2975 break;
2976 case QUERY_DESC_IDN_UNIT:
2977 *desc_len = hba->desc_size.unit_desc;
2978 break;
2979 case QUERY_DESC_IDN_INTERCONNECT:
2980 *desc_len = hba->desc_size.interc_desc;
2981 break;
2982 case QUERY_DESC_IDN_STRING:
2983 *desc_len = QUERY_DESC_MAX_SIZE;
2984 break;
2985 case QUERY_DESC_IDN_RFU_0:
2986 case QUERY_DESC_IDN_RFU_1:
2987 *desc_len = 0;
2988 break;
2989 default:
2990 *desc_len = 0;
2991 return -EINVAL;
2993 return 0;
2995 EXPORT_SYMBOL(ufshcd_map_desc_id_to_length);
2998 * ufshcd_read_desc_param - read the specified descriptor parameter
2999 * @hba: Pointer to adapter instance
3000 * @desc_id: descriptor idn value
3001 * @desc_index: descriptor index
3002 * @param_offset: offset of the parameter to read
3003 * @param_read_buf: pointer to buffer where parameter would be read
3004 * @param_size: sizeof(param_read_buf)
3006 * Return 0 in case of success, non-zero otherwise
3008 static int ufshcd_read_desc_param(struct ufs_hba *hba,
3009 enum desc_idn desc_id,
3010 int desc_index,
3011 u8 param_offset,
3012 u8 *param_read_buf,
3013 u8 param_size)
3015 int ret;
3016 u8 *desc_buf;
3017 int buff_len;
3018 bool is_kmalloc = true;
3020 /* Safety check */
3021 if (desc_id >= QUERY_DESC_IDN_MAX || !param_size)
3022 return -EINVAL;
3024 /* Get the max length of descriptor from structure filled up at probe
3025 * time.
3027 ret = ufshcd_map_desc_id_to_length(hba, desc_id, &buff_len);
3029 /* Sanity checks */
3030 if (ret || !buff_len) {
3031 dev_err(hba->dev, "%s: Failed to get full descriptor length",
3032 __func__);
3033 return ret;
3036 /* Check whether we need temp memory */
3037 if (param_offset != 0 || param_size < buff_len) {
3038 desc_buf = kmalloc(buff_len, GFP_KERNEL);
3039 if (!desc_buf)
3040 return -ENOMEM;
3041 } else {
3042 desc_buf = param_read_buf;
3043 is_kmalloc = false;
3046 /* Request for full descriptor */
3047 ret = ufshcd_query_descriptor_retry(hba, UPIU_QUERY_OPCODE_READ_DESC,
3048 desc_id, desc_index, 0,
3049 desc_buf, &buff_len);
3051 if (ret) {
3052 dev_err(hba->dev, "%s: Failed reading descriptor. desc_id %d, desc_index %d, param_offset %d, ret %d",
3053 __func__, desc_id, desc_index, param_offset, ret);
3054 goto out;
3057 /* Sanity check */
3058 if (desc_buf[QUERY_DESC_DESC_TYPE_OFFSET] != desc_id) {
3059 dev_err(hba->dev, "%s: invalid desc_id %d in descriptor header",
3060 __func__, desc_buf[QUERY_DESC_DESC_TYPE_OFFSET]);
3061 ret = -EINVAL;
3062 goto out;
3065 /* Check wherher we will not copy more data, than available */
3066 if (is_kmalloc && param_size > buff_len)
3067 param_size = buff_len;
3069 if (is_kmalloc)
3070 memcpy(param_read_buf, &desc_buf[param_offset], param_size);
3071 out:
3072 if (is_kmalloc)
3073 kfree(desc_buf);
3074 return ret;
3077 static inline int ufshcd_read_desc(struct ufs_hba *hba,
3078 enum desc_idn desc_id,
3079 int desc_index,
3080 u8 *buf,
3081 u32 size)
3083 return ufshcd_read_desc_param(hba, desc_id, desc_index, 0, buf, size);
3086 static inline int ufshcd_read_power_desc(struct ufs_hba *hba,
3087 u8 *buf,
3088 u32 size)
3090 return ufshcd_read_desc(hba, QUERY_DESC_IDN_POWER, 0, buf, size);
3093 static int ufshcd_read_device_desc(struct ufs_hba *hba, u8 *buf, u32 size)
3095 return ufshcd_read_desc(hba, QUERY_DESC_IDN_DEVICE, 0, buf, size);
3099 * ufshcd_read_string_desc - read string descriptor
3100 * @hba: pointer to adapter instance
3101 * @desc_index: descriptor index
3102 * @buf: pointer to buffer where descriptor would be read
3103 * @size: size of buf
3104 * @ascii: if true convert from unicode to ascii characters
3106 * Return 0 in case of success, non-zero otherwise
3108 #define ASCII_STD true
3109 static int ufshcd_read_string_desc(struct ufs_hba *hba, int desc_index,
3110 u8 *buf, u32 size, bool ascii)
3112 int err = 0;
3114 err = ufshcd_read_desc(hba,
3115 QUERY_DESC_IDN_STRING, desc_index, buf, size);
3117 if (err) {
3118 dev_err(hba->dev, "%s: reading String Desc failed after %d retries. err = %d\n",
3119 __func__, QUERY_REQ_RETRIES, err);
3120 goto out;
3123 if (ascii) {
3124 int desc_len;
3125 int ascii_len;
3126 int i;
3127 char *buff_ascii;
3129 desc_len = buf[0];
3130 /* remove header and divide by 2 to move from UTF16 to UTF8 */
3131 ascii_len = (desc_len - QUERY_DESC_HDR_SIZE) / 2 + 1;
3132 if (size < ascii_len + QUERY_DESC_HDR_SIZE) {
3133 dev_err(hba->dev, "%s: buffer allocated size is too small\n",
3134 __func__);
3135 err = -ENOMEM;
3136 goto out;
3139 buff_ascii = kmalloc(ascii_len, GFP_KERNEL);
3140 if (!buff_ascii) {
3141 err = -ENOMEM;
3142 goto out;
3146 * the descriptor contains string in UTF16 format
3147 * we need to convert to utf-8 so it can be displayed
3149 utf16s_to_utf8s((wchar_t *)&buf[QUERY_DESC_HDR_SIZE],
3150 desc_len - QUERY_DESC_HDR_SIZE,
3151 UTF16_BIG_ENDIAN, buff_ascii, ascii_len);
3153 /* replace non-printable or non-ASCII characters with spaces */
3154 for (i = 0; i < ascii_len; i++)
3155 ufshcd_remove_non_printable(&buff_ascii[i]);
3157 memset(buf + QUERY_DESC_HDR_SIZE, 0,
3158 size - QUERY_DESC_HDR_SIZE);
3159 memcpy(buf + QUERY_DESC_HDR_SIZE, buff_ascii, ascii_len);
3160 buf[QUERY_DESC_LENGTH_OFFSET] = ascii_len + QUERY_DESC_HDR_SIZE;
3161 kfree(buff_ascii);
3163 out:
3164 return err;
3168 * ufshcd_read_unit_desc_param - read the specified unit descriptor parameter
3169 * @hba: Pointer to adapter instance
3170 * @lun: lun id
3171 * @param_offset: offset of the parameter to read
3172 * @param_read_buf: pointer to buffer where parameter would be read
3173 * @param_size: sizeof(param_read_buf)
3175 * Return 0 in case of success, non-zero otherwise
3177 static inline int ufshcd_read_unit_desc_param(struct ufs_hba *hba,
3178 int lun,
3179 enum unit_desc_param param_offset,
3180 u8 *param_read_buf,
3181 u32 param_size)
3184 * Unit descriptors are only available for general purpose LUs (LUN id
3185 * from 0 to 7) and RPMB Well known LU.
3187 if (lun != UFS_UPIU_RPMB_WLUN && (lun >= UFS_UPIU_MAX_GENERAL_LUN))
3188 return -EOPNOTSUPP;
3190 return ufshcd_read_desc_param(hba, QUERY_DESC_IDN_UNIT, lun,
3191 param_offset, param_read_buf, param_size);
3195 * ufshcd_memory_alloc - allocate memory for host memory space data structures
3196 * @hba: per adapter instance
3198 * 1. Allocate DMA memory for Command Descriptor array
3199 * Each command descriptor consist of Command UPIU, Response UPIU and PRDT
3200 * 2. Allocate DMA memory for UTP Transfer Request Descriptor List (UTRDL).
3201 * 3. Allocate DMA memory for UTP Task Management Request Descriptor List
3202 * (UTMRDL)
3203 * 4. Allocate memory for local reference block(lrb).
3205 * Returns 0 for success, non-zero in case of failure
3207 static int ufshcd_memory_alloc(struct ufs_hba *hba)
3209 size_t utmrdl_size, utrdl_size, ucdl_size;
3211 /* Allocate memory for UTP command descriptors */
3212 ucdl_size = (sizeof(struct utp_transfer_cmd_desc) * hba->nutrs);
3213 hba->ucdl_base_addr = dmam_alloc_coherent(hba->dev,
3214 ucdl_size,
3215 &hba->ucdl_dma_addr,
3216 GFP_KERNEL);
3219 * UFSHCI requires UTP command descriptor to be 128 byte aligned.
3220 * make sure hba->ucdl_dma_addr is aligned to PAGE_SIZE
3221 * if hba->ucdl_dma_addr is aligned to PAGE_SIZE, then it will
3222 * be aligned to 128 bytes as well
3224 if (!hba->ucdl_base_addr ||
3225 WARN_ON(hba->ucdl_dma_addr & (PAGE_SIZE - 1))) {
3226 dev_err(hba->dev,
3227 "Command Descriptor Memory allocation failed\n");
3228 goto out;
3232 * Allocate memory for UTP Transfer descriptors
3233 * UFSHCI requires 1024 byte alignment of UTRD
3235 utrdl_size = (sizeof(struct utp_transfer_req_desc) * hba->nutrs);
3236 hba->utrdl_base_addr = dmam_alloc_coherent(hba->dev,
3237 utrdl_size,
3238 &hba->utrdl_dma_addr,
3239 GFP_KERNEL);
3240 if (!hba->utrdl_base_addr ||
3241 WARN_ON(hba->utrdl_dma_addr & (PAGE_SIZE - 1))) {
3242 dev_err(hba->dev,
3243 "Transfer Descriptor Memory allocation failed\n");
3244 goto out;
3248 * Allocate memory for UTP Task Management descriptors
3249 * UFSHCI requires 1024 byte alignment of UTMRD
3251 utmrdl_size = sizeof(struct utp_task_req_desc) * hba->nutmrs;
3252 hba->utmrdl_base_addr = dmam_alloc_coherent(hba->dev,
3253 utmrdl_size,
3254 &hba->utmrdl_dma_addr,
3255 GFP_KERNEL);
3256 if (!hba->utmrdl_base_addr ||
3257 WARN_ON(hba->utmrdl_dma_addr & (PAGE_SIZE - 1))) {
3258 dev_err(hba->dev,
3259 "Task Management Descriptor Memory allocation failed\n");
3260 goto out;
3263 /* Allocate memory for local reference block */
3264 hba->lrb = devm_kzalloc(hba->dev,
3265 hba->nutrs * sizeof(struct ufshcd_lrb),
3266 GFP_KERNEL);
3267 if (!hba->lrb) {
3268 dev_err(hba->dev, "LRB Memory allocation failed\n");
3269 goto out;
3271 return 0;
3272 out:
3273 return -ENOMEM;
3277 * ufshcd_host_memory_configure - configure local reference block with
3278 * memory offsets
3279 * @hba: per adapter instance
3281 * Configure Host memory space
3282 * 1. Update Corresponding UTRD.UCDBA and UTRD.UCDBAU with UCD DMA
3283 * address.
3284 * 2. Update each UTRD with Response UPIU offset, Response UPIU length
3285 * and PRDT offset.
3286 * 3. Save the corresponding addresses of UTRD, UCD.CMD, UCD.RSP and UCD.PRDT
3287 * into local reference block.
3289 static void ufshcd_host_memory_configure(struct ufs_hba *hba)
3291 struct utp_transfer_cmd_desc *cmd_descp;
3292 struct utp_transfer_req_desc *utrdlp;
3293 dma_addr_t cmd_desc_dma_addr;
3294 dma_addr_t cmd_desc_element_addr;
3295 u16 response_offset;
3296 u16 prdt_offset;
3297 int cmd_desc_size;
3298 int i;
3300 utrdlp = hba->utrdl_base_addr;
3301 cmd_descp = hba->ucdl_base_addr;
3303 response_offset =
3304 offsetof(struct utp_transfer_cmd_desc, response_upiu);
3305 prdt_offset =
3306 offsetof(struct utp_transfer_cmd_desc, prd_table);
3308 cmd_desc_size = sizeof(struct utp_transfer_cmd_desc);
3309 cmd_desc_dma_addr = hba->ucdl_dma_addr;
3311 for (i = 0; i < hba->nutrs; i++) {
3312 /* Configure UTRD with command descriptor base address */
3313 cmd_desc_element_addr =
3314 (cmd_desc_dma_addr + (cmd_desc_size * i));
3315 utrdlp[i].command_desc_base_addr_lo =
3316 cpu_to_le32(lower_32_bits(cmd_desc_element_addr));
3317 utrdlp[i].command_desc_base_addr_hi =
3318 cpu_to_le32(upper_32_bits(cmd_desc_element_addr));
3320 /* Response upiu and prdt offset should be in double words */
3321 if (hba->quirks & UFSHCD_QUIRK_PRDT_BYTE_GRAN) {
3322 utrdlp[i].response_upiu_offset =
3323 cpu_to_le16(response_offset);
3324 utrdlp[i].prd_table_offset =
3325 cpu_to_le16(prdt_offset);
3326 utrdlp[i].response_upiu_length =
3327 cpu_to_le16(ALIGNED_UPIU_SIZE);
3328 } else {
3329 utrdlp[i].response_upiu_offset =
3330 cpu_to_le16((response_offset >> 2));
3331 utrdlp[i].prd_table_offset =
3332 cpu_to_le16((prdt_offset >> 2));
3333 utrdlp[i].response_upiu_length =
3334 cpu_to_le16(ALIGNED_UPIU_SIZE >> 2);
3337 hba->lrb[i].utr_descriptor_ptr = (utrdlp + i);
3338 hba->lrb[i].utrd_dma_addr = hba->utrdl_dma_addr +
3339 (i * sizeof(struct utp_transfer_req_desc));
3340 hba->lrb[i].ucd_req_ptr =
3341 (struct utp_upiu_req *)(cmd_descp + i);
3342 hba->lrb[i].ucd_req_dma_addr = cmd_desc_element_addr;
3343 hba->lrb[i].ucd_rsp_ptr =
3344 (struct utp_upiu_rsp *)cmd_descp[i].response_upiu;
3345 hba->lrb[i].ucd_rsp_dma_addr = cmd_desc_element_addr +
3346 response_offset;
3347 hba->lrb[i].ucd_prdt_ptr =
3348 (struct ufshcd_sg_entry *)cmd_descp[i].prd_table;
3349 hba->lrb[i].ucd_prdt_dma_addr = cmd_desc_element_addr +
3350 prdt_offset;
3355 * ufshcd_dme_link_startup - Notify Unipro to perform link startup
3356 * @hba: per adapter instance
3358 * UIC_CMD_DME_LINK_STARTUP command must be issued to Unipro layer,
3359 * in order to initialize the Unipro link startup procedure.
3360 * Once the Unipro links are up, the device connected to the controller
3361 * is detected.
3363 * Returns 0 on success, non-zero value on failure
3365 static int ufshcd_dme_link_startup(struct ufs_hba *hba)
3367 struct uic_command uic_cmd = {0};
3368 int ret;
3370 uic_cmd.command = UIC_CMD_DME_LINK_STARTUP;
3372 ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
3373 if (ret)
3374 dev_dbg(hba->dev,
3375 "dme-link-startup: error code %d\n", ret);
3376 return ret;
3379 static inline void ufshcd_add_delay_before_dme_cmd(struct ufs_hba *hba)
3381 #define MIN_DELAY_BEFORE_DME_CMDS_US 1000
3382 unsigned long min_sleep_time_us;
3384 if (!(hba->quirks & UFSHCD_QUIRK_DELAY_BEFORE_DME_CMDS))
3385 return;
3388 * last_dme_cmd_tstamp will be 0 only for 1st call to
3389 * this function
3391 if (unlikely(!ktime_to_us(hba->last_dme_cmd_tstamp))) {
3392 min_sleep_time_us = MIN_DELAY_BEFORE_DME_CMDS_US;
3393 } else {
3394 unsigned long delta =
3395 (unsigned long) ktime_to_us(
3396 ktime_sub(ktime_get(),
3397 hba->last_dme_cmd_tstamp));
3399 if (delta < MIN_DELAY_BEFORE_DME_CMDS_US)
3400 min_sleep_time_us =
3401 MIN_DELAY_BEFORE_DME_CMDS_US - delta;
3402 else
3403 return; /* no more delay required */
3406 /* allow sleep for extra 50us if needed */
3407 usleep_range(min_sleep_time_us, min_sleep_time_us + 50);
3411 * ufshcd_dme_set_attr - UIC command for DME_SET, DME_PEER_SET
3412 * @hba: per adapter instance
3413 * @attr_sel: uic command argument1
3414 * @attr_set: attribute set type as uic command argument2
3415 * @mib_val: setting value as uic command argument3
3416 * @peer: indicate whether peer or local
3418 * Returns 0 on success, non-zero value on failure
3420 int ufshcd_dme_set_attr(struct ufs_hba *hba, u32 attr_sel,
3421 u8 attr_set, u32 mib_val, u8 peer)
3423 struct uic_command uic_cmd = {0};
3424 static const char *const action[] = {
3425 "dme-set",
3426 "dme-peer-set"
3428 const char *set = action[!!peer];
3429 int ret;
3430 int retries = UFS_UIC_COMMAND_RETRIES;
3432 uic_cmd.command = peer ?
3433 UIC_CMD_DME_PEER_SET : UIC_CMD_DME_SET;
3434 uic_cmd.argument1 = attr_sel;
3435 uic_cmd.argument2 = UIC_ARG_ATTR_TYPE(attr_set);
3436 uic_cmd.argument3 = mib_val;
3438 do {
3439 /* for peer attributes we retry upon failure */
3440 ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
3441 if (ret)
3442 dev_dbg(hba->dev, "%s: attr-id 0x%x val 0x%x error code %d\n",
3443 set, UIC_GET_ATTR_ID(attr_sel), mib_val, ret);
3444 } while (ret && peer && --retries);
3446 if (ret)
3447 dev_err(hba->dev, "%s: attr-id 0x%x val 0x%x failed %d retries\n",
3448 set, UIC_GET_ATTR_ID(attr_sel), mib_val,
3449 UFS_UIC_COMMAND_RETRIES - retries);
3451 return ret;
3453 EXPORT_SYMBOL_GPL(ufshcd_dme_set_attr);
3456 * ufshcd_dme_get_attr - UIC command for DME_GET, DME_PEER_GET
3457 * @hba: per adapter instance
3458 * @attr_sel: uic command argument1
3459 * @mib_val: the value of the attribute as returned by the UIC command
3460 * @peer: indicate whether peer or local
3462 * Returns 0 on success, non-zero value on failure
3464 int ufshcd_dme_get_attr(struct ufs_hba *hba, u32 attr_sel,
3465 u32 *mib_val, u8 peer)
3467 struct uic_command uic_cmd = {0};
3468 static const char *const action[] = {
3469 "dme-get",
3470 "dme-peer-get"
3472 const char *get = action[!!peer];
3473 int ret;
3474 int retries = UFS_UIC_COMMAND_RETRIES;
3475 struct ufs_pa_layer_attr orig_pwr_info;
3476 struct ufs_pa_layer_attr temp_pwr_info;
3477 bool pwr_mode_change = false;
3479 if (peer && (hba->quirks & UFSHCD_QUIRK_DME_PEER_ACCESS_AUTO_MODE)) {
3480 orig_pwr_info = hba->pwr_info;
3481 temp_pwr_info = orig_pwr_info;
3483 if (orig_pwr_info.pwr_tx == FAST_MODE ||
3484 orig_pwr_info.pwr_rx == FAST_MODE) {
3485 temp_pwr_info.pwr_tx = FASTAUTO_MODE;
3486 temp_pwr_info.pwr_rx = FASTAUTO_MODE;
3487 pwr_mode_change = true;
3488 } else if (orig_pwr_info.pwr_tx == SLOW_MODE ||
3489 orig_pwr_info.pwr_rx == SLOW_MODE) {
3490 temp_pwr_info.pwr_tx = SLOWAUTO_MODE;
3491 temp_pwr_info.pwr_rx = SLOWAUTO_MODE;
3492 pwr_mode_change = true;
3494 if (pwr_mode_change) {
3495 ret = ufshcd_change_power_mode(hba, &temp_pwr_info);
3496 if (ret)
3497 goto out;
3501 uic_cmd.command = peer ?
3502 UIC_CMD_DME_PEER_GET : UIC_CMD_DME_GET;
3503 uic_cmd.argument1 = attr_sel;
3505 do {
3506 /* for peer attributes we retry upon failure */
3507 ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
3508 if (ret)
3509 dev_dbg(hba->dev, "%s: attr-id 0x%x error code %d\n",
3510 get, UIC_GET_ATTR_ID(attr_sel), ret);
3511 } while (ret && peer && --retries);
3513 if (ret)
3514 dev_err(hba->dev, "%s: attr-id 0x%x failed %d retries\n",
3515 get, UIC_GET_ATTR_ID(attr_sel),
3516 UFS_UIC_COMMAND_RETRIES - retries);
3518 if (mib_val && !ret)
3519 *mib_val = uic_cmd.argument3;
3521 if (peer && (hba->quirks & UFSHCD_QUIRK_DME_PEER_ACCESS_AUTO_MODE)
3522 && pwr_mode_change)
3523 ufshcd_change_power_mode(hba, &orig_pwr_info);
3524 out:
3525 return ret;
3527 EXPORT_SYMBOL_GPL(ufshcd_dme_get_attr);
3530 * ufshcd_uic_pwr_ctrl - executes UIC commands (which affects the link power
3531 * state) and waits for it to take effect.
3533 * @hba: per adapter instance
3534 * @cmd: UIC command to execute
3536 * DME operations like DME_SET(PA_PWRMODE), DME_HIBERNATE_ENTER &
3537 * DME_HIBERNATE_EXIT commands take some time to take its effect on both host
3538 * and device UniPro link and hence it's final completion would be indicated by
3539 * dedicated status bits in Interrupt Status register (UPMS, UHES, UHXS) in
3540 * addition to normal UIC command completion Status (UCCS). This function only
3541 * returns after the relevant status bits indicate the completion.
3543 * Returns 0 on success, non-zero value on failure
3545 static int ufshcd_uic_pwr_ctrl(struct ufs_hba *hba, struct uic_command *cmd)
3547 struct completion uic_async_done;
3548 unsigned long flags;
3549 u8 status;
3550 int ret;
3551 bool reenable_intr = false;
3553 mutex_lock(&hba->uic_cmd_mutex);
3554 init_completion(&uic_async_done);
3555 ufshcd_add_delay_before_dme_cmd(hba);
3557 spin_lock_irqsave(hba->host->host_lock, flags);
3558 hba->uic_async_done = &uic_async_done;
3559 if (ufshcd_readl(hba, REG_INTERRUPT_ENABLE) & UIC_COMMAND_COMPL) {
3560 ufshcd_disable_intr(hba, UIC_COMMAND_COMPL);
3562 * Make sure UIC command completion interrupt is disabled before
3563 * issuing UIC command.
3565 wmb();
3566 reenable_intr = true;
3568 ret = __ufshcd_send_uic_cmd(hba, cmd, false);
3569 spin_unlock_irqrestore(hba->host->host_lock, flags);
3570 if (ret) {
3571 dev_err(hba->dev,
3572 "pwr ctrl cmd 0x%x with mode 0x%x uic error %d\n",
3573 cmd->command, cmd->argument3, ret);
3574 goto out;
3577 if (!wait_for_completion_timeout(hba->uic_async_done,
3578 msecs_to_jiffies(UIC_CMD_TIMEOUT))) {
3579 dev_err(hba->dev,
3580 "pwr ctrl cmd 0x%x with mode 0x%x completion timeout\n",
3581 cmd->command, cmd->argument3);
3582 ret = -ETIMEDOUT;
3583 goto out;
3586 status = ufshcd_get_upmcrs(hba);
3587 if (status != PWR_LOCAL) {
3588 dev_err(hba->dev,
3589 "pwr ctrl cmd 0x%0x failed, host upmcrs:0x%x\n",
3590 cmd->command, status);
3591 ret = (status != PWR_OK) ? status : -1;
3593 out:
3594 if (ret) {
3595 ufshcd_print_host_state(hba);
3596 ufshcd_print_pwr_info(hba);
3597 ufshcd_print_host_regs(hba);
3600 spin_lock_irqsave(hba->host->host_lock, flags);
3601 hba->active_uic_cmd = NULL;
3602 hba->uic_async_done = NULL;
3603 if (reenable_intr)
3604 ufshcd_enable_intr(hba, UIC_COMMAND_COMPL);
3605 spin_unlock_irqrestore(hba->host->host_lock, flags);
3606 mutex_unlock(&hba->uic_cmd_mutex);
3608 return ret;
3612 * ufshcd_uic_change_pwr_mode - Perform the UIC power mode chage
3613 * using DME_SET primitives.
3614 * @hba: per adapter instance
3615 * @mode: powr mode value
3617 * Returns 0 on success, non-zero value on failure
3619 static int ufshcd_uic_change_pwr_mode(struct ufs_hba *hba, u8 mode)
3621 struct uic_command uic_cmd = {0};
3622 int ret;
3624 if (hba->quirks & UFSHCD_QUIRK_BROKEN_PA_RXHSUNTERMCAP) {
3625 ret = ufshcd_dme_set(hba,
3626 UIC_ARG_MIB_SEL(PA_RXHSUNTERMCAP, 0), 1);
3627 if (ret) {
3628 dev_err(hba->dev, "%s: failed to enable PA_RXHSUNTERMCAP ret %d\n",
3629 __func__, ret);
3630 goto out;
3634 uic_cmd.command = UIC_CMD_DME_SET;
3635 uic_cmd.argument1 = UIC_ARG_MIB(PA_PWRMODE);
3636 uic_cmd.argument3 = mode;
3637 ufshcd_hold(hba, false);
3638 ret = ufshcd_uic_pwr_ctrl(hba, &uic_cmd);
3639 ufshcd_release(hba);
3641 out:
3642 return ret;
3645 static int ufshcd_link_recovery(struct ufs_hba *hba)
3647 int ret;
3648 unsigned long flags;
3650 spin_lock_irqsave(hba->host->host_lock, flags);
3651 hba->ufshcd_state = UFSHCD_STATE_RESET;
3652 ufshcd_set_eh_in_progress(hba);
3653 spin_unlock_irqrestore(hba->host->host_lock, flags);
3655 ret = ufshcd_host_reset_and_restore(hba);
3657 spin_lock_irqsave(hba->host->host_lock, flags);
3658 if (ret)
3659 hba->ufshcd_state = UFSHCD_STATE_ERROR;
3660 ufshcd_clear_eh_in_progress(hba);
3661 spin_unlock_irqrestore(hba->host->host_lock, flags);
3663 if (ret)
3664 dev_err(hba->dev, "%s: link recovery failed, err %d",
3665 __func__, ret);
3667 return ret;
3670 static int __ufshcd_uic_hibern8_enter(struct ufs_hba *hba)
3672 int ret;
3673 struct uic_command uic_cmd = {0};
3674 ktime_t start = ktime_get();
3676 ufshcd_vops_hibern8_notify(hba, UIC_CMD_DME_HIBER_ENTER, PRE_CHANGE);
3678 uic_cmd.command = UIC_CMD_DME_HIBER_ENTER;
3679 ret = ufshcd_uic_pwr_ctrl(hba, &uic_cmd);
3680 trace_ufshcd_profile_hibern8(dev_name(hba->dev), "enter",
3681 ktime_to_us(ktime_sub(ktime_get(), start)), ret);
3683 if (ret) {
3684 dev_err(hba->dev, "%s: hibern8 enter failed. ret = %d\n",
3685 __func__, ret);
3688 * If link recovery fails then return error so that caller
3689 * don't retry the hibern8 enter again.
3691 if (ufshcd_link_recovery(hba))
3692 ret = -ENOLINK;
3693 } else
3694 ufshcd_vops_hibern8_notify(hba, UIC_CMD_DME_HIBER_ENTER,
3695 POST_CHANGE);
3697 return ret;
3700 static int ufshcd_uic_hibern8_enter(struct ufs_hba *hba)
3702 int ret = 0, retries;
3704 for (retries = UIC_HIBERN8_ENTER_RETRIES; retries > 0; retries--) {
3705 ret = __ufshcd_uic_hibern8_enter(hba);
3706 if (!ret || ret == -ENOLINK)
3707 goto out;
3709 out:
3710 return ret;
3713 static int ufshcd_uic_hibern8_exit(struct ufs_hba *hba)
3715 struct uic_command uic_cmd = {0};
3716 int ret;
3717 ktime_t start = ktime_get();
3719 ufshcd_vops_hibern8_notify(hba, UIC_CMD_DME_HIBER_EXIT, PRE_CHANGE);
3721 uic_cmd.command = UIC_CMD_DME_HIBER_EXIT;
3722 ret = ufshcd_uic_pwr_ctrl(hba, &uic_cmd);
3723 trace_ufshcd_profile_hibern8(dev_name(hba->dev), "exit",
3724 ktime_to_us(ktime_sub(ktime_get(), start)), ret);
3726 if (ret) {
3727 dev_err(hba->dev, "%s: hibern8 exit failed. ret = %d\n",
3728 __func__, ret);
3729 ret = ufshcd_link_recovery(hba);
3730 } else {
3731 ufshcd_vops_hibern8_notify(hba, UIC_CMD_DME_HIBER_EXIT,
3732 POST_CHANGE);
3733 hba->ufs_stats.last_hibern8_exit_tstamp = ktime_get();
3734 hba->ufs_stats.hibern8_exit_cnt++;
3737 return ret;
3741 * ufshcd_init_pwr_info - setting the POR (power on reset)
3742 * values in hba power info
3743 * @hba: per-adapter instance
3745 static void ufshcd_init_pwr_info(struct ufs_hba *hba)
3747 hba->pwr_info.gear_rx = UFS_PWM_G1;
3748 hba->pwr_info.gear_tx = UFS_PWM_G1;
3749 hba->pwr_info.lane_rx = 1;
3750 hba->pwr_info.lane_tx = 1;
3751 hba->pwr_info.pwr_rx = SLOWAUTO_MODE;
3752 hba->pwr_info.pwr_tx = SLOWAUTO_MODE;
3753 hba->pwr_info.hs_rate = 0;
3757 * ufshcd_get_max_pwr_mode - reads the max power mode negotiated with device
3758 * @hba: per-adapter instance
3760 static int ufshcd_get_max_pwr_mode(struct ufs_hba *hba)
3762 struct ufs_pa_layer_attr *pwr_info = &hba->max_pwr_info.info;
3764 if (hba->max_pwr_info.is_valid)
3765 return 0;
3767 pwr_info->pwr_tx = FAST_MODE;
3768 pwr_info->pwr_rx = FAST_MODE;
3769 pwr_info->hs_rate = PA_HS_MODE_B;
3771 /* Get the connected lane count */
3772 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_CONNECTEDRXDATALANES),
3773 &pwr_info->lane_rx);
3774 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_CONNECTEDTXDATALANES),
3775 &pwr_info->lane_tx);
3777 if (!pwr_info->lane_rx || !pwr_info->lane_tx) {
3778 dev_err(hba->dev, "%s: invalid connected lanes value. rx=%d, tx=%d\n",
3779 __func__,
3780 pwr_info->lane_rx,
3781 pwr_info->lane_tx);
3782 return -EINVAL;
3786 * First, get the maximum gears of HS speed.
3787 * If a zero value, it means there is no HSGEAR capability.
3788 * Then, get the maximum gears of PWM speed.
3790 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_MAXRXHSGEAR), &pwr_info->gear_rx);
3791 if (!pwr_info->gear_rx) {
3792 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_MAXRXPWMGEAR),
3793 &pwr_info->gear_rx);
3794 if (!pwr_info->gear_rx) {
3795 dev_err(hba->dev, "%s: invalid max pwm rx gear read = %d\n",
3796 __func__, pwr_info->gear_rx);
3797 return -EINVAL;
3799 pwr_info->pwr_rx = SLOW_MODE;
3802 ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_MAXRXHSGEAR),
3803 &pwr_info->gear_tx);
3804 if (!pwr_info->gear_tx) {
3805 ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_MAXRXPWMGEAR),
3806 &pwr_info->gear_tx);
3807 if (!pwr_info->gear_tx) {
3808 dev_err(hba->dev, "%s: invalid max pwm tx gear read = %d\n",
3809 __func__, pwr_info->gear_tx);
3810 return -EINVAL;
3812 pwr_info->pwr_tx = SLOW_MODE;
3815 hba->max_pwr_info.is_valid = true;
3816 return 0;
3819 static int ufshcd_change_power_mode(struct ufs_hba *hba,
3820 struct ufs_pa_layer_attr *pwr_mode)
3822 int ret;
3824 /* if already configured to the requested pwr_mode */
3825 if (pwr_mode->gear_rx == hba->pwr_info.gear_rx &&
3826 pwr_mode->gear_tx == hba->pwr_info.gear_tx &&
3827 pwr_mode->lane_rx == hba->pwr_info.lane_rx &&
3828 pwr_mode->lane_tx == hba->pwr_info.lane_tx &&
3829 pwr_mode->pwr_rx == hba->pwr_info.pwr_rx &&
3830 pwr_mode->pwr_tx == hba->pwr_info.pwr_tx &&
3831 pwr_mode->hs_rate == hba->pwr_info.hs_rate) {
3832 dev_dbg(hba->dev, "%s: power already configured\n", __func__);
3833 return 0;
3837 * Configure attributes for power mode change with below.
3838 * - PA_RXGEAR, PA_ACTIVERXDATALANES, PA_RXTERMINATION,
3839 * - PA_TXGEAR, PA_ACTIVETXDATALANES, PA_TXTERMINATION,
3840 * - PA_HSSERIES
3842 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_RXGEAR), pwr_mode->gear_rx);
3843 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_ACTIVERXDATALANES),
3844 pwr_mode->lane_rx);
3845 if (pwr_mode->pwr_rx == FASTAUTO_MODE ||
3846 pwr_mode->pwr_rx == FAST_MODE)
3847 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_RXTERMINATION), TRUE);
3848 else
3849 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_RXTERMINATION), FALSE);
3851 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TXGEAR), pwr_mode->gear_tx);
3852 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_ACTIVETXDATALANES),
3853 pwr_mode->lane_tx);
3854 if (pwr_mode->pwr_tx == FASTAUTO_MODE ||
3855 pwr_mode->pwr_tx == FAST_MODE)
3856 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TXTERMINATION), TRUE);
3857 else
3858 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TXTERMINATION), FALSE);
3860 if (pwr_mode->pwr_rx == FASTAUTO_MODE ||
3861 pwr_mode->pwr_tx == FASTAUTO_MODE ||
3862 pwr_mode->pwr_rx == FAST_MODE ||
3863 pwr_mode->pwr_tx == FAST_MODE)
3864 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_HSSERIES),
3865 pwr_mode->hs_rate);
3867 ret = ufshcd_uic_change_pwr_mode(hba, pwr_mode->pwr_rx << 4
3868 | pwr_mode->pwr_tx);
3870 if (ret) {
3871 dev_err(hba->dev,
3872 "%s: power mode change failed %d\n", __func__, ret);
3873 } else {
3874 ufshcd_vops_pwr_change_notify(hba, POST_CHANGE, NULL,
3875 pwr_mode);
3877 memcpy(&hba->pwr_info, pwr_mode,
3878 sizeof(struct ufs_pa_layer_attr));
3881 return ret;
3885 * ufshcd_config_pwr_mode - configure a new power mode
3886 * @hba: per-adapter instance
3887 * @desired_pwr_mode: desired power configuration
3889 static int ufshcd_config_pwr_mode(struct ufs_hba *hba,
3890 struct ufs_pa_layer_attr *desired_pwr_mode)
3892 struct ufs_pa_layer_attr final_params = { 0 };
3893 int ret;
3895 ret = ufshcd_vops_pwr_change_notify(hba, PRE_CHANGE,
3896 desired_pwr_mode, &final_params);
3898 if (ret)
3899 memcpy(&final_params, desired_pwr_mode, sizeof(final_params));
3901 ret = ufshcd_change_power_mode(hba, &final_params);
3902 if (!ret)
3903 ufshcd_print_pwr_info(hba);
3905 return ret;
3909 * ufshcd_complete_dev_init() - checks device readiness
3910 * hba: per-adapter instance
3912 * Set fDeviceInit flag and poll until device toggles it.
3914 static int ufshcd_complete_dev_init(struct ufs_hba *hba)
3916 int i;
3917 int err;
3918 bool flag_res = 1;
3920 err = ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_SET_FLAG,
3921 QUERY_FLAG_IDN_FDEVICEINIT, NULL);
3922 if (err) {
3923 dev_err(hba->dev,
3924 "%s setting fDeviceInit flag failed with error %d\n",
3925 __func__, err);
3926 goto out;
3929 /* poll for max. 1000 iterations for fDeviceInit flag to clear */
3930 for (i = 0; i < 1000 && !err && flag_res; i++)
3931 err = ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_READ_FLAG,
3932 QUERY_FLAG_IDN_FDEVICEINIT, &flag_res);
3934 if (err)
3935 dev_err(hba->dev,
3936 "%s reading fDeviceInit flag failed with error %d\n",
3937 __func__, err);
3938 else if (flag_res)
3939 dev_err(hba->dev,
3940 "%s fDeviceInit was not cleared by the device\n",
3941 __func__);
3943 out:
3944 return err;
3948 * ufshcd_make_hba_operational - Make UFS controller operational
3949 * @hba: per adapter instance
3951 * To bring UFS host controller to operational state,
3952 * 1. Enable required interrupts
3953 * 2. Configure interrupt aggregation
3954 * 3. Program UTRL and UTMRL base address
3955 * 4. Configure run-stop-registers
3957 * Returns 0 on success, non-zero value on failure
3959 static int ufshcd_make_hba_operational(struct ufs_hba *hba)
3961 int err = 0;
3962 u32 reg;
3964 /* Enable required interrupts */
3965 ufshcd_enable_intr(hba, UFSHCD_ENABLE_INTRS);
3967 /* Configure interrupt aggregation */
3968 if (ufshcd_is_intr_aggr_allowed(hba))
3969 ufshcd_config_intr_aggr(hba, hba->nutrs - 1, INT_AGGR_DEF_TO);
3970 else
3971 ufshcd_disable_intr_aggr(hba);
3973 /* Configure UTRL and UTMRL base address registers */
3974 ufshcd_writel(hba, lower_32_bits(hba->utrdl_dma_addr),
3975 REG_UTP_TRANSFER_REQ_LIST_BASE_L);
3976 ufshcd_writel(hba, upper_32_bits(hba->utrdl_dma_addr),
3977 REG_UTP_TRANSFER_REQ_LIST_BASE_H);
3978 ufshcd_writel(hba, lower_32_bits(hba->utmrdl_dma_addr),
3979 REG_UTP_TASK_REQ_LIST_BASE_L);
3980 ufshcd_writel(hba, upper_32_bits(hba->utmrdl_dma_addr),
3981 REG_UTP_TASK_REQ_LIST_BASE_H);
3984 * Make sure base address and interrupt setup are updated before
3985 * enabling the run/stop registers below.
3987 wmb();
3990 * UCRDY, UTMRLDY and UTRLRDY bits must be 1
3992 reg = ufshcd_readl(hba, REG_CONTROLLER_STATUS);
3993 if (!(ufshcd_get_lists_status(reg))) {
3994 ufshcd_enable_run_stop_reg(hba);
3995 } else {
3996 dev_err(hba->dev,
3997 "Host controller not ready to process requests");
3998 err = -EIO;
3999 goto out;
4002 out:
4003 return err;
4007 * ufshcd_hba_stop - Send controller to reset state
4008 * @hba: per adapter instance
4009 * @can_sleep: perform sleep or just spin
4011 static inline void ufshcd_hba_stop(struct ufs_hba *hba, bool can_sleep)
4013 int err;
4015 ufshcd_writel(hba, CONTROLLER_DISABLE, REG_CONTROLLER_ENABLE);
4016 err = ufshcd_wait_for_register(hba, REG_CONTROLLER_ENABLE,
4017 CONTROLLER_ENABLE, CONTROLLER_DISABLE,
4018 10, 1, can_sleep);
4019 if (err)
4020 dev_err(hba->dev, "%s: Controller disable failed\n", __func__);
4024 * ufshcd_hba_enable - initialize the controller
4025 * @hba: per adapter instance
4027 * The controller resets itself and controller firmware initialization
4028 * sequence kicks off. When controller is ready it will set
4029 * the Host Controller Enable bit to 1.
4031 * Returns 0 on success, non-zero value on failure
4033 static int ufshcd_hba_enable(struct ufs_hba *hba)
4035 int retry;
4038 * msleep of 1 and 5 used in this function might result in msleep(20),
4039 * but it was necessary to send the UFS FPGA to reset mode during
4040 * development and testing of this driver. msleep can be changed to
4041 * mdelay and retry count can be reduced based on the controller.
4043 if (!ufshcd_is_hba_active(hba))
4044 /* change controller state to "reset state" */
4045 ufshcd_hba_stop(hba, true);
4047 /* UniPro link is disabled at this point */
4048 ufshcd_set_link_off(hba);
4050 ufshcd_vops_hce_enable_notify(hba, PRE_CHANGE);
4052 /* start controller initialization sequence */
4053 ufshcd_hba_start(hba);
4056 * To initialize a UFS host controller HCE bit must be set to 1.
4057 * During initialization the HCE bit value changes from 1->0->1.
4058 * When the host controller completes initialization sequence
4059 * it sets the value of HCE bit to 1. The same HCE bit is read back
4060 * to check if the controller has completed initialization sequence.
4061 * So without this delay the value HCE = 1, set in the previous
4062 * instruction might be read back.
4063 * This delay can be changed based on the controller.
4065 msleep(1);
4067 /* wait for the host controller to complete initialization */
4068 retry = 10;
4069 while (ufshcd_is_hba_active(hba)) {
4070 if (retry) {
4071 retry--;
4072 } else {
4073 dev_err(hba->dev,
4074 "Controller enable failed\n");
4075 return -EIO;
4077 msleep(5);
4080 /* enable UIC related interrupts */
4081 ufshcd_enable_intr(hba, UFSHCD_UIC_MASK);
4083 ufshcd_vops_hce_enable_notify(hba, POST_CHANGE);
4085 return 0;
4088 static int ufshcd_disable_tx_lcc(struct ufs_hba *hba, bool peer)
4090 int tx_lanes, i, err = 0;
4092 if (!peer)
4093 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_CONNECTEDTXDATALANES),
4094 &tx_lanes);
4095 else
4096 ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_CONNECTEDTXDATALANES),
4097 &tx_lanes);
4098 for (i = 0; i < tx_lanes; i++) {
4099 if (!peer)
4100 err = ufshcd_dme_set(hba,
4101 UIC_ARG_MIB_SEL(TX_LCC_ENABLE,
4102 UIC_ARG_MPHY_TX_GEN_SEL_INDEX(i)),
4104 else
4105 err = ufshcd_dme_peer_set(hba,
4106 UIC_ARG_MIB_SEL(TX_LCC_ENABLE,
4107 UIC_ARG_MPHY_TX_GEN_SEL_INDEX(i)),
4109 if (err) {
4110 dev_err(hba->dev, "%s: TX LCC Disable failed, peer = %d, lane = %d, err = %d",
4111 __func__, peer, i, err);
4112 break;
4116 return err;
4119 static inline int ufshcd_disable_device_tx_lcc(struct ufs_hba *hba)
4121 return ufshcd_disable_tx_lcc(hba, true);
4125 * ufshcd_link_startup - Initialize unipro link startup
4126 * @hba: per adapter instance
4128 * Returns 0 for success, non-zero in case of failure
4130 static int ufshcd_link_startup(struct ufs_hba *hba)
4132 int ret;
4133 int retries = DME_LINKSTARTUP_RETRIES;
4134 bool link_startup_again = false;
4137 * If UFS device isn't active then we will have to issue link startup
4138 * 2 times to make sure the device state move to active.
4140 if (!ufshcd_is_ufs_dev_active(hba))
4141 link_startup_again = true;
4143 link_startup:
4144 do {
4145 ufshcd_vops_link_startup_notify(hba, PRE_CHANGE);
4147 ret = ufshcd_dme_link_startup(hba);
4149 /* check if device is detected by inter-connect layer */
4150 if (!ret && !ufshcd_is_device_present(hba)) {
4151 dev_err(hba->dev, "%s: Device not present\n", __func__);
4152 ret = -ENXIO;
4153 goto out;
4157 * DME link lost indication is only received when link is up,
4158 * but we can't be sure if the link is up until link startup
4159 * succeeds. So reset the local Uni-Pro and try again.
4161 if (ret && ufshcd_hba_enable(hba))
4162 goto out;
4163 } while (ret && retries--);
4165 if (ret)
4166 /* failed to get the link up... retire */
4167 goto out;
4169 if (link_startup_again) {
4170 link_startup_again = false;
4171 retries = DME_LINKSTARTUP_RETRIES;
4172 goto link_startup;
4175 /* Mark that link is up in PWM-G1, 1-lane, SLOW-AUTO mode */
4176 ufshcd_init_pwr_info(hba);
4177 ufshcd_print_pwr_info(hba);
4179 if (hba->quirks & UFSHCD_QUIRK_BROKEN_LCC) {
4180 ret = ufshcd_disable_device_tx_lcc(hba);
4181 if (ret)
4182 goto out;
4185 /* Include any host controller configuration via UIC commands */
4186 ret = ufshcd_vops_link_startup_notify(hba, POST_CHANGE);
4187 if (ret)
4188 goto out;
4190 ret = ufshcd_make_hba_operational(hba);
4191 out:
4192 if (ret) {
4193 dev_err(hba->dev, "link startup failed %d\n", ret);
4194 ufshcd_print_host_state(hba);
4195 ufshcd_print_pwr_info(hba);
4196 ufshcd_print_host_regs(hba);
4198 return ret;
4202 * ufshcd_verify_dev_init() - Verify device initialization
4203 * @hba: per-adapter instance
4205 * Send NOP OUT UPIU and wait for NOP IN response to check whether the
4206 * device Transport Protocol (UTP) layer is ready after a reset.
4207 * If the UTP layer at the device side is not initialized, it may
4208 * not respond with NOP IN UPIU within timeout of %NOP_OUT_TIMEOUT
4209 * and we retry sending NOP OUT for %NOP_OUT_RETRIES iterations.
4211 static int ufshcd_verify_dev_init(struct ufs_hba *hba)
4213 int err = 0;
4214 int retries;
4216 ufshcd_hold(hba, false);
4217 mutex_lock(&hba->dev_cmd.lock);
4218 for (retries = NOP_OUT_RETRIES; retries > 0; retries--) {
4219 err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_NOP,
4220 NOP_OUT_TIMEOUT);
4222 if (!err || err == -ETIMEDOUT)
4223 break;
4225 dev_dbg(hba->dev, "%s: error %d retrying\n", __func__, err);
4227 mutex_unlock(&hba->dev_cmd.lock);
4228 ufshcd_release(hba);
4230 if (err)
4231 dev_err(hba->dev, "%s: NOP OUT failed %d\n", __func__, err);
4232 return err;
4236 * ufshcd_set_queue_depth - set lun queue depth
4237 * @sdev: pointer to SCSI device
4239 * Read bLUQueueDepth value and activate scsi tagged command
4240 * queueing. For WLUN, queue depth is set to 1. For best-effort
4241 * cases (bLUQueueDepth = 0) the queue depth is set to a maximum
4242 * value that host can queue.
4244 static void ufshcd_set_queue_depth(struct scsi_device *sdev)
4246 int ret = 0;
4247 u8 lun_qdepth;
4248 struct ufs_hba *hba;
4250 hba = shost_priv(sdev->host);
4252 lun_qdepth = hba->nutrs;
4253 ret = ufshcd_read_unit_desc_param(hba,
4254 ufshcd_scsi_to_upiu_lun(sdev->lun),
4255 UNIT_DESC_PARAM_LU_Q_DEPTH,
4256 &lun_qdepth,
4257 sizeof(lun_qdepth));
4259 /* Some WLUN doesn't support unit descriptor */
4260 if (ret == -EOPNOTSUPP)
4261 lun_qdepth = 1;
4262 else if (!lun_qdepth)
4263 /* eventually, we can figure out the real queue depth */
4264 lun_qdepth = hba->nutrs;
4265 else
4266 lun_qdepth = min_t(int, lun_qdepth, hba->nutrs);
4268 dev_dbg(hba->dev, "%s: activate tcq with queue depth %d\n",
4269 __func__, lun_qdepth);
4270 scsi_change_queue_depth(sdev, lun_qdepth);
4274 * ufshcd_get_lu_wp - returns the "b_lu_write_protect" from UNIT DESCRIPTOR
4275 * @hba: per-adapter instance
4276 * @lun: UFS device lun id
4277 * @b_lu_write_protect: pointer to buffer to hold the LU's write protect info
4279 * Returns 0 in case of success and b_lu_write_protect status would be returned
4280 * @b_lu_write_protect parameter.
4281 * Returns -ENOTSUPP if reading b_lu_write_protect is not supported.
4282 * Returns -EINVAL in case of invalid parameters passed to this function.
4284 static int ufshcd_get_lu_wp(struct ufs_hba *hba,
4285 u8 lun,
4286 u8 *b_lu_write_protect)
4288 int ret;
4290 if (!b_lu_write_protect)
4291 ret = -EINVAL;
4293 * According to UFS device spec, RPMB LU can't be write
4294 * protected so skip reading bLUWriteProtect parameter for
4295 * it. For other W-LUs, UNIT DESCRIPTOR is not available.
4297 else if (lun >= UFS_UPIU_MAX_GENERAL_LUN)
4298 ret = -ENOTSUPP;
4299 else
4300 ret = ufshcd_read_unit_desc_param(hba,
4301 lun,
4302 UNIT_DESC_PARAM_LU_WR_PROTECT,
4303 b_lu_write_protect,
4304 sizeof(*b_lu_write_protect));
4305 return ret;
4309 * ufshcd_get_lu_power_on_wp_status - get LU's power on write protect
4310 * status
4311 * @hba: per-adapter instance
4312 * @sdev: pointer to SCSI device
4315 static inline void ufshcd_get_lu_power_on_wp_status(struct ufs_hba *hba,
4316 struct scsi_device *sdev)
4318 if (hba->dev_info.f_power_on_wp_en &&
4319 !hba->dev_info.is_lu_power_on_wp) {
4320 u8 b_lu_write_protect;
4322 if (!ufshcd_get_lu_wp(hba, ufshcd_scsi_to_upiu_lun(sdev->lun),
4323 &b_lu_write_protect) &&
4324 (b_lu_write_protect == UFS_LU_POWER_ON_WP))
4325 hba->dev_info.is_lu_power_on_wp = true;
4330 * ufshcd_slave_alloc - handle initial SCSI device configurations
4331 * @sdev: pointer to SCSI device
4333 * Returns success
4335 static int ufshcd_slave_alloc(struct scsi_device *sdev)
4337 struct ufs_hba *hba;
4339 hba = shost_priv(sdev->host);
4341 /* Mode sense(6) is not supported by UFS, so use Mode sense(10) */
4342 sdev->use_10_for_ms = 1;
4344 /* allow SCSI layer to restart the device in case of errors */
4345 sdev->allow_restart = 1;
4347 /* REPORT SUPPORTED OPERATION CODES is not supported */
4348 sdev->no_report_opcodes = 1;
4351 ufshcd_set_queue_depth(sdev);
4353 ufshcd_get_lu_power_on_wp_status(hba, sdev);
4355 return 0;
4359 * ufshcd_change_queue_depth - change queue depth
4360 * @sdev: pointer to SCSI device
4361 * @depth: required depth to set
4363 * Change queue depth and make sure the max. limits are not crossed.
4365 static int ufshcd_change_queue_depth(struct scsi_device *sdev, int depth)
4367 struct ufs_hba *hba = shost_priv(sdev->host);
4369 if (depth > hba->nutrs)
4370 depth = hba->nutrs;
4371 return scsi_change_queue_depth(sdev, depth);
4375 * ufshcd_slave_configure - adjust SCSI device configurations
4376 * @sdev: pointer to SCSI device
4378 static int ufshcd_slave_configure(struct scsi_device *sdev)
4380 struct request_queue *q = sdev->request_queue;
4382 blk_queue_update_dma_pad(q, PRDT_DATA_BYTE_COUNT_PAD - 1);
4383 blk_queue_max_segment_size(q, PRDT_DATA_BYTE_COUNT_MAX);
4385 return 0;
4389 * ufshcd_slave_destroy - remove SCSI device configurations
4390 * @sdev: pointer to SCSI device
4392 static void ufshcd_slave_destroy(struct scsi_device *sdev)
4394 struct ufs_hba *hba;
4396 hba = shost_priv(sdev->host);
4397 /* Drop the reference as it won't be needed anymore */
4398 if (ufshcd_scsi_to_upiu_lun(sdev->lun) == UFS_UPIU_UFS_DEVICE_WLUN) {
4399 unsigned long flags;
4401 spin_lock_irqsave(hba->host->host_lock, flags);
4402 hba->sdev_ufs_device = NULL;
4403 spin_unlock_irqrestore(hba->host->host_lock, flags);
4408 * ufshcd_task_req_compl - handle task management request completion
4409 * @hba: per adapter instance
4410 * @index: index of the completed request
4411 * @resp: task management service response
4413 * Returns non-zero value on error, zero on success
4415 static int ufshcd_task_req_compl(struct ufs_hba *hba, u32 index, u8 *resp)
4417 struct utp_task_req_desc *task_req_descp;
4418 struct utp_upiu_task_rsp *task_rsp_upiup;
4419 unsigned long flags;
4420 int ocs_value;
4421 int task_result;
4423 spin_lock_irqsave(hba->host->host_lock, flags);
4425 /* Clear completed tasks from outstanding_tasks */
4426 __clear_bit(index, &hba->outstanding_tasks);
4428 task_req_descp = hba->utmrdl_base_addr;
4429 ocs_value = ufshcd_get_tmr_ocs(&task_req_descp[index]);
4431 if (ocs_value == OCS_SUCCESS) {
4432 task_rsp_upiup = (struct utp_upiu_task_rsp *)
4433 task_req_descp[index].task_rsp_upiu;
4434 task_result = be32_to_cpu(task_rsp_upiup->output_param1);
4435 task_result = task_result & MASK_TM_SERVICE_RESP;
4436 if (resp)
4437 *resp = (u8)task_result;
4438 } else {
4439 dev_err(hba->dev, "%s: failed, ocs = 0x%x\n",
4440 __func__, ocs_value);
4442 spin_unlock_irqrestore(hba->host->host_lock, flags);
4444 return ocs_value;
4448 * ufshcd_scsi_cmd_status - Update SCSI command result based on SCSI status
4449 * @lrb: pointer to local reference block of completed command
4450 * @scsi_status: SCSI command status
4452 * Returns value base on SCSI command status
4454 static inline int
4455 ufshcd_scsi_cmd_status(struct ufshcd_lrb *lrbp, int scsi_status)
4457 int result = 0;
4459 switch (scsi_status) {
4460 case SAM_STAT_CHECK_CONDITION:
4461 ufshcd_copy_sense_data(lrbp);
4462 case SAM_STAT_GOOD:
4463 result |= DID_OK << 16 |
4464 COMMAND_COMPLETE << 8 |
4465 scsi_status;
4466 break;
4467 case SAM_STAT_TASK_SET_FULL:
4468 case SAM_STAT_BUSY:
4469 case SAM_STAT_TASK_ABORTED:
4470 ufshcd_copy_sense_data(lrbp);
4471 result |= scsi_status;
4472 break;
4473 default:
4474 result |= DID_ERROR << 16;
4475 break;
4476 } /* end of switch */
4478 return result;
4482 * ufshcd_transfer_rsp_status - Get overall status of the response
4483 * @hba: per adapter instance
4484 * @lrb: pointer to local reference block of completed command
4486 * Returns result of the command to notify SCSI midlayer
4488 static inline int
4489 ufshcd_transfer_rsp_status(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
4491 int result = 0;
4492 int scsi_status;
4493 int ocs;
4495 /* overall command status of utrd */
4496 ocs = ufshcd_get_tr_ocs(lrbp);
4498 switch (ocs) {
4499 case OCS_SUCCESS:
4500 result = ufshcd_get_req_rsp(lrbp->ucd_rsp_ptr);
4501 hba->ufs_stats.last_hibern8_exit_tstamp = ktime_set(0, 0);
4502 switch (result) {
4503 case UPIU_TRANSACTION_RESPONSE:
4505 * get the response UPIU result to extract
4506 * the SCSI command status
4508 result = ufshcd_get_rsp_upiu_result(lrbp->ucd_rsp_ptr);
4511 * get the result based on SCSI status response
4512 * to notify the SCSI midlayer of the command status
4514 scsi_status = result & MASK_SCSI_STATUS;
4515 result = ufshcd_scsi_cmd_status(lrbp, scsi_status);
4518 * Currently we are only supporting BKOPs exception
4519 * events hence we can ignore BKOPs exception event
4520 * during power management callbacks. BKOPs exception
4521 * event is not expected to be raised in runtime suspend
4522 * callback as it allows the urgent bkops.
4523 * During system suspend, we are anyway forcefully
4524 * disabling the bkops and if urgent bkops is needed
4525 * it will be enabled on system resume. Long term
4526 * solution could be to abort the system suspend if
4527 * UFS device needs urgent BKOPs.
4529 if (!hba->pm_op_in_progress &&
4530 ufshcd_is_exception_event(lrbp->ucd_rsp_ptr))
4531 schedule_work(&hba->eeh_work);
4532 break;
4533 case UPIU_TRANSACTION_REJECT_UPIU:
4534 /* TODO: handle Reject UPIU Response */
4535 result = DID_ERROR << 16;
4536 dev_err(hba->dev,
4537 "Reject UPIU not fully implemented\n");
4538 break;
4539 default:
4540 result = DID_ERROR << 16;
4541 dev_err(hba->dev,
4542 "Unexpected request response code = %x\n",
4543 result);
4544 break;
4546 break;
4547 case OCS_ABORTED:
4548 result |= DID_ABORT << 16;
4549 break;
4550 case OCS_INVALID_COMMAND_STATUS:
4551 result |= DID_REQUEUE << 16;
4552 break;
4553 case OCS_INVALID_CMD_TABLE_ATTR:
4554 case OCS_INVALID_PRDT_ATTR:
4555 case OCS_MISMATCH_DATA_BUF_SIZE:
4556 case OCS_MISMATCH_RESP_UPIU_SIZE:
4557 case OCS_PEER_COMM_FAILURE:
4558 case OCS_FATAL_ERROR:
4559 default:
4560 result |= DID_ERROR << 16;
4561 dev_err(hba->dev,
4562 "OCS error from controller = %x for tag %d\n",
4563 ocs, lrbp->task_tag);
4564 ufshcd_print_host_regs(hba);
4565 ufshcd_print_host_state(hba);
4566 break;
4567 } /* end of switch */
4569 if (host_byte(result) != DID_OK)
4570 ufshcd_print_trs(hba, 1 << lrbp->task_tag, true);
4571 return result;
4575 * ufshcd_uic_cmd_compl - handle completion of uic command
4576 * @hba: per adapter instance
4577 * @intr_status: interrupt status generated by the controller
4579 static void ufshcd_uic_cmd_compl(struct ufs_hba *hba, u32 intr_status)
4581 if ((intr_status & UIC_COMMAND_COMPL) && hba->active_uic_cmd) {
4582 hba->active_uic_cmd->argument2 |=
4583 ufshcd_get_uic_cmd_result(hba);
4584 hba->active_uic_cmd->argument3 =
4585 ufshcd_get_dme_attr_val(hba);
4586 complete(&hba->active_uic_cmd->done);
4589 if ((intr_status & UFSHCD_UIC_PWR_MASK) && hba->uic_async_done)
4590 complete(hba->uic_async_done);
4594 * __ufshcd_transfer_req_compl - handle SCSI and query command completion
4595 * @hba: per adapter instance
4596 * @completed_reqs: requests to complete
4598 static void __ufshcd_transfer_req_compl(struct ufs_hba *hba,
4599 unsigned long completed_reqs)
4601 struct ufshcd_lrb *lrbp;
4602 struct scsi_cmnd *cmd;
4603 int result;
4604 int index;
4606 for_each_set_bit(index, &completed_reqs, hba->nutrs) {
4607 lrbp = &hba->lrb[index];
4608 cmd = lrbp->cmd;
4609 if (cmd) {
4610 ufshcd_add_command_trace(hba, index, "complete");
4611 result = ufshcd_transfer_rsp_status(hba, lrbp);
4612 scsi_dma_unmap(cmd);
4613 cmd->result = result;
4614 /* Mark completed command as NULL in LRB */
4615 lrbp->cmd = NULL;
4616 clear_bit_unlock(index, &hba->lrb_in_use);
4617 /* Do not touch lrbp after scsi done */
4618 cmd->scsi_done(cmd);
4619 __ufshcd_release(hba);
4620 } else if (lrbp->command_type == UTP_CMD_TYPE_DEV_MANAGE ||
4621 lrbp->command_type == UTP_CMD_TYPE_UFS_STORAGE) {
4622 if (hba->dev_cmd.complete) {
4623 ufshcd_add_command_trace(hba, index,
4624 "dev_complete");
4625 complete(hba->dev_cmd.complete);
4628 if (ufshcd_is_clkscaling_supported(hba))
4629 hba->clk_scaling.active_reqs--;
4632 /* clear corresponding bits of completed commands */
4633 hba->outstanding_reqs ^= completed_reqs;
4635 ufshcd_clk_scaling_update_busy(hba);
4637 /* we might have free'd some tags above */
4638 wake_up(&hba->dev_cmd.tag_wq);
4642 * ufshcd_transfer_req_compl - handle SCSI and query command completion
4643 * @hba: per adapter instance
4645 static void ufshcd_transfer_req_compl(struct ufs_hba *hba)
4647 unsigned long completed_reqs;
4648 u32 tr_doorbell;
4650 /* Resetting interrupt aggregation counters first and reading the
4651 * DOOR_BELL afterward allows us to handle all the completed requests.
4652 * In order to prevent other interrupts starvation the DB is read once
4653 * after reset. The down side of this solution is the possibility of
4654 * false interrupt if device completes another request after resetting
4655 * aggregation and before reading the DB.
4657 if (ufshcd_is_intr_aggr_allowed(hba))
4658 ufshcd_reset_intr_aggr(hba);
4660 tr_doorbell = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
4661 completed_reqs = tr_doorbell ^ hba->outstanding_reqs;
4663 __ufshcd_transfer_req_compl(hba, completed_reqs);
4667 * ufshcd_disable_ee - disable exception event
4668 * @hba: per-adapter instance
4669 * @mask: exception event to disable
4671 * Disables exception event in the device so that the EVENT_ALERT
4672 * bit is not set.
4674 * Returns zero on success, non-zero error value on failure.
4676 static int ufshcd_disable_ee(struct ufs_hba *hba, u16 mask)
4678 int err = 0;
4679 u32 val;
4681 if (!(hba->ee_ctrl_mask & mask))
4682 goto out;
4684 val = hba->ee_ctrl_mask & ~mask;
4685 val &= MASK_EE_STATUS;
4686 err = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_WRITE_ATTR,
4687 QUERY_ATTR_IDN_EE_CONTROL, 0, 0, &val);
4688 if (!err)
4689 hba->ee_ctrl_mask &= ~mask;
4690 out:
4691 return err;
4695 * ufshcd_enable_ee - enable exception event
4696 * @hba: per-adapter instance
4697 * @mask: exception event to enable
4699 * Enable corresponding exception event in the device to allow
4700 * device to alert host in critical scenarios.
4702 * Returns zero on success, non-zero error value on failure.
4704 static int ufshcd_enable_ee(struct ufs_hba *hba, u16 mask)
4706 int err = 0;
4707 u32 val;
4709 if (hba->ee_ctrl_mask & mask)
4710 goto out;
4712 val = hba->ee_ctrl_mask | mask;
4713 val &= MASK_EE_STATUS;
4714 err = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_WRITE_ATTR,
4715 QUERY_ATTR_IDN_EE_CONTROL, 0, 0, &val);
4716 if (!err)
4717 hba->ee_ctrl_mask |= mask;
4718 out:
4719 return err;
4723 * ufshcd_enable_auto_bkops - Allow device managed BKOPS
4724 * @hba: per-adapter instance
4726 * Allow device to manage background operations on its own. Enabling
4727 * this might lead to inconsistent latencies during normal data transfers
4728 * as the device is allowed to manage its own way of handling background
4729 * operations.
4731 * Returns zero on success, non-zero on failure.
4733 static int ufshcd_enable_auto_bkops(struct ufs_hba *hba)
4735 int err = 0;
4737 if (hba->auto_bkops_enabled)
4738 goto out;
4740 err = ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_SET_FLAG,
4741 QUERY_FLAG_IDN_BKOPS_EN, NULL);
4742 if (err) {
4743 dev_err(hba->dev, "%s: failed to enable bkops %d\n",
4744 __func__, err);
4745 goto out;
4748 hba->auto_bkops_enabled = true;
4749 trace_ufshcd_auto_bkops_state(dev_name(hba->dev), "Enabled");
4751 /* No need of URGENT_BKOPS exception from the device */
4752 err = ufshcd_disable_ee(hba, MASK_EE_URGENT_BKOPS);
4753 if (err)
4754 dev_err(hba->dev, "%s: failed to disable exception event %d\n",
4755 __func__, err);
4756 out:
4757 return err;
4761 * ufshcd_disable_auto_bkops - block device in doing background operations
4762 * @hba: per-adapter instance
4764 * Disabling background operations improves command response latency but
4765 * has drawback of device moving into critical state where the device is
4766 * not-operable. Make sure to call ufshcd_enable_auto_bkops() whenever the
4767 * host is idle so that BKOPS are managed effectively without any negative
4768 * impacts.
4770 * Returns zero on success, non-zero on failure.
4772 static int ufshcd_disable_auto_bkops(struct ufs_hba *hba)
4774 int err = 0;
4776 if (!hba->auto_bkops_enabled)
4777 goto out;
4780 * If host assisted BKOPs is to be enabled, make sure
4781 * urgent bkops exception is allowed.
4783 err = ufshcd_enable_ee(hba, MASK_EE_URGENT_BKOPS);
4784 if (err) {
4785 dev_err(hba->dev, "%s: failed to enable exception event %d\n",
4786 __func__, err);
4787 goto out;
4790 err = ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_CLEAR_FLAG,
4791 QUERY_FLAG_IDN_BKOPS_EN, NULL);
4792 if (err) {
4793 dev_err(hba->dev, "%s: failed to disable bkops %d\n",
4794 __func__, err);
4795 ufshcd_disable_ee(hba, MASK_EE_URGENT_BKOPS);
4796 goto out;
4799 hba->auto_bkops_enabled = false;
4800 trace_ufshcd_auto_bkops_state(dev_name(hba->dev), "Disabled");
4801 out:
4802 return err;
4806 * ufshcd_force_reset_auto_bkops - force reset auto bkops state
4807 * @hba: per adapter instance
4809 * After a device reset the device may toggle the BKOPS_EN flag
4810 * to default value. The s/w tracking variables should be updated
4811 * as well. This function would change the auto-bkops state based on
4812 * UFSHCD_CAP_KEEP_AUTO_BKOPS_ENABLED_EXCEPT_SUSPEND.
4814 static void ufshcd_force_reset_auto_bkops(struct ufs_hba *hba)
4816 if (ufshcd_keep_autobkops_enabled_except_suspend(hba)) {
4817 hba->auto_bkops_enabled = false;
4818 hba->ee_ctrl_mask |= MASK_EE_URGENT_BKOPS;
4819 ufshcd_enable_auto_bkops(hba);
4820 } else {
4821 hba->auto_bkops_enabled = true;
4822 hba->ee_ctrl_mask &= ~MASK_EE_URGENT_BKOPS;
4823 ufshcd_disable_auto_bkops(hba);
4827 static inline int ufshcd_get_bkops_status(struct ufs_hba *hba, u32 *status)
4829 return ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
4830 QUERY_ATTR_IDN_BKOPS_STATUS, 0, 0, status);
4834 * ufshcd_bkops_ctrl - control the auto bkops based on current bkops status
4835 * @hba: per-adapter instance
4836 * @status: bkops_status value
4838 * Read the bkops_status from the UFS device and Enable fBackgroundOpsEn
4839 * flag in the device to permit background operations if the device
4840 * bkops_status is greater than or equal to "status" argument passed to
4841 * this function, disable otherwise.
4843 * Returns 0 for success, non-zero in case of failure.
4845 * NOTE: Caller of this function can check the "hba->auto_bkops_enabled" flag
4846 * to know whether auto bkops is enabled or disabled after this function
4847 * returns control to it.
4849 static int ufshcd_bkops_ctrl(struct ufs_hba *hba,
4850 enum bkops_status status)
4852 int err;
4853 u32 curr_status = 0;
4855 err = ufshcd_get_bkops_status(hba, &curr_status);
4856 if (err) {
4857 dev_err(hba->dev, "%s: failed to get BKOPS status %d\n",
4858 __func__, err);
4859 goto out;
4860 } else if (curr_status > BKOPS_STATUS_MAX) {
4861 dev_err(hba->dev, "%s: invalid BKOPS status %d\n",
4862 __func__, curr_status);
4863 err = -EINVAL;
4864 goto out;
4867 if (curr_status >= status)
4868 err = ufshcd_enable_auto_bkops(hba);
4869 else
4870 err = ufshcd_disable_auto_bkops(hba);
4871 out:
4872 return err;
4876 * ufshcd_urgent_bkops - handle urgent bkops exception event
4877 * @hba: per-adapter instance
4879 * Enable fBackgroundOpsEn flag in the device to permit background
4880 * operations.
4882 * If BKOPs is enabled, this function returns 0, 1 if the bkops in not enabled
4883 * and negative error value for any other failure.
4885 static int ufshcd_urgent_bkops(struct ufs_hba *hba)
4887 return ufshcd_bkops_ctrl(hba, hba->urgent_bkops_lvl);
4890 static inline int ufshcd_get_ee_status(struct ufs_hba *hba, u32 *status)
4892 return ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
4893 QUERY_ATTR_IDN_EE_STATUS, 0, 0, status);
4896 static void ufshcd_bkops_exception_event_handler(struct ufs_hba *hba)
4898 int err;
4899 u32 curr_status = 0;
4901 if (hba->is_urgent_bkops_lvl_checked)
4902 goto enable_auto_bkops;
4904 err = ufshcd_get_bkops_status(hba, &curr_status);
4905 if (err) {
4906 dev_err(hba->dev, "%s: failed to get BKOPS status %d\n",
4907 __func__, err);
4908 goto out;
4912 * We are seeing that some devices are raising the urgent bkops
4913 * exception events even when BKOPS status doesn't indicate performace
4914 * impacted or critical. Handle these device by determining their urgent
4915 * bkops status at runtime.
4917 if (curr_status < BKOPS_STATUS_PERF_IMPACT) {
4918 dev_err(hba->dev, "%s: device raised urgent BKOPS exception for bkops status %d\n",
4919 __func__, curr_status);
4920 /* update the current status as the urgent bkops level */
4921 hba->urgent_bkops_lvl = curr_status;
4922 hba->is_urgent_bkops_lvl_checked = true;
4925 enable_auto_bkops:
4926 err = ufshcd_enable_auto_bkops(hba);
4927 out:
4928 if (err < 0)
4929 dev_err(hba->dev, "%s: failed to handle urgent bkops %d\n",
4930 __func__, err);
4934 * ufshcd_exception_event_handler - handle exceptions raised by device
4935 * @work: pointer to work data
4937 * Read bExceptionEventStatus attribute from the device and handle the
4938 * exception event accordingly.
4940 static void ufshcd_exception_event_handler(struct work_struct *work)
4942 struct ufs_hba *hba;
4943 int err;
4944 u32 status = 0;
4945 hba = container_of(work, struct ufs_hba, eeh_work);
4947 pm_runtime_get_sync(hba->dev);
4948 err = ufshcd_get_ee_status(hba, &status);
4949 if (err) {
4950 dev_err(hba->dev, "%s: failed to get exception status %d\n",
4951 __func__, err);
4952 goto out;
4955 status &= hba->ee_ctrl_mask;
4957 if (status & MASK_EE_URGENT_BKOPS)
4958 ufshcd_bkops_exception_event_handler(hba);
4960 out:
4961 pm_runtime_put_sync(hba->dev);
4962 return;
4965 /* Complete requests that have door-bell cleared */
4966 static void ufshcd_complete_requests(struct ufs_hba *hba)
4968 ufshcd_transfer_req_compl(hba);
4969 ufshcd_tmc_handler(hba);
4973 * ufshcd_quirk_dl_nac_errors - This function checks if error handling is
4974 * to recover from the DL NAC errors or not.
4975 * @hba: per-adapter instance
4977 * Returns true if error handling is required, false otherwise
4979 static bool ufshcd_quirk_dl_nac_errors(struct ufs_hba *hba)
4981 unsigned long flags;
4982 bool err_handling = true;
4984 spin_lock_irqsave(hba->host->host_lock, flags);
4986 * UFS_DEVICE_QUIRK_RECOVERY_FROM_DL_NAC_ERRORS only workaround the
4987 * device fatal error and/or DL NAC & REPLAY timeout errors.
4989 if (hba->saved_err & (CONTROLLER_FATAL_ERROR | SYSTEM_BUS_FATAL_ERROR))
4990 goto out;
4992 if ((hba->saved_err & DEVICE_FATAL_ERROR) ||
4993 ((hba->saved_err & UIC_ERROR) &&
4994 (hba->saved_uic_err & UFSHCD_UIC_DL_TCx_REPLAY_ERROR)))
4995 goto out;
4997 if ((hba->saved_err & UIC_ERROR) &&
4998 (hba->saved_uic_err & UFSHCD_UIC_DL_NAC_RECEIVED_ERROR)) {
4999 int err;
5001 * wait for 50ms to see if we can get any other errors or not.
5003 spin_unlock_irqrestore(hba->host->host_lock, flags);
5004 msleep(50);
5005 spin_lock_irqsave(hba->host->host_lock, flags);
5008 * now check if we have got any other severe errors other than
5009 * DL NAC error?
5011 if ((hba->saved_err & INT_FATAL_ERRORS) ||
5012 ((hba->saved_err & UIC_ERROR) &&
5013 (hba->saved_uic_err & ~UFSHCD_UIC_DL_NAC_RECEIVED_ERROR)))
5014 goto out;
5017 * As DL NAC is the only error received so far, send out NOP
5018 * command to confirm if link is still active or not.
5019 * - If we don't get any response then do error recovery.
5020 * - If we get response then clear the DL NAC error bit.
5023 spin_unlock_irqrestore(hba->host->host_lock, flags);
5024 err = ufshcd_verify_dev_init(hba);
5025 spin_lock_irqsave(hba->host->host_lock, flags);
5027 if (err)
5028 goto out;
5030 /* Link seems to be alive hence ignore the DL NAC errors */
5031 if (hba->saved_uic_err == UFSHCD_UIC_DL_NAC_RECEIVED_ERROR)
5032 hba->saved_err &= ~UIC_ERROR;
5033 /* clear NAC error */
5034 hba->saved_uic_err &= ~UFSHCD_UIC_DL_NAC_RECEIVED_ERROR;
5035 if (!hba->saved_uic_err) {
5036 err_handling = false;
5037 goto out;
5040 out:
5041 spin_unlock_irqrestore(hba->host->host_lock, flags);
5042 return err_handling;
5046 * ufshcd_err_handler - handle UFS errors that require s/w attention
5047 * @work: pointer to work structure
5049 static void ufshcd_err_handler(struct work_struct *work)
5051 struct ufs_hba *hba;
5052 unsigned long flags;
5053 u32 err_xfer = 0;
5054 u32 err_tm = 0;
5055 int err = 0;
5056 int tag;
5057 bool needs_reset = false;
5059 hba = container_of(work, struct ufs_hba, eh_work);
5061 pm_runtime_get_sync(hba->dev);
5062 ufshcd_hold(hba, false);
5064 spin_lock_irqsave(hba->host->host_lock, flags);
5065 if (hba->ufshcd_state == UFSHCD_STATE_RESET)
5066 goto out;
5068 hba->ufshcd_state = UFSHCD_STATE_RESET;
5069 ufshcd_set_eh_in_progress(hba);
5071 /* Complete requests that have door-bell cleared by h/w */
5072 ufshcd_complete_requests(hba);
5074 if (hba->dev_quirks & UFS_DEVICE_QUIRK_RECOVERY_FROM_DL_NAC_ERRORS) {
5075 bool ret;
5077 spin_unlock_irqrestore(hba->host->host_lock, flags);
5078 /* release the lock as ufshcd_quirk_dl_nac_errors() may sleep */
5079 ret = ufshcd_quirk_dl_nac_errors(hba);
5080 spin_lock_irqsave(hba->host->host_lock, flags);
5081 if (!ret)
5082 goto skip_err_handling;
5084 if ((hba->saved_err & INT_FATAL_ERRORS) ||
5085 ((hba->saved_err & UIC_ERROR) &&
5086 (hba->saved_uic_err & (UFSHCD_UIC_DL_PA_INIT_ERROR |
5087 UFSHCD_UIC_DL_NAC_RECEIVED_ERROR |
5088 UFSHCD_UIC_DL_TCx_REPLAY_ERROR))))
5089 needs_reset = true;
5092 * if host reset is required then skip clearing the pending
5093 * transfers forcefully because they will automatically get
5094 * cleared after link startup.
5096 if (needs_reset)
5097 goto skip_pending_xfer_clear;
5099 /* release lock as clear command might sleep */
5100 spin_unlock_irqrestore(hba->host->host_lock, flags);
5101 /* Clear pending transfer requests */
5102 for_each_set_bit(tag, &hba->outstanding_reqs, hba->nutrs) {
5103 if (ufshcd_clear_cmd(hba, tag)) {
5104 err_xfer = true;
5105 goto lock_skip_pending_xfer_clear;
5109 /* Clear pending task management requests */
5110 for_each_set_bit(tag, &hba->outstanding_tasks, hba->nutmrs) {
5111 if (ufshcd_clear_tm_cmd(hba, tag)) {
5112 err_tm = true;
5113 goto lock_skip_pending_xfer_clear;
5117 lock_skip_pending_xfer_clear:
5118 spin_lock_irqsave(hba->host->host_lock, flags);
5120 /* Complete the requests that are cleared by s/w */
5121 ufshcd_complete_requests(hba);
5123 if (err_xfer || err_tm)
5124 needs_reset = true;
5126 skip_pending_xfer_clear:
5127 /* Fatal errors need reset */
5128 if (needs_reset) {
5129 unsigned long max_doorbells = (1UL << hba->nutrs) - 1;
5132 * ufshcd_reset_and_restore() does the link reinitialization
5133 * which will need atleast one empty doorbell slot to send the
5134 * device management commands (NOP and query commands).
5135 * If there is no slot empty at this moment then free up last
5136 * slot forcefully.
5138 if (hba->outstanding_reqs == max_doorbells)
5139 __ufshcd_transfer_req_compl(hba,
5140 (1UL << (hba->nutrs - 1)));
5142 spin_unlock_irqrestore(hba->host->host_lock, flags);
5143 err = ufshcd_reset_and_restore(hba);
5144 spin_lock_irqsave(hba->host->host_lock, flags);
5145 if (err) {
5146 dev_err(hba->dev, "%s: reset and restore failed\n",
5147 __func__);
5148 hba->ufshcd_state = UFSHCD_STATE_ERROR;
5151 * Inform scsi mid-layer that we did reset and allow to handle
5152 * Unit Attention properly.
5154 scsi_report_bus_reset(hba->host, 0);
5155 hba->saved_err = 0;
5156 hba->saved_uic_err = 0;
5159 skip_err_handling:
5160 if (!needs_reset) {
5161 hba->ufshcd_state = UFSHCD_STATE_OPERATIONAL;
5162 if (hba->saved_err || hba->saved_uic_err)
5163 dev_err_ratelimited(hba->dev, "%s: exit: saved_err 0x%x saved_uic_err 0x%x",
5164 __func__, hba->saved_err, hba->saved_uic_err);
5167 ufshcd_clear_eh_in_progress(hba);
5169 out:
5170 spin_unlock_irqrestore(hba->host->host_lock, flags);
5171 scsi_unblock_requests(hba->host);
5172 ufshcd_release(hba);
5173 pm_runtime_put_sync(hba->dev);
5176 static void ufshcd_update_uic_reg_hist(struct ufs_uic_err_reg_hist *reg_hist,
5177 u32 reg)
5179 reg_hist->reg[reg_hist->pos] = reg;
5180 reg_hist->tstamp[reg_hist->pos] = ktime_get();
5181 reg_hist->pos = (reg_hist->pos + 1) % UIC_ERR_REG_HIST_LENGTH;
5185 * ufshcd_update_uic_error - check and set fatal UIC error flags.
5186 * @hba: per-adapter instance
5188 static void ufshcd_update_uic_error(struct ufs_hba *hba)
5190 u32 reg;
5192 /* PHY layer lane error */
5193 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_PHY_ADAPTER_LAYER);
5194 /* Ignore LINERESET indication, as this is not an error */
5195 if ((reg & UIC_PHY_ADAPTER_LAYER_ERROR) &&
5196 (reg & UIC_PHY_ADAPTER_LAYER_LANE_ERR_MASK)) {
5198 * To know whether this error is fatal or not, DB timeout
5199 * must be checked but this error is handled separately.
5201 dev_dbg(hba->dev, "%s: UIC Lane error reported\n", __func__);
5202 ufshcd_update_uic_reg_hist(&hba->ufs_stats.pa_err, reg);
5205 /* PA_INIT_ERROR is fatal and needs UIC reset */
5206 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_DATA_LINK_LAYER);
5207 if (reg)
5208 ufshcd_update_uic_reg_hist(&hba->ufs_stats.dl_err, reg);
5210 if (reg & UIC_DATA_LINK_LAYER_ERROR_PA_INIT)
5211 hba->uic_error |= UFSHCD_UIC_DL_PA_INIT_ERROR;
5212 else if (hba->dev_quirks &
5213 UFS_DEVICE_QUIRK_RECOVERY_FROM_DL_NAC_ERRORS) {
5214 if (reg & UIC_DATA_LINK_LAYER_ERROR_NAC_RECEIVED)
5215 hba->uic_error |=
5216 UFSHCD_UIC_DL_NAC_RECEIVED_ERROR;
5217 else if (reg & UIC_DATA_LINK_LAYER_ERROR_TCx_REPLAY_TIMEOUT)
5218 hba->uic_error |= UFSHCD_UIC_DL_TCx_REPLAY_ERROR;
5221 /* UIC NL/TL/DME errors needs software retry */
5222 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_NETWORK_LAYER);
5223 if (reg) {
5224 ufshcd_update_uic_reg_hist(&hba->ufs_stats.nl_err, reg);
5225 hba->uic_error |= UFSHCD_UIC_NL_ERROR;
5228 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_TRANSPORT_LAYER);
5229 if (reg) {
5230 ufshcd_update_uic_reg_hist(&hba->ufs_stats.tl_err, reg);
5231 hba->uic_error |= UFSHCD_UIC_TL_ERROR;
5234 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_DME);
5235 if (reg) {
5236 ufshcd_update_uic_reg_hist(&hba->ufs_stats.dme_err, reg);
5237 hba->uic_error |= UFSHCD_UIC_DME_ERROR;
5240 dev_dbg(hba->dev, "%s: UIC error flags = 0x%08x\n",
5241 __func__, hba->uic_error);
5245 * ufshcd_check_errors - Check for errors that need s/w attention
5246 * @hba: per-adapter instance
5248 static void ufshcd_check_errors(struct ufs_hba *hba)
5250 bool queue_eh_work = false;
5252 if (hba->errors & INT_FATAL_ERRORS)
5253 queue_eh_work = true;
5255 if (hba->errors & UIC_ERROR) {
5256 hba->uic_error = 0;
5257 ufshcd_update_uic_error(hba);
5258 if (hba->uic_error)
5259 queue_eh_work = true;
5262 if (queue_eh_work) {
5264 * update the transfer error masks to sticky bits, let's do this
5265 * irrespective of current ufshcd_state.
5267 hba->saved_err |= hba->errors;
5268 hba->saved_uic_err |= hba->uic_error;
5270 /* handle fatal errors only when link is functional */
5271 if (hba->ufshcd_state == UFSHCD_STATE_OPERATIONAL) {
5272 /* block commands from scsi mid-layer */
5273 scsi_block_requests(hba->host);
5275 hba->ufshcd_state = UFSHCD_STATE_EH_SCHEDULED;
5277 /* dump controller state before resetting */
5278 if (hba->saved_err & (INT_FATAL_ERRORS | UIC_ERROR)) {
5279 bool pr_prdt = !!(hba->saved_err &
5280 SYSTEM_BUS_FATAL_ERROR);
5282 dev_err(hba->dev, "%s: saved_err 0x%x saved_uic_err 0x%x\n",
5283 __func__, hba->saved_err,
5284 hba->saved_uic_err);
5286 ufshcd_print_host_regs(hba);
5287 ufshcd_print_pwr_info(hba);
5288 ufshcd_print_tmrs(hba, hba->outstanding_tasks);
5289 ufshcd_print_trs(hba, hba->outstanding_reqs,
5290 pr_prdt);
5292 schedule_work(&hba->eh_work);
5296 * if (!queue_eh_work) -
5297 * Other errors are either non-fatal where host recovers
5298 * itself without s/w intervention or errors that will be
5299 * handled by the SCSI core layer.
5304 * ufshcd_tmc_handler - handle task management function completion
5305 * @hba: per adapter instance
5307 static void ufshcd_tmc_handler(struct ufs_hba *hba)
5309 u32 tm_doorbell;
5311 tm_doorbell = ufshcd_readl(hba, REG_UTP_TASK_REQ_DOOR_BELL);
5312 hba->tm_condition = tm_doorbell ^ hba->outstanding_tasks;
5313 wake_up(&hba->tm_wq);
5317 * ufshcd_sl_intr - Interrupt service routine
5318 * @hba: per adapter instance
5319 * @intr_status: contains interrupts generated by the controller
5321 static void ufshcd_sl_intr(struct ufs_hba *hba, u32 intr_status)
5323 hba->errors = UFSHCD_ERROR_MASK & intr_status;
5324 if (hba->errors)
5325 ufshcd_check_errors(hba);
5327 if (intr_status & UFSHCD_UIC_MASK)
5328 ufshcd_uic_cmd_compl(hba, intr_status);
5330 if (intr_status & UTP_TASK_REQ_COMPL)
5331 ufshcd_tmc_handler(hba);
5333 if (intr_status & UTP_TRANSFER_REQ_COMPL)
5334 ufshcd_transfer_req_compl(hba);
5338 * ufshcd_intr - Main interrupt service routine
5339 * @irq: irq number
5340 * @__hba: pointer to adapter instance
5342 * Returns IRQ_HANDLED - If interrupt is valid
5343 * IRQ_NONE - If invalid interrupt
5345 static irqreturn_t ufshcd_intr(int irq, void *__hba)
5347 u32 intr_status, enabled_intr_status;
5348 irqreturn_t retval = IRQ_NONE;
5349 struct ufs_hba *hba = __hba;
5351 spin_lock(hba->host->host_lock);
5352 intr_status = ufshcd_readl(hba, REG_INTERRUPT_STATUS);
5353 enabled_intr_status =
5354 intr_status & ufshcd_readl(hba, REG_INTERRUPT_ENABLE);
5356 if (intr_status)
5357 ufshcd_writel(hba, intr_status, REG_INTERRUPT_STATUS);
5359 if (enabled_intr_status) {
5360 ufshcd_sl_intr(hba, enabled_intr_status);
5361 retval = IRQ_HANDLED;
5363 spin_unlock(hba->host->host_lock);
5364 return retval;
5367 static int ufshcd_clear_tm_cmd(struct ufs_hba *hba, int tag)
5369 int err = 0;
5370 u32 mask = 1 << tag;
5371 unsigned long flags;
5373 if (!test_bit(tag, &hba->outstanding_tasks))
5374 goto out;
5376 spin_lock_irqsave(hba->host->host_lock, flags);
5377 ufshcd_writel(hba, ~(1 << tag), REG_UTP_TASK_REQ_LIST_CLEAR);
5378 spin_unlock_irqrestore(hba->host->host_lock, flags);
5380 /* poll for max. 1 sec to clear door bell register by h/w */
5381 err = ufshcd_wait_for_register(hba,
5382 REG_UTP_TASK_REQ_DOOR_BELL,
5383 mask, 0, 1000, 1000, true);
5384 out:
5385 return err;
5389 * ufshcd_issue_tm_cmd - issues task management commands to controller
5390 * @hba: per adapter instance
5391 * @lun_id: LUN ID to which TM command is sent
5392 * @task_id: task ID to which the TM command is applicable
5393 * @tm_function: task management function opcode
5394 * @tm_response: task management service response return value
5396 * Returns non-zero value on error, zero on success.
5398 static int ufshcd_issue_tm_cmd(struct ufs_hba *hba, int lun_id, int task_id,
5399 u8 tm_function, u8 *tm_response)
5401 struct utp_task_req_desc *task_req_descp;
5402 struct utp_upiu_task_req *task_req_upiup;
5403 struct Scsi_Host *host;
5404 unsigned long flags;
5405 int free_slot;
5406 int err;
5407 int task_tag;
5409 host = hba->host;
5412 * Get free slot, sleep if slots are unavailable.
5413 * Even though we use wait_event() which sleeps indefinitely,
5414 * the maximum wait time is bounded by %TM_CMD_TIMEOUT.
5416 wait_event(hba->tm_tag_wq, ufshcd_get_tm_free_slot(hba, &free_slot));
5417 ufshcd_hold(hba, false);
5419 spin_lock_irqsave(host->host_lock, flags);
5420 task_req_descp = hba->utmrdl_base_addr;
5421 task_req_descp += free_slot;
5423 /* Configure task request descriptor */
5424 task_req_descp->header.dword_0 = cpu_to_le32(UTP_REQ_DESC_INT_CMD);
5425 task_req_descp->header.dword_2 =
5426 cpu_to_le32(OCS_INVALID_COMMAND_STATUS);
5428 /* Configure task request UPIU */
5429 task_req_upiup =
5430 (struct utp_upiu_task_req *) task_req_descp->task_req_upiu;
5431 task_tag = hba->nutrs + free_slot;
5432 task_req_upiup->header.dword_0 =
5433 UPIU_HEADER_DWORD(UPIU_TRANSACTION_TASK_REQ, 0,
5434 lun_id, task_tag);
5435 task_req_upiup->header.dword_1 =
5436 UPIU_HEADER_DWORD(0, tm_function, 0, 0);
5438 * The host shall provide the same value for LUN field in the basic
5439 * header and for Input Parameter.
5441 task_req_upiup->input_param1 = cpu_to_be32(lun_id);
5442 task_req_upiup->input_param2 = cpu_to_be32(task_id);
5444 ufshcd_vops_setup_task_mgmt(hba, free_slot, tm_function);
5446 /* send command to the controller */
5447 __set_bit(free_slot, &hba->outstanding_tasks);
5449 /* Make sure descriptors are ready before ringing the task doorbell */
5450 wmb();
5452 ufshcd_writel(hba, 1 << free_slot, REG_UTP_TASK_REQ_DOOR_BELL);
5453 /* Make sure that doorbell is committed immediately */
5454 wmb();
5456 spin_unlock_irqrestore(host->host_lock, flags);
5458 /* wait until the task management command is completed */
5459 err = wait_event_timeout(hba->tm_wq,
5460 test_bit(free_slot, &hba->tm_condition),
5461 msecs_to_jiffies(TM_CMD_TIMEOUT));
5462 if (!err) {
5463 dev_err(hba->dev, "%s: task management cmd 0x%.2x timed-out\n",
5464 __func__, tm_function);
5465 if (ufshcd_clear_tm_cmd(hba, free_slot))
5466 dev_WARN(hba->dev, "%s: unable clear tm cmd (slot %d) after timeout\n",
5467 __func__, free_slot);
5468 err = -ETIMEDOUT;
5469 } else {
5470 err = ufshcd_task_req_compl(hba, free_slot, tm_response);
5473 clear_bit(free_slot, &hba->tm_condition);
5474 ufshcd_put_tm_slot(hba, free_slot);
5475 wake_up(&hba->tm_tag_wq);
5477 ufshcd_release(hba);
5478 return err;
5482 * ufshcd_eh_device_reset_handler - device reset handler registered to
5483 * scsi layer.
5484 * @cmd: SCSI command pointer
5486 * Returns SUCCESS/FAILED
5488 static int ufshcd_eh_device_reset_handler(struct scsi_cmnd *cmd)
5490 struct Scsi_Host *host;
5491 struct ufs_hba *hba;
5492 unsigned int tag;
5493 u32 pos;
5494 int err;
5495 u8 resp = 0xF;
5496 struct ufshcd_lrb *lrbp;
5497 unsigned long flags;
5499 host = cmd->device->host;
5500 hba = shost_priv(host);
5501 tag = cmd->request->tag;
5503 lrbp = &hba->lrb[tag];
5504 err = ufshcd_issue_tm_cmd(hba, lrbp->lun, 0, UFS_LOGICAL_RESET, &resp);
5505 if (err || resp != UPIU_TASK_MANAGEMENT_FUNC_COMPL) {
5506 if (!err)
5507 err = resp;
5508 goto out;
5511 /* clear the commands that were pending for corresponding LUN */
5512 for_each_set_bit(pos, &hba->outstanding_reqs, hba->nutrs) {
5513 if (hba->lrb[pos].lun == lrbp->lun) {
5514 err = ufshcd_clear_cmd(hba, pos);
5515 if (err)
5516 break;
5519 spin_lock_irqsave(host->host_lock, flags);
5520 ufshcd_transfer_req_compl(hba);
5521 spin_unlock_irqrestore(host->host_lock, flags);
5523 out:
5524 hba->req_abort_count = 0;
5525 if (!err) {
5526 err = SUCCESS;
5527 } else {
5528 dev_err(hba->dev, "%s: failed with err %d\n", __func__, err);
5529 err = FAILED;
5531 return err;
5534 static void ufshcd_set_req_abort_skip(struct ufs_hba *hba, unsigned long bitmap)
5536 struct ufshcd_lrb *lrbp;
5537 int tag;
5539 for_each_set_bit(tag, &bitmap, hba->nutrs) {
5540 lrbp = &hba->lrb[tag];
5541 lrbp->req_abort_skip = true;
5546 * ufshcd_abort - abort a specific command
5547 * @cmd: SCSI command pointer
5549 * Abort the pending command in device by sending UFS_ABORT_TASK task management
5550 * command, and in host controller by clearing the door-bell register. There can
5551 * be race between controller sending the command to the device while abort is
5552 * issued. To avoid that, first issue UFS_QUERY_TASK to check if the command is
5553 * really issued and then try to abort it.
5555 * Returns SUCCESS/FAILED
5557 static int ufshcd_abort(struct scsi_cmnd *cmd)
5559 struct Scsi_Host *host;
5560 struct ufs_hba *hba;
5561 unsigned long flags;
5562 unsigned int tag;
5563 int err = 0;
5564 int poll_cnt;
5565 u8 resp = 0xF;
5566 struct ufshcd_lrb *lrbp;
5567 u32 reg;
5569 host = cmd->device->host;
5570 hba = shost_priv(host);
5571 tag = cmd->request->tag;
5572 lrbp = &hba->lrb[tag];
5573 if (!ufshcd_valid_tag(hba, tag)) {
5574 dev_err(hba->dev,
5575 "%s: invalid command tag %d: cmd=0x%p, cmd->request=0x%p",
5576 __func__, tag, cmd, cmd->request);
5577 BUG();
5581 * Task abort to the device W-LUN is illegal. When this command
5582 * will fail, due to spec violation, scsi err handling next step
5583 * will be to send LU reset which, again, is a spec violation.
5584 * To avoid these unnecessary/illegal step we skip to the last error
5585 * handling stage: reset and restore.
5587 if (lrbp->lun == UFS_UPIU_UFS_DEVICE_WLUN)
5588 return ufshcd_eh_host_reset_handler(cmd);
5590 ufshcd_hold(hba, false);
5591 reg = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
5592 /* If command is already aborted/completed, return SUCCESS */
5593 if (!(test_bit(tag, &hba->outstanding_reqs))) {
5594 dev_err(hba->dev,
5595 "%s: cmd at tag %d already completed, outstanding=0x%lx, doorbell=0x%x\n",
5596 __func__, tag, hba->outstanding_reqs, reg);
5597 goto out;
5600 if (!(reg & (1 << tag))) {
5601 dev_err(hba->dev,
5602 "%s: cmd was completed, but without a notifying intr, tag = %d",
5603 __func__, tag);
5606 /* Print Transfer Request of aborted task */
5607 dev_err(hba->dev, "%s: Device abort task at tag %d\n", __func__, tag);
5610 * Print detailed info about aborted request.
5611 * As more than one request might get aborted at the same time,
5612 * print full information only for the first aborted request in order
5613 * to reduce repeated printouts. For other aborted requests only print
5614 * basic details.
5616 scsi_print_command(hba->lrb[tag].cmd);
5617 if (!hba->req_abort_count) {
5618 ufshcd_print_host_regs(hba);
5619 ufshcd_print_host_state(hba);
5620 ufshcd_print_pwr_info(hba);
5621 ufshcd_print_trs(hba, 1 << tag, true);
5622 } else {
5623 ufshcd_print_trs(hba, 1 << tag, false);
5625 hba->req_abort_count++;
5627 /* Skip task abort in case previous aborts failed and report failure */
5628 if (lrbp->req_abort_skip) {
5629 err = -EIO;
5630 goto out;
5633 for (poll_cnt = 100; poll_cnt; poll_cnt--) {
5634 err = ufshcd_issue_tm_cmd(hba, lrbp->lun, lrbp->task_tag,
5635 UFS_QUERY_TASK, &resp);
5636 if (!err && resp == UPIU_TASK_MANAGEMENT_FUNC_SUCCEEDED) {
5637 /* cmd pending in the device */
5638 dev_err(hba->dev, "%s: cmd pending in the device. tag = %d\n",
5639 __func__, tag);
5640 break;
5641 } else if (!err && resp == UPIU_TASK_MANAGEMENT_FUNC_COMPL) {
5643 * cmd not pending in the device, check if it is
5644 * in transition.
5646 dev_err(hba->dev, "%s: cmd at tag %d not pending in the device.\n",
5647 __func__, tag);
5648 reg = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
5649 if (reg & (1 << tag)) {
5650 /* sleep for max. 200us to stabilize */
5651 usleep_range(100, 200);
5652 continue;
5654 /* command completed already */
5655 dev_err(hba->dev, "%s: cmd at tag %d successfully cleared from DB.\n",
5656 __func__, tag);
5657 goto out;
5658 } else {
5659 dev_err(hba->dev,
5660 "%s: no response from device. tag = %d, err %d\n",
5661 __func__, tag, err);
5662 if (!err)
5663 err = resp; /* service response error */
5664 goto out;
5668 if (!poll_cnt) {
5669 err = -EBUSY;
5670 goto out;
5673 err = ufshcd_issue_tm_cmd(hba, lrbp->lun, lrbp->task_tag,
5674 UFS_ABORT_TASK, &resp);
5675 if (err || resp != UPIU_TASK_MANAGEMENT_FUNC_COMPL) {
5676 if (!err) {
5677 err = resp; /* service response error */
5678 dev_err(hba->dev, "%s: issued. tag = %d, err %d\n",
5679 __func__, tag, err);
5681 goto out;
5684 err = ufshcd_clear_cmd(hba, tag);
5685 if (err) {
5686 dev_err(hba->dev, "%s: Failed clearing cmd at tag %d, err %d\n",
5687 __func__, tag, err);
5688 goto out;
5691 scsi_dma_unmap(cmd);
5693 spin_lock_irqsave(host->host_lock, flags);
5694 ufshcd_outstanding_req_clear(hba, tag);
5695 hba->lrb[tag].cmd = NULL;
5696 spin_unlock_irqrestore(host->host_lock, flags);
5698 clear_bit_unlock(tag, &hba->lrb_in_use);
5699 wake_up(&hba->dev_cmd.tag_wq);
5701 out:
5702 if (!err) {
5703 err = SUCCESS;
5704 } else {
5705 dev_err(hba->dev, "%s: failed with err %d\n", __func__, err);
5706 ufshcd_set_req_abort_skip(hba, hba->outstanding_reqs);
5707 err = FAILED;
5711 * This ufshcd_release() corresponds to the original scsi cmd that got
5712 * aborted here (as we won't get any IRQ for it).
5714 ufshcd_release(hba);
5715 return err;
5719 * ufshcd_host_reset_and_restore - reset and restore host controller
5720 * @hba: per-adapter instance
5722 * Note that host controller reset may issue DME_RESET to
5723 * local and remote (device) Uni-Pro stack and the attributes
5724 * are reset to default state.
5726 * Returns zero on success, non-zero on failure
5728 static int ufshcd_host_reset_and_restore(struct ufs_hba *hba)
5730 int err;
5731 unsigned long flags;
5733 /* Reset the host controller */
5734 spin_lock_irqsave(hba->host->host_lock, flags);
5735 ufshcd_hba_stop(hba, false);
5736 spin_unlock_irqrestore(hba->host->host_lock, flags);
5738 /* scale up clocks to max frequency before full reinitialization */
5739 ufshcd_scale_clks(hba, true);
5741 err = ufshcd_hba_enable(hba);
5742 if (err)
5743 goto out;
5745 /* Establish the link again and restore the device */
5746 err = ufshcd_probe_hba(hba);
5748 if (!err && (hba->ufshcd_state != UFSHCD_STATE_OPERATIONAL))
5749 err = -EIO;
5750 out:
5751 if (err)
5752 dev_err(hba->dev, "%s: Host init failed %d\n", __func__, err);
5754 return err;
5758 * ufshcd_reset_and_restore - reset and re-initialize host/device
5759 * @hba: per-adapter instance
5761 * Reset and recover device, host and re-establish link. This
5762 * is helpful to recover the communication in fatal error conditions.
5764 * Returns zero on success, non-zero on failure
5766 static int ufshcd_reset_and_restore(struct ufs_hba *hba)
5768 int err = 0;
5769 unsigned long flags;
5770 int retries = MAX_HOST_RESET_RETRIES;
5772 do {
5773 err = ufshcd_host_reset_and_restore(hba);
5774 } while (err && --retries);
5777 * After reset the door-bell might be cleared, complete
5778 * outstanding requests in s/w here.
5780 spin_lock_irqsave(hba->host->host_lock, flags);
5781 ufshcd_transfer_req_compl(hba);
5782 ufshcd_tmc_handler(hba);
5783 spin_unlock_irqrestore(hba->host->host_lock, flags);
5785 return err;
5789 * ufshcd_eh_host_reset_handler - host reset handler registered to scsi layer
5790 * @cmd - SCSI command pointer
5792 * Returns SUCCESS/FAILED
5794 static int ufshcd_eh_host_reset_handler(struct scsi_cmnd *cmd)
5796 int err;
5797 unsigned long flags;
5798 struct ufs_hba *hba;
5800 hba = shost_priv(cmd->device->host);
5802 ufshcd_hold(hba, false);
5804 * Check if there is any race with fatal error handling.
5805 * If so, wait for it to complete. Even though fatal error
5806 * handling does reset and restore in some cases, don't assume
5807 * anything out of it. We are just avoiding race here.
5809 do {
5810 spin_lock_irqsave(hba->host->host_lock, flags);
5811 if (!(work_pending(&hba->eh_work) ||
5812 hba->ufshcd_state == UFSHCD_STATE_RESET ||
5813 hba->ufshcd_state == UFSHCD_STATE_EH_SCHEDULED))
5814 break;
5815 spin_unlock_irqrestore(hba->host->host_lock, flags);
5816 dev_dbg(hba->dev, "%s: reset in progress\n", __func__);
5817 flush_work(&hba->eh_work);
5818 } while (1);
5820 hba->ufshcd_state = UFSHCD_STATE_RESET;
5821 ufshcd_set_eh_in_progress(hba);
5822 spin_unlock_irqrestore(hba->host->host_lock, flags);
5824 err = ufshcd_reset_and_restore(hba);
5826 spin_lock_irqsave(hba->host->host_lock, flags);
5827 if (!err) {
5828 err = SUCCESS;
5829 hba->ufshcd_state = UFSHCD_STATE_OPERATIONAL;
5830 } else {
5831 err = FAILED;
5832 hba->ufshcd_state = UFSHCD_STATE_ERROR;
5834 ufshcd_clear_eh_in_progress(hba);
5835 spin_unlock_irqrestore(hba->host->host_lock, flags);
5837 ufshcd_release(hba);
5838 return err;
5842 * ufshcd_get_max_icc_level - calculate the ICC level
5843 * @sup_curr_uA: max. current supported by the regulator
5844 * @start_scan: row at the desc table to start scan from
5845 * @buff: power descriptor buffer
5847 * Returns calculated max ICC level for specific regulator
5849 static u32 ufshcd_get_max_icc_level(int sup_curr_uA, u32 start_scan, char *buff)
5851 int i;
5852 int curr_uA;
5853 u16 data;
5854 u16 unit;
5856 for (i = start_scan; i >= 0; i--) {
5857 data = be16_to_cpup((__be16 *)&buff[2 * i]);
5858 unit = (data & ATTR_ICC_LVL_UNIT_MASK) >>
5859 ATTR_ICC_LVL_UNIT_OFFSET;
5860 curr_uA = data & ATTR_ICC_LVL_VALUE_MASK;
5861 switch (unit) {
5862 case UFSHCD_NANO_AMP:
5863 curr_uA = curr_uA / 1000;
5864 break;
5865 case UFSHCD_MILI_AMP:
5866 curr_uA = curr_uA * 1000;
5867 break;
5868 case UFSHCD_AMP:
5869 curr_uA = curr_uA * 1000 * 1000;
5870 break;
5871 case UFSHCD_MICRO_AMP:
5872 default:
5873 break;
5875 if (sup_curr_uA >= curr_uA)
5876 break;
5878 if (i < 0) {
5879 i = 0;
5880 pr_err("%s: Couldn't find valid icc_level = %d", __func__, i);
5883 return (u32)i;
5887 * ufshcd_calc_icc_level - calculate the max ICC level
5888 * In case regulators are not initialized we'll return 0
5889 * @hba: per-adapter instance
5890 * @desc_buf: power descriptor buffer to extract ICC levels from.
5891 * @len: length of desc_buff
5893 * Returns calculated ICC level
5895 static u32 ufshcd_find_max_sup_active_icc_level(struct ufs_hba *hba,
5896 u8 *desc_buf, int len)
5898 u32 icc_level = 0;
5900 if (!hba->vreg_info.vcc || !hba->vreg_info.vccq ||
5901 !hba->vreg_info.vccq2) {
5902 dev_err(hba->dev,
5903 "%s: Regulator capability was not set, actvIccLevel=%d",
5904 __func__, icc_level);
5905 goto out;
5908 if (hba->vreg_info.vcc)
5909 icc_level = ufshcd_get_max_icc_level(
5910 hba->vreg_info.vcc->max_uA,
5911 POWER_DESC_MAX_ACTV_ICC_LVLS - 1,
5912 &desc_buf[PWR_DESC_ACTIVE_LVLS_VCC_0]);
5914 if (hba->vreg_info.vccq)
5915 icc_level = ufshcd_get_max_icc_level(
5916 hba->vreg_info.vccq->max_uA,
5917 icc_level,
5918 &desc_buf[PWR_DESC_ACTIVE_LVLS_VCCQ_0]);
5920 if (hba->vreg_info.vccq2)
5921 icc_level = ufshcd_get_max_icc_level(
5922 hba->vreg_info.vccq2->max_uA,
5923 icc_level,
5924 &desc_buf[PWR_DESC_ACTIVE_LVLS_VCCQ2_0]);
5925 out:
5926 return icc_level;
5929 static void ufshcd_init_icc_levels(struct ufs_hba *hba)
5931 int ret;
5932 int buff_len = hba->desc_size.pwr_desc;
5933 u8 desc_buf[hba->desc_size.pwr_desc];
5935 ret = ufshcd_read_power_desc(hba, desc_buf, buff_len);
5936 if (ret) {
5937 dev_err(hba->dev,
5938 "%s: Failed reading power descriptor.len = %d ret = %d",
5939 __func__, buff_len, ret);
5940 return;
5943 hba->init_prefetch_data.icc_level =
5944 ufshcd_find_max_sup_active_icc_level(hba,
5945 desc_buf, buff_len);
5946 dev_dbg(hba->dev, "%s: setting icc_level 0x%x",
5947 __func__, hba->init_prefetch_data.icc_level);
5949 ret = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_WRITE_ATTR,
5950 QUERY_ATTR_IDN_ACTIVE_ICC_LVL, 0, 0,
5951 &hba->init_prefetch_data.icc_level);
5953 if (ret)
5954 dev_err(hba->dev,
5955 "%s: Failed configuring bActiveICCLevel = %d ret = %d",
5956 __func__, hba->init_prefetch_data.icc_level , ret);
5961 * ufshcd_scsi_add_wlus - Adds required W-LUs
5962 * @hba: per-adapter instance
5964 * UFS device specification requires the UFS devices to support 4 well known
5965 * logical units:
5966 * "REPORT_LUNS" (address: 01h)
5967 * "UFS Device" (address: 50h)
5968 * "RPMB" (address: 44h)
5969 * "BOOT" (address: 30h)
5970 * UFS device's power management needs to be controlled by "POWER CONDITION"
5971 * field of SSU (START STOP UNIT) command. But this "power condition" field
5972 * will take effect only when its sent to "UFS device" well known logical unit
5973 * hence we require the scsi_device instance to represent this logical unit in
5974 * order for the UFS host driver to send the SSU command for power management.
5976 * We also require the scsi_device instance for "RPMB" (Replay Protected Memory
5977 * Block) LU so user space process can control this LU. User space may also
5978 * want to have access to BOOT LU.
5980 * This function adds scsi device instances for each of all well known LUs
5981 * (except "REPORT LUNS" LU).
5983 * Returns zero on success (all required W-LUs are added successfully),
5984 * non-zero error value on failure (if failed to add any of the required W-LU).
5986 static int ufshcd_scsi_add_wlus(struct ufs_hba *hba)
5988 int ret = 0;
5989 struct scsi_device *sdev_rpmb;
5990 struct scsi_device *sdev_boot;
5992 hba->sdev_ufs_device = __scsi_add_device(hba->host, 0, 0,
5993 ufshcd_upiu_wlun_to_scsi_wlun(UFS_UPIU_UFS_DEVICE_WLUN), NULL);
5994 if (IS_ERR(hba->sdev_ufs_device)) {
5995 ret = PTR_ERR(hba->sdev_ufs_device);
5996 hba->sdev_ufs_device = NULL;
5997 goto out;
5999 scsi_device_put(hba->sdev_ufs_device);
6001 sdev_boot = __scsi_add_device(hba->host, 0, 0,
6002 ufshcd_upiu_wlun_to_scsi_wlun(UFS_UPIU_BOOT_WLUN), NULL);
6003 if (IS_ERR(sdev_boot)) {
6004 ret = PTR_ERR(sdev_boot);
6005 goto remove_sdev_ufs_device;
6007 scsi_device_put(sdev_boot);
6009 sdev_rpmb = __scsi_add_device(hba->host, 0, 0,
6010 ufshcd_upiu_wlun_to_scsi_wlun(UFS_UPIU_RPMB_WLUN), NULL);
6011 if (IS_ERR(sdev_rpmb)) {
6012 ret = PTR_ERR(sdev_rpmb);
6013 goto remove_sdev_boot;
6015 scsi_device_put(sdev_rpmb);
6016 goto out;
6018 remove_sdev_boot:
6019 scsi_remove_device(sdev_boot);
6020 remove_sdev_ufs_device:
6021 scsi_remove_device(hba->sdev_ufs_device);
6022 out:
6023 return ret;
6026 static int ufs_get_device_desc(struct ufs_hba *hba,
6027 struct ufs_dev_desc *dev_desc)
6029 int err;
6030 u8 model_index;
6031 u8 str_desc_buf[QUERY_DESC_MAX_SIZE + 1] = {0};
6032 u8 desc_buf[hba->desc_size.dev_desc];
6034 err = ufshcd_read_device_desc(hba, desc_buf, hba->desc_size.dev_desc);
6035 if (err) {
6036 dev_err(hba->dev, "%s: Failed reading Device Desc. err = %d\n",
6037 __func__, err);
6038 goto out;
6042 * getting vendor (manufacturerID) and Bank Index in big endian
6043 * format
6045 dev_desc->wmanufacturerid = desc_buf[DEVICE_DESC_PARAM_MANF_ID] << 8 |
6046 desc_buf[DEVICE_DESC_PARAM_MANF_ID + 1];
6048 model_index = desc_buf[DEVICE_DESC_PARAM_PRDCT_NAME];
6050 err = ufshcd_read_string_desc(hba, model_index, str_desc_buf,
6051 QUERY_DESC_MAX_SIZE, ASCII_STD);
6052 if (err) {
6053 dev_err(hba->dev, "%s: Failed reading Product Name. err = %d\n",
6054 __func__, err);
6055 goto out;
6058 str_desc_buf[QUERY_DESC_MAX_SIZE] = '\0';
6059 strlcpy(dev_desc->model, (str_desc_buf + QUERY_DESC_HDR_SIZE),
6060 min_t(u8, str_desc_buf[QUERY_DESC_LENGTH_OFFSET],
6061 MAX_MODEL_LEN));
6063 /* Null terminate the model string */
6064 dev_desc->model[MAX_MODEL_LEN] = '\0';
6066 out:
6067 return err;
6070 static void ufs_fixup_device_setup(struct ufs_hba *hba,
6071 struct ufs_dev_desc *dev_desc)
6073 struct ufs_dev_fix *f;
6075 for (f = ufs_fixups; f->quirk; f++) {
6076 if ((f->card.wmanufacturerid == dev_desc->wmanufacturerid ||
6077 f->card.wmanufacturerid == UFS_ANY_VENDOR) &&
6078 (STR_PRFX_EQUAL(f->card.model, dev_desc->model) ||
6079 !strcmp(f->card.model, UFS_ANY_MODEL)))
6080 hba->dev_quirks |= f->quirk;
6085 * ufshcd_tune_pa_tactivate - Tunes PA_TActivate of local UniPro
6086 * @hba: per-adapter instance
6088 * PA_TActivate parameter can be tuned manually if UniPro version is less than
6089 * 1.61. PA_TActivate needs to be greater than or equal to peerM-PHY's
6090 * RX_MIN_ACTIVATETIME_CAPABILITY attribute. This optimal value can help reduce
6091 * the hibern8 exit latency.
6093 * Returns zero on success, non-zero error value on failure.
6095 static int ufshcd_tune_pa_tactivate(struct ufs_hba *hba)
6097 int ret = 0;
6098 u32 peer_rx_min_activatetime = 0, tuned_pa_tactivate;
6100 ret = ufshcd_dme_peer_get(hba,
6101 UIC_ARG_MIB_SEL(
6102 RX_MIN_ACTIVATETIME_CAPABILITY,
6103 UIC_ARG_MPHY_RX_GEN_SEL_INDEX(0)),
6104 &peer_rx_min_activatetime);
6105 if (ret)
6106 goto out;
6108 /* make sure proper unit conversion is applied */
6109 tuned_pa_tactivate =
6110 ((peer_rx_min_activatetime * RX_MIN_ACTIVATETIME_UNIT_US)
6111 / PA_TACTIVATE_TIME_UNIT_US);
6112 ret = ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TACTIVATE),
6113 tuned_pa_tactivate);
6115 out:
6116 return ret;
6120 * ufshcd_tune_pa_hibern8time - Tunes PA_Hibern8Time of local UniPro
6121 * @hba: per-adapter instance
6123 * PA_Hibern8Time parameter can be tuned manually if UniPro version is less than
6124 * 1.61. PA_Hibern8Time needs to be maximum of local M-PHY's
6125 * TX_HIBERN8TIME_CAPABILITY & peer M-PHY's RX_HIBERN8TIME_CAPABILITY.
6126 * This optimal value can help reduce the hibern8 exit latency.
6128 * Returns zero on success, non-zero error value on failure.
6130 static int ufshcd_tune_pa_hibern8time(struct ufs_hba *hba)
6132 int ret = 0;
6133 u32 local_tx_hibern8_time_cap = 0, peer_rx_hibern8_time_cap = 0;
6134 u32 max_hibern8_time, tuned_pa_hibern8time;
6136 ret = ufshcd_dme_get(hba,
6137 UIC_ARG_MIB_SEL(TX_HIBERN8TIME_CAPABILITY,
6138 UIC_ARG_MPHY_TX_GEN_SEL_INDEX(0)),
6139 &local_tx_hibern8_time_cap);
6140 if (ret)
6141 goto out;
6143 ret = ufshcd_dme_peer_get(hba,
6144 UIC_ARG_MIB_SEL(RX_HIBERN8TIME_CAPABILITY,
6145 UIC_ARG_MPHY_RX_GEN_SEL_INDEX(0)),
6146 &peer_rx_hibern8_time_cap);
6147 if (ret)
6148 goto out;
6150 max_hibern8_time = max(local_tx_hibern8_time_cap,
6151 peer_rx_hibern8_time_cap);
6152 /* make sure proper unit conversion is applied */
6153 tuned_pa_hibern8time = ((max_hibern8_time * HIBERN8TIME_UNIT_US)
6154 / PA_HIBERN8_TIME_UNIT_US);
6155 ret = ufshcd_dme_set(hba, UIC_ARG_MIB(PA_HIBERN8TIME),
6156 tuned_pa_hibern8time);
6157 out:
6158 return ret;
6162 * ufshcd_quirk_tune_host_pa_tactivate - Ensures that host PA_TACTIVATE is
6163 * less than device PA_TACTIVATE time.
6164 * @hba: per-adapter instance
6166 * Some UFS devices require host PA_TACTIVATE to be lower than device
6167 * PA_TACTIVATE, we need to enable UFS_DEVICE_QUIRK_HOST_PA_TACTIVATE quirk
6168 * for such devices.
6170 * Returns zero on success, non-zero error value on failure.
6172 static int ufshcd_quirk_tune_host_pa_tactivate(struct ufs_hba *hba)
6174 int ret = 0;
6175 u32 granularity, peer_granularity;
6176 u32 pa_tactivate, peer_pa_tactivate;
6177 u32 pa_tactivate_us, peer_pa_tactivate_us;
6178 u8 gran_to_us_table[] = {1, 4, 8, 16, 32, 100};
6180 ret = ufshcd_dme_get(hba, UIC_ARG_MIB(PA_GRANULARITY),
6181 &granularity);
6182 if (ret)
6183 goto out;
6185 ret = ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_GRANULARITY),
6186 &peer_granularity);
6187 if (ret)
6188 goto out;
6190 if ((granularity < PA_GRANULARITY_MIN_VAL) ||
6191 (granularity > PA_GRANULARITY_MAX_VAL)) {
6192 dev_err(hba->dev, "%s: invalid host PA_GRANULARITY %d",
6193 __func__, granularity);
6194 return -EINVAL;
6197 if ((peer_granularity < PA_GRANULARITY_MIN_VAL) ||
6198 (peer_granularity > PA_GRANULARITY_MAX_VAL)) {
6199 dev_err(hba->dev, "%s: invalid device PA_GRANULARITY %d",
6200 __func__, peer_granularity);
6201 return -EINVAL;
6204 ret = ufshcd_dme_get(hba, UIC_ARG_MIB(PA_TACTIVATE), &pa_tactivate);
6205 if (ret)
6206 goto out;
6208 ret = ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_TACTIVATE),
6209 &peer_pa_tactivate);
6210 if (ret)
6211 goto out;
6213 pa_tactivate_us = pa_tactivate * gran_to_us_table[granularity - 1];
6214 peer_pa_tactivate_us = peer_pa_tactivate *
6215 gran_to_us_table[peer_granularity - 1];
6217 if (pa_tactivate_us > peer_pa_tactivate_us) {
6218 u32 new_peer_pa_tactivate;
6220 new_peer_pa_tactivate = pa_tactivate_us /
6221 gran_to_us_table[peer_granularity - 1];
6222 new_peer_pa_tactivate++;
6223 ret = ufshcd_dme_peer_set(hba, UIC_ARG_MIB(PA_TACTIVATE),
6224 new_peer_pa_tactivate);
6227 out:
6228 return ret;
6231 static void ufshcd_tune_unipro_params(struct ufs_hba *hba)
6233 if (ufshcd_is_unipro_pa_params_tuning_req(hba)) {
6234 ufshcd_tune_pa_tactivate(hba);
6235 ufshcd_tune_pa_hibern8time(hba);
6238 if (hba->dev_quirks & UFS_DEVICE_QUIRK_PA_TACTIVATE)
6239 /* set 1ms timeout for PA_TACTIVATE */
6240 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TACTIVATE), 10);
6242 if (hba->dev_quirks & UFS_DEVICE_QUIRK_HOST_PA_TACTIVATE)
6243 ufshcd_quirk_tune_host_pa_tactivate(hba);
6245 ufshcd_vops_apply_dev_quirks(hba);
6248 static void ufshcd_clear_dbg_ufs_stats(struct ufs_hba *hba)
6250 int err_reg_hist_size = sizeof(struct ufs_uic_err_reg_hist);
6252 hba->ufs_stats.hibern8_exit_cnt = 0;
6253 hba->ufs_stats.last_hibern8_exit_tstamp = ktime_set(0, 0);
6255 memset(&hba->ufs_stats.pa_err, 0, err_reg_hist_size);
6256 memset(&hba->ufs_stats.dl_err, 0, err_reg_hist_size);
6257 memset(&hba->ufs_stats.nl_err, 0, err_reg_hist_size);
6258 memset(&hba->ufs_stats.tl_err, 0, err_reg_hist_size);
6259 memset(&hba->ufs_stats.dme_err, 0, err_reg_hist_size);
6261 hba->req_abort_count = 0;
6264 static void ufshcd_init_desc_sizes(struct ufs_hba *hba)
6266 int err;
6268 err = ufshcd_read_desc_length(hba, QUERY_DESC_IDN_DEVICE, 0,
6269 &hba->desc_size.dev_desc);
6270 if (err)
6271 hba->desc_size.dev_desc = QUERY_DESC_DEVICE_DEF_SIZE;
6273 err = ufshcd_read_desc_length(hba, QUERY_DESC_IDN_POWER, 0,
6274 &hba->desc_size.pwr_desc);
6275 if (err)
6276 hba->desc_size.pwr_desc = QUERY_DESC_POWER_DEF_SIZE;
6278 err = ufshcd_read_desc_length(hba, QUERY_DESC_IDN_INTERCONNECT, 0,
6279 &hba->desc_size.interc_desc);
6280 if (err)
6281 hba->desc_size.interc_desc = QUERY_DESC_INTERCONNECT_DEF_SIZE;
6283 err = ufshcd_read_desc_length(hba, QUERY_DESC_IDN_CONFIGURATION, 0,
6284 &hba->desc_size.conf_desc);
6285 if (err)
6286 hba->desc_size.conf_desc = QUERY_DESC_CONFIGURATION_DEF_SIZE;
6288 err = ufshcd_read_desc_length(hba, QUERY_DESC_IDN_UNIT, 0,
6289 &hba->desc_size.unit_desc);
6290 if (err)
6291 hba->desc_size.unit_desc = QUERY_DESC_UNIT_DEF_SIZE;
6293 err = ufshcd_read_desc_length(hba, QUERY_DESC_IDN_GEOMETRY, 0,
6294 &hba->desc_size.geom_desc);
6295 if (err)
6296 hba->desc_size.geom_desc = QUERY_DESC_GEOMETRY_DEF_SIZE;
6299 static void ufshcd_def_desc_sizes(struct ufs_hba *hba)
6301 hba->desc_size.dev_desc = QUERY_DESC_DEVICE_DEF_SIZE;
6302 hba->desc_size.pwr_desc = QUERY_DESC_POWER_DEF_SIZE;
6303 hba->desc_size.interc_desc = QUERY_DESC_INTERCONNECT_DEF_SIZE;
6304 hba->desc_size.conf_desc = QUERY_DESC_CONFIGURATION_DEF_SIZE;
6305 hba->desc_size.unit_desc = QUERY_DESC_UNIT_DEF_SIZE;
6306 hba->desc_size.geom_desc = QUERY_DESC_GEOMETRY_DEF_SIZE;
6310 * ufshcd_probe_hba - probe hba to detect device and initialize
6311 * @hba: per-adapter instance
6313 * Execute link-startup and verify device initialization
6315 static int ufshcd_probe_hba(struct ufs_hba *hba)
6317 struct ufs_dev_desc card = {0};
6318 int ret;
6319 ktime_t start = ktime_get();
6321 ret = ufshcd_link_startup(hba);
6322 if (ret)
6323 goto out;
6325 /* set the default level for urgent bkops */
6326 hba->urgent_bkops_lvl = BKOPS_STATUS_PERF_IMPACT;
6327 hba->is_urgent_bkops_lvl_checked = false;
6329 /* Debug counters initialization */
6330 ufshcd_clear_dbg_ufs_stats(hba);
6332 /* UniPro link is active now */
6333 ufshcd_set_link_active(hba);
6335 ret = ufshcd_verify_dev_init(hba);
6336 if (ret)
6337 goto out;
6339 ret = ufshcd_complete_dev_init(hba);
6340 if (ret)
6341 goto out;
6343 /* Init check for device descriptor sizes */
6344 ufshcd_init_desc_sizes(hba);
6346 ret = ufs_get_device_desc(hba, &card);
6347 if (ret) {
6348 dev_err(hba->dev, "%s: Failed getting device info. err = %d\n",
6349 __func__, ret);
6350 goto out;
6353 ufs_fixup_device_setup(hba, &card);
6354 ufshcd_tune_unipro_params(hba);
6356 ret = ufshcd_set_vccq_rail_unused(hba,
6357 (hba->dev_quirks & UFS_DEVICE_NO_VCCQ) ? true : false);
6358 if (ret)
6359 goto out;
6361 /* UFS device is also active now */
6362 ufshcd_set_ufs_dev_active(hba);
6363 ufshcd_force_reset_auto_bkops(hba);
6364 hba->wlun_dev_clr_ua = true;
6366 if (ufshcd_get_max_pwr_mode(hba)) {
6367 dev_err(hba->dev,
6368 "%s: Failed getting max supported power mode\n",
6369 __func__);
6370 } else {
6371 ret = ufshcd_config_pwr_mode(hba, &hba->max_pwr_info.info);
6372 if (ret) {
6373 dev_err(hba->dev, "%s: Failed setting power mode, err = %d\n",
6374 __func__, ret);
6375 goto out;
6379 /* set the state as operational after switching to desired gear */
6380 hba->ufshcd_state = UFSHCD_STATE_OPERATIONAL;
6383 * If we are in error handling context or in power management callbacks
6384 * context, no need to scan the host
6386 if (!ufshcd_eh_in_progress(hba) && !hba->pm_op_in_progress) {
6387 bool flag;
6389 /* clear any previous UFS device information */
6390 memset(&hba->dev_info, 0, sizeof(hba->dev_info));
6391 if (!ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_READ_FLAG,
6392 QUERY_FLAG_IDN_PWR_ON_WPE, &flag))
6393 hba->dev_info.f_power_on_wp_en = flag;
6395 if (!hba->is_init_prefetch)
6396 ufshcd_init_icc_levels(hba);
6398 /* Add required well known logical units to scsi mid layer */
6399 if (ufshcd_scsi_add_wlus(hba))
6400 goto out;
6402 /* Initialize devfreq after UFS device is detected */
6403 if (ufshcd_is_clkscaling_supported(hba)) {
6404 memcpy(&hba->clk_scaling.saved_pwr_info.info,
6405 &hba->pwr_info,
6406 sizeof(struct ufs_pa_layer_attr));
6407 hba->clk_scaling.saved_pwr_info.is_valid = true;
6408 if (!hba->devfreq) {
6409 hba->devfreq = devm_devfreq_add_device(hba->dev,
6410 &ufs_devfreq_profile,
6411 "simple_ondemand",
6412 NULL);
6413 if (IS_ERR(hba->devfreq)) {
6414 ret = PTR_ERR(hba->devfreq);
6415 dev_err(hba->dev, "Unable to register with devfreq %d\n",
6416 ret);
6417 goto out;
6420 hba->clk_scaling.is_allowed = true;
6423 scsi_scan_host(hba->host);
6424 pm_runtime_put_sync(hba->dev);
6427 if (!hba->is_init_prefetch)
6428 hba->is_init_prefetch = true;
6430 out:
6432 * If we failed to initialize the device or the device is not
6433 * present, turn off the power/clocks etc.
6435 if (ret && !ufshcd_eh_in_progress(hba) && !hba->pm_op_in_progress) {
6436 pm_runtime_put_sync(hba->dev);
6437 ufshcd_hba_exit(hba);
6440 trace_ufshcd_init(dev_name(hba->dev), ret,
6441 ktime_to_us(ktime_sub(ktime_get(), start)),
6442 hba->curr_dev_pwr_mode, hba->uic_link_state);
6443 return ret;
6447 * ufshcd_async_scan - asynchronous execution for probing hba
6448 * @data: data pointer to pass to this function
6449 * @cookie: cookie data
6451 static void ufshcd_async_scan(void *data, async_cookie_t cookie)
6453 struct ufs_hba *hba = (struct ufs_hba *)data;
6455 ufshcd_probe_hba(hba);
6458 static enum blk_eh_timer_return ufshcd_eh_timed_out(struct scsi_cmnd *scmd)
6460 unsigned long flags;
6461 struct Scsi_Host *host;
6462 struct ufs_hba *hba;
6463 int index;
6464 bool found = false;
6466 if (!scmd || !scmd->device || !scmd->device->host)
6467 return BLK_EH_NOT_HANDLED;
6469 host = scmd->device->host;
6470 hba = shost_priv(host);
6471 if (!hba)
6472 return BLK_EH_NOT_HANDLED;
6474 spin_lock_irqsave(host->host_lock, flags);
6476 for_each_set_bit(index, &hba->outstanding_reqs, hba->nutrs) {
6477 if (hba->lrb[index].cmd == scmd) {
6478 found = true;
6479 break;
6483 spin_unlock_irqrestore(host->host_lock, flags);
6486 * Bypass SCSI error handling and reset the block layer timer if this
6487 * SCSI command was not actually dispatched to UFS driver, otherwise
6488 * let SCSI layer handle the error as usual.
6490 return found ? BLK_EH_NOT_HANDLED : BLK_EH_RESET_TIMER;
6493 static struct scsi_host_template ufshcd_driver_template = {
6494 .module = THIS_MODULE,
6495 .name = UFSHCD,
6496 .proc_name = UFSHCD,
6497 .queuecommand = ufshcd_queuecommand,
6498 .slave_alloc = ufshcd_slave_alloc,
6499 .slave_configure = ufshcd_slave_configure,
6500 .slave_destroy = ufshcd_slave_destroy,
6501 .change_queue_depth = ufshcd_change_queue_depth,
6502 .eh_abort_handler = ufshcd_abort,
6503 .eh_device_reset_handler = ufshcd_eh_device_reset_handler,
6504 .eh_host_reset_handler = ufshcd_eh_host_reset_handler,
6505 .eh_timed_out = ufshcd_eh_timed_out,
6506 .this_id = -1,
6507 .sg_tablesize = SG_ALL,
6508 .cmd_per_lun = UFSHCD_CMD_PER_LUN,
6509 .can_queue = UFSHCD_CAN_QUEUE,
6510 .max_host_blocked = 1,
6511 .track_queue_depth = 1,
6514 static int ufshcd_config_vreg_load(struct device *dev, struct ufs_vreg *vreg,
6515 int ua)
6517 int ret;
6519 if (!vreg)
6520 return 0;
6522 ret = regulator_set_load(vreg->reg, ua);
6523 if (ret < 0) {
6524 dev_err(dev, "%s: %s set load (ua=%d) failed, err=%d\n",
6525 __func__, vreg->name, ua, ret);
6528 return ret;
6531 static inline int ufshcd_config_vreg_lpm(struct ufs_hba *hba,
6532 struct ufs_vreg *vreg)
6534 if (!vreg)
6535 return 0;
6536 else if (vreg->unused)
6537 return 0;
6538 else
6539 return ufshcd_config_vreg_load(hba->dev, vreg,
6540 UFS_VREG_LPM_LOAD_UA);
6543 static inline int ufshcd_config_vreg_hpm(struct ufs_hba *hba,
6544 struct ufs_vreg *vreg)
6546 if (!vreg)
6547 return 0;
6548 else if (vreg->unused)
6549 return 0;
6550 else
6551 return ufshcd_config_vreg_load(hba->dev, vreg, vreg->max_uA);
6554 static int ufshcd_config_vreg(struct device *dev,
6555 struct ufs_vreg *vreg, bool on)
6557 int ret = 0;
6558 struct regulator *reg = vreg->reg;
6559 const char *name = vreg->name;
6560 int min_uV, uA_load;
6562 BUG_ON(!vreg);
6564 if (regulator_count_voltages(reg) > 0) {
6565 min_uV = on ? vreg->min_uV : 0;
6566 ret = regulator_set_voltage(reg, min_uV, vreg->max_uV);
6567 if (ret) {
6568 dev_err(dev, "%s: %s set voltage failed, err=%d\n",
6569 __func__, name, ret);
6570 goto out;
6573 uA_load = on ? vreg->max_uA : 0;
6574 ret = ufshcd_config_vreg_load(dev, vreg, uA_load);
6575 if (ret)
6576 goto out;
6578 out:
6579 return ret;
6582 static int ufshcd_enable_vreg(struct device *dev, struct ufs_vreg *vreg)
6584 int ret = 0;
6586 if (!vreg)
6587 goto out;
6588 else if (vreg->enabled || vreg->unused)
6589 goto out;
6591 ret = ufshcd_config_vreg(dev, vreg, true);
6592 if (!ret)
6593 ret = regulator_enable(vreg->reg);
6595 if (!ret)
6596 vreg->enabled = true;
6597 else
6598 dev_err(dev, "%s: %s enable failed, err=%d\n",
6599 __func__, vreg->name, ret);
6600 out:
6601 return ret;
6604 static int ufshcd_disable_vreg(struct device *dev, struct ufs_vreg *vreg)
6606 int ret = 0;
6608 if (!vreg)
6609 goto out;
6610 else if (!vreg->enabled || vreg->unused)
6611 goto out;
6613 ret = regulator_disable(vreg->reg);
6615 if (!ret) {
6616 /* ignore errors on applying disable config */
6617 ufshcd_config_vreg(dev, vreg, false);
6618 vreg->enabled = false;
6619 } else {
6620 dev_err(dev, "%s: %s disable failed, err=%d\n",
6621 __func__, vreg->name, ret);
6623 out:
6624 return ret;
6627 static int ufshcd_setup_vreg(struct ufs_hba *hba, bool on)
6629 int ret = 0;
6630 struct device *dev = hba->dev;
6631 struct ufs_vreg_info *info = &hba->vreg_info;
6633 if (!info)
6634 goto out;
6636 ret = ufshcd_toggle_vreg(dev, info->vcc, on);
6637 if (ret)
6638 goto out;
6640 ret = ufshcd_toggle_vreg(dev, info->vccq, on);
6641 if (ret)
6642 goto out;
6644 ret = ufshcd_toggle_vreg(dev, info->vccq2, on);
6645 if (ret)
6646 goto out;
6648 out:
6649 if (ret) {
6650 ufshcd_toggle_vreg(dev, info->vccq2, false);
6651 ufshcd_toggle_vreg(dev, info->vccq, false);
6652 ufshcd_toggle_vreg(dev, info->vcc, false);
6654 return ret;
6657 static int ufshcd_setup_hba_vreg(struct ufs_hba *hba, bool on)
6659 struct ufs_vreg_info *info = &hba->vreg_info;
6661 if (info)
6662 return ufshcd_toggle_vreg(hba->dev, info->vdd_hba, on);
6664 return 0;
6667 static int ufshcd_get_vreg(struct device *dev, struct ufs_vreg *vreg)
6669 int ret = 0;
6671 if (!vreg)
6672 goto out;
6674 vreg->reg = devm_regulator_get(dev, vreg->name);
6675 if (IS_ERR(vreg->reg)) {
6676 ret = PTR_ERR(vreg->reg);
6677 dev_err(dev, "%s: %s get failed, err=%d\n",
6678 __func__, vreg->name, ret);
6680 out:
6681 return ret;
6684 static int ufshcd_init_vreg(struct ufs_hba *hba)
6686 int ret = 0;
6687 struct device *dev = hba->dev;
6688 struct ufs_vreg_info *info = &hba->vreg_info;
6690 if (!info)
6691 goto out;
6693 ret = ufshcd_get_vreg(dev, info->vcc);
6694 if (ret)
6695 goto out;
6697 ret = ufshcd_get_vreg(dev, info->vccq);
6698 if (ret)
6699 goto out;
6701 ret = ufshcd_get_vreg(dev, info->vccq2);
6702 out:
6703 return ret;
6706 static int ufshcd_init_hba_vreg(struct ufs_hba *hba)
6708 struct ufs_vreg_info *info = &hba->vreg_info;
6710 if (info)
6711 return ufshcd_get_vreg(hba->dev, info->vdd_hba);
6713 return 0;
6716 static int ufshcd_set_vccq_rail_unused(struct ufs_hba *hba, bool unused)
6718 int ret = 0;
6719 struct ufs_vreg_info *info = &hba->vreg_info;
6721 if (!info)
6722 goto out;
6723 else if (!info->vccq)
6724 goto out;
6726 if (unused) {
6727 /* shut off the rail here */
6728 ret = ufshcd_toggle_vreg(hba->dev, info->vccq, false);
6730 * Mark this rail as no longer used, so it doesn't get enabled
6731 * later by mistake
6733 if (!ret)
6734 info->vccq->unused = true;
6735 } else {
6737 * rail should have been already enabled hence just make sure
6738 * that unused flag is cleared.
6740 info->vccq->unused = false;
6742 out:
6743 return ret;
6746 static int __ufshcd_setup_clocks(struct ufs_hba *hba, bool on,
6747 bool skip_ref_clk)
6749 int ret = 0;
6750 struct ufs_clk_info *clki;
6751 struct list_head *head = &hba->clk_list_head;
6752 unsigned long flags;
6753 ktime_t start = ktime_get();
6754 bool clk_state_changed = false;
6756 if (list_empty(head))
6757 goto out;
6759 ret = ufshcd_vops_setup_clocks(hba, on, PRE_CHANGE);
6760 if (ret)
6761 return ret;
6763 list_for_each_entry(clki, head, list) {
6764 if (!IS_ERR_OR_NULL(clki->clk)) {
6765 if (skip_ref_clk && !strcmp(clki->name, "ref_clk"))
6766 continue;
6768 clk_state_changed = on ^ clki->enabled;
6769 if (on && !clki->enabled) {
6770 ret = clk_prepare_enable(clki->clk);
6771 if (ret) {
6772 dev_err(hba->dev, "%s: %s prepare enable failed, %d\n",
6773 __func__, clki->name, ret);
6774 goto out;
6776 } else if (!on && clki->enabled) {
6777 clk_disable_unprepare(clki->clk);
6779 clki->enabled = on;
6780 dev_dbg(hba->dev, "%s: clk: %s %sabled\n", __func__,
6781 clki->name, on ? "en" : "dis");
6785 ret = ufshcd_vops_setup_clocks(hba, on, POST_CHANGE);
6786 if (ret)
6787 return ret;
6789 out:
6790 if (ret) {
6791 list_for_each_entry(clki, head, list) {
6792 if (!IS_ERR_OR_NULL(clki->clk) && clki->enabled)
6793 clk_disable_unprepare(clki->clk);
6795 } else if (!ret && on) {
6796 spin_lock_irqsave(hba->host->host_lock, flags);
6797 hba->clk_gating.state = CLKS_ON;
6798 trace_ufshcd_clk_gating(dev_name(hba->dev),
6799 hba->clk_gating.state);
6800 spin_unlock_irqrestore(hba->host->host_lock, flags);
6803 if (clk_state_changed)
6804 trace_ufshcd_profile_clk_gating(dev_name(hba->dev),
6805 (on ? "on" : "off"),
6806 ktime_to_us(ktime_sub(ktime_get(), start)), ret);
6807 return ret;
6810 static int ufshcd_setup_clocks(struct ufs_hba *hba, bool on)
6812 return __ufshcd_setup_clocks(hba, on, false);
6815 static int ufshcd_init_clocks(struct ufs_hba *hba)
6817 int ret = 0;
6818 struct ufs_clk_info *clki;
6819 struct device *dev = hba->dev;
6820 struct list_head *head = &hba->clk_list_head;
6822 if (list_empty(head))
6823 goto out;
6825 list_for_each_entry(clki, head, list) {
6826 if (!clki->name)
6827 continue;
6829 clki->clk = devm_clk_get(dev, clki->name);
6830 if (IS_ERR(clki->clk)) {
6831 ret = PTR_ERR(clki->clk);
6832 dev_err(dev, "%s: %s clk get failed, %d\n",
6833 __func__, clki->name, ret);
6834 goto out;
6837 if (clki->max_freq) {
6838 ret = clk_set_rate(clki->clk, clki->max_freq);
6839 if (ret) {
6840 dev_err(hba->dev, "%s: %s clk set rate(%dHz) failed, %d\n",
6841 __func__, clki->name,
6842 clki->max_freq, ret);
6843 goto out;
6845 clki->curr_freq = clki->max_freq;
6847 dev_dbg(dev, "%s: clk: %s, rate: %lu\n", __func__,
6848 clki->name, clk_get_rate(clki->clk));
6850 out:
6851 return ret;
6854 static int ufshcd_variant_hba_init(struct ufs_hba *hba)
6856 int err = 0;
6858 if (!hba->vops)
6859 goto out;
6861 err = ufshcd_vops_init(hba);
6862 if (err)
6863 goto out;
6865 err = ufshcd_vops_setup_regulators(hba, true);
6866 if (err)
6867 goto out_exit;
6869 goto out;
6871 out_exit:
6872 ufshcd_vops_exit(hba);
6873 out:
6874 if (err)
6875 dev_err(hba->dev, "%s: variant %s init failed err %d\n",
6876 __func__, ufshcd_get_var_name(hba), err);
6877 return err;
6880 static void ufshcd_variant_hba_exit(struct ufs_hba *hba)
6882 if (!hba->vops)
6883 return;
6885 ufshcd_vops_setup_regulators(hba, false);
6887 ufshcd_vops_exit(hba);
6890 static int ufshcd_hba_init(struct ufs_hba *hba)
6892 int err;
6895 * Handle host controller power separately from the UFS device power
6896 * rails as it will help controlling the UFS host controller power
6897 * collapse easily which is different than UFS device power collapse.
6898 * Also, enable the host controller power before we go ahead with rest
6899 * of the initialization here.
6901 err = ufshcd_init_hba_vreg(hba);
6902 if (err)
6903 goto out;
6905 err = ufshcd_setup_hba_vreg(hba, true);
6906 if (err)
6907 goto out;
6909 err = ufshcd_init_clocks(hba);
6910 if (err)
6911 goto out_disable_hba_vreg;
6913 err = ufshcd_setup_clocks(hba, true);
6914 if (err)
6915 goto out_disable_hba_vreg;
6917 err = ufshcd_init_vreg(hba);
6918 if (err)
6919 goto out_disable_clks;
6921 err = ufshcd_setup_vreg(hba, true);
6922 if (err)
6923 goto out_disable_clks;
6925 err = ufshcd_variant_hba_init(hba);
6926 if (err)
6927 goto out_disable_vreg;
6929 hba->is_powered = true;
6930 goto out;
6932 out_disable_vreg:
6933 ufshcd_setup_vreg(hba, false);
6934 out_disable_clks:
6935 ufshcd_setup_clocks(hba, false);
6936 out_disable_hba_vreg:
6937 ufshcd_setup_hba_vreg(hba, false);
6938 out:
6939 return err;
6942 static void ufshcd_hba_exit(struct ufs_hba *hba)
6944 if (hba->is_powered) {
6945 ufshcd_variant_hba_exit(hba);
6946 ufshcd_setup_vreg(hba, false);
6947 ufshcd_suspend_clkscaling(hba);
6948 if (ufshcd_is_clkscaling_supported(hba)) {
6949 if (hba->devfreq)
6950 ufshcd_suspend_clkscaling(hba);
6951 destroy_workqueue(hba->clk_scaling.workq);
6953 ufshcd_setup_clocks(hba, false);
6954 ufshcd_setup_hba_vreg(hba, false);
6955 hba->is_powered = false;
6959 static int
6960 ufshcd_send_request_sense(struct ufs_hba *hba, struct scsi_device *sdp)
6962 unsigned char cmd[6] = {REQUEST_SENSE,
6966 UFSHCD_REQ_SENSE_SIZE,
6968 char *buffer;
6969 int ret;
6971 buffer = kzalloc(UFSHCD_REQ_SENSE_SIZE, GFP_KERNEL);
6972 if (!buffer) {
6973 ret = -ENOMEM;
6974 goto out;
6977 ret = scsi_execute(sdp, cmd, DMA_FROM_DEVICE, buffer,
6978 UFSHCD_REQ_SENSE_SIZE, NULL, NULL,
6979 msecs_to_jiffies(1000), 3, 0, RQF_PM, NULL);
6980 if (ret)
6981 pr_err("%s: failed with err %d\n", __func__, ret);
6983 kfree(buffer);
6984 out:
6985 return ret;
6989 * ufshcd_set_dev_pwr_mode - sends START STOP UNIT command to set device
6990 * power mode
6991 * @hba: per adapter instance
6992 * @pwr_mode: device power mode to set
6994 * Returns 0 if requested power mode is set successfully
6995 * Returns non-zero if failed to set the requested power mode
6997 static int ufshcd_set_dev_pwr_mode(struct ufs_hba *hba,
6998 enum ufs_dev_pwr_mode pwr_mode)
7000 unsigned char cmd[6] = { START_STOP };
7001 struct scsi_sense_hdr sshdr;
7002 struct scsi_device *sdp;
7003 unsigned long flags;
7004 int ret;
7006 spin_lock_irqsave(hba->host->host_lock, flags);
7007 sdp = hba->sdev_ufs_device;
7008 if (sdp) {
7009 ret = scsi_device_get(sdp);
7010 if (!ret && !scsi_device_online(sdp)) {
7011 ret = -ENODEV;
7012 scsi_device_put(sdp);
7014 } else {
7015 ret = -ENODEV;
7017 spin_unlock_irqrestore(hba->host->host_lock, flags);
7019 if (ret)
7020 return ret;
7023 * If scsi commands fail, the scsi mid-layer schedules scsi error-
7024 * handling, which would wait for host to be resumed. Since we know
7025 * we are functional while we are here, skip host resume in error
7026 * handling context.
7028 hba->host->eh_noresume = 1;
7029 if (hba->wlun_dev_clr_ua) {
7030 ret = ufshcd_send_request_sense(hba, sdp);
7031 if (ret)
7032 goto out;
7033 /* Unit attention condition is cleared now */
7034 hba->wlun_dev_clr_ua = false;
7037 cmd[4] = pwr_mode << 4;
7040 * Current function would be generally called from the power management
7041 * callbacks hence set the RQF_PM flag so that it doesn't resume the
7042 * already suspended childs.
7044 ret = scsi_execute(sdp, cmd, DMA_NONE, NULL, 0, NULL, &sshdr,
7045 START_STOP_TIMEOUT, 0, 0, RQF_PM, NULL);
7046 if (ret) {
7047 sdev_printk(KERN_WARNING, sdp,
7048 "START_STOP failed for power mode: %d, result %x\n",
7049 pwr_mode, ret);
7050 if (driver_byte(ret) & DRIVER_SENSE)
7051 scsi_print_sense_hdr(sdp, NULL, &sshdr);
7054 if (!ret)
7055 hba->curr_dev_pwr_mode = pwr_mode;
7056 out:
7057 scsi_device_put(sdp);
7058 hba->host->eh_noresume = 0;
7059 return ret;
7062 static int ufshcd_link_state_transition(struct ufs_hba *hba,
7063 enum uic_link_state req_link_state,
7064 int check_for_bkops)
7066 int ret = 0;
7068 if (req_link_state == hba->uic_link_state)
7069 return 0;
7071 if (req_link_state == UIC_LINK_HIBERN8_STATE) {
7072 ret = ufshcd_uic_hibern8_enter(hba);
7073 if (!ret)
7074 ufshcd_set_link_hibern8(hba);
7075 else
7076 goto out;
7079 * If autobkops is enabled, link can't be turned off because
7080 * turning off the link would also turn off the device.
7082 else if ((req_link_state == UIC_LINK_OFF_STATE) &&
7083 (!check_for_bkops || (check_for_bkops &&
7084 !hba->auto_bkops_enabled))) {
7086 * Let's make sure that link is in low power mode, we are doing
7087 * this currently by putting the link in Hibern8. Otherway to
7088 * put the link in low power mode is to send the DME end point
7089 * to device and then send the DME reset command to local
7090 * unipro. But putting the link in hibern8 is much faster.
7092 ret = ufshcd_uic_hibern8_enter(hba);
7093 if (ret)
7094 goto out;
7096 * Change controller state to "reset state" which
7097 * should also put the link in off/reset state
7099 ufshcd_hba_stop(hba, true);
7101 * TODO: Check if we need any delay to make sure that
7102 * controller is reset
7104 ufshcd_set_link_off(hba);
7107 out:
7108 return ret;
7111 static void ufshcd_vreg_set_lpm(struct ufs_hba *hba)
7114 * It seems some UFS devices may keep drawing more than sleep current
7115 * (atleast for 500us) from UFS rails (especially from VCCQ rail).
7116 * To avoid this situation, add 2ms delay before putting these UFS
7117 * rails in LPM mode.
7119 if (!ufshcd_is_link_active(hba) &&
7120 hba->dev_quirks & UFS_DEVICE_QUIRK_DELAY_BEFORE_LPM)
7121 usleep_range(2000, 2100);
7124 * If UFS device is either in UFS_Sleep turn off VCC rail to save some
7125 * power.
7127 * If UFS device and link is in OFF state, all power supplies (VCC,
7128 * VCCQ, VCCQ2) can be turned off if power on write protect is not
7129 * required. If UFS link is inactive (Hibern8 or OFF state) and device
7130 * is in sleep state, put VCCQ & VCCQ2 rails in LPM mode.
7132 * Ignore the error returned by ufshcd_toggle_vreg() as device is anyway
7133 * in low power state which would save some power.
7135 if (ufshcd_is_ufs_dev_poweroff(hba) && ufshcd_is_link_off(hba) &&
7136 !hba->dev_info.is_lu_power_on_wp) {
7137 ufshcd_setup_vreg(hba, false);
7138 } else if (!ufshcd_is_ufs_dev_active(hba)) {
7139 ufshcd_toggle_vreg(hba->dev, hba->vreg_info.vcc, false);
7140 if (!ufshcd_is_link_active(hba)) {
7141 ufshcd_config_vreg_lpm(hba, hba->vreg_info.vccq);
7142 ufshcd_config_vreg_lpm(hba, hba->vreg_info.vccq2);
7147 static int ufshcd_vreg_set_hpm(struct ufs_hba *hba)
7149 int ret = 0;
7151 if (ufshcd_is_ufs_dev_poweroff(hba) && ufshcd_is_link_off(hba) &&
7152 !hba->dev_info.is_lu_power_on_wp) {
7153 ret = ufshcd_setup_vreg(hba, true);
7154 } else if (!ufshcd_is_ufs_dev_active(hba)) {
7155 if (!ret && !ufshcd_is_link_active(hba)) {
7156 ret = ufshcd_config_vreg_hpm(hba, hba->vreg_info.vccq);
7157 if (ret)
7158 goto vcc_disable;
7159 ret = ufshcd_config_vreg_hpm(hba, hba->vreg_info.vccq2);
7160 if (ret)
7161 goto vccq_lpm;
7163 ret = ufshcd_toggle_vreg(hba->dev, hba->vreg_info.vcc, true);
7165 goto out;
7167 vccq_lpm:
7168 ufshcd_config_vreg_lpm(hba, hba->vreg_info.vccq);
7169 vcc_disable:
7170 ufshcd_toggle_vreg(hba->dev, hba->vreg_info.vcc, false);
7171 out:
7172 return ret;
7175 static void ufshcd_hba_vreg_set_lpm(struct ufs_hba *hba)
7177 if (ufshcd_is_link_off(hba))
7178 ufshcd_setup_hba_vreg(hba, false);
7181 static void ufshcd_hba_vreg_set_hpm(struct ufs_hba *hba)
7183 if (ufshcd_is_link_off(hba))
7184 ufshcd_setup_hba_vreg(hba, true);
7188 * ufshcd_suspend - helper function for suspend operations
7189 * @hba: per adapter instance
7190 * @pm_op: desired low power operation type
7192 * This function will try to put the UFS device and link into low power
7193 * mode based on the "rpm_lvl" (Runtime PM level) or "spm_lvl"
7194 * (System PM level).
7196 * If this function is called during shutdown, it will make sure that
7197 * both UFS device and UFS link is powered off.
7199 * NOTE: UFS device & link must be active before we enter in this function.
7201 * Returns 0 for success and non-zero for failure
7203 static int ufshcd_suspend(struct ufs_hba *hba, enum ufs_pm_op pm_op)
7205 int ret = 0;
7206 enum ufs_pm_level pm_lvl;
7207 enum ufs_dev_pwr_mode req_dev_pwr_mode;
7208 enum uic_link_state req_link_state;
7210 hba->pm_op_in_progress = 1;
7211 if (!ufshcd_is_shutdown_pm(pm_op)) {
7212 pm_lvl = ufshcd_is_runtime_pm(pm_op) ?
7213 hba->rpm_lvl : hba->spm_lvl;
7214 req_dev_pwr_mode = ufs_get_pm_lvl_to_dev_pwr_mode(pm_lvl);
7215 req_link_state = ufs_get_pm_lvl_to_link_pwr_state(pm_lvl);
7216 } else {
7217 req_dev_pwr_mode = UFS_POWERDOWN_PWR_MODE;
7218 req_link_state = UIC_LINK_OFF_STATE;
7222 * If we can't transition into any of the low power modes
7223 * just gate the clocks.
7225 ufshcd_hold(hba, false);
7226 hba->clk_gating.is_suspended = true;
7228 if (hba->clk_scaling.is_allowed) {
7229 cancel_work_sync(&hba->clk_scaling.suspend_work);
7230 cancel_work_sync(&hba->clk_scaling.resume_work);
7231 ufshcd_suspend_clkscaling(hba);
7234 if (req_dev_pwr_mode == UFS_ACTIVE_PWR_MODE &&
7235 req_link_state == UIC_LINK_ACTIVE_STATE) {
7236 goto disable_clks;
7239 if ((req_dev_pwr_mode == hba->curr_dev_pwr_mode) &&
7240 (req_link_state == hba->uic_link_state))
7241 goto enable_gating;
7243 /* UFS device & link must be active before we enter in this function */
7244 if (!ufshcd_is_ufs_dev_active(hba) || !ufshcd_is_link_active(hba)) {
7245 ret = -EINVAL;
7246 goto enable_gating;
7249 if (ufshcd_is_runtime_pm(pm_op)) {
7250 if (ufshcd_can_autobkops_during_suspend(hba)) {
7252 * The device is idle with no requests in the queue,
7253 * allow background operations if bkops status shows
7254 * that performance might be impacted.
7256 ret = ufshcd_urgent_bkops(hba);
7257 if (ret)
7258 goto enable_gating;
7259 } else {
7260 /* make sure that auto bkops is disabled */
7261 ufshcd_disable_auto_bkops(hba);
7265 if ((req_dev_pwr_mode != hba->curr_dev_pwr_mode) &&
7266 ((ufshcd_is_runtime_pm(pm_op) && !hba->auto_bkops_enabled) ||
7267 !ufshcd_is_runtime_pm(pm_op))) {
7268 /* ensure that bkops is disabled */
7269 ufshcd_disable_auto_bkops(hba);
7270 ret = ufshcd_set_dev_pwr_mode(hba, req_dev_pwr_mode);
7271 if (ret)
7272 goto enable_gating;
7275 ret = ufshcd_link_state_transition(hba, req_link_state, 1);
7276 if (ret)
7277 goto set_dev_active;
7279 ufshcd_vreg_set_lpm(hba);
7281 disable_clks:
7283 * Call vendor specific suspend callback. As these callbacks may access
7284 * vendor specific host controller register space call them before the
7285 * host clocks are ON.
7287 ret = ufshcd_vops_suspend(hba, pm_op);
7288 if (ret)
7289 goto set_link_active;
7291 if (!ufshcd_is_link_active(hba))
7292 ufshcd_setup_clocks(hba, false);
7293 else
7294 /* If link is active, device ref_clk can't be switched off */
7295 __ufshcd_setup_clocks(hba, false, true);
7297 hba->clk_gating.state = CLKS_OFF;
7298 trace_ufshcd_clk_gating(dev_name(hba->dev), hba->clk_gating.state);
7300 * Disable the host irq as host controller as there won't be any
7301 * host controller transaction expected till resume.
7303 ufshcd_disable_irq(hba);
7304 /* Put the host controller in low power mode if possible */
7305 ufshcd_hba_vreg_set_lpm(hba);
7306 goto out;
7308 set_link_active:
7309 if (hba->clk_scaling.is_allowed)
7310 ufshcd_resume_clkscaling(hba);
7311 ufshcd_vreg_set_hpm(hba);
7312 if (ufshcd_is_link_hibern8(hba) && !ufshcd_uic_hibern8_exit(hba))
7313 ufshcd_set_link_active(hba);
7314 else if (ufshcd_is_link_off(hba))
7315 ufshcd_host_reset_and_restore(hba);
7316 set_dev_active:
7317 if (!ufshcd_set_dev_pwr_mode(hba, UFS_ACTIVE_PWR_MODE))
7318 ufshcd_disable_auto_bkops(hba);
7319 enable_gating:
7320 if (hba->clk_scaling.is_allowed)
7321 ufshcd_resume_clkscaling(hba);
7322 hba->clk_gating.is_suspended = false;
7323 ufshcd_release(hba);
7324 out:
7325 hba->pm_op_in_progress = 0;
7326 return ret;
7330 * ufshcd_resume - helper function for resume operations
7331 * @hba: per adapter instance
7332 * @pm_op: runtime PM or system PM
7334 * This function basically brings the UFS device, UniPro link and controller
7335 * to active state.
7337 * Returns 0 for success and non-zero for failure
7339 static int ufshcd_resume(struct ufs_hba *hba, enum ufs_pm_op pm_op)
7341 int ret;
7342 enum uic_link_state old_link_state;
7344 hba->pm_op_in_progress = 1;
7345 old_link_state = hba->uic_link_state;
7347 ufshcd_hba_vreg_set_hpm(hba);
7348 /* Make sure clocks are enabled before accessing controller */
7349 ret = ufshcd_setup_clocks(hba, true);
7350 if (ret)
7351 goto out;
7353 /* enable the host irq as host controller would be active soon */
7354 ret = ufshcd_enable_irq(hba);
7355 if (ret)
7356 goto disable_irq_and_vops_clks;
7358 ret = ufshcd_vreg_set_hpm(hba);
7359 if (ret)
7360 goto disable_irq_and_vops_clks;
7363 * Call vendor specific resume callback. As these callbacks may access
7364 * vendor specific host controller register space call them when the
7365 * host clocks are ON.
7367 ret = ufshcd_vops_resume(hba, pm_op);
7368 if (ret)
7369 goto disable_vreg;
7371 if (ufshcd_is_link_hibern8(hba)) {
7372 ret = ufshcd_uic_hibern8_exit(hba);
7373 if (!ret)
7374 ufshcd_set_link_active(hba);
7375 else
7376 goto vendor_suspend;
7377 } else if (ufshcd_is_link_off(hba)) {
7378 ret = ufshcd_host_reset_and_restore(hba);
7380 * ufshcd_host_reset_and_restore() should have already
7381 * set the link state as active
7383 if (ret || !ufshcd_is_link_active(hba))
7384 goto vendor_suspend;
7387 if (!ufshcd_is_ufs_dev_active(hba)) {
7388 ret = ufshcd_set_dev_pwr_mode(hba, UFS_ACTIVE_PWR_MODE);
7389 if (ret)
7390 goto set_old_link_state;
7393 if (ufshcd_keep_autobkops_enabled_except_suspend(hba))
7394 ufshcd_enable_auto_bkops(hba);
7395 else
7397 * If BKOPs operations are urgently needed at this moment then
7398 * keep auto-bkops enabled or else disable it.
7400 ufshcd_urgent_bkops(hba);
7402 hba->clk_gating.is_suspended = false;
7404 if (hba->clk_scaling.is_allowed)
7405 ufshcd_resume_clkscaling(hba);
7407 /* Schedule clock gating in case of no access to UFS device yet */
7408 ufshcd_release(hba);
7409 goto out;
7411 set_old_link_state:
7412 ufshcd_link_state_transition(hba, old_link_state, 0);
7413 vendor_suspend:
7414 ufshcd_vops_suspend(hba, pm_op);
7415 disable_vreg:
7416 ufshcd_vreg_set_lpm(hba);
7417 disable_irq_and_vops_clks:
7418 ufshcd_disable_irq(hba);
7419 if (hba->clk_scaling.is_allowed)
7420 ufshcd_suspend_clkscaling(hba);
7421 ufshcd_setup_clocks(hba, false);
7422 out:
7423 hba->pm_op_in_progress = 0;
7424 return ret;
7428 * ufshcd_system_suspend - system suspend routine
7429 * @hba: per adapter instance
7430 * @pm_op: runtime PM or system PM
7432 * Check the description of ufshcd_suspend() function for more details.
7434 * Returns 0 for success and non-zero for failure
7436 int ufshcd_system_suspend(struct ufs_hba *hba)
7438 int ret = 0;
7439 ktime_t start = ktime_get();
7441 if (!hba || !hba->is_powered)
7442 return 0;
7444 if ((ufs_get_pm_lvl_to_dev_pwr_mode(hba->spm_lvl) ==
7445 hba->curr_dev_pwr_mode) &&
7446 (ufs_get_pm_lvl_to_link_pwr_state(hba->spm_lvl) ==
7447 hba->uic_link_state))
7448 goto out;
7450 if (pm_runtime_suspended(hba->dev)) {
7452 * UFS device and/or UFS link low power states during runtime
7453 * suspend seems to be different than what is expected during
7454 * system suspend. Hence runtime resume the devic & link and
7455 * let the system suspend low power states to take effect.
7456 * TODO: If resume takes longer time, we might have optimize
7457 * it in future by not resuming everything if possible.
7459 ret = ufshcd_runtime_resume(hba);
7460 if (ret)
7461 goto out;
7464 ret = ufshcd_suspend(hba, UFS_SYSTEM_PM);
7465 out:
7466 trace_ufshcd_system_suspend(dev_name(hba->dev), ret,
7467 ktime_to_us(ktime_sub(ktime_get(), start)),
7468 hba->curr_dev_pwr_mode, hba->uic_link_state);
7469 if (!ret)
7470 hba->is_sys_suspended = true;
7471 return ret;
7473 EXPORT_SYMBOL(ufshcd_system_suspend);
7476 * ufshcd_system_resume - system resume routine
7477 * @hba: per adapter instance
7479 * Returns 0 for success and non-zero for failure
7482 int ufshcd_system_resume(struct ufs_hba *hba)
7484 int ret = 0;
7485 ktime_t start = ktime_get();
7487 if (!hba)
7488 return -EINVAL;
7490 if (!hba->is_powered || pm_runtime_suspended(hba->dev))
7492 * Let the runtime resume take care of resuming
7493 * if runtime suspended.
7495 goto out;
7496 else
7497 ret = ufshcd_resume(hba, UFS_SYSTEM_PM);
7498 out:
7499 trace_ufshcd_system_resume(dev_name(hba->dev), ret,
7500 ktime_to_us(ktime_sub(ktime_get(), start)),
7501 hba->curr_dev_pwr_mode, hba->uic_link_state);
7502 return ret;
7504 EXPORT_SYMBOL(ufshcd_system_resume);
7507 * ufshcd_runtime_suspend - runtime suspend routine
7508 * @hba: per adapter instance
7510 * Check the description of ufshcd_suspend() function for more details.
7512 * Returns 0 for success and non-zero for failure
7514 int ufshcd_runtime_suspend(struct ufs_hba *hba)
7516 int ret = 0;
7517 ktime_t start = ktime_get();
7519 if (!hba)
7520 return -EINVAL;
7522 if (!hba->is_powered)
7523 goto out;
7524 else
7525 ret = ufshcd_suspend(hba, UFS_RUNTIME_PM);
7526 out:
7527 trace_ufshcd_runtime_suspend(dev_name(hba->dev), ret,
7528 ktime_to_us(ktime_sub(ktime_get(), start)),
7529 hba->curr_dev_pwr_mode, hba->uic_link_state);
7530 return ret;
7532 EXPORT_SYMBOL(ufshcd_runtime_suspend);
7535 * ufshcd_runtime_resume - runtime resume routine
7536 * @hba: per adapter instance
7538 * This function basically brings the UFS device, UniPro link and controller
7539 * to active state. Following operations are done in this function:
7541 * 1. Turn on all the controller related clocks
7542 * 2. Bring the UniPro link out of Hibernate state
7543 * 3. If UFS device is in sleep state, turn ON VCC rail and bring the UFS device
7544 * to active state.
7545 * 4. If auto-bkops is enabled on the device, disable it.
7547 * So following would be the possible power state after this function return
7548 * successfully:
7549 * S1: UFS device in Active state with VCC rail ON
7550 * UniPro link in Active state
7551 * All the UFS/UniPro controller clocks are ON
7553 * Returns 0 for success and non-zero for failure
7555 int ufshcd_runtime_resume(struct ufs_hba *hba)
7557 int ret = 0;
7558 ktime_t start = ktime_get();
7560 if (!hba)
7561 return -EINVAL;
7563 if (!hba->is_powered)
7564 goto out;
7565 else
7566 ret = ufshcd_resume(hba, UFS_RUNTIME_PM);
7567 out:
7568 trace_ufshcd_runtime_resume(dev_name(hba->dev), ret,
7569 ktime_to_us(ktime_sub(ktime_get(), start)),
7570 hba->curr_dev_pwr_mode, hba->uic_link_state);
7571 return ret;
7573 EXPORT_SYMBOL(ufshcd_runtime_resume);
7575 int ufshcd_runtime_idle(struct ufs_hba *hba)
7577 return 0;
7579 EXPORT_SYMBOL(ufshcd_runtime_idle);
7581 static inline ssize_t ufshcd_pm_lvl_store(struct device *dev,
7582 struct device_attribute *attr,
7583 const char *buf, size_t count,
7584 bool rpm)
7586 struct ufs_hba *hba = dev_get_drvdata(dev);
7587 unsigned long flags, value;
7589 if (kstrtoul(buf, 0, &value))
7590 return -EINVAL;
7592 if (value >= UFS_PM_LVL_MAX)
7593 return -EINVAL;
7595 spin_lock_irqsave(hba->host->host_lock, flags);
7596 if (rpm)
7597 hba->rpm_lvl = value;
7598 else
7599 hba->spm_lvl = value;
7600 spin_unlock_irqrestore(hba->host->host_lock, flags);
7601 return count;
7604 static ssize_t ufshcd_rpm_lvl_show(struct device *dev,
7605 struct device_attribute *attr, char *buf)
7607 struct ufs_hba *hba = dev_get_drvdata(dev);
7608 int curr_len;
7609 u8 lvl;
7611 curr_len = snprintf(buf, PAGE_SIZE,
7612 "\nCurrent Runtime PM level [%d] => dev_state [%s] link_state [%s]\n",
7613 hba->rpm_lvl,
7614 ufschd_ufs_dev_pwr_mode_to_string(
7615 ufs_pm_lvl_states[hba->rpm_lvl].dev_state),
7616 ufschd_uic_link_state_to_string(
7617 ufs_pm_lvl_states[hba->rpm_lvl].link_state));
7619 curr_len += snprintf((buf + curr_len), (PAGE_SIZE - curr_len),
7620 "\nAll available Runtime PM levels info:\n");
7621 for (lvl = UFS_PM_LVL_0; lvl < UFS_PM_LVL_MAX; lvl++)
7622 curr_len += snprintf((buf + curr_len), (PAGE_SIZE - curr_len),
7623 "\tRuntime PM level [%d] => dev_state [%s] link_state [%s]\n",
7624 lvl,
7625 ufschd_ufs_dev_pwr_mode_to_string(
7626 ufs_pm_lvl_states[lvl].dev_state),
7627 ufschd_uic_link_state_to_string(
7628 ufs_pm_lvl_states[lvl].link_state));
7630 return curr_len;
7633 static ssize_t ufshcd_rpm_lvl_store(struct device *dev,
7634 struct device_attribute *attr, const char *buf, size_t count)
7636 return ufshcd_pm_lvl_store(dev, attr, buf, count, true);
7639 static void ufshcd_add_rpm_lvl_sysfs_nodes(struct ufs_hba *hba)
7641 hba->rpm_lvl_attr.show = ufshcd_rpm_lvl_show;
7642 hba->rpm_lvl_attr.store = ufshcd_rpm_lvl_store;
7643 sysfs_attr_init(&hba->rpm_lvl_attr.attr);
7644 hba->rpm_lvl_attr.attr.name = "rpm_lvl";
7645 hba->rpm_lvl_attr.attr.mode = 0644;
7646 if (device_create_file(hba->dev, &hba->rpm_lvl_attr))
7647 dev_err(hba->dev, "Failed to create sysfs for rpm_lvl\n");
7650 static ssize_t ufshcd_spm_lvl_show(struct device *dev,
7651 struct device_attribute *attr, char *buf)
7653 struct ufs_hba *hba = dev_get_drvdata(dev);
7654 int curr_len;
7655 u8 lvl;
7657 curr_len = snprintf(buf, PAGE_SIZE,
7658 "\nCurrent System PM level [%d] => dev_state [%s] link_state [%s]\n",
7659 hba->spm_lvl,
7660 ufschd_ufs_dev_pwr_mode_to_string(
7661 ufs_pm_lvl_states[hba->spm_lvl].dev_state),
7662 ufschd_uic_link_state_to_string(
7663 ufs_pm_lvl_states[hba->spm_lvl].link_state));
7665 curr_len += snprintf((buf + curr_len), (PAGE_SIZE - curr_len),
7666 "\nAll available System PM levels info:\n");
7667 for (lvl = UFS_PM_LVL_0; lvl < UFS_PM_LVL_MAX; lvl++)
7668 curr_len += snprintf((buf + curr_len), (PAGE_SIZE - curr_len),
7669 "\tSystem PM level [%d] => dev_state [%s] link_state [%s]\n",
7670 lvl,
7671 ufschd_ufs_dev_pwr_mode_to_string(
7672 ufs_pm_lvl_states[lvl].dev_state),
7673 ufschd_uic_link_state_to_string(
7674 ufs_pm_lvl_states[lvl].link_state));
7676 return curr_len;
7679 static ssize_t ufshcd_spm_lvl_store(struct device *dev,
7680 struct device_attribute *attr, const char *buf, size_t count)
7682 return ufshcd_pm_lvl_store(dev, attr, buf, count, false);
7685 static void ufshcd_add_spm_lvl_sysfs_nodes(struct ufs_hba *hba)
7687 hba->spm_lvl_attr.show = ufshcd_spm_lvl_show;
7688 hba->spm_lvl_attr.store = ufshcd_spm_lvl_store;
7689 sysfs_attr_init(&hba->spm_lvl_attr.attr);
7690 hba->spm_lvl_attr.attr.name = "spm_lvl";
7691 hba->spm_lvl_attr.attr.mode = 0644;
7692 if (device_create_file(hba->dev, &hba->spm_lvl_attr))
7693 dev_err(hba->dev, "Failed to create sysfs for spm_lvl\n");
7696 static inline void ufshcd_add_sysfs_nodes(struct ufs_hba *hba)
7698 ufshcd_add_rpm_lvl_sysfs_nodes(hba);
7699 ufshcd_add_spm_lvl_sysfs_nodes(hba);
7702 static inline void ufshcd_remove_sysfs_nodes(struct ufs_hba *hba)
7704 device_remove_file(hba->dev, &hba->rpm_lvl_attr);
7705 device_remove_file(hba->dev, &hba->spm_lvl_attr);
7709 * ufshcd_shutdown - shutdown routine
7710 * @hba: per adapter instance
7712 * This function would power off both UFS device and UFS link.
7714 * Returns 0 always to allow force shutdown even in case of errors.
7716 int ufshcd_shutdown(struct ufs_hba *hba)
7718 int ret = 0;
7720 if (ufshcd_is_ufs_dev_poweroff(hba) && ufshcd_is_link_off(hba))
7721 goto out;
7723 if (pm_runtime_suspended(hba->dev)) {
7724 ret = ufshcd_runtime_resume(hba);
7725 if (ret)
7726 goto out;
7729 ret = ufshcd_suspend(hba, UFS_SHUTDOWN_PM);
7730 out:
7731 if (ret)
7732 dev_err(hba->dev, "%s failed, err %d\n", __func__, ret);
7733 /* allow force shutdown even in case of errors */
7734 return 0;
7736 EXPORT_SYMBOL(ufshcd_shutdown);
7739 * ufshcd_remove - de-allocate SCSI host and host memory space
7740 * data structure memory
7741 * @hba - per adapter instance
7743 void ufshcd_remove(struct ufs_hba *hba)
7745 ufshcd_remove_sysfs_nodes(hba);
7746 scsi_remove_host(hba->host);
7747 /* disable interrupts */
7748 ufshcd_disable_intr(hba, hba->intr_mask);
7749 ufshcd_hba_stop(hba, true);
7751 ufshcd_exit_clk_gating(hba);
7752 if (ufshcd_is_clkscaling_supported(hba))
7753 device_remove_file(hba->dev, &hba->clk_scaling.enable_attr);
7754 ufshcd_hba_exit(hba);
7756 EXPORT_SYMBOL_GPL(ufshcd_remove);
7759 * ufshcd_dealloc_host - deallocate Host Bus Adapter (HBA)
7760 * @hba: pointer to Host Bus Adapter (HBA)
7762 void ufshcd_dealloc_host(struct ufs_hba *hba)
7764 scsi_host_put(hba->host);
7766 EXPORT_SYMBOL_GPL(ufshcd_dealloc_host);
7769 * ufshcd_set_dma_mask - Set dma mask based on the controller
7770 * addressing capability
7771 * @hba: per adapter instance
7773 * Returns 0 for success, non-zero for failure
7775 static int ufshcd_set_dma_mask(struct ufs_hba *hba)
7777 if (hba->capabilities & MASK_64_ADDRESSING_SUPPORT) {
7778 if (!dma_set_mask_and_coherent(hba->dev, DMA_BIT_MASK(64)))
7779 return 0;
7781 return dma_set_mask_and_coherent(hba->dev, DMA_BIT_MASK(32));
7785 * ufshcd_alloc_host - allocate Host Bus Adapter (HBA)
7786 * @dev: pointer to device handle
7787 * @hba_handle: driver private handle
7788 * Returns 0 on success, non-zero value on failure
7790 int ufshcd_alloc_host(struct device *dev, struct ufs_hba **hba_handle)
7792 struct Scsi_Host *host;
7793 struct ufs_hba *hba;
7794 int err = 0;
7796 if (!dev) {
7797 dev_err(dev,
7798 "Invalid memory reference for dev is NULL\n");
7799 err = -ENODEV;
7800 goto out_error;
7803 host = scsi_host_alloc(&ufshcd_driver_template,
7804 sizeof(struct ufs_hba));
7805 if (!host) {
7806 dev_err(dev, "scsi_host_alloc failed\n");
7807 err = -ENOMEM;
7808 goto out_error;
7810 hba = shost_priv(host);
7811 hba->host = host;
7812 hba->dev = dev;
7813 *hba_handle = hba;
7815 INIT_LIST_HEAD(&hba->clk_list_head);
7817 out_error:
7818 return err;
7820 EXPORT_SYMBOL(ufshcd_alloc_host);
7823 * ufshcd_init - Driver initialization routine
7824 * @hba: per-adapter instance
7825 * @mmio_base: base register address
7826 * @irq: Interrupt line of device
7827 * Returns 0 on success, non-zero value on failure
7829 int ufshcd_init(struct ufs_hba *hba, void __iomem *mmio_base, unsigned int irq)
7831 int err;
7832 struct Scsi_Host *host = hba->host;
7833 struct device *dev = hba->dev;
7835 if (!mmio_base) {
7836 dev_err(hba->dev,
7837 "Invalid memory reference for mmio_base is NULL\n");
7838 err = -ENODEV;
7839 goto out_error;
7842 hba->mmio_base = mmio_base;
7843 hba->irq = irq;
7845 /* Set descriptor lengths to specification defaults */
7846 ufshcd_def_desc_sizes(hba);
7848 err = ufshcd_hba_init(hba);
7849 if (err)
7850 goto out_error;
7852 /* Read capabilities registers */
7853 ufshcd_hba_capabilities(hba);
7855 /* Get UFS version supported by the controller */
7856 hba->ufs_version = ufshcd_get_ufs_version(hba);
7858 if ((hba->ufs_version != UFSHCI_VERSION_10) &&
7859 (hba->ufs_version != UFSHCI_VERSION_11) &&
7860 (hba->ufs_version != UFSHCI_VERSION_20) &&
7861 (hba->ufs_version != UFSHCI_VERSION_21))
7862 dev_err(hba->dev, "invalid UFS version 0x%x\n",
7863 hba->ufs_version);
7865 /* Get Interrupt bit mask per version */
7866 hba->intr_mask = ufshcd_get_intr_mask(hba);
7868 err = ufshcd_set_dma_mask(hba);
7869 if (err) {
7870 dev_err(hba->dev, "set dma mask failed\n");
7871 goto out_disable;
7874 /* Allocate memory for host memory space */
7875 err = ufshcd_memory_alloc(hba);
7876 if (err) {
7877 dev_err(hba->dev, "Memory allocation failed\n");
7878 goto out_disable;
7881 /* Configure LRB */
7882 ufshcd_host_memory_configure(hba);
7884 host->can_queue = hba->nutrs;
7885 host->cmd_per_lun = hba->nutrs;
7886 host->max_id = UFSHCD_MAX_ID;
7887 host->max_lun = UFS_MAX_LUNS;
7888 host->max_channel = UFSHCD_MAX_CHANNEL;
7889 host->unique_id = host->host_no;
7890 host->max_cmd_len = MAX_CDB_SIZE;
7892 hba->max_pwr_info.is_valid = false;
7894 /* Initailize wait queue for task management */
7895 init_waitqueue_head(&hba->tm_wq);
7896 init_waitqueue_head(&hba->tm_tag_wq);
7898 /* Initialize work queues */
7899 INIT_WORK(&hba->eh_work, ufshcd_err_handler);
7900 INIT_WORK(&hba->eeh_work, ufshcd_exception_event_handler);
7902 /* Initialize UIC command mutex */
7903 mutex_init(&hba->uic_cmd_mutex);
7905 /* Initialize mutex for device management commands */
7906 mutex_init(&hba->dev_cmd.lock);
7908 init_rwsem(&hba->clk_scaling_lock);
7910 /* Initialize device management tag acquire wait queue */
7911 init_waitqueue_head(&hba->dev_cmd.tag_wq);
7913 ufshcd_init_clk_gating(hba);
7916 * In order to avoid any spurious interrupt immediately after
7917 * registering UFS controller interrupt handler, clear any pending UFS
7918 * interrupt status and disable all the UFS interrupts.
7920 ufshcd_writel(hba, ufshcd_readl(hba, REG_INTERRUPT_STATUS),
7921 REG_INTERRUPT_STATUS);
7922 ufshcd_writel(hba, 0, REG_INTERRUPT_ENABLE);
7924 * Make sure that UFS interrupts are disabled and any pending interrupt
7925 * status is cleared before registering UFS interrupt handler.
7927 mb();
7929 /* IRQ registration */
7930 err = devm_request_irq(dev, irq, ufshcd_intr, IRQF_SHARED, UFSHCD, hba);
7931 if (err) {
7932 dev_err(hba->dev, "request irq failed\n");
7933 goto exit_gating;
7934 } else {
7935 hba->is_irq_enabled = true;
7938 err = scsi_add_host(host, hba->dev);
7939 if (err) {
7940 dev_err(hba->dev, "scsi_add_host failed\n");
7941 goto exit_gating;
7944 /* Host controller enable */
7945 err = ufshcd_hba_enable(hba);
7946 if (err) {
7947 dev_err(hba->dev, "Host controller enable failed\n");
7948 ufshcd_print_host_regs(hba);
7949 ufshcd_print_host_state(hba);
7950 goto out_remove_scsi_host;
7953 if (ufshcd_is_clkscaling_supported(hba)) {
7954 char wq_name[sizeof("ufs_clkscaling_00")];
7956 INIT_WORK(&hba->clk_scaling.suspend_work,
7957 ufshcd_clk_scaling_suspend_work);
7958 INIT_WORK(&hba->clk_scaling.resume_work,
7959 ufshcd_clk_scaling_resume_work);
7961 snprintf(wq_name, sizeof(wq_name), "ufs_clkscaling_%d",
7962 host->host_no);
7963 hba->clk_scaling.workq = create_singlethread_workqueue(wq_name);
7965 ufshcd_clkscaling_init_sysfs(hba);
7969 * Set the default power management level for runtime and system PM.
7970 * Default power saving mode is to keep UFS link in Hibern8 state
7971 * and UFS device in sleep state.
7973 hba->rpm_lvl = ufs_get_desired_pm_lvl_for_dev_link_state(
7974 UFS_SLEEP_PWR_MODE,
7975 UIC_LINK_HIBERN8_STATE);
7976 hba->spm_lvl = ufs_get_desired_pm_lvl_for_dev_link_state(
7977 UFS_SLEEP_PWR_MODE,
7978 UIC_LINK_HIBERN8_STATE);
7980 /* Hold auto suspend until async scan completes */
7981 pm_runtime_get_sync(dev);
7984 * We are assuming that device wasn't put in sleep/power-down
7985 * state exclusively during the boot stage before kernel.
7986 * This assumption helps avoid doing link startup twice during
7987 * ufshcd_probe_hba().
7989 ufshcd_set_ufs_dev_active(hba);
7991 async_schedule(ufshcd_async_scan, hba);
7992 ufshcd_add_sysfs_nodes(hba);
7994 return 0;
7996 out_remove_scsi_host:
7997 scsi_remove_host(hba->host);
7998 exit_gating:
7999 ufshcd_exit_clk_gating(hba);
8000 out_disable:
8001 hba->is_irq_enabled = false;
8002 ufshcd_hba_exit(hba);
8003 out_error:
8004 return err;
8006 EXPORT_SYMBOL_GPL(ufshcd_init);
8008 MODULE_AUTHOR("Santosh Yaragnavi <santosh.sy@samsung.com>");
8009 MODULE_AUTHOR("Vinayak Holikatti <h.vinayak@samsung.com>");
8010 MODULE_DESCRIPTION("Generic UFS host controller driver Core");
8011 MODULE_LICENSE("GPL");
8012 MODULE_VERSION(UFSHCD_DRIVER_VERSION);