2 * Universal Flash Storage Host controller driver Core
4 * This code is based on drivers/scsi/ufs/ufshcd.c
5 * Copyright (C) 2011-2013 Samsung India Software Operations
6 * Copyright (c) 2013-2016, The Linux Foundation. All rights reserved.
9 * Santosh Yaraganavi <santosh.sy@samsung.com>
10 * Vinayak Holikatti <h.vinayak@samsung.com>
12 * This program is free software; you can redistribute it and/or
13 * modify it under the terms of the GNU General Public License
14 * as published by the Free Software Foundation; either version 2
15 * of the License, or (at your option) any later version.
16 * See the COPYING file in the top-level directory or visit
17 * <http://www.gnu.org/licenses/gpl-2.0.html>
19 * This program is distributed in the hope that it will be useful,
20 * but WITHOUT ANY WARRANTY; without even the implied warranty of
21 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22 * GNU General Public License for more details.
24 * This program is provided "AS IS" and "WITH ALL FAULTS" and
25 * without warranty of any kind. You are solely responsible for
26 * determining the appropriateness of using and distributing
27 * the program and assume all risks associated with your exercise
28 * of rights with respect to the program, including but not limited
29 * to infringement of third party rights, the risks and costs of
30 * program errors, damage to or loss of data, programs or equipment,
31 * and unavailability or interruption of operations. Under no
32 * circumstances will the contributor of this Program be liable for
33 * any damages of any kind arising from your use or distribution of
36 * The Linux Foundation chooses to take subject only to the GPLv2
37 * license terms, and distributes only under these terms.
40 #include <linux/async.h>
41 #include <linux/devfreq.h>
42 #include <linux/nls.h>
45 #include "ufs_quirks.h"
48 #define UFSHCD_ENABLE_INTRS (UTP_TRANSFER_REQ_COMPL |\
51 /* UIC command timeout, unit: ms */
52 #define UIC_CMD_TIMEOUT 500
54 /* NOP OUT retries waiting for NOP IN response */
55 #define NOP_OUT_RETRIES 10
56 /* Timeout after 30 msecs if NOP OUT hangs without response */
57 #define NOP_OUT_TIMEOUT 30 /* msecs */
59 /* Query request retries */
60 #define QUERY_REQ_RETRIES 10
61 /* Query request timeout */
62 #define QUERY_REQ_TIMEOUT 30 /* msec */
64 * Query request timeout for fDeviceInit flag
65 * fDeviceInit query response time for some devices is too large that default
66 * QUERY_REQ_TIMEOUT may not be enough for such devices.
68 #define QUERY_FDEVICEINIT_REQ_TIMEOUT 600 /* msec */
70 /* Task management command timeout */
71 #define TM_CMD_TIMEOUT 100 /* msecs */
73 /* maximum number of retries for a general UIC command */
74 #define UFS_UIC_COMMAND_RETRIES 3
76 /* maximum number of link-startup retries */
77 #define DME_LINKSTARTUP_RETRIES 3
79 /* Maximum retries for Hibern8 enter */
80 #define UIC_HIBERN8_ENTER_RETRIES 3
82 /* maximum number of reset retries before giving up */
83 #define MAX_HOST_RESET_RETRIES 5
85 /* Expose the flag value from utp_upiu_query.value */
86 #define MASK_QUERY_UPIU_FLAG_LOC 0xFF
88 /* Interrupt aggregation default timeout, unit: 40us */
89 #define INT_AGGR_DEF_TO 0x02
91 #define ufshcd_toggle_vreg(_dev, _vreg, _on) \
95 _ret = ufshcd_enable_vreg(_dev, _vreg); \
97 _ret = ufshcd_disable_vreg(_dev, _vreg); \
101 static u32 ufs_query_desc_max_size[] = {
102 QUERY_DESC_DEVICE_MAX_SIZE,
103 QUERY_DESC_CONFIGURAION_MAX_SIZE,
104 QUERY_DESC_UNIT_MAX_SIZE,
105 QUERY_DESC_RFU_MAX_SIZE,
106 QUERY_DESC_INTERCONNECT_MAX_SIZE,
107 QUERY_DESC_STRING_MAX_SIZE,
108 QUERY_DESC_RFU_MAX_SIZE,
109 QUERY_DESC_GEOMETRY_MAX_SIZE,
110 QUERY_DESC_POWER_MAX_SIZE,
111 QUERY_DESC_RFU_MAX_SIZE,
115 UFSHCD_MAX_CHANNEL = 0,
117 UFSHCD_CMD_PER_LUN = 32,
118 UFSHCD_CAN_QUEUE = 32,
125 UFSHCD_STATE_OPERATIONAL,
128 /* UFSHCD error handling flags */
130 UFSHCD_EH_IN_PROGRESS = (1 << 0),
133 /* UFSHCD UIC layer error flags */
135 UFSHCD_UIC_DL_PA_INIT_ERROR = (1 << 0), /* Data link layer error */
136 UFSHCD_UIC_DL_NAC_RECEIVED_ERROR = (1 << 1), /* Data link layer error */
137 UFSHCD_UIC_DL_TCx_REPLAY_ERROR = (1 << 2), /* Data link layer error */
138 UFSHCD_UIC_NL_ERROR = (1 << 3), /* Network layer error */
139 UFSHCD_UIC_TL_ERROR = (1 << 4), /* Transport Layer error */
140 UFSHCD_UIC_DME_ERROR = (1 << 5), /* DME error */
143 /* Interrupt configuration options */
150 #define ufshcd_set_eh_in_progress(h) \
151 (h->eh_flags |= UFSHCD_EH_IN_PROGRESS)
152 #define ufshcd_eh_in_progress(h) \
153 (h->eh_flags & UFSHCD_EH_IN_PROGRESS)
154 #define ufshcd_clear_eh_in_progress(h) \
155 (h->eh_flags &= ~UFSHCD_EH_IN_PROGRESS)
157 #define ufshcd_set_ufs_dev_active(h) \
158 ((h)->curr_dev_pwr_mode = UFS_ACTIVE_PWR_MODE)
159 #define ufshcd_set_ufs_dev_sleep(h) \
160 ((h)->curr_dev_pwr_mode = UFS_SLEEP_PWR_MODE)
161 #define ufshcd_set_ufs_dev_poweroff(h) \
162 ((h)->curr_dev_pwr_mode = UFS_POWERDOWN_PWR_MODE)
163 #define ufshcd_is_ufs_dev_active(h) \
164 ((h)->curr_dev_pwr_mode == UFS_ACTIVE_PWR_MODE)
165 #define ufshcd_is_ufs_dev_sleep(h) \
166 ((h)->curr_dev_pwr_mode == UFS_SLEEP_PWR_MODE)
167 #define ufshcd_is_ufs_dev_poweroff(h) \
168 ((h)->curr_dev_pwr_mode == UFS_POWERDOWN_PWR_MODE)
170 static struct ufs_pm_lvl_states ufs_pm_lvl_states[] = {
171 {UFS_ACTIVE_PWR_MODE, UIC_LINK_ACTIVE_STATE},
172 {UFS_ACTIVE_PWR_MODE, UIC_LINK_HIBERN8_STATE},
173 {UFS_SLEEP_PWR_MODE, UIC_LINK_ACTIVE_STATE},
174 {UFS_SLEEP_PWR_MODE, UIC_LINK_HIBERN8_STATE},
175 {UFS_POWERDOWN_PWR_MODE, UIC_LINK_HIBERN8_STATE},
176 {UFS_POWERDOWN_PWR_MODE, UIC_LINK_OFF_STATE},
179 static inline enum ufs_dev_pwr_mode
180 ufs_get_pm_lvl_to_dev_pwr_mode(enum ufs_pm_level lvl)
182 return ufs_pm_lvl_states[lvl].dev_state;
185 static inline enum uic_link_state
186 ufs_get_pm_lvl_to_link_pwr_state(enum ufs_pm_level lvl)
188 return ufs_pm_lvl_states[lvl].link_state;
191 static void ufshcd_tmc_handler(struct ufs_hba *hba);
192 static void ufshcd_async_scan(void *data, async_cookie_t cookie);
193 static int ufshcd_reset_and_restore(struct ufs_hba *hba);
194 static int ufshcd_clear_tm_cmd(struct ufs_hba *hba, int tag);
195 static void ufshcd_hba_exit(struct ufs_hba *hba);
196 static int ufshcd_probe_hba(struct ufs_hba *hba);
197 static int __ufshcd_setup_clocks(struct ufs_hba *hba, bool on,
199 static int ufshcd_setup_clocks(struct ufs_hba *hba, bool on);
200 static int ufshcd_set_vccq_rail_unused(struct ufs_hba *hba, bool unused);
201 static int ufshcd_uic_hibern8_exit(struct ufs_hba *hba);
202 static int ufshcd_uic_hibern8_enter(struct ufs_hba *hba);
203 static inline void ufshcd_add_delay_before_dme_cmd(struct ufs_hba *hba);
204 static int ufshcd_host_reset_and_restore(struct ufs_hba *hba);
205 static irqreturn_t ufshcd_intr(int irq, void *__hba);
206 static int ufshcd_config_pwr_mode(struct ufs_hba *hba,
207 struct ufs_pa_layer_attr *desired_pwr_mode);
208 static int ufshcd_change_power_mode(struct ufs_hba *hba,
209 struct ufs_pa_layer_attr *pwr_mode);
210 static inline bool ufshcd_valid_tag(struct ufs_hba *hba, int tag)
212 return tag >= 0 && tag < hba->nutrs;
215 static inline int ufshcd_enable_irq(struct ufs_hba *hba)
219 if (!hba->is_irq_enabled) {
220 ret = request_irq(hba->irq, ufshcd_intr, IRQF_SHARED, UFSHCD,
223 dev_err(hba->dev, "%s: request_irq failed, ret=%d\n",
225 hba->is_irq_enabled = true;
231 static inline void ufshcd_disable_irq(struct ufs_hba *hba)
233 if (hba->is_irq_enabled) {
234 free_irq(hba->irq, hba);
235 hba->is_irq_enabled = false;
239 /* replace non-printable or non-ASCII characters with spaces */
240 static inline void ufshcd_remove_non_printable(char *val)
245 if (*val < 0x20 || *val > 0x7e)
250 * ufshcd_wait_for_register - wait for register value to change
251 * @hba - per-adapter interface
252 * @reg - mmio register offset
253 * @mask - mask to apply to read register value
254 * @val - wait condition
255 * @interval_us - polling interval in microsecs
256 * @timeout_ms - timeout in millisecs
257 * @can_sleep - perform sleep or just spin
259 * Returns -ETIMEDOUT on error, zero on success
261 int ufshcd_wait_for_register(struct ufs_hba *hba, u32 reg, u32 mask,
262 u32 val, unsigned long interval_us,
263 unsigned long timeout_ms, bool can_sleep)
266 unsigned long timeout = jiffies + msecs_to_jiffies(timeout_ms);
268 /* ignore bits that we don't intend to wait on */
271 while ((ufshcd_readl(hba, reg) & mask) != val) {
273 usleep_range(interval_us, interval_us + 50);
276 if (time_after(jiffies, timeout)) {
277 if ((ufshcd_readl(hba, reg) & mask) != val)
287 * ufshcd_get_intr_mask - Get the interrupt bit mask
288 * @hba - Pointer to adapter instance
290 * Returns interrupt bit mask per version
292 static inline u32 ufshcd_get_intr_mask(struct ufs_hba *hba)
294 if (hba->ufs_version == UFSHCI_VERSION_10)
295 return INTERRUPT_MASK_ALL_VER_10;
297 return INTERRUPT_MASK_ALL_VER_11;
301 * ufshcd_get_ufs_version - Get the UFS version supported by the HBA
302 * @hba - Pointer to adapter instance
304 * Returns UFSHCI version supported by the controller
306 static inline u32 ufshcd_get_ufs_version(struct ufs_hba *hba)
308 if (hba->quirks & UFSHCD_QUIRK_BROKEN_UFS_HCI_VERSION)
309 return ufshcd_vops_get_ufs_hci_version(hba);
311 return ufshcd_readl(hba, REG_UFS_VERSION);
315 * ufshcd_is_device_present - Check if any device connected to
316 * the host controller
317 * @hba: pointer to adapter instance
319 * Returns 1 if device present, 0 if no device detected
321 static inline int ufshcd_is_device_present(struct ufs_hba *hba)
323 return (ufshcd_readl(hba, REG_CONTROLLER_STATUS) &
324 DEVICE_PRESENT) ? 1 : 0;
328 * ufshcd_get_tr_ocs - Get the UTRD Overall Command Status
329 * @lrb: pointer to local command reference block
331 * This function is used to get the OCS field from UTRD
332 * Returns the OCS field in the UTRD
334 static inline int ufshcd_get_tr_ocs(struct ufshcd_lrb *lrbp)
336 return le32_to_cpu(lrbp->utr_descriptor_ptr->header.dword_2) & MASK_OCS;
340 * ufshcd_get_tmr_ocs - Get the UTMRD Overall Command Status
341 * @task_req_descp: pointer to utp_task_req_desc structure
343 * This function is used to get the OCS field from UTMRD
344 * Returns the OCS field in the UTMRD
347 ufshcd_get_tmr_ocs(struct utp_task_req_desc *task_req_descp)
349 return le32_to_cpu(task_req_descp->header.dword_2) & MASK_OCS;
353 * ufshcd_get_tm_free_slot - get a free slot for task management request
354 * @hba: per adapter instance
355 * @free_slot: pointer to variable with available slot value
357 * Get a free tag and lock it until ufshcd_put_tm_slot() is called.
358 * Returns 0 if free slot is not available, else return 1 with tag value
361 static bool ufshcd_get_tm_free_slot(struct ufs_hba *hba, int *free_slot)
370 tag = find_first_zero_bit(&hba->tm_slots_in_use, hba->nutmrs);
371 if (tag >= hba->nutmrs)
373 } while (test_and_set_bit_lock(tag, &hba->tm_slots_in_use));
381 static inline void ufshcd_put_tm_slot(struct ufs_hba *hba, int slot)
383 clear_bit_unlock(slot, &hba->tm_slots_in_use);
387 * ufshcd_utrl_clear - Clear a bit in UTRLCLR register
388 * @hba: per adapter instance
389 * @pos: position of the bit to be cleared
391 static inline void ufshcd_utrl_clear(struct ufs_hba *hba, u32 pos)
393 ufshcd_writel(hba, ~(1 << pos), REG_UTP_TRANSFER_REQ_LIST_CLEAR);
397 * ufshcd_outstanding_req_clear - Clear a bit in outstanding request field
398 * @hba: per adapter instance
399 * @tag: position of the bit to be cleared
401 static inline void ufshcd_outstanding_req_clear(struct ufs_hba *hba, int tag)
403 __clear_bit(tag, &hba->outstanding_reqs);
407 * ufshcd_get_lists_status - Check UCRDY, UTRLRDY and UTMRLRDY
408 * @reg: Register value of host controller status
410 * Returns integer, 0 on Success and positive value if failed
412 static inline int ufshcd_get_lists_status(u32 reg)
415 * The mask 0xFF is for the following HCS register bits
423 return ((reg & 0xFF) >> 1) ^ 0x07;
427 * ufshcd_get_uic_cmd_result - Get the UIC command result
428 * @hba: Pointer to adapter instance
430 * This function gets the result of UIC command completion
431 * Returns 0 on success, non zero value on error
433 static inline int ufshcd_get_uic_cmd_result(struct ufs_hba *hba)
435 return ufshcd_readl(hba, REG_UIC_COMMAND_ARG_2) &
436 MASK_UIC_COMMAND_RESULT;
440 * ufshcd_get_dme_attr_val - Get the value of attribute returned by UIC command
441 * @hba: Pointer to adapter instance
443 * This function gets UIC command argument3
444 * Returns 0 on success, non zero value on error
446 static inline u32 ufshcd_get_dme_attr_val(struct ufs_hba *hba)
448 return ufshcd_readl(hba, REG_UIC_COMMAND_ARG_3);
452 * ufshcd_get_req_rsp - returns the TR response transaction type
453 * @ucd_rsp_ptr: pointer to response UPIU
456 ufshcd_get_req_rsp(struct utp_upiu_rsp *ucd_rsp_ptr)
458 return be32_to_cpu(ucd_rsp_ptr->header.dword_0) >> 24;
462 * ufshcd_get_rsp_upiu_result - Get the result from response UPIU
463 * @ucd_rsp_ptr: pointer to response UPIU
465 * This function gets the response status and scsi_status from response UPIU
466 * Returns the response result code.
469 ufshcd_get_rsp_upiu_result(struct utp_upiu_rsp *ucd_rsp_ptr)
471 return be32_to_cpu(ucd_rsp_ptr->header.dword_1) & MASK_RSP_UPIU_RESULT;
475 * ufshcd_get_rsp_upiu_data_seg_len - Get the data segment length
477 * @ucd_rsp_ptr: pointer to response UPIU
479 * Return the data segment length.
481 static inline unsigned int
482 ufshcd_get_rsp_upiu_data_seg_len(struct utp_upiu_rsp *ucd_rsp_ptr)
484 return be32_to_cpu(ucd_rsp_ptr->header.dword_2) &
485 MASK_RSP_UPIU_DATA_SEG_LEN;
489 * ufshcd_is_exception_event - Check if the device raised an exception event
490 * @ucd_rsp_ptr: pointer to response UPIU
492 * The function checks if the device raised an exception event indicated in
493 * the Device Information field of response UPIU.
495 * Returns true if exception is raised, false otherwise.
497 static inline bool ufshcd_is_exception_event(struct utp_upiu_rsp *ucd_rsp_ptr)
499 return be32_to_cpu(ucd_rsp_ptr->header.dword_2) &
500 MASK_RSP_EXCEPTION_EVENT ? true : false;
504 * ufshcd_reset_intr_aggr - Reset interrupt aggregation values.
505 * @hba: per adapter instance
508 ufshcd_reset_intr_aggr(struct ufs_hba *hba)
510 ufshcd_writel(hba, INT_AGGR_ENABLE |
511 INT_AGGR_COUNTER_AND_TIMER_RESET,
512 REG_UTP_TRANSFER_REQ_INT_AGG_CONTROL);
516 * ufshcd_config_intr_aggr - Configure interrupt aggregation values.
517 * @hba: per adapter instance
518 * @cnt: Interrupt aggregation counter threshold
519 * @tmout: Interrupt aggregation timeout value
522 ufshcd_config_intr_aggr(struct ufs_hba *hba, u8 cnt, u8 tmout)
524 ufshcd_writel(hba, INT_AGGR_ENABLE | INT_AGGR_PARAM_WRITE |
525 INT_AGGR_COUNTER_THLD_VAL(cnt) |
526 INT_AGGR_TIMEOUT_VAL(tmout),
527 REG_UTP_TRANSFER_REQ_INT_AGG_CONTROL);
531 * ufshcd_disable_intr_aggr - Disables interrupt aggregation.
532 * @hba: per adapter instance
534 static inline void ufshcd_disable_intr_aggr(struct ufs_hba *hba)
536 ufshcd_writel(hba, 0, REG_UTP_TRANSFER_REQ_INT_AGG_CONTROL);
540 * ufshcd_enable_run_stop_reg - Enable run-stop registers,
541 * When run-stop registers are set to 1, it indicates the
542 * host controller that it can process the requests
543 * @hba: per adapter instance
545 static void ufshcd_enable_run_stop_reg(struct ufs_hba *hba)
547 ufshcd_writel(hba, UTP_TASK_REQ_LIST_RUN_STOP_BIT,
548 REG_UTP_TASK_REQ_LIST_RUN_STOP);
549 ufshcd_writel(hba, UTP_TRANSFER_REQ_LIST_RUN_STOP_BIT,
550 REG_UTP_TRANSFER_REQ_LIST_RUN_STOP);
554 * ufshcd_hba_start - Start controller initialization sequence
555 * @hba: per adapter instance
557 static inline void ufshcd_hba_start(struct ufs_hba *hba)
559 ufshcd_writel(hba, CONTROLLER_ENABLE, REG_CONTROLLER_ENABLE);
563 * ufshcd_is_hba_active - Get controller state
564 * @hba: per adapter instance
566 * Returns zero if controller is active, 1 otherwise
568 static inline int ufshcd_is_hba_active(struct ufs_hba *hba)
570 return (ufshcd_readl(hba, REG_CONTROLLER_ENABLE) & 0x1) ? 0 : 1;
573 static void ufshcd_ungate_work(struct work_struct *work)
577 struct ufs_hba *hba = container_of(work, struct ufs_hba,
578 clk_gating.ungate_work);
580 cancel_delayed_work_sync(&hba->clk_gating.gate_work);
582 spin_lock_irqsave(hba->host->host_lock, flags);
583 if (hba->clk_gating.state == CLKS_ON) {
584 spin_unlock_irqrestore(hba->host->host_lock, flags);
588 spin_unlock_irqrestore(hba->host->host_lock, flags);
589 ufshcd_setup_clocks(hba, true);
591 /* Exit from hibern8 */
592 if (ufshcd_can_hibern8_during_gating(hba)) {
593 /* Prevent gating in this path */
594 hba->clk_gating.is_suspended = true;
595 if (ufshcd_is_link_hibern8(hba)) {
596 ret = ufshcd_uic_hibern8_exit(hba);
598 dev_err(hba->dev, "%s: hibern8 exit failed %d\n",
601 ufshcd_set_link_active(hba);
603 hba->clk_gating.is_suspended = false;
606 if (ufshcd_is_clkscaling_enabled(hba))
607 devfreq_resume_device(hba->devfreq);
608 scsi_unblock_requests(hba->host);
612 * ufshcd_hold - Enable clocks that were gated earlier due to ufshcd_release.
613 * Also, exit from hibern8 mode and set the link as active.
614 * @hba: per adapter instance
615 * @async: This indicates whether caller should ungate clocks asynchronously.
617 int ufshcd_hold(struct ufs_hba *hba, bool async)
622 if (!ufshcd_is_clkgating_allowed(hba))
624 spin_lock_irqsave(hba->host->host_lock, flags);
625 hba->clk_gating.active_reqs++;
627 if (ufshcd_eh_in_progress(hba)) {
628 spin_unlock_irqrestore(hba->host->host_lock, flags);
633 switch (hba->clk_gating.state) {
637 if (cancel_delayed_work(&hba->clk_gating.gate_work)) {
638 hba->clk_gating.state = CLKS_ON;
642 * If we here, it means gating work is either done or
643 * currently running. Hence, fall through to cancel gating
644 * work and to enable clocks.
647 scsi_block_requests(hba->host);
648 hba->clk_gating.state = REQ_CLKS_ON;
649 schedule_work(&hba->clk_gating.ungate_work);
651 * fall through to check if we should wait for this
652 * work to be done or not.
657 hba->clk_gating.active_reqs--;
661 spin_unlock_irqrestore(hba->host->host_lock, flags);
662 flush_work(&hba->clk_gating.ungate_work);
663 /* Make sure state is CLKS_ON before returning */
664 spin_lock_irqsave(hba->host->host_lock, flags);
667 dev_err(hba->dev, "%s: clk gating is in invalid state %d\n",
668 __func__, hba->clk_gating.state);
671 spin_unlock_irqrestore(hba->host->host_lock, flags);
675 EXPORT_SYMBOL_GPL(ufshcd_hold);
677 static void ufshcd_gate_work(struct work_struct *work)
679 struct ufs_hba *hba = container_of(work, struct ufs_hba,
680 clk_gating.gate_work.work);
683 spin_lock_irqsave(hba->host->host_lock, flags);
684 if (hba->clk_gating.is_suspended) {
685 hba->clk_gating.state = CLKS_ON;
689 if (hba->clk_gating.active_reqs
690 || hba->ufshcd_state != UFSHCD_STATE_OPERATIONAL
691 || hba->lrb_in_use || hba->outstanding_tasks
692 || hba->active_uic_cmd || hba->uic_async_done)
695 spin_unlock_irqrestore(hba->host->host_lock, flags);
697 /* put the link into hibern8 mode before turning off clocks */
698 if (ufshcd_can_hibern8_during_gating(hba)) {
699 if (ufshcd_uic_hibern8_enter(hba)) {
700 hba->clk_gating.state = CLKS_ON;
703 ufshcd_set_link_hibern8(hba);
706 if (ufshcd_is_clkscaling_enabled(hba)) {
707 devfreq_suspend_device(hba->devfreq);
708 hba->clk_scaling.window_start_t = 0;
711 if (!ufshcd_is_link_active(hba))
712 ufshcd_setup_clocks(hba, false);
714 /* If link is active, device ref_clk can't be switched off */
715 __ufshcd_setup_clocks(hba, false, true);
718 * In case you are here to cancel this work the gating state
719 * would be marked as REQ_CLKS_ON. In this case keep the state
720 * as REQ_CLKS_ON which would anyway imply that clocks are off
721 * and a request to turn them on is pending. By doing this way,
722 * we keep the state machine in tact and this would ultimately
723 * prevent from doing cancel work multiple times when there are
724 * new requests arriving before the current cancel work is done.
726 spin_lock_irqsave(hba->host->host_lock, flags);
727 if (hba->clk_gating.state == REQ_CLKS_OFF)
728 hba->clk_gating.state = CLKS_OFF;
731 spin_unlock_irqrestore(hba->host->host_lock, flags);
736 /* host lock must be held before calling this variant */
737 static void __ufshcd_release(struct ufs_hba *hba)
739 if (!ufshcd_is_clkgating_allowed(hba))
742 hba->clk_gating.active_reqs--;
744 if (hba->clk_gating.active_reqs || hba->clk_gating.is_suspended
745 || hba->ufshcd_state != UFSHCD_STATE_OPERATIONAL
746 || hba->lrb_in_use || hba->outstanding_tasks
747 || hba->active_uic_cmd || hba->uic_async_done
748 || ufshcd_eh_in_progress(hba))
751 hba->clk_gating.state = REQ_CLKS_OFF;
752 schedule_delayed_work(&hba->clk_gating.gate_work,
753 msecs_to_jiffies(hba->clk_gating.delay_ms));
756 void ufshcd_release(struct ufs_hba *hba)
760 spin_lock_irqsave(hba->host->host_lock, flags);
761 __ufshcd_release(hba);
762 spin_unlock_irqrestore(hba->host->host_lock, flags);
764 EXPORT_SYMBOL_GPL(ufshcd_release);
766 static ssize_t ufshcd_clkgate_delay_show(struct device *dev,
767 struct device_attribute *attr, char *buf)
769 struct ufs_hba *hba = dev_get_drvdata(dev);
771 return snprintf(buf, PAGE_SIZE, "%lu\n", hba->clk_gating.delay_ms);
774 static ssize_t ufshcd_clkgate_delay_store(struct device *dev,
775 struct device_attribute *attr, const char *buf, size_t count)
777 struct ufs_hba *hba = dev_get_drvdata(dev);
778 unsigned long flags, value;
780 if (kstrtoul(buf, 0, &value))
783 spin_lock_irqsave(hba->host->host_lock, flags);
784 hba->clk_gating.delay_ms = value;
785 spin_unlock_irqrestore(hba->host->host_lock, flags);
789 static void ufshcd_init_clk_gating(struct ufs_hba *hba)
791 if (!ufshcd_is_clkgating_allowed(hba))
794 hba->clk_gating.delay_ms = 150;
795 INIT_DELAYED_WORK(&hba->clk_gating.gate_work, ufshcd_gate_work);
796 INIT_WORK(&hba->clk_gating.ungate_work, ufshcd_ungate_work);
798 hba->clk_gating.delay_attr.show = ufshcd_clkgate_delay_show;
799 hba->clk_gating.delay_attr.store = ufshcd_clkgate_delay_store;
800 sysfs_attr_init(&hba->clk_gating.delay_attr.attr);
801 hba->clk_gating.delay_attr.attr.name = "clkgate_delay_ms";
802 hba->clk_gating.delay_attr.attr.mode = S_IRUGO | S_IWUSR;
803 if (device_create_file(hba->dev, &hba->clk_gating.delay_attr))
804 dev_err(hba->dev, "Failed to create sysfs for clkgate_delay\n");
807 static void ufshcd_exit_clk_gating(struct ufs_hba *hba)
809 if (!ufshcd_is_clkgating_allowed(hba))
811 device_remove_file(hba->dev, &hba->clk_gating.delay_attr);
812 cancel_work_sync(&hba->clk_gating.ungate_work);
813 cancel_delayed_work_sync(&hba->clk_gating.gate_work);
816 /* Must be called with host lock acquired */
817 static void ufshcd_clk_scaling_start_busy(struct ufs_hba *hba)
819 if (!ufshcd_is_clkscaling_enabled(hba))
822 if (!hba->clk_scaling.is_busy_started) {
823 hba->clk_scaling.busy_start_t = ktime_get();
824 hba->clk_scaling.is_busy_started = true;
828 static void ufshcd_clk_scaling_update_busy(struct ufs_hba *hba)
830 struct ufs_clk_scaling *scaling = &hba->clk_scaling;
832 if (!ufshcd_is_clkscaling_enabled(hba))
835 if (!hba->outstanding_reqs && scaling->is_busy_started) {
836 scaling->tot_busy_t += ktime_to_us(ktime_sub(ktime_get(),
837 scaling->busy_start_t));
838 scaling->busy_start_t = ktime_set(0, 0);
839 scaling->is_busy_started = false;
843 * ufshcd_send_command - Send SCSI or device management commands
844 * @hba: per adapter instance
845 * @task_tag: Task tag of the command
848 void ufshcd_send_command(struct ufs_hba *hba, unsigned int task_tag)
850 ufshcd_clk_scaling_start_busy(hba);
851 __set_bit(task_tag, &hba->outstanding_reqs);
852 ufshcd_writel(hba, 1 << task_tag, REG_UTP_TRANSFER_REQ_DOOR_BELL);
856 * ufshcd_copy_sense_data - Copy sense data in case of check condition
857 * @lrb - pointer to local reference block
859 static inline void ufshcd_copy_sense_data(struct ufshcd_lrb *lrbp)
862 if (lrbp->sense_buffer &&
863 ufshcd_get_rsp_upiu_data_seg_len(lrbp->ucd_rsp_ptr)) {
864 len = be16_to_cpu(lrbp->ucd_rsp_ptr->sr.sense_data_len);
865 memcpy(lrbp->sense_buffer,
866 lrbp->ucd_rsp_ptr->sr.sense_data,
867 min_t(int, len, SCSI_SENSE_BUFFERSIZE));
872 * ufshcd_copy_query_response() - Copy the Query Response and the data
874 * @hba: per adapter instance
875 * @lrb - pointer to local reference block
878 int ufshcd_copy_query_response(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
880 struct ufs_query_res *query_res = &hba->dev_cmd.query.response;
882 memcpy(&query_res->upiu_res, &lrbp->ucd_rsp_ptr->qr, QUERY_OSF_SIZE);
884 /* Get the descriptor */
885 if (lrbp->ucd_rsp_ptr->qr.opcode == UPIU_QUERY_OPCODE_READ_DESC) {
886 u8 *descp = (u8 *)lrbp->ucd_rsp_ptr +
887 GENERAL_UPIU_REQUEST_SIZE;
891 /* data segment length */
892 resp_len = be32_to_cpu(lrbp->ucd_rsp_ptr->header.dword_2) &
893 MASK_QUERY_DATA_SEG_LEN;
894 buf_len = be16_to_cpu(
895 hba->dev_cmd.query.request.upiu_req.length);
896 if (likely(buf_len >= resp_len)) {
897 memcpy(hba->dev_cmd.query.descriptor, descp, resp_len);
900 "%s: Response size is bigger than buffer",
910 * ufshcd_hba_capabilities - Read controller capabilities
911 * @hba: per adapter instance
913 static inline void ufshcd_hba_capabilities(struct ufs_hba *hba)
915 hba->capabilities = ufshcd_readl(hba, REG_CONTROLLER_CAPABILITIES);
917 /* nutrs and nutmrs are 0 based values */
918 hba->nutrs = (hba->capabilities & MASK_TRANSFER_REQUESTS_SLOTS) + 1;
920 ((hba->capabilities & MASK_TASK_MANAGEMENT_REQUEST_SLOTS) >> 16) + 1;
924 * ufshcd_ready_for_uic_cmd - Check if controller is ready
925 * to accept UIC commands
926 * @hba: per adapter instance
927 * Return true on success, else false
929 static inline bool ufshcd_ready_for_uic_cmd(struct ufs_hba *hba)
931 if (ufshcd_readl(hba, REG_CONTROLLER_STATUS) & UIC_COMMAND_READY)
938 * ufshcd_get_upmcrs - Get the power mode change request status
939 * @hba: Pointer to adapter instance
941 * This function gets the UPMCRS field of HCS register
942 * Returns value of UPMCRS field
944 static inline u8 ufshcd_get_upmcrs(struct ufs_hba *hba)
946 return (ufshcd_readl(hba, REG_CONTROLLER_STATUS) >> 8) & 0x7;
950 * ufshcd_dispatch_uic_cmd - Dispatch UIC commands to unipro layers
951 * @hba: per adapter instance
952 * @uic_cmd: UIC command
954 * Mutex must be held.
957 ufshcd_dispatch_uic_cmd(struct ufs_hba *hba, struct uic_command *uic_cmd)
959 WARN_ON(hba->active_uic_cmd);
961 hba->active_uic_cmd = uic_cmd;
964 ufshcd_writel(hba, uic_cmd->argument1, REG_UIC_COMMAND_ARG_1);
965 ufshcd_writel(hba, uic_cmd->argument2, REG_UIC_COMMAND_ARG_2);
966 ufshcd_writel(hba, uic_cmd->argument3, REG_UIC_COMMAND_ARG_3);
969 ufshcd_writel(hba, uic_cmd->command & COMMAND_OPCODE_MASK,
974 * ufshcd_wait_for_uic_cmd - Wait complectioin of UIC command
975 * @hba: per adapter instance
976 * @uic_command: UIC command
978 * Must be called with mutex held.
979 * Returns 0 only if success.
982 ufshcd_wait_for_uic_cmd(struct ufs_hba *hba, struct uic_command *uic_cmd)
987 if (wait_for_completion_timeout(&uic_cmd->done,
988 msecs_to_jiffies(UIC_CMD_TIMEOUT)))
989 ret = uic_cmd->argument2 & MASK_UIC_COMMAND_RESULT;
993 spin_lock_irqsave(hba->host->host_lock, flags);
994 hba->active_uic_cmd = NULL;
995 spin_unlock_irqrestore(hba->host->host_lock, flags);
1001 * __ufshcd_send_uic_cmd - Send UIC commands and retrieve the result
1002 * @hba: per adapter instance
1003 * @uic_cmd: UIC command
1004 * @completion: initialize the completion only if this is set to true
1006 * Identical to ufshcd_send_uic_cmd() expect mutex. Must be called
1007 * with mutex held and host_lock locked.
1008 * Returns 0 only if success.
1011 __ufshcd_send_uic_cmd(struct ufs_hba *hba, struct uic_command *uic_cmd,
1014 if (!ufshcd_ready_for_uic_cmd(hba)) {
1016 "Controller not ready to accept UIC commands\n");
1021 init_completion(&uic_cmd->done);
1023 ufshcd_dispatch_uic_cmd(hba, uic_cmd);
1029 * ufshcd_send_uic_cmd - Send UIC commands and retrieve the result
1030 * @hba: per adapter instance
1031 * @uic_cmd: UIC command
1033 * Returns 0 only if success.
1036 ufshcd_send_uic_cmd(struct ufs_hba *hba, struct uic_command *uic_cmd)
1039 unsigned long flags;
1041 ufshcd_hold(hba, false);
1042 mutex_lock(&hba->uic_cmd_mutex);
1043 ufshcd_add_delay_before_dme_cmd(hba);
1045 spin_lock_irqsave(hba->host->host_lock, flags);
1046 ret = __ufshcd_send_uic_cmd(hba, uic_cmd, true);
1047 spin_unlock_irqrestore(hba->host->host_lock, flags);
1049 ret = ufshcd_wait_for_uic_cmd(hba, uic_cmd);
1051 mutex_unlock(&hba->uic_cmd_mutex);
1053 ufshcd_release(hba);
1058 * ufshcd_map_sg - Map scatter-gather list to prdt
1059 * @lrbp - pointer to local reference block
1061 * Returns 0 in case of success, non-zero value in case of failure
1063 static int ufshcd_map_sg(struct ufshcd_lrb *lrbp)
1065 struct ufshcd_sg_entry *prd_table;
1066 struct scatterlist *sg;
1067 struct scsi_cmnd *cmd;
1072 sg_segments = scsi_dma_map(cmd);
1073 if (sg_segments < 0)
1077 lrbp->utr_descriptor_ptr->prd_table_length =
1078 cpu_to_le16((u16) (sg_segments));
1080 prd_table = (struct ufshcd_sg_entry *)lrbp->ucd_prdt_ptr;
1082 scsi_for_each_sg(cmd, sg, sg_segments, i) {
1084 cpu_to_le32(((u32) sg_dma_len(sg))-1);
1085 prd_table[i].base_addr =
1086 cpu_to_le32(lower_32_bits(sg->dma_address));
1087 prd_table[i].upper_addr =
1088 cpu_to_le32(upper_32_bits(sg->dma_address));
1089 prd_table[i].reserved = 0;
1092 lrbp->utr_descriptor_ptr->prd_table_length = 0;
1099 * ufshcd_enable_intr - enable interrupts
1100 * @hba: per adapter instance
1101 * @intrs: interrupt bits
1103 static void ufshcd_enable_intr(struct ufs_hba *hba, u32 intrs)
1105 u32 set = ufshcd_readl(hba, REG_INTERRUPT_ENABLE);
1107 if (hba->ufs_version == UFSHCI_VERSION_10) {
1109 rw = set & INTERRUPT_MASK_RW_VER_10;
1110 set = rw | ((set ^ intrs) & intrs);
1115 ufshcd_writel(hba, set, REG_INTERRUPT_ENABLE);
1119 * ufshcd_disable_intr - disable interrupts
1120 * @hba: per adapter instance
1121 * @intrs: interrupt bits
1123 static void ufshcd_disable_intr(struct ufs_hba *hba, u32 intrs)
1125 u32 set = ufshcd_readl(hba, REG_INTERRUPT_ENABLE);
1127 if (hba->ufs_version == UFSHCI_VERSION_10) {
1129 rw = (set & INTERRUPT_MASK_RW_VER_10) &
1130 ~(intrs & INTERRUPT_MASK_RW_VER_10);
1131 set = rw | ((set & intrs) & ~INTERRUPT_MASK_RW_VER_10);
1137 ufshcd_writel(hba, set, REG_INTERRUPT_ENABLE);
1141 * ufshcd_prepare_req_desc_hdr() - Fills the requests header
1142 * descriptor according to request
1143 * @lrbp: pointer to local reference block
1144 * @upiu_flags: flags required in the header
1145 * @cmd_dir: requests data direction
1147 static void ufshcd_prepare_req_desc_hdr(struct ufshcd_lrb *lrbp,
1148 u32 *upiu_flags, enum dma_data_direction cmd_dir)
1150 struct utp_transfer_req_desc *req_desc = lrbp->utr_descriptor_ptr;
1154 if (cmd_dir == DMA_FROM_DEVICE) {
1155 data_direction = UTP_DEVICE_TO_HOST;
1156 *upiu_flags = UPIU_CMD_FLAGS_READ;
1157 } else if (cmd_dir == DMA_TO_DEVICE) {
1158 data_direction = UTP_HOST_TO_DEVICE;
1159 *upiu_flags = UPIU_CMD_FLAGS_WRITE;
1161 data_direction = UTP_NO_DATA_TRANSFER;
1162 *upiu_flags = UPIU_CMD_FLAGS_NONE;
1165 dword_0 = data_direction | (lrbp->command_type
1166 << UPIU_COMMAND_TYPE_OFFSET);
1168 dword_0 |= UTP_REQ_DESC_INT_CMD;
1170 /* Transfer request descriptor header fields */
1171 req_desc->header.dword_0 = cpu_to_le32(dword_0);
1172 /* dword_1 is reserved, hence it is set to 0 */
1173 req_desc->header.dword_1 = 0;
1175 * assigning invalid value for command status. Controller
1176 * updates OCS on command completion, with the command
1179 req_desc->header.dword_2 =
1180 cpu_to_le32(OCS_INVALID_COMMAND_STATUS);
1181 /* dword_3 is reserved, hence it is set to 0 */
1182 req_desc->header.dword_3 = 0;
1184 req_desc->prd_table_length = 0;
1188 * ufshcd_prepare_utp_scsi_cmd_upiu() - fills the utp_transfer_req_desc,
1190 * @lrbp - local reference block pointer
1191 * @upiu_flags - flags
1194 void ufshcd_prepare_utp_scsi_cmd_upiu(struct ufshcd_lrb *lrbp, u32 upiu_flags)
1196 struct utp_upiu_req *ucd_req_ptr = lrbp->ucd_req_ptr;
1197 unsigned short cdb_len;
1199 /* command descriptor fields */
1200 ucd_req_ptr->header.dword_0 = UPIU_HEADER_DWORD(
1201 UPIU_TRANSACTION_COMMAND, upiu_flags,
1202 lrbp->lun, lrbp->task_tag);
1203 ucd_req_ptr->header.dword_1 = UPIU_HEADER_DWORD(
1204 UPIU_COMMAND_SET_TYPE_SCSI, 0, 0, 0);
1206 /* Total EHS length and Data segment length will be zero */
1207 ucd_req_ptr->header.dword_2 = 0;
1209 ucd_req_ptr->sc.exp_data_transfer_len =
1210 cpu_to_be32(lrbp->cmd->sdb.length);
1212 cdb_len = min_t(unsigned short, lrbp->cmd->cmd_len, MAX_CDB_SIZE);
1213 memset(ucd_req_ptr->sc.cdb, 0, MAX_CDB_SIZE);
1214 memcpy(ucd_req_ptr->sc.cdb, lrbp->cmd->cmnd, cdb_len);
1216 memset(lrbp->ucd_rsp_ptr, 0, sizeof(struct utp_upiu_rsp));
1220 * ufshcd_prepare_utp_query_req_upiu() - fills the utp_transfer_req_desc,
1223 * @lrbp: local reference block pointer
1224 * @upiu_flags: flags
1226 static void ufshcd_prepare_utp_query_req_upiu(struct ufs_hba *hba,
1227 struct ufshcd_lrb *lrbp, u32 upiu_flags)
1229 struct utp_upiu_req *ucd_req_ptr = lrbp->ucd_req_ptr;
1230 struct ufs_query *query = &hba->dev_cmd.query;
1231 u16 len = be16_to_cpu(query->request.upiu_req.length);
1232 u8 *descp = (u8 *)lrbp->ucd_req_ptr + GENERAL_UPIU_REQUEST_SIZE;
1234 /* Query request header */
1235 ucd_req_ptr->header.dword_0 = UPIU_HEADER_DWORD(
1236 UPIU_TRANSACTION_QUERY_REQ, upiu_flags,
1237 lrbp->lun, lrbp->task_tag);
1238 ucd_req_ptr->header.dword_1 = UPIU_HEADER_DWORD(
1239 0, query->request.query_func, 0, 0);
1241 /* Data segment length */
1242 ucd_req_ptr->header.dword_2 = UPIU_HEADER_DWORD(
1243 0, 0, len >> 8, (u8)len);
1245 /* Copy the Query Request buffer as is */
1246 memcpy(&ucd_req_ptr->qr, &query->request.upiu_req,
1249 /* Copy the Descriptor */
1250 if (query->request.upiu_req.opcode == UPIU_QUERY_OPCODE_WRITE_DESC)
1251 memcpy(descp, query->descriptor, len);
1253 memset(lrbp->ucd_rsp_ptr, 0, sizeof(struct utp_upiu_rsp));
1256 static inline void ufshcd_prepare_utp_nop_upiu(struct ufshcd_lrb *lrbp)
1258 struct utp_upiu_req *ucd_req_ptr = lrbp->ucd_req_ptr;
1260 memset(ucd_req_ptr, 0, sizeof(struct utp_upiu_req));
1262 /* command descriptor fields */
1263 ucd_req_ptr->header.dword_0 =
1265 UPIU_TRANSACTION_NOP_OUT, 0, 0, lrbp->task_tag);
1266 /* clear rest of the fields of basic header */
1267 ucd_req_ptr->header.dword_1 = 0;
1268 ucd_req_ptr->header.dword_2 = 0;
1270 memset(lrbp->ucd_rsp_ptr, 0, sizeof(struct utp_upiu_rsp));
1274 * ufshcd_compose_upiu - form UFS Protocol Information Unit(UPIU)
1275 * @hba - per adapter instance
1276 * @lrb - pointer to local reference block
1278 static int ufshcd_compose_upiu(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
1283 switch (lrbp->command_type) {
1284 case UTP_CMD_TYPE_SCSI:
1285 if (likely(lrbp->cmd)) {
1286 ufshcd_prepare_req_desc_hdr(lrbp, &upiu_flags,
1287 lrbp->cmd->sc_data_direction);
1288 ufshcd_prepare_utp_scsi_cmd_upiu(lrbp, upiu_flags);
1293 case UTP_CMD_TYPE_DEV_MANAGE:
1294 ufshcd_prepare_req_desc_hdr(lrbp, &upiu_flags, DMA_NONE);
1295 if (hba->dev_cmd.type == DEV_CMD_TYPE_QUERY)
1296 ufshcd_prepare_utp_query_req_upiu(
1297 hba, lrbp, upiu_flags);
1298 else if (hba->dev_cmd.type == DEV_CMD_TYPE_NOP)
1299 ufshcd_prepare_utp_nop_upiu(lrbp);
1303 case UTP_CMD_TYPE_UFS:
1304 /* For UFS native command implementation */
1306 dev_err(hba->dev, "%s: UFS native command are not supported\n",
1311 dev_err(hba->dev, "%s: unknown command type: 0x%x\n",
1312 __func__, lrbp->command_type);
1314 } /* end of switch */
1320 * ufshcd_scsi_to_upiu_lun - maps scsi LUN to UPIU LUN
1321 * @scsi_lun: scsi LUN id
1323 * Returns UPIU LUN id
1325 static inline u8 ufshcd_scsi_to_upiu_lun(unsigned int scsi_lun)
1327 if (scsi_is_wlun(scsi_lun))
1328 return (scsi_lun & UFS_UPIU_MAX_UNIT_NUM_ID)
1331 return scsi_lun & UFS_UPIU_MAX_UNIT_NUM_ID;
1335 * ufshcd_upiu_wlun_to_scsi_wlun - maps UPIU W-LUN id to SCSI W-LUN ID
1336 * @scsi_lun: UPIU W-LUN id
1338 * Returns SCSI W-LUN id
1340 static inline u16 ufshcd_upiu_wlun_to_scsi_wlun(u8 upiu_wlun_id)
1342 return (upiu_wlun_id & ~UFS_UPIU_WLUN_ID) | SCSI_W_LUN_BASE;
1346 * ufshcd_queuecommand - main entry point for SCSI requests
1347 * @cmd: command from SCSI Midlayer
1348 * @done: call back function
1350 * Returns 0 for success, non-zero in case of failure
1352 static int ufshcd_queuecommand(struct Scsi_Host *host, struct scsi_cmnd *cmd)
1354 struct ufshcd_lrb *lrbp;
1355 struct ufs_hba *hba;
1356 unsigned long flags;
1360 hba = shost_priv(host);
1362 tag = cmd->request->tag;
1363 if (!ufshcd_valid_tag(hba, tag)) {
1365 "%s: invalid command tag %d: cmd=0x%p, cmd->request=0x%p",
1366 __func__, tag, cmd, cmd->request);
1370 spin_lock_irqsave(hba->host->host_lock, flags);
1371 switch (hba->ufshcd_state) {
1372 case UFSHCD_STATE_OPERATIONAL:
1374 case UFSHCD_STATE_RESET:
1375 err = SCSI_MLQUEUE_HOST_BUSY;
1377 case UFSHCD_STATE_ERROR:
1378 set_host_byte(cmd, DID_ERROR);
1379 cmd->scsi_done(cmd);
1382 dev_WARN_ONCE(hba->dev, 1, "%s: invalid state %d\n",
1383 __func__, hba->ufshcd_state);
1384 set_host_byte(cmd, DID_BAD_TARGET);
1385 cmd->scsi_done(cmd);
1389 /* if error handling is in progress, don't issue commands */
1390 if (ufshcd_eh_in_progress(hba)) {
1391 set_host_byte(cmd, DID_ERROR);
1392 cmd->scsi_done(cmd);
1395 spin_unlock_irqrestore(hba->host->host_lock, flags);
1397 /* acquire the tag to make sure device cmds don't use it */
1398 if (test_and_set_bit_lock(tag, &hba->lrb_in_use)) {
1400 * Dev manage command in progress, requeue the command.
1401 * Requeuing the command helps in cases where the request *may*
1402 * find different tag instead of waiting for dev manage command
1405 err = SCSI_MLQUEUE_HOST_BUSY;
1409 err = ufshcd_hold(hba, true);
1411 err = SCSI_MLQUEUE_HOST_BUSY;
1412 clear_bit_unlock(tag, &hba->lrb_in_use);
1415 WARN_ON(hba->clk_gating.state != CLKS_ON);
1417 lrbp = &hba->lrb[tag];
1421 lrbp->sense_bufflen = SCSI_SENSE_BUFFERSIZE;
1422 lrbp->sense_buffer = cmd->sense_buffer;
1423 lrbp->task_tag = tag;
1424 lrbp->lun = ufshcd_scsi_to_upiu_lun(cmd->device->lun);
1425 lrbp->intr_cmd = !ufshcd_is_intr_aggr_allowed(hba) ? true : false;
1426 lrbp->command_type = UTP_CMD_TYPE_SCSI;
1428 /* form UPIU before issuing the command */
1429 ufshcd_compose_upiu(hba, lrbp);
1430 err = ufshcd_map_sg(lrbp);
1433 clear_bit_unlock(tag, &hba->lrb_in_use);
1437 /* issue command to the controller */
1438 spin_lock_irqsave(hba->host->host_lock, flags);
1439 ufshcd_send_command(hba, tag);
1441 spin_unlock_irqrestore(hba->host->host_lock, flags);
1446 static int ufshcd_compose_dev_cmd(struct ufs_hba *hba,
1447 struct ufshcd_lrb *lrbp, enum dev_cmd_type cmd_type, int tag)
1450 lrbp->sense_bufflen = 0;
1451 lrbp->sense_buffer = NULL;
1452 lrbp->task_tag = tag;
1453 lrbp->lun = 0; /* device management cmd is not specific to any LUN */
1454 lrbp->command_type = UTP_CMD_TYPE_DEV_MANAGE;
1455 lrbp->intr_cmd = true; /* No interrupt aggregation */
1456 hba->dev_cmd.type = cmd_type;
1458 return ufshcd_compose_upiu(hba, lrbp);
1462 ufshcd_clear_cmd(struct ufs_hba *hba, int tag)
1465 unsigned long flags;
1466 u32 mask = 1 << tag;
1468 /* clear outstanding transaction before retry */
1469 spin_lock_irqsave(hba->host->host_lock, flags);
1470 ufshcd_utrl_clear(hba, tag);
1471 spin_unlock_irqrestore(hba->host->host_lock, flags);
1474 * wait for for h/w to clear corresponding bit in door-bell.
1475 * max. wait is 1 sec.
1477 err = ufshcd_wait_for_register(hba,
1478 REG_UTP_TRANSFER_REQ_DOOR_BELL,
1479 mask, ~mask, 1000, 1000, true);
1485 ufshcd_check_query_response(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
1487 struct ufs_query_res *query_res = &hba->dev_cmd.query.response;
1489 /* Get the UPIU response */
1490 query_res->response = ufshcd_get_rsp_upiu_result(lrbp->ucd_rsp_ptr) >>
1491 UPIU_RSP_CODE_OFFSET;
1492 return query_res->response;
1496 * ufshcd_dev_cmd_completion() - handles device management command responses
1497 * @hba: per adapter instance
1498 * @lrbp: pointer to local reference block
1501 ufshcd_dev_cmd_completion(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
1506 resp = ufshcd_get_req_rsp(lrbp->ucd_rsp_ptr);
1509 case UPIU_TRANSACTION_NOP_IN:
1510 if (hba->dev_cmd.type != DEV_CMD_TYPE_NOP) {
1512 dev_err(hba->dev, "%s: unexpected response %x\n",
1516 case UPIU_TRANSACTION_QUERY_RSP:
1517 err = ufshcd_check_query_response(hba, lrbp);
1519 err = ufshcd_copy_query_response(hba, lrbp);
1521 case UPIU_TRANSACTION_REJECT_UPIU:
1522 /* TODO: handle Reject UPIU Response */
1524 dev_err(hba->dev, "%s: Reject UPIU not fully implemented\n",
1529 dev_err(hba->dev, "%s: Invalid device management cmd response: %x\n",
1537 static int ufshcd_wait_for_dev_cmd(struct ufs_hba *hba,
1538 struct ufshcd_lrb *lrbp, int max_timeout)
1541 unsigned long time_left;
1542 unsigned long flags;
1544 time_left = wait_for_completion_timeout(hba->dev_cmd.complete,
1545 msecs_to_jiffies(max_timeout));
1547 spin_lock_irqsave(hba->host->host_lock, flags);
1548 hba->dev_cmd.complete = NULL;
1549 if (likely(time_left)) {
1550 err = ufshcd_get_tr_ocs(lrbp);
1552 err = ufshcd_dev_cmd_completion(hba, lrbp);
1554 spin_unlock_irqrestore(hba->host->host_lock, flags);
1558 dev_dbg(hba->dev, "%s: dev_cmd request timedout, tag %d\n",
1559 __func__, lrbp->task_tag);
1560 if (!ufshcd_clear_cmd(hba, lrbp->task_tag))
1561 /* successfully cleared the command, retry if needed */
1564 * in case of an error, after clearing the doorbell,
1565 * we also need to clear the outstanding_request
1568 ufshcd_outstanding_req_clear(hba, lrbp->task_tag);
1575 * ufshcd_get_dev_cmd_tag - Get device management command tag
1576 * @hba: per-adapter instance
1577 * @tag: pointer to variable with available slot value
1579 * Get a free slot and lock it until device management command
1582 * Returns false if free slot is unavailable for locking, else
1583 * return true with tag value in @tag.
1585 static bool ufshcd_get_dev_cmd_tag(struct ufs_hba *hba, int *tag_out)
1595 tmp = ~hba->lrb_in_use;
1596 tag = find_last_bit(&tmp, hba->nutrs);
1597 if (tag >= hba->nutrs)
1599 } while (test_and_set_bit_lock(tag, &hba->lrb_in_use));
1607 static inline void ufshcd_put_dev_cmd_tag(struct ufs_hba *hba, int tag)
1609 clear_bit_unlock(tag, &hba->lrb_in_use);
1613 * ufshcd_exec_dev_cmd - API for sending device management requests
1615 * @cmd_type - specifies the type (NOP, Query...)
1616 * @timeout - time in seconds
1618 * NOTE: Since there is only one available tag for device management commands,
1619 * it is expected you hold the hba->dev_cmd.lock mutex.
1621 static int ufshcd_exec_dev_cmd(struct ufs_hba *hba,
1622 enum dev_cmd_type cmd_type, int timeout)
1624 struct ufshcd_lrb *lrbp;
1627 struct completion wait;
1628 unsigned long flags;
1631 * Get free slot, sleep if slots are unavailable.
1632 * Even though we use wait_event() which sleeps indefinitely,
1633 * the maximum wait time is bounded by SCSI request timeout.
1635 wait_event(hba->dev_cmd.tag_wq, ufshcd_get_dev_cmd_tag(hba, &tag));
1637 init_completion(&wait);
1638 lrbp = &hba->lrb[tag];
1640 err = ufshcd_compose_dev_cmd(hba, lrbp, cmd_type, tag);
1644 hba->dev_cmd.complete = &wait;
1646 /* Make sure descriptors are ready before ringing the doorbell */
1648 spin_lock_irqsave(hba->host->host_lock, flags);
1649 ufshcd_send_command(hba, tag);
1650 spin_unlock_irqrestore(hba->host->host_lock, flags);
1652 err = ufshcd_wait_for_dev_cmd(hba, lrbp, timeout);
1655 ufshcd_put_dev_cmd_tag(hba, tag);
1656 wake_up(&hba->dev_cmd.tag_wq);
1661 * ufshcd_init_query() - init the query response and request parameters
1662 * @hba: per-adapter instance
1663 * @request: address of the request pointer to be initialized
1664 * @response: address of the response pointer to be initialized
1665 * @opcode: operation to perform
1666 * @idn: flag idn to access
1667 * @index: LU number to access
1668 * @selector: query/flag/descriptor further identification
1670 static inline void ufshcd_init_query(struct ufs_hba *hba,
1671 struct ufs_query_req **request, struct ufs_query_res **response,
1672 enum query_opcode opcode, u8 idn, u8 index, u8 selector)
1674 *request = &hba->dev_cmd.query.request;
1675 *response = &hba->dev_cmd.query.response;
1676 memset(*request, 0, sizeof(struct ufs_query_req));
1677 memset(*response, 0, sizeof(struct ufs_query_res));
1678 (*request)->upiu_req.opcode = opcode;
1679 (*request)->upiu_req.idn = idn;
1680 (*request)->upiu_req.index = index;
1681 (*request)->upiu_req.selector = selector;
1684 static int ufshcd_query_flag_retry(struct ufs_hba *hba,
1685 enum query_opcode opcode, enum flag_idn idn, bool *flag_res)
1690 for (retries = 0; retries < QUERY_REQ_RETRIES; retries++) {
1691 ret = ufshcd_query_flag(hba, opcode, idn, flag_res);
1694 "%s: failed with error %d, retries %d\n",
1695 __func__, ret, retries);
1702 "%s: query attribute, opcode %d, idn %d, failed with error %d after %d retires\n",
1703 __func__, opcode, idn, ret, retries);
1708 * ufshcd_query_flag() - API function for sending flag query requests
1709 * hba: per-adapter instance
1710 * query_opcode: flag query to perform
1711 * idn: flag idn to access
1712 * flag_res: the flag value after the query request completes
1714 * Returns 0 for success, non-zero in case of failure
1716 int ufshcd_query_flag(struct ufs_hba *hba, enum query_opcode opcode,
1717 enum flag_idn idn, bool *flag_res)
1719 struct ufs_query_req *request = NULL;
1720 struct ufs_query_res *response = NULL;
1721 int err, index = 0, selector = 0;
1722 int timeout = QUERY_REQ_TIMEOUT;
1726 ufshcd_hold(hba, false);
1727 mutex_lock(&hba->dev_cmd.lock);
1728 ufshcd_init_query(hba, &request, &response, opcode, idn, index,
1732 case UPIU_QUERY_OPCODE_SET_FLAG:
1733 case UPIU_QUERY_OPCODE_CLEAR_FLAG:
1734 case UPIU_QUERY_OPCODE_TOGGLE_FLAG:
1735 request->query_func = UPIU_QUERY_FUNC_STANDARD_WRITE_REQUEST;
1737 case UPIU_QUERY_OPCODE_READ_FLAG:
1738 request->query_func = UPIU_QUERY_FUNC_STANDARD_READ_REQUEST;
1740 /* No dummy reads */
1741 dev_err(hba->dev, "%s: Invalid argument for read request\n",
1749 "%s: Expected query flag opcode but got = %d\n",
1755 if (idn == QUERY_FLAG_IDN_FDEVICEINIT)
1756 timeout = QUERY_FDEVICEINIT_REQ_TIMEOUT;
1758 err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_QUERY, timeout);
1762 "%s: Sending flag query for idn %d failed, err = %d\n",
1763 __func__, idn, err);
1768 *flag_res = (be32_to_cpu(response->upiu_res.value) &
1769 MASK_QUERY_UPIU_FLAG_LOC) & 0x1;
1772 mutex_unlock(&hba->dev_cmd.lock);
1773 ufshcd_release(hba);
1778 * ufshcd_query_attr - API function for sending attribute requests
1779 * hba: per-adapter instance
1780 * opcode: attribute opcode
1781 * idn: attribute idn to access
1782 * index: index field
1783 * selector: selector field
1784 * attr_val: the attribute value after the query request completes
1786 * Returns 0 for success, non-zero in case of failure
1788 static int ufshcd_query_attr(struct ufs_hba *hba, enum query_opcode opcode,
1789 enum attr_idn idn, u8 index, u8 selector, u32 *attr_val)
1791 struct ufs_query_req *request = NULL;
1792 struct ufs_query_res *response = NULL;
1797 ufshcd_hold(hba, false);
1799 dev_err(hba->dev, "%s: attribute value required for opcode 0x%x\n",
1805 mutex_lock(&hba->dev_cmd.lock);
1806 ufshcd_init_query(hba, &request, &response, opcode, idn, index,
1810 case UPIU_QUERY_OPCODE_WRITE_ATTR:
1811 request->query_func = UPIU_QUERY_FUNC_STANDARD_WRITE_REQUEST;
1812 request->upiu_req.value = cpu_to_be32(*attr_val);
1814 case UPIU_QUERY_OPCODE_READ_ATTR:
1815 request->query_func = UPIU_QUERY_FUNC_STANDARD_READ_REQUEST;
1818 dev_err(hba->dev, "%s: Expected query attr opcode but got = 0x%.2x\n",
1824 err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_QUERY, QUERY_REQ_TIMEOUT);
1827 dev_err(hba->dev, "%s: opcode 0x%.2x for idn %d failed, err = %d\n",
1828 __func__, opcode, idn, err);
1832 *attr_val = be32_to_cpu(response->upiu_res.value);
1835 mutex_unlock(&hba->dev_cmd.lock);
1837 ufshcd_release(hba);
1842 * ufshcd_query_attr_retry() - API function for sending query
1843 * attribute with retries
1844 * @hba: per-adapter instance
1845 * @opcode: attribute opcode
1846 * @idn: attribute idn to access
1847 * @index: index field
1848 * @selector: selector field
1849 * @attr_val: the attribute value after the query request
1852 * Returns 0 for success, non-zero in case of failure
1854 static int ufshcd_query_attr_retry(struct ufs_hba *hba,
1855 enum query_opcode opcode, enum attr_idn idn, u8 index, u8 selector,
1861 for (retries = QUERY_REQ_RETRIES; retries > 0; retries--) {
1862 ret = ufshcd_query_attr(hba, opcode, idn, index,
1863 selector, attr_val);
1865 dev_dbg(hba->dev, "%s: failed with error %d, retries %d\n",
1866 __func__, ret, retries);
1873 "%s: query attribute, idn %d, failed with error %d after %d retires\n",
1874 __func__, idn, ret, QUERY_REQ_RETRIES);
1879 * ufshcd_query_descriptor - API function for sending descriptor requests
1880 * hba: per-adapter instance
1881 * opcode: attribute opcode
1882 * idn: attribute idn to access
1883 * index: index field
1884 * selector: selector field
1885 * desc_buf: the buffer that contains the descriptor
1886 * buf_len: length parameter passed to the device
1888 * Returns 0 for success, non-zero in case of failure.
1889 * The buf_len parameter will contain, on return, the length parameter
1890 * received on the response.
1892 static int ufshcd_query_descriptor(struct ufs_hba *hba,
1893 enum query_opcode opcode, enum desc_idn idn, u8 index,
1894 u8 selector, u8 *desc_buf, int *buf_len)
1896 struct ufs_query_req *request = NULL;
1897 struct ufs_query_res *response = NULL;
1902 ufshcd_hold(hba, false);
1904 dev_err(hba->dev, "%s: descriptor buffer required for opcode 0x%x\n",
1910 if (*buf_len <= QUERY_DESC_MIN_SIZE || *buf_len > QUERY_DESC_MAX_SIZE) {
1911 dev_err(hba->dev, "%s: descriptor buffer size (%d) is out of range\n",
1912 __func__, *buf_len);
1917 mutex_lock(&hba->dev_cmd.lock);
1918 ufshcd_init_query(hba, &request, &response, opcode, idn, index,
1920 hba->dev_cmd.query.descriptor = desc_buf;
1921 request->upiu_req.length = cpu_to_be16(*buf_len);
1924 case UPIU_QUERY_OPCODE_WRITE_DESC:
1925 request->query_func = UPIU_QUERY_FUNC_STANDARD_WRITE_REQUEST;
1927 case UPIU_QUERY_OPCODE_READ_DESC:
1928 request->query_func = UPIU_QUERY_FUNC_STANDARD_READ_REQUEST;
1932 "%s: Expected query descriptor opcode but got = 0x%.2x\n",
1938 err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_QUERY, QUERY_REQ_TIMEOUT);
1941 dev_err(hba->dev, "%s: opcode 0x%.2x for idn %d failed, err = %d\n",
1942 __func__, opcode, idn, err);
1946 hba->dev_cmd.query.descriptor = NULL;
1947 *buf_len = be16_to_cpu(response->upiu_res.length);
1950 mutex_unlock(&hba->dev_cmd.lock);
1952 ufshcd_release(hba);
1957 * ufshcd_read_desc_param - read the specified descriptor parameter
1958 * @hba: Pointer to adapter instance
1959 * @desc_id: descriptor idn value
1960 * @desc_index: descriptor index
1961 * @param_offset: offset of the parameter to read
1962 * @param_read_buf: pointer to buffer where parameter would be read
1963 * @param_size: sizeof(param_read_buf)
1965 * Return 0 in case of success, non-zero otherwise
1967 static int ufshcd_read_desc_param(struct ufs_hba *hba,
1968 enum desc_idn desc_id,
1977 bool is_kmalloc = true;
1980 if (desc_id >= QUERY_DESC_IDN_MAX)
1983 buff_len = ufs_query_desc_max_size[desc_id];
1984 if ((param_offset + param_size) > buff_len)
1987 if (!param_offset && (param_size == buff_len)) {
1988 /* memory space already available to hold full descriptor */
1989 desc_buf = param_read_buf;
1992 /* allocate memory to hold full descriptor */
1993 desc_buf = kmalloc(buff_len, GFP_KERNEL);
1998 ret = ufshcd_query_descriptor(hba, UPIU_QUERY_OPCODE_READ_DESC,
1999 desc_id, desc_index, 0, desc_buf,
2002 if (ret || (buff_len < ufs_query_desc_max_size[desc_id]) ||
2003 (desc_buf[QUERY_DESC_LENGTH_OFFSET] !=
2004 ufs_query_desc_max_size[desc_id])
2005 || (desc_buf[QUERY_DESC_DESC_TYPE_OFFSET] != desc_id)) {
2006 dev_err(hba->dev, "%s: Failed reading descriptor. desc_id %d param_offset %d buff_len %d ret %d",
2007 __func__, desc_id, param_offset, buff_len, ret);
2015 memcpy(param_read_buf, &desc_buf[param_offset], param_size);
2022 static inline int ufshcd_read_desc(struct ufs_hba *hba,
2023 enum desc_idn desc_id,
2028 return ufshcd_read_desc_param(hba, desc_id, desc_index, 0, buf, size);
2031 static inline int ufshcd_read_power_desc(struct ufs_hba *hba,
2035 return ufshcd_read_desc(hba, QUERY_DESC_IDN_POWER, 0, buf, size);
2038 int ufshcd_read_device_desc(struct ufs_hba *hba, u8 *buf, u32 size)
2040 return ufshcd_read_desc(hba, QUERY_DESC_IDN_DEVICE, 0, buf, size);
2042 EXPORT_SYMBOL(ufshcd_read_device_desc);
2045 * ufshcd_read_string_desc - read string descriptor
2046 * @hba: pointer to adapter instance
2047 * @desc_index: descriptor index
2048 * @buf: pointer to buffer where descriptor would be read
2049 * @size: size of buf
2050 * @ascii: if true convert from unicode to ascii characters
2052 * Return 0 in case of success, non-zero otherwise
2054 int ufshcd_read_string_desc(struct ufs_hba *hba, int desc_index, u8 *buf,
2055 u32 size, bool ascii)
2059 err = ufshcd_read_desc(hba,
2060 QUERY_DESC_IDN_STRING, desc_index, buf, size);
2063 dev_err(hba->dev, "%s: reading String Desc failed after %d retries. err = %d\n",
2064 __func__, QUERY_REQ_RETRIES, err);
2075 /* remove header and divide by 2 to move from UTF16 to UTF8 */
2076 ascii_len = (desc_len - QUERY_DESC_HDR_SIZE) / 2 + 1;
2077 if (size < ascii_len + QUERY_DESC_HDR_SIZE) {
2078 dev_err(hba->dev, "%s: buffer allocated size is too small\n",
2084 buff_ascii = kmalloc(ascii_len, GFP_KERNEL);
2091 * the descriptor contains string in UTF16 format
2092 * we need to convert to utf-8 so it can be displayed
2094 utf16s_to_utf8s((wchar_t *)&buf[QUERY_DESC_HDR_SIZE],
2095 desc_len - QUERY_DESC_HDR_SIZE,
2096 UTF16_BIG_ENDIAN, buff_ascii, ascii_len);
2098 /* replace non-printable or non-ASCII characters with spaces */
2099 for (i = 0; i < ascii_len; i++)
2100 ufshcd_remove_non_printable(&buff_ascii[i]);
2102 memset(buf + QUERY_DESC_HDR_SIZE, 0,
2103 size - QUERY_DESC_HDR_SIZE);
2104 memcpy(buf + QUERY_DESC_HDR_SIZE, buff_ascii, ascii_len);
2105 buf[QUERY_DESC_LENGTH_OFFSET] = ascii_len + QUERY_DESC_HDR_SIZE;
2112 EXPORT_SYMBOL(ufshcd_read_string_desc);
2115 * ufshcd_read_unit_desc_param - read the specified unit descriptor parameter
2116 * @hba: Pointer to adapter instance
2118 * @param_offset: offset of the parameter to read
2119 * @param_read_buf: pointer to buffer where parameter would be read
2120 * @param_size: sizeof(param_read_buf)
2122 * Return 0 in case of success, non-zero otherwise
2124 static inline int ufshcd_read_unit_desc_param(struct ufs_hba *hba,
2126 enum unit_desc_param param_offset,
2131 * Unit descriptors are only available for general purpose LUs (LUN id
2132 * from 0 to 7) and RPMB Well known LU.
2134 if (lun != UFS_UPIU_RPMB_WLUN && (lun >= UFS_UPIU_MAX_GENERAL_LUN))
2137 return ufshcd_read_desc_param(hba, QUERY_DESC_IDN_UNIT, lun,
2138 param_offset, param_read_buf, param_size);
2142 * ufshcd_memory_alloc - allocate memory for host memory space data structures
2143 * @hba: per adapter instance
2145 * 1. Allocate DMA memory for Command Descriptor array
2146 * Each command descriptor consist of Command UPIU, Response UPIU and PRDT
2147 * 2. Allocate DMA memory for UTP Transfer Request Descriptor List (UTRDL).
2148 * 3. Allocate DMA memory for UTP Task Management Request Descriptor List
2150 * 4. Allocate memory for local reference block(lrb).
2152 * Returns 0 for success, non-zero in case of failure
2154 static int ufshcd_memory_alloc(struct ufs_hba *hba)
2156 size_t utmrdl_size, utrdl_size, ucdl_size;
2158 /* Allocate memory for UTP command descriptors */
2159 ucdl_size = (sizeof(struct utp_transfer_cmd_desc) * hba->nutrs);
2160 hba->ucdl_base_addr = dmam_alloc_coherent(hba->dev,
2162 &hba->ucdl_dma_addr,
2166 * UFSHCI requires UTP command descriptor to be 128 byte aligned.
2167 * make sure hba->ucdl_dma_addr is aligned to PAGE_SIZE
2168 * if hba->ucdl_dma_addr is aligned to PAGE_SIZE, then it will
2169 * be aligned to 128 bytes as well
2171 if (!hba->ucdl_base_addr ||
2172 WARN_ON(hba->ucdl_dma_addr & (PAGE_SIZE - 1))) {
2174 "Command Descriptor Memory allocation failed\n");
2179 * Allocate memory for UTP Transfer descriptors
2180 * UFSHCI requires 1024 byte alignment of UTRD
2182 utrdl_size = (sizeof(struct utp_transfer_req_desc) * hba->nutrs);
2183 hba->utrdl_base_addr = dmam_alloc_coherent(hba->dev,
2185 &hba->utrdl_dma_addr,
2187 if (!hba->utrdl_base_addr ||
2188 WARN_ON(hba->utrdl_dma_addr & (PAGE_SIZE - 1))) {
2190 "Transfer Descriptor Memory allocation failed\n");
2195 * Allocate memory for UTP Task Management descriptors
2196 * UFSHCI requires 1024 byte alignment of UTMRD
2198 utmrdl_size = sizeof(struct utp_task_req_desc) * hba->nutmrs;
2199 hba->utmrdl_base_addr = dmam_alloc_coherent(hba->dev,
2201 &hba->utmrdl_dma_addr,
2203 if (!hba->utmrdl_base_addr ||
2204 WARN_ON(hba->utmrdl_dma_addr & (PAGE_SIZE - 1))) {
2206 "Task Management Descriptor Memory allocation failed\n");
2210 /* Allocate memory for local reference block */
2211 hba->lrb = devm_kzalloc(hba->dev,
2212 hba->nutrs * sizeof(struct ufshcd_lrb),
2215 dev_err(hba->dev, "LRB Memory allocation failed\n");
2224 * ufshcd_host_memory_configure - configure local reference block with
2226 * @hba: per adapter instance
2228 * Configure Host memory space
2229 * 1. Update Corresponding UTRD.UCDBA and UTRD.UCDBAU with UCD DMA
2231 * 2. Update each UTRD with Response UPIU offset, Response UPIU length
2233 * 3. Save the corresponding addresses of UTRD, UCD.CMD, UCD.RSP and UCD.PRDT
2234 * into local reference block.
2236 static void ufshcd_host_memory_configure(struct ufs_hba *hba)
2238 struct utp_transfer_cmd_desc *cmd_descp;
2239 struct utp_transfer_req_desc *utrdlp;
2240 dma_addr_t cmd_desc_dma_addr;
2241 dma_addr_t cmd_desc_element_addr;
2242 u16 response_offset;
2247 utrdlp = hba->utrdl_base_addr;
2248 cmd_descp = hba->ucdl_base_addr;
2251 offsetof(struct utp_transfer_cmd_desc, response_upiu);
2253 offsetof(struct utp_transfer_cmd_desc, prd_table);
2255 cmd_desc_size = sizeof(struct utp_transfer_cmd_desc);
2256 cmd_desc_dma_addr = hba->ucdl_dma_addr;
2258 for (i = 0; i < hba->nutrs; i++) {
2259 /* Configure UTRD with command descriptor base address */
2260 cmd_desc_element_addr =
2261 (cmd_desc_dma_addr + (cmd_desc_size * i));
2262 utrdlp[i].command_desc_base_addr_lo =
2263 cpu_to_le32(lower_32_bits(cmd_desc_element_addr));
2264 utrdlp[i].command_desc_base_addr_hi =
2265 cpu_to_le32(upper_32_bits(cmd_desc_element_addr));
2267 /* Response upiu and prdt offset should be in double words */
2268 utrdlp[i].response_upiu_offset =
2269 cpu_to_le16((response_offset >> 2));
2270 utrdlp[i].prd_table_offset =
2271 cpu_to_le16((prdt_offset >> 2));
2272 utrdlp[i].response_upiu_length =
2273 cpu_to_le16(ALIGNED_UPIU_SIZE >> 2);
2275 hba->lrb[i].utr_descriptor_ptr = (utrdlp + i);
2276 hba->lrb[i].ucd_req_ptr =
2277 (struct utp_upiu_req *)(cmd_descp + i);
2278 hba->lrb[i].ucd_rsp_ptr =
2279 (struct utp_upiu_rsp *)cmd_descp[i].response_upiu;
2280 hba->lrb[i].ucd_prdt_ptr =
2281 (struct ufshcd_sg_entry *)cmd_descp[i].prd_table;
2286 * ufshcd_dme_link_startup - Notify Unipro to perform link startup
2287 * @hba: per adapter instance
2289 * UIC_CMD_DME_LINK_STARTUP command must be issued to Unipro layer,
2290 * in order to initialize the Unipro link startup procedure.
2291 * Once the Unipro links are up, the device connected to the controller
2294 * Returns 0 on success, non-zero value on failure
2296 static int ufshcd_dme_link_startup(struct ufs_hba *hba)
2298 struct uic_command uic_cmd = {0};
2301 uic_cmd.command = UIC_CMD_DME_LINK_STARTUP;
2303 ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
2306 "dme-link-startup: error code %d\n", ret);
2310 static inline void ufshcd_add_delay_before_dme_cmd(struct ufs_hba *hba)
2312 #define MIN_DELAY_BEFORE_DME_CMDS_US 1000
2313 unsigned long min_sleep_time_us;
2315 if (!(hba->quirks & UFSHCD_QUIRK_DELAY_BEFORE_DME_CMDS))
2319 * last_dme_cmd_tstamp will be 0 only for 1st call to
2322 if (unlikely(!ktime_to_us(hba->last_dme_cmd_tstamp))) {
2323 min_sleep_time_us = MIN_DELAY_BEFORE_DME_CMDS_US;
2325 unsigned long delta =
2326 (unsigned long) ktime_to_us(
2327 ktime_sub(ktime_get(),
2328 hba->last_dme_cmd_tstamp));
2330 if (delta < MIN_DELAY_BEFORE_DME_CMDS_US)
2332 MIN_DELAY_BEFORE_DME_CMDS_US - delta;
2334 return; /* no more delay required */
2337 /* allow sleep for extra 50us if needed */
2338 usleep_range(min_sleep_time_us, min_sleep_time_us + 50);
2342 * ufshcd_dme_set_attr - UIC command for DME_SET, DME_PEER_SET
2343 * @hba: per adapter instance
2344 * @attr_sel: uic command argument1
2345 * @attr_set: attribute set type as uic command argument2
2346 * @mib_val: setting value as uic command argument3
2347 * @peer: indicate whether peer or local
2349 * Returns 0 on success, non-zero value on failure
2351 int ufshcd_dme_set_attr(struct ufs_hba *hba, u32 attr_sel,
2352 u8 attr_set, u32 mib_val, u8 peer)
2354 struct uic_command uic_cmd = {0};
2355 static const char *const action[] = {
2359 const char *set = action[!!peer];
2361 int retries = UFS_UIC_COMMAND_RETRIES;
2363 uic_cmd.command = peer ?
2364 UIC_CMD_DME_PEER_SET : UIC_CMD_DME_SET;
2365 uic_cmd.argument1 = attr_sel;
2366 uic_cmd.argument2 = UIC_ARG_ATTR_TYPE(attr_set);
2367 uic_cmd.argument3 = mib_val;
2370 /* for peer attributes we retry upon failure */
2371 ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
2373 dev_dbg(hba->dev, "%s: attr-id 0x%x val 0x%x error code %d\n",
2374 set, UIC_GET_ATTR_ID(attr_sel), mib_val, ret);
2375 } while (ret && peer && --retries);
2378 dev_err(hba->dev, "%s: attr-id 0x%x val 0x%x failed %d retries\n",
2379 set, UIC_GET_ATTR_ID(attr_sel), mib_val,
2384 EXPORT_SYMBOL_GPL(ufshcd_dme_set_attr);
2387 * ufshcd_dme_get_attr - UIC command for DME_GET, DME_PEER_GET
2388 * @hba: per adapter instance
2389 * @attr_sel: uic command argument1
2390 * @mib_val: the value of the attribute as returned by the UIC command
2391 * @peer: indicate whether peer or local
2393 * Returns 0 on success, non-zero value on failure
2395 int ufshcd_dme_get_attr(struct ufs_hba *hba, u32 attr_sel,
2396 u32 *mib_val, u8 peer)
2398 struct uic_command uic_cmd = {0};
2399 static const char *const action[] = {
2403 const char *get = action[!!peer];
2405 int retries = UFS_UIC_COMMAND_RETRIES;
2406 struct ufs_pa_layer_attr orig_pwr_info;
2407 struct ufs_pa_layer_attr temp_pwr_info;
2408 bool pwr_mode_change = false;
2410 if (peer && (hba->quirks & UFSHCD_QUIRK_DME_PEER_ACCESS_AUTO_MODE)) {
2411 orig_pwr_info = hba->pwr_info;
2412 temp_pwr_info = orig_pwr_info;
2414 if (orig_pwr_info.pwr_tx == FAST_MODE ||
2415 orig_pwr_info.pwr_rx == FAST_MODE) {
2416 temp_pwr_info.pwr_tx = FASTAUTO_MODE;
2417 temp_pwr_info.pwr_rx = FASTAUTO_MODE;
2418 pwr_mode_change = true;
2419 } else if (orig_pwr_info.pwr_tx == SLOW_MODE ||
2420 orig_pwr_info.pwr_rx == SLOW_MODE) {
2421 temp_pwr_info.pwr_tx = SLOWAUTO_MODE;
2422 temp_pwr_info.pwr_rx = SLOWAUTO_MODE;
2423 pwr_mode_change = true;
2425 if (pwr_mode_change) {
2426 ret = ufshcd_change_power_mode(hba, &temp_pwr_info);
2432 uic_cmd.command = peer ?
2433 UIC_CMD_DME_PEER_GET : UIC_CMD_DME_GET;
2434 uic_cmd.argument1 = attr_sel;
2437 /* for peer attributes we retry upon failure */
2438 ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
2440 dev_dbg(hba->dev, "%s: attr-id 0x%x error code %d\n",
2441 get, UIC_GET_ATTR_ID(attr_sel), ret);
2442 } while (ret && peer && --retries);
2445 dev_err(hba->dev, "%s: attr-id 0x%x failed %d retries\n",
2446 get, UIC_GET_ATTR_ID(attr_sel), retries);
2448 if (mib_val && !ret)
2449 *mib_val = uic_cmd.argument3;
2451 if (peer && (hba->quirks & UFSHCD_QUIRK_DME_PEER_ACCESS_AUTO_MODE)
2453 ufshcd_change_power_mode(hba, &orig_pwr_info);
2457 EXPORT_SYMBOL_GPL(ufshcd_dme_get_attr);
2460 * ufshcd_uic_pwr_ctrl - executes UIC commands (which affects the link power
2461 * state) and waits for it to take effect.
2463 * @hba: per adapter instance
2464 * @cmd: UIC command to execute
2466 * DME operations like DME_SET(PA_PWRMODE), DME_HIBERNATE_ENTER &
2467 * DME_HIBERNATE_EXIT commands take some time to take its effect on both host
2468 * and device UniPro link and hence it's final completion would be indicated by
2469 * dedicated status bits in Interrupt Status register (UPMS, UHES, UHXS) in
2470 * addition to normal UIC command completion Status (UCCS). This function only
2471 * returns after the relevant status bits indicate the completion.
2473 * Returns 0 on success, non-zero value on failure
2475 static int ufshcd_uic_pwr_ctrl(struct ufs_hba *hba, struct uic_command *cmd)
2477 struct completion uic_async_done;
2478 unsigned long flags;
2481 bool reenable_intr = false;
2483 mutex_lock(&hba->uic_cmd_mutex);
2484 init_completion(&uic_async_done);
2485 ufshcd_add_delay_before_dme_cmd(hba);
2487 spin_lock_irqsave(hba->host->host_lock, flags);
2488 hba->uic_async_done = &uic_async_done;
2489 if (ufshcd_readl(hba, REG_INTERRUPT_ENABLE) & UIC_COMMAND_COMPL) {
2490 ufshcd_disable_intr(hba, UIC_COMMAND_COMPL);
2492 * Make sure UIC command completion interrupt is disabled before
2493 * issuing UIC command.
2496 reenable_intr = true;
2498 ret = __ufshcd_send_uic_cmd(hba, cmd, false);
2499 spin_unlock_irqrestore(hba->host->host_lock, flags);
2502 "pwr ctrl cmd 0x%x with mode 0x%x uic error %d\n",
2503 cmd->command, cmd->argument3, ret);
2507 if (!wait_for_completion_timeout(hba->uic_async_done,
2508 msecs_to_jiffies(UIC_CMD_TIMEOUT))) {
2510 "pwr ctrl cmd 0x%x with mode 0x%x completion timeout\n",
2511 cmd->command, cmd->argument3);
2516 status = ufshcd_get_upmcrs(hba);
2517 if (status != PWR_LOCAL) {
2519 "pwr ctrl cmd 0x%0x failed, host umpcrs:0x%x\n",
2520 cmd->command, status);
2521 ret = (status != PWR_OK) ? status : -1;
2524 spin_lock_irqsave(hba->host->host_lock, flags);
2525 hba->active_uic_cmd = NULL;
2526 hba->uic_async_done = NULL;
2528 ufshcd_enable_intr(hba, UIC_COMMAND_COMPL);
2529 spin_unlock_irqrestore(hba->host->host_lock, flags);
2530 mutex_unlock(&hba->uic_cmd_mutex);
2536 * ufshcd_uic_change_pwr_mode - Perform the UIC power mode chage
2537 * using DME_SET primitives.
2538 * @hba: per adapter instance
2539 * @mode: powr mode value
2541 * Returns 0 on success, non-zero value on failure
2543 static int ufshcd_uic_change_pwr_mode(struct ufs_hba *hba, u8 mode)
2545 struct uic_command uic_cmd = {0};
2548 if (hba->quirks & UFSHCD_QUIRK_BROKEN_PA_RXHSUNTERMCAP) {
2549 ret = ufshcd_dme_set(hba,
2550 UIC_ARG_MIB_SEL(PA_RXHSUNTERMCAP, 0), 1);
2552 dev_err(hba->dev, "%s: failed to enable PA_RXHSUNTERMCAP ret %d\n",
2558 uic_cmd.command = UIC_CMD_DME_SET;
2559 uic_cmd.argument1 = UIC_ARG_MIB(PA_PWRMODE);
2560 uic_cmd.argument3 = mode;
2561 ufshcd_hold(hba, false);
2562 ret = ufshcd_uic_pwr_ctrl(hba, &uic_cmd);
2563 ufshcd_release(hba);
2569 static int ufshcd_link_recovery(struct ufs_hba *hba)
2572 unsigned long flags;
2574 spin_lock_irqsave(hba->host->host_lock, flags);
2575 hba->ufshcd_state = UFSHCD_STATE_RESET;
2576 ufshcd_set_eh_in_progress(hba);
2577 spin_unlock_irqrestore(hba->host->host_lock, flags);
2579 ret = ufshcd_host_reset_and_restore(hba);
2581 spin_lock_irqsave(hba->host->host_lock, flags);
2583 hba->ufshcd_state = UFSHCD_STATE_ERROR;
2584 ufshcd_clear_eh_in_progress(hba);
2585 spin_unlock_irqrestore(hba->host->host_lock, flags);
2588 dev_err(hba->dev, "%s: link recovery failed, err %d",
2594 static int __ufshcd_uic_hibern8_enter(struct ufs_hba *hba)
2597 struct uic_command uic_cmd = {0};
2599 uic_cmd.command = UIC_CMD_DME_HIBER_ENTER;
2600 ret = ufshcd_uic_pwr_ctrl(hba, &uic_cmd);
2603 dev_err(hba->dev, "%s: hibern8 enter failed. ret = %d\n",
2607 * If link recovery fails then return error so that caller
2608 * don't retry the hibern8 enter again.
2610 if (ufshcd_link_recovery(hba))
2617 static int ufshcd_uic_hibern8_enter(struct ufs_hba *hba)
2619 int ret = 0, retries;
2621 for (retries = UIC_HIBERN8_ENTER_RETRIES; retries > 0; retries--) {
2622 ret = __ufshcd_uic_hibern8_enter(hba);
2623 if (!ret || ret == -ENOLINK)
2630 static int ufshcd_uic_hibern8_exit(struct ufs_hba *hba)
2632 struct uic_command uic_cmd = {0};
2635 uic_cmd.command = UIC_CMD_DME_HIBER_EXIT;
2636 ret = ufshcd_uic_pwr_ctrl(hba, &uic_cmd);
2638 dev_err(hba->dev, "%s: hibern8 exit failed. ret = %d\n",
2640 ret = ufshcd_link_recovery(hba);
2647 * ufshcd_init_pwr_info - setting the POR (power on reset)
2648 * values in hba power info
2649 * @hba: per-adapter instance
2651 static void ufshcd_init_pwr_info(struct ufs_hba *hba)
2653 hba->pwr_info.gear_rx = UFS_PWM_G1;
2654 hba->pwr_info.gear_tx = UFS_PWM_G1;
2655 hba->pwr_info.lane_rx = 1;
2656 hba->pwr_info.lane_tx = 1;
2657 hba->pwr_info.pwr_rx = SLOWAUTO_MODE;
2658 hba->pwr_info.pwr_tx = SLOWAUTO_MODE;
2659 hba->pwr_info.hs_rate = 0;
2663 * ufshcd_get_max_pwr_mode - reads the max power mode negotiated with device
2664 * @hba: per-adapter instance
2666 static int ufshcd_get_max_pwr_mode(struct ufs_hba *hba)
2668 struct ufs_pa_layer_attr *pwr_info = &hba->max_pwr_info.info;
2670 if (hba->max_pwr_info.is_valid)
2673 pwr_info->pwr_tx = FASTAUTO_MODE;
2674 pwr_info->pwr_rx = FASTAUTO_MODE;
2675 pwr_info->hs_rate = PA_HS_MODE_B;
2677 /* Get the connected lane count */
2678 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_CONNECTEDRXDATALANES),
2679 &pwr_info->lane_rx);
2680 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_CONNECTEDTXDATALANES),
2681 &pwr_info->lane_tx);
2683 if (!pwr_info->lane_rx || !pwr_info->lane_tx) {
2684 dev_err(hba->dev, "%s: invalid connected lanes value. rx=%d, tx=%d\n",
2692 * First, get the maximum gears of HS speed.
2693 * If a zero value, it means there is no HSGEAR capability.
2694 * Then, get the maximum gears of PWM speed.
2696 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_MAXRXHSGEAR), &pwr_info->gear_rx);
2697 if (!pwr_info->gear_rx) {
2698 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_MAXRXPWMGEAR),
2699 &pwr_info->gear_rx);
2700 if (!pwr_info->gear_rx) {
2701 dev_err(hba->dev, "%s: invalid max pwm rx gear read = %d\n",
2702 __func__, pwr_info->gear_rx);
2705 pwr_info->pwr_rx = SLOWAUTO_MODE;
2708 ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_MAXRXHSGEAR),
2709 &pwr_info->gear_tx);
2710 if (!pwr_info->gear_tx) {
2711 ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_MAXRXPWMGEAR),
2712 &pwr_info->gear_tx);
2713 if (!pwr_info->gear_tx) {
2714 dev_err(hba->dev, "%s: invalid max pwm tx gear read = %d\n",
2715 __func__, pwr_info->gear_tx);
2718 pwr_info->pwr_tx = SLOWAUTO_MODE;
2721 hba->max_pwr_info.is_valid = true;
2725 static int ufshcd_change_power_mode(struct ufs_hba *hba,
2726 struct ufs_pa_layer_attr *pwr_mode)
2730 /* if already configured to the requested pwr_mode */
2731 if (pwr_mode->gear_rx == hba->pwr_info.gear_rx &&
2732 pwr_mode->gear_tx == hba->pwr_info.gear_tx &&
2733 pwr_mode->lane_rx == hba->pwr_info.lane_rx &&
2734 pwr_mode->lane_tx == hba->pwr_info.lane_tx &&
2735 pwr_mode->pwr_rx == hba->pwr_info.pwr_rx &&
2736 pwr_mode->pwr_tx == hba->pwr_info.pwr_tx &&
2737 pwr_mode->hs_rate == hba->pwr_info.hs_rate) {
2738 dev_dbg(hba->dev, "%s: power already configured\n", __func__);
2743 * Configure attributes for power mode change with below.
2744 * - PA_RXGEAR, PA_ACTIVERXDATALANES, PA_RXTERMINATION,
2745 * - PA_TXGEAR, PA_ACTIVETXDATALANES, PA_TXTERMINATION,
2748 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_RXGEAR), pwr_mode->gear_rx);
2749 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_ACTIVERXDATALANES),
2751 if (pwr_mode->pwr_rx == FASTAUTO_MODE ||
2752 pwr_mode->pwr_rx == FAST_MODE)
2753 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_RXTERMINATION), TRUE);
2755 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_RXTERMINATION), FALSE);
2757 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TXGEAR), pwr_mode->gear_tx);
2758 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_ACTIVETXDATALANES),
2760 if (pwr_mode->pwr_tx == FASTAUTO_MODE ||
2761 pwr_mode->pwr_tx == FAST_MODE)
2762 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TXTERMINATION), TRUE);
2764 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TXTERMINATION), FALSE);
2766 if (pwr_mode->pwr_rx == FASTAUTO_MODE ||
2767 pwr_mode->pwr_tx == FASTAUTO_MODE ||
2768 pwr_mode->pwr_rx == FAST_MODE ||
2769 pwr_mode->pwr_tx == FAST_MODE)
2770 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_HSSERIES),
2773 ret = ufshcd_uic_change_pwr_mode(hba, pwr_mode->pwr_rx << 4
2774 | pwr_mode->pwr_tx);
2778 "%s: power mode change failed %d\n", __func__, ret);
2780 ufshcd_vops_pwr_change_notify(hba, POST_CHANGE, NULL,
2783 memcpy(&hba->pwr_info, pwr_mode,
2784 sizeof(struct ufs_pa_layer_attr));
2791 * ufshcd_config_pwr_mode - configure a new power mode
2792 * @hba: per-adapter instance
2793 * @desired_pwr_mode: desired power configuration
2795 static int ufshcd_config_pwr_mode(struct ufs_hba *hba,
2796 struct ufs_pa_layer_attr *desired_pwr_mode)
2798 struct ufs_pa_layer_attr final_params = { 0 };
2801 ret = ufshcd_vops_pwr_change_notify(hba, PRE_CHANGE,
2802 desired_pwr_mode, &final_params);
2805 memcpy(&final_params, desired_pwr_mode, sizeof(final_params));
2807 ret = ufshcd_change_power_mode(hba, &final_params);
2813 * ufshcd_complete_dev_init() - checks device readiness
2814 * hba: per-adapter instance
2816 * Set fDeviceInit flag and poll until device toggles it.
2818 static int ufshcd_complete_dev_init(struct ufs_hba *hba)
2824 err = ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_SET_FLAG,
2825 QUERY_FLAG_IDN_FDEVICEINIT, NULL);
2828 "%s setting fDeviceInit flag failed with error %d\n",
2833 /* poll for max. 1000 iterations for fDeviceInit flag to clear */
2834 for (i = 0; i < 1000 && !err && flag_res; i++)
2835 err = ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_READ_FLAG,
2836 QUERY_FLAG_IDN_FDEVICEINIT, &flag_res);
2840 "%s reading fDeviceInit flag failed with error %d\n",
2844 "%s fDeviceInit was not cleared by the device\n",
2852 * ufshcd_make_hba_operational - Make UFS controller operational
2853 * @hba: per adapter instance
2855 * To bring UFS host controller to operational state,
2856 * 1. Enable required interrupts
2857 * 2. Configure interrupt aggregation
2858 * 3. Program UTRL and UTMRL base address
2859 * 4. Configure run-stop-registers
2861 * Returns 0 on success, non-zero value on failure
2863 static int ufshcd_make_hba_operational(struct ufs_hba *hba)
2868 /* Enable required interrupts */
2869 ufshcd_enable_intr(hba, UFSHCD_ENABLE_INTRS);
2871 /* Configure interrupt aggregation */
2872 if (ufshcd_is_intr_aggr_allowed(hba))
2873 ufshcd_config_intr_aggr(hba, hba->nutrs - 1, INT_AGGR_DEF_TO);
2875 ufshcd_disable_intr_aggr(hba);
2877 /* Configure UTRL and UTMRL base address registers */
2878 ufshcd_writel(hba, lower_32_bits(hba->utrdl_dma_addr),
2879 REG_UTP_TRANSFER_REQ_LIST_BASE_L);
2880 ufshcd_writel(hba, upper_32_bits(hba->utrdl_dma_addr),
2881 REG_UTP_TRANSFER_REQ_LIST_BASE_H);
2882 ufshcd_writel(hba, lower_32_bits(hba->utmrdl_dma_addr),
2883 REG_UTP_TASK_REQ_LIST_BASE_L);
2884 ufshcd_writel(hba, upper_32_bits(hba->utmrdl_dma_addr),
2885 REG_UTP_TASK_REQ_LIST_BASE_H);
2888 * Make sure base address and interrupt setup are updated before
2889 * enabling the run/stop registers below.
2894 * UCRDY, UTMRLDY and UTRLRDY bits must be 1
2896 reg = ufshcd_readl(hba, REG_CONTROLLER_STATUS);
2897 if (!(ufshcd_get_lists_status(reg))) {
2898 ufshcd_enable_run_stop_reg(hba);
2901 "Host controller not ready to process requests");
2911 * ufshcd_hba_stop - Send controller to reset state
2912 * @hba: per adapter instance
2913 * @can_sleep: perform sleep or just spin
2915 static inline void ufshcd_hba_stop(struct ufs_hba *hba, bool can_sleep)
2919 ufshcd_writel(hba, CONTROLLER_DISABLE, REG_CONTROLLER_ENABLE);
2920 err = ufshcd_wait_for_register(hba, REG_CONTROLLER_ENABLE,
2921 CONTROLLER_ENABLE, CONTROLLER_DISABLE,
2924 dev_err(hba->dev, "%s: Controller disable failed\n", __func__);
2928 * ufshcd_hba_enable - initialize the controller
2929 * @hba: per adapter instance
2931 * The controller resets itself and controller firmware initialization
2932 * sequence kicks off. When controller is ready it will set
2933 * the Host Controller Enable bit to 1.
2935 * Returns 0 on success, non-zero value on failure
2937 static int ufshcd_hba_enable(struct ufs_hba *hba)
2942 * msleep of 1 and 5 used in this function might result in msleep(20),
2943 * but it was necessary to send the UFS FPGA to reset mode during
2944 * development and testing of this driver. msleep can be changed to
2945 * mdelay and retry count can be reduced based on the controller.
2947 if (!ufshcd_is_hba_active(hba))
2948 /* change controller state to "reset state" */
2949 ufshcd_hba_stop(hba, true);
2951 /* UniPro link is disabled at this point */
2952 ufshcd_set_link_off(hba);
2954 ufshcd_vops_hce_enable_notify(hba, PRE_CHANGE);
2956 /* start controller initialization sequence */
2957 ufshcd_hba_start(hba);
2960 * To initialize a UFS host controller HCE bit must be set to 1.
2961 * During initialization the HCE bit value changes from 1->0->1.
2962 * When the host controller completes initialization sequence
2963 * it sets the value of HCE bit to 1. The same HCE bit is read back
2964 * to check if the controller has completed initialization sequence.
2965 * So without this delay the value HCE = 1, set in the previous
2966 * instruction might be read back.
2967 * This delay can be changed based on the controller.
2971 /* wait for the host controller to complete initialization */
2973 while (ufshcd_is_hba_active(hba)) {
2978 "Controller enable failed\n");
2984 /* enable UIC related interrupts */
2985 ufshcd_enable_intr(hba, UFSHCD_UIC_MASK);
2987 ufshcd_vops_hce_enable_notify(hba, POST_CHANGE);
2992 static int ufshcd_disable_tx_lcc(struct ufs_hba *hba, bool peer)
2994 int tx_lanes, i, err = 0;
2997 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_CONNECTEDTXDATALANES),
3000 ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_CONNECTEDTXDATALANES),
3002 for (i = 0; i < tx_lanes; i++) {
3004 err = ufshcd_dme_set(hba,
3005 UIC_ARG_MIB_SEL(TX_LCC_ENABLE,
3006 UIC_ARG_MPHY_TX_GEN_SEL_INDEX(i)),
3009 err = ufshcd_dme_peer_set(hba,
3010 UIC_ARG_MIB_SEL(TX_LCC_ENABLE,
3011 UIC_ARG_MPHY_TX_GEN_SEL_INDEX(i)),
3014 dev_err(hba->dev, "%s: TX LCC Disable failed, peer = %d, lane = %d, err = %d",
3015 __func__, peer, i, err);
3023 static inline int ufshcd_disable_device_tx_lcc(struct ufs_hba *hba)
3025 return ufshcd_disable_tx_lcc(hba, true);
3029 * ufshcd_link_startup - Initialize unipro link startup
3030 * @hba: per adapter instance
3032 * Returns 0 for success, non-zero in case of failure
3034 static int ufshcd_link_startup(struct ufs_hba *hba)
3037 int retries = DME_LINKSTARTUP_RETRIES;
3040 ufshcd_vops_link_startup_notify(hba, PRE_CHANGE);
3042 ret = ufshcd_dme_link_startup(hba);
3044 /* check if device is detected by inter-connect layer */
3045 if (!ret && !ufshcd_is_device_present(hba)) {
3046 dev_err(hba->dev, "%s: Device not present\n", __func__);
3052 * DME link lost indication is only received when link is up,
3053 * but we can't be sure if the link is up until link startup
3054 * succeeds. So reset the local Uni-Pro and try again.
3056 if (ret && ufshcd_hba_enable(hba))
3058 } while (ret && retries--);
3061 /* failed to get the link up... retire */
3064 if (hba->quirks & UFSHCD_QUIRK_BROKEN_LCC) {
3065 ret = ufshcd_disable_device_tx_lcc(hba);
3070 /* Include any host controller configuration via UIC commands */
3071 ret = ufshcd_vops_link_startup_notify(hba, POST_CHANGE);
3075 ret = ufshcd_make_hba_operational(hba);
3078 dev_err(hba->dev, "link startup failed %d\n", ret);
3083 * ufshcd_verify_dev_init() - Verify device initialization
3084 * @hba: per-adapter instance
3086 * Send NOP OUT UPIU and wait for NOP IN response to check whether the
3087 * device Transport Protocol (UTP) layer is ready after a reset.
3088 * If the UTP layer at the device side is not initialized, it may
3089 * not respond with NOP IN UPIU within timeout of %NOP_OUT_TIMEOUT
3090 * and we retry sending NOP OUT for %NOP_OUT_RETRIES iterations.
3092 static int ufshcd_verify_dev_init(struct ufs_hba *hba)
3097 ufshcd_hold(hba, false);
3098 mutex_lock(&hba->dev_cmd.lock);
3099 for (retries = NOP_OUT_RETRIES; retries > 0; retries--) {
3100 err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_NOP,
3103 if (!err || err == -ETIMEDOUT)
3106 dev_dbg(hba->dev, "%s: error %d retrying\n", __func__, err);
3108 mutex_unlock(&hba->dev_cmd.lock);
3109 ufshcd_release(hba);
3112 dev_err(hba->dev, "%s: NOP OUT failed %d\n", __func__, err);
3117 * ufshcd_set_queue_depth - set lun queue depth
3118 * @sdev: pointer to SCSI device
3120 * Read bLUQueueDepth value and activate scsi tagged command
3121 * queueing. For WLUN, queue depth is set to 1. For best-effort
3122 * cases (bLUQueueDepth = 0) the queue depth is set to a maximum
3123 * value that host can queue.
3125 static void ufshcd_set_queue_depth(struct scsi_device *sdev)
3129 struct ufs_hba *hba;
3131 hba = shost_priv(sdev->host);
3133 lun_qdepth = hba->nutrs;
3134 ret = ufshcd_read_unit_desc_param(hba,
3135 ufshcd_scsi_to_upiu_lun(sdev->lun),
3136 UNIT_DESC_PARAM_LU_Q_DEPTH,
3138 sizeof(lun_qdepth));
3140 /* Some WLUN doesn't support unit descriptor */
3141 if (ret == -EOPNOTSUPP)
3143 else if (!lun_qdepth)
3144 /* eventually, we can figure out the real queue depth */
3145 lun_qdepth = hba->nutrs;
3147 lun_qdepth = min_t(int, lun_qdepth, hba->nutrs);
3149 dev_dbg(hba->dev, "%s: activate tcq with queue depth %d\n",
3150 __func__, lun_qdepth);
3151 scsi_change_queue_depth(sdev, lun_qdepth);
3155 * ufshcd_get_lu_wp - returns the "b_lu_write_protect" from UNIT DESCRIPTOR
3156 * @hba: per-adapter instance
3157 * @lun: UFS device lun id
3158 * @b_lu_write_protect: pointer to buffer to hold the LU's write protect info
3160 * Returns 0 in case of success and b_lu_write_protect status would be returned
3161 * @b_lu_write_protect parameter.
3162 * Returns -ENOTSUPP if reading b_lu_write_protect is not supported.
3163 * Returns -EINVAL in case of invalid parameters passed to this function.
3165 static int ufshcd_get_lu_wp(struct ufs_hba *hba,
3167 u8 *b_lu_write_protect)
3171 if (!b_lu_write_protect)
3174 * According to UFS device spec, RPMB LU can't be write
3175 * protected so skip reading bLUWriteProtect parameter for
3176 * it. For other W-LUs, UNIT DESCRIPTOR is not available.
3178 else if (lun >= UFS_UPIU_MAX_GENERAL_LUN)
3181 ret = ufshcd_read_unit_desc_param(hba,
3183 UNIT_DESC_PARAM_LU_WR_PROTECT,
3185 sizeof(*b_lu_write_protect));
3190 * ufshcd_get_lu_power_on_wp_status - get LU's power on write protect
3192 * @hba: per-adapter instance
3193 * @sdev: pointer to SCSI device
3196 static inline void ufshcd_get_lu_power_on_wp_status(struct ufs_hba *hba,
3197 struct scsi_device *sdev)
3199 if (hba->dev_info.f_power_on_wp_en &&
3200 !hba->dev_info.is_lu_power_on_wp) {
3201 u8 b_lu_write_protect;
3203 if (!ufshcd_get_lu_wp(hba, ufshcd_scsi_to_upiu_lun(sdev->lun),
3204 &b_lu_write_protect) &&
3205 (b_lu_write_protect == UFS_LU_POWER_ON_WP))
3206 hba->dev_info.is_lu_power_on_wp = true;
3211 * ufshcd_slave_alloc - handle initial SCSI device configurations
3212 * @sdev: pointer to SCSI device
3216 static int ufshcd_slave_alloc(struct scsi_device *sdev)
3218 struct ufs_hba *hba;
3220 hba = shost_priv(sdev->host);
3222 /* Mode sense(6) is not supported by UFS, so use Mode sense(10) */
3223 sdev->use_10_for_ms = 1;
3225 /* allow SCSI layer to restart the device in case of errors */
3226 sdev->allow_restart = 1;
3228 /* REPORT SUPPORTED OPERATION CODES is not supported */
3229 sdev->no_report_opcodes = 1;
3232 ufshcd_set_queue_depth(sdev);
3234 ufshcd_get_lu_power_on_wp_status(hba, sdev);
3240 * ufshcd_change_queue_depth - change queue depth
3241 * @sdev: pointer to SCSI device
3242 * @depth: required depth to set
3244 * Change queue depth and make sure the max. limits are not crossed.
3246 static int ufshcd_change_queue_depth(struct scsi_device *sdev, int depth)
3248 struct ufs_hba *hba = shost_priv(sdev->host);
3250 if (depth > hba->nutrs)
3252 return scsi_change_queue_depth(sdev, depth);
3256 * ufshcd_slave_configure - adjust SCSI device configurations
3257 * @sdev: pointer to SCSI device
3259 static int ufshcd_slave_configure(struct scsi_device *sdev)
3261 struct request_queue *q = sdev->request_queue;
3263 blk_queue_update_dma_pad(q, PRDT_DATA_BYTE_COUNT_PAD - 1);
3264 blk_queue_max_segment_size(q, PRDT_DATA_BYTE_COUNT_MAX);
3270 * ufshcd_slave_destroy - remove SCSI device configurations
3271 * @sdev: pointer to SCSI device
3273 static void ufshcd_slave_destroy(struct scsi_device *sdev)
3275 struct ufs_hba *hba;
3277 hba = shost_priv(sdev->host);
3278 /* Drop the reference as it won't be needed anymore */
3279 if (ufshcd_scsi_to_upiu_lun(sdev->lun) == UFS_UPIU_UFS_DEVICE_WLUN) {
3280 unsigned long flags;
3282 spin_lock_irqsave(hba->host->host_lock, flags);
3283 hba->sdev_ufs_device = NULL;
3284 spin_unlock_irqrestore(hba->host->host_lock, flags);
3289 * ufshcd_task_req_compl - handle task management request completion
3290 * @hba: per adapter instance
3291 * @index: index of the completed request
3292 * @resp: task management service response
3294 * Returns non-zero value on error, zero on success
3296 static int ufshcd_task_req_compl(struct ufs_hba *hba, u32 index, u8 *resp)
3298 struct utp_task_req_desc *task_req_descp;
3299 struct utp_upiu_task_rsp *task_rsp_upiup;
3300 unsigned long flags;
3304 spin_lock_irqsave(hba->host->host_lock, flags);
3306 /* Clear completed tasks from outstanding_tasks */
3307 __clear_bit(index, &hba->outstanding_tasks);
3309 task_req_descp = hba->utmrdl_base_addr;
3310 ocs_value = ufshcd_get_tmr_ocs(&task_req_descp[index]);
3312 if (ocs_value == OCS_SUCCESS) {
3313 task_rsp_upiup = (struct utp_upiu_task_rsp *)
3314 task_req_descp[index].task_rsp_upiu;
3315 task_result = be32_to_cpu(task_rsp_upiup->header.dword_1);
3316 task_result = ((task_result & MASK_TASK_RESPONSE) >> 8);
3318 *resp = (u8)task_result;
3320 dev_err(hba->dev, "%s: failed, ocs = 0x%x\n",
3321 __func__, ocs_value);
3323 spin_unlock_irqrestore(hba->host->host_lock, flags);
3329 * ufshcd_scsi_cmd_status - Update SCSI command result based on SCSI status
3330 * @lrb: pointer to local reference block of completed command
3331 * @scsi_status: SCSI command status
3333 * Returns value base on SCSI command status
3336 ufshcd_scsi_cmd_status(struct ufshcd_lrb *lrbp, int scsi_status)
3340 switch (scsi_status) {
3341 case SAM_STAT_CHECK_CONDITION:
3342 ufshcd_copy_sense_data(lrbp);
3344 result |= DID_OK << 16 |
3345 COMMAND_COMPLETE << 8 |
3348 case SAM_STAT_TASK_SET_FULL:
3350 case SAM_STAT_TASK_ABORTED:
3351 ufshcd_copy_sense_data(lrbp);
3352 result |= scsi_status;
3355 result |= DID_ERROR << 16;
3357 } /* end of switch */
3363 * ufshcd_transfer_rsp_status - Get overall status of the response
3364 * @hba: per adapter instance
3365 * @lrb: pointer to local reference block of completed command
3367 * Returns result of the command to notify SCSI midlayer
3370 ufshcd_transfer_rsp_status(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
3376 /* overall command status of utrd */
3377 ocs = ufshcd_get_tr_ocs(lrbp);
3381 result = ufshcd_get_req_rsp(lrbp->ucd_rsp_ptr);
3384 case UPIU_TRANSACTION_RESPONSE:
3386 * get the response UPIU result to extract
3387 * the SCSI command status
3389 result = ufshcd_get_rsp_upiu_result(lrbp->ucd_rsp_ptr);
3392 * get the result based on SCSI status response
3393 * to notify the SCSI midlayer of the command status
3395 scsi_status = result & MASK_SCSI_STATUS;
3396 result = ufshcd_scsi_cmd_status(lrbp, scsi_status);
3399 * Currently we are only supporting BKOPs exception
3400 * events hence we can ignore BKOPs exception event
3401 * during power management callbacks. BKOPs exception
3402 * event is not expected to be raised in runtime suspend
3403 * callback as it allows the urgent bkops.
3404 * During system suspend, we are anyway forcefully
3405 * disabling the bkops and if urgent bkops is needed
3406 * it will be enabled on system resume. Long term
3407 * solution could be to abort the system suspend if
3408 * UFS device needs urgent BKOPs.
3410 if (!hba->pm_op_in_progress &&
3411 ufshcd_is_exception_event(lrbp->ucd_rsp_ptr))
3412 schedule_work(&hba->eeh_work);
3414 case UPIU_TRANSACTION_REJECT_UPIU:
3415 /* TODO: handle Reject UPIU Response */
3416 result = DID_ERROR << 16;
3418 "Reject UPIU not fully implemented\n");
3421 result = DID_ERROR << 16;
3423 "Unexpected request response code = %x\n",
3429 result |= DID_ABORT << 16;
3431 case OCS_INVALID_COMMAND_STATUS:
3432 result |= DID_REQUEUE << 16;
3434 case OCS_INVALID_CMD_TABLE_ATTR:
3435 case OCS_INVALID_PRDT_ATTR:
3436 case OCS_MISMATCH_DATA_BUF_SIZE:
3437 case OCS_MISMATCH_RESP_UPIU_SIZE:
3438 case OCS_PEER_COMM_FAILURE:
3439 case OCS_FATAL_ERROR:
3441 result |= DID_ERROR << 16;
3443 "OCS error from controller = %x\n", ocs);
3445 } /* end of switch */
3451 * ufshcd_uic_cmd_compl - handle completion of uic command
3452 * @hba: per adapter instance
3453 * @intr_status: interrupt status generated by the controller
3455 static void ufshcd_uic_cmd_compl(struct ufs_hba *hba, u32 intr_status)
3457 if ((intr_status & UIC_COMMAND_COMPL) && hba->active_uic_cmd) {
3458 hba->active_uic_cmd->argument2 |=
3459 ufshcd_get_uic_cmd_result(hba);
3460 hba->active_uic_cmd->argument3 =
3461 ufshcd_get_dme_attr_val(hba);
3462 complete(&hba->active_uic_cmd->done);
3465 if ((intr_status & UFSHCD_UIC_PWR_MASK) && hba->uic_async_done)
3466 complete(hba->uic_async_done);
3470 * __ufshcd_transfer_req_compl - handle SCSI and query command completion
3471 * @hba: per adapter instance
3472 * @completed_reqs: requests to complete
3474 static void __ufshcd_transfer_req_compl(struct ufs_hba *hba,
3475 unsigned long completed_reqs)
3477 struct ufshcd_lrb *lrbp;
3478 struct scsi_cmnd *cmd;
3482 for_each_set_bit(index, &completed_reqs, hba->nutrs) {
3483 lrbp = &hba->lrb[index];
3486 result = ufshcd_transfer_rsp_status(hba, lrbp);
3487 scsi_dma_unmap(cmd);
3488 cmd->result = result;
3489 /* Mark completed command as NULL in LRB */
3491 clear_bit_unlock(index, &hba->lrb_in_use);
3492 /* Do not touch lrbp after scsi done */
3493 cmd->scsi_done(cmd);
3494 __ufshcd_release(hba);
3495 } else if (lrbp->command_type == UTP_CMD_TYPE_DEV_MANAGE) {
3496 if (hba->dev_cmd.complete)
3497 complete(hba->dev_cmd.complete);
3501 /* clear corresponding bits of completed commands */
3502 hba->outstanding_reqs ^= completed_reqs;
3504 ufshcd_clk_scaling_update_busy(hba);
3506 /* we might have free'd some tags above */
3507 wake_up(&hba->dev_cmd.tag_wq);
3511 * ufshcd_transfer_req_compl - handle SCSI and query command completion
3512 * @hba: per adapter instance
3514 static void ufshcd_transfer_req_compl(struct ufs_hba *hba)
3516 unsigned long completed_reqs;
3519 /* Resetting interrupt aggregation counters first and reading the
3520 * DOOR_BELL afterward allows us to handle all the completed requests.
3521 * In order to prevent other interrupts starvation the DB is read once
3522 * after reset. The down side of this solution is the possibility of
3523 * false interrupt if device completes another request after resetting
3524 * aggregation and before reading the DB.
3526 if (ufshcd_is_intr_aggr_allowed(hba))
3527 ufshcd_reset_intr_aggr(hba);
3529 tr_doorbell = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
3530 completed_reqs = tr_doorbell ^ hba->outstanding_reqs;
3532 __ufshcd_transfer_req_compl(hba, completed_reqs);
3536 * ufshcd_disable_ee - disable exception event
3537 * @hba: per-adapter instance
3538 * @mask: exception event to disable
3540 * Disables exception event in the device so that the EVENT_ALERT
3543 * Returns zero on success, non-zero error value on failure.
3545 static int ufshcd_disable_ee(struct ufs_hba *hba, u16 mask)
3550 if (!(hba->ee_ctrl_mask & mask))
3553 val = hba->ee_ctrl_mask & ~mask;
3554 val &= 0xFFFF; /* 2 bytes */
3555 err = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_WRITE_ATTR,
3556 QUERY_ATTR_IDN_EE_CONTROL, 0, 0, &val);
3558 hba->ee_ctrl_mask &= ~mask;
3564 * ufshcd_enable_ee - enable exception event
3565 * @hba: per-adapter instance
3566 * @mask: exception event to enable
3568 * Enable corresponding exception event in the device to allow
3569 * device to alert host in critical scenarios.
3571 * Returns zero on success, non-zero error value on failure.
3573 static int ufshcd_enable_ee(struct ufs_hba *hba, u16 mask)
3578 if (hba->ee_ctrl_mask & mask)
3581 val = hba->ee_ctrl_mask | mask;
3582 val &= 0xFFFF; /* 2 bytes */
3583 err = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_WRITE_ATTR,
3584 QUERY_ATTR_IDN_EE_CONTROL, 0, 0, &val);
3586 hba->ee_ctrl_mask |= mask;
3592 * ufshcd_enable_auto_bkops - Allow device managed BKOPS
3593 * @hba: per-adapter instance
3595 * Allow device to manage background operations on its own. Enabling
3596 * this might lead to inconsistent latencies during normal data transfers
3597 * as the device is allowed to manage its own way of handling background
3600 * Returns zero on success, non-zero on failure.
3602 static int ufshcd_enable_auto_bkops(struct ufs_hba *hba)
3606 if (hba->auto_bkops_enabled)
3609 err = ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_SET_FLAG,
3610 QUERY_FLAG_IDN_BKOPS_EN, NULL);
3612 dev_err(hba->dev, "%s: failed to enable bkops %d\n",
3617 hba->auto_bkops_enabled = true;
3619 /* No need of URGENT_BKOPS exception from the device */
3620 err = ufshcd_disable_ee(hba, MASK_EE_URGENT_BKOPS);
3622 dev_err(hba->dev, "%s: failed to disable exception event %d\n",
3629 * ufshcd_disable_auto_bkops - block device in doing background operations
3630 * @hba: per-adapter instance
3632 * Disabling background operations improves command response latency but
3633 * has drawback of device moving into critical state where the device is
3634 * not-operable. Make sure to call ufshcd_enable_auto_bkops() whenever the
3635 * host is idle so that BKOPS are managed effectively without any negative
3638 * Returns zero on success, non-zero on failure.
3640 static int ufshcd_disable_auto_bkops(struct ufs_hba *hba)
3644 if (!hba->auto_bkops_enabled)
3648 * If host assisted BKOPs is to be enabled, make sure
3649 * urgent bkops exception is allowed.
3651 err = ufshcd_enable_ee(hba, MASK_EE_URGENT_BKOPS);
3653 dev_err(hba->dev, "%s: failed to enable exception event %d\n",
3658 err = ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_CLEAR_FLAG,
3659 QUERY_FLAG_IDN_BKOPS_EN, NULL);
3661 dev_err(hba->dev, "%s: failed to disable bkops %d\n",
3663 ufshcd_disable_ee(hba, MASK_EE_URGENT_BKOPS);
3667 hba->auto_bkops_enabled = false;
3673 * ufshcd_force_reset_auto_bkops - force enable of auto bkops
3674 * @hba: per adapter instance
3676 * After a device reset the device may toggle the BKOPS_EN flag
3677 * to default value. The s/w tracking variables should be updated
3678 * as well. Do this by forcing enable of auto bkops.
3680 static void ufshcd_force_reset_auto_bkops(struct ufs_hba *hba)
3682 hba->auto_bkops_enabled = false;
3683 hba->ee_ctrl_mask |= MASK_EE_URGENT_BKOPS;
3684 ufshcd_enable_auto_bkops(hba);
3687 static inline int ufshcd_get_bkops_status(struct ufs_hba *hba, u32 *status)
3689 return ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
3690 QUERY_ATTR_IDN_BKOPS_STATUS, 0, 0, status);
3694 * ufshcd_bkops_ctrl - control the auto bkops based on current bkops status
3695 * @hba: per-adapter instance
3696 * @status: bkops_status value
3698 * Read the bkops_status from the UFS device and Enable fBackgroundOpsEn
3699 * flag in the device to permit background operations if the device
3700 * bkops_status is greater than or equal to "status" argument passed to
3701 * this function, disable otherwise.
3703 * Returns 0 for success, non-zero in case of failure.
3705 * NOTE: Caller of this function can check the "hba->auto_bkops_enabled" flag
3706 * to know whether auto bkops is enabled or disabled after this function
3707 * returns control to it.
3709 static int ufshcd_bkops_ctrl(struct ufs_hba *hba,
3710 enum bkops_status status)
3713 u32 curr_status = 0;
3715 err = ufshcd_get_bkops_status(hba, &curr_status);
3717 dev_err(hba->dev, "%s: failed to get BKOPS status %d\n",
3720 } else if (curr_status > BKOPS_STATUS_MAX) {
3721 dev_err(hba->dev, "%s: invalid BKOPS status %d\n",
3722 __func__, curr_status);
3727 if (curr_status >= status)
3728 err = ufshcd_enable_auto_bkops(hba);
3730 err = ufshcd_disable_auto_bkops(hba);
3736 * ufshcd_urgent_bkops - handle urgent bkops exception event
3737 * @hba: per-adapter instance
3739 * Enable fBackgroundOpsEn flag in the device to permit background
3742 * If BKOPs is enabled, this function returns 0, 1 if the bkops in not enabled
3743 * and negative error value for any other failure.
3745 static int ufshcd_urgent_bkops(struct ufs_hba *hba)
3747 return ufshcd_bkops_ctrl(hba, BKOPS_STATUS_PERF_IMPACT);
3750 static inline int ufshcd_get_ee_status(struct ufs_hba *hba, u32 *status)
3752 return ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
3753 QUERY_ATTR_IDN_EE_STATUS, 0, 0, status);
3757 * ufshcd_exception_event_handler - handle exceptions raised by device
3758 * @work: pointer to work data
3760 * Read bExceptionEventStatus attribute from the device and handle the
3761 * exception event accordingly.
3763 static void ufshcd_exception_event_handler(struct work_struct *work)
3765 struct ufs_hba *hba;
3768 hba = container_of(work, struct ufs_hba, eeh_work);
3770 pm_runtime_get_sync(hba->dev);
3771 err = ufshcd_get_ee_status(hba, &status);
3773 dev_err(hba->dev, "%s: failed to get exception status %d\n",
3778 status &= hba->ee_ctrl_mask;
3779 if (status & MASK_EE_URGENT_BKOPS) {
3780 err = ufshcd_urgent_bkops(hba);
3782 dev_err(hba->dev, "%s: failed to handle urgent bkops %d\n",
3786 pm_runtime_put_sync(hba->dev);
3790 /* Complete requests that have door-bell cleared */
3791 static void ufshcd_complete_requests(struct ufs_hba *hba)
3793 ufshcd_transfer_req_compl(hba);
3794 ufshcd_tmc_handler(hba);
3798 * ufshcd_err_handler - handle UFS errors that require s/w attention
3799 * @work: pointer to work structure
3801 static void ufshcd_err_handler(struct work_struct *work)
3803 struct ufs_hba *hba;
3804 unsigned long flags;
3809 bool needs_reset = false;
3811 hba = container_of(work, struct ufs_hba, eh_work);
3813 pm_runtime_get_sync(hba->dev);
3814 ufshcd_hold(hba, false);
3816 spin_lock_irqsave(hba->host->host_lock, flags);
3817 if (hba->ufshcd_state == UFSHCD_STATE_RESET)
3820 hba->ufshcd_state = UFSHCD_STATE_RESET;
3821 ufshcd_set_eh_in_progress(hba);
3823 /* Complete requests that have door-bell cleared by h/w */
3824 ufshcd_complete_requests(hba);
3825 if ((hba->saved_err & INT_FATAL_ERRORS) ||
3826 ((hba->saved_err & UIC_ERROR) &&
3827 (hba->saved_uic_err & (UFSHCD_UIC_DL_PA_INIT_ERROR |
3828 UFSHCD_UIC_DL_NAC_RECEIVED_ERROR |
3829 UFSHCD_UIC_DL_TCx_REPLAY_ERROR))))
3833 * if host reset is required then skip clearing the pending
3834 * transfers forcefully because they will automatically get
3835 * cleared after link startup.
3838 goto skip_pending_xfer_clear;
3840 /* release lock as clear command might sleep */
3841 spin_unlock_irqrestore(hba->host->host_lock, flags);
3842 /* Clear pending transfer requests */
3843 for_each_set_bit(tag, &hba->outstanding_reqs, hba->nutrs) {
3844 if (ufshcd_clear_cmd(hba, tag)) {
3846 goto lock_skip_pending_xfer_clear;
3850 /* Clear pending task management requests */
3851 for_each_set_bit(tag, &hba->outstanding_tasks, hba->nutmrs) {
3852 if (ufshcd_clear_tm_cmd(hba, tag)) {
3854 goto lock_skip_pending_xfer_clear;
3858 lock_skip_pending_xfer_clear:
3859 spin_lock_irqsave(hba->host->host_lock, flags);
3861 /* Complete the requests that are cleared by s/w */
3862 ufshcd_complete_requests(hba);
3864 if (err_xfer || err_tm)
3867 skip_pending_xfer_clear:
3868 /* Fatal errors need reset */
3870 unsigned long max_doorbells = (1UL << hba->nutrs) - 1;
3873 * ufshcd_reset_and_restore() does the link reinitialization
3874 * which will need atleast one empty doorbell slot to send the
3875 * device management commands (NOP and query commands).
3876 * If there is no slot empty at this moment then free up last
3879 if (hba->outstanding_reqs == max_doorbells)
3880 __ufshcd_transfer_req_compl(hba,
3881 (1UL << (hba->nutrs - 1)));
3883 spin_unlock_irqrestore(hba->host->host_lock, flags);
3884 err = ufshcd_reset_and_restore(hba);
3885 spin_lock_irqsave(hba->host->host_lock, flags);
3887 dev_err(hba->dev, "%s: reset and restore failed\n",
3889 hba->ufshcd_state = UFSHCD_STATE_ERROR;
3892 * Inform scsi mid-layer that we did reset and allow to handle
3893 * Unit Attention properly.
3895 scsi_report_bus_reset(hba->host, 0);
3897 hba->saved_uic_err = 0;
3901 hba->ufshcd_state = UFSHCD_STATE_OPERATIONAL;
3902 if (hba->saved_err || hba->saved_uic_err)
3903 dev_err_ratelimited(hba->dev, "%s: exit: saved_err 0x%x saved_uic_err 0x%x",
3904 __func__, hba->saved_err, hba->saved_uic_err);
3907 ufshcd_clear_eh_in_progress(hba);
3910 spin_unlock_irqrestore(hba->host->host_lock, flags);
3911 scsi_unblock_requests(hba->host);
3912 ufshcd_release(hba);
3913 pm_runtime_put_sync(hba->dev);
3917 * ufshcd_update_uic_error - check and set fatal UIC error flags.
3918 * @hba: per-adapter instance
3920 static void ufshcd_update_uic_error(struct ufs_hba *hba)
3924 /* PA_INIT_ERROR is fatal and needs UIC reset */
3925 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_DATA_LINK_LAYER);
3926 if (reg & UIC_DATA_LINK_LAYER_ERROR_PA_INIT)
3927 hba->uic_error |= UFSHCD_UIC_DL_PA_INIT_ERROR;
3929 /* UIC NL/TL/DME errors needs software retry */
3930 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_NETWORK_LAYER);
3932 hba->uic_error |= UFSHCD_UIC_NL_ERROR;
3934 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_TRANSPORT_LAYER);
3936 hba->uic_error |= UFSHCD_UIC_TL_ERROR;
3938 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_DME);
3940 hba->uic_error |= UFSHCD_UIC_DME_ERROR;
3942 dev_dbg(hba->dev, "%s: UIC error flags = 0x%08x\n",
3943 __func__, hba->uic_error);
3947 * ufshcd_check_errors - Check for errors that need s/w attention
3948 * @hba: per-adapter instance
3950 static void ufshcd_check_errors(struct ufs_hba *hba)
3952 bool queue_eh_work = false;
3954 if (hba->errors & INT_FATAL_ERRORS)
3955 queue_eh_work = true;
3957 if (hba->errors & UIC_ERROR) {
3959 ufshcd_update_uic_error(hba);
3961 queue_eh_work = true;
3964 if (queue_eh_work) {
3966 * update the transfer error masks to sticky bits, let's do this
3967 * irrespective of current ufshcd_state.
3969 hba->saved_err |= hba->errors;
3970 hba->saved_uic_err |= hba->uic_error;
3972 /* handle fatal errors only when link is functional */
3973 if (hba->ufshcd_state == UFSHCD_STATE_OPERATIONAL) {
3974 /* block commands from scsi mid-layer */
3975 scsi_block_requests(hba->host);
3977 hba->ufshcd_state = UFSHCD_STATE_ERROR;
3978 schedule_work(&hba->eh_work);
3982 * if (!queue_eh_work) -
3983 * Other errors are either non-fatal where host recovers
3984 * itself without s/w intervention or errors that will be
3985 * handled by the SCSI core layer.
3990 * ufshcd_tmc_handler - handle task management function completion
3991 * @hba: per adapter instance
3993 static void ufshcd_tmc_handler(struct ufs_hba *hba)
3997 tm_doorbell = ufshcd_readl(hba, REG_UTP_TASK_REQ_DOOR_BELL);
3998 hba->tm_condition = tm_doorbell ^ hba->outstanding_tasks;
3999 wake_up(&hba->tm_wq);
4003 * ufshcd_sl_intr - Interrupt service routine
4004 * @hba: per adapter instance
4005 * @intr_status: contains interrupts generated by the controller
4007 static void ufshcd_sl_intr(struct ufs_hba *hba, u32 intr_status)
4009 hba->errors = UFSHCD_ERROR_MASK & intr_status;
4011 ufshcd_check_errors(hba);
4013 if (intr_status & UFSHCD_UIC_MASK)
4014 ufshcd_uic_cmd_compl(hba, intr_status);
4016 if (intr_status & UTP_TASK_REQ_COMPL)
4017 ufshcd_tmc_handler(hba);
4019 if (intr_status & UTP_TRANSFER_REQ_COMPL)
4020 ufshcd_transfer_req_compl(hba);
4024 * ufshcd_intr - Main interrupt service routine
4026 * @__hba: pointer to adapter instance
4028 * Returns IRQ_HANDLED - If interrupt is valid
4029 * IRQ_NONE - If invalid interrupt
4031 static irqreturn_t ufshcd_intr(int irq, void *__hba)
4033 u32 intr_status, enabled_intr_status;
4034 irqreturn_t retval = IRQ_NONE;
4035 struct ufs_hba *hba = __hba;
4037 spin_lock(hba->host->host_lock);
4038 intr_status = ufshcd_readl(hba, REG_INTERRUPT_STATUS);
4039 enabled_intr_status =
4040 intr_status & ufshcd_readl(hba, REG_INTERRUPT_ENABLE);
4043 ufshcd_writel(hba, intr_status, REG_INTERRUPT_STATUS);
4045 if (enabled_intr_status) {
4046 ufshcd_sl_intr(hba, enabled_intr_status);
4047 retval = IRQ_HANDLED;
4049 spin_unlock(hba->host->host_lock);
4053 static int ufshcd_clear_tm_cmd(struct ufs_hba *hba, int tag)
4056 u32 mask = 1 << tag;
4057 unsigned long flags;
4059 if (!test_bit(tag, &hba->outstanding_tasks))
4062 spin_lock_irqsave(hba->host->host_lock, flags);
4063 ufshcd_writel(hba, ~(1 << tag), REG_UTP_TASK_REQ_LIST_CLEAR);
4064 spin_unlock_irqrestore(hba->host->host_lock, flags);
4066 /* poll for max. 1 sec to clear door bell register by h/w */
4067 err = ufshcd_wait_for_register(hba,
4068 REG_UTP_TASK_REQ_DOOR_BELL,
4069 mask, 0, 1000, 1000, true);
4075 * ufshcd_issue_tm_cmd - issues task management commands to controller
4076 * @hba: per adapter instance
4077 * @lun_id: LUN ID to which TM command is sent
4078 * @task_id: task ID to which the TM command is applicable
4079 * @tm_function: task management function opcode
4080 * @tm_response: task management service response return value
4082 * Returns non-zero value on error, zero on success.
4084 static int ufshcd_issue_tm_cmd(struct ufs_hba *hba, int lun_id, int task_id,
4085 u8 tm_function, u8 *tm_response)
4087 struct utp_task_req_desc *task_req_descp;
4088 struct utp_upiu_task_req *task_req_upiup;
4089 struct Scsi_Host *host;
4090 unsigned long flags;
4098 * Get free slot, sleep if slots are unavailable.
4099 * Even though we use wait_event() which sleeps indefinitely,
4100 * the maximum wait time is bounded by %TM_CMD_TIMEOUT.
4102 wait_event(hba->tm_tag_wq, ufshcd_get_tm_free_slot(hba, &free_slot));
4103 ufshcd_hold(hba, false);
4105 spin_lock_irqsave(host->host_lock, flags);
4106 task_req_descp = hba->utmrdl_base_addr;
4107 task_req_descp += free_slot;
4109 /* Configure task request descriptor */
4110 task_req_descp->header.dword_0 = cpu_to_le32(UTP_REQ_DESC_INT_CMD);
4111 task_req_descp->header.dword_2 =
4112 cpu_to_le32(OCS_INVALID_COMMAND_STATUS);
4114 /* Configure task request UPIU */
4116 (struct utp_upiu_task_req *) task_req_descp->task_req_upiu;
4117 task_tag = hba->nutrs + free_slot;
4118 task_req_upiup->header.dword_0 =
4119 UPIU_HEADER_DWORD(UPIU_TRANSACTION_TASK_REQ, 0,
4121 task_req_upiup->header.dword_1 =
4122 UPIU_HEADER_DWORD(0, tm_function, 0, 0);
4124 * The host shall provide the same value for LUN field in the basic
4125 * header and for Input Parameter.
4127 task_req_upiup->input_param1 = cpu_to_be32(lun_id);
4128 task_req_upiup->input_param2 = cpu_to_be32(task_id);
4130 /* send command to the controller */
4131 __set_bit(free_slot, &hba->outstanding_tasks);
4133 /* Make sure descriptors are ready before ringing the task doorbell */
4136 ufshcd_writel(hba, 1 << free_slot, REG_UTP_TASK_REQ_DOOR_BELL);
4138 spin_unlock_irqrestore(host->host_lock, flags);
4140 /* wait until the task management command is completed */
4141 err = wait_event_timeout(hba->tm_wq,
4142 test_bit(free_slot, &hba->tm_condition),
4143 msecs_to_jiffies(TM_CMD_TIMEOUT));
4145 dev_err(hba->dev, "%s: task management cmd 0x%.2x timed-out\n",
4146 __func__, tm_function);
4147 if (ufshcd_clear_tm_cmd(hba, free_slot))
4148 dev_WARN(hba->dev, "%s: unable clear tm cmd (slot %d) after timeout\n",
4149 __func__, free_slot);
4152 err = ufshcd_task_req_compl(hba, free_slot, tm_response);
4155 clear_bit(free_slot, &hba->tm_condition);
4156 ufshcd_put_tm_slot(hba, free_slot);
4157 wake_up(&hba->tm_tag_wq);
4159 ufshcd_release(hba);
4164 * ufshcd_eh_device_reset_handler - device reset handler registered to
4166 * @cmd: SCSI command pointer
4168 * Returns SUCCESS/FAILED
4170 static int ufshcd_eh_device_reset_handler(struct scsi_cmnd *cmd)
4172 struct Scsi_Host *host;
4173 struct ufs_hba *hba;
4178 struct ufshcd_lrb *lrbp;
4179 unsigned long flags;
4181 host = cmd->device->host;
4182 hba = shost_priv(host);
4183 tag = cmd->request->tag;
4185 lrbp = &hba->lrb[tag];
4186 err = ufshcd_issue_tm_cmd(hba, lrbp->lun, 0, UFS_LOGICAL_RESET, &resp);
4187 if (err || resp != UPIU_TASK_MANAGEMENT_FUNC_COMPL) {
4193 /* clear the commands that were pending for corresponding LUN */
4194 for_each_set_bit(pos, &hba->outstanding_reqs, hba->nutrs) {
4195 if (hba->lrb[pos].lun == lrbp->lun) {
4196 err = ufshcd_clear_cmd(hba, pos);
4201 spin_lock_irqsave(host->host_lock, flags);
4202 ufshcd_transfer_req_compl(hba);
4203 spin_unlock_irqrestore(host->host_lock, flags);
4208 dev_err(hba->dev, "%s: failed with err %d\n", __func__, err);
4215 * ufshcd_abort - abort a specific command
4216 * @cmd: SCSI command pointer
4218 * Abort the pending command in device by sending UFS_ABORT_TASK task management
4219 * command, and in host controller by clearing the door-bell register. There can
4220 * be race between controller sending the command to the device while abort is
4221 * issued. To avoid that, first issue UFS_QUERY_TASK to check if the command is
4222 * really issued and then try to abort it.
4224 * Returns SUCCESS/FAILED
4226 static int ufshcd_abort(struct scsi_cmnd *cmd)
4228 struct Scsi_Host *host;
4229 struct ufs_hba *hba;
4230 unsigned long flags;
4235 struct ufshcd_lrb *lrbp;
4238 host = cmd->device->host;
4239 hba = shost_priv(host);
4240 tag = cmd->request->tag;
4241 if (!ufshcd_valid_tag(hba, tag)) {
4243 "%s: invalid command tag %d: cmd=0x%p, cmd->request=0x%p",
4244 __func__, tag, cmd, cmd->request);
4248 ufshcd_hold(hba, false);
4249 reg = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
4250 /* If command is already aborted/completed, return SUCCESS */
4251 if (!(test_bit(tag, &hba->outstanding_reqs))) {
4253 "%s: cmd at tag %d already completed, outstanding=0x%lx, doorbell=0x%x\n",
4254 __func__, tag, hba->outstanding_reqs, reg);
4258 if (!(reg & (1 << tag))) {
4260 "%s: cmd was completed, but without a notifying intr, tag = %d",
4264 lrbp = &hba->lrb[tag];
4265 for (poll_cnt = 100; poll_cnt; poll_cnt--) {
4266 err = ufshcd_issue_tm_cmd(hba, lrbp->lun, lrbp->task_tag,
4267 UFS_QUERY_TASK, &resp);
4268 if (!err && resp == UPIU_TASK_MANAGEMENT_FUNC_SUCCEEDED) {
4269 /* cmd pending in the device */
4271 } else if (!err && resp == UPIU_TASK_MANAGEMENT_FUNC_COMPL) {
4273 * cmd not pending in the device, check if it is
4276 reg = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
4277 if (reg & (1 << tag)) {
4278 /* sleep for max. 200us to stabilize */
4279 usleep_range(100, 200);
4282 /* command completed already */
4286 err = resp; /* service response error */
4296 err = ufshcd_issue_tm_cmd(hba, lrbp->lun, lrbp->task_tag,
4297 UFS_ABORT_TASK, &resp);
4298 if (err || resp != UPIU_TASK_MANAGEMENT_FUNC_COMPL) {
4300 err = resp; /* service response error */
4304 err = ufshcd_clear_cmd(hba, tag);
4308 scsi_dma_unmap(cmd);
4310 spin_lock_irqsave(host->host_lock, flags);
4311 ufshcd_outstanding_req_clear(hba, tag);
4312 hba->lrb[tag].cmd = NULL;
4313 spin_unlock_irqrestore(host->host_lock, flags);
4315 clear_bit_unlock(tag, &hba->lrb_in_use);
4316 wake_up(&hba->dev_cmd.tag_wq);
4322 dev_err(hba->dev, "%s: failed with err %d\n", __func__, err);
4327 * This ufshcd_release() corresponds to the original scsi cmd that got
4328 * aborted here (as we won't get any IRQ for it).
4330 ufshcd_release(hba);
4335 * ufshcd_host_reset_and_restore - reset and restore host controller
4336 * @hba: per-adapter instance
4338 * Note that host controller reset may issue DME_RESET to
4339 * local and remote (device) Uni-Pro stack and the attributes
4340 * are reset to default state.
4342 * Returns zero on success, non-zero on failure
4344 static int ufshcd_host_reset_and_restore(struct ufs_hba *hba)
4347 unsigned long flags;
4349 /* Reset the host controller */
4350 spin_lock_irqsave(hba->host->host_lock, flags);
4351 ufshcd_hba_stop(hba, false);
4352 spin_unlock_irqrestore(hba->host->host_lock, flags);
4354 err = ufshcd_hba_enable(hba);
4358 /* Establish the link again and restore the device */
4359 err = ufshcd_probe_hba(hba);
4361 if (!err && (hba->ufshcd_state != UFSHCD_STATE_OPERATIONAL))
4365 dev_err(hba->dev, "%s: Host init failed %d\n", __func__, err);
4371 * ufshcd_reset_and_restore - reset and re-initialize host/device
4372 * @hba: per-adapter instance
4374 * Reset and recover device, host and re-establish link. This
4375 * is helpful to recover the communication in fatal error conditions.
4377 * Returns zero on success, non-zero on failure
4379 static int ufshcd_reset_and_restore(struct ufs_hba *hba)
4382 unsigned long flags;
4383 int retries = MAX_HOST_RESET_RETRIES;
4386 err = ufshcd_host_reset_and_restore(hba);
4387 } while (err && --retries);
4390 * After reset the door-bell might be cleared, complete
4391 * outstanding requests in s/w here.
4393 spin_lock_irqsave(hba->host->host_lock, flags);
4394 ufshcd_transfer_req_compl(hba);
4395 ufshcd_tmc_handler(hba);
4396 spin_unlock_irqrestore(hba->host->host_lock, flags);
4402 * ufshcd_eh_host_reset_handler - host reset handler registered to scsi layer
4403 * @cmd - SCSI command pointer
4405 * Returns SUCCESS/FAILED
4407 static int ufshcd_eh_host_reset_handler(struct scsi_cmnd *cmd)
4410 unsigned long flags;
4411 struct ufs_hba *hba;
4413 hba = shost_priv(cmd->device->host);
4415 ufshcd_hold(hba, false);
4417 * Check if there is any race with fatal error handling.
4418 * If so, wait for it to complete. Even though fatal error
4419 * handling does reset and restore in some cases, don't assume
4420 * anything out of it. We are just avoiding race here.
4423 spin_lock_irqsave(hba->host->host_lock, flags);
4424 if (!(work_pending(&hba->eh_work) ||
4425 hba->ufshcd_state == UFSHCD_STATE_RESET))
4427 spin_unlock_irqrestore(hba->host->host_lock, flags);
4428 dev_dbg(hba->dev, "%s: reset in progress\n", __func__);
4429 flush_work(&hba->eh_work);
4432 hba->ufshcd_state = UFSHCD_STATE_RESET;
4433 ufshcd_set_eh_in_progress(hba);
4434 spin_unlock_irqrestore(hba->host->host_lock, flags);
4436 err = ufshcd_reset_and_restore(hba);
4438 spin_lock_irqsave(hba->host->host_lock, flags);
4441 hba->ufshcd_state = UFSHCD_STATE_OPERATIONAL;
4444 hba->ufshcd_state = UFSHCD_STATE_ERROR;
4446 ufshcd_clear_eh_in_progress(hba);
4447 spin_unlock_irqrestore(hba->host->host_lock, flags);
4449 ufshcd_release(hba);
4454 * ufshcd_get_max_icc_level - calculate the ICC level
4455 * @sup_curr_uA: max. current supported by the regulator
4456 * @start_scan: row at the desc table to start scan from
4457 * @buff: power descriptor buffer
4459 * Returns calculated max ICC level for specific regulator
4461 static u32 ufshcd_get_max_icc_level(int sup_curr_uA, u32 start_scan, char *buff)
4468 for (i = start_scan; i >= 0; i--) {
4469 data = be16_to_cpu(*((u16 *)(buff + 2*i)));
4470 unit = (data & ATTR_ICC_LVL_UNIT_MASK) >>
4471 ATTR_ICC_LVL_UNIT_OFFSET;
4472 curr_uA = data & ATTR_ICC_LVL_VALUE_MASK;
4474 case UFSHCD_NANO_AMP:
4475 curr_uA = curr_uA / 1000;
4477 case UFSHCD_MILI_AMP:
4478 curr_uA = curr_uA * 1000;
4481 curr_uA = curr_uA * 1000 * 1000;
4483 case UFSHCD_MICRO_AMP:
4487 if (sup_curr_uA >= curr_uA)
4492 pr_err("%s: Couldn't find valid icc_level = %d", __func__, i);
4499 * ufshcd_calc_icc_level - calculate the max ICC level
4500 * In case regulators are not initialized we'll return 0
4501 * @hba: per-adapter instance
4502 * @desc_buf: power descriptor buffer to extract ICC levels from.
4503 * @len: length of desc_buff
4505 * Returns calculated ICC level
4507 static u32 ufshcd_find_max_sup_active_icc_level(struct ufs_hba *hba,
4508 u8 *desc_buf, int len)
4512 if (!hba->vreg_info.vcc || !hba->vreg_info.vccq ||
4513 !hba->vreg_info.vccq2) {
4515 "%s: Regulator capability was not set, actvIccLevel=%d",
4516 __func__, icc_level);
4520 if (hba->vreg_info.vcc)
4521 icc_level = ufshcd_get_max_icc_level(
4522 hba->vreg_info.vcc->max_uA,
4523 POWER_DESC_MAX_ACTV_ICC_LVLS - 1,
4524 &desc_buf[PWR_DESC_ACTIVE_LVLS_VCC_0]);
4526 if (hba->vreg_info.vccq)
4527 icc_level = ufshcd_get_max_icc_level(
4528 hba->vreg_info.vccq->max_uA,
4530 &desc_buf[PWR_DESC_ACTIVE_LVLS_VCCQ_0]);
4532 if (hba->vreg_info.vccq2)
4533 icc_level = ufshcd_get_max_icc_level(
4534 hba->vreg_info.vccq2->max_uA,
4536 &desc_buf[PWR_DESC_ACTIVE_LVLS_VCCQ2_0]);
4541 static void ufshcd_init_icc_levels(struct ufs_hba *hba)
4544 int buff_len = QUERY_DESC_POWER_MAX_SIZE;
4545 u8 desc_buf[QUERY_DESC_POWER_MAX_SIZE];
4547 ret = ufshcd_read_power_desc(hba, desc_buf, buff_len);
4550 "%s: Failed reading power descriptor.len = %d ret = %d",
4551 __func__, buff_len, ret);
4555 hba->init_prefetch_data.icc_level =
4556 ufshcd_find_max_sup_active_icc_level(hba,
4557 desc_buf, buff_len);
4558 dev_dbg(hba->dev, "%s: setting icc_level 0x%x",
4559 __func__, hba->init_prefetch_data.icc_level);
4561 ret = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_WRITE_ATTR,
4562 QUERY_ATTR_IDN_ACTIVE_ICC_LVL, 0, 0,
4563 &hba->init_prefetch_data.icc_level);
4567 "%s: Failed configuring bActiveICCLevel = %d ret = %d",
4568 __func__, hba->init_prefetch_data.icc_level , ret);
4573 * ufshcd_scsi_add_wlus - Adds required W-LUs
4574 * @hba: per-adapter instance
4576 * UFS device specification requires the UFS devices to support 4 well known
4578 * "REPORT_LUNS" (address: 01h)
4579 * "UFS Device" (address: 50h)
4580 * "RPMB" (address: 44h)
4581 * "BOOT" (address: 30h)
4582 * UFS device's power management needs to be controlled by "POWER CONDITION"
4583 * field of SSU (START STOP UNIT) command. But this "power condition" field
4584 * will take effect only when its sent to "UFS device" well known logical unit
4585 * hence we require the scsi_device instance to represent this logical unit in
4586 * order for the UFS host driver to send the SSU command for power management.
4588 * We also require the scsi_device instance for "RPMB" (Replay Protected Memory
4589 * Block) LU so user space process can control this LU. User space may also
4590 * want to have access to BOOT LU.
4592 * This function adds scsi device instances for each of all well known LUs
4593 * (except "REPORT LUNS" LU).
4595 * Returns zero on success (all required W-LUs are added successfully),
4596 * non-zero error value on failure (if failed to add any of the required W-LU).
4598 static int ufshcd_scsi_add_wlus(struct ufs_hba *hba)
4601 struct scsi_device *sdev_rpmb;
4602 struct scsi_device *sdev_boot;
4604 hba->sdev_ufs_device = __scsi_add_device(hba->host, 0, 0,
4605 ufshcd_upiu_wlun_to_scsi_wlun(UFS_UPIU_UFS_DEVICE_WLUN), NULL);
4606 if (IS_ERR(hba->sdev_ufs_device)) {
4607 ret = PTR_ERR(hba->sdev_ufs_device);
4608 hba->sdev_ufs_device = NULL;
4611 scsi_device_put(hba->sdev_ufs_device);
4613 sdev_boot = __scsi_add_device(hba->host, 0, 0,
4614 ufshcd_upiu_wlun_to_scsi_wlun(UFS_UPIU_BOOT_WLUN), NULL);
4615 if (IS_ERR(sdev_boot)) {
4616 ret = PTR_ERR(sdev_boot);
4617 goto remove_sdev_ufs_device;
4619 scsi_device_put(sdev_boot);
4621 sdev_rpmb = __scsi_add_device(hba->host, 0, 0,
4622 ufshcd_upiu_wlun_to_scsi_wlun(UFS_UPIU_RPMB_WLUN), NULL);
4623 if (IS_ERR(sdev_rpmb)) {
4624 ret = PTR_ERR(sdev_rpmb);
4625 goto remove_sdev_boot;
4627 scsi_device_put(sdev_rpmb);
4631 scsi_remove_device(sdev_boot);
4632 remove_sdev_ufs_device:
4633 scsi_remove_device(hba->sdev_ufs_device);
4638 static int ufs_get_device_info(struct ufs_hba *hba,
4639 struct ufs_device_info *card_data)
4643 u8 str_desc_buf[QUERY_DESC_STRING_MAX_SIZE + 1] = {0};
4644 u8 desc_buf[QUERY_DESC_DEVICE_MAX_SIZE];
4646 err = ufshcd_read_device_desc(hba, desc_buf,
4647 QUERY_DESC_DEVICE_MAX_SIZE);
4649 dev_err(hba->dev, "%s: Failed reading Device Desc. err = %d\n",
4655 * getting vendor (manufacturerID) and Bank Index in big endian
4658 card_data->wmanufacturerid = desc_buf[DEVICE_DESC_PARAM_MANF_ID] << 8 |
4659 desc_buf[DEVICE_DESC_PARAM_MANF_ID + 1];
4661 model_index = desc_buf[DEVICE_DESC_PARAM_PRDCT_NAME];
4663 err = ufshcd_read_string_desc(hba, model_index, str_desc_buf,
4664 QUERY_DESC_STRING_MAX_SIZE, ASCII_STD);
4666 dev_err(hba->dev, "%s: Failed reading Product Name. err = %d\n",
4671 str_desc_buf[QUERY_DESC_STRING_MAX_SIZE] = '\0';
4672 strlcpy(card_data->model, (str_desc_buf + QUERY_DESC_HDR_SIZE),
4673 min_t(u8, str_desc_buf[QUERY_DESC_LENGTH_OFFSET],
4676 /* Null terminate the model string */
4677 card_data->model[MAX_MODEL_LEN] = '\0';
4683 void ufs_advertise_fixup_device(struct ufs_hba *hba)
4686 struct ufs_dev_fix *f;
4687 struct ufs_device_info card_data;
4689 card_data.wmanufacturerid = 0;
4691 err = ufs_get_device_info(hba, &card_data);
4693 dev_err(hba->dev, "%s: Failed getting device info. err = %d\n",
4698 for (f = ufs_fixups; f->quirk; f++) {
4699 if (((f->card.wmanufacturerid == card_data.wmanufacturerid) ||
4700 (f->card.wmanufacturerid == UFS_ANY_VENDOR)) &&
4701 (STR_PRFX_EQUAL(f->card.model, card_data.model) ||
4702 !strcmp(f->card.model, UFS_ANY_MODEL)))
4703 hba->dev_quirks |= f->quirk;
4708 * ufshcd_probe_hba - probe hba to detect device and initialize
4709 * @hba: per-adapter instance
4711 * Execute link-startup and verify device initialization
4713 static int ufshcd_probe_hba(struct ufs_hba *hba)
4717 ret = ufshcd_link_startup(hba);
4721 ufshcd_init_pwr_info(hba);
4723 /* UniPro link is active now */
4724 ufshcd_set_link_active(hba);
4726 ret = ufshcd_verify_dev_init(hba);
4730 ret = ufshcd_complete_dev_init(hba);
4734 ufs_advertise_fixup_device(hba);
4736 ret = ufshcd_set_vccq_rail_unused(hba,
4737 (hba->dev_quirks & UFS_DEVICE_NO_VCCQ) ? true : false);
4741 /* UFS device is also active now */
4742 ufshcd_set_ufs_dev_active(hba);
4743 ufshcd_force_reset_auto_bkops(hba);
4744 hba->wlun_dev_clr_ua = true;
4746 if (ufshcd_get_max_pwr_mode(hba)) {
4748 "%s: Failed getting max supported power mode\n",
4751 ret = ufshcd_config_pwr_mode(hba, &hba->max_pwr_info.info);
4753 dev_err(hba->dev, "%s: Failed setting power mode, err = %d\n",
4757 /* set the state as operational after switching to desired gear */
4758 hba->ufshcd_state = UFSHCD_STATE_OPERATIONAL;
4760 * If we are in error handling context or in power management callbacks
4761 * context, no need to scan the host
4763 if (!ufshcd_eh_in_progress(hba) && !hba->pm_op_in_progress) {
4766 /* clear any previous UFS device information */
4767 memset(&hba->dev_info, 0, sizeof(hba->dev_info));
4768 if (!ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_READ_FLAG,
4769 QUERY_FLAG_IDN_PWR_ON_WPE, &flag))
4770 hba->dev_info.f_power_on_wp_en = flag;
4772 if (!hba->is_init_prefetch)
4773 ufshcd_init_icc_levels(hba);
4775 /* Add required well known logical units to scsi mid layer */
4776 if (ufshcd_scsi_add_wlus(hba))
4779 scsi_scan_host(hba->host);
4780 pm_runtime_put_sync(hba->dev);
4783 if (!hba->is_init_prefetch)
4784 hba->is_init_prefetch = true;
4786 /* Resume devfreq after UFS device is detected */
4787 if (ufshcd_is_clkscaling_enabled(hba))
4788 devfreq_resume_device(hba->devfreq);
4792 * If we failed to initialize the device or the device is not
4793 * present, turn off the power/clocks etc.
4795 if (ret && !ufshcd_eh_in_progress(hba) && !hba->pm_op_in_progress) {
4796 pm_runtime_put_sync(hba->dev);
4797 ufshcd_hba_exit(hba);
4804 * ufshcd_async_scan - asynchronous execution for probing hba
4805 * @data: data pointer to pass to this function
4806 * @cookie: cookie data
4808 static void ufshcd_async_scan(void *data, async_cookie_t cookie)
4810 struct ufs_hba *hba = (struct ufs_hba *)data;
4812 ufshcd_probe_hba(hba);
4815 static enum blk_eh_timer_return ufshcd_eh_timed_out(struct scsi_cmnd *scmd)
4817 unsigned long flags;
4818 struct Scsi_Host *host;
4819 struct ufs_hba *hba;
4823 if (!scmd || !scmd->device || !scmd->device->host)
4824 return BLK_EH_NOT_HANDLED;
4826 host = scmd->device->host;
4827 hba = shost_priv(host);
4829 return BLK_EH_NOT_HANDLED;
4831 spin_lock_irqsave(host->host_lock, flags);
4833 for_each_set_bit(index, &hba->outstanding_reqs, hba->nutrs) {
4834 if (hba->lrb[index].cmd == scmd) {
4840 spin_unlock_irqrestore(host->host_lock, flags);
4843 * Bypass SCSI error handling and reset the block layer timer if this
4844 * SCSI command was not actually dispatched to UFS driver, otherwise
4845 * let SCSI layer handle the error as usual.
4847 return found ? BLK_EH_NOT_HANDLED : BLK_EH_RESET_TIMER;
4850 static struct scsi_host_template ufshcd_driver_template = {
4851 .module = THIS_MODULE,
4853 .proc_name = UFSHCD,
4854 .queuecommand = ufshcd_queuecommand,
4855 .slave_alloc = ufshcd_slave_alloc,
4856 .slave_configure = ufshcd_slave_configure,
4857 .slave_destroy = ufshcd_slave_destroy,
4858 .change_queue_depth = ufshcd_change_queue_depth,
4859 .eh_abort_handler = ufshcd_abort,
4860 .eh_device_reset_handler = ufshcd_eh_device_reset_handler,
4861 .eh_host_reset_handler = ufshcd_eh_host_reset_handler,
4862 .eh_timed_out = ufshcd_eh_timed_out,
4864 .sg_tablesize = SG_ALL,
4865 .cmd_per_lun = UFSHCD_CMD_PER_LUN,
4866 .can_queue = UFSHCD_CAN_QUEUE,
4867 .max_host_blocked = 1,
4868 .track_queue_depth = 1,
4871 static int ufshcd_config_vreg_load(struct device *dev, struct ufs_vreg *vreg,
4879 ret = regulator_set_load(vreg->reg, ua);
4881 dev_err(dev, "%s: %s set load (ua=%d) failed, err=%d\n",
4882 __func__, vreg->name, ua, ret);
4888 static inline int ufshcd_config_vreg_lpm(struct ufs_hba *hba,
4889 struct ufs_vreg *vreg)
4893 else if (vreg->unused)
4896 return ufshcd_config_vreg_load(hba->dev, vreg,
4897 UFS_VREG_LPM_LOAD_UA);
4900 static inline int ufshcd_config_vreg_hpm(struct ufs_hba *hba,
4901 struct ufs_vreg *vreg)
4905 else if (vreg->unused)
4908 return ufshcd_config_vreg_load(hba->dev, vreg, vreg->max_uA);
4911 static int ufshcd_config_vreg(struct device *dev,
4912 struct ufs_vreg *vreg, bool on)
4915 struct regulator *reg = vreg->reg;
4916 const char *name = vreg->name;
4917 int min_uV, uA_load;
4921 if (regulator_count_voltages(reg) > 0) {
4922 min_uV = on ? vreg->min_uV : 0;
4923 ret = regulator_set_voltage(reg, min_uV, vreg->max_uV);
4925 dev_err(dev, "%s: %s set voltage failed, err=%d\n",
4926 __func__, name, ret);
4930 uA_load = on ? vreg->max_uA : 0;
4931 ret = ufshcd_config_vreg_load(dev, vreg, uA_load);
4939 static int ufshcd_enable_vreg(struct device *dev, struct ufs_vreg *vreg)
4945 else if (vreg->enabled || vreg->unused)
4948 ret = ufshcd_config_vreg(dev, vreg, true);
4950 ret = regulator_enable(vreg->reg);
4953 vreg->enabled = true;
4955 dev_err(dev, "%s: %s enable failed, err=%d\n",
4956 __func__, vreg->name, ret);
4961 static int ufshcd_disable_vreg(struct device *dev, struct ufs_vreg *vreg)
4967 else if (!vreg->enabled || vreg->unused)
4970 ret = regulator_disable(vreg->reg);
4973 /* ignore errors on applying disable config */
4974 ufshcd_config_vreg(dev, vreg, false);
4975 vreg->enabled = false;
4977 dev_err(dev, "%s: %s disable failed, err=%d\n",
4978 __func__, vreg->name, ret);
4984 static int ufshcd_setup_vreg(struct ufs_hba *hba, bool on)
4987 struct device *dev = hba->dev;
4988 struct ufs_vreg_info *info = &hba->vreg_info;
4993 ret = ufshcd_toggle_vreg(dev, info->vcc, on);
4997 ret = ufshcd_toggle_vreg(dev, info->vccq, on);
5001 ret = ufshcd_toggle_vreg(dev, info->vccq2, on);
5007 ufshcd_toggle_vreg(dev, info->vccq2, false);
5008 ufshcd_toggle_vreg(dev, info->vccq, false);
5009 ufshcd_toggle_vreg(dev, info->vcc, false);
5014 static int ufshcd_setup_hba_vreg(struct ufs_hba *hba, bool on)
5016 struct ufs_vreg_info *info = &hba->vreg_info;
5019 return ufshcd_toggle_vreg(hba->dev, info->vdd_hba, on);
5024 static int ufshcd_get_vreg(struct device *dev, struct ufs_vreg *vreg)
5031 vreg->reg = devm_regulator_get(dev, vreg->name);
5032 if (IS_ERR(vreg->reg)) {
5033 ret = PTR_ERR(vreg->reg);
5034 dev_err(dev, "%s: %s get failed, err=%d\n",
5035 __func__, vreg->name, ret);
5041 static int ufshcd_init_vreg(struct ufs_hba *hba)
5044 struct device *dev = hba->dev;
5045 struct ufs_vreg_info *info = &hba->vreg_info;
5050 ret = ufshcd_get_vreg(dev, info->vcc);
5054 ret = ufshcd_get_vreg(dev, info->vccq);
5058 ret = ufshcd_get_vreg(dev, info->vccq2);
5063 static int ufshcd_init_hba_vreg(struct ufs_hba *hba)
5065 struct ufs_vreg_info *info = &hba->vreg_info;
5068 return ufshcd_get_vreg(hba->dev, info->vdd_hba);
5073 static int ufshcd_set_vccq_rail_unused(struct ufs_hba *hba, bool unused)
5076 struct ufs_vreg_info *info = &hba->vreg_info;
5080 else if (!info->vccq)
5084 /* shut off the rail here */
5085 ret = ufshcd_toggle_vreg(hba->dev, info->vccq, false);
5087 * Mark this rail as no longer used, so it doesn't get enabled
5091 info->vccq->unused = true;
5094 * rail should have been already enabled hence just make sure
5095 * that unused flag is cleared.
5097 info->vccq->unused = false;
5103 static int __ufshcd_setup_clocks(struct ufs_hba *hba, bool on,
5107 struct ufs_clk_info *clki;
5108 struct list_head *head = &hba->clk_list_head;
5109 unsigned long flags;
5111 if (!head || list_empty(head))
5114 list_for_each_entry(clki, head, list) {
5115 if (!IS_ERR_OR_NULL(clki->clk)) {
5116 if (skip_ref_clk && !strcmp(clki->name, "ref_clk"))
5119 if (on && !clki->enabled) {
5120 ret = clk_prepare_enable(clki->clk);
5122 dev_err(hba->dev, "%s: %s prepare enable failed, %d\n",
5123 __func__, clki->name, ret);
5126 } else if (!on && clki->enabled) {
5127 clk_disable_unprepare(clki->clk);
5130 dev_dbg(hba->dev, "%s: clk: %s %sabled\n", __func__,
5131 clki->name, on ? "en" : "dis");
5135 ret = ufshcd_vops_setup_clocks(hba, on);
5138 list_for_each_entry(clki, head, list) {
5139 if (!IS_ERR_OR_NULL(clki->clk) && clki->enabled)
5140 clk_disable_unprepare(clki->clk);
5143 spin_lock_irqsave(hba->host->host_lock, flags);
5144 hba->clk_gating.state = CLKS_ON;
5145 spin_unlock_irqrestore(hba->host->host_lock, flags);
5150 static int ufshcd_setup_clocks(struct ufs_hba *hba, bool on)
5152 return __ufshcd_setup_clocks(hba, on, false);
5155 static int ufshcd_init_clocks(struct ufs_hba *hba)
5158 struct ufs_clk_info *clki;
5159 struct device *dev = hba->dev;
5160 struct list_head *head = &hba->clk_list_head;
5162 if (!head || list_empty(head))
5165 list_for_each_entry(clki, head, list) {
5169 clki->clk = devm_clk_get(dev, clki->name);
5170 if (IS_ERR(clki->clk)) {
5171 ret = PTR_ERR(clki->clk);
5172 dev_err(dev, "%s: %s clk get failed, %d\n",
5173 __func__, clki->name, ret);
5177 if (clki->max_freq) {
5178 ret = clk_set_rate(clki->clk, clki->max_freq);
5180 dev_err(hba->dev, "%s: %s clk set rate(%dHz) failed, %d\n",
5181 __func__, clki->name,
5182 clki->max_freq, ret);
5185 clki->curr_freq = clki->max_freq;
5187 dev_dbg(dev, "%s: clk: %s, rate: %lu\n", __func__,
5188 clki->name, clk_get_rate(clki->clk));
5194 static int ufshcd_variant_hba_init(struct ufs_hba *hba)
5201 err = ufshcd_vops_init(hba);
5205 err = ufshcd_vops_setup_regulators(hba, true);
5212 ufshcd_vops_exit(hba);
5215 dev_err(hba->dev, "%s: variant %s init failed err %d\n",
5216 __func__, ufshcd_get_var_name(hba), err);
5220 static void ufshcd_variant_hba_exit(struct ufs_hba *hba)
5225 ufshcd_vops_setup_clocks(hba, false);
5227 ufshcd_vops_setup_regulators(hba, false);
5229 ufshcd_vops_exit(hba);
5232 static int ufshcd_hba_init(struct ufs_hba *hba)
5237 * Handle host controller power separately from the UFS device power
5238 * rails as it will help controlling the UFS host controller power
5239 * collapse easily which is different than UFS device power collapse.
5240 * Also, enable the host controller power before we go ahead with rest
5241 * of the initialization here.
5243 err = ufshcd_init_hba_vreg(hba);
5247 err = ufshcd_setup_hba_vreg(hba, true);
5251 err = ufshcd_init_clocks(hba);
5253 goto out_disable_hba_vreg;
5255 err = ufshcd_setup_clocks(hba, true);
5257 goto out_disable_hba_vreg;
5259 err = ufshcd_init_vreg(hba);
5261 goto out_disable_clks;
5263 err = ufshcd_setup_vreg(hba, true);
5265 goto out_disable_clks;
5267 err = ufshcd_variant_hba_init(hba);
5269 goto out_disable_vreg;
5271 hba->is_powered = true;
5275 ufshcd_setup_vreg(hba, false);
5277 ufshcd_setup_clocks(hba, false);
5278 out_disable_hba_vreg:
5279 ufshcd_setup_hba_vreg(hba, false);
5284 static void ufshcd_hba_exit(struct ufs_hba *hba)
5286 if (hba->is_powered) {
5287 ufshcd_variant_hba_exit(hba);
5288 ufshcd_setup_vreg(hba, false);
5289 ufshcd_setup_clocks(hba, false);
5290 ufshcd_setup_hba_vreg(hba, false);
5291 hba->is_powered = false;
5296 ufshcd_send_request_sense(struct ufs_hba *hba, struct scsi_device *sdp)
5298 unsigned char cmd[6] = {REQUEST_SENSE,
5302 SCSI_SENSE_BUFFERSIZE,
5307 buffer = kzalloc(SCSI_SENSE_BUFFERSIZE, GFP_KERNEL);
5313 ret = scsi_execute_req_flags(sdp, cmd, DMA_FROM_DEVICE, buffer,
5314 SCSI_SENSE_BUFFERSIZE, NULL,
5315 msecs_to_jiffies(1000), 3, NULL, REQ_PM);
5317 pr_err("%s: failed with err %d\n", __func__, ret);
5325 * ufshcd_set_dev_pwr_mode - sends START STOP UNIT command to set device
5327 * @hba: per adapter instance
5328 * @pwr_mode: device power mode to set
5330 * Returns 0 if requested power mode is set successfully
5331 * Returns non-zero if failed to set the requested power mode
5333 static int ufshcd_set_dev_pwr_mode(struct ufs_hba *hba,
5334 enum ufs_dev_pwr_mode pwr_mode)
5336 unsigned char cmd[6] = { START_STOP };
5337 struct scsi_sense_hdr sshdr;
5338 struct scsi_device *sdp;
5339 unsigned long flags;
5342 spin_lock_irqsave(hba->host->host_lock, flags);
5343 sdp = hba->sdev_ufs_device;
5345 ret = scsi_device_get(sdp);
5346 if (!ret && !scsi_device_online(sdp)) {
5348 scsi_device_put(sdp);
5353 spin_unlock_irqrestore(hba->host->host_lock, flags);
5359 * If scsi commands fail, the scsi mid-layer schedules scsi error-
5360 * handling, which would wait for host to be resumed. Since we know
5361 * we are functional while we are here, skip host resume in error
5364 hba->host->eh_noresume = 1;
5365 if (hba->wlun_dev_clr_ua) {
5366 ret = ufshcd_send_request_sense(hba, sdp);
5369 /* Unit attention condition is cleared now */
5370 hba->wlun_dev_clr_ua = false;
5373 cmd[4] = pwr_mode << 4;
5376 * Current function would be generally called from the power management
5377 * callbacks hence set the REQ_PM flag so that it doesn't resume the
5378 * already suspended childs.
5380 ret = scsi_execute_req_flags(sdp, cmd, DMA_NONE, NULL, 0, &sshdr,
5381 START_STOP_TIMEOUT, 0, NULL, REQ_PM);
5383 sdev_printk(KERN_WARNING, sdp,
5384 "START_STOP failed for power mode: %d, result %x\n",
5386 if (driver_byte(ret) & DRIVER_SENSE)
5387 scsi_print_sense_hdr(sdp, NULL, &sshdr);
5391 hba->curr_dev_pwr_mode = pwr_mode;
5393 scsi_device_put(sdp);
5394 hba->host->eh_noresume = 0;
5398 static int ufshcd_link_state_transition(struct ufs_hba *hba,
5399 enum uic_link_state req_link_state,
5400 int check_for_bkops)
5404 if (req_link_state == hba->uic_link_state)
5407 if (req_link_state == UIC_LINK_HIBERN8_STATE) {
5408 ret = ufshcd_uic_hibern8_enter(hba);
5410 ufshcd_set_link_hibern8(hba);
5415 * If autobkops is enabled, link can't be turned off because
5416 * turning off the link would also turn off the device.
5418 else if ((req_link_state == UIC_LINK_OFF_STATE) &&
5419 (!check_for_bkops || (check_for_bkops &&
5420 !hba->auto_bkops_enabled))) {
5422 * Change controller state to "reset state" which
5423 * should also put the link in off/reset state
5425 ufshcd_hba_stop(hba, true);
5427 * TODO: Check if we need any delay to make sure that
5428 * controller is reset
5430 ufshcd_set_link_off(hba);
5437 static void ufshcd_vreg_set_lpm(struct ufs_hba *hba)
5440 * If UFS device is either in UFS_Sleep turn off VCC rail to save some
5443 * If UFS device and link is in OFF state, all power supplies (VCC,
5444 * VCCQ, VCCQ2) can be turned off if power on write protect is not
5445 * required. If UFS link is inactive (Hibern8 or OFF state) and device
5446 * is in sleep state, put VCCQ & VCCQ2 rails in LPM mode.
5448 * Ignore the error returned by ufshcd_toggle_vreg() as device is anyway
5449 * in low power state which would save some power.
5451 if (ufshcd_is_ufs_dev_poweroff(hba) && ufshcd_is_link_off(hba) &&
5452 !hba->dev_info.is_lu_power_on_wp) {
5453 ufshcd_setup_vreg(hba, false);
5454 } else if (!ufshcd_is_ufs_dev_active(hba)) {
5455 ufshcd_toggle_vreg(hba->dev, hba->vreg_info.vcc, false);
5456 if (!ufshcd_is_link_active(hba)) {
5457 ufshcd_config_vreg_lpm(hba, hba->vreg_info.vccq);
5458 ufshcd_config_vreg_lpm(hba, hba->vreg_info.vccq2);
5463 static int ufshcd_vreg_set_hpm(struct ufs_hba *hba)
5467 if (ufshcd_is_ufs_dev_poweroff(hba) && ufshcd_is_link_off(hba) &&
5468 !hba->dev_info.is_lu_power_on_wp) {
5469 ret = ufshcd_setup_vreg(hba, true);
5470 } else if (!ufshcd_is_ufs_dev_active(hba)) {
5471 ret = ufshcd_toggle_vreg(hba->dev, hba->vreg_info.vcc, true);
5472 if (!ret && !ufshcd_is_link_active(hba)) {
5473 ret = ufshcd_config_vreg_hpm(hba, hba->vreg_info.vccq);
5476 ret = ufshcd_config_vreg_hpm(hba, hba->vreg_info.vccq2);
5484 ufshcd_config_vreg_lpm(hba, hba->vreg_info.vccq);
5486 ufshcd_toggle_vreg(hba->dev, hba->vreg_info.vcc, false);
5491 static void ufshcd_hba_vreg_set_lpm(struct ufs_hba *hba)
5493 if (ufshcd_is_link_off(hba))
5494 ufshcd_setup_hba_vreg(hba, false);
5497 static void ufshcd_hba_vreg_set_hpm(struct ufs_hba *hba)
5499 if (ufshcd_is_link_off(hba))
5500 ufshcd_setup_hba_vreg(hba, true);
5504 * ufshcd_suspend - helper function for suspend operations
5505 * @hba: per adapter instance
5506 * @pm_op: desired low power operation type
5508 * This function will try to put the UFS device and link into low power
5509 * mode based on the "rpm_lvl" (Runtime PM level) or "spm_lvl"
5510 * (System PM level).
5512 * If this function is called during shutdown, it will make sure that
5513 * both UFS device and UFS link is powered off.
5515 * NOTE: UFS device & link must be active before we enter in this function.
5517 * Returns 0 for success and non-zero for failure
5519 static int ufshcd_suspend(struct ufs_hba *hba, enum ufs_pm_op pm_op)
5522 enum ufs_pm_level pm_lvl;
5523 enum ufs_dev_pwr_mode req_dev_pwr_mode;
5524 enum uic_link_state req_link_state;
5526 hba->pm_op_in_progress = 1;
5527 if (!ufshcd_is_shutdown_pm(pm_op)) {
5528 pm_lvl = ufshcd_is_runtime_pm(pm_op) ?
5529 hba->rpm_lvl : hba->spm_lvl;
5530 req_dev_pwr_mode = ufs_get_pm_lvl_to_dev_pwr_mode(pm_lvl);
5531 req_link_state = ufs_get_pm_lvl_to_link_pwr_state(pm_lvl);
5533 req_dev_pwr_mode = UFS_POWERDOWN_PWR_MODE;
5534 req_link_state = UIC_LINK_OFF_STATE;
5538 * If we can't transition into any of the low power modes
5539 * just gate the clocks.
5541 ufshcd_hold(hba, false);
5542 hba->clk_gating.is_suspended = true;
5544 if (req_dev_pwr_mode == UFS_ACTIVE_PWR_MODE &&
5545 req_link_state == UIC_LINK_ACTIVE_STATE) {
5549 if ((req_dev_pwr_mode == hba->curr_dev_pwr_mode) &&
5550 (req_link_state == hba->uic_link_state))
5553 /* UFS device & link must be active before we enter in this function */
5554 if (!ufshcd_is_ufs_dev_active(hba) || !ufshcd_is_link_active(hba)) {
5559 if (ufshcd_is_runtime_pm(pm_op)) {
5560 if (ufshcd_can_autobkops_during_suspend(hba)) {
5562 * The device is idle with no requests in the queue,
5563 * allow background operations if bkops status shows
5564 * that performance might be impacted.
5566 ret = ufshcd_urgent_bkops(hba);
5570 /* make sure that auto bkops is disabled */
5571 ufshcd_disable_auto_bkops(hba);
5575 if ((req_dev_pwr_mode != hba->curr_dev_pwr_mode) &&
5576 ((ufshcd_is_runtime_pm(pm_op) && !hba->auto_bkops_enabled) ||
5577 !ufshcd_is_runtime_pm(pm_op))) {
5578 /* ensure that bkops is disabled */
5579 ufshcd_disable_auto_bkops(hba);
5580 ret = ufshcd_set_dev_pwr_mode(hba, req_dev_pwr_mode);
5585 ret = ufshcd_link_state_transition(hba, req_link_state, 1);
5587 goto set_dev_active;
5589 ufshcd_vreg_set_lpm(hba);
5593 * The clock scaling needs access to controller registers. Hence, Wait
5594 * for pending clock scaling work to be done before clocks are
5597 if (ufshcd_is_clkscaling_enabled(hba)) {
5598 devfreq_suspend_device(hba->devfreq);
5599 hba->clk_scaling.window_start_t = 0;
5602 * Call vendor specific suspend callback. As these callbacks may access
5603 * vendor specific host controller register space call them before the
5604 * host clocks are ON.
5606 ret = ufshcd_vops_suspend(hba, pm_op);
5608 goto set_link_active;
5610 ret = ufshcd_vops_setup_clocks(hba, false);
5614 if (!ufshcd_is_link_active(hba))
5615 ufshcd_setup_clocks(hba, false);
5617 /* If link is active, device ref_clk can't be switched off */
5618 __ufshcd_setup_clocks(hba, false, true);
5620 hba->clk_gating.state = CLKS_OFF;
5622 * Disable the host irq as host controller as there won't be any
5623 * host controller transaction expected till resume.
5625 ufshcd_disable_irq(hba);
5626 /* Put the host controller in low power mode if possible */
5627 ufshcd_hba_vreg_set_lpm(hba);
5631 ufshcd_vops_resume(hba, pm_op);
5633 ufshcd_vreg_set_hpm(hba);
5634 if (ufshcd_is_link_hibern8(hba) && !ufshcd_uic_hibern8_exit(hba))
5635 ufshcd_set_link_active(hba);
5636 else if (ufshcd_is_link_off(hba))
5637 ufshcd_host_reset_and_restore(hba);
5639 if (!ufshcd_set_dev_pwr_mode(hba, UFS_ACTIVE_PWR_MODE))
5640 ufshcd_disable_auto_bkops(hba);
5642 hba->clk_gating.is_suspended = false;
5643 ufshcd_release(hba);
5645 hba->pm_op_in_progress = 0;
5650 * ufshcd_resume - helper function for resume operations
5651 * @hba: per adapter instance
5652 * @pm_op: runtime PM or system PM
5654 * This function basically brings the UFS device, UniPro link and controller
5657 * Returns 0 for success and non-zero for failure
5659 static int ufshcd_resume(struct ufs_hba *hba, enum ufs_pm_op pm_op)
5662 enum uic_link_state old_link_state;
5664 hba->pm_op_in_progress = 1;
5665 old_link_state = hba->uic_link_state;
5667 ufshcd_hba_vreg_set_hpm(hba);
5668 /* Make sure clocks are enabled before accessing controller */
5669 ret = ufshcd_setup_clocks(hba, true);
5673 /* enable the host irq as host controller would be active soon */
5674 ret = ufshcd_enable_irq(hba);
5676 goto disable_irq_and_vops_clks;
5678 ret = ufshcd_vreg_set_hpm(hba);
5680 goto disable_irq_and_vops_clks;
5683 * Call vendor specific resume callback. As these callbacks may access
5684 * vendor specific host controller register space call them when the
5685 * host clocks are ON.
5687 ret = ufshcd_vops_resume(hba, pm_op);
5691 if (ufshcd_is_link_hibern8(hba)) {
5692 ret = ufshcd_uic_hibern8_exit(hba);
5694 ufshcd_set_link_active(hba);
5696 goto vendor_suspend;
5697 } else if (ufshcd_is_link_off(hba)) {
5698 ret = ufshcd_host_reset_and_restore(hba);
5700 * ufshcd_host_reset_and_restore() should have already
5701 * set the link state as active
5703 if (ret || !ufshcd_is_link_active(hba))
5704 goto vendor_suspend;
5707 if (!ufshcd_is_ufs_dev_active(hba)) {
5708 ret = ufshcd_set_dev_pwr_mode(hba, UFS_ACTIVE_PWR_MODE);
5710 goto set_old_link_state;
5714 * If BKOPs operations are urgently needed at this moment then
5715 * keep auto-bkops enabled or else disable it.
5717 ufshcd_urgent_bkops(hba);
5718 hba->clk_gating.is_suspended = false;
5720 if (ufshcd_is_clkscaling_enabled(hba))
5721 devfreq_resume_device(hba->devfreq);
5723 /* Schedule clock gating in case of no access to UFS device yet */
5724 ufshcd_release(hba);
5728 ufshcd_link_state_transition(hba, old_link_state, 0);
5730 ufshcd_vops_suspend(hba, pm_op);
5732 ufshcd_vreg_set_lpm(hba);
5733 disable_irq_and_vops_clks:
5734 ufshcd_disable_irq(hba);
5735 ufshcd_setup_clocks(hba, false);
5737 hba->pm_op_in_progress = 0;
5742 * ufshcd_system_suspend - system suspend routine
5743 * @hba: per adapter instance
5744 * @pm_op: runtime PM or system PM
5746 * Check the description of ufshcd_suspend() function for more details.
5748 * Returns 0 for success and non-zero for failure
5750 int ufshcd_system_suspend(struct ufs_hba *hba)
5754 if (!hba || !hba->is_powered)
5757 if (pm_runtime_suspended(hba->dev)) {
5758 if (hba->rpm_lvl == hba->spm_lvl)
5760 * There is possibility that device may still be in
5761 * active state during the runtime suspend.
5763 if ((ufs_get_pm_lvl_to_dev_pwr_mode(hba->spm_lvl) ==
5764 hba->curr_dev_pwr_mode) && !hba->auto_bkops_enabled)
5768 * UFS device and/or UFS link low power states during runtime
5769 * suspend seems to be different than what is expected during
5770 * system suspend. Hence runtime resume the devic & link and
5771 * let the system suspend low power states to take effect.
5772 * TODO: If resume takes longer time, we might have optimize
5773 * it in future by not resuming everything if possible.
5775 ret = ufshcd_runtime_resume(hba);
5780 ret = ufshcd_suspend(hba, UFS_SYSTEM_PM);
5783 hba->is_sys_suspended = true;
5786 EXPORT_SYMBOL(ufshcd_system_suspend);
5789 * ufshcd_system_resume - system resume routine
5790 * @hba: per adapter instance
5792 * Returns 0 for success and non-zero for failure
5795 int ufshcd_system_resume(struct ufs_hba *hba)
5797 if (!hba || !hba->is_powered || pm_runtime_suspended(hba->dev))
5799 * Let the runtime resume take care of resuming
5800 * if runtime suspended.
5804 return ufshcd_resume(hba, UFS_SYSTEM_PM);
5806 EXPORT_SYMBOL(ufshcd_system_resume);
5809 * ufshcd_runtime_suspend - runtime suspend routine
5810 * @hba: per adapter instance
5812 * Check the description of ufshcd_suspend() function for more details.
5814 * Returns 0 for success and non-zero for failure
5816 int ufshcd_runtime_suspend(struct ufs_hba *hba)
5818 if (!hba || !hba->is_powered)
5821 return ufshcd_suspend(hba, UFS_RUNTIME_PM);
5823 EXPORT_SYMBOL(ufshcd_runtime_suspend);
5826 * ufshcd_runtime_resume - runtime resume routine
5827 * @hba: per adapter instance
5829 * This function basically brings the UFS device, UniPro link and controller
5830 * to active state. Following operations are done in this function:
5832 * 1. Turn on all the controller related clocks
5833 * 2. Bring the UniPro link out of Hibernate state
5834 * 3. If UFS device is in sleep state, turn ON VCC rail and bring the UFS device
5836 * 4. If auto-bkops is enabled on the device, disable it.
5838 * So following would be the possible power state after this function return
5840 * S1: UFS device in Active state with VCC rail ON
5841 * UniPro link in Active state
5842 * All the UFS/UniPro controller clocks are ON
5844 * Returns 0 for success and non-zero for failure
5846 int ufshcd_runtime_resume(struct ufs_hba *hba)
5848 if (!hba || !hba->is_powered)
5851 return ufshcd_resume(hba, UFS_RUNTIME_PM);
5853 EXPORT_SYMBOL(ufshcd_runtime_resume);
5855 int ufshcd_runtime_idle(struct ufs_hba *hba)
5859 EXPORT_SYMBOL(ufshcd_runtime_idle);
5862 * ufshcd_shutdown - shutdown routine
5863 * @hba: per adapter instance
5865 * This function would power off both UFS device and UFS link.
5867 * Returns 0 always to allow force shutdown even in case of errors.
5869 int ufshcd_shutdown(struct ufs_hba *hba)
5873 if (ufshcd_is_ufs_dev_poweroff(hba) && ufshcd_is_link_off(hba))
5876 if (pm_runtime_suspended(hba->dev)) {
5877 ret = ufshcd_runtime_resume(hba);
5882 ret = ufshcd_suspend(hba, UFS_SHUTDOWN_PM);
5885 dev_err(hba->dev, "%s failed, err %d\n", __func__, ret);
5886 /* allow force shutdown even in case of errors */
5889 EXPORT_SYMBOL(ufshcd_shutdown);
5892 * ufshcd_remove - de-allocate SCSI host and host memory space
5893 * data structure memory
5894 * @hba - per adapter instance
5896 void ufshcd_remove(struct ufs_hba *hba)
5898 scsi_remove_host(hba->host);
5899 /* disable interrupts */
5900 ufshcd_disable_intr(hba, hba->intr_mask);
5901 ufshcd_hba_stop(hba, true);
5903 scsi_host_put(hba->host);
5905 ufshcd_exit_clk_gating(hba);
5906 if (ufshcd_is_clkscaling_enabled(hba))
5907 devfreq_remove_device(hba->devfreq);
5908 ufshcd_hba_exit(hba);
5910 EXPORT_SYMBOL_GPL(ufshcd_remove);
5913 * ufshcd_dealloc_host - deallocate Host Bus Adapter (HBA)
5914 * @hba: pointer to Host Bus Adapter (HBA)
5916 void ufshcd_dealloc_host(struct ufs_hba *hba)
5918 scsi_host_put(hba->host);
5920 EXPORT_SYMBOL_GPL(ufshcd_dealloc_host);
5923 * ufshcd_set_dma_mask - Set dma mask based on the controller
5924 * addressing capability
5925 * @hba: per adapter instance
5927 * Returns 0 for success, non-zero for failure
5929 static int ufshcd_set_dma_mask(struct ufs_hba *hba)
5931 if (hba->capabilities & MASK_64_ADDRESSING_SUPPORT) {
5932 if (!dma_set_mask_and_coherent(hba->dev, DMA_BIT_MASK(64)))
5935 return dma_set_mask_and_coherent(hba->dev, DMA_BIT_MASK(32));
5939 * ufshcd_alloc_host - allocate Host Bus Adapter (HBA)
5940 * @dev: pointer to device handle
5941 * @hba_handle: driver private handle
5942 * Returns 0 on success, non-zero value on failure
5944 int ufshcd_alloc_host(struct device *dev, struct ufs_hba **hba_handle)
5946 struct Scsi_Host *host;
5947 struct ufs_hba *hba;
5952 "Invalid memory reference for dev is NULL\n");
5957 host = scsi_host_alloc(&ufshcd_driver_template,
5958 sizeof(struct ufs_hba));
5960 dev_err(dev, "scsi_host_alloc failed\n");
5964 hba = shost_priv(host);
5972 EXPORT_SYMBOL(ufshcd_alloc_host);
5974 static int ufshcd_scale_clks(struct ufs_hba *hba, bool scale_up)
5977 struct ufs_clk_info *clki;
5978 struct list_head *head = &hba->clk_list_head;
5980 if (!head || list_empty(head))
5983 ret = ufshcd_vops_clk_scale_notify(hba, scale_up, PRE_CHANGE);
5987 list_for_each_entry(clki, head, list) {
5988 if (!IS_ERR_OR_NULL(clki->clk)) {
5989 if (scale_up && clki->max_freq) {
5990 if (clki->curr_freq == clki->max_freq)
5992 ret = clk_set_rate(clki->clk, clki->max_freq);
5994 dev_err(hba->dev, "%s: %s clk set rate(%dHz) failed, %d\n",
5995 __func__, clki->name,
5996 clki->max_freq, ret);
5999 clki->curr_freq = clki->max_freq;
6001 } else if (!scale_up && clki->min_freq) {
6002 if (clki->curr_freq == clki->min_freq)
6004 ret = clk_set_rate(clki->clk, clki->min_freq);
6006 dev_err(hba->dev, "%s: %s clk set rate(%dHz) failed, %d\n",
6007 __func__, clki->name,
6008 clki->min_freq, ret);
6011 clki->curr_freq = clki->min_freq;
6014 dev_dbg(hba->dev, "%s: clk: %s, rate: %lu\n", __func__,
6015 clki->name, clk_get_rate(clki->clk));
6018 ret = ufshcd_vops_clk_scale_notify(hba, scale_up, POST_CHANGE);
6024 static int ufshcd_devfreq_target(struct device *dev,
6025 unsigned long *freq, u32 flags)
6028 struct ufs_hba *hba = dev_get_drvdata(dev);
6030 if (!ufshcd_is_clkscaling_enabled(hba))
6033 if (*freq == UINT_MAX)
6034 err = ufshcd_scale_clks(hba, true);
6035 else if (*freq == 0)
6036 err = ufshcd_scale_clks(hba, false);
6041 static int ufshcd_devfreq_get_dev_status(struct device *dev,
6042 struct devfreq_dev_status *stat)
6044 struct ufs_hba *hba = dev_get_drvdata(dev);
6045 struct ufs_clk_scaling *scaling = &hba->clk_scaling;
6046 unsigned long flags;
6048 if (!ufshcd_is_clkscaling_enabled(hba))
6051 memset(stat, 0, sizeof(*stat));
6053 spin_lock_irqsave(hba->host->host_lock, flags);
6054 if (!scaling->window_start_t)
6057 if (scaling->is_busy_started)
6058 scaling->tot_busy_t += ktime_to_us(ktime_sub(ktime_get(),
6059 scaling->busy_start_t));
6061 stat->total_time = jiffies_to_usecs((long)jiffies -
6062 (long)scaling->window_start_t);
6063 stat->busy_time = scaling->tot_busy_t;
6065 scaling->window_start_t = jiffies;
6066 scaling->tot_busy_t = 0;
6068 if (hba->outstanding_reqs) {
6069 scaling->busy_start_t = ktime_get();
6070 scaling->is_busy_started = true;
6072 scaling->busy_start_t = ktime_set(0, 0);
6073 scaling->is_busy_started = false;
6075 spin_unlock_irqrestore(hba->host->host_lock, flags);
6079 static struct devfreq_dev_profile ufs_devfreq_profile = {
6081 .target = ufshcd_devfreq_target,
6082 .get_dev_status = ufshcd_devfreq_get_dev_status,
6086 * ufshcd_init - Driver initialization routine
6087 * @hba: per-adapter instance
6088 * @mmio_base: base register address
6089 * @irq: Interrupt line of device
6090 * Returns 0 on success, non-zero value on failure
6092 int ufshcd_init(struct ufs_hba *hba, void __iomem *mmio_base, unsigned int irq)
6095 struct Scsi_Host *host = hba->host;
6096 struct device *dev = hba->dev;
6100 "Invalid memory reference for mmio_base is NULL\n");
6105 hba->mmio_base = mmio_base;
6108 err = ufshcd_hba_init(hba);
6112 /* Read capabilities registers */
6113 ufshcd_hba_capabilities(hba);
6115 /* Get UFS version supported by the controller */
6116 hba->ufs_version = ufshcd_get_ufs_version(hba);
6118 /* Get Interrupt bit mask per version */
6119 hba->intr_mask = ufshcd_get_intr_mask(hba);
6121 err = ufshcd_set_dma_mask(hba);
6123 dev_err(hba->dev, "set dma mask failed\n");
6127 /* Allocate memory for host memory space */
6128 err = ufshcd_memory_alloc(hba);
6130 dev_err(hba->dev, "Memory allocation failed\n");
6135 ufshcd_host_memory_configure(hba);
6137 host->can_queue = hba->nutrs;
6138 host->cmd_per_lun = hba->nutrs;
6139 host->max_id = UFSHCD_MAX_ID;
6140 host->max_lun = UFS_MAX_LUNS;
6141 host->max_channel = UFSHCD_MAX_CHANNEL;
6142 host->unique_id = host->host_no;
6143 host->max_cmd_len = MAX_CDB_SIZE;
6145 hba->max_pwr_info.is_valid = false;
6147 /* Initailize wait queue for task management */
6148 init_waitqueue_head(&hba->tm_wq);
6149 init_waitqueue_head(&hba->tm_tag_wq);
6151 /* Initialize work queues */
6152 INIT_WORK(&hba->eh_work, ufshcd_err_handler);
6153 INIT_WORK(&hba->eeh_work, ufshcd_exception_event_handler);
6155 /* Initialize UIC command mutex */
6156 mutex_init(&hba->uic_cmd_mutex);
6158 /* Initialize mutex for device management commands */
6159 mutex_init(&hba->dev_cmd.lock);
6161 /* Initialize device management tag acquire wait queue */
6162 init_waitqueue_head(&hba->dev_cmd.tag_wq);
6164 ufshcd_init_clk_gating(hba);
6167 * In order to avoid any spurious interrupt immediately after
6168 * registering UFS controller interrupt handler, clear any pending UFS
6169 * interrupt status and disable all the UFS interrupts.
6171 ufshcd_writel(hba, ufshcd_readl(hba, REG_INTERRUPT_STATUS),
6172 REG_INTERRUPT_STATUS);
6173 ufshcd_writel(hba, 0, REG_INTERRUPT_ENABLE);
6175 * Make sure that UFS interrupts are disabled and any pending interrupt
6176 * status is cleared before registering UFS interrupt handler.
6180 /* IRQ registration */
6181 err = devm_request_irq(dev, irq, ufshcd_intr, IRQF_SHARED, UFSHCD, hba);
6183 dev_err(hba->dev, "request irq failed\n");
6186 hba->is_irq_enabled = true;
6189 err = scsi_add_host(host, hba->dev);
6191 dev_err(hba->dev, "scsi_add_host failed\n");
6195 /* Host controller enable */
6196 err = ufshcd_hba_enable(hba);
6198 dev_err(hba->dev, "Host controller enable failed\n");
6199 goto out_remove_scsi_host;
6202 if (ufshcd_is_clkscaling_enabled(hba)) {
6203 hba->devfreq = devfreq_add_device(dev, &ufs_devfreq_profile,
6204 "simple_ondemand", NULL);
6205 if (IS_ERR(hba->devfreq)) {
6206 dev_err(hba->dev, "Unable to register with devfreq %ld\n",
6207 PTR_ERR(hba->devfreq));
6208 goto out_remove_scsi_host;
6210 /* Suspend devfreq until the UFS device is detected */
6211 devfreq_suspend_device(hba->devfreq);
6212 hba->clk_scaling.window_start_t = 0;
6215 /* Hold auto suspend until async scan completes */
6216 pm_runtime_get_sync(dev);
6219 * The device-initialize-sequence hasn't been invoked yet.
6220 * Set the device to power-off state
6222 ufshcd_set_ufs_dev_poweroff(hba);
6224 async_schedule(ufshcd_async_scan, hba);
6228 out_remove_scsi_host:
6229 scsi_remove_host(hba->host);
6231 ufshcd_exit_clk_gating(hba);
6233 hba->is_irq_enabled = false;
6234 scsi_host_put(host);
6235 ufshcd_hba_exit(hba);
6239 EXPORT_SYMBOL_GPL(ufshcd_init);
6241 MODULE_AUTHOR("Santosh Yaragnavi <santosh.sy@samsung.com>");
6242 MODULE_AUTHOR("Vinayak Holikatti <h.vinayak@samsung.com>");
6243 MODULE_DESCRIPTION("Generic UFS host controller driver Core");
6244 MODULE_LICENSE("GPL");
6245 MODULE_VERSION(UFSHCD_DRIVER_VERSION);