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 u32 ufshcd_get_local_unipro_ver(struct ufs_hba *hba)
575 /* HCI version 1.0 and 1.1 supports UniPro 1.41 */
576 if ((hba->ufs_version == UFSHCI_VERSION_10) ||
577 (hba->ufs_version == UFSHCI_VERSION_11))
578 return UFS_UNIPRO_VER_1_41;
580 return UFS_UNIPRO_VER_1_6;
582 EXPORT_SYMBOL(ufshcd_get_local_unipro_ver);
584 static bool ufshcd_is_unipro_pa_params_tuning_req(struct ufs_hba *hba)
587 * If both host and device support UniPro ver1.6 or later, PA layer
588 * parameters tuning happens during link startup itself.
590 * We can manually tune PA layer parameters if either host or device
591 * doesn't support UniPro ver 1.6 or later. But to keep manual tuning
592 * logic simple, we will only do manual tuning if local unipro version
593 * doesn't support ver1.6 or later.
595 if (ufshcd_get_local_unipro_ver(hba) < UFS_UNIPRO_VER_1_6)
601 static void ufshcd_ungate_work(struct work_struct *work)
605 struct ufs_hba *hba = container_of(work, struct ufs_hba,
606 clk_gating.ungate_work);
608 cancel_delayed_work_sync(&hba->clk_gating.gate_work);
610 spin_lock_irqsave(hba->host->host_lock, flags);
611 if (hba->clk_gating.state == CLKS_ON) {
612 spin_unlock_irqrestore(hba->host->host_lock, flags);
616 spin_unlock_irqrestore(hba->host->host_lock, flags);
617 ufshcd_setup_clocks(hba, true);
619 /* Exit from hibern8 */
620 if (ufshcd_can_hibern8_during_gating(hba)) {
621 /* Prevent gating in this path */
622 hba->clk_gating.is_suspended = true;
623 if (ufshcd_is_link_hibern8(hba)) {
624 ret = ufshcd_uic_hibern8_exit(hba);
626 dev_err(hba->dev, "%s: hibern8 exit failed %d\n",
629 ufshcd_set_link_active(hba);
631 hba->clk_gating.is_suspended = false;
634 if (ufshcd_is_clkscaling_enabled(hba))
635 devfreq_resume_device(hba->devfreq);
636 scsi_unblock_requests(hba->host);
640 * ufshcd_hold - Enable clocks that were gated earlier due to ufshcd_release.
641 * Also, exit from hibern8 mode and set the link as active.
642 * @hba: per adapter instance
643 * @async: This indicates whether caller should ungate clocks asynchronously.
645 int ufshcd_hold(struct ufs_hba *hba, bool async)
650 if (!ufshcd_is_clkgating_allowed(hba))
652 spin_lock_irqsave(hba->host->host_lock, flags);
653 hba->clk_gating.active_reqs++;
655 if (ufshcd_eh_in_progress(hba)) {
656 spin_unlock_irqrestore(hba->host->host_lock, flags);
661 switch (hba->clk_gating.state) {
665 if (cancel_delayed_work(&hba->clk_gating.gate_work)) {
666 hba->clk_gating.state = CLKS_ON;
670 * If we here, it means gating work is either done or
671 * currently running. Hence, fall through to cancel gating
672 * work and to enable clocks.
675 scsi_block_requests(hba->host);
676 hba->clk_gating.state = REQ_CLKS_ON;
677 schedule_work(&hba->clk_gating.ungate_work);
679 * fall through to check if we should wait for this
680 * work to be done or not.
685 hba->clk_gating.active_reqs--;
689 spin_unlock_irqrestore(hba->host->host_lock, flags);
690 flush_work(&hba->clk_gating.ungate_work);
691 /* Make sure state is CLKS_ON before returning */
692 spin_lock_irqsave(hba->host->host_lock, flags);
695 dev_err(hba->dev, "%s: clk gating is in invalid state %d\n",
696 __func__, hba->clk_gating.state);
699 spin_unlock_irqrestore(hba->host->host_lock, flags);
703 EXPORT_SYMBOL_GPL(ufshcd_hold);
705 static void ufshcd_gate_work(struct work_struct *work)
707 struct ufs_hba *hba = container_of(work, struct ufs_hba,
708 clk_gating.gate_work.work);
711 spin_lock_irqsave(hba->host->host_lock, flags);
712 if (hba->clk_gating.is_suspended) {
713 hba->clk_gating.state = CLKS_ON;
717 if (hba->clk_gating.active_reqs
718 || hba->ufshcd_state != UFSHCD_STATE_OPERATIONAL
719 || hba->lrb_in_use || hba->outstanding_tasks
720 || hba->active_uic_cmd || hba->uic_async_done)
723 spin_unlock_irqrestore(hba->host->host_lock, flags);
725 /* put the link into hibern8 mode before turning off clocks */
726 if (ufshcd_can_hibern8_during_gating(hba)) {
727 if (ufshcd_uic_hibern8_enter(hba)) {
728 hba->clk_gating.state = CLKS_ON;
731 ufshcd_set_link_hibern8(hba);
734 if (ufshcd_is_clkscaling_enabled(hba)) {
735 devfreq_suspend_device(hba->devfreq);
736 hba->clk_scaling.window_start_t = 0;
739 if (!ufshcd_is_link_active(hba))
740 ufshcd_setup_clocks(hba, false);
742 /* If link is active, device ref_clk can't be switched off */
743 __ufshcd_setup_clocks(hba, false, true);
746 * In case you are here to cancel this work the gating state
747 * would be marked as REQ_CLKS_ON. In this case keep the state
748 * as REQ_CLKS_ON which would anyway imply that clocks are off
749 * and a request to turn them on is pending. By doing this way,
750 * we keep the state machine in tact and this would ultimately
751 * prevent from doing cancel work multiple times when there are
752 * new requests arriving before the current cancel work is done.
754 spin_lock_irqsave(hba->host->host_lock, flags);
755 if (hba->clk_gating.state == REQ_CLKS_OFF)
756 hba->clk_gating.state = CLKS_OFF;
759 spin_unlock_irqrestore(hba->host->host_lock, flags);
764 /* host lock must be held before calling this variant */
765 static void __ufshcd_release(struct ufs_hba *hba)
767 if (!ufshcd_is_clkgating_allowed(hba))
770 hba->clk_gating.active_reqs--;
772 if (hba->clk_gating.active_reqs || hba->clk_gating.is_suspended
773 || hba->ufshcd_state != UFSHCD_STATE_OPERATIONAL
774 || hba->lrb_in_use || hba->outstanding_tasks
775 || hba->active_uic_cmd || hba->uic_async_done
776 || ufshcd_eh_in_progress(hba))
779 hba->clk_gating.state = REQ_CLKS_OFF;
780 schedule_delayed_work(&hba->clk_gating.gate_work,
781 msecs_to_jiffies(hba->clk_gating.delay_ms));
784 void ufshcd_release(struct ufs_hba *hba)
788 spin_lock_irqsave(hba->host->host_lock, flags);
789 __ufshcd_release(hba);
790 spin_unlock_irqrestore(hba->host->host_lock, flags);
792 EXPORT_SYMBOL_GPL(ufshcd_release);
794 static ssize_t ufshcd_clkgate_delay_show(struct device *dev,
795 struct device_attribute *attr, char *buf)
797 struct ufs_hba *hba = dev_get_drvdata(dev);
799 return snprintf(buf, PAGE_SIZE, "%lu\n", hba->clk_gating.delay_ms);
802 static ssize_t ufshcd_clkgate_delay_store(struct device *dev,
803 struct device_attribute *attr, const char *buf, size_t count)
805 struct ufs_hba *hba = dev_get_drvdata(dev);
806 unsigned long flags, value;
808 if (kstrtoul(buf, 0, &value))
811 spin_lock_irqsave(hba->host->host_lock, flags);
812 hba->clk_gating.delay_ms = value;
813 spin_unlock_irqrestore(hba->host->host_lock, flags);
817 static void ufshcd_init_clk_gating(struct ufs_hba *hba)
819 if (!ufshcd_is_clkgating_allowed(hba))
822 hba->clk_gating.delay_ms = 150;
823 INIT_DELAYED_WORK(&hba->clk_gating.gate_work, ufshcd_gate_work);
824 INIT_WORK(&hba->clk_gating.ungate_work, ufshcd_ungate_work);
826 hba->clk_gating.delay_attr.show = ufshcd_clkgate_delay_show;
827 hba->clk_gating.delay_attr.store = ufshcd_clkgate_delay_store;
828 sysfs_attr_init(&hba->clk_gating.delay_attr.attr);
829 hba->clk_gating.delay_attr.attr.name = "clkgate_delay_ms";
830 hba->clk_gating.delay_attr.attr.mode = S_IRUGO | S_IWUSR;
831 if (device_create_file(hba->dev, &hba->clk_gating.delay_attr))
832 dev_err(hba->dev, "Failed to create sysfs for clkgate_delay\n");
835 static void ufshcd_exit_clk_gating(struct ufs_hba *hba)
837 if (!ufshcd_is_clkgating_allowed(hba))
839 device_remove_file(hba->dev, &hba->clk_gating.delay_attr);
840 cancel_work_sync(&hba->clk_gating.ungate_work);
841 cancel_delayed_work_sync(&hba->clk_gating.gate_work);
844 /* Must be called with host lock acquired */
845 static void ufshcd_clk_scaling_start_busy(struct ufs_hba *hba)
847 if (!ufshcd_is_clkscaling_enabled(hba))
850 if (!hba->clk_scaling.is_busy_started) {
851 hba->clk_scaling.busy_start_t = ktime_get();
852 hba->clk_scaling.is_busy_started = true;
856 static void ufshcd_clk_scaling_update_busy(struct ufs_hba *hba)
858 struct ufs_clk_scaling *scaling = &hba->clk_scaling;
860 if (!ufshcd_is_clkscaling_enabled(hba))
863 if (!hba->outstanding_reqs && scaling->is_busy_started) {
864 scaling->tot_busy_t += ktime_to_us(ktime_sub(ktime_get(),
865 scaling->busy_start_t));
866 scaling->busy_start_t = ktime_set(0, 0);
867 scaling->is_busy_started = false;
871 * ufshcd_send_command - Send SCSI or device management commands
872 * @hba: per adapter instance
873 * @task_tag: Task tag of the command
876 void ufshcd_send_command(struct ufs_hba *hba, unsigned int task_tag)
878 ufshcd_clk_scaling_start_busy(hba);
879 __set_bit(task_tag, &hba->outstanding_reqs);
880 ufshcd_writel(hba, 1 << task_tag, REG_UTP_TRANSFER_REQ_DOOR_BELL);
884 * ufshcd_copy_sense_data - Copy sense data in case of check condition
885 * @lrb - pointer to local reference block
887 static inline void ufshcd_copy_sense_data(struct ufshcd_lrb *lrbp)
890 if (lrbp->sense_buffer &&
891 ufshcd_get_rsp_upiu_data_seg_len(lrbp->ucd_rsp_ptr)) {
894 len = be16_to_cpu(lrbp->ucd_rsp_ptr->sr.sense_data_len);
895 len_to_copy = min_t(int, RESPONSE_UPIU_SENSE_DATA_LENGTH, len);
897 memcpy(lrbp->sense_buffer,
898 lrbp->ucd_rsp_ptr->sr.sense_data,
899 min_t(int, len_to_copy, SCSI_SENSE_BUFFERSIZE));
904 * ufshcd_copy_query_response() - Copy the Query Response and the data
906 * @hba: per adapter instance
907 * @lrb - pointer to local reference block
910 int ufshcd_copy_query_response(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
912 struct ufs_query_res *query_res = &hba->dev_cmd.query.response;
914 memcpy(&query_res->upiu_res, &lrbp->ucd_rsp_ptr->qr, QUERY_OSF_SIZE);
916 /* Get the descriptor */
917 if (lrbp->ucd_rsp_ptr->qr.opcode == UPIU_QUERY_OPCODE_READ_DESC) {
918 u8 *descp = (u8 *)lrbp->ucd_rsp_ptr +
919 GENERAL_UPIU_REQUEST_SIZE;
923 /* data segment length */
924 resp_len = be32_to_cpu(lrbp->ucd_rsp_ptr->header.dword_2) &
925 MASK_QUERY_DATA_SEG_LEN;
926 buf_len = be16_to_cpu(
927 hba->dev_cmd.query.request.upiu_req.length);
928 if (likely(buf_len >= resp_len)) {
929 memcpy(hba->dev_cmd.query.descriptor, descp, resp_len);
932 "%s: Response size is bigger than buffer",
942 * ufshcd_hba_capabilities - Read controller capabilities
943 * @hba: per adapter instance
945 static inline void ufshcd_hba_capabilities(struct ufs_hba *hba)
947 hba->capabilities = ufshcd_readl(hba, REG_CONTROLLER_CAPABILITIES);
949 /* nutrs and nutmrs are 0 based values */
950 hba->nutrs = (hba->capabilities & MASK_TRANSFER_REQUESTS_SLOTS) + 1;
952 ((hba->capabilities & MASK_TASK_MANAGEMENT_REQUEST_SLOTS) >> 16) + 1;
956 * ufshcd_ready_for_uic_cmd - Check if controller is ready
957 * to accept UIC commands
958 * @hba: per adapter instance
959 * Return true on success, else false
961 static inline bool ufshcd_ready_for_uic_cmd(struct ufs_hba *hba)
963 if (ufshcd_readl(hba, REG_CONTROLLER_STATUS) & UIC_COMMAND_READY)
970 * ufshcd_get_upmcrs - Get the power mode change request status
971 * @hba: Pointer to adapter instance
973 * This function gets the UPMCRS field of HCS register
974 * Returns value of UPMCRS field
976 static inline u8 ufshcd_get_upmcrs(struct ufs_hba *hba)
978 return (ufshcd_readl(hba, REG_CONTROLLER_STATUS) >> 8) & 0x7;
982 * ufshcd_dispatch_uic_cmd - Dispatch UIC commands to unipro layers
983 * @hba: per adapter instance
984 * @uic_cmd: UIC command
986 * Mutex must be held.
989 ufshcd_dispatch_uic_cmd(struct ufs_hba *hba, struct uic_command *uic_cmd)
991 WARN_ON(hba->active_uic_cmd);
993 hba->active_uic_cmd = uic_cmd;
996 ufshcd_writel(hba, uic_cmd->argument1, REG_UIC_COMMAND_ARG_1);
997 ufshcd_writel(hba, uic_cmd->argument2, REG_UIC_COMMAND_ARG_2);
998 ufshcd_writel(hba, uic_cmd->argument3, REG_UIC_COMMAND_ARG_3);
1001 ufshcd_writel(hba, uic_cmd->command & COMMAND_OPCODE_MASK,
1006 * ufshcd_wait_for_uic_cmd - Wait complectioin of UIC command
1007 * @hba: per adapter instance
1008 * @uic_command: UIC command
1010 * Must be called with mutex held.
1011 * Returns 0 only if success.
1014 ufshcd_wait_for_uic_cmd(struct ufs_hba *hba, struct uic_command *uic_cmd)
1017 unsigned long flags;
1019 if (wait_for_completion_timeout(&uic_cmd->done,
1020 msecs_to_jiffies(UIC_CMD_TIMEOUT)))
1021 ret = uic_cmd->argument2 & MASK_UIC_COMMAND_RESULT;
1025 spin_lock_irqsave(hba->host->host_lock, flags);
1026 hba->active_uic_cmd = NULL;
1027 spin_unlock_irqrestore(hba->host->host_lock, flags);
1033 * __ufshcd_send_uic_cmd - Send UIC commands and retrieve the result
1034 * @hba: per adapter instance
1035 * @uic_cmd: UIC command
1036 * @completion: initialize the completion only if this is set to true
1038 * Identical to ufshcd_send_uic_cmd() expect mutex. Must be called
1039 * with mutex held and host_lock locked.
1040 * Returns 0 only if success.
1043 __ufshcd_send_uic_cmd(struct ufs_hba *hba, struct uic_command *uic_cmd,
1046 if (!ufshcd_ready_for_uic_cmd(hba)) {
1048 "Controller not ready to accept UIC commands\n");
1053 init_completion(&uic_cmd->done);
1055 ufshcd_dispatch_uic_cmd(hba, uic_cmd);
1061 * ufshcd_send_uic_cmd - Send UIC commands and retrieve the result
1062 * @hba: per adapter instance
1063 * @uic_cmd: UIC command
1065 * Returns 0 only if success.
1068 ufshcd_send_uic_cmd(struct ufs_hba *hba, struct uic_command *uic_cmd)
1071 unsigned long flags;
1073 ufshcd_hold(hba, false);
1074 mutex_lock(&hba->uic_cmd_mutex);
1075 ufshcd_add_delay_before_dme_cmd(hba);
1077 spin_lock_irqsave(hba->host->host_lock, flags);
1078 ret = __ufshcd_send_uic_cmd(hba, uic_cmd, true);
1079 spin_unlock_irqrestore(hba->host->host_lock, flags);
1081 ret = ufshcd_wait_for_uic_cmd(hba, uic_cmd);
1083 mutex_unlock(&hba->uic_cmd_mutex);
1085 ufshcd_release(hba);
1090 * ufshcd_map_sg - Map scatter-gather list to prdt
1091 * @lrbp - pointer to local reference block
1093 * Returns 0 in case of success, non-zero value in case of failure
1095 static int ufshcd_map_sg(struct ufshcd_lrb *lrbp)
1097 struct ufshcd_sg_entry *prd_table;
1098 struct scatterlist *sg;
1099 struct scsi_cmnd *cmd;
1104 sg_segments = scsi_dma_map(cmd);
1105 if (sg_segments < 0)
1109 lrbp->utr_descriptor_ptr->prd_table_length =
1110 cpu_to_le16((u16) (sg_segments));
1112 prd_table = (struct ufshcd_sg_entry *)lrbp->ucd_prdt_ptr;
1114 scsi_for_each_sg(cmd, sg, sg_segments, i) {
1116 cpu_to_le32(((u32) sg_dma_len(sg))-1);
1117 prd_table[i].base_addr =
1118 cpu_to_le32(lower_32_bits(sg->dma_address));
1119 prd_table[i].upper_addr =
1120 cpu_to_le32(upper_32_bits(sg->dma_address));
1121 prd_table[i].reserved = 0;
1124 lrbp->utr_descriptor_ptr->prd_table_length = 0;
1131 * ufshcd_enable_intr - enable interrupts
1132 * @hba: per adapter instance
1133 * @intrs: interrupt bits
1135 static void ufshcd_enable_intr(struct ufs_hba *hba, u32 intrs)
1137 u32 set = ufshcd_readl(hba, REG_INTERRUPT_ENABLE);
1139 if (hba->ufs_version == UFSHCI_VERSION_10) {
1141 rw = set & INTERRUPT_MASK_RW_VER_10;
1142 set = rw | ((set ^ intrs) & intrs);
1147 ufshcd_writel(hba, set, REG_INTERRUPT_ENABLE);
1151 * ufshcd_disable_intr - disable interrupts
1152 * @hba: per adapter instance
1153 * @intrs: interrupt bits
1155 static void ufshcd_disable_intr(struct ufs_hba *hba, u32 intrs)
1157 u32 set = ufshcd_readl(hba, REG_INTERRUPT_ENABLE);
1159 if (hba->ufs_version == UFSHCI_VERSION_10) {
1161 rw = (set & INTERRUPT_MASK_RW_VER_10) &
1162 ~(intrs & INTERRUPT_MASK_RW_VER_10);
1163 set = rw | ((set & intrs) & ~INTERRUPT_MASK_RW_VER_10);
1169 ufshcd_writel(hba, set, REG_INTERRUPT_ENABLE);
1173 * ufshcd_prepare_req_desc_hdr() - Fills the requests header
1174 * descriptor according to request
1175 * @lrbp: pointer to local reference block
1176 * @upiu_flags: flags required in the header
1177 * @cmd_dir: requests data direction
1179 static void ufshcd_prepare_req_desc_hdr(struct ufshcd_lrb *lrbp,
1180 u32 *upiu_flags, enum dma_data_direction cmd_dir)
1182 struct utp_transfer_req_desc *req_desc = lrbp->utr_descriptor_ptr;
1186 if (cmd_dir == DMA_FROM_DEVICE) {
1187 data_direction = UTP_DEVICE_TO_HOST;
1188 *upiu_flags = UPIU_CMD_FLAGS_READ;
1189 } else if (cmd_dir == DMA_TO_DEVICE) {
1190 data_direction = UTP_HOST_TO_DEVICE;
1191 *upiu_flags = UPIU_CMD_FLAGS_WRITE;
1193 data_direction = UTP_NO_DATA_TRANSFER;
1194 *upiu_flags = UPIU_CMD_FLAGS_NONE;
1197 dword_0 = data_direction | (lrbp->command_type
1198 << UPIU_COMMAND_TYPE_OFFSET);
1200 dword_0 |= UTP_REQ_DESC_INT_CMD;
1202 /* Transfer request descriptor header fields */
1203 req_desc->header.dword_0 = cpu_to_le32(dword_0);
1204 /* dword_1 is reserved, hence it is set to 0 */
1205 req_desc->header.dword_1 = 0;
1207 * assigning invalid value for command status. Controller
1208 * updates OCS on command completion, with the command
1211 req_desc->header.dword_2 =
1212 cpu_to_le32(OCS_INVALID_COMMAND_STATUS);
1213 /* dword_3 is reserved, hence it is set to 0 */
1214 req_desc->header.dword_3 = 0;
1216 req_desc->prd_table_length = 0;
1220 * ufshcd_prepare_utp_scsi_cmd_upiu() - fills the utp_transfer_req_desc,
1222 * @lrbp - local reference block pointer
1223 * @upiu_flags - flags
1226 void ufshcd_prepare_utp_scsi_cmd_upiu(struct ufshcd_lrb *lrbp, u32 upiu_flags)
1228 struct utp_upiu_req *ucd_req_ptr = lrbp->ucd_req_ptr;
1229 unsigned short cdb_len;
1231 /* command descriptor fields */
1232 ucd_req_ptr->header.dword_0 = UPIU_HEADER_DWORD(
1233 UPIU_TRANSACTION_COMMAND, upiu_flags,
1234 lrbp->lun, lrbp->task_tag);
1235 ucd_req_ptr->header.dword_1 = UPIU_HEADER_DWORD(
1236 UPIU_COMMAND_SET_TYPE_SCSI, 0, 0, 0);
1238 /* Total EHS length and Data segment length will be zero */
1239 ucd_req_ptr->header.dword_2 = 0;
1241 ucd_req_ptr->sc.exp_data_transfer_len =
1242 cpu_to_be32(lrbp->cmd->sdb.length);
1244 cdb_len = min_t(unsigned short, lrbp->cmd->cmd_len, MAX_CDB_SIZE);
1245 memset(ucd_req_ptr->sc.cdb, 0, MAX_CDB_SIZE);
1246 memcpy(ucd_req_ptr->sc.cdb, lrbp->cmd->cmnd, cdb_len);
1248 memset(lrbp->ucd_rsp_ptr, 0, sizeof(struct utp_upiu_rsp));
1252 * ufshcd_prepare_utp_query_req_upiu() - fills the utp_transfer_req_desc,
1255 * @lrbp: local reference block pointer
1256 * @upiu_flags: flags
1258 static void ufshcd_prepare_utp_query_req_upiu(struct ufs_hba *hba,
1259 struct ufshcd_lrb *lrbp, u32 upiu_flags)
1261 struct utp_upiu_req *ucd_req_ptr = lrbp->ucd_req_ptr;
1262 struct ufs_query *query = &hba->dev_cmd.query;
1263 u16 len = be16_to_cpu(query->request.upiu_req.length);
1264 u8 *descp = (u8 *)lrbp->ucd_req_ptr + GENERAL_UPIU_REQUEST_SIZE;
1266 /* Query request header */
1267 ucd_req_ptr->header.dword_0 = UPIU_HEADER_DWORD(
1268 UPIU_TRANSACTION_QUERY_REQ, upiu_flags,
1269 lrbp->lun, lrbp->task_tag);
1270 ucd_req_ptr->header.dword_1 = UPIU_HEADER_DWORD(
1271 0, query->request.query_func, 0, 0);
1273 /* Data segment length only need for WRITE_DESC */
1274 if (query->request.upiu_req.opcode == UPIU_QUERY_OPCODE_WRITE_DESC)
1275 ucd_req_ptr->header.dword_2 =
1276 UPIU_HEADER_DWORD(0, 0, (len >> 8), (u8)len);
1278 ucd_req_ptr->header.dword_2 = 0;
1280 /* Copy the Query Request buffer as is */
1281 memcpy(&ucd_req_ptr->qr, &query->request.upiu_req,
1284 /* Copy the Descriptor */
1285 if (query->request.upiu_req.opcode == UPIU_QUERY_OPCODE_WRITE_DESC)
1286 memcpy(descp, query->descriptor, len);
1288 memset(lrbp->ucd_rsp_ptr, 0, sizeof(struct utp_upiu_rsp));
1291 static inline void ufshcd_prepare_utp_nop_upiu(struct ufshcd_lrb *lrbp)
1293 struct utp_upiu_req *ucd_req_ptr = lrbp->ucd_req_ptr;
1295 memset(ucd_req_ptr, 0, sizeof(struct utp_upiu_req));
1297 /* command descriptor fields */
1298 ucd_req_ptr->header.dword_0 =
1300 UPIU_TRANSACTION_NOP_OUT, 0, 0, lrbp->task_tag);
1301 /* clear rest of the fields of basic header */
1302 ucd_req_ptr->header.dword_1 = 0;
1303 ucd_req_ptr->header.dword_2 = 0;
1305 memset(lrbp->ucd_rsp_ptr, 0, sizeof(struct utp_upiu_rsp));
1309 * ufshcd_comp_devman_upiu - UFS Protocol Information Unit(UPIU)
1310 * for Device Management Purposes
1311 * @hba - per adapter instance
1312 * @lrb - pointer to local reference block
1314 static int ufshcd_comp_devman_upiu(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
1319 if (hba->ufs_version == UFSHCI_VERSION_20)
1320 lrbp->command_type = UTP_CMD_TYPE_UFS_STORAGE;
1322 lrbp->command_type = UTP_CMD_TYPE_DEV_MANAGE;
1324 ufshcd_prepare_req_desc_hdr(lrbp, &upiu_flags, DMA_NONE);
1325 if (hba->dev_cmd.type == DEV_CMD_TYPE_QUERY)
1326 ufshcd_prepare_utp_query_req_upiu(hba, lrbp, upiu_flags);
1327 else if (hba->dev_cmd.type == DEV_CMD_TYPE_NOP)
1328 ufshcd_prepare_utp_nop_upiu(lrbp);
1336 * ufshcd_comp_scsi_upiu - UFS Protocol Information Unit(UPIU)
1338 * @hba - per adapter instance
1339 * @lrb - pointer to local reference block
1341 static int ufshcd_comp_scsi_upiu(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
1346 if (hba->ufs_version == UFSHCI_VERSION_20)
1347 lrbp->command_type = UTP_CMD_TYPE_UFS_STORAGE;
1349 lrbp->command_type = UTP_CMD_TYPE_SCSI;
1351 if (likely(lrbp->cmd)) {
1352 ufshcd_prepare_req_desc_hdr(lrbp, &upiu_flags,
1353 lrbp->cmd->sc_data_direction);
1354 ufshcd_prepare_utp_scsi_cmd_upiu(lrbp, upiu_flags);
1363 * ufshcd_scsi_to_upiu_lun - maps scsi LUN to UPIU LUN
1364 * @scsi_lun: scsi LUN id
1366 * Returns UPIU LUN id
1368 static inline u8 ufshcd_scsi_to_upiu_lun(unsigned int scsi_lun)
1370 if (scsi_is_wlun(scsi_lun))
1371 return (scsi_lun & UFS_UPIU_MAX_UNIT_NUM_ID)
1374 return scsi_lun & UFS_UPIU_MAX_UNIT_NUM_ID;
1378 * ufshcd_upiu_wlun_to_scsi_wlun - maps UPIU W-LUN id to SCSI W-LUN ID
1379 * @scsi_lun: UPIU W-LUN id
1381 * Returns SCSI W-LUN id
1383 static inline u16 ufshcd_upiu_wlun_to_scsi_wlun(u8 upiu_wlun_id)
1385 return (upiu_wlun_id & ~UFS_UPIU_WLUN_ID) | SCSI_W_LUN_BASE;
1389 * ufshcd_queuecommand - main entry point for SCSI requests
1390 * @cmd: command from SCSI Midlayer
1391 * @done: call back function
1393 * Returns 0 for success, non-zero in case of failure
1395 static int ufshcd_queuecommand(struct Scsi_Host *host, struct scsi_cmnd *cmd)
1397 struct ufshcd_lrb *lrbp;
1398 struct ufs_hba *hba;
1399 unsigned long flags;
1403 hba = shost_priv(host);
1405 tag = cmd->request->tag;
1406 if (!ufshcd_valid_tag(hba, tag)) {
1408 "%s: invalid command tag %d: cmd=0x%p, cmd->request=0x%p",
1409 __func__, tag, cmd, cmd->request);
1413 spin_lock_irqsave(hba->host->host_lock, flags);
1414 switch (hba->ufshcd_state) {
1415 case UFSHCD_STATE_OPERATIONAL:
1417 case UFSHCD_STATE_RESET:
1418 err = SCSI_MLQUEUE_HOST_BUSY;
1420 case UFSHCD_STATE_ERROR:
1421 set_host_byte(cmd, DID_ERROR);
1422 cmd->scsi_done(cmd);
1425 dev_WARN_ONCE(hba->dev, 1, "%s: invalid state %d\n",
1426 __func__, hba->ufshcd_state);
1427 set_host_byte(cmd, DID_BAD_TARGET);
1428 cmd->scsi_done(cmd);
1432 /* if error handling is in progress, don't issue commands */
1433 if (ufshcd_eh_in_progress(hba)) {
1434 set_host_byte(cmd, DID_ERROR);
1435 cmd->scsi_done(cmd);
1438 spin_unlock_irqrestore(hba->host->host_lock, flags);
1440 /* acquire the tag to make sure device cmds don't use it */
1441 if (test_and_set_bit_lock(tag, &hba->lrb_in_use)) {
1443 * Dev manage command in progress, requeue the command.
1444 * Requeuing the command helps in cases where the request *may*
1445 * find different tag instead of waiting for dev manage command
1448 err = SCSI_MLQUEUE_HOST_BUSY;
1452 err = ufshcd_hold(hba, true);
1454 err = SCSI_MLQUEUE_HOST_BUSY;
1455 clear_bit_unlock(tag, &hba->lrb_in_use);
1458 WARN_ON(hba->clk_gating.state != CLKS_ON);
1460 lrbp = &hba->lrb[tag];
1464 lrbp->sense_bufflen = SCSI_SENSE_BUFFERSIZE;
1465 lrbp->sense_buffer = cmd->sense_buffer;
1466 lrbp->task_tag = tag;
1467 lrbp->lun = ufshcd_scsi_to_upiu_lun(cmd->device->lun);
1468 lrbp->intr_cmd = !ufshcd_is_intr_aggr_allowed(hba) ? true : false;
1470 ufshcd_comp_scsi_upiu(hba, lrbp);
1472 err = ufshcd_map_sg(lrbp);
1475 clear_bit_unlock(tag, &hba->lrb_in_use);
1479 /* issue command to the controller */
1480 spin_lock_irqsave(hba->host->host_lock, flags);
1481 ufshcd_send_command(hba, tag);
1483 spin_unlock_irqrestore(hba->host->host_lock, flags);
1488 static int ufshcd_compose_dev_cmd(struct ufs_hba *hba,
1489 struct ufshcd_lrb *lrbp, enum dev_cmd_type cmd_type, int tag)
1492 lrbp->sense_bufflen = 0;
1493 lrbp->sense_buffer = NULL;
1494 lrbp->task_tag = tag;
1495 lrbp->lun = 0; /* device management cmd is not specific to any LUN */
1496 lrbp->intr_cmd = true; /* No interrupt aggregation */
1497 hba->dev_cmd.type = cmd_type;
1499 return ufshcd_comp_devman_upiu(hba, lrbp);
1503 ufshcd_clear_cmd(struct ufs_hba *hba, int tag)
1506 unsigned long flags;
1507 u32 mask = 1 << tag;
1509 /* clear outstanding transaction before retry */
1510 spin_lock_irqsave(hba->host->host_lock, flags);
1511 ufshcd_utrl_clear(hba, tag);
1512 spin_unlock_irqrestore(hba->host->host_lock, flags);
1515 * wait for for h/w to clear corresponding bit in door-bell.
1516 * max. wait is 1 sec.
1518 err = ufshcd_wait_for_register(hba,
1519 REG_UTP_TRANSFER_REQ_DOOR_BELL,
1520 mask, ~mask, 1000, 1000, true);
1526 ufshcd_check_query_response(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
1528 struct ufs_query_res *query_res = &hba->dev_cmd.query.response;
1530 /* Get the UPIU response */
1531 query_res->response = ufshcd_get_rsp_upiu_result(lrbp->ucd_rsp_ptr) >>
1532 UPIU_RSP_CODE_OFFSET;
1533 return query_res->response;
1537 * ufshcd_dev_cmd_completion() - handles device management command responses
1538 * @hba: per adapter instance
1539 * @lrbp: pointer to local reference block
1542 ufshcd_dev_cmd_completion(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
1547 resp = ufshcd_get_req_rsp(lrbp->ucd_rsp_ptr);
1550 case UPIU_TRANSACTION_NOP_IN:
1551 if (hba->dev_cmd.type != DEV_CMD_TYPE_NOP) {
1553 dev_err(hba->dev, "%s: unexpected response %x\n",
1557 case UPIU_TRANSACTION_QUERY_RSP:
1558 err = ufshcd_check_query_response(hba, lrbp);
1560 err = ufshcd_copy_query_response(hba, lrbp);
1562 case UPIU_TRANSACTION_REJECT_UPIU:
1563 /* TODO: handle Reject UPIU Response */
1565 dev_err(hba->dev, "%s: Reject UPIU not fully implemented\n",
1570 dev_err(hba->dev, "%s: Invalid device management cmd response: %x\n",
1578 static int ufshcd_wait_for_dev_cmd(struct ufs_hba *hba,
1579 struct ufshcd_lrb *lrbp, int max_timeout)
1582 unsigned long time_left;
1583 unsigned long flags;
1585 time_left = wait_for_completion_timeout(hba->dev_cmd.complete,
1586 msecs_to_jiffies(max_timeout));
1588 spin_lock_irqsave(hba->host->host_lock, flags);
1589 hba->dev_cmd.complete = NULL;
1590 if (likely(time_left)) {
1591 err = ufshcd_get_tr_ocs(lrbp);
1593 err = ufshcd_dev_cmd_completion(hba, lrbp);
1595 spin_unlock_irqrestore(hba->host->host_lock, flags);
1599 dev_dbg(hba->dev, "%s: dev_cmd request timedout, tag %d\n",
1600 __func__, lrbp->task_tag);
1601 if (!ufshcd_clear_cmd(hba, lrbp->task_tag))
1602 /* successfully cleared the command, retry if needed */
1605 * in case of an error, after clearing the doorbell,
1606 * we also need to clear the outstanding_request
1609 ufshcd_outstanding_req_clear(hba, lrbp->task_tag);
1616 * ufshcd_get_dev_cmd_tag - Get device management command tag
1617 * @hba: per-adapter instance
1618 * @tag: pointer to variable with available slot value
1620 * Get a free slot and lock it until device management command
1623 * Returns false if free slot is unavailable for locking, else
1624 * return true with tag value in @tag.
1626 static bool ufshcd_get_dev_cmd_tag(struct ufs_hba *hba, int *tag_out)
1636 tmp = ~hba->lrb_in_use;
1637 tag = find_last_bit(&tmp, hba->nutrs);
1638 if (tag >= hba->nutrs)
1640 } while (test_and_set_bit_lock(tag, &hba->lrb_in_use));
1648 static inline void ufshcd_put_dev_cmd_tag(struct ufs_hba *hba, int tag)
1650 clear_bit_unlock(tag, &hba->lrb_in_use);
1654 * ufshcd_exec_dev_cmd - API for sending device management requests
1656 * @cmd_type - specifies the type (NOP, Query...)
1657 * @timeout - time in seconds
1659 * NOTE: Since there is only one available tag for device management commands,
1660 * it is expected you hold the hba->dev_cmd.lock mutex.
1662 static int ufshcd_exec_dev_cmd(struct ufs_hba *hba,
1663 enum dev_cmd_type cmd_type, int timeout)
1665 struct ufshcd_lrb *lrbp;
1668 struct completion wait;
1669 unsigned long flags;
1672 * Get free slot, sleep if slots are unavailable.
1673 * Even though we use wait_event() which sleeps indefinitely,
1674 * the maximum wait time is bounded by SCSI request timeout.
1676 wait_event(hba->dev_cmd.tag_wq, ufshcd_get_dev_cmd_tag(hba, &tag));
1678 init_completion(&wait);
1679 lrbp = &hba->lrb[tag];
1681 err = ufshcd_compose_dev_cmd(hba, lrbp, cmd_type, tag);
1685 hba->dev_cmd.complete = &wait;
1687 /* Make sure descriptors are ready before ringing the doorbell */
1689 spin_lock_irqsave(hba->host->host_lock, flags);
1690 ufshcd_send_command(hba, tag);
1691 spin_unlock_irqrestore(hba->host->host_lock, flags);
1693 err = ufshcd_wait_for_dev_cmd(hba, lrbp, timeout);
1696 ufshcd_put_dev_cmd_tag(hba, tag);
1697 wake_up(&hba->dev_cmd.tag_wq);
1702 * ufshcd_init_query() - init the query response and request parameters
1703 * @hba: per-adapter instance
1704 * @request: address of the request pointer to be initialized
1705 * @response: address of the response pointer to be initialized
1706 * @opcode: operation to perform
1707 * @idn: flag idn to access
1708 * @index: LU number to access
1709 * @selector: query/flag/descriptor further identification
1711 static inline void ufshcd_init_query(struct ufs_hba *hba,
1712 struct ufs_query_req **request, struct ufs_query_res **response,
1713 enum query_opcode opcode, u8 idn, u8 index, u8 selector)
1715 *request = &hba->dev_cmd.query.request;
1716 *response = &hba->dev_cmd.query.response;
1717 memset(*request, 0, sizeof(struct ufs_query_req));
1718 memset(*response, 0, sizeof(struct ufs_query_res));
1719 (*request)->upiu_req.opcode = opcode;
1720 (*request)->upiu_req.idn = idn;
1721 (*request)->upiu_req.index = index;
1722 (*request)->upiu_req.selector = selector;
1725 static int ufshcd_query_flag_retry(struct ufs_hba *hba,
1726 enum query_opcode opcode, enum flag_idn idn, bool *flag_res)
1731 for (retries = 0; retries < QUERY_REQ_RETRIES; retries++) {
1732 ret = ufshcd_query_flag(hba, opcode, idn, flag_res);
1735 "%s: failed with error %d, retries %d\n",
1736 __func__, ret, retries);
1743 "%s: query attribute, opcode %d, idn %d, failed with error %d after %d retires\n",
1744 __func__, opcode, idn, ret, retries);
1749 * ufshcd_query_flag() - API function for sending flag query requests
1750 * hba: per-adapter instance
1751 * query_opcode: flag query to perform
1752 * idn: flag idn to access
1753 * flag_res: the flag value after the query request completes
1755 * Returns 0 for success, non-zero in case of failure
1757 int ufshcd_query_flag(struct ufs_hba *hba, enum query_opcode opcode,
1758 enum flag_idn idn, bool *flag_res)
1760 struct ufs_query_req *request = NULL;
1761 struct ufs_query_res *response = NULL;
1762 int err, index = 0, selector = 0;
1763 int timeout = QUERY_REQ_TIMEOUT;
1767 ufshcd_hold(hba, false);
1768 mutex_lock(&hba->dev_cmd.lock);
1769 ufshcd_init_query(hba, &request, &response, opcode, idn, index,
1773 case UPIU_QUERY_OPCODE_SET_FLAG:
1774 case UPIU_QUERY_OPCODE_CLEAR_FLAG:
1775 case UPIU_QUERY_OPCODE_TOGGLE_FLAG:
1776 request->query_func = UPIU_QUERY_FUNC_STANDARD_WRITE_REQUEST;
1778 case UPIU_QUERY_OPCODE_READ_FLAG:
1779 request->query_func = UPIU_QUERY_FUNC_STANDARD_READ_REQUEST;
1781 /* No dummy reads */
1782 dev_err(hba->dev, "%s: Invalid argument for read request\n",
1790 "%s: Expected query flag opcode but got = %d\n",
1796 if (idn == QUERY_FLAG_IDN_FDEVICEINIT)
1797 timeout = QUERY_FDEVICEINIT_REQ_TIMEOUT;
1799 err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_QUERY, timeout);
1803 "%s: Sending flag query for idn %d failed, err = %d\n",
1804 __func__, idn, err);
1809 *flag_res = (be32_to_cpu(response->upiu_res.value) &
1810 MASK_QUERY_UPIU_FLAG_LOC) & 0x1;
1813 mutex_unlock(&hba->dev_cmd.lock);
1814 ufshcd_release(hba);
1819 * ufshcd_query_attr - API function for sending attribute requests
1820 * hba: per-adapter instance
1821 * opcode: attribute opcode
1822 * idn: attribute idn to access
1823 * index: index field
1824 * selector: selector field
1825 * attr_val: the attribute value after the query request completes
1827 * Returns 0 for success, non-zero in case of failure
1829 static int ufshcd_query_attr(struct ufs_hba *hba, enum query_opcode opcode,
1830 enum attr_idn idn, u8 index, u8 selector, u32 *attr_val)
1832 struct ufs_query_req *request = NULL;
1833 struct ufs_query_res *response = NULL;
1838 ufshcd_hold(hba, false);
1840 dev_err(hba->dev, "%s: attribute value required for opcode 0x%x\n",
1846 mutex_lock(&hba->dev_cmd.lock);
1847 ufshcd_init_query(hba, &request, &response, opcode, idn, index,
1851 case UPIU_QUERY_OPCODE_WRITE_ATTR:
1852 request->query_func = UPIU_QUERY_FUNC_STANDARD_WRITE_REQUEST;
1853 request->upiu_req.value = cpu_to_be32(*attr_val);
1855 case UPIU_QUERY_OPCODE_READ_ATTR:
1856 request->query_func = UPIU_QUERY_FUNC_STANDARD_READ_REQUEST;
1859 dev_err(hba->dev, "%s: Expected query attr opcode but got = 0x%.2x\n",
1865 err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_QUERY, QUERY_REQ_TIMEOUT);
1868 dev_err(hba->dev, "%s: opcode 0x%.2x for idn %d failed, err = %d\n",
1869 __func__, opcode, idn, err);
1873 *attr_val = be32_to_cpu(response->upiu_res.value);
1876 mutex_unlock(&hba->dev_cmd.lock);
1878 ufshcd_release(hba);
1883 * ufshcd_query_attr_retry() - API function for sending query
1884 * attribute with retries
1885 * @hba: per-adapter instance
1886 * @opcode: attribute opcode
1887 * @idn: attribute idn to access
1888 * @index: index field
1889 * @selector: selector field
1890 * @attr_val: the attribute value after the query request
1893 * Returns 0 for success, non-zero in case of failure
1895 static int ufshcd_query_attr_retry(struct ufs_hba *hba,
1896 enum query_opcode opcode, enum attr_idn idn, u8 index, u8 selector,
1902 for (retries = QUERY_REQ_RETRIES; retries > 0; retries--) {
1903 ret = ufshcd_query_attr(hba, opcode, idn, index,
1904 selector, attr_val);
1906 dev_dbg(hba->dev, "%s: failed with error %d, retries %d\n",
1907 __func__, ret, retries);
1914 "%s: query attribute, idn %d, failed with error %d after %d retires\n",
1915 __func__, idn, ret, QUERY_REQ_RETRIES);
1919 static int __ufshcd_query_descriptor(struct ufs_hba *hba,
1920 enum query_opcode opcode, enum desc_idn idn, u8 index,
1921 u8 selector, u8 *desc_buf, int *buf_len)
1923 struct ufs_query_req *request = NULL;
1924 struct ufs_query_res *response = NULL;
1929 ufshcd_hold(hba, false);
1931 dev_err(hba->dev, "%s: descriptor buffer required for opcode 0x%x\n",
1937 if (*buf_len <= QUERY_DESC_MIN_SIZE || *buf_len > QUERY_DESC_MAX_SIZE) {
1938 dev_err(hba->dev, "%s: descriptor buffer size (%d) is out of range\n",
1939 __func__, *buf_len);
1944 mutex_lock(&hba->dev_cmd.lock);
1945 ufshcd_init_query(hba, &request, &response, opcode, idn, index,
1947 hba->dev_cmd.query.descriptor = desc_buf;
1948 request->upiu_req.length = cpu_to_be16(*buf_len);
1951 case UPIU_QUERY_OPCODE_WRITE_DESC:
1952 request->query_func = UPIU_QUERY_FUNC_STANDARD_WRITE_REQUEST;
1954 case UPIU_QUERY_OPCODE_READ_DESC:
1955 request->query_func = UPIU_QUERY_FUNC_STANDARD_READ_REQUEST;
1959 "%s: Expected query descriptor opcode but got = 0x%.2x\n",
1965 err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_QUERY, QUERY_REQ_TIMEOUT);
1968 dev_err(hba->dev, "%s: opcode 0x%.2x for idn %d failed, err = %d\n",
1969 __func__, opcode, idn, err);
1973 hba->dev_cmd.query.descriptor = NULL;
1974 *buf_len = be16_to_cpu(response->upiu_res.length);
1977 mutex_unlock(&hba->dev_cmd.lock);
1979 ufshcd_release(hba);
1984 * ufshcd_query_descriptor_retry - API function for sending descriptor
1986 * hba: per-adapter instance
1987 * opcode: attribute opcode
1988 * idn: attribute idn to access
1989 * index: index field
1990 * selector: selector field
1991 * desc_buf: the buffer that contains the descriptor
1992 * buf_len: length parameter passed to the device
1994 * Returns 0 for success, non-zero in case of failure.
1995 * The buf_len parameter will contain, on return, the length parameter
1996 * received on the response.
1998 int ufshcd_query_descriptor_retry(struct ufs_hba *hba,
1999 enum query_opcode opcode, enum desc_idn idn, u8 index,
2000 u8 selector, u8 *desc_buf, int *buf_len)
2005 for (retries = QUERY_REQ_RETRIES; retries > 0; retries--) {
2006 err = __ufshcd_query_descriptor(hba, opcode, idn, index,
2007 selector, desc_buf, buf_len);
2008 if (!err || err == -EINVAL)
2014 EXPORT_SYMBOL(ufshcd_query_descriptor_retry);
2017 * ufshcd_read_desc_param - read the specified descriptor parameter
2018 * @hba: Pointer to adapter instance
2019 * @desc_id: descriptor idn value
2020 * @desc_index: descriptor index
2021 * @param_offset: offset of the parameter to read
2022 * @param_read_buf: pointer to buffer where parameter would be read
2023 * @param_size: sizeof(param_read_buf)
2025 * Return 0 in case of success, non-zero otherwise
2027 static int ufshcd_read_desc_param(struct ufs_hba *hba,
2028 enum desc_idn desc_id,
2037 bool is_kmalloc = true;
2040 if (desc_id >= QUERY_DESC_IDN_MAX)
2043 buff_len = ufs_query_desc_max_size[desc_id];
2044 if ((param_offset + param_size) > buff_len)
2047 if (!param_offset && (param_size == buff_len)) {
2048 /* memory space already available to hold full descriptor */
2049 desc_buf = param_read_buf;
2052 /* allocate memory to hold full descriptor */
2053 desc_buf = kmalloc(buff_len, GFP_KERNEL);
2058 ret = ufshcd_query_descriptor_retry(hba, UPIU_QUERY_OPCODE_READ_DESC,
2059 desc_id, desc_index, 0, desc_buf,
2062 if (ret || (buff_len < ufs_query_desc_max_size[desc_id]) ||
2063 (desc_buf[QUERY_DESC_LENGTH_OFFSET] !=
2064 ufs_query_desc_max_size[desc_id])
2065 || (desc_buf[QUERY_DESC_DESC_TYPE_OFFSET] != desc_id)) {
2066 dev_err(hba->dev, "%s: Failed reading descriptor. desc_id %d param_offset %d buff_len %d ret %d",
2067 __func__, desc_id, param_offset, buff_len, ret);
2075 memcpy(param_read_buf, &desc_buf[param_offset], param_size);
2082 static inline int ufshcd_read_desc(struct ufs_hba *hba,
2083 enum desc_idn desc_id,
2088 return ufshcd_read_desc_param(hba, desc_id, desc_index, 0, buf, size);
2091 static inline int ufshcd_read_power_desc(struct ufs_hba *hba,
2095 return ufshcd_read_desc(hba, QUERY_DESC_IDN_POWER, 0, buf, size);
2098 int ufshcd_read_device_desc(struct ufs_hba *hba, u8 *buf, u32 size)
2100 return ufshcd_read_desc(hba, QUERY_DESC_IDN_DEVICE, 0, buf, size);
2102 EXPORT_SYMBOL(ufshcd_read_device_desc);
2105 * ufshcd_read_string_desc - read string descriptor
2106 * @hba: pointer to adapter instance
2107 * @desc_index: descriptor index
2108 * @buf: pointer to buffer where descriptor would be read
2109 * @size: size of buf
2110 * @ascii: if true convert from unicode to ascii characters
2112 * Return 0 in case of success, non-zero otherwise
2114 int ufshcd_read_string_desc(struct ufs_hba *hba, int desc_index, u8 *buf,
2115 u32 size, bool ascii)
2119 err = ufshcd_read_desc(hba,
2120 QUERY_DESC_IDN_STRING, desc_index, buf, size);
2123 dev_err(hba->dev, "%s: reading String Desc failed after %d retries. err = %d\n",
2124 __func__, QUERY_REQ_RETRIES, err);
2135 /* remove header and divide by 2 to move from UTF16 to UTF8 */
2136 ascii_len = (desc_len - QUERY_DESC_HDR_SIZE) / 2 + 1;
2137 if (size < ascii_len + QUERY_DESC_HDR_SIZE) {
2138 dev_err(hba->dev, "%s: buffer allocated size is too small\n",
2144 buff_ascii = kmalloc(ascii_len, GFP_KERNEL);
2151 * the descriptor contains string in UTF16 format
2152 * we need to convert to utf-8 so it can be displayed
2154 utf16s_to_utf8s((wchar_t *)&buf[QUERY_DESC_HDR_SIZE],
2155 desc_len - QUERY_DESC_HDR_SIZE,
2156 UTF16_BIG_ENDIAN, buff_ascii, ascii_len);
2158 /* replace non-printable or non-ASCII characters with spaces */
2159 for (i = 0; i < ascii_len; i++)
2160 ufshcd_remove_non_printable(&buff_ascii[i]);
2162 memset(buf + QUERY_DESC_HDR_SIZE, 0,
2163 size - QUERY_DESC_HDR_SIZE);
2164 memcpy(buf + QUERY_DESC_HDR_SIZE, buff_ascii, ascii_len);
2165 buf[QUERY_DESC_LENGTH_OFFSET] = ascii_len + QUERY_DESC_HDR_SIZE;
2171 EXPORT_SYMBOL(ufshcd_read_string_desc);
2174 * ufshcd_read_unit_desc_param - read the specified unit descriptor parameter
2175 * @hba: Pointer to adapter instance
2177 * @param_offset: offset of the parameter to read
2178 * @param_read_buf: pointer to buffer where parameter would be read
2179 * @param_size: sizeof(param_read_buf)
2181 * Return 0 in case of success, non-zero otherwise
2183 static inline int ufshcd_read_unit_desc_param(struct ufs_hba *hba,
2185 enum unit_desc_param param_offset,
2190 * Unit descriptors are only available for general purpose LUs (LUN id
2191 * from 0 to 7) and RPMB Well known LU.
2193 if (lun != UFS_UPIU_RPMB_WLUN && (lun >= UFS_UPIU_MAX_GENERAL_LUN))
2196 return ufshcd_read_desc_param(hba, QUERY_DESC_IDN_UNIT, lun,
2197 param_offset, param_read_buf, param_size);
2201 * ufshcd_memory_alloc - allocate memory for host memory space data structures
2202 * @hba: per adapter instance
2204 * 1. Allocate DMA memory for Command Descriptor array
2205 * Each command descriptor consist of Command UPIU, Response UPIU and PRDT
2206 * 2. Allocate DMA memory for UTP Transfer Request Descriptor List (UTRDL).
2207 * 3. Allocate DMA memory for UTP Task Management Request Descriptor List
2209 * 4. Allocate memory for local reference block(lrb).
2211 * Returns 0 for success, non-zero in case of failure
2213 static int ufshcd_memory_alloc(struct ufs_hba *hba)
2215 size_t utmrdl_size, utrdl_size, ucdl_size;
2217 /* Allocate memory for UTP command descriptors */
2218 ucdl_size = (sizeof(struct utp_transfer_cmd_desc) * hba->nutrs);
2219 hba->ucdl_base_addr = dmam_alloc_coherent(hba->dev,
2221 &hba->ucdl_dma_addr,
2225 * UFSHCI requires UTP command descriptor to be 128 byte aligned.
2226 * make sure hba->ucdl_dma_addr is aligned to PAGE_SIZE
2227 * if hba->ucdl_dma_addr is aligned to PAGE_SIZE, then it will
2228 * be aligned to 128 bytes as well
2230 if (!hba->ucdl_base_addr ||
2231 WARN_ON(hba->ucdl_dma_addr & (PAGE_SIZE - 1))) {
2233 "Command Descriptor Memory allocation failed\n");
2238 * Allocate memory for UTP Transfer descriptors
2239 * UFSHCI requires 1024 byte alignment of UTRD
2241 utrdl_size = (sizeof(struct utp_transfer_req_desc) * hba->nutrs);
2242 hba->utrdl_base_addr = dmam_alloc_coherent(hba->dev,
2244 &hba->utrdl_dma_addr,
2246 if (!hba->utrdl_base_addr ||
2247 WARN_ON(hba->utrdl_dma_addr & (PAGE_SIZE - 1))) {
2249 "Transfer Descriptor Memory allocation failed\n");
2254 * Allocate memory for UTP Task Management descriptors
2255 * UFSHCI requires 1024 byte alignment of UTMRD
2257 utmrdl_size = sizeof(struct utp_task_req_desc) * hba->nutmrs;
2258 hba->utmrdl_base_addr = dmam_alloc_coherent(hba->dev,
2260 &hba->utmrdl_dma_addr,
2262 if (!hba->utmrdl_base_addr ||
2263 WARN_ON(hba->utmrdl_dma_addr & (PAGE_SIZE - 1))) {
2265 "Task Management Descriptor Memory allocation failed\n");
2269 /* Allocate memory for local reference block */
2270 hba->lrb = devm_kzalloc(hba->dev,
2271 hba->nutrs * sizeof(struct ufshcd_lrb),
2274 dev_err(hba->dev, "LRB Memory allocation failed\n");
2283 * ufshcd_host_memory_configure - configure local reference block with
2285 * @hba: per adapter instance
2287 * Configure Host memory space
2288 * 1. Update Corresponding UTRD.UCDBA and UTRD.UCDBAU with UCD DMA
2290 * 2. Update each UTRD with Response UPIU offset, Response UPIU length
2292 * 3. Save the corresponding addresses of UTRD, UCD.CMD, UCD.RSP and UCD.PRDT
2293 * into local reference block.
2295 static void ufshcd_host_memory_configure(struct ufs_hba *hba)
2297 struct utp_transfer_cmd_desc *cmd_descp;
2298 struct utp_transfer_req_desc *utrdlp;
2299 dma_addr_t cmd_desc_dma_addr;
2300 dma_addr_t cmd_desc_element_addr;
2301 u16 response_offset;
2306 utrdlp = hba->utrdl_base_addr;
2307 cmd_descp = hba->ucdl_base_addr;
2310 offsetof(struct utp_transfer_cmd_desc, response_upiu);
2312 offsetof(struct utp_transfer_cmd_desc, prd_table);
2314 cmd_desc_size = sizeof(struct utp_transfer_cmd_desc);
2315 cmd_desc_dma_addr = hba->ucdl_dma_addr;
2317 for (i = 0; i < hba->nutrs; i++) {
2318 /* Configure UTRD with command descriptor base address */
2319 cmd_desc_element_addr =
2320 (cmd_desc_dma_addr + (cmd_desc_size * i));
2321 utrdlp[i].command_desc_base_addr_lo =
2322 cpu_to_le32(lower_32_bits(cmd_desc_element_addr));
2323 utrdlp[i].command_desc_base_addr_hi =
2324 cpu_to_le32(upper_32_bits(cmd_desc_element_addr));
2326 /* Response upiu and prdt offset should be in double words */
2327 utrdlp[i].response_upiu_offset =
2328 cpu_to_le16((response_offset >> 2));
2329 utrdlp[i].prd_table_offset =
2330 cpu_to_le16((prdt_offset >> 2));
2331 utrdlp[i].response_upiu_length =
2332 cpu_to_le16(ALIGNED_UPIU_SIZE >> 2);
2334 hba->lrb[i].utr_descriptor_ptr = (utrdlp + i);
2335 hba->lrb[i].ucd_req_ptr =
2336 (struct utp_upiu_req *)(cmd_descp + i);
2337 hba->lrb[i].ucd_rsp_ptr =
2338 (struct utp_upiu_rsp *)cmd_descp[i].response_upiu;
2339 hba->lrb[i].ucd_prdt_ptr =
2340 (struct ufshcd_sg_entry *)cmd_descp[i].prd_table;
2345 * ufshcd_dme_link_startup - Notify Unipro to perform link startup
2346 * @hba: per adapter instance
2348 * UIC_CMD_DME_LINK_STARTUP command must be issued to Unipro layer,
2349 * in order to initialize the Unipro link startup procedure.
2350 * Once the Unipro links are up, the device connected to the controller
2353 * Returns 0 on success, non-zero value on failure
2355 static int ufshcd_dme_link_startup(struct ufs_hba *hba)
2357 struct uic_command uic_cmd = {0};
2360 uic_cmd.command = UIC_CMD_DME_LINK_STARTUP;
2362 ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
2365 "dme-link-startup: error code %d\n", ret);
2369 static inline void ufshcd_add_delay_before_dme_cmd(struct ufs_hba *hba)
2371 #define MIN_DELAY_BEFORE_DME_CMDS_US 1000
2372 unsigned long min_sleep_time_us;
2374 if (!(hba->quirks & UFSHCD_QUIRK_DELAY_BEFORE_DME_CMDS))
2378 * last_dme_cmd_tstamp will be 0 only for 1st call to
2381 if (unlikely(!ktime_to_us(hba->last_dme_cmd_tstamp))) {
2382 min_sleep_time_us = MIN_DELAY_BEFORE_DME_CMDS_US;
2384 unsigned long delta =
2385 (unsigned long) ktime_to_us(
2386 ktime_sub(ktime_get(),
2387 hba->last_dme_cmd_tstamp));
2389 if (delta < MIN_DELAY_BEFORE_DME_CMDS_US)
2391 MIN_DELAY_BEFORE_DME_CMDS_US - delta;
2393 return; /* no more delay required */
2396 /* allow sleep for extra 50us if needed */
2397 usleep_range(min_sleep_time_us, min_sleep_time_us + 50);
2401 * ufshcd_dme_set_attr - UIC command for DME_SET, DME_PEER_SET
2402 * @hba: per adapter instance
2403 * @attr_sel: uic command argument1
2404 * @attr_set: attribute set type as uic command argument2
2405 * @mib_val: setting value as uic command argument3
2406 * @peer: indicate whether peer or local
2408 * Returns 0 on success, non-zero value on failure
2410 int ufshcd_dme_set_attr(struct ufs_hba *hba, u32 attr_sel,
2411 u8 attr_set, u32 mib_val, u8 peer)
2413 struct uic_command uic_cmd = {0};
2414 static const char *const action[] = {
2418 const char *set = action[!!peer];
2420 int retries = UFS_UIC_COMMAND_RETRIES;
2422 uic_cmd.command = peer ?
2423 UIC_CMD_DME_PEER_SET : UIC_CMD_DME_SET;
2424 uic_cmd.argument1 = attr_sel;
2425 uic_cmd.argument2 = UIC_ARG_ATTR_TYPE(attr_set);
2426 uic_cmd.argument3 = mib_val;
2429 /* for peer attributes we retry upon failure */
2430 ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
2432 dev_dbg(hba->dev, "%s: attr-id 0x%x val 0x%x error code %d\n",
2433 set, UIC_GET_ATTR_ID(attr_sel), mib_val, ret);
2434 } while (ret && peer && --retries);
2437 dev_err(hba->dev, "%s: attr-id 0x%x val 0x%x failed %d retries\n",
2438 set, UIC_GET_ATTR_ID(attr_sel), mib_val,
2443 EXPORT_SYMBOL_GPL(ufshcd_dme_set_attr);
2446 * ufshcd_dme_get_attr - UIC command for DME_GET, DME_PEER_GET
2447 * @hba: per adapter instance
2448 * @attr_sel: uic command argument1
2449 * @mib_val: the value of the attribute as returned by the UIC command
2450 * @peer: indicate whether peer or local
2452 * Returns 0 on success, non-zero value on failure
2454 int ufshcd_dme_get_attr(struct ufs_hba *hba, u32 attr_sel,
2455 u32 *mib_val, u8 peer)
2457 struct uic_command uic_cmd = {0};
2458 static const char *const action[] = {
2462 const char *get = action[!!peer];
2464 int retries = UFS_UIC_COMMAND_RETRIES;
2465 struct ufs_pa_layer_attr orig_pwr_info;
2466 struct ufs_pa_layer_attr temp_pwr_info;
2467 bool pwr_mode_change = false;
2469 if (peer && (hba->quirks & UFSHCD_QUIRK_DME_PEER_ACCESS_AUTO_MODE)) {
2470 orig_pwr_info = hba->pwr_info;
2471 temp_pwr_info = orig_pwr_info;
2473 if (orig_pwr_info.pwr_tx == FAST_MODE ||
2474 orig_pwr_info.pwr_rx == FAST_MODE) {
2475 temp_pwr_info.pwr_tx = FASTAUTO_MODE;
2476 temp_pwr_info.pwr_rx = FASTAUTO_MODE;
2477 pwr_mode_change = true;
2478 } else if (orig_pwr_info.pwr_tx == SLOW_MODE ||
2479 orig_pwr_info.pwr_rx == SLOW_MODE) {
2480 temp_pwr_info.pwr_tx = SLOWAUTO_MODE;
2481 temp_pwr_info.pwr_rx = SLOWAUTO_MODE;
2482 pwr_mode_change = true;
2484 if (pwr_mode_change) {
2485 ret = ufshcd_change_power_mode(hba, &temp_pwr_info);
2491 uic_cmd.command = peer ?
2492 UIC_CMD_DME_PEER_GET : UIC_CMD_DME_GET;
2493 uic_cmd.argument1 = attr_sel;
2496 /* for peer attributes we retry upon failure */
2497 ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
2499 dev_dbg(hba->dev, "%s: attr-id 0x%x error code %d\n",
2500 get, UIC_GET_ATTR_ID(attr_sel), ret);
2501 } while (ret && peer && --retries);
2504 dev_err(hba->dev, "%s: attr-id 0x%x failed %d retries\n",
2505 get, UIC_GET_ATTR_ID(attr_sel), retries);
2507 if (mib_val && !ret)
2508 *mib_val = uic_cmd.argument3;
2510 if (peer && (hba->quirks & UFSHCD_QUIRK_DME_PEER_ACCESS_AUTO_MODE)
2512 ufshcd_change_power_mode(hba, &orig_pwr_info);
2516 EXPORT_SYMBOL_GPL(ufshcd_dme_get_attr);
2519 * ufshcd_uic_pwr_ctrl - executes UIC commands (which affects the link power
2520 * state) and waits for it to take effect.
2522 * @hba: per adapter instance
2523 * @cmd: UIC command to execute
2525 * DME operations like DME_SET(PA_PWRMODE), DME_HIBERNATE_ENTER &
2526 * DME_HIBERNATE_EXIT commands take some time to take its effect on both host
2527 * and device UniPro link and hence it's final completion would be indicated by
2528 * dedicated status bits in Interrupt Status register (UPMS, UHES, UHXS) in
2529 * addition to normal UIC command completion Status (UCCS). This function only
2530 * returns after the relevant status bits indicate the completion.
2532 * Returns 0 on success, non-zero value on failure
2534 static int ufshcd_uic_pwr_ctrl(struct ufs_hba *hba, struct uic_command *cmd)
2536 struct completion uic_async_done;
2537 unsigned long flags;
2540 bool reenable_intr = false;
2542 mutex_lock(&hba->uic_cmd_mutex);
2543 init_completion(&uic_async_done);
2544 ufshcd_add_delay_before_dme_cmd(hba);
2546 spin_lock_irqsave(hba->host->host_lock, flags);
2547 hba->uic_async_done = &uic_async_done;
2548 if (ufshcd_readl(hba, REG_INTERRUPT_ENABLE) & UIC_COMMAND_COMPL) {
2549 ufshcd_disable_intr(hba, UIC_COMMAND_COMPL);
2551 * Make sure UIC command completion interrupt is disabled before
2552 * issuing UIC command.
2555 reenable_intr = true;
2557 ret = __ufshcd_send_uic_cmd(hba, cmd, false);
2558 spin_unlock_irqrestore(hba->host->host_lock, flags);
2561 "pwr ctrl cmd 0x%x with mode 0x%x uic error %d\n",
2562 cmd->command, cmd->argument3, ret);
2566 if (!wait_for_completion_timeout(hba->uic_async_done,
2567 msecs_to_jiffies(UIC_CMD_TIMEOUT))) {
2569 "pwr ctrl cmd 0x%x with mode 0x%x completion timeout\n",
2570 cmd->command, cmd->argument3);
2575 status = ufshcd_get_upmcrs(hba);
2576 if (status != PWR_LOCAL) {
2578 "pwr ctrl cmd 0x%0x failed, host upmcrs:0x%x\n",
2579 cmd->command, status);
2580 ret = (status != PWR_OK) ? status : -1;
2583 spin_lock_irqsave(hba->host->host_lock, flags);
2584 hba->active_uic_cmd = NULL;
2585 hba->uic_async_done = NULL;
2587 ufshcd_enable_intr(hba, UIC_COMMAND_COMPL);
2588 spin_unlock_irqrestore(hba->host->host_lock, flags);
2589 mutex_unlock(&hba->uic_cmd_mutex);
2595 * ufshcd_uic_change_pwr_mode - Perform the UIC power mode chage
2596 * using DME_SET primitives.
2597 * @hba: per adapter instance
2598 * @mode: powr mode value
2600 * Returns 0 on success, non-zero value on failure
2602 static int ufshcd_uic_change_pwr_mode(struct ufs_hba *hba, u8 mode)
2604 struct uic_command uic_cmd = {0};
2607 if (hba->quirks & UFSHCD_QUIRK_BROKEN_PA_RXHSUNTERMCAP) {
2608 ret = ufshcd_dme_set(hba,
2609 UIC_ARG_MIB_SEL(PA_RXHSUNTERMCAP, 0), 1);
2611 dev_err(hba->dev, "%s: failed to enable PA_RXHSUNTERMCAP ret %d\n",
2617 uic_cmd.command = UIC_CMD_DME_SET;
2618 uic_cmd.argument1 = UIC_ARG_MIB(PA_PWRMODE);
2619 uic_cmd.argument3 = mode;
2620 ufshcd_hold(hba, false);
2621 ret = ufshcd_uic_pwr_ctrl(hba, &uic_cmd);
2622 ufshcd_release(hba);
2628 static int ufshcd_link_recovery(struct ufs_hba *hba)
2631 unsigned long flags;
2633 spin_lock_irqsave(hba->host->host_lock, flags);
2634 hba->ufshcd_state = UFSHCD_STATE_RESET;
2635 ufshcd_set_eh_in_progress(hba);
2636 spin_unlock_irqrestore(hba->host->host_lock, flags);
2638 ret = ufshcd_host_reset_and_restore(hba);
2640 spin_lock_irqsave(hba->host->host_lock, flags);
2642 hba->ufshcd_state = UFSHCD_STATE_ERROR;
2643 ufshcd_clear_eh_in_progress(hba);
2644 spin_unlock_irqrestore(hba->host->host_lock, flags);
2647 dev_err(hba->dev, "%s: link recovery failed, err %d",
2653 static int __ufshcd_uic_hibern8_enter(struct ufs_hba *hba)
2656 struct uic_command uic_cmd = {0};
2658 uic_cmd.command = UIC_CMD_DME_HIBER_ENTER;
2659 ret = ufshcd_uic_pwr_ctrl(hba, &uic_cmd);
2662 dev_err(hba->dev, "%s: hibern8 enter failed. ret = %d\n",
2666 * If link recovery fails then return error so that caller
2667 * don't retry the hibern8 enter again.
2669 if (ufshcd_link_recovery(hba))
2676 static int ufshcd_uic_hibern8_enter(struct ufs_hba *hba)
2678 int ret = 0, retries;
2680 for (retries = UIC_HIBERN8_ENTER_RETRIES; retries > 0; retries--) {
2681 ret = __ufshcd_uic_hibern8_enter(hba);
2682 if (!ret || ret == -ENOLINK)
2689 static int ufshcd_uic_hibern8_exit(struct ufs_hba *hba)
2691 struct uic_command uic_cmd = {0};
2694 uic_cmd.command = UIC_CMD_DME_HIBER_EXIT;
2695 ret = ufshcd_uic_pwr_ctrl(hba, &uic_cmd);
2697 dev_err(hba->dev, "%s: hibern8 exit failed. ret = %d\n",
2699 ret = ufshcd_link_recovery(hba);
2706 * ufshcd_init_pwr_info - setting the POR (power on reset)
2707 * values in hba power info
2708 * @hba: per-adapter instance
2710 static void ufshcd_init_pwr_info(struct ufs_hba *hba)
2712 hba->pwr_info.gear_rx = UFS_PWM_G1;
2713 hba->pwr_info.gear_tx = UFS_PWM_G1;
2714 hba->pwr_info.lane_rx = 1;
2715 hba->pwr_info.lane_tx = 1;
2716 hba->pwr_info.pwr_rx = SLOWAUTO_MODE;
2717 hba->pwr_info.pwr_tx = SLOWAUTO_MODE;
2718 hba->pwr_info.hs_rate = 0;
2722 * ufshcd_get_max_pwr_mode - reads the max power mode negotiated with device
2723 * @hba: per-adapter instance
2725 static int ufshcd_get_max_pwr_mode(struct ufs_hba *hba)
2727 struct ufs_pa_layer_attr *pwr_info = &hba->max_pwr_info.info;
2729 if (hba->max_pwr_info.is_valid)
2732 pwr_info->pwr_tx = FASTAUTO_MODE;
2733 pwr_info->pwr_rx = FASTAUTO_MODE;
2734 pwr_info->hs_rate = PA_HS_MODE_B;
2736 /* Get the connected lane count */
2737 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_CONNECTEDRXDATALANES),
2738 &pwr_info->lane_rx);
2739 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_CONNECTEDTXDATALANES),
2740 &pwr_info->lane_tx);
2742 if (!pwr_info->lane_rx || !pwr_info->lane_tx) {
2743 dev_err(hba->dev, "%s: invalid connected lanes value. rx=%d, tx=%d\n",
2751 * First, get the maximum gears of HS speed.
2752 * If a zero value, it means there is no HSGEAR capability.
2753 * Then, get the maximum gears of PWM speed.
2755 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_MAXRXHSGEAR), &pwr_info->gear_rx);
2756 if (!pwr_info->gear_rx) {
2757 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_MAXRXPWMGEAR),
2758 &pwr_info->gear_rx);
2759 if (!pwr_info->gear_rx) {
2760 dev_err(hba->dev, "%s: invalid max pwm rx gear read = %d\n",
2761 __func__, pwr_info->gear_rx);
2764 pwr_info->pwr_rx = SLOWAUTO_MODE;
2767 ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_MAXRXHSGEAR),
2768 &pwr_info->gear_tx);
2769 if (!pwr_info->gear_tx) {
2770 ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_MAXRXPWMGEAR),
2771 &pwr_info->gear_tx);
2772 if (!pwr_info->gear_tx) {
2773 dev_err(hba->dev, "%s: invalid max pwm tx gear read = %d\n",
2774 __func__, pwr_info->gear_tx);
2777 pwr_info->pwr_tx = SLOWAUTO_MODE;
2780 hba->max_pwr_info.is_valid = true;
2784 static int ufshcd_change_power_mode(struct ufs_hba *hba,
2785 struct ufs_pa_layer_attr *pwr_mode)
2789 /* if already configured to the requested pwr_mode */
2790 if (pwr_mode->gear_rx == hba->pwr_info.gear_rx &&
2791 pwr_mode->gear_tx == hba->pwr_info.gear_tx &&
2792 pwr_mode->lane_rx == hba->pwr_info.lane_rx &&
2793 pwr_mode->lane_tx == hba->pwr_info.lane_tx &&
2794 pwr_mode->pwr_rx == hba->pwr_info.pwr_rx &&
2795 pwr_mode->pwr_tx == hba->pwr_info.pwr_tx &&
2796 pwr_mode->hs_rate == hba->pwr_info.hs_rate) {
2797 dev_dbg(hba->dev, "%s: power already configured\n", __func__);
2802 * Configure attributes for power mode change with below.
2803 * - PA_RXGEAR, PA_ACTIVERXDATALANES, PA_RXTERMINATION,
2804 * - PA_TXGEAR, PA_ACTIVETXDATALANES, PA_TXTERMINATION,
2807 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_RXGEAR), pwr_mode->gear_rx);
2808 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_ACTIVERXDATALANES),
2810 if (pwr_mode->pwr_rx == FASTAUTO_MODE ||
2811 pwr_mode->pwr_rx == FAST_MODE)
2812 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_RXTERMINATION), TRUE);
2814 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_RXTERMINATION), FALSE);
2816 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TXGEAR), pwr_mode->gear_tx);
2817 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_ACTIVETXDATALANES),
2819 if (pwr_mode->pwr_tx == FASTAUTO_MODE ||
2820 pwr_mode->pwr_tx == FAST_MODE)
2821 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TXTERMINATION), TRUE);
2823 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TXTERMINATION), FALSE);
2825 if (pwr_mode->pwr_rx == FASTAUTO_MODE ||
2826 pwr_mode->pwr_tx == FASTAUTO_MODE ||
2827 pwr_mode->pwr_rx == FAST_MODE ||
2828 pwr_mode->pwr_tx == FAST_MODE)
2829 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_HSSERIES),
2832 ret = ufshcd_uic_change_pwr_mode(hba, pwr_mode->pwr_rx << 4
2833 | pwr_mode->pwr_tx);
2837 "%s: power mode change failed %d\n", __func__, ret);
2839 ufshcd_vops_pwr_change_notify(hba, POST_CHANGE, NULL,
2842 memcpy(&hba->pwr_info, pwr_mode,
2843 sizeof(struct ufs_pa_layer_attr));
2850 * ufshcd_config_pwr_mode - configure a new power mode
2851 * @hba: per-adapter instance
2852 * @desired_pwr_mode: desired power configuration
2854 static int ufshcd_config_pwr_mode(struct ufs_hba *hba,
2855 struct ufs_pa_layer_attr *desired_pwr_mode)
2857 struct ufs_pa_layer_attr final_params = { 0 };
2860 ret = ufshcd_vops_pwr_change_notify(hba, PRE_CHANGE,
2861 desired_pwr_mode, &final_params);
2864 memcpy(&final_params, desired_pwr_mode, sizeof(final_params));
2866 ret = ufshcd_change_power_mode(hba, &final_params);
2872 * ufshcd_complete_dev_init() - checks device readiness
2873 * hba: per-adapter instance
2875 * Set fDeviceInit flag and poll until device toggles it.
2877 static int ufshcd_complete_dev_init(struct ufs_hba *hba)
2883 err = ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_SET_FLAG,
2884 QUERY_FLAG_IDN_FDEVICEINIT, NULL);
2887 "%s setting fDeviceInit flag failed with error %d\n",
2892 /* poll for max. 1000 iterations for fDeviceInit flag to clear */
2893 for (i = 0; i < 1000 && !err && flag_res; i++)
2894 err = ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_READ_FLAG,
2895 QUERY_FLAG_IDN_FDEVICEINIT, &flag_res);
2899 "%s reading fDeviceInit flag failed with error %d\n",
2903 "%s fDeviceInit was not cleared by the device\n",
2911 * ufshcd_make_hba_operational - Make UFS controller operational
2912 * @hba: per adapter instance
2914 * To bring UFS host controller to operational state,
2915 * 1. Enable required interrupts
2916 * 2. Configure interrupt aggregation
2917 * 3. Program UTRL and UTMRL base address
2918 * 4. Configure run-stop-registers
2920 * Returns 0 on success, non-zero value on failure
2922 static int ufshcd_make_hba_operational(struct ufs_hba *hba)
2927 /* Enable required interrupts */
2928 ufshcd_enable_intr(hba, UFSHCD_ENABLE_INTRS);
2930 /* Configure interrupt aggregation */
2931 if (ufshcd_is_intr_aggr_allowed(hba))
2932 ufshcd_config_intr_aggr(hba, hba->nutrs - 1, INT_AGGR_DEF_TO);
2934 ufshcd_disable_intr_aggr(hba);
2936 /* Configure UTRL and UTMRL base address registers */
2937 ufshcd_writel(hba, lower_32_bits(hba->utrdl_dma_addr),
2938 REG_UTP_TRANSFER_REQ_LIST_BASE_L);
2939 ufshcd_writel(hba, upper_32_bits(hba->utrdl_dma_addr),
2940 REG_UTP_TRANSFER_REQ_LIST_BASE_H);
2941 ufshcd_writel(hba, lower_32_bits(hba->utmrdl_dma_addr),
2942 REG_UTP_TASK_REQ_LIST_BASE_L);
2943 ufshcd_writel(hba, upper_32_bits(hba->utmrdl_dma_addr),
2944 REG_UTP_TASK_REQ_LIST_BASE_H);
2947 * Make sure base address and interrupt setup are updated before
2948 * enabling the run/stop registers below.
2953 * UCRDY, UTMRLDY and UTRLRDY bits must be 1
2955 reg = ufshcd_readl(hba, REG_CONTROLLER_STATUS);
2956 if (!(ufshcd_get_lists_status(reg))) {
2957 ufshcd_enable_run_stop_reg(hba);
2960 "Host controller not ready to process requests");
2970 * ufshcd_hba_stop - Send controller to reset state
2971 * @hba: per adapter instance
2972 * @can_sleep: perform sleep or just spin
2974 static inline void ufshcd_hba_stop(struct ufs_hba *hba, bool can_sleep)
2978 ufshcd_writel(hba, CONTROLLER_DISABLE, REG_CONTROLLER_ENABLE);
2979 err = ufshcd_wait_for_register(hba, REG_CONTROLLER_ENABLE,
2980 CONTROLLER_ENABLE, CONTROLLER_DISABLE,
2983 dev_err(hba->dev, "%s: Controller disable failed\n", __func__);
2987 * ufshcd_hba_enable - initialize the controller
2988 * @hba: per adapter instance
2990 * The controller resets itself and controller firmware initialization
2991 * sequence kicks off. When controller is ready it will set
2992 * the Host Controller Enable bit to 1.
2994 * Returns 0 on success, non-zero value on failure
2996 static int ufshcd_hba_enable(struct ufs_hba *hba)
3001 * msleep of 1 and 5 used in this function might result in msleep(20),
3002 * but it was necessary to send the UFS FPGA to reset mode during
3003 * development and testing of this driver. msleep can be changed to
3004 * mdelay and retry count can be reduced based on the controller.
3006 if (!ufshcd_is_hba_active(hba))
3007 /* change controller state to "reset state" */
3008 ufshcd_hba_stop(hba, true);
3010 /* UniPro link is disabled at this point */
3011 ufshcd_set_link_off(hba);
3013 ufshcd_vops_hce_enable_notify(hba, PRE_CHANGE);
3015 /* start controller initialization sequence */
3016 ufshcd_hba_start(hba);
3019 * To initialize a UFS host controller HCE bit must be set to 1.
3020 * During initialization the HCE bit value changes from 1->0->1.
3021 * When the host controller completes initialization sequence
3022 * it sets the value of HCE bit to 1. The same HCE bit is read back
3023 * to check if the controller has completed initialization sequence.
3024 * So without this delay the value HCE = 1, set in the previous
3025 * instruction might be read back.
3026 * This delay can be changed based on the controller.
3030 /* wait for the host controller to complete initialization */
3032 while (ufshcd_is_hba_active(hba)) {
3037 "Controller enable failed\n");
3043 /* enable UIC related interrupts */
3044 ufshcd_enable_intr(hba, UFSHCD_UIC_MASK);
3046 ufshcd_vops_hce_enable_notify(hba, POST_CHANGE);
3051 static int ufshcd_disable_tx_lcc(struct ufs_hba *hba, bool peer)
3053 int tx_lanes, i, err = 0;
3056 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_CONNECTEDTXDATALANES),
3059 ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_CONNECTEDTXDATALANES),
3061 for (i = 0; i < tx_lanes; i++) {
3063 err = ufshcd_dme_set(hba,
3064 UIC_ARG_MIB_SEL(TX_LCC_ENABLE,
3065 UIC_ARG_MPHY_TX_GEN_SEL_INDEX(i)),
3068 err = ufshcd_dme_peer_set(hba,
3069 UIC_ARG_MIB_SEL(TX_LCC_ENABLE,
3070 UIC_ARG_MPHY_TX_GEN_SEL_INDEX(i)),
3073 dev_err(hba->dev, "%s: TX LCC Disable failed, peer = %d, lane = %d, err = %d",
3074 __func__, peer, i, err);
3082 static inline int ufshcd_disable_device_tx_lcc(struct ufs_hba *hba)
3084 return ufshcd_disable_tx_lcc(hba, true);
3088 * ufshcd_link_startup - Initialize unipro link startup
3089 * @hba: per adapter instance
3091 * Returns 0 for success, non-zero in case of failure
3093 static int ufshcd_link_startup(struct ufs_hba *hba)
3096 int retries = DME_LINKSTARTUP_RETRIES;
3099 ufshcd_vops_link_startup_notify(hba, PRE_CHANGE);
3101 ret = ufshcd_dme_link_startup(hba);
3103 /* check if device is detected by inter-connect layer */
3104 if (!ret && !ufshcd_is_device_present(hba)) {
3105 dev_err(hba->dev, "%s: Device not present\n", __func__);
3111 * DME link lost indication is only received when link is up,
3112 * but we can't be sure if the link is up until link startup
3113 * succeeds. So reset the local Uni-Pro and try again.
3115 if (ret && ufshcd_hba_enable(hba))
3117 } while (ret && retries--);
3120 /* failed to get the link up... retire */
3123 if (hba->quirks & UFSHCD_QUIRK_BROKEN_LCC) {
3124 ret = ufshcd_disable_device_tx_lcc(hba);
3129 /* Include any host controller configuration via UIC commands */
3130 ret = ufshcd_vops_link_startup_notify(hba, POST_CHANGE);
3134 ret = ufshcd_make_hba_operational(hba);
3137 dev_err(hba->dev, "link startup failed %d\n", ret);
3142 * ufshcd_verify_dev_init() - Verify device initialization
3143 * @hba: per-adapter instance
3145 * Send NOP OUT UPIU and wait for NOP IN response to check whether the
3146 * device Transport Protocol (UTP) layer is ready after a reset.
3147 * If the UTP layer at the device side is not initialized, it may
3148 * not respond with NOP IN UPIU within timeout of %NOP_OUT_TIMEOUT
3149 * and we retry sending NOP OUT for %NOP_OUT_RETRIES iterations.
3151 static int ufshcd_verify_dev_init(struct ufs_hba *hba)
3156 ufshcd_hold(hba, false);
3157 mutex_lock(&hba->dev_cmd.lock);
3158 for (retries = NOP_OUT_RETRIES; retries > 0; retries--) {
3159 err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_NOP,
3162 if (!err || err == -ETIMEDOUT)
3165 dev_dbg(hba->dev, "%s: error %d retrying\n", __func__, err);
3167 mutex_unlock(&hba->dev_cmd.lock);
3168 ufshcd_release(hba);
3171 dev_err(hba->dev, "%s: NOP OUT failed %d\n", __func__, err);
3176 * ufshcd_set_queue_depth - set lun queue depth
3177 * @sdev: pointer to SCSI device
3179 * Read bLUQueueDepth value and activate scsi tagged command
3180 * queueing. For WLUN, queue depth is set to 1. For best-effort
3181 * cases (bLUQueueDepth = 0) the queue depth is set to a maximum
3182 * value that host can queue.
3184 static void ufshcd_set_queue_depth(struct scsi_device *sdev)
3188 struct ufs_hba *hba;
3190 hba = shost_priv(sdev->host);
3192 lun_qdepth = hba->nutrs;
3193 ret = ufshcd_read_unit_desc_param(hba,
3194 ufshcd_scsi_to_upiu_lun(sdev->lun),
3195 UNIT_DESC_PARAM_LU_Q_DEPTH,
3197 sizeof(lun_qdepth));
3199 /* Some WLUN doesn't support unit descriptor */
3200 if (ret == -EOPNOTSUPP)
3202 else if (!lun_qdepth)
3203 /* eventually, we can figure out the real queue depth */
3204 lun_qdepth = hba->nutrs;
3206 lun_qdepth = min_t(int, lun_qdepth, hba->nutrs);
3208 dev_dbg(hba->dev, "%s: activate tcq with queue depth %d\n",
3209 __func__, lun_qdepth);
3210 scsi_change_queue_depth(sdev, lun_qdepth);
3214 * ufshcd_get_lu_wp - returns the "b_lu_write_protect" from UNIT DESCRIPTOR
3215 * @hba: per-adapter instance
3216 * @lun: UFS device lun id
3217 * @b_lu_write_protect: pointer to buffer to hold the LU's write protect info
3219 * Returns 0 in case of success and b_lu_write_protect status would be returned
3220 * @b_lu_write_protect parameter.
3221 * Returns -ENOTSUPP if reading b_lu_write_protect is not supported.
3222 * Returns -EINVAL in case of invalid parameters passed to this function.
3224 static int ufshcd_get_lu_wp(struct ufs_hba *hba,
3226 u8 *b_lu_write_protect)
3230 if (!b_lu_write_protect)
3233 * According to UFS device spec, RPMB LU can't be write
3234 * protected so skip reading bLUWriteProtect parameter for
3235 * it. For other W-LUs, UNIT DESCRIPTOR is not available.
3237 else if (lun >= UFS_UPIU_MAX_GENERAL_LUN)
3240 ret = ufshcd_read_unit_desc_param(hba,
3242 UNIT_DESC_PARAM_LU_WR_PROTECT,
3244 sizeof(*b_lu_write_protect));
3249 * ufshcd_get_lu_power_on_wp_status - get LU's power on write protect
3251 * @hba: per-adapter instance
3252 * @sdev: pointer to SCSI device
3255 static inline void ufshcd_get_lu_power_on_wp_status(struct ufs_hba *hba,
3256 struct scsi_device *sdev)
3258 if (hba->dev_info.f_power_on_wp_en &&
3259 !hba->dev_info.is_lu_power_on_wp) {
3260 u8 b_lu_write_protect;
3262 if (!ufshcd_get_lu_wp(hba, ufshcd_scsi_to_upiu_lun(sdev->lun),
3263 &b_lu_write_protect) &&
3264 (b_lu_write_protect == UFS_LU_POWER_ON_WP))
3265 hba->dev_info.is_lu_power_on_wp = true;
3270 * ufshcd_slave_alloc - handle initial SCSI device configurations
3271 * @sdev: pointer to SCSI device
3275 static int ufshcd_slave_alloc(struct scsi_device *sdev)
3277 struct ufs_hba *hba;
3279 hba = shost_priv(sdev->host);
3281 /* Mode sense(6) is not supported by UFS, so use Mode sense(10) */
3282 sdev->use_10_for_ms = 1;
3284 /* allow SCSI layer to restart the device in case of errors */
3285 sdev->allow_restart = 1;
3287 /* REPORT SUPPORTED OPERATION CODES is not supported */
3288 sdev->no_report_opcodes = 1;
3291 ufshcd_set_queue_depth(sdev);
3293 ufshcd_get_lu_power_on_wp_status(hba, sdev);
3299 * ufshcd_change_queue_depth - change queue depth
3300 * @sdev: pointer to SCSI device
3301 * @depth: required depth to set
3303 * Change queue depth and make sure the max. limits are not crossed.
3305 static int ufshcd_change_queue_depth(struct scsi_device *sdev, int depth)
3307 struct ufs_hba *hba = shost_priv(sdev->host);
3309 if (depth > hba->nutrs)
3311 return scsi_change_queue_depth(sdev, depth);
3315 * ufshcd_slave_configure - adjust SCSI device configurations
3316 * @sdev: pointer to SCSI device
3318 static int ufshcd_slave_configure(struct scsi_device *sdev)
3320 struct request_queue *q = sdev->request_queue;
3322 blk_queue_update_dma_pad(q, PRDT_DATA_BYTE_COUNT_PAD - 1);
3323 blk_queue_max_segment_size(q, PRDT_DATA_BYTE_COUNT_MAX);
3329 * ufshcd_slave_destroy - remove SCSI device configurations
3330 * @sdev: pointer to SCSI device
3332 static void ufshcd_slave_destroy(struct scsi_device *sdev)
3334 struct ufs_hba *hba;
3336 hba = shost_priv(sdev->host);
3337 /* Drop the reference as it won't be needed anymore */
3338 if (ufshcd_scsi_to_upiu_lun(sdev->lun) == UFS_UPIU_UFS_DEVICE_WLUN) {
3339 unsigned long flags;
3341 spin_lock_irqsave(hba->host->host_lock, flags);
3342 hba->sdev_ufs_device = NULL;
3343 spin_unlock_irqrestore(hba->host->host_lock, flags);
3348 * ufshcd_task_req_compl - handle task management request completion
3349 * @hba: per adapter instance
3350 * @index: index of the completed request
3351 * @resp: task management service response
3353 * Returns non-zero value on error, zero on success
3355 static int ufshcd_task_req_compl(struct ufs_hba *hba, u32 index, u8 *resp)
3357 struct utp_task_req_desc *task_req_descp;
3358 struct utp_upiu_task_rsp *task_rsp_upiup;
3359 unsigned long flags;
3363 spin_lock_irqsave(hba->host->host_lock, flags);
3365 /* Clear completed tasks from outstanding_tasks */
3366 __clear_bit(index, &hba->outstanding_tasks);
3368 task_req_descp = hba->utmrdl_base_addr;
3369 ocs_value = ufshcd_get_tmr_ocs(&task_req_descp[index]);
3371 if (ocs_value == OCS_SUCCESS) {
3372 task_rsp_upiup = (struct utp_upiu_task_rsp *)
3373 task_req_descp[index].task_rsp_upiu;
3374 task_result = be32_to_cpu(task_rsp_upiup->output_param1);
3375 task_result = task_result & MASK_TM_SERVICE_RESP;
3377 *resp = (u8)task_result;
3379 dev_err(hba->dev, "%s: failed, ocs = 0x%x\n",
3380 __func__, ocs_value);
3382 spin_unlock_irqrestore(hba->host->host_lock, flags);
3388 * ufshcd_scsi_cmd_status - Update SCSI command result based on SCSI status
3389 * @lrb: pointer to local reference block of completed command
3390 * @scsi_status: SCSI command status
3392 * Returns value base on SCSI command status
3395 ufshcd_scsi_cmd_status(struct ufshcd_lrb *lrbp, int scsi_status)
3399 switch (scsi_status) {
3400 case SAM_STAT_CHECK_CONDITION:
3401 ufshcd_copy_sense_data(lrbp);
3403 result |= DID_OK << 16 |
3404 COMMAND_COMPLETE << 8 |
3407 case SAM_STAT_TASK_SET_FULL:
3409 case SAM_STAT_TASK_ABORTED:
3410 ufshcd_copy_sense_data(lrbp);
3411 result |= scsi_status;
3414 result |= DID_ERROR << 16;
3416 } /* end of switch */
3422 * ufshcd_transfer_rsp_status - Get overall status of the response
3423 * @hba: per adapter instance
3424 * @lrb: pointer to local reference block of completed command
3426 * Returns result of the command to notify SCSI midlayer
3429 ufshcd_transfer_rsp_status(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
3435 /* overall command status of utrd */
3436 ocs = ufshcd_get_tr_ocs(lrbp);
3440 result = ufshcd_get_req_rsp(lrbp->ucd_rsp_ptr);
3443 case UPIU_TRANSACTION_RESPONSE:
3445 * get the response UPIU result to extract
3446 * the SCSI command status
3448 result = ufshcd_get_rsp_upiu_result(lrbp->ucd_rsp_ptr);
3451 * get the result based on SCSI status response
3452 * to notify the SCSI midlayer of the command status
3454 scsi_status = result & MASK_SCSI_STATUS;
3455 result = ufshcd_scsi_cmd_status(lrbp, scsi_status);
3458 * Currently we are only supporting BKOPs exception
3459 * events hence we can ignore BKOPs exception event
3460 * during power management callbacks. BKOPs exception
3461 * event is not expected to be raised in runtime suspend
3462 * callback as it allows the urgent bkops.
3463 * During system suspend, we are anyway forcefully
3464 * disabling the bkops and if urgent bkops is needed
3465 * it will be enabled on system resume. Long term
3466 * solution could be to abort the system suspend if
3467 * UFS device needs urgent BKOPs.
3469 if (!hba->pm_op_in_progress &&
3470 ufshcd_is_exception_event(lrbp->ucd_rsp_ptr))
3471 schedule_work(&hba->eeh_work);
3473 case UPIU_TRANSACTION_REJECT_UPIU:
3474 /* TODO: handle Reject UPIU Response */
3475 result = DID_ERROR << 16;
3477 "Reject UPIU not fully implemented\n");
3480 result = DID_ERROR << 16;
3482 "Unexpected request response code = %x\n",
3488 result |= DID_ABORT << 16;
3490 case OCS_INVALID_COMMAND_STATUS:
3491 result |= DID_REQUEUE << 16;
3493 case OCS_INVALID_CMD_TABLE_ATTR:
3494 case OCS_INVALID_PRDT_ATTR:
3495 case OCS_MISMATCH_DATA_BUF_SIZE:
3496 case OCS_MISMATCH_RESP_UPIU_SIZE:
3497 case OCS_PEER_COMM_FAILURE:
3498 case OCS_FATAL_ERROR:
3500 result |= DID_ERROR << 16;
3502 "OCS error from controller = %x\n", ocs);
3504 } /* end of switch */
3510 * ufshcd_uic_cmd_compl - handle completion of uic command
3511 * @hba: per adapter instance
3512 * @intr_status: interrupt status generated by the controller
3514 static void ufshcd_uic_cmd_compl(struct ufs_hba *hba, u32 intr_status)
3516 if ((intr_status & UIC_COMMAND_COMPL) && hba->active_uic_cmd) {
3517 hba->active_uic_cmd->argument2 |=
3518 ufshcd_get_uic_cmd_result(hba);
3519 hba->active_uic_cmd->argument3 =
3520 ufshcd_get_dme_attr_val(hba);
3521 complete(&hba->active_uic_cmd->done);
3524 if ((intr_status & UFSHCD_UIC_PWR_MASK) && hba->uic_async_done)
3525 complete(hba->uic_async_done);
3529 * __ufshcd_transfer_req_compl - handle SCSI and query command completion
3530 * @hba: per adapter instance
3531 * @completed_reqs: requests to complete
3533 static void __ufshcd_transfer_req_compl(struct ufs_hba *hba,
3534 unsigned long completed_reqs)
3536 struct ufshcd_lrb *lrbp;
3537 struct scsi_cmnd *cmd;
3541 for_each_set_bit(index, &completed_reqs, hba->nutrs) {
3542 lrbp = &hba->lrb[index];
3545 result = ufshcd_transfer_rsp_status(hba, lrbp);
3546 scsi_dma_unmap(cmd);
3547 cmd->result = result;
3548 /* Mark completed command as NULL in LRB */
3550 clear_bit_unlock(index, &hba->lrb_in_use);
3551 /* Do not touch lrbp after scsi done */
3552 cmd->scsi_done(cmd);
3553 __ufshcd_release(hba);
3554 } else if (lrbp->command_type == UTP_CMD_TYPE_DEV_MANAGE ||
3555 lrbp->command_type == UTP_CMD_TYPE_UFS_STORAGE) {
3556 if (hba->dev_cmd.complete)
3557 complete(hba->dev_cmd.complete);
3561 /* clear corresponding bits of completed commands */
3562 hba->outstanding_reqs ^= completed_reqs;
3564 ufshcd_clk_scaling_update_busy(hba);
3566 /* we might have free'd some tags above */
3567 wake_up(&hba->dev_cmd.tag_wq);
3571 * ufshcd_transfer_req_compl - handle SCSI and query command completion
3572 * @hba: per adapter instance
3574 static void ufshcd_transfer_req_compl(struct ufs_hba *hba)
3576 unsigned long completed_reqs;
3579 /* Resetting interrupt aggregation counters first and reading the
3580 * DOOR_BELL afterward allows us to handle all the completed requests.
3581 * In order to prevent other interrupts starvation the DB is read once
3582 * after reset. The down side of this solution is the possibility of
3583 * false interrupt if device completes another request after resetting
3584 * aggregation and before reading the DB.
3586 if (ufshcd_is_intr_aggr_allowed(hba))
3587 ufshcd_reset_intr_aggr(hba);
3589 tr_doorbell = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
3590 completed_reqs = tr_doorbell ^ hba->outstanding_reqs;
3592 __ufshcd_transfer_req_compl(hba, completed_reqs);
3596 * ufshcd_disable_ee - disable exception event
3597 * @hba: per-adapter instance
3598 * @mask: exception event to disable
3600 * Disables exception event in the device so that the EVENT_ALERT
3603 * Returns zero on success, non-zero error value on failure.
3605 static int ufshcd_disable_ee(struct ufs_hba *hba, u16 mask)
3610 if (!(hba->ee_ctrl_mask & mask))
3613 val = hba->ee_ctrl_mask & ~mask;
3614 val &= 0xFFFF; /* 2 bytes */
3615 err = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_WRITE_ATTR,
3616 QUERY_ATTR_IDN_EE_CONTROL, 0, 0, &val);
3618 hba->ee_ctrl_mask &= ~mask;
3624 * ufshcd_enable_ee - enable exception event
3625 * @hba: per-adapter instance
3626 * @mask: exception event to enable
3628 * Enable corresponding exception event in the device to allow
3629 * device to alert host in critical scenarios.
3631 * Returns zero on success, non-zero error value on failure.
3633 static int ufshcd_enable_ee(struct ufs_hba *hba, u16 mask)
3638 if (hba->ee_ctrl_mask & mask)
3641 val = hba->ee_ctrl_mask | mask;
3642 val &= 0xFFFF; /* 2 bytes */
3643 err = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_WRITE_ATTR,
3644 QUERY_ATTR_IDN_EE_CONTROL, 0, 0, &val);
3646 hba->ee_ctrl_mask |= mask;
3652 * ufshcd_enable_auto_bkops - Allow device managed BKOPS
3653 * @hba: per-adapter instance
3655 * Allow device to manage background operations on its own. Enabling
3656 * this might lead to inconsistent latencies during normal data transfers
3657 * as the device is allowed to manage its own way of handling background
3660 * Returns zero on success, non-zero on failure.
3662 static int ufshcd_enable_auto_bkops(struct ufs_hba *hba)
3666 if (hba->auto_bkops_enabled)
3669 err = ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_SET_FLAG,
3670 QUERY_FLAG_IDN_BKOPS_EN, NULL);
3672 dev_err(hba->dev, "%s: failed to enable bkops %d\n",
3677 hba->auto_bkops_enabled = true;
3679 /* No need of URGENT_BKOPS exception from the device */
3680 err = ufshcd_disable_ee(hba, MASK_EE_URGENT_BKOPS);
3682 dev_err(hba->dev, "%s: failed to disable exception event %d\n",
3689 * ufshcd_disable_auto_bkops - block device in doing background operations
3690 * @hba: per-adapter instance
3692 * Disabling background operations improves command response latency but
3693 * has drawback of device moving into critical state where the device is
3694 * not-operable. Make sure to call ufshcd_enable_auto_bkops() whenever the
3695 * host is idle so that BKOPS are managed effectively without any negative
3698 * Returns zero on success, non-zero on failure.
3700 static int ufshcd_disable_auto_bkops(struct ufs_hba *hba)
3704 if (!hba->auto_bkops_enabled)
3708 * If host assisted BKOPs is to be enabled, make sure
3709 * urgent bkops exception is allowed.
3711 err = ufshcd_enable_ee(hba, MASK_EE_URGENT_BKOPS);
3713 dev_err(hba->dev, "%s: failed to enable exception event %d\n",
3718 err = ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_CLEAR_FLAG,
3719 QUERY_FLAG_IDN_BKOPS_EN, NULL);
3721 dev_err(hba->dev, "%s: failed to disable bkops %d\n",
3723 ufshcd_disable_ee(hba, MASK_EE_URGENT_BKOPS);
3727 hba->auto_bkops_enabled = false;
3733 * ufshcd_force_reset_auto_bkops - force enable of auto bkops
3734 * @hba: per adapter instance
3736 * After a device reset the device may toggle the BKOPS_EN flag
3737 * to default value. The s/w tracking variables should be updated
3738 * as well. Do this by forcing enable of auto bkops.
3740 static void ufshcd_force_reset_auto_bkops(struct ufs_hba *hba)
3742 hba->auto_bkops_enabled = false;
3743 hba->ee_ctrl_mask |= MASK_EE_URGENT_BKOPS;
3744 ufshcd_enable_auto_bkops(hba);
3747 static inline int ufshcd_get_bkops_status(struct ufs_hba *hba, u32 *status)
3749 return ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
3750 QUERY_ATTR_IDN_BKOPS_STATUS, 0, 0, status);
3754 * ufshcd_bkops_ctrl - control the auto bkops based on current bkops status
3755 * @hba: per-adapter instance
3756 * @status: bkops_status value
3758 * Read the bkops_status from the UFS device and Enable fBackgroundOpsEn
3759 * flag in the device to permit background operations if the device
3760 * bkops_status is greater than or equal to "status" argument passed to
3761 * this function, disable otherwise.
3763 * Returns 0 for success, non-zero in case of failure.
3765 * NOTE: Caller of this function can check the "hba->auto_bkops_enabled" flag
3766 * to know whether auto bkops is enabled or disabled after this function
3767 * returns control to it.
3769 static int ufshcd_bkops_ctrl(struct ufs_hba *hba,
3770 enum bkops_status status)
3773 u32 curr_status = 0;
3775 err = ufshcd_get_bkops_status(hba, &curr_status);
3777 dev_err(hba->dev, "%s: failed to get BKOPS status %d\n",
3780 } else if (curr_status > BKOPS_STATUS_MAX) {
3781 dev_err(hba->dev, "%s: invalid BKOPS status %d\n",
3782 __func__, curr_status);
3787 if (curr_status >= status)
3788 err = ufshcd_enable_auto_bkops(hba);
3790 err = ufshcd_disable_auto_bkops(hba);
3796 * ufshcd_urgent_bkops - handle urgent bkops exception event
3797 * @hba: per-adapter instance
3799 * Enable fBackgroundOpsEn flag in the device to permit background
3802 * If BKOPs is enabled, this function returns 0, 1 if the bkops in not enabled
3803 * and negative error value for any other failure.
3805 static int ufshcd_urgent_bkops(struct ufs_hba *hba)
3807 return ufshcd_bkops_ctrl(hba, hba->urgent_bkops_lvl);
3810 static inline int ufshcd_get_ee_status(struct ufs_hba *hba, u32 *status)
3812 return ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
3813 QUERY_ATTR_IDN_EE_STATUS, 0, 0, status);
3816 static void ufshcd_bkops_exception_event_handler(struct ufs_hba *hba)
3819 u32 curr_status = 0;
3821 if (hba->is_urgent_bkops_lvl_checked)
3822 goto enable_auto_bkops;
3824 err = ufshcd_get_bkops_status(hba, &curr_status);
3826 dev_err(hba->dev, "%s: failed to get BKOPS status %d\n",
3832 * We are seeing that some devices are raising the urgent bkops
3833 * exception events even when BKOPS status doesn't indicate performace
3834 * impacted or critical. Handle these device by determining their urgent
3835 * bkops status at runtime.
3837 if (curr_status < BKOPS_STATUS_PERF_IMPACT) {
3838 dev_err(hba->dev, "%s: device raised urgent BKOPS exception for bkops status %d\n",
3839 __func__, curr_status);
3840 /* update the current status as the urgent bkops level */
3841 hba->urgent_bkops_lvl = curr_status;
3842 hba->is_urgent_bkops_lvl_checked = true;
3846 err = ufshcd_enable_auto_bkops(hba);
3849 dev_err(hba->dev, "%s: failed to handle urgent bkops %d\n",
3854 * ufshcd_exception_event_handler - handle exceptions raised by device
3855 * @work: pointer to work data
3857 * Read bExceptionEventStatus attribute from the device and handle the
3858 * exception event accordingly.
3860 static void ufshcd_exception_event_handler(struct work_struct *work)
3862 struct ufs_hba *hba;
3865 hba = container_of(work, struct ufs_hba, eeh_work);
3867 pm_runtime_get_sync(hba->dev);
3868 err = ufshcd_get_ee_status(hba, &status);
3870 dev_err(hba->dev, "%s: failed to get exception status %d\n",
3875 status &= hba->ee_ctrl_mask;
3877 if (status & MASK_EE_URGENT_BKOPS)
3878 ufshcd_bkops_exception_event_handler(hba);
3881 pm_runtime_put_sync(hba->dev);
3885 /* Complete requests that have door-bell cleared */
3886 static void ufshcd_complete_requests(struct ufs_hba *hba)
3888 ufshcd_transfer_req_compl(hba);
3889 ufshcd_tmc_handler(hba);
3893 * ufshcd_quirk_dl_nac_errors - This function checks if error handling is
3894 * to recover from the DL NAC errors or not.
3895 * @hba: per-adapter instance
3897 * Returns true if error handling is required, false otherwise
3899 static bool ufshcd_quirk_dl_nac_errors(struct ufs_hba *hba)
3901 unsigned long flags;
3902 bool err_handling = true;
3904 spin_lock_irqsave(hba->host->host_lock, flags);
3906 * UFS_DEVICE_QUIRK_RECOVERY_FROM_DL_NAC_ERRORS only workaround the
3907 * device fatal error and/or DL NAC & REPLAY timeout errors.
3909 if (hba->saved_err & (CONTROLLER_FATAL_ERROR | SYSTEM_BUS_FATAL_ERROR))
3912 if ((hba->saved_err & DEVICE_FATAL_ERROR) ||
3913 ((hba->saved_err & UIC_ERROR) &&
3914 (hba->saved_uic_err & UFSHCD_UIC_DL_TCx_REPLAY_ERROR)))
3917 if ((hba->saved_err & UIC_ERROR) &&
3918 (hba->saved_uic_err & UFSHCD_UIC_DL_NAC_RECEIVED_ERROR)) {
3921 * wait for 50ms to see if we can get any other errors or not.
3923 spin_unlock_irqrestore(hba->host->host_lock, flags);
3925 spin_lock_irqsave(hba->host->host_lock, flags);
3928 * now check if we have got any other severe errors other than
3931 if ((hba->saved_err & INT_FATAL_ERRORS) ||
3932 ((hba->saved_err & UIC_ERROR) &&
3933 (hba->saved_uic_err & ~UFSHCD_UIC_DL_NAC_RECEIVED_ERROR)))
3937 * As DL NAC is the only error received so far, send out NOP
3938 * command to confirm if link is still active or not.
3939 * - If we don't get any response then do error recovery.
3940 * - If we get response then clear the DL NAC error bit.
3943 spin_unlock_irqrestore(hba->host->host_lock, flags);
3944 err = ufshcd_verify_dev_init(hba);
3945 spin_lock_irqsave(hba->host->host_lock, flags);
3950 /* Link seems to be alive hence ignore the DL NAC errors */
3951 if (hba->saved_uic_err == UFSHCD_UIC_DL_NAC_RECEIVED_ERROR)
3952 hba->saved_err &= ~UIC_ERROR;
3953 /* clear NAC error */
3954 hba->saved_uic_err &= ~UFSHCD_UIC_DL_NAC_RECEIVED_ERROR;
3955 if (!hba->saved_uic_err) {
3956 err_handling = false;
3961 spin_unlock_irqrestore(hba->host->host_lock, flags);
3962 return err_handling;
3966 * ufshcd_err_handler - handle UFS errors that require s/w attention
3967 * @work: pointer to work structure
3969 static void ufshcd_err_handler(struct work_struct *work)
3971 struct ufs_hba *hba;
3972 unsigned long flags;
3977 bool needs_reset = false;
3979 hba = container_of(work, struct ufs_hba, eh_work);
3981 pm_runtime_get_sync(hba->dev);
3982 ufshcd_hold(hba, false);
3984 spin_lock_irqsave(hba->host->host_lock, flags);
3985 if (hba->ufshcd_state == UFSHCD_STATE_RESET)
3988 hba->ufshcd_state = UFSHCD_STATE_RESET;
3989 ufshcd_set_eh_in_progress(hba);
3991 /* Complete requests that have door-bell cleared by h/w */
3992 ufshcd_complete_requests(hba);
3994 if (hba->dev_quirks & UFS_DEVICE_QUIRK_RECOVERY_FROM_DL_NAC_ERRORS) {
3997 spin_unlock_irqrestore(hba->host->host_lock, flags);
3998 /* release the lock as ufshcd_quirk_dl_nac_errors() may sleep */
3999 ret = ufshcd_quirk_dl_nac_errors(hba);
4000 spin_lock_irqsave(hba->host->host_lock, flags);
4002 goto skip_err_handling;
4004 if ((hba->saved_err & INT_FATAL_ERRORS) ||
4005 ((hba->saved_err & UIC_ERROR) &&
4006 (hba->saved_uic_err & (UFSHCD_UIC_DL_PA_INIT_ERROR |
4007 UFSHCD_UIC_DL_NAC_RECEIVED_ERROR |
4008 UFSHCD_UIC_DL_TCx_REPLAY_ERROR))))
4012 * if host reset is required then skip clearing the pending
4013 * transfers forcefully because they will automatically get
4014 * cleared after link startup.
4017 goto skip_pending_xfer_clear;
4019 /* release lock as clear command might sleep */
4020 spin_unlock_irqrestore(hba->host->host_lock, flags);
4021 /* Clear pending transfer requests */
4022 for_each_set_bit(tag, &hba->outstanding_reqs, hba->nutrs) {
4023 if (ufshcd_clear_cmd(hba, tag)) {
4025 goto lock_skip_pending_xfer_clear;
4029 /* Clear pending task management requests */
4030 for_each_set_bit(tag, &hba->outstanding_tasks, hba->nutmrs) {
4031 if (ufshcd_clear_tm_cmd(hba, tag)) {
4033 goto lock_skip_pending_xfer_clear;
4037 lock_skip_pending_xfer_clear:
4038 spin_lock_irqsave(hba->host->host_lock, flags);
4040 /* Complete the requests that are cleared by s/w */
4041 ufshcd_complete_requests(hba);
4043 if (err_xfer || err_tm)
4046 skip_pending_xfer_clear:
4047 /* Fatal errors need reset */
4049 unsigned long max_doorbells = (1UL << hba->nutrs) - 1;
4052 * ufshcd_reset_and_restore() does the link reinitialization
4053 * which will need atleast one empty doorbell slot to send the
4054 * device management commands (NOP and query commands).
4055 * If there is no slot empty at this moment then free up last
4058 if (hba->outstanding_reqs == max_doorbells)
4059 __ufshcd_transfer_req_compl(hba,
4060 (1UL << (hba->nutrs - 1)));
4062 spin_unlock_irqrestore(hba->host->host_lock, flags);
4063 err = ufshcd_reset_and_restore(hba);
4064 spin_lock_irqsave(hba->host->host_lock, flags);
4066 dev_err(hba->dev, "%s: reset and restore failed\n",
4068 hba->ufshcd_state = UFSHCD_STATE_ERROR;
4071 * Inform scsi mid-layer that we did reset and allow to handle
4072 * Unit Attention properly.
4074 scsi_report_bus_reset(hba->host, 0);
4076 hba->saved_uic_err = 0;
4081 hba->ufshcd_state = UFSHCD_STATE_OPERATIONAL;
4082 if (hba->saved_err || hba->saved_uic_err)
4083 dev_err_ratelimited(hba->dev, "%s: exit: saved_err 0x%x saved_uic_err 0x%x",
4084 __func__, hba->saved_err, hba->saved_uic_err);
4087 ufshcd_clear_eh_in_progress(hba);
4090 spin_unlock_irqrestore(hba->host->host_lock, flags);
4091 scsi_unblock_requests(hba->host);
4092 ufshcd_release(hba);
4093 pm_runtime_put_sync(hba->dev);
4097 * ufshcd_update_uic_error - check and set fatal UIC error flags.
4098 * @hba: per-adapter instance
4100 static void ufshcd_update_uic_error(struct ufs_hba *hba)
4104 /* PA_INIT_ERROR is fatal and needs UIC reset */
4105 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_DATA_LINK_LAYER);
4106 if (reg & UIC_DATA_LINK_LAYER_ERROR_PA_INIT)
4107 hba->uic_error |= UFSHCD_UIC_DL_PA_INIT_ERROR;
4108 else if (hba->dev_quirks &
4109 UFS_DEVICE_QUIRK_RECOVERY_FROM_DL_NAC_ERRORS) {
4110 if (reg & UIC_DATA_LINK_LAYER_ERROR_NAC_RECEIVED)
4112 UFSHCD_UIC_DL_NAC_RECEIVED_ERROR;
4113 else if (reg & UIC_DATA_LINK_LAYER_ERROR_TCx_REPLAY_TIMEOUT)
4114 hba->uic_error |= UFSHCD_UIC_DL_TCx_REPLAY_ERROR;
4117 /* UIC NL/TL/DME errors needs software retry */
4118 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_NETWORK_LAYER);
4120 hba->uic_error |= UFSHCD_UIC_NL_ERROR;
4122 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_TRANSPORT_LAYER);
4124 hba->uic_error |= UFSHCD_UIC_TL_ERROR;
4126 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_DME);
4128 hba->uic_error |= UFSHCD_UIC_DME_ERROR;
4130 dev_dbg(hba->dev, "%s: UIC error flags = 0x%08x\n",
4131 __func__, hba->uic_error);
4135 * ufshcd_check_errors - Check for errors that need s/w attention
4136 * @hba: per-adapter instance
4138 static void ufshcd_check_errors(struct ufs_hba *hba)
4140 bool queue_eh_work = false;
4142 if (hba->errors & INT_FATAL_ERRORS)
4143 queue_eh_work = true;
4145 if (hba->errors & UIC_ERROR) {
4147 ufshcd_update_uic_error(hba);
4149 queue_eh_work = true;
4152 if (queue_eh_work) {
4154 * update the transfer error masks to sticky bits, let's do this
4155 * irrespective of current ufshcd_state.
4157 hba->saved_err |= hba->errors;
4158 hba->saved_uic_err |= hba->uic_error;
4160 /* handle fatal errors only when link is functional */
4161 if (hba->ufshcd_state == UFSHCD_STATE_OPERATIONAL) {
4162 /* block commands from scsi mid-layer */
4163 scsi_block_requests(hba->host);
4165 hba->ufshcd_state = UFSHCD_STATE_ERROR;
4166 schedule_work(&hba->eh_work);
4170 * if (!queue_eh_work) -
4171 * Other errors are either non-fatal where host recovers
4172 * itself without s/w intervention or errors that will be
4173 * handled by the SCSI core layer.
4178 * ufshcd_tmc_handler - handle task management function completion
4179 * @hba: per adapter instance
4181 static void ufshcd_tmc_handler(struct ufs_hba *hba)
4185 tm_doorbell = ufshcd_readl(hba, REG_UTP_TASK_REQ_DOOR_BELL);
4186 hba->tm_condition = tm_doorbell ^ hba->outstanding_tasks;
4187 wake_up(&hba->tm_wq);
4191 * ufshcd_sl_intr - Interrupt service routine
4192 * @hba: per adapter instance
4193 * @intr_status: contains interrupts generated by the controller
4195 static void ufshcd_sl_intr(struct ufs_hba *hba, u32 intr_status)
4197 hba->errors = UFSHCD_ERROR_MASK & intr_status;
4199 ufshcd_check_errors(hba);
4201 if (intr_status & UFSHCD_UIC_MASK)
4202 ufshcd_uic_cmd_compl(hba, intr_status);
4204 if (intr_status & UTP_TASK_REQ_COMPL)
4205 ufshcd_tmc_handler(hba);
4207 if (intr_status & UTP_TRANSFER_REQ_COMPL)
4208 ufshcd_transfer_req_compl(hba);
4212 * ufshcd_intr - Main interrupt service routine
4214 * @__hba: pointer to adapter instance
4216 * Returns IRQ_HANDLED - If interrupt is valid
4217 * IRQ_NONE - If invalid interrupt
4219 static irqreturn_t ufshcd_intr(int irq, void *__hba)
4221 u32 intr_status, enabled_intr_status;
4222 irqreturn_t retval = IRQ_NONE;
4223 struct ufs_hba *hba = __hba;
4225 spin_lock(hba->host->host_lock);
4226 intr_status = ufshcd_readl(hba, REG_INTERRUPT_STATUS);
4227 enabled_intr_status =
4228 intr_status & ufshcd_readl(hba, REG_INTERRUPT_ENABLE);
4231 ufshcd_writel(hba, intr_status, REG_INTERRUPT_STATUS);
4233 if (enabled_intr_status) {
4234 ufshcd_sl_intr(hba, enabled_intr_status);
4235 retval = IRQ_HANDLED;
4237 spin_unlock(hba->host->host_lock);
4241 static int ufshcd_clear_tm_cmd(struct ufs_hba *hba, int tag)
4244 u32 mask = 1 << tag;
4245 unsigned long flags;
4247 if (!test_bit(tag, &hba->outstanding_tasks))
4250 spin_lock_irqsave(hba->host->host_lock, flags);
4251 ufshcd_writel(hba, ~(1 << tag), REG_UTP_TASK_REQ_LIST_CLEAR);
4252 spin_unlock_irqrestore(hba->host->host_lock, flags);
4254 /* poll for max. 1 sec to clear door bell register by h/w */
4255 err = ufshcd_wait_for_register(hba,
4256 REG_UTP_TASK_REQ_DOOR_BELL,
4257 mask, 0, 1000, 1000, true);
4263 * ufshcd_issue_tm_cmd - issues task management commands to controller
4264 * @hba: per adapter instance
4265 * @lun_id: LUN ID to which TM command is sent
4266 * @task_id: task ID to which the TM command is applicable
4267 * @tm_function: task management function opcode
4268 * @tm_response: task management service response return value
4270 * Returns non-zero value on error, zero on success.
4272 static int ufshcd_issue_tm_cmd(struct ufs_hba *hba, int lun_id, int task_id,
4273 u8 tm_function, u8 *tm_response)
4275 struct utp_task_req_desc *task_req_descp;
4276 struct utp_upiu_task_req *task_req_upiup;
4277 struct Scsi_Host *host;
4278 unsigned long flags;
4286 * Get free slot, sleep if slots are unavailable.
4287 * Even though we use wait_event() which sleeps indefinitely,
4288 * the maximum wait time is bounded by %TM_CMD_TIMEOUT.
4290 wait_event(hba->tm_tag_wq, ufshcd_get_tm_free_slot(hba, &free_slot));
4291 ufshcd_hold(hba, false);
4293 spin_lock_irqsave(host->host_lock, flags);
4294 task_req_descp = hba->utmrdl_base_addr;
4295 task_req_descp += free_slot;
4297 /* Configure task request descriptor */
4298 task_req_descp->header.dword_0 = cpu_to_le32(UTP_REQ_DESC_INT_CMD);
4299 task_req_descp->header.dword_2 =
4300 cpu_to_le32(OCS_INVALID_COMMAND_STATUS);
4302 /* Configure task request UPIU */
4304 (struct utp_upiu_task_req *) task_req_descp->task_req_upiu;
4305 task_tag = hba->nutrs + free_slot;
4306 task_req_upiup->header.dword_0 =
4307 UPIU_HEADER_DWORD(UPIU_TRANSACTION_TASK_REQ, 0,
4309 task_req_upiup->header.dword_1 =
4310 UPIU_HEADER_DWORD(0, tm_function, 0, 0);
4312 * The host shall provide the same value for LUN field in the basic
4313 * header and for Input Parameter.
4315 task_req_upiup->input_param1 = cpu_to_be32(lun_id);
4316 task_req_upiup->input_param2 = cpu_to_be32(task_id);
4318 /* send command to the controller */
4319 __set_bit(free_slot, &hba->outstanding_tasks);
4321 /* Make sure descriptors are ready before ringing the task doorbell */
4324 ufshcd_writel(hba, 1 << free_slot, REG_UTP_TASK_REQ_DOOR_BELL);
4326 spin_unlock_irqrestore(host->host_lock, flags);
4328 /* wait until the task management command is completed */
4329 err = wait_event_timeout(hba->tm_wq,
4330 test_bit(free_slot, &hba->tm_condition),
4331 msecs_to_jiffies(TM_CMD_TIMEOUT));
4333 dev_err(hba->dev, "%s: task management cmd 0x%.2x timed-out\n",
4334 __func__, tm_function);
4335 if (ufshcd_clear_tm_cmd(hba, free_slot))
4336 dev_WARN(hba->dev, "%s: unable clear tm cmd (slot %d) after timeout\n",
4337 __func__, free_slot);
4340 err = ufshcd_task_req_compl(hba, free_slot, tm_response);
4343 clear_bit(free_slot, &hba->tm_condition);
4344 ufshcd_put_tm_slot(hba, free_slot);
4345 wake_up(&hba->tm_tag_wq);
4347 ufshcd_release(hba);
4352 * ufshcd_eh_device_reset_handler - device reset handler registered to
4354 * @cmd: SCSI command pointer
4356 * Returns SUCCESS/FAILED
4358 static int ufshcd_eh_device_reset_handler(struct scsi_cmnd *cmd)
4360 struct Scsi_Host *host;
4361 struct ufs_hba *hba;
4366 struct ufshcd_lrb *lrbp;
4367 unsigned long flags;
4369 host = cmd->device->host;
4370 hba = shost_priv(host);
4371 tag = cmd->request->tag;
4373 lrbp = &hba->lrb[tag];
4374 err = ufshcd_issue_tm_cmd(hba, lrbp->lun, 0, UFS_LOGICAL_RESET, &resp);
4375 if (err || resp != UPIU_TASK_MANAGEMENT_FUNC_COMPL) {
4381 /* clear the commands that were pending for corresponding LUN */
4382 for_each_set_bit(pos, &hba->outstanding_reqs, hba->nutrs) {
4383 if (hba->lrb[pos].lun == lrbp->lun) {
4384 err = ufshcd_clear_cmd(hba, pos);
4389 spin_lock_irqsave(host->host_lock, flags);
4390 ufshcd_transfer_req_compl(hba);
4391 spin_unlock_irqrestore(host->host_lock, flags);
4396 dev_err(hba->dev, "%s: failed with err %d\n", __func__, err);
4403 * ufshcd_abort - abort a specific command
4404 * @cmd: SCSI command pointer
4406 * Abort the pending command in device by sending UFS_ABORT_TASK task management
4407 * command, and in host controller by clearing the door-bell register. There can
4408 * be race between controller sending the command to the device while abort is
4409 * issued. To avoid that, first issue UFS_QUERY_TASK to check if the command is
4410 * really issued and then try to abort it.
4412 * Returns SUCCESS/FAILED
4414 static int ufshcd_abort(struct scsi_cmnd *cmd)
4416 struct Scsi_Host *host;
4417 struct ufs_hba *hba;
4418 unsigned long flags;
4423 struct ufshcd_lrb *lrbp;
4426 host = cmd->device->host;
4427 hba = shost_priv(host);
4428 tag = cmd->request->tag;
4429 if (!ufshcd_valid_tag(hba, tag)) {
4431 "%s: invalid command tag %d: cmd=0x%p, cmd->request=0x%p",
4432 __func__, tag, cmd, cmd->request);
4436 ufshcd_hold(hba, false);
4437 reg = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
4438 /* If command is already aborted/completed, return SUCCESS */
4439 if (!(test_bit(tag, &hba->outstanding_reqs))) {
4441 "%s: cmd at tag %d already completed, outstanding=0x%lx, doorbell=0x%x\n",
4442 __func__, tag, hba->outstanding_reqs, reg);
4446 if (!(reg & (1 << tag))) {
4448 "%s: cmd was completed, but without a notifying intr, tag = %d",
4452 lrbp = &hba->lrb[tag];
4453 for (poll_cnt = 100; poll_cnt; poll_cnt--) {
4454 err = ufshcd_issue_tm_cmd(hba, lrbp->lun, lrbp->task_tag,
4455 UFS_QUERY_TASK, &resp);
4456 if (!err && resp == UPIU_TASK_MANAGEMENT_FUNC_SUCCEEDED) {
4457 /* cmd pending in the device */
4459 } else if (!err && resp == UPIU_TASK_MANAGEMENT_FUNC_COMPL) {
4461 * cmd not pending in the device, check if it is
4464 reg = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
4465 if (reg & (1 << tag)) {
4466 /* sleep for max. 200us to stabilize */
4467 usleep_range(100, 200);
4470 /* command completed already */
4474 err = resp; /* service response error */
4484 err = ufshcd_issue_tm_cmd(hba, lrbp->lun, lrbp->task_tag,
4485 UFS_ABORT_TASK, &resp);
4486 if (err || resp != UPIU_TASK_MANAGEMENT_FUNC_COMPL) {
4488 err = resp; /* service response error */
4492 err = ufshcd_clear_cmd(hba, tag);
4496 scsi_dma_unmap(cmd);
4498 spin_lock_irqsave(host->host_lock, flags);
4499 ufshcd_outstanding_req_clear(hba, tag);
4500 hba->lrb[tag].cmd = NULL;
4501 spin_unlock_irqrestore(host->host_lock, flags);
4503 clear_bit_unlock(tag, &hba->lrb_in_use);
4504 wake_up(&hba->dev_cmd.tag_wq);
4510 dev_err(hba->dev, "%s: failed with err %d\n", __func__, err);
4515 * This ufshcd_release() corresponds to the original scsi cmd that got
4516 * aborted here (as we won't get any IRQ for it).
4518 ufshcd_release(hba);
4523 * ufshcd_host_reset_and_restore - reset and restore host controller
4524 * @hba: per-adapter instance
4526 * Note that host controller reset may issue DME_RESET to
4527 * local and remote (device) Uni-Pro stack and the attributes
4528 * are reset to default state.
4530 * Returns zero on success, non-zero on failure
4532 static int ufshcd_host_reset_and_restore(struct ufs_hba *hba)
4535 unsigned long flags;
4537 /* Reset the host controller */
4538 spin_lock_irqsave(hba->host->host_lock, flags);
4539 ufshcd_hba_stop(hba, false);
4540 spin_unlock_irqrestore(hba->host->host_lock, flags);
4542 err = ufshcd_hba_enable(hba);
4546 /* Establish the link again and restore the device */
4547 err = ufshcd_probe_hba(hba);
4549 if (!err && (hba->ufshcd_state != UFSHCD_STATE_OPERATIONAL))
4553 dev_err(hba->dev, "%s: Host init failed %d\n", __func__, err);
4559 * ufshcd_reset_and_restore - reset and re-initialize host/device
4560 * @hba: per-adapter instance
4562 * Reset and recover device, host and re-establish link. This
4563 * is helpful to recover the communication in fatal error conditions.
4565 * Returns zero on success, non-zero on failure
4567 static int ufshcd_reset_and_restore(struct ufs_hba *hba)
4570 unsigned long flags;
4571 int retries = MAX_HOST_RESET_RETRIES;
4574 err = ufshcd_host_reset_and_restore(hba);
4575 } while (err && --retries);
4578 * After reset the door-bell might be cleared, complete
4579 * outstanding requests in s/w here.
4581 spin_lock_irqsave(hba->host->host_lock, flags);
4582 ufshcd_transfer_req_compl(hba);
4583 ufshcd_tmc_handler(hba);
4584 spin_unlock_irqrestore(hba->host->host_lock, flags);
4590 * ufshcd_eh_host_reset_handler - host reset handler registered to scsi layer
4591 * @cmd - SCSI command pointer
4593 * Returns SUCCESS/FAILED
4595 static int ufshcd_eh_host_reset_handler(struct scsi_cmnd *cmd)
4598 unsigned long flags;
4599 struct ufs_hba *hba;
4601 hba = shost_priv(cmd->device->host);
4603 ufshcd_hold(hba, false);
4605 * Check if there is any race with fatal error handling.
4606 * If so, wait for it to complete. Even though fatal error
4607 * handling does reset and restore in some cases, don't assume
4608 * anything out of it. We are just avoiding race here.
4611 spin_lock_irqsave(hba->host->host_lock, flags);
4612 if (!(work_pending(&hba->eh_work) ||
4613 hba->ufshcd_state == UFSHCD_STATE_RESET))
4615 spin_unlock_irqrestore(hba->host->host_lock, flags);
4616 dev_dbg(hba->dev, "%s: reset in progress\n", __func__);
4617 flush_work(&hba->eh_work);
4620 hba->ufshcd_state = UFSHCD_STATE_RESET;
4621 ufshcd_set_eh_in_progress(hba);
4622 spin_unlock_irqrestore(hba->host->host_lock, flags);
4624 err = ufshcd_reset_and_restore(hba);
4626 spin_lock_irqsave(hba->host->host_lock, flags);
4629 hba->ufshcd_state = UFSHCD_STATE_OPERATIONAL;
4632 hba->ufshcd_state = UFSHCD_STATE_ERROR;
4634 ufshcd_clear_eh_in_progress(hba);
4635 spin_unlock_irqrestore(hba->host->host_lock, flags);
4637 ufshcd_release(hba);
4642 * ufshcd_get_max_icc_level - calculate the ICC level
4643 * @sup_curr_uA: max. current supported by the regulator
4644 * @start_scan: row at the desc table to start scan from
4645 * @buff: power descriptor buffer
4647 * Returns calculated max ICC level for specific regulator
4649 static u32 ufshcd_get_max_icc_level(int sup_curr_uA, u32 start_scan, char *buff)
4656 for (i = start_scan; i >= 0; i--) {
4657 data = be16_to_cpu(*((u16 *)(buff + 2*i)));
4658 unit = (data & ATTR_ICC_LVL_UNIT_MASK) >>
4659 ATTR_ICC_LVL_UNIT_OFFSET;
4660 curr_uA = data & ATTR_ICC_LVL_VALUE_MASK;
4662 case UFSHCD_NANO_AMP:
4663 curr_uA = curr_uA / 1000;
4665 case UFSHCD_MILI_AMP:
4666 curr_uA = curr_uA * 1000;
4669 curr_uA = curr_uA * 1000 * 1000;
4671 case UFSHCD_MICRO_AMP:
4675 if (sup_curr_uA >= curr_uA)
4680 pr_err("%s: Couldn't find valid icc_level = %d", __func__, i);
4687 * ufshcd_calc_icc_level - calculate the max ICC level
4688 * In case regulators are not initialized we'll return 0
4689 * @hba: per-adapter instance
4690 * @desc_buf: power descriptor buffer to extract ICC levels from.
4691 * @len: length of desc_buff
4693 * Returns calculated ICC level
4695 static u32 ufshcd_find_max_sup_active_icc_level(struct ufs_hba *hba,
4696 u8 *desc_buf, int len)
4700 if (!hba->vreg_info.vcc || !hba->vreg_info.vccq ||
4701 !hba->vreg_info.vccq2) {
4703 "%s: Regulator capability was not set, actvIccLevel=%d",
4704 __func__, icc_level);
4708 if (hba->vreg_info.vcc)
4709 icc_level = ufshcd_get_max_icc_level(
4710 hba->vreg_info.vcc->max_uA,
4711 POWER_DESC_MAX_ACTV_ICC_LVLS - 1,
4712 &desc_buf[PWR_DESC_ACTIVE_LVLS_VCC_0]);
4714 if (hba->vreg_info.vccq)
4715 icc_level = ufshcd_get_max_icc_level(
4716 hba->vreg_info.vccq->max_uA,
4718 &desc_buf[PWR_DESC_ACTIVE_LVLS_VCCQ_0]);
4720 if (hba->vreg_info.vccq2)
4721 icc_level = ufshcd_get_max_icc_level(
4722 hba->vreg_info.vccq2->max_uA,
4724 &desc_buf[PWR_DESC_ACTIVE_LVLS_VCCQ2_0]);
4729 static void ufshcd_init_icc_levels(struct ufs_hba *hba)
4732 int buff_len = QUERY_DESC_POWER_MAX_SIZE;
4733 u8 desc_buf[QUERY_DESC_POWER_MAX_SIZE];
4735 ret = ufshcd_read_power_desc(hba, desc_buf, buff_len);
4738 "%s: Failed reading power descriptor.len = %d ret = %d",
4739 __func__, buff_len, ret);
4743 hba->init_prefetch_data.icc_level =
4744 ufshcd_find_max_sup_active_icc_level(hba,
4745 desc_buf, buff_len);
4746 dev_dbg(hba->dev, "%s: setting icc_level 0x%x",
4747 __func__, hba->init_prefetch_data.icc_level);
4749 ret = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_WRITE_ATTR,
4750 QUERY_ATTR_IDN_ACTIVE_ICC_LVL, 0, 0,
4751 &hba->init_prefetch_data.icc_level);
4755 "%s: Failed configuring bActiveICCLevel = %d ret = %d",
4756 __func__, hba->init_prefetch_data.icc_level , ret);
4761 * ufshcd_scsi_add_wlus - Adds required W-LUs
4762 * @hba: per-adapter instance
4764 * UFS device specification requires the UFS devices to support 4 well known
4766 * "REPORT_LUNS" (address: 01h)
4767 * "UFS Device" (address: 50h)
4768 * "RPMB" (address: 44h)
4769 * "BOOT" (address: 30h)
4770 * UFS device's power management needs to be controlled by "POWER CONDITION"
4771 * field of SSU (START STOP UNIT) command. But this "power condition" field
4772 * will take effect only when its sent to "UFS device" well known logical unit
4773 * hence we require the scsi_device instance to represent this logical unit in
4774 * order for the UFS host driver to send the SSU command for power management.
4776 * We also require the scsi_device instance for "RPMB" (Replay Protected Memory
4777 * Block) LU so user space process can control this LU. User space may also
4778 * want to have access to BOOT LU.
4780 * This function adds scsi device instances for each of all well known LUs
4781 * (except "REPORT LUNS" LU).
4783 * Returns zero on success (all required W-LUs are added successfully),
4784 * non-zero error value on failure (if failed to add any of the required W-LU).
4786 static int ufshcd_scsi_add_wlus(struct ufs_hba *hba)
4789 struct scsi_device *sdev_rpmb;
4790 struct scsi_device *sdev_boot;
4792 hba->sdev_ufs_device = __scsi_add_device(hba->host, 0, 0,
4793 ufshcd_upiu_wlun_to_scsi_wlun(UFS_UPIU_UFS_DEVICE_WLUN), NULL);
4794 if (IS_ERR(hba->sdev_ufs_device)) {
4795 ret = PTR_ERR(hba->sdev_ufs_device);
4796 hba->sdev_ufs_device = NULL;
4799 scsi_device_put(hba->sdev_ufs_device);
4801 sdev_boot = __scsi_add_device(hba->host, 0, 0,
4802 ufshcd_upiu_wlun_to_scsi_wlun(UFS_UPIU_BOOT_WLUN), NULL);
4803 if (IS_ERR(sdev_boot)) {
4804 ret = PTR_ERR(sdev_boot);
4805 goto remove_sdev_ufs_device;
4807 scsi_device_put(sdev_boot);
4809 sdev_rpmb = __scsi_add_device(hba->host, 0, 0,
4810 ufshcd_upiu_wlun_to_scsi_wlun(UFS_UPIU_RPMB_WLUN), NULL);
4811 if (IS_ERR(sdev_rpmb)) {
4812 ret = PTR_ERR(sdev_rpmb);
4813 goto remove_sdev_boot;
4815 scsi_device_put(sdev_rpmb);
4819 scsi_remove_device(sdev_boot);
4820 remove_sdev_ufs_device:
4821 scsi_remove_device(hba->sdev_ufs_device);
4826 static int ufs_get_device_info(struct ufs_hba *hba,
4827 struct ufs_device_info *card_data)
4831 u8 str_desc_buf[QUERY_DESC_STRING_MAX_SIZE + 1] = {0};
4832 u8 desc_buf[QUERY_DESC_DEVICE_MAX_SIZE];
4834 err = ufshcd_read_device_desc(hba, desc_buf,
4835 QUERY_DESC_DEVICE_MAX_SIZE);
4837 dev_err(hba->dev, "%s: Failed reading Device Desc. err = %d\n",
4843 * getting vendor (manufacturerID) and Bank Index in big endian
4846 card_data->wmanufacturerid = desc_buf[DEVICE_DESC_PARAM_MANF_ID] << 8 |
4847 desc_buf[DEVICE_DESC_PARAM_MANF_ID + 1];
4849 model_index = desc_buf[DEVICE_DESC_PARAM_PRDCT_NAME];
4851 err = ufshcd_read_string_desc(hba, model_index, str_desc_buf,
4852 QUERY_DESC_STRING_MAX_SIZE, ASCII_STD);
4854 dev_err(hba->dev, "%s: Failed reading Product Name. err = %d\n",
4859 str_desc_buf[QUERY_DESC_STRING_MAX_SIZE] = '\0';
4860 strlcpy(card_data->model, (str_desc_buf + QUERY_DESC_HDR_SIZE),
4861 min_t(u8, str_desc_buf[QUERY_DESC_LENGTH_OFFSET],
4864 /* Null terminate the model string */
4865 card_data->model[MAX_MODEL_LEN] = '\0';
4871 void ufs_advertise_fixup_device(struct ufs_hba *hba)
4874 struct ufs_dev_fix *f;
4875 struct ufs_device_info card_data;
4877 card_data.wmanufacturerid = 0;
4879 err = ufs_get_device_info(hba, &card_data);
4881 dev_err(hba->dev, "%s: Failed getting device info. err = %d\n",
4886 for (f = ufs_fixups; f->quirk; f++) {
4887 if (((f->card.wmanufacturerid == card_data.wmanufacturerid) ||
4888 (f->card.wmanufacturerid == UFS_ANY_VENDOR)) &&
4889 (STR_PRFX_EQUAL(f->card.model, card_data.model) ||
4890 !strcmp(f->card.model, UFS_ANY_MODEL)))
4891 hba->dev_quirks |= f->quirk;
4896 * ufshcd_tune_pa_tactivate - Tunes PA_TActivate of local UniPro
4897 * @hba: per-adapter instance
4899 * PA_TActivate parameter can be tuned manually if UniPro version is less than
4900 * 1.61. PA_TActivate needs to be greater than or equal to peerM-PHY's
4901 * RX_MIN_ACTIVATETIME_CAPABILITY attribute. This optimal value can help reduce
4902 * the hibern8 exit latency.
4904 * Returns zero on success, non-zero error value on failure.
4906 static int ufshcd_tune_pa_tactivate(struct ufs_hba *hba)
4909 u32 peer_rx_min_activatetime = 0, tuned_pa_tactivate;
4911 ret = ufshcd_dme_peer_get(hba,
4913 RX_MIN_ACTIVATETIME_CAPABILITY,
4914 UIC_ARG_MPHY_RX_GEN_SEL_INDEX(0)),
4915 &peer_rx_min_activatetime);
4919 /* make sure proper unit conversion is applied */
4920 tuned_pa_tactivate =
4921 ((peer_rx_min_activatetime * RX_MIN_ACTIVATETIME_UNIT_US)
4922 / PA_TACTIVATE_TIME_UNIT_US);
4923 ret = ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TACTIVATE),
4924 tuned_pa_tactivate);
4931 * ufshcd_tune_pa_hibern8time - Tunes PA_Hibern8Time of local UniPro
4932 * @hba: per-adapter instance
4934 * PA_Hibern8Time parameter can be tuned manually if UniPro version is less than
4935 * 1.61. PA_Hibern8Time needs to be maximum of local M-PHY's
4936 * TX_HIBERN8TIME_CAPABILITY & peer M-PHY's RX_HIBERN8TIME_CAPABILITY.
4937 * This optimal value can help reduce the hibern8 exit latency.
4939 * Returns zero on success, non-zero error value on failure.
4941 static int ufshcd_tune_pa_hibern8time(struct ufs_hba *hba)
4944 u32 local_tx_hibern8_time_cap = 0, peer_rx_hibern8_time_cap = 0;
4945 u32 max_hibern8_time, tuned_pa_hibern8time;
4947 ret = ufshcd_dme_get(hba,
4948 UIC_ARG_MIB_SEL(TX_HIBERN8TIME_CAPABILITY,
4949 UIC_ARG_MPHY_TX_GEN_SEL_INDEX(0)),
4950 &local_tx_hibern8_time_cap);
4954 ret = ufshcd_dme_peer_get(hba,
4955 UIC_ARG_MIB_SEL(RX_HIBERN8TIME_CAPABILITY,
4956 UIC_ARG_MPHY_RX_GEN_SEL_INDEX(0)),
4957 &peer_rx_hibern8_time_cap);
4961 max_hibern8_time = max(local_tx_hibern8_time_cap,
4962 peer_rx_hibern8_time_cap);
4963 /* make sure proper unit conversion is applied */
4964 tuned_pa_hibern8time = ((max_hibern8_time * HIBERN8TIME_UNIT_US)
4965 / PA_HIBERN8_TIME_UNIT_US);
4966 ret = ufshcd_dme_set(hba, UIC_ARG_MIB(PA_HIBERN8TIME),
4967 tuned_pa_hibern8time);
4972 static void ufshcd_tune_unipro_params(struct ufs_hba *hba)
4974 if (ufshcd_is_unipro_pa_params_tuning_req(hba)) {
4975 ufshcd_tune_pa_tactivate(hba);
4976 ufshcd_tune_pa_hibern8time(hba);
4979 if (hba->dev_quirks & UFS_DEVICE_QUIRK_PA_TACTIVATE)
4980 /* set 1ms timeout for PA_TACTIVATE */
4981 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TACTIVATE), 10);
4985 * ufshcd_probe_hba - probe hba to detect device and initialize
4986 * @hba: per-adapter instance
4988 * Execute link-startup and verify device initialization
4990 static int ufshcd_probe_hba(struct ufs_hba *hba)
4994 ret = ufshcd_link_startup(hba);
4998 ufshcd_init_pwr_info(hba);
5000 /* set the default level for urgent bkops */
5001 hba->urgent_bkops_lvl = BKOPS_STATUS_PERF_IMPACT;
5002 hba->is_urgent_bkops_lvl_checked = false;
5004 /* UniPro link is active now */
5005 ufshcd_set_link_active(hba);
5007 ret = ufshcd_verify_dev_init(hba);
5011 ret = ufshcd_complete_dev_init(hba);
5015 ufs_advertise_fixup_device(hba);
5016 ufshcd_tune_unipro_params(hba);
5018 ret = ufshcd_set_vccq_rail_unused(hba,
5019 (hba->dev_quirks & UFS_DEVICE_NO_VCCQ) ? true : false);
5023 /* UFS device is also active now */
5024 ufshcd_set_ufs_dev_active(hba);
5025 ufshcd_force_reset_auto_bkops(hba);
5026 hba->wlun_dev_clr_ua = true;
5028 if (ufshcd_get_max_pwr_mode(hba)) {
5030 "%s: Failed getting max supported power mode\n",
5033 ret = ufshcd_config_pwr_mode(hba, &hba->max_pwr_info.info);
5035 dev_err(hba->dev, "%s: Failed setting power mode, err = %d\n",
5039 /* set the state as operational after switching to desired gear */
5040 hba->ufshcd_state = UFSHCD_STATE_OPERATIONAL;
5042 * If we are in error handling context or in power management callbacks
5043 * context, no need to scan the host
5045 if (!ufshcd_eh_in_progress(hba) && !hba->pm_op_in_progress) {
5048 /* clear any previous UFS device information */
5049 memset(&hba->dev_info, 0, sizeof(hba->dev_info));
5050 if (!ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_READ_FLAG,
5051 QUERY_FLAG_IDN_PWR_ON_WPE, &flag))
5052 hba->dev_info.f_power_on_wp_en = flag;
5054 if (!hba->is_init_prefetch)
5055 ufshcd_init_icc_levels(hba);
5057 /* Add required well known logical units to scsi mid layer */
5058 if (ufshcd_scsi_add_wlus(hba))
5061 scsi_scan_host(hba->host);
5062 pm_runtime_put_sync(hba->dev);
5065 if (!hba->is_init_prefetch)
5066 hba->is_init_prefetch = true;
5068 /* Resume devfreq after UFS device is detected */
5069 if (ufshcd_is_clkscaling_enabled(hba))
5070 devfreq_resume_device(hba->devfreq);
5074 * If we failed to initialize the device or the device is not
5075 * present, turn off the power/clocks etc.
5077 if (ret && !ufshcd_eh_in_progress(hba) && !hba->pm_op_in_progress) {
5078 pm_runtime_put_sync(hba->dev);
5079 ufshcd_hba_exit(hba);
5086 * ufshcd_async_scan - asynchronous execution for probing hba
5087 * @data: data pointer to pass to this function
5088 * @cookie: cookie data
5090 static void ufshcd_async_scan(void *data, async_cookie_t cookie)
5092 struct ufs_hba *hba = (struct ufs_hba *)data;
5094 ufshcd_probe_hba(hba);
5097 static enum blk_eh_timer_return ufshcd_eh_timed_out(struct scsi_cmnd *scmd)
5099 unsigned long flags;
5100 struct Scsi_Host *host;
5101 struct ufs_hba *hba;
5105 if (!scmd || !scmd->device || !scmd->device->host)
5106 return BLK_EH_NOT_HANDLED;
5108 host = scmd->device->host;
5109 hba = shost_priv(host);
5111 return BLK_EH_NOT_HANDLED;
5113 spin_lock_irqsave(host->host_lock, flags);
5115 for_each_set_bit(index, &hba->outstanding_reqs, hba->nutrs) {
5116 if (hba->lrb[index].cmd == scmd) {
5122 spin_unlock_irqrestore(host->host_lock, flags);
5125 * Bypass SCSI error handling and reset the block layer timer if this
5126 * SCSI command was not actually dispatched to UFS driver, otherwise
5127 * let SCSI layer handle the error as usual.
5129 return found ? BLK_EH_NOT_HANDLED : BLK_EH_RESET_TIMER;
5132 static struct scsi_host_template ufshcd_driver_template = {
5133 .module = THIS_MODULE,
5135 .proc_name = UFSHCD,
5136 .queuecommand = ufshcd_queuecommand,
5137 .slave_alloc = ufshcd_slave_alloc,
5138 .slave_configure = ufshcd_slave_configure,
5139 .slave_destroy = ufshcd_slave_destroy,
5140 .change_queue_depth = ufshcd_change_queue_depth,
5141 .eh_abort_handler = ufshcd_abort,
5142 .eh_device_reset_handler = ufshcd_eh_device_reset_handler,
5143 .eh_host_reset_handler = ufshcd_eh_host_reset_handler,
5144 .eh_timed_out = ufshcd_eh_timed_out,
5146 .sg_tablesize = SG_ALL,
5147 .cmd_per_lun = UFSHCD_CMD_PER_LUN,
5148 .can_queue = UFSHCD_CAN_QUEUE,
5149 .max_host_blocked = 1,
5150 .track_queue_depth = 1,
5153 static int ufshcd_config_vreg_load(struct device *dev, struct ufs_vreg *vreg,
5161 ret = regulator_set_load(vreg->reg, ua);
5163 dev_err(dev, "%s: %s set load (ua=%d) failed, err=%d\n",
5164 __func__, vreg->name, ua, ret);
5170 static inline int ufshcd_config_vreg_lpm(struct ufs_hba *hba,
5171 struct ufs_vreg *vreg)
5175 else if (vreg->unused)
5178 return ufshcd_config_vreg_load(hba->dev, vreg,
5179 UFS_VREG_LPM_LOAD_UA);
5182 static inline int ufshcd_config_vreg_hpm(struct ufs_hba *hba,
5183 struct ufs_vreg *vreg)
5187 else if (vreg->unused)
5190 return ufshcd_config_vreg_load(hba->dev, vreg, vreg->max_uA);
5193 static int ufshcd_config_vreg(struct device *dev,
5194 struct ufs_vreg *vreg, bool on)
5197 struct regulator *reg = vreg->reg;
5198 const char *name = vreg->name;
5199 int min_uV, uA_load;
5203 if (regulator_count_voltages(reg) > 0) {
5204 min_uV = on ? vreg->min_uV : 0;
5205 ret = regulator_set_voltage(reg, min_uV, vreg->max_uV);
5207 dev_err(dev, "%s: %s set voltage failed, err=%d\n",
5208 __func__, name, ret);
5212 uA_load = on ? vreg->max_uA : 0;
5213 ret = ufshcd_config_vreg_load(dev, vreg, uA_load);
5221 static int ufshcd_enable_vreg(struct device *dev, struct ufs_vreg *vreg)
5227 else if (vreg->enabled || vreg->unused)
5230 ret = ufshcd_config_vreg(dev, vreg, true);
5232 ret = regulator_enable(vreg->reg);
5235 vreg->enabled = true;
5237 dev_err(dev, "%s: %s enable failed, err=%d\n",
5238 __func__, vreg->name, ret);
5243 static int ufshcd_disable_vreg(struct device *dev, struct ufs_vreg *vreg)
5249 else if (!vreg->enabled || vreg->unused)
5252 ret = regulator_disable(vreg->reg);
5255 /* ignore errors on applying disable config */
5256 ufshcd_config_vreg(dev, vreg, false);
5257 vreg->enabled = false;
5259 dev_err(dev, "%s: %s disable failed, err=%d\n",
5260 __func__, vreg->name, ret);
5266 static int ufshcd_setup_vreg(struct ufs_hba *hba, bool on)
5269 struct device *dev = hba->dev;
5270 struct ufs_vreg_info *info = &hba->vreg_info;
5275 ret = ufshcd_toggle_vreg(dev, info->vcc, on);
5279 ret = ufshcd_toggle_vreg(dev, info->vccq, on);
5283 ret = ufshcd_toggle_vreg(dev, info->vccq2, on);
5289 ufshcd_toggle_vreg(dev, info->vccq2, false);
5290 ufshcd_toggle_vreg(dev, info->vccq, false);
5291 ufshcd_toggle_vreg(dev, info->vcc, false);
5296 static int ufshcd_setup_hba_vreg(struct ufs_hba *hba, bool on)
5298 struct ufs_vreg_info *info = &hba->vreg_info;
5301 return ufshcd_toggle_vreg(hba->dev, info->vdd_hba, on);
5306 static int ufshcd_get_vreg(struct device *dev, struct ufs_vreg *vreg)
5313 vreg->reg = devm_regulator_get(dev, vreg->name);
5314 if (IS_ERR(vreg->reg)) {
5315 ret = PTR_ERR(vreg->reg);
5316 dev_err(dev, "%s: %s get failed, err=%d\n",
5317 __func__, vreg->name, ret);
5323 static int ufshcd_init_vreg(struct ufs_hba *hba)
5326 struct device *dev = hba->dev;
5327 struct ufs_vreg_info *info = &hba->vreg_info;
5332 ret = ufshcd_get_vreg(dev, info->vcc);
5336 ret = ufshcd_get_vreg(dev, info->vccq);
5340 ret = ufshcd_get_vreg(dev, info->vccq2);
5345 static int ufshcd_init_hba_vreg(struct ufs_hba *hba)
5347 struct ufs_vreg_info *info = &hba->vreg_info;
5350 return ufshcd_get_vreg(hba->dev, info->vdd_hba);
5355 static int ufshcd_set_vccq_rail_unused(struct ufs_hba *hba, bool unused)
5358 struct ufs_vreg_info *info = &hba->vreg_info;
5362 else if (!info->vccq)
5366 /* shut off the rail here */
5367 ret = ufshcd_toggle_vreg(hba->dev, info->vccq, false);
5369 * Mark this rail as no longer used, so it doesn't get enabled
5373 info->vccq->unused = true;
5376 * rail should have been already enabled hence just make sure
5377 * that unused flag is cleared.
5379 info->vccq->unused = false;
5385 static int __ufshcd_setup_clocks(struct ufs_hba *hba, bool on,
5389 struct ufs_clk_info *clki;
5390 struct list_head *head = &hba->clk_list_head;
5391 unsigned long flags;
5393 if (!head || list_empty(head))
5396 ret = ufshcd_vops_setup_clocks(hba, on, PRE_CHANGE);
5400 list_for_each_entry(clki, head, list) {
5401 if (!IS_ERR_OR_NULL(clki->clk)) {
5402 if (skip_ref_clk && !strcmp(clki->name, "ref_clk"))
5405 if (on && !clki->enabled) {
5406 ret = clk_prepare_enable(clki->clk);
5408 dev_err(hba->dev, "%s: %s prepare enable failed, %d\n",
5409 __func__, clki->name, ret);
5412 } else if (!on && clki->enabled) {
5413 clk_disable_unprepare(clki->clk);
5416 dev_dbg(hba->dev, "%s: clk: %s %sabled\n", __func__,
5417 clki->name, on ? "en" : "dis");
5421 ret = ufshcd_vops_setup_clocks(hba, on, POST_CHANGE);
5427 list_for_each_entry(clki, head, list) {
5428 if (!IS_ERR_OR_NULL(clki->clk) && clki->enabled)
5429 clk_disable_unprepare(clki->clk);
5432 spin_lock_irqsave(hba->host->host_lock, flags);
5433 hba->clk_gating.state = CLKS_ON;
5434 spin_unlock_irqrestore(hba->host->host_lock, flags);
5439 static int ufshcd_setup_clocks(struct ufs_hba *hba, bool on)
5441 return __ufshcd_setup_clocks(hba, on, false);
5444 static int ufshcd_init_clocks(struct ufs_hba *hba)
5447 struct ufs_clk_info *clki;
5448 struct device *dev = hba->dev;
5449 struct list_head *head = &hba->clk_list_head;
5451 if (!head || list_empty(head))
5454 list_for_each_entry(clki, head, list) {
5458 clki->clk = devm_clk_get(dev, clki->name);
5459 if (IS_ERR(clki->clk)) {
5460 ret = PTR_ERR(clki->clk);
5461 dev_err(dev, "%s: %s clk get failed, %d\n",
5462 __func__, clki->name, ret);
5466 if (clki->max_freq) {
5467 ret = clk_set_rate(clki->clk, clki->max_freq);
5469 dev_err(hba->dev, "%s: %s clk set rate(%dHz) failed, %d\n",
5470 __func__, clki->name,
5471 clki->max_freq, ret);
5474 clki->curr_freq = clki->max_freq;
5476 dev_dbg(dev, "%s: clk: %s, rate: %lu\n", __func__,
5477 clki->name, clk_get_rate(clki->clk));
5483 static int ufshcd_variant_hba_init(struct ufs_hba *hba)
5490 err = ufshcd_vops_init(hba);
5494 err = ufshcd_vops_setup_regulators(hba, true);
5501 ufshcd_vops_exit(hba);
5504 dev_err(hba->dev, "%s: variant %s init failed err %d\n",
5505 __func__, ufshcd_get_var_name(hba), err);
5509 static void ufshcd_variant_hba_exit(struct ufs_hba *hba)
5514 ufshcd_vops_setup_regulators(hba, false);
5516 ufshcd_vops_exit(hba);
5519 static int ufshcd_hba_init(struct ufs_hba *hba)
5524 * Handle host controller power separately from the UFS device power
5525 * rails as it will help controlling the UFS host controller power
5526 * collapse easily which is different than UFS device power collapse.
5527 * Also, enable the host controller power before we go ahead with rest
5528 * of the initialization here.
5530 err = ufshcd_init_hba_vreg(hba);
5534 err = ufshcd_setup_hba_vreg(hba, true);
5538 err = ufshcd_init_clocks(hba);
5540 goto out_disable_hba_vreg;
5542 err = ufshcd_setup_clocks(hba, true);
5544 goto out_disable_hba_vreg;
5546 err = ufshcd_init_vreg(hba);
5548 goto out_disable_clks;
5550 err = ufshcd_setup_vreg(hba, true);
5552 goto out_disable_clks;
5554 err = ufshcd_variant_hba_init(hba);
5556 goto out_disable_vreg;
5558 hba->is_powered = true;
5562 ufshcd_setup_vreg(hba, false);
5564 ufshcd_setup_clocks(hba, false);
5565 out_disable_hba_vreg:
5566 ufshcd_setup_hba_vreg(hba, false);
5571 static void ufshcd_hba_exit(struct ufs_hba *hba)
5573 if (hba->is_powered) {
5574 ufshcd_variant_hba_exit(hba);
5575 ufshcd_setup_vreg(hba, false);
5576 ufshcd_setup_clocks(hba, false);
5577 ufshcd_setup_hba_vreg(hba, false);
5578 hba->is_powered = false;
5583 ufshcd_send_request_sense(struct ufs_hba *hba, struct scsi_device *sdp)
5585 unsigned char cmd[6] = {REQUEST_SENSE,
5589 SCSI_SENSE_BUFFERSIZE,
5594 buffer = kzalloc(SCSI_SENSE_BUFFERSIZE, GFP_KERNEL);
5600 ret = scsi_execute_req_flags(sdp, cmd, DMA_FROM_DEVICE, buffer,
5601 SCSI_SENSE_BUFFERSIZE, NULL,
5602 msecs_to_jiffies(1000), 3, NULL, REQ_PM);
5604 pr_err("%s: failed with err %d\n", __func__, ret);
5612 * ufshcd_set_dev_pwr_mode - sends START STOP UNIT command to set device
5614 * @hba: per adapter instance
5615 * @pwr_mode: device power mode to set
5617 * Returns 0 if requested power mode is set successfully
5618 * Returns non-zero if failed to set the requested power mode
5620 static int ufshcd_set_dev_pwr_mode(struct ufs_hba *hba,
5621 enum ufs_dev_pwr_mode pwr_mode)
5623 unsigned char cmd[6] = { START_STOP };
5624 struct scsi_sense_hdr sshdr;
5625 struct scsi_device *sdp;
5626 unsigned long flags;
5629 spin_lock_irqsave(hba->host->host_lock, flags);
5630 sdp = hba->sdev_ufs_device;
5632 ret = scsi_device_get(sdp);
5633 if (!ret && !scsi_device_online(sdp)) {
5635 scsi_device_put(sdp);
5640 spin_unlock_irqrestore(hba->host->host_lock, flags);
5646 * If scsi commands fail, the scsi mid-layer schedules scsi error-
5647 * handling, which would wait for host to be resumed. Since we know
5648 * we are functional while we are here, skip host resume in error
5651 hba->host->eh_noresume = 1;
5652 if (hba->wlun_dev_clr_ua) {
5653 ret = ufshcd_send_request_sense(hba, sdp);
5656 /* Unit attention condition is cleared now */
5657 hba->wlun_dev_clr_ua = false;
5660 cmd[4] = pwr_mode << 4;
5663 * Current function would be generally called from the power management
5664 * callbacks hence set the REQ_PM flag so that it doesn't resume the
5665 * already suspended childs.
5667 ret = scsi_execute_req_flags(sdp, cmd, DMA_NONE, NULL, 0, &sshdr,
5668 START_STOP_TIMEOUT, 0, NULL, REQ_PM);
5670 sdev_printk(KERN_WARNING, sdp,
5671 "START_STOP failed for power mode: %d, result %x\n",
5673 if (driver_byte(ret) & DRIVER_SENSE)
5674 scsi_print_sense_hdr(sdp, NULL, &sshdr);
5678 hba->curr_dev_pwr_mode = pwr_mode;
5680 scsi_device_put(sdp);
5681 hba->host->eh_noresume = 0;
5685 static int ufshcd_link_state_transition(struct ufs_hba *hba,
5686 enum uic_link_state req_link_state,
5687 int check_for_bkops)
5691 if (req_link_state == hba->uic_link_state)
5694 if (req_link_state == UIC_LINK_HIBERN8_STATE) {
5695 ret = ufshcd_uic_hibern8_enter(hba);
5697 ufshcd_set_link_hibern8(hba);
5702 * If autobkops is enabled, link can't be turned off because
5703 * turning off the link would also turn off the device.
5705 else if ((req_link_state == UIC_LINK_OFF_STATE) &&
5706 (!check_for_bkops || (check_for_bkops &&
5707 !hba->auto_bkops_enabled))) {
5709 * Let's make sure that link is in low power mode, we are doing
5710 * this currently by putting the link in Hibern8. Otherway to
5711 * put the link in low power mode is to send the DME end point
5712 * to device and then send the DME reset command to local
5713 * unipro. But putting the link in hibern8 is much faster.
5715 ret = ufshcd_uic_hibern8_enter(hba);
5719 * Change controller state to "reset state" which
5720 * should also put the link in off/reset state
5722 ufshcd_hba_stop(hba, true);
5724 * TODO: Check if we need any delay to make sure that
5725 * controller is reset
5727 ufshcd_set_link_off(hba);
5734 static void ufshcd_vreg_set_lpm(struct ufs_hba *hba)
5737 * It seems some UFS devices may keep drawing more than sleep current
5738 * (atleast for 500us) from UFS rails (especially from VCCQ rail).
5739 * To avoid this situation, add 2ms delay before putting these UFS
5740 * rails in LPM mode.
5742 if (!ufshcd_is_link_active(hba) &&
5743 hba->dev_quirks & UFS_DEVICE_QUIRK_DELAY_BEFORE_LPM)
5744 usleep_range(2000, 2100);
5747 * If UFS device is either in UFS_Sleep turn off VCC rail to save some
5750 * If UFS device and link is in OFF state, all power supplies (VCC,
5751 * VCCQ, VCCQ2) can be turned off if power on write protect is not
5752 * required. If UFS link is inactive (Hibern8 or OFF state) and device
5753 * is in sleep state, put VCCQ & VCCQ2 rails in LPM mode.
5755 * Ignore the error returned by ufshcd_toggle_vreg() as device is anyway
5756 * in low power state which would save some power.
5758 if (ufshcd_is_ufs_dev_poweroff(hba) && ufshcd_is_link_off(hba) &&
5759 !hba->dev_info.is_lu_power_on_wp) {
5760 ufshcd_setup_vreg(hba, false);
5761 } else if (!ufshcd_is_ufs_dev_active(hba)) {
5762 ufshcd_toggle_vreg(hba->dev, hba->vreg_info.vcc, false);
5763 if (!ufshcd_is_link_active(hba)) {
5764 ufshcd_config_vreg_lpm(hba, hba->vreg_info.vccq);
5765 ufshcd_config_vreg_lpm(hba, hba->vreg_info.vccq2);
5770 static int ufshcd_vreg_set_hpm(struct ufs_hba *hba)
5774 if (ufshcd_is_ufs_dev_poweroff(hba) && ufshcd_is_link_off(hba) &&
5775 !hba->dev_info.is_lu_power_on_wp) {
5776 ret = ufshcd_setup_vreg(hba, true);
5777 } else if (!ufshcd_is_ufs_dev_active(hba)) {
5778 ret = ufshcd_toggle_vreg(hba->dev, hba->vreg_info.vcc, true);
5779 if (!ret && !ufshcd_is_link_active(hba)) {
5780 ret = ufshcd_config_vreg_hpm(hba, hba->vreg_info.vccq);
5783 ret = ufshcd_config_vreg_hpm(hba, hba->vreg_info.vccq2);
5791 ufshcd_config_vreg_lpm(hba, hba->vreg_info.vccq);
5793 ufshcd_toggle_vreg(hba->dev, hba->vreg_info.vcc, false);
5798 static void ufshcd_hba_vreg_set_lpm(struct ufs_hba *hba)
5800 if (ufshcd_is_link_off(hba))
5801 ufshcd_setup_hba_vreg(hba, false);
5804 static void ufshcd_hba_vreg_set_hpm(struct ufs_hba *hba)
5806 if (ufshcd_is_link_off(hba))
5807 ufshcd_setup_hba_vreg(hba, true);
5811 * ufshcd_suspend - helper function for suspend operations
5812 * @hba: per adapter instance
5813 * @pm_op: desired low power operation type
5815 * This function will try to put the UFS device and link into low power
5816 * mode based on the "rpm_lvl" (Runtime PM level) or "spm_lvl"
5817 * (System PM level).
5819 * If this function is called during shutdown, it will make sure that
5820 * both UFS device and UFS link is powered off.
5822 * NOTE: UFS device & link must be active before we enter in this function.
5824 * Returns 0 for success and non-zero for failure
5826 static int ufshcd_suspend(struct ufs_hba *hba, enum ufs_pm_op pm_op)
5829 enum ufs_pm_level pm_lvl;
5830 enum ufs_dev_pwr_mode req_dev_pwr_mode;
5831 enum uic_link_state req_link_state;
5833 hba->pm_op_in_progress = 1;
5834 if (!ufshcd_is_shutdown_pm(pm_op)) {
5835 pm_lvl = ufshcd_is_runtime_pm(pm_op) ?
5836 hba->rpm_lvl : hba->spm_lvl;
5837 req_dev_pwr_mode = ufs_get_pm_lvl_to_dev_pwr_mode(pm_lvl);
5838 req_link_state = ufs_get_pm_lvl_to_link_pwr_state(pm_lvl);
5840 req_dev_pwr_mode = UFS_POWERDOWN_PWR_MODE;
5841 req_link_state = UIC_LINK_OFF_STATE;
5845 * If we can't transition into any of the low power modes
5846 * just gate the clocks.
5848 ufshcd_hold(hba, false);
5849 hba->clk_gating.is_suspended = true;
5851 if (req_dev_pwr_mode == UFS_ACTIVE_PWR_MODE &&
5852 req_link_state == UIC_LINK_ACTIVE_STATE) {
5856 if ((req_dev_pwr_mode == hba->curr_dev_pwr_mode) &&
5857 (req_link_state == hba->uic_link_state))
5860 /* UFS device & link must be active before we enter in this function */
5861 if (!ufshcd_is_ufs_dev_active(hba) || !ufshcd_is_link_active(hba)) {
5866 if (ufshcd_is_runtime_pm(pm_op)) {
5867 if (ufshcd_can_autobkops_during_suspend(hba)) {
5869 * The device is idle with no requests in the queue,
5870 * allow background operations if bkops status shows
5871 * that performance might be impacted.
5873 ret = ufshcd_urgent_bkops(hba);
5877 /* make sure that auto bkops is disabled */
5878 ufshcd_disable_auto_bkops(hba);
5882 if ((req_dev_pwr_mode != hba->curr_dev_pwr_mode) &&
5883 ((ufshcd_is_runtime_pm(pm_op) && !hba->auto_bkops_enabled) ||
5884 !ufshcd_is_runtime_pm(pm_op))) {
5885 /* ensure that bkops is disabled */
5886 ufshcd_disable_auto_bkops(hba);
5887 ret = ufshcd_set_dev_pwr_mode(hba, req_dev_pwr_mode);
5892 ret = ufshcd_link_state_transition(hba, req_link_state, 1);
5894 goto set_dev_active;
5896 ufshcd_vreg_set_lpm(hba);
5900 * The clock scaling needs access to controller registers. Hence, Wait
5901 * for pending clock scaling work to be done before clocks are
5904 if (ufshcd_is_clkscaling_enabled(hba)) {
5905 devfreq_suspend_device(hba->devfreq);
5906 hba->clk_scaling.window_start_t = 0;
5909 * Call vendor specific suspend callback. As these callbacks may access
5910 * vendor specific host controller register space call them before the
5911 * host clocks are ON.
5913 ret = ufshcd_vops_suspend(hba, pm_op);
5915 goto set_link_active;
5917 if (!ufshcd_is_link_active(hba))
5918 ufshcd_setup_clocks(hba, false);
5920 /* If link is active, device ref_clk can't be switched off */
5921 __ufshcd_setup_clocks(hba, false, true);
5923 hba->clk_gating.state = CLKS_OFF;
5925 * Disable the host irq as host controller as there won't be any
5926 * host controller transaction expected till resume.
5928 ufshcd_disable_irq(hba);
5929 /* Put the host controller in low power mode if possible */
5930 ufshcd_hba_vreg_set_lpm(hba);
5934 ufshcd_vreg_set_hpm(hba);
5935 if (ufshcd_is_link_hibern8(hba) && !ufshcd_uic_hibern8_exit(hba))
5936 ufshcd_set_link_active(hba);
5937 else if (ufshcd_is_link_off(hba))
5938 ufshcd_host_reset_and_restore(hba);
5940 if (!ufshcd_set_dev_pwr_mode(hba, UFS_ACTIVE_PWR_MODE))
5941 ufshcd_disable_auto_bkops(hba);
5943 hba->clk_gating.is_suspended = false;
5944 ufshcd_release(hba);
5946 hba->pm_op_in_progress = 0;
5951 * ufshcd_resume - helper function for resume operations
5952 * @hba: per adapter instance
5953 * @pm_op: runtime PM or system PM
5955 * This function basically brings the UFS device, UniPro link and controller
5958 * Returns 0 for success and non-zero for failure
5960 static int ufshcd_resume(struct ufs_hba *hba, enum ufs_pm_op pm_op)
5963 enum uic_link_state old_link_state;
5965 hba->pm_op_in_progress = 1;
5966 old_link_state = hba->uic_link_state;
5968 ufshcd_hba_vreg_set_hpm(hba);
5969 /* Make sure clocks are enabled before accessing controller */
5970 ret = ufshcd_setup_clocks(hba, true);
5974 /* enable the host irq as host controller would be active soon */
5975 ret = ufshcd_enable_irq(hba);
5977 goto disable_irq_and_vops_clks;
5979 ret = ufshcd_vreg_set_hpm(hba);
5981 goto disable_irq_and_vops_clks;
5984 * Call vendor specific resume callback. As these callbacks may access
5985 * vendor specific host controller register space call them when the
5986 * host clocks are ON.
5988 ret = ufshcd_vops_resume(hba, pm_op);
5992 if (ufshcd_is_link_hibern8(hba)) {
5993 ret = ufshcd_uic_hibern8_exit(hba);
5995 ufshcd_set_link_active(hba);
5997 goto vendor_suspend;
5998 } else if (ufshcd_is_link_off(hba)) {
5999 ret = ufshcd_host_reset_and_restore(hba);
6001 * ufshcd_host_reset_and_restore() should have already
6002 * set the link state as active
6004 if (ret || !ufshcd_is_link_active(hba))
6005 goto vendor_suspend;
6008 if (!ufshcd_is_ufs_dev_active(hba)) {
6009 ret = ufshcd_set_dev_pwr_mode(hba, UFS_ACTIVE_PWR_MODE);
6011 goto set_old_link_state;
6015 * If BKOPs operations are urgently needed at this moment then
6016 * keep auto-bkops enabled or else disable it.
6018 ufshcd_urgent_bkops(hba);
6019 hba->clk_gating.is_suspended = false;
6021 if (ufshcd_is_clkscaling_enabled(hba))
6022 devfreq_resume_device(hba->devfreq);
6024 /* Schedule clock gating in case of no access to UFS device yet */
6025 ufshcd_release(hba);
6029 ufshcd_link_state_transition(hba, old_link_state, 0);
6031 ufshcd_vops_suspend(hba, pm_op);
6033 ufshcd_vreg_set_lpm(hba);
6034 disable_irq_and_vops_clks:
6035 ufshcd_disable_irq(hba);
6036 ufshcd_setup_clocks(hba, false);
6038 hba->pm_op_in_progress = 0;
6043 * ufshcd_system_suspend - system suspend routine
6044 * @hba: per adapter instance
6045 * @pm_op: runtime PM or system PM
6047 * Check the description of ufshcd_suspend() function for more details.
6049 * Returns 0 for success and non-zero for failure
6051 int ufshcd_system_suspend(struct ufs_hba *hba)
6055 if (!hba || !hba->is_powered)
6058 if (pm_runtime_suspended(hba->dev)) {
6059 if (hba->rpm_lvl == hba->spm_lvl)
6061 * There is possibility that device may still be in
6062 * active state during the runtime suspend.
6064 if ((ufs_get_pm_lvl_to_dev_pwr_mode(hba->spm_lvl) ==
6065 hba->curr_dev_pwr_mode) && !hba->auto_bkops_enabled)
6069 * UFS device and/or UFS link low power states during runtime
6070 * suspend seems to be different than what is expected during
6071 * system suspend. Hence runtime resume the devic & link and
6072 * let the system suspend low power states to take effect.
6073 * TODO: If resume takes longer time, we might have optimize
6074 * it in future by not resuming everything if possible.
6076 ret = ufshcd_runtime_resume(hba);
6081 ret = ufshcd_suspend(hba, UFS_SYSTEM_PM);
6084 hba->is_sys_suspended = true;
6087 EXPORT_SYMBOL(ufshcd_system_suspend);
6090 * ufshcd_system_resume - system resume routine
6091 * @hba: per adapter instance
6093 * Returns 0 for success and non-zero for failure
6096 int ufshcd_system_resume(struct ufs_hba *hba)
6101 if (!hba->is_powered || pm_runtime_suspended(hba->dev))
6103 * Let the runtime resume take care of resuming
6104 * if runtime suspended.
6108 return ufshcd_resume(hba, UFS_SYSTEM_PM);
6110 EXPORT_SYMBOL(ufshcd_system_resume);
6113 * ufshcd_runtime_suspend - runtime suspend routine
6114 * @hba: per adapter instance
6116 * Check the description of ufshcd_suspend() function for more details.
6118 * Returns 0 for success and non-zero for failure
6120 int ufshcd_runtime_suspend(struct ufs_hba *hba)
6125 if (!hba->is_powered)
6128 return ufshcd_suspend(hba, UFS_RUNTIME_PM);
6130 EXPORT_SYMBOL(ufshcd_runtime_suspend);
6133 * ufshcd_runtime_resume - runtime resume routine
6134 * @hba: per adapter instance
6136 * This function basically brings the UFS device, UniPro link and controller
6137 * to active state. Following operations are done in this function:
6139 * 1. Turn on all the controller related clocks
6140 * 2. Bring the UniPro link out of Hibernate state
6141 * 3. If UFS device is in sleep state, turn ON VCC rail and bring the UFS device
6143 * 4. If auto-bkops is enabled on the device, disable it.
6145 * So following would be the possible power state after this function return
6147 * S1: UFS device in Active state with VCC rail ON
6148 * UniPro link in Active state
6149 * All the UFS/UniPro controller clocks are ON
6151 * Returns 0 for success and non-zero for failure
6153 int ufshcd_runtime_resume(struct ufs_hba *hba)
6158 if (!hba->is_powered)
6161 return ufshcd_resume(hba, UFS_RUNTIME_PM);
6163 EXPORT_SYMBOL(ufshcd_runtime_resume);
6165 int ufshcd_runtime_idle(struct ufs_hba *hba)
6169 EXPORT_SYMBOL(ufshcd_runtime_idle);
6172 * ufshcd_shutdown - shutdown routine
6173 * @hba: per adapter instance
6175 * This function would power off both UFS device and UFS link.
6177 * Returns 0 always to allow force shutdown even in case of errors.
6179 int ufshcd_shutdown(struct ufs_hba *hba)
6183 if (ufshcd_is_ufs_dev_poweroff(hba) && ufshcd_is_link_off(hba))
6186 if (pm_runtime_suspended(hba->dev)) {
6187 ret = ufshcd_runtime_resume(hba);
6192 ret = ufshcd_suspend(hba, UFS_SHUTDOWN_PM);
6195 dev_err(hba->dev, "%s failed, err %d\n", __func__, ret);
6196 /* allow force shutdown even in case of errors */
6199 EXPORT_SYMBOL(ufshcd_shutdown);
6202 * ufshcd_remove - de-allocate SCSI host and host memory space
6203 * data structure memory
6204 * @hba - per adapter instance
6206 void ufshcd_remove(struct ufs_hba *hba)
6208 scsi_remove_host(hba->host);
6209 /* disable interrupts */
6210 ufshcd_disable_intr(hba, hba->intr_mask);
6211 ufshcd_hba_stop(hba, true);
6213 scsi_host_put(hba->host);
6215 ufshcd_exit_clk_gating(hba);
6216 if (ufshcd_is_clkscaling_enabled(hba))
6217 devfreq_remove_device(hba->devfreq);
6218 ufshcd_hba_exit(hba);
6220 EXPORT_SYMBOL_GPL(ufshcd_remove);
6223 * ufshcd_dealloc_host - deallocate Host Bus Adapter (HBA)
6224 * @hba: pointer to Host Bus Adapter (HBA)
6226 void ufshcd_dealloc_host(struct ufs_hba *hba)
6228 scsi_host_put(hba->host);
6230 EXPORT_SYMBOL_GPL(ufshcd_dealloc_host);
6233 * ufshcd_set_dma_mask - Set dma mask based on the controller
6234 * addressing capability
6235 * @hba: per adapter instance
6237 * Returns 0 for success, non-zero for failure
6239 static int ufshcd_set_dma_mask(struct ufs_hba *hba)
6241 if (hba->capabilities & MASK_64_ADDRESSING_SUPPORT) {
6242 if (!dma_set_mask_and_coherent(hba->dev, DMA_BIT_MASK(64)))
6245 return dma_set_mask_and_coherent(hba->dev, DMA_BIT_MASK(32));
6249 * ufshcd_alloc_host - allocate Host Bus Adapter (HBA)
6250 * @dev: pointer to device handle
6251 * @hba_handle: driver private handle
6252 * Returns 0 on success, non-zero value on failure
6254 int ufshcd_alloc_host(struct device *dev, struct ufs_hba **hba_handle)
6256 struct Scsi_Host *host;
6257 struct ufs_hba *hba;
6262 "Invalid memory reference for dev is NULL\n");
6267 host = scsi_host_alloc(&ufshcd_driver_template,
6268 sizeof(struct ufs_hba));
6270 dev_err(dev, "scsi_host_alloc failed\n");
6274 hba = shost_priv(host);
6282 EXPORT_SYMBOL(ufshcd_alloc_host);
6284 static int ufshcd_scale_clks(struct ufs_hba *hba, bool scale_up)
6287 struct ufs_clk_info *clki;
6288 struct list_head *head = &hba->clk_list_head;
6290 if (!head || list_empty(head))
6293 ret = ufshcd_vops_clk_scale_notify(hba, scale_up, PRE_CHANGE);
6297 list_for_each_entry(clki, head, list) {
6298 if (!IS_ERR_OR_NULL(clki->clk)) {
6299 if (scale_up && clki->max_freq) {
6300 if (clki->curr_freq == clki->max_freq)
6302 ret = clk_set_rate(clki->clk, clki->max_freq);
6304 dev_err(hba->dev, "%s: %s clk set rate(%dHz) failed, %d\n",
6305 __func__, clki->name,
6306 clki->max_freq, ret);
6309 clki->curr_freq = clki->max_freq;
6311 } else if (!scale_up && clki->min_freq) {
6312 if (clki->curr_freq == clki->min_freq)
6314 ret = clk_set_rate(clki->clk, clki->min_freq);
6316 dev_err(hba->dev, "%s: %s clk set rate(%dHz) failed, %d\n",
6317 __func__, clki->name,
6318 clki->min_freq, ret);
6321 clki->curr_freq = clki->min_freq;
6324 dev_dbg(hba->dev, "%s: clk: %s, rate: %lu\n", __func__,
6325 clki->name, clk_get_rate(clki->clk));
6328 ret = ufshcd_vops_clk_scale_notify(hba, scale_up, POST_CHANGE);
6334 static int ufshcd_devfreq_target(struct device *dev,
6335 unsigned long *freq, u32 flags)
6338 struct ufs_hba *hba = dev_get_drvdata(dev);
6340 if (!ufshcd_is_clkscaling_enabled(hba))
6343 if (*freq == UINT_MAX)
6344 err = ufshcd_scale_clks(hba, true);
6345 else if (*freq == 0)
6346 err = ufshcd_scale_clks(hba, false);
6351 static int ufshcd_devfreq_get_dev_status(struct device *dev,
6352 struct devfreq_dev_status *stat)
6354 struct ufs_hba *hba = dev_get_drvdata(dev);
6355 struct ufs_clk_scaling *scaling = &hba->clk_scaling;
6356 unsigned long flags;
6358 if (!ufshcd_is_clkscaling_enabled(hba))
6361 memset(stat, 0, sizeof(*stat));
6363 spin_lock_irqsave(hba->host->host_lock, flags);
6364 if (!scaling->window_start_t)
6367 if (scaling->is_busy_started)
6368 scaling->tot_busy_t += ktime_to_us(ktime_sub(ktime_get(),
6369 scaling->busy_start_t));
6371 stat->total_time = jiffies_to_usecs((long)jiffies -
6372 (long)scaling->window_start_t);
6373 stat->busy_time = scaling->tot_busy_t;
6375 scaling->window_start_t = jiffies;
6376 scaling->tot_busy_t = 0;
6378 if (hba->outstanding_reqs) {
6379 scaling->busy_start_t = ktime_get();
6380 scaling->is_busy_started = true;
6382 scaling->busy_start_t = ktime_set(0, 0);
6383 scaling->is_busy_started = false;
6385 spin_unlock_irqrestore(hba->host->host_lock, flags);
6389 static struct devfreq_dev_profile ufs_devfreq_profile = {
6391 .target = ufshcd_devfreq_target,
6392 .get_dev_status = ufshcd_devfreq_get_dev_status,
6396 * ufshcd_init - Driver initialization routine
6397 * @hba: per-adapter instance
6398 * @mmio_base: base register address
6399 * @irq: Interrupt line of device
6400 * Returns 0 on success, non-zero value on failure
6402 int ufshcd_init(struct ufs_hba *hba, void __iomem *mmio_base, unsigned int irq)
6405 struct Scsi_Host *host = hba->host;
6406 struct device *dev = hba->dev;
6410 "Invalid memory reference for mmio_base is NULL\n");
6415 hba->mmio_base = mmio_base;
6418 err = ufshcd_hba_init(hba);
6422 /* Read capabilities registers */
6423 ufshcd_hba_capabilities(hba);
6425 /* Get UFS version supported by the controller */
6426 hba->ufs_version = ufshcd_get_ufs_version(hba);
6428 /* Get Interrupt bit mask per version */
6429 hba->intr_mask = ufshcd_get_intr_mask(hba);
6431 err = ufshcd_set_dma_mask(hba);
6433 dev_err(hba->dev, "set dma mask failed\n");
6437 /* Allocate memory for host memory space */
6438 err = ufshcd_memory_alloc(hba);
6440 dev_err(hba->dev, "Memory allocation failed\n");
6445 ufshcd_host_memory_configure(hba);
6447 host->can_queue = hba->nutrs;
6448 host->cmd_per_lun = hba->nutrs;
6449 host->max_id = UFSHCD_MAX_ID;
6450 host->max_lun = UFS_MAX_LUNS;
6451 host->max_channel = UFSHCD_MAX_CHANNEL;
6452 host->unique_id = host->host_no;
6453 host->max_cmd_len = MAX_CDB_SIZE;
6455 hba->max_pwr_info.is_valid = false;
6457 /* Initailize wait queue for task management */
6458 init_waitqueue_head(&hba->tm_wq);
6459 init_waitqueue_head(&hba->tm_tag_wq);
6461 /* Initialize work queues */
6462 INIT_WORK(&hba->eh_work, ufshcd_err_handler);
6463 INIT_WORK(&hba->eeh_work, ufshcd_exception_event_handler);
6465 /* Initialize UIC command mutex */
6466 mutex_init(&hba->uic_cmd_mutex);
6468 /* Initialize mutex for device management commands */
6469 mutex_init(&hba->dev_cmd.lock);
6471 /* Initialize device management tag acquire wait queue */
6472 init_waitqueue_head(&hba->dev_cmd.tag_wq);
6474 ufshcd_init_clk_gating(hba);
6477 * In order to avoid any spurious interrupt immediately after
6478 * registering UFS controller interrupt handler, clear any pending UFS
6479 * interrupt status and disable all the UFS interrupts.
6481 ufshcd_writel(hba, ufshcd_readl(hba, REG_INTERRUPT_STATUS),
6482 REG_INTERRUPT_STATUS);
6483 ufshcd_writel(hba, 0, REG_INTERRUPT_ENABLE);
6485 * Make sure that UFS interrupts are disabled and any pending interrupt
6486 * status is cleared before registering UFS interrupt handler.
6490 /* IRQ registration */
6491 err = devm_request_irq(dev, irq, ufshcd_intr, IRQF_SHARED, UFSHCD, hba);
6493 dev_err(hba->dev, "request irq failed\n");
6496 hba->is_irq_enabled = true;
6499 err = scsi_add_host(host, hba->dev);
6501 dev_err(hba->dev, "scsi_add_host failed\n");
6505 /* Host controller enable */
6506 err = ufshcd_hba_enable(hba);
6508 dev_err(hba->dev, "Host controller enable failed\n");
6509 goto out_remove_scsi_host;
6512 if (ufshcd_is_clkscaling_enabled(hba)) {
6513 hba->devfreq = devfreq_add_device(dev, &ufs_devfreq_profile,
6514 "simple_ondemand", NULL);
6515 if (IS_ERR(hba->devfreq)) {
6516 dev_err(hba->dev, "Unable to register with devfreq %ld\n",
6517 PTR_ERR(hba->devfreq));
6518 err = PTR_ERR(hba->devfreq);
6519 goto out_remove_scsi_host;
6521 /* Suspend devfreq until the UFS device is detected */
6522 devfreq_suspend_device(hba->devfreq);
6523 hba->clk_scaling.window_start_t = 0;
6526 /* Hold auto suspend until async scan completes */
6527 pm_runtime_get_sync(dev);
6530 * The device-initialize-sequence hasn't been invoked yet.
6531 * Set the device to power-off state
6533 ufshcd_set_ufs_dev_poweroff(hba);
6535 async_schedule(ufshcd_async_scan, hba);
6539 out_remove_scsi_host:
6540 scsi_remove_host(hba->host);
6542 ufshcd_exit_clk_gating(hba);
6544 hba->is_irq_enabled = false;
6545 scsi_host_put(host);
6546 ufshcd_hba_exit(hba);
6550 EXPORT_SYMBOL_GPL(ufshcd_init);
6552 MODULE_AUTHOR("Santosh Yaragnavi <santosh.sy@samsung.com>");
6553 MODULE_AUTHOR("Vinayak Holikatti <h.vinayak@samsung.com>");
6554 MODULE_DESCRIPTION("Generic UFS host controller driver Core");
6555 MODULE_LICENSE("GPL");
6556 MODULE_VERSION(UFSHCD_DRIVER_VERSION);