scsi: ufshcd: release resources if probe fails
[linux/fpc-iii.git] / drivers / scsi / ufs / ufshcd.c
blob6c0082e2591e96f499d0bf9c2728571f2b4f09fc
1 /*
2 * Universal Flash Storage Host controller driver Core
4 * This code is based on drivers/scsi/ufs/ufshcd.c
5 * Copyright (C) 2011-2013 Samsung India Software Operations
6 * Copyright (c) 2013-2016, The Linux Foundation. All rights reserved.
8 * Authors:
9 * Santosh Yaraganavi <santosh.sy@samsung.com>
10 * Vinayak Holikatti <h.vinayak@samsung.com>
12 * This program is free software; you can redistribute it and/or
13 * modify it under the terms of the GNU General Public License
14 * as published by the Free Software Foundation; either version 2
15 * of the License, or (at your option) any later version.
16 * See the COPYING file in the top-level directory or visit
17 * <http://www.gnu.org/licenses/gpl-2.0.html>
19 * This program is distributed in the hope that it will be useful,
20 * but WITHOUT ANY WARRANTY; without even the implied warranty of
21 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22 * GNU General Public License for more details.
24 * This program is provided "AS IS" and "WITH ALL FAULTS" and
25 * without warranty of any kind. You are solely responsible for
26 * determining the appropriateness of using and distributing
27 * the program and assume all risks associated with your exercise
28 * of rights with respect to the program, including but not limited
29 * to infringement of third party rights, the risks and costs of
30 * program errors, damage to or loss of data, programs or equipment,
31 * and unavailability or interruption of operations. Under no
32 * circumstances will the contributor of this Program be liable for
33 * any damages of any kind arising from your use or distribution of
34 * this program.
36 * The Linux Foundation chooses to take subject only to the GPLv2
37 * license terms, and distributes only under these terms.
40 #include <linux/async.h>
41 #include <linux/devfreq.h>
42 #include <linux/nls.h>
43 #include <linux/of.h>
44 #include "ufshcd.h"
45 #include "ufs_quirks.h"
46 #include "unipro.h"
48 #define UFSHCD_REQ_SENSE_SIZE 18
50 #define UFSHCD_ENABLE_INTRS (UTP_TRANSFER_REQ_COMPL |\
51 UTP_TASK_REQ_COMPL |\
52 UFSHCD_ERROR_MASK)
53 /* UIC command timeout, unit: ms */
54 #define UIC_CMD_TIMEOUT 500
56 /* NOP OUT retries waiting for NOP IN response */
57 #define NOP_OUT_RETRIES 10
58 /* Timeout after 30 msecs if NOP OUT hangs without response */
59 #define NOP_OUT_TIMEOUT 30 /* msecs */
61 /* Query request retries */
62 #define QUERY_REQ_RETRIES 10
63 /* Query request timeout */
64 #define QUERY_REQ_TIMEOUT 30 /* msec */
66 * Query request timeout for fDeviceInit flag
67 * fDeviceInit query response time for some devices is too large that default
68 * QUERY_REQ_TIMEOUT may not be enough for such devices.
70 #define QUERY_FDEVICEINIT_REQ_TIMEOUT 600 /* msec */
72 /* Task management command timeout */
73 #define TM_CMD_TIMEOUT 100 /* msecs */
75 /* maximum number of retries for a general UIC command */
76 #define UFS_UIC_COMMAND_RETRIES 3
78 /* maximum number of link-startup retries */
79 #define DME_LINKSTARTUP_RETRIES 3
81 /* Maximum retries for Hibern8 enter */
82 #define UIC_HIBERN8_ENTER_RETRIES 3
84 /* maximum number of reset retries before giving up */
85 #define MAX_HOST_RESET_RETRIES 5
87 /* Expose the flag value from utp_upiu_query.value */
88 #define MASK_QUERY_UPIU_FLAG_LOC 0xFF
90 /* Interrupt aggregation default timeout, unit: 40us */
91 #define INT_AGGR_DEF_TO 0x02
93 #define ufshcd_toggle_vreg(_dev, _vreg, _on) \
94 ({ \
95 int _ret; \
96 if (_on) \
97 _ret = ufshcd_enable_vreg(_dev, _vreg); \
98 else \
99 _ret = ufshcd_disable_vreg(_dev, _vreg); \
100 _ret; \
103 static u32 ufs_query_desc_max_size[] = {
104 QUERY_DESC_DEVICE_MAX_SIZE,
105 QUERY_DESC_CONFIGURAION_MAX_SIZE,
106 QUERY_DESC_UNIT_MAX_SIZE,
107 QUERY_DESC_RFU_MAX_SIZE,
108 QUERY_DESC_INTERCONNECT_MAX_SIZE,
109 QUERY_DESC_STRING_MAX_SIZE,
110 QUERY_DESC_RFU_MAX_SIZE,
111 QUERY_DESC_GEOMETRY_MAX_SIZE,
112 QUERY_DESC_POWER_MAX_SIZE,
113 QUERY_DESC_RFU_MAX_SIZE,
116 enum {
117 UFSHCD_MAX_CHANNEL = 0,
118 UFSHCD_MAX_ID = 1,
119 UFSHCD_CMD_PER_LUN = 32,
120 UFSHCD_CAN_QUEUE = 32,
123 /* UFSHCD states */
124 enum {
125 UFSHCD_STATE_RESET,
126 UFSHCD_STATE_ERROR,
127 UFSHCD_STATE_OPERATIONAL,
130 /* UFSHCD error handling flags */
131 enum {
132 UFSHCD_EH_IN_PROGRESS = (1 << 0),
135 /* UFSHCD UIC layer error flags */
136 enum {
137 UFSHCD_UIC_DL_PA_INIT_ERROR = (1 << 0), /* Data link layer error */
138 UFSHCD_UIC_DL_NAC_RECEIVED_ERROR = (1 << 1), /* Data link layer error */
139 UFSHCD_UIC_DL_TCx_REPLAY_ERROR = (1 << 2), /* Data link layer error */
140 UFSHCD_UIC_NL_ERROR = (1 << 3), /* Network layer error */
141 UFSHCD_UIC_TL_ERROR = (1 << 4), /* Transport Layer error */
142 UFSHCD_UIC_DME_ERROR = (1 << 5), /* DME error */
145 /* Interrupt configuration options */
146 enum {
147 UFSHCD_INT_DISABLE,
148 UFSHCD_INT_ENABLE,
149 UFSHCD_INT_CLEAR,
152 #define ufshcd_set_eh_in_progress(h) \
153 (h->eh_flags |= UFSHCD_EH_IN_PROGRESS)
154 #define ufshcd_eh_in_progress(h) \
155 (h->eh_flags & UFSHCD_EH_IN_PROGRESS)
156 #define ufshcd_clear_eh_in_progress(h) \
157 (h->eh_flags &= ~UFSHCD_EH_IN_PROGRESS)
159 #define ufshcd_set_ufs_dev_active(h) \
160 ((h)->curr_dev_pwr_mode = UFS_ACTIVE_PWR_MODE)
161 #define ufshcd_set_ufs_dev_sleep(h) \
162 ((h)->curr_dev_pwr_mode = UFS_SLEEP_PWR_MODE)
163 #define ufshcd_set_ufs_dev_poweroff(h) \
164 ((h)->curr_dev_pwr_mode = UFS_POWERDOWN_PWR_MODE)
165 #define ufshcd_is_ufs_dev_active(h) \
166 ((h)->curr_dev_pwr_mode == UFS_ACTIVE_PWR_MODE)
167 #define ufshcd_is_ufs_dev_sleep(h) \
168 ((h)->curr_dev_pwr_mode == UFS_SLEEP_PWR_MODE)
169 #define ufshcd_is_ufs_dev_poweroff(h) \
170 ((h)->curr_dev_pwr_mode == UFS_POWERDOWN_PWR_MODE)
172 static struct ufs_pm_lvl_states ufs_pm_lvl_states[] = {
173 {UFS_ACTIVE_PWR_MODE, UIC_LINK_ACTIVE_STATE},
174 {UFS_ACTIVE_PWR_MODE, UIC_LINK_HIBERN8_STATE},
175 {UFS_SLEEP_PWR_MODE, UIC_LINK_ACTIVE_STATE},
176 {UFS_SLEEP_PWR_MODE, UIC_LINK_HIBERN8_STATE},
177 {UFS_POWERDOWN_PWR_MODE, UIC_LINK_HIBERN8_STATE},
178 {UFS_POWERDOWN_PWR_MODE, UIC_LINK_OFF_STATE},
181 static inline enum ufs_dev_pwr_mode
182 ufs_get_pm_lvl_to_dev_pwr_mode(enum ufs_pm_level lvl)
184 return ufs_pm_lvl_states[lvl].dev_state;
187 static inline enum uic_link_state
188 ufs_get_pm_lvl_to_link_pwr_state(enum ufs_pm_level lvl)
190 return ufs_pm_lvl_states[lvl].link_state;
193 static void ufshcd_tmc_handler(struct ufs_hba *hba);
194 static void ufshcd_async_scan(void *data, async_cookie_t cookie);
195 static int ufshcd_reset_and_restore(struct ufs_hba *hba);
196 static int ufshcd_clear_tm_cmd(struct ufs_hba *hba, int tag);
197 static void ufshcd_hba_exit(struct ufs_hba *hba);
198 static int ufshcd_probe_hba(struct ufs_hba *hba);
199 static int __ufshcd_setup_clocks(struct ufs_hba *hba, bool on,
200 bool skip_ref_clk);
201 static int ufshcd_setup_clocks(struct ufs_hba *hba, bool on);
202 static int ufshcd_set_vccq_rail_unused(struct ufs_hba *hba, bool unused);
203 static int ufshcd_uic_hibern8_exit(struct ufs_hba *hba);
204 static int ufshcd_uic_hibern8_enter(struct ufs_hba *hba);
205 static inline void ufshcd_add_delay_before_dme_cmd(struct ufs_hba *hba);
206 static int ufshcd_host_reset_and_restore(struct ufs_hba *hba);
207 static irqreturn_t ufshcd_intr(int irq, void *__hba);
208 static int ufshcd_config_pwr_mode(struct ufs_hba *hba,
209 struct ufs_pa_layer_attr *desired_pwr_mode);
210 static int ufshcd_change_power_mode(struct ufs_hba *hba,
211 struct ufs_pa_layer_attr *pwr_mode);
212 static inline bool ufshcd_valid_tag(struct ufs_hba *hba, int tag)
214 return tag >= 0 && tag < hba->nutrs;
217 static inline int ufshcd_enable_irq(struct ufs_hba *hba)
219 int ret = 0;
221 if (!hba->is_irq_enabled) {
222 ret = request_irq(hba->irq, ufshcd_intr, IRQF_SHARED, UFSHCD,
223 hba);
224 if (ret)
225 dev_err(hba->dev, "%s: request_irq failed, ret=%d\n",
226 __func__, ret);
227 hba->is_irq_enabled = true;
230 return ret;
233 static inline void ufshcd_disable_irq(struct ufs_hba *hba)
235 if (hba->is_irq_enabled) {
236 free_irq(hba->irq, hba);
237 hba->is_irq_enabled = false;
241 /* replace non-printable or non-ASCII characters with spaces */
242 static inline void ufshcd_remove_non_printable(char *val)
244 if (!val)
245 return;
247 if (*val < 0x20 || *val > 0x7e)
248 *val = ' ';
252 * ufshcd_wait_for_register - wait for register value to change
253 * @hba - per-adapter interface
254 * @reg - mmio register offset
255 * @mask - mask to apply to read register value
256 * @val - wait condition
257 * @interval_us - polling interval in microsecs
258 * @timeout_ms - timeout in millisecs
259 * @can_sleep - perform sleep or just spin
261 * Returns -ETIMEDOUT on error, zero on success
263 int ufshcd_wait_for_register(struct ufs_hba *hba, u32 reg, u32 mask,
264 u32 val, unsigned long interval_us,
265 unsigned long timeout_ms, bool can_sleep)
267 int err = 0;
268 unsigned long timeout = jiffies + msecs_to_jiffies(timeout_ms);
270 /* ignore bits that we don't intend to wait on */
271 val = val & mask;
273 while ((ufshcd_readl(hba, reg) & mask) != val) {
274 if (can_sleep)
275 usleep_range(interval_us, interval_us + 50);
276 else
277 udelay(interval_us);
278 if (time_after(jiffies, timeout)) {
279 if ((ufshcd_readl(hba, reg) & mask) != val)
280 err = -ETIMEDOUT;
281 break;
285 return err;
289 * ufshcd_get_intr_mask - Get the interrupt bit mask
290 * @hba - Pointer to adapter instance
292 * Returns interrupt bit mask per version
294 static inline u32 ufshcd_get_intr_mask(struct ufs_hba *hba)
296 if (hba->ufs_version == UFSHCI_VERSION_10)
297 return INTERRUPT_MASK_ALL_VER_10;
298 else
299 return INTERRUPT_MASK_ALL_VER_11;
303 * ufshcd_get_ufs_version - Get the UFS version supported by the HBA
304 * @hba - Pointer to adapter instance
306 * Returns UFSHCI version supported by the controller
308 static inline u32 ufshcd_get_ufs_version(struct ufs_hba *hba)
310 if (hba->quirks & UFSHCD_QUIRK_BROKEN_UFS_HCI_VERSION)
311 return ufshcd_vops_get_ufs_hci_version(hba);
313 return ufshcd_readl(hba, REG_UFS_VERSION);
317 * ufshcd_is_device_present - Check if any device connected to
318 * the host controller
319 * @hba: pointer to adapter instance
321 * Returns 1 if device present, 0 if no device detected
323 static inline int ufshcd_is_device_present(struct ufs_hba *hba)
325 return (ufshcd_readl(hba, REG_CONTROLLER_STATUS) &
326 DEVICE_PRESENT) ? 1 : 0;
330 * ufshcd_get_tr_ocs - Get the UTRD Overall Command Status
331 * @lrb: pointer to local command reference block
333 * This function is used to get the OCS field from UTRD
334 * Returns the OCS field in the UTRD
336 static inline int ufshcd_get_tr_ocs(struct ufshcd_lrb *lrbp)
338 return le32_to_cpu(lrbp->utr_descriptor_ptr->header.dword_2) & MASK_OCS;
342 * ufshcd_get_tmr_ocs - Get the UTMRD Overall Command Status
343 * @task_req_descp: pointer to utp_task_req_desc structure
345 * This function is used to get the OCS field from UTMRD
346 * Returns the OCS field in the UTMRD
348 static inline int
349 ufshcd_get_tmr_ocs(struct utp_task_req_desc *task_req_descp)
351 return le32_to_cpu(task_req_descp->header.dword_2) & MASK_OCS;
355 * ufshcd_get_tm_free_slot - get a free slot for task management request
356 * @hba: per adapter instance
357 * @free_slot: pointer to variable with available slot value
359 * Get a free tag and lock it until ufshcd_put_tm_slot() is called.
360 * Returns 0 if free slot is not available, else return 1 with tag value
361 * in @free_slot.
363 static bool ufshcd_get_tm_free_slot(struct ufs_hba *hba, int *free_slot)
365 int tag;
366 bool ret = false;
368 if (!free_slot)
369 goto out;
371 do {
372 tag = find_first_zero_bit(&hba->tm_slots_in_use, hba->nutmrs);
373 if (tag >= hba->nutmrs)
374 goto out;
375 } while (test_and_set_bit_lock(tag, &hba->tm_slots_in_use));
377 *free_slot = tag;
378 ret = true;
379 out:
380 return ret;
383 static inline void ufshcd_put_tm_slot(struct ufs_hba *hba, int slot)
385 clear_bit_unlock(slot, &hba->tm_slots_in_use);
389 * ufshcd_utrl_clear - Clear a bit in UTRLCLR register
390 * @hba: per adapter instance
391 * @pos: position of the bit to be cleared
393 static inline void ufshcd_utrl_clear(struct ufs_hba *hba, u32 pos)
395 ufshcd_writel(hba, ~(1 << pos), REG_UTP_TRANSFER_REQ_LIST_CLEAR);
399 * ufshcd_outstanding_req_clear - Clear a bit in outstanding request field
400 * @hba: per adapter instance
401 * @tag: position of the bit to be cleared
403 static inline void ufshcd_outstanding_req_clear(struct ufs_hba *hba, int tag)
405 __clear_bit(tag, &hba->outstanding_reqs);
409 * ufshcd_get_lists_status - Check UCRDY, UTRLRDY and UTMRLRDY
410 * @reg: Register value of host controller status
412 * Returns integer, 0 on Success and positive value if failed
414 static inline int ufshcd_get_lists_status(u32 reg)
417 * The mask 0xFF is for the following HCS register bits
418 * Bit Description
419 * 0 Device Present
420 * 1 UTRLRDY
421 * 2 UTMRLRDY
422 * 3 UCRDY
423 * 4-7 reserved
425 return ((reg & 0xFF) >> 1) ^ 0x07;
429 * ufshcd_get_uic_cmd_result - Get the UIC command result
430 * @hba: Pointer to adapter instance
432 * This function gets the result of UIC command completion
433 * Returns 0 on success, non zero value on error
435 static inline int ufshcd_get_uic_cmd_result(struct ufs_hba *hba)
437 return ufshcd_readl(hba, REG_UIC_COMMAND_ARG_2) &
438 MASK_UIC_COMMAND_RESULT;
442 * ufshcd_get_dme_attr_val - Get the value of attribute returned by UIC command
443 * @hba: Pointer to adapter instance
445 * This function gets UIC command argument3
446 * Returns 0 on success, non zero value on error
448 static inline u32 ufshcd_get_dme_attr_val(struct ufs_hba *hba)
450 return ufshcd_readl(hba, REG_UIC_COMMAND_ARG_3);
454 * ufshcd_get_req_rsp - returns the TR response transaction type
455 * @ucd_rsp_ptr: pointer to response UPIU
457 static inline int
458 ufshcd_get_req_rsp(struct utp_upiu_rsp *ucd_rsp_ptr)
460 return be32_to_cpu(ucd_rsp_ptr->header.dword_0) >> 24;
464 * ufshcd_get_rsp_upiu_result - Get the result from response UPIU
465 * @ucd_rsp_ptr: pointer to response UPIU
467 * This function gets the response status and scsi_status from response UPIU
468 * Returns the response result code.
470 static inline int
471 ufshcd_get_rsp_upiu_result(struct utp_upiu_rsp *ucd_rsp_ptr)
473 return be32_to_cpu(ucd_rsp_ptr->header.dword_1) & MASK_RSP_UPIU_RESULT;
477 * ufshcd_get_rsp_upiu_data_seg_len - Get the data segment length
478 * from response UPIU
479 * @ucd_rsp_ptr: pointer to response UPIU
481 * Return the data segment length.
483 static inline unsigned int
484 ufshcd_get_rsp_upiu_data_seg_len(struct utp_upiu_rsp *ucd_rsp_ptr)
486 return be32_to_cpu(ucd_rsp_ptr->header.dword_2) &
487 MASK_RSP_UPIU_DATA_SEG_LEN;
491 * ufshcd_is_exception_event - Check if the device raised an exception event
492 * @ucd_rsp_ptr: pointer to response UPIU
494 * The function checks if the device raised an exception event indicated in
495 * the Device Information field of response UPIU.
497 * Returns true if exception is raised, false otherwise.
499 static inline bool ufshcd_is_exception_event(struct utp_upiu_rsp *ucd_rsp_ptr)
501 return be32_to_cpu(ucd_rsp_ptr->header.dword_2) &
502 MASK_RSP_EXCEPTION_EVENT ? true : false;
506 * ufshcd_reset_intr_aggr - Reset interrupt aggregation values.
507 * @hba: per adapter instance
509 static inline void
510 ufshcd_reset_intr_aggr(struct ufs_hba *hba)
512 ufshcd_writel(hba, INT_AGGR_ENABLE |
513 INT_AGGR_COUNTER_AND_TIMER_RESET,
514 REG_UTP_TRANSFER_REQ_INT_AGG_CONTROL);
518 * ufshcd_config_intr_aggr - Configure interrupt aggregation values.
519 * @hba: per adapter instance
520 * @cnt: Interrupt aggregation counter threshold
521 * @tmout: Interrupt aggregation timeout value
523 static inline void
524 ufshcd_config_intr_aggr(struct ufs_hba *hba, u8 cnt, u8 tmout)
526 ufshcd_writel(hba, INT_AGGR_ENABLE | INT_AGGR_PARAM_WRITE |
527 INT_AGGR_COUNTER_THLD_VAL(cnt) |
528 INT_AGGR_TIMEOUT_VAL(tmout),
529 REG_UTP_TRANSFER_REQ_INT_AGG_CONTROL);
533 * ufshcd_disable_intr_aggr - Disables interrupt aggregation.
534 * @hba: per adapter instance
536 static inline void ufshcd_disable_intr_aggr(struct ufs_hba *hba)
538 ufshcd_writel(hba, 0, REG_UTP_TRANSFER_REQ_INT_AGG_CONTROL);
542 * ufshcd_enable_run_stop_reg - Enable run-stop registers,
543 * When run-stop registers are set to 1, it indicates the
544 * host controller that it can process the requests
545 * @hba: per adapter instance
547 static void ufshcd_enable_run_stop_reg(struct ufs_hba *hba)
549 ufshcd_writel(hba, UTP_TASK_REQ_LIST_RUN_STOP_BIT,
550 REG_UTP_TASK_REQ_LIST_RUN_STOP);
551 ufshcd_writel(hba, UTP_TRANSFER_REQ_LIST_RUN_STOP_BIT,
552 REG_UTP_TRANSFER_REQ_LIST_RUN_STOP);
556 * ufshcd_hba_start - Start controller initialization sequence
557 * @hba: per adapter instance
559 static inline void ufshcd_hba_start(struct ufs_hba *hba)
561 ufshcd_writel(hba, CONTROLLER_ENABLE, REG_CONTROLLER_ENABLE);
565 * ufshcd_is_hba_active - Get controller state
566 * @hba: per adapter instance
568 * Returns zero if controller is active, 1 otherwise
570 static inline int ufshcd_is_hba_active(struct ufs_hba *hba)
572 return (ufshcd_readl(hba, REG_CONTROLLER_ENABLE) & 0x1) ? 0 : 1;
575 u32 ufshcd_get_local_unipro_ver(struct ufs_hba *hba)
577 /* HCI version 1.0 and 1.1 supports UniPro 1.41 */
578 if ((hba->ufs_version == UFSHCI_VERSION_10) ||
579 (hba->ufs_version == UFSHCI_VERSION_11))
580 return UFS_UNIPRO_VER_1_41;
581 else
582 return UFS_UNIPRO_VER_1_6;
584 EXPORT_SYMBOL(ufshcd_get_local_unipro_ver);
586 static bool ufshcd_is_unipro_pa_params_tuning_req(struct ufs_hba *hba)
589 * If both host and device support UniPro ver1.6 or later, PA layer
590 * parameters tuning happens during link startup itself.
592 * We can manually tune PA layer parameters if either host or device
593 * doesn't support UniPro ver 1.6 or later. But to keep manual tuning
594 * logic simple, we will only do manual tuning if local unipro version
595 * doesn't support ver1.6 or later.
597 if (ufshcd_get_local_unipro_ver(hba) < UFS_UNIPRO_VER_1_6)
598 return true;
599 else
600 return false;
603 static void ufshcd_suspend_clkscaling(struct ufs_hba *hba)
605 if (ufshcd_is_clkscaling_enabled(hba)) {
606 devfreq_suspend_device(hba->devfreq);
607 hba->clk_scaling.window_start_t = 0;
611 static void ufshcd_resume_clkscaling(struct ufs_hba *hba)
613 if (ufshcd_is_clkscaling_enabled(hba))
614 devfreq_resume_device(hba->devfreq);
617 static void ufshcd_ungate_work(struct work_struct *work)
619 int ret;
620 unsigned long flags;
621 struct ufs_hba *hba = container_of(work, struct ufs_hba,
622 clk_gating.ungate_work);
624 cancel_delayed_work_sync(&hba->clk_gating.gate_work);
626 spin_lock_irqsave(hba->host->host_lock, flags);
627 if (hba->clk_gating.state == CLKS_ON) {
628 spin_unlock_irqrestore(hba->host->host_lock, flags);
629 goto unblock_reqs;
632 spin_unlock_irqrestore(hba->host->host_lock, flags);
633 ufshcd_setup_clocks(hba, true);
635 /* Exit from hibern8 */
636 if (ufshcd_can_hibern8_during_gating(hba)) {
637 /* Prevent gating in this path */
638 hba->clk_gating.is_suspended = true;
639 if (ufshcd_is_link_hibern8(hba)) {
640 ret = ufshcd_uic_hibern8_exit(hba);
641 if (ret)
642 dev_err(hba->dev, "%s: hibern8 exit failed %d\n",
643 __func__, ret);
644 else
645 ufshcd_set_link_active(hba);
647 hba->clk_gating.is_suspended = false;
649 unblock_reqs:
650 ufshcd_resume_clkscaling(hba);
651 scsi_unblock_requests(hba->host);
655 * ufshcd_hold - Enable clocks that were gated earlier due to ufshcd_release.
656 * Also, exit from hibern8 mode and set the link as active.
657 * @hba: per adapter instance
658 * @async: This indicates whether caller should ungate clocks asynchronously.
660 int ufshcd_hold(struct ufs_hba *hba, bool async)
662 int rc = 0;
663 unsigned long flags;
665 if (!ufshcd_is_clkgating_allowed(hba))
666 goto out;
667 spin_lock_irqsave(hba->host->host_lock, flags);
668 hba->clk_gating.active_reqs++;
670 if (ufshcd_eh_in_progress(hba)) {
671 spin_unlock_irqrestore(hba->host->host_lock, flags);
672 return 0;
675 start:
676 switch (hba->clk_gating.state) {
677 case CLKS_ON:
679 * Wait for the ungate work to complete if in progress.
680 * Though the clocks may be in ON state, the link could
681 * still be in hibner8 state if hibern8 is allowed
682 * during clock gating.
683 * Make sure we exit hibern8 state also in addition to
684 * clocks being ON.
686 if (ufshcd_can_hibern8_during_gating(hba) &&
687 ufshcd_is_link_hibern8(hba)) {
688 spin_unlock_irqrestore(hba->host->host_lock, flags);
689 flush_work(&hba->clk_gating.ungate_work);
690 spin_lock_irqsave(hba->host->host_lock, flags);
691 goto start;
693 break;
694 case REQ_CLKS_OFF:
695 if (cancel_delayed_work(&hba->clk_gating.gate_work)) {
696 hba->clk_gating.state = CLKS_ON;
697 break;
700 * If we here, it means gating work is either done or
701 * currently running. Hence, fall through to cancel gating
702 * work and to enable clocks.
704 case CLKS_OFF:
705 scsi_block_requests(hba->host);
706 hba->clk_gating.state = REQ_CLKS_ON;
707 schedule_work(&hba->clk_gating.ungate_work);
709 * fall through to check if we should wait for this
710 * work to be done or not.
712 case REQ_CLKS_ON:
713 if (async) {
714 rc = -EAGAIN;
715 hba->clk_gating.active_reqs--;
716 break;
719 spin_unlock_irqrestore(hba->host->host_lock, flags);
720 flush_work(&hba->clk_gating.ungate_work);
721 /* Make sure state is CLKS_ON before returning */
722 spin_lock_irqsave(hba->host->host_lock, flags);
723 goto start;
724 default:
725 dev_err(hba->dev, "%s: clk gating is in invalid state %d\n",
726 __func__, hba->clk_gating.state);
727 break;
729 spin_unlock_irqrestore(hba->host->host_lock, flags);
730 out:
731 return rc;
733 EXPORT_SYMBOL_GPL(ufshcd_hold);
735 static void ufshcd_gate_work(struct work_struct *work)
737 struct ufs_hba *hba = container_of(work, struct ufs_hba,
738 clk_gating.gate_work.work);
739 unsigned long flags;
741 spin_lock_irqsave(hba->host->host_lock, flags);
743 * In case you are here to cancel this work the gating state
744 * would be marked as REQ_CLKS_ON. In this case save time by
745 * skipping the gating work and exit after changing the clock
746 * state to CLKS_ON.
748 if (hba->clk_gating.is_suspended ||
749 (hba->clk_gating.state == REQ_CLKS_ON)) {
750 hba->clk_gating.state = CLKS_ON;
751 goto rel_lock;
754 if (hba->clk_gating.active_reqs
755 || hba->ufshcd_state != UFSHCD_STATE_OPERATIONAL
756 || hba->lrb_in_use || hba->outstanding_tasks
757 || hba->active_uic_cmd || hba->uic_async_done)
758 goto rel_lock;
760 spin_unlock_irqrestore(hba->host->host_lock, flags);
762 /* put the link into hibern8 mode before turning off clocks */
763 if (ufshcd_can_hibern8_during_gating(hba)) {
764 if (ufshcd_uic_hibern8_enter(hba)) {
765 hba->clk_gating.state = CLKS_ON;
766 goto out;
768 ufshcd_set_link_hibern8(hba);
771 ufshcd_suspend_clkscaling(hba);
773 if (!ufshcd_is_link_active(hba))
774 ufshcd_setup_clocks(hba, false);
775 else
776 /* If link is active, device ref_clk can't be switched off */
777 __ufshcd_setup_clocks(hba, false, true);
780 * In case you are here to cancel this work the gating state
781 * would be marked as REQ_CLKS_ON. In this case keep the state
782 * as REQ_CLKS_ON which would anyway imply that clocks are off
783 * and a request to turn them on is pending. By doing this way,
784 * we keep the state machine in tact and this would ultimately
785 * prevent from doing cancel work multiple times when there are
786 * new requests arriving before the current cancel work is done.
788 spin_lock_irqsave(hba->host->host_lock, flags);
789 if (hba->clk_gating.state == REQ_CLKS_OFF)
790 hba->clk_gating.state = CLKS_OFF;
792 rel_lock:
793 spin_unlock_irqrestore(hba->host->host_lock, flags);
794 out:
795 return;
798 /* host lock must be held before calling this variant */
799 static void __ufshcd_release(struct ufs_hba *hba)
801 if (!ufshcd_is_clkgating_allowed(hba))
802 return;
804 hba->clk_gating.active_reqs--;
806 if (hba->clk_gating.active_reqs || hba->clk_gating.is_suspended
807 || hba->ufshcd_state != UFSHCD_STATE_OPERATIONAL
808 || hba->lrb_in_use || hba->outstanding_tasks
809 || hba->active_uic_cmd || hba->uic_async_done
810 || ufshcd_eh_in_progress(hba))
811 return;
813 hba->clk_gating.state = REQ_CLKS_OFF;
814 schedule_delayed_work(&hba->clk_gating.gate_work,
815 msecs_to_jiffies(hba->clk_gating.delay_ms));
818 void ufshcd_release(struct ufs_hba *hba)
820 unsigned long flags;
822 spin_lock_irqsave(hba->host->host_lock, flags);
823 __ufshcd_release(hba);
824 spin_unlock_irqrestore(hba->host->host_lock, flags);
826 EXPORT_SYMBOL_GPL(ufshcd_release);
828 static ssize_t ufshcd_clkgate_delay_show(struct device *dev,
829 struct device_attribute *attr, char *buf)
831 struct ufs_hba *hba = dev_get_drvdata(dev);
833 return snprintf(buf, PAGE_SIZE, "%lu\n", hba->clk_gating.delay_ms);
836 static ssize_t ufshcd_clkgate_delay_store(struct device *dev,
837 struct device_attribute *attr, const char *buf, size_t count)
839 struct ufs_hba *hba = dev_get_drvdata(dev);
840 unsigned long flags, value;
842 if (kstrtoul(buf, 0, &value))
843 return -EINVAL;
845 spin_lock_irqsave(hba->host->host_lock, flags);
846 hba->clk_gating.delay_ms = value;
847 spin_unlock_irqrestore(hba->host->host_lock, flags);
848 return count;
851 static void ufshcd_init_clk_gating(struct ufs_hba *hba)
853 if (!ufshcd_is_clkgating_allowed(hba))
854 return;
856 hba->clk_gating.delay_ms = 150;
857 INIT_DELAYED_WORK(&hba->clk_gating.gate_work, ufshcd_gate_work);
858 INIT_WORK(&hba->clk_gating.ungate_work, ufshcd_ungate_work);
860 hba->clk_gating.delay_attr.show = ufshcd_clkgate_delay_show;
861 hba->clk_gating.delay_attr.store = ufshcd_clkgate_delay_store;
862 sysfs_attr_init(&hba->clk_gating.delay_attr.attr);
863 hba->clk_gating.delay_attr.attr.name = "clkgate_delay_ms";
864 hba->clk_gating.delay_attr.attr.mode = S_IRUGO | S_IWUSR;
865 if (device_create_file(hba->dev, &hba->clk_gating.delay_attr))
866 dev_err(hba->dev, "Failed to create sysfs for clkgate_delay\n");
869 static void ufshcd_exit_clk_gating(struct ufs_hba *hba)
871 if (!ufshcd_is_clkgating_allowed(hba))
872 return;
873 device_remove_file(hba->dev, &hba->clk_gating.delay_attr);
874 cancel_work_sync(&hba->clk_gating.ungate_work);
875 cancel_delayed_work_sync(&hba->clk_gating.gate_work);
878 /* Must be called with host lock acquired */
879 static void ufshcd_clk_scaling_start_busy(struct ufs_hba *hba)
881 if (!ufshcd_is_clkscaling_enabled(hba))
882 return;
884 if (!hba->clk_scaling.is_busy_started) {
885 hba->clk_scaling.busy_start_t = ktime_get();
886 hba->clk_scaling.is_busy_started = true;
890 static void ufshcd_clk_scaling_update_busy(struct ufs_hba *hba)
892 struct ufs_clk_scaling *scaling = &hba->clk_scaling;
894 if (!ufshcd_is_clkscaling_enabled(hba))
895 return;
897 if (!hba->outstanding_reqs && scaling->is_busy_started) {
898 scaling->tot_busy_t += ktime_to_us(ktime_sub(ktime_get(),
899 scaling->busy_start_t));
900 scaling->busy_start_t = ktime_set(0, 0);
901 scaling->is_busy_started = false;
905 * ufshcd_send_command - Send SCSI or device management commands
906 * @hba: per adapter instance
907 * @task_tag: Task tag of the command
909 static inline
910 void ufshcd_send_command(struct ufs_hba *hba, unsigned int task_tag)
912 ufshcd_clk_scaling_start_busy(hba);
913 __set_bit(task_tag, &hba->outstanding_reqs);
914 ufshcd_writel(hba, 1 << task_tag, REG_UTP_TRANSFER_REQ_DOOR_BELL);
915 /* Make sure that doorbell is committed immediately */
916 wmb();
920 * ufshcd_copy_sense_data - Copy sense data in case of check condition
921 * @lrb - pointer to local reference block
923 static inline void ufshcd_copy_sense_data(struct ufshcd_lrb *lrbp)
925 int len;
926 if (lrbp->sense_buffer &&
927 ufshcd_get_rsp_upiu_data_seg_len(lrbp->ucd_rsp_ptr)) {
928 int len_to_copy;
930 len = be16_to_cpu(lrbp->ucd_rsp_ptr->sr.sense_data_len);
931 len_to_copy = min_t(int, RESPONSE_UPIU_SENSE_DATA_LENGTH, len);
933 memcpy(lrbp->sense_buffer,
934 lrbp->ucd_rsp_ptr->sr.sense_data,
935 min_t(int, len_to_copy, UFSHCD_REQ_SENSE_SIZE));
940 * ufshcd_copy_query_response() - Copy the Query Response and the data
941 * descriptor
942 * @hba: per adapter instance
943 * @lrb - pointer to local reference block
945 static
946 int ufshcd_copy_query_response(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
948 struct ufs_query_res *query_res = &hba->dev_cmd.query.response;
950 memcpy(&query_res->upiu_res, &lrbp->ucd_rsp_ptr->qr, QUERY_OSF_SIZE);
952 /* Get the descriptor */
953 if (lrbp->ucd_rsp_ptr->qr.opcode == UPIU_QUERY_OPCODE_READ_DESC) {
954 u8 *descp = (u8 *)lrbp->ucd_rsp_ptr +
955 GENERAL_UPIU_REQUEST_SIZE;
956 u16 resp_len;
957 u16 buf_len;
959 /* data segment length */
960 resp_len = be32_to_cpu(lrbp->ucd_rsp_ptr->header.dword_2) &
961 MASK_QUERY_DATA_SEG_LEN;
962 buf_len = be16_to_cpu(
963 hba->dev_cmd.query.request.upiu_req.length);
964 if (likely(buf_len >= resp_len)) {
965 memcpy(hba->dev_cmd.query.descriptor, descp, resp_len);
966 } else {
967 dev_warn(hba->dev,
968 "%s: Response size is bigger than buffer",
969 __func__);
970 return -EINVAL;
974 return 0;
978 * ufshcd_hba_capabilities - Read controller capabilities
979 * @hba: per adapter instance
981 static inline void ufshcd_hba_capabilities(struct ufs_hba *hba)
983 hba->capabilities = ufshcd_readl(hba, REG_CONTROLLER_CAPABILITIES);
985 /* nutrs and nutmrs are 0 based values */
986 hba->nutrs = (hba->capabilities & MASK_TRANSFER_REQUESTS_SLOTS) + 1;
987 hba->nutmrs =
988 ((hba->capabilities & MASK_TASK_MANAGEMENT_REQUEST_SLOTS) >> 16) + 1;
992 * ufshcd_ready_for_uic_cmd - Check if controller is ready
993 * to accept UIC commands
994 * @hba: per adapter instance
995 * Return true on success, else false
997 static inline bool ufshcd_ready_for_uic_cmd(struct ufs_hba *hba)
999 if (ufshcd_readl(hba, REG_CONTROLLER_STATUS) & UIC_COMMAND_READY)
1000 return true;
1001 else
1002 return false;
1006 * ufshcd_get_upmcrs - Get the power mode change request status
1007 * @hba: Pointer to adapter instance
1009 * This function gets the UPMCRS field of HCS register
1010 * Returns value of UPMCRS field
1012 static inline u8 ufshcd_get_upmcrs(struct ufs_hba *hba)
1014 return (ufshcd_readl(hba, REG_CONTROLLER_STATUS) >> 8) & 0x7;
1018 * ufshcd_dispatch_uic_cmd - Dispatch UIC commands to unipro layers
1019 * @hba: per adapter instance
1020 * @uic_cmd: UIC command
1022 * Mutex must be held.
1024 static inline void
1025 ufshcd_dispatch_uic_cmd(struct ufs_hba *hba, struct uic_command *uic_cmd)
1027 WARN_ON(hba->active_uic_cmd);
1029 hba->active_uic_cmd = uic_cmd;
1031 /* Write Args */
1032 ufshcd_writel(hba, uic_cmd->argument1, REG_UIC_COMMAND_ARG_1);
1033 ufshcd_writel(hba, uic_cmd->argument2, REG_UIC_COMMAND_ARG_2);
1034 ufshcd_writel(hba, uic_cmd->argument3, REG_UIC_COMMAND_ARG_3);
1036 /* Write UIC Cmd */
1037 ufshcd_writel(hba, uic_cmd->command & COMMAND_OPCODE_MASK,
1038 REG_UIC_COMMAND);
1042 * ufshcd_wait_for_uic_cmd - Wait complectioin of UIC command
1043 * @hba: per adapter instance
1044 * @uic_command: UIC command
1046 * Must be called with mutex held.
1047 * Returns 0 only if success.
1049 static int
1050 ufshcd_wait_for_uic_cmd(struct ufs_hba *hba, struct uic_command *uic_cmd)
1052 int ret;
1053 unsigned long flags;
1055 if (wait_for_completion_timeout(&uic_cmd->done,
1056 msecs_to_jiffies(UIC_CMD_TIMEOUT)))
1057 ret = uic_cmd->argument2 & MASK_UIC_COMMAND_RESULT;
1058 else
1059 ret = -ETIMEDOUT;
1061 spin_lock_irqsave(hba->host->host_lock, flags);
1062 hba->active_uic_cmd = NULL;
1063 spin_unlock_irqrestore(hba->host->host_lock, flags);
1065 return ret;
1069 * __ufshcd_send_uic_cmd - Send UIC commands and retrieve the result
1070 * @hba: per adapter instance
1071 * @uic_cmd: UIC command
1072 * @completion: initialize the completion only if this is set to true
1074 * Identical to ufshcd_send_uic_cmd() expect mutex. Must be called
1075 * with mutex held and host_lock locked.
1076 * Returns 0 only if success.
1078 static int
1079 __ufshcd_send_uic_cmd(struct ufs_hba *hba, struct uic_command *uic_cmd,
1080 bool completion)
1082 if (!ufshcd_ready_for_uic_cmd(hba)) {
1083 dev_err(hba->dev,
1084 "Controller not ready to accept UIC commands\n");
1085 return -EIO;
1088 if (completion)
1089 init_completion(&uic_cmd->done);
1091 ufshcd_dispatch_uic_cmd(hba, uic_cmd);
1093 return 0;
1097 * ufshcd_send_uic_cmd - Send UIC commands and retrieve the result
1098 * @hba: per adapter instance
1099 * @uic_cmd: UIC command
1101 * Returns 0 only if success.
1103 static int
1104 ufshcd_send_uic_cmd(struct ufs_hba *hba, struct uic_command *uic_cmd)
1106 int ret;
1107 unsigned long flags;
1109 ufshcd_hold(hba, false);
1110 mutex_lock(&hba->uic_cmd_mutex);
1111 ufshcd_add_delay_before_dme_cmd(hba);
1113 spin_lock_irqsave(hba->host->host_lock, flags);
1114 ret = __ufshcd_send_uic_cmd(hba, uic_cmd, true);
1115 spin_unlock_irqrestore(hba->host->host_lock, flags);
1116 if (!ret)
1117 ret = ufshcd_wait_for_uic_cmd(hba, uic_cmd);
1119 mutex_unlock(&hba->uic_cmd_mutex);
1121 ufshcd_release(hba);
1122 return ret;
1126 * ufshcd_map_sg - Map scatter-gather list to prdt
1127 * @lrbp - pointer to local reference block
1129 * Returns 0 in case of success, non-zero value in case of failure
1131 static int ufshcd_map_sg(struct ufshcd_lrb *lrbp)
1133 struct ufshcd_sg_entry *prd_table;
1134 struct scatterlist *sg;
1135 struct scsi_cmnd *cmd;
1136 int sg_segments;
1137 int i;
1139 cmd = lrbp->cmd;
1140 sg_segments = scsi_dma_map(cmd);
1141 if (sg_segments < 0)
1142 return sg_segments;
1144 if (sg_segments) {
1145 lrbp->utr_descriptor_ptr->prd_table_length =
1146 cpu_to_le16((u16) (sg_segments));
1148 prd_table = (struct ufshcd_sg_entry *)lrbp->ucd_prdt_ptr;
1150 scsi_for_each_sg(cmd, sg, sg_segments, i) {
1151 prd_table[i].size =
1152 cpu_to_le32(((u32) sg_dma_len(sg))-1);
1153 prd_table[i].base_addr =
1154 cpu_to_le32(lower_32_bits(sg->dma_address));
1155 prd_table[i].upper_addr =
1156 cpu_to_le32(upper_32_bits(sg->dma_address));
1157 prd_table[i].reserved = 0;
1159 } else {
1160 lrbp->utr_descriptor_ptr->prd_table_length = 0;
1163 return 0;
1167 * ufshcd_enable_intr - enable interrupts
1168 * @hba: per adapter instance
1169 * @intrs: interrupt bits
1171 static void ufshcd_enable_intr(struct ufs_hba *hba, u32 intrs)
1173 u32 set = ufshcd_readl(hba, REG_INTERRUPT_ENABLE);
1175 if (hba->ufs_version == UFSHCI_VERSION_10) {
1176 u32 rw;
1177 rw = set & INTERRUPT_MASK_RW_VER_10;
1178 set = rw | ((set ^ intrs) & intrs);
1179 } else {
1180 set |= intrs;
1183 ufshcd_writel(hba, set, REG_INTERRUPT_ENABLE);
1187 * ufshcd_disable_intr - disable interrupts
1188 * @hba: per adapter instance
1189 * @intrs: interrupt bits
1191 static void ufshcd_disable_intr(struct ufs_hba *hba, u32 intrs)
1193 u32 set = ufshcd_readl(hba, REG_INTERRUPT_ENABLE);
1195 if (hba->ufs_version == UFSHCI_VERSION_10) {
1196 u32 rw;
1197 rw = (set & INTERRUPT_MASK_RW_VER_10) &
1198 ~(intrs & INTERRUPT_MASK_RW_VER_10);
1199 set = rw | ((set & intrs) & ~INTERRUPT_MASK_RW_VER_10);
1201 } else {
1202 set &= ~intrs;
1205 ufshcd_writel(hba, set, REG_INTERRUPT_ENABLE);
1209 * ufshcd_prepare_req_desc_hdr() - Fills the requests header
1210 * descriptor according to request
1211 * @lrbp: pointer to local reference block
1212 * @upiu_flags: flags required in the header
1213 * @cmd_dir: requests data direction
1215 static void ufshcd_prepare_req_desc_hdr(struct ufshcd_lrb *lrbp,
1216 u32 *upiu_flags, enum dma_data_direction cmd_dir)
1218 struct utp_transfer_req_desc *req_desc = lrbp->utr_descriptor_ptr;
1219 u32 data_direction;
1220 u32 dword_0;
1222 if (cmd_dir == DMA_FROM_DEVICE) {
1223 data_direction = UTP_DEVICE_TO_HOST;
1224 *upiu_flags = UPIU_CMD_FLAGS_READ;
1225 } else if (cmd_dir == DMA_TO_DEVICE) {
1226 data_direction = UTP_HOST_TO_DEVICE;
1227 *upiu_flags = UPIU_CMD_FLAGS_WRITE;
1228 } else {
1229 data_direction = UTP_NO_DATA_TRANSFER;
1230 *upiu_flags = UPIU_CMD_FLAGS_NONE;
1233 dword_0 = data_direction | (lrbp->command_type
1234 << UPIU_COMMAND_TYPE_OFFSET);
1235 if (lrbp->intr_cmd)
1236 dword_0 |= UTP_REQ_DESC_INT_CMD;
1238 /* Transfer request descriptor header fields */
1239 req_desc->header.dword_0 = cpu_to_le32(dword_0);
1240 /* dword_1 is reserved, hence it is set to 0 */
1241 req_desc->header.dword_1 = 0;
1243 * assigning invalid value for command status. Controller
1244 * updates OCS on command completion, with the command
1245 * status
1247 req_desc->header.dword_2 =
1248 cpu_to_le32(OCS_INVALID_COMMAND_STATUS);
1249 /* dword_3 is reserved, hence it is set to 0 */
1250 req_desc->header.dword_3 = 0;
1252 req_desc->prd_table_length = 0;
1256 * ufshcd_prepare_utp_scsi_cmd_upiu() - fills the utp_transfer_req_desc,
1257 * for scsi commands
1258 * @lrbp - local reference block pointer
1259 * @upiu_flags - flags
1261 static
1262 void ufshcd_prepare_utp_scsi_cmd_upiu(struct ufshcd_lrb *lrbp, u32 upiu_flags)
1264 struct utp_upiu_req *ucd_req_ptr = lrbp->ucd_req_ptr;
1265 unsigned short cdb_len;
1267 /* command descriptor fields */
1268 ucd_req_ptr->header.dword_0 = UPIU_HEADER_DWORD(
1269 UPIU_TRANSACTION_COMMAND, upiu_flags,
1270 lrbp->lun, lrbp->task_tag);
1271 ucd_req_ptr->header.dword_1 = UPIU_HEADER_DWORD(
1272 UPIU_COMMAND_SET_TYPE_SCSI, 0, 0, 0);
1274 /* Total EHS length and Data segment length will be zero */
1275 ucd_req_ptr->header.dword_2 = 0;
1277 ucd_req_ptr->sc.exp_data_transfer_len =
1278 cpu_to_be32(lrbp->cmd->sdb.length);
1280 cdb_len = min_t(unsigned short, lrbp->cmd->cmd_len, MAX_CDB_SIZE);
1281 memset(ucd_req_ptr->sc.cdb, 0, MAX_CDB_SIZE);
1282 memcpy(ucd_req_ptr->sc.cdb, lrbp->cmd->cmnd, cdb_len);
1284 memset(lrbp->ucd_rsp_ptr, 0, sizeof(struct utp_upiu_rsp));
1288 * ufshcd_prepare_utp_query_req_upiu() - fills the utp_transfer_req_desc,
1289 * for query requsts
1290 * @hba: UFS hba
1291 * @lrbp: local reference block pointer
1292 * @upiu_flags: flags
1294 static void ufshcd_prepare_utp_query_req_upiu(struct ufs_hba *hba,
1295 struct ufshcd_lrb *lrbp, u32 upiu_flags)
1297 struct utp_upiu_req *ucd_req_ptr = lrbp->ucd_req_ptr;
1298 struct ufs_query *query = &hba->dev_cmd.query;
1299 u16 len = be16_to_cpu(query->request.upiu_req.length);
1300 u8 *descp = (u8 *)lrbp->ucd_req_ptr + GENERAL_UPIU_REQUEST_SIZE;
1302 /* Query request header */
1303 ucd_req_ptr->header.dword_0 = UPIU_HEADER_DWORD(
1304 UPIU_TRANSACTION_QUERY_REQ, upiu_flags,
1305 lrbp->lun, lrbp->task_tag);
1306 ucd_req_ptr->header.dword_1 = UPIU_HEADER_DWORD(
1307 0, query->request.query_func, 0, 0);
1309 /* Data segment length only need for WRITE_DESC */
1310 if (query->request.upiu_req.opcode == UPIU_QUERY_OPCODE_WRITE_DESC)
1311 ucd_req_ptr->header.dword_2 =
1312 UPIU_HEADER_DWORD(0, 0, (len >> 8), (u8)len);
1313 else
1314 ucd_req_ptr->header.dword_2 = 0;
1316 /* Copy the Query Request buffer as is */
1317 memcpy(&ucd_req_ptr->qr, &query->request.upiu_req,
1318 QUERY_OSF_SIZE);
1320 /* Copy the Descriptor */
1321 if (query->request.upiu_req.opcode == UPIU_QUERY_OPCODE_WRITE_DESC)
1322 memcpy(descp, query->descriptor, len);
1324 memset(lrbp->ucd_rsp_ptr, 0, sizeof(struct utp_upiu_rsp));
1327 static inline void ufshcd_prepare_utp_nop_upiu(struct ufshcd_lrb *lrbp)
1329 struct utp_upiu_req *ucd_req_ptr = lrbp->ucd_req_ptr;
1331 memset(ucd_req_ptr, 0, sizeof(struct utp_upiu_req));
1333 /* command descriptor fields */
1334 ucd_req_ptr->header.dword_0 =
1335 UPIU_HEADER_DWORD(
1336 UPIU_TRANSACTION_NOP_OUT, 0, 0, lrbp->task_tag);
1337 /* clear rest of the fields of basic header */
1338 ucd_req_ptr->header.dword_1 = 0;
1339 ucd_req_ptr->header.dword_2 = 0;
1341 memset(lrbp->ucd_rsp_ptr, 0, sizeof(struct utp_upiu_rsp));
1345 * ufshcd_comp_devman_upiu - UFS Protocol Information Unit(UPIU)
1346 * for Device Management Purposes
1347 * @hba - per adapter instance
1348 * @lrb - pointer to local reference block
1350 static int ufshcd_comp_devman_upiu(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
1352 u32 upiu_flags;
1353 int ret = 0;
1355 if (hba->ufs_version == UFSHCI_VERSION_20)
1356 lrbp->command_type = UTP_CMD_TYPE_UFS_STORAGE;
1357 else
1358 lrbp->command_type = UTP_CMD_TYPE_DEV_MANAGE;
1360 ufshcd_prepare_req_desc_hdr(lrbp, &upiu_flags, DMA_NONE);
1361 if (hba->dev_cmd.type == DEV_CMD_TYPE_QUERY)
1362 ufshcd_prepare_utp_query_req_upiu(hba, lrbp, upiu_flags);
1363 else if (hba->dev_cmd.type == DEV_CMD_TYPE_NOP)
1364 ufshcd_prepare_utp_nop_upiu(lrbp);
1365 else
1366 ret = -EINVAL;
1368 return ret;
1372 * ufshcd_comp_scsi_upiu - UFS Protocol Information Unit(UPIU)
1373 * for SCSI Purposes
1374 * @hba - per adapter instance
1375 * @lrb - pointer to local reference block
1377 static int ufshcd_comp_scsi_upiu(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
1379 u32 upiu_flags;
1380 int ret = 0;
1382 if (hba->ufs_version == UFSHCI_VERSION_20)
1383 lrbp->command_type = UTP_CMD_TYPE_UFS_STORAGE;
1384 else
1385 lrbp->command_type = UTP_CMD_TYPE_SCSI;
1387 if (likely(lrbp->cmd)) {
1388 ufshcd_prepare_req_desc_hdr(lrbp, &upiu_flags,
1389 lrbp->cmd->sc_data_direction);
1390 ufshcd_prepare_utp_scsi_cmd_upiu(lrbp, upiu_flags);
1391 } else {
1392 ret = -EINVAL;
1395 return ret;
1399 * ufshcd_scsi_to_upiu_lun - maps scsi LUN to UPIU LUN
1400 * @scsi_lun: scsi LUN id
1402 * Returns UPIU LUN id
1404 static inline u8 ufshcd_scsi_to_upiu_lun(unsigned int scsi_lun)
1406 if (scsi_is_wlun(scsi_lun))
1407 return (scsi_lun & UFS_UPIU_MAX_UNIT_NUM_ID)
1408 | UFS_UPIU_WLUN_ID;
1409 else
1410 return scsi_lun & UFS_UPIU_MAX_UNIT_NUM_ID;
1414 * ufshcd_upiu_wlun_to_scsi_wlun - maps UPIU W-LUN id to SCSI W-LUN ID
1415 * @scsi_lun: UPIU W-LUN id
1417 * Returns SCSI W-LUN id
1419 static inline u16 ufshcd_upiu_wlun_to_scsi_wlun(u8 upiu_wlun_id)
1421 return (upiu_wlun_id & ~UFS_UPIU_WLUN_ID) | SCSI_W_LUN_BASE;
1425 * ufshcd_queuecommand - main entry point for SCSI requests
1426 * @cmd: command from SCSI Midlayer
1427 * @done: call back function
1429 * Returns 0 for success, non-zero in case of failure
1431 static int ufshcd_queuecommand(struct Scsi_Host *host, struct scsi_cmnd *cmd)
1433 struct ufshcd_lrb *lrbp;
1434 struct ufs_hba *hba;
1435 unsigned long flags;
1436 int tag;
1437 int err = 0;
1439 hba = shost_priv(host);
1441 tag = cmd->request->tag;
1442 if (!ufshcd_valid_tag(hba, tag)) {
1443 dev_err(hba->dev,
1444 "%s: invalid command tag %d: cmd=0x%p, cmd->request=0x%p",
1445 __func__, tag, cmd, cmd->request);
1446 BUG();
1449 spin_lock_irqsave(hba->host->host_lock, flags);
1450 switch (hba->ufshcd_state) {
1451 case UFSHCD_STATE_OPERATIONAL:
1452 break;
1453 case UFSHCD_STATE_RESET:
1454 err = SCSI_MLQUEUE_HOST_BUSY;
1455 goto out_unlock;
1456 case UFSHCD_STATE_ERROR:
1457 set_host_byte(cmd, DID_ERROR);
1458 cmd->scsi_done(cmd);
1459 goto out_unlock;
1460 default:
1461 dev_WARN_ONCE(hba->dev, 1, "%s: invalid state %d\n",
1462 __func__, hba->ufshcd_state);
1463 set_host_byte(cmd, DID_BAD_TARGET);
1464 cmd->scsi_done(cmd);
1465 goto out_unlock;
1468 /* if error handling is in progress, don't issue commands */
1469 if (ufshcd_eh_in_progress(hba)) {
1470 set_host_byte(cmd, DID_ERROR);
1471 cmd->scsi_done(cmd);
1472 goto out_unlock;
1474 spin_unlock_irqrestore(hba->host->host_lock, flags);
1476 /* acquire the tag to make sure device cmds don't use it */
1477 if (test_and_set_bit_lock(tag, &hba->lrb_in_use)) {
1479 * Dev manage command in progress, requeue the command.
1480 * Requeuing the command helps in cases where the request *may*
1481 * find different tag instead of waiting for dev manage command
1482 * completion.
1484 err = SCSI_MLQUEUE_HOST_BUSY;
1485 goto out;
1488 err = ufshcd_hold(hba, true);
1489 if (err) {
1490 err = SCSI_MLQUEUE_HOST_BUSY;
1491 clear_bit_unlock(tag, &hba->lrb_in_use);
1492 goto out;
1494 WARN_ON(hba->clk_gating.state != CLKS_ON);
1496 lrbp = &hba->lrb[tag];
1498 WARN_ON(lrbp->cmd);
1499 lrbp->cmd = cmd;
1500 lrbp->sense_bufflen = UFSHCD_REQ_SENSE_SIZE;
1501 lrbp->sense_buffer = cmd->sense_buffer;
1502 lrbp->task_tag = tag;
1503 lrbp->lun = ufshcd_scsi_to_upiu_lun(cmd->device->lun);
1504 lrbp->intr_cmd = !ufshcd_is_intr_aggr_allowed(hba) ? true : false;
1506 ufshcd_comp_scsi_upiu(hba, lrbp);
1508 err = ufshcd_map_sg(lrbp);
1509 if (err) {
1510 lrbp->cmd = NULL;
1511 clear_bit_unlock(tag, &hba->lrb_in_use);
1512 goto out;
1514 /* Make sure descriptors are ready before ringing the doorbell */
1515 wmb();
1517 /* issue command to the controller */
1518 spin_lock_irqsave(hba->host->host_lock, flags);
1519 ufshcd_send_command(hba, tag);
1520 out_unlock:
1521 spin_unlock_irqrestore(hba->host->host_lock, flags);
1522 out:
1523 return err;
1526 static int ufshcd_compose_dev_cmd(struct ufs_hba *hba,
1527 struct ufshcd_lrb *lrbp, enum dev_cmd_type cmd_type, int tag)
1529 lrbp->cmd = NULL;
1530 lrbp->sense_bufflen = 0;
1531 lrbp->sense_buffer = NULL;
1532 lrbp->task_tag = tag;
1533 lrbp->lun = 0; /* device management cmd is not specific to any LUN */
1534 lrbp->intr_cmd = true; /* No interrupt aggregation */
1535 hba->dev_cmd.type = cmd_type;
1537 return ufshcd_comp_devman_upiu(hba, lrbp);
1540 static int
1541 ufshcd_clear_cmd(struct ufs_hba *hba, int tag)
1543 int err = 0;
1544 unsigned long flags;
1545 u32 mask = 1 << tag;
1547 /* clear outstanding transaction before retry */
1548 spin_lock_irqsave(hba->host->host_lock, flags);
1549 ufshcd_utrl_clear(hba, tag);
1550 spin_unlock_irqrestore(hba->host->host_lock, flags);
1553 * wait for for h/w to clear corresponding bit in door-bell.
1554 * max. wait is 1 sec.
1556 err = ufshcd_wait_for_register(hba,
1557 REG_UTP_TRANSFER_REQ_DOOR_BELL,
1558 mask, ~mask, 1000, 1000, true);
1560 return err;
1563 static int
1564 ufshcd_check_query_response(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
1566 struct ufs_query_res *query_res = &hba->dev_cmd.query.response;
1568 /* Get the UPIU response */
1569 query_res->response = ufshcd_get_rsp_upiu_result(lrbp->ucd_rsp_ptr) >>
1570 UPIU_RSP_CODE_OFFSET;
1571 return query_res->response;
1575 * ufshcd_dev_cmd_completion() - handles device management command responses
1576 * @hba: per adapter instance
1577 * @lrbp: pointer to local reference block
1579 static int
1580 ufshcd_dev_cmd_completion(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
1582 int resp;
1583 int err = 0;
1585 resp = ufshcd_get_req_rsp(lrbp->ucd_rsp_ptr);
1587 switch (resp) {
1588 case UPIU_TRANSACTION_NOP_IN:
1589 if (hba->dev_cmd.type != DEV_CMD_TYPE_NOP) {
1590 err = -EINVAL;
1591 dev_err(hba->dev, "%s: unexpected response %x\n",
1592 __func__, resp);
1594 break;
1595 case UPIU_TRANSACTION_QUERY_RSP:
1596 err = ufshcd_check_query_response(hba, lrbp);
1597 if (!err)
1598 err = ufshcd_copy_query_response(hba, lrbp);
1599 break;
1600 case UPIU_TRANSACTION_REJECT_UPIU:
1601 /* TODO: handle Reject UPIU Response */
1602 err = -EPERM;
1603 dev_err(hba->dev, "%s: Reject UPIU not fully implemented\n",
1604 __func__);
1605 break;
1606 default:
1607 err = -EINVAL;
1608 dev_err(hba->dev, "%s: Invalid device management cmd response: %x\n",
1609 __func__, resp);
1610 break;
1613 return err;
1616 static int ufshcd_wait_for_dev_cmd(struct ufs_hba *hba,
1617 struct ufshcd_lrb *lrbp, int max_timeout)
1619 int err = 0;
1620 unsigned long time_left;
1621 unsigned long flags;
1623 time_left = wait_for_completion_timeout(hba->dev_cmd.complete,
1624 msecs_to_jiffies(max_timeout));
1626 /* Make sure descriptors are ready before ringing the doorbell */
1627 wmb();
1628 spin_lock_irqsave(hba->host->host_lock, flags);
1629 hba->dev_cmd.complete = NULL;
1630 if (likely(time_left)) {
1631 err = ufshcd_get_tr_ocs(lrbp);
1632 if (!err)
1633 err = ufshcd_dev_cmd_completion(hba, lrbp);
1635 spin_unlock_irqrestore(hba->host->host_lock, flags);
1637 if (!time_left) {
1638 err = -ETIMEDOUT;
1639 dev_dbg(hba->dev, "%s: dev_cmd request timedout, tag %d\n",
1640 __func__, lrbp->task_tag);
1641 if (!ufshcd_clear_cmd(hba, lrbp->task_tag))
1642 /* successfully cleared the command, retry if needed */
1643 err = -EAGAIN;
1645 * in case of an error, after clearing the doorbell,
1646 * we also need to clear the outstanding_request
1647 * field in hba
1649 ufshcd_outstanding_req_clear(hba, lrbp->task_tag);
1652 return err;
1656 * ufshcd_get_dev_cmd_tag - Get device management command tag
1657 * @hba: per-adapter instance
1658 * @tag: pointer to variable with available slot value
1660 * Get a free slot and lock it until device management command
1661 * completes.
1663 * Returns false if free slot is unavailable for locking, else
1664 * return true with tag value in @tag.
1666 static bool ufshcd_get_dev_cmd_tag(struct ufs_hba *hba, int *tag_out)
1668 int tag;
1669 bool ret = false;
1670 unsigned long tmp;
1672 if (!tag_out)
1673 goto out;
1675 do {
1676 tmp = ~hba->lrb_in_use;
1677 tag = find_last_bit(&tmp, hba->nutrs);
1678 if (tag >= hba->nutrs)
1679 goto out;
1680 } while (test_and_set_bit_lock(tag, &hba->lrb_in_use));
1682 *tag_out = tag;
1683 ret = true;
1684 out:
1685 return ret;
1688 static inline void ufshcd_put_dev_cmd_tag(struct ufs_hba *hba, int tag)
1690 clear_bit_unlock(tag, &hba->lrb_in_use);
1694 * ufshcd_exec_dev_cmd - API for sending device management requests
1695 * @hba - UFS hba
1696 * @cmd_type - specifies the type (NOP, Query...)
1697 * @timeout - time in seconds
1699 * NOTE: Since there is only one available tag for device management commands,
1700 * it is expected you hold the hba->dev_cmd.lock mutex.
1702 static int ufshcd_exec_dev_cmd(struct ufs_hba *hba,
1703 enum dev_cmd_type cmd_type, int timeout)
1705 struct ufshcd_lrb *lrbp;
1706 int err;
1707 int tag;
1708 struct completion wait;
1709 unsigned long flags;
1712 * Get free slot, sleep if slots are unavailable.
1713 * Even though we use wait_event() which sleeps indefinitely,
1714 * the maximum wait time is bounded by SCSI request timeout.
1716 wait_event(hba->dev_cmd.tag_wq, ufshcd_get_dev_cmd_tag(hba, &tag));
1718 init_completion(&wait);
1719 lrbp = &hba->lrb[tag];
1720 WARN_ON(lrbp->cmd);
1721 err = ufshcd_compose_dev_cmd(hba, lrbp, cmd_type, tag);
1722 if (unlikely(err))
1723 goto out_put_tag;
1725 hba->dev_cmd.complete = &wait;
1727 /* Make sure descriptors are ready before ringing the doorbell */
1728 wmb();
1729 spin_lock_irqsave(hba->host->host_lock, flags);
1730 ufshcd_send_command(hba, tag);
1731 spin_unlock_irqrestore(hba->host->host_lock, flags);
1733 err = ufshcd_wait_for_dev_cmd(hba, lrbp, timeout);
1735 out_put_tag:
1736 ufshcd_put_dev_cmd_tag(hba, tag);
1737 wake_up(&hba->dev_cmd.tag_wq);
1738 return err;
1742 * ufshcd_init_query() - init the query response and request parameters
1743 * @hba: per-adapter instance
1744 * @request: address of the request pointer to be initialized
1745 * @response: address of the response pointer to be initialized
1746 * @opcode: operation to perform
1747 * @idn: flag idn to access
1748 * @index: LU number to access
1749 * @selector: query/flag/descriptor further identification
1751 static inline void ufshcd_init_query(struct ufs_hba *hba,
1752 struct ufs_query_req **request, struct ufs_query_res **response,
1753 enum query_opcode opcode, u8 idn, u8 index, u8 selector)
1755 *request = &hba->dev_cmd.query.request;
1756 *response = &hba->dev_cmd.query.response;
1757 memset(*request, 0, sizeof(struct ufs_query_req));
1758 memset(*response, 0, sizeof(struct ufs_query_res));
1759 (*request)->upiu_req.opcode = opcode;
1760 (*request)->upiu_req.idn = idn;
1761 (*request)->upiu_req.index = index;
1762 (*request)->upiu_req.selector = selector;
1765 static int ufshcd_query_flag_retry(struct ufs_hba *hba,
1766 enum query_opcode opcode, enum flag_idn idn, bool *flag_res)
1768 int ret;
1769 int retries;
1771 for (retries = 0; retries < QUERY_REQ_RETRIES; retries++) {
1772 ret = ufshcd_query_flag(hba, opcode, idn, flag_res);
1773 if (ret)
1774 dev_dbg(hba->dev,
1775 "%s: failed with error %d, retries %d\n",
1776 __func__, ret, retries);
1777 else
1778 break;
1781 if (ret)
1782 dev_err(hba->dev,
1783 "%s: query attribute, opcode %d, idn %d, failed with error %d after %d retires\n",
1784 __func__, opcode, idn, ret, retries);
1785 return ret;
1789 * ufshcd_query_flag() - API function for sending flag query requests
1790 * hba: per-adapter instance
1791 * query_opcode: flag query to perform
1792 * idn: flag idn to access
1793 * flag_res: the flag value after the query request completes
1795 * Returns 0 for success, non-zero in case of failure
1797 int ufshcd_query_flag(struct ufs_hba *hba, enum query_opcode opcode,
1798 enum flag_idn idn, bool *flag_res)
1800 struct ufs_query_req *request = NULL;
1801 struct ufs_query_res *response = NULL;
1802 int err, index = 0, selector = 0;
1803 int timeout = QUERY_REQ_TIMEOUT;
1805 BUG_ON(!hba);
1807 ufshcd_hold(hba, false);
1808 mutex_lock(&hba->dev_cmd.lock);
1809 ufshcd_init_query(hba, &request, &response, opcode, idn, index,
1810 selector);
1812 switch (opcode) {
1813 case UPIU_QUERY_OPCODE_SET_FLAG:
1814 case UPIU_QUERY_OPCODE_CLEAR_FLAG:
1815 case UPIU_QUERY_OPCODE_TOGGLE_FLAG:
1816 request->query_func = UPIU_QUERY_FUNC_STANDARD_WRITE_REQUEST;
1817 break;
1818 case UPIU_QUERY_OPCODE_READ_FLAG:
1819 request->query_func = UPIU_QUERY_FUNC_STANDARD_READ_REQUEST;
1820 if (!flag_res) {
1821 /* No dummy reads */
1822 dev_err(hba->dev, "%s: Invalid argument for read request\n",
1823 __func__);
1824 err = -EINVAL;
1825 goto out_unlock;
1827 break;
1828 default:
1829 dev_err(hba->dev,
1830 "%s: Expected query flag opcode but got = %d\n",
1831 __func__, opcode);
1832 err = -EINVAL;
1833 goto out_unlock;
1836 if (idn == QUERY_FLAG_IDN_FDEVICEINIT)
1837 timeout = QUERY_FDEVICEINIT_REQ_TIMEOUT;
1839 err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_QUERY, timeout);
1841 if (err) {
1842 dev_err(hba->dev,
1843 "%s: Sending flag query for idn %d failed, err = %d\n",
1844 __func__, idn, err);
1845 goto out_unlock;
1848 if (flag_res)
1849 *flag_res = (be32_to_cpu(response->upiu_res.value) &
1850 MASK_QUERY_UPIU_FLAG_LOC) & 0x1;
1852 out_unlock:
1853 mutex_unlock(&hba->dev_cmd.lock);
1854 ufshcd_release(hba);
1855 return err;
1859 * ufshcd_query_attr - API function for sending attribute requests
1860 * hba: per-adapter instance
1861 * opcode: attribute opcode
1862 * idn: attribute idn to access
1863 * index: index field
1864 * selector: selector field
1865 * attr_val: the attribute value after the query request completes
1867 * Returns 0 for success, non-zero in case of failure
1869 static int ufshcd_query_attr(struct ufs_hba *hba, enum query_opcode opcode,
1870 enum attr_idn idn, u8 index, u8 selector, u32 *attr_val)
1872 struct ufs_query_req *request = NULL;
1873 struct ufs_query_res *response = NULL;
1874 int err;
1876 BUG_ON(!hba);
1878 ufshcd_hold(hba, false);
1879 if (!attr_val) {
1880 dev_err(hba->dev, "%s: attribute value required for opcode 0x%x\n",
1881 __func__, opcode);
1882 err = -EINVAL;
1883 goto out;
1886 mutex_lock(&hba->dev_cmd.lock);
1887 ufshcd_init_query(hba, &request, &response, opcode, idn, index,
1888 selector);
1890 switch (opcode) {
1891 case UPIU_QUERY_OPCODE_WRITE_ATTR:
1892 request->query_func = UPIU_QUERY_FUNC_STANDARD_WRITE_REQUEST;
1893 request->upiu_req.value = cpu_to_be32(*attr_val);
1894 break;
1895 case UPIU_QUERY_OPCODE_READ_ATTR:
1896 request->query_func = UPIU_QUERY_FUNC_STANDARD_READ_REQUEST;
1897 break;
1898 default:
1899 dev_err(hba->dev, "%s: Expected query attr opcode but got = 0x%.2x\n",
1900 __func__, opcode);
1901 err = -EINVAL;
1902 goto out_unlock;
1905 err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_QUERY, QUERY_REQ_TIMEOUT);
1907 if (err) {
1908 dev_err(hba->dev, "%s: opcode 0x%.2x for idn %d failed, err = %d\n",
1909 __func__, opcode, idn, err);
1910 goto out_unlock;
1913 *attr_val = be32_to_cpu(response->upiu_res.value);
1915 out_unlock:
1916 mutex_unlock(&hba->dev_cmd.lock);
1917 out:
1918 ufshcd_release(hba);
1919 return err;
1923 * ufshcd_query_attr_retry() - API function for sending query
1924 * attribute with retries
1925 * @hba: per-adapter instance
1926 * @opcode: attribute opcode
1927 * @idn: attribute idn to access
1928 * @index: index field
1929 * @selector: selector field
1930 * @attr_val: the attribute value after the query request
1931 * completes
1933 * Returns 0 for success, non-zero in case of failure
1935 static int ufshcd_query_attr_retry(struct ufs_hba *hba,
1936 enum query_opcode opcode, enum attr_idn idn, u8 index, u8 selector,
1937 u32 *attr_val)
1939 int ret = 0;
1940 u32 retries;
1942 for (retries = QUERY_REQ_RETRIES; retries > 0; retries--) {
1943 ret = ufshcd_query_attr(hba, opcode, idn, index,
1944 selector, attr_val);
1945 if (ret)
1946 dev_dbg(hba->dev, "%s: failed with error %d, retries %d\n",
1947 __func__, ret, retries);
1948 else
1949 break;
1952 if (ret)
1953 dev_err(hba->dev,
1954 "%s: query attribute, idn %d, failed with error %d after %d retires\n",
1955 __func__, idn, ret, QUERY_REQ_RETRIES);
1956 return ret;
1959 static int __ufshcd_query_descriptor(struct ufs_hba *hba,
1960 enum query_opcode opcode, enum desc_idn idn, u8 index,
1961 u8 selector, u8 *desc_buf, int *buf_len)
1963 struct ufs_query_req *request = NULL;
1964 struct ufs_query_res *response = NULL;
1965 int err;
1967 BUG_ON(!hba);
1969 ufshcd_hold(hba, false);
1970 if (!desc_buf) {
1971 dev_err(hba->dev, "%s: descriptor buffer required for opcode 0x%x\n",
1972 __func__, opcode);
1973 err = -EINVAL;
1974 goto out;
1977 if (*buf_len <= QUERY_DESC_MIN_SIZE || *buf_len > QUERY_DESC_MAX_SIZE) {
1978 dev_err(hba->dev, "%s: descriptor buffer size (%d) is out of range\n",
1979 __func__, *buf_len);
1980 err = -EINVAL;
1981 goto out;
1984 mutex_lock(&hba->dev_cmd.lock);
1985 ufshcd_init_query(hba, &request, &response, opcode, idn, index,
1986 selector);
1987 hba->dev_cmd.query.descriptor = desc_buf;
1988 request->upiu_req.length = cpu_to_be16(*buf_len);
1990 switch (opcode) {
1991 case UPIU_QUERY_OPCODE_WRITE_DESC:
1992 request->query_func = UPIU_QUERY_FUNC_STANDARD_WRITE_REQUEST;
1993 break;
1994 case UPIU_QUERY_OPCODE_READ_DESC:
1995 request->query_func = UPIU_QUERY_FUNC_STANDARD_READ_REQUEST;
1996 break;
1997 default:
1998 dev_err(hba->dev,
1999 "%s: Expected query descriptor opcode but got = 0x%.2x\n",
2000 __func__, opcode);
2001 err = -EINVAL;
2002 goto out_unlock;
2005 err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_QUERY, QUERY_REQ_TIMEOUT);
2007 if (err) {
2008 dev_err(hba->dev, "%s: opcode 0x%.2x for idn %d failed, err = %d\n",
2009 __func__, opcode, idn, err);
2010 goto out_unlock;
2013 hba->dev_cmd.query.descriptor = NULL;
2014 *buf_len = be16_to_cpu(response->upiu_res.length);
2016 out_unlock:
2017 mutex_unlock(&hba->dev_cmd.lock);
2018 out:
2019 ufshcd_release(hba);
2020 return err;
2024 * ufshcd_query_descriptor_retry - API function for sending descriptor
2025 * requests
2026 * hba: per-adapter instance
2027 * opcode: attribute opcode
2028 * idn: attribute idn to access
2029 * index: index field
2030 * selector: selector field
2031 * desc_buf: the buffer that contains the descriptor
2032 * buf_len: length parameter passed to the device
2034 * Returns 0 for success, non-zero in case of failure.
2035 * The buf_len parameter will contain, on return, the length parameter
2036 * received on the response.
2038 int ufshcd_query_descriptor_retry(struct ufs_hba *hba,
2039 enum query_opcode opcode, enum desc_idn idn, u8 index,
2040 u8 selector, u8 *desc_buf, int *buf_len)
2042 int err;
2043 int retries;
2045 for (retries = QUERY_REQ_RETRIES; retries > 0; retries--) {
2046 err = __ufshcd_query_descriptor(hba, opcode, idn, index,
2047 selector, desc_buf, buf_len);
2048 if (!err || err == -EINVAL)
2049 break;
2052 return err;
2054 EXPORT_SYMBOL(ufshcd_query_descriptor_retry);
2057 * ufshcd_read_desc_param - read the specified descriptor parameter
2058 * @hba: Pointer to adapter instance
2059 * @desc_id: descriptor idn value
2060 * @desc_index: descriptor index
2061 * @param_offset: offset of the parameter to read
2062 * @param_read_buf: pointer to buffer where parameter would be read
2063 * @param_size: sizeof(param_read_buf)
2065 * Return 0 in case of success, non-zero otherwise
2067 static int ufshcd_read_desc_param(struct ufs_hba *hba,
2068 enum desc_idn desc_id,
2069 int desc_index,
2070 u32 param_offset,
2071 u8 *param_read_buf,
2072 u32 param_size)
2074 int ret;
2075 u8 *desc_buf;
2076 u32 buff_len;
2077 bool is_kmalloc = true;
2079 /* safety checks */
2080 if (desc_id >= QUERY_DESC_IDN_MAX)
2081 return -EINVAL;
2083 buff_len = ufs_query_desc_max_size[desc_id];
2084 if ((param_offset + param_size) > buff_len)
2085 return -EINVAL;
2087 if (!param_offset && (param_size == buff_len)) {
2088 /* memory space already available to hold full descriptor */
2089 desc_buf = param_read_buf;
2090 is_kmalloc = false;
2091 } else {
2092 /* allocate memory to hold full descriptor */
2093 desc_buf = kmalloc(buff_len, GFP_KERNEL);
2094 if (!desc_buf)
2095 return -ENOMEM;
2098 ret = ufshcd_query_descriptor_retry(hba, UPIU_QUERY_OPCODE_READ_DESC,
2099 desc_id, desc_index, 0, desc_buf,
2100 &buff_len);
2102 if (ret || (buff_len < ufs_query_desc_max_size[desc_id]) ||
2103 (desc_buf[QUERY_DESC_LENGTH_OFFSET] !=
2104 ufs_query_desc_max_size[desc_id])
2105 || (desc_buf[QUERY_DESC_DESC_TYPE_OFFSET] != desc_id)) {
2106 dev_err(hba->dev, "%s: Failed reading descriptor. desc_id %d param_offset %d buff_len %d ret %d",
2107 __func__, desc_id, param_offset, buff_len, ret);
2108 if (!ret)
2109 ret = -EINVAL;
2111 goto out;
2114 if (is_kmalloc)
2115 memcpy(param_read_buf, &desc_buf[param_offset], param_size);
2116 out:
2117 if (is_kmalloc)
2118 kfree(desc_buf);
2119 return ret;
2122 static inline int ufshcd_read_desc(struct ufs_hba *hba,
2123 enum desc_idn desc_id,
2124 int desc_index,
2125 u8 *buf,
2126 u32 size)
2128 return ufshcd_read_desc_param(hba, desc_id, desc_index, 0, buf, size);
2131 static inline int ufshcd_read_power_desc(struct ufs_hba *hba,
2132 u8 *buf,
2133 u32 size)
2135 return ufshcd_read_desc(hba, QUERY_DESC_IDN_POWER, 0, buf, size);
2138 int ufshcd_read_device_desc(struct ufs_hba *hba, u8 *buf, u32 size)
2140 return ufshcd_read_desc(hba, QUERY_DESC_IDN_DEVICE, 0, buf, size);
2142 EXPORT_SYMBOL(ufshcd_read_device_desc);
2145 * ufshcd_read_string_desc - read string descriptor
2146 * @hba: pointer to adapter instance
2147 * @desc_index: descriptor index
2148 * @buf: pointer to buffer where descriptor would be read
2149 * @size: size of buf
2150 * @ascii: if true convert from unicode to ascii characters
2152 * Return 0 in case of success, non-zero otherwise
2154 int ufshcd_read_string_desc(struct ufs_hba *hba, int desc_index, u8 *buf,
2155 u32 size, bool ascii)
2157 int err = 0;
2159 err = ufshcd_read_desc(hba,
2160 QUERY_DESC_IDN_STRING, desc_index, buf, size);
2162 if (err) {
2163 dev_err(hba->dev, "%s: reading String Desc failed after %d retries. err = %d\n",
2164 __func__, QUERY_REQ_RETRIES, err);
2165 goto out;
2168 if (ascii) {
2169 int desc_len;
2170 int ascii_len;
2171 int i;
2172 char *buff_ascii;
2174 desc_len = buf[0];
2175 /* remove header and divide by 2 to move from UTF16 to UTF8 */
2176 ascii_len = (desc_len - QUERY_DESC_HDR_SIZE) / 2 + 1;
2177 if (size < ascii_len + QUERY_DESC_HDR_SIZE) {
2178 dev_err(hba->dev, "%s: buffer allocated size is too small\n",
2179 __func__);
2180 err = -ENOMEM;
2181 goto out;
2184 buff_ascii = kmalloc(ascii_len, GFP_KERNEL);
2185 if (!buff_ascii) {
2186 err = -ENOMEM;
2187 goto out;
2191 * the descriptor contains string in UTF16 format
2192 * we need to convert to utf-8 so it can be displayed
2194 utf16s_to_utf8s((wchar_t *)&buf[QUERY_DESC_HDR_SIZE],
2195 desc_len - QUERY_DESC_HDR_SIZE,
2196 UTF16_BIG_ENDIAN, buff_ascii, ascii_len);
2198 /* replace non-printable or non-ASCII characters with spaces */
2199 for (i = 0; i < ascii_len; i++)
2200 ufshcd_remove_non_printable(&buff_ascii[i]);
2202 memset(buf + QUERY_DESC_HDR_SIZE, 0,
2203 size - QUERY_DESC_HDR_SIZE);
2204 memcpy(buf + QUERY_DESC_HDR_SIZE, buff_ascii, ascii_len);
2205 buf[QUERY_DESC_LENGTH_OFFSET] = ascii_len + QUERY_DESC_HDR_SIZE;
2206 kfree(buff_ascii);
2208 out:
2209 return err;
2211 EXPORT_SYMBOL(ufshcd_read_string_desc);
2214 * ufshcd_read_unit_desc_param - read the specified unit descriptor parameter
2215 * @hba: Pointer to adapter instance
2216 * @lun: lun id
2217 * @param_offset: offset of the parameter to read
2218 * @param_read_buf: pointer to buffer where parameter would be read
2219 * @param_size: sizeof(param_read_buf)
2221 * Return 0 in case of success, non-zero otherwise
2223 static inline int ufshcd_read_unit_desc_param(struct ufs_hba *hba,
2224 int lun,
2225 enum unit_desc_param param_offset,
2226 u8 *param_read_buf,
2227 u32 param_size)
2230 * Unit descriptors are only available for general purpose LUs (LUN id
2231 * from 0 to 7) and RPMB Well known LU.
2233 if (lun != UFS_UPIU_RPMB_WLUN && (lun >= UFS_UPIU_MAX_GENERAL_LUN))
2234 return -EOPNOTSUPP;
2236 return ufshcd_read_desc_param(hba, QUERY_DESC_IDN_UNIT, lun,
2237 param_offset, param_read_buf, param_size);
2241 * ufshcd_memory_alloc - allocate memory for host memory space data structures
2242 * @hba: per adapter instance
2244 * 1. Allocate DMA memory for Command Descriptor array
2245 * Each command descriptor consist of Command UPIU, Response UPIU and PRDT
2246 * 2. Allocate DMA memory for UTP Transfer Request Descriptor List (UTRDL).
2247 * 3. Allocate DMA memory for UTP Task Management Request Descriptor List
2248 * (UTMRDL)
2249 * 4. Allocate memory for local reference block(lrb).
2251 * Returns 0 for success, non-zero in case of failure
2253 static int ufshcd_memory_alloc(struct ufs_hba *hba)
2255 size_t utmrdl_size, utrdl_size, ucdl_size;
2257 /* Allocate memory for UTP command descriptors */
2258 ucdl_size = (sizeof(struct utp_transfer_cmd_desc) * hba->nutrs);
2259 hba->ucdl_base_addr = dmam_alloc_coherent(hba->dev,
2260 ucdl_size,
2261 &hba->ucdl_dma_addr,
2262 GFP_KERNEL);
2265 * UFSHCI requires UTP command descriptor to be 128 byte aligned.
2266 * make sure hba->ucdl_dma_addr is aligned to PAGE_SIZE
2267 * if hba->ucdl_dma_addr is aligned to PAGE_SIZE, then it will
2268 * be aligned to 128 bytes as well
2270 if (!hba->ucdl_base_addr ||
2271 WARN_ON(hba->ucdl_dma_addr & (PAGE_SIZE - 1))) {
2272 dev_err(hba->dev,
2273 "Command Descriptor Memory allocation failed\n");
2274 goto out;
2278 * Allocate memory for UTP Transfer descriptors
2279 * UFSHCI requires 1024 byte alignment of UTRD
2281 utrdl_size = (sizeof(struct utp_transfer_req_desc) * hba->nutrs);
2282 hba->utrdl_base_addr = dmam_alloc_coherent(hba->dev,
2283 utrdl_size,
2284 &hba->utrdl_dma_addr,
2285 GFP_KERNEL);
2286 if (!hba->utrdl_base_addr ||
2287 WARN_ON(hba->utrdl_dma_addr & (PAGE_SIZE - 1))) {
2288 dev_err(hba->dev,
2289 "Transfer Descriptor Memory allocation failed\n");
2290 goto out;
2294 * Allocate memory for UTP Task Management descriptors
2295 * UFSHCI requires 1024 byte alignment of UTMRD
2297 utmrdl_size = sizeof(struct utp_task_req_desc) * hba->nutmrs;
2298 hba->utmrdl_base_addr = dmam_alloc_coherent(hba->dev,
2299 utmrdl_size,
2300 &hba->utmrdl_dma_addr,
2301 GFP_KERNEL);
2302 if (!hba->utmrdl_base_addr ||
2303 WARN_ON(hba->utmrdl_dma_addr & (PAGE_SIZE - 1))) {
2304 dev_err(hba->dev,
2305 "Task Management Descriptor Memory allocation failed\n");
2306 goto out;
2309 /* Allocate memory for local reference block */
2310 hba->lrb = devm_kzalloc(hba->dev,
2311 hba->nutrs * sizeof(struct ufshcd_lrb),
2312 GFP_KERNEL);
2313 if (!hba->lrb) {
2314 dev_err(hba->dev, "LRB Memory allocation failed\n");
2315 goto out;
2317 return 0;
2318 out:
2319 return -ENOMEM;
2323 * ufshcd_host_memory_configure - configure local reference block with
2324 * memory offsets
2325 * @hba: per adapter instance
2327 * Configure Host memory space
2328 * 1. Update Corresponding UTRD.UCDBA and UTRD.UCDBAU with UCD DMA
2329 * address.
2330 * 2. Update each UTRD with Response UPIU offset, Response UPIU length
2331 * and PRDT offset.
2332 * 3. Save the corresponding addresses of UTRD, UCD.CMD, UCD.RSP and UCD.PRDT
2333 * into local reference block.
2335 static void ufshcd_host_memory_configure(struct ufs_hba *hba)
2337 struct utp_transfer_cmd_desc *cmd_descp;
2338 struct utp_transfer_req_desc *utrdlp;
2339 dma_addr_t cmd_desc_dma_addr;
2340 dma_addr_t cmd_desc_element_addr;
2341 u16 response_offset;
2342 u16 prdt_offset;
2343 int cmd_desc_size;
2344 int i;
2346 utrdlp = hba->utrdl_base_addr;
2347 cmd_descp = hba->ucdl_base_addr;
2349 response_offset =
2350 offsetof(struct utp_transfer_cmd_desc, response_upiu);
2351 prdt_offset =
2352 offsetof(struct utp_transfer_cmd_desc, prd_table);
2354 cmd_desc_size = sizeof(struct utp_transfer_cmd_desc);
2355 cmd_desc_dma_addr = hba->ucdl_dma_addr;
2357 for (i = 0; i < hba->nutrs; i++) {
2358 /* Configure UTRD with command descriptor base address */
2359 cmd_desc_element_addr =
2360 (cmd_desc_dma_addr + (cmd_desc_size * i));
2361 utrdlp[i].command_desc_base_addr_lo =
2362 cpu_to_le32(lower_32_bits(cmd_desc_element_addr));
2363 utrdlp[i].command_desc_base_addr_hi =
2364 cpu_to_le32(upper_32_bits(cmd_desc_element_addr));
2366 /* Response upiu and prdt offset should be in double words */
2367 utrdlp[i].response_upiu_offset =
2368 cpu_to_le16((response_offset >> 2));
2369 utrdlp[i].prd_table_offset =
2370 cpu_to_le16((prdt_offset >> 2));
2371 utrdlp[i].response_upiu_length =
2372 cpu_to_le16(ALIGNED_UPIU_SIZE >> 2);
2374 hba->lrb[i].utr_descriptor_ptr = (utrdlp + i);
2375 hba->lrb[i].ucd_req_ptr =
2376 (struct utp_upiu_req *)(cmd_descp + i);
2377 hba->lrb[i].ucd_rsp_ptr =
2378 (struct utp_upiu_rsp *)cmd_descp[i].response_upiu;
2379 hba->lrb[i].ucd_prdt_ptr =
2380 (struct ufshcd_sg_entry *)cmd_descp[i].prd_table;
2385 * ufshcd_dme_link_startup - Notify Unipro to perform link startup
2386 * @hba: per adapter instance
2388 * UIC_CMD_DME_LINK_STARTUP command must be issued to Unipro layer,
2389 * in order to initialize the Unipro link startup procedure.
2390 * Once the Unipro links are up, the device connected to the controller
2391 * is detected.
2393 * Returns 0 on success, non-zero value on failure
2395 static int ufshcd_dme_link_startup(struct ufs_hba *hba)
2397 struct uic_command uic_cmd = {0};
2398 int ret;
2400 uic_cmd.command = UIC_CMD_DME_LINK_STARTUP;
2402 ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
2403 if (ret)
2404 dev_err(hba->dev,
2405 "dme-link-startup: error code %d\n", ret);
2406 return ret;
2409 static inline void ufshcd_add_delay_before_dme_cmd(struct ufs_hba *hba)
2411 #define MIN_DELAY_BEFORE_DME_CMDS_US 1000
2412 unsigned long min_sleep_time_us;
2414 if (!(hba->quirks & UFSHCD_QUIRK_DELAY_BEFORE_DME_CMDS))
2415 return;
2418 * last_dme_cmd_tstamp will be 0 only for 1st call to
2419 * this function
2421 if (unlikely(!ktime_to_us(hba->last_dme_cmd_tstamp))) {
2422 min_sleep_time_us = MIN_DELAY_BEFORE_DME_CMDS_US;
2423 } else {
2424 unsigned long delta =
2425 (unsigned long) ktime_to_us(
2426 ktime_sub(ktime_get(),
2427 hba->last_dme_cmd_tstamp));
2429 if (delta < MIN_DELAY_BEFORE_DME_CMDS_US)
2430 min_sleep_time_us =
2431 MIN_DELAY_BEFORE_DME_CMDS_US - delta;
2432 else
2433 return; /* no more delay required */
2436 /* allow sleep for extra 50us if needed */
2437 usleep_range(min_sleep_time_us, min_sleep_time_us + 50);
2441 * ufshcd_dme_set_attr - UIC command for DME_SET, DME_PEER_SET
2442 * @hba: per adapter instance
2443 * @attr_sel: uic command argument1
2444 * @attr_set: attribute set type as uic command argument2
2445 * @mib_val: setting value as uic command argument3
2446 * @peer: indicate whether peer or local
2448 * Returns 0 on success, non-zero value on failure
2450 int ufshcd_dme_set_attr(struct ufs_hba *hba, u32 attr_sel,
2451 u8 attr_set, u32 mib_val, u8 peer)
2453 struct uic_command uic_cmd = {0};
2454 static const char *const action[] = {
2455 "dme-set",
2456 "dme-peer-set"
2458 const char *set = action[!!peer];
2459 int ret;
2460 int retries = UFS_UIC_COMMAND_RETRIES;
2462 uic_cmd.command = peer ?
2463 UIC_CMD_DME_PEER_SET : UIC_CMD_DME_SET;
2464 uic_cmd.argument1 = attr_sel;
2465 uic_cmd.argument2 = UIC_ARG_ATTR_TYPE(attr_set);
2466 uic_cmd.argument3 = mib_val;
2468 do {
2469 /* for peer attributes we retry upon failure */
2470 ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
2471 if (ret)
2472 dev_dbg(hba->dev, "%s: attr-id 0x%x val 0x%x error code %d\n",
2473 set, UIC_GET_ATTR_ID(attr_sel), mib_val, ret);
2474 } while (ret && peer && --retries);
2476 if (!retries)
2477 dev_err(hba->dev, "%s: attr-id 0x%x val 0x%x failed %d retries\n",
2478 set, UIC_GET_ATTR_ID(attr_sel), mib_val,
2479 retries);
2481 return ret;
2483 EXPORT_SYMBOL_GPL(ufshcd_dme_set_attr);
2486 * ufshcd_dme_get_attr - UIC command for DME_GET, DME_PEER_GET
2487 * @hba: per adapter instance
2488 * @attr_sel: uic command argument1
2489 * @mib_val: the value of the attribute as returned by the UIC command
2490 * @peer: indicate whether peer or local
2492 * Returns 0 on success, non-zero value on failure
2494 int ufshcd_dme_get_attr(struct ufs_hba *hba, u32 attr_sel,
2495 u32 *mib_val, u8 peer)
2497 struct uic_command uic_cmd = {0};
2498 static const char *const action[] = {
2499 "dme-get",
2500 "dme-peer-get"
2502 const char *get = action[!!peer];
2503 int ret;
2504 int retries = UFS_UIC_COMMAND_RETRIES;
2505 struct ufs_pa_layer_attr orig_pwr_info;
2506 struct ufs_pa_layer_attr temp_pwr_info;
2507 bool pwr_mode_change = false;
2509 if (peer && (hba->quirks & UFSHCD_QUIRK_DME_PEER_ACCESS_AUTO_MODE)) {
2510 orig_pwr_info = hba->pwr_info;
2511 temp_pwr_info = orig_pwr_info;
2513 if (orig_pwr_info.pwr_tx == FAST_MODE ||
2514 orig_pwr_info.pwr_rx == FAST_MODE) {
2515 temp_pwr_info.pwr_tx = FASTAUTO_MODE;
2516 temp_pwr_info.pwr_rx = FASTAUTO_MODE;
2517 pwr_mode_change = true;
2518 } else if (orig_pwr_info.pwr_tx == SLOW_MODE ||
2519 orig_pwr_info.pwr_rx == SLOW_MODE) {
2520 temp_pwr_info.pwr_tx = SLOWAUTO_MODE;
2521 temp_pwr_info.pwr_rx = SLOWAUTO_MODE;
2522 pwr_mode_change = true;
2524 if (pwr_mode_change) {
2525 ret = ufshcd_change_power_mode(hba, &temp_pwr_info);
2526 if (ret)
2527 goto out;
2531 uic_cmd.command = peer ?
2532 UIC_CMD_DME_PEER_GET : UIC_CMD_DME_GET;
2533 uic_cmd.argument1 = attr_sel;
2535 do {
2536 /* for peer attributes we retry upon failure */
2537 ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
2538 if (ret)
2539 dev_dbg(hba->dev, "%s: attr-id 0x%x error code %d\n",
2540 get, UIC_GET_ATTR_ID(attr_sel), ret);
2541 } while (ret && peer && --retries);
2543 if (!retries)
2544 dev_err(hba->dev, "%s: attr-id 0x%x failed %d retries\n",
2545 get, UIC_GET_ATTR_ID(attr_sel), retries);
2547 if (mib_val && !ret)
2548 *mib_val = uic_cmd.argument3;
2550 if (peer && (hba->quirks & UFSHCD_QUIRK_DME_PEER_ACCESS_AUTO_MODE)
2551 && pwr_mode_change)
2552 ufshcd_change_power_mode(hba, &orig_pwr_info);
2553 out:
2554 return ret;
2556 EXPORT_SYMBOL_GPL(ufshcd_dme_get_attr);
2559 * ufshcd_uic_pwr_ctrl - executes UIC commands (which affects the link power
2560 * state) and waits for it to take effect.
2562 * @hba: per adapter instance
2563 * @cmd: UIC command to execute
2565 * DME operations like DME_SET(PA_PWRMODE), DME_HIBERNATE_ENTER &
2566 * DME_HIBERNATE_EXIT commands take some time to take its effect on both host
2567 * and device UniPro link and hence it's final completion would be indicated by
2568 * dedicated status bits in Interrupt Status register (UPMS, UHES, UHXS) in
2569 * addition to normal UIC command completion Status (UCCS). This function only
2570 * returns after the relevant status bits indicate the completion.
2572 * Returns 0 on success, non-zero value on failure
2574 static int ufshcd_uic_pwr_ctrl(struct ufs_hba *hba, struct uic_command *cmd)
2576 struct completion uic_async_done;
2577 unsigned long flags;
2578 u8 status;
2579 int ret;
2580 bool reenable_intr = false;
2582 mutex_lock(&hba->uic_cmd_mutex);
2583 init_completion(&uic_async_done);
2584 ufshcd_add_delay_before_dme_cmd(hba);
2586 spin_lock_irqsave(hba->host->host_lock, flags);
2587 hba->uic_async_done = &uic_async_done;
2588 if (ufshcd_readl(hba, REG_INTERRUPT_ENABLE) & UIC_COMMAND_COMPL) {
2589 ufshcd_disable_intr(hba, UIC_COMMAND_COMPL);
2591 * Make sure UIC command completion interrupt is disabled before
2592 * issuing UIC command.
2594 wmb();
2595 reenable_intr = true;
2597 ret = __ufshcd_send_uic_cmd(hba, cmd, false);
2598 spin_unlock_irqrestore(hba->host->host_lock, flags);
2599 if (ret) {
2600 dev_err(hba->dev,
2601 "pwr ctrl cmd 0x%x with mode 0x%x uic error %d\n",
2602 cmd->command, cmd->argument3, ret);
2603 goto out;
2606 if (!wait_for_completion_timeout(hba->uic_async_done,
2607 msecs_to_jiffies(UIC_CMD_TIMEOUT))) {
2608 dev_err(hba->dev,
2609 "pwr ctrl cmd 0x%x with mode 0x%x completion timeout\n",
2610 cmd->command, cmd->argument3);
2611 ret = -ETIMEDOUT;
2612 goto out;
2615 status = ufshcd_get_upmcrs(hba);
2616 if (status != PWR_LOCAL) {
2617 dev_err(hba->dev,
2618 "pwr ctrl cmd 0x%0x failed, host upmcrs:0x%x\n",
2619 cmd->command, status);
2620 ret = (status != PWR_OK) ? status : -1;
2622 out:
2623 spin_lock_irqsave(hba->host->host_lock, flags);
2624 hba->active_uic_cmd = NULL;
2625 hba->uic_async_done = NULL;
2626 if (reenable_intr)
2627 ufshcd_enable_intr(hba, UIC_COMMAND_COMPL);
2628 spin_unlock_irqrestore(hba->host->host_lock, flags);
2629 mutex_unlock(&hba->uic_cmd_mutex);
2631 return ret;
2635 * ufshcd_uic_change_pwr_mode - Perform the UIC power mode chage
2636 * using DME_SET primitives.
2637 * @hba: per adapter instance
2638 * @mode: powr mode value
2640 * Returns 0 on success, non-zero value on failure
2642 static int ufshcd_uic_change_pwr_mode(struct ufs_hba *hba, u8 mode)
2644 struct uic_command uic_cmd = {0};
2645 int ret;
2647 if (hba->quirks & UFSHCD_QUIRK_BROKEN_PA_RXHSUNTERMCAP) {
2648 ret = ufshcd_dme_set(hba,
2649 UIC_ARG_MIB_SEL(PA_RXHSUNTERMCAP, 0), 1);
2650 if (ret) {
2651 dev_err(hba->dev, "%s: failed to enable PA_RXHSUNTERMCAP ret %d\n",
2652 __func__, ret);
2653 goto out;
2657 uic_cmd.command = UIC_CMD_DME_SET;
2658 uic_cmd.argument1 = UIC_ARG_MIB(PA_PWRMODE);
2659 uic_cmd.argument3 = mode;
2660 ufshcd_hold(hba, false);
2661 ret = ufshcd_uic_pwr_ctrl(hba, &uic_cmd);
2662 ufshcd_release(hba);
2664 out:
2665 return ret;
2668 static int ufshcd_link_recovery(struct ufs_hba *hba)
2670 int ret;
2671 unsigned long flags;
2673 spin_lock_irqsave(hba->host->host_lock, flags);
2674 hba->ufshcd_state = UFSHCD_STATE_RESET;
2675 ufshcd_set_eh_in_progress(hba);
2676 spin_unlock_irqrestore(hba->host->host_lock, flags);
2678 ret = ufshcd_host_reset_and_restore(hba);
2680 spin_lock_irqsave(hba->host->host_lock, flags);
2681 if (ret)
2682 hba->ufshcd_state = UFSHCD_STATE_ERROR;
2683 ufshcd_clear_eh_in_progress(hba);
2684 spin_unlock_irqrestore(hba->host->host_lock, flags);
2686 if (ret)
2687 dev_err(hba->dev, "%s: link recovery failed, err %d",
2688 __func__, ret);
2690 return ret;
2693 static int __ufshcd_uic_hibern8_enter(struct ufs_hba *hba)
2695 int ret;
2696 struct uic_command uic_cmd = {0};
2698 uic_cmd.command = UIC_CMD_DME_HIBER_ENTER;
2699 ret = ufshcd_uic_pwr_ctrl(hba, &uic_cmd);
2701 if (ret) {
2702 dev_err(hba->dev, "%s: hibern8 enter failed. ret = %d\n",
2703 __func__, ret);
2706 * If link recovery fails then return error so that caller
2707 * don't retry the hibern8 enter again.
2709 if (ufshcd_link_recovery(hba))
2710 ret = -ENOLINK;
2713 return ret;
2716 static int ufshcd_uic_hibern8_enter(struct ufs_hba *hba)
2718 int ret = 0, retries;
2720 for (retries = UIC_HIBERN8_ENTER_RETRIES; retries > 0; retries--) {
2721 ret = __ufshcd_uic_hibern8_enter(hba);
2722 if (!ret || ret == -ENOLINK)
2723 goto out;
2725 out:
2726 return ret;
2729 static int ufshcd_uic_hibern8_exit(struct ufs_hba *hba)
2731 struct uic_command uic_cmd = {0};
2732 int ret;
2734 uic_cmd.command = UIC_CMD_DME_HIBER_EXIT;
2735 ret = ufshcd_uic_pwr_ctrl(hba, &uic_cmd);
2736 if (ret) {
2737 dev_err(hba->dev, "%s: hibern8 exit failed. ret = %d\n",
2738 __func__, ret);
2739 ret = ufshcd_link_recovery(hba);
2742 return ret;
2746 * ufshcd_init_pwr_info - setting the POR (power on reset)
2747 * values in hba power info
2748 * @hba: per-adapter instance
2750 static void ufshcd_init_pwr_info(struct ufs_hba *hba)
2752 hba->pwr_info.gear_rx = UFS_PWM_G1;
2753 hba->pwr_info.gear_tx = UFS_PWM_G1;
2754 hba->pwr_info.lane_rx = 1;
2755 hba->pwr_info.lane_tx = 1;
2756 hba->pwr_info.pwr_rx = SLOWAUTO_MODE;
2757 hba->pwr_info.pwr_tx = SLOWAUTO_MODE;
2758 hba->pwr_info.hs_rate = 0;
2762 * ufshcd_get_max_pwr_mode - reads the max power mode negotiated with device
2763 * @hba: per-adapter instance
2765 static int ufshcd_get_max_pwr_mode(struct ufs_hba *hba)
2767 struct ufs_pa_layer_attr *pwr_info = &hba->max_pwr_info.info;
2769 if (hba->max_pwr_info.is_valid)
2770 return 0;
2772 pwr_info->pwr_tx = FASTAUTO_MODE;
2773 pwr_info->pwr_rx = FASTAUTO_MODE;
2774 pwr_info->hs_rate = PA_HS_MODE_B;
2776 /* Get the connected lane count */
2777 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_CONNECTEDRXDATALANES),
2778 &pwr_info->lane_rx);
2779 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_CONNECTEDTXDATALANES),
2780 &pwr_info->lane_tx);
2782 if (!pwr_info->lane_rx || !pwr_info->lane_tx) {
2783 dev_err(hba->dev, "%s: invalid connected lanes value. rx=%d, tx=%d\n",
2784 __func__,
2785 pwr_info->lane_rx,
2786 pwr_info->lane_tx);
2787 return -EINVAL;
2791 * First, get the maximum gears of HS speed.
2792 * If a zero value, it means there is no HSGEAR capability.
2793 * Then, get the maximum gears of PWM speed.
2795 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_MAXRXHSGEAR), &pwr_info->gear_rx);
2796 if (!pwr_info->gear_rx) {
2797 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_MAXRXPWMGEAR),
2798 &pwr_info->gear_rx);
2799 if (!pwr_info->gear_rx) {
2800 dev_err(hba->dev, "%s: invalid max pwm rx gear read = %d\n",
2801 __func__, pwr_info->gear_rx);
2802 return -EINVAL;
2804 pwr_info->pwr_rx = SLOWAUTO_MODE;
2807 ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_MAXRXHSGEAR),
2808 &pwr_info->gear_tx);
2809 if (!pwr_info->gear_tx) {
2810 ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_MAXRXPWMGEAR),
2811 &pwr_info->gear_tx);
2812 if (!pwr_info->gear_tx) {
2813 dev_err(hba->dev, "%s: invalid max pwm tx gear read = %d\n",
2814 __func__, pwr_info->gear_tx);
2815 return -EINVAL;
2817 pwr_info->pwr_tx = SLOWAUTO_MODE;
2820 hba->max_pwr_info.is_valid = true;
2821 return 0;
2824 static int ufshcd_change_power_mode(struct ufs_hba *hba,
2825 struct ufs_pa_layer_attr *pwr_mode)
2827 int ret;
2829 /* if already configured to the requested pwr_mode */
2830 if (pwr_mode->gear_rx == hba->pwr_info.gear_rx &&
2831 pwr_mode->gear_tx == hba->pwr_info.gear_tx &&
2832 pwr_mode->lane_rx == hba->pwr_info.lane_rx &&
2833 pwr_mode->lane_tx == hba->pwr_info.lane_tx &&
2834 pwr_mode->pwr_rx == hba->pwr_info.pwr_rx &&
2835 pwr_mode->pwr_tx == hba->pwr_info.pwr_tx &&
2836 pwr_mode->hs_rate == hba->pwr_info.hs_rate) {
2837 dev_dbg(hba->dev, "%s: power already configured\n", __func__);
2838 return 0;
2842 * Configure attributes for power mode change with below.
2843 * - PA_RXGEAR, PA_ACTIVERXDATALANES, PA_RXTERMINATION,
2844 * - PA_TXGEAR, PA_ACTIVETXDATALANES, PA_TXTERMINATION,
2845 * - PA_HSSERIES
2847 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_RXGEAR), pwr_mode->gear_rx);
2848 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_ACTIVERXDATALANES),
2849 pwr_mode->lane_rx);
2850 if (pwr_mode->pwr_rx == FASTAUTO_MODE ||
2851 pwr_mode->pwr_rx == FAST_MODE)
2852 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_RXTERMINATION), TRUE);
2853 else
2854 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_RXTERMINATION), FALSE);
2856 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TXGEAR), pwr_mode->gear_tx);
2857 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_ACTIVETXDATALANES),
2858 pwr_mode->lane_tx);
2859 if (pwr_mode->pwr_tx == FASTAUTO_MODE ||
2860 pwr_mode->pwr_tx == FAST_MODE)
2861 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TXTERMINATION), TRUE);
2862 else
2863 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TXTERMINATION), FALSE);
2865 if (pwr_mode->pwr_rx == FASTAUTO_MODE ||
2866 pwr_mode->pwr_tx == FASTAUTO_MODE ||
2867 pwr_mode->pwr_rx == FAST_MODE ||
2868 pwr_mode->pwr_tx == FAST_MODE)
2869 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_HSSERIES),
2870 pwr_mode->hs_rate);
2872 ret = ufshcd_uic_change_pwr_mode(hba, pwr_mode->pwr_rx << 4
2873 | pwr_mode->pwr_tx);
2875 if (ret) {
2876 dev_err(hba->dev,
2877 "%s: power mode change failed %d\n", __func__, ret);
2878 } else {
2879 ufshcd_vops_pwr_change_notify(hba, POST_CHANGE, NULL,
2880 pwr_mode);
2882 memcpy(&hba->pwr_info, pwr_mode,
2883 sizeof(struct ufs_pa_layer_attr));
2886 return ret;
2890 * ufshcd_config_pwr_mode - configure a new power mode
2891 * @hba: per-adapter instance
2892 * @desired_pwr_mode: desired power configuration
2894 static int ufshcd_config_pwr_mode(struct ufs_hba *hba,
2895 struct ufs_pa_layer_attr *desired_pwr_mode)
2897 struct ufs_pa_layer_attr final_params = { 0 };
2898 int ret;
2900 ret = ufshcd_vops_pwr_change_notify(hba, PRE_CHANGE,
2901 desired_pwr_mode, &final_params);
2903 if (ret)
2904 memcpy(&final_params, desired_pwr_mode, sizeof(final_params));
2906 ret = ufshcd_change_power_mode(hba, &final_params);
2908 return ret;
2912 * ufshcd_complete_dev_init() - checks device readiness
2913 * hba: per-adapter instance
2915 * Set fDeviceInit flag and poll until device toggles it.
2917 static int ufshcd_complete_dev_init(struct ufs_hba *hba)
2919 int i;
2920 int err;
2921 bool flag_res = 1;
2923 err = ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_SET_FLAG,
2924 QUERY_FLAG_IDN_FDEVICEINIT, NULL);
2925 if (err) {
2926 dev_err(hba->dev,
2927 "%s setting fDeviceInit flag failed with error %d\n",
2928 __func__, err);
2929 goto out;
2932 /* poll for max. 1000 iterations for fDeviceInit flag to clear */
2933 for (i = 0; i < 1000 && !err && flag_res; i++)
2934 err = ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_READ_FLAG,
2935 QUERY_FLAG_IDN_FDEVICEINIT, &flag_res);
2937 if (err)
2938 dev_err(hba->dev,
2939 "%s reading fDeviceInit flag failed with error %d\n",
2940 __func__, err);
2941 else if (flag_res)
2942 dev_err(hba->dev,
2943 "%s fDeviceInit was not cleared by the device\n",
2944 __func__);
2946 out:
2947 return err;
2951 * ufshcd_make_hba_operational - Make UFS controller operational
2952 * @hba: per adapter instance
2954 * To bring UFS host controller to operational state,
2955 * 1. Enable required interrupts
2956 * 2. Configure interrupt aggregation
2957 * 3. Program UTRL and UTMRL base address
2958 * 4. Configure run-stop-registers
2960 * Returns 0 on success, non-zero value on failure
2962 static int ufshcd_make_hba_operational(struct ufs_hba *hba)
2964 int err = 0;
2965 u32 reg;
2967 /* Enable required interrupts */
2968 ufshcd_enable_intr(hba, UFSHCD_ENABLE_INTRS);
2970 /* Configure interrupt aggregation */
2971 if (ufshcd_is_intr_aggr_allowed(hba))
2972 ufshcd_config_intr_aggr(hba, hba->nutrs - 1, INT_AGGR_DEF_TO);
2973 else
2974 ufshcd_disable_intr_aggr(hba);
2976 /* Configure UTRL and UTMRL base address registers */
2977 ufshcd_writel(hba, lower_32_bits(hba->utrdl_dma_addr),
2978 REG_UTP_TRANSFER_REQ_LIST_BASE_L);
2979 ufshcd_writel(hba, upper_32_bits(hba->utrdl_dma_addr),
2980 REG_UTP_TRANSFER_REQ_LIST_BASE_H);
2981 ufshcd_writel(hba, lower_32_bits(hba->utmrdl_dma_addr),
2982 REG_UTP_TASK_REQ_LIST_BASE_L);
2983 ufshcd_writel(hba, upper_32_bits(hba->utmrdl_dma_addr),
2984 REG_UTP_TASK_REQ_LIST_BASE_H);
2987 * Make sure base address and interrupt setup are updated before
2988 * enabling the run/stop registers below.
2990 wmb();
2993 * UCRDY, UTMRLDY and UTRLRDY bits must be 1
2995 reg = ufshcd_readl(hba, REG_CONTROLLER_STATUS);
2996 if (!(ufshcd_get_lists_status(reg))) {
2997 ufshcd_enable_run_stop_reg(hba);
2998 } else {
2999 dev_err(hba->dev,
3000 "Host controller not ready to process requests");
3001 err = -EIO;
3002 goto out;
3005 out:
3006 return err;
3010 * ufshcd_hba_stop - Send controller to reset state
3011 * @hba: per adapter instance
3012 * @can_sleep: perform sleep or just spin
3014 static inline void ufshcd_hba_stop(struct ufs_hba *hba, bool can_sleep)
3016 int err;
3018 ufshcd_writel(hba, CONTROLLER_DISABLE, REG_CONTROLLER_ENABLE);
3019 err = ufshcd_wait_for_register(hba, REG_CONTROLLER_ENABLE,
3020 CONTROLLER_ENABLE, CONTROLLER_DISABLE,
3021 10, 1, can_sleep);
3022 if (err)
3023 dev_err(hba->dev, "%s: Controller disable failed\n", __func__);
3027 * ufshcd_hba_enable - initialize the controller
3028 * @hba: per adapter instance
3030 * The controller resets itself and controller firmware initialization
3031 * sequence kicks off. When controller is ready it will set
3032 * the Host Controller Enable bit to 1.
3034 * Returns 0 on success, non-zero value on failure
3036 static int ufshcd_hba_enable(struct ufs_hba *hba)
3038 int retry;
3041 * msleep of 1 and 5 used in this function might result in msleep(20),
3042 * but it was necessary to send the UFS FPGA to reset mode during
3043 * development and testing of this driver. msleep can be changed to
3044 * mdelay and retry count can be reduced based on the controller.
3046 if (!ufshcd_is_hba_active(hba))
3047 /* change controller state to "reset state" */
3048 ufshcd_hba_stop(hba, true);
3050 /* UniPro link is disabled at this point */
3051 ufshcd_set_link_off(hba);
3053 ufshcd_vops_hce_enable_notify(hba, PRE_CHANGE);
3055 /* start controller initialization sequence */
3056 ufshcd_hba_start(hba);
3059 * To initialize a UFS host controller HCE bit must be set to 1.
3060 * During initialization the HCE bit value changes from 1->0->1.
3061 * When the host controller completes initialization sequence
3062 * it sets the value of HCE bit to 1. The same HCE bit is read back
3063 * to check if the controller has completed initialization sequence.
3064 * So without this delay the value HCE = 1, set in the previous
3065 * instruction might be read back.
3066 * This delay can be changed based on the controller.
3068 msleep(1);
3070 /* wait for the host controller to complete initialization */
3071 retry = 10;
3072 while (ufshcd_is_hba_active(hba)) {
3073 if (retry) {
3074 retry--;
3075 } else {
3076 dev_err(hba->dev,
3077 "Controller enable failed\n");
3078 return -EIO;
3080 msleep(5);
3083 /* enable UIC related interrupts */
3084 ufshcd_enable_intr(hba, UFSHCD_UIC_MASK);
3086 ufshcd_vops_hce_enable_notify(hba, POST_CHANGE);
3088 return 0;
3091 static int ufshcd_disable_tx_lcc(struct ufs_hba *hba, bool peer)
3093 int tx_lanes, i, err = 0;
3095 if (!peer)
3096 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_CONNECTEDTXDATALANES),
3097 &tx_lanes);
3098 else
3099 ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_CONNECTEDTXDATALANES),
3100 &tx_lanes);
3101 for (i = 0; i < tx_lanes; i++) {
3102 if (!peer)
3103 err = ufshcd_dme_set(hba,
3104 UIC_ARG_MIB_SEL(TX_LCC_ENABLE,
3105 UIC_ARG_MPHY_TX_GEN_SEL_INDEX(i)),
3107 else
3108 err = ufshcd_dme_peer_set(hba,
3109 UIC_ARG_MIB_SEL(TX_LCC_ENABLE,
3110 UIC_ARG_MPHY_TX_GEN_SEL_INDEX(i)),
3112 if (err) {
3113 dev_err(hba->dev, "%s: TX LCC Disable failed, peer = %d, lane = %d, err = %d",
3114 __func__, peer, i, err);
3115 break;
3119 return err;
3122 static inline int ufshcd_disable_device_tx_lcc(struct ufs_hba *hba)
3124 return ufshcd_disable_tx_lcc(hba, true);
3128 * ufshcd_link_startup - Initialize unipro link startup
3129 * @hba: per adapter instance
3131 * Returns 0 for success, non-zero in case of failure
3133 static int ufshcd_link_startup(struct ufs_hba *hba)
3135 int ret;
3136 int retries = DME_LINKSTARTUP_RETRIES;
3138 do {
3139 ufshcd_vops_link_startup_notify(hba, PRE_CHANGE);
3141 ret = ufshcd_dme_link_startup(hba);
3143 /* check if device is detected by inter-connect layer */
3144 if (!ret && !ufshcd_is_device_present(hba)) {
3145 dev_err(hba->dev, "%s: Device not present\n", __func__);
3146 ret = -ENXIO;
3147 goto out;
3151 * DME link lost indication is only received when link is up,
3152 * but we can't be sure if the link is up until link startup
3153 * succeeds. So reset the local Uni-Pro and try again.
3155 if (ret && ufshcd_hba_enable(hba))
3156 goto out;
3157 } while (ret && retries--);
3159 if (ret)
3160 /* failed to get the link up... retire */
3161 goto out;
3163 if (hba->quirks & UFSHCD_QUIRK_BROKEN_LCC) {
3164 ret = ufshcd_disable_device_tx_lcc(hba);
3165 if (ret)
3166 goto out;
3169 /* Include any host controller configuration via UIC commands */
3170 ret = ufshcd_vops_link_startup_notify(hba, POST_CHANGE);
3171 if (ret)
3172 goto out;
3174 ret = ufshcd_make_hba_operational(hba);
3175 out:
3176 if (ret)
3177 dev_err(hba->dev, "link startup failed %d\n", ret);
3178 return ret;
3182 * ufshcd_verify_dev_init() - Verify device initialization
3183 * @hba: per-adapter instance
3185 * Send NOP OUT UPIU and wait for NOP IN response to check whether the
3186 * device Transport Protocol (UTP) layer is ready after a reset.
3187 * If the UTP layer at the device side is not initialized, it may
3188 * not respond with NOP IN UPIU within timeout of %NOP_OUT_TIMEOUT
3189 * and we retry sending NOP OUT for %NOP_OUT_RETRIES iterations.
3191 static int ufshcd_verify_dev_init(struct ufs_hba *hba)
3193 int err = 0;
3194 int retries;
3196 ufshcd_hold(hba, false);
3197 mutex_lock(&hba->dev_cmd.lock);
3198 for (retries = NOP_OUT_RETRIES; retries > 0; retries--) {
3199 err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_NOP,
3200 NOP_OUT_TIMEOUT);
3202 if (!err || err == -ETIMEDOUT)
3203 break;
3205 dev_dbg(hba->dev, "%s: error %d retrying\n", __func__, err);
3207 mutex_unlock(&hba->dev_cmd.lock);
3208 ufshcd_release(hba);
3210 if (err)
3211 dev_err(hba->dev, "%s: NOP OUT failed %d\n", __func__, err);
3212 return err;
3216 * ufshcd_set_queue_depth - set lun queue depth
3217 * @sdev: pointer to SCSI device
3219 * Read bLUQueueDepth value and activate scsi tagged command
3220 * queueing. For WLUN, queue depth is set to 1. For best-effort
3221 * cases (bLUQueueDepth = 0) the queue depth is set to a maximum
3222 * value that host can queue.
3224 static void ufshcd_set_queue_depth(struct scsi_device *sdev)
3226 int ret = 0;
3227 u8 lun_qdepth;
3228 struct ufs_hba *hba;
3230 hba = shost_priv(sdev->host);
3232 lun_qdepth = hba->nutrs;
3233 ret = ufshcd_read_unit_desc_param(hba,
3234 ufshcd_scsi_to_upiu_lun(sdev->lun),
3235 UNIT_DESC_PARAM_LU_Q_DEPTH,
3236 &lun_qdepth,
3237 sizeof(lun_qdepth));
3239 /* Some WLUN doesn't support unit descriptor */
3240 if (ret == -EOPNOTSUPP)
3241 lun_qdepth = 1;
3242 else if (!lun_qdepth)
3243 /* eventually, we can figure out the real queue depth */
3244 lun_qdepth = hba->nutrs;
3245 else
3246 lun_qdepth = min_t(int, lun_qdepth, hba->nutrs);
3248 dev_dbg(hba->dev, "%s: activate tcq with queue depth %d\n",
3249 __func__, lun_qdepth);
3250 scsi_change_queue_depth(sdev, lun_qdepth);
3254 * ufshcd_get_lu_wp - returns the "b_lu_write_protect" from UNIT DESCRIPTOR
3255 * @hba: per-adapter instance
3256 * @lun: UFS device lun id
3257 * @b_lu_write_protect: pointer to buffer to hold the LU's write protect info
3259 * Returns 0 in case of success and b_lu_write_protect status would be returned
3260 * @b_lu_write_protect parameter.
3261 * Returns -ENOTSUPP if reading b_lu_write_protect is not supported.
3262 * Returns -EINVAL in case of invalid parameters passed to this function.
3264 static int ufshcd_get_lu_wp(struct ufs_hba *hba,
3265 u8 lun,
3266 u8 *b_lu_write_protect)
3268 int ret;
3270 if (!b_lu_write_protect)
3271 ret = -EINVAL;
3273 * According to UFS device spec, RPMB LU can't be write
3274 * protected so skip reading bLUWriteProtect parameter for
3275 * it. For other W-LUs, UNIT DESCRIPTOR is not available.
3277 else if (lun >= UFS_UPIU_MAX_GENERAL_LUN)
3278 ret = -ENOTSUPP;
3279 else
3280 ret = ufshcd_read_unit_desc_param(hba,
3281 lun,
3282 UNIT_DESC_PARAM_LU_WR_PROTECT,
3283 b_lu_write_protect,
3284 sizeof(*b_lu_write_protect));
3285 return ret;
3289 * ufshcd_get_lu_power_on_wp_status - get LU's power on write protect
3290 * status
3291 * @hba: per-adapter instance
3292 * @sdev: pointer to SCSI device
3295 static inline void ufshcd_get_lu_power_on_wp_status(struct ufs_hba *hba,
3296 struct scsi_device *sdev)
3298 if (hba->dev_info.f_power_on_wp_en &&
3299 !hba->dev_info.is_lu_power_on_wp) {
3300 u8 b_lu_write_protect;
3302 if (!ufshcd_get_lu_wp(hba, ufshcd_scsi_to_upiu_lun(sdev->lun),
3303 &b_lu_write_protect) &&
3304 (b_lu_write_protect == UFS_LU_POWER_ON_WP))
3305 hba->dev_info.is_lu_power_on_wp = true;
3310 * ufshcd_slave_alloc - handle initial SCSI device configurations
3311 * @sdev: pointer to SCSI device
3313 * Returns success
3315 static int ufshcd_slave_alloc(struct scsi_device *sdev)
3317 struct ufs_hba *hba;
3319 hba = shost_priv(sdev->host);
3321 /* Mode sense(6) is not supported by UFS, so use Mode sense(10) */
3322 sdev->use_10_for_ms = 1;
3324 /* allow SCSI layer to restart the device in case of errors */
3325 sdev->allow_restart = 1;
3327 /* REPORT SUPPORTED OPERATION CODES is not supported */
3328 sdev->no_report_opcodes = 1;
3331 ufshcd_set_queue_depth(sdev);
3333 ufshcd_get_lu_power_on_wp_status(hba, sdev);
3335 return 0;
3339 * ufshcd_change_queue_depth - change queue depth
3340 * @sdev: pointer to SCSI device
3341 * @depth: required depth to set
3343 * Change queue depth and make sure the max. limits are not crossed.
3345 static int ufshcd_change_queue_depth(struct scsi_device *sdev, int depth)
3347 struct ufs_hba *hba = shost_priv(sdev->host);
3349 if (depth > hba->nutrs)
3350 depth = hba->nutrs;
3351 return scsi_change_queue_depth(sdev, depth);
3355 * ufshcd_slave_configure - adjust SCSI device configurations
3356 * @sdev: pointer to SCSI device
3358 static int ufshcd_slave_configure(struct scsi_device *sdev)
3360 struct request_queue *q = sdev->request_queue;
3362 blk_queue_update_dma_pad(q, PRDT_DATA_BYTE_COUNT_PAD - 1);
3363 blk_queue_max_segment_size(q, PRDT_DATA_BYTE_COUNT_MAX);
3365 return 0;
3369 * ufshcd_slave_destroy - remove SCSI device configurations
3370 * @sdev: pointer to SCSI device
3372 static void ufshcd_slave_destroy(struct scsi_device *sdev)
3374 struct ufs_hba *hba;
3376 hba = shost_priv(sdev->host);
3377 /* Drop the reference as it won't be needed anymore */
3378 if (ufshcd_scsi_to_upiu_lun(sdev->lun) == UFS_UPIU_UFS_DEVICE_WLUN) {
3379 unsigned long flags;
3381 spin_lock_irqsave(hba->host->host_lock, flags);
3382 hba->sdev_ufs_device = NULL;
3383 spin_unlock_irqrestore(hba->host->host_lock, flags);
3388 * ufshcd_task_req_compl - handle task management request completion
3389 * @hba: per adapter instance
3390 * @index: index of the completed request
3391 * @resp: task management service response
3393 * Returns non-zero value on error, zero on success
3395 static int ufshcd_task_req_compl(struct ufs_hba *hba, u32 index, u8 *resp)
3397 struct utp_task_req_desc *task_req_descp;
3398 struct utp_upiu_task_rsp *task_rsp_upiup;
3399 unsigned long flags;
3400 int ocs_value;
3401 int task_result;
3403 spin_lock_irqsave(hba->host->host_lock, flags);
3405 /* Clear completed tasks from outstanding_tasks */
3406 __clear_bit(index, &hba->outstanding_tasks);
3408 task_req_descp = hba->utmrdl_base_addr;
3409 ocs_value = ufshcd_get_tmr_ocs(&task_req_descp[index]);
3411 if (ocs_value == OCS_SUCCESS) {
3412 task_rsp_upiup = (struct utp_upiu_task_rsp *)
3413 task_req_descp[index].task_rsp_upiu;
3414 task_result = be32_to_cpu(task_rsp_upiup->output_param1);
3415 task_result = task_result & MASK_TM_SERVICE_RESP;
3416 if (resp)
3417 *resp = (u8)task_result;
3418 } else {
3419 dev_err(hba->dev, "%s: failed, ocs = 0x%x\n",
3420 __func__, ocs_value);
3422 spin_unlock_irqrestore(hba->host->host_lock, flags);
3424 return ocs_value;
3428 * ufshcd_scsi_cmd_status - Update SCSI command result based on SCSI status
3429 * @lrb: pointer to local reference block of completed command
3430 * @scsi_status: SCSI command status
3432 * Returns value base on SCSI command status
3434 static inline int
3435 ufshcd_scsi_cmd_status(struct ufshcd_lrb *lrbp, int scsi_status)
3437 int result = 0;
3439 switch (scsi_status) {
3440 case SAM_STAT_CHECK_CONDITION:
3441 ufshcd_copy_sense_data(lrbp);
3442 case SAM_STAT_GOOD:
3443 result |= DID_OK << 16 |
3444 COMMAND_COMPLETE << 8 |
3445 scsi_status;
3446 break;
3447 case SAM_STAT_TASK_SET_FULL:
3448 case SAM_STAT_BUSY:
3449 case SAM_STAT_TASK_ABORTED:
3450 ufshcd_copy_sense_data(lrbp);
3451 result |= scsi_status;
3452 break;
3453 default:
3454 result |= DID_ERROR << 16;
3455 break;
3456 } /* end of switch */
3458 return result;
3462 * ufshcd_transfer_rsp_status - Get overall status of the response
3463 * @hba: per adapter instance
3464 * @lrb: pointer to local reference block of completed command
3466 * Returns result of the command to notify SCSI midlayer
3468 static inline int
3469 ufshcd_transfer_rsp_status(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
3471 int result = 0;
3472 int scsi_status;
3473 int ocs;
3475 /* overall command status of utrd */
3476 ocs = ufshcd_get_tr_ocs(lrbp);
3478 switch (ocs) {
3479 case OCS_SUCCESS:
3480 result = ufshcd_get_req_rsp(lrbp->ucd_rsp_ptr);
3482 switch (result) {
3483 case UPIU_TRANSACTION_RESPONSE:
3485 * get the response UPIU result to extract
3486 * the SCSI command status
3488 result = ufshcd_get_rsp_upiu_result(lrbp->ucd_rsp_ptr);
3491 * get the result based on SCSI status response
3492 * to notify the SCSI midlayer of the command status
3494 scsi_status = result & MASK_SCSI_STATUS;
3495 result = ufshcd_scsi_cmd_status(lrbp, scsi_status);
3498 * Currently we are only supporting BKOPs exception
3499 * events hence we can ignore BKOPs exception event
3500 * during power management callbacks. BKOPs exception
3501 * event is not expected to be raised in runtime suspend
3502 * callback as it allows the urgent bkops.
3503 * During system suspend, we are anyway forcefully
3504 * disabling the bkops and if urgent bkops is needed
3505 * it will be enabled on system resume. Long term
3506 * solution could be to abort the system suspend if
3507 * UFS device needs urgent BKOPs.
3509 if (!hba->pm_op_in_progress &&
3510 ufshcd_is_exception_event(lrbp->ucd_rsp_ptr))
3511 schedule_work(&hba->eeh_work);
3512 break;
3513 case UPIU_TRANSACTION_REJECT_UPIU:
3514 /* TODO: handle Reject UPIU Response */
3515 result = DID_ERROR << 16;
3516 dev_err(hba->dev,
3517 "Reject UPIU not fully implemented\n");
3518 break;
3519 default:
3520 result = DID_ERROR << 16;
3521 dev_err(hba->dev,
3522 "Unexpected request response code = %x\n",
3523 result);
3524 break;
3526 break;
3527 case OCS_ABORTED:
3528 result |= DID_ABORT << 16;
3529 break;
3530 case OCS_INVALID_COMMAND_STATUS:
3531 result |= DID_REQUEUE << 16;
3532 break;
3533 case OCS_INVALID_CMD_TABLE_ATTR:
3534 case OCS_INVALID_PRDT_ATTR:
3535 case OCS_MISMATCH_DATA_BUF_SIZE:
3536 case OCS_MISMATCH_RESP_UPIU_SIZE:
3537 case OCS_PEER_COMM_FAILURE:
3538 case OCS_FATAL_ERROR:
3539 default:
3540 result |= DID_ERROR << 16;
3541 dev_err(hba->dev,
3542 "OCS error from controller = %x\n", ocs);
3543 break;
3544 } /* end of switch */
3546 return result;
3550 * ufshcd_uic_cmd_compl - handle completion of uic command
3551 * @hba: per adapter instance
3552 * @intr_status: interrupt status generated by the controller
3554 static void ufshcd_uic_cmd_compl(struct ufs_hba *hba, u32 intr_status)
3556 if ((intr_status & UIC_COMMAND_COMPL) && hba->active_uic_cmd) {
3557 hba->active_uic_cmd->argument2 |=
3558 ufshcd_get_uic_cmd_result(hba);
3559 hba->active_uic_cmd->argument3 =
3560 ufshcd_get_dme_attr_val(hba);
3561 complete(&hba->active_uic_cmd->done);
3564 if ((intr_status & UFSHCD_UIC_PWR_MASK) && hba->uic_async_done)
3565 complete(hba->uic_async_done);
3569 * __ufshcd_transfer_req_compl - handle SCSI and query command completion
3570 * @hba: per adapter instance
3571 * @completed_reqs: requests to complete
3573 static void __ufshcd_transfer_req_compl(struct ufs_hba *hba,
3574 unsigned long completed_reqs)
3576 struct ufshcd_lrb *lrbp;
3577 struct scsi_cmnd *cmd;
3578 int result;
3579 int index;
3581 for_each_set_bit(index, &completed_reqs, hba->nutrs) {
3582 lrbp = &hba->lrb[index];
3583 cmd = lrbp->cmd;
3584 if (cmd) {
3585 result = ufshcd_transfer_rsp_status(hba, lrbp);
3586 scsi_dma_unmap(cmd);
3587 cmd->result = result;
3588 /* Mark completed command as NULL in LRB */
3589 lrbp->cmd = NULL;
3590 clear_bit_unlock(index, &hba->lrb_in_use);
3591 /* Do not touch lrbp after scsi done */
3592 cmd->scsi_done(cmd);
3593 __ufshcd_release(hba);
3594 } else if (lrbp->command_type == UTP_CMD_TYPE_DEV_MANAGE ||
3595 lrbp->command_type == UTP_CMD_TYPE_UFS_STORAGE) {
3596 if (hba->dev_cmd.complete)
3597 complete(hba->dev_cmd.complete);
3601 /* clear corresponding bits of completed commands */
3602 hba->outstanding_reqs ^= completed_reqs;
3604 ufshcd_clk_scaling_update_busy(hba);
3606 /* we might have free'd some tags above */
3607 wake_up(&hba->dev_cmd.tag_wq);
3611 * ufshcd_transfer_req_compl - handle SCSI and query command completion
3612 * @hba: per adapter instance
3614 static void ufshcd_transfer_req_compl(struct ufs_hba *hba)
3616 unsigned long completed_reqs;
3617 u32 tr_doorbell;
3619 /* Resetting interrupt aggregation counters first and reading the
3620 * DOOR_BELL afterward allows us to handle all the completed requests.
3621 * In order to prevent other interrupts starvation the DB is read once
3622 * after reset. The down side of this solution is the possibility of
3623 * false interrupt if device completes another request after resetting
3624 * aggregation and before reading the DB.
3626 if (ufshcd_is_intr_aggr_allowed(hba))
3627 ufshcd_reset_intr_aggr(hba);
3629 tr_doorbell = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
3630 completed_reqs = tr_doorbell ^ hba->outstanding_reqs;
3632 __ufshcd_transfer_req_compl(hba, completed_reqs);
3636 * ufshcd_disable_ee - disable exception event
3637 * @hba: per-adapter instance
3638 * @mask: exception event to disable
3640 * Disables exception event in the device so that the EVENT_ALERT
3641 * bit is not set.
3643 * Returns zero on success, non-zero error value on failure.
3645 static int ufshcd_disable_ee(struct ufs_hba *hba, u16 mask)
3647 int err = 0;
3648 u32 val;
3650 if (!(hba->ee_ctrl_mask & mask))
3651 goto out;
3653 val = hba->ee_ctrl_mask & ~mask;
3654 val &= 0xFFFF; /* 2 bytes */
3655 err = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_WRITE_ATTR,
3656 QUERY_ATTR_IDN_EE_CONTROL, 0, 0, &val);
3657 if (!err)
3658 hba->ee_ctrl_mask &= ~mask;
3659 out:
3660 return err;
3664 * ufshcd_enable_ee - enable exception event
3665 * @hba: per-adapter instance
3666 * @mask: exception event to enable
3668 * Enable corresponding exception event in the device to allow
3669 * device to alert host in critical scenarios.
3671 * Returns zero on success, non-zero error value on failure.
3673 static int ufshcd_enable_ee(struct ufs_hba *hba, u16 mask)
3675 int err = 0;
3676 u32 val;
3678 if (hba->ee_ctrl_mask & mask)
3679 goto out;
3681 val = hba->ee_ctrl_mask | mask;
3682 val &= 0xFFFF; /* 2 bytes */
3683 err = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_WRITE_ATTR,
3684 QUERY_ATTR_IDN_EE_CONTROL, 0, 0, &val);
3685 if (!err)
3686 hba->ee_ctrl_mask |= mask;
3687 out:
3688 return err;
3692 * ufshcd_enable_auto_bkops - Allow device managed BKOPS
3693 * @hba: per-adapter instance
3695 * Allow device to manage background operations on its own. Enabling
3696 * this might lead to inconsistent latencies during normal data transfers
3697 * as the device is allowed to manage its own way of handling background
3698 * operations.
3700 * Returns zero on success, non-zero on failure.
3702 static int ufshcd_enable_auto_bkops(struct ufs_hba *hba)
3704 int err = 0;
3706 if (hba->auto_bkops_enabled)
3707 goto out;
3709 err = ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_SET_FLAG,
3710 QUERY_FLAG_IDN_BKOPS_EN, NULL);
3711 if (err) {
3712 dev_err(hba->dev, "%s: failed to enable bkops %d\n",
3713 __func__, err);
3714 goto out;
3717 hba->auto_bkops_enabled = true;
3719 /* No need of URGENT_BKOPS exception from the device */
3720 err = ufshcd_disable_ee(hba, MASK_EE_URGENT_BKOPS);
3721 if (err)
3722 dev_err(hba->dev, "%s: failed to disable exception event %d\n",
3723 __func__, err);
3724 out:
3725 return err;
3729 * ufshcd_disable_auto_bkops - block device in doing background operations
3730 * @hba: per-adapter instance
3732 * Disabling background operations improves command response latency but
3733 * has drawback of device moving into critical state where the device is
3734 * not-operable. Make sure to call ufshcd_enable_auto_bkops() whenever the
3735 * host is idle so that BKOPS are managed effectively without any negative
3736 * impacts.
3738 * Returns zero on success, non-zero on failure.
3740 static int ufshcd_disable_auto_bkops(struct ufs_hba *hba)
3742 int err = 0;
3744 if (!hba->auto_bkops_enabled)
3745 goto out;
3748 * If host assisted BKOPs is to be enabled, make sure
3749 * urgent bkops exception is allowed.
3751 err = ufshcd_enable_ee(hba, MASK_EE_URGENT_BKOPS);
3752 if (err) {
3753 dev_err(hba->dev, "%s: failed to enable exception event %d\n",
3754 __func__, err);
3755 goto out;
3758 err = ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_CLEAR_FLAG,
3759 QUERY_FLAG_IDN_BKOPS_EN, NULL);
3760 if (err) {
3761 dev_err(hba->dev, "%s: failed to disable bkops %d\n",
3762 __func__, err);
3763 ufshcd_disable_ee(hba, MASK_EE_URGENT_BKOPS);
3764 goto out;
3767 hba->auto_bkops_enabled = false;
3768 out:
3769 return err;
3773 * ufshcd_force_reset_auto_bkops - force enable of auto bkops
3774 * @hba: per adapter instance
3776 * After a device reset the device may toggle the BKOPS_EN flag
3777 * to default value. The s/w tracking variables should be updated
3778 * as well. Do this by forcing enable of auto bkops.
3780 static void ufshcd_force_reset_auto_bkops(struct ufs_hba *hba)
3782 hba->auto_bkops_enabled = false;
3783 hba->ee_ctrl_mask |= MASK_EE_URGENT_BKOPS;
3784 ufshcd_enable_auto_bkops(hba);
3787 static inline int ufshcd_get_bkops_status(struct ufs_hba *hba, u32 *status)
3789 return ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
3790 QUERY_ATTR_IDN_BKOPS_STATUS, 0, 0, status);
3794 * ufshcd_bkops_ctrl - control the auto bkops based on current bkops status
3795 * @hba: per-adapter instance
3796 * @status: bkops_status value
3798 * Read the bkops_status from the UFS device and Enable fBackgroundOpsEn
3799 * flag in the device to permit background operations if the device
3800 * bkops_status is greater than or equal to "status" argument passed to
3801 * this function, disable otherwise.
3803 * Returns 0 for success, non-zero in case of failure.
3805 * NOTE: Caller of this function can check the "hba->auto_bkops_enabled" flag
3806 * to know whether auto bkops is enabled or disabled after this function
3807 * returns control to it.
3809 static int ufshcd_bkops_ctrl(struct ufs_hba *hba,
3810 enum bkops_status status)
3812 int err;
3813 u32 curr_status = 0;
3815 err = ufshcd_get_bkops_status(hba, &curr_status);
3816 if (err) {
3817 dev_err(hba->dev, "%s: failed to get BKOPS status %d\n",
3818 __func__, err);
3819 goto out;
3820 } else if (curr_status > BKOPS_STATUS_MAX) {
3821 dev_err(hba->dev, "%s: invalid BKOPS status %d\n",
3822 __func__, curr_status);
3823 err = -EINVAL;
3824 goto out;
3827 if (curr_status >= status)
3828 err = ufshcd_enable_auto_bkops(hba);
3829 else
3830 err = ufshcd_disable_auto_bkops(hba);
3831 out:
3832 return err;
3836 * ufshcd_urgent_bkops - handle urgent bkops exception event
3837 * @hba: per-adapter instance
3839 * Enable fBackgroundOpsEn flag in the device to permit background
3840 * operations.
3842 * If BKOPs is enabled, this function returns 0, 1 if the bkops in not enabled
3843 * and negative error value for any other failure.
3845 static int ufshcd_urgent_bkops(struct ufs_hba *hba)
3847 return ufshcd_bkops_ctrl(hba, hba->urgent_bkops_lvl);
3850 static inline int ufshcd_get_ee_status(struct ufs_hba *hba, u32 *status)
3852 return ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
3853 QUERY_ATTR_IDN_EE_STATUS, 0, 0, status);
3856 static void ufshcd_bkops_exception_event_handler(struct ufs_hba *hba)
3858 int err;
3859 u32 curr_status = 0;
3861 if (hba->is_urgent_bkops_lvl_checked)
3862 goto enable_auto_bkops;
3864 err = ufshcd_get_bkops_status(hba, &curr_status);
3865 if (err) {
3866 dev_err(hba->dev, "%s: failed to get BKOPS status %d\n",
3867 __func__, err);
3868 goto out;
3872 * We are seeing that some devices are raising the urgent bkops
3873 * exception events even when BKOPS status doesn't indicate performace
3874 * impacted or critical. Handle these device by determining their urgent
3875 * bkops status at runtime.
3877 if (curr_status < BKOPS_STATUS_PERF_IMPACT) {
3878 dev_err(hba->dev, "%s: device raised urgent BKOPS exception for bkops status %d\n",
3879 __func__, curr_status);
3880 /* update the current status as the urgent bkops level */
3881 hba->urgent_bkops_lvl = curr_status;
3882 hba->is_urgent_bkops_lvl_checked = true;
3885 enable_auto_bkops:
3886 err = ufshcd_enable_auto_bkops(hba);
3887 out:
3888 if (err < 0)
3889 dev_err(hba->dev, "%s: failed to handle urgent bkops %d\n",
3890 __func__, err);
3894 * ufshcd_exception_event_handler - handle exceptions raised by device
3895 * @work: pointer to work data
3897 * Read bExceptionEventStatus attribute from the device and handle the
3898 * exception event accordingly.
3900 static void ufshcd_exception_event_handler(struct work_struct *work)
3902 struct ufs_hba *hba;
3903 int err;
3904 u32 status = 0;
3905 hba = container_of(work, struct ufs_hba, eeh_work);
3907 pm_runtime_get_sync(hba->dev);
3908 err = ufshcd_get_ee_status(hba, &status);
3909 if (err) {
3910 dev_err(hba->dev, "%s: failed to get exception status %d\n",
3911 __func__, err);
3912 goto out;
3915 status &= hba->ee_ctrl_mask;
3917 if (status & MASK_EE_URGENT_BKOPS)
3918 ufshcd_bkops_exception_event_handler(hba);
3920 out:
3921 pm_runtime_put_sync(hba->dev);
3922 return;
3925 /* Complete requests that have door-bell cleared */
3926 static void ufshcd_complete_requests(struct ufs_hba *hba)
3928 ufshcd_transfer_req_compl(hba);
3929 ufshcd_tmc_handler(hba);
3933 * ufshcd_quirk_dl_nac_errors - This function checks if error handling is
3934 * to recover from the DL NAC errors or not.
3935 * @hba: per-adapter instance
3937 * Returns true if error handling is required, false otherwise
3939 static bool ufshcd_quirk_dl_nac_errors(struct ufs_hba *hba)
3941 unsigned long flags;
3942 bool err_handling = true;
3944 spin_lock_irqsave(hba->host->host_lock, flags);
3946 * UFS_DEVICE_QUIRK_RECOVERY_FROM_DL_NAC_ERRORS only workaround the
3947 * device fatal error and/or DL NAC & REPLAY timeout errors.
3949 if (hba->saved_err & (CONTROLLER_FATAL_ERROR | SYSTEM_BUS_FATAL_ERROR))
3950 goto out;
3952 if ((hba->saved_err & DEVICE_FATAL_ERROR) ||
3953 ((hba->saved_err & UIC_ERROR) &&
3954 (hba->saved_uic_err & UFSHCD_UIC_DL_TCx_REPLAY_ERROR)))
3955 goto out;
3957 if ((hba->saved_err & UIC_ERROR) &&
3958 (hba->saved_uic_err & UFSHCD_UIC_DL_NAC_RECEIVED_ERROR)) {
3959 int err;
3961 * wait for 50ms to see if we can get any other errors or not.
3963 spin_unlock_irqrestore(hba->host->host_lock, flags);
3964 msleep(50);
3965 spin_lock_irqsave(hba->host->host_lock, flags);
3968 * now check if we have got any other severe errors other than
3969 * DL NAC error?
3971 if ((hba->saved_err & INT_FATAL_ERRORS) ||
3972 ((hba->saved_err & UIC_ERROR) &&
3973 (hba->saved_uic_err & ~UFSHCD_UIC_DL_NAC_RECEIVED_ERROR)))
3974 goto out;
3977 * As DL NAC is the only error received so far, send out NOP
3978 * command to confirm if link is still active or not.
3979 * - If we don't get any response then do error recovery.
3980 * - If we get response then clear the DL NAC error bit.
3983 spin_unlock_irqrestore(hba->host->host_lock, flags);
3984 err = ufshcd_verify_dev_init(hba);
3985 spin_lock_irqsave(hba->host->host_lock, flags);
3987 if (err)
3988 goto out;
3990 /* Link seems to be alive hence ignore the DL NAC errors */
3991 if (hba->saved_uic_err == UFSHCD_UIC_DL_NAC_RECEIVED_ERROR)
3992 hba->saved_err &= ~UIC_ERROR;
3993 /* clear NAC error */
3994 hba->saved_uic_err &= ~UFSHCD_UIC_DL_NAC_RECEIVED_ERROR;
3995 if (!hba->saved_uic_err) {
3996 err_handling = false;
3997 goto out;
4000 out:
4001 spin_unlock_irqrestore(hba->host->host_lock, flags);
4002 return err_handling;
4006 * ufshcd_err_handler - handle UFS errors that require s/w attention
4007 * @work: pointer to work structure
4009 static void ufshcd_err_handler(struct work_struct *work)
4011 struct ufs_hba *hba;
4012 unsigned long flags;
4013 u32 err_xfer = 0;
4014 u32 err_tm = 0;
4015 int err = 0;
4016 int tag;
4017 bool needs_reset = false;
4019 hba = container_of(work, struct ufs_hba, eh_work);
4021 pm_runtime_get_sync(hba->dev);
4022 ufshcd_hold(hba, false);
4024 spin_lock_irqsave(hba->host->host_lock, flags);
4025 if (hba->ufshcd_state == UFSHCD_STATE_RESET)
4026 goto out;
4028 hba->ufshcd_state = UFSHCD_STATE_RESET;
4029 ufshcd_set_eh_in_progress(hba);
4031 /* Complete requests that have door-bell cleared by h/w */
4032 ufshcd_complete_requests(hba);
4034 if (hba->dev_quirks & UFS_DEVICE_QUIRK_RECOVERY_FROM_DL_NAC_ERRORS) {
4035 bool ret;
4037 spin_unlock_irqrestore(hba->host->host_lock, flags);
4038 /* release the lock as ufshcd_quirk_dl_nac_errors() may sleep */
4039 ret = ufshcd_quirk_dl_nac_errors(hba);
4040 spin_lock_irqsave(hba->host->host_lock, flags);
4041 if (!ret)
4042 goto skip_err_handling;
4044 if ((hba->saved_err & INT_FATAL_ERRORS) ||
4045 ((hba->saved_err & UIC_ERROR) &&
4046 (hba->saved_uic_err & (UFSHCD_UIC_DL_PA_INIT_ERROR |
4047 UFSHCD_UIC_DL_NAC_RECEIVED_ERROR |
4048 UFSHCD_UIC_DL_TCx_REPLAY_ERROR))))
4049 needs_reset = true;
4052 * if host reset is required then skip clearing the pending
4053 * transfers forcefully because they will automatically get
4054 * cleared after link startup.
4056 if (needs_reset)
4057 goto skip_pending_xfer_clear;
4059 /* release lock as clear command might sleep */
4060 spin_unlock_irqrestore(hba->host->host_lock, flags);
4061 /* Clear pending transfer requests */
4062 for_each_set_bit(tag, &hba->outstanding_reqs, hba->nutrs) {
4063 if (ufshcd_clear_cmd(hba, tag)) {
4064 err_xfer = true;
4065 goto lock_skip_pending_xfer_clear;
4069 /* Clear pending task management requests */
4070 for_each_set_bit(tag, &hba->outstanding_tasks, hba->nutmrs) {
4071 if (ufshcd_clear_tm_cmd(hba, tag)) {
4072 err_tm = true;
4073 goto lock_skip_pending_xfer_clear;
4077 lock_skip_pending_xfer_clear:
4078 spin_lock_irqsave(hba->host->host_lock, flags);
4080 /* Complete the requests that are cleared by s/w */
4081 ufshcd_complete_requests(hba);
4083 if (err_xfer || err_tm)
4084 needs_reset = true;
4086 skip_pending_xfer_clear:
4087 /* Fatal errors need reset */
4088 if (needs_reset) {
4089 unsigned long max_doorbells = (1UL << hba->nutrs) - 1;
4092 * ufshcd_reset_and_restore() does the link reinitialization
4093 * which will need atleast one empty doorbell slot to send the
4094 * device management commands (NOP and query commands).
4095 * If there is no slot empty at this moment then free up last
4096 * slot forcefully.
4098 if (hba->outstanding_reqs == max_doorbells)
4099 __ufshcd_transfer_req_compl(hba,
4100 (1UL << (hba->nutrs - 1)));
4102 spin_unlock_irqrestore(hba->host->host_lock, flags);
4103 err = ufshcd_reset_and_restore(hba);
4104 spin_lock_irqsave(hba->host->host_lock, flags);
4105 if (err) {
4106 dev_err(hba->dev, "%s: reset and restore failed\n",
4107 __func__);
4108 hba->ufshcd_state = UFSHCD_STATE_ERROR;
4111 * Inform scsi mid-layer that we did reset and allow to handle
4112 * Unit Attention properly.
4114 scsi_report_bus_reset(hba->host, 0);
4115 hba->saved_err = 0;
4116 hba->saved_uic_err = 0;
4119 skip_err_handling:
4120 if (!needs_reset) {
4121 hba->ufshcd_state = UFSHCD_STATE_OPERATIONAL;
4122 if (hba->saved_err || hba->saved_uic_err)
4123 dev_err_ratelimited(hba->dev, "%s: exit: saved_err 0x%x saved_uic_err 0x%x",
4124 __func__, hba->saved_err, hba->saved_uic_err);
4127 ufshcd_clear_eh_in_progress(hba);
4129 out:
4130 spin_unlock_irqrestore(hba->host->host_lock, flags);
4131 scsi_unblock_requests(hba->host);
4132 ufshcd_release(hba);
4133 pm_runtime_put_sync(hba->dev);
4137 * ufshcd_update_uic_error - check and set fatal UIC error flags.
4138 * @hba: per-adapter instance
4140 static void ufshcd_update_uic_error(struct ufs_hba *hba)
4142 u32 reg;
4144 /* PA_INIT_ERROR is fatal and needs UIC reset */
4145 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_DATA_LINK_LAYER);
4146 if (reg & UIC_DATA_LINK_LAYER_ERROR_PA_INIT)
4147 hba->uic_error |= UFSHCD_UIC_DL_PA_INIT_ERROR;
4148 else if (hba->dev_quirks &
4149 UFS_DEVICE_QUIRK_RECOVERY_FROM_DL_NAC_ERRORS) {
4150 if (reg & UIC_DATA_LINK_LAYER_ERROR_NAC_RECEIVED)
4151 hba->uic_error |=
4152 UFSHCD_UIC_DL_NAC_RECEIVED_ERROR;
4153 else if (reg & UIC_DATA_LINK_LAYER_ERROR_TCx_REPLAY_TIMEOUT)
4154 hba->uic_error |= UFSHCD_UIC_DL_TCx_REPLAY_ERROR;
4157 /* UIC NL/TL/DME errors needs software retry */
4158 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_NETWORK_LAYER);
4159 if (reg)
4160 hba->uic_error |= UFSHCD_UIC_NL_ERROR;
4162 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_TRANSPORT_LAYER);
4163 if (reg)
4164 hba->uic_error |= UFSHCD_UIC_TL_ERROR;
4166 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_DME);
4167 if (reg)
4168 hba->uic_error |= UFSHCD_UIC_DME_ERROR;
4170 dev_dbg(hba->dev, "%s: UIC error flags = 0x%08x\n",
4171 __func__, hba->uic_error);
4175 * ufshcd_check_errors - Check for errors that need s/w attention
4176 * @hba: per-adapter instance
4178 static void ufshcd_check_errors(struct ufs_hba *hba)
4180 bool queue_eh_work = false;
4182 if (hba->errors & INT_FATAL_ERRORS)
4183 queue_eh_work = true;
4185 if (hba->errors & UIC_ERROR) {
4186 hba->uic_error = 0;
4187 ufshcd_update_uic_error(hba);
4188 if (hba->uic_error)
4189 queue_eh_work = true;
4192 if (queue_eh_work) {
4194 * update the transfer error masks to sticky bits, let's do this
4195 * irrespective of current ufshcd_state.
4197 hba->saved_err |= hba->errors;
4198 hba->saved_uic_err |= hba->uic_error;
4200 /* handle fatal errors only when link is functional */
4201 if (hba->ufshcd_state == UFSHCD_STATE_OPERATIONAL) {
4202 /* block commands from scsi mid-layer */
4203 scsi_block_requests(hba->host);
4205 hba->ufshcd_state = UFSHCD_STATE_ERROR;
4206 schedule_work(&hba->eh_work);
4210 * if (!queue_eh_work) -
4211 * Other errors are either non-fatal where host recovers
4212 * itself without s/w intervention or errors that will be
4213 * handled by the SCSI core layer.
4218 * ufshcd_tmc_handler - handle task management function completion
4219 * @hba: per adapter instance
4221 static void ufshcd_tmc_handler(struct ufs_hba *hba)
4223 u32 tm_doorbell;
4225 tm_doorbell = ufshcd_readl(hba, REG_UTP_TASK_REQ_DOOR_BELL);
4226 hba->tm_condition = tm_doorbell ^ hba->outstanding_tasks;
4227 wake_up(&hba->tm_wq);
4231 * ufshcd_sl_intr - Interrupt service routine
4232 * @hba: per adapter instance
4233 * @intr_status: contains interrupts generated by the controller
4235 static void ufshcd_sl_intr(struct ufs_hba *hba, u32 intr_status)
4237 hba->errors = UFSHCD_ERROR_MASK & intr_status;
4238 if (hba->errors)
4239 ufshcd_check_errors(hba);
4241 if (intr_status & UFSHCD_UIC_MASK)
4242 ufshcd_uic_cmd_compl(hba, intr_status);
4244 if (intr_status & UTP_TASK_REQ_COMPL)
4245 ufshcd_tmc_handler(hba);
4247 if (intr_status & UTP_TRANSFER_REQ_COMPL)
4248 ufshcd_transfer_req_compl(hba);
4252 * ufshcd_intr - Main interrupt service routine
4253 * @irq: irq number
4254 * @__hba: pointer to adapter instance
4256 * Returns IRQ_HANDLED - If interrupt is valid
4257 * IRQ_NONE - If invalid interrupt
4259 static irqreturn_t ufshcd_intr(int irq, void *__hba)
4261 u32 intr_status, enabled_intr_status;
4262 irqreturn_t retval = IRQ_NONE;
4263 struct ufs_hba *hba = __hba;
4265 spin_lock(hba->host->host_lock);
4266 intr_status = ufshcd_readl(hba, REG_INTERRUPT_STATUS);
4267 enabled_intr_status =
4268 intr_status & ufshcd_readl(hba, REG_INTERRUPT_ENABLE);
4270 if (intr_status)
4271 ufshcd_writel(hba, intr_status, REG_INTERRUPT_STATUS);
4273 if (enabled_intr_status) {
4274 ufshcd_sl_intr(hba, enabled_intr_status);
4275 retval = IRQ_HANDLED;
4277 spin_unlock(hba->host->host_lock);
4278 return retval;
4281 static int ufshcd_clear_tm_cmd(struct ufs_hba *hba, int tag)
4283 int err = 0;
4284 u32 mask = 1 << tag;
4285 unsigned long flags;
4287 if (!test_bit(tag, &hba->outstanding_tasks))
4288 goto out;
4290 spin_lock_irqsave(hba->host->host_lock, flags);
4291 ufshcd_writel(hba, ~(1 << tag), REG_UTP_TASK_REQ_LIST_CLEAR);
4292 spin_unlock_irqrestore(hba->host->host_lock, flags);
4294 /* poll for max. 1 sec to clear door bell register by h/w */
4295 err = ufshcd_wait_for_register(hba,
4296 REG_UTP_TASK_REQ_DOOR_BELL,
4297 mask, 0, 1000, 1000, true);
4298 out:
4299 return err;
4303 * ufshcd_issue_tm_cmd - issues task management commands to controller
4304 * @hba: per adapter instance
4305 * @lun_id: LUN ID to which TM command is sent
4306 * @task_id: task ID to which the TM command is applicable
4307 * @tm_function: task management function opcode
4308 * @tm_response: task management service response return value
4310 * Returns non-zero value on error, zero on success.
4312 static int ufshcd_issue_tm_cmd(struct ufs_hba *hba, int lun_id, int task_id,
4313 u8 tm_function, u8 *tm_response)
4315 struct utp_task_req_desc *task_req_descp;
4316 struct utp_upiu_task_req *task_req_upiup;
4317 struct Scsi_Host *host;
4318 unsigned long flags;
4319 int free_slot;
4320 int err;
4321 int task_tag;
4323 host = hba->host;
4326 * Get free slot, sleep if slots are unavailable.
4327 * Even though we use wait_event() which sleeps indefinitely,
4328 * the maximum wait time is bounded by %TM_CMD_TIMEOUT.
4330 wait_event(hba->tm_tag_wq, ufshcd_get_tm_free_slot(hba, &free_slot));
4331 ufshcd_hold(hba, false);
4333 spin_lock_irqsave(host->host_lock, flags);
4334 task_req_descp = hba->utmrdl_base_addr;
4335 task_req_descp += free_slot;
4337 /* Configure task request descriptor */
4338 task_req_descp->header.dword_0 = cpu_to_le32(UTP_REQ_DESC_INT_CMD);
4339 task_req_descp->header.dword_2 =
4340 cpu_to_le32(OCS_INVALID_COMMAND_STATUS);
4342 /* Configure task request UPIU */
4343 task_req_upiup =
4344 (struct utp_upiu_task_req *) task_req_descp->task_req_upiu;
4345 task_tag = hba->nutrs + free_slot;
4346 task_req_upiup->header.dword_0 =
4347 UPIU_HEADER_DWORD(UPIU_TRANSACTION_TASK_REQ, 0,
4348 lun_id, task_tag);
4349 task_req_upiup->header.dword_1 =
4350 UPIU_HEADER_DWORD(0, tm_function, 0, 0);
4352 * The host shall provide the same value for LUN field in the basic
4353 * header and for Input Parameter.
4355 task_req_upiup->input_param1 = cpu_to_be32(lun_id);
4356 task_req_upiup->input_param2 = cpu_to_be32(task_id);
4358 /* send command to the controller */
4359 __set_bit(free_slot, &hba->outstanding_tasks);
4361 /* Make sure descriptors are ready before ringing the task doorbell */
4362 wmb();
4364 ufshcd_writel(hba, 1 << free_slot, REG_UTP_TASK_REQ_DOOR_BELL);
4365 /* Make sure that doorbell is committed immediately */
4366 wmb();
4368 spin_unlock_irqrestore(host->host_lock, flags);
4370 /* wait until the task management command is completed */
4371 err = wait_event_timeout(hba->tm_wq,
4372 test_bit(free_slot, &hba->tm_condition),
4373 msecs_to_jiffies(TM_CMD_TIMEOUT));
4374 if (!err) {
4375 dev_err(hba->dev, "%s: task management cmd 0x%.2x timed-out\n",
4376 __func__, tm_function);
4377 if (ufshcd_clear_tm_cmd(hba, free_slot))
4378 dev_WARN(hba->dev, "%s: unable clear tm cmd (slot %d) after timeout\n",
4379 __func__, free_slot);
4380 err = -ETIMEDOUT;
4381 } else {
4382 err = ufshcd_task_req_compl(hba, free_slot, tm_response);
4385 clear_bit(free_slot, &hba->tm_condition);
4386 ufshcd_put_tm_slot(hba, free_slot);
4387 wake_up(&hba->tm_tag_wq);
4389 ufshcd_release(hba);
4390 return err;
4394 * ufshcd_eh_device_reset_handler - device reset handler registered to
4395 * scsi layer.
4396 * @cmd: SCSI command pointer
4398 * Returns SUCCESS/FAILED
4400 static int ufshcd_eh_device_reset_handler(struct scsi_cmnd *cmd)
4402 struct Scsi_Host *host;
4403 struct ufs_hba *hba;
4404 unsigned int tag;
4405 u32 pos;
4406 int err;
4407 u8 resp = 0xF;
4408 struct ufshcd_lrb *lrbp;
4409 unsigned long flags;
4411 host = cmd->device->host;
4412 hba = shost_priv(host);
4413 tag = cmd->request->tag;
4415 lrbp = &hba->lrb[tag];
4416 err = ufshcd_issue_tm_cmd(hba, lrbp->lun, 0, UFS_LOGICAL_RESET, &resp);
4417 if (err || resp != UPIU_TASK_MANAGEMENT_FUNC_COMPL) {
4418 if (!err)
4419 err = resp;
4420 goto out;
4423 /* clear the commands that were pending for corresponding LUN */
4424 for_each_set_bit(pos, &hba->outstanding_reqs, hba->nutrs) {
4425 if (hba->lrb[pos].lun == lrbp->lun) {
4426 err = ufshcd_clear_cmd(hba, pos);
4427 if (err)
4428 break;
4431 spin_lock_irqsave(host->host_lock, flags);
4432 ufshcd_transfer_req_compl(hba);
4433 spin_unlock_irqrestore(host->host_lock, flags);
4434 out:
4435 if (!err) {
4436 err = SUCCESS;
4437 } else {
4438 dev_err(hba->dev, "%s: failed with err %d\n", __func__, err);
4439 err = FAILED;
4441 return err;
4445 * ufshcd_abort - abort a specific command
4446 * @cmd: SCSI command pointer
4448 * Abort the pending command in device by sending UFS_ABORT_TASK task management
4449 * command, and in host controller by clearing the door-bell register. There can
4450 * be race between controller sending the command to the device while abort is
4451 * issued. To avoid that, first issue UFS_QUERY_TASK to check if the command is
4452 * really issued and then try to abort it.
4454 * Returns SUCCESS/FAILED
4456 static int ufshcd_abort(struct scsi_cmnd *cmd)
4458 struct Scsi_Host *host;
4459 struct ufs_hba *hba;
4460 unsigned long flags;
4461 unsigned int tag;
4462 int err = 0;
4463 int poll_cnt;
4464 u8 resp = 0xF;
4465 struct ufshcd_lrb *lrbp;
4466 u32 reg;
4468 host = cmd->device->host;
4469 hba = shost_priv(host);
4470 tag = cmd->request->tag;
4471 if (!ufshcd_valid_tag(hba, tag)) {
4472 dev_err(hba->dev,
4473 "%s: invalid command tag %d: cmd=0x%p, cmd->request=0x%p",
4474 __func__, tag, cmd, cmd->request);
4475 BUG();
4478 ufshcd_hold(hba, false);
4479 reg = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
4480 /* If command is already aborted/completed, return SUCCESS */
4481 if (!(test_bit(tag, &hba->outstanding_reqs))) {
4482 dev_err(hba->dev,
4483 "%s: cmd at tag %d already completed, outstanding=0x%lx, doorbell=0x%x\n",
4484 __func__, tag, hba->outstanding_reqs, reg);
4485 goto out;
4488 if (!(reg & (1 << tag))) {
4489 dev_err(hba->dev,
4490 "%s: cmd was completed, but without a notifying intr, tag = %d",
4491 __func__, tag);
4494 lrbp = &hba->lrb[tag];
4495 for (poll_cnt = 100; poll_cnt; poll_cnt--) {
4496 err = ufshcd_issue_tm_cmd(hba, lrbp->lun, lrbp->task_tag,
4497 UFS_QUERY_TASK, &resp);
4498 if (!err && resp == UPIU_TASK_MANAGEMENT_FUNC_SUCCEEDED) {
4499 /* cmd pending in the device */
4500 break;
4501 } else if (!err && resp == UPIU_TASK_MANAGEMENT_FUNC_COMPL) {
4503 * cmd not pending in the device, check if it is
4504 * in transition.
4506 reg = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
4507 if (reg & (1 << tag)) {
4508 /* sleep for max. 200us to stabilize */
4509 usleep_range(100, 200);
4510 continue;
4512 /* command completed already */
4513 goto out;
4514 } else {
4515 if (!err)
4516 err = resp; /* service response error */
4517 goto out;
4521 if (!poll_cnt) {
4522 err = -EBUSY;
4523 goto out;
4526 err = ufshcd_issue_tm_cmd(hba, lrbp->lun, lrbp->task_tag,
4527 UFS_ABORT_TASK, &resp);
4528 if (err || resp != UPIU_TASK_MANAGEMENT_FUNC_COMPL) {
4529 if (!err)
4530 err = resp; /* service response error */
4531 goto out;
4534 err = ufshcd_clear_cmd(hba, tag);
4535 if (err)
4536 goto out;
4538 scsi_dma_unmap(cmd);
4540 spin_lock_irqsave(host->host_lock, flags);
4541 ufshcd_outstanding_req_clear(hba, tag);
4542 hba->lrb[tag].cmd = NULL;
4543 spin_unlock_irqrestore(host->host_lock, flags);
4545 clear_bit_unlock(tag, &hba->lrb_in_use);
4546 wake_up(&hba->dev_cmd.tag_wq);
4548 out:
4549 if (!err) {
4550 err = SUCCESS;
4551 } else {
4552 dev_err(hba->dev, "%s: failed with err %d\n", __func__, err);
4553 err = FAILED;
4557 * This ufshcd_release() corresponds to the original scsi cmd that got
4558 * aborted here (as we won't get any IRQ for it).
4560 ufshcd_release(hba);
4561 return err;
4565 * ufshcd_host_reset_and_restore - reset and restore host controller
4566 * @hba: per-adapter instance
4568 * Note that host controller reset may issue DME_RESET to
4569 * local and remote (device) Uni-Pro stack and the attributes
4570 * are reset to default state.
4572 * Returns zero on success, non-zero on failure
4574 static int ufshcd_host_reset_and_restore(struct ufs_hba *hba)
4576 int err;
4577 unsigned long flags;
4579 /* Reset the host controller */
4580 spin_lock_irqsave(hba->host->host_lock, flags);
4581 ufshcd_hba_stop(hba, false);
4582 spin_unlock_irqrestore(hba->host->host_lock, flags);
4584 err = ufshcd_hba_enable(hba);
4585 if (err)
4586 goto out;
4588 /* Establish the link again and restore the device */
4589 err = ufshcd_probe_hba(hba);
4591 if (!err && (hba->ufshcd_state != UFSHCD_STATE_OPERATIONAL))
4592 err = -EIO;
4593 out:
4594 if (err)
4595 dev_err(hba->dev, "%s: Host init failed %d\n", __func__, err);
4597 return err;
4601 * ufshcd_reset_and_restore - reset and re-initialize host/device
4602 * @hba: per-adapter instance
4604 * Reset and recover device, host and re-establish link. This
4605 * is helpful to recover the communication in fatal error conditions.
4607 * Returns zero on success, non-zero on failure
4609 static int ufshcd_reset_and_restore(struct ufs_hba *hba)
4611 int err = 0;
4612 unsigned long flags;
4613 int retries = MAX_HOST_RESET_RETRIES;
4615 do {
4616 err = ufshcd_host_reset_and_restore(hba);
4617 } while (err && --retries);
4620 * After reset the door-bell might be cleared, complete
4621 * outstanding requests in s/w here.
4623 spin_lock_irqsave(hba->host->host_lock, flags);
4624 ufshcd_transfer_req_compl(hba);
4625 ufshcd_tmc_handler(hba);
4626 spin_unlock_irqrestore(hba->host->host_lock, flags);
4628 return err;
4632 * ufshcd_eh_host_reset_handler - host reset handler registered to scsi layer
4633 * @cmd - SCSI command pointer
4635 * Returns SUCCESS/FAILED
4637 static int ufshcd_eh_host_reset_handler(struct scsi_cmnd *cmd)
4639 int err;
4640 unsigned long flags;
4641 struct ufs_hba *hba;
4643 hba = shost_priv(cmd->device->host);
4645 ufshcd_hold(hba, false);
4647 * Check if there is any race with fatal error handling.
4648 * If so, wait for it to complete. Even though fatal error
4649 * handling does reset and restore in some cases, don't assume
4650 * anything out of it. We are just avoiding race here.
4652 do {
4653 spin_lock_irqsave(hba->host->host_lock, flags);
4654 if (!(work_pending(&hba->eh_work) ||
4655 hba->ufshcd_state == UFSHCD_STATE_RESET))
4656 break;
4657 spin_unlock_irqrestore(hba->host->host_lock, flags);
4658 dev_dbg(hba->dev, "%s: reset in progress\n", __func__);
4659 flush_work(&hba->eh_work);
4660 } while (1);
4662 hba->ufshcd_state = UFSHCD_STATE_RESET;
4663 ufshcd_set_eh_in_progress(hba);
4664 spin_unlock_irqrestore(hba->host->host_lock, flags);
4666 err = ufshcd_reset_and_restore(hba);
4668 spin_lock_irqsave(hba->host->host_lock, flags);
4669 if (!err) {
4670 err = SUCCESS;
4671 hba->ufshcd_state = UFSHCD_STATE_OPERATIONAL;
4672 } else {
4673 err = FAILED;
4674 hba->ufshcd_state = UFSHCD_STATE_ERROR;
4676 ufshcd_clear_eh_in_progress(hba);
4677 spin_unlock_irqrestore(hba->host->host_lock, flags);
4679 ufshcd_release(hba);
4680 return err;
4684 * ufshcd_get_max_icc_level - calculate the ICC level
4685 * @sup_curr_uA: max. current supported by the regulator
4686 * @start_scan: row at the desc table to start scan from
4687 * @buff: power descriptor buffer
4689 * Returns calculated max ICC level for specific regulator
4691 static u32 ufshcd_get_max_icc_level(int sup_curr_uA, u32 start_scan, char *buff)
4693 int i;
4694 int curr_uA;
4695 u16 data;
4696 u16 unit;
4698 for (i = start_scan; i >= 0; i--) {
4699 data = be16_to_cpu(*((u16 *)(buff + 2*i)));
4700 unit = (data & ATTR_ICC_LVL_UNIT_MASK) >>
4701 ATTR_ICC_LVL_UNIT_OFFSET;
4702 curr_uA = data & ATTR_ICC_LVL_VALUE_MASK;
4703 switch (unit) {
4704 case UFSHCD_NANO_AMP:
4705 curr_uA = curr_uA / 1000;
4706 break;
4707 case UFSHCD_MILI_AMP:
4708 curr_uA = curr_uA * 1000;
4709 break;
4710 case UFSHCD_AMP:
4711 curr_uA = curr_uA * 1000 * 1000;
4712 break;
4713 case UFSHCD_MICRO_AMP:
4714 default:
4715 break;
4717 if (sup_curr_uA >= curr_uA)
4718 break;
4720 if (i < 0) {
4721 i = 0;
4722 pr_err("%s: Couldn't find valid icc_level = %d", __func__, i);
4725 return (u32)i;
4729 * ufshcd_calc_icc_level - calculate the max ICC level
4730 * In case regulators are not initialized we'll return 0
4731 * @hba: per-adapter instance
4732 * @desc_buf: power descriptor buffer to extract ICC levels from.
4733 * @len: length of desc_buff
4735 * Returns calculated ICC level
4737 static u32 ufshcd_find_max_sup_active_icc_level(struct ufs_hba *hba,
4738 u8 *desc_buf, int len)
4740 u32 icc_level = 0;
4742 if (!hba->vreg_info.vcc || !hba->vreg_info.vccq ||
4743 !hba->vreg_info.vccq2) {
4744 dev_err(hba->dev,
4745 "%s: Regulator capability was not set, actvIccLevel=%d",
4746 __func__, icc_level);
4747 goto out;
4750 if (hba->vreg_info.vcc)
4751 icc_level = ufshcd_get_max_icc_level(
4752 hba->vreg_info.vcc->max_uA,
4753 POWER_DESC_MAX_ACTV_ICC_LVLS - 1,
4754 &desc_buf[PWR_DESC_ACTIVE_LVLS_VCC_0]);
4756 if (hba->vreg_info.vccq)
4757 icc_level = ufshcd_get_max_icc_level(
4758 hba->vreg_info.vccq->max_uA,
4759 icc_level,
4760 &desc_buf[PWR_DESC_ACTIVE_LVLS_VCCQ_0]);
4762 if (hba->vreg_info.vccq2)
4763 icc_level = ufshcd_get_max_icc_level(
4764 hba->vreg_info.vccq2->max_uA,
4765 icc_level,
4766 &desc_buf[PWR_DESC_ACTIVE_LVLS_VCCQ2_0]);
4767 out:
4768 return icc_level;
4771 static void ufshcd_init_icc_levels(struct ufs_hba *hba)
4773 int ret;
4774 int buff_len = QUERY_DESC_POWER_MAX_SIZE;
4775 u8 desc_buf[QUERY_DESC_POWER_MAX_SIZE];
4777 ret = ufshcd_read_power_desc(hba, desc_buf, buff_len);
4778 if (ret) {
4779 dev_err(hba->dev,
4780 "%s: Failed reading power descriptor.len = %d ret = %d",
4781 __func__, buff_len, ret);
4782 return;
4785 hba->init_prefetch_data.icc_level =
4786 ufshcd_find_max_sup_active_icc_level(hba,
4787 desc_buf, buff_len);
4788 dev_dbg(hba->dev, "%s: setting icc_level 0x%x",
4789 __func__, hba->init_prefetch_data.icc_level);
4791 ret = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_WRITE_ATTR,
4792 QUERY_ATTR_IDN_ACTIVE_ICC_LVL, 0, 0,
4793 &hba->init_prefetch_data.icc_level);
4795 if (ret)
4796 dev_err(hba->dev,
4797 "%s: Failed configuring bActiveICCLevel = %d ret = %d",
4798 __func__, hba->init_prefetch_data.icc_level , ret);
4803 * ufshcd_scsi_add_wlus - Adds required W-LUs
4804 * @hba: per-adapter instance
4806 * UFS device specification requires the UFS devices to support 4 well known
4807 * logical units:
4808 * "REPORT_LUNS" (address: 01h)
4809 * "UFS Device" (address: 50h)
4810 * "RPMB" (address: 44h)
4811 * "BOOT" (address: 30h)
4812 * UFS device's power management needs to be controlled by "POWER CONDITION"
4813 * field of SSU (START STOP UNIT) command. But this "power condition" field
4814 * will take effect only when its sent to "UFS device" well known logical unit
4815 * hence we require the scsi_device instance to represent this logical unit in
4816 * order for the UFS host driver to send the SSU command for power management.
4818 * We also require the scsi_device instance for "RPMB" (Replay Protected Memory
4819 * Block) LU so user space process can control this LU. User space may also
4820 * want to have access to BOOT LU.
4822 * This function adds scsi device instances for each of all well known LUs
4823 * (except "REPORT LUNS" LU).
4825 * Returns zero on success (all required W-LUs are added successfully),
4826 * non-zero error value on failure (if failed to add any of the required W-LU).
4828 static int ufshcd_scsi_add_wlus(struct ufs_hba *hba)
4830 int ret = 0;
4831 struct scsi_device *sdev_rpmb;
4832 struct scsi_device *sdev_boot;
4834 hba->sdev_ufs_device = __scsi_add_device(hba->host, 0, 0,
4835 ufshcd_upiu_wlun_to_scsi_wlun(UFS_UPIU_UFS_DEVICE_WLUN), NULL);
4836 if (IS_ERR(hba->sdev_ufs_device)) {
4837 ret = PTR_ERR(hba->sdev_ufs_device);
4838 hba->sdev_ufs_device = NULL;
4839 goto out;
4841 scsi_device_put(hba->sdev_ufs_device);
4843 sdev_boot = __scsi_add_device(hba->host, 0, 0,
4844 ufshcd_upiu_wlun_to_scsi_wlun(UFS_UPIU_BOOT_WLUN), NULL);
4845 if (IS_ERR(sdev_boot)) {
4846 ret = PTR_ERR(sdev_boot);
4847 goto remove_sdev_ufs_device;
4849 scsi_device_put(sdev_boot);
4851 sdev_rpmb = __scsi_add_device(hba->host, 0, 0,
4852 ufshcd_upiu_wlun_to_scsi_wlun(UFS_UPIU_RPMB_WLUN), NULL);
4853 if (IS_ERR(sdev_rpmb)) {
4854 ret = PTR_ERR(sdev_rpmb);
4855 goto remove_sdev_boot;
4857 scsi_device_put(sdev_rpmb);
4858 goto out;
4860 remove_sdev_boot:
4861 scsi_remove_device(sdev_boot);
4862 remove_sdev_ufs_device:
4863 scsi_remove_device(hba->sdev_ufs_device);
4864 out:
4865 return ret;
4868 static int ufs_get_device_info(struct ufs_hba *hba,
4869 struct ufs_device_info *card_data)
4871 int err;
4872 u8 model_index;
4873 u8 str_desc_buf[QUERY_DESC_STRING_MAX_SIZE + 1] = {0};
4874 u8 desc_buf[QUERY_DESC_DEVICE_MAX_SIZE];
4876 err = ufshcd_read_device_desc(hba, desc_buf,
4877 QUERY_DESC_DEVICE_MAX_SIZE);
4878 if (err) {
4879 dev_err(hba->dev, "%s: Failed reading Device Desc. err = %d\n",
4880 __func__, err);
4881 goto out;
4885 * getting vendor (manufacturerID) and Bank Index in big endian
4886 * format
4888 card_data->wmanufacturerid = desc_buf[DEVICE_DESC_PARAM_MANF_ID] << 8 |
4889 desc_buf[DEVICE_DESC_PARAM_MANF_ID + 1];
4891 model_index = desc_buf[DEVICE_DESC_PARAM_PRDCT_NAME];
4893 err = ufshcd_read_string_desc(hba, model_index, str_desc_buf,
4894 QUERY_DESC_STRING_MAX_SIZE, ASCII_STD);
4895 if (err) {
4896 dev_err(hba->dev, "%s: Failed reading Product Name. err = %d\n",
4897 __func__, err);
4898 goto out;
4901 str_desc_buf[QUERY_DESC_STRING_MAX_SIZE] = '\0';
4902 strlcpy(card_data->model, (str_desc_buf + QUERY_DESC_HDR_SIZE),
4903 min_t(u8, str_desc_buf[QUERY_DESC_LENGTH_OFFSET],
4904 MAX_MODEL_LEN));
4906 /* Null terminate the model string */
4907 card_data->model[MAX_MODEL_LEN] = '\0';
4909 out:
4910 return err;
4913 void ufs_advertise_fixup_device(struct ufs_hba *hba)
4915 int err;
4916 struct ufs_dev_fix *f;
4917 struct ufs_device_info card_data;
4919 card_data.wmanufacturerid = 0;
4921 err = ufs_get_device_info(hba, &card_data);
4922 if (err) {
4923 dev_err(hba->dev, "%s: Failed getting device info. err = %d\n",
4924 __func__, err);
4925 return;
4928 for (f = ufs_fixups; f->quirk; f++) {
4929 if (((f->card.wmanufacturerid == card_data.wmanufacturerid) ||
4930 (f->card.wmanufacturerid == UFS_ANY_VENDOR)) &&
4931 (STR_PRFX_EQUAL(f->card.model, card_data.model) ||
4932 !strcmp(f->card.model, UFS_ANY_MODEL)))
4933 hba->dev_quirks |= f->quirk;
4938 * ufshcd_tune_pa_tactivate - Tunes PA_TActivate of local UniPro
4939 * @hba: per-adapter instance
4941 * PA_TActivate parameter can be tuned manually if UniPro version is less than
4942 * 1.61. PA_TActivate needs to be greater than or equal to peerM-PHY's
4943 * RX_MIN_ACTIVATETIME_CAPABILITY attribute. This optimal value can help reduce
4944 * the hibern8 exit latency.
4946 * Returns zero on success, non-zero error value on failure.
4948 static int ufshcd_tune_pa_tactivate(struct ufs_hba *hba)
4950 int ret = 0;
4951 u32 peer_rx_min_activatetime = 0, tuned_pa_tactivate;
4953 ret = ufshcd_dme_peer_get(hba,
4954 UIC_ARG_MIB_SEL(
4955 RX_MIN_ACTIVATETIME_CAPABILITY,
4956 UIC_ARG_MPHY_RX_GEN_SEL_INDEX(0)),
4957 &peer_rx_min_activatetime);
4958 if (ret)
4959 goto out;
4961 /* make sure proper unit conversion is applied */
4962 tuned_pa_tactivate =
4963 ((peer_rx_min_activatetime * RX_MIN_ACTIVATETIME_UNIT_US)
4964 / PA_TACTIVATE_TIME_UNIT_US);
4965 ret = ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TACTIVATE),
4966 tuned_pa_tactivate);
4968 out:
4969 return ret;
4973 * ufshcd_tune_pa_hibern8time - Tunes PA_Hibern8Time of local UniPro
4974 * @hba: per-adapter instance
4976 * PA_Hibern8Time parameter can be tuned manually if UniPro version is less than
4977 * 1.61. PA_Hibern8Time needs to be maximum of local M-PHY's
4978 * TX_HIBERN8TIME_CAPABILITY & peer M-PHY's RX_HIBERN8TIME_CAPABILITY.
4979 * This optimal value can help reduce the hibern8 exit latency.
4981 * Returns zero on success, non-zero error value on failure.
4983 static int ufshcd_tune_pa_hibern8time(struct ufs_hba *hba)
4985 int ret = 0;
4986 u32 local_tx_hibern8_time_cap = 0, peer_rx_hibern8_time_cap = 0;
4987 u32 max_hibern8_time, tuned_pa_hibern8time;
4989 ret = ufshcd_dme_get(hba,
4990 UIC_ARG_MIB_SEL(TX_HIBERN8TIME_CAPABILITY,
4991 UIC_ARG_MPHY_TX_GEN_SEL_INDEX(0)),
4992 &local_tx_hibern8_time_cap);
4993 if (ret)
4994 goto out;
4996 ret = ufshcd_dme_peer_get(hba,
4997 UIC_ARG_MIB_SEL(RX_HIBERN8TIME_CAPABILITY,
4998 UIC_ARG_MPHY_RX_GEN_SEL_INDEX(0)),
4999 &peer_rx_hibern8_time_cap);
5000 if (ret)
5001 goto out;
5003 max_hibern8_time = max(local_tx_hibern8_time_cap,
5004 peer_rx_hibern8_time_cap);
5005 /* make sure proper unit conversion is applied */
5006 tuned_pa_hibern8time = ((max_hibern8_time * HIBERN8TIME_UNIT_US)
5007 / PA_HIBERN8_TIME_UNIT_US);
5008 ret = ufshcd_dme_set(hba, UIC_ARG_MIB(PA_HIBERN8TIME),
5009 tuned_pa_hibern8time);
5010 out:
5011 return ret;
5014 static void ufshcd_tune_unipro_params(struct ufs_hba *hba)
5016 if (ufshcd_is_unipro_pa_params_tuning_req(hba)) {
5017 ufshcd_tune_pa_tactivate(hba);
5018 ufshcd_tune_pa_hibern8time(hba);
5021 if (hba->dev_quirks & UFS_DEVICE_QUIRK_PA_TACTIVATE)
5022 /* set 1ms timeout for PA_TACTIVATE */
5023 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TACTIVATE), 10);
5027 * ufshcd_probe_hba - probe hba to detect device and initialize
5028 * @hba: per-adapter instance
5030 * Execute link-startup and verify device initialization
5032 static int ufshcd_probe_hba(struct ufs_hba *hba)
5034 int ret;
5036 ret = ufshcd_link_startup(hba);
5037 if (ret)
5038 goto out;
5040 ufshcd_init_pwr_info(hba);
5042 /* set the default level for urgent bkops */
5043 hba->urgent_bkops_lvl = BKOPS_STATUS_PERF_IMPACT;
5044 hba->is_urgent_bkops_lvl_checked = false;
5046 /* UniPro link is active now */
5047 ufshcd_set_link_active(hba);
5049 ret = ufshcd_verify_dev_init(hba);
5050 if (ret)
5051 goto out;
5053 ret = ufshcd_complete_dev_init(hba);
5054 if (ret)
5055 goto out;
5057 ufs_advertise_fixup_device(hba);
5058 ufshcd_tune_unipro_params(hba);
5060 ret = ufshcd_set_vccq_rail_unused(hba,
5061 (hba->dev_quirks & UFS_DEVICE_NO_VCCQ) ? true : false);
5062 if (ret)
5063 goto out;
5065 /* UFS device is also active now */
5066 ufshcd_set_ufs_dev_active(hba);
5067 ufshcd_force_reset_auto_bkops(hba);
5068 hba->wlun_dev_clr_ua = true;
5070 if (ufshcd_get_max_pwr_mode(hba)) {
5071 dev_err(hba->dev,
5072 "%s: Failed getting max supported power mode\n",
5073 __func__);
5074 } else {
5075 ret = ufshcd_config_pwr_mode(hba, &hba->max_pwr_info.info);
5076 if (ret) {
5077 dev_err(hba->dev, "%s: Failed setting power mode, err = %d\n",
5078 __func__, ret);
5079 goto out;
5083 /* set the state as operational after switching to desired gear */
5084 hba->ufshcd_state = UFSHCD_STATE_OPERATIONAL;
5086 * If we are in error handling context or in power management callbacks
5087 * context, no need to scan the host
5089 if (!ufshcd_eh_in_progress(hba) && !hba->pm_op_in_progress) {
5090 bool flag;
5092 /* clear any previous UFS device information */
5093 memset(&hba->dev_info, 0, sizeof(hba->dev_info));
5094 if (!ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_READ_FLAG,
5095 QUERY_FLAG_IDN_PWR_ON_WPE, &flag))
5096 hba->dev_info.f_power_on_wp_en = flag;
5098 if (!hba->is_init_prefetch)
5099 ufshcd_init_icc_levels(hba);
5101 /* Add required well known logical units to scsi mid layer */
5102 if (ufshcd_scsi_add_wlus(hba))
5103 goto out;
5105 scsi_scan_host(hba->host);
5106 pm_runtime_put_sync(hba->dev);
5109 if (!hba->is_init_prefetch)
5110 hba->is_init_prefetch = true;
5112 /* Resume devfreq after UFS device is detected */
5113 ufshcd_resume_clkscaling(hba);
5115 out:
5117 * If we failed to initialize the device or the device is not
5118 * present, turn off the power/clocks etc.
5120 if (ret && !ufshcd_eh_in_progress(hba) && !hba->pm_op_in_progress) {
5121 pm_runtime_put_sync(hba->dev);
5122 ufshcd_hba_exit(hba);
5125 return ret;
5129 * ufshcd_async_scan - asynchronous execution for probing hba
5130 * @data: data pointer to pass to this function
5131 * @cookie: cookie data
5133 static void ufshcd_async_scan(void *data, async_cookie_t cookie)
5135 struct ufs_hba *hba = (struct ufs_hba *)data;
5137 ufshcd_probe_hba(hba);
5140 static enum blk_eh_timer_return ufshcd_eh_timed_out(struct scsi_cmnd *scmd)
5142 unsigned long flags;
5143 struct Scsi_Host *host;
5144 struct ufs_hba *hba;
5145 int index;
5146 bool found = false;
5148 if (!scmd || !scmd->device || !scmd->device->host)
5149 return BLK_EH_NOT_HANDLED;
5151 host = scmd->device->host;
5152 hba = shost_priv(host);
5153 if (!hba)
5154 return BLK_EH_NOT_HANDLED;
5156 spin_lock_irqsave(host->host_lock, flags);
5158 for_each_set_bit(index, &hba->outstanding_reqs, hba->nutrs) {
5159 if (hba->lrb[index].cmd == scmd) {
5160 found = true;
5161 break;
5165 spin_unlock_irqrestore(host->host_lock, flags);
5168 * Bypass SCSI error handling and reset the block layer timer if this
5169 * SCSI command was not actually dispatched to UFS driver, otherwise
5170 * let SCSI layer handle the error as usual.
5172 return found ? BLK_EH_NOT_HANDLED : BLK_EH_RESET_TIMER;
5175 static struct scsi_host_template ufshcd_driver_template = {
5176 .module = THIS_MODULE,
5177 .name = UFSHCD,
5178 .proc_name = UFSHCD,
5179 .queuecommand = ufshcd_queuecommand,
5180 .slave_alloc = ufshcd_slave_alloc,
5181 .slave_configure = ufshcd_slave_configure,
5182 .slave_destroy = ufshcd_slave_destroy,
5183 .change_queue_depth = ufshcd_change_queue_depth,
5184 .eh_abort_handler = ufshcd_abort,
5185 .eh_device_reset_handler = ufshcd_eh_device_reset_handler,
5186 .eh_host_reset_handler = ufshcd_eh_host_reset_handler,
5187 .eh_timed_out = ufshcd_eh_timed_out,
5188 .this_id = -1,
5189 .sg_tablesize = SG_ALL,
5190 .cmd_per_lun = UFSHCD_CMD_PER_LUN,
5191 .can_queue = UFSHCD_CAN_QUEUE,
5192 .max_host_blocked = 1,
5193 .track_queue_depth = 1,
5196 static int ufshcd_config_vreg_load(struct device *dev, struct ufs_vreg *vreg,
5197 int ua)
5199 int ret;
5201 if (!vreg)
5202 return 0;
5204 ret = regulator_set_load(vreg->reg, ua);
5205 if (ret < 0) {
5206 dev_err(dev, "%s: %s set load (ua=%d) failed, err=%d\n",
5207 __func__, vreg->name, ua, ret);
5210 return ret;
5213 static inline int ufshcd_config_vreg_lpm(struct ufs_hba *hba,
5214 struct ufs_vreg *vreg)
5216 if (!vreg)
5217 return 0;
5218 else if (vreg->unused)
5219 return 0;
5220 else
5221 return ufshcd_config_vreg_load(hba->dev, vreg,
5222 UFS_VREG_LPM_LOAD_UA);
5225 static inline int ufshcd_config_vreg_hpm(struct ufs_hba *hba,
5226 struct ufs_vreg *vreg)
5228 if (!vreg)
5229 return 0;
5230 else if (vreg->unused)
5231 return 0;
5232 else
5233 return ufshcd_config_vreg_load(hba->dev, vreg, vreg->max_uA);
5236 static int ufshcd_config_vreg(struct device *dev,
5237 struct ufs_vreg *vreg, bool on)
5239 int ret = 0;
5240 struct regulator *reg = vreg->reg;
5241 const char *name = vreg->name;
5242 int min_uV, uA_load;
5244 BUG_ON(!vreg);
5246 if (regulator_count_voltages(reg) > 0) {
5247 min_uV = on ? vreg->min_uV : 0;
5248 ret = regulator_set_voltage(reg, min_uV, vreg->max_uV);
5249 if (ret) {
5250 dev_err(dev, "%s: %s set voltage failed, err=%d\n",
5251 __func__, name, ret);
5252 goto out;
5255 uA_load = on ? vreg->max_uA : 0;
5256 ret = ufshcd_config_vreg_load(dev, vreg, uA_load);
5257 if (ret)
5258 goto out;
5260 out:
5261 return ret;
5264 static int ufshcd_enable_vreg(struct device *dev, struct ufs_vreg *vreg)
5266 int ret = 0;
5268 if (!vreg)
5269 goto out;
5270 else if (vreg->enabled || vreg->unused)
5271 goto out;
5273 ret = ufshcd_config_vreg(dev, vreg, true);
5274 if (!ret)
5275 ret = regulator_enable(vreg->reg);
5277 if (!ret)
5278 vreg->enabled = true;
5279 else
5280 dev_err(dev, "%s: %s enable failed, err=%d\n",
5281 __func__, vreg->name, ret);
5282 out:
5283 return ret;
5286 static int ufshcd_disable_vreg(struct device *dev, struct ufs_vreg *vreg)
5288 int ret = 0;
5290 if (!vreg)
5291 goto out;
5292 else if (!vreg->enabled || vreg->unused)
5293 goto out;
5295 ret = regulator_disable(vreg->reg);
5297 if (!ret) {
5298 /* ignore errors on applying disable config */
5299 ufshcd_config_vreg(dev, vreg, false);
5300 vreg->enabled = false;
5301 } else {
5302 dev_err(dev, "%s: %s disable failed, err=%d\n",
5303 __func__, vreg->name, ret);
5305 out:
5306 return ret;
5309 static int ufshcd_setup_vreg(struct ufs_hba *hba, bool on)
5311 int ret = 0;
5312 struct device *dev = hba->dev;
5313 struct ufs_vreg_info *info = &hba->vreg_info;
5315 if (!info)
5316 goto out;
5318 ret = ufshcd_toggle_vreg(dev, info->vcc, on);
5319 if (ret)
5320 goto out;
5322 ret = ufshcd_toggle_vreg(dev, info->vccq, on);
5323 if (ret)
5324 goto out;
5326 ret = ufshcd_toggle_vreg(dev, info->vccq2, on);
5327 if (ret)
5328 goto out;
5330 out:
5331 if (ret) {
5332 ufshcd_toggle_vreg(dev, info->vccq2, false);
5333 ufshcd_toggle_vreg(dev, info->vccq, false);
5334 ufshcd_toggle_vreg(dev, info->vcc, false);
5336 return ret;
5339 static int ufshcd_setup_hba_vreg(struct ufs_hba *hba, bool on)
5341 struct ufs_vreg_info *info = &hba->vreg_info;
5343 if (info)
5344 return ufshcd_toggle_vreg(hba->dev, info->vdd_hba, on);
5346 return 0;
5349 static int ufshcd_get_vreg(struct device *dev, struct ufs_vreg *vreg)
5351 int ret = 0;
5353 if (!vreg)
5354 goto out;
5356 vreg->reg = devm_regulator_get(dev, vreg->name);
5357 if (IS_ERR(vreg->reg)) {
5358 ret = PTR_ERR(vreg->reg);
5359 dev_err(dev, "%s: %s get failed, err=%d\n",
5360 __func__, vreg->name, ret);
5362 out:
5363 return ret;
5366 static int ufshcd_init_vreg(struct ufs_hba *hba)
5368 int ret = 0;
5369 struct device *dev = hba->dev;
5370 struct ufs_vreg_info *info = &hba->vreg_info;
5372 if (!info)
5373 goto out;
5375 ret = ufshcd_get_vreg(dev, info->vcc);
5376 if (ret)
5377 goto out;
5379 ret = ufshcd_get_vreg(dev, info->vccq);
5380 if (ret)
5381 goto out;
5383 ret = ufshcd_get_vreg(dev, info->vccq2);
5384 out:
5385 return ret;
5388 static int ufshcd_init_hba_vreg(struct ufs_hba *hba)
5390 struct ufs_vreg_info *info = &hba->vreg_info;
5392 if (info)
5393 return ufshcd_get_vreg(hba->dev, info->vdd_hba);
5395 return 0;
5398 static int ufshcd_set_vccq_rail_unused(struct ufs_hba *hba, bool unused)
5400 int ret = 0;
5401 struct ufs_vreg_info *info = &hba->vreg_info;
5403 if (!info)
5404 goto out;
5405 else if (!info->vccq)
5406 goto out;
5408 if (unused) {
5409 /* shut off the rail here */
5410 ret = ufshcd_toggle_vreg(hba->dev, info->vccq, false);
5412 * Mark this rail as no longer used, so it doesn't get enabled
5413 * later by mistake
5415 if (!ret)
5416 info->vccq->unused = true;
5417 } else {
5419 * rail should have been already enabled hence just make sure
5420 * that unused flag is cleared.
5422 info->vccq->unused = false;
5424 out:
5425 return ret;
5428 static int __ufshcd_setup_clocks(struct ufs_hba *hba, bool on,
5429 bool skip_ref_clk)
5431 int ret = 0;
5432 struct ufs_clk_info *clki;
5433 struct list_head *head = &hba->clk_list_head;
5434 unsigned long flags;
5436 if (!head || list_empty(head))
5437 goto out;
5439 ret = ufshcd_vops_setup_clocks(hba, on, PRE_CHANGE);
5440 if (ret)
5441 return ret;
5443 list_for_each_entry(clki, head, list) {
5444 if (!IS_ERR_OR_NULL(clki->clk)) {
5445 if (skip_ref_clk && !strcmp(clki->name, "ref_clk"))
5446 continue;
5448 if (on && !clki->enabled) {
5449 ret = clk_prepare_enable(clki->clk);
5450 if (ret) {
5451 dev_err(hba->dev, "%s: %s prepare enable failed, %d\n",
5452 __func__, clki->name, ret);
5453 goto out;
5455 } else if (!on && clki->enabled) {
5456 clk_disable_unprepare(clki->clk);
5458 clki->enabled = on;
5459 dev_dbg(hba->dev, "%s: clk: %s %sabled\n", __func__,
5460 clki->name, on ? "en" : "dis");
5464 ret = ufshcd_vops_setup_clocks(hba, on, POST_CHANGE);
5465 if (ret)
5466 return ret;
5468 out:
5469 if (ret) {
5470 list_for_each_entry(clki, head, list) {
5471 if (!IS_ERR_OR_NULL(clki->clk) && clki->enabled)
5472 clk_disable_unprepare(clki->clk);
5474 } else if (on) {
5475 spin_lock_irqsave(hba->host->host_lock, flags);
5476 hba->clk_gating.state = CLKS_ON;
5477 spin_unlock_irqrestore(hba->host->host_lock, flags);
5479 return ret;
5482 static int ufshcd_setup_clocks(struct ufs_hba *hba, bool on)
5484 return __ufshcd_setup_clocks(hba, on, false);
5487 static int ufshcd_init_clocks(struct ufs_hba *hba)
5489 int ret = 0;
5490 struct ufs_clk_info *clki;
5491 struct device *dev = hba->dev;
5492 struct list_head *head = &hba->clk_list_head;
5494 if (!head || list_empty(head))
5495 goto out;
5497 list_for_each_entry(clki, head, list) {
5498 if (!clki->name)
5499 continue;
5501 clki->clk = devm_clk_get(dev, clki->name);
5502 if (IS_ERR(clki->clk)) {
5503 ret = PTR_ERR(clki->clk);
5504 dev_err(dev, "%s: %s clk get failed, %d\n",
5505 __func__, clki->name, ret);
5506 goto out;
5509 if (clki->max_freq) {
5510 ret = clk_set_rate(clki->clk, clki->max_freq);
5511 if (ret) {
5512 dev_err(hba->dev, "%s: %s clk set rate(%dHz) failed, %d\n",
5513 __func__, clki->name,
5514 clki->max_freq, ret);
5515 goto out;
5517 clki->curr_freq = clki->max_freq;
5519 dev_dbg(dev, "%s: clk: %s, rate: %lu\n", __func__,
5520 clki->name, clk_get_rate(clki->clk));
5522 out:
5523 return ret;
5526 static int ufshcd_variant_hba_init(struct ufs_hba *hba)
5528 int err = 0;
5530 if (!hba->vops)
5531 goto out;
5533 err = ufshcd_vops_init(hba);
5534 if (err)
5535 goto out;
5537 err = ufshcd_vops_setup_regulators(hba, true);
5538 if (err)
5539 goto out_exit;
5541 goto out;
5543 out_exit:
5544 ufshcd_vops_exit(hba);
5545 out:
5546 if (err)
5547 dev_err(hba->dev, "%s: variant %s init failed err %d\n",
5548 __func__, ufshcd_get_var_name(hba), err);
5549 return err;
5552 static void ufshcd_variant_hba_exit(struct ufs_hba *hba)
5554 if (!hba->vops)
5555 return;
5557 ufshcd_vops_setup_regulators(hba, false);
5559 ufshcd_vops_exit(hba);
5562 static int ufshcd_hba_init(struct ufs_hba *hba)
5564 int err;
5567 * Handle host controller power separately from the UFS device power
5568 * rails as it will help controlling the UFS host controller power
5569 * collapse easily which is different than UFS device power collapse.
5570 * Also, enable the host controller power before we go ahead with rest
5571 * of the initialization here.
5573 err = ufshcd_init_hba_vreg(hba);
5574 if (err)
5575 goto out;
5577 err = ufshcd_setup_hba_vreg(hba, true);
5578 if (err)
5579 goto out;
5581 err = ufshcd_init_clocks(hba);
5582 if (err)
5583 goto out_disable_hba_vreg;
5585 err = ufshcd_setup_clocks(hba, true);
5586 if (err)
5587 goto out_disable_hba_vreg;
5589 err = ufshcd_init_vreg(hba);
5590 if (err)
5591 goto out_disable_clks;
5593 err = ufshcd_setup_vreg(hba, true);
5594 if (err)
5595 goto out_disable_clks;
5597 err = ufshcd_variant_hba_init(hba);
5598 if (err)
5599 goto out_disable_vreg;
5601 hba->is_powered = true;
5602 goto out;
5604 out_disable_vreg:
5605 ufshcd_setup_vreg(hba, false);
5606 out_disable_clks:
5607 ufshcd_setup_clocks(hba, false);
5608 out_disable_hba_vreg:
5609 ufshcd_setup_hba_vreg(hba, false);
5610 out:
5611 return err;
5614 static void ufshcd_hba_exit(struct ufs_hba *hba)
5616 if (hba->is_powered) {
5617 ufshcd_variant_hba_exit(hba);
5618 ufshcd_setup_vreg(hba, false);
5619 ufshcd_suspend_clkscaling(hba);
5620 ufshcd_setup_clocks(hba, false);
5621 ufshcd_setup_hba_vreg(hba, false);
5622 hba->is_powered = false;
5626 static int
5627 ufshcd_send_request_sense(struct ufs_hba *hba, struct scsi_device *sdp)
5629 unsigned char cmd[6] = {REQUEST_SENSE,
5633 UFSHCD_REQ_SENSE_SIZE,
5635 char *buffer;
5636 int ret;
5638 buffer = kzalloc(UFSHCD_REQ_SENSE_SIZE, GFP_KERNEL);
5639 if (!buffer) {
5640 ret = -ENOMEM;
5641 goto out;
5644 ret = scsi_execute_req_flags(sdp, cmd, DMA_FROM_DEVICE, buffer,
5645 UFSHCD_REQ_SENSE_SIZE, NULL,
5646 msecs_to_jiffies(1000), 3, NULL, REQ_PM);
5647 if (ret)
5648 pr_err("%s: failed with err %d\n", __func__, ret);
5650 kfree(buffer);
5651 out:
5652 return ret;
5656 * ufshcd_set_dev_pwr_mode - sends START STOP UNIT command to set device
5657 * power mode
5658 * @hba: per adapter instance
5659 * @pwr_mode: device power mode to set
5661 * Returns 0 if requested power mode is set successfully
5662 * Returns non-zero if failed to set the requested power mode
5664 static int ufshcd_set_dev_pwr_mode(struct ufs_hba *hba,
5665 enum ufs_dev_pwr_mode pwr_mode)
5667 unsigned char cmd[6] = { START_STOP };
5668 struct scsi_sense_hdr sshdr;
5669 struct scsi_device *sdp;
5670 unsigned long flags;
5671 int ret;
5673 spin_lock_irqsave(hba->host->host_lock, flags);
5674 sdp = hba->sdev_ufs_device;
5675 if (sdp) {
5676 ret = scsi_device_get(sdp);
5677 if (!ret && !scsi_device_online(sdp)) {
5678 ret = -ENODEV;
5679 scsi_device_put(sdp);
5681 } else {
5682 ret = -ENODEV;
5684 spin_unlock_irqrestore(hba->host->host_lock, flags);
5686 if (ret)
5687 return ret;
5690 * If scsi commands fail, the scsi mid-layer schedules scsi error-
5691 * handling, which would wait for host to be resumed. Since we know
5692 * we are functional while we are here, skip host resume in error
5693 * handling context.
5695 hba->host->eh_noresume = 1;
5696 if (hba->wlun_dev_clr_ua) {
5697 ret = ufshcd_send_request_sense(hba, sdp);
5698 if (ret)
5699 goto out;
5700 /* Unit attention condition is cleared now */
5701 hba->wlun_dev_clr_ua = false;
5704 cmd[4] = pwr_mode << 4;
5707 * Current function would be generally called from the power management
5708 * callbacks hence set the REQ_PM flag so that it doesn't resume the
5709 * already suspended childs.
5711 ret = scsi_execute_req_flags(sdp, cmd, DMA_NONE, NULL, 0, &sshdr,
5712 START_STOP_TIMEOUT, 0, NULL, REQ_PM);
5713 if (ret) {
5714 sdev_printk(KERN_WARNING, sdp,
5715 "START_STOP failed for power mode: %d, result %x\n",
5716 pwr_mode, ret);
5717 if (driver_byte(ret) & DRIVER_SENSE)
5718 scsi_print_sense_hdr(sdp, NULL, &sshdr);
5721 if (!ret)
5722 hba->curr_dev_pwr_mode = pwr_mode;
5723 out:
5724 scsi_device_put(sdp);
5725 hba->host->eh_noresume = 0;
5726 return ret;
5729 static int ufshcd_link_state_transition(struct ufs_hba *hba,
5730 enum uic_link_state req_link_state,
5731 int check_for_bkops)
5733 int ret = 0;
5735 if (req_link_state == hba->uic_link_state)
5736 return 0;
5738 if (req_link_state == UIC_LINK_HIBERN8_STATE) {
5739 ret = ufshcd_uic_hibern8_enter(hba);
5740 if (!ret)
5741 ufshcd_set_link_hibern8(hba);
5742 else
5743 goto out;
5746 * If autobkops is enabled, link can't be turned off because
5747 * turning off the link would also turn off the device.
5749 else if ((req_link_state == UIC_LINK_OFF_STATE) &&
5750 (!check_for_bkops || (check_for_bkops &&
5751 !hba->auto_bkops_enabled))) {
5753 * Let's make sure that link is in low power mode, we are doing
5754 * this currently by putting the link in Hibern8. Otherway to
5755 * put the link in low power mode is to send the DME end point
5756 * to device and then send the DME reset command to local
5757 * unipro. But putting the link in hibern8 is much faster.
5759 ret = ufshcd_uic_hibern8_enter(hba);
5760 if (ret)
5761 goto out;
5763 * Change controller state to "reset state" which
5764 * should also put the link in off/reset state
5766 ufshcd_hba_stop(hba, true);
5768 * TODO: Check if we need any delay to make sure that
5769 * controller is reset
5771 ufshcd_set_link_off(hba);
5774 out:
5775 return ret;
5778 static void ufshcd_vreg_set_lpm(struct ufs_hba *hba)
5781 * It seems some UFS devices may keep drawing more than sleep current
5782 * (atleast for 500us) from UFS rails (especially from VCCQ rail).
5783 * To avoid this situation, add 2ms delay before putting these UFS
5784 * rails in LPM mode.
5786 if (!ufshcd_is_link_active(hba) &&
5787 hba->dev_quirks & UFS_DEVICE_QUIRK_DELAY_BEFORE_LPM)
5788 usleep_range(2000, 2100);
5791 * If UFS device is either in UFS_Sleep turn off VCC rail to save some
5792 * power.
5794 * If UFS device and link is in OFF state, all power supplies (VCC,
5795 * VCCQ, VCCQ2) can be turned off if power on write protect is not
5796 * required. If UFS link is inactive (Hibern8 or OFF state) and device
5797 * is in sleep state, put VCCQ & VCCQ2 rails in LPM mode.
5799 * Ignore the error returned by ufshcd_toggle_vreg() as device is anyway
5800 * in low power state which would save some power.
5802 if (ufshcd_is_ufs_dev_poweroff(hba) && ufshcd_is_link_off(hba) &&
5803 !hba->dev_info.is_lu_power_on_wp) {
5804 ufshcd_setup_vreg(hba, false);
5805 } else if (!ufshcd_is_ufs_dev_active(hba)) {
5806 ufshcd_toggle_vreg(hba->dev, hba->vreg_info.vcc, false);
5807 if (!ufshcd_is_link_active(hba)) {
5808 ufshcd_config_vreg_lpm(hba, hba->vreg_info.vccq);
5809 ufshcd_config_vreg_lpm(hba, hba->vreg_info.vccq2);
5814 static int ufshcd_vreg_set_hpm(struct ufs_hba *hba)
5816 int ret = 0;
5818 if (ufshcd_is_ufs_dev_poweroff(hba) && ufshcd_is_link_off(hba) &&
5819 !hba->dev_info.is_lu_power_on_wp) {
5820 ret = ufshcd_setup_vreg(hba, true);
5821 } else if (!ufshcd_is_ufs_dev_active(hba)) {
5822 ret = ufshcd_toggle_vreg(hba->dev, hba->vreg_info.vcc, true);
5823 if (!ret && !ufshcd_is_link_active(hba)) {
5824 ret = ufshcd_config_vreg_hpm(hba, hba->vreg_info.vccq);
5825 if (ret)
5826 goto vcc_disable;
5827 ret = ufshcd_config_vreg_hpm(hba, hba->vreg_info.vccq2);
5828 if (ret)
5829 goto vccq_lpm;
5832 goto out;
5834 vccq_lpm:
5835 ufshcd_config_vreg_lpm(hba, hba->vreg_info.vccq);
5836 vcc_disable:
5837 ufshcd_toggle_vreg(hba->dev, hba->vreg_info.vcc, false);
5838 out:
5839 return ret;
5842 static void ufshcd_hba_vreg_set_lpm(struct ufs_hba *hba)
5844 if (ufshcd_is_link_off(hba))
5845 ufshcd_setup_hba_vreg(hba, false);
5848 static void ufshcd_hba_vreg_set_hpm(struct ufs_hba *hba)
5850 if (ufshcd_is_link_off(hba))
5851 ufshcd_setup_hba_vreg(hba, true);
5855 * ufshcd_suspend - helper function for suspend operations
5856 * @hba: per adapter instance
5857 * @pm_op: desired low power operation type
5859 * This function will try to put the UFS device and link into low power
5860 * mode based on the "rpm_lvl" (Runtime PM level) or "spm_lvl"
5861 * (System PM level).
5863 * If this function is called during shutdown, it will make sure that
5864 * both UFS device and UFS link is powered off.
5866 * NOTE: UFS device & link must be active before we enter in this function.
5868 * Returns 0 for success and non-zero for failure
5870 static int ufshcd_suspend(struct ufs_hba *hba, enum ufs_pm_op pm_op)
5872 int ret = 0;
5873 enum ufs_pm_level pm_lvl;
5874 enum ufs_dev_pwr_mode req_dev_pwr_mode;
5875 enum uic_link_state req_link_state;
5877 hba->pm_op_in_progress = 1;
5878 if (!ufshcd_is_shutdown_pm(pm_op)) {
5879 pm_lvl = ufshcd_is_runtime_pm(pm_op) ?
5880 hba->rpm_lvl : hba->spm_lvl;
5881 req_dev_pwr_mode = ufs_get_pm_lvl_to_dev_pwr_mode(pm_lvl);
5882 req_link_state = ufs_get_pm_lvl_to_link_pwr_state(pm_lvl);
5883 } else {
5884 req_dev_pwr_mode = UFS_POWERDOWN_PWR_MODE;
5885 req_link_state = UIC_LINK_OFF_STATE;
5889 * If we can't transition into any of the low power modes
5890 * just gate the clocks.
5892 ufshcd_hold(hba, false);
5893 hba->clk_gating.is_suspended = true;
5895 if (req_dev_pwr_mode == UFS_ACTIVE_PWR_MODE &&
5896 req_link_state == UIC_LINK_ACTIVE_STATE) {
5897 goto disable_clks;
5900 if ((req_dev_pwr_mode == hba->curr_dev_pwr_mode) &&
5901 (req_link_state == hba->uic_link_state))
5902 goto out;
5904 /* UFS device & link must be active before we enter in this function */
5905 if (!ufshcd_is_ufs_dev_active(hba) || !ufshcd_is_link_active(hba)) {
5906 ret = -EINVAL;
5907 goto out;
5910 if (ufshcd_is_runtime_pm(pm_op)) {
5911 if (ufshcd_can_autobkops_during_suspend(hba)) {
5913 * The device is idle with no requests in the queue,
5914 * allow background operations if bkops status shows
5915 * that performance might be impacted.
5917 ret = ufshcd_urgent_bkops(hba);
5918 if (ret)
5919 goto enable_gating;
5920 } else {
5921 /* make sure that auto bkops is disabled */
5922 ufshcd_disable_auto_bkops(hba);
5926 if ((req_dev_pwr_mode != hba->curr_dev_pwr_mode) &&
5927 ((ufshcd_is_runtime_pm(pm_op) && !hba->auto_bkops_enabled) ||
5928 !ufshcd_is_runtime_pm(pm_op))) {
5929 /* ensure that bkops is disabled */
5930 ufshcd_disable_auto_bkops(hba);
5931 ret = ufshcd_set_dev_pwr_mode(hba, req_dev_pwr_mode);
5932 if (ret)
5933 goto enable_gating;
5936 ret = ufshcd_link_state_transition(hba, req_link_state, 1);
5937 if (ret)
5938 goto set_dev_active;
5940 ufshcd_vreg_set_lpm(hba);
5942 disable_clks:
5944 * The clock scaling needs access to controller registers. Hence, Wait
5945 * for pending clock scaling work to be done before clocks are
5946 * turned off.
5948 ufshcd_suspend_clkscaling(hba);
5951 * Call vendor specific suspend callback. As these callbacks may access
5952 * vendor specific host controller register space call them before the
5953 * host clocks are ON.
5955 ret = ufshcd_vops_suspend(hba, pm_op);
5956 if (ret)
5957 goto set_link_active;
5959 if (!ufshcd_is_link_active(hba))
5960 ufshcd_setup_clocks(hba, false);
5961 else
5962 /* If link is active, device ref_clk can't be switched off */
5963 __ufshcd_setup_clocks(hba, false, true);
5965 hba->clk_gating.state = CLKS_OFF;
5967 * Disable the host irq as host controller as there won't be any
5968 * host controller transaction expected till resume.
5970 ufshcd_disable_irq(hba);
5971 /* Put the host controller in low power mode if possible */
5972 ufshcd_hba_vreg_set_lpm(hba);
5973 goto out;
5975 set_link_active:
5976 ufshcd_resume_clkscaling(hba);
5977 ufshcd_vreg_set_hpm(hba);
5978 if (ufshcd_is_link_hibern8(hba) && !ufshcd_uic_hibern8_exit(hba))
5979 ufshcd_set_link_active(hba);
5980 else if (ufshcd_is_link_off(hba))
5981 ufshcd_host_reset_and_restore(hba);
5982 set_dev_active:
5983 if (!ufshcd_set_dev_pwr_mode(hba, UFS_ACTIVE_PWR_MODE))
5984 ufshcd_disable_auto_bkops(hba);
5985 enable_gating:
5986 hba->clk_gating.is_suspended = false;
5987 ufshcd_release(hba);
5988 out:
5989 hba->pm_op_in_progress = 0;
5990 return ret;
5994 * ufshcd_resume - helper function for resume operations
5995 * @hba: per adapter instance
5996 * @pm_op: runtime PM or system PM
5998 * This function basically brings the UFS device, UniPro link and controller
5999 * to active state.
6001 * Returns 0 for success and non-zero for failure
6003 static int ufshcd_resume(struct ufs_hba *hba, enum ufs_pm_op pm_op)
6005 int ret;
6006 enum uic_link_state old_link_state;
6008 hba->pm_op_in_progress = 1;
6009 old_link_state = hba->uic_link_state;
6011 ufshcd_hba_vreg_set_hpm(hba);
6012 /* Make sure clocks are enabled before accessing controller */
6013 ret = ufshcd_setup_clocks(hba, true);
6014 if (ret)
6015 goto out;
6017 /* enable the host irq as host controller would be active soon */
6018 ret = ufshcd_enable_irq(hba);
6019 if (ret)
6020 goto disable_irq_and_vops_clks;
6022 ret = ufshcd_vreg_set_hpm(hba);
6023 if (ret)
6024 goto disable_irq_and_vops_clks;
6027 * Call vendor specific resume callback. As these callbacks may access
6028 * vendor specific host controller register space call them when the
6029 * host clocks are ON.
6031 ret = ufshcd_vops_resume(hba, pm_op);
6032 if (ret)
6033 goto disable_vreg;
6035 if (ufshcd_is_link_hibern8(hba)) {
6036 ret = ufshcd_uic_hibern8_exit(hba);
6037 if (!ret)
6038 ufshcd_set_link_active(hba);
6039 else
6040 goto vendor_suspend;
6041 } else if (ufshcd_is_link_off(hba)) {
6042 ret = ufshcd_host_reset_and_restore(hba);
6044 * ufshcd_host_reset_and_restore() should have already
6045 * set the link state as active
6047 if (ret || !ufshcd_is_link_active(hba))
6048 goto vendor_suspend;
6051 if (!ufshcd_is_ufs_dev_active(hba)) {
6052 ret = ufshcd_set_dev_pwr_mode(hba, UFS_ACTIVE_PWR_MODE);
6053 if (ret)
6054 goto set_old_link_state;
6058 * If BKOPs operations are urgently needed at this moment then
6059 * keep auto-bkops enabled or else disable it.
6061 ufshcd_urgent_bkops(hba);
6062 hba->clk_gating.is_suspended = false;
6064 ufshcd_resume_clkscaling(hba);
6066 /* Schedule clock gating in case of no access to UFS device yet */
6067 ufshcd_release(hba);
6068 goto out;
6070 set_old_link_state:
6071 ufshcd_link_state_transition(hba, old_link_state, 0);
6072 vendor_suspend:
6073 ufshcd_vops_suspend(hba, pm_op);
6074 disable_vreg:
6075 ufshcd_vreg_set_lpm(hba);
6076 disable_irq_and_vops_clks:
6077 ufshcd_disable_irq(hba);
6078 ufshcd_suspend_clkscaling(hba);
6079 ufshcd_setup_clocks(hba, false);
6080 out:
6081 hba->pm_op_in_progress = 0;
6082 return ret;
6086 * ufshcd_system_suspend - system suspend routine
6087 * @hba: per adapter instance
6088 * @pm_op: runtime PM or system PM
6090 * Check the description of ufshcd_suspend() function for more details.
6092 * Returns 0 for success and non-zero for failure
6094 int ufshcd_system_suspend(struct ufs_hba *hba)
6096 int ret = 0;
6098 if (!hba || !hba->is_powered)
6099 return 0;
6101 if (pm_runtime_suspended(hba->dev)) {
6102 if (hba->rpm_lvl == hba->spm_lvl)
6104 * There is possibility that device may still be in
6105 * active state during the runtime suspend.
6107 if ((ufs_get_pm_lvl_to_dev_pwr_mode(hba->spm_lvl) ==
6108 hba->curr_dev_pwr_mode) && !hba->auto_bkops_enabled)
6109 goto out;
6112 * UFS device and/or UFS link low power states during runtime
6113 * suspend seems to be different than what is expected during
6114 * system suspend. Hence runtime resume the devic & link and
6115 * let the system suspend low power states to take effect.
6116 * TODO: If resume takes longer time, we might have optimize
6117 * it in future by not resuming everything if possible.
6119 ret = ufshcd_runtime_resume(hba);
6120 if (ret)
6121 goto out;
6124 ret = ufshcd_suspend(hba, UFS_SYSTEM_PM);
6125 out:
6126 if (!ret)
6127 hba->is_sys_suspended = true;
6128 return ret;
6130 EXPORT_SYMBOL(ufshcd_system_suspend);
6133 * ufshcd_system_resume - system resume routine
6134 * @hba: per adapter instance
6136 * Returns 0 for success and non-zero for failure
6139 int ufshcd_system_resume(struct ufs_hba *hba)
6141 if (!hba)
6142 return -EINVAL;
6144 if (!hba->is_powered || pm_runtime_suspended(hba->dev))
6146 * Let the runtime resume take care of resuming
6147 * if runtime suspended.
6149 return 0;
6151 return ufshcd_resume(hba, UFS_SYSTEM_PM);
6153 EXPORT_SYMBOL(ufshcd_system_resume);
6156 * ufshcd_runtime_suspend - runtime suspend routine
6157 * @hba: per adapter instance
6159 * Check the description of ufshcd_suspend() function for more details.
6161 * Returns 0 for success and non-zero for failure
6163 int ufshcd_runtime_suspend(struct ufs_hba *hba)
6165 if (!hba)
6166 return -EINVAL;
6168 if (!hba->is_powered)
6169 return 0;
6171 return ufshcd_suspend(hba, UFS_RUNTIME_PM);
6173 EXPORT_SYMBOL(ufshcd_runtime_suspend);
6176 * ufshcd_runtime_resume - runtime resume routine
6177 * @hba: per adapter instance
6179 * This function basically brings the UFS device, UniPro link and controller
6180 * to active state. Following operations are done in this function:
6182 * 1. Turn on all the controller related clocks
6183 * 2. Bring the UniPro link out of Hibernate state
6184 * 3. If UFS device is in sleep state, turn ON VCC rail and bring the UFS device
6185 * to active state.
6186 * 4. If auto-bkops is enabled on the device, disable it.
6188 * So following would be the possible power state after this function return
6189 * successfully:
6190 * S1: UFS device in Active state with VCC rail ON
6191 * UniPro link in Active state
6192 * All the UFS/UniPro controller clocks are ON
6194 * Returns 0 for success and non-zero for failure
6196 int ufshcd_runtime_resume(struct ufs_hba *hba)
6198 if (!hba)
6199 return -EINVAL;
6201 if (!hba->is_powered)
6202 return 0;
6204 return ufshcd_resume(hba, UFS_RUNTIME_PM);
6206 EXPORT_SYMBOL(ufshcd_runtime_resume);
6208 int ufshcd_runtime_idle(struct ufs_hba *hba)
6210 return 0;
6212 EXPORT_SYMBOL(ufshcd_runtime_idle);
6215 * ufshcd_shutdown - shutdown routine
6216 * @hba: per adapter instance
6218 * This function would power off both UFS device and UFS link.
6220 * Returns 0 always to allow force shutdown even in case of errors.
6222 int ufshcd_shutdown(struct ufs_hba *hba)
6224 int ret = 0;
6226 if (ufshcd_is_ufs_dev_poweroff(hba) && ufshcd_is_link_off(hba))
6227 goto out;
6229 if (pm_runtime_suspended(hba->dev)) {
6230 ret = ufshcd_runtime_resume(hba);
6231 if (ret)
6232 goto out;
6235 ret = ufshcd_suspend(hba, UFS_SHUTDOWN_PM);
6236 out:
6237 if (ret)
6238 dev_err(hba->dev, "%s failed, err %d\n", __func__, ret);
6239 /* allow force shutdown even in case of errors */
6240 return 0;
6242 EXPORT_SYMBOL(ufshcd_shutdown);
6245 * ufshcd_remove - de-allocate SCSI host and host memory space
6246 * data structure memory
6247 * @hba - per adapter instance
6249 void ufshcd_remove(struct ufs_hba *hba)
6251 scsi_remove_host(hba->host);
6252 /* disable interrupts */
6253 ufshcd_disable_intr(hba, hba->intr_mask);
6254 ufshcd_hba_stop(hba, true);
6256 ufshcd_exit_clk_gating(hba);
6257 if (ufshcd_is_clkscaling_enabled(hba))
6258 devfreq_remove_device(hba->devfreq);
6259 ufshcd_hba_exit(hba);
6261 EXPORT_SYMBOL_GPL(ufshcd_remove);
6264 * ufshcd_dealloc_host - deallocate Host Bus Adapter (HBA)
6265 * @hba: pointer to Host Bus Adapter (HBA)
6267 void ufshcd_dealloc_host(struct ufs_hba *hba)
6269 scsi_host_put(hba->host);
6271 EXPORT_SYMBOL_GPL(ufshcd_dealloc_host);
6274 * ufshcd_set_dma_mask - Set dma mask based on the controller
6275 * addressing capability
6276 * @hba: per adapter instance
6278 * Returns 0 for success, non-zero for failure
6280 static int ufshcd_set_dma_mask(struct ufs_hba *hba)
6282 if (hba->capabilities & MASK_64_ADDRESSING_SUPPORT) {
6283 if (!dma_set_mask_and_coherent(hba->dev, DMA_BIT_MASK(64)))
6284 return 0;
6286 return dma_set_mask_and_coherent(hba->dev, DMA_BIT_MASK(32));
6290 * ufshcd_alloc_host - allocate Host Bus Adapter (HBA)
6291 * @dev: pointer to device handle
6292 * @hba_handle: driver private handle
6293 * Returns 0 on success, non-zero value on failure
6295 int ufshcd_alloc_host(struct device *dev, struct ufs_hba **hba_handle)
6297 struct Scsi_Host *host;
6298 struct ufs_hba *hba;
6299 int err = 0;
6301 if (!dev) {
6302 dev_err(dev,
6303 "Invalid memory reference for dev is NULL\n");
6304 err = -ENODEV;
6305 goto out_error;
6308 host = scsi_host_alloc(&ufshcd_driver_template,
6309 sizeof(struct ufs_hba));
6310 if (!host) {
6311 dev_err(dev, "scsi_host_alloc failed\n");
6312 err = -ENOMEM;
6313 goto out_error;
6315 hba = shost_priv(host);
6316 hba->host = host;
6317 hba->dev = dev;
6318 *hba_handle = hba;
6320 out_error:
6321 return err;
6323 EXPORT_SYMBOL(ufshcd_alloc_host);
6325 static int ufshcd_scale_clks(struct ufs_hba *hba, bool scale_up)
6327 int ret = 0;
6328 struct ufs_clk_info *clki;
6329 struct list_head *head = &hba->clk_list_head;
6331 if (!head || list_empty(head))
6332 goto out;
6334 ret = ufshcd_vops_clk_scale_notify(hba, scale_up, PRE_CHANGE);
6335 if (ret)
6336 return ret;
6338 list_for_each_entry(clki, head, list) {
6339 if (!IS_ERR_OR_NULL(clki->clk)) {
6340 if (scale_up && clki->max_freq) {
6341 if (clki->curr_freq == clki->max_freq)
6342 continue;
6343 ret = clk_set_rate(clki->clk, clki->max_freq);
6344 if (ret) {
6345 dev_err(hba->dev, "%s: %s clk set rate(%dHz) failed, %d\n",
6346 __func__, clki->name,
6347 clki->max_freq, ret);
6348 break;
6350 clki->curr_freq = clki->max_freq;
6352 } else if (!scale_up && clki->min_freq) {
6353 if (clki->curr_freq == clki->min_freq)
6354 continue;
6355 ret = clk_set_rate(clki->clk, clki->min_freq);
6356 if (ret) {
6357 dev_err(hba->dev, "%s: %s clk set rate(%dHz) failed, %d\n",
6358 __func__, clki->name,
6359 clki->min_freq, ret);
6360 break;
6362 clki->curr_freq = clki->min_freq;
6365 dev_dbg(hba->dev, "%s: clk: %s, rate: %lu\n", __func__,
6366 clki->name, clk_get_rate(clki->clk));
6369 ret = ufshcd_vops_clk_scale_notify(hba, scale_up, POST_CHANGE);
6371 out:
6372 return ret;
6375 static int ufshcd_devfreq_target(struct device *dev,
6376 unsigned long *freq, u32 flags)
6378 int err = 0;
6379 struct ufs_hba *hba = dev_get_drvdata(dev);
6380 bool release_clk_hold = false;
6381 unsigned long irq_flags;
6383 if (!ufshcd_is_clkscaling_enabled(hba))
6384 return -EINVAL;
6386 spin_lock_irqsave(hba->host->host_lock, irq_flags);
6387 if (ufshcd_eh_in_progress(hba)) {
6388 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
6389 return 0;
6392 if (ufshcd_is_clkgating_allowed(hba) &&
6393 (hba->clk_gating.state != CLKS_ON)) {
6394 if (cancel_delayed_work(&hba->clk_gating.gate_work)) {
6395 /* hold the vote until the scaling work is completed */
6396 hba->clk_gating.active_reqs++;
6397 release_clk_hold = true;
6398 hba->clk_gating.state = CLKS_ON;
6399 } else {
6401 * Clock gating work seems to be running in parallel
6402 * hence skip scaling work to avoid deadlock between
6403 * current scaling work and gating work.
6405 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
6406 return 0;
6409 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
6411 if (*freq == UINT_MAX)
6412 err = ufshcd_scale_clks(hba, true);
6413 else if (*freq == 0)
6414 err = ufshcd_scale_clks(hba, false);
6416 spin_lock_irqsave(hba->host->host_lock, irq_flags);
6417 if (release_clk_hold)
6418 __ufshcd_release(hba);
6419 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
6421 return err;
6424 static int ufshcd_devfreq_get_dev_status(struct device *dev,
6425 struct devfreq_dev_status *stat)
6427 struct ufs_hba *hba = dev_get_drvdata(dev);
6428 struct ufs_clk_scaling *scaling = &hba->clk_scaling;
6429 unsigned long flags;
6431 if (!ufshcd_is_clkscaling_enabled(hba))
6432 return -EINVAL;
6434 memset(stat, 0, sizeof(*stat));
6436 spin_lock_irqsave(hba->host->host_lock, flags);
6437 if (!scaling->window_start_t)
6438 goto start_window;
6440 if (scaling->is_busy_started)
6441 scaling->tot_busy_t += ktime_to_us(ktime_sub(ktime_get(),
6442 scaling->busy_start_t));
6444 stat->total_time = jiffies_to_usecs((long)jiffies -
6445 (long)scaling->window_start_t);
6446 stat->busy_time = scaling->tot_busy_t;
6447 start_window:
6448 scaling->window_start_t = jiffies;
6449 scaling->tot_busy_t = 0;
6451 if (hba->outstanding_reqs) {
6452 scaling->busy_start_t = ktime_get();
6453 scaling->is_busy_started = true;
6454 } else {
6455 scaling->busy_start_t = ktime_set(0, 0);
6456 scaling->is_busy_started = false;
6458 spin_unlock_irqrestore(hba->host->host_lock, flags);
6459 return 0;
6462 static struct devfreq_dev_profile ufs_devfreq_profile = {
6463 .polling_ms = 100,
6464 .target = ufshcd_devfreq_target,
6465 .get_dev_status = ufshcd_devfreq_get_dev_status,
6469 * ufshcd_init - Driver initialization routine
6470 * @hba: per-adapter instance
6471 * @mmio_base: base register address
6472 * @irq: Interrupt line of device
6473 * Returns 0 on success, non-zero value on failure
6475 int ufshcd_init(struct ufs_hba *hba, void __iomem *mmio_base, unsigned int irq)
6477 int err;
6478 struct Scsi_Host *host = hba->host;
6479 struct device *dev = hba->dev;
6481 if (!mmio_base) {
6482 dev_err(hba->dev,
6483 "Invalid memory reference for mmio_base is NULL\n");
6484 err = -ENODEV;
6485 goto out_error;
6488 hba->mmio_base = mmio_base;
6489 hba->irq = irq;
6491 err = ufshcd_hba_init(hba);
6492 if (err)
6493 goto out_error;
6495 /* Read capabilities registers */
6496 ufshcd_hba_capabilities(hba);
6498 /* Get UFS version supported by the controller */
6499 hba->ufs_version = ufshcd_get_ufs_version(hba);
6501 /* Get Interrupt bit mask per version */
6502 hba->intr_mask = ufshcd_get_intr_mask(hba);
6504 err = ufshcd_set_dma_mask(hba);
6505 if (err) {
6506 dev_err(hba->dev, "set dma mask failed\n");
6507 goto out_disable;
6510 /* Allocate memory for host memory space */
6511 err = ufshcd_memory_alloc(hba);
6512 if (err) {
6513 dev_err(hba->dev, "Memory allocation failed\n");
6514 goto out_disable;
6517 /* Configure LRB */
6518 ufshcd_host_memory_configure(hba);
6520 host->can_queue = hba->nutrs;
6521 host->cmd_per_lun = hba->nutrs;
6522 host->max_id = UFSHCD_MAX_ID;
6523 host->max_lun = UFS_MAX_LUNS;
6524 host->max_channel = UFSHCD_MAX_CHANNEL;
6525 host->unique_id = host->host_no;
6526 host->max_cmd_len = MAX_CDB_SIZE;
6528 hba->max_pwr_info.is_valid = false;
6530 /* Initailize wait queue for task management */
6531 init_waitqueue_head(&hba->tm_wq);
6532 init_waitqueue_head(&hba->tm_tag_wq);
6534 /* Initialize work queues */
6535 INIT_WORK(&hba->eh_work, ufshcd_err_handler);
6536 INIT_WORK(&hba->eeh_work, ufshcd_exception_event_handler);
6538 /* Initialize UIC command mutex */
6539 mutex_init(&hba->uic_cmd_mutex);
6541 /* Initialize mutex for device management commands */
6542 mutex_init(&hba->dev_cmd.lock);
6544 /* Initialize device management tag acquire wait queue */
6545 init_waitqueue_head(&hba->dev_cmd.tag_wq);
6547 ufshcd_init_clk_gating(hba);
6550 * In order to avoid any spurious interrupt immediately after
6551 * registering UFS controller interrupt handler, clear any pending UFS
6552 * interrupt status and disable all the UFS interrupts.
6554 ufshcd_writel(hba, ufshcd_readl(hba, REG_INTERRUPT_STATUS),
6555 REG_INTERRUPT_STATUS);
6556 ufshcd_writel(hba, 0, REG_INTERRUPT_ENABLE);
6558 * Make sure that UFS interrupts are disabled and any pending interrupt
6559 * status is cleared before registering UFS interrupt handler.
6561 mb();
6563 /* IRQ registration */
6564 err = devm_request_irq(dev, irq, ufshcd_intr, IRQF_SHARED, UFSHCD, hba);
6565 if (err) {
6566 dev_err(hba->dev, "request irq failed\n");
6567 goto exit_gating;
6568 } else {
6569 hba->is_irq_enabled = true;
6572 err = scsi_add_host(host, hba->dev);
6573 if (err) {
6574 dev_err(hba->dev, "scsi_add_host failed\n");
6575 goto exit_gating;
6578 /* Host controller enable */
6579 err = ufshcd_hba_enable(hba);
6580 if (err) {
6581 dev_err(hba->dev, "Host controller enable failed\n");
6582 goto out_remove_scsi_host;
6585 if (ufshcd_is_clkscaling_enabled(hba)) {
6586 hba->devfreq = devfreq_add_device(dev, &ufs_devfreq_profile,
6587 "simple_ondemand", NULL);
6588 if (IS_ERR(hba->devfreq)) {
6589 dev_err(hba->dev, "Unable to register with devfreq %ld\n",
6590 PTR_ERR(hba->devfreq));
6591 err = PTR_ERR(hba->devfreq);
6592 goto out_remove_scsi_host;
6594 /* Suspend devfreq until the UFS device is detected */
6595 ufshcd_suspend_clkscaling(hba);
6598 /* Hold auto suspend until async scan completes */
6599 pm_runtime_get_sync(dev);
6602 * The device-initialize-sequence hasn't been invoked yet.
6603 * Set the device to power-off state
6605 ufshcd_set_ufs_dev_poweroff(hba);
6607 async_schedule(ufshcd_async_scan, hba);
6609 return 0;
6611 out_remove_scsi_host:
6612 scsi_remove_host(hba->host);
6613 exit_gating:
6614 ufshcd_exit_clk_gating(hba);
6615 out_disable:
6616 hba->is_irq_enabled = false;
6617 ufshcd_hba_exit(hba);
6618 out_error:
6619 return err;
6621 EXPORT_SYMBOL_GPL(ufshcd_init);
6623 MODULE_AUTHOR("Santosh Yaragnavi <santosh.sy@samsung.com>");
6624 MODULE_AUTHOR("Vinayak Holikatti <h.vinayak@samsung.com>");
6625 MODULE_DESCRIPTION("Generic UFS host controller driver Core");
6626 MODULE_LICENSE("GPL");
6627 MODULE_VERSION(UFSHCD_DRIVER_VERSION);