workqueue: Make worker_attach/detach_pool() update worker->pool
[linux/fpc-iii.git] / drivers / scsi / ufs / ufshcd.c
blob00e79057f870dfa67303dc3ed7bff96ba874f329
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 "ufshcd.h"
46 #include "ufs_quirks.h"
47 #include "unipro.h"
48 #include "ufs-sysfs.h"
50 #define CREATE_TRACE_POINTS
51 #include <trace/events/ufs.h>
53 #define UFSHCD_REQ_SENSE_SIZE 18
55 #define UFSHCD_ENABLE_INTRS (UTP_TRANSFER_REQ_COMPL |\
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 #define ufshcd_toggle_vreg(_dev, _vreg, _on) \
93 ({ \
94 int _ret; \
95 if (_on) \
96 _ret = ufshcd_enable_vreg(_dev, _vreg); \
97 else \
98 _ret = ufshcd_disable_vreg(_dev, _vreg); \
99 _ret; \
102 #define ufshcd_hex_dump(prefix_str, buf, len) \
103 print_hex_dump(KERN_ERR, prefix_str, DUMP_PREFIX_OFFSET, 16, 4, buf, len, false)
105 enum {
106 UFSHCD_MAX_CHANNEL = 0,
107 UFSHCD_MAX_ID = 1,
108 UFSHCD_CMD_PER_LUN = 32,
109 UFSHCD_CAN_QUEUE = 32,
112 /* UFSHCD states */
113 enum {
114 UFSHCD_STATE_RESET,
115 UFSHCD_STATE_ERROR,
116 UFSHCD_STATE_OPERATIONAL,
117 UFSHCD_STATE_EH_SCHEDULED,
120 /* UFSHCD error handling flags */
121 enum {
122 UFSHCD_EH_IN_PROGRESS = (1 << 0),
125 /* UFSHCD UIC layer error flags */
126 enum {
127 UFSHCD_UIC_DL_PA_INIT_ERROR = (1 << 0), /* Data link layer error */
128 UFSHCD_UIC_DL_NAC_RECEIVED_ERROR = (1 << 1), /* Data link layer error */
129 UFSHCD_UIC_DL_TCx_REPLAY_ERROR = (1 << 2), /* Data link layer error */
130 UFSHCD_UIC_NL_ERROR = (1 << 3), /* Network layer error */
131 UFSHCD_UIC_TL_ERROR = (1 << 4), /* Transport Layer error */
132 UFSHCD_UIC_DME_ERROR = (1 << 5), /* DME error */
135 #define ufshcd_set_eh_in_progress(h) \
136 ((h)->eh_flags |= UFSHCD_EH_IN_PROGRESS)
137 #define ufshcd_eh_in_progress(h) \
138 ((h)->eh_flags & UFSHCD_EH_IN_PROGRESS)
139 #define ufshcd_clear_eh_in_progress(h) \
140 ((h)->eh_flags &= ~UFSHCD_EH_IN_PROGRESS)
142 #define ufshcd_set_ufs_dev_active(h) \
143 ((h)->curr_dev_pwr_mode = UFS_ACTIVE_PWR_MODE)
144 #define ufshcd_set_ufs_dev_sleep(h) \
145 ((h)->curr_dev_pwr_mode = UFS_SLEEP_PWR_MODE)
146 #define ufshcd_set_ufs_dev_poweroff(h) \
147 ((h)->curr_dev_pwr_mode = UFS_POWERDOWN_PWR_MODE)
148 #define ufshcd_is_ufs_dev_active(h) \
149 ((h)->curr_dev_pwr_mode == UFS_ACTIVE_PWR_MODE)
150 #define ufshcd_is_ufs_dev_sleep(h) \
151 ((h)->curr_dev_pwr_mode == UFS_SLEEP_PWR_MODE)
152 #define ufshcd_is_ufs_dev_poweroff(h) \
153 ((h)->curr_dev_pwr_mode == UFS_POWERDOWN_PWR_MODE)
155 struct ufs_pm_lvl_states ufs_pm_lvl_states[] = {
156 {UFS_ACTIVE_PWR_MODE, UIC_LINK_ACTIVE_STATE},
157 {UFS_ACTIVE_PWR_MODE, UIC_LINK_HIBERN8_STATE},
158 {UFS_SLEEP_PWR_MODE, UIC_LINK_ACTIVE_STATE},
159 {UFS_SLEEP_PWR_MODE, UIC_LINK_HIBERN8_STATE},
160 {UFS_POWERDOWN_PWR_MODE, UIC_LINK_HIBERN8_STATE},
161 {UFS_POWERDOWN_PWR_MODE, UIC_LINK_OFF_STATE},
164 static inline enum ufs_dev_pwr_mode
165 ufs_get_pm_lvl_to_dev_pwr_mode(enum ufs_pm_level lvl)
167 return ufs_pm_lvl_states[lvl].dev_state;
170 static inline enum uic_link_state
171 ufs_get_pm_lvl_to_link_pwr_state(enum ufs_pm_level lvl)
173 return ufs_pm_lvl_states[lvl].link_state;
176 static inline enum ufs_pm_level
177 ufs_get_desired_pm_lvl_for_dev_link_state(enum ufs_dev_pwr_mode dev_state,
178 enum uic_link_state link_state)
180 enum ufs_pm_level lvl;
182 for (lvl = UFS_PM_LVL_0; lvl < UFS_PM_LVL_MAX; lvl++) {
183 if ((ufs_pm_lvl_states[lvl].dev_state == dev_state) &&
184 (ufs_pm_lvl_states[lvl].link_state == link_state))
185 return lvl;
188 /* if no match found, return the level 0 */
189 return UFS_PM_LVL_0;
192 static struct ufs_dev_fix ufs_fixups[] = {
193 /* UFS cards deviations table */
194 UFS_FIX(UFS_VENDOR_SAMSUNG, UFS_ANY_MODEL,
195 UFS_DEVICE_QUIRK_DELAY_BEFORE_LPM),
196 UFS_FIX(UFS_VENDOR_SAMSUNG, UFS_ANY_MODEL, UFS_DEVICE_NO_VCCQ),
197 UFS_FIX(UFS_VENDOR_SAMSUNG, UFS_ANY_MODEL,
198 UFS_DEVICE_QUIRK_RECOVERY_FROM_DL_NAC_ERRORS),
199 UFS_FIX(UFS_VENDOR_SAMSUNG, UFS_ANY_MODEL,
200 UFS_DEVICE_NO_FASTAUTO),
201 UFS_FIX(UFS_VENDOR_SAMSUNG, UFS_ANY_MODEL,
202 UFS_DEVICE_QUIRK_HOST_PA_TACTIVATE),
203 UFS_FIX(UFS_VENDOR_TOSHIBA, UFS_ANY_MODEL,
204 UFS_DEVICE_QUIRK_DELAY_BEFORE_LPM),
205 UFS_FIX(UFS_VENDOR_TOSHIBA, "THGLF2G9C8KBADG",
206 UFS_DEVICE_QUIRK_PA_TACTIVATE),
207 UFS_FIX(UFS_VENDOR_TOSHIBA, "THGLF2G9D8KBADG",
208 UFS_DEVICE_QUIRK_PA_TACTIVATE),
209 UFS_FIX(UFS_VENDOR_SKHYNIX, UFS_ANY_MODEL, UFS_DEVICE_NO_VCCQ),
210 UFS_FIX(UFS_VENDOR_SKHYNIX, UFS_ANY_MODEL,
211 UFS_DEVICE_QUIRK_HOST_PA_SAVECONFIGTIME),
213 END_FIX
216 static void ufshcd_tmc_handler(struct ufs_hba *hba);
217 static void ufshcd_async_scan(void *data, async_cookie_t cookie);
218 static int ufshcd_reset_and_restore(struct ufs_hba *hba);
219 static int ufshcd_eh_host_reset_handler(struct scsi_cmnd *cmd);
220 static int ufshcd_clear_tm_cmd(struct ufs_hba *hba, int tag);
221 static void ufshcd_hba_exit(struct ufs_hba *hba);
222 static int ufshcd_probe_hba(struct ufs_hba *hba);
223 static int __ufshcd_setup_clocks(struct ufs_hba *hba, bool on,
224 bool skip_ref_clk);
225 static int ufshcd_setup_clocks(struct ufs_hba *hba, bool on);
226 static int ufshcd_set_vccq_rail_unused(struct ufs_hba *hba, bool unused);
227 static int ufshcd_uic_hibern8_exit(struct ufs_hba *hba);
228 static int ufshcd_uic_hibern8_enter(struct ufs_hba *hba);
229 static inline void ufshcd_add_delay_before_dme_cmd(struct ufs_hba *hba);
230 static int ufshcd_host_reset_and_restore(struct ufs_hba *hba);
231 static void ufshcd_resume_clkscaling(struct ufs_hba *hba);
232 static void ufshcd_suspend_clkscaling(struct ufs_hba *hba);
233 static void __ufshcd_suspend_clkscaling(struct ufs_hba *hba);
234 static int ufshcd_scale_clks(struct ufs_hba *hba, bool scale_up);
235 static irqreturn_t ufshcd_intr(int irq, void *__hba);
236 static int ufshcd_config_pwr_mode(struct ufs_hba *hba,
237 struct ufs_pa_layer_attr *desired_pwr_mode);
238 static int ufshcd_change_power_mode(struct ufs_hba *hba,
239 struct ufs_pa_layer_attr *pwr_mode);
240 static inline bool ufshcd_valid_tag(struct ufs_hba *hba, int tag)
242 return tag >= 0 && tag < hba->nutrs;
245 static inline int ufshcd_enable_irq(struct ufs_hba *hba)
247 int ret = 0;
249 if (!hba->is_irq_enabled) {
250 ret = request_irq(hba->irq, ufshcd_intr, IRQF_SHARED, UFSHCD,
251 hba);
252 if (ret)
253 dev_err(hba->dev, "%s: request_irq failed, ret=%d\n",
254 __func__, ret);
255 hba->is_irq_enabled = true;
258 return ret;
261 static inline void ufshcd_disable_irq(struct ufs_hba *hba)
263 if (hba->is_irq_enabled) {
264 free_irq(hba->irq, hba);
265 hba->is_irq_enabled = false;
269 /* replace non-printable or non-ASCII characters with spaces */
270 static inline void ufshcd_remove_non_printable(char *val)
272 if (!val)
273 return;
275 if (*val < 0x20 || *val > 0x7e)
276 *val = ' ';
279 static void ufshcd_add_cmd_upiu_trace(struct ufs_hba *hba, unsigned int tag,
280 const char *str)
282 struct utp_upiu_req *rq = hba->lrb[tag].ucd_req_ptr;
284 trace_ufshcd_upiu(dev_name(hba->dev), str, &rq->header, &rq->sc.cdb);
287 static void ufshcd_add_query_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->qr);
295 static void ufshcd_add_tm_upiu_trace(struct ufs_hba *hba, unsigned int tag,
296 const char *str)
298 struct utp_task_req_desc *descp;
299 struct utp_upiu_task_req *task_req;
300 int off = (int)tag - hba->nutrs;
302 descp = &hba->utmrdl_base_addr[off];
303 task_req = (struct utp_upiu_task_req *)descp->task_req_upiu;
304 trace_ufshcd_upiu(dev_name(hba->dev), str, &task_req->header,
305 &task_req->input_param1);
308 static void ufshcd_add_command_trace(struct ufs_hba *hba,
309 unsigned int tag, const char *str)
311 sector_t lba = -1;
312 u8 opcode = 0;
313 u32 intr, doorbell;
314 struct ufshcd_lrb *lrbp;
315 int transfer_len = -1;
317 /* trace UPIU also */
318 ufshcd_add_cmd_upiu_trace(hba, tag, str);
320 if (!trace_ufshcd_command_enabled())
321 return;
323 lrbp = &hba->lrb[tag];
325 if (lrbp->cmd) { /* data phase exists */
326 opcode = (u8)(*lrbp->cmd->cmnd);
327 if ((opcode == READ_10) || (opcode == WRITE_10)) {
329 * Currently we only fully trace read(10) and write(10)
330 * commands
332 if (lrbp->cmd->request && lrbp->cmd->request->bio)
333 lba =
334 lrbp->cmd->request->bio->bi_iter.bi_sector;
335 transfer_len = be32_to_cpu(
336 lrbp->ucd_req_ptr->sc.exp_data_transfer_len);
340 intr = ufshcd_readl(hba, REG_INTERRUPT_STATUS);
341 doorbell = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
342 trace_ufshcd_command(dev_name(hba->dev), str, tag,
343 doorbell, transfer_len, intr, lba, opcode);
346 static void ufshcd_print_clk_freqs(struct ufs_hba *hba)
348 struct ufs_clk_info *clki;
349 struct list_head *head = &hba->clk_list_head;
351 if (list_empty(head))
352 return;
354 list_for_each_entry(clki, head, list) {
355 if (!IS_ERR_OR_NULL(clki->clk) && clki->min_freq &&
356 clki->max_freq)
357 dev_err(hba->dev, "clk: %s, rate: %u\n",
358 clki->name, clki->curr_freq);
362 static void ufshcd_print_uic_err_hist(struct ufs_hba *hba,
363 struct ufs_uic_err_reg_hist *err_hist, char *err_name)
365 int i;
367 for (i = 0; i < UIC_ERR_REG_HIST_LENGTH; i++) {
368 int p = (i + err_hist->pos - 1) % UIC_ERR_REG_HIST_LENGTH;
370 if (err_hist->reg[p] == 0)
371 continue;
372 dev_err(hba->dev, "%s[%d] = 0x%x at %lld us\n", err_name, i,
373 err_hist->reg[p], ktime_to_us(err_hist->tstamp[p]));
377 static void ufshcd_print_host_regs(struct ufs_hba *hba)
380 * hex_dump reads its data without the readl macro. This might
381 * cause inconsistency issues on some platform, as the printed
382 * values may be from cache and not the most recent value.
383 * To know whether you are looking at an un-cached version verify
384 * that IORESOURCE_MEM flag is on when xxx_get_resource() is invoked
385 * during platform/pci probe function.
387 ufshcd_hex_dump("host regs: ", hba->mmio_base, UFSHCI_REG_SPACE_SIZE);
388 dev_err(hba->dev, "hba->ufs_version = 0x%x, hba->capabilities = 0x%x\n",
389 hba->ufs_version, hba->capabilities);
390 dev_err(hba->dev,
391 "hba->outstanding_reqs = 0x%x, hba->outstanding_tasks = 0x%x\n",
392 (u32)hba->outstanding_reqs, (u32)hba->outstanding_tasks);
393 dev_err(hba->dev,
394 "last_hibern8_exit_tstamp at %lld us, hibern8_exit_cnt = %d\n",
395 ktime_to_us(hba->ufs_stats.last_hibern8_exit_tstamp),
396 hba->ufs_stats.hibern8_exit_cnt);
398 ufshcd_print_uic_err_hist(hba, &hba->ufs_stats.pa_err, "pa_err");
399 ufshcd_print_uic_err_hist(hba, &hba->ufs_stats.dl_err, "dl_err");
400 ufshcd_print_uic_err_hist(hba, &hba->ufs_stats.nl_err, "nl_err");
401 ufshcd_print_uic_err_hist(hba, &hba->ufs_stats.tl_err, "tl_err");
402 ufshcd_print_uic_err_hist(hba, &hba->ufs_stats.dme_err, "dme_err");
404 ufshcd_print_clk_freqs(hba);
406 if (hba->vops && hba->vops->dbg_register_dump)
407 hba->vops->dbg_register_dump(hba);
410 static
411 void ufshcd_print_trs(struct ufs_hba *hba, unsigned long bitmap, bool pr_prdt)
413 struct ufshcd_lrb *lrbp;
414 int prdt_length;
415 int tag;
417 for_each_set_bit(tag, &bitmap, hba->nutrs) {
418 lrbp = &hba->lrb[tag];
420 dev_err(hba->dev, "UPIU[%d] - issue time %lld us\n",
421 tag, ktime_to_us(lrbp->issue_time_stamp));
422 dev_err(hba->dev, "UPIU[%d] - complete time %lld us\n",
423 tag, ktime_to_us(lrbp->compl_time_stamp));
424 dev_err(hba->dev,
425 "UPIU[%d] - Transfer Request Descriptor phys@0x%llx\n",
426 tag, (u64)lrbp->utrd_dma_addr);
428 ufshcd_hex_dump("UPIU TRD: ", lrbp->utr_descriptor_ptr,
429 sizeof(struct utp_transfer_req_desc));
430 dev_err(hba->dev, "UPIU[%d] - Request UPIU phys@0x%llx\n", tag,
431 (u64)lrbp->ucd_req_dma_addr);
432 ufshcd_hex_dump("UPIU REQ: ", lrbp->ucd_req_ptr,
433 sizeof(struct utp_upiu_req));
434 dev_err(hba->dev, "UPIU[%d] - Response UPIU phys@0x%llx\n", tag,
435 (u64)lrbp->ucd_rsp_dma_addr);
436 ufshcd_hex_dump("UPIU RSP: ", lrbp->ucd_rsp_ptr,
437 sizeof(struct utp_upiu_rsp));
439 prdt_length = le16_to_cpu(
440 lrbp->utr_descriptor_ptr->prd_table_length);
441 dev_err(hba->dev,
442 "UPIU[%d] - PRDT - %d entries phys@0x%llx\n",
443 tag, prdt_length,
444 (u64)lrbp->ucd_prdt_dma_addr);
446 if (pr_prdt)
447 ufshcd_hex_dump("UPIU PRDT: ", lrbp->ucd_prdt_ptr,
448 sizeof(struct ufshcd_sg_entry) * prdt_length);
452 static void ufshcd_print_tmrs(struct ufs_hba *hba, unsigned long bitmap)
454 struct utp_task_req_desc *tmrdp;
455 int tag;
457 for_each_set_bit(tag, &bitmap, hba->nutmrs) {
458 tmrdp = &hba->utmrdl_base_addr[tag];
459 dev_err(hba->dev, "TM[%d] - Task Management Header\n", tag);
460 ufshcd_hex_dump("TM TRD: ", &tmrdp->header,
461 sizeof(struct request_desc_header));
462 dev_err(hba->dev, "TM[%d] - Task Management Request UPIU\n",
463 tag);
464 ufshcd_hex_dump("TM REQ: ", tmrdp->task_req_upiu,
465 sizeof(struct utp_upiu_req));
466 dev_err(hba->dev, "TM[%d] - Task Management Response UPIU\n",
467 tag);
468 ufshcd_hex_dump("TM RSP: ", tmrdp->task_rsp_upiu,
469 sizeof(struct utp_task_req_desc));
473 static void ufshcd_print_host_state(struct ufs_hba *hba)
475 dev_err(hba->dev, "UFS Host state=%d\n", hba->ufshcd_state);
476 dev_err(hba->dev, "lrb in use=0x%lx, outstanding reqs=0x%lx tasks=0x%lx\n",
477 hba->lrb_in_use, hba->outstanding_reqs, hba->outstanding_tasks);
478 dev_err(hba->dev, "saved_err=0x%x, saved_uic_err=0x%x\n",
479 hba->saved_err, hba->saved_uic_err);
480 dev_err(hba->dev, "Device power mode=%d, UIC link state=%d\n",
481 hba->curr_dev_pwr_mode, hba->uic_link_state);
482 dev_err(hba->dev, "PM in progress=%d, sys. suspended=%d\n",
483 hba->pm_op_in_progress, hba->is_sys_suspended);
484 dev_err(hba->dev, "Auto BKOPS=%d, Host self-block=%d\n",
485 hba->auto_bkops_enabled, hba->host->host_self_blocked);
486 dev_err(hba->dev, "Clk gate=%d\n", hba->clk_gating.state);
487 dev_err(hba->dev, "error handling flags=0x%x, req. abort count=%d\n",
488 hba->eh_flags, hba->req_abort_count);
489 dev_err(hba->dev, "Host capabilities=0x%x, caps=0x%x\n",
490 hba->capabilities, hba->caps);
491 dev_err(hba->dev, "quirks=0x%x, dev. quirks=0x%x\n", hba->quirks,
492 hba->dev_quirks);
496 * ufshcd_print_pwr_info - print power params as saved in hba
497 * power info
498 * @hba: per-adapter instance
500 static void ufshcd_print_pwr_info(struct ufs_hba *hba)
502 static const char * const names[] = {
503 "INVALID MODE",
504 "FAST MODE",
505 "SLOW_MODE",
506 "INVALID MODE",
507 "FASTAUTO_MODE",
508 "SLOWAUTO_MODE",
509 "INVALID MODE",
512 dev_err(hba->dev, "%s:[RX, TX]: gear=[%d, %d], lane[%d, %d], pwr[%s, %s], rate = %d\n",
513 __func__,
514 hba->pwr_info.gear_rx, hba->pwr_info.gear_tx,
515 hba->pwr_info.lane_rx, hba->pwr_info.lane_tx,
516 names[hba->pwr_info.pwr_rx],
517 names[hba->pwr_info.pwr_tx],
518 hba->pwr_info.hs_rate);
522 * ufshcd_wait_for_register - wait for register value to change
523 * @hba - per-adapter interface
524 * @reg - mmio register offset
525 * @mask - mask to apply to read register value
526 * @val - wait condition
527 * @interval_us - polling interval in microsecs
528 * @timeout_ms - timeout in millisecs
529 * @can_sleep - perform sleep or just spin
531 * Returns -ETIMEDOUT on error, zero on success
533 int ufshcd_wait_for_register(struct ufs_hba *hba, u32 reg, u32 mask,
534 u32 val, unsigned long interval_us,
535 unsigned long timeout_ms, bool can_sleep)
537 int err = 0;
538 unsigned long timeout = jiffies + msecs_to_jiffies(timeout_ms);
540 /* ignore bits that we don't intend to wait on */
541 val = val & mask;
543 while ((ufshcd_readl(hba, reg) & mask) != val) {
544 if (can_sleep)
545 usleep_range(interval_us, interval_us + 50);
546 else
547 udelay(interval_us);
548 if (time_after(jiffies, timeout)) {
549 if ((ufshcd_readl(hba, reg) & mask) != val)
550 err = -ETIMEDOUT;
551 break;
555 return err;
559 * ufshcd_get_intr_mask - Get the interrupt bit mask
560 * @hba: Pointer to adapter instance
562 * Returns interrupt bit mask per version
564 static inline u32 ufshcd_get_intr_mask(struct ufs_hba *hba)
566 u32 intr_mask = 0;
568 switch (hba->ufs_version) {
569 case UFSHCI_VERSION_10:
570 intr_mask = INTERRUPT_MASK_ALL_VER_10;
571 break;
572 case UFSHCI_VERSION_11:
573 case UFSHCI_VERSION_20:
574 intr_mask = INTERRUPT_MASK_ALL_VER_11;
575 break;
576 case UFSHCI_VERSION_21:
577 default:
578 intr_mask = INTERRUPT_MASK_ALL_VER_21;
579 break;
582 return intr_mask;
586 * ufshcd_get_ufs_version - Get the UFS version supported by the HBA
587 * @hba: Pointer to adapter instance
589 * Returns UFSHCI version supported by the controller
591 static inline u32 ufshcd_get_ufs_version(struct ufs_hba *hba)
593 if (hba->quirks & UFSHCD_QUIRK_BROKEN_UFS_HCI_VERSION)
594 return ufshcd_vops_get_ufs_hci_version(hba);
596 return ufshcd_readl(hba, REG_UFS_VERSION);
600 * ufshcd_is_device_present - Check if any device connected to
601 * the host controller
602 * @hba: pointer to adapter instance
604 * Returns true if device present, false if no device detected
606 static inline bool ufshcd_is_device_present(struct ufs_hba *hba)
608 return (ufshcd_readl(hba, REG_CONTROLLER_STATUS) &
609 DEVICE_PRESENT) ? true : false;
613 * ufshcd_get_tr_ocs - Get the UTRD Overall Command Status
614 * @lrbp: pointer to local command reference block
616 * This function is used to get the OCS field from UTRD
617 * Returns the OCS field in the UTRD
619 static inline int ufshcd_get_tr_ocs(struct ufshcd_lrb *lrbp)
621 return le32_to_cpu(lrbp->utr_descriptor_ptr->header.dword_2) & MASK_OCS;
625 * ufshcd_get_tmr_ocs - Get the UTMRD Overall Command Status
626 * @task_req_descp: pointer to utp_task_req_desc structure
628 * This function is used to get the OCS field from UTMRD
629 * Returns the OCS field in the UTMRD
631 static inline int
632 ufshcd_get_tmr_ocs(struct utp_task_req_desc *task_req_descp)
634 return le32_to_cpu(task_req_descp->header.dword_2) & MASK_OCS;
638 * ufshcd_get_tm_free_slot - get a free slot for task management request
639 * @hba: per adapter instance
640 * @free_slot: pointer to variable with available slot value
642 * Get a free tag and lock it until ufshcd_put_tm_slot() is called.
643 * Returns 0 if free slot is not available, else return 1 with tag value
644 * in @free_slot.
646 static bool ufshcd_get_tm_free_slot(struct ufs_hba *hba, int *free_slot)
648 int tag;
649 bool ret = false;
651 if (!free_slot)
652 goto out;
654 do {
655 tag = find_first_zero_bit(&hba->tm_slots_in_use, hba->nutmrs);
656 if (tag >= hba->nutmrs)
657 goto out;
658 } while (test_and_set_bit_lock(tag, &hba->tm_slots_in_use));
660 *free_slot = tag;
661 ret = true;
662 out:
663 return ret;
666 static inline void ufshcd_put_tm_slot(struct ufs_hba *hba, int slot)
668 clear_bit_unlock(slot, &hba->tm_slots_in_use);
672 * ufshcd_utrl_clear - Clear a bit in UTRLCLR register
673 * @hba: per adapter instance
674 * @pos: position of the bit to be cleared
676 static inline void ufshcd_utrl_clear(struct ufs_hba *hba, u32 pos)
678 ufshcd_writel(hba, ~(1 << pos), REG_UTP_TRANSFER_REQ_LIST_CLEAR);
682 * ufshcd_outstanding_req_clear - Clear a bit in outstanding request field
683 * @hba: per adapter instance
684 * @tag: position of the bit to be cleared
686 static inline void ufshcd_outstanding_req_clear(struct ufs_hba *hba, int tag)
688 __clear_bit(tag, &hba->outstanding_reqs);
692 * ufshcd_get_lists_status - Check UCRDY, UTRLRDY and UTMRLRDY
693 * @reg: Register value of host controller status
695 * Returns integer, 0 on Success and positive value if failed
697 static inline int ufshcd_get_lists_status(u32 reg)
699 return !((reg & UFSHCD_STATUS_READY) == UFSHCD_STATUS_READY);
703 * ufshcd_get_uic_cmd_result - Get the UIC command result
704 * @hba: Pointer to adapter instance
706 * This function gets the result of UIC command completion
707 * Returns 0 on success, non zero value on error
709 static inline int ufshcd_get_uic_cmd_result(struct ufs_hba *hba)
711 return ufshcd_readl(hba, REG_UIC_COMMAND_ARG_2) &
712 MASK_UIC_COMMAND_RESULT;
716 * ufshcd_get_dme_attr_val - Get the value of attribute returned by UIC command
717 * @hba: Pointer to adapter instance
719 * This function gets UIC command argument3
720 * Returns 0 on success, non zero value on error
722 static inline u32 ufshcd_get_dme_attr_val(struct ufs_hba *hba)
724 return ufshcd_readl(hba, REG_UIC_COMMAND_ARG_3);
728 * ufshcd_get_req_rsp - returns the TR response transaction type
729 * @ucd_rsp_ptr: pointer to response UPIU
731 static inline int
732 ufshcd_get_req_rsp(struct utp_upiu_rsp *ucd_rsp_ptr)
734 return be32_to_cpu(ucd_rsp_ptr->header.dword_0) >> 24;
738 * ufshcd_get_rsp_upiu_result - Get the result from response UPIU
739 * @ucd_rsp_ptr: pointer to response UPIU
741 * This function gets the response status and scsi_status from response UPIU
742 * Returns the response result code.
744 static inline int
745 ufshcd_get_rsp_upiu_result(struct utp_upiu_rsp *ucd_rsp_ptr)
747 return be32_to_cpu(ucd_rsp_ptr->header.dword_1) & MASK_RSP_UPIU_RESULT;
751 * ufshcd_get_rsp_upiu_data_seg_len - Get the data segment length
752 * from response UPIU
753 * @ucd_rsp_ptr: pointer to response UPIU
755 * Return the data segment length.
757 static inline unsigned int
758 ufshcd_get_rsp_upiu_data_seg_len(struct utp_upiu_rsp *ucd_rsp_ptr)
760 return be32_to_cpu(ucd_rsp_ptr->header.dword_2) &
761 MASK_RSP_UPIU_DATA_SEG_LEN;
765 * ufshcd_is_exception_event - Check if the device raised an exception event
766 * @ucd_rsp_ptr: pointer to response UPIU
768 * The function checks if the device raised an exception event indicated in
769 * the Device Information field of response UPIU.
771 * Returns true if exception is raised, false otherwise.
773 static inline bool ufshcd_is_exception_event(struct utp_upiu_rsp *ucd_rsp_ptr)
775 return be32_to_cpu(ucd_rsp_ptr->header.dword_2) &
776 MASK_RSP_EXCEPTION_EVENT ? true : false;
780 * ufshcd_reset_intr_aggr - Reset interrupt aggregation values.
781 * @hba: per adapter instance
783 static inline void
784 ufshcd_reset_intr_aggr(struct ufs_hba *hba)
786 ufshcd_writel(hba, INT_AGGR_ENABLE |
787 INT_AGGR_COUNTER_AND_TIMER_RESET,
788 REG_UTP_TRANSFER_REQ_INT_AGG_CONTROL);
792 * ufshcd_config_intr_aggr - Configure interrupt aggregation values.
793 * @hba: per adapter instance
794 * @cnt: Interrupt aggregation counter threshold
795 * @tmout: Interrupt aggregation timeout value
797 static inline void
798 ufshcd_config_intr_aggr(struct ufs_hba *hba, u8 cnt, u8 tmout)
800 ufshcd_writel(hba, INT_AGGR_ENABLE | INT_AGGR_PARAM_WRITE |
801 INT_AGGR_COUNTER_THLD_VAL(cnt) |
802 INT_AGGR_TIMEOUT_VAL(tmout),
803 REG_UTP_TRANSFER_REQ_INT_AGG_CONTROL);
807 * ufshcd_disable_intr_aggr - Disables interrupt aggregation.
808 * @hba: per adapter instance
810 static inline void ufshcd_disable_intr_aggr(struct ufs_hba *hba)
812 ufshcd_writel(hba, 0, REG_UTP_TRANSFER_REQ_INT_AGG_CONTROL);
816 * ufshcd_enable_run_stop_reg - Enable run-stop registers,
817 * When run-stop registers are set to 1, it indicates the
818 * host controller that it can process the requests
819 * @hba: per adapter instance
821 static void ufshcd_enable_run_stop_reg(struct ufs_hba *hba)
823 ufshcd_writel(hba, UTP_TASK_REQ_LIST_RUN_STOP_BIT,
824 REG_UTP_TASK_REQ_LIST_RUN_STOP);
825 ufshcd_writel(hba, UTP_TRANSFER_REQ_LIST_RUN_STOP_BIT,
826 REG_UTP_TRANSFER_REQ_LIST_RUN_STOP);
830 * ufshcd_hba_start - Start controller initialization sequence
831 * @hba: per adapter instance
833 static inline void ufshcd_hba_start(struct ufs_hba *hba)
835 ufshcd_writel(hba, CONTROLLER_ENABLE, REG_CONTROLLER_ENABLE);
839 * ufshcd_is_hba_active - Get controller state
840 * @hba: per adapter instance
842 * Returns false if controller is active, true otherwise
844 static inline bool ufshcd_is_hba_active(struct ufs_hba *hba)
846 return (ufshcd_readl(hba, REG_CONTROLLER_ENABLE) & CONTROLLER_ENABLE)
847 ? false : true;
850 u32 ufshcd_get_local_unipro_ver(struct ufs_hba *hba)
852 /* HCI version 1.0 and 1.1 supports UniPro 1.41 */
853 if ((hba->ufs_version == UFSHCI_VERSION_10) ||
854 (hba->ufs_version == UFSHCI_VERSION_11))
855 return UFS_UNIPRO_VER_1_41;
856 else
857 return UFS_UNIPRO_VER_1_6;
859 EXPORT_SYMBOL(ufshcd_get_local_unipro_ver);
861 static bool ufshcd_is_unipro_pa_params_tuning_req(struct ufs_hba *hba)
864 * If both host and device support UniPro ver1.6 or later, PA layer
865 * parameters tuning happens during link startup itself.
867 * We can manually tune PA layer parameters if either host or device
868 * doesn't support UniPro ver 1.6 or later. But to keep manual tuning
869 * logic simple, we will only do manual tuning if local unipro version
870 * doesn't support ver1.6 or later.
872 if (ufshcd_get_local_unipro_ver(hba) < UFS_UNIPRO_VER_1_6)
873 return true;
874 else
875 return false;
878 static int ufshcd_scale_clks(struct ufs_hba *hba, bool scale_up)
880 int ret = 0;
881 struct ufs_clk_info *clki;
882 struct list_head *head = &hba->clk_list_head;
883 ktime_t start = ktime_get();
884 bool clk_state_changed = false;
886 if (list_empty(head))
887 goto out;
889 ret = ufshcd_vops_clk_scale_notify(hba, scale_up, PRE_CHANGE);
890 if (ret)
891 return ret;
893 list_for_each_entry(clki, head, list) {
894 if (!IS_ERR_OR_NULL(clki->clk)) {
895 if (scale_up && clki->max_freq) {
896 if (clki->curr_freq == clki->max_freq)
897 continue;
899 clk_state_changed = true;
900 ret = clk_set_rate(clki->clk, clki->max_freq);
901 if (ret) {
902 dev_err(hba->dev, "%s: %s clk set rate(%dHz) failed, %d\n",
903 __func__, clki->name,
904 clki->max_freq, ret);
905 break;
907 trace_ufshcd_clk_scaling(dev_name(hba->dev),
908 "scaled up", clki->name,
909 clki->curr_freq,
910 clki->max_freq);
912 clki->curr_freq = clki->max_freq;
914 } else if (!scale_up && clki->min_freq) {
915 if (clki->curr_freq == clki->min_freq)
916 continue;
918 clk_state_changed = true;
919 ret = clk_set_rate(clki->clk, clki->min_freq);
920 if (ret) {
921 dev_err(hba->dev, "%s: %s clk set rate(%dHz) failed, %d\n",
922 __func__, clki->name,
923 clki->min_freq, ret);
924 break;
926 trace_ufshcd_clk_scaling(dev_name(hba->dev),
927 "scaled down", clki->name,
928 clki->curr_freq,
929 clki->min_freq);
930 clki->curr_freq = clki->min_freq;
933 dev_dbg(hba->dev, "%s: clk: %s, rate: %lu\n", __func__,
934 clki->name, clk_get_rate(clki->clk));
937 ret = ufshcd_vops_clk_scale_notify(hba, scale_up, POST_CHANGE);
939 out:
940 if (clk_state_changed)
941 trace_ufshcd_profile_clk_scaling(dev_name(hba->dev),
942 (scale_up ? "up" : "down"),
943 ktime_to_us(ktime_sub(ktime_get(), start)), ret);
944 return ret;
948 * ufshcd_is_devfreq_scaling_required - check if scaling is required or not
949 * @hba: per adapter instance
950 * @scale_up: True if scaling up and false if scaling down
952 * Returns true if scaling is required, false otherwise.
954 static bool ufshcd_is_devfreq_scaling_required(struct ufs_hba *hba,
955 bool scale_up)
957 struct ufs_clk_info *clki;
958 struct list_head *head = &hba->clk_list_head;
960 if (list_empty(head))
961 return false;
963 list_for_each_entry(clki, head, list) {
964 if (!IS_ERR_OR_NULL(clki->clk)) {
965 if (scale_up && clki->max_freq) {
966 if (clki->curr_freq == clki->max_freq)
967 continue;
968 return true;
969 } else if (!scale_up && clki->min_freq) {
970 if (clki->curr_freq == clki->min_freq)
971 continue;
972 return true;
977 return false;
980 static int ufshcd_wait_for_doorbell_clr(struct ufs_hba *hba,
981 u64 wait_timeout_us)
983 unsigned long flags;
984 int ret = 0;
985 u32 tm_doorbell;
986 u32 tr_doorbell;
987 bool timeout = false, do_last_check = false;
988 ktime_t start;
990 ufshcd_hold(hba, false);
991 spin_lock_irqsave(hba->host->host_lock, flags);
993 * Wait for all the outstanding tasks/transfer requests.
994 * Verify by checking the doorbell registers are clear.
996 start = ktime_get();
997 do {
998 if (hba->ufshcd_state != UFSHCD_STATE_OPERATIONAL) {
999 ret = -EBUSY;
1000 goto out;
1003 tm_doorbell = ufshcd_readl(hba, REG_UTP_TASK_REQ_DOOR_BELL);
1004 tr_doorbell = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
1005 if (!tm_doorbell && !tr_doorbell) {
1006 timeout = false;
1007 break;
1008 } else if (do_last_check) {
1009 break;
1012 spin_unlock_irqrestore(hba->host->host_lock, flags);
1013 schedule();
1014 if (ktime_to_us(ktime_sub(ktime_get(), start)) >
1015 wait_timeout_us) {
1016 timeout = true;
1018 * We might have scheduled out for long time so make
1019 * sure to check if doorbells are cleared by this time
1020 * or not.
1022 do_last_check = true;
1024 spin_lock_irqsave(hba->host->host_lock, flags);
1025 } while (tm_doorbell || tr_doorbell);
1027 if (timeout) {
1028 dev_err(hba->dev,
1029 "%s: timedout waiting for doorbell to clear (tm=0x%x, tr=0x%x)\n",
1030 __func__, tm_doorbell, tr_doorbell);
1031 ret = -EBUSY;
1033 out:
1034 spin_unlock_irqrestore(hba->host->host_lock, flags);
1035 ufshcd_release(hba);
1036 return ret;
1040 * ufshcd_scale_gear - scale up/down UFS gear
1041 * @hba: per adapter instance
1042 * @scale_up: True for scaling up gear and false for scaling down
1044 * Returns 0 for success,
1045 * Returns -EBUSY if scaling can't happen at this time
1046 * Returns non-zero for any other errors
1048 static int ufshcd_scale_gear(struct ufs_hba *hba, bool scale_up)
1050 #define UFS_MIN_GEAR_TO_SCALE_DOWN UFS_HS_G1
1051 int ret = 0;
1052 struct ufs_pa_layer_attr new_pwr_info;
1054 if (scale_up) {
1055 memcpy(&new_pwr_info, &hba->clk_scaling.saved_pwr_info.info,
1056 sizeof(struct ufs_pa_layer_attr));
1057 } else {
1058 memcpy(&new_pwr_info, &hba->pwr_info,
1059 sizeof(struct ufs_pa_layer_attr));
1061 if (hba->pwr_info.gear_tx > UFS_MIN_GEAR_TO_SCALE_DOWN
1062 || hba->pwr_info.gear_rx > UFS_MIN_GEAR_TO_SCALE_DOWN) {
1063 /* save the current power mode */
1064 memcpy(&hba->clk_scaling.saved_pwr_info.info,
1065 &hba->pwr_info,
1066 sizeof(struct ufs_pa_layer_attr));
1068 /* scale down gear */
1069 new_pwr_info.gear_tx = UFS_MIN_GEAR_TO_SCALE_DOWN;
1070 new_pwr_info.gear_rx = UFS_MIN_GEAR_TO_SCALE_DOWN;
1074 /* check if the power mode needs to be changed or not? */
1075 ret = ufshcd_change_power_mode(hba, &new_pwr_info);
1077 if (ret)
1078 dev_err(hba->dev, "%s: failed err %d, old gear: (tx %d rx %d), new gear: (tx %d rx %d)",
1079 __func__, ret,
1080 hba->pwr_info.gear_tx, hba->pwr_info.gear_rx,
1081 new_pwr_info.gear_tx, new_pwr_info.gear_rx);
1083 return ret;
1086 static int ufshcd_clock_scaling_prepare(struct ufs_hba *hba)
1088 #define DOORBELL_CLR_TOUT_US (1000 * 1000) /* 1 sec */
1089 int ret = 0;
1091 * make sure that there are no outstanding requests when
1092 * clock scaling is in progress
1094 scsi_block_requests(hba->host);
1095 down_write(&hba->clk_scaling_lock);
1096 if (ufshcd_wait_for_doorbell_clr(hba, DOORBELL_CLR_TOUT_US)) {
1097 ret = -EBUSY;
1098 up_write(&hba->clk_scaling_lock);
1099 scsi_unblock_requests(hba->host);
1102 return ret;
1105 static void ufshcd_clock_scaling_unprepare(struct ufs_hba *hba)
1107 up_write(&hba->clk_scaling_lock);
1108 scsi_unblock_requests(hba->host);
1112 * ufshcd_devfreq_scale - scale up/down UFS clocks and gear
1113 * @hba: per adapter instance
1114 * @scale_up: True for scaling up and false for scalin down
1116 * Returns 0 for success,
1117 * Returns -EBUSY if scaling can't happen at this time
1118 * Returns non-zero for any other errors
1120 static int ufshcd_devfreq_scale(struct ufs_hba *hba, bool scale_up)
1122 int ret = 0;
1124 /* let's not get into low power until clock scaling is completed */
1125 ufshcd_hold(hba, false);
1127 ret = ufshcd_clock_scaling_prepare(hba);
1128 if (ret)
1129 return ret;
1131 /* scale down the gear before scaling down clocks */
1132 if (!scale_up) {
1133 ret = ufshcd_scale_gear(hba, false);
1134 if (ret)
1135 goto out;
1138 ret = ufshcd_scale_clks(hba, scale_up);
1139 if (ret) {
1140 if (!scale_up)
1141 ufshcd_scale_gear(hba, true);
1142 goto out;
1145 /* scale up the gear after scaling up clocks */
1146 if (scale_up) {
1147 ret = ufshcd_scale_gear(hba, true);
1148 if (ret) {
1149 ufshcd_scale_clks(hba, false);
1150 goto out;
1154 ret = ufshcd_vops_clk_scale_notify(hba, scale_up, POST_CHANGE);
1156 out:
1157 ufshcd_clock_scaling_unprepare(hba);
1158 ufshcd_release(hba);
1159 return ret;
1162 static void ufshcd_clk_scaling_suspend_work(struct work_struct *work)
1164 struct ufs_hba *hba = container_of(work, struct ufs_hba,
1165 clk_scaling.suspend_work);
1166 unsigned long irq_flags;
1168 spin_lock_irqsave(hba->host->host_lock, irq_flags);
1169 if (hba->clk_scaling.active_reqs || hba->clk_scaling.is_suspended) {
1170 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1171 return;
1173 hba->clk_scaling.is_suspended = true;
1174 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1176 __ufshcd_suspend_clkscaling(hba);
1179 static void ufshcd_clk_scaling_resume_work(struct work_struct *work)
1181 struct ufs_hba *hba = container_of(work, struct ufs_hba,
1182 clk_scaling.resume_work);
1183 unsigned long irq_flags;
1185 spin_lock_irqsave(hba->host->host_lock, irq_flags);
1186 if (!hba->clk_scaling.is_suspended) {
1187 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1188 return;
1190 hba->clk_scaling.is_suspended = false;
1191 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1193 devfreq_resume_device(hba->devfreq);
1196 static int ufshcd_devfreq_target(struct device *dev,
1197 unsigned long *freq, u32 flags)
1199 int ret = 0;
1200 struct ufs_hba *hba = dev_get_drvdata(dev);
1201 ktime_t start;
1202 bool scale_up, sched_clk_scaling_suspend_work = false;
1203 unsigned long irq_flags;
1205 if (!ufshcd_is_clkscaling_supported(hba))
1206 return -EINVAL;
1208 if ((*freq > 0) && (*freq < UINT_MAX)) {
1209 dev_err(hba->dev, "%s: invalid freq = %lu\n", __func__, *freq);
1210 return -EINVAL;
1213 spin_lock_irqsave(hba->host->host_lock, irq_flags);
1214 if (ufshcd_eh_in_progress(hba)) {
1215 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1216 return 0;
1219 if (!hba->clk_scaling.active_reqs)
1220 sched_clk_scaling_suspend_work = true;
1222 scale_up = (*freq == UINT_MAX) ? true : false;
1223 if (!ufshcd_is_devfreq_scaling_required(hba, scale_up)) {
1224 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1225 ret = 0;
1226 goto out; /* no state change required */
1228 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1230 start = ktime_get();
1231 ret = ufshcd_devfreq_scale(hba, scale_up);
1233 trace_ufshcd_profile_clk_scaling(dev_name(hba->dev),
1234 (scale_up ? "up" : "down"),
1235 ktime_to_us(ktime_sub(ktime_get(), start)), ret);
1237 out:
1238 if (sched_clk_scaling_suspend_work)
1239 queue_work(hba->clk_scaling.workq,
1240 &hba->clk_scaling.suspend_work);
1242 return ret;
1246 static int ufshcd_devfreq_get_dev_status(struct device *dev,
1247 struct devfreq_dev_status *stat)
1249 struct ufs_hba *hba = dev_get_drvdata(dev);
1250 struct ufs_clk_scaling *scaling = &hba->clk_scaling;
1251 unsigned long flags;
1253 if (!ufshcd_is_clkscaling_supported(hba))
1254 return -EINVAL;
1256 memset(stat, 0, sizeof(*stat));
1258 spin_lock_irqsave(hba->host->host_lock, flags);
1259 if (!scaling->window_start_t)
1260 goto start_window;
1262 if (scaling->is_busy_started)
1263 scaling->tot_busy_t += ktime_to_us(ktime_sub(ktime_get(),
1264 scaling->busy_start_t));
1266 stat->total_time = jiffies_to_usecs((long)jiffies -
1267 (long)scaling->window_start_t);
1268 stat->busy_time = scaling->tot_busy_t;
1269 start_window:
1270 scaling->window_start_t = jiffies;
1271 scaling->tot_busy_t = 0;
1273 if (hba->outstanding_reqs) {
1274 scaling->busy_start_t = ktime_get();
1275 scaling->is_busy_started = true;
1276 } else {
1277 scaling->busy_start_t = 0;
1278 scaling->is_busy_started = false;
1280 spin_unlock_irqrestore(hba->host->host_lock, flags);
1281 return 0;
1284 static struct devfreq_dev_profile ufs_devfreq_profile = {
1285 .polling_ms = 100,
1286 .target = ufshcd_devfreq_target,
1287 .get_dev_status = ufshcd_devfreq_get_dev_status,
1290 static void __ufshcd_suspend_clkscaling(struct ufs_hba *hba)
1292 unsigned long flags;
1294 devfreq_suspend_device(hba->devfreq);
1295 spin_lock_irqsave(hba->host->host_lock, flags);
1296 hba->clk_scaling.window_start_t = 0;
1297 spin_unlock_irqrestore(hba->host->host_lock, flags);
1300 static void ufshcd_suspend_clkscaling(struct ufs_hba *hba)
1302 unsigned long flags;
1303 bool suspend = false;
1305 if (!ufshcd_is_clkscaling_supported(hba))
1306 return;
1308 spin_lock_irqsave(hba->host->host_lock, flags);
1309 if (!hba->clk_scaling.is_suspended) {
1310 suspend = true;
1311 hba->clk_scaling.is_suspended = true;
1313 spin_unlock_irqrestore(hba->host->host_lock, flags);
1315 if (suspend)
1316 __ufshcd_suspend_clkscaling(hba);
1319 static void ufshcd_resume_clkscaling(struct ufs_hba *hba)
1321 unsigned long flags;
1322 bool resume = false;
1324 if (!ufshcd_is_clkscaling_supported(hba))
1325 return;
1327 spin_lock_irqsave(hba->host->host_lock, flags);
1328 if (hba->clk_scaling.is_suspended) {
1329 resume = true;
1330 hba->clk_scaling.is_suspended = false;
1332 spin_unlock_irqrestore(hba->host->host_lock, flags);
1334 if (resume)
1335 devfreq_resume_device(hba->devfreq);
1338 static ssize_t ufshcd_clkscale_enable_show(struct device *dev,
1339 struct device_attribute *attr, char *buf)
1341 struct ufs_hba *hba = dev_get_drvdata(dev);
1343 return snprintf(buf, PAGE_SIZE, "%d\n", hba->clk_scaling.is_allowed);
1346 static ssize_t ufshcd_clkscale_enable_store(struct device *dev,
1347 struct device_attribute *attr, const char *buf, size_t count)
1349 struct ufs_hba *hba = dev_get_drvdata(dev);
1350 u32 value;
1351 int err;
1353 if (kstrtou32(buf, 0, &value))
1354 return -EINVAL;
1356 value = !!value;
1357 if (value == hba->clk_scaling.is_allowed)
1358 goto out;
1360 pm_runtime_get_sync(hba->dev);
1361 ufshcd_hold(hba, false);
1363 cancel_work_sync(&hba->clk_scaling.suspend_work);
1364 cancel_work_sync(&hba->clk_scaling.resume_work);
1366 hba->clk_scaling.is_allowed = value;
1368 if (value) {
1369 ufshcd_resume_clkscaling(hba);
1370 } else {
1371 ufshcd_suspend_clkscaling(hba);
1372 err = ufshcd_devfreq_scale(hba, true);
1373 if (err)
1374 dev_err(hba->dev, "%s: failed to scale clocks up %d\n",
1375 __func__, err);
1378 ufshcd_release(hba);
1379 pm_runtime_put_sync(hba->dev);
1380 out:
1381 return count;
1384 static void ufshcd_clkscaling_init_sysfs(struct ufs_hba *hba)
1386 hba->clk_scaling.enable_attr.show = ufshcd_clkscale_enable_show;
1387 hba->clk_scaling.enable_attr.store = ufshcd_clkscale_enable_store;
1388 sysfs_attr_init(&hba->clk_scaling.enable_attr.attr);
1389 hba->clk_scaling.enable_attr.attr.name = "clkscale_enable";
1390 hba->clk_scaling.enable_attr.attr.mode = 0644;
1391 if (device_create_file(hba->dev, &hba->clk_scaling.enable_attr))
1392 dev_err(hba->dev, "Failed to create sysfs for clkscale_enable\n");
1395 static void ufshcd_ungate_work(struct work_struct *work)
1397 int ret;
1398 unsigned long flags;
1399 struct ufs_hba *hba = container_of(work, struct ufs_hba,
1400 clk_gating.ungate_work);
1402 cancel_delayed_work_sync(&hba->clk_gating.gate_work);
1404 spin_lock_irqsave(hba->host->host_lock, flags);
1405 if (hba->clk_gating.state == CLKS_ON) {
1406 spin_unlock_irqrestore(hba->host->host_lock, flags);
1407 goto unblock_reqs;
1410 spin_unlock_irqrestore(hba->host->host_lock, flags);
1411 ufshcd_setup_clocks(hba, true);
1413 /* Exit from hibern8 */
1414 if (ufshcd_can_hibern8_during_gating(hba)) {
1415 /* Prevent gating in this path */
1416 hba->clk_gating.is_suspended = true;
1417 if (ufshcd_is_link_hibern8(hba)) {
1418 ret = ufshcd_uic_hibern8_exit(hba);
1419 if (ret)
1420 dev_err(hba->dev, "%s: hibern8 exit failed %d\n",
1421 __func__, ret);
1422 else
1423 ufshcd_set_link_active(hba);
1425 hba->clk_gating.is_suspended = false;
1427 unblock_reqs:
1428 scsi_unblock_requests(hba->host);
1432 * ufshcd_hold - Enable clocks that were gated earlier due to ufshcd_release.
1433 * Also, exit from hibern8 mode and set the link as active.
1434 * @hba: per adapter instance
1435 * @async: This indicates whether caller should ungate clocks asynchronously.
1437 int ufshcd_hold(struct ufs_hba *hba, bool async)
1439 int rc = 0;
1440 unsigned long flags;
1442 if (!ufshcd_is_clkgating_allowed(hba))
1443 goto out;
1444 spin_lock_irqsave(hba->host->host_lock, flags);
1445 hba->clk_gating.active_reqs++;
1447 if (ufshcd_eh_in_progress(hba)) {
1448 spin_unlock_irqrestore(hba->host->host_lock, flags);
1449 return 0;
1452 start:
1453 switch (hba->clk_gating.state) {
1454 case CLKS_ON:
1456 * Wait for the ungate work to complete if in progress.
1457 * Though the clocks may be in ON state, the link could
1458 * still be in hibner8 state if hibern8 is allowed
1459 * during clock gating.
1460 * Make sure we exit hibern8 state also in addition to
1461 * clocks being ON.
1463 if (ufshcd_can_hibern8_during_gating(hba) &&
1464 ufshcd_is_link_hibern8(hba)) {
1465 spin_unlock_irqrestore(hba->host->host_lock, flags);
1466 flush_work(&hba->clk_gating.ungate_work);
1467 spin_lock_irqsave(hba->host->host_lock, flags);
1468 goto start;
1470 break;
1471 case REQ_CLKS_OFF:
1472 if (cancel_delayed_work(&hba->clk_gating.gate_work)) {
1473 hba->clk_gating.state = CLKS_ON;
1474 trace_ufshcd_clk_gating(dev_name(hba->dev),
1475 hba->clk_gating.state);
1476 break;
1479 * If we are here, it means gating work is either done or
1480 * currently running. Hence, fall through to cancel gating
1481 * work and to enable clocks.
1483 case CLKS_OFF:
1484 scsi_block_requests(hba->host);
1485 hba->clk_gating.state = REQ_CLKS_ON;
1486 trace_ufshcd_clk_gating(dev_name(hba->dev),
1487 hba->clk_gating.state);
1488 schedule_work(&hba->clk_gating.ungate_work);
1490 * fall through to check if we should wait for this
1491 * work to be done or not.
1493 case REQ_CLKS_ON:
1494 if (async) {
1495 rc = -EAGAIN;
1496 hba->clk_gating.active_reqs--;
1497 break;
1500 spin_unlock_irqrestore(hba->host->host_lock, flags);
1501 flush_work(&hba->clk_gating.ungate_work);
1502 /* Make sure state is CLKS_ON before returning */
1503 spin_lock_irqsave(hba->host->host_lock, flags);
1504 goto start;
1505 default:
1506 dev_err(hba->dev, "%s: clk gating is in invalid state %d\n",
1507 __func__, hba->clk_gating.state);
1508 break;
1510 spin_unlock_irqrestore(hba->host->host_lock, flags);
1511 out:
1512 return rc;
1514 EXPORT_SYMBOL_GPL(ufshcd_hold);
1516 static void ufshcd_gate_work(struct work_struct *work)
1518 struct ufs_hba *hba = container_of(work, struct ufs_hba,
1519 clk_gating.gate_work.work);
1520 unsigned long flags;
1522 spin_lock_irqsave(hba->host->host_lock, flags);
1524 * In case you are here to cancel this work the gating state
1525 * would be marked as REQ_CLKS_ON. In this case save time by
1526 * skipping the gating work and exit after changing the clock
1527 * state to CLKS_ON.
1529 if (hba->clk_gating.is_suspended ||
1530 (hba->clk_gating.state == REQ_CLKS_ON)) {
1531 hba->clk_gating.state = CLKS_ON;
1532 trace_ufshcd_clk_gating(dev_name(hba->dev),
1533 hba->clk_gating.state);
1534 goto rel_lock;
1537 if (hba->clk_gating.active_reqs
1538 || hba->ufshcd_state != UFSHCD_STATE_OPERATIONAL
1539 || hba->lrb_in_use || hba->outstanding_tasks
1540 || hba->active_uic_cmd || hba->uic_async_done)
1541 goto rel_lock;
1543 spin_unlock_irqrestore(hba->host->host_lock, flags);
1545 /* put the link into hibern8 mode before turning off clocks */
1546 if (ufshcd_can_hibern8_during_gating(hba)) {
1547 if (ufshcd_uic_hibern8_enter(hba)) {
1548 hba->clk_gating.state = CLKS_ON;
1549 trace_ufshcd_clk_gating(dev_name(hba->dev),
1550 hba->clk_gating.state);
1551 goto out;
1553 ufshcd_set_link_hibern8(hba);
1556 if (!ufshcd_is_link_active(hba))
1557 ufshcd_setup_clocks(hba, false);
1558 else
1559 /* If link is active, device ref_clk can't be switched off */
1560 __ufshcd_setup_clocks(hba, false, true);
1563 * In case you are here to cancel this work the gating state
1564 * would be marked as REQ_CLKS_ON. In this case keep the state
1565 * as REQ_CLKS_ON which would anyway imply that clocks are off
1566 * and a request to turn them on is pending. By doing this way,
1567 * we keep the state machine in tact and this would ultimately
1568 * prevent from doing cancel work multiple times when there are
1569 * new requests arriving before the current cancel work is done.
1571 spin_lock_irqsave(hba->host->host_lock, flags);
1572 if (hba->clk_gating.state == REQ_CLKS_OFF) {
1573 hba->clk_gating.state = CLKS_OFF;
1574 trace_ufshcd_clk_gating(dev_name(hba->dev),
1575 hba->clk_gating.state);
1577 rel_lock:
1578 spin_unlock_irqrestore(hba->host->host_lock, flags);
1579 out:
1580 return;
1583 /* host lock must be held before calling this variant */
1584 static void __ufshcd_release(struct ufs_hba *hba)
1586 if (!ufshcd_is_clkgating_allowed(hba))
1587 return;
1589 hba->clk_gating.active_reqs--;
1591 if (hba->clk_gating.active_reqs || hba->clk_gating.is_suspended
1592 || hba->ufshcd_state != UFSHCD_STATE_OPERATIONAL
1593 || hba->lrb_in_use || hba->outstanding_tasks
1594 || hba->active_uic_cmd || hba->uic_async_done
1595 || ufshcd_eh_in_progress(hba))
1596 return;
1598 hba->clk_gating.state = REQ_CLKS_OFF;
1599 trace_ufshcd_clk_gating(dev_name(hba->dev), hba->clk_gating.state);
1600 schedule_delayed_work(&hba->clk_gating.gate_work,
1601 msecs_to_jiffies(hba->clk_gating.delay_ms));
1604 void ufshcd_release(struct ufs_hba *hba)
1606 unsigned long flags;
1608 spin_lock_irqsave(hba->host->host_lock, flags);
1609 __ufshcd_release(hba);
1610 spin_unlock_irqrestore(hba->host->host_lock, flags);
1612 EXPORT_SYMBOL_GPL(ufshcd_release);
1614 static ssize_t ufshcd_clkgate_delay_show(struct device *dev,
1615 struct device_attribute *attr, char *buf)
1617 struct ufs_hba *hba = dev_get_drvdata(dev);
1619 return snprintf(buf, PAGE_SIZE, "%lu\n", hba->clk_gating.delay_ms);
1622 static ssize_t ufshcd_clkgate_delay_store(struct device *dev,
1623 struct device_attribute *attr, const char *buf, size_t count)
1625 struct ufs_hba *hba = dev_get_drvdata(dev);
1626 unsigned long flags, value;
1628 if (kstrtoul(buf, 0, &value))
1629 return -EINVAL;
1631 spin_lock_irqsave(hba->host->host_lock, flags);
1632 hba->clk_gating.delay_ms = value;
1633 spin_unlock_irqrestore(hba->host->host_lock, flags);
1634 return count;
1637 static ssize_t ufshcd_clkgate_enable_show(struct device *dev,
1638 struct device_attribute *attr, char *buf)
1640 struct ufs_hba *hba = dev_get_drvdata(dev);
1642 return snprintf(buf, PAGE_SIZE, "%d\n", hba->clk_gating.is_enabled);
1645 static ssize_t ufshcd_clkgate_enable_store(struct device *dev,
1646 struct device_attribute *attr, const char *buf, size_t count)
1648 struct ufs_hba *hba = dev_get_drvdata(dev);
1649 unsigned long flags;
1650 u32 value;
1652 if (kstrtou32(buf, 0, &value))
1653 return -EINVAL;
1655 value = !!value;
1656 if (value == hba->clk_gating.is_enabled)
1657 goto out;
1659 if (value) {
1660 ufshcd_release(hba);
1661 } else {
1662 spin_lock_irqsave(hba->host->host_lock, flags);
1663 hba->clk_gating.active_reqs++;
1664 spin_unlock_irqrestore(hba->host->host_lock, flags);
1667 hba->clk_gating.is_enabled = value;
1668 out:
1669 return count;
1672 static void ufshcd_init_clk_gating(struct ufs_hba *hba)
1674 if (!ufshcd_is_clkgating_allowed(hba))
1675 return;
1677 hba->clk_gating.delay_ms = 150;
1678 INIT_DELAYED_WORK(&hba->clk_gating.gate_work, ufshcd_gate_work);
1679 INIT_WORK(&hba->clk_gating.ungate_work, ufshcd_ungate_work);
1681 hba->clk_gating.is_enabled = true;
1683 hba->clk_gating.delay_attr.show = ufshcd_clkgate_delay_show;
1684 hba->clk_gating.delay_attr.store = ufshcd_clkgate_delay_store;
1685 sysfs_attr_init(&hba->clk_gating.delay_attr.attr);
1686 hba->clk_gating.delay_attr.attr.name = "clkgate_delay_ms";
1687 hba->clk_gating.delay_attr.attr.mode = 0644;
1688 if (device_create_file(hba->dev, &hba->clk_gating.delay_attr))
1689 dev_err(hba->dev, "Failed to create sysfs for clkgate_delay\n");
1691 hba->clk_gating.enable_attr.show = ufshcd_clkgate_enable_show;
1692 hba->clk_gating.enable_attr.store = ufshcd_clkgate_enable_store;
1693 sysfs_attr_init(&hba->clk_gating.enable_attr.attr);
1694 hba->clk_gating.enable_attr.attr.name = "clkgate_enable";
1695 hba->clk_gating.enable_attr.attr.mode = 0644;
1696 if (device_create_file(hba->dev, &hba->clk_gating.enable_attr))
1697 dev_err(hba->dev, "Failed to create sysfs for clkgate_enable\n");
1700 static void ufshcd_exit_clk_gating(struct ufs_hba *hba)
1702 if (!ufshcd_is_clkgating_allowed(hba))
1703 return;
1704 device_remove_file(hba->dev, &hba->clk_gating.delay_attr);
1705 device_remove_file(hba->dev, &hba->clk_gating.enable_attr);
1706 cancel_work_sync(&hba->clk_gating.ungate_work);
1707 cancel_delayed_work_sync(&hba->clk_gating.gate_work);
1710 /* Must be called with host lock acquired */
1711 static void ufshcd_clk_scaling_start_busy(struct ufs_hba *hba)
1713 bool queue_resume_work = false;
1715 if (!ufshcd_is_clkscaling_supported(hba))
1716 return;
1718 if (!hba->clk_scaling.active_reqs++)
1719 queue_resume_work = true;
1721 if (!hba->clk_scaling.is_allowed || hba->pm_op_in_progress)
1722 return;
1724 if (queue_resume_work)
1725 queue_work(hba->clk_scaling.workq,
1726 &hba->clk_scaling.resume_work);
1728 if (!hba->clk_scaling.window_start_t) {
1729 hba->clk_scaling.window_start_t = jiffies;
1730 hba->clk_scaling.tot_busy_t = 0;
1731 hba->clk_scaling.is_busy_started = false;
1734 if (!hba->clk_scaling.is_busy_started) {
1735 hba->clk_scaling.busy_start_t = ktime_get();
1736 hba->clk_scaling.is_busy_started = true;
1740 static void ufshcd_clk_scaling_update_busy(struct ufs_hba *hba)
1742 struct ufs_clk_scaling *scaling = &hba->clk_scaling;
1744 if (!ufshcd_is_clkscaling_supported(hba))
1745 return;
1747 if (!hba->outstanding_reqs && scaling->is_busy_started) {
1748 scaling->tot_busy_t += ktime_to_us(ktime_sub(ktime_get(),
1749 scaling->busy_start_t));
1750 scaling->busy_start_t = 0;
1751 scaling->is_busy_started = false;
1755 * ufshcd_send_command - Send SCSI or device management commands
1756 * @hba: per adapter instance
1757 * @task_tag: Task tag of the command
1759 static inline
1760 void ufshcd_send_command(struct ufs_hba *hba, unsigned int task_tag)
1762 hba->lrb[task_tag].issue_time_stamp = ktime_get();
1763 hba->lrb[task_tag].compl_time_stamp = ktime_set(0, 0);
1764 ufshcd_clk_scaling_start_busy(hba);
1765 __set_bit(task_tag, &hba->outstanding_reqs);
1766 ufshcd_writel(hba, 1 << task_tag, REG_UTP_TRANSFER_REQ_DOOR_BELL);
1767 /* Make sure that doorbell is committed immediately */
1768 wmb();
1769 ufshcd_add_command_trace(hba, task_tag, "send");
1773 * ufshcd_copy_sense_data - Copy sense data in case of check condition
1774 * @lrbp: pointer to local reference block
1776 static inline void ufshcd_copy_sense_data(struct ufshcd_lrb *lrbp)
1778 int len;
1779 if (lrbp->sense_buffer &&
1780 ufshcd_get_rsp_upiu_data_seg_len(lrbp->ucd_rsp_ptr)) {
1781 int len_to_copy;
1783 len = be16_to_cpu(lrbp->ucd_rsp_ptr->sr.sense_data_len);
1784 len_to_copy = min_t(int, RESPONSE_UPIU_SENSE_DATA_LENGTH, len);
1786 memcpy(lrbp->sense_buffer,
1787 lrbp->ucd_rsp_ptr->sr.sense_data,
1788 min_t(int, len_to_copy, UFSHCD_REQ_SENSE_SIZE));
1793 * ufshcd_copy_query_response() - Copy the Query Response and the data
1794 * descriptor
1795 * @hba: per adapter instance
1796 * @lrbp: pointer to local reference block
1798 static
1799 int ufshcd_copy_query_response(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
1801 struct ufs_query_res *query_res = &hba->dev_cmd.query.response;
1803 memcpy(&query_res->upiu_res, &lrbp->ucd_rsp_ptr->qr, QUERY_OSF_SIZE);
1805 /* Get the descriptor */
1806 if (lrbp->ucd_rsp_ptr->qr.opcode == UPIU_QUERY_OPCODE_READ_DESC) {
1807 u8 *descp = (u8 *)lrbp->ucd_rsp_ptr +
1808 GENERAL_UPIU_REQUEST_SIZE;
1809 u16 resp_len;
1810 u16 buf_len;
1812 /* data segment length */
1813 resp_len = be32_to_cpu(lrbp->ucd_rsp_ptr->header.dword_2) &
1814 MASK_QUERY_DATA_SEG_LEN;
1815 buf_len = be16_to_cpu(
1816 hba->dev_cmd.query.request.upiu_req.length);
1817 if (likely(buf_len >= resp_len)) {
1818 memcpy(hba->dev_cmd.query.descriptor, descp, resp_len);
1819 } else {
1820 dev_warn(hba->dev,
1821 "%s: Response size is bigger than buffer",
1822 __func__);
1823 return -EINVAL;
1827 return 0;
1831 * ufshcd_hba_capabilities - Read controller capabilities
1832 * @hba: per adapter instance
1834 static inline void ufshcd_hba_capabilities(struct ufs_hba *hba)
1836 hba->capabilities = ufshcd_readl(hba, REG_CONTROLLER_CAPABILITIES);
1838 /* nutrs and nutmrs are 0 based values */
1839 hba->nutrs = (hba->capabilities & MASK_TRANSFER_REQUESTS_SLOTS) + 1;
1840 hba->nutmrs =
1841 ((hba->capabilities & MASK_TASK_MANAGEMENT_REQUEST_SLOTS) >> 16) + 1;
1845 * ufshcd_ready_for_uic_cmd - Check if controller is ready
1846 * to accept UIC commands
1847 * @hba: per adapter instance
1848 * Return true on success, else false
1850 static inline bool ufshcd_ready_for_uic_cmd(struct ufs_hba *hba)
1852 if (ufshcd_readl(hba, REG_CONTROLLER_STATUS) & UIC_COMMAND_READY)
1853 return true;
1854 else
1855 return false;
1859 * ufshcd_get_upmcrs - Get the power mode change request status
1860 * @hba: Pointer to adapter instance
1862 * This function gets the UPMCRS field of HCS register
1863 * Returns value of UPMCRS field
1865 static inline u8 ufshcd_get_upmcrs(struct ufs_hba *hba)
1867 return (ufshcd_readl(hba, REG_CONTROLLER_STATUS) >> 8) & 0x7;
1871 * ufshcd_dispatch_uic_cmd - Dispatch UIC commands to unipro layers
1872 * @hba: per adapter instance
1873 * @uic_cmd: UIC command
1875 * Mutex must be held.
1877 static inline void
1878 ufshcd_dispatch_uic_cmd(struct ufs_hba *hba, struct uic_command *uic_cmd)
1880 WARN_ON(hba->active_uic_cmd);
1882 hba->active_uic_cmd = uic_cmd;
1884 /* Write Args */
1885 ufshcd_writel(hba, uic_cmd->argument1, REG_UIC_COMMAND_ARG_1);
1886 ufshcd_writel(hba, uic_cmd->argument2, REG_UIC_COMMAND_ARG_2);
1887 ufshcd_writel(hba, uic_cmd->argument3, REG_UIC_COMMAND_ARG_3);
1889 /* Write UIC Cmd */
1890 ufshcd_writel(hba, uic_cmd->command & COMMAND_OPCODE_MASK,
1891 REG_UIC_COMMAND);
1895 * ufshcd_wait_for_uic_cmd - Wait complectioin of UIC command
1896 * @hba: per adapter instance
1897 * @uic_cmd: UIC command
1899 * Must be called with mutex held.
1900 * Returns 0 only if success.
1902 static int
1903 ufshcd_wait_for_uic_cmd(struct ufs_hba *hba, struct uic_command *uic_cmd)
1905 int ret;
1906 unsigned long flags;
1908 if (wait_for_completion_timeout(&uic_cmd->done,
1909 msecs_to_jiffies(UIC_CMD_TIMEOUT)))
1910 ret = uic_cmd->argument2 & MASK_UIC_COMMAND_RESULT;
1911 else
1912 ret = -ETIMEDOUT;
1914 spin_lock_irqsave(hba->host->host_lock, flags);
1915 hba->active_uic_cmd = NULL;
1916 spin_unlock_irqrestore(hba->host->host_lock, flags);
1918 return ret;
1922 * __ufshcd_send_uic_cmd - Send UIC commands and retrieve the result
1923 * @hba: per adapter instance
1924 * @uic_cmd: UIC command
1925 * @completion: initialize the completion only if this is set to true
1927 * Identical to ufshcd_send_uic_cmd() expect mutex. Must be called
1928 * with mutex held and host_lock locked.
1929 * Returns 0 only if success.
1931 static int
1932 __ufshcd_send_uic_cmd(struct ufs_hba *hba, struct uic_command *uic_cmd,
1933 bool completion)
1935 if (!ufshcd_ready_for_uic_cmd(hba)) {
1936 dev_err(hba->dev,
1937 "Controller not ready to accept UIC commands\n");
1938 return -EIO;
1941 if (completion)
1942 init_completion(&uic_cmd->done);
1944 ufshcd_dispatch_uic_cmd(hba, uic_cmd);
1946 return 0;
1950 * ufshcd_send_uic_cmd - Send UIC commands and retrieve the result
1951 * @hba: per adapter instance
1952 * @uic_cmd: UIC command
1954 * Returns 0 only if success.
1956 static int
1957 ufshcd_send_uic_cmd(struct ufs_hba *hba, struct uic_command *uic_cmd)
1959 int ret;
1960 unsigned long flags;
1962 ufshcd_hold(hba, false);
1963 mutex_lock(&hba->uic_cmd_mutex);
1964 ufshcd_add_delay_before_dme_cmd(hba);
1966 spin_lock_irqsave(hba->host->host_lock, flags);
1967 ret = __ufshcd_send_uic_cmd(hba, uic_cmd, true);
1968 spin_unlock_irqrestore(hba->host->host_lock, flags);
1969 if (!ret)
1970 ret = ufshcd_wait_for_uic_cmd(hba, uic_cmd);
1972 mutex_unlock(&hba->uic_cmd_mutex);
1974 ufshcd_release(hba);
1975 return ret;
1979 * ufshcd_map_sg - Map scatter-gather list to prdt
1980 * @hba: per adapter instance
1981 * @lrbp: pointer to local reference block
1983 * Returns 0 in case of success, non-zero value in case of failure
1985 static int ufshcd_map_sg(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
1987 struct ufshcd_sg_entry *prd_table;
1988 struct scatterlist *sg;
1989 struct scsi_cmnd *cmd;
1990 int sg_segments;
1991 int i;
1993 cmd = lrbp->cmd;
1994 sg_segments = scsi_dma_map(cmd);
1995 if (sg_segments < 0)
1996 return sg_segments;
1998 if (sg_segments) {
1999 if (hba->quirks & UFSHCD_QUIRK_PRDT_BYTE_GRAN)
2000 lrbp->utr_descriptor_ptr->prd_table_length =
2001 cpu_to_le16((u16)(sg_segments *
2002 sizeof(struct ufshcd_sg_entry)));
2003 else
2004 lrbp->utr_descriptor_ptr->prd_table_length =
2005 cpu_to_le16((u16) (sg_segments));
2007 prd_table = (struct ufshcd_sg_entry *)lrbp->ucd_prdt_ptr;
2009 scsi_for_each_sg(cmd, sg, sg_segments, i) {
2010 prd_table[i].size =
2011 cpu_to_le32(((u32) sg_dma_len(sg))-1);
2012 prd_table[i].base_addr =
2013 cpu_to_le32(lower_32_bits(sg->dma_address));
2014 prd_table[i].upper_addr =
2015 cpu_to_le32(upper_32_bits(sg->dma_address));
2016 prd_table[i].reserved = 0;
2018 } else {
2019 lrbp->utr_descriptor_ptr->prd_table_length = 0;
2022 return 0;
2026 * ufshcd_enable_intr - enable interrupts
2027 * @hba: per adapter instance
2028 * @intrs: interrupt bits
2030 static void ufshcd_enable_intr(struct ufs_hba *hba, u32 intrs)
2032 u32 set = ufshcd_readl(hba, REG_INTERRUPT_ENABLE);
2034 if (hba->ufs_version == UFSHCI_VERSION_10) {
2035 u32 rw;
2036 rw = set & INTERRUPT_MASK_RW_VER_10;
2037 set = rw | ((set ^ intrs) & intrs);
2038 } else {
2039 set |= intrs;
2042 ufshcd_writel(hba, set, REG_INTERRUPT_ENABLE);
2046 * ufshcd_disable_intr - disable interrupts
2047 * @hba: per adapter instance
2048 * @intrs: interrupt bits
2050 static void ufshcd_disable_intr(struct ufs_hba *hba, u32 intrs)
2052 u32 set = ufshcd_readl(hba, REG_INTERRUPT_ENABLE);
2054 if (hba->ufs_version == UFSHCI_VERSION_10) {
2055 u32 rw;
2056 rw = (set & INTERRUPT_MASK_RW_VER_10) &
2057 ~(intrs & INTERRUPT_MASK_RW_VER_10);
2058 set = rw | ((set & intrs) & ~INTERRUPT_MASK_RW_VER_10);
2060 } else {
2061 set &= ~intrs;
2064 ufshcd_writel(hba, set, REG_INTERRUPT_ENABLE);
2068 * ufshcd_prepare_req_desc_hdr() - Fills the requests header
2069 * descriptor according to request
2070 * @lrbp: pointer to local reference block
2071 * @upiu_flags: flags required in the header
2072 * @cmd_dir: requests data direction
2074 static void ufshcd_prepare_req_desc_hdr(struct ufshcd_lrb *lrbp,
2075 u32 *upiu_flags, enum dma_data_direction cmd_dir)
2077 struct utp_transfer_req_desc *req_desc = lrbp->utr_descriptor_ptr;
2078 u32 data_direction;
2079 u32 dword_0;
2081 if (cmd_dir == DMA_FROM_DEVICE) {
2082 data_direction = UTP_DEVICE_TO_HOST;
2083 *upiu_flags = UPIU_CMD_FLAGS_READ;
2084 } else if (cmd_dir == DMA_TO_DEVICE) {
2085 data_direction = UTP_HOST_TO_DEVICE;
2086 *upiu_flags = UPIU_CMD_FLAGS_WRITE;
2087 } else {
2088 data_direction = UTP_NO_DATA_TRANSFER;
2089 *upiu_flags = UPIU_CMD_FLAGS_NONE;
2092 dword_0 = data_direction | (lrbp->command_type
2093 << UPIU_COMMAND_TYPE_OFFSET);
2094 if (lrbp->intr_cmd)
2095 dword_0 |= UTP_REQ_DESC_INT_CMD;
2097 /* Transfer request descriptor header fields */
2098 req_desc->header.dword_0 = cpu_to_le32(dword_0);
2099 /* dword_1 is reserved, hence it is set to 0 */
2100 req_desc->header.dword_1 = 0;
2102 * assigning invalid value for command status. Controller
2103 * updates OCS on command completion, with the command
2104 * status
2106 req_desc->header.dword_2 =
2107 cpu_to_le32(OCS_INVALID_COMMAND_STATUS);
2108 /* dword_3 is reserved, hence it is set to 0 */
2109 req_desc->header.dword_3 = 0;
2111 req_desc->prd_table_length = 0;
2115 * ufshcd_prepare_utp_scsi_cmd_upiu() - fills the utp_transfer_req_desc,
2116 * for scsi commands
2117 * @lrbp: local reference block pointer
2118 * @upiu_flags: flags
2120 static
2121 void ufshcd_prepare_utp_scsi_cmd_upiu(struct ufshcd_lrb *lrbp, u32 upiu_flags)
2123 struct utp_upiu_req *ucd_req_ptr = lrbp->ucd_req_ptr;
2124 unsigned short cdb_len;
2126 /* command descriptor fields */
2127 ucd_req_ptr->header.dword_0 = UPIU_HEADER_DWORD(
2128 UPIU_TRANSACTION_COMMAND, upiu_flags,
2129 lrbp->lun, lrbp->task_tag);
2130 ucd_req_ptr->header.dword_1 = UPIU_HEADER_DWORD(
2131 UPIU_COMMAND_SET_TYPE_SCSI, 0, 0, 0);
2133 /* Total EHS length and Data segment length will be zero */
2134 ucd_req_ptr->header.dword_2 = 0;
2136 ucd_req_ptr->sc.exp_data_transfer_len =
2137 cpu_to_be32(lrbp->cmd->sdb.length);
2139 cdb_len = min_t(unsigned short, lrbp->cmd->cmd_len, MAX_CDB_SIZE);
2140 memset(ucd_req_ptr->sc.cdb, 0, MAX_CDB_SIZE);
2141 memcpy(ucd_req_ptr->sc.cdb, lrbp->cmd->cmnd, cdb_len);
2143 memset(lrbp->ucd_rsp_ptr, 0, sizeof(struct utp_upiu_rsp));
2147 * ufshcd_prepare_utp_query_req_upiu() - fills the utp_transfer_req_desc,
2148 * for query requsts
2149 * @hba: UFS hba
2150 * @lrbp: local reference block pointer
2151 * @upiu_flags: flags
2153 static void ufshcd_prepare_utp_query_req_upiu(struct ufs_hba *hba,
2154 struct ufshcd_lrb *lrbp, u32 upiu_flags)
2156 struct utp_upiu_req *ucd_req_ptr = lrbp->ucd_req_ptr;
2157 struct ufs_query *query = &hba->dev_cmd.query;
2158 u16 len = be16_to_cpu(query->request.upiu_req.length);
2159 u8 *descp = (u8 *)lrbp->ucd_req_ptr + GENERAL_UPIU_REQUEST_SIZE;
2161 /* Query request header */
2162 ucd_req_ptr->header.dword_0 = UPIU_HEADER_DWORD(
2163 UPIU_TRANSACTION_QUERY_REQ, upiu_flags,
2164 lrbp->lun, lrbp->task_tag);
2165 ucd_req_ptr->header.dword_1 = UPIU_HEADER_DWORD(
2166 0, query->request.query_func, 0, 0);
2168 /* Data segment length only need for WRITE_DESC */
2169 if (query->request.upiu_req.opcode == UPIU_QUERY_OPCODE_WRITE_DESC)
2170 ucd_req_ptr->header.dword_2 =
2171 UPIU_HEADER_DWORD(0, 0, (len >> 8), (u8)len);
2172 else
2173 ucd_req_ptr->header.dword_2 = 0;
2175 /* Copy the Query Request buffer as is */
2176 memcpy(&ucd_req_ptr->qr, &query->request.upiu_req,
2177 QUERY_OSF_SIZE);
2179 /* Copy the Descriptor */
2180 if (query->request.upiu_req.opcode == UPIU_QUERY_OPCODE_WRITE_DESC)
2181 memcpy(descp, query->descriptor, len);
2183 memset(lrbp->ucd_rsp_ptr, 0, sizeof(struct utp_upiu_rsp));
2186 static inline void ufshcd_prepare_utp_nop_upiu(struct ufshcd_lrb *lrbp)
2188 struct utp_upiu_req *ucd_req_ptr = lrbp->ucd_req_ptr;
2190 memset(ucd_req_ptr, 0, sizeof(struct utp_upiu_req));
2192 /* command descriptor fields */
2193 ucd_req_ptr->header.dword_0 =
2194 UPIU_HEADER_DWORD(
2195 UPIU_TRANSACTION_NOP_OUT, 0, 0, lrbp->task_tag);
2196 /* clear rest of the fields of basic header */
2197 ucd_req_ptr->header.dword_1 = 0;
2198 ucd_req_ptr->header.dword_2 = 0;
2200 memset(lrbp->ucd_rsp_ptr, 0, sizeof(struct utp_upiu_rsp));
2204 * ufshcd_comp_devman_upiu - UFS Protocol Information Unit(UPIU)
2205 * for Device Management Purposes
2206 * @hba: per adapter instance
2207 * @lrbp: pointer to local reference block
2209 static int ufshcd_comp_devman_upiu(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
2211 u32 upiu_flags;
2212 int ret = 0;
2214 if ((hba->ufs_version == UFSHCI_VERSION_10) ||
2215 (hba->ufs_version == UFSHCI_VERSION_11))
2216 lrbp->command_type = UTP_CMD_TYPE_DEV_MANAGE;
2217 else
2218 lrbp->command_type = UTP_CMD_TYPE_UFS_STORAGE;
2220 ufshcd_prepare_req_desc_hdr(lrbp, &upiu_flags, DMA_NONE);
2221 if (hba->dev_cmd.type == DEV_CMD_TYPE_QUERY)
2222 ufshcd_prepare_utp_query_req_upiu(hba, lrbp, upiu_flags);
2223 else if (hba->dev_cmd.type == DEV_CMD_TYPE_NOP)
2224 ufshcd_prepare_utp_nop_upiu(lrbp);
2225 else
2226 ret = -EINVAL;
2228 return ret;
2232 * ufshcd_comp_scsi_upiu - UFS Protocol Information Unit(UPIU)
2233 * for SCSI Purposes
2234 * @hba: per adapter instance
2235 * @lrbp: pointer to local reference block
2237 static int ufshcd_comp_scsi_upiu(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
2239 u32 upiu_flags;
2240 int ret = 0;
2242 if ((hba->ufs_version == UFSHCI_VERSION_10) ||
2243 (hba->ufs_version == UFSHCI_VERSION_11))
2244 lrbp->command_type = UTP_CMD_TYPE_SCSI;
2245 else
2246 lrbp->command_type = UTP_CMD_TYPE_UFS_STORAGE;
2248 if (likely(lrbp->cmd)) {
2249 ufshcd_prepare_req_desc_hdr(lrbp, &upiu_flags,
2250 lrbp->cmd->sc_data_direction);
2251 ufshcd_prepare_utp_scsi_cmd_upiu(lrbp, upiu_flags);
2252 } else {
2253 ret = -EINVAL;
2256 return ret;
2260 * ufshcd_upiu_wlun_to_scsi_wlun - maps UPIU W-LUN id to SCSI W-LUN ID
2261 * @upiu_wlun_id: UPIU W-LUN id
2263 * Returns SCSI W-LUN id
2265 static inline u16 ufshcd_upiu_wlun_to_scsi_wlun(u8 upiu_wlun_id)
2267 return (upiu_wlun_id & ~UFS_UPIU_WLUN_ID) | SCSI_W_LUN_BASE;
2271 * ufshcd_queuecommand - main entry point for SCSI requests
2272 * @host: SCSI host pointer
2273 * @cmd: command from SCSI Midlayer
2275 * Returns 0 for success, non-zero in case of failure
2277 static int ufshcd_queuecommand(struct Scsi_Host *host, struct scsi_cmnd *cmd)
2279 struct ufshcd_lrb *lrbp;
2280 struct ufs_hba *hba;
2281 unsigned long flags;
2282 int tag;
2283 int err = 0;
2285 hba = shost_priv(host);
2287 tag = cmd->request->tag;
2288 if (!ufshcd_valid_tag(hba, tag)) {
2289 dev_err(hba->dev,
2290 "%s: invalid command tag %d: cmd=0x%p, cmd->request=0x%p",
2291 __func__, tag, cmd, cmd->request);
2292 BUG();
2295 if (!down_read_trylock(&hba->clk_scaling_lock))
2296 return SCSI_MLQUEUE_HOST_BUSY;
2298 spin_lock_irqsave(hba->host->host_lock, flags);
2299 switch (hba->ufshcd_state) {
2300 case UFSHCD_STATE_OPERATIONAL:
2301 break;
2302 case UFSHCD_STATE_EH_SCHEDULED:
2303 case UFSHCD_STATE_RESET:
2304 err = SCSI_MLQUEUE_HOST_BUSY;
2305 goto out_unlock;
2306 case UFSHCD_STATE_ERROR:
2307 set_host_byte(cmd, DID_ERROR);
2308 cmd->scsi_done(cmd);
2309 goto out_unlock;
2310 default:
2311 dev_WARN_ONCE(hba->dev, 1, "%s: invalid state %d\n",
2312 __func__, hba->ufshcd_state);
2313 set_host_byte(cmd, DID_BAD_TARGET);
2314 cmd->scsi_done(cmd);
2315 goto out_unlock;
2318 /* if error handling is in progress, don't issue commands */
2319 if (ufshcd_eh_in_progress(hba)) {
2320 set_host_byte(cmd, DID_ERROR);
2321 cmd->scsi_done(cmd);
2322 goto out_unlock;
2324 spin_unlock_irqrestore(hba->host->host_lock, flags);
2326 hba->req_abort_count = 0;
2328 /* acquire the tag to make sure device cmds don't use it */
2329 if (test_and_set_bit_lock(tag, &hba->lrb_in_use)) {
2331 * Dev manage command in progress, requeue the command.
2332 * Requeuing the command helps in cases where the request *may*
2333 * find different tag instead of waiting for dev manage command
2334 * completion.
2336 err = SCSI_MLQUEUE_HOST_BUSY;
2337 goto out;
2340 err = ufshcd_hold(hba, true);
2341 if (err) {
2342 err = SCSI_MLQUEUE_HOST_BUSY;
2343 clear_bit_unlock(tag, &hba->lrb_in_use);
2344 goto out;
2346 WARN_ON(hba->clk_gating.state != CLKS_ON);
2348 lrbp = &hba->lrb[tag];
2350 WARN_ON(lrbp->cmd);
2351 lrbp->cmd = cmd;
2352 lrbp->sense_bufflen = UFSHCD_REQ_SENSE_SIZE;
2353 lrbp->sense_buffer = cmd->sense_buffer;
2354 lrbp->task_tag = tag;
2355 lrbp->lun = ufshcd_scsi_to_upiu_lun(cmd->device->lun);
2356 lrbp->intr_cmd = !ufshcd_is_intr_aggr_allowed(hba) ? true : false;
2357 lrbp->req_abort_skip = false;
2359 ufshcd_comp_scsi_upiu(hba, lrbp);
2361 err = ufshcd_map_sg(hba, lrbp);
2362 if (err) {
2363 lrbp->cmd = NULL;
2364 clear_bit_unlock(tag, &hba->lrb_in_use);
2365 goto out;
2367 /* Make sure descriptors are ready before ringing the doorbell */
2368 wmb();
2370 /* issue command to the controller */
2371 spin_lock_irqsave(hba->host->host_lock, flags);
2372 ufshcd_vops_setup_xfer_req(hba, tag, (lrbp->cmd ? true : false));
2373 ufshcd_send_command(hba, tag);
2374 out_unlock:
2375 spin_unlock_irqrestore(hba->host->host_lock, flags);
2376 out:
2377 up_read(&hba->clk_scaling_lock);
2378 return err;
2381 static int ufshcd_compose_dev_cmd(struct ufs_hba *hba,
2382 struct ufshcd_lrb *lrbp, enum dev_cmd_type cmd_type, int tag)
2384 lrbp->cmd = NULL;
2385 lrbp->sense_bufflen = 0;
2386 lrbp->sense_buffer = NULL;
2387 lrbp->task_tag = tag;
2388 lrbp->lun = 0; /* device management cmd is not specific to any LUN */
2389 lrbp->intr_cmd = true; /* No interrupt aggregation */
2390 hba->dev_cmd.type = cmd_type;
2392 return ufshcd_comp_devman_upiu(hba, lrbp);
2395 static int
2396 ufshcd_clear_cmd(struct ufs_hba *hba, int tag)
2398 int err = 0;
2399 unsigned long flags;
2400 u32 mask = 1 << tag;
2402 /* clear outstanding transaction before retry */
2403 spin_lock_irqsave(hba->host->host_lock, flags);
2404 ufshcd_utrl_clear(hba, tag);
2405 spin_unlock_irqrestore(hba->host->host_lock, flags);
2408 * wait for for h/w to clear corresponding bit in door-bell.
2409 * max. wait is 1 sec.
2411 err = ufshcd_wait_for_register(hba,
2412 REG_UTP_TRANSFER_REQ_DOOR_BELL,
2413 mask, ~mask, 1000, 1000, true);
2415 return err;
2418 static int
2419 ufshcd_check_query_response(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
2421 struct ufs_query_res *query_res = &hba->dev_cmd.query.response;
2423 /* Get the UPIU response */
2424 query_res->response = ufshcd_get_rsp_upiu_result(lrbp->ucd_rsp_ptr) >>
2425 UPIU_RSP_CODE_OFFSET;
2426 return query_res->response;
2430 * ufshcd_dev_cmd_completion() - handles device management command responses
2431 * @hba: per adapter instance
2432 * @lrbp: pointer to local reference block
2434 static int
2435 ufshcd_dev_cmd_completion(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
2437 int resp;
2438 int err = 0;
2440 hba->ufs_stats.last_hibern8_exit_tstamp = ktime_set(0, 0);
2441 resp = ufshcd_get_req_rsp(lrbp->ucd_rsp_ptr);
2443 switch (resp) {
2444 case UPIU_TRANSACTION_NOP_IN:
2445 if (hba->dev_cmd.type != DEV_CMD_TYPE_NOP) {
2446 err = -EINVAL;
2447 dev_err(hba->dev, "%s: unexpected response %x\n",
2448 __func__, resp);
2450 break;
2451 case UPIU_TRANSACTION_QUERY_RSP:
2452 err = ufshcd_check_query_response(hba, lrbp);
2453 if (!err)
2454 err = ufshcd_copy_query_response(hba, lrbp);
2455 break;
2456 case UPIU_TRANSACTION_REJECT_UPIU:
2457 /* TODO: handle Reject UPIU Response */
2458 err = -EPERM;
2459 dev_err(hba->dev, "%s: Reject UPIU not fully implemented\n",
2460 __func__);
2461 break;
2462 default:
2463 err = -EINVAL;
2464 dev_err(hba->dev, "%s: Invalid device management cmd response: %x\n",
2465 __func__, resp);
2466 break;
2469 return err;
2472 static int ufshcd_wait_for_dev_cmd(struct ufs_hba *hba,
2473 struct ufshcd_lrb *lrbp, int max_timeout)
2475 int err = 0;
2476 unsigned long time_left;
2477 unsigned long flags;
2479 time_left = wait_for_completion_timeout(hba->dev_cmd.complete,
2480 msecs_to_jiffies(max_timeout));
2482 /* Make sure descriptors are ready before ringing the doorbell */
2483 wmb();
2484 spin_lock_irqsave(hba->host->host_lock, flags);
2485 hba->dev_cmd.complete = NULL;
2486 if (likely(time_left)) {
2487 err = ufshcd_get_tr_ocs(lrbp);
2488 if (!err)
2489 err = ufshcd_dev_cmd_completion(hba, lrbp);
2491 spin_unlock_irqrestore(hba->host->host_lock, flags);
2493 if (!time_left) {
2494 err = -ETIMEDOUT;
2495 dev_dbg(hba->dev, "%s: dev_cmd request timedout, tag %d\n",
2496 __func__, lrbp->task_tag);
2497 if (!ufshcd_clear_cmd(hba, lrbp->task_tag))
2498 /* successfully cleared the command, retry if needed */
2499 err = -EAGAIN;
2501 * in case of an error, after clearing the doorbell,
2502 * we also need to clear the outstanding_request
2503 * field in hba
2505 ufshcd_outstanding_req_clear(hba, lrbp->task_tag);
2508 return err;
2512 * ufshcd_get_dev_cmd_tag - Get device management command tag
2513 * @hba: per-adapter instance
2514 * @tag_out: pointer to variable with available slot value
2516 * Get a free slot and lock it until device management command
2517 * completes.
2519 * Returns false if free slot is unavailable for locking, else
2520 * return true with tag value in @tag.
2522 static bool ufshcd_get_dev_cmd_tag(struct ufs_hba *hba, int *tag_out)
2524 int tag;
2525 bool ret = false;
2526 unsigned long tmp;
2528 if (!tag_out)
2529 goto out;
2531 do {
2532 tmp = ~hba->lrb_in_use;
2533 tag = find_last_bit(&tmp, hba->nutrs);
2534 if (tag >= hba->nutrs)
2535 goto out;
2536 } while (test_and_set_bit_lock(tag, &hba->lrb_in_use));
2538 *tag_out = tag;
2539 ret = true;
2540 out:
2541 return ret;
2544 static inline void ufshcd_put_dev_cmd_tag(struct ufs_hba *hba, int tag)
2546 clear_bit_unlock(tag, &hba->lrb_in_use);
2550 * ufshcd_exec_dev_cmd - API for sending device management requests
2551 * @hba: UFS hba
2552 * @cmd_type: specifies the type (NOP, Query...)
2553 * @timeout: time in seconds
2555 * NOTE: Since there is only one available tag for device management commands,
2556 * it is expected you hold the hba->dev_cmd.lock mutex.
2558 static int ufshcd_exec_dev_cmd(struct ufs_hba *hba,
2559 enum dev_cmd_type cmd_type, int timeout)
2561 struct ufshcd_lrb *lrbp;
2562 int err;
2563 int tag;
2564 struct completion wait;
2565 unsigned long flags;
2567 down_read(&hba->clk_scaling_lock);
2570 * Get free slot, sleep if slots are unavailable.
2571 * Even though we use wait_event() which sleeps indefinitely,
2572 * the maximum wait time is bounded by SCSI request timeout.
2574 wait_event(hba->dev_cmd.tag_wq, ufshcd_get_dev_cmd_tag(hba, &tag));
2576 init_completion(&wait);
2577 lrbp = &hba->lrb[tag];
2578 WARN_ON(lrbp->cmd);
2579 err = ufshcd_compose_dev_cmd(hba, lrbp, cmd_type, tag);
2580 if (unlikely(err))
2581 goto out_put_tag;
2583 hba->dev_cmd.complete = &wait;
2585 ufshcd_add_query_upiu_trace(hba, tag, "query_send");
2586 /* Make sure descriptors are ready before ringing the doorbell */
2587 wmb();
2588 spin_lock_irqsave(hba->host->host_lock, flags);
2589 ufshcd_vops_setup_xfer_req(hba, tag, (lrbp->cmd ? true : false));
2590 ufshcd_send_command(hba, tag);
2591 spin_unlock_irqrestore(hba->host->host_lock, flags);
2593 err = ufshcd_wait_for_dev_cmd(hba, lrbp, timeout);
2595 ufshcd_add_query_upiu_trace(hba, tag,
2596 err ? "query_complete_err" : "query_complete");
2598 out_put_tag:
2599 ufshcd_put_dev_cmd_tag(hba, tag);
2600 wake_up(&hba->dev_cmd.tag_wq);
2601 up_read(&hba->clk_scaling_lock);
2602 return err;
2606 * ufshcd_init_query() - init the query response and request parameters
2607 * @hba: per-adapter instance
2608 * @request: address of the request pointer to be initialized
2609 * @response: address of the response pointer to be initialized
2610 * @opcode: operation to perform
2611 * @idn: flag idn to access
2612 * @index: LU number to access
2613 * @selector: query/flag/descriptor further identification
2615 static inline void ufshcd_init_query(struct ufs_hba *hba,
2616 struct ufs_query_req **request, struct ufs_query_res **response,
2617 enum query_opcode opcode, u8 idn, u8 index, u8 selector)
2619 *request = &hba->dev_cmd.query.request;
2620 *response = &hba->dev_cmd.query.response;
2621 memset(*request, 0, sizeof(struct ufs_query_req));
2622 memset(*response, 0, sizeof(struct ufs_query_res));
2623 (*request)->upiu_req.opcode = opcode;
2624 (*request)->upiu_req.idn = idn;
2625 (*request)->upiu_req.index = index;
2626 (*request)->upiu_req.selector = selector;
2629 static int ufshcd_query_flag_retry(struct ufs_hba *hba,
2630 enum query_opcode opcode, enum flag_idn idn, bool *flag_res)
2632 int ret;
2633 int retries;
2635 for (retries = 0; retries < QUERY_REQ_RETRIES; retries++) {
2636 ret = ufshcd_query_flag(hba, opcode, idn, flag_res);
2637 if (ret)
2638 dev_dbg(hba->dev,
2639 "%s: failed with error %d, retries %d\n",
2640 __func__, ret, retries);
2641 else
2642 break;
2645 if (ret)
2646 dev_err(hba->dev,
2647 "%s: query attribute, opcode %d, idn %d, failed with error %d after %d retires\n",
2648 __func__, opcode, idn, ret, retries);
2649 return ret;
2653 * ufshcd_query_flag() - API function for sending flag query requests
2654 * @hba: per-adapter instance
2655 * @opcode: flag query to perform
2656 * @idn: flag idn to access
2657 * @flag_res: the flag value after the query request completes
2659 * Returns 0 for success, non-zero in case of failure
2661 int ufshcd_query_flag(struct ufs_hba *hba, enum query_opcode opcode,
2662 enum flag_idn idn, bool *flag_res)
2664 struct ufs_query_req *request = NULL;
2665 struct ufs_query_res *response = NULL;
2666 int err, index = 0, selector = 0;
2667 int timeout = QUERY_REQ_TIMEOUT;
2669 BUG_ON(!hba);
2671 ufshcd_hold(hba, false);
2672 mutex_lock(&hba->dev_cmd.lock);
2673 ufshcd_init_query(hba, &request, &response, opcode, idn, index,
2674 selector);
2676 switch (opcode) {
2677 case UPIU_QUERY_OPCODE_SET_FLAG:
2678 case UPIU_QUERY_OPCODE_CLEAR_FLAG:
2679 case UPIU_QUERY_OPCODE_TOGGLE_FLAG:
2680 request->query_func = UPIU_QUERY_FUNC_STANDARD_WRITE_REQUEST;
2681 break;
2682 case UPIU_QUERY_OPCODE_READ_FLAG:
2683 request->query_func = UPIU_QUERY_FUNC_STANDARD_READ_REQUEST;
2684 if (!flag_res) {
2685 /* No dummy reads */
2686 dev_err(hba->dev, "%s: Invalid argument for read request\n",
2687 __func__);
2688 err = -EINVAL;
2689 goto out_unlock;
2691 break;
2692 default:
2693 dev_err(hba->dev,
2694 "%s: Expected query flag opcode but got = %d\n",
2695 __func__, opcode);
2696 err = -EINVAL;
2697 goto out_unlock;
2700 err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_QUERY, timeout);
2702 if (err) {
2703 dev_err(hba->dev,
2704 "%s: Sending flag query for idn %d failed, err = %d\n",
2705 __func__, idn, err);
2706 goto out_unlock;
2709 if (flag_res)
2710 *flag_res = (be32_to_cpu(response->upiu_res.value) &
2711 MASK_QUERY_UPIU_FLAG_LOC) & 0x1;
2713 out_unlock:
2714 mutex_unlock(&hba->dev_cmd.lock);
2715 ufshcd_release(hba);
2716 return err;
2720 * ufshcd_query_attr - API function for sending attribute requests
2721 * @hba: per-adapter instance
2722 * @opcode: attribute opcode
2723 * @idn: attribute idn to access
2724 * @index: index field
2725 * @selector: selector field
2726 * @attr_val: the attribute value after the query request completes
2728 * Returns 0 for success, non-zero in case of failure
2730 int ufshcd_query_attr(struct ufs_hba *hba, enum query_opcode opcode,
2731 enum attr_idn idn, u8 index, u8 selector, u32 *attr_val)
2733 struct ufs_query_req *request = NULL;
2734 struct ufs_query_res *response = NULL;
2735 int err;
2737 BUG_ON(!hba);
2739 ufshcd_hold(hba, false);
2740 if (!attr_val) {
2741 dev_err(hba->dev, "%s: attribute value required for opcode 0x%x\n",
2742 __func__, opcode);
2743 err = -EINVAL;
2744 goto out;
2747 mutex_lock(&hba->dev_cmd.lock);
2748 ufshcd_init_query(hba, &request, &response, opcode, idn, index,
2749 selector);
2751 switch (opcode) {
2752 case UPIU_QUERY_OPCODE_WRITE_ATTR:
2753 request->query_func = UPIU_QUERY_FUNC_STANDARD_WRITE_REQUEST;
2754 request->upiu_req.value = cpu_to_be32(*attr_val);
2755 break;
2756 case UPIU_QUERY_OPCODE_READ_ATTR:
2757 request->query_func = UPIU_QUERY_FUNC_STANDARD_READ_REQUEST;
2758 break;
2759 default:
2760 dev_err(hba->dev, "%s: Expected query attr opcode but got = 0x%.2x\n",
2761 __func__, opcode);
2762 err = -EINVAL;
2763 goto out_unlock;
2766 err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_QUERY, QUERY_REQ_TIMEOUT);
2768 if (err) {
2769 dev_err(hba->dev, "%s: opcode 0x%.2x for idn %d failed, index %d, err = %d\n",
2770 __func__, opcode, idn, index, err);
2771 goto out_unlock;
2774 *attr_val = be32_to_cpu(response->upiu_res.value);
2776 out_unlock:
2777 mutex_unlock(&hba->dev_cmd.lock);
2778 out:
2779 ufshcd_release(hba);
2780 return err;
2784 * ufshcd_query_attr_retry() - API function for sending query
2785 * attribute with retries
2786 * @hba: per-adapter instance
2787 * @opcode: attribute opcode
2788 * @idn: attribute idn to access
2789 * @index: index field
2790 * @selector: selector field
2791 * @attr_val: the attribute value after the query request
2792 * completes
2794 * Returns 0 for success, non-zero in case of failure
2796 static int ufshcd_query_attr_retry(struct ufs_hba *hba,
2797 enum query_opcode opcode, enum attr_idn idn, u8 index, u8 selector,
2798 u32 *attr_val)
2800 int ret = 0;
2801 u32 retries;
2803 for (retries = QUERY_REQ_RETRIES; retries > 0; retries--) {
2804 ret = ufshcd_query_attr(hba, opcode, idn, index,
2805 selector, attr_val);
2806 if (ret)
2807 dev_dbg(hba->dev, "%s: failed with error %d, retries %d\n",
2808 __func__, ret, retries);
2809 else
2810 break;
2813 if (ret)
2814 dev_err(hba->dev,
2815 "%s: query attribute, idn %d, failed with error %d after %d retires\n",
2816 __func__, idn, ret, QUERY_REQ_RETRIES);
2817 return ret;
2820 static int __ufshcd_query_descriptor(struct ufs_hba *hba,
2821 enum query_opcode opcode, enum desc_idn idn, u8 index,
2822 u8 selector, u8 *desc_buf, int *buf_len)
2824 struct ufs_query_req *request = NULL;
2825 struct ufs_query_res *response = NULL;
2826 int err;
2828 BUG_ON(!hba);
2830 ufshcd_hold(hba, false);
2831 if (!desc_buf) {
2832 dev_err(hba->dev, "%s: descriptor buffer required for opcode 0x%x\n",
2833 __func__, opcode);
2834 err = -EINVAL;
2835 goto out;
2838 if (*buf_len < QUERY_DESC_MIN_SIZE || *buf_len > QUERY_DESC_MAX_SIZE) {
2839 dev_err(hba->dev, "%s: descriptor buffer size (%d) is out of range\n",
2840 __func__, *buf_len);
2841 err = -EINVAL;
2842 goto out;
2845 mutex_lock(&hba->dev_cmd.lock);
2846 ufshcd_init_query(hba, &request, &response, opcode, idn, index,
2847 selector);
2848 hba->dev_cmd.query.descriptor = desc_buf;
2849 request->upiu_req.length = cpu_to_be16(*buf_len);
2851 switch (opcode) {
2852 case UPIU_QUERY_OPCODE_WRITE_DESC:
2853 request->query_func = UPIU_QUERY_FUNC_STANDARD_WRITE_REQUEST;
2854 break;
2855 case UPIU_QUERY_OPCODE_READ_DESC:
2856 request->query_func = UPIU_QUERY_FUNC_STANDARD_READ_REQUEST;
2857 break;
2858 default:
2859 dev_err(hba->dev,
2860 "%s: Expected query descriptor opcode but got = 0x%.2x\n",
2861 __func__, opcode);
2862 err = -EINVAL;
2863 goto out_unlock;
2866 err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_QUERY, QUERY_REQ_TIMEOUT);
2868 if (err) {
2869 dev_err(hba->dev, "%s: opcode 0x%.2x for idn %d failed, index %d, err = %d\n",
2870 __func__, opcode, idn, index, err);
2871 goto out_unlock;
2874 hba->dev_cmd.query.descriptor = NULL;
2875 *buf_len = be16_to_cpu(response->upiu_res.length);
2877 out_unlock:
2878 mutex_unlock(&hba->dev_cmd.lock);
2879 out:
2880 ufshcd_release(hba);
2881 return err;
2885 * ufshcd_query_descriptor_retry - API function for sending descriptor requests
2886 * @hba: per-adapter instance
2887 * @opcode: attribute opcode
2888 * @idn: attribute idn to access
2889 * @index: index field
2890 * @selector: selector field
2891 * @desc_buf: the buffer that contains the descriptor
2892 * @buf_len: length parameter passed to the device
2894 * Returns 0 for success, non-zero in case of failure.
2895 * The buf_len parameter will contain, on return, the length parameter
2896 * received on the response.
2898 int ufshcd_query_descriptor_retry(struct ufs_hba *hba,
2899 enum query_opcode opcode,
2900 enum desc_idn idn, u8 index,
2901 u8 selector,
2902 u8 *desc_buf, int *buf_len)
2904 int err;
2905 int retries;
2907 for (retries = QUERY_REQ_RETRIES; retries > 0; retries--) {
2908 err = __ufshcd_query_descriptor(hba, opcode, idn, index,
2909 selector, desc_buf, buf_len);
2910 if (!err || err == -EINVAL)
2911 break;
2914 return err;
2918 * ufshcd_read_desc_length - read the specified descriptor length from header
2919 * @hba: Pointer to adapter instance
2920 * @desc_id: descriptor idn value
2921 * @desc_index: descriptor index
2922 * @desc_length: pointer to variable to read the length of descriptor
2924 * Return 0 in case of success, non-zero otherwise
2926 static int ufshcd_read_desc_length(struct ufs_hba *hba,
2927 enum desc_idn desc_id,
2928 int desc_index,
2929 int *desc_length)
2931 int ret;
2932 u8 header[QUERY_DESC_HDR_SIZE];
2933 int header_len = QUERY_DESC_HDR_SIZE;
2935 if (desc_id >= QUERY_DESC_IDN_MAX)
2936 return -EINVAL;
2938 ret = ufshcd_query_descriptor_retry(hba, UPIU_QUERY_OPCODE_READ_DESC,
2939 desc_id, desc_index, 0, header,
2940 &header_len);
2942 if (ret) {
2943 dev_err(hba->dev, "%s: Failed to get descriptor header id %d",
2944 __func__, desc_id);
2945 return ret;
2946 } else if (desc_id != header[QUERY_DESC_DESC_TYPE_OFFSET]) {
2947 dev_warn(hba->dev, "%s: descriptor header id %d and desc_id %d mismatch",
2948 __func__, header[QUERY_DESC_DESC_TYPE_OFFSET],
2949 desc_id);
2950 ret = -EINVAL;
2953 *desc_length = header[QUERY_DESC_LENGTH_OFFSET];
2954 return ret;
2959 * ufshcd_map_desc_id_to_length - map descriptor IDN to its length
2960 * @hba: Pointer to adapter instance
2961 * @desc_id: descriptor idn value
2962 * @desc_len: mapped desc length (out)
2964 * Return 0 in case of success, non-zero otherwise
2966 int ufshcd_map_desc_id_to_length(struct ufs_hba *hba,
2967 enum desc_idn desc_id, int *desc_len)
2969 switch (desc_id) {
2970 case QUERY_DESC_IDN_DEVICE:
2971 *desc_len = hba->desc_size.dev_desc;
2972 break;
2973 case QUERY_DESC_IDN_POWER:
2974 *desc_len = hba->desc_size.pwr_desc;
2975 break;
2976 case QUERY_DESC_IDN_GEOMETRY:
2977 *desc_len = hba->desc_size.geom_desc;
2978 break;
2979 case QUERY_DESC_IDN_CONFIGURATION:
2980 *desc_len = hba->desc_size.conf_desc;
2981 break;
2982 case QUERY_DESC_IDN_UNIT:
2983 *desc_len = hba->desc_size.unit_desc;
2984 break;
2985 case QUERY_DESC_IDN_INTERCONNECT:
2986 *desc_len = hba->desc_size.interc_desc;
2987 break;
2988 case QUERY_DESC_IDN_STRING:
2989 *desc_len = QUERY_DESC_MAX_SIZE;
2990 break;
2991 case QUERY_DESC_IDN_HEALTH:
2992 *desc_len = hba->desc_size.hlth_desc;
2993 break;
2994 case QUERY_DESC_IDN_RFU_0:
2995 case QUERY_DESC_IDN_RFU_1:
2996 *desc_len = 0;
2997 break;
2998 default:
2999 *desc_len = 0;
3000 return -EINVAL;
3002 return 0;
3004 EXPORT_SYMBOL(ufshcd_map_desc_id_to_length);
3007 * ufshcd_read_desc_param - read the specified descriptor parameter
3008 * @hba: Pointer to adapter instance
3009 * @desc_id: descriptor idn value
3010 * @desc_index: descriptor index
3011 * @param_offset: offset of the parameter to read
3012 * @param_read_buf: pointer to buffer where parameter would be read
3013 * @param_size: sizeof(param_read_buf)
3015 * Return 0 in case of success, non-zero otherwise
3017 int ufshcd_read_desc_param(struct ufs_hba *hba,
3018 enum desc_idn desc_id,
3019 int desc_index,
3020 u8 param_offset,
3021 u8 *param_read_buf,
3022 u8 param_size)
3024 int ret;
3025 u8 *desc_buf;
3026 int buff_len;
3027 bool is_kmalloc = true;
3029 /* Safety check */
3030 if (desc_id >= QUERY_DESC_IDN_MAX || !param_size)
3031 return -EINVAL;
3033 /* Get the max length of descriptor from structure filled up at probe
3034 * time.
3036 ret = ufshcd_map_desc_id_to_length(hba, desc_id, &buff_len);
3038 /* Sanity checks */
3039 if (ret || !buff_len) {
3040 dev_err(hba->dev, "%s: Failed to get full descriptor length",
3041 __func__);
3042 return ret;
3045 /* Check whether we need temp memory */
3046 if (param_offset != 0 || param_size < buff_len) {
3047 desc_buf = kmalloc(buff_len, GFP_KERNEL);
3048 if (!desc_buf)
3049 return -ENOMEM;
3050 } else {
3051 desc_buf = param_read_buf;
3052 is_kmalloc = false;
3055 /* Request for full descriptor */
3056 ret = ufshcd_query_descriptor_retry(hba, UPIU_QUERY_OPCODE_READ_DESC,
3057 desc_id, desc_index, 0,
3058 desc_buf, &buff_len);
3060 if (ret) {
3061 dev_err(hba->dev, "%s: Failed reading descriptor. desc_id %d, desc_index %d, param_offset %d, ret %d",
3062 __func__, desc_id, desc_index, param_offset, ret);
3063 goto out;
3066 /* Sanity check */
3067 if (desc_buf[QUERY_DESC_DESC_TYPE_OFFSET] != desc_id) {
3068 dev_err(hba->dev, "%s: invalid desc_id %d in descriptor header",
3069 __func__, desc_buf[QUERY_DESC_DESC_TYPE_OFFSET]);
3070 ret = -EINVAL;
3071 goto out;
3074 /* Check wherher we will not copy more data, than available */
3075 if (is_kmalloc && param_size > buff_len)
3076 param_size = buff_len;
3078 if (is_kmalloc)
3079 memcpy(param_read_buf, &desc_buf[param_offset], param_size);
3080 out:
3081 if (is_kmalloc)
3082 kfree(desc_buf);
3083 return ret;
3086 static inline int ufshcd_read_desc(struct ufs_hba *hba,
3087 enum desc_idn desc_id,
3088 int desc_index,
3089 u8 *buf,
3090 u32 size)
3092 return ufshcd_read_desc_param(hba, desc_id, desc_index, 0, buf, size);
3095 static inline int ufshcd_read_power_desc(struct ufs_hba *hba,
3096 u8 *buf,
3097 u32 size)
3099 return ufshcd_read_desc(hba, QUERY_DESC_IDN_POWER, 0, buf, size);
3102 static int ufshcd_read_device_desc(struct ufs_hba *hba, u8 *buf, u32 size)
3104 return ufshcd_read_desc(hba, QUERY_DESC_IDN_DEVICE, 0, buf, size);
3108 * ufshcd_read_string_desc - read string descriptor
3109 * @hba: pointer to adapter instance
3110 * @desc_index: descriptor index
3111 * @buf: pointer to buffer where descriptor would be read
3112 * @size: size of buf
3113 * @ascii: if true convert from unicode to ascii characters
3115 * Return 0 in case of success, non-zero otherwise
3117 int ufshcd_read_string_desc(struct ufs_hba *hba, int desc_index,
3118 u8 *buf, u32 size, bool ascii)
3120 int err = 0;
3122 err = ufshcd_read_desc(hba,
3123 QUERY_DESC_IDN_STRING, desc_index, buf, size);
3125 if (err) {
3126 dev_err(hba->dev, "%s: reading String Desc failed after %d retries. err = %d\n",
3127 __func__, QUERY_REQ_RETRIES, err);
3128 goto out;
3131 if (ascii) {
3132 int desc_len;
3133 int ascii_len;
3134 int i;
3135 char *buff_ascii;
3137 desc_len = buf[0];
3138 /* remove header and divide by 2 to move from UTF16 to UTF8 */
3139 ascii_len = (desc_len - QUERY_DESC_HDR_SIZE) / 2 + 1;
3140 if (size < ascii_len + QUERY_DESC_HDR_SIZE) {
3141 dev_err(hba->dev, "%s: buffer allocated size is too small\n",
3142 __func__);
3143 err = -ENOMEM;
3144 goto out;
3147 buff_ascii = kmalloc(ascii_len, GFP_KERNEL);
3148 if (!buff_ascii) {
3149 err = -ENOMEM;
3150 goto out;
3154 * the descriptor contains string in UTF16 format
3155 * we need to convert to utf-8 so it can be displayed
3157 utf16s_to_utf8s((wchar_t *)&buf[QUERY_DESC_HDR_SIZE],
3158 desc_len - QUERY_DESC_HDR_SIZE,
3159 UTF16_BIG_ENDIAN, buff_ascii, ascii_len);
3161 /* replace non-printable or non-ASCII characters with spaces */
3162 for (i = 0; i < ascii_len; i++)
3163 ufshcd_remove_non_printable(&buff_ascii[i]);
3165 memset(buf + QUERY_DESC_HDR_SIZE, 0,
3166 size - QUERY_DESC_HDR_SIZE);
3167 memcpy(buf + QUERY_DESC_HDR_SIZE, buff_ascii, ascii_len);
3168 buf[QUERY_DESC_LENGTH_OFFSET] = ascii_len + QUERY_DESC_HDR_SIZE;
3169 kfree(buff_ascii);
3171 out:
3172 return err;
3176 * ufshcd_read_unit_desc_param - read the specified unit descriptor parameter
3177 * @hba: Pointer to adapter instance
3178 * @lun: lun id
3179 * @param_offset: offset of the parameter to read
3180 * @param_read_buf: pointer to buffer where parameter would be read
3181 * @param_size: sizeof(param_read_buf)
3183 * Return 0 in case of success, non-zero otherwise
3185 static inline int ufshcd_read_unit_desc_param(struct ufs_hba *hba,
3186 int lun,
3187 enum unit_desc_param param_offset,
3188 u8 *param_read_buf,
3189 u32 param_size)
3192 * Unit descriptors are only available for general purpose LUs (LUN id
3193 * from 0 to 7) and RPMB Well known LU.
3195 if (!ufs_is_valid_unit_desc_lun(lun))
3196 return -EOPNOTSUPP;
3198 return ufshcd_read_desc_param(hba, QUERY_DESC_IDN_UNIT, lun,
3199 param_offset, param_read_buf, param_size);
3203 * ufshcd_memory_alloc - allocate memory for host memory space data structures
3204 * @hba: per adapter instance
3206 * 1. Allocate DMA memory for Command Descriptor array
3207 * Each command descriptor consist of Command UPIU, Response UPIU and PRDT
3208 * 2. Allocate DMA memory for UTP Transfer Request Descriptor List (UTRDL).
3209 * 3. Allocate DMA memory for UTP Task Management Request Descriptor List
3210 * (UTMRDL)
3211 * 4. Allocate memory for local reference block(lrb).
3213 * Returns 0 for success, non-zero in case of failure
3215 static int ufshcd_memory_alloc(struct ufs_hba *hba)
3217 size_t utmrdl_size, utrdl_size, ucdl_size;
3219 /* Allocate memory for UTP command descriptors */
3220 ucdl_size = (sizeof(struct utp_transfer_cmd_desc) * hba->nutrs);
3221 hba->ucdl_base_addr = dmam_alloc_coherent(hba->dev,
3222 ucdl_size,
3223 &hba->ucdl_dma_addr,
3224 GFP_KERNEL);
3227 * UFSHCI requires UTP command descriptor to be 128 byte aligned.
3228 * make sure hba->ucdl_dma_addr is aligned to PAGE_SIZE
3229 * if hba->ucdl_dma_addr is aligned to PAGE_SIZE, then it will
3230 * be aligned to 128 bytes as well
3232 if (!hba->ucdl_base_addr ||
3233 WARN_ON(hba->ucdl_dma_addr & (PAGE_SIZE - 1))) {
3234 dev_err(hba->dev,
3235 "Command Descriptor Memory allocation failed\n");
3236 goto out;
3240 * Allocate memory for UTP Transfer descriptors
3241 * UFSHCI requires 1024 byte alignment of UTRD
3243 utrdl_size = (sizeof(struct utp_transfer_req_desc) * hba->nutrs);
3244 hba->utrdl_base_addr = dmam_alloc_coherent(hba->dev,
3245 utrdl_size,
3246 &hba->utrdl_dma_addr,
3247 GFP_KERNEL);
3248 if (!hba->utrdl_base_addr ||
3249 WARN_ON(hba->utrdl_dma_addr & (PAGE_SIZE - 1))) {
3250 dev_err(hba->dev,
3251 "Transfer Descriptor Memory allocation failed\n");
3252 goto out;
3256 * Allocate memory for UTP Task Management descriptors
3257 * UFSHCI requires 1024 byte alignment of UTMRD
3259 utmrdl_size = sizeof(struct utp_task_req_desc) * hba->nutmrs;
3260 hba->utmrdl_base_addr = dmam_alloc_coherent(hba->dev,
3261 utmrdl_size,
3262 &hba->utmrdl_dma_addr,
3263 GFP_KERNEL);
3264 if (!hba->utmrdl_base_addr ||
3265 WARN_ON(hba->utmrdl_dma_addr & (PAGE_SIZE - 1))) {
3266 dev_err(hba->dev,
3267 "Task Management Descriptor Memory allocation failed\n");
3268 goto out;
3271 /* Allocate memory for local reference block */
3272 hba->lrb = devm_kzalloc(hba->dev,
3273 hba->nutrs * sizeof(struct ufshcd_lrb),
3274 GFP_KERNEL);
3275 if (!hba->lrb) {
3276 dev_err(hba->dev, "LRB Memory allocation failed\n");
3277 goto out;
3279 return 0;
3280 out:
3281 return -ENOMEM;
3285 * ufshcd_host_memory_configure - configure local reference block with
3286 * memory offsets
3287 * @hba: per adapter instance
3289 * Configure Host memory space
3290 * 1. Update Corresponding UTRD.UCDBA and UTRD.UCDBAU with UCD DMA
3291 * address.
3292 * 2. Update each UTRD with Response UPIU offset, Response UPIU length
3293 * and PRDT offset.
3294 * 3. Save the corresponding addresses of UTRD, UCD.CMD, UCD.RSP and UCD.PRDT
3295 * into local reference block.
3297 static void ufshcd_host_memory_configure(struct ufs_hba *hba)
3299 struct utp_transfer_cmd_desc *cmd_descp;
3300 struct utp_transfer_req_desc *utrdlp;
3301 dma_addr_t cmd_desc_dma_addr;
3302 dma_addr_t cmd_desc_element_addr;
3303 u16 response_offset;
3304 u16 prdt_offset;
3305 int cmd_desc_size;
3306 int i;
3308 utrdlp = hba->utrdl_base_addr;
3309 cmd_descp = hba->ucdl_base_addr;
3311 response_offset =
3312 offsetof(struct utp_transfer_cmd_desc, response_upiu);
3313 prdt_offset =
3314 offsetof(struct utp_transfer_cmd_desc, prd_table);
3316 cmd_desc_size = sizeof(struct utp_transfer_cmd_desc);
3317 cmd_desc_dma_addr = hba->ucdl_dma_addr;
3319 for (i = 0; i < hba->nutrs; i++) {
3320 /* Configure UTRD with command descriptor base address */
3321 cmd_desc_element_addr =
3322 (cmd_desc_dma_addr + (cmd_desc_size * i));
3323 utrdlp[i].command_desc_base_addr_lo =
3324 cpu_to_le32(lower_32_bits(cmd_desc_element_addr));
3325 utrdlp[i].command_desc_base_addr_hi =
3326 cpu_to_le32(upper_32_bits(cmd_desc_element_addr));
3328 /* Response upiu and prdt offset should be in double words */
3329 if (hba->quirks & UFSHCD_QUIRK_PRDT_BYTE_GRAN) {
3330 utrdlp[i].response_upiu_offset =
3331 cpu_to_le16(response_offset);
3332 utrdlp[i].prd_table_offset =
3333 cpu_to_le16(prdt_offset);
3334 utrdlp[i].response_upiu_length =
3335 cpu_to_le16(ALIGNED_UPIU_SIZE);
3336 } else {
3337 utrdlp[i].response_upiu_offset =
3338 cpu_to_le16((response_offset >> 2));
3339 utrdlp[i].prd_table_offset =
3340 cpu_to_le16((prdt_offset >> 2));
3341 utrdlp[i].response_upiu_length =
3342 cpu_to_le16(ALIGNED_UPIU_SIZE >> 2);
3345 hba->lrb[i].utr_descriptor_ptr = (utrdlp + i);
3346 hba->lrb[i].utrd_dma_addr = hba->utrdl_dma_addr +
3347 (i * sizeof(struct utp_transfer_req_desc));
3348 hba->lrb[i].ucd_req_ptr =
3349 (struct utp_upiu_req *)(cmd_descp + i);
3350 hba->lrb[i].ucd_req_dma_addr = cmd_desc_element_addr;
3351 hba->lrb[i].ucd_rsp_ptr =
3352 (struct utp_upiu_rsp *)cmd_descp[i].response_upiu;
3353 hba->lrb[i].ucd_rsp_dma_addr = cmd_desc_element_addr +
3354 response_offset;
3355 hba->lrb[i].ucd_prdt_ptr =
3356 (struct ufshcd_sg_entry *)cmd_descp[i].prd_table;
3357 hba->lrb[i].ucd_prdt_dma_addr = cmd_desc_element_addr +
3358 prdt_offset;
3363 * ufshcd_dme_link_startup - Notify Unipro to perform link startup
3364 * @hba: per adapter instance
3366 * UIC_CMD_DME_LINK_STARTUP command must be issued to Unipro layer,
3367 * in order to initialize the Unipro link startup procedure.
3368 * Once the Unipro links are up, the device connected to the controller
3369 * is detected.
3371 * Returns 0 on success, non-zero value on failure
3373 static int ufshcd_dme_link_startup(struct ufs_hba *hba)
3375 struct uic_command uic_cmd = {0};
3376 int ret;
3378 uic_cmd.command = UIC_CMD_DME_LINK_STARTUP;
3380 ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
3381 if (ret)
3382 dev_dbg(hba->dev,
3383 "dme-link-startup: error code %d\n", ret);
3384 return ret;
3387 static inline void ufshcd_add_delay_before_dme_cmd(struct ufs_hba *hba)
3389 #define MIN_DELAY_BEFORE_DME_CMDS_US 1000
3390 unsigned long min_sleep_time_us;
3392 if (!(hba->quirks & UFSHCD_QUIRK_DELAY_BEFORE_DME_CMDS))
3393 return;
3396 * last_dme_cmd_tstamp will be 0 only for 1st call to
3397 * this function
3399 if (unlikely(!ktime_to_us(hba->last_dme_cmd_tstamp))) {
3400 min_sleep_time_us = MIN_DELAY_BEFORE_DME_CMDS_US;
3401 } else {
3402 unsigned long delta =
3403 (unsigned long) ktime_to_us(
3404 ktime_sub(ktime_get(),
3405 hba->last_dme_cmd_tstamp));
3407 if (delta < MIN_DELAY_BEFORE_DME_CMDS_US)
3408 min_sleep_time_us =
3409 MIN_DELAY_BEFORE_DME_CMDS_US - delta;
3410 else
3411 return; /* no more delay required */
3414 /* allow sleep for extra 50us if needed */
3415 usleep_range(min_sleep_time_us, min_sleep_time_us + 50);
3419 * ufshcd_dme_set_attr - UIC command for DME_SET, DME_PEER_SET
3420 * @hba: per adapter instance
3421 * @attr_sel: uic command argument1
3422 * @attr_set: attribute set type as uic command argument2
3423 * @mib_val: setting value as uic command argument3
3424 * @peer: indicate whether peer or local
3426 * Returns 0 on success, non-zero value on failure
3428 int ufshcd_dme_set_attr(struct ufs_hba *hba, u32 attr_sel,
3429 u8 attr_set, u32 mib_val, u8 peer)
3431 struct uic_command uic_cmd = {0};
3432 static const char *const action[] = {
3433 "dme-set",
3434 "dme-peer-set"
3436 const char *set = action[!!peer];
3437 int ret;
3438 int retries = UFS_UIC_COMMAND_RETRIES;
3440 uic_cmd.command = peer ?
3441 UIC_CMD_DME_PEER_SET : UIC_CMD_DME_SET;
3442 uic_cmd.argument1 = attr_sel;
3443 uic_cmd.argument2 = UIC_ARG_ATTR_TYPE(attr_set);
3444 uic_cmd.argument3 = mib_val;
3446 do {
3447 /* for peer attributes we retry upon failure */
3448 ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
3449 if (ret)
3450 dev_dbg(hba->dev, "%s: attr-id 0x%x val 0x%x error code %d\n",
3451 set, UIC_GET_ATTR_ID(attr_sel), mib_val, ret);
3452 } while (ret && peer && --retries);
3454 if (ret)
3455 dev_err(hba->dev, "%s: attr-id 0x%x val 0x%x failed %d retries\n",
3456 set, UIC_GET_ATTR_ID(attr_sel), mib_val,
3457 UFS_UIC_COMMAND_RETRIES - retries);
3459 return ret;
3461 EXPORT_SYMBOL_GPL(ufshcd_dme_set_attr);
3464 * ufshcd_dme_get_attr - UIC command for DME_GET, DME_PEER_GET
3465 * @hba: per adapter instance
3466 * @attr_sel: uic command argument1
3467 * @mib_val: the value of the attribute as returned by the UIC command
3468 * @peer: indicate whether peer or local
3470 * Returns 0 on success, non-zero value on failure
3472 int ufshcd_dme_get_attr(struct ufs_hba *hba, u32 attr_sel,
3473 u32 *mib_val, u8 peer)
3475 struct uic_command uic_cmd = {0};
3476 static const char *const action[] = {
3477 "dme-get",
3478 "dme-peer-get"
3480 const char *get = action[!!peer];
3481 int ret;
3482 int retries = UFS_UIC_COMMAND_RETRIES;
3483 struct ufs_pa_layer_attr orig_pwr_info;
3484 struct ufs_pa_layer_attr temp_pwr_info;
3485 bool pwr_mode_change = false;
3487 if (peer && (hba->quirks & UFSHCD_QUIRK_DME_PEER_ACCESS_AUTO_MODE)) {
3488 orig_pwr_info = hba->pwr_info;
3489 temp_pwr_info = orig_pwr_info;
3491 if (orig_pwr_info.pwr_tx == FAST_MODE ||
3492 orig_pwr_info.pwr_rx == FAST_MODE) {
3493 temp_pwr_info.pwr_tx = FASTAUTO_MODE;
3494 temp_pwr_info.pwr_rx = FASTAUTO_MODE;
3495 pwr_mode_change = true;
3496 } else if (orig_pwr_info.pwr_tx == SLOW_MODE ||
3497 orig_pwr_info.pwr_rx == SLOW_MODE) {
3498 temp_pwr_info.pwr_tx = SLOWAUTO_MODE;
3499 temp_pwr_info.pwr_rx = SLOWAUTO_MODE;
3500 pwr_mode_change = true;
3502 if (pwr_mode_change) {
3503 ret = ufshcd_change_power_mode(hba, &temp_pwr_info);
3504 if (ret)
3505 goto out;
3509 uic_cmd.command = peer ?
3510 UIC_CMD_DME_PEER_GET : UIC_CMD_DME_GET;
3511 uic_cmd.argument1 = attr_sel;
3513 do {
3514 /* for peer attributes we retry upon failure */
3515 ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
3516 if (ret)
3517 dev_dbg(hba->dev, "%s: attr-id 0x%x error code %d\n",
3518 get, UIC_GET_ATTR_ID(attr_sel), ret);
3519 } while (ret && peer && --retries);
3521 if (ret)
3522 dev_err(hba->dev, "%s: attr-id 0x%x failed %d retries\n",
3523 get, UIC_GET_ATTR_ID(attr_sel),
3524 UFS_UIC_COMMAND_RETRIES - retries);
3526 if (mib_val && !ret)
3527 *mib_val = uic_cmd.argument3;
3529 if (peer && (hba->quirks & UFSHCD_QUIRK_DME_PEER_ACCESS_AUTO_MODE)
3530 && pwr_mode_change)
3531 ufshcd_change_power_mode(hba, &orig_pwr_info);
3532 out:
3533 return ret;
3535 EXPORT_SYMBOL_GPL(ufshcd_dme_get_attr);
3538 * ufshcd_uic_pwr_ctrl - executes UIC commands (which affects the link power
3539 * state) and waits for it to take effect.
3541 * @hba: per adapter instance
3542 * @cmd: UIC command to execute
3544 * DME operations like DME_SET(PA_PWRMODE), DME_HIBERNATE_ENTER &
3545 * DME_HIBERNATE_EXIT commands take some time to take its effect on both host
3546 * and device UniPro link and hence it's final completion would be indicated by
3547 * dedicated status bits in Interrupt Status register (UPMS, UHES, UHXS) in
3548 * addition to normal UIC command completion Status (UCCS). This function only
3549 * returns after the relevant status bits indicate the completion.
3551 * Returns 0 on success, non-zero value on failure
3553 static int ufshcd_uic_pwr_ctrl(struct ufs_hba *hba, struct uic_command *cmd)
3555 struct completion uic_async_done;
3556 unsigned long flags;
3557 u8 status;
3558 int ret;
3559 bool reenable_intr = false;
3561 mutex_lock(&hba->uic_cmd_mutex);
3562 init_completion(&uic_async_done);
3563 ufshcd_add_delay_before_dme_cmd(hba);
3565 spin_lock_irqsave(hba->host->host_lock, flags);
3566 hba->uic_async_done = &uic_async_done;
3567 if (ufshcd_readl(hba, REG_INTERRUPT_ENABLE) & UIC_COMMAND_COMPL) {
3568 ufshcd_disable_intr(hba, UIC_COMMAND_COMPL);
3570 * Make sure UIC command completion interrupt is disabled before
3571 * issuing UIC command.
3573 wmb();
3574 reenable_intr = true;
3576 ret = __ufshcd_send_uic_cmd(hba, cmd, false);
3577 spin_unlock_irqrestore(hba->host->host_lock, flags);
3578 if (ret) {
3579 dev_err(hba->dev,
3580 "pwr ctrl cmd 0x%x with mode 0x%x uic error %d\n",
3581 cmd->command, cmd->argument3, ret);
3582 goto out;
3585 if (!wait_for_completion_timeout(hba->uic_async_done,
3586 msecs_to_jiffies(UIC_CMD_TIMEOUT))) {
3587 dev_err(hba->dev,
3588 "pwr ctrl cmd 0x%x with mode 0x%x completion timeout\n",
3589 cmd->command, cmd->argument3);
3590 ret = -ETIMEDOUT;
3591 goto out;
3594 status = ufshcd_get_upmcrs(hba);
3595 if (status != PWR_LOCAL) {
3596 dev_err(hba->dev,
3597 "pwr ctrl cmd 0x%x failed, host upmcrs:0x%x\n",
3598 cmd->command, status);
3599 ret = (status != PWR_OK) ? status : -1;
3601 out:
3602 if (ret) {
3603 ufshcd_print_host_state(hba);
3604 ufshcd_print_pwr_info(hba);
3605 ufshcd_print_host_regs(hba);
3608 spin_lock_irqsave(hba->host->host_lock, flags);
3609 hba->active_uic_cmd = NULL;
3610 hba->uic_async_done = NULL;
3611 if (reenable_intr)
3612 ufshcd_enable_intr(hba, UIC_COMMAND_COMPL);
3613 spin_unlock_irqrestore(hba->host->host_lock, flags);
3614 mutex_unlock(&hba->uic_cmd_mutex);
3616 return ret;
3620 * ufshcd_uic_change_pwr_mode - Perform the UIC power mode chage
3621 * using DME_SET primitives.
3622 * @hba: per adapter instance
3623 * @mode: powr mode value
3625 * Returns 0 on success, non-zero value on failure
3627 static int ufshcd_uic_change_pwr_mode(struct ufs_hba *hba, u8 mode)
3629 struct uic_command uic_cmd = {0};
3630 int ret;
3632 if (hba->quirks & UFSHCD_QUIRK_BROKEN_PA_RXHSUNTERMCAP) {
3633 ret = ufshcd_dme_set(hba,
3634 UIC_ARG_MIB_SEL(PA_RXHSUNTERMCAP, 0), 1);
3635 if (ret) {
3636 dev_err(hba->dev, "%s: failed to enable PA_RXHSUNTERMCAP ret %d\n",
3637 __func__, ret);
3638 goto out;
3642 uic_cmd.command = UIC_CMD_DME_SET;
3643 uic_cmd.argument1 = UIC_ARG_MIB(PA_PWRMODE);
3644 uic_cmd.argument3 = mode;
3645 ufshcd_hold(hba, false);
3646 ret = ufshcd_uic_pwr_ctrl(hba, &uic_cmd);
3647 ufshcd_release(hba);
3649 out:
3650 return ret;
3653 static int ufshcd_link_recovery(struct ufs_hba *hba)
3655 int ret;
3656 unsigned long flags;
3658 spin_lock_irqsave(hba->host->host_lock, flags);
3659 hba->ufshcd_state = UFSHCD_STATE_RESET;
3660 ufshcd_set_eh_in_progress(hba);
3661 spin_unlock_irqrestore(hba->host->host_lock, flags);
3663 ret = ufshcd_host_reset_and_restore(hba);
3665 spin_lock_irqsave(hba->host->host_lock, flags);
3666 if (ret)
3667 hba->ufshcd_state = UFSHCD_STATE_ERROR;
3668 ufshcd_clear_eh_in_progress(hba);
3669 spin_unlock_irqrestore(hba->host->host_lock, flags);
3671 if (ret)
3672 dev_err(hba->dev, "%s: link recovery failed, err %d",
3673 __func__, ret);
3675 return ret;
3678 static int __ufshcd_uic_hibern8_enter(struct ufs_hba *hba)
3680 int ret;
3681 struct uic_command uic_cmd = {0};
3682 ktime_t start = ktime_get();
3684 ufshcd_vops_hibern8_notify(hba, UIC_CMD_DME_HIBER_ENTER, PRE_CHANGE);
3686 uic_cmd.command = UIC_CMD_DME_HIBER_ENTER;
3687 ret = ufshcd_uic_pwr_ctrl(hba, &uic_cmd);
3688 trace_ufshcd_profile_hibern8(dev_name(hba->dev), "enter",
3689 ktime_to_us(ktime_sub(ktime_get(), start)), ret);
3691 if (ret) {
3692 dev_err(hba->dev, "%s: hibern8 enter failed. ret = %d\n",
3693 __func__, ret);
3696 * If link recovery fails then return error so that caller
3697 * don't retry the hibern8 enter again.
3699 if (ufshcd_link_recovery(hba))
3700 ret = -ENOLINK;
3701 } else
3702 ufshcd_vops_hibern8_notify(hba, UIC_CMD_DME_HIBER_ENTER,
3703 POST_CHANGE);
3705 return ret;
3708 static int ufshcd_uic_hibern8_enter(struct ufs_hba *hba)
3710 int ret = 0, retries;
3712 for (retries = UIC_HIBERN8_ENTER_RETRIES; retries > 0; retries--) {
3713 ret = __ufshcd_uic_hibern8_enter(hba);
3714 if (!ret || ret == -ENOLINK)
3715 goto out;
3717 out:
3718 return ret;
3721 static int ufshcd_uic_hibern8_exit(struct ufs_hba *hba)
3723 struct uic_command uic_cmd = {0};
3724 int ret;
3725 ktime_t start = ktime_get();
3727 ufshcd_vops_hibern8_notify(hba, UIC_CMD_DME_HIBER_EXIT, PRE_CHANGE);
3729 uic_cmd.command = UIC_CMD_DME_HIBER_EXIT;
3730 ret = ufshcd_uic_pwr_ctrl(hba, &uic_cmd);
3731 trace_ufshcd_profile_hibern8(dev_name(hba->dev), "exit",
3732 ktime_to_us(ktime_sub(ktime_get(), start)), ret);
3734 if (ret) {
3735 dev_err(hba->dev, "%s: hibern8 exit failed. ret = %d\n",
3736 __func__, ret);
3737 ret = ufshcd_link_recovery(hba);
3738 } else {
3739 ufshcd_vops_hibern8_notify(hba, UIC_CMD_DME_HIBER_EXIT,
3740 POST_CHANGE);
3741 hba->ufs_stats.last_hibern8_exit_tstamp = ktime_get();
3742 hba->ufs_stats.hibern8_exit_cnt++;
3745 return ret;
3748 static void ufshcd_auto_hibern8_enable(struct ufs_hba *hba)
3750 unsigned long flags;
3752 if (!(hba->capabilities & MASK_AUTO_HIBERN8_SUPPORT) || !hba->ahit)
3753 return;
3755 spin_lock_irqsave(hba->host->host_lock, flags);
3756 ufshcd_writel(hba, hba->ahit, REG_AUTO_HIBERNATE_IDLE_TIMER);
3757 spin_unlock_irqrestore(hba->host->host_lock, flags);
3761 * ufshcd_init_pwr_info - setting the POR (power on reset)
3762 * values in hba power info
3763 * @hba: per-adapter instance
3765 static void ufshcd_init_pwr_info(struct ufs_hba *hba)
3767 hba->pwr_info.gear_rx = UFS_PWM_G1;
3768 hba->pwr_info.gear_tx = UFS_PWM_G1;
3769 hba->pwr_info.lane_rx = 1;
3770 hba->pwr_info.lane_tx = 1;
3771 hba->pwr_info.pwr_rx = SLOWAUTO_MODE;
3772 hba->pwr_info.pwr_tx = SLOWAUTO_MODE;
3773 hba->pwr_info.hs_rate = 0;
3777 * ufshcd_get_max_pwr_mode - reads the max power mode negotiated with device
3778 * @hba: per-adapter instance
3780 static int ufshcd_get_max_pwr_mode(struct ufs_hba *hba)
3782 struct ufs_pa_layer_attr *pwr_info = &hba->max_pwr_info.info;
3784 if (hba->max_pwr_info.is_valid)
3785 return 0;
3787 pwr_info->pwr_tx = FAST_MODE;
3788 pwr_info->pwr_rx = FAST_MODE;
3789 pwr_info->hs_rate = PA_HS_MODE_B;
3791 /* Get the connected lane count */
3792 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_CONNECTEDRXDATALANES),
3793 &pwr_info->lane_rx);
3794 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_CONNECTEDTXDATALANES),
3795 &pwr_info->lane_tx);
3797 if (!pwr_info->lane_rx || !pwr_info->lane_tx) {
3798 dev_err(hba->dev, "%s: invalid connected lanes value. rx=%d, tx=%d\n",
3799 __func__,
3800 pwr_info->lane_rx,
3801 pwr_info->lane_tx);
3802 return -EINVAL;
3806 * First, get the maximum gears of HS speed.
3807 * If a zero value, it means there is no HSGEAR capability.
3808 * Then, get the maximum gears of PWM speed.
3810 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_MAXRXHSGEAR), &pwr_info->gear_rx);
3811 if (!pwr_info->gear_rx) {
3812 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_MAXRXPWMGEAR),
3813 &pwr_info->gear_rx);
3814 if (!pwr_info->gear_rx) {
3815 dev_err(hba->dev, "%s: invalid max pwm rx gear read = %d\n",
3816 __func__, pwr_info->gear_rx);
3817 return -EINVAL;
3819 pwr_info->pwr_rx = SLOW_MODE;
3822 ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_MAXRXHSGEAR),
3823 &pwr_info->gear_tx);
3824 if (!pwr_info->gear_tx) {
3825 ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_MAXRXPWMGEAR),
3826 &pwr_info->gear_tx);
3827 if (!pwr_info->gear_tx) {
3828 dev_err(hba->dev, "%s: invalid max pwm tx gear read = %d\n",
3829 __func__, pwr_info->gear_tx);
3830 return -EINVAL;
3832 pwr_info->pwr_tx = SLOW_MODE;
3835 hba->max_pwr_info.is_valid = true;
3836 return 0;
3839 static int ufshcd_change_power_mode(struct ufs_hba *hba,
3840 struct ufs_pa_layer_attr *pwr_mode)
3842 int ret;
3844 /* if already configured to the requested pwr_mode */
3845 if (pwr_mode->gear_rx == hba->pwr_info.gear_rx &&
3846 pwr_mode->gear_tx == hba->pwr_info.gear_tx &&
3847 pwr_mode->lane_rx == hba->pwr_info.lane_rx &&
3848 pwr_mode->lane_tx == hba->pwr_info.lane_tx &&
3849 pwr_mode->pwr_rx == hba->pwr_info.pwr_rx &&
3850 pwr_mode->pwr_tx == hba->pwr_info.pwr_tx &&
3851 pwr_mode->hs_rate == hba->pwr_info.hs_rate) {
3852 dev_dbg(hba->dev, "%s: power already configured\n", __func__);
3853 return 0;
3857 * Configure attributes for power mode change with below.
3858 * - PA_RXGEAR, PA_ACTIVERXDATALANES, PA_RXTERMINATION,
3859 * - PA_TXGEAR, PA_ACTIVETXDATALANES, PA_TXTERMINATION,
3860 * - PA_HSSERIES
3862 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_RXGEAR), pwr_mode->gear_rx);
3863 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_ACTIVERXDATALANES),
3864 pwr_mode->lane_rx);
3865 if (pwr_mode->pwr_rx == FASTAUTO_MODE ||
3866 pwr_mode->pwr_rx == FAST_MODE)
3867 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_RXTERMINATION), TRUE);
3868 else
3869 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_RXTERMINATION), FALSE);
3871 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TXGEAR), pwr_mode->gear_tx);
3872 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_ACTIVETXDATALANES),
3873 pwr_mode->lane_tx);
3874 if (pwr_mode->pwr_tx == FASTAUTO_MODE ||
3875 pwr_mode->pwr_tx == FAST_MODE)
3876 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TXTERMINATION), TRUE);
3877 else
3878 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TXTERMINATION), FALSE);
3880 if (pwr_mode->pwr_rx == FASTAUTO_MODE ||
3881 pwr_mode->pwr_tx == FASTAUTO_MODE ||
3882 pwr_mode->pwr_rx == FAST_MODE ||
3883 pwr_mode->pwr_tx == FAST_MODE)
3884 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_HSSERIES),
3885 pwr_mode->hs_rate);
3887 ret = ufshcd_uic_change_pwr_mode(hba, pwr_mode->pwr_rx << 4
3888 | pwr_mode->pwr_tx);
3890 if (ret) {
3891 dev_err(hba->dev,
3892 "%s: power mode change failed %d\n", __func__, ret);
3893 } else {
3894 ufshcd_vops_pwr_change_notify(hba, POST_CHANGE, NULL,
3895 pwr_mode);
3897 memcpy(&hba->pwr_info, pwr_mode,
3898 sizeof(struct ufs_pa_layer_attr));
3901 return ret;
3905 * ufshcd_config_pwr_mode - configure a new power mode
3906 * @hba: per-adapter instance
3907 * @desired_pwr_mode: desired power configuration
3909 static int ufshcd_config_pwr_mode(struct ufs_hba *hba,
3910 struct ufs_pa_layer_attr *desired_pwr_mode)
3912 struct ufs_pa_layer_attr final_params = { 0 };
3913 int ret;
3915 ret = ufshcd_vops_pwr_change_notify(hba, PRE_CHANGE,
3916 desired_pwr_mode, &final_params);
3918 if (ret)
3919 memcpy(&final_params, desired_pwr_mode, sizeof(final_params));
3921 ret = ufshcd_change_power_mode(hba, &final_params);
3922 if (!ret)
3923 ufshcd_print_pwr_info(hba);
3925 return ret;
3929 * ufshcd_complete_dev_init() - checks device readiness
3930 * @hba: per-adapter instance
3932 * Set fDeviceInit flag and poll until device toggles it.
3934 static int ufshcd_complete_dev_init(struct ufs_hba *hba)
3936 int i;
3937 int err;
3938 bool flag_res = 1;
3940 err = ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_SET_FLAG,
3941 QUERY_FLAG_IDN_FDEVICEINIT, NULL);
3942 if (err) {
3943 dev_err(hba->dev,
3944 "%s setting fDeviceInit flag failed with error %d\n",
3945 __func__, err);
3946 goto out;
3949 /* poll for max. 1000 iterations for fDeviceInit flag to clear */
3950 for (i = 0; i < 1000 && !err && flag_res; i++)
3951 err = ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_READ_FLAG,
3952 QUERY_FLAG_IDN_FDEVICEINIT, &flag_res);
3954 if (err)
3955 dev_err(hba->dev,
3956 "%s reading fDeviceInit flag failed with error %d\n",
3957 __func__, err);
3958 else if (flag_res)
3959 dev_err(hba->dev,
3960 "%s fDeviceInit was not cleared by the device\n",
3961 __func__);
3963 out:
3964 return err;
3968 * ufshcd_make_hba_operational - Make UFS controller operational
3969 * @hba: per adapter instance
3971 * To bring UFS host controller to operational state,
3972 * 1. Enable required interrupts
3973 * 2. Configure interrupt aggregation
3974 * 3. Program UTRL and UTMRL base address
3975 * 4. Configure run-stop-registers
3977 * Returns 0 on success, non-zero value on failure
3979 static int ufshcd_make_hba_operational(struct ufs_hba *hba)
3981 int err = 0;
3982 u32 reg;
3984 /* Enable required interrupts */
3985 ufshcd_enable_intr(hba, UFSHCD_ENABLE_INTRS);
3987 /* Configure interrupt aggregation */
3988 if (ufshcd_is_intr_aggr_allowed(hba))
3989 ufshcd_config_intr_aggr(hba, hba->nutrs - 1, INT_AGGR_DEF_TO);
3990 else
3991 ufshcd_disable_intr_aggr(hba);
3993 /* Configure UTRL and UTMRL base address registers */
3994 ufshcd_writel(hba, lower_32_bits(hba->utrdl_dma_addr),
3995 REG_UTP_TRANSFER_REQ_LIST_BASE_L);
3996 ufshcd_writel(hba, upper_32_bits(hba->utrdl_dma_addr),
3997 REG_UTP_TRANSFER_REQ_LIST_BASE_H);
3998 ufshcd_writel(hba, lower_32_bits(hba->utmrdl_dma_addr),
3999 REG_UTP_TASK_REQ_LIST_BASE_L);
4000 ufshcd_writel(hba, upper_32_bits(hba->utmrdl_dma_addr),
4001 REG_UTP_TASK_REQ_LIST_BASE_H);
4004 * Make sure base address and interrupt setup are updated before
4005 * enabling the run/stop registers below.
4007 wmb();
4010 * UCRDY, UTMRLDY and UTRLRDY bits must be 1
4012 reg = ufshcd_readl(hba, REG_CONTROLLER_STATUS);
4013 if (!(ufshcd_get_lists_status(reg))) {
4014 ufshcd_enable_run_stop_reg(hba);
4015 } else {
4016 dev_err(hba->dev,
4017 "Host controller not ready to process requests");
4018 err = -EIO;
4019 goto out;
4022 out:
4023 return err;
4027 * ufshcd_hba_stop - Send controller to reset state
4028 * @hba: per adapter instance
4029 * @can_sleep: perform sleep or just spin
4031 static inline void ufshcd_hba_stop(struct ufs_hba *hba, bool can_sleep)
4033 int err;
4035 ufshcd_writel(hba, CONTROLLER_DISABLE, REG_CONTROLLER_ENABLE);
4036 err = ufshcd_wait_for_register(hba, REG_CONTROLLER_ENABLE,
4037 CONTROLLER_ENABLE, CONTROLLER_DISABLE,
4038 10, 1, can_sleep);
4039 if (err)
4040 dev_err(hba->dev, "%s: Controller disable failed\n", __func__);
4044 * ufshcd_hba_enable - initialize the controller
4045 * @hba: per adapter instance
4047 * The controller resets itself and controller firmware initialization
4048 * sequence kicks off. When controller is ready it will set
4049 * the Host Controller Enable bit to 1.
4051 * Returns 0 on success, non-zero value on failure
4053 static int ufshcd_hba_enable(struct ufs_hba *hba)
4055 int retry;
4058 * msleep of 1 and 5 used in this function might result in msleep(20),
4059 * but it was necessary to send the UFS FPGA to reset mode during
4060 * development and testing of this driver. msleep can be changed to
4061 * mdelay and retry count can be reduced based on the controller.
4063 if (!ufshcd_is_hba_active(hba))
4064 /* change controller state to "reset state" */
4065 ufshcd_hba_stop(hba, true);
4067 /* UniPro link is disabled at this point */
4068 ufshcd_set_link_off(hba);
4070 ufshcd_vops_hce_enable_notify(hba, PRE_CHANGE);
4072 /* start controller initialization sequence */
4073 ufshcd_hba_start(hba);
4076 * To initialize a UFS host controller HCE bit must be set to 1.
4077 * During initialization the HCE bit value changes from 1->0->1.
4078 * When the host controller completes initialization sequence
4079 * it sets the value of HCE bit to 1. The same HCE bit is read back
4080 * to check if the controller has completed initialization sequence.
4081 * So without this delay the value HCE = 1, set in the previous
4082 * instruction might be read back.
4083 * This delay can be changed based on the controller.
4085 msleep(1);
4087 /* wait for the host controller to complete initialization */
4088 retry = 10;
4089 while (ufshcd_is_hba_active(hba)) {
4090 if (retry) {
4091 retry--;
4092 } else {
4093 dev_err(hba->dev,
4094 "Controller enable failed\n");
4095 return -EIO;
4097 msleep(5);
4100 /* enable UIC related interrupts */
4101 ufshcd_enable_intr(hba, UFSHCD_UIC_MASK);
4103 ufshcd_vops_hce_enable_notify(hba, POST_CHANGE);
4105 return 0;
4108 static int ufshcd_disable_tx_lcc(struct ufs_hba *hba, bool peer)
4110 int tx_lanes, i, err = 0;
4112 if (!peer)
4113 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_CONNECTEDTXDATALANES),
4114 &tx_lanes);
4115 else
4116 ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_CONNECTEDTXDATALANES),
4117 &tx_lanes);
4118 for (i = 0; i < tx_lanes; i++) {
4119 if (!peer)
4120 err = ufshcd_dme_set(hba,
4121 UIC_ARG_MIB_SEL(TX_LCC_ENABLE,
4122 UIC_ARG_MPHY_TX_GEN_SEL_INDEX(i)),
4124 else
4125 err = ufshcd_dme_peer_set(hba,
4126 UIC_ARG_MIB_SEL(TX_LCC_ENABLE,
4127 UIC_ARG_MPHY_TX_GEN_SEL_INDEX(i)),
4129 if (err) {
4130 dev_err(hba->dev, "%s: TX LCC Disable failed, peer = %d, lane = %d, err = %d",
4131 __func__, peer, i, err);
4132 break;
4136 return err;
4139 static inline int ufshcd_disable_device_tx_lcc(struct ufs_hba *hba)
4141 return ufshcd_disable_tx_lcc(hba, true);
4145 * ufshcd_link_startup - Initialize unipro link startup
4146 * @hba: per adapter instance
4148 * Returns 0 for success, non-zero in case of failure
4150 static int ufshcd_link_startup(struct ufs_hba *hba)
4152 int ret;
4153 int retries = DME_LINKSTARTUP_RETRIES;
4154 bool link_startup_again = false;
4157 * If UFS device isn't active then we will have to issue link startup
4158 * 2 times to make sure the device state move to active.
4160 if (!ufshcd_is_ufs_dev_active(hba))
4161 link_startup_again = true;
4163 link_startup:
4164 do {
4165 ufshcd_vops_link_startup_notify(hba, PRE_CHANGE);
4167 ret = ufshcd_dme_link_startup(hba);
4169 /* check if device is detected by inter-connect layer */
4170 if (!ret && !ufshcd_is_device_present(hba)) {
4171 dev_err(hba->dev, "%s: Device not present\n", __func__);
4172 ret = -ENXIO;
4173 goto out;
4177 * DME link lost indication is only received when link is up,
4178 * but we can't be sure if the link is up until link startup
4179 * succeeds. So reset the local Uni-Pro and try again.
4181 if (ret && ufshcd_hba_enable(hba))
4182 goto out;
4183 } while (ret && retries--);
4185 if (ret)
4186 /* failed to get the link up... retire */
4187 goto out;
4189 if (link_startup_again) {
4190 link_startup_again = false;
4191 retries = DME_LINKSTARTUP_RETRIES;
4192 goto link_startup;
4195 /* Mark that link is up in PWM-G1, 1-lane, SLOW-AUTO mode */
4196 ufshcd_init_pwr_info(hba);
4197 ufshcd_print_pwr_info(hba);
4199 if (hba->quirks & UFSHCD_QUIRK_BROKEN_LCC) {
4200 ret = ufshcd_disable_device_tx_lcc(hba);
4201 if (ret)
4202 goto out;
4205 /* Include any host controller configuration via UIC commands */
4206 ret = ufshcd_vops_link_startup_notify(hba, POST_CHANGE);
4207 if (ret)
4208 goto out;
4210 ret = ufshcd_make_hba_operational(hba);
4211 out:
4212 if (ret) {
4213 dev_err(hba->dev, "link startup failed %d\n", ret);
4214 ufshcd_print_host_state(hba);
4215 ufshcd_print_pwr_info(hba);
4216 ufshcd_print_host_regs(hba);
4218 return ret;
4222 * ufshcd_verify_dev_init() - Verify device initialization
4223 * @hba: per-adapter instance
4225 * Send NOP OUT UPIU and wait for NOP IN response to check whether the
4226 * device Transport Protocol (UTP) layer is ready after a reset.
4227 * If the UTP layer at the device side is not initialized, it may
4228 * not respond with NOP IN UPIU within timeout of %NOP_OUT_TIMEOUT
4229 * and we retry sending NOP OUT for %NOP_OUT_RETRIES iterations.
4231 static int ufshcd_verify_dev_init(struct ufs_hba *hba)
4233 int err = 0;
4234 int retries;
4236 ufshcd_hold(hba, false);
4237 mutex_lock(&hba->dev_cmd.lock);
4238 for (retries = NOP_OUT_RETRIES; retries > 0; retries--) {
4239 err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_NOP,
4240 NOP_OUT_TIMEOUT);
4242 if (!err || err == -ETIMEDOUT)
4243 break;
4245 dev_dbg(hba->dev, "%s: error %d retrying\n", __func__, err);
4247 mutex_unlock(&hba->dev_cmd.lock);
4248 ufshcd_release(hba);
4250 if (err)
4251 dev_err(hba->dev, "%s: NOP OUT failed %d\n", __func__, err);
4252 return err;
4256 * ufshcd_set_queue_depth - set lun queue depth
4257 * @sdev: pointer to SCSI device
4259 * Read bLUQueueDepth value and activate scsi tagged command
4260 * queueing. For WLUN, queue depth is set to 1. For best-effort
4261 * cases (bLUQueueDepth = 0) the queue depth is set to a maximum
4262 * value that host can queue.
4264 static void ufshcd_set_queue_depth(struct scsi_device *sdev)
4266 int ret = 0;
4267 u8 lun_qdepth;
4268 struct ufs_hba *hba;
4270 hba = shost_priv(sdev->host);
4272 lun_qdepth = hba->nutrs;
4273 ret = ufshcd_read_unit_desc_param(hba,
4274 ufshcd_scsi_to_upiu_lun(sdev->lun),
4275 UNIT_DESC_PARAM_LU_Q_DEPTH,
4276 &lun_qdepth,
4277 sizeof(lun_qdepth));
4279 /* Some WLUN doesn't support unit descriptor */
4280 if (ret == -EOPNOTSUPP)
4281 lun_qdepth = 1;
4282 else if (!lun_qdepth)
4283 /* eventually, we can figure out the real queue depth */
4284 lun_qdepth = hba->nutrs;
4285 else
4286 lun_qdepth = min_t(int, lun_qdepth, hba->nutrs);
4288 dev_dbg(hba->dev, "%s: activate tcq with queue depth %d\n",
4289 __func__, lun_qdepth);
4290 scsi_change_queue_depth(sdev, lun_qdepth);
4294 * ufshcd_get_lu_wp - returns the "b_lu_write_protect" from UNIT DESCRIPTOR
4295 * @hba: per-adapter instance
4296 * @lun: UFS device lun id
4297 * @b_lu_write_protect: pointer to buffer to hold the LU's write protect info
4299 * Returns 0 in case of success and b_lu_write_protect status would be returned
4300 * @b_lu_write_protect parameter.
4301 * Returns -ENOTSUPP if reading b_lu_write_protect is not supported.
4302 * Returns -EINVAL in case of invalid parameters passed to this function.
4304 static int ufshcd_get_lu_wp(struct ufs_hba *hba,
4305 u8 lun,
4306 u8 *b_lu_write_protect)
4308 int ret;
4310 if (!b_lu_write_protect)
4311 ret = -EINVAL;
4313 * According to UFS device spec, RPMB LU can't be write
4314 * protected so skip reading bLUWriteProtect parameter for
4315 * it. For other W-LUs, UNIT DESCRIPTOR is not available.
4317 else if (lun >= UFS_UPIU_MAX_GENERAL_LUN)
4318 ret = -ENOTSUPP;
4319 else
4320 ret = ufshcd_read_unit_desc_param(hba,
4321 lun,
4322 UNIT_DESC_PARAM_LU_WR_PROTECT,
4323 b_lu_write_protect,
4324 sizeof(*b_lu_write_protect));
4325 return ret;
4329 * ufshcd_get_lu_power_on_wp_status - get LU's power on write protect
4330 * status
4331 * @hba: per-adapter instance
4332 * @sdev: pointer to SCSI device
4335 static inline void ufshcd_get_lu_power_on_wp_status(struct ufs_hba *hba,
4336 struct scsi_device *sdev)
4338 if (hba->dev_info.f_power_on_wp_en &&
4339 !hba->dev_info.is_lu_power_on_wp) {
4340 u8 b_lu_write_protect;
4342 if (!ufshcd_get_lu_wp(hba, ufshcd_scsi_to_upiu_lun(sdev->lun),
4343 &b_lu_write_protect) &&
4344 (b_lu_write_protect == UFS_LU_POWER_ON_WP))
4345 hba->dev_info.is_lu_power_on_wp = true;
4350 * ufshcd_slave_alloc - handle initial SCSI device configurations
4351 * @sdev: pointer to SCSI device
4353 * Returns success
4355 static int ufshcd_slave_alloc(struct scsi_device *sdev)
4357 struct ufs_hba *hba;
4359 hba = shost_priv(sdev->host);
4361 /* Mode sense(6) is not supported by UFS, so use Mode sense(10) */
4362 sdev->use_10_for_ms = 1;
4364 /* allow SCSI layer to restart the device in case of errors */
4365 sdev->allow_restart = 1;
4367 /* REPORT SUPPORTED OPERATION CODES is not supported */
4368 sdev->no_report_opcodes = 1;
4370 /* WRITE_SAME command is not supported */
4371 sdev->no_write_same = 1;
4373 ufshcd_set_queue_depth(sdev);
4375 ufshcd_get_lu_power_on_wp_status(hba, sdev);
4377 return 0;
4381 * ufshcd_change_queue_depth - change queue depth
4382 * @sdev: pointer to SCSI device
4383 * @depth: required depth to set
4385 * Change queue depth and make sure the max. limits are not crossed.
4387 static int ufshcd_change_queue_depth(struct scsi_device *sdev, int depth)
4389 struct ufs_hba *hba = shost_priv(sdev->host);
4391 if (depth > hba->nutrs)
4392 depth = hba->nutrs;
4393 return scsi_change_queue_depth(sdev, depth);
4397 * ufshcd_slave_configure - adjust SCSI device configurations
4398 * @sdev: pointer to SCSI device
4400 static int ufshcd_slave_configure(struct scsi_device *sdev)
4402 struct request_queue *q = sdev->request_queue;
4404 blk_queue_update_dma_pad(q, PRDT_DATA_BYTE_COUNT_PAD - 1);
4405 blk_queue_max_segment_size(q, PRDT_DATA_BYTE_COUNT_MAX);
4407 return 0;
4411 * ufshcd_slave_destroy - remove SCSI device configurations
4412 * @sdev: pointer to SCSI device
4414 static void ufshcd_slave_destroy(struct scsi_device *sdev)
4416 struct ufs_hba *hba;
4418 hba = shost_priv(sdev->host);
4419 /* Drop the reference as it won't be needed anymore */
4420 if (ufshcd_scsi_to_upiu_lun(sdev->lun) == UFS_UPIU_UFS_DEVICE_WLUN) {
4421 unsigned long flags;
4423 spin_lock_irqsave(hba->host->host_lock, flags);
4424 hba->sdev_ufs_device = NULL;
4425 spin_unlock_irqrestore(hba->host->host_lock, flags);
4430 * ufshcd_task_req_compl - handle task management request completion
4431 * @hba: per adapter instance
4432 * @index: index of the completed request
4433 * @resp: task management service response
4435 * Returns non-zero value on error, zero on success
4437 static int ufshcd_task_req_compl(struct ufs_hba *hba, u32 index, u8 *resp)
4439 struct utp_task_req_desc *task_req_descp;
4440 struct utp_upiu_task_rsp *task_rsp_upiup;
4441 unsigned long flags;
4442 int ocs_value;
4443 int task_result;
4445 spin_lock_irqsave(hba->host->host_lock, flags);
4447 /* Clear completed tasks from outstanding_tasks */
4448 __clear_bit(index, &hba->outstanding_tasks);
4450 task_req_descp = hba->utmrdl_base_addr;
4451 ocs_value = ufshcd_get_tmr_ocs(&task_req_descp[index]);
4453 if (ocs_value == OCS_SUCCESS) {
4454 task_rsp_upiup = (struct utp_upiu_task_rsp *)
4455 task_req_descp[index].task_rsp_upiu;
4456 task_result = be32_to_cpu(task_rsp_upiup->output_param1);
4457 task_result = task_result & MASK_TM_SERVICE_RESP;
4458 if (resp)
4459 *resp = (u8)task_result;
4460 } else {
4461 dev_err(hba->dev, "%s: failed, ocs = 0x%x\n",
4462 __func__, ocs_value);
4464 spin_unlock_irqrestore(hba->host->host_lock, flags);
4466 return ocs_value;
4470 * ufshcd_scsi_cmd_status - Update SCSI command result based on SCSI status
4471 * @lrbp: pointer to local reference block of completed command
4472 * @scsi_status: SCSI command status
4474 * Returns value base on SCSI command status
4476 static inline int
4477 ufshcd_scsi_cmd_status(struct ufshcd_lrb *lrbp, int scsi_status)
4479 int result = 0;
4481 switch (scsi_status) {
4482 case SAM_STAT_CHECK_CONDITION:
4483 ufshcd_copy_sense_data(lrbp);
4484 case SAM_STAT_GOOD:
4485 result |= DID_OK << 16 |
4486 COMMAND_COMPLETE << 8 |
4487 scsi_status;
4488 break;
4489 case SAM_STAT_TASK_SET_FULL:
4490 case SAM_STAT_BUSY:
4491 case SAM_STAT_TASK_ABORTED:
4492 ufshcd_copy_sense_data(lrbp);
4493 result |= scsi_status;
4494 break;
4495 default:
4496 result |= DID_ERROR << 16;
4497 break;
4498 } /* end of switch */
4500 return result;
4504 * ufshcd_transfer_rsp_status - Get overall status of the response
4505 * @hba: per adapter instance
4506 * @lrbp: pointer to local reference block of completed command
4508 * Returns result of the command to notify SCSI midlayer
4510 static inline int
4511 ufshcd_transfer_rsp_status(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
4513 int result = 0;
4514 int scsi_status;
4515 int ocs;
4517 /* overall command status of utrd */
4518 ocs = ufshcd_get_tr_ocs(lrbp);
4520 switch (ocs) {
4521 case OCS_SUCCESS:
4522 result = ufshcd_get_req_rsp(lrbp->ucd_rsp_ptr);
4523 hba->ufs_stats.last_hibern8_exit_tstamp = ktime_set(0, 0);
4524 switch (result) {
4525 case UPIU_TRANSACTION_RESPONSE:
4527 * get the response UPIU result to extract
4528 * the SCSI command status
4530 result = ufshcd_get_rsp_upiu_result(lrbp->ucd_rsp_ptr);
4533 * get the result based on SCSI status response
4534 * to notify the SCSI midlayer of the command status
4536 scsi_status = result & MASK_SCSI_STATUS;
4537 result = ufshcd_scsi_cmd_status(lrbp, scsi_status);
4540 * Currently we are only supporting BKOPs exception
4541 * events hence we can ignore BKOPs exception event
4542 * during power management callbacks. BKOPs exception
4543 * event is not expected to be raised in runtime suspend
4544 * callback as it allows the urgent bkops.
4545 * During system suspend, we are anyway forcefully
4546 * disabling the bkops and if urgent bkops is needed
4547 * it will be enabled on system resume. Long term
4548 * solution could be to abort the system suspend if
4549 * UFS device needs urgent BKOPs.
4551 if (!hba->pm_op_in_progress &&
4552 ufshcd_is_exception_event(lrbp->ucd_rsp_ptr))
4553 schedule_work(&hba->eeh_work);
4554 break;
4555 case UPIU_TRANSACTION_REJECT_UPIU:
4556 /* TODO: handle Reject UPIU Response */
4557 result = DID_ERROR << 16;
4558 dev_err(hba->dev,
4559 "Reject UPIU not fully implemented\n");
4560 break;
4561 default:
4562 result = DID_ERROR << 16;
4563 dev_err(hba->dev,
4564 "Unexpected request response code = %x\n",
4565 result);
4566 break;
4568 break;
4569 case OCS_ABORTED:
4570 result |= DID_ABORT << 16;
4571 break;
4572 case OCS_INVALID_COMMAND_STATUS:
4573 result |= DID_REQUEUE << 16;
4574 break;
4575 case OCS_INVALID_CMD_TABLE_ATTR:
4576 case OCS_INVALID_PRDT_ATTR:
4577 case OCS_MISMATCH_DATA_BUF_SIZE:
4578 case OCS_MISMATCH_RESP_UPIU_SIZE:
4579 case OCS_PEER_COMM_FAILURE:
4580 case OCS_FATAL_ERROR:
4581 default:
4582 result |= DID_ERROR << 16;
4583 dev_err(hba->dev,
4584 "OCS error from controller = %x for tag %d\n",
4585 ocs, lrbp->task_tag);
4586 ufshcd_print_host_regs(hba);
4587 ufshcd_print_host_state(hba);
4588 break;
4589 } /* end of switch */
4591 if (host_byte(result) != DID_OK)
4592 ufshcd_print_trs(hba, 1 << lrbp->task_tag, true);
4593 return result;
4597 * ufshcd_uic_cmd_compl - handle completion of uic command
4598 * @hba: per adapter instance
4599 * @intr_status: interrupt status generated by the controller
4601 static void ufshcd_uic_cmd_compl(struct ufs_hba *hba, u32 intr_status)
4603 if ((intr_status & UIC_COMMAND_COMPL) && hba->active_uic_cmd) {
4604 hba->active_uic_cmd->argument2 |=
4605 ufshcd_get_uic_cmd_result(hba);
4606 hba->active_uic_cmd->argument3 =
4607 ufshcd_get_dme_attr_val(hba);
4608 complete(&hba->active_uic_cmd->done);
4611 if ((intr_status & UFSHCD_UIC_PWR_MASK) && hba->uic_async_done)
4612 complete(hba->uic_async_done);
4616 * __ufshcd_transfer_req_compl - handle SCSI and query command completion
4617 * @hba: per adapter instance
4618 * @completed_reqs: requests to complete
4620 static void __ufshcd_transfer_req_compl(struct ufs_hba *hba,
4621 unsigned long completed_reqs)
4623 struct ufshcd_lrb *lrbp;
4624 struct scsi_cmnd *cmd;
4625 int result;
4626 int index;
4628 for_each_set_bit(index, &completed_reqs, hba->nutrs) {
4629 lrbp = &hba->lrb[index];
4630 cmd = lrbp->cmd;
4631 if (cmd) {
4632 ufshcd_add_command_trace(hba, index, "complete");
4633 result = ufshcd_transfer_rsp_status(hba, lrbp);
4634 scsi_dma_unmap(cmd);
4635 cmd->result = result;
4636 /* Mark completed command as NULL in LRB */
4637 lrbp->cmd = NULL;
4638 clear_bit_unlock(index, &hba->lrb_in_use);
4639 /* Do not touch lrbp after scsi done */
4640 cmd->scsi_done(cmd);
4641 __ufshcd_release(hba);
4642 } else if (lrbp->command_type == UTP_CMD_TYPE_DEV_MANAGE ||
4643 lrbp->command_type == UTP_CMD_TYPE_UFS_STORAGE) {
4644 if (hba->dev_cmd.complete) {
4645 ufshcd_add_command_trace(hba, index,
4646 "dev_complete");
4647 complete(hba->dev_cmd.complete);
4650 if (ufshcd_is_clkscaling_supported(hba))
4651 hba->clk_scaling.active_reqs--;
4653 lrbp->compl_time_stamp = ktime_get();
4656 /* clear corresponding bits of completed commands */
4657 hba->outstanding_reqs ^= completed_reqs;
4659 ufshcd_clk_scaling_update_busy(hba);
4661 /* we might have free'd some tags above */
4662 wake_up(&hba->dev_cmd.tag_wq);
4666 * ufshcd_transfer_req_compl - handle SCSI and query command completion
4667 * @hba: per adapter instance
4669 static void ufshcd_transfer_req_compl(struct ufs_hba *hba)
4671 unsigned long completed_reqs;
4672 u32 tr_doorbell;
4674 /* Resetting interrupt aggregation counters first and reading the
4675 * DOOR_BELL afterward allows us to handle all the completed requests.
4676 * In order to prevent other interrupts starvation the DB is read once
4677 * after reset. The down side of this solution is the possibility of
4678 * false interrupt if device completes another request after resetting
4679 * aggregation and before reading the DB.
4681 if (ufshcd_is_intr_aggr_allowed(hba))
4682 ufshcd_reset_intr_aggr(hba);
4684 tr_doorbell = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
4685 completed_reqs = tr_doorbell ^ hba->outstanding_reqs;
4687 __ufshcd_transfer_req_compl(hba, completed_reqs);
4691 * ufshcd_disable_ee - disable exception event
4692 * @hba: per-adapter instance
4693 * @mask: exception event to disable
4695 * Disables exception event in the device so that the EVENT_ALERT
4696 * bit is not set.
4698 * Returns zero on success, non-zero error value on failure.
4700 static int ufshcd_disable_ee(struct ufs_hba *hba, u16 mask)
4702 int err = 0;
4703 u32 val;
4705 if (!(hba->ee_ctrl_mask & mask))
4706 goto out;
4708 val = hba->ee_ctrl_mask & ~mask;
4709 val &= MASK_EE_STATUS;
4710 err = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_WRITE_ATTR,
4711 QUERY_ATTR_IDN_EE_CONTROL, 0, 0, &val);
4712 if (!err)
4713 hba->ee_ctrl_mask &= ~mask;
4714 out:
4715 return err;
4719 * ufshcd_enable_ee - enable exception event
4720 * @hba: per-adapter instance
4721 * @mask: exception event to enable
4723 * Enable corresponding exception event in the device to allow
4724 * device to alert host in critical scenarios.
4726 * Returns zero on success, non-zero error value on failure.
4728 static int ufshcd_enable_ee(struct ufs_hba *hba, u16 mask)
4730 int err = 0;
4731 u32 val;
4733 if (hba->ee_ctrl_mask & mask)
4734 goto out;
4736 val = hba->ee_ctrl_mask | mask;
4737 val &= MASK_EE_STATUS;
4738 err = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_WRITE_ATTR,
4739 QUERY_ATTR_IDN_EE_CONTROL, 0, 0, &val);
4740 if (!err)
4741 hba->ee_ctrl_mask |= mask;
4742 out:
4743 return err;
4747 * ufshcd_enable_auto_bkops - Allow device managed BKOPS
4748 * @hba: per-adapter instance
4750 * Allow device to manage background operations on its own. Enabling
4751 * this might lead to inconsistent latencies during normal data transfers
4752 * as the device is allowed to manage its own way of handling background
4753 * operations.
4755 * Returns zero on success, non-zero on failure.
4757 static int ufshcd_enable_auto_bkops(struct ufs_hba *hba)
4759 int err = 0;
4761 if (hba->auto_bkops_enabled)
4762 goto out;
4764 err = ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_SET_FLAG,
4765 QUERY_FLAG_IDN_BKOPS_EN, NULL);
4766 if (err) {
4767 dev_err(hba->dev, "%s: failed to enable bkops %d\n",
4768 __func__, err);
4769 goto out;
4772 hba->auto_bkops_enabled = true;
4773 trace_ufshcd_auto_bkops_state(dev_name(hba->dev), "Enabled");
4775 /* No need of URGENT_BKOPS exception from the device */
4776 err = ufshcd_disable_ee(hba, MASK_EE_URGENT_BKOPS);
4777 if (err)
4778 dev_err(hba->dev, "%s: failed to disable exception event %d\n",
4779 __func__, err);
4780 out:
4781 return err;
4785 * ufshcd_disable_auto_bkops - block device in doing background operations
4786 * @hba: per-adapter instance
4788 * Disabling background operations improves command response latency but
4789 * has drawback of device moving into critical state where the device is
4790 * not-operable. Make sure to call ufshcd_enable_auto_bkops() whenever the
4791 * host is idle so that BKOPS are managed effectively without any negative
4792 * impacts.
4794 * Returns zero on success, non-zero on failure.
4796 static int ufshcd_disable_auto_bkops(struct ufs_hba *hba)
4798 int err = 0;
4800 if (!hba->auto_bkops_enabled)
4801 goto out;
4804 * If host assisted BKOPs is to be enabled, make sure
4805 * urgent bkops exception is allowed.
4807 err = ufshcd_enable_ee(hba, MASK_EE_URGENT_BKOPS);
4808 if (err) {
4809 dev_err(hba->dev, "%s: failed to enable exception event %d\n",
4810 __func__, err);
4811 goto out;
4814 err = ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_CLEAR_FLAG,
4815 QUERY_FLAG_IDN_BKOPS_EN, NULL);
4816 if (err) {
4817 dev_err(hba->dev, "%s: failed to disable bkops %d\n",
4818 __func__, err);
4819 ufshcd_disable_ee(hba, MASK_EE_URGENT_BKOPS);
4820 goto out;
4823 hba->auto_bkops_enabled = false;
4824 trace_ufshcd_auto_bkops_state(dev_name(hba->dev), "Disabled");
4825 out:
4826 return err;
4830 * ufshcd_force_reset_auto_bkops - force reset auto bkops state
4831 * @hba: per adapter instance
4833 * After a device reset the device may toggle the BKOPS_EN flag
4834 * to default value. The s/w tracking variables should be updated
4835 * as well. This function would change the auto-bkops state based on
4836 * UFSHCD_CAP_KEEP_AUTO_BKOPS_ENABLED_EXCEPT_SUSPEND.
4838 static void ufshcd_force_reset_auto_bkops(struct ufs_hba *hba)
4840 if (ufshcd_keep_autobkops_enabled_except_suspend(hba)) {
4841 hba->auto_bkops_enabled = false;
4842 hba->ee_ctrl_mask |= MASK_EE_URGENT_BKOPS;
4843 ufshcd_enable_auto_bkops(hba);
4844 } else {
4845 hba->auto_bkops_enabled = true;
4846 hba->ee_ctrl_mask &= ~MASK_EE_URGENT_BKOPS;
4847 ufshcd_disable_auto_bkops(hba);
4851 static inline int ufshcd_get_bkops_status(struct ufs_hba *hba, u32 *status)
4853 return ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
4854 QUERY_ATTR_IDN_BKOPS_STATUS, 0, 0, status);
4858 * ufshcd_bkops_ctrl - control the auto bkops based on current bkops status
4859 * @hba: per-adapter instance
4860 * @status: bkops_status value
4862 * Read the bkops_status from the UFS device and Enable fBackgroundOpsEn
4863 * flag in the device to permit background operations if the device
4864 * bkops_status is greater than or equal to "status" argument passed to
4865 * this function, disable otherwise.
4867 * Returns 0 for success, non-zero in case of failure.
4869 * NOTE: Caller of this function can check the "hba->auto_bkops_enabled" flag
4870 * to know whether auto bkops is enabled or disabled after this function
4871 * returns control to it.
4873 static int ufshcd_bkops_ctrl(struct ufs_hba *hba,
4874 enum bkops_status status)
4876 int err;
4877 u32 curr_status = 0;
4879 err = ufshcd_get_bkops_status(hba, &curr_status);
4880 if (err) {
4881 dev_err(hba->dev, "%s: failed to get BKOPS status %d\n",
4882 __func__, err);
4883 goto out;
4884 } else if (curr_status > BKOPS_STATUS_MAX) {
4885 dev_err(hba->dev, "%s: invalid BKOPS status %d\n",
4886 __func__, curr_status);
4887 err = -EINVAL;
4888 goto out;
4891 if (curr_status >= status)
4892 err = ufshcd_enable_auto_bkops(hba);
4893 else
4894 err = ufshcd_disable_auto_bkops(hba);
4895 out:
4896 return err;
4900 * ufshcd_urgent_bkops - handle urgent bkops exception event
4901 * @hba: per-adapter instance
4903 * Enable fBackgroundOpsEn flag in the device to permit background
4904 * operations.
4906 * If BKOPs is enabled, this function returns 0, 1 if the bkops in not enabled
4907 * and negative error value for any other failure.
4909 static int ufshcd_urgent_bkops(struct ufs_hba *hba)
4911 return ufshcd_bkops_ctrl(hba, hba->urgent_bkops_lvl);
4914 static inline int ufshcd_get_ee_status(struct ufs_hba *hba, u32 *status)
4916 return ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
4917 QUERY_ATTR_IDN_EE_STATUS, 0, 0, status);
4920 static void ufshcd_bkops_exception_event_handler(struct ufs_hba *hba)
4922 int err;
4923 u32 curr_status = 0;
4925 if (hba->is_urgent_bkops_lvl_checked)
4926 goto enable_auto_bkops;
4928 err = ufshcd_get_bkops_status(hba, &curr_status);
4929 if (err) {
4930 dev_err(hba->dev, "%s: failed to get BKOPS status %d\n",
4931 __func__, err);
4932 goto out;
4936 * We are seeing that some devices are raising the urgent bkops
4937 * exception events even when BKOPS status doesn't indicate performace
4938 * impacted or critical. Handle these device by determining their urgent
4939 * bkops status at runtime.
4941 if (curr_status < BKOPS_STATUS_PERF_IMPACT) {
4942 dev_err(hba->dev, "%s: device raised urgent BKOPS exception for bkops status %d\n",
4943 __func__, curr_status);
4944 /* update the current status as the urgent bkops level */
4945 hba->urgent_bkops_lvl = curr_status;
4946 hba->is_urgent_bkops_lvl_checked = true;
4949 enable_auto_bkops:
4950 err = ufshcd_enable_auto_bkops(hba);
4951 out:
4952 if (err < 0)
4953 dev_err(hba->dev, "%s: failed to handle urgent bkops %d\n",
4954 __func__, err);
4958 * ufshcd_exception_event_handler - handle exceptions raised by device
4959 * @work: pointer to work data
4961 * Read bExceptionEventStatus attribute from the device and handle the
4962 * exception event accordingly.
4964 static void ufshcd_exception_event_handler(struct work_struct *work)
4966 struct ufs_hba *hba;
4967 int err;
4968 u32 status = 0;
4969 hba = container_of(work, struct ufs_hba, eeh_work);
4971 pm_runtime_get_sync(hba->dev);
4972 err = ufshcd_get_ee_status(hba, &status);
4973 if (err) {
4974 dev_err(hba->dev, "%s: failed to get exception status %d\n",
4975 __func__, err);
4976 goto out;
4979 status &= hba->ee_ctrl_mask;
4981 if (status & MASK_EE_URGENT_BKOPS)
4982 ufshcd_bkops_exception_event_handler(hba);
4984 out:
4985 pm_runtime_put_sync(hba->dev);
4986 return;
4989 /* Complete requests that have door-bell cleared */
4990 static void ufshcd_complete_requests(struct ufs_hba *hba)
4992 ufshcd_transfer_req_compl(hba);
4993 ufshcd_tmc_handler(hba);
4997 * ufshcd_quirk_dl_nac_errors - This function checks if error handling is
4998 * to recover from the DL NAC errors or not.
4999 * @hba: per-adapter instance
5001 * Returns true if error handling is required, false otherwise
5003 static bool ufshcd_quirk_dl_nac_errors(struct ufs_hba *hba)
5005 unsigned long flags;
5006 bool err_handling = true;
5008 spin_lock_irqsave(hba->host->host_lock, flags);
5010 * UFS_DEVICE_QUIRK_RECOVERY_FROM_DL_NAC_ERRORS only workaround the
5011 * device fatal error and/or DL NAC & REPLAY timeout errors.
5013 if (hba->saved_err & (CONTROLLER_FATAL_ERROR | SYSTEM_BUS_FATAL_ERROR))
5014 goto out;
5016 if ((hba->saved_err & DEVICE_FATAL_ERROR) ||
5017 ((hba->saved_err & UIC_ERROR) &&
5018 (hba->saved_uic_err & UFSHCD_UIC_DL_TCx_REPLAY_ERROR)))
5019 goto out;
5021 if ((hba->saved_err & UIC_ERROR) &&
5022 (hba->saved_uic_err & UFSHCD_UIC_DL_NAC_RECEIVED_ERROR)) {
5023 int err;
5025 * wait for 50ms to see if we can get any other errors or not.
5027 spin_unlock_irqrestore(hba->host->host_lock, flags);
5028 msleep(50);
5029 spin_lock_irqsave(hba->host->host_lock, flags);
5032 * now check if we have got any other severe errors other than
5033 * DL NAC error?
5035 if ((hba->saved_err & INT_FATAL_ERRORS) ||
5036 ((hba->saved_err & UIC_ERROR) &&
5037 (hba->saved_uic_err & ~UFSHCD_UIC_DL_NAC_RECEIVED_ERROR)))
5038 goto out;
5041 * As DL NAC is the only error received so far, send out NOP
5042 * command to confirm if link is still active or not.
5043 * - If we don't get any response then do error recovery.
5044 * - If we get response then clear the DL NAC error bit.
5047 spin_unlock_irqrestore(hba->host->host_lock, flags);
5048 err = ufshcd_verify_dev_init(hba);
5049 spin_lock_irqsave(hba->host->host_lock, flags);
5051 if (err)
5052 goto out;
5054 /* Link seems to be alive hence ignore the DL NAC errors */
5055 if (hba->saved_uic_err == UFSHCD_UIC_DL_NAC_RECEIVED_ERROR)
5056 hba->saved_err &= ~UIC_ERROR;
5057 /* clear NAC error */
5058 hba->saved_uic_err &= ~UFSHCD_UIC_DL_NAC_RECEIVED_ERROR;
5059 if (!hba->saved_uic_err) {
5060 err_handling = false;
5061 goto out;
5064 out:
5065 spin_unlock_irqrestore(hba->host->host_lock, flags);
5066 return err_handling;
5070 * ufshcd_err_handler - handle UFS errors that require s/w attention
5071 * @work: pointer to work structure
5073 static void ufshcd_err_handler(struct work_struct *work)
5075 struct ufs_hba *hba;
5076 unsigned long flags;
5077 u32 err_xfer = 0;
5078 u32 err_tm = 0;
5079 int err = 0;
5080 int tag;
5081 bool needs_reset = false;
5083 hba = container_of(work, struct ufs_hba, eh_work);
5085 pm_runtime_get_sync(hba->dev);
5086 ufshcd_hold(hba, false);
5088 spin_lock_irqsave(hba->host->host_lock, flags);
5089 if (hba->ufshcd_state == UFSHCD_STATE_RESET)
5090 goto out;
5092 hba->ufshcd_state = UFSHCD_STATE_RESET;
5093 ufshcd_set_eh_in_progress(hba);
5095 /* Complete requests that have door-bell cleared by h/w */
5096 ufshcd_complete_requests(hba);
5098 if (hba->dev_quirks & UFS_DEVICE_QUIRK_RECOVERY_FROM_DL_NAC_ERRORS) {
5099 bool ret;
5101 spin_unlock_irqrestore(hba->host->host_lock, flags);
5102 /* release the lock as ufshcd_quirk_dl_nac_errors() may sleep */
5103 ret = ufshcd_quirk_dl_nac_errors(hba);
5104 spin_lock_irqsave(hba->host->host_lock, flags);
5105 if (!ret)
5106 goto skip_err_handling;
5108 if ((hba->saved_err & INT_FATAL_ERRORS) ||
5109 ((hba->saved_err & UIC_ERROR) &&
5110 (hba->saved_uic_err & (UFSHCD_UIC_DL_PA_INIT_ERROR |
5111 UFSHCD_UIC_DL_NAC_RECEIVED_ERROR |
5112 UFSHCD_UIC_DL_TCx_REPLAY_ERROR))))
5113 needs_reset = true;
5116 * if host reset is required then skip clearing the pending
5117 * transfers forcefully because they will automatically get
5118 * cleared after link startup.
5120 if (needs_reset)
5121 goto skip_pending_xfer_clear;
5123 /* release lock as clear command might sleep */
5124 spin_unlock_irqrestore(hba->host->host_lock, flags);
5125 /* Clear pending transfer requests */
5126 for_each_set_bit(tag, &hba->outstanding_reqs, hba->nutrs) {
5127 if (ufshcd_clear_cmd(hba, tag)) {
5128 err_xfer = true;
5129 goto lock_skip_pending_xfer_clear;
5133 /* Clear pending task management requests */
5134 for_each_set_bit(tag, &hba->outstanding_tasks, hba->nutmrs) {
5135 if (ufshcd_clear_tm_cmd(hba, tag)) {
5136 err_tm = true;
5137 goto lock_skip_pending_xfer_clear;
5141 lock_skip_pending_xfer_clear:
5142 spin_lock_irqsave(hba->host->host_lock, flags);
5144 /* Complete the requests that are cleared by s/w */
5145 ufshcd_complete_requests(hba);
5147 if (err_xfer || err_tm)
5148 needs_reset = true;
5150 skip_pending_xfer_clear:
5151 /* Fatal errors need reset */
5152 if (needs_reset) {
5153 unsigned long max_doorbells = (1UL << hba->nutrs) - 1;
5156 * ufshcd_reset_and_restore() does the link reinitialization
5157 * which will need atleast one empty doorbell slot to send the
5158 * device management commands (NOP and query commands).
5159 * If there is no slot empty at this moment then free up last
5160 * slot forcefully.
5162 if (hba->outstanding_reqs == max_doorbells)
5163 __ufshcd_transfer_req_compl(hba,
5164 (1UL << (hba->nutrs - 1)));
5166 spin_unlock_irqrestore(hba->host->host_lock, flags);
5167 err = ufshcd_reset_and_restore(hba);
5168 spin_lock_irqsave(hba->host->host_lock, flags);
5169 if (err) {
5170 dev_err(hba->dev, "%s: reset and restore failed\n",
5171 __func__);
5172 hba->ufshcd_state = UFSHCD_STATE_ERROR;
5175 * Inform scsi mid-layer that we did reset and allow to handle
5176 * Unit Attention properly.
5178 scsi_report_bus_reset(hba->host, 0);
5179 hba->saved_err = 0;
5180 hba->saved_uic_err = 0;
5183 skip_err_handling:
5184 if (!needs_reset) {
5185 hba->ufshcd_state = UFSHCD_STATE_OPERATIONAL;
5186 if (hba->saved_err || hba->saved_uic_err)
5187 dev_err_ratelimited(hba->dev, "%s: exit: saved_err 0x%x saved_uic_err 0x%x",
5188 __func__, hba->saved_err, hba->saved_uic_err);
5191 ufshcd_clear_eh_in_progress(hba);
5193 out:
5194 spin_unlock_irqrestore(hba->host->host_lock, flags);
5195 scsi_unblock_requests(hba->host);
5196 ufshcd_release(hba);
5197 pm_runtime_put_sync(hba->dev);
5200 static void ufshcd_update_uic_reg_hist(struct ufs_uic_err_reg_hist *reg_hist,
5201 u32 reg)
5203 reg_hist->reg[reg_hist->pos] = reg;
5204 reg_hist->tstamp[reg_hist->pos] = ktime_get();
5205 reg_hist->pos = (reg_hist->pos + 1) % UIC_ERR_REG_HIST_LENGTH;
5209 * ufshcd_update_uic_error - check and set fatal UIC error flags.
5210 * @hba: per-adapter instance
5212 static void ufshcd_update_uic_error(struct ufs_hba *hba)
5214 u32 reg;
5216 /* PHY layer lane error */
5217 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_PHY_ADAPTER_LAYER);
5218 /* Ignore LINERESET indication, as this is not an error */
5219 if ((reg & UIC_PHY_ADAPTER_LAYER_ERROR) &&
5220 (reg & UIC_PHY_ADAPTER_LAYER_LANE_ERR_MASK)) {
5222 * To know whether this error is fatal or not, DB timeout
5223 * must be checked but this error is handled separately.
5225 dev_dbg(hba->dev, "%s: UIC Lane error reported\n", __func__);
5226 ufshcd_update_uic_reg_hist(&hba->ufs_stats.pa_err, reg);
5229 /* PA_INIT_ERROR is fatal and needs UIC reset */
5230 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_DATA_LINK_LAYER);
5231 if (reg)
5232 ufshcd_update_uic_reg_hist(&hba->ufs_stats.dl_err, reg);
5234 if (reg & UIC_DATA_LINK_LAYER_ERROR_PA_INIT)
5235 hba->uic_error |= UFSHCD_UIC_DL_PA_INIT_ERROR;
5236 else if (hba->dev_quirks &
5237 UFS_DEVICE_QUIRK_RECOVERY_FROM_DL_NAC_ERRORS) {
5238 if (reg & UIC_DATA_LINK_LAYER_ERROR_NAC_RECEIVED)
5239 hba->uic_error |=
5240 UFSHCD_UIC_DL_NAC_RECEIVED_ERROR;
5241 else if (reg & UIC_DATA_LINK_LAYER_ERROR_TCx_REPLAY_TIMEOUT)
5242 hba->uic_error |= UFSHCD_UIC_DL_TCx_REPLAY_ERROR;
5245 /* UIC NL/TL/DME errors needs software retry */
5246 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_NETWORK_LAYER);
5247 if (reg) {
5248 ufshcd_update_uic_reg_hist(&hba->ufs_stats.nl_err, reg);
5249 hba->uic_error |= UFSHCD_UIC_NL_ERROR;
5252 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_TRANSPORT_LAYER);
5253 if (reg) {
5254 ufshcd_update_uic_reg_hist(&hba->ufs_stats.tl_err, reg);
5255 hba->uic_error |= UFSHCD_UIC_TL_ERROR;
5258 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_DME);
5259 if (reg) {
5260 ufshcd_update_uic_reg_hist(&hba->ufs_stats.dme_err, reg);
5261 hba->uic_error |= UFSHCD_UIC_DME_ERROR;
5264 dev_dbg(hba->dev, "%s: UIC error flags = 0x%08x\n",
5265 __func__, hba->uic_error);
5269 * ufshcd_check_errors - Check for errors that need s/w attention
5270 * @hba: per-adapter instance
5272 static void ufshcd_check_errors(struct ufs_hba *hba)
5274 bool queue_eh_work = false;
5276 if (hba->errors & INT_FATAL_ERRORS)
5277 queue_eh_work = true;
5279 if (hba->errors & UIC_ERROR) {
5280 hba->uic_error = 0;
5281 ufshcd_update_uic_error(hba);
5282 if (hba->uic_error)
5283 queue_eh_work = true;
5286 if (queue_eh_work) {
5288 * update the transfer error masks to sticky bits, let's do this
5289 * irrespective of current ufshcd_state.
5291 hba->saved_err |= hba->errors;
5292 hba->saved_uic_err |= hba->uic_error;
5294 /* handle fatal errors only when link is functional */
5295 if (hba->ufshcd_state == UFSHCD_STATE_OPERATIONAL) {
5296 /* block commands from scsi mid-layer */
5297 scsi_block_requests(hba->host);
5299 hba->ufshcd_state = UFSHCD_STATE_EH_SCHEDULED;
5301 /* dump controller state before resetting */
5302 if (hba->saved_err & (INT_FATAL_ERRORS | UIC_ERROR)) {
5303 bool pr_prdt = !!(hba->saved_err &
5304 SYSTEM_BUS_FATAL_ERROR);
5306 dev_err(hba->dev, "%s: saved_err 0x%x saved_uic_err 0x%x\n",
5307 __func__, hba->saved_err,
5308 hba->saved_uic_err);
5310 ufshcd_print_host_regs(hba);
5311 ufshcd_print_pwr_info(hba);
5312 ufshcd_print_tmrs(hba, hba->outstanding_tasks);
5313 ufshcd_print_trs(hba, hba->outstanding_reqs,
5314 pr_prdt);
5316 schedule_work(&hba->eh_work);
5320 * if (!queue_eh_work) -
5321 * Other errors are either non-fatal where host recovers
5322 * itself without s/w intervention or errors that will be
5323 * handled by the SCSI core layer.
5328 * ufshcd_tmc_handler - handle task management function completion
5329 * @hba: per adapter instance
5331 static void ufshcd_tmc_handler(struct ufs_hba *hba)
5333 u32 tm_doorbell;
5335 tm_doorbell = ufshcd_readl(hba, REG_UTP_TASK_REQ_DOOR_BELL);
5336 hba->tm_condition = tm_doorbell ^ hba->outstanding_tasks;
5337 wake_up(&hba->tm_wq);
5341 * ufshcd_sl_intr - Interrupt service routine
5342 * @hba: per adapter instance
5343 * @intr_status: contains interrupts generated by the controller
5345 static void ufshcd_sl_intr(struct ufs_hba *hba, u32 intr_status)
5347 hba->errors = UFSHCD_ERROR_MASK & intr_status;
5348 if (hba->errors)
5349 ufshcd_check_errors(hba);
5351 if (intr_status & UFSHCD_UIC_MASK)
5352 ufshcd_uic_cmd_compl(hba, intr_status);
5354 if (intr_status & UTP_TASK_REQ_COMPL)
5355 ufshcd_tmc_handler(hba);
5357 if (intr_status & UTP_TRANSFER_REQ_COMPL)
5358 ufshcd_transfer_req_compl(hba);
5362 * ufshcd_intr - Main interrupt service routine
5363 * @irq: irq number
5364 * @__hba: pointer to adapter instance
5366 * Returns IRQ_HANDLED - If interrupt is valid
5367 * IRQ_NONE - If invalid interrupt
5369 static irqreturn_t ufshcd_intr(int irq, void *__hba)
5371 u32 intr_status, enabled_intr_status;
5372 irqreturn_t retval = IRQ_NONE;
5373 struct ufs_hba *hba = __hba;
5375 spin_lock(hba->host->host_lock);
5376 intr_status = ufshcd_readl(hba, REG_INTERRUPT_STATUS);
5377 enabled_intr_status =
5378 intr_status & ufshcd_readl(hba, REG_INTERRUPT_ENABLE);
5380 if (intr_status)
5381 ufshcd_writel(hba, intr_status, REG_INTERRUPT_STATUS);
5383 if (enabled_intr_status) {
5384 ufshcd_sl_intr(hba, enabled_intr_status);
5385 retval = IRQ_HANDLED;
5387 spin_unlock(hba->host->host_lock);
5388 return retval;
5391 static int ufshcd_clear_tm_cmd(struct ufs_hba *hba, int tag)
5393 int err = 0;
5394 u32 mask = 1 << tag;
5395 unsigned long flags;
5397 if (!test_bit(tag, &hba->outstanding_tasks))
5398 goto out;
5400 spin_lock_irqsave(hba->host->host_lock, flags);
5401 ufshcd_writel(hba, ~(1 << tag), REG_UTP_TASK_REQ_LIST_CLEAR);
5402 spin_unlock_irqrestore(hba->host->host_lock, flags);
5404 /* poll for max. 1 sec to clear door bell register by h/w */
5405 err = ufshcd_wait_for_register(hba,
5406 REG_UTP_TASK_REQ_DOOR_BELL,
5407 mask, 0, 1000, 1000, true);
5408 out:
5409 return err;
5413 * ufshcd_issue_tm_cmd - issues task management commands to controller
5414 * @hba: per adapter instance
5415 * @lun_id: LUN ID to which TM command is sent
5416 * @task_id: task ID to which the TM command is applicable
5417 * @tm_function: task management function opcode
5418 * @tm_response: task management service response return value
5420 * Returns non-zero value on error, zero on success.
5422 static int ufshcd_issue_tm_cmd(struct ufs_hba *hba, int lun_id, int task_id,
5423 u8 tm_function, u8 *tm_response)
5425 struct utp_task_req_desc *task_req_descp;
5426 struct utp_upiu_task_req *task_req_upiup;
5427 struct Scsi_Host *host;
5428 unsigned long flags;
5429 int free_slot;
5430 int err;
5431 int task_tag;
5433 host = hba->host;
5436 * Get free slot, sleep if slots are unavailable.
5437 * Even though we use wait_event() which sleeps indefinitely,
5438 * the maximum wait time is bounded by %TM_CMD_TIMEOUT.
5440 wait_event(hba->tm_tag_wq, ufshcd_get_tm_free_slot(hba, &free_slot));
5441 ufshcd_hold(hba, false);
5443 spin_lock_irqsave(host->host_lock, flags);
5444 task_req_descp = hba->utmrdl_base_addr;
5445 task_req_descp += free_slot;
5447 /* Configure task request descriptor */
5448 task_req_descp->header.dword_0 = cpu_to_le32(UTP_REQ_DESC_INT_CMD);
5449 task_req_descp->header.dword_2 =
5450 cpu_to_le32(OCS_INVALID_COMMAND_STATUS);
5452 /* Configure task request UPIU */
5453 task_req_upiup =
5454 (struct utp_upiu_task_req *) task_req_descp->task_req_upiu;
5455 task_tag = hba->nutrs + free_slot;
5456 task_req_upiup->header.dword_0 =
5457 UPIU_HEADER_DWORD(UPIU_TRANSACTION_TASK_REQ, 0,
5458 lun_id, task_tag);
5459 task_req_upiup->header.dword_1 =
5460 UPIU_HEADER_DWORD(0, tm_function, 0, 0);
5462 * The host shall provide the same value for LUN field in the basic
5463 * header and for Input Parameter.
5465 task_req_upiup->input_param1 = cpu_to_be32(lun_id);
5466 task_req_upiup->input_param2 = cpu_to_be32(task_id);
5468 ufshcd_vops_setup_task_mgmt(hba, free_slot, tm_function);
5470 /* send command to the controller */
5471 __set_bit(free_slot, &hba->outstanding_tasks);
5473 /* Make sure descriptors are ready before ringing the task doorbell */
5474 wmb();
5476 ufshcd_writel(hba, 1 << free_slot, REG_UTP_TASK_REQ_DOOR_BELL);
5477 /* Make sure that doorbell is committed immediately */
5478 wmb();
5480 spin_unlock_irqrestore(host->host_lock, flags);
5482 ufshcd_add_tm_upiu_trace(hba, task_tag, "tm_send");
5484 /* wait until the task management command is completed */
5485 err = wait_event_timeout(hba->tm_wq,
5486 test_bit(free_slot, &hba->tm_condition),
5487 msecs_to_jiffies(TM_CMD_TIMEOUT));
5488 if (!err) {
5489 ufshcd_add_tm_upiu_trace(hba, task_tag, "tm_complete_err");
5490 dev_err(hba->dev, "%s: task management cmd 0x%.2x timed-out\n",
5491 __func__, tm_function);
5492 if (ufshcd_clear_tm_cmd(hba, free_slot))
5493 dev_WARN(hba->dev, "%s: unable clear tm cmd (slot %d) after timeout\n",
5494 __func__, free_slot);
5495 err = -ETIMEDOUT;
5496 } else {
5497 err = ufshcd_task_req_compl(hba, free_slot, tm_response);
5498 ufshcd_add_tm_upiu_trace(hba, task_tag, "tm_complete");
5501 clear_bit(free_slot, &hba->tm_condition);
5502 ufshcd_put_tm_slot(hba, free_slot);
5503 wake_up(&hba->tm_tag_wq);
5505 ufshcd_release(hba);
5506 return err;
5510 * ufshcd_eh_device_reset_handler - device reset handler registered to
5511 * scsi layer.
5512 * @cmd: SCSI command pointer
5514 * Returns SUCCESS/FAILED
5516 static int ufshcd_eh_device_reset_handler(struct scsi_cmnd *cmd)
5518 struct Scsi_Host *host;
5519 struct ufs_hba *hba;
5520 unsigned int tag;
5521 u32 pos;
5522 int err;
5523 u8 resp = 0xF;
5524 struct ufshcd_lrb *lrbp;
5525 unsigned long flags;
5527 host = cmd->device->host;
5528 hba = shost_priv(host);
5529 tag = cmd->request->tag;
5531 lrbp = &hba->lrb[tag];
5532 err = ufshcd_issue_tm_cmd(hba, lrbp->lun, 0, UFS_LOGICAL_RESET, &resp);
5533 if (err || resp != UPIU_TASK_MANAGEMENT_FUNC_COMPL) {
5534 if (!err)
5535 err = resp;
5536 goto out;
5539 /* clear the commands that were pending for corresponding LUN */
5540 for_each_set_bit(pos, &hba->outstanding_reqs, hba->nutrs) {
5541 if (hba->lrb[pos].lun == lrbp->lun) {
5542 err = ufshcd_clear_cmd(hba, pos);
5543 if (err)
5544 break;
5547 spin_lock_irqsave(host->host_lock, flags);
5548 ufshcd_transfer_req_compl(hba);
5549 spin_unlock_irqrestore(host->host_lock, flags);
5551 out:
5552 hba->req_abort_count = 0;
5553 if (!err) {
5554 err = SUCCESS;
5555 } else {
5556 dev_err(hba->dev, "%s: failed with err %d\n", __func__, err);
5557 err = FAILED;
5559 return err;
5562 static void ufshcd_set_req_abort_skip(struct ufs_hba *hba, unsigned long bitmap)
5564 struct ufshcd_lrb *lrbp;
5565 int tag;
5567 for_each_set_bit(tag, &bitmap, hba->nutrs) {
5568 lrbp = &hba->lrb[tag];
5569 lrbp->req_abort_skip = true;
5574 * ufshcd_abort - abort a specific command
5575 * @cmd: SCSI command pointer
5577 * Abort the pending command in device by sending UFS_ABORT_TASK task management
5578 * command, and in host controller by clearing the door-bell register. There can
5579 * be race between controller sending the command to the device while abort is
5580 * issued. To avoid that, first issue UFS_QUERY_TASK to check if the command is
5581 * really issued and then try to abort it.
5583 * Returns SUCCESS/FAILED
5585 static int ufshcd_abort(struct scsi_cmnd *cmd)
5587 struct Scsi_Host *host;
5588 struct ufs_hba *hba;
5589 unsigned long flags;
5590 unsigned int tag;
5591 int err = 0;
5592 int poll_cnt;
5593 u8 resp = 0xF;
5594 struct ufshcd_lrb *lrbp;
5595 u32 reg;
5597 host = cmd->device->host;
5598 hba = shost_priv(host);
5599 tag = cmd->request->tag;
5600 lrbp = &hba->lrb[tag];
5601 if (!ufshcd_valid_tag(hba, tag)) {
5602 dev_err(hba->dev,
5603 "%s: invalid command tag %d: cmd=0x%p, cmd->request=0x%p",
5604 __func__, tag, cmd, cmd->request);
5605 BUG();
5609 * Task abort to the device W-LUN is illegal. When this command
5610 * will fail, due to spec violation, scsi err handling next step
5611 * will be to send LU reset which, again, is a spec violation.
5612 * To avoid these unnecessary/illegal step we skip to the last error
5613 * handling stage: reset and restore.
5615 if (lrbp->lun == UFS_UPIU_UFS_DEVICE_WLUN)
5616 return ufshcd_eh_host_reset_handler(cmd);
5618 ufshcd_hold(hba, false);
5619 reg = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
5620 /* If command is already aborted/completed, return SUCCESS */
5621 if (!(test_bit(tag, &hba->outstanding_reqs))) {
5622 dev_err(hba->dev,
5623 "%s: cmd at tag %d already completed, outstanding=0x%lx, doorbell=0x%x\n",
5624 __func__, tag, hba->outstanding_reqs, reg);
5625 goto out;
5628 if (!(reg & (1 << tag))) {
5629 dev_err(hba->dev,
5630 "%s: cmd was completed, but without a notifying intr, tag = %d",
5631 __func__, tag);
5634 /* Print Transfer Request of aborted task */
5635 dev_err(hba->dev, "%s: Device abort task at tag %d\n", __func__, tag);
5638 * Print detailed info about aborted request.
5639 * As more than one request might get aborted at the same time,
5640 * print full information only for the first aborted request in order
5641 * to reduce repeated printouts. For other aborted requests only print
5642 * basic details.
5644 scsi_print_command(hba->lrb[tag].cmd);
5645 if (!hba->req_abort_count) {
5646 ufshcd_print_host_regs(hba);
5647 ufshcd_print_host_state(hba);
5648 ufshcd_print_pwr_info(hba);
5649 ufshcd_print_trs(hba, 1 << tag, true);
5650 } else {
5651 ufshcd_print_trs(hba, 1 << tag, false);
5653 hba->req_abort_count++;
5655 /* Skip task abort in case previous aborts failed and report failure */
5656 if (lrbp->req_abort_skip) {
5657 err = -EIO;
5658 goto out;
5661 for (poll_cnt = 100; poll_cnt; poll_cnt--) {
5662 err = ufshcd_issue_tm_cmd(hba, lrbp->lun, lrbp->task_tag,
5663 UFS_QUERY_TASK, &resp);
5664 if (!err && resp == UPIU_TASK_MANAGEMENT_FUNC_SUCCEEDED) {
5665 /* cmd pending in the device */
5666 dev_err(hba->dev, "%s: cmd pending in the device. tag = %d\n",
5667 __func__, tag);
5668 break;
5669 } else if (!err && resp == UPIU_TASK_MANAGEMENT_FUNC_COMPL) {
5671 * cmd not pending in the device, check if it is
5672 * in transition.
5674 dev_err(hba->dev, "%s: cmd at tag %d not pending in the device.\n",
5675 __func__, tag);
5676 reg = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
5677 if (reg & (1 << tag)) {
5678 /* sleep for max. 200us to stabilize */
5679 usleep_range(100, 200);
5680 continue;
5682 /* command completed already */
5683 dev_err(hba->dev, "%s: cmd at tag %d successfully cleared from DB.\n",
5684 __func__, tag);
5685 goto out;
5686 } else {
5687 dev_err(hba->dev,
5688 "%s: no response from device. tag = %d, err %d\n",
5689 __func__, tag, err);
5690 if (!err)
5691 err = resp; /* service response error */
5692 goto out;
5696 if (!poll_cnt) {
5697 err = -EBUSY;
5698 goto out;
5701 err = ufshcd_issue_tm_cmd(hba, lrbp->lun, lrbp->task_tag,
5702 UFS_ABORT_TASK, &resp);
5703 if (err || resp != UPIU_TASK_MANAGEMENT_FUNC_COMPL) {
5704 if (!err) {
5705 err = resp; /* service response error */
5706 dev_err(hba->dev, "%s: issued. tag = %d, err %d\n",
5707 __func__, tag, err);
5709 goto out;
5712 err = ufshcd_clear_cmd(hba, tag);
5713 if (err) {
5714 dev_err(hba->dev, "%s: Failed clearing cmd at tag %d, err %d\n",
5715 __func__, tag, err);
5716 goto out;
5719 scsi_dma_unmap(cmd);
5721 spin_lock_irqsave(host->host_lock, flags);
5722 ufshcd_outstanding_req_clear(hba, tag);
5723 hba->lrb[tag].cmd = NULL;
5724 spin_unlock_irqrestore(host->host_lock, flags);
5726 clear_bit_unlock(tag, &hba->lrb_in_use);
5727 wake_up(&hba->dev_cmd.tag_wq);
5729 out:
5730 if (!err) {
5731 err = SUCCESS;
5732 } else {
5733 dev_err(hba->dev, "%s: failed with err %d\n", __func__, err);
5734 ufshcd_set_req_abort_skip(hba, hba->outstanding_reqs);
5735 err = FAILED;
5739 * This ufshcd_release() corresponds to the original scsi cmd that got
5740 * aborted here (as we won't get any IRQ for it).
5742 ufshcd_release(hba);
5743 return err;
5747 * ufshcd_host_reset_and_restore - reset and restore host controller
5748 * @hba: per-adapter instance
5750 * Note that host controller reset may issue DME_RESET to
5751 * local and remote (device) Uni-Pro stack and the attributes
5752 * are reset to default state.
5754 * Returns zero on success, non-zero on failure
5756 static int ufshcd_host_reset_and_restore(struct ufs_hba *hba)
5758 int err;
5759 unsigned long flags;
5761 /* Reset the host controller */
5762 spin_lock_irqsave(hba->host->host_lock, flags);
5763 ufshcd_hba_stop(hba, false);
5764 spin_unlock_irqrestore(hba->host->host_lock, flags);
5766 /* scale up clocks to max frequency before full reinitialization */
5767 ufshcd_scale_clks(hba, true);
5769 err = ufshcd_hba_enable(hba);
5770 if (err)
5771 goto out;
5773 /* Establish the link again and restore the device */
5774 err = ufshcd_probe_hba(hba);
5776 if (!err && (hba->ufshcd_state != UFSHCD_STATE_OPERATIONAL))
5777 err = -EIO;
5778 out:
5779 if (err)
5780 dev_err(hba->dev, "%s: Host init failed %d\n", __func__, err);
5782 return err;
5786 * ufshcd_reset_and_restore - reset and re-initialize host/device
5787 * @hba: per-adapter instance
5789 * Reset and recover device, host and re-establish link. This
5790 * is helpful to recover the communication in fatal error conditions.
5792 * Returns zero on success, non-zero on failure
5794 static int ufshcd_reset_and_restore(struct ufs_hba *hba)
5796 int err = 0;
5797 unsigned long flags;
5798 int retries = MAX_HOST_RESET_RETRIES;
5800 do {
5801 err = ufshcd_host_reset_and_restore(hba);
5802 } while (err && --retries);
5805 * After reset the door-bell might be cleared, complete
5806 * outstanding requests in s/w here.
5808 spin_lock_irqsave(hba->host->host_lock, flags);
5809 ufshcd_transfer_req_compl(hba);
5810 ufshcd_tmc_handler(hba);
5811 spin_unlock_irqrestore(hba->host->host_lock, flags);
5813 return err;
5817 * ufshcd_eh_host_reset_handler - host reset handler registered to scsi layer
5818 * @cmd: SCSI command pointer
5820 * Returns SUCCESS/FAILED
5822 static int ufshcd_eh_host_reset_handler(struct scsi_cmnd *cmd)
5824 int err;
5825 unsigned long flags;
5826 struct ufs_hba *hba;
5828 hba = shost_priv(cmd->device->host);
5830 ufshcd_hold(hba, false);
5832 * Check if there is any race with fatal error handling.
5833 * If so, wait for it to complete. Even though fatal error
5834 * handling does reset and restore in some cases, don't assume
5835 * anything out of it. We are just avoiding race here.
5837 do {
5838 spin_lock_irqsave(hba->host->host_lock, flags);
5839 if (!(work_pending(&hba->eh_work) ||
5840 hba->ufshcd_state == UFSHCD_STATE_RESET ||
5841 hba->ufshcd_state == UFSHCD_STATE_EH_SCHEDULED))
5842 break;
5843 spin_unlock_irqrestore(hba->host->host_lock, flags);
5844 dev_dbg(hba->dev, "%s: reset in progress\n", __func__);
5845 flush_work(&hba->eh_work);
5846 } while (1);
5848 hba->ufshcd_state = UFSHCD_STATE_RESET;
5849 ufshcd_set_eh_in_progress(hba);
5850 spin_unlock_irqrestore(hba->host->host_lock, flags);
5852 err = ufshcd_reset_and_restore(hba);
5854 spin_lock_irqsave(hba->host->host_lock, flags);
5855 if (!err) {
5856 err = SUCCESS;
5857 hba->ufshcd_state = UFSHCD_STATE_OPERATIONAL;
5858 } else {
5859 err = FAILED;
5860 hba->ufshcd_state = UFSHCD_STATE_ERROR;
5862 ufshcd_clear_eh_in_progress(hba);
5863 spin_unlock_irqrestore(hba->host->host_lock, flags);
5865 ufshcd_release(hba);
5866 return err;
5870 * ufshcd_get_max_icc_level - calculate the ICC level
5871 * @sup_curr_uA: max. current supported by the regulator
5872 * @start_scan: row at the desc table to start scan from
5873 * @buff: power descriptor buffer
5875 * Returns calculated max ICC level for specific regulator
5877 static u32 ufshcd_get_max_icc_level(int sup_curr_uA, u32 start_scan, char *buff)
5879 int i;
5880 int curr_uA;
5881 u16 data;
5882 u16 unit;
5884 for (i = start_scan; i >= 0; i--) {
5885 data = be16_to_cpup((__be16 *)&buff[2 * i]);
5886 unit = (data & ATTR_ICC_LVL_UNIT_MASK) >>
5887 ATTR_ICC_LVL_UNIT_OFFSET;
5888 curr_uA = data & ATTR_ICC_LVL_VALUE_MASK;
5889 switch (unit) {
5890 case UFSHCD_NANO_AMP:
5891 curr_uA = curr_uA / 1000;
5892 break;
5893 case UFSHCD_MILI_AMP:
5894 curr_uA = curr_uA * 1000;
5895 break;
5896 case UFSHCD_AMP:
5897 curr_uA = curr_uA * 1000 * 1000;
5898 break;
5899 case UFSHCD_MICRO_AMP:
5900 default:
5901 break;
5903 if (sup_curr_uA >= curr_uA)
5904 break;
5906 if (i < 0) {
5907 i = 0;
5908 pr_err("%s: Couldn't find valid icc_level = %d", __func__, i);
5911 return (u32)i;
5915 * ufshcd_calc_icc_level - calculate the max ICC level
5916 * In case regulators are not initialized we'll return 0
5917 * @hba: per-adapter instance
5918 * @desc_buf: power descriptor buffer to extract ICC levels from.
5919 * @len: length of desc_buff
5921 * Returns calculated ICC level
5923 static u32 ufshcd_find_max_sup_active_icc_level(struct ufs_hba *hba,
5924 u8 *desc_buf, int len)
5926 u32 icc_level = 0;
5928 if (!hba->vreg_info.vcc || !hba->vreg_info.vccq ||
5929 !hba->vreg_info.vccq2) {
5930 dev_err(hba->dev,
5931 "%s: Regulator capability was not set, actvIccLevel=%d",
5932 __func__, icc_level);
5933 goto out;
5936 if (hba->vreg_info.vcc)
5937 icc_level = ufshcd_get_max_icc_level(
5938 hba->vreg_info.vcc->max_uA,
5939 POWER_DESC_MAX_ACTV_ICC_LVLS - 1,
5940 &desc_buf[PWR_DESC_ACTIVE_LVLS_VCC_0]);
5942 if (hba->vreg_info.vccq)
5943 icc_level = ufshcd_get_max_icc_level(
5944 hba->vreg_info.vccq->max_uA,
5945 icc_level,
5946 &desc_buf[PWR_DESC_ACTIVE_LVLS_VCCQ_0]);
5948 if (hba->vreg_info.vccq2)
5949 icc_level = ufshcd_get_max_icc_level(
5950 hba->vreg_info.vccq2->max_uA,
5951 icc_level,
5952 &desc_buf[PWR_DESC_ACTIVE_LVLS_VCCQ2_0]);
5953 out:
5954 return icc_level;
5957 static void ufshcd_init_icc_levels(struct ufs_hba *hba)
5959 int ret;
5960 int buff_len = hba->desc_size.pwr_desc;
5961 u8 desc_buf[hba->desc_size.pwr_desc];
5963 ret = ufshcd_read_power_desc(hba, desc_buf, buff_len);
5964 if (ret) {
5965 dev_err(hba->dev,
5966 "%s: Failed reading power descriptor.len = %d ret = %d",
5967 __func__, buff_len, ret);
5968 return;
5971 hba->init_prefetch_data.icc_level =
5972 ufshcd_find_max_sup_active_icc_level(hba,
5973 desc_buf, buff_len);
5974 dev_dbg(hba->dev, "%s: setting icc_level 0x%x",
5975 __func__, hba->init_prefetch_data.icc_level);
5977 ret = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_WRITE_ATTR,
5978 QUERY_ATTR_IDN_ACTIVE_ICC_LVL, 0, 0,
5979 &hba->init_prefetch_data.icc_level);
5981 if (ret)
5982 dev_err(hba->dev,
5983 "%s: Failed configuring bActiveICCLevel = %d ret = %d",
5984 __func__, hba->init_prefetch_data.icc_level , ret);
5989 * ufshcd_scsi_add_wlus - Adds required W-LUs
5990 * @hba: per-adapter instance
5992 * UFS device specification requires the UFS devices to support 4 well known
5993 * logical units:
5994 * "REPORT_LUNS" (address: 01h)
5995 * "UFS Device" (address: 50h)
5996 * "RPMB" (address: 44h)
5997 * "BOOT" (address: 30h)
5998 * UFS device's power management needs to be controlled by "POWER CONDITION"
5999 * field of SSU (START STOP UNIT) command. But this "power condition" field
6000 * will take effect only when its sent to "UFS device" well known logical unit
6001 * hence we require the scsi_device instance to represent this logical unit in
6002 * order for the UFS host driver to send the SSU command for power management.
6004 * We also require the scsi_device instance for "RPMB" (Replay Protected Memory
6005 * Block) LU so user space process can control this LU. User space may also
6006 * want to have access to BOOT LU.
6008 * This function adds scsi device instances for each of all well known LUs
6009 * (except "REPORT LUNS" LU).
6011 * Returns zero on success (all required W-LUs are added successfully),
6012 * non-zero error value on failure (if failed to add any of the required W-LU).
6014 static int ufshcd_scsi_add_wlus(struct ufs_hba *hba)
6016 int ret = 0;
6017 struct scsi_device *sdev_rpmb;
6018 struct scsi_device *sdev_boot;
6020 hba->sdev_ufs_device = __scsi_add_device(hba->host, 0, 0,
6021 ufshcd_upiu_wlun_to_scsi_wlun(UFS_UPIU_UFS_DEVICE_WLUN), NULL);
6022 if (IS_ERR(hba->sdev_ufs_device)) {
6023 ret = PTR_ERR(hba->sdev_ufs_device);
6024 hba->sdev_ufs_device = NULL;
6025 goto out;
6027 scsi_device_put(hba->sdev_ufs_device);
6029 sdev_rpmb = __scsi_add_device(hba->host, 0, 0,
6030 ufshcd_upiu_wlun_to_scsi_wlun(UFS_UPIU_RPMB_WLUN), NULL);
6031 if (IS_ERR(sdev_rpmb)) {
6032 ret = PTR_ERR(sdev_rpmb);
6033 goto remove_sdev_ufs_device;
6035 scsi_device_put(sdev_rpmb);
6037 sdev_boot = __scsi_add_device(hba->host, 0, 0,
6038 ufshcd_upiu_wlun_to_scsi_wlun(UFS_UPIU_BOOT_WLUN), NULL);
6039 if (IS_ERR(sdev_boot))
6040 dev_err(hba->dev, "%s: BOOT WLUN not found\n", __func__);
6041 else
6042 scsi_device_put(sdev_boot);
6043 goto out;
6045 remove_sdev_ufs_device:
6046 scsi_remove_device(hba->sdev_ufs_device);
6047 out:
6048 return ret;
6051 static int ufs_get_device_desc(struct ufs_hba *hba,
6052 struct ufs_dev_desc *dev_desc)
6054 int err;
6055 u8 model_index;
6056 u8 str_desc_buf[QUERY_DESC_MAX_SIZE + 1] = {0};
6057 u8 desc_buf[hba->desc_size.dev_desc];
6059 err = ufshcd_read_device_desc(hba, desc_buf, hba->desc_size.dev_desc);
6060 if (err) {
6061 dev_err(hba->dev, "%s: Failed reading Device Desc. err = %d\n",
6062 __func__, err);
6063 goto out;
6067 * getting vendor (manufacturerID) and Bank Index in big endian
6068 * format
6070 dev_desc->wmanufacturerid = desc_buf[DEVICE_DESC_PARAM_MANF_ID] << 8 |
6071 desc_buf[DEVICE_DESC_PARAM_MANF_ID + 1];
6073 model_index = desc_buf[DEVICE_DESC_PARAM_PRDCT_NAME];
6075 err = ufshcd_read_string_desc(hba, model_index, str_desc_buf,
6076 QUERY_DESC_MAX_SIZE, true/*ASCII*/);
6077 if (err) {
6078 dev_err(hba->dev, "%s: Failed reading Product Name. err = %d\n",
6079 __func__, err);
6080 goto out;
6083 str_desc_buf[QUERY_DESC_MAX_SIZE] = '\0';
6084 strlcpy(dev_desc->model, (str_desc_buf + QUERY_DESC_HDR_SIZE),
6085 min_t(u8, str_desc_buf[QUERY_DESC_LENGTH_OFFSET],
6086 MAX_MODEL_LEN));
6088 /* Null terminate the model string */
6089 dev_desc->model[MAX_MODEL_LEN] = '\0';
6091 out:
6092 return err;
6095 static void ufs_fixup_device_setup(struct ufs_hba *hba,
6096 struct ufs_dev_desc *dev_desc)
6098 struct ufs_dev_fix *f;
6100 for (f = ufs_fixups; f->quirk; f++) {
6101 if ((f->card.wmanufacturerid == dev_desc->wmanufacturerid ||
6102 f->card.wmanufacturerid == UFS_ANY_VENDOR) &&
6103 (STR_PRFX_EQUAL(f->card.model, dev_desc->model) ||
6104 !strcmp(f->card.model, UFS_ANY_MODEL)))
6105 hba->dev_quirks |= f->quirk;
6110 * ufshcd_tune_pa_tactivate - Tunes PA_TActivate of local UniPro
6111 * @hba: per-adapter instance
6113 * PA_TActivate parameter can be tuned manually if UniPro version is less than
6114 * 1.61. PA_TActivate needs to be greater than or equal to peerM-PHY's
6115 * RX_MIN_ACTIVATETIME_CAPABILITY attribute. This optimal value can help reduce
6116 * the hibern8 exit latency.
6118 * Returns zero on success, non-zero error value on failure.
6120 static int ufshcd_tune_pa_tactivate(struct ufs_hba *hba)
6122 int ret = 0;
6123 u32 peer_rx_min_activatetime = 0, tuned_pa_tactivate;
6125 ret = ufshcd_dme_peer_get(hba,
6126 UIC_ARG_MIB_SEL(
6127 RX_MIN_ACTIVATETIME_CAPABILITY,
6128 UIC_ARG_MPHY_RX_GEN_SEL_INDEX(0)),
6129 &peer_rx_min_activatetime);
6130 if (ret)
6131 goto out;
6133 /* make sure proper unit conversion is applied */
6134 tuned_pa_tactivate =
6135 ((peer_rx_min_activatetime * RX_MIN_ACTIVATETIME_UNIT_US)
6136 / PA_TACTIVATE_TIME_UNIT_US);
6137 ret = ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TACTIVATE),
6138 tuned_pa_tactivate);
6140 out:
6141 return ret;
6145 * ufshcd_tune_pa_hibern8time - Tunes PA_Hibern8Time of local UniPro
6146 * @hba: per-adapter instance
6148 * PA_Hibern8Time parameter can be tuned manually if UniPro version is less than
6149 * 1.61. PA_Hibern8Time needs to be maximum of local M-PHY's
6150 * TX_HIBERN8TIME_CAPABILITY & peer M-PHY's RX_HIBERN8TIME_CAPABILITY.
6151 * This optimal value can help reduce the hibern8 exit latency.
6153 * Returns zero on success, non-zero error value on failure.
6155 static int ufshcd_tune_pa_hibern8time(struct ufs_hba *hba)
6157 int ret = 0;
6158 u32 local_tx_hibern8_time_cap = 0, peer_rx_hibern8_time_cap = 0;
6159 u32 max_hibern8_time, tuned_pa_hibern8time;
6161 ret = ufshcd_dme_get(hba,
6162 UIC_ARG_MIB_SEL(TX_HIBERN8TIME_CAPABILITY,
6163 UIC_ARG_MPHY_TX_GEN_SEL_INDEX(0)),
6164 &local_tx_hibern8_time_cap);
6165 if (ret)
6166 goto out;
6168 ret = ufshcd_dme_peer_get(hba,
6169 UIC_ARG_MIB_SEL(RX_HIBERN8TIME_CAPABILITY,
6170 UIC_ARG_MPHY_RX_GEN_SEL_INDEX(0)),
6171 &peer_rx_hibern8_time_cap);
6172 if (ret)
6173 goto out;
6175 max_hibern8_time = max(local_tx_hibern8_time_cap,
6176 peer_rx_hibern8_time_cap);
6177 /* make sure proper unit conversion is applied */
6178 tuned_pa_hibern8time = ((max_hibern8_time * HIBERN8TIME_UNIT_US)
6179 / PA_HIBERN8_TIME_UNIT_US);
6180 ret = ufshcd_dme_set(hba, UIC_ARG_MIB(PA_HIBERN8TIME),
6181 tuned_pa_hibern8time);
6182 out:
6183 return ret;
6187 * ufshcd_quirk_tune_host_pa_tactivate - Ensures that host PA_TACTIVATE is
6188 * less than device PA_TACTIVATE time.
6189 * @hba: per-adapter instance
6191 * Some UFS devices require host PA_TACTIVATE to be lower than device
6192 * PA_TACTIVATE, we need to enable UFS_DEVICE_QUIRK_HOST_PA_TACTIVATE quirk
6193 * for such devices.
6195 * Returns zero on success, non-zero error value on failure.
6197 static int ufshcd_quirk_tune_host_pa_tactivate(struct ufs_hba *hba)
6199 int ret = 0;
6200 u32 granularity, peer_granularity;
6201 u32 pa_tactivate, peer_pa_tactivate;
6202 u32 pa_tactivate_us, peer_pa_tactivate_us;
6203 u8 gran_to_us_table[] = {1, 4, 8, 16, 32, 100};
6205 ret = ufshcd_dme_get(hba, UIC_ARG_MIB(PA_GRANULARITY),
6206 &granularity);
6207 if (ret)
6208 goto out;
6210 ret = ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_GRANULARITY),
6211 &peer_granularity);
6212 if (ret)
6213 goto out;
6215 if ((granularity < PA_GRANULARITY_MIN_VAL) ||
6216 (granularity > PA_GRANULARITY_MAX_VAL)) {
6217 dev_err(hba->dev, "%s: invalid host PA_GRANULARITY %d",
6218 __func__, granularity);
6219 return -EINVAL;
6222 if ((peer_granularity < PA_GRANULARITY_MIN_VAL) ||
6223 (peer_granularity > PA_GRANULARITY_MAX_VAL)) {
6224 dev_err(hba->dev, "%s: invalid device PA_GRANULARITY %d",
6225 __func__, peer_granularity);
6226 return -EINVAL;
6229 ret = ufshcd_dme_get(hba, UIC_ARG_MIB(PA_TACTIVATE), &pa_tactivate);
6230 if (ret)
6231 goto out;
6233 ret = ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_TACTIVATE),
6234 &peer_pa_tactivate);
6235 if (ret)
6236 goto out;
6238 pa_tactivate_us = pa_tactivate * gran_to_us_table[granularity - 1];
6239 peer_pa_tactivate_us = peer_pa_tactivate *
6240 gran_to_us_table[peer_granularity - 1];
6242 if (pa_tactivate_us > peer_pa_tactivate_us) {
6243 u32 new_peer_pa_tactivate;
6245 new_peer_pa_tactivate = pa_tactivate_us /
6246 gran_to_us_table[peer_granularity - 1];
6247 new_peer_pa_tactivate++;
6248 ret = ufshcd_dme_peer_set(hba, UIC_ARG_MIB(PA_TACTIVATE),
6249 new_peer_pa_tactivate);
6252 out:
6253 return ret;
6256 static void ufshcd_tune_unipro_params(struct ufs_hba *hba)
6258 if (ufshcd_is_unipro_pa_params_tuning_req(hba)) {
6259 ufshcd_tune_pa_tactivate(hba);
6260 ufshcd_tune_pa_hibern8time(hba);
6263 if (hba->dev_quirks & UFS_DEVICE_QUIRK_PA_TACTIVATE)
6264 /* set 1ms timeout for PA_TACTIVATE */
6265 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TACTIVATE), 10);
6267 if (hba->dev_quirks & UFS_DEVICE_QUIRK_HOST_PA_TACTIVATE)
6268 ufshcd_quirk_tune_host_pa_tactivate(hba);
6270 ufshcd_vops_apply_dev_quirks(hba);
6273 static void ufshcd_clear_dbg_ufs_stats(struct ufs_hba *hba)
6275 int err_reg_hist_size = sizeof(struct ufs_uic_err_reg_hist);
6277 hba->ufs_stats.hibern8_exit_cnt = 0;
6278 hba->ufs_stats.last_hibern8_exit_tstamp = ktime_set(0, 0);
6280 memset(&hba->ufs_stats.pa_err, 0, err_reg_hist_size);
6281 memset(&hba->ufs_stats.dl_err, 0, err_reg_hist_size);
6282 memset(&hba->ufs_stats.nl_err, 0, err_reg_hist_size);
6283 memset(&hba->ufs_stats.tl_err, 0, err_reg_hist_size);
6284 memset(&hba->ufs_stats.dme_err, 0, err_reg_hist_size);
6286 hba->req_abort_count = 0;
6289 static void ufshcd_init_desc_sizes(struct ufs_hba *hba)
6291 int err;
6293 err = ufshcd_read_desc_length(hba, QUERY_DESC_IDN_DEVICE, 0,
6294 &hba->desc_size.dev_desc);
6295 if (err)
6296 hba->desc_size.dev_desc = QUERY_DESC_DEVICE_DEF_SIZE;
6298 err = ufshcd_read_desc_length(hba, QUERY_DESC_IDN_POWER, 0,
6299 &hba->desc_size.pwr_desc);
6300 if (err)
6301 hba->desc_size.pwr_desc = QUERY_DESC_POWER_DEF_SIZE;
6303 err = ufshcd_read_desc_length(hba, QUERY_DESC_IDN_INTERCONNECT, 0,
6304 &hba->desc_size.interc_desc);
6305 if (err)
6306 hba->desc_size.interc_desc = QUERY_DESC_INTERCONNECT_DEF_SIZE;
6308 err = ufshcd_read_desc_length(hba, QUERY_DESC_IDN_CONFIGURATION, 0,
6309 &hba->desc_size.conf_desc);
6310 if (err)
6311 hba->desc_size.conf_desc = QUERY_DESC_CONFIGURATION_DEF_SIZE;
6313 err = ufshcd_read_desc_length(hba, QUERY_DESC_IDN_UNIT, 0,
6314 &hba->desc_size.unit_desc);
6315 if (err)
6316 hba->desc_size.unit_desc = QUERY_DESC_UNIT_DEF_SIZE;
6318 err = ufshcd_read_desc_length(hba, QUERY_DESC_IDN_GEOMETRY, 0,
6319 &hba->desc_size.geom_desc);
6320 if (err)
6321 hba->desc_size.geom_desc = QUERY_DESC_GEOMETRY_DEF_SIZE;
6322 err = ufshcd_read_desc_length(hba, QUERY_DESC_IDN_HEALTH, 0,
6323 &hba->desc_size.hlth_desc);
6324 if (err)
6325 hba->desc_size.hlth_desc = QUERY_DESC_HEALTH_DEF_SIZE;
6328 static void ufshcd_def_desc_sizes(struct ufs_hba *hba)
6330 hba->desc_size.dev_desc = QUERY_DESC_DEVICE_DEF_SIZE;
6331 hba->desc_size.pwr_desc = QUERY_DESC_POWER_DEF_SIZE;
6332 hba->desc_size.interc_desc = QUERY_DESC_INTERCONNECT_DEF_SIZE;
6333 hba->desc_size.conf_desc = QUERY_DESC_CONFIGURATION_DEF_SIZE;
6334 hba->desc_size.unit_desc = QUERY_DESC_UNIT_DEF_SIZE;
6335 hba->desc_size.geom_desc = QUERY_DESC_GEOMETRY_DEF_SIZE;
6336 hba->desc_size.hlth_desc = QUERY_DESC_HEALTH_DEF_SIZE;
6340 * ufshcd_probe_hba - probe hba to detect device and initialize
6341 * @hba: per-adapter instance
6343 * Execute link-startup and verify device initialization
6345 static int ufshcd_probe_hba(struct ufs_hba *hba)
6347 struct ufs_dev_desc card = {0};
6348 int ret;
6349 ktime_t start = ktime_get();
6351 ret = ufshcd_link_startup(hba);
6352 if (ret)
6353 goto out;
6355 /* set the default level for urgent bkops */
6356 hba->urgent_bkops_lvl = BKOPS_STATUS_PERF_IMPACT;
6357 hba->is_urgent_bkops_lvl_checked = false;
6359 /* Debug counters initialization */
6360 ufshcd_clear_dbg_ufs_stats(hba);
6362 /* UniPro link is active now */
6363 ufshcd_set_link_active(hba);
6365 /* Enable Auto-Hibernate if configured */
6366 ufshcd_auto_hibern8_enable(hba);
6368 ret = ufshcd_verify_dev_init(hba);
6369 if (ret)
6370 goto out;
6372 ret = ufshcd_complete_dev_init(hba);
6373 if (ret)
6374 goto out;
6376 /* Init check for device descriptor sizes */
6377 ufshcd_init_desc_sizes(hba);
6379 ret = ufs_get_device_desc(hba, &card);
6380 if (ret) {
6381 dev_err(hba->dev, "%s: Failed getting device info. err = %d\n",
6382 __func__, ret);
6383 goto out;
6386 ufs_fixup_device_setup(hba, &card);
6387 ufshcd_tune_unipro_params(hba);
6389 ret = ufshcd_set_vccq_rail_unused(hba,
6390 (hba->dev_quirks & UFS_DEVICE_NO_VCCQ) ? true : false);
6391 if (ret)
6392 goto out;
6394 /* UFS device is also active now */
6395 ufshcd_set_ufs_dev_active(hba);
6396 ufshcd_force_reset_auto_bkops(hba);
6397 hba->wlun_dev_clr_ua = true;
6399 if (ufshcd_get_max_pwr_mode(hba)) {
6400 dev_err(hba->dev,
6401 "%s: Failed getting max supported power mode\n",
6402 __func__);
6403 } else {
6404 ret = ufshcd_config_pwr_mode(hba, &hba->max_pwr_info.info);
6405 if (ret) {
6406 dev_err(hba->dev, "%s: Failed setting power mode, err = %d\n",
6407 __func__, ret);
6408 goto out;
6412 /* set the state as operational after switching to desired gear */
6413 hba->ufshcd_state = UFSHCD_STATE_OPERATIONAL;
6416 * If we are in error handling context or in power management callbacks
6417 * context, no need to scan the host
6419 if (!ufshcd_eh_in_progress(hba) && !hba->pm_op_in_progress) {
6420 bool flag;
6422 /* clear any previous UFS device information */
6423 memset(&hba->dev_info, 0, sizeof(hba->dev_info));
6424 if (!ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_READ_FLAG,
6425 QUERY_FLAG_IDN_PWR_ON_WPE, &flag))
6426 hba->dev_info.f_power_on_wp_en = flag;
6428 if (!hba->is_init_prefetch)
6429 ufshcd_init_icc_levels(hba);
6431 /* Add required well known logical units to scsi mid layer */
6432 if (ufshcd_scsi_add_wlus(hba))
6433 goto out;
6435 /* Initialize devfreq after UFS device is detected */
6436 if (ufshcd_is_clkscaling_supported(hba)) {
6437 memcpy(&hba->clk_scaling.saved_pwr_info.info,
6438 &hba->pwr_info,
6439 sizeof(struct ufs_pa_layer_attr));
6440 hba->clk_scaling.saved_pwr_info.is_valid = true;
6441 if (!hba->devfreq) {
6442 hba->devfreq = devm_devfreq_add_device(hba->dev,
6443 &ufs_devfreq_profile,
6444 "simple_ondemand",
6445 NULL);
6446 if (IS_ERR(hba->devfreq)) {
6447 ret = PTR_ERR(hba->devfreq);
6448 dev_err(hba->dev, "Unable to register with devfreq %d\n",
6449 ret);
6450 goto out;
6453 hba->clk_scaling.is_allowed = true;
6456 scsi_scan_host(hba->host);
6457 pm_runtime_put_sync(hba->dev);
6460 if (!hba->is_init_prefetch)
6461 hba->is_init_prefetch = true;
6463 out:
6465 * If we failed to initialize the device or the device is not
6466 * present, turn off the power/clocks etc.
6468 if (ret && !ufshcd_eh_in_progress(hba) && !hba->pm_op_in_progress) {
6469 pm_runtime_put_sync(hba->dev);
6470 ufshcd_hba_exit(hba);
6473 trace_ufshcd_init(dev_name(hba->dev), ret,
6474 ktime_to_us(ktime_sub(ktime_get(), start)),
6475 hba->curr_dev_pwr_mode, hba->uic_link_state);
6476 return ret;
6480 * ufshcd_async_scan - asynchronous execution for probing hba
6481 * @data: data pointer to pass to this function
6482 * @cookie: cookie data
6484 static void ufshcd_async_scan(void *data, async_cookie_t cookie)
6486 struct ufs_hba *hba = (struct ufs_hba *)data;
6488 ufshcd_probe_hba(hba);
6491 static enum blk_eh_timer_return ufshcd_eh_timed_out(struct scsi_cmnd *scmd)
6493 unsigned long flags;
6494 struct Scsi_Host *host;
6495 struct ufs_hba *hba;
6496 int index;
6497 bool found = false;
6499 if (!scmd || !scmd->device || !scmd->device->host)
6500 return BLK_EH_NOT_HANDLED;
6502 host = scmd->device->host;
6503 hba = shost_priv(host);
6504 if (!hba)
6505 return BLK_EH_NOT_HANDLED;
6507 spin_lock_irqsave(host->host_lock, flags);
6509 for_each_set_bit(index, &hba->outstanding_reqs, hba->nutrs) {
6510 if (hba->lrb[index].cmd == scmd) {
6511 found = true;
6512 break;
6516 spin_unlock_irqrestore(host->host_lock, flags);
6519 * Bypass SCSI error handling and reset the block layer timer if this
6520 * SCSI command was not actually dispatched to UFS driver, otherwise
6521 * let SCSI layer handle the error as usual.
6523 return found ? BLK_EH_NOT_HANDLED : BLK_EH_RESET_TIMER;
6526 static const struct attribute_group *ufshcd_driver_groups[] = {
6527 &ufs_sysfs_unit_descriptor_group,
6528 &ufs_sysfs_lun_attributes_group,
6529 NULL,
6532 static struct scsi_host_template ufshcd_driver_template = {
6533 .module = THIS_MODULE,
6534 .name = UFSHCD,
6535 .proc_name = UFSHCD,
6536 .queuecommand = ufshcd_queuecommand,
6537 .slave_alloc = ufshcd_slave_alloc,
6538 .slave_configure = ufshcd_slave_configure,
6539 .slave_destroy = ufshcd_slave_destroy,
6540 .change_queue_depth = ufshcd_change_queue_depth,
6541 .eh_abort_handler = ufshcd_abort,
6542 .eh_device_reset_handler = ufshcd_eh_device_reset_handler,
6543 .eh_host_reset_handler = ufshcd_eh_host_reset_handler,
6544 .eh_timed_out = ufshcd_eh_timed_out,
6545 .this_id = -1,
6546 .sg_tablesize = SG_ALL,
6547 .cmd_per_lun = UFSHCD_CMD_PER_LUN,
6548 .can_queue = UFSHCD_CAN_QUEUE,
6549 .max_host_blocked = 1,
6550 .track_queue_depth = 1,
6551 .sdev_groups = ufshcd_driver_groups,
6554 static int ufshcd_config_vreg_load(struct device *dev, struct ufs_vreg *vreg,
6555 int ua)
6557 int ret;
6559 if (!vreg)
6560 return 0;
6562 ret = regulator_set_load(vreg->reg, ua);
6563 if (ret < 0) {
6564 dev_err(dev, "%s: %s set load (ua=%d) failed, err=%d\n",
6565 __func__, vreg->name, ua, ret);
6568 return ret;
6571 static inline int ufshcd_config_vreg_lpm(struct ufs_hba *hba,
6572 struct ufs_vreg *vreg)
6574 if (!vreg)
6575 return 0;
6576 else if (vreg->unused)
6577 return 0;
6578 else
6579 return ufshcd_config_vreg_load(hba->dev, vreg,
6580 UFS_VREG_LPM_LOAD_UA);
6583 static inline int ufshcd_config_vreg_hpm(struct ufs_hba *hba,
6584 struct ufs_vreg *vreg)
6586 if (!vreg)
6587 return 0;
6588 else if (vreg->unused)
6589 return 0;
6590 else
6591 return ufshcd_config_vreg_load(hba->dev, vreg, vreg->max_uA);
6594 static int ufshcd_config_vreg(struct device *dev,
6595 struct ufs_vreg *vreg, bool on)
6597 int ret = 0;
6598 struct regulator *reg;
6599 const char *name;
6600 int min_uV, uA_load;
6602 BUG_ON(!vreg);
6604 reg = vreg->reg;
6605 name = vreg->name;
6607 if (regulator_count_voltages(reg) > 0) {
6608 min_uV = on ? vreg->min_uV : 0;
6609 ret = regulator_set_voltage(reg, min_uV, vreg->max_uV);
6610 if (ret) {
6611 dev_err(dev, "%s: %s set voltage failed, err=%d\n",
6612 __func__, name, ret);
6613 goto out;
6616 uA_load = on ? vreg->max_uA : 0;
6617 ret = ufshcd_config_vreg_load(dev, vreg, uA_load);
6618 if (ret)
6619 goto out;
6621 out:
6622 return ret;
6625 static int ufshcd_enable_vreg(struct device *dev, struct ufs_vreg *vreg)
6627 int ret = 0;
6629 if (!vreg)
6630 goto out;
6631 else if (vreg->enabled || vreg->unused)
6632 goto out;
6634 ret = ufshcd_config_vreg(dev, vreg, true);
6635 if (!ret)
6636 ret = regulator_enable(vreg->reg);
6638 if (!ret)
6639 vreg->enabled = true;
6640 else
6641 dev_err(dev, "%s: %s enable failed, err=%d\n",
6642 __func__, vreg->name, ret);
6643 out:
6644 return ret;
6647 static int ufshcd_disable_vreg(struct device *dev, struct ufs_vreg *vreg)
6649 int ret = 0;
6651 if (!vreg)
6652 goto out;
6653 else if (!vreg->enabled || vreg->unused)
6654 goto out;
6656 ret = regulator_disable(vreg->reg);
6658 if (!ret) {
6659 /* ignore errors on applying disable config */
6660 ufshcd_config_vreg(dev, vreg, false);
6661 vreg->enabled = false;
6662 } else {
6663 dev_err(dev, "%s: %s disable failed, err=%d\n",
6664 __func__, vreg->name, ret);
6666 out:
6667 return ret;
6670 static int ufshcd_setup_vreg(struct ufs_hba *hba, bool on)
6672 int ret = 0;
6673 struct device *dev = hba->dev;
6674 struct ufs_vreg_info *info = &hba->vreg_info;
6676 if (!info)
6677 goto out;
6679 ret = ufshcd_toggle_vreg(dev, info->vcc, on);
6680 if (ret)
6681 goto out;
6683 ret = ufshcd_toggle_vreg(dev, info->vccq, on);
6684 if (ret)
6685 goto out;
6687 ret = ufshcd_toggle_vreg(dev, info->vccq2, on);
6688 if (ret)
6689 goto out;
6691 out:
6692 if (ret) {
6693 ufshcd_toggle_vreg(dev, info->vccq2, false);
6694 ufshcd_toggle_vreg(dev, info->vccq, false);
6695 ufshcd_toggle_vreg(dev, info->vcc, false);
6697 return ret;
6700 static int ufshcd_setup_hba_vreg(struct ufs_hba *hba, bool on)
6702 struct ufs_vreg_info *info = &hba->vreg_info;
6704 if (info)
6705 return ufshcd_toggle_vreg(hba->dev, info->vdd_hba, on);
6707 return 0;
6710 static int ufshcd_get_vreg(struct device *dev, struct ufs_vreg *vreg)
6712 int ret = 0;
6714 if (!vreg)
6715 goto out;
6717 vreg->reg = devm_regulator_get(dev, vreg->name);
6718 if (IS_ERR(vreg->reg)) {
6719 ret = PTR_ERR(vreg->reg);
6720 dev_err(dev, "%s: %s get failed, err=%d\n",
6721 __func__, vreg->name, ret);
6723 out:
6724 return ret;
6727 static int ufshcd_init_vreg(struct ufs_hba *hba)
6729 int ret = 0;
6730 struct device *dev = hba->dev;
6731 struct ufs_vreg_info *info = &hba->vreg_info;
6733 if (!info)
6734 goto out;
6736 ret = ufshcd_get_vreg(dev, info->vcc);
6737 if (ret)
6738 goto out;
6740 ret = ufshcd_get_vreg(dev, info->vccq);
6741 if (ret)
6742 goto out;
6744 ret = ufshcd_get_vreg(dev, info->vccq2);
6745 out:
6746 return ret;
6749 static int ufshcd_init_hba_vreg(struct ufs_hba *hba)
6751 struct ufs_vreg_info *info = &hba->vreg_info;
6753 if (info)
6754 return ufshcd_get_vreg(hba->dev, info->vdd_hba);
6756 return 0;
6759 static int ufshcd_set_vccq_rail_unused(struct ufs_hba *hba, bool unused)
6761 int ret = 0;
6762 struct ufs_vreg_info *info = &hba->vreg_info;
6764 if (!info)
6765 goto out;
6766 else if (!info->vccq)
6767 goto out;
6769 if (unused) {
6770 /* shut off the rail here */
6771 ret = ufshcd_toggle_vreg(hba->dev, info->vccq, false);
6773 * Mark this rail as no longer used, so it doesn't get enabled
6774 * later by mistake
6776 if (!ret)
6777 info->vccq->unused = true;
6778 } else {
6780 * rail should have been already enabled hence just make sure
6781 * that unused flag is cleared.
6783 info->vccq->unused = false;
6785 out:
6786 return ret;
6789 static int __ufshcd_setup_clocks(struct ufs_hba *hba, bool on,
6790 bool skip_ref_clk)
6792 int ret = 0;
6793 struct ufs_clk_info *clki;
6794 struct list_head *head = &hba->clk_list_head;
6795 unsigned long flags;
6796 ktime_t start = ktime_get();
6797 bool clk_state_changed = false;
6799 if (list_empty(head))
6800 goto out;
6802 ret = ufshcd_vops_setup_clocks(hba, on, PRE_CHANGE);
6803 if (ret)
6804 return ret;
6806 list_for_each_entry(clki, head, list) {
6807 if (!IS_ERR_OR_NULL(clki->clk)) {
6808 if (skip_ref_clk && !strcmp(clki->name, "ref_clk"))
6809 continue;
6811 clk_state_changed = on ^ clki->enabled;
6812 if (on && !clki->enabled) {
6813 ret = clk_prepare_enable(clki->clk);
6814 if (ret) {
6815 dev_err(hba->dev, "%s: %s prepare enable failed, %d\n",
6816 __func__, clki->name, ret);
6817 goto out;
6819 } else if (!on && clki->enabled) {
6820 clk_disable_unprepare(clki->clk);
6822 clki->enabled = on;
6823 dev_dbg(hba->dev, "%s: clk: %s %sabled\n", __func__,
6824 clki->name, on ? "en" : "dis");
6828 ret = ufshcd_vops_setup_clocks(hba, on, POST_CHANGE);
6829 if (ret)
6830 return ret;
6832 out:
6833 if (ret) {
6834 list_for_each_entry(clki, head, list) {
6835 if (!IS_ERR_OR_NULL(clki->clk) && clki->enabled)
6836 clk_disable_unprepare(clki->clk);
6838 } else if (!ret && on) {
6839 spin_lock_irqsave(hba->host->host_lock, flags);
6840 hba->clk_gating.state = CLKS_ON;
6841 trace_ufshcd_clk_gating(dev_name(hba->dev),
6842 hba->clk_gating.state);
6843 spin_unlock_irqrestore(hba->host->host_lock, flags);
6846 if (clk_state_changed)
6847 trace_ufshcd_profile_clk_gating(dev_name(hba->dev),
6848 (on ? "on" : "off"),
6849 ktime_to_us(ktime_sub(ktime_get(), start)), ret);
6850 return ret;
6853 static int ufshcd_setup_clocks(struct ufs_hba *hba, bool on)
6855 return __ufshcd_setup_clocks(hba, on, false);
6858 static int ufshcd_init_clocks(struct ufs_hba *hba)
6860 int ret = 0;
6861 struct ufs_clk_info *clki;
6862 struct device *dev = hba->dev;
6863 struct list_head *head = &hba->clk_list_head;
6865 if (list_empty(head))
6866 goto out;
6868 list_for_each_entry(clki, head, list) {
6869 if (!clki->name)
6870 continue;
6872 clki->clk = devm_clk_get(dev, clki->name);
6873 if (IS_ERR(clki->clk)) {
6874 ret = PTR_ERR(clki->clk);
6875 dev_err(dev, "%s: %s clk get failed, %d\n",
6876 __func__, clki->name, ret);
6877 goto out;
6880 if (clki->max_freq) {
6881 ret = clk_set_rate(clki->clk, clki->max_freq);
6882 if (ret) {
6883 dev_err(hba->dev, "%s: %s clk set rate(%dHz) failed, %d\n",
6884 __func__, clki->name,
6885 clki->max_freq, ret);
6886 goto out;
6888 clki->curr_freq = clki->max_freq;
6890 dev_dbg(dev, "%s: clk: %s, rate: %lu\n", __func__,
6891 clki->name, clk_get_rate(clki->clk));
6893 out:
6894 return ret;
6897 static int ufshcd_variant_hba_init(struct ufs_hba *hba)
6899 int err = 0;
6901 if (!hba->vops)
6902 goto out;
6904 err = ufshcd_vops_init(hba);
6905 if (err)
6906 goto out;
6908 err = ufshcd_vops_setup_regulators(hba, true);
6909 if (err)
6910 goto out_exit;
6912 goto out;
6914 out_exit:
6915 ufshcd_vops_exit(hba);
6916 out:
6917 if (err)
6918 dev_err(hba->dev, "%s: variant %s init failed err %d\n",
6919 __func__, ufshcd_get_var_name(hba), err);
6920 return err;
6923 static void ufshcd_variant_hba_exit(struct ufs_hba *hba)
6925 if (!hba->vops)
6926 return;
6928 ufshcd_vops_setup_regulators(hba, false);
6930 ufshcd_vops_exit(hba);
6933 static int ufshcd_hba_init(struct ufs_hba *hba)
6935 int err;
6938 * Handle host controller power separately from the UFS device power
6939 * rails as it will help controlling the UFS host controller power
6940 * collapse easily which is different than UFS device power collapse.
6941 * Also, enable the host controller power before we go ahead with rest
6942 * of the initialization here.
6944 err = ufshcd_init_hba_vreg(hba);
6945 if (err)
6946 goto out;
6948 err = ufshcd_setup_hba_vreg(hba, true);
6949 if (err)
6950 goto out;
6952 err = ufshcd_init_clocks(hba);
6953 if (err)
6954 goto out_disable_hba_vreg;
6956 err = ufshcd_setup_clocks(hba, true);
6957 if (err)
6958 goto out_disable_hba_vreg;
6960 err = ufshcd_init_vreg(hba);
6961 if (err)
6962 goto out_disable_clks;
6964 err = ufshcd_setup_vreg(hba, true);
6965 if (err)
6966 goto out_disable_clks;
6968 err = ufshcd_variant_hba_init(hba);
6969 if (err)
6970 goto out_disable_vreg;
6972 hba->is_powered = true;
6973 goto out;
6975 out_disable_vreg:
6976 ufshcd_setup_vreg(hba, false);
6977 out_disable_clks:
6978 ufshcd_setup_clocks(hba, false);
6979 out_disable_hba_vreg:
6980 ufshcd_setup_hba_vreg(hba, false);
6981 out:
6982 return err;
6985 static void ufshcd_hba_exit(struct ufs_hba *hba)
6987 if (hba->is_powered) {
6988 ufshcd_variant_hba_exit(hba);
6989 ufshcd_setup_vreg(hba, false);
6990 ufshcd_suspend_clkscaling(hba);
6991 if (ufshcd_is_clkscaling_supported(hba)) {
6992 if (hba->devfreq)
6993 ufshcd_suspend_clkscaling(hba);
6994 destroy_workqueue(hba->clk_scaling.workq);
6996 ufshcd_setup_clocks(hba, false);
6997 ufshcd_setup_hba_vreg(hba, false);
6998 hba->is_powered = false;
7002 static int
7003 ufshcd_send_request_sense(struct ufs_hba *hba, struct scsi_device *sdp)
7005 unsigned char cmd[6] = {REQUEST_SENSE,
7009 UFSHCD_REQ_SENSE_SIZE,
7011 char *buffer;
7012 int ret;
7014 buffer = kzalloc(UFSHCD_REQ_SENSE_SIZE, GFP_KERNEL);
7015 if (!buffer) {
7016 ret = -ENOMEM;
7017 goto out;
7020 ret = scsi_execute(sdp, cmd, DMA_FROM_DEVICE, buffer,
7021 UFSHCD_REQ_SENSE_SIZE, NULL, NULL,
7022 msecs_to_jiffies(1000), 3, 0, RQF_PM, NULL);
7023 if (ret)
7024 pr_err("%s: failed with err %d\n", __func__, ret);
7026 kfree(buffer);
7027 out:
7028 return ret;
7032 * ufshcd_set_dev_pwr_mode - sends START STOP UNIT command to set device
7033 * power mode
7034 * @hba: per adapter instance
7035 * @pwr_mode: device power mode to set
7037 * Returns 0 if requested power mode is set successfully
7038 * Returns non-zero if failed to set the requested power mode
7040 static int ufshcd_set_dev_pwr_mode(struct ufs_hba *hba,
7041 enum ufs_dev_pwr_mode pwr_mode)
7043 unsigned char cmd[6] = { START_STOP };
7044 struct scsi_sense_hdr sshdr;
7045 struct scsi_device *sdp;
7046 unsigned long flags;
7047 int ret;
7049 spin_lock_irqsave(hba->host->host_lock, flags);
7050 sdp = hba->sdev_ufs_device;
7051 if (sdp) {
7052 ret = scsi_device_get(sdp);
7053 if (!ret && !scsi_device_online(sdp)) {
7054 ret = -ENODEV;
7055 scsi_device_put(sdp);
7057 } else {
7058 ret = -ENODEV;
7060 spin_unlock_irqrestore(hba->host->host_lock, flags);
7062 if (ret)
7063 return ret;
7066 * If scsi commands fail, the scsi mid-layer schedules scsi error-
7067 * handling, which would wait for host to be resumed. Since we know
7068 * we are functional while we are here, skip host resume in error
7069 * handling context.
7071 hba->host->eh_noresume = 1;
7072 if (hba->wlun_dev_clr_ua) {
7073 ret = ufshcd_send_request_sense(hba, sdp);
7074 if (ret)
7075 goto out;
7076 /* Unit attention condition is cleared now */
7077 hba->wlun_dev_clr_ua = false;
7080 cmd[4] = pwr_mode << 4;
7083 * Current function would be generally called from the power management
7084 * callbacks hence set the RQF_PM flag so that it doesn't resume the
7085 * already suspended childs.
7087 ret = scsi_execute(sdp, cmd, DMA_NONE, NULL, 0, NULL, &sshdr,
7088 START_STOP_TIMEOUT, 0, 0, RQF_PM, NULL);
7089 if (ret) {
7090 sdev_printk(KERN_WARNING, sdp,
7091 "START_STOP failed for power mode: %d, result %x\n",
7092 pwr_mode, ret);
7093 if (driver_byte(ret) & DRIVER_SENSE)
7094 scsi_print_sense_hdr(sdp, NULL, &sshdr);
7097 if (!ret)
7098 hba->curr_dev_pwr_mode = pwr_mode;
7099 out:
7100 scsi_device_put(sdp);
7101 hba->host->eh_noresume = 0;
7102 return ret;
7105 static int ufshcd_link_state_transition(struct ufs_hba *hba,
7106 enum uic_link_state req_link_state,
7107 int check_for_bkops)
7109 int ret = 0;
7111 if (req_link_state == hba->uic_link_state)
7112 return 0;
7114 if (req_link_state == UIC_LINK_HIBERN8_STATE) {
7115 ret = ufshcd_uic_hibern8_enter(hba);
7116 if (!ret)
7117 ufshcd_set_link_hibern8(hba);
7118 else
7119 goto out;
7122 * If autobkops is enabled, link can't be turned off because
7123 * turning off the link would also turn off the device.
7125 else if ((req_link_state == UIC_LINK_OFF_STATE) &&
7126 (!check_for_bkops || (check_for_bkops &&
7127 !hba->auto_bkops_enabled))) {
7129 * Let's make sure that link is in low power mode, we are doing
7130 * this currently by putting the link in Hibern8. Otherway to
7131 * put the link in low power mode is to send the DME end point
7132 * to device and then send the DME reset command to local
7133 * unipro. But putting the link in hibern8 is much faster.
7135 ret = ufshcd_uic_hibern8_enter(hba);
7136 if (ret)
7137 goto out;
7139 * Change controller state to "reset state" which
7140 * should also put the link in off/reset state
7142 ufshcd_hba_stop(hba, true);
7144 * TODO: Check if we need any delay to make sure that
7145 * controller is reset
7147 ufshcd_set_link_off(hba);
7150 out:
7151 return ret;
7154 static void ufshcd_vreg_set_lpm(struct ufs_hba *hba)
7157 * It seems some UFS devices may keep drawing more than sleep current
7158 * (atleast for 500us) from UFS rails (especially from VCCQ rail).
7159 * To avoid this situation, add 2ms delay before putting these UFS
7160 * rails in LPM mode.
7162 if (!ufshcd_is_link_active(hba) &&
7163 hba->dev_quirks & UFS_DEVICE_QUIRK_DELAY_BEFORE_LPM)
7164 usleep_range(2000, 2100);
7167 * If UFS device is either in UFS_Sleep turn off VCC rail to save some
7168 * power.
7170 * If UFS device and link is in OFF state, all power supplies (VCC,
7171 * VCCQ, VCCQ2) can be turned off if power on write protect is not
7172 * required. If UFS link is inactive (Hibern8 or OFF state) and device
7173 * is in sleep state, put VCCQ & VCCQ2 rails in LPM mode.
7175 * Ignore the error returned by ufshcd_toggle_vreg() as device is anyway
7176 * in low power state which would save some power.
7178 if (ufshcd_is_ufs_dev_poweroff(hba) && ufshcd_is_link_off(hba) &&
7179 !hba->dev_info.is_lu_power_on_wp) {
7180 ufshcd_setup_vreg(hba, false);
7181 } else if (!ufshcd_is_ufs_dev_active(hba)) {
7182 ufshcd_toggle_vreg(hba->dev, hba->vreg_info.vcc, false);
7183 if (!ufshcd_is_link_active(hba)) {
7184 ufshcd_config_vreg_lpm(hba, hba->vreg_info.vccq);
7185 ufshcd_config_vreg_lpm(hba, hba->vreg_info.vccq2);
7190 static int ufshcd_vreg_set_hpm(struct ufs_hba *hba)
7192 int ret = 0;
7194 if (ufshcd_is_ufs_dev_poweroff(hba) && ufshcd_is_link_off(hba) &&
7195 !hba->dev_info.is_lu_power_on_wp) {
7196 ret = ufshcd_setup_vreg(hba, true);
7197 } else if (!ufshcd_is_ufs_dev_active(hba)) {
7198 if (!ret && !ufshcd_is_link_active(hba)) {
7199 ret = ufshcd_config_vreg_hpm(hba, hba->vreg_info.vccq);
7200 if (ret)
7201 goto vcc_disable;
7202 ret = ufshcd_config_vreg_hpm(hba, hba->vreg_info.vccq2);
7203 if (ret)
7204 goto vccq_lpm;
7206 ret = ufshcd_toggle_vreg(hba->dev, hba->vreg_info.vcc, true);
7208 goto out;
7210 vccq_lpm:
7211 ufshcd_config_vreg_lpm(hba, hba->vreg_info.vccq);
7212 vcc_disable:
7213 ufshcd_toggle_vreg(hba->dev, hba->vreg_info.vcc, false);
7214 out:
7215 return ret;
7218 static void ufshcd_hba_vreg_set_lpm(struct ufs_hba *hba)
7220 if (ufshcd_is_link_off(hba))
7221 ufshcd_setup_hba_vreg(hba, false);
7224 static void ufshcd_hba_vreg_set_hpm(struct ufs_hba *hba)
7226 if (ufshcd_is_link_off(hba))
7227 ufshcd_setup_hba_vreg(hba, true);
7231 * ufshcd_suspend - helper function for suspend operations
7232 * @hba: per adapter instance
7233 * @pm_op: desired low power operation type
7235 * This function will try to put the UFS device and link into low power
7236 * mode based on the "rpm_lvl" (Runtime PM level) or "spm_lvl"
7237 * (System PM level).
7239 * If this function is called during shutdown, it will make sure that
7240 * both UFS device and UFS link is powered off.
7242 * NOTE: UFS device & link must be active before we enter in this function.
7244 * Returns 0 for success and non-zero for failure
7246 static int ufshcd_suspend(struct ufs_hba *hba, enum ufs_pm_op pm_op)
7248 int ret = 0;
7249 enum ufs_pm_level pm_lvl;
7250 enum ufs_dev_pwr_mode req_dev_pwr_mode;
7251 enum uic_link_state req_link_state;
7253 hba->pm_op_in_progress = 1;
7254 if (!ufshcd_is_shutdown_pm(pm_op)) {
7255 pm_lvl = ufshcd_is_runtime_pm(pm_op) ?
7256 hba->rpm_lvl : hba->spm_lvl;
7257 req_dev_pwr_mode = ufs_get_pm_lvl_to_dev_pwr_mode(pm_lvl);
7258 req_link_state = ufs_get_pm_lvl_to_link_pwr_state(pm_lvl);
7259 } else {
7260 req_dev_pwr_mode = UFS_POWERDOWN_PWR_MODE;
7261 req_link_state = UIC_LINK_OFF_STATE;
7265 * If we can't transition into any of the low power modes
7266 * just gate the clocks.
7268 ufshcd_hold(hba, false);
7269 hba->clk_gating.is_suspended = true;
7271 if (hba->clk_scaling.is_allowed) {
7272 cancel_work_sync(&hba->clk_scaling.suspend_work);
7273 cancel_work_sync(&hba->clk_scaling.resume_work);
7274 ufshcd_suspend_clkscaling(hba);
7277 if (req_dev_pwr_mode == UFS_ACTIVE_PWR_MODE &&
7278 req_link_state == UIC_LINK_ACTIVE_STATE) {
7279 goto disable_clks;
7282 if ((req_dev_pwr_mode == hba->curr_dev_pwr_mode) &&
7283 (req_link_state == hba->uic_link_state))
7284 goto enable_gating;
7286 /* UFS device & link must be active before we enter in this function */
7287 if (!ufshcd_is_ufs_dev_active(hba) || !ufshcd_is_link_active(hba)) {
7288 ret = -EINVAL;
7289 goto enable_gating;
7292 if (ufshcd_is_runtime_pm(pm_op)) {
7293 if (ufshcd_can_autobkops_during_suspend(hba)) {
7295 * The device is idle with no requests in the queue,
7296 * allow background operations if bkops status shows
7297 * that performance might be impacted.
7299 ret = ufshcd_urgent_bkops(hba);
7300 if (ret)
7301 goto enable_gating;
7302 } else {
7303 /* make sure that auto bkops is disabled */
7304 ufshcd_disable_auto_bkops(hba);
7308 if ((req_dev_pwr_mode != hba->curr_dev_pwr_mode) &&
7309 ((ufshcd_is_runtime_pm(pm_op) && !hba->auto_bkops_enabled) ||
7310 !ufshcd_is_runtime_pm(pm_op))) {
7311 /* ensure that bkops is disabled */
7312 ufshcd_disable_auto_bkops(hba);
7313 ret = ufshcd_set_dev_pwr_mode(hba, req_dev_pwr_mode);
7314 if (ret)
7315 goto enable_gating;
7318 ret = ufshcd_link_state_transition(hba, req_link_state, 1);
7319 if (ret)
7320 goto set_dev_active;
7322 ufshcd_vreg_set_lpm(hba);
7324 disable_clks:
7326 * Call vendor specific suspend callback. As these callbacks may access
7327 * vendor specific host controller register space call them before the
7328 * host clocks are ON.
7330 ret = ufshcd_vops_suspend(hba, pm_op);
7331 if (ret)
7332 goto set_link_active;
7334 if (!ufshcd_is_link_active(hba))
7335 ufshcd_setup_clocks(hba, false);
7336 else
7337 /* If link is active, device ref_clk can't be switched off */
7338 __ufshcd_setup_clocks(hba, false, true);
7340 hba->clk_gating.state = CLKS_OFF;
7341 trace_ufshcd_clk_gating(dev_name(hba->dev), hba->clk_gating.state);
7343 * Disable the host irq as host controller as there won't be any
7344 * host controller transaction expected till resume.
7346 ufshcd_disable_irq(hba);
7347 /* Put the host controller in low power mode if possible */
7348 ufshcd_hba_vreg_set_lpm(hba);
7349 goto out;
7351 set_link_active:
7352 if (hba->clk_scaling.is_allowed)
7353 ufshcd_resume_clkscaling(hba);
7354 ufshcd_vreg_set_hpm(hba);
7355 if (ufshcd_is_link_hibern8(hba) && !ufshcd_uic_hibern8_exit(hba))
7356 ufshcd_set_link_active(hba);
7357 else if (ufshcd_is_link_off(hba))
7358 ufshcd_host_reset_and_restore(hba);
7359 set_dev_active:
7360 if (!ufshcd_set_dev_pwr_mode(hba, UFS_ACTIVE_PWR_MODE))
7361 ufshcd_disable_auto_bkops(hba);
7362 enable_gating:
7363 if (hba->clk_scaling.is_allowed)
7364 ufshcd_resume_clkscaling(hba);
7365 hba->clk_gating.is_suspended = false;
7366 ufshcd_release(hba);
7367 out:
7368 hba->pm_op_in_progress = 0;
7369 return ret;
7373 * ufshcd_resume - helper function for resume operations
7374 * @hba: per adapter instance
7375 * @pm_op: runtime PM or system PM
7377 * This function basically brings the UFS device, UniPro link and controller
7378 * to active state.
7380 * Returns 0 for success and non-zero for failure
7382 static int ufshcd_resume(struct ufs_hba *hba, enum ufs_pm_op pm_op)
7384 int ret;
7385 enum uic_link_state old_link_state;
7387 hba->pm_op_in_progress = 1;
7388 old_link_state = hba->uic_link_state;
7390 ufshcd_hba_vreg_set_hpm(hba);
7391 /* Make sure clocks are enabled before accessing controller */
7392 ret = ufshcd_setup_clocks(hba, true);
7393 if (ret)
7394 goto out;
7396 /* enable the host irq as host controller would be active soon */
7397 ret = ufshcd_enable_irq(hba);
7398 if (ret)
7399 goto disable_irq_and_vops_clks;
7401 ret = ufshcd_vreg_set_hpm(hba);
7402 if (ret)
7403 goto disable_irq_and_vops_clks;
7406 * Call vendor specific resume callback. As these callbacks may access
7407 * vendor specific host controller register space call them when the
7408 * host clocks are ON.
7410 ret = ufshcd_vops_resume(hba, pm_op);
7411 if (ret)
7412 goto disable_vreg;
7414 if (ufshcd_is_link_hibern8(hba)) {
7415 ret = ufshcd_uic_hibern8_exit(hba);
7416 if (!ret)
7417 ufshcd_set_link_active(hba);
7418 else
7419 goto vendor_suspend;
7420 } else if (ufshcd_is_link_off(hba)) {
7421 ret = ufshcd_host_reset_and_restore(hba);
7423 * ufshcd_host_reset_and_restore() should have already
7424 * set the link state as active
7426 if (ret || !ufshcd_is_link_active(hba))
7427 goto vendor_suspend;
7430 if (!ufshcd_is_ufs_dev_active(hba)) {
7431 ret = ufshcd_set_dev_pwr_mode(hba, UFS_ACTIVE_PWR_MODE);
7432 if (ret)
7433 goto set_old_link_state;
7436 if (ufshcd_keep_autobkops_enabled_except_suspend(hba))
7437 ufshcd_enable_auto_bkops(hba);
7438 else
7440 * If BKOPs operations are urgently needed at this moment then
7441 * keep auto-bkops enabled or else disable it.
7443 ufshcd_urgent_bkops(hba);
7445 hba->clk_gating.is_suspended = false;
7447 if (hba->clk_scaling.is_allowed)
7448 ufshcd_resume_clkscaling(hba);
7450 /* Schedule clock gating in case of no access to UFS device yet */
7451 ufshcd_release(hba);
7453 /* Enable Auto-Hibernate if configured */
7454 ufshcd_auto_hibern8_enable(hba);
7456 goto out;
7458 set_old_link_state:
7459 ufshcd_link_state_transition(hba, old_link_state, 0);
7460 vendor_suspend:
7461 ufshcd_vops_suspend(hba, pm_op);
7462 disable_vreg:
7463 ufshcd_vreg_set_lpm(hba);
7464 disable_irq_and_vops_clks:
7465 ufshcd_disable_irq(hba);
7466 if (hba->clk_scaling.is_allowed)
7467 ufshcd_suspend_clkscaling(hba);
7468 ufshcd_setup_clocks(hba, false);
7469 out:
7470 hba->pm_op_in_progress = 0;
7471 return ret;
7475 * ufshcd_system_suspend - system suspend routine
7476 * @hba: per adapter instance
7478 * Check the description of ufshcd_suspend() function for more details.
7480 * Returns 0 for success and non-zero for failure
7482 int ufshcd_system_suspend(struct ufs_hba *hba)
7484 int ret = 0;
7485 ktime_t start = ktime_get();
7487 if (!hba || !hba->is_powered)
7488 return 0;
7490 if ((ufs_get_pm_lvl_to_dev_pwr_mode(hba->spm_lvl) ==
7491 hba->curr_dev_pwr_mode) &&
7492 (ufs_get_pm_lvl_to_link_pwr_state(hba->spm_lvl) ==
7493 hba->uic_link_state))
7494 goto out;
7496 if (pm_runtime_suspended(hba->dev)) {
7498 * UFS device and/or UFS link low power states during runtime
7499 * suspend seems to be different than what is expected during
7500 * system suspend. Hence runtime resume the devic & link and
7501 * let the system suspend low power states to take effect.
7502 * TODO: If resume takes longer time, we might have optimize
7503 * it in future by not resuming everything if possible.
7505 ret = ufshcd_runtime_resume(hba);
7506 if (ret)
7507 goto out;
7510 ret = ufshcd_suspend(hba, UFS_SYSTEM_PM);
7511 out:
7512 trace_ufshcd_system_suspend(dev_name(hba->dev), ret,
7513 ktime_to_us(ktime_sub(ktime_get(), start)),
7514 hba->curr_dev_pwr_mode, hba->uic_link_state);
7515 if (!ret)
7516 hba->is_sys_suspended = true;
7517 return ret;
7519 EXPORT_SYMBOL(ufshcd_system_suspend);
7522 * ufshcd_system_resume - system resume routine
7523 * @hba: per adapter instance
7525 * Returns 0 for success and non-zero for failure
7528 int ufshcd_system_resume(struct ufs_hba *hba)
7530 int ret = 0;
7531 ktime_t start = ktime_get();
7533 if (!hba)
7534 return -EINVAL;
7536 if (!hba->is_powered || pm_runtime_suspended(hba->dev))
7538 * Let the runtime resume take care of resuming
7539 * if runtime suspended.
7541 goto out;
7542 else
7543 ret = ufshcd_resume(hba, UFS_SYSTEM_PM);
7544 out:
7545 trace_ufshcd_system_resume(dev_name(hba->dev), ret,
7546 ktime_to_us(ktime_sub(ktime_get(), start)),
7547 hba->curr_dev_pwr_mode, hba->uic_link_state);
7548 return ret;
7550 EXPORT_SYMBOL(ufshcd_system_resume);
7553 * ufshcd_runtime_suspend - runtime suspend routine
7554 * @hba: per adapter instance
7556 * Check the description of ufshcd_suspend() function for more details.
7558 * Returns 0 for success and non-zero for failure
7560 int ufshcd_runtime_suspend(struct ufs_hba *hba)
7562 int ret = 0;
7563 ktime_t start = ktime_get();
7565 if (!hba)
7566 return -EINVAL;
7568 if (!hba->is_powered)
7569 goto out;
7570 else
7571 ret = ufshcd_suspend(hba, UFS_RUNTIME_PM);
7572 out:
7573 trace_ufshcd_runtime_suspend(dev_name(hba->dev), ret,
7574 ktime_to_us(ktime_sub(ktime_get(), start)),
7575 hba->curr_dev_pwr_mode, hba->uic_link_state);
7576 return ret;
7578 EXPORT_SYMBOL(ufshcd_runtime_suspend);
7581 * ufshcd_runtime_resume - runtime resume routine
7582 * @hba: per adapter instance
7584 * This function basically brings the UFS device, UniPro link and controller
7585 * to active state. Following operations are done in this function:
7587 * 1. Turn on all the controller related clocks
7588 * 2. Bring the UniPro link out of Hibernate state
7589 * 3. If UFS device is in sleep state, turn ON VCC rail and bring the UFS device
7590 * to active state.
7591 * 4. If auto-bkops is enabled on the device, disable it.
7593 * So following would be the possible power state after this function return
7594 * successfully:
7595 * S1: UFS device in Active state with VCC rail ON
7596 * UniPro link in Active state
7597 * All the UFS/UniPro controller clocks are ON
7599 * Returns 0 for success and non-zero for failure
7601 int ufshcd_runtime_resume(struct ufs_hba *hba)
7603 int ret = 0;
7604 ktime_t start = ktime_get();
7606 if (!hba)
7607 return -EINVAL;
7609 if (!hba->is_powered)
7610 goto out;
7611 else
7612 ret = ufshcd_resume(hba, UFS_RUNTIME_PM);
7613 out:
7614 trace_ufshcd_runtime_resume(dev_name(hba->dev), ret,
7615 ktime_to_us(ktime_sub(ktime_get(), start)),
7616 hba->curr_dev_pwr_mode, hba->uic_link_state);
7617 return ret;
7619 EXPORT_SYMBOL(ufshcd_runtime_resume);
7621 int ufshcd_runtime_idle(struct ufs_hba *hba)
7623 return 0;
7625 EXPORT_SYMBOL(ufshcd_runtime_idle);
7628 * ufshcd_shutdown - shutdown routine
7629 * @hba: per adapter instance
7631 * This function would power off both UFS device and UFS link.
7633 * Returns 0 always to allow force shutdown even in case of errors.
7635 int ufshcd_shutdown(struct ufs_hba *hba)
7637 int ret = 0;
7639 if (ufshcd_is_ufs_dev_poweroff(hba) && ufshcd_is_link_off(hba))
7640 goto out;
7642 if (pm_runtime_suspended(hba->dev)) {
7643 ret = ufshcd_runtime_resume(hba);
7644 if (ret)
7645 goto out;
7648 ret = ufshcd_suspend(hba, UFS_SHUTDOWN_PM);
7649 out:
7650 if (ret)
7651 dev_err(hba->dev, "%s failed, err %d\n", __func__, ret);
7652 /* allow force shutdown even in case of errors */
7653 return 0;
7655 EXPORT_SYMBOL(ufshcd_shutdown);
7658 * ufshcd_remove - de-allocate SCSI host and host memory space
7659 * data structure memory
7660 * @hba: per adapter instance
7662 void ufshcd_remove(struct ufs_hba *hba)
7664 ufs_sysfs_remove_nodes(hba->dev);
7665 scsi_remove_host(hba->host);
7666 /* disable interrupts */
7667 ufshcd_disable_intr(hba, hba->intr_mask);
7668 ufshcd_hba_stop(hba, true);
7670 ufshcd_exit_clk_gating(hba);
7671 if (ufshcd_is_clkscaling_supported(hba))
7672 device_remove_file(hba->dev, &hba->clk_scaling.enable_attr);
7673 ufshcd_hba_exit(hba);
7675 EXPORT_SYMBOL_GPL(ufshcd_remove);
7678 * ufshcd_dealloc_host - deallocate Host Bus Adapter (HBA)
7679 * @hba: pointer to Host Bus Adapter (HBA)
7681 void ufshcd_dealloc_host(struct ufs_hba *hba)
7683 scsi_host_put(hba->host);
7685 EXPORT_SYMBOL_GPL(ufshcd_dealloc_host);
7688 * ufshcd_set_dma_mask - Set dma mask based on the controller
7689 * addressing capability
7690 * @hba: per adapter instance
7692 * Returns 0 for success, non-zero for failure
7694 static int ufshcd_set_dma_mask(struct ufs_hba *hba)
7696 if (hba->capabilities & MASK_64_ADDRESSING_SUPPORT) {
7697 if (!dma_set_mask_and_coherent(hba->dev, DMA_BIT_MASK(64)))
7698 return 0;
7700 return dma_set_mask_and_coherent(hba->dev, DMA_BIT_MASK(32));
7704 * ufshcd_alloc_host - allocate Host Bus Adapter (HBA)
7705 * @dev: pointer to device handle
7706 * @hba_handle: driver private handle
7707 * Returns 0 on success, non-zero value on failure
7709 int ufshcd_alloc_host(struct device *dev, struct ufs_hba **hba_handle)
7711 struct Scsi_Host *host;
7712 struct ufs_hba *hba;
7713 int err = 0;
7715 if (!dev) {
7716 dev_err(dev,
7717 "Invalid memory reference for dev is NULL\n");
7718 err = -ENODEV;
7719 goto out_error;
7722 host = scsi_host_alloc(&ufshcd_driver_template,
7723 sizeof(struct ufs_hba));
7724 if (!host) {
7725 dev_err(dev, "scsi_host_alloc failed\n");
7726 err = -ENOMEM;
7727 goto out_error;
7729 hba = shost_priv(host);
7730 hba->host = host;
7731 hba->dev = dev;
7732 *hba_handle = hba;
7734 INIT_LIST_HEAD(&hba->clk_list_head);
7736 out_error:
7737 return err;
7739 EXPORT_SYMBOL(ufshcd_alloc_host);
7742 * ufshcd_init - Driver initialization routine
7743 * @hba: per-adapter instance
7744 * @mmio_base: base register address
7745 * @irq: Interrupt line of device
7746 * Returns 0 on success, non-zero value on failure
7748 int ufshcd_init(struct ufs_hba *hba, void __iomem *mmio_base, unsigned int irq)
7750 int err;
7751 struct Scsi_Host *host = hba->host;
7752 struct device *dev = hba->dev;
7754 if (!mmio_base) {
7755 dev_err(hba->dev,
7756 "Invalid memory reference for mmio_base is NULL\n");
7757 err = -ENODEV;
7758 goto out_error;
7761 hba->mmio_base = mmio_base;
7762 hba->irq = irq;
7764 /* Set descriptor lengths to specification defaults */
7765 ufshcd_def_desc_sizes(hba);
7767 err = ufshcd_hba_init(hba);
7768 if (err)
7769 goto out_error;
7771 /* Read capabilities registers */
7772 ufshcd_hba_capabilities(hba);
7774 /* Get UFS version supported by the controller */
7775 hba->ufs_version = ufshcd_get_ufs_version(hba);
7777 if ((hba->ufs_version != UFSHCI_VERSION_10) &&
7778 (hba->ufs_version != UFSHCI_VERSION_11) &&
7779 (hba->ufs_version != UFSHCI_VERSION_20) &&
7780 (hba->ufs_version != UFSHCI_VERSION_21))
7781 dev_err(hba->dev, "invalid UFS version 0x%x\n",
7782 hba->ufs_version);
7784 /* Get Interrupt bit mask per version */
7785 hba->intr_mask = ufshcd_get_intr_mask(hba);
7787 err = ufshcd_set_dma_mask(hba);
7788 if (err) {
7789 dev_err(hba->dev, "set dma mask failed\n");
7790 goto out_disable;
7793 /* Allocate memory for host memory space */
7794 err = ufshcd_memory_alloc(hba);
7795 if (err) {
7796 dev_err(hba->dev, "Memory allocation failed\n");
7797 goto out_disable;
7800 /* Configure LRB */
7801 ufshcd_host_memory_configure(hba);
7803 host->can_queue = hba->nutrs;
7804 host->cmd_per_lun = hba->nutrs;
7805 host->max_id = UFSHCD_MAX_ID;
7806 host->max_lun = UFS_MAX_LUNS;
7807 host->max_channel = UFSHCD_MAX_CHANNEL;
7808 host->unique_id = host->host_no;
7809 host->max_cmd_len = MAX_CDB_SIZE;
7811 hba->max_pwr_info.is_valid = false;
7813 /* Initailize wait queue for task management */
7814 init_waitqueue_head(&hba->tm_wq);
7815 init_waitqueue_head(&hba->tm_tag_wq);
7817 /* Initialize work queues */
7818 INIT_WORK(&hba->eh_work, ufshcd_err_handler);
7819 INIT_WORK(&hba->eeh_work, ufshcd_exception_event_handler);
7821 /* Initialize UIC command mutex */
7822 mutex_init(&hba->uic_cmd_mutex);
7824 /* Initialize mutex for device management commands */
7825 mutex_init(&hba->dev_cmd.lock);
7827 init_rwsem(&hba->clk_scaling_lock);
7829 /* Initialize device management tag acquire wait queue */
7830 init_waitqueue_head(&hba->dev_cmd.tag_wq);
7832 ufshcd_init_clk_gating(hba);
7835 * In order to avoid any spurious interrupt immediately after
7836 * registering UFS controller interrupt handler, clear any pending UFS
7837 * interrupt status and disable all the UFS interrupts.
7839 ufshcd_writel(hba, ufshcd_readl(hba, REG_INTERRUPT_STATUS),
7840 REG_INTERRUPT_STATUS);
7841 ufshcd_writel(hba, 0, REG_INTERRUPT_ENABLE);
7843 * Make sure that UFS interrupts are disabled and any pending interrupt
7844 * status is cleared before registering UFS interrupt handler.
7846 mb();
7848 /* IRQ registration */
7849 err = devm_request_irq(dev, irq, ufshcd_intr, IRQF_SHARED, UFSHCD, hba);
7850 if (err) {
7851 dev_err(hba->dev, "request irq failed\n");
7852 goto exit_gating;
7853 } else {
7854 hba->is_irq_enabled = true;
7857 err = scsi_add_host(host, hba->dev);
7858 if (err) {
7859 dev_err(hba->dev, "scsi_add_host failed\n");
7860 goto exit_gating;
7863 /* Host controller enable */
7864 err = ufshcd_hba_enable(hba);
7865 if (err) {
7866 dev_err(hba->dev, "Host controller enable failed\n");
7867 ufshcd_print_host_regs(hba);
7868 ufshcd_print_host_state(hba);
7869 goto out_remove_scsi_host;
7872 if (ufshcd_is_clkscaling_supported(hba)) {
7873 char wq_name[sizeof("ufs_clkscaling_00")];
7875 INIT_WORK(&hba->clk_scaling.suspend_work,
7876 ufshcd_clk_scaling_suspend_work);
7877 INIT_WORK(&hba->clk_scaling.resume_work,
7878 ufshcd_clk_scaling_resume_work);
7880 snprintf(wq_name, sizeof(wq_name), "ufs_clkscaling_%d",
7881 host->host_no);
7882 hba->clk_scaling.workq = create_singlethread_workqueue(wq_name);
7884 ufshcd_clkscaling_init_sysfs(hba);
7888 * Set the default power management level for runtime and system PM.
7889 * Default power saving mode is to keep UFS link in Hibern8 state
7890 * and UFS device in sleep state.
7892 hba->rpm_lvl = ufs_get_desired_pm_lvl_for_dev_link_state(
7893 UFS_SLEEP_PWR_MODE,
7894 UIC_LINK_HIBERN8_STATE);
7895 hba->spm_lvl = ufs_get_desired_pm_lvl_for_dev_link_state(
7896 UFS_SLEEP_PWR_MODE,
7897 UIC_LINK_HIBERN8_STATE);
7899 /* Set the default auto-hiberate idle timer value to 150 ms */
7900 if (hba->capabilities & MASK_AUTO_HIBERN8_SUPPORT) {
7901 hba->ahit = FIELD_PREP(UFSHCI_AHIBERN8_TIMER_MASK, 150) |
7902 FIELD_PREP(UFSHCI_AHIBERN8_SCALE_MASK, 3);
7905 /* Hold auto suspend until async scan completes */
7906 pm_runtime_get_sync(dev);
7909 * We are assuming that device wasn't put in sleep/power-down
7910 * state exclusively during the boot stage before kernel.
7911 * This assumption helps avoid doing link startup twice during
7912 * ufshcd_probe_hba().
7914 ufshcd_set_ufs_dev_active(hba);
7916 async_schedule(ufshcd_async_scan, hba);
7917 ufs_sysfs_add_nodes(hba->dev);
7919 return 0;
7921 out_remove_scsi_host:
7922 scsi_remove_host(hba->host);
7923 exit_gating:
7924 ufshcd_exit_clk_gating(hba);
7925 out_disable:
7926 hba->is_irq_enabled = false;
7927 ufshcd_hba_exit(hba);
7928 out_error:
7929 return err;
7931 EXPORT_SYMBOL_GPL(ufshcd_init);
7933 MODULE_AUTHOR("Santosh Yaragnavi <santosh.sy@samsung.com>");
7934 MODULE_AUTHOR("Vinayak Holikatti <h.vinayak@samsung.com>");
7935 MODULE_DESCRIPTION("Generic UFS host controller driver Core");
7936 MODULE_LICENSE("GPL");
7937 MODULE_VERSION(UFSHCD_DRIVER_VERSION);