Revert "tty: hvc: Fix data abort due to race in hvc_open"
[linux/fpc-iii.git] / drivers / scsi / ufs / ufshcd.c
blob52740b60d78692ade175244dbd0c38ebe684f0ba
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 <linux/bitfield.h>
45 #include <linux/blk-pm.h>
46 #include "ufshcd.h"
47 #include "ufs_quirks.h"
48 #include "unipro.h"
49 #include "ufs-sysfs.h"
50 #include "ufs_bsg.h"
52 #define CREATE_TRACE_POINTS
53 #include <trace/events/ufs.h>
55 #define UFSHCD_ENABLE_INTRS (UTP_TRANSFER_REQ_COMPL |\
56 UTP_TASK_REQ_COMPL |\
57 UFSHCD_ERROR_MASK)
58 /* UIC command timeout, unit: ms */
59 #define UIC_CMD_TIMEOUT 500
61 /* NOP OUT retries waiting for NOP IN response */
62 #define NOP_OUT_RETRIES 10
63 /* Timeout after 30 msecs if NOP OUT hangs without response */
64 #define NOP_OUT_TIMEOUT 30 /* msecs */
66 /* Query request retries */
67 #define QUERY_REQ_RETRIES 3
68 /* Query request timeout */
69 #define QUERY_REQ_TIMEOUT 1500 /* 1.5 seconds */
71 /* Task management command timeout */
72 #define TM_CMD_TIMEOUT 100 /* msecs */
74 /* maximum number of retries for a general UIC command */
75 #define UFS_UIC_COMMAND_RETRIES 3
77 /* maximum number of link-startup retries */
78 #define DME_LINKSTARTUP_RETRIES 3
80 /* Maximum retries for Hibern8 enter */
81 #define UIC_HIBERN8_ENTER_RETRIES 3
83 /* maximum number of reset retries before giving up */
84 #define MAX_HOST_RESET_RETRIES 5
86 /* Expose the flag value from utp_upiu_query.value */
87 #define MASK_QUERY_UPIU_FLAG_LOC 0xFF
89 /* Interrupt aggregation default timeout, unit: 40us */
90 #define INT_AGGR_DEF_TO 0x02
92 /* default delay of autosuspend: 2000 ms */
93 #define RPM_AUTOSUSPEND_DELAY_MS 2000
95 /* Default value of wait time before gating device ref clock */
96 #define UFSHCD_REF_CLK_GATING_WAIT_US 0xFF /* microsecs */
98 #define ufshcd_toggle_vreg(_dev, _vreg, _on) \
99 ({ \
100 int _ret; \
101 if (_on) \
102 _ret = ufshcd_enable_vreg(_dev, _vreg); \
103 else \
104 _ret = ufshcd_disable_vreg(_dev, _vreg); \
105 _ret; \
108 #define ufshcd_hex_dump(prefix_str, buf, len) do { \
109 size_t __len = (len); \
110 print_hex_dump(KERN_ERR, prefix_str, \
111 __len > 4 ? DUMP_PREFIX_OFFSET : DUMP_PREFIX_NONE,\
112 16, 4, buf, __len, false); \
113 } while (0)
115 int ufshcd_dump_regs(struct ufs_hba *hba, size_t offset, size_t len,
116 const char *prefix)
118 u32 *regs;
119 size_t pos;
121 if (offset % 4 != 0 || len % 4 != 0) /* keep readl happy */
122 return -EINVAL;
124 regs = kzalloc(len, GFP_ATOMIC);
125 if (!regs)
126 return -ENOMEM;
128 for (pos = 0; pos < len; pos += 4)
129 regs[pos / 4] = ufshcd_readl(hba, offset + pos);
131 ufshcd_hex_dump(prefix, regs, len);
132 kfree(regs);
134 return 0;
136 EXPORT_SYMBOL_GPL(ufshcd_dump_regs);
138 enum {
139 UFSHCD_MAX_CHANNEL = 0,
140 UFSHCD_MAX_ID = 1,
141 UFSHCD_CMD_PER_LUN = 32,
142 UFSHCD_CAN_QUEUE = 32,
145 /* UFSHCD states */
146 enum {
147 UFSHCD_STATE_RESET,
148 UFSHCD_STATE_ERROR,
149 UFSHCD_STATE_OPERATIONAL,
150 UFSHCD_STATE_EH_SCHEDULED,
153 /* UFSHCD error handling flags */
154 enum {
155 UFSHCD_EH_IN_PROGRESS = (1 << 0),
158 /* UFSHCD UIC layer error flags */
159 enum {
160 UFSHCD_UIC_DL_PA_INIT_ERROR = (1 << 0), /* Data link layer error */
161 UFSHCD_UIC_DL_NAC_RECEIVED_ERROR = (1 << 1), /* Data link layer error */
162 UFSHCD_UIC_DL_TCx_REPLAY_ERROR = (1 << 2), /* Data link layer error */
163 UFSHCD_UIC_NL_ERROR = (1 << 3), /* Network layer error */
164 UFSHCD_UIC_TL_ERROR = (1 << 4), /* Transport Layer error */
165 UFSHCD_UIC_DME_ERROR = (1 << 5), /* DME error */
168 #define ufshcd_set_eh_in_progress(h) \
169 ((h)->eh_flags |= UFSHCD_EH_IN_PROGRESS)
170 #define ufshcd_eh_in_progress(h) \
171 ((h)->eh_flags & UFSHCD_EH_IN_PROGRESS)
172 #define ufshcd_clear_eh_in_progress(h) \
173 ((h)->eh_flags &= ~UFSHCD_EH_IN_PROGRESS)
175 struct ufs_pm_lvl_states ufs_pm_lvl_states[] = {
176 {UFS_ACTIVE_PWR_MODE, UIC_LINK_ACTIVE_STATE},
177 {UFS_ACTIVE_PWR_MODE, UIC_LINK_HIBERN8_STATE},
178 {UFS_SLEEP_PWR_MODE, UIC_LINK_ACTIVE_STATE},
179 {UFS_SLEEP_PWR_MODE, UIC_LINK_HIBERN8_STATE},
180 {UFS_POWERDOWN_PWR_MODE, UIC_LINK_HIBERN8_STATE},
181 {UFS_POWERDOWN_PWR_MODE, UIC_LINK_OFF_STATE},
184 static inline enum ufs_dev_pwr_mode
185 ufs_get_pm_lvl_to_dev_pwr_mode(enum ufs_pm_level lvl)
187 return ufs_pm_lvl_states[lvl].dev_state;
190 static inline enum uic_link_state
191 ufs_get_pm_lvl_to_link_pwr_state(enum ufs_pm_level lvl)
193 return ufs_pm_lvl_states[lvl].link_state;
196 static inline enum ufs_pm_level
197 ufs_get_desired_pm_lvl_for_dev_link_state(enum ufs_dev_pwr_mode dev_state,
198 enum uic_link_state link_state)
200 enum ufs_pm_level lvl;
202 for (lvl = UFS_PM_LVL_0; lvl < UFS_PM_LVL_MAX; lvl++) {
203 if ((ufs_pm_lvl_states[lvl].dev_state == dev_state) &&
204 (ufs_pm_lvl_states[lvl].link_state == link_state))
205 return lvl;
208 /* if no match found, return the level 0 */
209 return UFS_PM_LVL_0;
212 static struct ufs_dev_fix ufs_fixups[] = {
213 /* UFS cards deviations table */
214 UFS_FIX(UFS_VENDOR_SAMSUNG, UFS_ANY_MODEL,
215 UFS_DEVICE_QUIRK_DELAY_BEFORE_LPM),
216 UFS_FIX(UFS_VENDOR_SAMSUNG, UFS_ANY_MODEL,
217 UFS_DEVICE_QUIRK_RECOVERY_FROM_DL_NAC_ERRORS),
218 UFS_FIX(UFS_VENDOR_SAMSUNG, UFS_ANY_MODEL,
219 UFS_DEVICE_QUIRK_HOST_PA_TACTIVATE),
220 UFS_FIX(UFS_VENDOR_TOSHIBA, UFS_ANY_MODEL,
221 UFS_DEVICE_QUIRK_DELAY_BEFORE_LPM),
222 UFS_FIX(UFS_VENDOR_TOSHIBA, "THGLF2G9C8KBADG",
223 UFS_DEVICE_QUIRK_PA_TACTIVATE),
224 UFS_FIX(UFS_VENDOR_TOSHIBA, "THGLF2G9D8KBADG",
225 UFS_DEVICE_QUIRK_PA_TACTIVATE),
226 UFS_FIX(UFS_VENDOR_SKHYNIX, UFS_ANY_MODEL,
227 UFS_DEVICE_QUIRK_HOST_PA_SAVECONFIGTIME),
228 UFS_FIX(UFS_VENDOR_SKHYNIX, "hB8aL1" /*H28U62301AMR*/,
229 UFS_DEVICE_QUIRK_HOST_VS_DEBUGSAVECONFIGTIME),
231 END_FIX
234 static irqreturn_t ufshcd_tmc_handler(struct ufs_hba *hba);
235 static void ufshcd_async_scan(void *data, async_cookie_t cookie);
236 static int ufshcd_reset_and_restore(struct ufs_hba *hba);
237 static int ufshcd_eh_host_reset_handler(struct scsi_cmnd *cmd);
238 static int ufshcd_clear_tm_cmd(struct ufs_hba *hba, int tag);
239 static void ufshcd_hba_exit(struct ufs_hba *hba);
240 static int ufshcd_probe_hba(struct ufs_hba *hba, bool async);
241 static int __ufshcd_setup_clocks(struct ufs_hba *hba, bool on,
242 bool skip_ref_clk);
243 static int ufshcd_setup_clocks(struct ufs_hba *hba, bool on);
244 static int ufshcd_uic_hibern8_enter(struct ufs_hba *hba);
245 static inline void ufshcd_add_delay_before_dme_cmd(struct ufs_hba *hba);
246 static int ufshcd_host_reset_and_restore(struct ufs_hba *hba);
247 static void ufshcd_resume_clkscaling(struct ufs_hba *hba);
248 static void ufshcd_suspend_clkscaling(struct ufs_hba *hba);
249 static void __ufshcd_suspend_clkscaling(struct ufs_hba *hba);
250 static int ufshcd_scale_clks(struct ufs_hba *hba, bool scale_up);
251 static irqreturn_t ufshcd_intr(int irq, void *__hba);
252 static int ufshcd_change_power_mode(struct ufs_hba *hba,
253 struct ufs_pa_layer_attr *pwr_mode);
254 static inline bool ufshcd_valid_tag(struct ufs_hba *hba, int tag)
256 return tag >= 0 && tag < hba->nutrs;
259 static inline void ufshcd_enable_irq(struct ufs_hba *hba)
261 if (!hba->is_irq_enabled) {
262 enable_irq(hba->irq);
263 hba->is_irq_enabled = true;
267 static inline void ufshcd_disable_irq(struct ufs_hba *hba)
269 if (hba->is_irq_enabled) {
270 disable_irq(hba->irq);
271 hba->is_irq_enabled = false;
275 static void ufshcd_scsi_unblock_requests(struct ufs_hba *hba)
277 if (atomic_dec_and_test(&hba->scsi_block_reqs_cnt))
278 scsi_unblock_requests(hba->host);
281 static void ufshcd_scsi_block_requests(struct ufs_hba *hba)
283 if (atomic_inc_return(&hba->scsi_block_reqs_cnt) == 1)
284 scsi_block_requests(hba->host);
287 static void ufshcd_add_cmd_upiu_trace(struct ufs_hba *hba, unsigned int tag,
288 const char *str)
290 struct utp_upiu_req *rq = hba->lrb[tag].ucd_req_ptr;
292 trace_ufshcd_upiu(dev_name(hba->dev), str, &rq->header, &rq->sc.cdb);
295 static void ufshcd_add_query_upiu_trace(struct ufs_hba *hba, unsigned int tag,
296 const char *str)
298 struct utp_upiu_req *rq = hba->lrb[tag].ucd_req_ptr;
300 trace_ufshcd_upiu(dev_name(hba->dev), str, &rq->header, &rq->qr);
303 static void ufshcd_add_tm_upiu_trace(struct ufs_hba *hba, unsigned int tag,
304 const char *str)
306 int off = (int)tag - hba->nutrs;
307 struct utp_task_req_desc *descp = &hba->utmrdl_base_addr[off];
309 trace_ufshcd_upiu(dev_name(hba->dev), str, &descp->req_header,
310 &descp->input_param1);
313 static void ufshcd_add_command_trace(struct ufs_hba *hba,
314 unsigned int tag, const char *str)
316 sector_t lba = -1;
317 u8 opcode = 0;
318 u32 intr, doorbell;
319 struct ufshcd_lrb *lrbp = &hba->lrb[tag];
320 struct scsi_cmnd *cmd = lrbp->cmd;
321 int transfer_len = -1;
323 if (!trace_ufshcd_command_enabled()) {
324 /* trace UPIU W/O tracing command */
325 if (cmd)
326 ufshcd_add_cmd_upiu_trace(hba, tag, str);
327 return;
330 if (cmd) { /* data phase exists */
331 /* trace UPIU also */
332 ufshcd_add_cmd_upiu_trace(hba, tag, str);
333 opcode = cmd->cmnd[0];
334 if ((opcode == READ_10) || (opcode == WRITE_10)) {
336 * Currently we only fully trace read(10) and write(10)
337 * commands
339 if (cmd->request && cmd->request->bio)
340 lba = cmd->request->bio->bi_iter.bi_sector;
341 transfer_len = be32_to_cpu(
342 lrbp->ucd_req_ptr->sc.exp_data_transfer_len);
346 intr = ufshcd_readl(hba, REG_INTERRUPT_STATUS);
347 doorbell = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
348 trace_ufshcd_command(dev_name(hba->dev), str, tag,
349 doorbell, transfer_len, intr, lba, opcode);
352 static void ufshcd_print_clk_freqs(struct ufs_hba *hba)
354 struct ufs_clk_info *clki;
355 struct list_head *head = &hba->clk_list_head;
357 if (list_empty(head))
358 return;
360 list_for_each_entry(clki, head, list) {
361 if (!IS_ERR_OR_NULL(clki->clk) && clki->min_freq &&
362 clki->max_freq)
363 dev_err(hba->dev, "clk: %s, rate: %u\n",
364 clki->name, clki->curr_freq);
368 static void ufshcd_print_err_hist(struct ufs_hba *hba,
369 struct ufs_err_reg_hist *err_hist,
370 char *err_name)
372 int i;
373 bool found = false;
375 for (i = 0; i < UFS_ERR_REG_HIST_LENGTH; i++) {
376 int p = (i + err_hist->pos) % UFS_ERR_REG_HIST_LENGTH;
378 if (err_hist->tstamp[p] == 0)
379 continue;
380 dev_err(hba->dev, "%s[%d] = 0x%x at %lld us\n", err_name, p,
381 err_hist->reg[p], ktime_to_us(err_hist->tstamp[p]));
382 found = true;
385 if (!found)
386 dev_err(hba->dev, "No record of %s\n", err_name);
389 static void ufshcd_print_host_regs(struct ufs_hba *hba)
391 ufshcd_dump_regs(hba, 0, UFSHCI_REG_SPACE_SIZE, "host_regs: ");
392 dev_err(hba->dev, "hba->ufs_version = 0x%x, hba->capabilities = 0x%x\n",
393 hba->ufs_version, hba->capabilities);
394 dev_err(hba->dev,
395 "hba->outstanding_reqs = 0x%x, hba->outstanding_tasks = 0x%x\n",
396 (u32)hba->outstanding_reqs, (u32)hba->outstanding_tasks);
397 dev_err(hba->dev,
398 "last_hibern8_exit_tstamp at %lld us, hibern8_exit_cnt = %d\n",
399 ktime_to_us(hba->ufs_stats.last_hibern8_exit_tstamp),
400 hba->ufs_stats.hibern8_exit_cnt);
402 ufshcd_print_err_hist(hba, &hba->ufs_stats.pa_err, "pa_err");
403 ufshcd_print_err_hist(hba, &hba->ufs_stats.dl_err, "dl_err");
404 ufshcd_print_err_hist(hba, &hba->ufs_stats.nl_err, "nl_err");
405 ufshcd_print_err_hist(hba, &hba->ufs_stats.tl_err, "tl_err");
406 ufshcd_print_err_hist(hba, &hba->ufs_stats.dme_err, "dme_err");
407 ufshcd_print_err_hist(hba, &hba->ufs_stats.auto_hibern8_err,
408 "auto_hibern8_err");
409 ufshcd_print_err_hist(hba, &hba->ufs_stats.fatal_err, "fatal_err");
410 ufshcd_print_err_hist(hba, &hba->ufs_stats.link_startup_err,
411 "link_startup_fail");
412 ufshcd_print_err_hist(hba, &hba->ufs_stats.resume_err, "resume_fail");
413 ufshcd_print_err_hist(hba, &hba->ufs_stats.suspend_err,
414 "suspend_fail");
415 ufshcd_print_err_hist(hba, &hba->ufs_stats.dev_reset, "dev_reset");
416 ufshcd_print_err_hist(hba, &hba->ufs_stats.host_reset, "host_reset");
417 ufshcd_print_err_hist(hba, &hba->ufs_stats.task_abort, "task_abort");
419 ufshcd_print_clk_freqs(hba);
421 ufshcd_vops_dbg_register_dump(hba);
424 static
425 void ufshcd_print_trs(struct ufs_hba *hba, unsigned long bitmap, bool pr_prdt)
427 struct ufshcd_lrb *lrbp;
428 int prdt_length;
429 int tag;
431 for_each_set_bit(tag, &bitmap, hba->nutrs) {
432 lrbp = &hba->lrb[tag];
434 dev_err(hba->dev, "UPIU[%d] - issue time %lld us\n",
435 tag, ktime_to_us(lrbp->issue_time_stamp));
436 dev_err(hba->dev, "UPIU[%d] - complete time %lld us\n",
437 tag, ktime_to_us(lrbp->compl_time_stamp));
438 dev_err(hba->dev,
439 "UPIU[%d] - Transfer Request Descriptor phys@0x%llx\n",
440 tag, (u64)lrbp->utrd_dma_addr);
442 ufshcd_hex_dump("UPIU TRD: ", lrbp->utr_descriptor_ptr,
443 sizeof(struct utp_transfer_req_desc));
444 dev_err(hba->dev, "UPIU[%d] - Request UPIU phys@0x%llx\n", tag,
445 (u64)lrbp->ucd_req_dma_addr);
446 ufshcd_hex_dump("UPIU REQ: ", lrbp->ucd_req_ptr,
447 sizeof(struct utp_upiu_req));
448 dev_err(hba->dev, "UPIU[%d] - Response UPIU phys@0x%llx\n", tag,
449 (u64)lrbp->ucd_rsp_dma_addr);
450 ufshcd_hex_dump("UPIU RSP: ", lrbp->ucd_rsp_ptr,
451 sizeof(struct utp_upiu_rsp));
453 prdt_length = le16_to_cpu(
454 lrbp->utr_descriptor_ptr->prd_table_length);
455 dev_err(hba->dev,
456 "UPIU[%d] - PRDT - %d entries phys@0x%llx\n",
457 tag, prdt_length,
458 (u64)lrbp->ucd_prdt_dma_addr);
460 if (pr_prdt)
461 ufshcd_hex_dump("UPIU PRDT: ", lrbp->ucd_prdt_ptr,
462 sizeof(struct ufshcd_sg_entry) * prdt_length);
466 static void ufshcd_print_tmrs(struct ufs_hba *hba, unsigned long bitmap)
468 int tag;
470 for_each_set_bit(tag, &bitmap, hba->nutmrs) {
471 struct utp_task_req_desc *tmrdp = &hba->utmrdl_base_addr[tag];
473 dev_err(hba->dev, "TM[%d] - Task Management Header\n", tag);
474 ufshcd_hex_dump("", tmrdp, sizeof(*tmrdp));
478 static void ufshcd_print_host_state(struct ufs_hba *hba)
480 dev_err(hba->dev, "UFS Host state=%d\n", hba->ufshcd_state);
481 dev_err(hba->dev, "outstanding reqs=0x%lx tasks=0x%lx\n",
482 hba->outstanding_reqs, hba->outstanding_tasks);
483 dev_err(hba->dev, "saved_err=0x%x, saved_uic_err=0x%x\n",
484 hba->saved_err, hba->saved_uic_err);
485 dev_err(hba->dev, "Device power mode=%d, UIC link state=%d\n",
486 hba->curr_dev_pwr_mode, hba->uic_link_state);
487 dev_err(hba->dev, "PM in progress=%d, sys. suspended=%d\n",
488 hba->pm_op_in_progress, hba->is_sys_suspended);
489 dev_err(hba->dev, "Auto BKOPS=%d, Host self-block=%d\n",
490 hba->auto_bkops_enabled, hba->host->host_self_blocked);
491 dev_err(hba->dev, "Clk gate=%d\n", hba->clk_gating.state);
492 dev_err(hba->dev, "error handling flags=0x%x, req. abort count=%d\n",
493 hba->eh_flags, hba->req_abort_count);
494 dev_err(hba->dev, "Host capabilities=0x%x, caps=0x%x\n",
495 hba->capabilities, hba->caps);
496 dev_err(hba->dev, "quirks=0x%x, dev. quirks=0x%x\n", hba->quirks,
497 hba->dev_quirks);
501 * ufshcd_print_pwr_info - print power params as saved in hba
502 * power info
503 * @hba: per-adapter instance
505 static void ufshcd_print_pwr_info(struct ufs_hba *hba)
507 static const char * const names[] = {
508 "INVALID MODE",
509 "FAST MODE",
510 "SLOW_MODE",
511 "INVALID MODE",
512 "FASTAUTO_MODE",
513 "SLOWAUTO_MODE",
514 "INVALID MODE",
517 dev_err(hba->dev, "%s:[RX, TX]: gear=[%d, %d], lane[%d, %d], pwr[%s, %s], rate = %d\n",
518 __func__,
519 hba->pwr_info.gear_rx, hba->pwr_info.gear_tx,
520 hba->pwr_info.lane_rx, hba->pwr_info.lane_tx,
521 names[hba->pwr_info.pwr_rx],
522 names[hba->pwr_info.pwr_tx],
523 hba->pwr_info.hs_rate);
526 void ufshcd_delay_us(unsigned long us, unsigned long tolerance)
528 if (!us)
529 return;
531 if (us < 10)
532 udelay(us);
533 else
534 usleep_range(us, us + tolerance);
536 EXPORT_SYMBOL_GPL(ufshcd_delay_us);
539 * ufshcd_wait_for_register - wait for register value to change
540 * @hba - per-adapter interface
541 * @reg - mmio register offset
542 * @mask - mask to apply to read register value
543 * @val - wait condition
544 * @interval_us - polling interval in microsecs
545 * @timeout_ms - timeout in millisecs
546 * @can_sleep - perform sleep or just spin
548 * Returns -ETIMEDOUT on error, zero on success
550 int ufshcd_wait_for_register(struct ufs_hba *hba, u32 reg, u32 mask,
551 u32 val, unsigned long interval_us,
552 unsigned long timeout_ms, bool can_sleep)
554 int err = 0;
555 unsigned long timeout = jiffies + msecs_to_jiffies(timeout_ms);
557 /* ignore bits that we don't intend to wait on */
558 val = val & mask;
560 while ((ufshcd_readl(hba, reg) & mask) != val) {
561 if (can_sleep)
562 usleep_range(interval_us, interval_us + 50);
563 else
564 udelay(interval_us);
565 if (time_after(jiffies, timeout)) {
566 if ((ufshcd_readl(hba, reg) & mask) != val)
567 err = -ETIMEDOUT;
568 break;
572 return err;
576 * ufshcd_get_intr_mask - Get the interrupt bit mask
577 * @hba: Pointer to adapter instance
579 * Returns interrupt bit mask per version
581 static inline u32 ufshcd_get_intr_mask(struct ufs_hba *hba)
583 u32 intr_mask = 0;
585 switch (hba->ufs_version) {
586 case UFSHCI_VERSION_10:
587 intr_mask = INTERRUPT_MASK_ALL_VER_10;
588 break;
589 case UFSHCI_VERSION_11:
590 case UFSHCI_VERSION_20:
591 intr_mask = INTERRUPT_MASK_ALL_VER_11;
592 break;
593 case UFSHCI_VERSION_21:
594 default:
595 intr_mask = INTERRUPT_MASK_ALL_VER_21;
596 break;
599 return intr_mask;
603 * ufshcd_get_ufs_version - Get the UFS version supported by the HBA
604 * @hba: Pointer to adapter instance
606 * Returns UFSHCI version supported by the controller
608 static inline u32 ufshcd_get_ufs_version(struct ufs_hba *hba)
610 if (hba->quirks & UFSHCD_QUIRK_BROKEN_UFS_HCI_VERSION)
611 return ufshcd_vops_get_ufs_hci_version(hba);
613 return ufshcd_readl(hba, REG_UFS_VERSION);
617 * ufshcd_is_device_present - Check if any device connected to
618 * the host controller
619 * @hba: pointer to adapter instance
621 * Returns true if device present, false if no device detected
623 static inline bool ufshcd_is_device_present(struct ufs_hba *hba)
625 return (ufshcd_readl(hba, REG_CONTROLLER_STATUS) &
626 DEVICE_PRESENT) ? true : false;
630 * ufshcd_get_tr_ocs - Get the UTRD Overall Command Status
631 * @lrbp: pointer to local command reference block
633 * This function is used to get the OCS field from UTRD
634 * Returns the OCS field in the UTRD
636 static inline int ufshcd_get_tr_ocs(struct ufshcd_lrb *lrbp)
638 return le32_to_cpu(lrbp->utr_descriptor_ptr->header.dword_2) & MASK_OCS;
642 * ufshcd_utrl_clear - Clear a bit in UTRLCLR register
643 * @hba: per adapter instance
644 * @pos: position of the bit to be cleared
646 static inline void ufshcd_utrl_clear(struct ufs_hba *hba, u32 pos)
648 ufshcd_writel(hba, ~(1 << pos), REG_UTP_TRANSFER_REQ_LIST_CLEAR);
652 * ufshcd_utmrl_clear - Clear a bit in UTRMLCLR register
653 * @hba: per adapter instance
654 * @pos: position of the bit to be cleared
656 static inline void ufshcd_utmrl_clear(struct ufs_hba *hba, u32 pos)
658 ufshcd_writel(hba, ~(1 << pos), REG_UTP_TASK_REQ_LIST_CLEAR);
662 * ufshcd_outstanding_req_clear - Clear a bit in outstanding request field
663 * @hba: per adapter instance
664 * @tag: position of the bit to be cleared
666 static inline void ufshcd_outstanding_req_clear(struct ufs_hba *hba, int tag)
668 __clear_bit(tag, &hba->outstanding_reqs);
672 * ufshcd_get_lists_status - Check UCRDY, UTRLRDY and UTMRLRDY
673 * @reg: Register value of host controller status
675 * Returns integer, 0 on Success and positive value if failed
677 static inline int ufshcd_get_lists_status(u32 reg)
679 return !((reg & UFSHCD_STATUS_READY) == UFSHCD_STATUS_READY);
683 * ufshcd_get_uic_cmd_result - Get the UIC command result
684 * @hba: Pointer to adapter instance
686 * This function gets the result of UIC command completion
687 * Returns 0 on success, non zero value on error
689 static inline int ufshcd_get_uic_cmd_result(struct ufs_hba *hba)
691 return ufshcd_readl(hba, REG_UIC_COMMAND_ARG_2) &
692 MASK_UIC_COMMAND_RESULT;
696 * ufshcd_get_dme_attr_val - Get the value of attribute returned by UIC command
697 * @hba: Pointer to adapter instance
699 * This function gets UIC command argument3
700 * Returns 0 on success, non zero value on error
702 static inline u32 ufshcd_get_dme_attr_val(struct ufs_hba *hba)
704 return ufshcd_readl(hba, REG_UIC_COMMAND_ARG_3);
708 * ufshcd_get_req_rsp - returns the TR response transaction type
709 * @ucd_rsp_ptr: pointer to response UPIU
711 static inline int
712 ufshcd_get_req_rsp(struct utp_upiu_rsp *ucd_rsp_ptr)
714 return be32_to_cpu(ucd_rsp_ptr->header.dword_0) >> 24;
718 * ufshcd_get_rsp_upiu_result - Get the result from response UPIU
719 * @ucd_rsp_ptr: pointer to response UPIU
721 * This function gets the response status and scsi_status from response UPIU
722 * Returns the response result code.
724 static inline int
725 ufshcd_get_rsp_upiu_result(struct utp_upiu_rsp *ucd_rsp_ptr)
727 return be32_to_cpu(ucd_rsp_ptr->header.dword_1) & MASK_RSP_UPIU_RESULT;
731 * ufshcd_get_rsp_upiu_data_seg_len - Get the data segment length
732 * from response UPIU
733 * @ucd_rsp_ptr: pointer to response UPIU
735 * Return the data segment length.
737 static inline unsigned int
738 ufshcd_get_rsp_upiu_data_seg_len(struct utp_upiu_rsp *ucd_rsp_ptr)
740 return be32_to_cpu(ucd_rsp_ptr->header.dword_2) &
741 MASK_RSP_UPIU_DATA_SEG_LEN;
745 * ufshcd_is_exception_event - Check if the device raised an exception event
746 * @ucd_rsp_ptr: pointer to response UPIU
748 * The function checks if the device raised an exception event indicated in
749 * the Device Information field of response UPIU.
751 * Returns true if exception is raised, false otherwise.
753 static inline bool ufshcd_is_exception_event(struct utp_upiu_rsp *ucd_rsp_ptr)
755 return be32_to_cpu(ucd_rsp_ptr->header.dword_2) &
756 MASK_RSP_EXCEPTION_EVENT ? true : false;
760 * ufshcd_reset_intr_aggr - Reset interrupt aggregation values.
761 * @hba: per adapter instance
763 static inline void
764 ufshcd_reset_intr_aggr(struct ufs_hba *hba)
766 ufshcd_writel(hba, INT_AGGR_ENABLE |
767 INT_AGGR_COUNTER_AND_TIMER_RESET,
768 REG_UTP_TRANSFER_REQ_INT_AGG_CONTROL);
772 * ufshcd_config_intr_aggr - Configure interrupt aggregation values.
773 * @hba: per adapter instance
774 * @cnt: Interrupt aggregation counter threshold
775 * @tmout: Interrupt aggregation timeout value
777 static inline void
778 ufshcd_config_intr_aggr(struct ufs_hba *hba, u8 cnt, u8 tmout)
780 ufshcd_writel(hba, INT_AGGR_ENABLE | INT_AGGR_PARAM_WRITE |
781 INT_AGGR_COUNTER_THLD_VAL(cnt) |
782 INT_AGGR_TIMEOUT_VAL(tmout),
783 REG_UTP_TRANSFER_REQ_INT_AGG_CONTROL);
787 * ufshcd_disable_intr_aggr - Disables interrupt aggregation.
788 * @hba: per adapter instance
790 static inline void ufshcd_disable_intr_aggr(struct ufs_hba *hba)
792 ufshcd_writel(hba, 0, REG_UTP_TRANSFER_REQ_INT_AGG_CONTROL);
796 * ufshcd_enable_run_stop_reg - Enable run-stop registers,
797 * When run-stop registers are set to 1, it indicates the
798 * host controller that it can process the requests
799 * @hba: per adapter instance
801 static void ufshcd_enable_run_stop_reg(struct ufs_hba *hba)
803 ufshcd_writel(hba, UTP_TASK_REQ_LIST_RUN_STOP_BIT,
804 REG_UTP_TASK_REQ_LIST_RUN_STOP);
805 ufshcd_writel(hba, UTP_TRANSFER_REQ_LIST_RUN_STOP_BIT,
806 REG_UTP_TRANSFER_REQ_LIST_RUN_STOP);
810 * ufshcd_hba_start - Start controller initialization sequence
811 * @hba: per adapter instance
813 static inline void ufshcd_hba_start(struct ufs_hba *hba)
815 ufshcd_writel(hba, CONTROLLER_ENABLE, REG_CONTROLLER_ENABLE);
819 * ufshcd_is_hba_active - Get controller state
820 * @hba: per adapter instance
822 * Returns false if controller is active, true otherwise
824 static inline bool ufshcd_is_hba_active(struct ufs_hba *hba)
826 return (ufshcd_readl(hba, REG_CONTROLLER_ENABLE) & CONTROLLER_ENABLE)
827 ? false : true;
830 u32 ufshcd_get_local_unipro_ver(struct ufs_hba *hba)
832 /* HCI version 1.0 and 1.1 supports UniPro 1.41 */
833 if ((hba->ufs_version == UFSHCI_VERSION_10) ||
834 (hba->ufs_version == UFSHCI_VERSION_11))
835 return UFS_UNIPRO_VER_1_41;
836 else
837 return UFS_UNIPRO_VER_1_6;
839 EXPORT_SYMBOL(ufshcd_get_local_unipro_ver);
841 static bool ufshcd_is_unipro_pa_params_tuning_req(struct ufs_hba *hba)
844 * If both host and device support UniPro ver1.6 or later, PA layer
845 * parameters tuning happens during link startup itself.
847 * We can manually tune PA layer parameters if either host or device
848 * doesn't support UniPro ver 1.6 or later. But to keep manual tuning
849 * logic simple, we will only do manual tuning if local unipro version
850 * doesn't support ver1.6 or later.
852 if (ufshcd_get_local_unipro_ver(hba) < UFS_UNIPRO_VER_1_6)
853 return true;
854 else
855 return false;
859 * ufshcd_set_clk_freq - set UFS controller clock frequencies
860 * @hba: per adapter instance
861 * @scale_up: If True, set max possible frequency othewise set low frequency
863 * Returns 0 if successful
864 * Returns < 0 for any other errors
866 static int ufshcd_set_clk_freq(struct ufs_hba *hba, bool scale_up)
868 int ret = 0;
869 struct ufs_clk_info *clki;
870 struct list_head *head = &hba->clk_list_head;
872 if (list_empty(head))
873 goto out;
875 list_for_each_entry(clki, head, list) {
876 if (!IS_ERR_OR_NULL(clki->clk)) {
877 if (scale_up && clki->max_freq) {
878 if (clki->curr_freq == clki->max_freq)
879 continue;
881 ret = clk_set_rate(clki->clk, clki->max_freq);
882 if (ret) {
883 dev_err(hba->dev, "%s: %s clk set rate(%dHz) failed, %d\n",
884 __func__, clki->name,
885 clki->max_freq, ret);
886 break;
888 trace_ufshcd_clk_scaling(dev_name(hba->dev),
889 "scaled up", clki->name,
890 clki->curr_freq,
891 clki->max_freq);
893 clki->curr_freq = clki->max_freq;
895 } else if (!scale_up && clki->min_freq) {
896 if (clki->curr_freq == clki->min_freq)
897 continue;
899 ret = clk_set_rate(clki->clk, clki->min_freq);
900 if (ret) {
901 dev_err(hba->dev, "%s: %s clk set rate(%dHz) failed, %d\n",
902 __func__, clki->name,
903 clki->min_freq, ret);
904 break;
906 trace_ufshcd_clk_scaling(dev_name(hba->dev),
907 "scaled down", clki->name,
908 clki->curr_freq,
909 clki->min_freq);
910 clki->curr_freq = clki->min_freq;
913 dev_dbg(hba->dev, "%s: clk: %s, rate: %lu\n", __func__,
914 clki->name, clk_get_rate(clki->clk));
917 out:
918 return ret;
922 * ufshcd_scale_clks - scale up or scale down UFS controller clocks
923 * @hba: per adapter instance
924 * @scale_up: True if scaling up and false if scaling down
926 * Returns 0 if successful
927 * Returns < 0 for any other errors
929 static int ufshcd_scale_clks(struct ufs_hba *hba, bool scale_up)
931 int ret = 0;
932 ktime_t start = ktime_get();
934 ret = ufshcd_vops_clk_scale_notify(hba, scale_up, PRE_CHANGE);
935 if (ret)
936 goto out;
938 ret = ufshcd_set_clk_freq(hba, scale_up);
939 if (ret)
940 goto out;
942 ret = ufshcd_vops_clk_scale_notify(hba, scale_up, POST_CHANGE);
943 if (ret)
944 ufshcd_set_clk_freq(hba, !scale_up);
946 out:
947 trace_ufshcd_profile_clk_scaling(dev_name(hba->dev),
948 (scale_up ? "up" : "down"),
949 ktime_to_us(ktime_sub(ktime_get(), start)), ret);
950 return ret;
954 * ufshcd_is_devfreq_scaling_required - check if scaling is required or not
955 * @hba: per adapter instance
956 * @scale_up: True if scaling up and false if scaling down
958 * Returns true if scaling is required, false otherwise.
960 static bool ufshcd_is_devfreq_scaling_required(struct ufs_hba *hba,
961 bool scale_up)
963 struct ufs_clk_info *clki;
964 struct list_head *head = &hba->clk_list_head;
966 if (list_empty(head))
967 return false;
969 list_for_each_entry(clki, head, list) {
970 if (!IS_ERR_OR_NULL(clki->clk)) {
971 if (scale_up && clki->max_freq) {
972 if (clki->curr_freq == clki->max_freq)
973 continue;
974 return true;
975 } else if (!scale_up && clki->min_freq) {
976 if (clki->curr_freq == clki->min_freq)
977 continue;
978 return true;
983 return false;
986 static int ufshcd_wait_for_doorbell_clr(struct ufs_hba *hba,
987 u64 wait_timeout_us)
989 unsigned long flags;
990 int ret = 0;
991 u32 tm_doorbell;
992 u32 tr_doorbell;
993 bool timeout = false, do_last_check = false;
994 ktime_t start;
996 ufshcd_hold(hba, false);
997 spin_lock_irqsave(hba->host->host_lock, flags);
999 * Wait for all the outstanding tasks/transfer requests.
1000 * Verify by checking the doorbell registers are clear.
1002 start = ktime_get();
1003 do {
1004 if (hba->ufshcd_state != UFSHCD_STATE_OPERATIONAL) {
1005 ret = -EBUSY;
1006 goto out;
1009 tm_doorbell = ufshcd_readl(hba, REG_UTP_TASK_REQ_DOOR_BELL);
1010 tr_doorbell = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
1011 if (!tm_doorbell && !tr_doorbell) {
1012 timeout = false;
1013 break;
1014 } else if (do_last_check) {
1015 break;
1018 spin_unlock_irqrestore(hba->host->host_lock, flags);
1019 schedule();
1020 if (ktime_to_us(ktime_sub(ktime_get(), start)) >
1021 wait_timeout_us) {
1022 timeout = true;
1024 * We might have scheduled out for long time so make
1025 * sure to check if doorbells are cleared by this time
1026 * or not.
1028 do_last_check = true;
1030 spin_lock_irqsave(hba->host->host_lock, flags);
1031 } while (tm_doorbell || tr_doorbell);
1033 if (timeout) {
1034 dev_err(hba->dev,
1035 "%s: timedout waiting for doorbell to clear (tm=0x%x, tr=0x%x)\n",
1036 __func__, tm_doorbell, tr_doorbell);
1037 ret = -EBUSY;
1039 out:
1040 spin_unlock_irqrestore(hba->host->host_lock, flags);
1041 ufshcd_release(hba);
1042 return ret;
1046 * ufshcd_scale_gear - scale up/down UFS gear
1047 * @hba: per adapter instance
1048 * @scale_up: True for scaling up gear and false for scaling down
1050 * Returns 0 for success,
1051 * Returns -EBUSY if scaling can't happen at this time
1052 * Returns non-zero for any other errors
1054 static int ufshcd_scale_gear(struct ufs_hba *hba, bool scale_up)
1056 #define UFS_MIN_GEAR_TO_SCALE_DOWN UFS_HS_G1
1057 int ret = 0;
1058 struct ufs_pa_layer_attr new_pwr_info;
1060 if (scale_up) {
1061 memcpy(&new_pwr_info, &hba->clk_scaling.saved_pwr_info.info,
1062 sizeof(struct ufs_pa_layer_attr));
1063 } else {
1064 memcpy(&new_pwr_info, &hba->pwr_info,
1065 sizeof(struct ufs_pa_layer_attr));
1067 if (hba->pwr_info.gear_tx > UFS_MIN_GEAR_TO_SCALE_DOWN
1068 || hba->pwr_info.gear_rx > UFS_MIN_GEAR_TO_SCALE_DOWN) {
1069 /* save the current power mode */
1070 memcpy(&hba->clk_scaling.saved_pwr_info.info,
1071 &hba->pwr_info,
1072 sizeof(struct ufs_pa_layer_attr));
1074 /* scale down gear */
1075 new_pwr_info.gear_tx = UFS_MIN_GEAR_TO_SCALE_DOWN;
1076 new_pwr_info.gear_rx = UFS_MIN_GEAR_TO_SCALE_DOWN;
1080 /* check if the power mode needs to be changed or not? */
1081 ret = ufshcd_config_pwr_mode(hba, &new_pwr_info);
1082 if (ret)
1083 dev_err(hba->dev, "%s: failed err %d, old gear: (tx %d rx %d), new gear: (tx %d rx %d)",
1084 __func__, ret,
1085 hba->pwr_info.gear_tx, hba->pwr_info.gear_rx,
1086 new_pwr_info.gear_tx, new_pwr_info.gear_rx);
1088 return ret;
1091 static int ufshcd_clock_scaling_prepare(struct ufs_hba *hba)
1093 #define DOORBELL_CLR_TOUT_US (1000 * 1000) /* 1 sec */
1094 int ret = 0;
1096 * make sure that there are no outstanding requests when
1097 * clock scaling is in progress
1099 ufshcd_scsi_block_requests(hba);
1100 down_write(&hba->clk_scaling_lock);
1101 if (ufshcd_wait_for_doorbell_clr(hba, DOORBELL_CLR_TOUT_US)) {
1102 ret = -EBUSY;
1103 up_write(&hba->clk_scaling_lock);
1104 ufshcd_scsi_unblock_requests(hba);
1107 return ret;
1110 static void ufshcd_clock_scaling_unprepare(struct ufs_hba *hba)
1112 up_write(&hba->clk_scaling_lock);
1113 ufshcd_scsi_unblock_requests(hba);
1117 * ufshcd_devfreq_scale - scale up/down UFS clocks and gear
1118 * @hba: per adapter instance
1119 * @scale_up: True for scaling up and false for scalin down
1121 * Returns 0 for success,
1122 * Returns -EBUSY if scaling can't happen at this time
1123 * Returns non-zero for any other errors
1125 static int ufshcd_devfreq_scale(struct ufs_hba *hba, bool scale_up)
1127 int ret = 0;
1129 /* let's not get into low power until clock scaling is completed */
1130 ufshcd_hold(hba, false);
1132 ret = ufshcd_clock_scaling_prepare(hba);
1133 if (ret)
1134 goto out;
1136 /* scale down the gear before scaling down clocks */
1137 if (!scale_up) {
1138 ret = ufshcd_scale_gear(hba, false);
1139 if (ret)
1140 goto out_unprepare;
1143 ret = ufshcd_scale_clks(hba, scale_up);
1144 if (ret) {
1145 if (!scale_up)
1146 ufshcd_scale_gear(hba, true);
1147 goto out_unprepare;
1150 /* scale up the gear after scaling up clocks */
1151 if (scale_up) {
1152 ret = ufshcd_scale_gear(hba, true);
1153 if (ret)
1154 ufshcd_scale_clks(hba, false);
1157 out_unprepare:
1158 ufshcd_clock_scaling_unprepare(hba);
1159 out:
1160 ufshcd_release(hba);
1161 return ret;
1164 static void ufshcd_clk_scaling_suspend_work(struct work_struct *work)
1166 struct ufs_hba *hba = container_of(work, struct ufs_hba,
1167 clk_scaling.suspend_work);
1168 unsigned long irq_flags;
1170 spin_lock_irqsave(hba->host->host_lock, irq_flags);
1171 if (hba->clk_scaling.active_reqs || hba->clk_scaling.is_suspended) {
1172 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1173 return;
1175 hba->clk_scaling.is_suspended = true;
1176 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1178 __ufshcd_suspend_clkscaling(hba);
1181 static void ufshcd_clk_scaling_resume_work(struct work_struct *work)
1183 struct ufs_hba *hba = container_of(work, struct ufs_hba,
1184 clk_scaling.resume_work);
1185 unsigned long irq_flags;
1187 spin_lock_irqsave(hba->host->host_lock, irq_flags);
1188 if (!hba->clk_scaling.is_suspended) {
1189 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1190 return;
1192 hba->clk_scaling.is_suspended = false;
1193 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1195 devfreq_resume_device(hba->devfreq);
1198 static int ufshcd_devfreq_target(struct device *dev,
1199 unsigned long *freq, u32 flags)
1201 int ret = 0;
1202 struct ufs_hba *hba = dev_get_drvdata(dev);
1203 ktime_t start;
1204 bool scale_up, sched_clk_scaling_suspend_work = false;
1205 struct list_head *clk_list = &hba->clk_list_head;
1206 struct ufs_clk_info *clki;
1207 unsigned long irq_flags;
1209 if (!ufshcd_is_clkscaling_supported(hba))
1210 return -EINVAL;
1212 clki = list_first_entry(&hba->clk_list_head, struct ufs_clk_info, list);
1213 /* Override with the closest supported frequency */
1214 *freq = (unsigned long) clk_round_rate(clki->clk, *freq);
1215 spin_lock_irqsave(hba->host->host_lock, irq_flags);
1216 if (ufshcd_eh_in_progress(hba)) {
1217 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1218 return 0;
1221 if (!hba->clk_scaling.active_reqs)
1222 sched_clk_scaling_suspend_work = true;
1224 if (list_empty(clk_list)) {
1225 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1226 goto out;
1229 /* Decide based on the rounded-off frequency and update */
1230 scale_up = (*freq == clki->max_freq) ? true : false;
1231 if (!scale_up)
1232 *freq = clki->min_freq;
1233 /* Update the frequency */
1234 if (!ufshcd_is_devfreq_scaling_required(hba, scale_up)) {
1235 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1236 ret = 0;
1237 goto out; /* no state change required */
1239 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1241 start = ktime_get();
1242 ret = ufshcd_devfreq_scale(hba, scale_up);
1244 trace_ufshcd_profile_clk_scaling(dev_name(hba->dev),
1245 (scale_up ? "up" : "down"),
1246 ktime_to_us(ktime_sub(ktime_get(), start)), ret);
1248 out:
1249 if (sched_clk_scaling_suspend_work)
1250 queue_work(hba->clk_scaling.workq,
1251 &hba->clk_scaling.suspend_work);
1253 return ret;
1256 static bool ufshcd_is_busy(struct request *req, void *priv, bool reserved)
1258 int *busy = priv;
1260 WARN_ON_ONCE(reserved);
1261 (*busy)++;
1262 return false;
1265 /* Whether or not any tag is in use by a request that is in progress. */
1266 static bool ufshcd_any_tag_in_use(struct ufs_hba *hba)
1268 struct request_queue *q = hba->cmd_queue;
1269 int busy = 0;
1271 blk_mq_tagset_busy_iter(q->tag_set, ufshcd_is_busy, &busy);
1272 return busy;
1275 static int ufshcd_devfreq_get_dev_status(struct device *dev,
1276 struct devfreq_dev_status *stat)
1278 struct ufs_hba *hba = dev_get_drvdata(dev);
1279 struct ufs_clk_scaling *scaling = &hba->clk_scaling;
1280 unsigned long flags;
1281 struct list_head *clk_list = &hba->clk_list_head;
1282 struct ufs_clk_info *clki;
1284 if (!ufshcd_is_clkscaling_supported(hba))
1285 return -EINVAL;
1287 memset(stat, 0, sizeof(*stat));
1289 spin_lock_irqsave(hba->host->host_lock, flags);
1290 if (!scaling->window_start_t)
1291 goto start_window;
1293 clki = list_first_entry(clk_list, struct ufs_clk_info, list);
1295 * If current frequency is 0, then the ondemand governor considers
1296 * there's no initial frequency set. And it always requests to set
1297 * to max. frequency.
1299 stat->current_frequency = clki->curr_freq;
1300 if (scaling->is_busy_started)
1301 scaling->tot_busy_t += ktime_to_us(ktime_sub(ktime_get(),
1302 scaling->busy_start_t));
1304 stat->total_time = jiffies_to_usecs((long)jiffies -
1305 (long)scaling->window_start_t);
1306 stat->busy_time = scaling->tot_busy_t;
1307 start_window:
1308 scaling->window_start_t = jiffies;
1309 scaling->tot_busy_t = 0;
1311 if (hba->outstanding_reqs) {
1312 scaling->busy_start_t = ktime_get();
1313 scaling->is_busy_started = true;
1314 } else {
1315 scaling->busy_start_t = 0;
1316 scaling->is_busy_started = false;
1318 spin_unlock_irqrestore(hba->host->host_lock, flags);
1319 return 0;
1322 static struct devfreq_dev_profile ufs_devfreq_profile = {
1323 .polling_ms = 100,
1324 .target = ufshcd_devfreq_target,
1325 .get_dev_status = ufshcd_devfreq_get_dev_status,
1328 #if IS_ENABLED(CONFIG_DEVFREQ_GOV_SIMPLE_ONDEMAND)
1329 static struct devfreq_simple_ondemand_data ufs_ondemand_data = {
1330 .upthreshold = 70,
1331 .downdifferential = 5,
1334 static void *gov_data = &ufs_ondemand_data;
1335 #else
1336 static void *gov_data; /* NULL */
1337 #endif
1339 static int ufshcd_devfreq_init(struct ufs_hba *hba)
1341 struct list_head *clk_list = &hba->clk_list_head;
1342 struct ufs_clk_info *clki;
1343 struct devfreq *devfreq;
1344 int ret;
1346 /* Skip devfreq if we don't have any clocks in the list */
1347 if (list_empty(clk_list))
1348 return 0;
1350 clki = list_first_entry(clk_list, struct ufs_clk_info, list);
1351 dev_pm_opp_add(hba->dev, clki->min_freq, 0);
1352 dev_pm_opp_add(hba->dev, clki->max_freq, 0);
1354 ufshcd_vops_config_scaling_param(hba, &ufs_devfreq_profile,
1355 gov_data);
1356 devfreq = devfreq_add_device(hba->dev,
1357 &ufs_devfreq_profile,
1358 DEVFREQ_GOV_SIMPLE_ONDEMAND,
1359 gov_data);
1360 if (IS_ERR(devfreq)) {
1361 ret = PTR_ERR(devfreq);
1362 dev_err(hba->dev, "Unable to register with devfreq %d\n", ret);
1364 dev_pm_opp_remove(hba->dev, clki->min_freq);
1365 dev_pm_opp_remove(hba->dev, clki->max_freq);
1366 return ret;
1369 hba->devfreq = devfreq;
1371 return 0;
1374 static void ufshcd_devfreq_remove(struct ufs_hba *hba)
1376 struct list_head *clk_list = &hba->clk_list_head;
1377 struct ufs_clk_info *clki;
1379 if (!hba->devfreq)
1380 return;
1382 devfreq_remove_device(hba->devfreq);
1383 hba->devfreq = NULL;
1385 clki = list_first_entry(clk_list, struct ufs_clk_info, list);
1386 dev_pm_opp_remove(hba->dev, clki->min_freq);
1387 dev_pm_opp_remove(hba->dev, clki->max_freq);
1390 static void __ufshcd_suspend_clkscaling(struct ufs_hba *hba)
1392 unsigned long flags;
1394 devfreq_suspend_device(hba->devfreq);
1395 spin_lock_irqsave(hba->host->host_lock, flags);
1396 hba->clk_scaling.window_start_t = 0;
1397 spin_unlock_irqrestore(hba->host->host_lock, flags);
1400 static void ufshcd_suspend_clkscaling(struct ufs_hba *hba)
1402 unsigned long flags;
1403 bool suspend = false;
1405 if (!ufshcd_is_clkscaling_supported(hba))
1406 return;
1408 spin_lock_irqsave(hba->host->host_lock, flags);
1409 if (!hba->clk_scaling.is_suspended) {
1410 suspend = true;
1411 hba->clk_scaling.is_suspended = true;
1413 spin_unlock_irqrestore(hba->host->host_lock, flags);
1415 if (suspend)
1416 __ufshcd_suspend_clkscaling(hba);
1419 static void ufshcd_resume_clkscaling(struct ufs_hba *hba)
1421 unsigned long flags;
1422 bool resume = false;
1424 if (!ufshcd_is_clkscaling_supported(hba))
1425 return;
1427 spin_lock_irqsave(hba->host->host_lock, flags);
1428 if (hba->clk_scaling.is_suspended) {
1429 resume = true;
1430 hba->clk_scaling.is_suspended = false;
1432 spin_unlock_irqrestore(hba->host->host_lock, flags);
1434 if (resume)
1435 devfreq_resume_device(hba->devfreq);
1438 static ssize_t ufshcd_clkscale_enable_show(struct device *dev,
1439 struct device_attribute *attr, char *buf)
1441 struct ufs_hba *hba = dev_get_drvdata(dev);
1443 return snprintf(buf, PAGE_SIZE, "%d\n", hba->clk_scaling.is_allowed);
1446 static ssize_t ufshcd_clkscale_enable_store(struct device *dev,
1447 struct device_attribute *attr, const char *buf, size_t count)
1449 struct ufs_hba *hba = dev_get_drvdata(dev);
1450 u32 value;
1451 int err;
1453 if (kstrtou32(buf, 0, &value))
1454 return -EINVAL;
1456 value = !!value;
1457 if (value == hba->clk_scaling.is_allowed)
1458 goto out;
1460 pm_runtime_get_sync(hba->dev);
1461 ufshcd_hold(hba, false);
1463 cancel_work_sync(&hba->clk_scaling.suspend_work);
1464 cancel_work_sync(&hba->clk_scaling.resume_work);
1466 hba->clk_scaling.is_allowed = value;
1468 if (value) {
1469 ufshcd_resume_clkscaling(hba);
1470 } else {
1471 ufshcd_suspend_clkscaling(hba);
1472 err = ufshcd_devfreq_scale(hba, true);
1473 if (err)
1474 dev_err(hba->dev, "%s: failed to scale clocks up %d\n",
1475 __func__, err);
1478 ufshcd_release(hba);
1479 pm_runtime_put_sync(hba->dev);
1480 out:
1481 return count;
1484 static void ufshcd_clkscaling_init_sysfs(struct ufs_hba *hba)
1486 hba->clk_scaling.enable_attr.show = ufshcd_clkscale_enable_show;
1487 hba->clk_scaling.enable_attr.store = ufshcd_clkscale_enable_store;
1488 sysfs_attr_init(&hba->clk_scaling.enable_attr.attr);
1489 hba->clk_scaling.enable_attr.attr.name = "clkscale_enable";
1490 hba->clk_scaling.enable_attr.attr.mode = 0644;
1491 if (device_create_file(hba->dev, &hba->clk_scaling.enable_attr))
1492 dev_err(hba->dev, "Failed to create sysfs for clkscale_enable\n");
1495 static void ufshcd_ungate_work(struct work_struct *work)
1497 int ret;
1498 unsigned long flags;
1499 struct ufs_hba *hba = container_of(work, struct ufs_hba,
1500 clk_gating.ungate_work);
1502 cancel_delayed_work_sync(&hba->clk_gating.gate_work);
1504 spin_lock_irqsave(hba->host->host_lock, flags);
1505 if (hba->clk_gating.state == CLKS_ON) {
1506 spin_unlock_irqrestore(hba->host->host_lock, flags);
1507 goto unblock_reqs;
1510 spin_unlock_irqrestore(hba->host->host_lock, flags);
1511 ufshcd_setup_clocks(hba, true);
1513 ufshcd_enable_irq(hba);
1515 /* Exit from hibern8 */
1516 if (ufshcd_can_hibern8_during_gating(hba)) {
1517 /* Prevent gating in this path */
1518 hba->clk_gating.is_suspended = true;
1519 if (ufshcd_is_link_hibern8(hba)) {
1520 ret = ufshcd_uic_hibern8_exit(hba);
1521 if (ret)
1522 dev_err(hba->dev, "%s: hibern8 exit failed %d\n",
1523 __func__, ret);
1524 else
1525 ufshcd_set_link_active(hba);
1527 hba->clk_gating.is_suspended = false;
1529 unblock_reqs:
1530 ufshcd_scsi_unblock_requests(hba);
1534 * ufshcd_hold - Enable clocks that were gated earlier due to ufshcd_release.
1535 * Also, exit from hibern8 mode and set the link as active.
1536 * @hba: per adapter instance
1537 * @async: This indicates whether caller should ungate clocks asynchronously.
1539 int ufshcd_hold(struct ufs_hba *hba, bool async)
1541 int rc = 0;
1542 unsigned long flags;
1544 if (!ufshcd_is_clkgating_allowed(hba))
1545 goto out;
1546 spin_lock_irqsave(hba->host->host_lock, flags);
1547 hba->clk_gating.active_reqs++;
1549 if (ufshcd_eh_in_progress(hba)) {
1550 spin_unlock_irqrestore(hba->host->host_lock, flags);
1551 return 0;
1554 start:
1555 switch (hba->clk_gating.state) {
1556 case CLKS_ON:
1558 * Wait for the ungate work to complete if in progress.
1559 * Though the clocks may be in ON state, the link could
1560 * still be in hibner8 state if hibern8 is allowed
1561 * during clock gating.
1562 * Make sure we exit hibern8 state also in addition to
1563 * clocks being ON.
1565 if (ufshcd_can_hibern8_during_gating(hba) &&
1566 ufshcd_is_link_hibern8(hba)) {
1567 if (async) {
1568 rc = -EAGAIN;
1569 hba->clk_gating.active_reqs--;
1570 break;
1572 spin_unlock_irqrestore(hba->host->host_lock, flags);
1573 flush_work(&hba->clk_gating.ungate_work);
1574 spin_lock_irqsave(hba->host->host_lock, flags);
1575 goto start;
1577 break;
1578 case REQ_CLKS_OFF:
1579 if (cancel_delayed_work(&hba->clk_gating.gate_work)) {
1580 hba->clk_gating.state = CLKS_ON;
1581 trace_ufshcd_clk_gating(dev_name(hba->dev),
1582 hba->clk_gating.state);
1583 break;
1586 * If we are here, it means gating work is either done or
1587 * currently running. Hence, fall through to cancel gating
1588 * work and to enable clocks.
1590 /* fallthrough */
1591 case CLKS_OFF:
1592 ufshcd_scsi_block_requests(hba);
1593 hba->clk_gating.state = REQ_CLKS_ON;
1594 trace_ufshcd_clk_gating(dev_name(hba->dev),
1595 hba->clk_gating.state);
1596 queue_work(hba->clk_gating.clk_gating_workq,
1597 &hba->clk_gating.ungate_work);
1599 * fall through to check if we should wait for this
1600 * work to be done or not.
1602 /* fallthrough */
1603 case REQ_CLKS_ON:
1604 if (async) {
1605 rc = -EAGAIN;
1606 hba->clk_gating.active_reqs--;
1607 break;
1610 spin_unlock_irqrestore(hba->host->host_lock, flags);
1611 flush_work(&hba->clk_gating.ungate_work);
1612 /* Make sure state is CLKS_ON before returning */
1613 spin_lock_irqsave(hba->host->host_lock, flags);
1614 goto start;
1615 default:
1616 dev_err(hba->dev, "%s: clk gating is in invalid state %d\n",
1617 __func__, hba->clk_gating.state);
1618 break;
1620 spin_unlock_irqrestore(hba->host->host_lock, flags);
1621 out:
1622 return rc;
1624 EXPORT_SYMBOL_GPL(ufshcd_hold);
1626 static void ufshcd_gate_work(struct work_struct *work)
1628 struct ufs_hba *hba = container_of(work, struct ufs_hba,
1629 clk_gating.gate_work.work);
1630 unsigned long flags;
1632 spin_lock_irqsave(hba->host->host_lock, flags);
1634 * In case you are here to cancel this work the gating state
1635 * would be marked as REQ_CLKS_ON. In this case save time by
1636 * skipping the gating work and exit after changing the clock
1637 * state to CLKS_ON.
1639 if (hba->clk_gating.is_suspended ||
1640 (hba->clk_gating.state != REQ_CLKS_OFF)) {
1641 hba->clk_gating.state = CLKS_ON;
1642 trace_ufshcd_clk_gating(dev_name(hba->dev),
1643 hba->clk_gating.state);
1644 goto rel_lock;
1647 if (hba->clk_gating.active_reqs
1648 || hba->ufshcd_state != UFSHCD_STATE_OPERATIONAL
1649 || ufshcd_any_tag_in_use(hba) || hba->outstanding_tasks
1650 || hba->active_uic_cmd || hba->uic_async_done)
1651 goto rel_lock;
1653 spin_unlock_irqrestore(hba->host->host_lock, flags);
1655 /* put the link into hibern8 mode before turning off clocks */
1656 if (ufshcd_can_hibern8_during_gating(hba)) {
1657 if (ufshcd_uic_hibern8_enter(hba)) {
1658 hba->clk_gating.state = CLKS_ON;
1659 trace_ufshcd_clk_gating(dev_name(hba->dev),
1660 hba->clk_gating.state);
1661 goto out;
1663 ufshcd_set_link_hibern8(hba);
1666 ufshcd_disable_irq(hba);
1668 if (!ufshcd_is_link_active(hba))
1669 ufshcd_setup_clocks(hba, false);
1670 else
1671 /* If link is active, device ref_clk can't be switched off */
1672 __ufshcd_setup_clocks(hba, false, true);
1675 * In case you are here to cancel this work the gating state
1676 * would be marked as REQ_CLKS_ON. In this case keep the state
1677 * as REQ_CLKS_ON which would anyway imply that clocks are off
1678 * and a request to turn them on is pending. By doing this way,
1679 * we keep the state machine in tact and this would ultimately
1680 * prevent from doing cancel work multiple times when there are
1681 * new requests arriving before the current cancel work is done.
1683 spin_lock_irqsave(hba->host->host_lock, flags);
1684 if (hba->clk_gating.state == REQ_CLKS_OFF) {
1685 hba->clk_gating.state = CLKS_OFF;
1686 trace_ufshcd_clk_gating(dev_name(hba->dev),
1687 hba->clk_gating.state);
1689 rel_lock:
1690 spin_unlock_irqrestore(hba->host->host_lock, flags);
1691 out:
1692 return;
1695 /* host lock must be held before calling this variant */
1696 static void __ufshcd_release(struct ufs_hba *hba)
1698 if (!ufshcd_is_clkgating_allowed(hba))
1699 return;
1701 hba->clk_gating.active_reqs--;
1703 if (hba->clk_gating.active_reqs || hba->clk_gating.is_suspended
1704 || hba->ufshcd_state != UFSHCD_STATE_OPERATIONAL
1705 || ufshcd_any_tag_in_use(hba) || hba->outstanding_tasks
1706 || hba->active_uic_cmd || hba->uic_async_done
1707 || ufshcd_eh_in_progress(hba))
1708 return;
1710 hba->clk_gating.state = REQ_CLKS_OFF;
1711 trace_ufshcd_clk_gating(dev_name(hba->dev), hba->clk_gating.state);
1712 queue_delayed_work(hba->clk_gating.clk_gating_workq,
1713 &hba->clk_gating.gate_work,
1714 msecs_to_jiffies(hba->clk_gating.delay_ms));
1717 void ufshcd_release(struct ufs_hba *hba)
1719 unsigned long flags;
1721 spin_lock_irqsave(hba->host->host_lock, flags);
1722 __ufshcd_release(hba);
1723 spin_unlock_irqrestore(hba->host->host_lock, flags);
1725 EXPORT_SYMBOL_GPL(ufshcd_release);
1727 static ssize_t ufshcd_clkgate_delay_show(struct device *dev,
1728 struct device_attribute *attr, char *buf)
1730 struct ufs_hba *hba = dev_get_drvdata(dev);
1732 return snprintf(buf, PAGE_SIZE, "%lu\n", hba->clk_gating.delay_ms);
1735 static ssize_t ufshcd_clkgate_delay_store(struct device *dev,
1736 struct device_attribute *attr, const char *buf, size_t count)
1738 struct ufs_hba *hba = dev_get_drvdata(dev);
1739 unsigned long flags, value;
1741 if (kstrtoul(buf, 0, &value))
1742 return -EINVAL;
1744 spin_lock_irqsave(hba->host->host_lock, flags);
1745 hba->clk_gating.delay_ms = value;
1746 spin_unlock_irqrestore(hba->host->host_lock, flags);
1747 return count;
1750 static ssize_t ufshcd_clkgate_enable_show(struct device *dev,
1751 struct device_attribute *attr, char *buf)
1753 struct ufs_hba *hba = dev_get_drvdata(dev);
1755 return snprintf(buf, PAGE_SIZE, "%d\n", hba->clk_gating.is_enabled);
1758 static ssize_t ufshcd_clkgate_enable_store(struct device *dev,
1759 struct device_attribute *attr, const char *buf, size_t count)
1761 struct ufs_hba *hba = dev_get_drvdata(dev);
1762 unsigned long flags;
1763 u32 value;
1765 if (kstrtou32(buf, 0, &value))
1766 return -EINVAL;
1768 value = !!value;
1769 if (value == hba->clk_gating.is_enabled)
1770 goto out;
1772 if (value) {
1773 ufshcd_release(hba);
1774 } else {
1775 spin_lock_irqsave(hba->host->host_lock, flags);
1776 hba->clk_gating.active_reqs++;
1777 spin_unlock_irqrestore(hba->host->host_lock, flags);
1780 hba->clk_gating.is_enabled = value;
1781 out:
1782 return count;
1785 static void ufshcd_init_clk_scaling(struct ufs_hba *hba)
1787 char wq_name[sizeof("ufs_clkscaling_00")];
1789 if (!ufshcd_is_clkscaling_supported(hba))
1790 return;
1792 INIT_WORK(&hba->clk_scaling.suspend_work,
1793 ufshcd_clk_scaling_suspend_work);
1794 INIT_WORK(&hba->clk_scaling.resume_work,
1795 ufshcd_clk_scaling_resume_work);
1797 snprintf(wq_name, sizeof(wq_name), "ufs_clkscaling_%d",
1798 hba->host->host_no);
1799 hba->clk_scaling.workq = create_singlethread_workqueue(wq_name);
1801 ufshcd_clkscaling_init_sysfs(hba);
1804 static void ufshcd_exit_clk_scaling(struct ufs_hba *hba)
1806 if (!ufshcd_is_clkscaling_supported(hba))
1807 return;
1809 destroy_workqueue(hba->clk_scaling.workq);
1810 ufshcd_devfreq_remove(hba);
1813 static void ufshcd_init_clk_gating(struct ufs_hba *hba)
1815 char wq_name[sizeof("ufs_clk_gating_00")];
1817 if (!ufshcd_is_clkgating_allowed(hba))
1818 return;
1820 hba->clk_gating.delay_ms = 150;
1821 INIT_DELAYED_WORK(&hba->clk_gating.gate_work, ufshcd_gate_work);
1822 INIT_WORK(&hba->clk_gating.ungate_work, ufshcd_ungate_work);
1824 snprintf(wq_name, ARRAY_SIZE(wq_name), "ufs_clk_gating_%d",
1825 hba->host->host_no);
1826 hba->clk_gating.clk_gating_workq = alloc_ordered_workqueue(wq_name,
1827 WQ_MEM_RECLAIM);
1829 hba->clk_gating.is_enabled = true;
1831 hba->clk_gating.delay_attr.show = ufshcd_clkgate_delay_show;
1832 hba->clk_gating.delay_attr.store = ufshcd_clkgate_delay_store;
1833 sysfs_attr_init(&hba->clk_gating.delay_attr.attr);
1834 hba->clk_gating.delay_attr.attr.name = "clkgate_delay_ms";
1835 hba->clk_gating.delay_attr.attr.mode = 0644;
1836 if (device_create_file(hba->dev, &hba->clk_gating.delay_attr))
1837 dev_err(hba->dev, "Failed to create sysfs for clkgate_delay\n");
1839 hba->clk_gating.enable_attr.show = ufshcd_clkgate_enable_show;
1840 hba->clk_gating.enable_attr.store = ufshcd_clkgate_enable_store;
1841 sysfs_attr_init(&hba->clk_gating.enable_attr.attr);
1842 hba->clk_gating.enable_attr.attr.name = "clkgate_enable";
1843 hba->clk_gating.enable_attr.attr.mode = 0644;
1844 if (device_create_file(hba->dev, &hba->clk_gating.enable_attr))
1845 dev_err(hba->dev, "Failed to create sysfs for clkgate_enable\n");
1848 static void ufshcd_exit_clk_gating(struct ufs_hba *hba)
1850 if (!ufshcd_is_clkgating_allowed(hba))
1851 return;
1852 device_remove_file(hba->dev, &hba->clk_gating.delay_attr);
1853 device_remove_file(hba->dev, &hba->clk_gating.enable_attr);
1854 cancel_work_sync(&hba->clk_gating.ungate_work);
1855 cancel_delayed_work_sync(&hba->clk_gating.gate_work);
1856 destroy_workqueue(hba->clk_gating.clk_gating_workq);
1859 /* Must be called with host lock acquired */
1860 static void ufshcd_clk_scaling_start_busy(struct ufs_hba *hba)
1862 bool queue_resume_work = false;
1864 if (!ufshcd_is_clkscaling_supported(hba))
1865 return;
1867 if (!hba->clk_scaling.active_reqs++)
1868 queue_resume_work = true;
1870 if (!hba->clk_scaling.is_allowed || hba->pm_op_in_progress)
1871 return;
1873 if (queue_resume_work)
1874 queue_work(hba->clk_scaling.workq,
1875 &hba->clk_scaling.resume_work);
1877 if (!hba->clk_scaling.window_start_t) {
1878 hba->clk_scaling.window_start_t = jiffies;
1879 hba->clk_scaling.tot_busy_t = 0;
1880 hba->clk_scaling.is_busy_started = false;
1883 if (!hba->clk_scaling.is_busy_started) {
1884 hba->clk_scaling.busy_start_t = ktime_get();
1885 hba->clk_scaling.is_busy_started = true;
1889 static void ufshcd_clk_scaling_update_busy(struct ufs_hba *hba)
1891 struct ufs_clk_scaling *scaling = &hba->clk_scaling;
1893 if (!ufshcd_is_clkscaling_supported(hba))
1894 return;
1896 if (!hba->outstanding_reqs && scaling->is_busy_started) {
1897 scaling->tot_busy_t += ktime_to_us(ktime_sub(ktime_get(),
1898 scaling->busy_start_t));
1899 scaling->busy_start_t = 0;
1900 scaling->is_busy_started = false;
1904 * ufshcd_send_command - Send SCSI or device management commands
1905 * @hba: per adapter instance
1906 * @task_tag: Task tag of the command
1908 static inline
1909 void ufshcd_send_command(struct ufs_hba *hba, unsigned int task_tag)
1911 hba->lrb[task_tag].issue_time_stamp = ktime_get();
1912 hba->lrb[task_tag].compl_time_stamp = ktime_set(0, 0);
1913 ufshcd_add_command_trace(hba, task_tag, "send");
1914 ufshcd_clk_scaling_start_busy(hba);
1915 __set_bit(task_tag, &hba->outstanding_reqs);
1916 ufshcd_writel(hba, 1 << task_tag, REG_UTP_TRANSFER_REQ_DOOR_BELL);
1917 /* Make sure that doorbell is committed immediately */
1918 wmb();
1922 * ufshcd_copy_sense_data - Copy sense data in case of check condition
1923 * @lrbp: pointer to local reference block
1925 static inline void ufshcd_copy_sense_data(struct ufshcd_lrb *lrbp)
1927 int len;
1928 if (lrbp->sense_buffer &&
1929 ufshcd_get_rsp_upiu_data_seg_len(lrbp->ucd_rsp_ptr)) {
1930 int len_to_copy;
1932 len = be16_to_cpu(lrbp->ucd_rsp_ptr->sr.sense_data_len);
1933 len_to_copy = min_t(int, UFS_SENSE_SIZE, len);
1935 memcpy(lrbp->sense_buffer, lrbp->ucd_rsp_ptr->sr.sense_data,
1936 len_to_copy);
1941 * ufshcd_copy_query_response() - Copy the Query Response and the data
1942 * descriptor
1943 * @hba: per adapter instance
1944 * @lrbp: pointer to local reference block
1946 static
1947 int ufshcd_copy_query_response(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
1949 struct ufs_query_res *query_res = &hba->dev_cmd.query.response;
1951 memcpy(&query_res->upiu_res, &lrbp->ucd_rsp_ptr->qr, QUERY_OSF_SIZE);
1953 /* Get the descriptor */
1954 if (hba->dev_cmd.query.descriptor &&
1955 lrbp->ucd_rsp_ptr->qr.opcode == UPIU_QUERY_OPCODE_READ_DESC) {
1956 u8 *descp = (u8 *)lrbp->ucd_rsp_ptr +
1957 GENERAL_UPIU_REQUEST_SIZE;
1958 u16 resp_len;
1959 u16 buf_len;
1961 /* data segment length */
1962 resp_len = be32_to_cpu(lrbp->ucd_rsp_ptr->header.dword_2) &
1963 MASK_QUERY_DATA_SEG_LEN;
1964 buf_len = be16_to_cpu(
1965 hba->dev_cmd.query.request.upiu_req.length);
1966 if (likely(buf_len >= resp_len)) {
1967 memcpy(hba->dev_cmd.query.descriptor, descp, resp_len);
1968 } else {
1969 dev_warn(hba->dev,
1970 "%s: rsp size %d is bigger than buffer size %d",
1971 __func__, resp_len, buf_len);
1972 return -EINVAL;
1976 return 0;
1980 * ufshcd_hba_capabilities - Read controller capabilities
1981 * @hba: per adapter instance
1983 static inline void ufshcd_hba_capabilities(struct ufs_hba *hba)
1985 hba->capabilities = ufshcd_readl(hba, REG_CONTROLLER_CAPABILITIES);
1987 /* nutrs and nutmrs are 0 based values */
1988 hba->nutrs = (hba->capabilities & MASK_TRANSFER_REQUESTS_SLOTS) + 1;
1989 hba->nutmrs =
1990 ((hba->capabilities & MASK_TASK_MANAGEMENT_REQUEST_SLOTS) >> 16) + 1;
1994 * ufshcd_ready_for_uic_cmd - Check if controller is ready
1995 * to accept UIC commands
1996 * @hba: per adapter instance
1997 * Return true on success, else false
1999 static inline bool ufshcd_ready_for_uic_cmd(struct ufs_hba *hba)
2001 if (ufshcd_readl(hba, REG_CONTROLLER_STATUS) & UIC_COMMAND_READY)
2002 return true;
2003 else
2004 return false;
2008 * ufshcd_get_upmcrs - Get the power mode change request status
2009 * @hba: Pointer to adapter instance
2011 * This function gets the UPMCRS field of HCS register
2012 * Returns value of UPMCRS field
2014 static inline u8 ufshcd_get_upmcrs(struct ufs_hba *hba)
2016 return (ufshcd_readl(hba, REG_CONTROLLER_STATUS) >> 8) & 0x7;
2020 * ufshcd_dispatch_uic_cmd - Dispatch UIC commands to unipro layers
2021 * @hba: per adapter instance
2022 * @uic_cmd: UIC command
2024 * Mutex must be held.
2026 static inline void
2027 ufshcd_dispatch_uic_cmd(struct ufs_hba *hba, struct uic_command *uic_cmd)
2029 WARN_ON(hba->active_uic_cmd);
2031 hba->active_uic_cmd = uic_cmd;
2033 /* Write Args */
2034 ufshcd_writel(hba, uic_cmd->argument1, REG_UIC_COMMAND_ARG_1);
2035 ufshcd_writel(hba, uic_cmd->argument2, REG_UIC_COMMAND_ARG_2);
2036 ufshcd_writel(hba, uic_cmd->argument3, REG_UIC_COMMAND_ARG_3);
2038 /* Write UIC Cmd */
2039 ufshcd_writel(hba, uic_cmd->command & COMMAND_OPCODE_MASK,
2040 REG_UIC_COMMAND);
2044 * ufshcd_wait_for_uic_cmd - Wait complectioin of UIC command
2045 * @hba: per adapter instance
2046 * @uic_cmd: UIC command
2048 * Must be called with mutex held.
2049 * Returns 0 only if success.
2051 static int
2052 ufshcd_wait_for_uic_cmd(struct ufs_hba *hba, struct uic_command *uic_cmd)
2054 int ret;
2055 unsigned long flags;
2057 if (wait_for_completion_timeout(&uic_cmd->done,
2058 msecs_to_jiffies(UIC_CMD_TIMEOUT)))
2059 ret = uic_cmd->argument2 & MASK_UIC_COMMAND_RESULT;
2060 else
2061 ret = -ETIMEDOUT;
2063 spin_lock_irqsave(hba->host->host_lock, flags);
2064 hba->active_uic_cmd = NULL;
2065 spin_unlock_irqrestore(hba->host->host_lock, flags);
2067 return ret;
2071 * __ufshcd_send_uic_cmd - Send UIC commands and retrieve the result
2072 * @hba: per adapter instance
2073 * @uic_cmd: UIC command
2074 * @completion: initialize the completion only if this is set to true
2076 * Identical to ufshcd_send_uic_cmd() expect mutex. Must be called
2077 * with mutex held and host_lock locked.
2078 * Returns 0 only if success.
2080 static int
2081 __ufshcd_send_uic_cmd(struct ufs_hba *hba, struct uic_command *uic_cmd,
2082 bool completion)
2084 if (!ufshcd_ready_for_uic_cmd(hba)) {
2085 dev_err(hba->dev,
2086 "Controller not ready to accept UIC commands\n");
2087 return -EIO;
2090 if (completion)
2091 init_completion(&uic_cmd->done);
2093 ufshcd_dispatch_uic_cmd(hba, uic_cmd);
2095 return 0;
2099 * ufshcd_send_uic_cmd - Send UIC commands and retrieve the result
2100 * @hba: per adapter instance
2101 * @uic_cmd: UIC command
2103 * Returns 0 only if success.
2105 int ufshcd_send_uic_cmd(struct ufs_hba *hba, struct uic_command *uic_cmd)
2107 int ret;
2108 unsigned long flags;
2110 ufshcd_hold(hba, false);
2111 mutex_lock(&hba->uic_cmd_mutex);
2112 ufshcd_add_delay_before_dme_cmd(hba);
2114 spin_lock_irqsave(hba->host->host_lock, flags);
2115 ret = __ufshcd_send_uic_cmd(hba, uic_cmd, true);
2116 spin_unlock_irqrestore(hba->host->host_lock, flags);
2117 if (!ret)
2118 ret = ufshcd_wait_for_uic_cmd(hba, uic_cmd);
2120 mutex_unlock(&hba->uic_cmd_mutex);
2122 ufshcd_release(hba);
2123 return ret;
2127 * ufshcd_map_sg - Map scatter-gather list to prdt
2128 * @hba: per adapter instance
2129 * @lrbp: pointer to local reference block
2131 * Returns 0 in case of success, non-zero value in case of failure
2133 static int ufshcd_map_sg(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
2135 struct ufshcd_sg_entry *prd_table;
2136 struct scatterlist *sg;
2137 struct scsi_cmnd *cmd;
2138 int sg_segments;
2139 int i;
2141 cmd = lrbp->cmd;
2142 sg_segments = scsi_dma_map(cmd);
2143 if (sg_segments < 0)
2144 return sg_segments;
2146 if (sg_segments) {
2147 lrbp->utr_descriptor_ptr->prd_table_length =
2148 cpu_to_le16((u16)sg_segments);
2150 prd_table = (struct ufshcd_sg_entry *)lrbp->ucd_prdt_ptr;
2152 scsi_for_each_sg(cmd, sg, sg_segments, i) {
2153 prd_table[i].size =
2154 cpu_to_le32(((u32) sg_dma_len(sg))-1);
2155 prd_table[i].base_addr =
2156 cpu_to_le32(lower_32_bits(sg->dma_address));
2157 prd_table[i].upper_addr =
2158 cpu_to_le32(upper_32_bits(sg->dma_address));
2159 prd_table[i].reserved = 0;
2161 } else {
2162 lrbp->utr_descriptor_ptr->prd_table_length = 0;
2165 return 0;
2169 * ufshcd_enable_intr - enable interrupts
2170 * @hba: per adapter instance
2171 * @intrs: interrupt bits
2173 static void ufshcd_enable_intr(struct ufs_hba *hba, u32 intrs)
2175 u32 set = ufshcd_readl(hba, REG_INTERRUPT_ENABLE);
2177 if (hba->ufs_version == UFSHCI_VERSION_10) {
2178 u32 rw;
2179 rw = set & INTERRUPT_MASK_RW_VER_10;
2180 set = rw | ((set ^ intrs) & intrs);
2181 } else {
2182 set |= intrs;
2185 ufshcd_writel(hba, set, REG_INTERRUPT_ENABLE);
2189 * ufshcd_disable_intr - disable interrupts
2190 * @hba: per adapter instance
2191 * @intrs: interrupt bits
2193 static void ufshcd_disable_intr(struct ufs_hba *hba, u32 intrs)
2195 u32 set = ufshcd_readl(hba, REG_INTERRUPT_ENABLE);
2197 if (hba->ufs_version == UFSHCI_VERSION_10) {
2198 u32 rw;
2199 rw = (set & INTERRUPT_MASK_RW_VER_10) &
2200 ~(intrs & INTERRUPT_MASK_RW_VER_10);
2201 set = rw | ((set & intrs) & ~INTERRUPT_MASK_RW_VER_10);
2203 } else {
2204 set &= ~intrs;
2207 ufshcd_writel(hba, set, REG_INTERRUPT_ENABLE);
2211 * ufshcd_prepare_req_desc_hdr() - Fills the requests header
2212 * descriptor according to request
2213 * @lrbp: pointer to local reference block
2214 * @upiu_flags: flags required in the header
2215 * @cmd_dir: requests data direction
2217 static void ufshcd_prepare_req_desc_hdr(struct ufshcd_lrb *lrbp,
2218 u32 *upiu_flags, enum dma_data_direction cmd_dir)
2220 struct utp_transfer_req_desc *req_desc = lrbp->utr_descriptor_ptr;
2221 u32 data_direction;
2222 u32 dword_0;
2224 if (cmd_dir == DMA_FROM_DEVICE) {
2225 data_direction = UTP_DEVICE_TO_HOST;
2226 *upiu_flags = UPIU_CMD_FLAGS_READ;
2227 } else if (cmd_dir == DMA_TO_DEVICE) {
2228 data_direction = UTP_HOST_TO_DEVICE;
2229 *upiu_flags = UPIU_CMD_FLAGS_WRITE;
2230 } else {
2231 data_direction = UTP_NO_DATA_TRANSFER;
2232 *upiu_flags = UPIU_CMD_FLAGS_NONE;
2235 dword_0 = data_direction | (lrbp->command_type
2236 << UPIU_COMMAND_TYPE_OFFSET);
2237 if (lrbp->intr_cmd)
2238 dword_0 |= UTP_REQ_DESC_INT_CMD;
2240 /* Transfer request descriptor header fields */
2241 req_desc->header.dword_0 = cpu_to_le32(dword_0);
2242 /* dword_1 is reserved, hence it is set to 0 */
2243 req_desc->header.dword_1 = 0;
2245 * assigning invalid value for command status. Controller
2246 * updates OCS on command completion, with the command
2247 * status
2249 req_desc->header.dword_2 =
2250 cpu_to_le32(OCS_INVALID_COMMAND_STATUS);
2251 /* dword_3 is reserved, hence it is set to 0 */
2252 req_desc->header.dword_3 = 0;
2254 req_desc->prd_table_length = 0;
2258 * ufshcd_prepare_utp_scsi_cmd_upiu() - fills the utp_transfer_req_desc,
2259 * for scsi commands
2260 * @lrbp: local reference block pointer
2261 * @upiu_flags: flags
2263 static
2264 void ufshcd_prepare_utp_scsi_cmd_upiu(struct ufshcd_lrb *lrbp, u32 upiu_flags)
2266 struct scsi_cmnd *cmd = lrbp->cmd;
2267 struct utp_upiu_req *ucd_req_ptr = lrbp->ucd_req_ptr;
2268 unsigned short cdb_len;
2270 /* command descriptor fields */
2271 ucd_req_ptr->header.dword_0 = UPIU_HEADER_DWORD(
2272 UPIU_TRANSACTION_COMMAND, upiu_flags,
2273 lrbp->lun, lrbp->task_tag);
2274 ucd_req_ptr->header.dword_1 = UPIU_HEADER_DWORD(
2275 UPIU_COMMAND_SET_TYPE_SCSI, 0, 0, 0);
2277 /* Total EHS length and Data segment length will be zero */
2278 ucd_req_ptr->header.dword_2 = 0;
2280 ucd_req_ptr->sc.exp_data_transfer_len = cpu_to_be32(cmd->sdb.length);
2282 cdb_len = min_t(unsigned short, cmd->cmd_len, UFS_CDB_SIZE);
2283 memset(ucd_req_ptr->sc.cdb, 0, UFS_CDB_SIZE);
2284 memcpy(ucd_req_ptr->sc.cdb, cmd->cmnd, cdb_len);
2286 memset(lrbp->ucd_rsp_ptr, 0, sizeof(struct utp_upiu_rsp));
2290 * ufshcd_prepare_utp_query_req_upiu() - fills the utp_transfer_req_desc,
2291 * for query requsts
2292 * @hba: UFS hba
2293 * @lrbp: local reference block pointer
2294 * @upiu_flags: flags
2296 static void ufshcd_prepare_utp_query_req_upiu(struct ufs_hba *hba,
2297 struct ufshcd_lrb *lrbp, u32 upiu_flags)
2299 struct utp_upiu_req *ucd_req_ptr = lrbp->ucd_req_ptr;
2300 struct ufs_query *query = &hba->dev_cmd.query;
2301 u16 len = be16_to_cpu(query->request.upiu_req.length);
2303 /* Query request header */
2304 ucd_req_ptr->header.dword_0 = UPIU_HEADER_DWORD(
2305 UPIU_TRANSACTION_QUERY_REQ, upiu_flags,
2306 lrbp->lun, lrbp->task_tag);
2307 ucd_req_ptr->header.dword_1 = UPIU_HEADER_DWORD(
2308 0, query->request.query_func, 0, 0);
2310 /* Data segment length only need for WRITE_DESC */
2311 if (query->request.upiu_req.opcode == UPIU_QUERY_OPCODE_WRITE_DESC)
2312 ucd_req_ptr->header.dword_2 =
2313 UPIU_HEADER_DWORD(0, 0, (len >> 8), (u8)len);
2314 else
2315 ucd_req_ptr->header.dword_2 = 0;
2317 /* Copy the Query Request buffer as is */
2318 memcpy(&ucd_req_ptr->qr, &query->request.upiu_req,
2319 QUERY_OSF_SIZE);
2321 /* Copy the Descriptor */
2322 if (query->request.upiu_req.opcode == UPIU_QUERY_OPCODE_WRITE_DESC)
2323 memcpy(ucd_req_ptr + 1, query->descriptor, len);
2325 memset(lrbp->ucd_rsp_ptr, 0, sizeof(struct utp_upiu_rsp));
2328 static inline void ufshcd_prepare_utp_nop_upiu(struct ufshcd_lrb *lrbp)
2330 struct utp_upiu_req *ucd_req_ptr = lrbp->ucd_req_ptr;
2332 memset(ucd_req_ptr, 0, sizeof(struct utp_upiu_req));
2334 /* command descriptor fields */
2335 ucd_req_ptr->header.dword_0 =
2336 UPIU_HEADER_DWORD(
2337 UPIU_TRANSACTION_NOP_OUT, 0, 0, lrbp->task_tag);
2338 /* clear rest of the fields of basic header */
2339 ucd_req_ptr->header.dword_1 = 0;
2340 ucd_req_ptr->header.dword_2 = 0;
2342 memset(lrbp->ucd_rsp_ptr, 0, sizeof(struct utp_upiu_rsp));
2346 * ufshcd_comp_devman_upiu - UFS Protocol Information Unit(UPIU)
2347 * for Device Management Purposes
2348 * @hba: per adapter instance
2349 * @lrbp: pointer to local reference block
2351 static int ufshcd_comp_devman_upiu(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
2353 u32 upiu_flags;
2354 int ret = 0;
2356 if ((hba->ufs_version == UFSHCI_VERSION_10) ||
2357 (hba->ufs_version == UFSHCI_VERSION_11))
2358 lrbp->command_type = UTP_CMD_TYPE_DEV_MANAGE;
2359 else
2360 lrbp->command_type = UTP_CMD_TYPE_UFS_STORAGE;
2362 ufshcd_prepare_req_desc_hdr(lrbp, &upiu_flags, DMA_NONE);
2363 if (hba->dev_cmd.type == DEV_CMD_TYPE_QUERY)
2364 ufshcd_prepare_utp_query_req_upiu(hba, lrbp, upiu_flags);
2365 else if (hba->dev_cmd.type == DEV_CMD_TYPE_NOP)
2366 ufshcd_prepare_utp_nop_upiu(lrbp);
2367 else
2368 ret = -EINVAL;
2370 return ret;
2374 * ufshcd_comp_scsi_upiu - UFS Protocol Information Unit(UPIU)
2375 * for SCSI Purposes
2376 * @hba: per adapter instance
2377 * @lrbp: pointer to local reference block
2379 static int ufshcd_comp_scsi_upiu(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
2381 u32 upiu_flags;
2382 int ret = 0;
2384 if ((hba->ufs_version == UFSHCI_VERSION_10) ||
2385 (hba->ufs_version == UFSHCI_VERSION_11))
2386 lrbp->command_type = UTP_CMD_TYPE_SCSI;
2387 else
2388 lrbp->command_type = UTP_CMD_TYPE_UFS_STORAGE;
2390 if (likely(lrbp->cmd)) {
2391 ufshcd_prepare_req_desc_hdr(lrbp, &upiu_flags,
2392 lrbp->cmd->sc_data_direction);
2393 ufshcd_prepare_utp_scsi_cmd_upiu(lrbp, upiu_flags);
2394 } else {
2395 ret = -EINVAL;
2398 return ret;
2402 * ufshcd_upiu_wlun_to_scsi_wlun - maps UPIU W-LUN id to SCSI W-LUN ID
2403 * @upiu_wlun_id: UPIU W-LUN id
2405 * Returns SCSI W-LUN id
2407 static inline u16 ufshcd_upiu_wlun_to_scsi_wlun(u8 upiu_wlun_id)
2409 return (upiu_wlun_id & ~UFS_UPIU_WLUN_ID) | SCSI_W_LUN_BASE;
2412 static void ufshcd_init_lrb(struct ufs_hba *hba, struct ufshcd_lrb *lrb, int i)
2414 struct utp_transfer_cmd_desc *cmd_descp = hba->ucdl_base_addr;
2415 struct utp_transfer_req_desc *utrdlp = hba->utrdl_base_addr;
2416 dma_addr_t cmd_desc_element_addr = hba->ucdl_dma_addr +
2417 i * sizeof(struct utp_transfer_cmd_desc);
2418 u16 response_offset = offsetof(struct utp_transfer_cmd_desc,
2419 response_upiu);
2420 u16 prdt_offset = offsetof(struct utp_transfer_cmd_desc, prd_table);
2422 lrb->utr_descriptor_ptr = utrdlp + i;
2423 lrb->utrd_dma_addr = hba->utrdl_dma_addr +
2424 i * sizeof(struct utp_transfer_req_desc);
2425 lrb->ucd_req_ptr = (struct utp_upiu_req *)(cmd_descp + i);
2426 lrb->ucd_req_dma_addr = cmd_desc_element_addr;
2427 lrb->ucd_rsp_ptr = (struct utp_upiu_rsp *)cmd_descp[i].response_upiu;
2428 lrb->ucd_rsp_dma_addr = cmd_desc_element_addr + response_offset;
2429 lrb->ucd_prdt_ptr = (struct ufshcd_sg_entry *)cmd_descp[i].prd_table;
2430 lrb->ucd_prdt_dma_addr = cmd_desc_element_addr + prdt_offset;
2434 * ufshcd_queuecommand - main entry point for SCSI requests
2435 * @host: SCSI host pointer
2436 * @cmd: command from SCSI Midlayer
2438 * Returns 0 for success, non-zero in case of failure
2440 static int ufshcd_queuecommand(struct Scsi_Host *host, struct scsi_cmnd *cmd)
2442 struct ufshcd_lrb *lrbp;
2443 struct ufs_hba *hba;
2444 unsigned long flags;
2445 int tag;
2446 int err = 0;
2448 hba = shost_priv(host);
2450 tag = cmd->request->tag;
2451 if (!ufshcd_valid_tag(hba, tag)) {
2452 dev_err(hba->dev,
2453 "%s: invalid command tag %d: cmd=0x%p, cmd->request=0x%p",
2454 __func__, tag, cmd, cmd->request);
2455 BUG();
2458 if (!down_read_trylock(&hba->clk_scaling_lock))
2459 return SCSI_MLQUEUE_HOST_BUSY;
2461 spin_lock_irqsave(hba->host->host_lock, flags);
2462 switch (hba->ufshcd_state) {
2463 case UFSHCD_STATE_OPERATIONAL:
2464 break;
2465 case UFSHCD_STATE_EH_SCHEDULED:
2466 case UFSHCD_STATE_RESET:
2467 err = SCSI_MLQUEUE_HOST_BUSY;
2468 goto out_unlock;
2469 case UFSHCD_STATE_ERROR:
2470 set_host_byte(cmd, DID_ERROR);
2471 cmd->scsi_done(cmd);
2472 goto out_unlock;
2473 default:
2474 dev_WARN_ONCE(hba->dev, 1, "%s: invalid state %d\n",
2475 __func__, hba->ufshcd_state);
2476 set_host_byte(cmd, DID_BAD_TARGET);
2477 cmd->scsi_done(cmd);
2478 goto out_unlock;
2481 /* if error handling is in progress, don't issue commands */
2482 if (ufshcd_eh_in_progress(hba)) {
2483 set_host_byte(cmd, DID_ERROR);
2484 cmd->scsi_done(cmd);
2485 goto out_unlock;
2487 spin_unlock_irqrestore(hba->host->host_lock, flags);
2489 hba->req_abort_count = 0;
2491 err = ufshcd_hold(hba, true);
2492 if (err) {
2493 err = SCSI_MLQUEUE_HOST_BUSY;
2494 goto out;
2496 WARN_ON(hba->clk_gating.state != CLKS_ON);
2498 lrbp = &hba->lrb[tag];
2500 WARN_ON(lrbp->cmd);
2501 lrbp->cmd = cmd;
2502 lrbp->sense_bufflen = UFS_SENSE_SIZE;
2503 lrbp->sense_buffer = cmd->sense_buffer;
2504 lrbp->task_tag = tag;
2505 lrbp->lun = ufshcd_scsi_to_upiu_lun(cmd->device->lun);
2506 lrbp->intr_cmd = !ufshcd_is_intr_aggr_allowed(hba) ? true : false;
2507 lrbp->req_abort_skip = false;
2509 ufshcd_comp_scsi_upiu(hba, lrbp);
2511 err = ufshcd_map_sg(hba, lrbp);
2512 if (err) {
2513 lrbp->cmd = NULL;
2514 ufshcd_release(hba);
2515 goto out;
2517 /* Make sure descriptors are ready before ringing the doorbell */
2518 wmb();
2520 /* issue command to the controller */
2521 spin_lock_irqsave(hba->host->host_lock, flags);
2522 ufshcd_vops_setup_xfer_req(hba, tag, true);
2523 ufshcd_send_command(hba, tag);
2524 out_unlock:
2525 spin_unlock_irqrestore(hba->host->host_lock, flags);
2526 out:
2527 up_read(&hba->clk_scaling_lock);
2528 return err;
2531 static int ufshcd_compose_dev_cmd(struct ufs_hba *hba,
2532 struct ufshcd_lrb *lrbp, enum dev_cmd_type cmd_type, int tag)
2534 lrbp->cmd = NULL;
2535 lrbp->sense_bufflen = 0;
2536 lrbp->sense_buffer = NULL;
2537 lrbp->task_tag = tag;
2538 lrbp->lun = 0; /* device management cmd is not specific to any LUN */
2539 lrbp->intr_cmd = true; /* No interrupt aggregation */
2540 hba->dev_cmd.type = cmd_type;
2542 return ufshcd_comp_devman_upiu(hba, lrbp);
2545 static int
2546 ufshcd_clear_cmd(struct ufs_hba *hba, int tag)
2548 int err = 0;
2549 unsigned long flags;
2550 u32 mask = 1 << tag;
2552 /* clear outstanding transaction before retry */
2553 spin_lock_irqsave(hba->host->host_lock, flags);
2554 ufshcd_utrl_clear(hba, tag);
2555 spin_unlock_irqrestore(hba->host->host_lock, flags);
2558 * wait for for h/w to clear corresponding bit in door-bell.
2559 * max. wait is 1 sec.
2561 err = ufshcd_wait_for_register(hba,
2562 REG_UTP_TRANSFER_REQ_DOOR_BELL,
2563 mask, ~mask, 1000, 1000, true);
2565 return err;
2568 static int
2569 ufshcd_check_query_response(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
2571 struct ufs_query_res *query_res = &hba->dev_cmd.query.response;
2573 /* Get the UPIU response */
2574 query_res->response = ufshcd_get_rsp_upiu_result(lrbp->ucd_rsp_ptr) >>
2575 UPIU_RSP_CODE_OFFSET;
2576 return query_res->response;
2580 * ufshcd_dev_cmd_completion() - handles device management command responses
2581 * @hba: per adapter instance
2582 * @lrbp: pointer to local reference block
2584 static int
2585 ufshcd_dev_cmd_completion(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
2587 int resp;
2588 int err = 0;
2590 hba->ufs_stats.last_hibern8_exit_tstamp = ktime_set(0, 0);
2591 resp = ufshcd_get_req_rsp(lrbp->ucd_rsp_ptr);
2593 switch (resp) {
2594 case UPIU_TRANSACTION_NOP_IN:
2595 if (hba->dev_cmd.type != DEV_CMD_TYPE_NOP) {
2596 err = -EINVAL;
2597 dev_err(hba->dev, "%s: unexpected response %x\n",
2598 __func__, resp);
2600 break;
2601 case UPIU_TRANSACTION_QUERY_RSP:
2602 err = ufshcd_check_query_response(hba, lrbp);
2603 if (!err)
2604 err = ufshcd_copy_query_response(hba, lrbp);
2605 break;
2606 case UPIU_TRANSACTION_REJECT_UPIU:
2607 /* TODO: handle Reject UPIU Response */
2608 err = -EPERM;
2609 dev_err(hba->dev, "%s: Reject UPIU not fully implemented\n",
2610 __func__);
2611 break;
2612 default:
2613 err = -EINVAL;
2614 dev_err(hba->dev, "%s: Invalid device management cmd response: %x\n",
2615 __func__, resp);
2616 break;
2619 return err;
2622 static int ufshcd_wait_for_dev_cmd(struct ufs_hba *hba,
2623 struct ufshcd_lrb *lrbp, int max_timeout)
2625 int err = 0;
2626 unsigned long time_left;
2627 unsigned long flags;
2629 time_left = wait_for_completion_timeout(hba->dev_cmd.complete,
2630 msecs_to_jiffies(max_timeout));
2632 /* Make sure descriptors are ready before ringing the doorbell */
2633 wmb();
2634 spin_lock_irqsave(hba->host->host_lock, flags);
2635 hba->dev_cmd.complete = NULL;
2636 if (likely(time_left)) {
2637 err = ufshcd_get_tr_ocs(lrbp);
2638 if (!err)
2639 err = ufshcd_dev_cmd_completion(hba, lrbp);
2641 spin_unlock_irqrestore(hba->host->host_lock, flags);
2643 if (!time_left) {
2644 err = -ETIMEDOUT;
2645 dev_dbg(hba->dev, "%s: dev_cmd request timedout, tag %d\n",
2646 __func__, lrbp->task_tag);
2647 if (!ufshcd_clear_cmd(hba, lrbp->task_tag))
2648 /* successfully cleared the command, retry if needed */
2649 err = -EAGAIN;
2651 * in case of an error, after clearing the doorbell,
2652 * we also need to clear the outstanding_request
2653 * field in hba
2655 ufshcd_outstanding_req_clear(hba, lrbp->task_tag);
2658 return err;
2662 * ufshcd_exec_dev_cmd - API for sending device management requests
2663 * @hba: UFS hba
2664 * @cmd_type: specifies the type (NOP, Query...)
2665 * @timeout: time in seconds
2667 * NOTE: Since there is only one available tag for device management commands,
2668 * it is expected you hold the hba->dev_cmd.lock mutex.
2670 static int ufshcd_exec_dev_cmd(struct ufs_hba *hba,
2671 enum dev_cmd_type cmd_type, int timeout)
2673 struct request_queue *q = hba->cmd_queue;
2674 struct request *req;
2675 struct ufshcd_lrb *lrbp;
2676 int err;
2677 int tag;
2678 struct completion wait;
2679 unsigned long flags;
2681 down_read(&hba->clk_scaling_lock);
2684 * Get free slot, sleep if slots are unavailable.
2685 * Even though we use wait_event() which sleeps indefinitely,
2686 * the maximum wait time is bounded by SCSI request timeout.
2688 req = blk_get_request(q, REQ_OP_DRV_OUT, 0);
2689 if (IS_ERR(req)) {
2690 err = PTR_ERR(req);
2691 goto out_unlock;
2693 tag = req->tag;
2694 WARN_ON_ONCE(!ufshcd_valid_tag(hba, tag));
2696 init_completion(&wait);
2697 lrbp = &hba->lrb[tag];
2698 WARN_ON(lrbp->cmd);
2699 err = ufshcd_compose_dev_cmd(hba, lrbp, cmd_type, tag);
2700 if (unlikely(err))
2701 goto out_put_tag;
2703 hba->dev_cmd.complete = &wait;
2705 ufshcd_add_query_upiu_trace(hba, tag, "query_send");
2706 /* Make sure descriptors are ready before ringing the doorbell */
2707 wmb();
2708 spin_lock_irqsave(hba->host->host_lock, flags);
2709 ufshcd_vops_setup_xfer_req(hba, tag, false);
2710 ufshcd_send_command(hba, tag);
2711 spin_unlock_irqrestore(hba->host->host_lock, flags);
2713 err = ufshcd_wait_for_dev_cmd(hba, lrbp, timeout);
2715 ufshcd_add_query_upiu_trace(hba, tag,
2716 err ? "query_complete_err" : "query_complete");
2718 out_put_tag:
2719 blk_put_request(req);
2720 out_unlock:
2721 up_read(&hba->clk_scaling_lock);
2722 return err;
2726 * ufshcd_init_query() - init the query response and request parameters
2727 * @hba: per-adapter instance
2728 * @request: address of the request pointer to be initialized
2729 * @response: address of the response pointer to be initialized
2730 * @opcode: operation to perform
2731 * @idn: flag idn to access
2732 * @index: LU number to access
2733 * @selector: query/flag/descriptor further identification
2735 static inline void ufshcd_init_query(struct ufs_hba *hba,
2736 struct ufs_query_req **request, struct ufs_query_res **response,
2737 enum query_opcode opcode, u8 idn, u8 index, u8 selector)
2739 *request = &hba->dev_cmd.query.request;
2740 *response = &hba->dev_cmd.query.response;
2741 memset(*request, 0, sizeof(struct ufs_query_req));
2742 memset(*response, 0, sizeof(struct ufs_query_res));
2743 (*request)->upiu_req.opcode = opcode;
2744 (*request)->upiu_req.idn = idn;
2745 (*request)->upiu_req.index = index;
2746 (*request)->upiu_req.selector = selector;
2749 static int ufshcd_query_flag_retry(struct ufs_hba *hba,
2750 enum query_opcode opcode, enum flag_idn idn, bool *flag_res)
2752 int ret;
2753 int retries;
2755 for (retries = 0; retries < QUERY_REQ_RETRIES; retries++) {
2756 ret = ufshcd_query_flag(hba, opcode, idn, flag_res);
2757 if (ret)
2758 dev_dbg(hba->dev,
2759 "%s: failed with error %d, retries %d\n",
2760 __func__, ret, retries);
2761 else
2762 break;
2765 if (ret)
2766 dev_err(hba->dev,
2767 "%s: query attribute, opcode %d, idn %d, failed with error %d after %d retires\n",
2768 __func__, opcode, idn, ret, retries);
2769 return ret;
2773 * ufshcd_query_flag() - API function for sending flag query requests
2774 * @hba: per-adapter instance
2775 * @opcode: flag query to perform
2776 * @idn: flag idn to access
2777 * @flag_res: the flag value after the query request completes
2779 * Returns 0 for success, non-zero in case of failure
2781 int ufshcd_query_flag(struct ufs_hba *hba, enum query_opcode opcode,
2782 enum flag_idn idn, bool *flag_res)
2784 struct ufs_query_req *request = NULL;
2785 struct ufs_query_res *response = NULL;
2786 int err, index = 0, selector = 0;
2787 int timeout = QUERY_REQ_TIMEOUT;
2789 BUG_ON(!hba);
2791 ufshcd_hold(hba, false);
2792 mutex_lock(&hba->dev_cmd.lock);
2793 ufshcd_init_query(hba, &request, &response, opcode, idn, index,
2794 selector);
2796 switch (opcode) {
2797 case UPIU_QUERY_OPCODE_SET_FLAG:
2798 case UPIU_QUERY_OPCODE_CLEAR_FLAG:
2799 case UPIU_QUERY_OPCODE_TOGGLE_FLAG:
2800 request->query_func = UPIU_QUERY_FUNC_STANDARD_WRITE_REQUEST;
2801 break;
2802 case UPIU_QUERY_OPCODE_READ_FLAG:
2803 request->query_func = UPIU_QUERY_FUNC_STANDARD_READ_REQUEST;
2804 if (!flag_res) {
2805 /* No dummy reads */
2806 dev_err(hba->dev, "%s: Invalid argument for read request\n",
2807 __func__);
2808 err = -EINVAL;
2809 goto out_unlock;
2811 break;
2812 default:
2813 dev_err(hba->dev,
2814 "%s: Expected query flag opcode but got = %d\n",
2815 __func__, opcode);
2816 err = -EINVAL;
2817 goto out_unlock;
2820 err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_QUERY, timeout);
2822 if (err) {
2823 dev_err(hba->dev,
2824 "%s: Sending flag query for idn %d failed, err = %d\n",
2825 __func__, idn, err);
2826 goto out_unlock;
2829 if (flag_res)
2830 *flag_res = (be32_to_cpu(response->upiu_res.value) &
2831 MASK_QUERY_UPIU_FLAG_LOC) & 0x1;
2833 out_unlock:
2834 mutex_unlock(&hba->dev_cmd.lock);
2835 ufshcd_release(hba);
2836 return err;
2840 * ufshcd_query_attr - API function for sending attribute requests
2841 * @hba: per-adapter instance
2842 * @opcode: attribute opcode
2843 * @idn: attribute idn to access
2844 * @index: index field
2845 * @selector: selector field
2846 * @attr_val: the attribute value after the query request completes
2848 * Returns 0 for success, non-zero in case of failure
2850 int ufshcd_query_attr(struct ufs_hba *hba, enum query_opcode opcode,
2851 enum attr_idn idn, u8 index, u8 selector, u32 *attr_val)
2853 struct ufs_query_req *request = NULL;
2854 struct ufs_query_res *response = NULL;
2855 int err;
2857 BUG_ON(!hba);
2859 ufshcd_hold(hba, false);
2860 if (!attr_val) {
2861 dev_err(hba->dev, "%s: attribute value required for opcode 0x%x\n",
2862 __func__, opcode);
2863 err = -EINVAL;
2864 goto out;
2867 mutex_lock(&hba->dev_cmd.lock);
2868 ufshcd_init_query(hba, &request, &response, opcode, idn, index,
2869 selector);
2871 switch (opcode) {
2872 case UPIU_QUERY_OPCODE_WRITE_ATTR:
2873 request->query_func = UPIU_QUERY_FUNC_STANDARD_WRITE_REQUEST;
2874 request->upiu_req.value = cpu_to_be32(*attr_val);
2875 break;
2876 case UPIU_QUERY_OPCODE_READ_ATTR:
2877 request->query_func = UPIU_QUERY_FUNC_STANDARD_READ_REQUEST;
2878 break;
2879 default:
2880 dev_err(hba->dev, "%s: Expected query attr opcode but got = 0x%.2x\n",
2881 __func__, opcode);
2882 err = -EINVAL;
2883 goto out_unlock;
2886 err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_QUERY, QUERY_REQ_TIMEOUT);
2888 if (err) {
2889 dev_err(hba->dev, "%s: opcode 0x%.2x for idn %d failed, index %d, err = %d\n",
2890 __func__, opcode, idn, index, err);
2891 goto out_unlock;
2894 *attr_val = be32_to_cpu(response->upiu_res.value);
2896 out_unlock:
2897 mutex_unlock(&hba->dev_cmd.lock);
2898 out:
2899 ufshcd_release(hba);
2900 return err;
2904 * ufshcd_query_attr_retry() - API function for sending query
2905 * attribute with retries
2906 * @hba: per-adapter instance
2907 * @opcode: attribute opcode
2908 * @idn: attribute idn to access
2909 * @index: index field
2910 * @selector: selector field
2911 * @attr_val: the attribute value after the query request
2912 * completes
2914 * Returns 0 for success, non-zero in case of failure
2916 static int ufshcd_query_attr_retry(struct ufs_hba *hba,
2917 enum query_opcode opcode, enum attr_idn idn, u8 index, u8 selector,
2918 u32 *attr_val)
2920 int ret = 0;
2921 u32 retries;
2923 for (retries = QUERY_REQ_RETRIES; retries > 0; retries--) {
2924 ret = ufshcd_query_attr(hba, opcode, idn, index,
2925 selector, attr_val);
2926 if (ret)
2927 dev_dbg(hba->dev, "%s: failed with error %d, retries %d\n",
2928 __func__, ret, retries);
2929 else
2930 break;
2933 if (ret)
2934 dev_err(hba->dev,
2935 "%s: query attribute, idn %d, failed with error %d after %d retires\n",
2936 __func__, idn, ret, QUERY_REQ_RETRIES);
2937 return ret;
2940 static int __ufshcd_query_descriptor(struct ufs_hba *hba,
2941 enum query_opcode opcode, enum desc_idn idn, u8 index,
2942 u8 selector, u8 *desc_buf, int *buf_len)
2944 struct ufs_query_req *request = NULL;
2945 struct ufs_query_res *response = NULL;
2946 int err;
2948 BUG_ON(!hba);
2950 ufshcd_hold(hba, false);
2951 if (!desc_buf) {
2952 dev_err(hba->dev, "%s: descriptor buffer required for opcode 0x%x\n",
2953 __func__, opcode);
2954 err = -EINVAL;
2955 goto out;
2958 if (*buf_len < QUERY_DESC_MIN_SIZE || *buf_len > QUERY_DESC_MAX_SIZE) {
2959 dev_err(hba->dev, "%s: descriptor buffer size (%d) is out of range\n",
2960 __func__, *buf_len);
2961 err = -EINVAL;
2962 goto out;
2965 mutex_lock(&hba->dev_cmd.lock);
2966 ufshcd_init_query(hba, &request, &response, opcode, idn, index,
2967 selector);
2968 hba->dev_cmd.query.descriptor = desc_buf;
2969 request->upiu_req.length = cpu_to_be16(*buf_len);
2971 switch (opcode) {
2972 case UPIU_QUERY_OPCODE_WRITE_DESC:
2973 request->query_func = UPIU_QUERY_FUNC_STANDARD_WRITE_REQUEST;
2974 break;
2975 case UPIU_QUERY_OPCODE_READ_DESC:
2976 request->query_func = UPIU_QUERY_FUNC_STANDARD_READ_REQUEST;
2977 break;
2978 default:
2979 dev_err(hba->dev,
2980 "%s: Expected query descriptor opcode but got = 0x%.2x\n",
2981 __func__, opcode);
2982 err = -EINVAL;
2983 goto out_unlock;
2986 err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_QUERY, QUERY_REQ_TIMEOUT);
2988 if (err) {
2989 dev_err(hba->dev, "%s: opcode 0x%.2x for idn %d failed, index %d, err = %d\n",
2990 __func__, opcode, idn, index, err);
2991 goto out_unlock;
2994 *buf_len = be16_to_cpu(response->upiu_res.length);
2996 out_unlock:
2997 hba->dev_cmd.query.descriptor = NULL;
2998 mutex_unlock(&hba->dev_cmd.lock);
2999 out:
3000 ufshcd_release(hba);
3001 return err;
3005 * ufshcd_query_descriptor_retry - API function for sending descriptor requests
3006 * @hba: per-adapter instance
3007 * @opcode: attribute opcode
3008 * @idn: attribute idn to access
3009 * @index: index field
3010 * @selector: selector field
3011 * @desc_buf: the buffer that contains the descriptor
3012 * @buf_len: length parameter passed to the device
3014 * Returns 0 for success, non-zero in case of failure.
3015 * The buf_len parameter will contain, on return, the length parameter
3016 * received on the response.
3018 int ufshcd_query_descriptor_retry(struct ufs_hba *hba,
3019 enum query_opcode opcode,
3020 enum desc_idn idn, u8 index,
3021 u8 selector,
3022 u8 *desc_buf, int *buf_len)
3024 int err;
3025 int retries;
3027 for (retries = QUERY_REQ_RETRIES; retries > 0; retries--) {
3028 err = __ufshcd_query_descriptor(hba, opcode, idn, index,
3029 selector, desc_buf, buf_len);
3030 if (!err || err == -EINVAL)
3031 break;
3034 return err;
3038 * ufshcd_read_desc_length - read the specified descriptor length from header
3039 * @hba: Pointer to adapter instance
3040 * @desc_id: descriptor idn value
3041 * @desc_index: descriptor index
3042 * @desc_length: pointer to variable to read the length of descriptor
3044 * Return 0 in case of success, non-zero otherwise
3046 static int ufshcd_read_desc_length(struct ufs_hba *hba,
3047 enum desc_idn desc_id,
3048 int desc_index,
3049 int *desc_length)
3051 int ret;
3052 u8 header[QUERY_DESC_HDR_SIZE];
3053 int header_len = QUERY_DESC_HDR_SIZE;
3055 if (desc_id >= QUERY_DESC_IDN_MAX)
3056 return -EINVAL;
3058 ret = ufshcd_query_descriptor_retry(hba, UPIU_QUERY_OPCODE_READ_DESC,
3059 desc_id, desc_index, 0, header,
3060 &header_len);
3062 if (ret) {
3063 dev_err(hba->dev, "%s: Failed to get descriptor header id %d",
3064 __func__, desc_id);
3065 return ret;
3066 } else if (desc_id != header[QUERY_DESC_DESC_TYPE_OFFSET]) {
3067 dev_warn(hba->dev, "%s: descriptor header id %d and desc_id %d mismatch",
3068 __func__, header[QUERY_DESC_DESC_TYPE_OFFSET],
3069 desc_id);
3070 ret = -EINVAL;
3073 *desc_length = header[QUERY_DESC_LENGTH_OFFSET];
3074 return ret;
3079 * ufshcd_map_desc_id_to_length - map descriptor IDN to its length
3080 * @hba: Pointer to adapter instance
3081 * @desc_id: descriptor idn value
3082 * @desc_len: mapped desc length (out)
3084 * Return 0 in case of success, non-zero otherwise
3086 int ufshcd_map_desc_id_to_length(struct ufs_hba *hba,
3087 enum desc_idn desc_id, int *desc_len)
3089 switch (desc_id) {
3090 case QUERY_DESC_IDN_DEVICE:
3091 *desc_len = hba->desc_size.dev_desc;
3092 break;
3093 case QUERY_DESC_IDN_POWER:
3094 *desc_len = hba->desc_size.pwr_desc;
3095 break;
3096 case QUERY_DESC_IDN_GEOMETRY:
3097 *desc_len = hba->desc_size.geom_desc;
3098 break;
3099 case QUERY_DESC_IDN_CONFIGURATION:
3100 *desc_len = hba->desc_size.conf_desc;
3101 break;
3102 case QUERY_DESC_IDN_UNIT:
3103 *desc_len = hba->desc_size.unit_desc;
3104 break;
3105 case QUERY_DESC_IDN_INTERCONNECT:
3106 *desc_len = hba->desc_size.interc_desc;
3107 break;
3108 case QUERY_DESC_IDN_STRING:
3109 *desc_len = QUERY_DESC_MAX_SIZE;
3110 break;
3111 case QUERY_DESC_IDN_HEALTH:
3112 *desc_len = hba->desc_size.hlth_desc;
3113 break;
3114 case QUERY_DESC_IDN_RFU_0:
3115 case QUERY_DESC_IDN_RFU_1:
3116 *desc_len = 0;
3117 break;
3118 default:
3119 *desc_len = 0;
3120 return -EINVAL;
3122 return 0;
3124 EXPORT_SYMBOL(ufshcd_map_desc_id_to_length);
3127 * ufshcd_read_desc_param - read the specified descriptor parameter
3128 * @hba: Pointer to adapter instance
3129 * @desc_id: descriptor idn value
3130 * @desc_index: descriptor index
3131 * @param_offset: offset of the parameter to read
3132 * @param_read_buf: pointer to buffer where parameter would be read
3133 * @param_size: sizeof(param_read_buf)
3135 * Return 0 in case of success, non-zero otherwise
3137 int ufshcd_read_desc_param(struct ufs_hba *hba,
3138 enum desc_idn desc_id,
3139 int desc_index,
3140 u8 param_offset,
3141 u8 *param_read_buf,
3142 u8 param_size)
3144 int ret;
3145 u8 *desc_buf;
3146 int buff_len;
3147 bool is_kmalloc = true;
3149 /* Safety check */
3150 if (desc_id >= QUERY_DESC_IDN_MAX || !param_size)
3151 return -EINVAL;
3153 /* Get the max length of descriptor from structure filled up at probe
3154 * time.
3156 ret = ufshcd_map_desc_id_to_length(hba, desc_id, &buff_len);
3158 /* Sanity checks */
3159 if (ret || !buff_len) {
3160 dev_err(hba->dev, "%s: Failed to get full descriptor length",
3161 __func__);
3162 return ret;
3165 /* Check whether we need temp memory */
3166 if (param_offset != 0 || param_size < buff_len) {
3167 desc_buf = kmalloc(buff_len, GFP_KERNEL);
3168 if (!desc_buf)
3169 return -ENOMEM;
3170 } else {
3171 desc_buf = param_read_buf;
3172 is_kmalloc = false;
3175 /* Request for full descriptor */
3176 ret = ufshcd_query_descriptor_retry(hba, UPIU_QUERY_OPCODE_READ_DESC,
3177 desc_id, desc_index, 0,
3178 desc_buf, &buff_len);
3180 if (ret) {
3181 dev_err(hba->dev, "%s: Failed reading descriptor. desc_id %d, desc_index %d, param_offset %d, ret %d",
3182 __func__, desc_id, desc_index, param_offset, ret);
3183 goto out;
3186 /* Sanity check */
3187 if (desc_buf[QUERY_DESC_DESC_TYPE_OFFSET] != desc_id) {
3188 dev_err(hba->dev, "%s: invalid desc_id %d in descriptor header",
3189 __func__, desc_buf[QUERY_DESC_DESC_TYPE_OFFSET]);
3190 ret = -EINVAL;
3191 goto out;
3194 /* Check wherher we will not copy more data, than available */
3195 if (is_kmalloc && param_size > buff_len)
3196 param_size = buff_len;
3198 if (is_kmalloc)
3199 memcpy(param_read_buf, &desc_buf[param_offset], param_size);
3200 out:
3201 if (is_kmalloc)
3202 kfree(desc_buf);
3203 return ret;
3206 static inline int ufshcd_read_desc(struct ufs_hba *hba,
3207 enum desc_idn desc_id,
3208 int desc_index,
3209 void *buf,
3210 u32 size)
3212 return ufshcd_read_desc_param(hba, desc_id, desc_index, 0, buf, size);
3217 * struct uc_string_id - unicode string
3219 * @len: size of this descriptor inclusive
3220 * @type: descriptor type
3221 * @uc: unicode string character
3223 struct uc_string_id {
3224 u8 len;
3225 u8 type;
3226 wchar_t uc[0];
3227 } __packed;
3229 /* replace non-printable or non-ASCII characters with spaces */
3230 static inline char ufshcd_remove_non_printable(u8 ch)
3232 return (ch >= 0x20 && ch <= 0x7e) ? ch : ' ';
3236 * ufshcd_read_string_desc - read string descriptor
3237 * @hba: pointer to adapter instance
3238 * @desc_index: descriptor index
3239 * @buf: pointer to buffer where descriptor would be read,
3240 * the caller should free the memory.
3241 * @ascii: if true convert from unicode to ascii characters
3242 * null terminated string.
3244 * Return:
3245 * * string size on success.
3246 * * -ENOMEM: on allocation failure
3247 * * -EINVAL: on a wrong parameter
3249 int ufshcd_read_string_desc(struct ufs_hba *hba, u8 desc_index,
3250 u8 **buf, bool ascii)
3252 struct uc_string_id *uc_str;
3253 u8 *str;
3254 int ret;
3256 if (!buf)
3257 return -EINVAL;
3259 uc_str = kzalloc(QUERY_DESC_MAX_SIZE, GFP_KERNEL);
3260 if (!uc_str)
3261 return -ENOMEM;
3263 ret = ufshcd_read_desc(hba, QUERY_DESC_IDN_STRING,
3264 desc_index, uc_str,
3265 QUERY_DESC_MAX_SIZE);
3266 if (ret < 0) {
3267 dev_err(hba->dev, "Reading String Desc failed after %d retries. err = %d\n",
3268 QUERY_REQ_RETRIES, ret);
3269 str = NULL;
3270 goto out;
3273 if (uc_str->len <= QUERY_DESC_HDR_SIZE) {
3274 dev_dbg(hba->dev, "String Desc is of zero length\n");
3275 str = NULL;
3276 ret = 0;
3277 goto out;
3280 if (ascii) {
3281 ssize_t ascii_len;
3282 int i;
3283 /* remove header and divide by 2 to move from UTF16 to UTF8 */
3284 ascii_len = (uc_str->len - QUERY_DESC_HDR_SIZE) / 2 + 1;
3285 str = kzalloc(ascii_len, GFP_KERNEL);
3286 if (!str) {
3287 ret = -ENOMEM;
3288 goto out;
3292 * the descriptor contains string in UTF16 format
3293 * we need to convert to utf-8 so it can be displayed
3295 ret = utf16s_to_utf8s(uc_str->uc,
3296 uc_str->len - QUERY_DESC_HDR_SIZE,
3297 UTF16_BIG_ENDIAN, str, ascii_len);
3299 /* replace non-printable or non-ASCII characters with spaces */
3300 for (i = 0; i < ret; i++)
3301 str[i] = ufshcd_remove_non_printable(str[i]);
3303 str[ret++] = '\0';
3305 } else {
3306 str = kmemdup(uc_str, uc_str->len, GFP_KERNEL);
3307 if (!str) {
3308 ret = -ENOMEM;
3309 goto out;
3311 ret = uc_str->len;
3313 out:
3314 *buf = str;
3315 kfree(uc_str);
3316 return ret;
3320 * ufshcd_read_unit_desc_param - read the specified unit descriptor parameter
3321 * @hba: Pointer to adapter instance
3322 * @lun: lun id
3323 * @param_offset: offset of the parameter to read
3324 * @param_read_buf: pointer to buffer where parameter would be read
3325 * @param_size: sizeof(param_read_buf)
3327 * Return 0 in case of success, non-zero otherwise
3329 static inline int ufshcd_read_unit_desc_param(struct ufs_hba *hba,
3330 int lun,
3331 enum unit_desc_param param_offset,
3332 u8 *param_read_buf,
3333 u32 param_size)
3336 * Unit descriptors are only available for general purpose LUs (LUN id
3337 * from 0 to 7) and RPMB Well known LU.
3339 if (!ufs_is_valid_unit_desc_lun(&hba->dev_info, lun))
3340 return -EOPNOTSUPP;
3342 return ufshcd_read_desc_param(hba, QUERY_DESC_IDN_UNIT, lun,
3343 param_offset, param_read_buf, param_size);
3346 static int ufshcd_get_ref_clk_gating_wait(struct ufs_hba *hba)
3348 int err = 0;
3349 u32 gating_wait = UFSHCD_REF_CLK_GATING_WAIT_US;
3351 if (hba->dev_info.wspecversion >= 0x300) {
3352 err = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
3353 QUERY_ATTR_IDN_REF_CLK_GATING_WAIT_TIME, 0, 0,
3354 &gating_wait);
3355 if (err)
3356 dev_err(hba->dev, "Failed reading bRefClkGatingWait. err = %d, use default %uus\n",
3357 err, gating_wait);
3359 if (gating_wait == 0) {
3360 gating_wait = UFSHCD_REF_CLK_GATING_WAIT_US;
3361 dev_err(hba->dev, "Undefined ref clk gating wait time, use default %uus\n",
3362 gating_wait);
3365 hba->dev_info.clk_gating_wait_us = gating_wait;
3368 return err;
3372 * ufshcd_memory_alloc - allocate memory for host memory space data structures
3373 * @hba: per adapter instance
3375 * 1. Allocate DMA memory for Command Descriptor array
3376 * Each command descriptor consist of Command UPIU, Response UPIU and PRDT
3377 * 2. Allocate DMA memory for UTP Transfer Request Descriptor List (UTRDL).
3378 * 3. Allocate DMA memory for UTP Task Management Request Descriptor List
3379 * (UTMRDL)
3380 * 4. Allocate memory for local reference block(lrb).
3382 * Returns 0 for success, non-zero in case of failure
3384 static int ufshcd_memory_alloc(struct ufs_hba *hba)
3386 size_t utmrdl_size, utrdl_size, ucdl_size;
3388 /* Allocate memory for UTP command descriptors */
3389 ucdl_size = (sizeof(struct utp_transfer_cmd_desc) * hba->nutrs);
3390 hba->ucdl_base_addr = dmam_alloc_coherent(hba->dev,
3391 ucdl_size,
3392 &hba->ucdl_dma_addr,
3393 GFP_KERNEL);
3396 * UFSHCI requires UTP command descriptor to be 128 byte aligned.
3397 * make sure hba->ucdl_dma_addr is aligned to PAGE_SIZE
3398 * if hba->ucdl_dma_addr is aligned to PAGE_SIZE, then it will
3399 * be aligned to 128 bytes as well
3401 if (!hba->ucdl_base_addr ||
3402 WARN_ON(hba->ucdl_dma_addr & (PAGE_SIZE - 1))) {
3403 dev_err(hba->dev,
3404 "Command Descriptor Memory allocation failed\n");
3405 goto out;
3409 * Allocate memory for UTP Transfer descriptors
3410 * UFSHCI requires 1024 byte alignment of UTRD
3412 utrdl_size = (sizeof(struct utp_transfer_req_desc) * hba->nutrs);
3413 hba->utrdl_base_addr = dmam_alloc_coherent(hba->dev,
3414 utrdl_size,
3415 &hba->utrdl_dma_addr,
3416 GFP_KERNEL);
3417 if (!hba->utrdl_base_addr ||
3418 WARN_ON(hba->utrdl_dma_addr & (PAGE_SIZE - 1))) {
3419 dev_err(hba->dev,
3420 "Transfer Descriptor Memory allocation failed\n");
3421 goto out;
3425 * Allocate memory for UTP Task Management descriptors
3426 * UFSHCI requires 1024 byte alignment of UTMRD
3428 utmrdl_size = sizeof(struct utp_task_req_desc) * hba->nutmrs;
3429 hba->utmrdl_base_addr = dmam_alloc_coherent(hba->dev,
3430 utmrdl_size,
3431 &hba->utmrdl_dma_addr,
3432 GFP_KERNEL);
3433 if (!hba->utmrdl_base_addr ||
3434 WARN_ON(hba->utmrdl_dma_addr & (PAGE_SIZE - 1))) {
3435 dev_err(hba->dev,
3436 "Task Management Descriptor Memory allocation failed\n");
3437 goto out;
3440 /* Allocate memory for local reference block */
3441 hba->lrb = devm_kcalloc(hba->dev,
3442 hba->nutrs, sizeof(struct ufshcd_lrb),
3443 GFP_KERNEL);
3444 if (!hba->lrb) {
3445 dev_err(hba->dev, "LRB Memory allocation failed\n");
3446 goto out;
3448 return 0;
3449 out:
3450 return -ENOMEM;
3454 * ufshcd_host_memory_configure - configure local reference block with
3455 * memory offsets
3456 * @hba: per adapter instance
3458 * Configure Host memory space
3459 * 1. Update Corresponding UTRD.UCDBA and UTRD.UCDBAU with UCD DMA
3460 * address.
3461 * 2. Update each UTRD with Response UPIU offset, Response UPIU length
3462 * and PRDT offset.
3463 * 3. Save the corresponding addresses of UTRD, UCD.CMD, UCD.RSP and UCD.PRDT
3464 * into local reference block.
3466 static void ufshcd_host_memory_configure(struct ufs_hba *hba)
3468 struct utp_transfer_req_desc *utrdlp;
3469 dma_addr_t cmd_desc_dma_addr;
3470 dma_addr_t cmd_desc_element_addr;
3471 u16 response_offset;
3472 u16 prdt_offset;
3473 int cmd_desc_size;
3474 int i;
3476 utrdlp = hba->utrdl_base_addr;
3478 response_offset =
3479 offsetof(struct utp_transfer_cmd_desc, response_upiu);
3480 prdt_offset =
3481 offsetof(struct utp_transfer_cmd_desc, prd_table);
3483 cmd_desc_size = sizeof(struct utp_transfer_cmd_desc);
3484 cmd_desc_dma_addr = hba->ucdl_dma_addr;
3486 for (i = 0; i < hba->nutrs; i++) {
3487 /* Configure UTRD with command descriptor base address */
3488 cmd_desc_element_addr =
3489 (cmd_desc_dma_addr + (cmd_desc_size * i));
3490 utrdlp[i].command_desc_base_addr_lo =
3491 cpu_to_le32(lower_32_bits(cmd_desc_element_addr));
3492 utrdlp[i].command_desc_base_addr_hi =
3493 cpu_to_le32(upper_32_bits(cmd_desc_element_addr));
3495 /* Response upiu and prdt offset should be in double words */
3496 utrdlp[i].response_upiu_offset =
3497 cpu_to_le16(response_offset >> 2);
3498 utrdlp[i].prd_table_offset = cpu_to_le16(prdt_offset >> 2);
3499 utrdlp[i].response_upiu_length =
3500 cpu_to_le16(ALIGNED_UPIU_SIZE >> 2);
3502 ufshcd_init_lrb(hba, &hba->lrb[i], i);
3507 * ufshcd_dme_link_startup - Notify Unipro to perform link startup
3508 * @hba: per adapter instance
3510 * UIC_CMD_DME_LINK_STARTUP command must be issued to Unipro layer,
3511 * in order to initialize the Unipro link startup procedure.
3512 * Once the Unipro links are up, the device connected to the controller
3513 * is detected.
3515 * Returns 0 on success, non-zero value on failure
3517 static int ufshcd_dme_link_startup(struct ufs_hba *hba)
3519 struct uic_command uic_cmd = {0};
3520 int ret;
3522 uic_cmd.command = UIC_CMD_DME_LINK_STARTUP;
3524 ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
3525 if (ret)
3526 dev_dbg(hba->dev,
3527 "dme-link-startup: error code %d\n", ret);
3528 return ret;
3531 static inline void ufshcd_add_delay_before_dme_cmd(struct ufs_hba *hba)
3533 #define MIN_DELAY_BEFORE_DME_CMDS_US 1000
3534 unsigned long min_sleep_time_us;
3536 if (!(hba->quirks & UFSHCD_QUIRK_DELAY_BEFORE_DME_CMDS))
3537 return;
3540 * last_dme_cmd_tstamp will be 0 only for 1st call to
3541 * this function
3543 if (unlikely(!ktime_to_us(hba->last_dme_cmd_tstamp))) {
3544 min_sleep_time_us = MIN_DELAY_BEFORE_DME_CMDS_US;
3545 } else {
3546 unsigned long delta =
3547 (unsigned long) ktime_to_us(
3548 ktime_sub(ktime_get(),
3549 hba->last_dme_cmd_tstamp));
3551 if (delta < MIN_DELAY_BEFORE_DME_CMDS_US)
3552 min_sleep_time_us =
3553 MIN_DELAY_BEFORE_DME_CMDS_US - delta;
3554 else
3555 return; /* no more delay required */
3558 /* allow sleep for extra 50us if needed */
3559 usleep_range(min_sleep_time_us, min_sleep_time_us + 50);
3563 * ufshcd_dme_set_attr - UIC command for DME_SET, DME_PEER_SET
3564 * @hba: per adapter instance
3565 * @attr_sel: uic command argument1
3566 * @attr_set: attribute set type as uic command argument2
3567 * @mib_val: setting value as uic command argument3
3568 * @peer: indicate whether peer or local
3570 * Returns 0 on success, non-zero value on failure
3572 int ufshcd_dme_set_attr(struct ufs_hba *hba, u32 attr_sel,
3573 u8 attr_set, u32 mib_val, u8 peer)
3575 struct uic_command uic_cmd = {0};
3576 static const char *const action[] = {
3577 "dme-set",
3578 "dme-peer-set"
3580 const char *set = action[!!peer];
3581 int ret;
3582 int retries = UFS_UIC_COMMAND_RETRIES;
3584 uic_cmd.command = peer ?
3585 UIC_CMD_DME_PEER_SET : UIC_CMD_DME_SET;
3586 uic_cmd.argument1 = attr_sel;
3587 uic_cmd.argument2 = UIC_ARG_ATTR_TYPE(attr_set);
3588 uic_cmd.argument3 = mib_val;
3590 do {
3591 /* for peer attributes we retry upon failure */
3592 ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
3593 if (ret)
3594 dev_dbg(hba->dev, "%s: attr-id 0x%x val 0x%x error code %d\n",
3595 set, UIC_GET_ATTR_ID(attr_sel), mib_val, ret);
3596 } while (ret && peer && --retries);
3598 if (ret)
3599 dev_err(hba->dev, "%s: attr-id 0x%x val 0x%x failed %d retries\n",
3600 set, UIC_GET_ATTR_ID(attr_sel), mib_val,
3601 UFS_UIC_COMMAND_RETRIES - retries);
3603 return ret;
3605 EXPORT_SYMBOL_GPL(ufshcd_dme_set_attr);
3608 * ufshcd_dme_get_attr - UIC command for DME_GET, DME_PEER_GET
3609 * @hba: per adapter instance
3610 * @attr_sel: uic command argument1
3611 * @mib_val: the value of the attribute as returned by the UIC command
3612 * @peer: indicate whether peer or local
3614 * Returns 0 on success, non-zero value on failure
3616 int ufshcd_dme_get_attr(struct ufs_hba *hba, u32 attr_sel,
3617 u32 *mib_val, u8 peer)
3619 struct uic_command uic_cmd = {0};
3620 static const char *const action[] = {
3621 "dme-get",
3622 "dme-peer-get"
3624 const char *get = action[!!peer];
3625 int ret;
3626 int retries = UFS_UIC_COMMAND_RETRIES;
3627 struct ufs_pa_layer_attr orig_pwr_info;
3628 struct ufs_pa_layer_attr temp_pwr_info;
3629 bool pwr_mode_change = false;
3631 if (peer && (hba->quirks & UFSHCD_QUIRK_DME_PEER_ACCESS_AUTO_MODE)) {
3632 orig_pwr_info = hba->pwr_info;
3633 temp_pwr_info = orig_pwr_info;
3635 if (orig_pwr_info.pwr_tx == FAST_MODE ||
3636 orig_pwr_info.pwr_rx == FAST_MODE) {
3637 temp_pwr_info.pwr_tx = FASTAUTO_MODE;
3638 temp_pwr_info.pwr_rx = FASTAUTO_MODE;
3639 pwr_mode_change = true;
3640 } else if (orig_pwr_info.pwr_tx == SLOW_MODE ||
3641 orig_pwr_info.pwr_rx == SLOW_MODE) {
3642 temp_pwr_info.pwr_tx = SLOWAUTO_MODE;
3643 temp_pwr_info.pwr_rx = SLOWAUTO_MODE;
3644 pwr_mode_change = true;
3646 if (pwr_mode_change) {
3647 ret = ufshcd_change_power_mode(hba, &temp_pwr_info);
3648 if (ret)
3649 goto out;
3653 uic_cmd.command = peer ?
3654 UIC_CMD_DME_PEER_GET : UIC_CMD_DME_GET;
3655 uic_cmd.argument1 = attr_sel;
3657 do {
3658 /* for peer attributes we retry upon failure */
3659 ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
3660 if (ret)
3661 dev_dbg(hba->dev, "%s: attr-id 0x%x error code %d\n",
3662 get, UIC_GET_ATTR_ID(attr_sel), ret);
3663 } while (ret && peer && --retries);
3665 if (ret)
3666 dev_err(hba->dev, "%s: attr-id 0x%x failed %d retries\n",
3667 get, UIC_GET_ATTR_ID(attr_sel),
3668 UFS_UIC_COMMAND_RETRIES - retries);
3670 if (mib_val && !ret)
3671 *mib_val = uic_cmd.argument3;
3673 if (peer && (hba->quirks & UFSHCD_QUIRK_DME_PEER_ACCESS_AUTO_MODE)
3674 && pwr_mode_change)
3675 ufshcd_change_power_mode(hba, &orig_pwr_info);
3676 out:
3677 return ret;
3679 EXPORT_SYMBOL_GPL(ufshcd_dme_get_attr);
3682 * ufshcd_uic_pwr_ctrl - executes UIC commands (which affects the link power
3683 * state) and waits for it to take effect.
3685 * @hba: per adapter instance
3686 * @cmd: UIC command to execute
3688 * DME operations like DME_SET(PA_PWRMODE), DME_HIBERNATE_ENTER &
3689 * DME_HIBERNATE_EXIT commands take some time to take its effect on both host
3690 * and device UniPro link and hence it's final completion would be indicated by
3691 * dedicated status bits in Interrupt Status register (UPMS, UHES, UHXS) in
3692 * addition to normal UIC command completion Status (UCCS). This function only
3693 * returns after the relevant status bits indicate the completion.
3695 * Returns 0 on success, non-zero value on failure
3697 static int ufshcd_uic_pwr_ctrl(struct ufs_hba *hba, struct uic_command *cmd)
3699 struct completion uic_async_done;
3700 unsigned long flags;
3701 u8 status;
3702 int ret;
3703 bool reenable_intr = false;
3705 mutex_lock(&hba->uic_cmd_mutex);
3706 init_completion(&uic_async_done);
3707 ufshcd_add_delay_before_dme_cmd(hba);
3709 spin_lock_irqsave(hba->host->host_lock, flags);
3710 hba->uic_async_done = &uic_async_done;
3711 if (ufshcd_readl(hba, REG_INTERRUPT_ENABLE) & UIC_COMMAND_COMPL) {
3712 ufshcd_disable_intr(hba, UIC_COMMAND_COMPL);
3714 * Make sure UIC command completion interrupt is disabled before
3715 * issuing UIC command.
3717 wmb();
3718 reenable_intr = true;
3720 ret = __ufshcd_send_uic_cmd(hba, cmd, false);
3721 spin_unlock_irqrestore(hba->host->host_lock, flags);
3722 if (ret) {
3723 dev_err(hba->dev,
3724 "pwr ctrl cmd 0x%x with mode 0x%x uic error %d\n",
3725 cmd->command, cmd->argument3, ret);
3726 goto out;
3729 if (!wait_for_completion_timeout(hba->uic_async_done,
3730 msecs_to_jiffies(UIC_CMD_TIMEOUT))) {
3731 dev_err(hba->dev,
3732 "pwr ctrl cmd 0x%x with mode 0x%x completion timeout\n",
3733 cmd->command, cmd->argument3);
3734 ret = -ETIMEDOUT;
3735 goto out;
3738 status = ufshcd_get_upmcrs(hba);
3739 if (status != PWR_LOCAL) {
3740 dev_err(hba->dev,
3741 "pwr ctrl cmd 0x%x failed, host upmcrs:0x%x\n",
3742 cmd->command, status);
3743 ret = (status != PWR_OK) ? status : -1;
3745 out:
3746 if (ret) {
3747 ufshcd_print_host_state(hba);
3748 ufshcd_print_pwr_info(hba);
3749 ufshcd_print_host_regs(hba);
3752 spin_lock_irqsave(hba->host->host_lock, flags);
3753 hba->active_uic_cmd = NULL;
3754 hba->uic_async_done = NULL;
3755 if (reenable_intr)
3756 ufshcd_enable_intr(hba, UIC_COMMAND_COMPL);
3757 spin_unlock_irqrestore(hba->host->host_lock, flags);
3758 mutex_unlock(&hba->uic_cmd_mutex);
3760 return ret;
3764 * ufshcd_uic_change_pwr_mode - Perform the UIC power mode chage
3765 * using DME_SET primitives.
3766 * @hba: per adapter instance
3767 * @mode: powr mode value
3769 * Returns 0 on success, non-zero value on failure
3771 static int ufshcd_uic_change_pwr_mode(struct ufs_hba *hba, u8 mode)
3773 struct uic_command uic_cmd = {0};
3774 int ret;
3776 if (hba->quirks & UFSHCD_QUIRK_BROKEN_PA_RXHSUNTERMCAP) {
3777 ret = ufshcd_dme_set(hba,
3778 UIC_ARG_MIB_SEL(PA_RXHSUNTERMCAP, 0), 1);
3779 if (ret) {
3780 dev_err(hba->dev, "%s: failed to enable PA_RXHSUNTERMCAP ret %d\n",
3781 __func__, ret);
3782 goto out;
3786 uic_cmd.command = UIC_CMD_DME_SET;
3787 uic_cmd.argument1 = UIC_ARG_MIB(PA_PWRMODE);
3788 uic_cmd.argument3 = mode;
3789 ufshcd_hold(hba, false);
3790 ret = ufshcd_uic_pwr_ctrl(hba, &uic_cmd);
3791 ufshcd_release(hba);
3793 out:
3794 return ret;
3797 int ufshcd_link_recovery(struct ufs_hba *hba)
3799 int ret;
3800 unsigned long flags;
3802 spin_lock_irqsave(hba->host->host_lock, flags);
3803 hba->ufshcd_state = UFSHCD_STATE_RESET;
3804 ufshcd_set_eh_in_progress(hba);
3805 spin_unlock_irqrestore(hba->host->host_lock, flags);
3807 /* Reset the attached device */
3808 ufshcd_vops_device_reset(hba);
3810 ret = ufshcd_host_reset_and_restore(hba);
3812 spin_lock_irqsave(hba->host->host_lock, flags);
3813 if (ret)
3814 hba->ufshcd_state = UFSHCD_STATE_ERROR;
3815 ufshcd_clear_eh_in_progress(hba);
3816 spin_unlock_irqrestore(hba->host->host_lock, flags);
3818 if (ret)
3819 dev_err(hba->dev, "%s: link recovery failed, err %d",
3820 __func__, ret);
3822 return ret;
3824 EXPORT_SYMBOL_GPL(ufshcd_link_recovery);
3826 static int __ufshcd_uic_hibern8_enter(struct ufs_hba *hba)
3828 int ret;
3829 struct uic_command uic_cmd = {0};
3830 ktime_t start = ktime_get();
3832 ufshcd_vops_hibern8_notify(hba, UIC_CMD_DME_HIBER_ENTER, PRE_CHANGE);
3834 uic_cmd.command = UIC_CMD_DME_HIBER_ENTER;
3835 ret = ufshcd_uic_pwr_ctrl(hba, &uic_cmd);
3836 trace_ufshcd_profile_hibern8(dev_name(hba->dev), "enter",
3837 ktime_to_us(ktime_sub(ktime_get(), start)), ret);
3839 if (ret) {
3840 int err;
3842 dev_err(hba->dev, "%s: hibern8 enter failed. ret = %d\n",
3843 __func__, ret);
3846 * If link recovery fails then return error code returned from
3847 * ufshcd_link_recovery().
3848 * If link recovery succeeds then return -EAGAIN to attempt
3849 * hibern8 enter retry again.
3851 err = ufshcd_link_recovery(hba);
3852 if (err) {
3853 dev_err(hba->dev, "%s: link recovery failed", __func__);
3854 ret = err;
3855 } else {
3856 ret = -EAGAIN;
3858 } else
3859 ufshcd_vops_hibern8_notify(hba, UIC_CMD_DME_HIBER_ENTER,
3860 POST_CHANGE);
3862 return ret;
3865 static int ufshcd_uic_hibern8_enter(struct ufs_hba *hba)
3867 int ret = 0, retries;
3869 for (retries = UIC_HIBERN8_ENTER_RETRIES; retries > 0; retries--) {
3870 ret = __ufshcd_uic_hibern8_enter(hba);
3871 if (!ret)
3872 goto out;
3874 out:
3875 return ret;
3878 int ufshcd_uic_hibern8_exit(struct ufs_hba *hba)
3880 struct uic_command uic_cmd = {0};
3881 int ret;
3882 ktime_t start = ktime_get();
3884 ufshcd_vops_hibern8_notify(hba, UIC_CMD_DME_HIBER_EXIT, PRE_CHANGE);
3886 uic_cmd.command = UIC_CMD_DME_HIBER_EXIT;
3887 ret = ufshcd_uic_pwr_ctrl(hba, &uic_cmd);
3888 trace_ufshcd_profile_hibern8(dev_name(hba->dev), "exit",
3889 ktime_to_us(ktime_sub(ktime_get(), start)), ret);
3891 if (ret) {
3892 dev_err(hba->dev, "%s: hibern8 exit failed. ret = %d\n",
3893 __func__, ret);
3894 ret = ufshcd_link_recovery(hba);
3895 } else {
3896 ufshcd_vops_hibern8_notify(hba, UIC_CMD_DME_HIBER_EXIT,
3897 POST_CHANGE);
3898 hba->ufs_stats.last_hibern8_exit_tstamp = ktime_get();
3899 hba->ufs_stats.hibern8_exit_cnt++;
3902 return ret;
3904 EXPORT_SYMBOL_GPL(ufshcd_uic_hibern8_exit);
3906 void ufshcd_auto_hibern8_update(struct ufs_hba *hba, u32 ahit)
3908 unsigned long flags;
3909 bool update = false;
3911 if (!ufshcd_is_auto_hibern8_supported(hba))
3912 return;
3914 spin_lock_irqsave(hba->host->host_lock, flags);
3915 if (hba->ahit != ahit) {
3916 hba->ahit = ahit;
3917 update = true;
3919 spin_unlock_irqrestore(hba->host->host_lock, flags);
3921 if (update && !pm_runtime_suspended(hba->dev)) {
3922 pm_runtime_get_sync(hba->dev);
3923 ufshcd_hold(hba, false);
3924 ufshcd_auto_hibern8_enable(hba);
3925 ufshcd_release(hba);
3926 pm_runtime_put(hba->dev);
3929 EXPORT_SYMBOL_GPL(ufshcd_auto_hibern8_update);
3931 void ufshcd_auto_hibern8_enable(struct ufs_hba *hba)
3933 unsigned long flags;
3935 if (!ufshcd_is_auto_hibern8_supported(hba) || !hba->ahit)
3936 return;
3938 spin_lock_irqsave(hba->host->host_lock, flags);
3939 ufshcd_writel(hba, hba->ahit, REG_AUTO_HIBERNATE_IDLE_TIMER);
3940 spin_unlock_irqrestore(hba->host->host_lock, flags);
3944 * ufshcd_init_pwr_info - setting the POR (power on reset)
3945 * values in hba power info
3946 * @hba: per-adapter instance
3948 static void ufshcd_init_pwr_info(struct ufs_hba *hba)
3950 hba->pwr_info.gear_rx = UFS_PWM_G1;
3951 hba->pwr_info.gear_tx = UFS_PWM_G1;
3952 hba->pwr_info.lane_rx = 1;
3953 hba->pwr_info.lane_tx = 1;
3954 hba->pwr_info.pwr_rx = SLOWAUTO_MODE;
3955 hba->pwr_info.pwr_tx = SLOWAUTO_MODE;
3956 hba->pwr_info.hs_rate = 0;
3960 * ufshcd_get_max_pwr_mode - reads the max power mode negotiated with device
3961 * @hba: per-adapter instance
3963 static int ufshcd_get_max_pwr_mode(struct ufs_hba *hba)
3965 struct ufs_pa_layer_attr *pwr_info = &hba->max_pwr_info.info;
3967 if (hba->max_pwr_info.is_valid)
3968 return 0;
3970 pwr_info->pwr_tx = FAST_MODE;
3971 pwr_info->pwr_rx = FAST_MODE;
3972 pwr_info->hs_rate = PA_HS_MODE_B;
3974 /* Get the connected lane count */
3975 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_CONNECTEDRXDATALANES),
3976 &pwr_info->lane_rx);
3977 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_CONNECTEDTXDATALANES),
3978 &pwr_info->lane_tx);
3980 if (!pwr_info->lane_rx || !pwr_info->lane_tx) {
3981 dev_err(hba->dev, "%s: invalid connected lanes value. rx=%d, tx=%d\n",
3982 __func__,
3983 pwr_info->lane_rx,
3984 pwr_info->lane_tx);
3985 return -EINVAL;
3989 * First, get the maximum gears of HS speed.
3990 * If a zero value, it means there is no HSGEAR capability.
3991 * Then, get the maximum gears of PWM speed.
3993 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_MAXRXHSGEAR), &pwr_info->gear_rx);
3994 if (!pwr_info->gear_rx) {
3995 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_MAXRXPWMGEAR),
3996 &pwr_info->gear_rx);
3997 if (!pwr_info->gear_rx) {
3998 dev_err(hba->dev, "%s: invalid max pwm rx gear read = %d\n",
3999 __func__, pwr_info->gear_rx);
4000 return -EINVAL;
4002 pwr_info->pwr_rx = SLOW_MODE;
4005 ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_MAXRXHSGEAR),
4006 &pwr_info->gear_tx);
4007 if (!pwr_info->gear_tx) {
4008 ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_MAXRXPWMGEAR),
4009 &pwr_info->gear_tx);
4010 if (!pwr_info->gear_tx) {
4011 dev_err(hba->dev, "%s: invalid max pwm tx gear read = %d\n",
4012 __func__, pwr_info->gear_tx);
4013 return -EINVAL;
4015 pwr_info->pwr_tx = SLOW_MODE;
4018 hba->max_pwr_info.is_valid = true;
4019 return 0;
4022 static int ufshcd_change_power_mode(struct ufs_hba *hba,
4023 struct ufs_pa_layer_attr *pwr_mode)
4025 int ret;
4027 /* if already configured to the requested pwr_mode */
4028 if (pwr_mode->gear_rx == hba->pwr_info.gear_rx &&
4029 pwr_mode->gear_tx == hba->pwr_info.gear_tx &&
4030 pwr_mode->lane_rx == hba->pwr_info.lane_rx &&
4031 pwr_mode->lane_tx == hba->pwr_info.lane_tx &&
4032 pwr_mode->pwr_rx == hba->pwr_info.pwr_rx &&
4033 pwr_mode->pwr_tx == hba->pwr_info.pwr_tx &&
4034 pwr_mode->hs_rate == hba->pwr_info.hs_rate) {
4035 dev_dbg(hba->dev, "%s: power already configured\n", __func__);
4036 return 0;
4040 * Configure attributes for power mode change with below.
4041 * - PA_RXGEAR, PA_ACTIVERXDATALANES, PA_RXTERMINATION,
4042 * - PA_TXGEAR, PA_ACTIVETXDATALANES, PA_TXTERMINATION,
4043 * - PA_HSSERIES
4045 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_RXGEAR), pwr_mode->gear_rx);
4046 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_ACTIVERXDATALANES),
4047 pwr_mode->lane_rx);
4048 if (pwr_mode->pwr_rx == FASTAUTO_MODE ||
4049 pwr_mode->pwr_rx == FAST_MODE)
4050 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_RXTERMINATION), TRUE);
4051 else
4052 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_RXTERMINATION), FALSE);
4054 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TXGEAR), pwr_mode->gear_tx);
4055 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_ACTIVETXDATALANES),
4056 pwr_mode->lane_tx);
4057 if (pwr_mode->pwr_tx == FASTAUTO_MODE ||
4058 pwr_mode->pwr_tx == FAST_MODE)
4059 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TXTERMINATION), TRUE);
4060 else
4061 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TXTERMINATION), FALSE);
4063 if (pwr_mode->pwr_rx == FASTAUTO_MODE ||
4064 pwr_mode->pwr_tx == FASTAUTO_MODE ||
4065 pwr_mode->pwr_rx == FAST_MODE ||
4066 pwr_mode->pwr_tx == FAST_MODE)
4067 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_HSSERIES),
4068 pwr_mode->hs_rate);
4070 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_PWRMODEUSERDATA0),
4071 DL_FC0ProtectionTimeOutVal_Default);
4072 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_PWRMODEUSERDATA1),
4073 DL_TC0ReplayTimeOutVal_Default);
4074 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_PWRMODEUSERDATA2),
4075 DL_AFC0ReqTimeOutVal_Default);
4076 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_PWRMODEUSERDATA3),
4077 DL_FC1ProtectionTimeOutVal_Default);
4078 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_PWRMODEUSERDATA4),
4079 DL_TC1ReplayTimeOutVal_Default);
4080 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_PWRMODEUSERDATA5),
4081 DL_AFC1ReqTimeOutVal_Default);
4083 ufshcd_dme_set(hba, UIC_ARG_MIB(DME_LocalFC0ProtectionTimeOutVal),
4084 DL_FC0ProtectionTimeOutVal_Default);
4085 ufshcd_dme_set(hba, UIC_ARG_MIB(DME_LocalTC0ReplayTimeOutVal),
4086 DL_TC0ReplayTimeOutVal_Default);
4087 ufshcd_dme_set(hba, UIC_ARG_MIB(DME_LocalAFC0ReqTimeOutVal),
4088 DL_AFC0ReqTimeOutVal_Default);
4090 ret = ufshcd_uic_change_pwr_mode(hba, pwr_mode->pwr_rx << 4
4091 | pwr_mode->pwr_tx);
4093 if (ret) {
4094 dev_err(hba->dev,
4095 "%s: power mode change failed %d\n", __func__, ret);
4096 } else {
4097 ufshcd_vops_pwr_change_notify(hba, POST_CHANGE, NULL,
4098 pwr_mode);
4100 memcpy(&hba->pwr_info, pwr_mode,
4101 sizeof(struct ufs_pa_layer_attr));
4104 return ret;
4108 * ufshcd_config_pwr_mode - configure a new power mode
4109 * @hba: per-adapter instance
4110 * @desired_pwr_mode: desired power configuration
4112 int ufshcd_config_pwr_mode(struct ufs_hba *hba,
4113 struct ufs_pa_layer_attr *desired_pwr_mode)
4115 struct ufs_pa_layer_attr final_params = { 0 };
4116 int ret;
4118 ret = ufshcd_vops_pwr_change_notify(hba, PRE_CHANGE,
4119 desired_pwr_mode, &final_params);
4121 if (ret)
4122 memcpy(&final_params, desired_pwr_mode, sizeof(final_params));
4124 ret = ufshcd_change_power_mode(hba, &final_params);
4126 return ret;
4128 EXPORT_SYMBOL_GPL(ufshcd_config_pwr_mode);
4131 * ufshcd_complete_dev_init() - checks device readiness
4132 * @hba: per-adapter instance
4134 * Set fDeviceInit flag and poll until device toggles it.
4136 static int ufshcd_complete_dev_init(struct ufs_hba *hba)
4138 int i;
4139 int err;
4140 bool flag_res = 1;
4142 err = ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_SET_FLAG,
4143 QUERY_FLAG_IDN_FDEVICEINIT, NULL);
4144 if (err) {
4145 dev_err(hba->dev,
4146 "%s setting fDeviceInit flag failed with error %d\n",
4147 __func__, err);
4148 goto out;
4151 /* poll for max. 1000 iterations for fDeviceInit flag to clear */
4152 for (i = 0; i < 1000 && !err && flag_res; i++)
4153 err = ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_READ_FLAG,
4154 QUERY_FLAG_IDN_FDEVICEINIT, &flag_res);
4156 if (err)
4157 dev_err(hba->dev,
4158 "%s reading fDeviceInit flag failed with error %d\n",
4159 __func__, err);
4160 else if (flag_res)
4161 dev_err(hba->dev,
4162 "%s fDeviceInit was not cleared by the device\n",
4163 __func__);
4165 out:
4166 return err;
4170 * ufshcd_make_hba_operational - Make UFS controller operational
4171 * @hba: per adapter instance
4173 * To bring UFS host controller to operational state,
4174 * 1. Enable required interrupts
4175 * 2. Configure interrupt aggregation
4176 * 3. Program UTRL and UTMRL base address
4177 * 4. Configure run-stop-registers
4179 * Returns 0 on success, non-zero value on failure
4181 int ufshcd_make_hba_operational(struct ufs_hba *hba)
4183 int err = 0;
4184 u32 reg;
4186 /* Enable required interrupts */
4187 ufshcd_enable_intr(hba, UFSHCD_ENABLE_INTRS);
4189 /* Configure interrupt aggregation */
4190 if (ufshcd_is_intr_aggr_allowed(hba))
4191 ufshcd_config_intr_aggr(hba, hba->nutrs - 1, INT_AGGR_DEF_TO);
4192 else
4193 ufshcd_disable_intr_aggr(hba);
4195 /* Configure UTRL and UTMRL base address registers */
4196 ufshcd_writel(hba, lower_32_bits(hba->utrdl_dma_addr),
4197 REG_UTP_TRANSFER_REQ_LIST_BASE_L);
4198 ufshcd_writel(hba, upper_32_bits(hba->utrdl_dma_addr),
4199 REG_UTP_TRANSFER_REQ_LIST_BASE_H);
4200 ufshcd_writel(hba, lower_32_bits(hba->utmrdl_dma_addr),
4201 REG_UTP_TASK_REQ_LIST_BASE_L);
4202 ufshcd_writel(hba, upper_32_bits(hba->utmrdl_dma_addr),
4203 REG_UTP_TASK_REQ_LIST_BASE_H);
4206 * Make sure base address and interrupt setup are updated before
4207 * enabling the run/stop registers below.
4209 wmb();
4212 * UCRDY, UTMRLDY and UTRLRDY bits must be 1
4214 reg = ufshcd_readl(hba, REG_CONTROLLER_STATUS);
4215 if (!(ufshcd_get_lists_status(reg))) {
4216 ufshcd_enable_run_stop_reg(hba);
4217 } else {
4218 dev_err(hba->dev,
4219 "Host controller not ready to process requests");
4220 err = -EIO;
4221 goto out;
4224 out:
4225 return err;
4227 EXPORT_SYMBOL_GPL(ufshcd_make_hba_operational);
4230 * ufshcd_hba_stop - Send controller to reset state
4231 * @hba: per adapter instance
4232 * @can_sleep: perform sleep or just spin
4234 static inline void ufshcd_hba_stop(struct ufs_hba *hba, bool can_sleep)
4236 int err;
4238 ufshcd_writel(hba, CONTROLLER_DISABLE, REG_CONTROLLER_ENABLE);
4239 err = ufshcd_wait_for_register(hba, REG_CONTROLLER_ENABLE,
4240 CONTROLLER_ENABLE, CONTROLLER_DISABLE,
4241 10, 1, can_sleep);
4242 if (err)
4243 dev_err(hba->dev, "%s: Controller disable failed\n", __func__);
4247 * ufshcd_hba_enable - initialize the controller
4248 * @hba: per adapter instance
4250 * The controller resets itself and controller firmware initialization
4251 * sequence kicks off. When controller is ready it will set
4252 * the Host Controller Enable bit to 1.
4254 * Returns 0 on success, non-zero value on failure
4256 int ufshcd_hba_enable(struct ufs_hba *hba)
4258 int retry;
4260 if (!ufshcd_is_hba_active(hba))
4261 /* change controller state to "reset state" */
4262 ufshcd_hba_stop(hba, true);
4264 /* UniPro link is disabled at this point */
4265 ufshcd_set_link_off(hba);
4267 ufshcd_vops_hce_enable_notify(hba, PRE_CHANGE);
4269 /* start controller initialization sequence */
4270 ufshcd_hba_start(hba);
4273 * To initialize a UFS host controller HCE bit must be set to 1.
4274 * During initialization the HCE bit value changes from 1->0->1.
4275 * When the host controller completes initialization sequence
4276 * it sets the value of HCE bit to 1. The same HCE bit is read back
4277 * to check if the controller has completed initialization sequence.
4278 * So without this delay the value HCE = 1, set in the previous
4279 * instruction might be read back.
4280 * This delay can be changed based on the controller.
4282 ufshcd_delay_us(hba->hba_enable_delay_us, 100);
4284 /* wait for the host controller to complete initialization */
4285 retry = 50;
4286 while (ufshcd_is_hba_active(hba)) {
4287 if (retry) {
4288 retry--;
4289 } else {
4290 dev_err(hba->dev,
4291 "Controller enable failed\n");
4292 return -EIO;
4294 usleep_range(1000, 1100);
4297 /* enable UIC related interrupts */
4298 ufshcd_enable_intr(hba, UFSHCD_UIC_MASK);
4300 ufshcd_vops_hce_enable_notify(hba, POST_CHANGE);
4302 return 0;
4304 EXPORT_SYMBOL_GPL(ufshcd_hba_enable);
4306 static int ufshcd_disable_tx_lcc(struct ufs_hba *hba, bool peer)
4308 int tx_lanes = 0, i, err = 0;
4310 if (!peer)
4311 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_CONNECTEDTXDATALANES),
4312 &tx_lanes);
4313 else
4314 ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_CONNECTEDTXDATALANES),
4315 &tx_lanes);
4316 for (i = 0; i < tx_lanes; i++) {
4317 if (!peer)
4318 err = ufshcd_dme_set(hba,
4319 UIC_ARG_MIB_SEL(TX_LCC_ENABLE,
4320 UIC_ARG_MPHY_TX_GEN_SEL_INDEX(i)),
4322 else
4323 err = ufshcd_dme_peer_set(hba,
4324 UIC_ARG_MIB_SEL(TX_LCC_ENABLE,
4325 UIC_ARG_MPHY_TX_GEN_SEL_INDEX(i)),
4327 if (err) {
4328 dev_err(hba->dev, "%s: TX LCC Disable failed, peer = %d, lane = %d, err = %d",
4329 __func__, peer, i, err);
4330 break;
4334 return err;
4337 static inline int ufshcd_disable_device_tx_lcc(struct ufs_hba *hba)
4339 return ufshcd_disable_tx_lcc(hba, true);
4342 void ufshcd_update_reg_hist(struct ufs_err_reg_hist *reg_hist,
4343 u32 reg)
4345 reg_hist->reg[reg_hist->pos] = reg;
4346 reg_hist->tstamp[reg_hist->pos] = ktime_get();
4347 reg_hist->pos = (reg_hist->pos + 1) % UFS_ERR_REG_HIST_LENGTH;
4349 EXPORT_SYMBOL_GPL(ufshcd_update_reg_hist);
4352 * ufshcd_link_startup - Initialize unipro link startup
4353 * @hba: per adapter instance
4355 * Returns 0 for success, non-zero in case of failure
4357 static int ufshcd_link_startup(struct ufs_hba *hba)
4359 int ret;
4360 int retries = DME_LINKSTARTUP_RETRIES;
4361 bool link_startup_again = false;
4364 * If UFS device isn't active then we will have to issue link startup
4365 * 2 times to make sure the device state move to active.
4367 if (!ufshcd_is_ufs_dev_active(hba))
4368 link_startup_again = true;
4370 link_startup:
4371 do {
4372 ufshcd_vops_link_startup_notify(hba, PRE_CHANGE);
4374 ret = ufshcd_dme_link_startup(hba);
4376 /* check if device is detected by inter-connect layer */
4377 if (!ret && !ufshcd_is_device_present(hba)) {
4378 ufshcd_update_reg_hist(&hba->ufs_stats.link_startup_err,
4380 dev_err(hba->dev, "%s: Device not present\n", __func__);
4381 ret = -ENXIO;
4382 goto out;
4386 * DME link lost indication is only received when link is up,
4387 * but we can't be sure if the link is up until link startup
4388 * succeeds. So reset the local Uni-Pro and try again.
4390 if (ret && ufshcd_hba_enable(hba)) {
4391 ufshcd_update_reg_hist(&hba->ufs_stats.link_startup_err,
4392 (u32)ret);
4393 goto out;
4395 } while (ret && retries--);
4397 if (ret) {
4398 /* failed to get the link up... retire */
4399 ufshcd_update_reg_hist(&hba->ufs_stats.link_startup_err,
4400 (u32)ret);
4401 goto out;
4404 if (link_startup_again) {
4405 link_startup_again = false;
4406 retries = DME_LINKSTARTUP_RETRIES;
4407 goto link_startup;
4410 /* Mark that link is up in PWM-G1, 1-lane, SLOW-AUTO mode */
4411 ufshcd_init_pwr_info(hba);
4412 ufshcd_print_pwr_info(hba);
4414 if (hba->quirks & UFSHCD_QUIRK_BROKEN_LCC) {
4415 ret = ufshcd_disable_device_tx_lcc(hba);
4416 if (ret)
4417 goto out;
4420 /* Include any host controller configuration via UIC commands */
4421 ret = ufshcd_vops_link_startup_notify(hba, POST_CHANGE);
4422 if (ret)
4423 goto out;
4425 ret = ufshcd_make_hba_operational(hba);
4426 out:
4427 if (ret) {
4428 dev_err(hba->dev, "link startup failed %d\n", ret);
4429 ufshcd_print_host_state(hba);
4430 ufshcd_print_pwr_info(hba);
4431 ufshcd_print_host_regs(hba);
4433 return ret;
4437 * ufshcd_verify_dev_init() - Verify device initialization
4438 * @hba: per-adapter instance
4440 * Send NOP OUT UPIU and wait for NOP IN response to check whether the
4441 * device Transport Protocol (UTP) layer is ready after a reset.
4442 * If the UTP layer at the device side is not initialized, it may
4443 * not respond with NOP IN UPIU within timeout of %NOP_OUT_TIMEOUT
4444 * and we retry sending NOP OUT for %NOP_OUT_RETRIES iterations.
4446 static int ufshcd_verify_dev_init(struct ufs_hba *hba)
4448 int err = 0;
4449 int retries;
4451 ufshcd_hold(hba, false);
4452 mutex_lock(&hba->dev_cmd.lock);
4453 for (retries = NOP_OUT_RETRIES; retries > 0; retries--) {
4454 err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_NOP,
4455 NOP_OUT_TIMEOUT);
4457 if (!err || err == -ETIMEDOUT)
4458 break;
4460 dev_dbg(hba->dev, "%s: error %d retrying\n", __func__, err);
4462 mutex_unlock(&hba->dev_cmd.lock);
4463 ufshcd_release(hba);
4465 if (err)
4466 dev_err(hba->dev, "%s: NOP OUT failed %d\n", __func__, err);
4467 return err;
4471 * ufshcd_set_queue_depth - set lun queue depth
4472 * @sdev: pointer to SCSI device
4474 * Read bLUQueueDepth value and activate scsi tagged command
4475 * queueing. For WLUN, queue depth is set to 1. For best-effort
4476 * cases (bLUQueueDepth = 0) the queue depth is set to a maximum
4477 * value that host can queue.
4479 static void ufshcd_set_queue_depth(struct scsi_device *sdev)
4481 int ret = 0;
4482 u8 lun_qdepth;
4483 struct ufs_hba *hba;
4485 hba = shost_priv(sdev->host);
4487 lun_qdepth = hba->nutrs;
4488 ret = ufshcd_read_unit_desc_param(hba,
4489 ufshcd_scsi_to_upiu_lun(sdev->lun),
4490 UNIT_DESC_PARAM_LU_Q_DEPTH,
4491 &lun_qdepth,
4492 sizeof(lun_qdepth));
4494 /* Some WLUN doesn't support unit descriptor */
4495 if (ret == -EOPNOTSUPP)
4496 lun_qdepth = 1;
4497 else if (!lun_qdepth)
4498 /* eventually, we can figure out the real queue depth */
4499 lun_qdepth = hba->nutrs;
4500 else
4501 lun_qdepth = min_t(int, lun_qdepth, hba->nutrs);
4503 dev_dbg(hba->dev, "%s: activate tcq with queue depth %d\n",
4504 __func__, lun_qdepth);
4505 scsi_change_queue_depth(sdev, lun_qdepth);
4509 * ufshcd_get_lu_wp - returns the "b_lu_write_protect" from UNIT DESCRIPTOR
4510 * @hba: per-adapter instance
4511 * @lun: UFS device lun id
4512 * @b_lu_write_protect: pointer to buffer to hold the LU's write protect info
4514 * Returns 0 in case of success and b_lu_write_protect status would be returned
4515 * @b_lu_write_protect parameter.
4516 * Returns -ENOTSUPP if reading b_lu_write_protect is not supported.
4517 * Returns -EINVAL in case of invalid parameters passed to this function.
4519 static int ufshcd_get_lu_wp(struct ufs_hba *hba,
4520 u8 lun,
4521 u8 *b_lu_write_protect)
4523 int ret;
4525 if (!b_lu_write_protect)
4526 ret = -EINVAL;
4528 * According to UFS device spec, RPMB LU can't be write
4529 * protected so skip reading bLUWriteProtect parameter for
4530 * it. For other W-LUs, UNIT DESCRIPTOR is not available.
4532 else if (lun >= hba->dev_info.max_lu_supported)
4533 ret = -ENOTSUPP;
4534 else
4535 ret = ufshcd_read_unit_desc_param(hba,
4536 lun,
4537 UNIT_DESC_PARAM_LU_WR_PROTECT,
4538 b_lu_write_protect,
4539 sizeof(*b_lu_write_protect));
4540 return ret;
4544 * ufshcd_get_lu_power_on_wp_status - get LU's power on write protect
4545 * status
4546 * @hba: per-adapter instance
4547 * @sdev: pointer to SCSI device
4550 static inline void ufshcd_get_lu_power_on_wp_status(struct ufs_hba *hba,
4551 struct scsi_device *sdev)
4553 if (hba->dev_info.f_power_on_wp_en &&
4554 !hba->dev_info.is_lu_power_on_wp) {
4555 u8 b_lu_write_protect;
4557 if (!ufshcd_get_lu_wp(hba, ufshcd_scsi_to_upiu_lun(sdev->lun),
4558 &b_lu_write_protect) &&
4559 (b_lu_write_protect == UFS_LU_POWER_ON_WP))
4560 hba->dev_info.is_lu_power_on_wp = true;
4565 * ufshcd_slave_alloc - handle initial SCSI device configurations
4566 * @sdev: pointer to SCSI device
4568 * Returns success
4570 static int ufshcd_slave_alloc(struct scsi_device *sdev)
4572 struct ufs_hba *hba;
4574 hba = shost_priv(sdev->host);
4576 /* Mode sense(6) is not supported by UFS, so use Mode sense(10) */
4577 sdev->use_10_for_ms = 1;
4579 /* DBD field should be set to 1 in mode sense(10) */
4580 sdev->set_dbd_for_ms = 1;
4582 /* allow SCSI layer to restart the device in case of errors */
4583 sdev->allow_restart = 1;
4585 /* REPORT SUPPORTED OPERATION CODES is not supported */
4586 sdev->no_report_opcodes = 1;
4588 /* WRITE_SAME command is not supported */
4589 sdev->no_write_same = 1;
4591 ufshcd_set_queue_depth(sdev);
4593 ufshcd_get_lu_power_on_wp_status(hba, sdev);
4595 return 0;
4599 * ufshcd_change_queue_depth - change queue depth
4600 * @sdev: pointer to SCSI device
4601 * @depth: required depth to set
4603 * Change queue depth and make sure the max. limits are not crossed.
4605 static int ufshcd_change_queue_depth(struct scsi_device *sdev, int depth)
4607 struct ufs_hba *hba = shost_priv(sdev->host);
4609 if (depth > hba->nutrs)
4610 depth = hba->nutrs;
4611 return scsi_change_queue_depth(sdev, depth);
4615 * ufshcd_slave_configure - adjust SCSI device configurations
4616 * @sdev: pointer to SCSI device
4618 static int ufshcd_slave_configure(struct scsi_device *sdev)
4620 struct ufs_hba *hba = shost_priv(sdev->host);
4621 struct request_queue *q = sdev->request_queue;
4623 blk_queue_update_dma_pad(q, PRDT_DATA_BYTE_COUNT_PAD - 1);
4625 if (ufshcd_is_rpm_autosuspend_allowed(hba))
4626 sdev->rpm_autosuspend = 1;
4628 return 0;
4632 * ufshcd_slave_destroy - remove SCSI device configurations
4633 * @sdev: pointer to SCSI device
4635 static void ufshcd_slave_destroy(struct scsi_device *sdev)
4637 struct ufs_hba *hba;
4639 hba = shost_priv(sdev->host);
4640 /* Drop the reference as it won't be needed anymore */
4641 if (ufshcd_scsi_to_upiu_lun(sdev->lun) == UFS_UPIU_UFS_DEVICE_WLUN) {
4642 unsigned long flags;
4644 spin_lock_irqsave(hba->host->host_lock, flags);
4645 hba->sdev_ufs_device = NULL;
4646 spin_unlock_irqrestore(hba->host->host_lock, flags);
4651 * ufshcd_scsi_cmd_status - Update SCSI command result based on SCSI status
4652 * @lrbp: pointer to local reference block of completed command
4653 * @scsi_status: SCSI command status
4655 * Returns value base on SCSI command status
4657 static inline int
4658 ufshcd_scsi_cmd_status(struct ufshcd_lrb *lrbp, int scsi_status)
4660 int result = 0;
4662 switch (scsi_status) {
4663 case SAM_STAT_CHECK_CONDITION:
4664 ufshcd_copy_sense_data(lrbp);
4665 /* fallthrough */
4666 case SAM_STAT_GOOD:
4667 result |= DID_OK << 16 |
4668 COMMAND_COMPLETE << 8 |
4669 scsi_status;
4670 break;
4671 case SAM_STAT_TASK_SET_FULL:
4672 case SAM_STAT_BUSY:
4673 case SAM_STAT_TASK_ABORTED:
4674 ufshcd_copy_sense_data(lrbp);
4675 result |= scsi_status;
4676 break;
4677 default:
4678 result |= DID_ERROR << 16;
4679 break;
4680 } /* end of switch */
4682 return result;
4686 * ufshcd_transfer_rsp_status - Get overall status of the response
4687 * @hba: per adapter instance
4688 * @lrbp: pointer to local reference block of completed command
4690 * Returns result of the command to notify SCSI midlayer
4692 static inline int
4693 ufshcd_transfer_rsp_status(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
4695 int result = 0;
4696 int scsi_status;
4697 int ocs;
4699 /* overall command status of utrd */
4700 ocs = ufshcd_get_tr_ocs(lrbp);
4702 switch (ocs) {
4703 case OCS_SUCCESS:
4704 result = ufshcd_get_req_rsp(lrbp->ucd_rsp_ptr);
4705 hba->ufs_stats.last_hibern8_exit_tstamp = ktime_set(0, 0);
4706 switch (result) {
4707 case UPIU_TRANSACTION_RESPONSE:
4709 * get the response UPIU result to extract
4710 * the SCSI command status
4712 result = ufshcd_get_rsp_upiu_result(lrbp->ucd_rsp_ptr);
4715 * get the result based on SCSI status response
4716 * to notify the SCSI midlayer of the command status
4718 scsi_status = result & MASK_SCSI_STATUS;
4719 result = ufshcd_scsi_cmd_status(lrbp, scsi_status);
4722 * Currently we are only supporting BKOPs exception
4723 * events hence we can ignore BKOPs exception event
4724 * during power management callbacks. BKOPs exception
4725 * event is not expected to be raised in runtime suspend
4726 * callback as it allows the urgent bkops.
4727 * During system suspend, we are anyway forcefully
4728 * disabling the bkops and if urgent bkops is needed
4729 * it will be enabled on system resume. Long term
4730 * solution could be to abort the system suspend if
4731 * UFS device needs urgent BKOPs.
4733 if (!hba->pm_op_in_progress &&
4734 ufshcd_is_exception_event(lrbp->ucd_rsp_ptr) &&
4735 schedule_work(&hba->eeh_work)) {
4737 * Prevent suspend once eeh_work is scheduled
4738 * to avoid deadlock between ufshcd_suspend
4739 * and exception event handler.
4741 pm_runtime_get_noresume(hba->dev);
4743 break;
4744 case UPIU_TRANSACTION_REJECT_UPIU:
4745 /* TODO: handle Reject UPIU Response */
4746 result = DID_ERROR << 16;
4747 dev_err(hba->dev,
4748 "Reject UPIU not fully implemented\n");
4749 break;
4750 default:
4751 dev_err(hba->dev,
4752 "Unexpected request response code = %x\n",
4753 result);
4754 result = DID_ERROR << 16;
4755 break;
4757 break;
4758 case OCS_ABORTED:
4759 result |= DID_ABORT << 16;
4760 break;
4761 case OCS_INVALID_COMMAND_STATUS:
4762 result |= DID_REQUEUE << 16;
4763 break;
4764 case OCS_INVALID_CMD_TABLE_ATTR:
4765 case OCS_INVALID_PRDT_ATTR:
4766 case OCS_MISMATCH_DATA_BUF_SIZE:
4767 case OCS_MISMATCH_RESP_UPIU_SIZE:
4768 case OCS_PEER_COMM_FAILURE:
4769 case OCS_FATAL_ERROR:
4770 default:
4771 result |= DID_ERROR << 16;
4772 dev_err(hba->dev,
4773 "OCS error from controller = %x for tag %d\n",
4774 ocs, lrbp->task_tag);
4775 ufshcd_print_host_regs(hba);
4776 ufshcd_print_host_state(hba);
4777 break;
4778 } /* end of switch */
4780 if ((host_byte(result) != DID_OK) && !hba->silence_err_logs)
4781 ufshcd_print_trs(hba, 1 << lrbp->task_tag, true);
4782 return result;
4786 * ufshcd_uic_cmd_compl - handle completion of uic command
4787 * @hba: per adapter instance
4788 * @intr_status: interrupt status generated by the controller
4790 * Returns
4791 * IRQ_HANDLED - If interrupt is valid
4792 * IRQ_NONE - If invalid interrupt
4794 static irqreturn_t ufshcd_uic_cmd_compl(struct ufs_hba *hba, u32 intr_status)
4796 irqreturn_t retval = IRQ_NONE;
4798 if ((intr_status & UIC_COMMAND_COMPL) && hba->active_uic_cmd) {
4799 hba->active_uic_cmd->argument2 |=
4800 ufshcd_get_uic_cmd_result(hba);
4801 hba->active_uic_cmd->argument3 =
4802 ufshcd_get_dme_attr_val(hba);
4803 complete(&hba->active_uic_cmd->done);
4804 retval = IRQ_HANDLED;
4807 if ((intr_status & UFSHCD_UIC_PWR_MASK) && hba->uic_async_done) {
4808 complete(hba->uic_async_done);
4809 retval = IRQ_HANDLED;
4811 return retval;
4815 * __ufshcd_transfer_req_compl - handle SCSI and query command completion
4816 * @hba: per adapter instance
4817 * @completed_reqs: requests to complete
4819 static void __ufshcd_transfer_req_compl(struct ufs_hba *hba,
4820 unsigned long completed_reqs)
4822 struct ufshcd_lrb *lrbp;
4823 struct scsi_cmnd *cmd;
4824 int result;
4825 int index;
4827 for_each_set_bit(index, &completed_reqs, hba->nutrs) {
4828 lrbp = &hba->lrb[index];
4829 cmd = lrbp->cmd;
4830 if (cmd) {
4831 ufshcd_add_command_trace(hba, index, "complete");
4832 result = ufshcd_transfer_rsp_status(hba, lrbp);
4833 scsi_dma_unmap(cmd);
4834 cmd->result = result;
4835 /* Mark completed command as NULL in LRB */
4836 lrbp->cmd = NULL;
4837 lrbp->compl_time_stamp = ktime_get();
4838 /* Do not touch lrbp after scsi done */
4839 cmd->scsi_done(cmd);
4840 __ufshcd_release(hba);
4841 } else if (lrbp->command_type == UTP_CMD_TYPE_DEV_MANAGE ||
4842 lrbp->command_type == UTP_CMD_TYPE_UFS_STORAGE) {
4843 lrbp->compl_time_stamp = ktime_get();
4844 if (hba->dev_cmd.complete) {
4845 ufshcd_add_command_trace(hba, index,
4846 "dev_complete");
4847 complete(hba->dev_cmd.complete);
4850 if (ufshcd_is_clkscaling_supported(hba))
4851 hba->clk_scaling.active_reqs--;
4854 /* clear corresponding bits of completed commands */
4855 hba->outstanding_reqs ^= completed_reqs;
4857 ufshcd_clk_scaling_update_busy(hba);
4861 * ufshcd_transfer_req_compl - handle SCSI and query command completion
4862 * @hba: per adapter instance
4864 * Returns
4865 * IRQ_HANDLED - If interrupt is valid
4866 * IRQ_NONE - If invalid interrupt
4868 static irqreturn_t ufshcd_transfer_req_compl(struct ufs_hba *hba)
4870 unsigned long completed_reqs;
4871 u32 tr_doorbell;
4873 /* Resetting interrupt aggregation counters first and reading the
4874 * DOOR_BELL afterward allows us to handle all the completed requests.
4875 * In order to prevent other interrupts starvation the DB is read once
4876 * after reset. The down side of this solution is the possibility of
4877 * false interrupt if device completes another request after resetting
4878 * aggregation and before reading the DB.
4880 if (ufshcd_is_intr_aggr_allowed(hba))
4881 ufshcd_reset_intr_aggr(hba);
4883 tr_doorbell = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
4884 completed_reqs = tr_doorbell ^ hba->outstanding_reqs;
4886 if (completed_reqs) {
4887 __ufshcd_transfer_req_compl(hba, completed_reqs);
4888 return IRQ_HANDLED;
4889 } else {
4890 return IRQ_NONE;
4895 * ufshcd_disable_ee - disable exception event
4896 * @hba: per-adapter instance
4897 * @mask: exception event to disable
4899 * Disables exception event in the device so that the EVENT_ALERT
4900 * bit is not set.
4902 * Returns zero on success, non-zero error value on failure.
4904 static int ufshcd_disable_ee(struct ufs_hba *hba, u16 mask)
4906 int err = 0;
4907 u32 val;
4909 if (!(hba->ee_ctrl_mask & mask))
4910 goto out;
4912 val = hba->ee_ctrl_mask & ~mask;
4913 val &= MASK_EE_STATUS;
4914 err = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_WRITE_ATTR,
4915 QUERY_ATTR_IDN_EE_CONTROL, 0, 0, &val);
4916 if (!err)
4917 hba->ee_ctrl_mask &= ~mask;
4918 out:
4919 return err;
4923 * ufshcd_enable_ee - enable exception event
4924 * @hba: per-adapter instance
4925 * @mask: exception event to enable
4927 * Enable corresponding exception event in the device to allow
4928 * device to alert host in critical scenarios.
4930 * Returns zero on success, non-zero error value on failure.
4932 static int ufshcd_enable_ee(struct ufs_hba *hba, u16 mask)
4934 int err = 0;
4935 u32 val;
4937 if (hba->ee_ctrl_mask & mask)
4938 goto out;
4940 val = hba->ee_ctrl_mask | mask;
4941 val &= MASK_EE_STATUS;
4942 err = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_WRITE_ATTR,
4943 QUERY_ATTR_IDN_EE_CONTROL, 0, 0, &val);
4944 if (!err)
4945 hba->ee_ctrl_mask |= mask;
4946 out:
4947 return err;
4951 * ufshcd_enable_auto_bkops - Allow device managed BKOPS
4952 * @hba: per-adapter instance
4954 * Allow device to manage background operations on its own. Enabling
4955 * this might lead to inconsistent latencies during normal data transfers
4956 * as the device is allowed to manage its own way of handling background
4957 * operations.
4959 * Returns zero on success, non-zero on failure.
4961 static int ufshcd_enable_auto_bkops(struct ufs_hba *hba)
4963 int err = 0;
4965 if (hba->auto_bkops_enabled)
4966 goto out;
4968 err = ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_SET_FLAG,
4969 QUERY_FLAG_IDN_BKOPS_EN, NULL);
4970 if (err) {
4971 dev_err(hba->dev, "%s: failed to enable bkops %d\n",
4972 __func__, err);
4973 goto out;
4976 hba->auto_bkops_enabled = true;
4977 trace_ufshcd_auto_bkops_state(dev_name(hba->dev), "Enabled");
4979 /* No need of URGENT_BKOPS exception from the device */
4980 err = ufshcd_disable_ee(hba, MASK_EE_URGENT_BKOPS);
4981 if (err)
4982 dev_err(hba->dev, "%s: failed to disable exception event %d\n",
4983 __func__, err);
4984 out:
4985 return err;
4989 * ufshcd_disable_auto_bkops - block device in doing background operations
4990 * @hba: per-adapter instance
4992 * Disabling background operations improves command response latency but
4993 * has drawback of device moving into critical state where the device is
4994 * not-operable. Make sure to call ufshcd_enable_auto_bkops() whenever the
4995 * host is idle so that BKOPS are managed effectively without any negative
4996 * impacts.
4998 * Returns zero on success, non-zero on failure.
5000 static int ufshcd_disable_auto_bkops(struct ufs_hba *hba)
5002 int err = 0;
5004 if (!hba->auto_bkops_enabled)
5005 goto out;
5008 * If host assisted BKOPs is to be enabled, make sure
5009 * urgent bkops exception is allowed.
5011 err = ufshcd_enable_ee(hba, MASK_EE_URGENT_BKOPS);
5012 if (err) {
5013 dev_err(hba->dev, "%s: failed to enable exception event %d\n",
5014 __func__, err);
5015 goto out;
5018 err = ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_CLEAR_FLAG,
5019 QUERY_FLAG_IDN_BKOPS_EN, NULL);
5020 if (err) {
5021 dev_err(hba->dev, "%s: failed to disable bkops %d\n",
5022 __func__, err);
5023 ufshcd_disable_ee(hba, MASK_EE_URGENT_BKOPS);
5024 goto out;
5027 hba->auto_bkops_enabled = false;
5028 trace_ufshcd_auto_bkops_state(dev_name(hba->dev), "Disabled");
5029 hba->is_urgent_bkops_lvl_checked = false;
5030 out:
5031 return err;
5035 * ufshcd_force_reset_auto_bkops - force reset auto bkops state
5036 * @hba: per adapter instance
5038 * After a device reset the device may toggle the BKOPS_EN flag
5039 * to default value. The s/w tracking variables should be updated
5040 * as well. This function would change the auto-bkops state based on
5041 * UFSHCD_CAP_KEEP_AUTO_BKOPS_ENABLED_EXCEPT_SUSPEND.
5043 static void ufshcd_force_reset_auto_bkops(struct ufs_hba *hba)
5045 if (ufshcd_keep_autobkops_enabled_except_suspend(hba)) {
5046 hba->auto_bkops_enabled = false;
5047 hba->ee_ctrl_mask |= MASK_EE_URGENT_BKOPS;
5048 ufshcd_enable_auto_bkops(hba);
5049 } else {
5050 hba->auto_bkops_enabled = true;
5051 hba->ee_ctrl_mask &= ~MASK_EE_URGENT_BKOPS;
5052 ufshcd_disable_auto_bkops(hba);
5054 hba->is_urgent_bkops_lvl_checked = false;
5057 static inline int ufshcd_get_bkops_status(struct ufs_hba *hba, u32 *status)
5059 return ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
5060 QUERY_ATTR_IDN_BKOPS_STATUS, 0, 0, status);
5064 * ufshcd_bkops_ctrl - control the auto bkops based on current bkops status
5065 * @hba: per-adapter instance
5066 * @status: bkops_status value
5068 * Read the bkops_status from the UFS device and Enable fBackgroundOpsEn
5069 * flag in the device to permit background operations if the device
5070 * bkops_status is greater than or equal to "status" argument passed to
5071 * this function, disable otherwise.
5073 * Returns 0 for success, non-zero in case of failure.
5075 * NOTE: Caller of this function can check the "hba->auto_bkops_enabled" flag
5076 * to know whether auto bkops is enabled or disabled after this function
5077 * returns control to it.
5079 static int ufshcd_bkops_ctrl(struct ufs_hba *hba,
5080 enum bkops_status status)
5082 int err;
5083 u32 curr_status = 0;
5085 err = ufshcd_get_bkops_status(hba, &curr_status);
5086 if (err) {
5087 dev_err(hba->dev, "%s: failed to get BKOPS status %d\n",
5088 __func__, err);
5089 goto out;
5090 } else if (curr_status > BKOPS_STATUS_MAX) {
5091 dev_err(hba->dev, "%s: invalid BKOPS status %d\n",
5092 __func__, curr_status);
5093 err = -EINVAL;
5094 goto out;
5097 if (curr_status >= status)
5098 err = ufshcd_enable_auto_bkops(hba);
5099 else
5100 err = ufshcd_disable_auto_bkops(hba);
5101 out:
5102 return err;
5106 * ufshcd_urgent_bkops - handle urgent bkops exception event
5107 * @hba: per-adapter instance
5109 * Enable fBackgroundOpsEn flag in the device to permit background
5110 * operations.
5112 * If BKOPs is enabled, this function returns 0, 1 if the bkops in not enabled
5113 * and negative error value for any other failure.
5115 static int ufshcd_urgent_bkops(struct ufs_hba *hba)
5117 return ufshcd_bkops_ctrl(hba, hba->urgent_bkops_lvl);
5120 static inline int ufshcd_get_ee_status(struct ufs_hba *hba, u32 *status)
5122 return ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
5123 QUERY_ATTR_IDN_EE_STATUS, 0, 0, status);
5126 static void ufshcd_bkops_exception_event_handler(struct ufs_hba *hba)
5128 int err;
5129 u32 curr_status = 0;
5131 if (hba->is_urgent_bkops_lvl_checked)
5132 goto enable_auto_bkops;
5134 err = ufshcd_get_bkops_status(hba, &curr_status);
5135 if (err) {
5136 dev_err(hba->dev, "%s: failed to get BKOPS status %d\n",
5137 __func__, err);
5138 goto out;
5142 * We are seeing that some devices are raising the urgent bkops
5143 * exception events even when BKOPS status doesn't indicate performace
5144 * impacted or critical. Handle these device by determining their urgent
5145 * bkops status at runtime.
5147 if (curr_status < BKOPS_STATUS_PERF_IMPACT) {
5148 dev_err(hba->dev, "%s: device raised urgent BKOPS exception for bkops status %d\n",
5149 __func__, curr_status);
5150 /* update the current status as the urgent bkops level */
5151 hba->urgent_bkops_lvl = curr_status;
5152 hba->is_urgent_bkops_lvl_checked = true;
5155 enable_auto_bkops:
5156 err = ufshcd_enable_auto_bkops(hba);
5157 out:
5158 if (err < 0)
5159 dev_err(hba->dev, "%s: failed to handle urgent bkops %d\n",
5160 __func__, err);
5164 * ufshcd_exception_event_handler - handle exceptions raised by device
5165 * @work: pointer to work data
5167 * Read bExceptionEventStatus attribute from the device and handle the
5168 * exception event accordingly.
5170 static void ufshcd_exception_event_handler(struct work_struct *work)
5172 struct ufs_hba *hba;
5173 int err;
5174 u32 status = 0;
5175 hba = container_of(work, struct ufs_hba, eeh_work);
5177 pm_runtime_get_sync(hba->dev);
5178 ufshcd_scsi_block_requests(hba);
5179 err = ufshcd_get_ee_status(hba, &status);
5180 if (err) {
5181 dev_err(hba->dev, "%s: failed to get exception status %d\n",
5182 __func__, err);
5183 goto out;
5186 status &= hba->ee_ctrl_mask;
5188 if (status & MASK_EE_URGENT_BKOPS)
5189 ufshcd_bkops_exception_event_handler(hba);
5191 out:
5192 ufshcd_scsi_unblock_requests(hba);
5194 * pm_runtime_get_noresume is called while scheduling
5195 * eeh_work to avoid suspend racing with exception work.
5196 * Hence decrement usage counter using pm_runtime_put_noidle
5197 * to allow suspend on completion of exception event handler.
5199 pm_runtime_put_noidle(hba->dev);
5200 pm_runtime_put(hba->dev);
5201 return;
5204 /* Complete requests that have door-bell cleared */
5205 static void ufshcd_complete_requests(struct ufs_hba *hba)
5207 ufshcd_transfer_req_compl(hba);
5208 ufshcd_tmc_handler(hba);
5212 * ufshcd_quirk_dl_nac_errors - This function checks if error handling is
5213 * to recover from the DL NAC errors or not.
5214 * @hba: per-adapter instance
5216 * Returns true if error handling is required, false otherwise
5218 static bool ufshcd_quirk_dl_nac_errors(struct ufs_hba *hba)
5220 unsigned long flags;
5221 bool err_handling = true;
5223 spin_lock_irqsave(hba->host->host_lock, flags);
5225 * UFS_DEVICE_QUIRK_RECOVERY_FROM_DL_NAC_ERRORS only workaround the
5226 * device fatal error and/or DL NAC & REPLAY timeout errors.
5228 if (hba->saved_err & (CONTROLLER_FATAL_ERROR | SYSTEM_BUS_FATAL_ERROR))
5229 goto out;
5231 if ((hba->saved_err & DEVICE_FATAL_ERROR) ||
5232 ((hba->saved_err & UIC_ERROR) &&
5233 (hba->saved_uic_err & UFSHCD_UIC_DL_TCx_REPLAY_ERROR)))
5234 goto out;
5236 if ((hba->saved_err & UIC_ERROR) &&
5237 (hba->saved_uic_err & UFSHCD_UIC_DL_NAC_RECEIVED_ERROR)) {
5238 int err;
5240 * wait for 50ms to see if we can get any other errors or not.
5242 spin_unlock_irqrestore(hba->host->host_lock, flags);
5243 msleep(50);
5244 spin_lock_irqsave(hba->host->host_lock, flags);
5247 * now check if we have got any other severe errors other than
5248 * DL NAC error?
5250 if ((hba->saved_err & INT_FATAL_ERRORS) ||
5251 ((hba->saved_err & UIC_ERROR) &&
5252 (hba->saved_uic_err & ~UFSHCD_UIC_DL_NAC_RECEIVED_ERROR)))
5253 goto out;
5256 * As DL NAC is the only error received so far, send out NOP
5257 * command to confirm if link is still active or not.
5258 * - If we don't get any response then do error recovery.
5259 * - If we get response then clear the DL NAC error bit.
5262 spin_unlock_irqrestore(hba->host->host_lock, flags);
5263 err = ufshcd_verify_dev_init(hba);
5264 spin_lock_irqsave(hba->host->host_lock, flags);
5266 if (err)
5267 goto out;
5269 /* Link seems to be alive hence ignore the DL NAC errors */
5270 if (hba->saved_uic_err == UFSHCD_UIC_DL_NAC_RECEIVED_ERROR)
5271 hba->saved_err &= ~UIC_ERROR;
5272 /* clear NAC error */
5273 hba->saved_uic_err &= ~UFSHCD_UIC_DL_NAC_RECEIVED_ERROR;
5274 if (!hba->saved_uic_err) {
5275 err_handling = false;
5276 goto out;
5279 out:
5280 spin_unlock_irqrestore(hba->host->host_lock, flags);
5281 return err_handling;
5285 * ufshcd_err_handler - handle UFS errors that require s/w attention
5286 * @work: pointer to work structure
5288 static void ufshcd_err_handler(struct work_struct *work)
5290 struct ufs_hba *hba;
5291 unsigned long flags;
5292 u32 err_xfer = 0;
5293 u32 err_tm = 0;
5294 int err = 0;
5295 int tag;
5296 bool needs_reset = false;
5298 hba = container_of(work, struct ufs_hba, eh_work);
5300 pm_runtime_get_sync(hba->dev);
5301 ufshcd_hold(hba, false);
5303 spin_lock_irqsave(hba->host->host_lock, flags);
5304 if (hba->ufshcd_state == UFSHCD_STATE_RESET)
5305 goto out;
5307 hba->ufshcd_state = UFSHCD_STATE_RESET;
5308 ufshcd_set_eh_in_progress(hba);
5310 /* Complete requests that have door-bell cleared by h/w */
5311 ufshcd_complete_requests(hba);
5313 if (hba->dev_quirks & UFS_DEVICE_QUIRK_RECOVERY_FROM_DL_NAC_ERRORS) {
5314 bool ret;
5316 spin_unlock_irqrestore(hba->host->host_lock, flags);
5317 /* release the lock as ufshcd_quirk_dl_nac_errors() may sleep */
5318 ret = ufshcd_quirk_dl_nac_errors(hba);
5319 spin_lock_irqsave(hba->host->host_lock, flags);
5320 if (!ret)
5321 goto skip_err_handling;
5323 if ((hba->saved_err & INT_FATAL_ERRORS) ||
5324 (hba->saved_err & UFSHCD_UIC_HIBERN8_MASK) ||
5325 ((hba->saved_err & UIC_ERROR) &&
5326 (hba->saved_uic_err & (UFSHCD_UIC_DL_PA_INIT_ERROR |
5327 UFSHCD_UIC_DL_NAC_RECEIVED_ERROR |
5328 UFSHCD_UIC_DL_TCx_REPLAY_ERROR))))
5329 needs_reset = true;
5332 * if host reset is required then skip clearing the pending
5333 * transfers forcefully because they will get cleared during
5334 * host reset and restore
5336 if (needs_reset)
5337 goto skip_pending_xfer_clear;
5339 /* release lock as clear command might sleep */
5340 spin_unlock_irqrestore(hba->host->host_lock, flags);
5341 /* Clear pending transfer requests */
5342 for_each_set_bit(tag, &hba->outstanding_reqs, hba->nutrs) {
5343 if (ufshcd_clear_cmd(hba, tag)) {
5344 err_xfer = true;
5345 goto lock_skip_pending_xfer_clear;
5349 /* Clear pending task management requests */
5350 for_each_set_bit(tag, &hba->outstanding_tasks, hba->nutmrs) {
5351 if (ufshcd_clear_tm_cmd(hba, tag)) {
5352 err_tm = true;
5353 goto lock_skip_pending_xfer_clear;
5357 lock_skip_pending_xfer_clear:
5358 spin_lock_irqsave(hba->host->host_lock, flags);
5360 /* Complete the requests that are cleared by s/w */
5361 ufshcd_complete_requests(hba);
5363 if (err_xfer || err_tm)
5364 needs_reset = true;
5366 skip_pending_xfer_clear:
5367 /* Fatal errors need reset */
5368 if (needs_reset) {
5369 unsigned long max_doorbells = (1UL << hba->nutrs) - 1;
5372 * ufshcd_reset_and_restore() does the link reinitialization
5373 * which will need atleast one empty doorbell slot to send the
5374 * device management commands (NOP and query commands).
5375 * If there is no slot empty at this moment then free up last
5376 * slot forcefully.
5378 if (hba->outstanding_reqs == max_doorbells)
5379 __ufshcd_transfer_req_compl(hba,
5380 (1UL << (hba->nutrs - 1)));
5382 spin_unlock_irqrestore(hba->host->host_lock, flags);
5383 err = ufshcd_reset_and_restore(hba);
5384 spin_lock_irqsave(hba->host->host_lock, flags);
5385 if (err) {
5386 dev_err(hba->dev, "%s: reset and restore failed\n",
5387 __func__);
5388 hba->ufshcd_state = UFSHCD_STATE_ERROR;
5391 * Inform scsi mid-layer that we did reset and allow to handle
5392 * Unit Attention properly.
5394 scsi_report_bus_reset(hba->host, 0);
5395 hba->saved_err = 0;
5396 hba->saved_uic_err = 0;
5399 skip_err_handling:
5400 if (!needs_reset) {
5401 hba->ufshcd_state = UFSHCD_STATE_OPERATIONAL;
5402 if (hba->saved_err || hba->saved_uic_err)
5403 dev_err_ratelimited(hba->dev, "%s: exit: saved_err 0x%x saved_uic_err 0x%x",
5404 __func__, hba->saved_err, hba->saved_uic_err);
5407 ufshcd_clear_eh_in_progress(hba);
5409 out:
5410 spin_unlock_irqrestore(hba->host->host_lock, flags);
5411 ufshcd_scsi_unblock_requests(hba);
5412 ufshcd_release(hba);
5413 pm_runtime_put_sync(hba->dev);
5417 * ufshcd_update_uic_error - check and set fatal UIC error flags.
5418 * @hba: per-adapter instance
5420 * Returns
5421 * IRQ_HANDLED - If interrupt is valid
5422 * IRQ_NONE - If invalid interrupt
5424 static irqreturn_t ufshcd_update_uic_error(struct ufs_hba *hba)
5426 u32 reg;
5427 irqreturn_t retval = IRQ_NONE;
5429 /* PHY layer lane error */
5430 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_PHY_ADAPTER_LAYER);
5431 /* Ignore LINERESET indication, as this is not an error */
5432 if ((reg & UIC_PHY_ADAPTER_LAYER_ERROR) &&
5433 (reg & UIC_PHY_ADAPTER_LAYER_LANE_ERR_MASK)) {
5435 * To know whether this error is fatal or not, DB timeout
5436 * must be checked but this error is handled separately.
5438 dev_dbg(hba->dev, "%s: UIC Lane error reported\n", __func__);
5439 ufshcd_update_reg_hist(&hba->ufs_stats.pa_err, reg);
5440 retval |= IRQ_HANDLED;
5443 /* PA_INIT_ERROR is fatal and needs UIC reset */
5444 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_DATA_LINK_LAYER);
5445 if ((reg & UIC_DATA_LINK_LAYER_ERROR) &&
5446 (reg & UIC_DATA_LINK_LAYER_ERROR_CODE_MASK)) {
5447 ufshcd_update_reg_hist(&hba->ufs_stats.dl_err, reg);
5449 if (reg & UIC_DATA_LINK_LAYER_ERROR_PA_INIT)
5450 hba->uic_error |= UFSHCD_UIC_DL_PA_INIT_ERROR;
5451 else if (hba->dev_quirks &
5452 UFS_DEVICE_QUIRK_RECOVERY_FROM_DL_NAC_ERRORS) {
5453 if (reg & UIC_DATA_LINK_LAYER_ERROR_NAC_RECEIVED)
5454 hba->uic_error |=
5455 UFSHCD_UIC_DL_NAC_RECEIVED_ERROR;
5456 else if (reg & UIC_DATA_LINK_LAYER_ERROR_TCx_REPLAY_TIMEOUT)
5457 hba->uic_error |= UFSHCD_UIC_DL_TCx_REPLAY_ERROR;
5459 retval |= IRQ_HANDLED;
5462 /* UIC NL/TL/DME errors needs software retry */
5463 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_NETWORK_LAYER);
5464 if ((reg & UIC_NETWORK_LAYER_ERROR) &&
5465 (reg & UIC_NETWORK_LAYER_ERROR_CODE_MASK)) {
5466 ufshcd_update_reg_hist(&hba->ufs_stats.nl_err, reg);
5467 hba->uic_error |= UFSHCD_UIC_NL_ERROR;
5468 retval |= IRQ_HANDLED;
5471 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_TRANSPORT_LAYER);
5472 if ((reg & UIC_TRANSPORT_LAYER_ERROR) &&
5473 (reg & UIC_TRANSPORT_LAYER_ERROR_CODE_MASK)) {
5474 ufshcd_update_reg_hist(&hba->ufs_stats.tl_err, reg);
5475 hba->uic_error |= UFSHCD_UIC_TL_ERROR;
5476 retval |= IRQ_HANDLED;
5479 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_DME);
5480 if ((reg & UIC_DME_ERROR) &&
5481 (reg & UIC_DME_ERROR_CODE_MASK)) {
5482 ufshcd_update_reg_hist(&hba->ufs_stats.dme_err, reg);
5483 hba->uic_error |= UFSHCD_UIC_DME_ERROR;
5484 retval |= IRQ_HANDLED;
5487 dev_dbg(hba->dev, "%s: UIC error flags = 0x%08x\n",
5488 __func__, hba->uic_error);
5489 return retval;
5492 static bool ufshcd_is_auto_hibern8_error(struct ufs_hba *hba,
5493 u32 intr_mask)
5495 if (!ufshcd_is_auto_hibern8_supported(hba) ||
5496 !ufshcd_is_auto_hibern8_enabled(hba))
5497 return false;
5499 if (!(intr_mask & UFSHCD_UIC_HIBERN8_MASK))
5500 return false;
5502 if (hba->active_uic_cmd &&
5503 (hba->active_uic_cmd->command == UIC_CMD_DME_HIBER_ENTER ||
5504 hba->active_uic_cmd->command == UIC_CMD_DME_HIBER_EXIT))
5505 return false;
5507 return true;
5511 * ufshcd_check_errors - Check for errors that need s/w attention
5512 * @hba: per-adapter instance
5514 * Returns
5515 * IRQ_HANDLED - If interrupt is valid
5516 * IRQ_NONE - If invalid interrupt
5518 static irqreturn_t ufshcd_check_errors(struct ufs_hba *hba)
5520 bool queue_eh_work = false;
5521 irqreturn_t retval = IRQ_NONE;
5523 if (hba->errors & INT_FATAL_ERRORS) {
5524 ufshcd_update_reg_hist(&hba->ufs_stats.fatal_err, hba->errors);
5525 queue_eh_work = true;
5528 if (hba->errors & UIC_ERROR) {
5529 hba->uic_error = 0;
5530 retval = ufshcd_update_uic_error(hba);
5531 if (hba->uic_error)
5532 queue_eh_work = true;
5535 if (hba->errors & UFSHCD_UIC_HIBERN8_MASK) {
5536 dev_err(hba->dev,
5537 "%s: Auto Hibern8 %s failed - status: 0x%08x, upmcrs: 0x%08x\n",
5538 __func__, (hba->errors & UIC_HIBERNATE_ENTER) ?
5539 "Enter" : "Exit",
5540 hba->errors, ufshcd_get_upmcrs(hba));
5541 ufshcd_update_reg_hist(&hba->ufs_stats.auto_hibern8_err,
5542 hba->errors);
5543 queue_eh_work = true;
5546 if (queue_eh_work) {
5548 * update the transfer error masks to sticky bits, let's do this
5549 * irrespective of current ufshcd_state.
5551 hba->saved_err |= hba->errors;
5552 hba->saved_uic_err |= hba->uic_error;
5554 /* handle fatal errors only when link is functional */
5555 if (hba->ufshcd_state == UFSHCD_STATE_OPERATIONAL) {
5556 /* block commands from scsi mid-layer */
5557 ufshcd_scsi_block_requests(hba);
5559 hba->ufshcd_state = UFSHCD_STATE_EH_SCHEDULED;
5561 /* dump controller state before resetting */
5562 if (hba->saved_err & (INT_FATAL_ERRORS | UIC_ERROR)) {
5563 bool pr_prdt = !!(hba->saved_err &
5564 SYSTEM_BUS_FATAL_ERROR);
5566 dev_err(hba->dev, "%s: saved_err 0x%x saved_uic_err 0x%x\n",
5567 __func__, hba->saved_err,
5568 hba->saved_uic_err);
5570 ufshcd_print_host_regs(hba);
5571 ufshcd_print_pwr_info(hba);
5572 ufshcd_print_tmrs(hba, hba->outstanding_tasks);
5573 ufshcd_print_trs(hba, hba->outstanding_reqs,
5574 pr_prdt);
5576 schedule_work(&hba->eh_work);
5578 retval |= IRQ_HANDLED;
5581 * if (!queue_eh_work) -
5582 * Other errors are either non-fatal where host recovers
5583 * itself without s/w intervention or errors that will be
5584 * handled by the SCSI core layer.
5586 return retval;
5589 struct ctm_info {
5590 struct ufs_hba *hba;
5591 unsigned long pending;
5592 unsigned int ncpl;
5595 static bool ufshcd_compl_tm(struct request *req, void *priv, bool reserved)
5597 struct ctm_info *const ci = priv;
5598 struct completion *c;
5600 WARN_ON_ONCE(reserved);
5601 if (test_bit(req->tag, &ci->pending))
5602 return true;
5603 ci->ncpl++;
5604 c = req->end_io_data;
5605 if (c)
5606 complete(c);
5607 return true;
5611 * ufshcd_tmc_handler - handle task management function completion
5612 * @hba: per adapter instance
5614 * Returns
5615 * IRQ_HANDLED - If interrupt is valid
5616 * IRQ_NONE - If invalid interrupt
5618 static irqreturn_t ufshcd_tmc_handler(struct ufs_hba *hba)
5620 struct request_queue *q = hba->tmf_queue;
5621 struct ctm_info ci = {
5622 .hba = hba,
5623 .pending = ufshcd_readl(hba, REG_UTP_TASK_REQ_DOOR_BELL),
5626 blk_mq_tagset_busy_iter(q->tag_set, ufshcd_compl_tm, &ci);
5627 return ci.ncpl ? IRQ_HANDLED : IRQ_NONE;
5631 * ufshcd_sl_intr - Interrupt service routine
5632 * @hba: per adapter instance
5633 * @intr_status: contains interrupts generated by the controller
5635 * Returns
5636 * IRQ_HANDLED - If interrupt is valid
5637 * IRQ_NONE - If invalid interrupt
5639 static irqreturn_t ufshcd_sl_intr(struct ufs_hba *hba, u32 intr_status)
5641 irqreturn_t retval = IRQ_NONE;
5643 hba->errors = UFSHCD_ERROR_MASK & intr_status;
5645 if (ufshcd_is_auto_hibern8_error(hba, intr_status))
5646 hba->errors |= (UFSHCD_UIC_HIBERN8_MASK & intr_status);
5648 if (hba->errors)
5649 retval |= ufshcd_check_errors(hba);
5651 if (intr_status & UFSHCD_UIC_MASK)
5652 retval |= ufshcd_uic_cmd_compl(hba, intr_status);
5654 if (intr_status & UTP_TASK_REQ_COMPL)
5655 retval |= ufshcd_tmc_handler(hba);
5657 if (intr_status & UTP_TRANSFER_REQ_COMPL)
5658 retval |= ufshcd_transfer_req_compl(hba);
5660 return retval;
5664 * ufshcd_intr - Main interrupt service routine
5665 * @irq: irq number
5666 * @__hba: pointer to adapter instance
5668 * Returns
5669 * IRQ_HANDLED - If interrupt is valid
5670 * IRQ_NONE - If invalid interrupt
5672 static irqreturn_t ufshcd_intr(int irq, void *__hba)
5674 u32 intr_status, enabled_intr_status;
5675 irqreturn_t retval = IRQ_NONE;
5676 struct ufs_hba *hba = __hba;
5677 int retries = hba->nutrs;
5679 spin_lock(hba->host->host_lock);
5680 intr_status = ufshcd_readl(hba, REG_INTERRUPT_STATUS);
5683 * There could be max of hba->nutrs reqs in flight and in worst case
5684 * if the reqs get finished 1 by 1 after the interrupt status is
5685 * read, make sure we handle them by checking the interrupt status
5686 * again in a loop until we process all of the reqs before returning.
5688 do {
5689 enabled_intr_status =
5690 intr_status & ufshcd_readl(hba, REG_INTERRUPT_ENABLE);
5691 if (intr_status)
5692 ufshcd_writel(hba, intr_status, REG_INTERRUPT_STATUS);
5693 if (enabled_intr_status)
5694 retval |= ufshcd_sl_intr(hba, enabled_intr_status);
5696 intr_status = ufshcd_readl(hba, REG_INTERRUPT_STATUS);
5697 } while (intr_status && --retries);
5699 if (retval == IRQ_NONE) {
5700 dev_err(hba->dev, "%s: Unhandled interrupt 0x%08x\n",
5701 __func__, intr_status);
5702 ufshcd_dump_regs(hba, 0, UFSHCI_REG_SPACE_SIZE, "host_regs: ");
5705 spin_unlock(hba->host->host_lock);
5706 return retval;
5709 static int ufshcd_clear_tm_cmd(struct ufs_hba *hba, int tag)
5711 int err = 0;
5712 u32 mask = 1 << tag;
5713 unsigned long flags;
5715 if (!test_bit(tag, &hba->outstanding_tasks))
5716 goto out;
5718 spin_lock_irqsave(hba->host->host_lock, flags);
5719 ufshcd_utmrl_clear(hba, tag);
5720 spin_unlock_irqrestore(hba->host->host_lock, flags);
5722 /* poll for max. 1 sec to clear door bell register by h/w */
5723 err = ufshcd_wait_for_register(hba,
5724 REG_UTP_TASK_REQ_DOOR_BELL,
5725 mask, 0, 1000, 1000, true);
5726 out:
5727 return err;
5730 static int __ufshcd_issue_tm_cmd(struct ufs_hba *hba,
5731 struct utp_task_req_desc *treq, u8 tm_function)
5733 struct request_queue *q = hba->tmf_queue;
5734 struct Scsi_Host *host = hba->host;
5735 DECLARE_COMPLETION_ONSTACK(wait);
5736 struct request *req;
5737 unsigned long flags;
5738 int free_slot, task_tag, err;
5741 * Get free slot, sleep if slots are unavailable.
5742 * Even though we use wait_event() which sleeps indefinitely,
5743 * the maximum wait time is bounded by %TM_CMD_TIMEOUT.
5745 req = blk_get_request(q, REQ_OP_DRV_OUT, BLK_MQ_REQ_RESERVED);
5746 req->end_io_data = &wait;
5747 free_slot = req->tag;
5748 WARN_ON_ONCE(free_slot < 0 || free_slot >= hba->nutmrs);
5749 ufshcd_hold(hba, false);
5751 spin_lock_irqsave(host->host_lock, flags);
5752 task_tag = hba->nutrs + free_slot;
5754 treq->req_header.dword_0 |= cpu_to_be32(task_tag);
5756 memcpy(hba->utmrdl_base_addr + free_slot, treq, sizeof(*treq));
5757 ufshcd_vops_setup_task_mgmt(hba, free_slot, tm_function);
5759 /* send command to the controller */
5760 __set_bit(free_slot, &hba->outstanding_tasks);
5762 /* Make sure descriptors are ready before ringing the task doorbell */
5763 wmb();
5765 ufshcd_writel(hba, 1 << free_slot, REG_UTP_TASK_REQ_DOOR_BELL);
5766 /* Make sure that doorbell is committed immediately */
5767 wmb();
5769 spin_unlock_irqrestore(host->host_lock, flags);
5771 ufshcd_add_tm_upiu_trace(hba, task_tag, "tm_send");
5773 /* wait until the task management command is completed */
5774 err = wait_for_completion_io_timeout(&wait,
5775 msecs_to_jiffies(TM_CMD_TIMEOUT));
5776 if (!err) {
5778 * Make sure that ufshcd_compl_tm() does not trigger a
5779 * use-after-free.
5781 req->end_io_data = NULL;
5782 ufshcd_add_tm_upiu_trace(hba, task_tag, "tm_complete_err");
5783 dev_err(hba->dev, "%s: task management cmd 0x%.2x timed-out\n",
5784 __func__, tm_function);
5785 if (ufshcd_clear_tm_cmd(hba, free_slot))
5786 dev_WARN(hba->dev, "%s: unable clear tm cmd (slot %d) after timeout\n",
5787 __func__, free_slot);
5788 err = -ETIMEDOUT;
5789 } else {
5790 err = 0;
5791 memcpy(treq, hba->utmrdl_base_addr + free_slot, sizeof(*treq));
5793 ufshcd_add_tm_upiu_trace(hba, task_tag, "tm_complete");
5796 spin_lock_irqsave(hba->host->host_lock, flags);
5797 __clear_bit(free_slot, &hba->outstanding_tasks);
5798 spin_unlock_irqrestore(hba->host->host_lock, flags);
5800 blk_put_request(req);
5802 ufshcd_release(hba);
5803 return err;
5807 * ufshcd_issue_tm_cmd - issues task management commands to controller
5808 * @hba: per adapter instance
5809 * @lun_id: LUN ID to which TM command is sent
5810 * @task_id: task ID to which the TM command is applicable
5811 * @tm_function: task management function opcode
5812 * @tm_response: task management service response return value
5814 * Returns non-zero value on error, zero on success.
5816 static int ufshcd_issue_tm_cmd(struct ufs_hba *hba, int lun_id, int task_id,
5817 u8 tm_function, u8 *tm_response)
5819 struct utp_task_req_desc treq = { { 0 }, };
5820 int ocs_value, err;
5822 /* Configure task request descriptor */
5823 treq.header.dword_0 = cpu_to_le32(UTP_REQ_DESC_INT_CMD);
5824 treq.header.dword_2 = cpu_to_le32(OCS_INVALID_COMMAND_STATUS);
5826 /* Configure task request UPIU */
5827 treq.req_header.dword_0 = cpu_to_be32(lun_id << 8) |
5828 cpu_to_be32(UPIU_TRANSACTION_TASK_REQ << 24);
5829 treq.req_header.dword_1 = cpu_to_be32(tm_function << 16);
5832 * The host shall provide the same value for LUN field in the basic
5833 * header and for Input Parameter.
5835 treq.input_param1 = cpu_to_be32(lun_id);
5836 treq.input_param2 = cpu_to_be32(task_id);
5838 err = __ufshcd_issue_tm_cmd(hba, &treq, tm_function);
5839 if (err == -ETIMEDOUT)
5840 return err;
5842 ocs_value = le32_to_cpu(treq.header.dword_2) & MASK_OCS;
5843 if (ocs_value != OCS_SUCCESS)
5844 dev_err(hba->dev, "%s: failed, ocs = 0x%x\n",
5845 __func__, ocs_value);
5846 else if (tm_response)
5847 *tm_response = be32_to_cpu(treq.output_param1) &
5848 MASK_TM_SERVICE_RESP;
5849 return err;
5853 * ufshcd_issue_devman_upiu_cmd - API for sending "utrd" type requests
5854 * @hba: per-adapter instance
5855 * @req_upiu: upiu request
5856 * @rsp_upiu: upiu reply
5857 * @desc_buff: pointer to descriptor buffer, NULL if NA
5858 * @buff_len: descriptor size, 0 if NA
5859 * @cmd_type: specifies the type (NOP, Query...)
5860 * @desc_op: descriptor operation
5862 * Those type of requests uses UTP Transfer Request Descriptor - utrd.
5863 * Therefore, it "rides" the device management infrastructure: uses its tag and
5864 * tasks work queues.
5866 * Since there is only one available tag for device management commands,
5867 * the caller is expected to hold the hba->dev_cmd.lock mutex.
5869 static int ufshcd_issue_devman_upiu_cmd(struct ufs_hba *hba,
5870 struct utp_upiu_req *req_upiu,
5871 struct utp_upiu_req *rsp_upiu,
5872 u8 *desc_buff, int *buff_len,
5873 enum dev_cmd_type cmd_type,
5874 enum query_opcode desc_op)
5876 struct request_queue *q = hba->cmd_queue;
5877 struct request *req;
5878 struct ufshcd_lrb *lrbp;
5879 int err = 0;
5880 int tag;
5881 struct completion wait;
5882 unsigned long flags;
5883 u32 upiu_flags;
5885 down_read(&hba->clk_scaling_lock);
5887 req = blk_get_request(q, REQ_OP_DRV_OUT, 0);
5888 if (IS_ERR(req)) {
5889 err = PTR_ERR(req);
5890 goto out_unlock;
5892 tag = req->tag;
5893 WARN_ON_ONCE(!ufshcd_valid_tag(hba, tag));
5895 init_completion(&wait);
5896 lrbp = &hba->lrb[tag];
5897 WARN_ON(lrbp->cmd);
5899 lrbp->cmd = NULL;
5900 lrbp->sense_bufflen = 0;
5901 lrbp->sense_buffer = NULL;
5902 lrbp->task_tag = tag;
5903 lrbp->lun = 0;
5904 lrbp->intr_cmd = true;
5905 hba->dev_cmd.type = cmd_type;
5907 switch (hba->ufs_version) {
5908 case UFSHCI_VERSION_10:
5909 case UFSHCI_VERSION_11:
5910 lrbp->command_type = UTP_CMD_TYPE_DEV_MANAGE;
5911 break;
5912 default:
5913 lrbp->command_type = UTP_CMD_TYPE_UFS_STORAGE;
5914 break;
5917 /* update the task tag in the request upiu */
5918 req_upiu->header.dword_0 |= cpu_to_be32(tag);
5920 ufshcd_prepare_req_desc_hdr(lrbp, &upiu_flags, DMA_NONE);
5922 /* just copy the upiu request as it is */
5923 memcpy(lrbp->ucd_req_ptr, req_upiu, sizeof(*lrbp->ucd_req_ptr));
5924 if (desc_buff && desc_op == UPIU_QUERY_OPCODE_WRITE_DESC) {
5925 /* The Data Segment Area is optional depending upon the query
5926 * function value. for WRITE DESCRIPTOR, the data segment
5927 * follows right after the tsf.
5929 memcpy(lrbp->ucd_req_ptr + 1, desc_buff, *buff_len);
5930 *buff_len = 0;
5933 memset(lrbp->ucd_rsp_ptr, 0, sizeof(struct utp_upiu_rsp));
5935 hba->dev_cmd.complete = &wait;
5937 /* Make sure descriptors are ready before ringing the doorbell */
5938 wmb();
5939 spin_lock_irqsave(hba->host->host_lock, flags);
5940 ufshcd_send_command(hba, tag);
5941 spin_unlock_irqrestore(hba->host->host_lock, flags);
5944 * ignore the returning value here - ufshcd_check_query_response is
5945 * bound to fail since dev_cmd.query and dev_cmd.type were left empty.
5946 * read the response directly ignoring all errors.
5948 ufshcd_wait_for_dev_cmd(hba, lrbp, QUERY_REQ_TIMEOUT);
5950 /* just copy the upiu response as it is */
5951 memcpy(rsp_upiu, lrbp->ucd_rsp_ptr, sizeof(*rsp_upiu));
5952 if (desc_buff && desc_op == UPIU_QUERY_OPCODE_READ_DESC) {
5953 u8 *descp = (u8 *)lrbp->ucd_rsp_ptr + sizeof(*rsp_upiu);
5954 u16 resp_len = be32_to_cpu(lrbp->ucd_rsp_ptr->header.dword_2) &
5955 MASK_QUERY_DATA_SEG_LEN;
5957 if (*buff_len >= resp_len) {
5958 memcpy(desc_buff, descp, resp_len);
5959 *buff_len = resp_len;
5960 } else {
5961 dev_warn(hba->dev,
5962 "%s: rsp size %d is bigger than buffer size %d",
5963 __func__, resp_len, *buff_len);
5964 *buff_len = 0;
5965 err = -EINVAL;
5969 blk_put_request(req);
5970 out_unlock:
5971 up_read(&hba->clk_scaling_lock);
5972 return err;
5976 * ufshcd_exec_raw_upiu_cmd - API function for sending raw upiu commands
5977 * @hba: per-adapter instance
5978 * @req_upiu: upiu request
5979 * @rsp_upiu: upiu reply - only 8 DW as we do not support scsi commands
5980 * @msgcode: message code, one of UPIU Transaction Codes Initiator to Target
5981 * @desc_buff: pointer to descriptor buffer, NULL if NA
5982 * @buff_len: descriptor size, 0 if NA
5983 * @desc_op: descriptor operation
5985 * Supports UTP Transfer requests (nop and query), and UTP Task
5986 * Management requests.
5987 * It is up to the caller to fill the upiu conent properly, as it will
5988 * be copied without any further input validations.
5990 int ufshcd_exec_raw_upiu_cmd(struct ufs_hba *hba,
5991 struct utp_upiu_req *req_upiu,
5992 struct utp_upiu_req *rsp_upiu,
5993 int msgcode,
5994 u8 *desc_buff, int *buff_len,
5995 enum query_opcode desc_op)
5997 int err;
5998 enum dev_cmd_type cmd_type = DEV_CMD_TYPE_QUERY;
5999 struct utp_task_req_desc treq = { { 0 }, };
6000 int ocs_value;
6001 u8 tm_f = be32_to_cpu(req_upiu->header.dword_1) >> 16 & MASK_TM_FUNC;
6003 switch (msgcode) {
6004 case UPIU_TRANSACTION_NOP_OUT:
6005 cmd_type = DEV_CMD_TYPE_NOP;
6006 /* fall through */
6007 case UPIU_TRANSACTION_QUERY_REQ:
6008 ufshcd_hold(hba, false);
6009 mutex_lock(&hba->dev_cmd.lock);
6010 err = ufshcd_issue_devman_upiu_cmd(hba, req_upiu, rsp_upiu,
6011 desc_buff, buff_len,
6012 cmd_type, desc_op);
6013 mutex_unlock(&hba->dev_cmd.lock);
6014 ufshcd_release(hba);
6016 break;
6017 case UPIU_TRANSACTION_TASK_REQ:
6018 treq.header.dword_0 = cpu_to_le32(UTP_REQ_DESC_INT_CMD);
6019 treq.header.dword_2 = cpu_to_le32(OCS_INVALID_COMMAND_STATUS);
6021 memcpy(&treq.req_header, req_upiu, sizeof(*req_upiu));
6023 err = __ufshcd_issue_tm_cmd(hba, &treq, tm_f);
6024 if (err == -ETIMEDOUT)
6025 break;
6027 ocs_value = le32_to_cpu(treq.header.dword_2) & MASK_OCS;
6028 if (ocs_value != OCS_SUCCESS) {
6029 dev_err(hba->dev, "%s: failed, ocs = 0x%x\n", __func__,
6030 ocs_value);
6031 break;
6034 memcpy(rsp_upiu, &treq.rsp_header, sizeof(*rsp_upiu));
6036 break;
6037 default:
6038 err = -EINVAL;
6040 break;
6043 return err;
6047 * ufshcd_eh_device_reset_handler - device reset handler registered to
6048 * scsi layer.
6049 * @cmd: SCSI command pointer
6051 * Returns SUCCESS/FAILED
6053 static int ufshcd_eh_device_reset_handler(struct scsi_cmnd *cmd)
6055 struct Scsi_Host *host;
6056 struct ufs_hba *hba;
6057 unsigned int tag;
6058 u32 pos;
6059 int err;
6060 u8 resp = 0xF;
6061 struct ufshcd_lrb *lrbp;
6062 unsigned long flags;
6064 host = cmd->device->host;
6065 hba = shost_priv(host);
6066 tag = cmd->request->tag;
6068 lrbp = &hba->lrb[tag];
6069 err = ufshcd_issue_tm_cmd(hba, lrbp->lun, 0, UFS_LOGICAL_RESET, &resp);
6070 if (err || resp != UPIU_TASK_MANAGEMENT_FUNC_COMPL) {
6071 if (!err)
6072 err = resp;
6073 goto out;
6076 /* clear the commands that were pending for corresponding LUN */
6077 for_each_set_bit(pos, &hba->outstanding_reqs, hba->nutrs) {
6078 if (hba->lrb[pos].lun == lrbp->lun) {
6079 err = ufshcd_clear_cmd(hba, pos);
6080 if (err)
6081 break;
6084 spin_lock_irqsave(host->host_lock, flags);
6085 ufshcd_transfer_req_compl(hba);
6086 spin_unlock_irqrestore(host->host_lock, flags);
6088 out:
6089 hba->req_abort_count = 0;
6090 ufshcd_update_reg_hist(&hba->ufs_stats.dev_reset, (u32)err);
6091 if (!err) {
6092 err = SUCCESS;
6093 } else {
6094 dev_err(hba->dev, "%s: failed with err %d\n", __func__, err);
6095 err = FAILED;
6097 return err;
6100 static void ufshcd_set_req_abort_skip(struct ufs_hba *hba, unsigned long bitmap)
6102 struct ufshcd_lrb *lrbp;
6103 int tag;
6105 for_each_set_bit(tag, &bitmap, hba->nutrs) {
6106 lrbp = &hba->lrb[tag];
6107 lrbp->req_abort_skip = true;
6112 * ufshcd_abort - abort a specific command
6113 * @cmd: SCSI command pointer
6115 * Abort the pending command in device by sending UFS_ABORT_TASK task management
6116 * command, and in host controller by clearing the door-bell register. There can
6117 * be race between controller sending the command to the device while abort is
6118 * issued. To avoid that, first issue UFS_QUERY_TASK to check if the command is
6119 * really issued and then try to abort it.
6121 * Returns SUCCESS/FAILED
6123 static int ufshcd_abort(struct scsi_cmnd *cmd)
6125 struct Scsi_Host *host;
6126 struct ufs_hba *hba;
6127 unsigned long flags;
6128 unsigned int tag;
6129 int err = 0;
6130 int poll_cnt;
6131 u8 resp = 0xF;
6132 struct ufshcd_lrb *lrbp;
6133 u32 reg;
6135 host = cmd->device->host;
6136 hba = shost_priv(host);
6137 tag = cmd->request->tag;
6138 lrbp = &hba->lrb[tag];
6139 if (!ufshcd_valid_tag(hba, tag)) {
6140 dev_err(hba->dev,
6141 "%s: invalid command tag %d: cmd=0x%p, cmd->request=0x%p",
6142 __func__, tag, cmd, cmd->request);
6143 BUG();
6147 * Task abort to the device W-LUN is illegal. When this command
6148 * will fail, due to spec violation, scsi err handling next step
6149 * will be to send LU reset which, again, is a spec violation.
6150 * To avoid these unnecessary/illegal step we skip to the last error
6151 * handling stage: reset and restore.
6153 if (lrbp->lun == UFS_UPIU_UFS_DEVICE_WLUN)
6154 return ufshcd_eh_host_reset_handler(cmd);
6156 ufshcd_hold(hba, false);
6157 reg = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
6158 /* If command is already aborted/completed, return SUCCESS */
6159 if (!(test_bit(tag, &hba->outstanding_reqs))) {
6160 dev_err(hba->dev,
6161 "%s: cmd at tag %d already completed, outstanding=0x%lx, doorbell=0x%x\n",
6162 __func__, tag, hba->outstanding_reqs, reg);
6163 goto out;
6166 if (!(reg & (1 << tag))) {
6167 dev_err(hba->dev,
6168 "%s: cmd was completed, but without a notifying intr, tag = %d",
6169 __func__, tag);
6172 /* Print Transfer Request of aborted task */
6173 dev_err(hba->dev, "%s: Device abort task at tag %d\n", __func__, tag);
6176 * Print detailed info about aborted request.
6177 * As more than one request might get aborted at the same time,
6178 * print full information only for the first aborted request in order
6179 * to reduce repeated printouts. For other aborted requests only print
6180 * basic details.
6182 scsi_print_command(hba->lrb[tag].cmd);
6183 if (!hba->req_abort_count) {
6184 ufshcd_update_reg_hist(&hba->ufs_stats.task_abort, 0);
6185 ufshcd_print_host_regs(hba);
6186 ufshcd_print_host_state(hba);
6187 ufshcd_print_pwr_info(hba);
6188 ufshcd_print_trs(hba, 1 << tag, true);
6189 } else {
6190 ufshcd_print_trs(hba, 1 << tag, false);
6192 hba->req_abort_count++;
6194 /* Skip task abort in case previous aborts failed and report failure */
6195 if (lrbp->req_abort_skip) {
6196 err = -EIO;
6197 goto out;
6200 for (poll_cnt = 100; poll_cnt; poll_cnt--) {
6201 err = ufshcd_issue_tm_cmd(hba, lrbp->lun, lrbp->task_tag,
6202 UFS_QUERY_TASK, &resp);
6203 if (!err && resp == UPIU_TASK_MANAGEMENT_FUNC_SUCCEEDED) {
6204 /* cmd pending in the device */
6205 dev_err(hba->dev, "%s: cmd pending in the device. tag = %d\n",
6206 __func__, tag);
6207 break;
6208 } else if (!err && resp == UPIU_TASK_MANAGEMENT_FUNC_COMPL) {
6210 * cmd not pending in the device, check if it is
6211 * in transition.
6213 dev_err(hba->dev, "%s: cmd at tag %d not pending in the device.\n",
6214 __func__, tag);
6215 reg = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
6216 if (reg & (1 << tag)) {
6217 /* sleep for max. 200us to stabilize */
6218 usleep_range(100, 200);
6219 continue;
6221 /* command completed already */
6222 dev_err(hba->dev, "%s: cmd at tag %d successfully cleared from DB.\n",
6223 __func__, tag);
6224 goto out;
6225 } else {
6226 dev_err(hba->dev,
6227 "%s: no response from device. tag = %d, err %d\n",
6228 __func__, tag, err);
6229 if (!err)
6230 err = resp; /* service response error */
6231 goto out;
6235 if (!poll_cnt) {
6236 err = -EBUSY;
6237 goto out;
6240 err = ufshcd_issue_tm_cmd(hba, lrbp->lun, lrbp->task_tag,
6241 UFS_ABORT_TASK, &resp);
6242 if (err || resp != UPIU_TASK_MANAGEMENT_FUNC_COMPL) {
6243 if (!err) {
6244 err = resp; /* service response error */
6245 dev_err(hba->dev, "%s: issued. tag = %d, err %d\n",
6246 __func__, tag, err);
6248 goto out;
6251 err = ufshcd_clear_cmd(hba, tag);
6252 if (err) {
6253 dev_err(hba->dev, "%s: Failed clearing cmd at tag %d, err %d\n",
6254 __func__, tag, err);
6255 goto out;
6258 scsi_dma_unmap(cmd);
6260 spin_lock_irqsave(host->host_lock, flags);
6261 ufshcd_outstanding_req_clear(hba, tag);
6262 hba->lrb[tag].cmd = NULL;
6263 spin_unlock_irqrestore(host->host_lock, flags);
6265 out:
6266 if (!err) {
6267 err = SUCCESS;
6268 } else {
6269 dev_err(hba->dev, "%s: failed with err %d\n", __func__, err);
6270 ufshcd_set_req_abort_skip(hba, hba->outstanding_reqs);
6271 err = FAILED;
6275 * This ufshcd_release() corresponds to the original scsi cmd that got
6276 * aborted here (as we won't get any IRQ for it).
6278 ufshcd_release(hba);
6279 return err;
6283 * ufshcd_host_reset_and_restore - reset and restore host controller
6284 * @hba: per-adapter instance
6286 * Note that host controller reset may issue DME_RESET to
6287 * local and remote (device) Uni-Pro stack and the attributes
6288 * are reset to default state.
6290 * Returns zero on success, non-zero on failure
6292 static int ufshcd_host_reset_and_restore(struct ufs_hba *hba)
6294 int err;
6295 unsigned long flags;
6298 * Stop the host controller and complete the requests
6299 * cleared by h/w
6301 spin_lock_irqsave(hba->host->host_lock, flags);
6302 ufshcd_hba_stop(hba, false);
6303 hba->silence_err_logs = true;
6304 ufshcd_complete_requests(hba);
6305 hba->silence_err_logs = false;
6306 spin_unlock_irqrestore(hba->host->host_lock, flags);
6308 /* scale up clocks to max frequency before full reinitialization */
6309 ufshcd_set_clk_freq(hba, true);
6311 err = ufshcd_hba_enable(hba);
6312 if (err)
6313 goto out;
6315 /* Establish the link again and restore the device */
6316 err = ufshcd_probe_hba(hba, false);
6318 if (!err && (hba->ufshcd_state != UFSHCD_STATE_OPERATIONAL))
6319 err = -EIO;
6320 out:
6321 if (err)
6322 dev_err(hba->dev, "%s: Host init failed %d\n", __func__, err);
6323 ufshcd_update_reg_hist(&hba->ufs_stats.host_reset, (u32)err);
6324 return err;
6328 * ufshcd_reset_and_restore - reset and re-initialize host/device
6329 * @hba: per-adapter instance
6331 * Reset and recover device, host and re-establish link. This
6332 * is helpful to recover the communication in fatal error conditions.
6334 * Returns zero on success, non-zero on failure
6336 static int ufshcd_reset_and_restore(struct ufs_hba *hba)
6338 int err = 0;
6339 int retries = MAX_HOST_RESET_RETRIES;
6341 do {
6342 /* Reset the attached device */
6343 ufshcd_vops_device_reset(hba);
6345 err = ufshcd_host_reset_and_restore(hba);
6346 } while (err && --retries);
6348 return err;
6352 * ufshcd_eh_host_reset_handler - host reset handler registered to scsi layer
6353 * @cmd: SCSI command pointer
6355 * Returns SUCCESS/FAILED
6357 static int ufshcd_eh_host_reset_handler(struct scsi_cmnd *cmd)
6359 int err;
6360 unsigned long flags;
6361 struct ufs_hba *hba;
6363 hba = shost_priv(cmd->device->host);
6365 ufshcd_hold(hba, false);
6367 * Check if there is any race with fatal error handling.
6368 * If so, wait for it to complete. Even though fatal error
6369 * handling does reset and restore in some cases, don't assume
6370 * anything out of it. We are just avoiding race here.
6372 do {
6373 spin_lock_irqsave(hba->host->host_lock, flags);
6374 if (!(work_pending(&hba->eh_work) ||
6375 hba->ufshcd_state == UFSHCD_STATE_RESET ||
6376 hba->ufshcd_state == UFSHCD_STATE_EH_SCHEDULED))
6377 break;
6378 spin_unlock_irqrestore(hba->host->host_lock, flags);
6379 dev_dbg(hba->dev, "%s: reset in progress\n", __func__);
6380 flush_work(&hba->eh_work);
6381 } while (1);
6383 hba->ufshcd_state = UFSHCD_STATE_RESET;
6384 ufshcd_set_eh_in_progress(hba);
6385 spin_unlock_irqrestore(hba->host->host_lock, flags);
6387 err = ufshcd_reset_and_restore(hba);
6389 spin_lock_irqsave(hba->host->host_lock, flags);
6390 if (!err) {
6391 err = SUCCESS;
6392 hba->ufshcd_state = UFSHCD_STATE_OPERATIONAL;
6393 } else {
6394 err = FAILED;
6395 hba->ufshcd_state = UFSHCD_STATE_ERROR;
6397 ufshcd_clear_eh_in_progress(hba);
6398 spin_unlock_irqrestore(hba->host->host_lock, flags);
6400 ufshcd_release(hba);
6401 return err;
6405 * ufshcd_get_max_icc_level - calculate the ICC level
6406 * @sup_curr_uA: max. current supported by the regulator
6407 * @start_scan: row at the desc table to start scan from
6408 * @buff: power descriptor buffer
6410 * Returns calculated max ICC level for specific regulator
6412 static u32 ufshcd_get_max_icc_level(int sup_curr_uA, u32 start_scan, char *buff)
6414 int i;
6415 int curr_uA;
6416 u16 data;
6417 u16 unit;
6419 for (i = start_scan; i >= 0; i--) {
6420 data = be16_to_cpup((__be16 *)&buff[2 * i]);
6421 unit = (data & ATTR_ICC_LVL_UNIT_MASK) >>
6422 ATTR_ICC_LVL_UNIT_OFFSET;
6423 curr_uA = data & ATTR_ICC_LVL_VALUE_MASK;
6424 switch (unit) {
6425 case UFSHCD_NANO_AMP:
6426 curr_uA = curr_uA / 1000;
6427 break;
6428 case UFSHCD_MILI_AMP:
6429 curr_uA = curr_uA * 1000;
6430 break;
6431 case UFSHCD_AMP:
6432 curr_uA = curr_uA * 1000 * 1000;
6433 break;
6434 case UFSHCD_MICRO_AMP:
6435 default:
6436 break;
6438 if (sup_curr_uA >= curr_uA)
6439 break;
6441 if (i < 0) {
6442 i = 0;
6443 pr_err("%s: Couldn't find valid icc_level = %d", __func__, i);
6446 return (u32)i;
6450 * ufshcd_calc_icc_level - calculate the max ICC level
6451 * In case regulators are not initialized we'll return 0
6452 * @hba: per-adapter instance
6453 * @desc_buf: power descriptor buffer to extract ICC levels from.
6454 * @len: length of desc_buff
6456 * Returns calculated ICC level
6458 static u32 ufshcd_find_max_sup_active_icc_level(struct ufs_hba *hba,
6459 u8 *desc_buf, int len)
6461 u32 icc_level = 0;
6463 if (!hba->vreg_info.vcc || !hba->vreg_info.vccq ||
6464 !hba->vreg_info.vccq2) {
6465 dev_err(hba->dev,
6466 "%s: Regulator capability was not set, actvIccLevel=%d",
6467 __func__, icc_level);
6468 goto out;
6471 if (hba->vreg_info.vcc && hba->vreg_info.vcc->max_uA)
6472 icc_level = ufshcd_get_max_icc_level(
6473 hba->vreg_info.vcc->max_uA,
6474 POWER_DESC_MAX_ACTV_ICC_LVLS - 1,
6475 &desc_buf[PWR_DESC_ACTIVE_LVLS_VCC_0]);
6477 if (hba->vreg_info.vccq && hba->vreg_info.vccq->max_uA)
6478 icc_level = ufshcd_get_max_icc_level(
6479 hba->vreg_info.vccq->max_uA,
6480 icc_level,
6481 &desc_buf[PWR_DESC_ACTIVE_LVLS_VCCQ_0]);
6483 if (hba->vreg_info.vccq2 && hba->vreg_info.vccq2->max_uA)
6484 icc_level = ufshcd_get_max_icc_level(
6485 hba->vreg_info.vccq2->max_uA,
6486 icc_level,
6487 &desc_buf[PWR_DESC_ACTIVE_LVLS_VCCQ2_0]);
6488 out:
6489 return icc_level;
6492 static void ufshcd_set_active_icc_lvl(struct ufs_hba *hba)
6494 int ret;
6495 int buff_len = hba->desc_size.pwr_desc;
6496 u8 *desc_buf;
6497 u32 icc_level;
6499 desc_buf = kmalloc(buff_len, GFP_KERNEL);
6500 if (!desc_buf)
6501 return;
6503 ret = ufshcd_read_desc(hba, QUERY_DESC_IDN_POWER, 0,
6504 desc_buf, buff_len);
6505 if (ret) {
6506 dev_err(hba->dev,
6507 "%s: Failed reading power descriptor.len = %d ret = %d",
6508 __func__, buff_len, ret);
6509 goto out;
6512 icc_level = ufshcd_find_max_sup_active_icc_level(hba, desc_buf,
6513 buff_len);
6514 dev_dbg(hba->dev, "%s: setting icc_level 0x%x", __func__, icc_level);
6516 ret = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_WRITE_ATTR,
6517 QUERY_ATTR_IDN_ACTIVE_ICC_LVL, 0, 0, &icc_level);
6519 if (ret)
6520 dev_err(hba->dev,
6521 "%s: Failed configuring bActiveICCLevel = %d ret = %d",
6522 __func__, icc_level, ret);
6524 out:
6525 kfree(desc_buf);
6528 static inline void ufshcd_blk_pm_runtime_init(struct scsi_device *sdev)
6530 scsi_autopm_get_device(sdev);
6531 blk_pm_runtime_init(sdev->request_queue, &sdev->sdev_gendev);
6532 if (sdev->rpm_autosuspend)
6533 pm_runtime_set_autosuspend_delay(&sdev->sdev_gendev,
6534 RPM_AUTOSUSPEND_DELAY_MS);
6535 scsi_autopm_put_device(sdev);
6539 * ufshcd_scsi_add_wlus - Adds required W-LUs
6540 * @hba: per-adapter instance
6542 * UFS device specification requires the UFS devices to support 4 well known
6543 * logical units:
6544 * "REPORT_LUNS" (address: 01h)
6545 * "UFS Device" (address: 50h)
6546 * "RPMB" (address: 44h)
6547 * "BOOT" (address: 30h)
6548 * UFS device's power management needs to be controlled by "POWER CONDITION"
6549 * field of SSU (START STOP UNIT) command. But this "power condition" field
6550 * will take effect only when its sent to "UFS device" well known logical unit
6551 * hence we require the scsi_device instance to represent this logical unit in
6552 * order for the UFS host driver to send the SSU command for power management.
6554 * We also require the scsi_device instance for "RPMB" (Replay Protected Memory
6555 * Block) LU so user space process can control this LU. User space may also
6556 * want to have access to BOOT LU.
6558 * This function adds scsi device instances for each of all well known LUs
6559 * (except "REPORT LUNS" LU).
6561 * Returns zero on success (all required W-LUs are added successfully),
6562 * non-zero error value on failure (if failed to add any of the required W-LU).
6564 static int ufshcd_scsi_add_wlus(struct ufs_hba *hba)
6566 int ret = 0;
6567 struct scsi_device *sdev_rpmb;
6568 struct scsi_device *sdev_boot;
6570 hba->sdev_ufs_device = __scsi_add_device(hba->host, 0, 0,
6571 ufshcd_upiu_wlun_to_scsi_wlun(UFS_UPIU_UFS_DEVICE_WLUN), NULL);
6572 if (IS_ERR(hba->sdev_ufs_device)) {
6573 ret = PTR_ERR(hba->sdev_ufs_device);
6574 hba->sdev_ufs_device = NULL;
6575 goto out;
6577 ufshcd_blk_pm_runtime_init(hba->sdev_ufs_device);
6578 scsi_device_put(hba->sdev_ufs_device);
6580 sdev_rpmb = __scsi_add_device(hba->host, 0, 0,
6581 ufshcd_upiu_wlun_to_scsi_wlun(UFS_UPIU_RPMB_WLUN), NULL);
6582 if (IS_ERR(sdev_rpmb)) {
6583 ret = PTR_ERR(sdev_rpmb);
6584 goto remove_sdev_ufs_device;
6586 ufshcd_blk_pm_runtime_init(sdev_rpmb);
6587 scsi_device_put(sdev_rpmb);
6589 sdev_boot = __scsi_add_device(hba->host, 0, 0,
6590 ufshcd_upiu_wlun_to_scsi_wlun(UFS_UPIU_BOOT_WLUN), NULL);
6591 if (IS_ERR(sdev_boot)) {
6592 dev_err(hba->dev, "%s: BOOT WLUN not found\n", __func__);
6593 } else {
6594 ufshcd_blk_pm_runtime_init(sdev_boot);
6595 scsi_device_put(sdev_boot);
6597 goto out;
6599 remove_sdev_ufs_device:
6600 scsi_remove_device(hba->sdev_ufs_device);
6601 out:
6602 return ret;
6605 static int ufs_get_device_desc(struct ufs_hba *hba)
6607 int err;
6608 size_t buff_len;
6609 u8 model_index;
6610 u8 *desc_buf;
6611 struct ufs_dev_info *dev_info = &hba->dev_info;
6613 buff_len = max_t(size_t, hba->desc_size.dev_desc,
6614 QUERY_DESC_MAX_SIZE + 1);
6615 desc_buf = kmalloc(buff_len, GFP_KERNEL);
6616 if (!desc_buf) {
6617 err = -ENOMEM;
6618 goto out;
6621 err = ufshcd_read_desc(hba, QUERY_DESC_IDN_DEVICE, 0, desc_buf,
6622 hba->desc_size.dev_desc);
6623 if (err) {
6624 dev_err(hba->dev, "%s: Failed reading Device Desc. err = %d\n",
6625 __func__, err);
6626 goto out;
6630 * getting vendor (manufacturerID) and Bank Index in big endian
6631 * format
6633 dev_info->wmanufacturerid = desc_buf[DEVICE_DESC_PARAM_MANF_ID] << 8 |
6634 desc_buf[DEVICE_DESC_PARAM_MANF_ID + 1];
6636 /* getting Specification Version in big endian format */
6637 dev_info->wspecversion = desc_buf[DEVICE_DESC_PARAM_SPEC_VER] << 8 |
6638 desc_buf[DEVICE_DESC_PARAM_SPEC_VER + 1];
6640 model_index = desc_buf[DEVICE_DESC_PARAM_PRDCT_NAME];
6641 err = ufshcd_read_string_desc(hba, model_index,
6642 &dev_info->model, SD_ASCII_STD);
6643 if (err < 0) {
6644 dev_err(hba->dev, "%s: Failed reading Product Name. err = %d\n",
6645 __func__, err);
6646 goto out;
6650 * ufshcd_read_string_desc returns size of the string
6651 * reset the error value
6653 err = 0;
6655 out:
6656 kfree(desc_buf);
6657 return err;
6660 static void ufs_put_device_desc(struct ufs_hba *hba)
6662 struct ufs_dev_info *dev_info = &hba->dev_info;
6664 kfree(dev_info->model);
6665 dev_info->model = NULL;
6668 static void ufs_fixup_device_setup(struct ufs_hba *hba)
6670 struct ufs_dev_fix *f;
6671 struct ufs_dev_info *dev_info = &hba->dev_info;
6673 for (f = ufs_fixups; f->quirk; f++) {
6674 if ((f->wmanufacturerid == dev_info->wmanufacturerid ||
6675 f->wmanufacturerid == UFS_ANY_VENDOR) &&
6676 ((dev_info->model &&
6677 STR_PRFX_EQUAL(f->model, dev_info->model)) ||
6678 !strcmp(f->model, UFS_ANY_MODEL)))
6679 hba->dev_quirks |= f->quirk;
6684 * ufshcd_tune_pa_tactivate - Tunes PA_TActivate of local UniPro
6685 * @hba: per-adapter instance
6687 * PA_TActivate parameter can be tuned manually if UniPro version is less than
6688 * 1.61. PA_TActivate needs to be greater than or equal to peerM-PHY's
6689 * RX_MIN_ACTIVATETIME_CAPABILITY attribute. This optimal value can help reduce
6690 * the hibern8 exit latency.
6692 * Returns zero on success, non-zero error value on failure.
6694 static int ufshcd_tune_pa_tactivate(struct ufs_hba *hba)
6696 int ret = 0;
6697 u32 peer_rx_min_activatetime = 0, tuned_pa_tactivate;
6699 ret = ufshcd_dme_peer_get(hba,
6700 UIC_ARG_MIB_SEL(
6701 RX_MIN_ACTIVATETIME_CAPABILITY,
6702 UIC_ARG_MPHY_RX_GEN_SEL_INDEX(0)),
6703 &peer_rx_min_activatetime);
6704 if (ret)
6705 goto out;
6707 /* make sure proper unit conversion is applied */
6708 tuned_pa_tactivate =
6709 ((peer_rx_min_activatetime * RX_MIN_ACTIVATETIME_UNIT_US)
6710 / PA_TACTIVATE_TIME_UNIT_US);
6711 ret = ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TACTIVATE),
6712 tuned_pa_tactivate);
6714 out:
6715 return ret;
6719 * ufshcd_tune_pa_hibern8time - Tunes PA_Hibern8Time of local UniPro
6720 * @hba: per-adapter instance
6722 * PA_Hibern8Time parameter can be tuned manually if UniPro version is less than
6723 * 1.61. PA_Hibern8Time needs to be maximum of local M-PHY's
6724 * TX_HIBERN8TIME_CAPABILITY & peer M-PHY's RX_HIBERN8TIME_CAPABILITY.
6725 * This optimal value can help reduce the hibern8 exit latency.
6727 * Returns zero on success, non-zero error value on failure.
6729 static int ufshcd_tune_pa_hibern8time(struct ufs_hba *hba)
6731 int ret = 0;
6732 u32 local_tx_hibern8_time_cap = 0, peer_rx_hibern8_time_cap = 0;
6733 u32 max_hibern8_time, tuned_pa_hibern8time;
6735 ret = ufshcd_dme_get(hba,
6736 UIC_ARG_MIB_SEL(TX_HIBERN8TIME_CAPABILITY,
6737 UIC_ARG_MPHY_TX_GEN_SEL_INDEX(0)),
6738 &local_tx_hibern8_time_cap);
6739 if (ret)
6740 goto out;
6742 ret = ufshcd_dme_peer_get(hba,
6743 UIC_ARG_MIB_SEL(RX_HIBERN8TIME_CAPABILITY,
6744 UIC_ARG_MPHY_RX_GEN_SEL_INDEX(0)),
6745 &peer_rx_hibern8_time_cap);
6746 if (ret)
6747 goto out;
6749 max_hibern8_time = max(local_tx_hibern8_time_cap,
6750 peer_rx_hibern8_time_cap);
6751 /* make sure proper unit conversion is applied */
6752 tuned_pa_hibern8time = ((max_hibern8_time * HIBERN8TIME_UNIT_US)
6753 / PA_HIBERN8_TIME_UNIT_US);
6754 ret = ufshcd_dme_set(hba, UIC_ARG_MIB(PA_HIBERN8TIME),
6755 tuned_pa_hibern8time);
6756 out:
6757 return ret;
6761 * ufshcd_quirk_tune_host_pa_tactivate - Ensures that host PA_TACTIVATE is
6762 * less than device PA_TACTIVATE time.
6763 * @hba: per-adapter instance
6765 * Some UFS devices require host PA_TACTIVATE to be lower than device
6766 * PA_TACTIVATE, we need to enable UFS_DEVICE_QUIRK_HOST_PA_TACTIVATE quirk
6767 * for such devices.
6769 * Returns zero on success, non-zero error value on failure.
6771 static int ufshcd_quirk_tune_host_pa_tactivate(struct ufs_hba *hba)
6773 int ret = 0;
6774 u32 granularity, peer_granularity;
6775 u32 pa_tactivate, peer_pa_tactivate;
6776 u32 pa_tactivate_us, peer_pa_tactivate_us;
6777 u8 gran_to_us_table[] = {1, 4, 8, 16, 32, 100};
6779 ret = ufshcd_dme_get(hba, UIC_ARG_MIB(PA_GRANULARITY),
6780 &granularity);
6781 if (ret)
6782 goto out;
6784 ret = ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_GRANULARITY),
6785 &peer_granularity);
6786 if (ret)
6787 goto out;
6789 if ((granularity < PA_GRANULARITY_MIN_VAL) ||
6790 (granularity > PA_GRANULARITY_MAX_VAL)) {
6791 dev_err(hba->dev, "%s: invalid host PA_GRANULARITY %d",
6792 __func__, granularity);
6793 return -EINVAL;
6796 if ((peer_granularity < PA_GRANULARITY_MIN_VAL) ||
6797 (peer_granularity > PA_GRANULARITY_MAX_VAL)) {
6798 dev_err(hba->dev, "%s: invalid device PA_GRANULARITY %d",
6799 __func__, peer_granularity);
6800 return -EINVAL;
6803 ret = ufshcd_dme_get(hba, UIC_ARG_MIB(PA_TACTIVATE), &pa_tactivate);
6804 if (ret)
6805 goto out;
6807 ret = ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_TACTIVATE),
6808 &peer_pa_tactivate);
6809 if (ret)
6810 goto out;
6812 pa_tactivate_us = pa_tactivate * gran_to_us_table[granularity - 1];
6813 peer_pa_tactivate_us = peer_pa_tactivate *
6814 gran_to_us_table[peer_granularity - 1];
6816 if (pa_tactivate_us > peer_pa_tactivate_us) {
6817 u32 new_peer_pa_tactivate;
6819 new_peer_pa_tactivate = pa_tactivate_us /
6820 gran_to_us_table[peer_granularity - 1];
6821 new_peer_pa_tactivate++;
6822 ret = ufshcd_dme_peer_set(hba, UIC_ARG_MIB(PA_TACTIVATE),
6823 new_peer_pa_tactivate);
6826 out:
6827 return ret;
6830 static void ufshcd_tune_unipro_params(struct ufs_hba *hba)
6832 if (ufshcd_is_unipro_pa_params_tuning_req(hba)) {
6833 ufshcd_tune_pa_tactivate(hba);
6834 ufshcd_tune_pa_hibern8time(hba);
6837 ufshcd_vops_apply_dev_quirks(hba);
6839 if (hba->dev_quirks & UFS_DEVICE_QUIRK_PA_TACTIVATE)
6840 /* set 1ms timeout for PA_TACTIVATE */
6841 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TACTIVATE), 10);
6843 if (hba->dev_quirks & UFS_DEVICE_QUIRK_HOST_PA_TACTIVATE)
6844 ufshcd_quirk_tune_host_pa_tactivate(hba);
6847 static void ufshcd_clear_dbg_ufs_stats(struct ufs_hba *hba)
6849 hba->ufs_stats.hibern8_exit_cnt = 0;
6850 hba->ufs_stats.last_hibern8_exit_tstamp = ktime_set(0, 0);
6851 hba->req_abort_count = 0;
6854 static void ufshcd_init_desc_sizes(struct ufs_hba *hba)
6856 int err;
6858 err = ufshcd_read_desc_length(hba, QUERY_DESC_IDN_DEVICE, 0,
6859 &hba->desc_size.dev_desc);
6860 if (err)
6861 hba->desc_size.dev_desc = QUERY_DESC_DEVICE_DEF_SIZE;
6863 err = ufshcd_read_desc_length(hba, QUERY_DESC_IDN_POWER, 0,
6864 &hba->desc_size.pwr_desc);
6865 if (err)
6866 hba->desc_size.pwr_desc = QUERY_DESC_POWER_DEF_SIZE;
6868 err = ufshcd_read_desc_length(hba, QUERY_DESC_IDN_INTERCONNECT, 0,
6869 &hba->desc_size.interc_desc);
6870 if (err)
6871 hba->desc_size.interc_desc = QUERY_DESC_INTERCONNECT_DEF_SIZE;
6873 err = ufshcd_read_desc_length(hba, QUERY_DESC_IDN_CONFIGURATION, 0,
6874 &hba->desc_size.conf_desc);
6875 if (err)
6876 hba->desc_size.conf_desc = QUERY_DESC_CONFIGURATION_DEF_SIZE;
6878 err = ufshcd_read_desc_length(hba, QUERY_DESC_IDN_UNIT, 0,
6879 &hba->desc_size.unit_desc);
6880 if (err)
6881 hba->desc_size.unit_desc = QUERY_DESC_UNIT_DEF_SIZE;
6883 err = ufshcd_read_desc_length(hba, QUERY_DESC_IDN_GEOMETRY, 0,
6884 &hba->desc_size.geom_desc);
6885 if (err)
6886 hba->desc_size.geom_desc = QUERY_DESC_GEOMETRY_DEF_SIZE;
6888 err = ufshcd_read_desc_length(hba, QUERY_DESC_IDN_HEALTH, 0,
6889 &hba->desc_size.hlth_desc);
6890 if (err)
6891 hba->desc_size.hlth_desc = QUERY_DESC_HEALTH_DEF_SIZE;
6894 static int ufshcd_device_geo_params_init(struct ufs_hba *hba)
6896 int err;
6897 size_t buff_len;
6898 u8 *desc_buf;
6900 buff_len = hba->desc_size.geom_desc;
6901 desc_buf = kmalloc(buff_len, GFP_KERNEL);
6902 if (!desc_buf) {
6903 err = -ENOMEM;
6904 goto out;
6907 err = ufshcd_read_desc(hba, QUERY_DESC_IDN_GEOMETRY, 0,
6908 desc_buf, buff_len);
6909 if (err) {
6910 dev_err(hba->dev, "%s: Failed reading Geometry Desc. err = %d\n",
6911 __func__, err);
6912 goto out;
6915 if (desc_buf[GEOMETRY_DESC_PARAM_MAX_NUM_LUN] == 1)
6916 hba->dev_info.max_lu_supported = 32;
6917 else if (desc_buf[GEOMETRY_DESC_PARAM_MAX_NUM_LUN] == 0)
6918 hba->dev_info.max_lu_supported = 8;
6920 out:
6921 kfree(desc_buf);
6922 return err;
6925 static struct ufs_ref_clk ufs_ref_clk_freqs[] = {
6926 {19200000, REF_CLK_FREQ_19_2_MHZ},
6927 {26000000, REF_CLK_FREQ_26_MHZ},
6928 {38400000, REF_CLK_FREQ_38_4_MHZ},
6929 {52000000, REF_CLK_FREQ_52_MHZ},
6930 {0, REF_CLK_FREQ_INVAL},
6933 static enum ufs_ref_clk_freq
6934 ufs_get_bref_clk_from_hz(unsigned long freq)
6936 int i;
6938 for (i = 0; ufs_ref_clk_freqs[i].freq_hz; i++)
6939 if (ufs_ref_clk_freqs[i].freq_hz == freq)
6940 return ufs_ref_clk_freqs[i].val;
6942 return REF_CLK_FREQ_INVAL;
6945 void ufshcd_parse_dev_ref_clk_freq(struct ufs_hba *hba, struct clk *refclk)
6947 unsigned long freq;
6949 freq = clk_get_rate(refclk);
6951 hba->dev_ref_clk_freq =
6952 ufs_get_bref_clk_from_hz(freq);
6954 if (hba->dev_ref_clk_freq == REF_CLK_FREQ_INVAL)
6955 dev_err(hba->dev,
6956 "invalid ref_clk setting = %ld\n", freq);
6959 static int ufshcd_set_dev_ref_clk(struct ufs_hba *hba)
6961 int err;
6962 u32 ref_clk;
6963 u32 freq = hba->dev_ref_clk_freq;
6965 err = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
6966 QUERY_ATTR_IDN_REF_CLK_FREQ, 0, 0, &ref_clk);
6968 if (err) {
6969 dev_err(hba->dev, "failed reading bRefClkFreq. err = %d\n",
6970 err);
6971 goto out;
6974 if (ref_clk == freq)
6975 goto out; /* nothing to update */
6977 err = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_WRITE_ATTR,
6978 QUERY_ATTR_IDN_REF_CLK_FREQ, 0, 0, &freq);
6980 if (err) {
6981 dev_err(hba->dev, "bRefClkFreq setting to %lu Hz failed\n",
6982 ufs_ref_clk_freqs[freq].freq_hz);
6983 goto out;
6986 dev_dbg(hba->dev, "bRefClkFreq setting to %lu Hz succeeded\n",
6987 ufs_ref_clk_freqs[freq].freq_hz);
6989 out:
6990 return err;
6993 static int ufshcd_device_params_init(struct ufs_hba *hba)
6995 bool flag;
6996 int ret;
6998 /* Clear any previous UFS device information */
6999 memset(&hba->dev_info, 0, sizeof(hba->dev_info));
7001 /* Init check for device descriptor sizes */
7002 ufshcd_init_desc_sizes(hba);
7004 /* Init UFS geometry descriptor related parameters */
7005 ret = ufshcd_device_geo_params_init(hba);
7006 if (ret)
7007 goto out;
7009 /* Check and apply UFS device quirks */
7010 ret = ufs_get_device_desc(hba);
7011 if (ret) {
7012 dev_err(hba->dev, "%s: Failed getting device info. err = %d\n",
7013 __func__, ret);
7014 goto out;
7017 ufshcd_get_ref_clk_gating_wait(hba);
7019 ufs_fixup_device_setup(hba);
7021 if (!ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_READ_FLAG,
7022 QUERY_FLAG_IDN_PWR_ON_WPE, &flag))
7023 hba->dev_info.f_power_on_wp_en = flag;
7025 /* Probe maximum power mode co-supported by both UFS host and device */
7026 if (ufshcd_get_max_pwr_mode(hba))
7027 dev_err(hba->dev,
7028 "%s: Failed getting max supported power mode\n",
7029 __func__);
7030 out:
7031 return ret;
7035 * ufshcd_add_lus - probe and add UFS logical units
7036 * @hba: per-adapter instance
7038 static int ufshcd_add_lus(struct ufs_hba *hba)
7040 int ret;
7042 /* Add required well known logical units to scsi mid layer */
7043 ret = ufshcd_scsi_add_wlus(hba);
7044 if (ret)
7045 goto out;
7047 /* Initialize devfreq after UFS device is detected */
7048 if (ufshcd_is_clkscaling_supported(hba)) {
7049 memcpy(&hba->clk_scaling.saved_pwr_info.info,
7050 &hba->pwr_info,
7051 sizeof(struct ufs_pa_layer_attr));
7052 hba->clk_scaling.saved_pwr_info.is_valid = true;
7053 if (!hba->devfreq) {
7054 ret = ufshcd_devfreq_init(hba);
7055 if (ret)
7056 goto out;
7059 hba->clk_scaling.is_allowed = true;
7062 ufs_bsg_probe(hba);
7063 scsi_scan_host(hba->host);
7064 pm_runtime_put_sync(hba->dev);
7066 out:
7067 return ret;
7071 * ufshcd_probe_hba - probe hba to detect device and initialize
7072 * @hba: per-adapter instance
7073 * @async: asynchronous execution or not
7075 * Execute link-startup and verify device initialization
7077 static int ufshcd_probe_hba(struct ufs_hba *hba, bool async)
7079 int ret;
7080 ktime_t start = ktime_get();
7082 ret = ufshcd_link_startup(hba);
7083 if (ret)
7084 goto out;
7086 /* set the default level for urgent bkops */
7087 hba->urgent_bkops_lvl = BKOPS_STATUS_PERF_IMPACT;
7088 hba->is_urgent_bkops_lvl_checked = false;
7090 /* Debug counters initialization */
7091 ufshcd_clear_dbg_ufs_stats(hba);
7093 /* UniPro link is active now */
7094 ufshcd_set_link_active(hba);
7096 /* Verify device initialization by sending NOP OUT UPIU */
7097 ret = ufshcd_verify_dev_init(hba);
7098 if (ret)
7099 goto out;
7101 /* Initiate UFS initialization, and waiting until completion */
7102 ret = ufshcd_complete_dev_init(hba);
7103 if (ret)
7104 goto out;
7107 * Initialize UFS device parameters used by driver, these
7108 * parameters are associated with UFS descriptors.
7110 if (async) {
7111 ret = ufshcd_device_params_init(hba);
7112 if (ret)
7113 goto out;
7116 ufshcd_tune_unipro_params(hba);
7118 /* UFS device is also active now */
7119 ufshcd_set_ufs_dev_active(hba);
7120 ufshcd_force_reset_auto_bkops(hba);
7121 hba->wlun_dev_clr_ua = true;
7123 /* Gear up to HS gear if supported */
7124 if (hba->max_pwr_info.is_valid) {
7126 * Set the right value to bRefClkFreq before attempting to
7127 * switch to HS gears.
7129 if (hba->dev_ref_clk_freq != REF_CLK_FREQ_INVAL)
7130 ufshcd_set_dev_ref_clk(hba);
7131 ret = ufshcd_config_pwr_mode(hba, &hba->max_pwr_info.info);
7132 if (ret) {
7133 dev_err(hba->dev, "%s: Failed setting power mode, err = %d\n",
7134 __func__, ret);
7135 goto out;
7137 ufshcd_print_pwr_info(hba);
7141 * bActiveICCLevel is volatile for UFS device (as per latest v2.1 spec)
7142 * and for removable UFS card as well, hence always set the parameter.
7143 * Note: Error handler may issue the device reset hence resetting
7144 * bActiveICCLevel as well so it is always safe to set this here.
7146 ufshcd_set_active_icc_lvl(hba);
7148 /* set the state as operational after switching to desired gear */
7149 hba->ufshcd_state = UFSHCD_STATE_OPERATIONAL;
7151 /* Enable Auto-Hibernate if configured */
7152 ufshcd_auto_hibern8_enable(hba);
7154 out:
7156 trace_ufshcd_init(dev_name(hba->dev), ret,
7157 ktime_to_us(ktime_sub(ktime_get(), start)),
7158 hba->curr_dev_pwr_mode, hba->uic_link_state);
7159 return ret;
7163 * ufshcd_async_scan - asynchronous execution for probing hba
7164 * @data: data pointer to pass to this function
7165 * @cookie: cookie data
7167 static void ufshcd_async_scan(void *data, async_cookie_t cookie)
7169 struct ufs_hba *hba = (struct ufs_hba *)data;
7170 int ret;
7172 /* Initialize hba, detect and initialize UFS device */
7173 ret = ufshcd_probe_hba(hba, true);
7174 if (ret)
7175 goto out;
7177 /* Probe and add UFS logical units */
7178 ret = ufshcd_add_lus(hba);
7179 out:
7181 * If we failed to initialize the device or the device is not
7182 * present, turn off the power/clocks etc.
7184 if (ret) {
7185 pm_runtime_put_sync(hba->dev);
7186 ufshcd_exit_clk_scaling(hba);
7187 ufshcd_hba_exit(hba);
7191 static const struct attribute_group *ufshcd_driver_groups[] = {
7192 &ufs_sysfs_unit_descriptor_group,
7193 &ufs_sysfs_lun_attributes_group,
7194 NULL,
7197 static struct scsi_host_template ufshcd_driver_template = {
7198 .module = THIS_MODULE,
7199 .name = UFSHCD,
7200 .proc_name = UFSHCD,
7201 .queuecommand = ufshcd_queuecommand,
7202 .slave_alloc = ufshcd_slave_alloc,
7203 .slave_configure = ufshcd_slave_configure,
7204 .slave_destroy = ufshcd_slave_destroy,
7205 .change_queue_depth = ufshcd_change_queue_depth,
7206 .eh_abort_handler = ufshcd_abort,
7207 .eh_device_reset_handler = ufshcd_eh_device_reset_handler,
7208 .eh_host_reset_handler = ufshcd_eh_host_reset_handler,
7209 .this_id = -1,
7210 .sg_tablesize = SG_ALL,
7211 .cmd_per_lun = UFSHCD_CMD_PER_LUN,
7212 .can_queue = UFSHCD_CAN_QUEUE,
7213 .max_segment_size = PRDT_DATA_BYTE_COUNT_MAX,
7214 .max_host_blocked = 1,
7215 .track_queue_depth = 1,
7216 .sdev_groups = ufshcd_driver_groups,
7217 .dma_boundary = PAGE_SIZE - 1,
7218 .rpm_autosuspend_delay = RPM_AUTOSUSPEND_DELAY_MS,
7221 static int ufshcd_config_vreg_load(struct device *dev, struct ufs_vreg *vreg,
7222 int ua)
7224 int ret;
7226 if (!vreg)
7227 return 0;
7230 * "set_load" operation shall be required on those regulators
7231 * which specifically configured current limitation. Otherwise
7232 * zero max_uA may cause unexpected behavior when regulator is
7233 * enabled or set as high power mode.
7235 if (!vreg->max_uA)
7236 return 0;
7238 ret = regulator_set_load(vreg->reg, ua);
7239 if (ret < 0) {
7240 dev_err(dev, "%s: %s set load (ua=%d) failed, err=%d\n",
7241 __func__, vreg->name, ua, ret);
7244 return ret;
7247 static inline int ufshcd_config_vreg_lpm(struct ufs_hba *hba,
7248 struct ufs_vreg *vreg)
7250 return ufshcd_config_vreg_load(hba->dev, vreg, UFS_VREG_LPM_LOAD_UA);
7253 static inline int ufshcd_config_vreg_hpm(struct ufs_hba *hba,
7254 struct ufs_vreg *vreg)
7256 if (!vreg)
7257 return 0;
7259 return ufshcd_config_vreg_load(hba->dev, vreg, vreg->max_uA);
7262 static int ufshcd_config_vreg(struct device *dev,
7263 struct ufs_vreg *vreg, bool on)
7265 int ret = 0;
7266 struct regulator *reg;
7267 const char *name;
7268 int min_uV, uA_load;
7270 BUG_ON(!vreg);
7272 reg = vreg->reg;
7273 name = vreg->name;
7275 if (regulator_count_voltages(reg) > 0) {
7276 uA_load = on ? vreg->max_uA : 0;
7277 ret = ufshcd_config_vreg_load(dev, vreg, uA_load);
7278 if (ret)
7279 goto out;
7281 if (vreg->min_uV && vreg->max_uV) {
7282 min_uV = on ? vreg->min_uV : 0;
7283 ret = regulator_set_voltage(reg, min_uV, vreg->max_uV);
7284 if (ret) {
7285 dev_err(dev,
7286 "%s: %s set voltage failed, err=%d\n",
7287 __func__, name, ret);
7288 goto out;
7292 out:
7293 return ret;
7296 static int ufshcd_enable_vreg(struct device *dev, struct ufs_vreg *vreg)
7298 int ret = 0;
7300 if (!vreg || vreg->enabled)
7301 goto out;
7303 ret = ufshcd_config_vreg(dev, vreg, true);
7304 if (!ret)
7305 ret = regulator_enable(vreg->reg);
7307 if (!ret)
7308 vreg->enabled = true;
7309 else
7310 dev_err(dev, "%s: %s enable failed, err=%d\n",
7311 __func__, vreg->name, ret);
7312 out:
7313 return ret;
7316 static int ufshcd_disable_vreg(struct device *dev, struct ufs_vreg *vreg)
7318 int ret = 0;
7320 if (!vreg || !vreg->enabled)
7321 goto out;
7323 ret = regulator_disable(vreg->reg);
7325 if (!ret) {
7326 /* ignore errors on applying disable config */
7327 ufshcd_config_vreg(dev, vreg, false);
7328 vreg->enabled = false;
7329 } else {
7330 dev_err(dev, "%s: %s disable failed, err=%d\n",
7331 __func__, vreg->name, ret);
7333 out:
7334 return ret;
7337 static int ufshcd_setup_vreg(struct ufs_hba *hba, bool on)
7339 int ret = 0;
7340 struct device *dev = hba->dev;
7341 struct ufs_vreg_info *info = &hba->vreg_info;
7343 ret = ufshcd_toggle_vreg(dev, info->vcc, on);
7344 if (ret)
7345 goto out;
7347 ret = ufshcd_toggle_vreg(dev, info->vccq, on);
7348 if (ret)
7349 goto out;
7351 ret = ufshcd_toggle_vreg(dev, info->vccq2, on);
7352 if (ret)
7353 goto out;
7355 out:
7356 if (ret) {
7357 ufshcd_toggle_vreg(dev, info->vccq2, false);
7358 ufshcd_toggle_vreg(dev, info->vccq, false);
7359 ufshcd_toggle_vreg(dev, info->vcc, false);
7361 return ret;
7364 static int ufshcd_setup_hba_vreg(struct ufs_hba *hba, bool on)
7366 struct ufs_vreg_info *info = &hba->vreg_info;
7368 return ufshcd_toggle_vreg(hba->dev, info->vdd_hba, on);
7371 static int ufshcd_get_vreg(struct device *dev, struct ufs_vreg *vreg)
7373 int ret = 0;
7375 if (!vreg)
7376 goto out;
7378 vreg->reg = devm_regulator_get(dev, vreg->name);
7379 if (IS_ERR(vreg->reg)) {
7380 ret = PTR_ERR(vreg->reg);
7381 dev_err(dev, "%s: %s get failed, err=%d\n",
7382 __func__, vreg->name, ret);
7384 out:
7385 return ret;
7388 static int ufshcd_init_vreg(struct ufs_hba *hba)
7390 int ret = 0;
7391 struct device *dev = hba->dev;
7392 struct ufs_vreg_info *info = &hba->vreg_info;
7394 ret = ufshcd_get_vreg(dev, info->vcc);
7395 if (ret)
7396 goto out;
7398 ret = ufshcd_get_vreg(dev, info->vccq);
7399 if (ret)
7400 goto out;
7402 ret = ufshcd_get_vreg(dev, info->vccq2);
7403 out:
7404 return ret;
7407 static int ufshcd_init_hba_vreg(struct ufs_hba *hba)
7409 struct ufs_vreg_info *info = &hba->vreg_info;
7411 if (info)
7412 return ufshcd_get_vreg(hba->dev, info->vdd_hba);
7414 return 0;
7417 static int __ufshcd_setup_clocks(struct ufs_hba *hba, bool on,
7418 bool skip_ref_clk)
7420 int ret = 0;
7421 struct ufs_clk_info *clki;
7422 struct list_head *head = &hba->clk_list_head;
7423 unsigned long flags;
7424 ktime_t start = ktime_get();
7425 bool clk_state_changed = false;
7427 if (list_empty(head))
7428 goto out;
7430 ret = ufshcd_vops_setup_clocks(hba, on, PRE_CHANGE);
7431 if (ret)
7432 return ret;
7434 list_for_each_entry(clki, head, list) {
7435 if (!IS_ERR_OR_NULL(clki->clk)) {
7436 if (skip_ref_clk && !strcmp(clki->name, "ref_clk"))
7437 continue;
7439 clk_state_changed = on ^ clki->enabled;
7440 if (on && !clki->enabled) {
7441 ret = clk_prepare_enable(clki->clk);
7442 if (ret) {
7443 dev_err(hba->dev, "%s: %s prepare enable failed, %d\n",
7444 __func__, clki->name, ret);
7445 goto out;
7447 } else if (!on && clki->enabled) {
7448 clk_disable_unprepare(clki->clk);
7450 clki->enabled = on;
7451 dev_dbg(hba->dev, "%s: clk: %s %sabled\n", __func__,
7452 clki->name, on ? "en" : "dis");
7456 ret = ufshcd_vops_setup_clocks(hba, on, POST_CHANGE);
7457 if (ret)
7458 return ret;
7460 out:
7461 if (ret) {
7462 list_for_each_entry(clki, head, list) {
7463 if (!IS_ERR_OR_NULL(clki->clk) && clki->enabled)
7464 clk_disable_unprepare(clki->clk);
7466 } else if (!ret && on) {
7467 spin_lock_irqsave(hba->host->host_lock, flags);
7468 hba->clk_gating.state = CLKS_ON;
7469 trace_ufshcd_clk_gating(dev_name(hba->dev),
7470 hba->clk_gating.state);
7471 spin_unlock_irqrestore(hba->host->host_lock, flags);
7474 if (clk_state_changed)
7475 trace_ufshcd_profile_clk_gating(dev_name(hba->dev),
7476 (on ? "on" : "off"),
7477 ktime_to_us(ktime_sub(ktime_get(), start)), ret);
7478 return ret;
7481 static int ufshcd_setup_clocks(struct ufs_hba *hba, bool on)
7483 return __ufshcd_setup_clocks(hba, on, false);
7486 static int ufshcd_init_clocks(struct ufs_hba *hba)
7488 int ret = 0;
7489 struct ufs_clk_info *clki;
7490 struct device *dev = hba->dev;
7491 struct list_head *head = &hba->clk_list_head;
7493 if (list_empty(head))
7494 goto out;
7496 list_for_each_entry(clki, head, list) {
7497 if (!clki->name)
7498 continue;
7500 clki->clk = devm_clk_get(dev, clki->name);
7501 if (IS_ERR(clki->clk)) {
7502 ret = PTR_ERR(clki->clk);
7503 dev_err(dev, "%s: %s clk get failed, %d\n",
7504 __func__, clki->name, ret);
7505 goto out;
7509 * Parse device ref clk freq as per device tree "ref_clk".
7510 * Default dev_ref_clk_freq is set to REF_CLK_FREQ_INVAL
7511 * in ufshcd_alloc_host().
7513 if (!strcmp(clki->name, "ref_clk"))
7514 ufshcd_parse_dev_ref_clk_freq(hba, clki->clk);
7516 if (clki->max_freq) {
7517 ret = clk_set_rate(clki->clk, clki->max_freq);
7518 if (ret) {
7519 dev_err(hba->dev, "%s: %s clk set rate(%dHz) failed, %d\n",
7520 __func__, clki->name,
7521 clki->max_freq, ret);
7522 goto out;
7524 clki->curr_freq = clki->max_freq;
7526 dev_dbg(dev, "%s: clk: %s, rate: %lu\n", __func__,
7527 clki->name, clk_get_rate(clki->clk));
7529 out:
7530 return ret;
7533 static int ufshcd_variant_hba_init(struct ufs_hba *hba)
7535 int err = 0;
7537 if (!hba->vops)
7538 goto out;
7540 err = ufshcd_vops_init(hba);
7541 if (err)
7542 goto out;
7544 err = ufshcd_vops_setup_regulators(hba, true);
7545 if (err)
7546 goto out_exit;
7548 goto out;
7550 out_exit:
7551 ufshcd_vops_exit(hba);
7552 out:
7553 if (err)
7554 dev_err(hba->dev, "%s: variant %s init failed err %d\n",
7555 __func__, ufshcd_get_var_name(hba), err);
7556 return err;
7559 static void ufshcd_variant_hba_exit(struct ufs_hba *hba)
7561 if (!hba->vops)
7562 return;
7564 ufshcd_vops_setup_regulators(hba, false);
7566 ufshcd_vops_exit(hba);
7569 static int ufshcd_hba_init(struct ufs_hba *hba)
7571 int err;
7574 * Handle host controller power separately from the UFS device power
7575 * rails as it will help controlling the UFS host controller power
7576 * collapse easily which is different than UFS device power collapse.
7577 * Also, enable the host controller power before we go ahead with rest
7578 * of the initialization here.
7580 err = ufshcd_init_hba_vreg(hba);
7581 if (err)
7582 goto out;
7584 err = ufshcd_setup_hba_vreg(hba, true);
7585 if (err)
7586 goto out;
7588 err = ufshcd_init_clocks(hba);
7589 if (err)
7590 goto out_disable_hba_vreg;
7592 err = ufshcd_setup_clocks(hba, true);
7593 if (err)
7594 goto out_disable_hba_vreg;
7596 err = ufshcd_init_vreg(hba);
7597 if (err)
7598 goto out_disable_clks;
7600 err = ufshcd_setup_vreg(hba, true);
7601 if (err)
7602 goto out_disable_clks;
7604 err = ufshcd_variant_hba_init(hba);
7605 if (err)
7606 goto out_disable_vreg;
7608 hba->is_powered = true;
7609 goto out;
7611 out_disable_vreg:
7612 ufshcd_setup_vreg(hba, false);
7613 out_disable_clks:
7614 ufshcd_setup_clocks(hba, false);
7615 out_disable_hba_vreg:
7616 ufshcd_setup_hba_vreg(hba, false);
7617 out:
7618 return err;
7621 static void ufshcd_hba_exit(struct ufs_hba *hba)
7623 if (hba->is_powered) {
7624 ufshcd_variant_hba_exit(hba);
7625 ufshcd_setup_vreg(hba, false);
7626 ufshcd_suspend_clkscaling(hba);
7627 if (ufshcd_is_clkscaling_supported(hba))
7628 if (hba->devfreq)
7629 ufshcd_suspend_clkscaling(hba);
7630 ufshcd_setup_clocks(hba, false);
7631 ufshcd_setup_hba_vreg(hba, false);
7632 hba->is_powered = false;
7633 ufs_put_device_desc(hba);
7637 static int
7638 ufshcd_send_request_sense(struct ufs_hba *hba, struct scsi_device *sdp)
7640 unsigned char cmd[6] = {REQUEST_SENSE,
7644 UFS_SENSE_SIZE,
7646 char *buffer;
7647 int ret;
7649 buffer = kzalloc(UFS_SENSE_SIZE, GFP_KERNEL);
7650 if (!buffer) {
7651 ret = -ENOMEM;
7652 goto out;
7655 ret = scsi_execute(sdp, cmd, DMA_FROM_DEVICE, buffer,
7656 UFS_SENSE_SIZE, NULL, NULL,
7657 msecs_to_jiffies(1000), 3, 0, RQF_PM, NULL);
7658 if (ret)
7659 pr_err("%s: failed with err %d\n", __func__, ret);
7661 kfree(buffer);
7662 out:
7663 return ret;
7667 * ufshcd_set_dev_pwr_mode - sends START STOP UNIT command to set device
7668 * power mode
7669 * @hba: per adapter instance
7670 * @pwr_mode: device power mode to set
7672 * Returns 0 if requested power mode is set successfully
7673 * Returns non-zero if failed to set the requested power mode
7675 static int ufshcd_set_dev_pwr_mode(struct ufs_hba *hba,
7676 enum ufs_dev_pwr_mode pwr_mode)
7678 unsigned char cmd[6] = { START_STOP };
7679 struct scsi_sense_hdr sshdr;
7680 struct scsi_device *sdp;
7681 unsigned long flags;
7682 int ret;
7684 spin_lock_irqsave(hba->host->host_lock, flags);
7685 sdp = hba->sdev_ufs_device;
7686 if (sdp) {
7687 ret = scsi_device_get(sdp);
7688 if (!ret && !scsi_device_online(sdp)) {
7689 ret = -ENODEV;
7690 scsi_device_put(sdp);
7692 } else {
7693 ret = -ENODEV;
7695 spin_unlock_irqrestore(hba->host->host_lock, flags);
7697 if (ret)
7698 return ret;
7701 * If scsi commands fail, the scsi mid-layer schedules scsi error-
7702 * handling, which would wait for host to be resumed. Since we know
7703 * we are functional while we are here, skip host resume in error
7704 * handling context.
7706 hba->host->eh_noresume = 1;
7707 if (hba->wlun_dev_clr_ua) {
7708 ret = ufshcd_send_request_sense(hba, sdp);
7709 if (ret)
7710 goto out;
7711 /* Unit attention condition is cleared now */
7712 hba->wlun_dev_clr_ua = false;
7715 cmd[4] = pwr_mode << 4;
7718 * Current function would be generally called from the power management
7719 * callbacks hence set the RQF_PM flag so that it doesn't resume the
7720 * already suspended childs.
7722 ret = scsi_execute(sdp, cmd, DMA_NONE, NULL, 0, NULL, &sshdr,
7723 START_STOP_TIMEOUT, 0, 0, RQF_PM, NULL);
7724 if (ret) {
7725 sdev_printk(KERN_WARNING, sdp,
7726 "START_STOP failed for power mode: %d, result %x\n",
7727 pwr_mode, ret);
7728 if (driver_byte(ret) == DRIVER_SENSE)
7729 scsi_print_sense_hdr(sdp, NULL, &sshdr);
7732 if (!ret)
7733 hba->curr_dev_pwr_mode = pwr_mode;
7734 out:
7735 scsi_device_put(sdp);
7736 hba->host->eh_noresume = 0;
7737 return ret;
7740 static int ufshcd_link_state_transition(struct ufs_hba *hba,
7741 enum uic_link_state req_link_state,
7742 int check_for_bkops)
7744 int ret = 0;
7746 if (req_link_state == hba->uic_link_state)
7747 return 0;
7749 if (req_link_state == UIC_LINK_HIBERN8_STATE) {
7750 ret = ufshcd_uic_hibern8_enter(hba);
7751 if (!ret)
7752 ufshcd_set_link_hibern8(hba);
7753 else
7754 goto out;
7757 * If autobkops is enabled, link can't be turned off because
7758 * turning off the link would also turn off the device.
7760 else if ((req_link_state == UIC_LINK_OFF_STATE) &&
7761 (!check_for_bkops || !hba->auto_bkops_enabled)) {
7763 * Let's make sure that link is in low power mode, we are doing
7764 * this currently by putting the link in Hibern8. Otherway to
7765 * put the link in low power mode is to send the DME end point
7766 * to device and then send the DME reset command to local
7767 * unipro. But putting the link in hibern8 is much faster.
7769 ret = ufshcd_uic_hibern8_enter(hba);
7770 if (ret)
7771 goto out;
7773 * Change controller state to "reset state" which
7774 * should also put the link in off/reset state
7776 ufshcd_hba_stop(hba, true);
7778 * TODO: Check if we need any delay to make sure that
7779 * controller is reset
7781 ufshcd_set_link_off(hba);
7784 out:
7785 return ret;
7788 static void ufshcd_vreg_set_lpm(struct ufs_hba *hba)
7791 * It seems some UFS devices may keep drawing more than sleep current
7792 * (atleast for 500us) from UFS rails (especially from VCCQ rail).
7793 * To avoid this situation, add 2ms delay before putting these UFS
7794 * rails in LPM mode.
7796 if (!ufshcd_is_link_active(hba) &&
7797 hba->dev_quirks & UFS_DEVICE_QUIRK_DELAY_BEFORE_LPM)
7798 usleep_range(2000, 2100);
7801 * If UFS device is either in UFS_Sleep turn off VCC rail to save some
7802 * power.
7804 * If UFS device and link is in OFF state, all power supplies (VCC,
7805 * VCCQ, VCCQ2) can be turned off if power on write protect is not
7806 * required. If UFS link is inactive (Hibern8 or OFF state) and device
7807 * is in sleep state, put VCCQ & VCCQ2 rails in LPM mode.
7809 * Ignore the error returned by ufshcd_toggle_vreg() as device is anyway
7810 * in low power state which would save some power.
7812 if (ufshcd_is_ufs_dev_poweroff(hba) && ufshcd_is_link_off(hba) &&
7813 !hba->dev_info.is_lu_power_on_wp) {
7814 ufshcd_setup_vreg(hba, false);
7815 } else if (!ufshcd_is_ufs_dev_active(hba)) {
7816 ufshcd_toggle_vreg(hba->dev, hba->vreg_info.vcc, false);
7817 if (!ufshcd_is_link_active(hba)) {
7818 ufshcd_config_vreg_lpm(hba, hba->vreg_info.vccq);
7819 ufshcd_config_vreg_lpm(hba, hba->vreg_info.vccq2);
7824 static int ufshcd_vreg_set_hpm(struct ufs_hba *hba)
7826 int ret = 0;
7828 if (ufshcd_is_ufs_dev_poweroff(hba) && ufshcd_is_link_off(hba) &&
7829 !hba->dev_info.is_lu_power_on_wp) {
7830 ret = ufshcd_setup_vreg(hba, true);
7831 } else if (!ufshcd_is_ufs_dev_active(hba)) {
7832 if (!ret && !ufshcd_is_link_active(hba)) {
7833 ret = ufshcd_config_vreg_hpm(hba, hba->vreg_info.vccq);
7834 if (ret)
7835 goto vcc_disable;
7836 ret = ufshcd_config_vreg_hpm(hba, hba->vreg_info.vccq2);
7837 if (ret)
7838 goto vccq_lpm;
7840 ret = ufshcd_toggle_vreg(hba->dev, hba->vreg_info.vcc, true);
7842 goto out;
7844 vccq_lpm:
7845 ufshcd_config_vreg_lpm(hba, hba->vreg_info.vccq);
7846 vcc_disable:
7847 ufshcd_toggle_vreg(hba->dev, hba->vreg_info.vcc, false);
7848 out:
7849 return ret;
7852 static void ufshcd_hba_vreg_set_lpm(struct ufs_hba *hba)
7854 if (ufshcd_is_link_off(hba))
7855 ufshcd_setup_hba_vreg(hba, false);
7858 static void ufshcd_hba_vreg_set_hpm(struct ufs_hba *hba)
7860 if (ufshcd_is_link_off(hba))
7861 ufshcd_setup_hba_vreg(hba, true);
7865 * ufshcd_suspend - helper function for suspend operations
7866 * @hba: per adapter instance
7867 * @pm_op: desired low power operation type
7869 * This function will try to put the UFS device and link into low power
7870 * mode based on the "rpm_lvl" (Runtime PM level) or "spm_lvl"
7871 * (System PM level).
7873 * If this function is called during shutdown, it will make sure that
7874 * both UFS device and UFS link is powered off.
7876 * NOTE: UFS device & link must be active before we enter in this function.
7878 * Returns 0 for success and non-zero for failure
7880 static int ufshcd_suspend(struct ufs_hba *hba, enum ufs_pm_op pm_op)
7882 int ret = 0;
7883 enum ufs_pm_level pm_lvl;
7884 enum ufs_dev_pwr_mode req_dev_pwr_mode;
7885 enum uic_link_state req_link_state;
7887 hba->pm_op_in_progress = 1;
7888 if (!ufshcd_is_shutdown_pm(pm_op)) {
7889 pm_lvl = ufshcd_is_runtime_pm(pm_op) ?
7890 hba->rpm_lvl : hba->spm_lvl;
7891 req_dev_pwr_mode = ufs_get_pm_lvl_to_dev_pwr_mode(pm_lvl);
7892 req_link_state = ufs_get_pm_lvl_to_link_pwr_state(pm_lvl);
7893 } else {
7894 req_dev_pwr_mode = UFS_POWERDOWN_PWR_MODE;
7895 req_link_state = UIC_LINK_OFF_STATE;
7899 * If we can't transition into any of the low power modes
7900 * just gate the clocks.
7902 ufshcd_hold(hba, false);
7903 hba->clk_gating.is_suspended = true;
7905 if (hba->clk_scaling.is_allowed) {
7906 cancel_work_sync(&hba->clk_scaling.suspend_work);
7907 cancel_work_sync(&hba->clk_scaling.resume_work);
7908 ufshcd_suspend_clkscaling(hba);
7911 if (req_dev_pwr_mode == UFS_ACTIVE_PWR_MODE &&
7912 req_link_state == UIC_LINK_ACTIVE_STATE) {
7913 goto disable_clks;
7916 if ((req_dev_pwr_mode == hba->curr_dev_pwr_mode) &&
7917 (req_link_state == hba->uic_link_state))
7918 goto enable_gating;
7920 /* UFS device & link must be active before we enter in this function */
7921 if (!ufshcd_is_ufs_dev_active(hba) || !ufshcd_is_link_active(hba)) {
7922 ret = -EINVAL;
7923 goto enable_gating;
7926 if (ufshcd_is_runtime_pm(pm_op)) {
7927 if (ufshcd_can_autobkops_during_suspend(hba)) {
7929 * The device is idle with no requests in the queue,
7930 * allow background operations if bkops status shows
7931 * that performance might be impacted.
7933 ret = ufshcd_urgent_bkops(hba);
7934 if (ret)
7935 goto enable_gating;
7936 } else {
7937 /* make sure that auto bkops is disabled */
7938 ufshcd_disable_auto_bkops(hba);
7942 if ((req_dev_pwr_mode != hba->curr_dev_pwr_mode) &&
7943 ((ufshcd_is_runtime_pm(pm_op) && !hba->auto_bkops_enabled) ||
7944 !ufshcd_is_runtime_pm(pm_op))) {
7945 /* ensure that bkops is disabled */
7946 ufshcd_disable_auto_bkops(hba);
7947 ret = ufshcd_set_dev_pwr_mode(hba, req_dev_pwr_mode);
7948 if (ret)
7949 goto enable_gating;
7952 flush_work(&hba->eeh_work);
7953 ret = ufshcd_link_state_transition(hba, req_link_state, 1);
7954 if (ret)
7955 goto set_dev_active;
7957 ufshcd_vreg_set_lpm(hba);
7959 disable_clks:
7961 * Call vendor specific suspend callback. As these callbacks may access
7962 * vendor specific host controller register space call them before the
7963 * host clocks are ON.
7965 ret = ufshcd_vops_suspend(hba, pm_op);
7966 if (ret)
7967 goto set_link_active;
7969 * Disable the host irq as host controller as there won't be any
7970 * host controller transaction expected till resume.
7972 ufshcd_disable_irq(hba);
7974 if (!ufshcd_is_link_active(hba))
7975 ufshcd_setup_clocks(hba, false);
7976 else
7977 /* If link is active, device ref_clk can't be switched off */
7978 __ufshcd_setup_clocks(hba, false, true);
7980 hba->clk_gating.state = CLKS_OFF;
7981 trace_ufshcd_clk_gating(dev_name(hba->dev), hba->clk_gating.state);
7983 /* Put the host controller in low power mode if possible */
7984 ufshcd_hba_vreg_set_lpm(hba);
7985 goto out;
7987 set_link_active:
7988 if (hba->clk_scaling.is_allowed)
7989 ufshcd_resume_clkscaling(hba);
7990 ufshcd_vreg_set_hpm(hba);
7991 if (ufshcd_is_link_hibern8(hba) && !ufshcd_uic_hibern8_exit(hba))
7992 ufshcd_set_link_active(hba);
7993 else if (ufshcd_is_link_off(hba))
7994 ufshcd_host_reset_and_restore(hba);
7995 set_dev_active:
7996 if (!ufshcd_set_dev_pwr_mode(hba, UFS_ACTIVE_PWR_MODE))
7997 ufshcd_disable_auto_bkops(hba);
7998 enable_gating:
7999 if (hba->clk_scaling.is_allowed)
8000 ufshcd_resume_clkscaling(hba);
8001 hba->clk_gating.is_suspended = false;
8002 ufshcd_release(hba);
8003 out:
8004 hba->pm_op_in_progress = 0;
8005 if (ret)
8006 ufshcd_update_reg_hist(&hba->ufs_stats.suspend_err, (u32)ret);
8007 return ret;
8011 * ufshcd_resume - helper function for resume operations
8012 * @hba: per adapter instance
8013 * @pm_op: runtime PM or system PM
8015 * This function basically brings the UFS device, UniPro link and controller
8016 * to active state.
8018 * Returns 0 for success and non-zero for failure
8020 static int ufshcd_resume(struct ufs_hba *hba, enum ufs_pm_op pm_op)
8022 int ret;
8023 enum uic_link_state old_link_state;
8025 hba->pm_op_in_progress = 1;
8026 old_link_state = hba->uic_link_state;
8028 ufshcd_hba_vreg_set_hpm(hba);
8029 /* Make sure clocks are enabled before accessing controller */
8030 ret = ufshcd_setup_clocks(hba, true);
8031 if (ret)
8032 goto out;
8034 /* enable the host irq as host controller would be active soon */
8035 ufshcd_enable_irq(hba);
8037 ret = ufshcd_vreg_set_hpm(hba);
8038 if (ret)
8039 goto disable_irq_and_vops_clks;
8042 * Call vendor specific resume callback. As these callbacks may access
8043 * vendor specific host controller register space call them when the
8044 * host clocks are ON.
8046 ret = ufshcd_vops_resume(hba, pm_op);
8047 if (ret)
8048 goto disable_vreg;
8050 if (ufshcd_is_link_hibern8(hba)) {
8051 ret = ufshcd_uic_hibern8_exit(hba);
8052 if (!ret)
8053 ufshcd_set_link_active(hba);
8054 else
8055 goto vendor_suspend;
8056 } else if (ufshcd_is_link_off(hba)) {
8057 ret = ufshcd_host_reset_and_restore(hba);
8059 * ufshcd_host_reset_and_restore() should have already
8060 * set the link state as active
8062 if (ret || !ufshcd_is_link_active(hba))
8063 goto vendor_suspend;
8066 if (!ufshcd_is_ufs_dev_active(hba)) {
8067 ret = ufshcd_set_dev_pwr_mode(hba, UFS_ACTIVE_PWR_MODE);
8068 if (ret)
8069 goto set_old_link_state;
8072 if (ufshcd_keep_autobkops_enabled_except_suspend(hba))
8073 ufshcd_enable_auto_bkops(hba);
8074 else
8076 * If BKOPs operations are urgently needed at this moment then
8077 * keep auto-bkops enabled or else disable it.
8079 ufshcd_urgent_bkops(hba);
8081 hba->clk_gating.is_suspended = false;
8083 if (hba->clk_scaling.is_allowed)
8084 ufshcd_resume_clkscaling(hba);
8086 /* Enable Auto-Hibernate if configured */
8087 ufshcd_auto_hibern8_enable(hba);
8089 /* Schedule clock gating in case of no access to UFS device yet */
8090 ufshcd_release(hba);
8092 goto out;
8094 set_old_link_state:
8095 ufshcd_link_state_transition(hba, old_link_state, 0);
8096 vendor_suspend:
8097 ufshcd_vops_suspend(hba, pm_op);
8098 disable_vreg:
8099 ufshcd_vreg_set_lpm(hba);
8100 disable_irq_and_vops_clks:
8101 ufshcd_disable_irq(hba);
8102 if (hba->clk_scaling.is_allowed)
8103 ufshcd_suspend_clkscaling(hba);
8104 ufshcd_setup_clocks(hba, false);
8105 out:
8106 hba->pm_op_in_progress = 0;
8107 if (ret)
8108 ufshcd_update_reg_hist(&hba->ufs_stats.resume_err, (u32)ret);
8109 return ret;
8113 * ufshcd_system_suspend - system suspend routine
8114 * @hba: per adapter instance
8116 * Check the description of ufshcd_suspend() function for more details.
8118 * Returns 0 for success and non-zero for failure
8120 int ufshcd_system_suspend(struct ufs_hba *hba)
8122 int ret = 0;
8123 ktime_t start = ktime_get();
8125 if (!hba || !hba->is_powered)
8126 return 0;
8128 if ((ufs_get_pm_lvl_to_dev_pwr_mode(hba->spm_lvl) ==
8129 hba->curr_dev_pwr_mode) &&
8130 (ufs_get_pm_lvl_to_link_pwr_state(hba->spm_lvl) ==
8131 hba->uic_link_state))
8132 goto out;
8134 if (pm_runtime_suspended(hba->dev)) {
8136 * UFS device and/or UFS link low power states during runtime
8137 * suspend seems to be different than what is expected during
8138 * system suspend. Hence runtime resume the devic & link and
8139 * let the system suspend low power states to take effect.
8140 * TODO: If resume takes longer time, we might have optimize
8141 * it in future by not resuming everything if possible.
8143 ret = ufshcd_runtime_resume(hba);
8144 if (ret)
8145 goto out;
8148 ret = ufshcd_suspend(hba, UFS_SYSTEM_PM);
8149 out:
8150 trace_ufshcd_system_suspend(dev_name(hba->dev), ret,
8151 ktime_to_us(ktime_sub(ktime_get(), start)),
8152 hba->curr_dev_pwr_mode, hba->uic_link_state);
8153 if (!ret)
8154 hba->is_sys_suspended = true;
8155 return ret;
8157 EXPORT_SYMBOL(ufshcd_system_suspend);
8160 * ufshcd_system_resume - system resume routine
8161 * @hba: per adapter instance
8163 * Returns 0 for success and non-zero for failure
8166 int ufshcd_system_resume(struct ufs_hba *hba)
8168 int ret = 0;
8169 ktime_t start = ktime_get();
8171 if (!hba)
8172 return -EINVAL;
8174 if (!hba->is_powered || pm_runtime_suspended(hba->dev))
8176 * Let the runtime resume take care of resuming
8177 * if runtime suspended.
8179 goto out;
8180 else
8181 ret = ufshcd_resume(hba, UFS_SYSTEM_PM);
8182 out:
8183 trace_ufshcd_system_resume(dev_name(hba->dev), ret,
8184 ktime_to_us(ktime_sub(ktime_get(), start)),
8185 hba->curr_dev_pwr_mode, hba->uic_link_state);
8186 if (!ret)
8187 hba->is_sys_suspended = false;
8188 return ret;
8190 EXPORT_SYMBOL(ufshcd_system_resume);
8193 * ufshcd_runtime_suspend - runtime suspend routine
8194 * @hba: per adapter instance
8196 * Check the description of ufshcd_suspend() function for more details.
8198 * Returns 0 for success and non-zero for failure
8200 int ufshcd_runtime_suspend(struct ufs_hba *hba)
8202 int ret = 0;
8203 ktime_t start = ktime_get();
8205 if (!hba)
8206 return -EINVAL;
8208 if (!hba->is_powered)
8209 goto out;
8210 else
8211 ret = ufshcd_suspend(hba, UFS_RUNTIME_PM);
8212 out:
8213 trace_ufshcd_runtime_suspend(dev_name(hba->dev), ret,
8214 ktime_to_us(ktime_sub(ktime_get(), start)),
8215 hba->curr_dev_pwr_mode, hba->uic_link_state);
8216 return ret;
8218 EXPORT_SYMBOL(ufshcd_runtime_suspend);
8221 * ufshcd_runtime_resume - runtime resume routine
8222 * @hba: per adapter instance
8224 * This function basically brings the UFS device, UniPro link and controller
8225 * to active state. Following operations are done in this function:
8227 * 1. Turn on all the controller related clocks
8228 * 2. Bring the UniPro link out of Hibernate state
8229 * 3. If UFS device is in sleep state, turn ON VCC rail and bring the UFS device
8230 * to active state.
8231 * 4. If auto-bkops is enabled on the device, disable it.
8233 * So following would be the possible power state after this function return
8234 * successfully:
8235 * S1: UFS device in Active state with VCC rail ON
8236 * UniPro link in Active state
8237 * All the UFS/UniPro controller clocks are ON
8239 * Returns 0 for success and non-zero for failure
8241 int ufshcd_runtime_resume(struct ufs_hba *hba)
8243 int ret = 0;
8244 ktime_t start = ktime_get();
8246 if (!hba)
8247 return -EINVAL;
8249 if (!hba->is_powered)
8250 goto out;
8251 else
8252 ret = ufshcd_resume(hba, UFS_RUNTIME_PM);
8253 out:
8254 trace_ufshcd_runtime_resume(dev_name(hba->dev), ret,
8255 ktime_to_us(ktime_sub(ktime_get(), start)),
8256 hba->curr_dev_pwr_mode, hba->uic_link_state);
8257 return ret;
8259 EXPORT_SYMBOL(ufshcd_runtime_resume);
8261 int ufshcd_runtime_idle(struct ufs_hba *hba)
8263 return 0;
8265 EXPORT_SYMBOL(ufshcd_runtime_idle);
8268 * ufshcd_shutdown - shutdown routine
8269 * @hba: per adapter instance
8271 * This function would power off both UFS device and UFS link.
8273 * Returns 0 always to allow force shutdown even in case of errors.
8275 int ufshcd_shutdown(struct ufs_hba *hba)
8277 int ret = 0;
8279 if (!hba->is_powered)
8280 goto out;
8282 if (ufshcd_is_ufs_dev_poweroff(hba) && ufshcd_is_link_off(hba))
8283 goto out;
8285 if (pm_runtime_suspended(hba->dev)) {
8286 ret = ufshcd_runtime_resume(hba);
8287 if (ret)
8288 goto out;
8291 ret = ufshcd_suspend(hba, UFS_SHUTDOWN_PM);
8292 out:
8293 if (ret)
8294 dev_err(hba->dev, "%s failed, err %d\n", __func__, ret);
8295 /* allow force shutdown even in case of errors */
8296 return 0;
8298 EXPORT_SYMBOL(ufshcd_shutdown);
8301 * ufshcd_remove - de-allocate SCSI host and host memory space
8302 * data structure memory
8303 * @hba: per adapter instance
8305 void ufshcd_remove(struct ufs_hba *hba)
8307 ufs_bsg_remove(hba);
8308 ufs_sysfs_remove_nodes(hba->dev);
8309 blk_cleanup_queue(hba->tmf_queue);
8310 blk_mq_free_tag_set(&hba->tmf_tag_set);
8311 blk_cleanup_queue(hba->cmd_queue);
8312 scsi_remove_host(hba->host);
8313 /* disable interrupts */
8314 ufshcd_disable_intr(hba, hba->intr_mask);
8315 ufshcd_hba_stop(hba, true);
8317 ufshcd_exit_clk_scaling(hba);
8318 ufshcd_exit_clk_gating(hba);
8319 if (ufshcd_is_clkscaling_supported(hba))
8320 device_remove_file(hba->dev, &hba->clk_scaling.enable_attr);
8321 ufshcd_hba_exit(hba);
8323 EXPORT_SYMBOL_GPL(ufshcd_remove);
8326 * ufshcd_dealloc_host - deallocate Host Bus Adapter (HBA)
8327 * @hba: pointer to Host Bus Adapter (HBA)
8329 void ufshcd_dealloc_host(struct ufs_hba *hba)
8331 scsi_host_put(hba->host);
8333 EXPORT_SYMBOL_GPL(ufshcd_dealloc_host);
8336 * ufshcd_set_dma_mask - Set dma mask based on the controller
8337 * addressing capability
8338 * @hba: per adapter instance
8340 * Returns 0 for success, non-zero for failure
8342 static int ufshcd_set_dma_mask(struct ufs_hba *hba)
8344 if (hba->capabilities & MASK_64_ADDRESSING_SUPPORT) {
8345 if (!dma_set_mask_and_coherent(hba->dev, DMA_BIT_MASK(64)))
8346 return 0;
8348 return dma_set_mask_and_coherent(hba->dev, DMA_BIT_MASK(32));
8352 * ufshcd_alloc_host - allocate Host Bus Adapter (HBA)
8353 * @dev: pointer to device handle
8354 * @hba_handle: driver private handle
8355 * Returns 0 on success, non-zero value on failure
8357 int ufshcd_alloc_host(struct device *dev, struct ufs_hba **hba_handle)
8359 struct Scsi_Host *host;
8360 struct ufs_hba *hba;
8361 int err = 0;
8363 if (!dev) {
8364 dev_err(dev,
8365 "Invalid memory reference for dev is NULL\n");
8366 err = -ENODEV;
8367 goto out_error;
8370 host = scsi_host_alloc(&ufshcd_driver_template,
8371 sizeof(struct ufs_hba));
8372 if (!host) {
8373 dev_err(dev, "scsi_host_alloc failed\n");
8374 err = -ENOMEM;
8375 goto out_error;
8377 hba = shost_priv(host);
8378 hba->host = host;
8379 hba->dev = dev;
8380 *hba_handle = hba;
8381 hba->dev_ref_clk_freq = REF_CLK_FREQ_INVAL;
8383 INIT_LIST_HEAD(&hba->clk_list_head);
8385 out_error:
8386 return err;
8388 EXPORT_SYMBOL(ufshcd_alloc_host);
8390 /* This function exists because blk_mq_alloc_tag_set() requires this. */
8391 static blk_status_t ufshcd_queue_tmf(struct blk_mq_hw_ctx *hctx,
8392 const struct blk_mq_queue_data *qd)
8394 WARN_ON_ONCE(true);
8395 return BLK_STS_NOTSUPP;
8398 static const struct blk_mq_ops ufshcd_tmf_ops = {
8399 .queue_rq = ufshcd_queue_tmf,
8403 * ufshcd_init - Driver initialization routine
8404 * @hba: per-adapter instance
8405 * @mmio_base: base register address
8406 * @irq: Interrupt line of device
8407 * Returns 0 on success, non-zero value on failure
8409 int ufshcd_init(struct ufs_hba *hba, void __iomem *mmio_base, unsigned int irq)
8411 int err;
8412 struct Scsi_Host *host = hba->host;
8413 struct device *dev = hba->dev;
8415 if (!mmio_base) {
8416 dev_err(hba->dev,
8417 "Invalid memory reference for mmio_base is NULL\n");
8418 err = -ENODEV;
8419 goto out_error;
8422 hba->mmio_base = mmio_base;
8423 hba->irq = irq;
8424 hba->hba_enable_delay_us = 1000;
8426 err = ufshcd_hba_init(hba);
8427 if (err)
8428 goto out_error;
8430 /* Read capabilities registers */
8431 ufshcd_hba_capabilities(hba);
8433 /* Get UFS version supported by the controller */
8434 hba->ufs_version = ufshcd_get_ufs_version(hba);
8436 if ((hba->ufs_version != UFSHCI_VERSION_10) &&
8437 (hba->ufs_version != UFSHCI_VERSION_11) &&
8438 (hba->ufs_version != UFSHCI_VERSION_20) &&
8439 (hba->ufs_version != UFSHCI_VERSION_21))
8440 dev_err(hba->dev, "invalid UFS version 0x%x\n",
8441 hba->ufs_version);
8443 /* Get Interrupt bit mask per version */
8444 hba->intr_mask = ufshcd_get_intr_mask(hba);
8446 err = ufshcd_set_dma_mask(hba);
8447 if (err) {
8448 dev_err(hba->dev, "set dma mask failed\n");
8449 goto out_disable;
8452 /* Allocate memory for host memory space */
8453 err = ufshcd_memory_alloc(hba);
8454 if (err) {
8455 dev_err(hba->dev, "Memory allocation failed\n");
8456 goto out_disable;
8459 /* Configure LRB */
8460 ufshcd_host_memory_configure(hba);
8462 host->can_queue = hba->nutrs;
8463 host->cmd_per_lun = hba->nutrs;
8464 host->max_id = UFSHCD_MAX_ID;
8465 host->max_lun = UFS_MAX_LUNS;
8466 host->max_channel = UFSHCD_MAX_CHANNEL;
8467 host->unique_id = host->host_no;
8468 host->max_cmd_len = UFS_CDB_SIZE;
8470 hba->max_pwr_info.is_valid = false;
8472 /* Initialize work queues */
8473 INIT_WORK(&hba->eh_work, ufshcd_err_handler);
8474 INIT_WORK(&hba->eeh_work, ufshcd_exception_event_handler);
8476 /* Initialize UIC command mutex */
8477 mutex_init(&hba->uic_cmd_mutex);
8479 /* Initialize mutex for device management commands */
8480 mutex_init(&hba->dev_cmd.lock);
8482 init_rwsem(&hba->clk_scaling_lock);
8484 ufshcd_init_clk_gating(hba);
8486 ufshcd_init_clk_scaling(hba);
8489 * In order to avoid any spurious interrupt immediately after
8490 * registering UFS controller interrupt handler, clear any pending UFS
8491 * interrupt status and disable all the UFS interrupts.
8493 ufshcd_writel(hba, ufshcd_readl(hba, REG_INTERRUPT_STATUS),
8494 REG_INTERRUPT_STATUS);
8495 ufshcd_writel(hba, 0, REG_INTERRUPT_ENABLE);
8497 * Make sure that UFS interrupts are disabled and any pending interrupt
8498 * status is cleared before registering UFS interrupt handler.
8500 mb();
8502 /* IRQ registration */
8503 err = devm_request_irq(dev, irq, ufshcd_intr, IRQF_SHARED, UFSHCD, hba);
8504 if (err) {
8505 dev_err(hba->dev, "request irq failed\n");
8506 goto exit_gating;
8507 } else {
8508 hba->is_irq_enabled = true;
8511 err = scsi_add_host(host, hba->dev);
8512 if (err) {
8513 dev_err(hba->dev, "scsi_add_host failed\n");
8514 goto exit_gating;
8517 hba->cmd_queue = blk_mq_init_queue(&hba->host->tag_set);
8518 if (IS_ERR(hba->cmd_queue)) {
8519 err = PTR_ERR(hba->cmd_queue);
8520 goto out_remove_scsi_host;
8523 hba->tmf_tag_set = (struct blk_mq_tag_set) {
8524 .nr_hw_queues = 1,
8525 .queue_depth = hba->nutmrs,
8526 .ops = &ufshcd_tmf_ops,
8527 .flags = BLK_MQ_F_NO_SCHED,
8529 err = blk_mq_alloc_tag_set(&hba->tmf_tag_set);
8530 if (err < 0)
8531 goto free_cmd_queue;
8532 hba->tmf_queue = blk_mq_init_queue(&hba->tmf_tag_set);
8533 if (IS_ERR(hba->tmf_queue)) {
8534 err = PTR_ERR(hba->tmf_queue);
8535 goto free_tmf_tag_set;
8538 /* Reset the attached device */
8539 ufshcd_vops_device_reset(hba);
8541 /* Host controller enable */
8542 err = ufshcd_hba_enable(hba);
8543 if (err) {
8544 dev_err(hba->dev, "Host controller enable failed\n");
8545 ufshcd_print_host_regs(hba);
8546 ufshcd_print_host_state(hba);
8547 goto free_tmf_queue;
8551 * Set the default power management level for runtime and system PM.
8552 * Default power saving mode is to keep UFS link in Hibern8 state
8553 * and UFS device in sleep state.
8555 hba->rpm_lvl = ufs_get_desired_pm_lvl_for_dev_link_state(
8556 UFS_SLEEP_PWR_MODE,
8557 UIC_LINK_HIBERN8_STATE);
8558 hba->spm_lvl = ufs_get_desired_pm_lvl_for_dev_link_state(
8559 UFS_SLEEP_PWR_MODE,
8560 UIC_LINK_HIBERN8_STATE);
8562 /* Set the default auto-hiberate idle timer value to 150 ms */
8563 if (ufshcd_is_auto_hibern8_supported(hba) && !hba->ahit) {
8564 hba->ahit = FIELD_PREP(UFSHCI_AHIBERN8_TIMER_MASK, 150) |
8565 FIELD_PREP(UFSHCI_AHIBERN8_SCALE_MASK, 3);
8568 /* Hold auto suspend until async scan completes */
8569 pm_runtime_get_sync(dev);
8570 atomic_set(&hba->scsi_block_reqs_cnt, 0);
8572 * We are assuming that device wasn't put in sleep/power-down
8573 * state exclusively during the boot stage before kernel.
8574 * This assumption helps avoid doing link startup twice during
8575 * ufshcd_probe_hba().
8577 ufshcd_set_ufs_dev_active(hba);
8579 async_schedule(ufshcd_async_scan, hba);
8580 ufs_sysfs_add_nodes(hba->dev);
8582 return 0;
8584 free_tmf_queue:
8585 blk_cleanup_queue(hba->tmf_queue);
8586 free_tmf_tag_set:
8587 blk_mq_free_tag_set(&hba->tmf_tag_set);
8588 free_cmd_queue:
8589 blk_cleanup_queue(hba->cmd_queue);
8590 out_remove_scsi_host:
8591 scsi_remove_host(hba->host);
8592 exit_gating:
8593 ufshcd_exit_clk_scaling(hba);
8594 ufshcd_exit_clk_gating(hba);
8595 out_disable:
8596 hba->is_irq_enabled = false;
8597 ufshcd_hba_exit(hba);
8598 out_error:
8599 return err;
8601 EXPORT_SYMBOL_GPL(ufshcd_init);
8603 MODULE_AUTHOR("Santosh Yaragnavi <santosh.sy@samsung.com>");
8604 MODULE_AUTHOR("Vinayak Holikatti <h.vinayak@samsung.com>");
8605 MODULE_DESCRIPTION("Generic UFS host controller driver Core");
8606 MODULE_LICENSE("GPL");
8607 MODULE_VERSION(UFSHCD_DRIVER_VERSION);